: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(desktop): redesign the agents surface inside Settings (#95745)
Shy Alter507e047c536e
diff --git a/products/desktop/docs/AGENTS-SETTINGS.md b/products/desktop/docs/AGENTS-SETTINGS.mdnew file mode 100644index 000000000000..6ebdf3f2bb34--- /dev/null+++ b/products/desktop/docs/AGENTS-SETTINGS.md@@ -0,0 +1,49 @@+# Agent settings++Open Settings > Agents to manage scheduled agents. The page has three tabs:+Agents, Memory, and Setup. Each browser tab keeps its own selection.+A link to an agent or a signal opens that item. The `/agents` link opens the fleet.++Review agent reports in Self-driving. The Self-driving link and report total on+the Agents tab open that page. Old `/agents/findings` and+`/agents/scouts/findings` links also open Self-driving. Agents can create or+update reports directly, so a zero count of older signals does not mean that+agents produced no reports.++The fleet shows up to 18 recent runs for each agent. It uses one request for+these runs and one request for output totals. Output totals cover recent output+runs in the last three days. The API limits the totals to 120 output runs and+50 reports. The success rate describes only the runs shown in the table.++Each agent has Activity, Output, and Settings tabs. Activity and Output load a+three-day run window for that agent. Runs from other agents do not consume its+page limit. Output shows links to reports the agent created or updated, plus+older signal findings when present. Report links open the report in Self-driving+or its assigned space. Expanded Activity rows also show these links.+Each link shows the report title, a short summary, priority when available, and+whether the run created or updated the report. Report details load as their+cards approach the visible area and share the Self-driving cache.++The page identifies+incomplete history and keeps available data visible if a refresh fails. A run+that creates or updates a report counts as output. An agent with a failure streak+still needs attention when its run history is not available.++Interval agents with no previous run are due now. Cron schedules use the project+timezone. The page shows the cron schedule without an estimated next run time+because the config response does not include that timezone. A schedule change+applies immediately. A disabled agent can run manually for a test. An agent with+a queued or active run cannot start another run.++A run that exceeds its deadline shows a stuck status. Silence alone does not+cause an automatic pause. Resume starts a new grace period after an inactivity+pause. Use Never pause for inactivity to prevent another inactivity pause.++A failed draft request keeps the entered brief. Expanded signal cards and memory+notes keep their state when they scroll out of view. Search and sort changes+return lists to the top. Narrow windows hide secondary table columns so that+controls remain available. Run boxes show their labels on keyboard focus.++Query snapshots stay in a bounded memory cache. They do not persist to disk.+Sign-out clears the cache. Older plaintext snapshots are removed when the module+loads. Run summaries do not load remote Markdown images.diff --git a/products/desktop/packages/api-client/src/posthog-client.test.ts b/products/desktop/packages/api-client/src/posthog-client.test.tsindex 8b34fc4cce23..ce764e7dfdb3 100644--- a/products/desktop/packages/api-client/src/posthog-client.test.ts+++ b/products/desktop/packages/api-client/src/posthog-client.test.ts@@ -6,10 +6,29 @@ import {CloudUsageLimitError,DESKTOP_BILLING_LIMIT_ERROR_CODE,PostHogAPIClient,+ ScoutRequestError,SESSION_LOGS_PAGE_TIMEOUT_MS,} from "./posthog-client";describe("PostHogAPIClient", () => {+ it("sends the selected scout to the runs endpoint", async () => {+ const fetch = vi+ .fn()+ .mockResolvedValue(new Response("[]", { status: 200 }));+ const client = new PostHogAPIClient(+ "https://app.posthog.test",+ async () => "token",+ async () => "token",+ 42,+ { fetch },+ );++ await client.listScoutRuns(42, { skill_name: "signals-scout-example" });++ const url = fetch.mock.calls[0][0] as URL;+ expect(url.pathname).toBe("/api/projects/42/signals/scout/runs/");+ expect(url.searchParams.get("skill_name")).toBe("signals-scout-example");+ });describe("updateTaskChannelAutoArchive", () => {it("rejects a successful response that did not save the setting", async () => {const fetch = vi.fn().mockResolvedValue(@@ -3157,3 +3176,29 @@ describe("PostHogAPIClient", () => {});});});++describe("manual scout run refusals", () => {+ it.each([403, 409, 429])(+ "preserves HTTP status %s from the production fetcher",+ async (status) => {+ const fetch = vi.fn().mockResolvedValue(+ new Response(JSON.stringify({ detail: "Run request refused." }), {+ status,+ headers: { "Content-Type": "application/json" },+ }),+ );+ const client = new PostHogAPIClient(+ "https://example.com",+ async () => "test-token",+ async () => "test-token",+ 42,+ { fetch },+ );+ const error = await client+ .runScoutNow(42, "config-1")+ .catch((value: unknown) => value);+ expect(error).toBeInstanceOf(ScoutRequestError);+ expect(error).toMatchObject({ status });+ },+ );+});diff --git a/products/desktop/packages/api-client/src/posthog-client.ts b/products/desktop/packages/api-client/src/posthog-client.tsindex 82377d9bbc46..21fb79c1f527 100644--- a/products/desktop/packages/api-client/src/posthog-client.ts+++ b/products/desktop/packages/api-client/src/posthog-client.ts@@ -568,8 +568,58 @@ export interface ScoutConfig {created_at: string;}+export interface ScoutSuggestionProposedConfig {+ /** Five-field cron in the project timezone, or null for a rolling interval. */+ run_cron_schedule: string | null;+ /** Minutes between runs when no cron is given; null means the daily default. */+ run_interval_minutes: number | null;+ /** False means the suggested scout would run dry and file nothing. */+ emit: boolean;+}++export interface ScoutSuggestionItem {+ id: string;+ /** `canonical` turns on a PostHog scout that is off; `custom` creates a drafted one. */+ kind: "canonical" | "custom";+ skill_name: string;+ title: string;+ /** Project-specific evidence for this suggestion, in prose. */+ why_here: string;+ /** Custom only: the one-line description the scout would be created with. */+ description: string;+ /** Custom only: the complete skill body the scout would be created with. */+ draft_body: string;+ proposed_config: ScoutSuggestionProposedConfig;+ /** Nothing in the current fleet covers this. */+ gap: boolean;+ confidence: "low" | "medium" | "high";+}++export interface ScoutSuggestionSet {+ /** `fresh`, `stale` (the fleet moved on), `failed` (prior batch, if any), `empty`. */+ status: "fresh" | "stale" | "failed" | "empty";+ generated_at: string | null;+ model: string;+ /** Skill names that were enabled when the batch was generated. */+ fleet_snapshot: string[];+ /** Suggestions not yet dismissed or acted on, best first. Up to 5. */+ items: ScoutSuggestionItem[];+}++export interface ScoutOutputSummary {+ count: number;+ scout_count: number;+ authored_report_count: number;+ edited_report_count: number;+ run_count: number;+ latest_at: string | null;+}+export interface ScoutRun {run_id: string;+ created_at?: string;+ emitted_report_ids?: string[];+ edited_report_ids?: string[];skill_name: string;skill_version: number;/** TaskRun-derived status, e.g. "completed" | "failed" | "in_progress" | "queued". */@@ -626,6 +676,7 @@ export interface ScoutScratchpadEntry {}export interface ScoutRunsQueryParams {+ skill_name?: string;date_from?: string;date_to?: string;text?: string;@@ -2348,14 +2399,21 @@ export class PostHogAPIClient {for (const [key, value] of Object.entries(query ?? {})) {if (value !== undefined) url.searchParams.set(key, String(value));}- const response = await this.api.fetcher.fetch({- method: "post",- url,- path: urlPath,- overrides: {- body: JSON.stringify(body),- },- });+ const response = await this.api.fetcher+ .fetch({+ method: "post",+ url,+ path: urlPath,+ overrides: {+ body: JSON.stringify(body),+ },+ })+ .catch((error: unknown) => {+ if (error instanceof ApiRequestError) {+ throw new ScoutRequestError(error.status, subPath, readDetail(error));+ }+ throw error;+ });if (!response.ok) {throw new ScoutRequestError(response.status,@@ -2386,6 +2444,26 @@ export class PostHogAPIClient {return Array.isArray(data) ? data : (data.results ?? []);}+ /**+ * The pre-computed "Suggested for this project" batch: PostHog scouts worth+ * turning on, and drafts worth creating, each with the evidence behind it.+ * A coordinator refreshes it on a schedule, so this read never waits on one.+ */+ async listScoutSuggestions(projectId: number): Promise<ScoutSuggestionSet> {+ return this.scoutGet<ScoutSuggestionSet>(projectId, "suggestions/");+ }++ async dismissScoutSuggestion(+ projectId: number,+ suggestionId: string,+ ): Promise<void> {+ await this.scoutPost<unknown>(+ projectId,+ `suggestions/${suggestionId}/dismiss/`,+ {},+ );+ }+async updateScoutConfig(projectId: number,configId: string,@@ -2425,6 +2503,17 @@ export class PostHogAPIClient {return (await response.json()) as ScoutConfig;}+ /**+ * Queue one run of a scout outside its schedule. 409 when a run is already in+ * flight, 429 when the project's daily run budget is spent.+ */+ async runScoutNow(+ projectId: number,+ configId: string,+ ): Promise<{ skill_name: string; workflow_id: string; started: boolean }> {+ return await this.scoutPost(projectId, `configs/${configId}/run/`, {});+ }+async listScoutRuns(projectId: number,params?: ScoutRunsQueryParams,@@ -2433,6 +2522,7 @@ export class PostHogAPIClient {projectId,"runs/",{+ skill_name: params?.skill_name,date_from: params?.date_from,date_to: params?.date_to,text: params?.text,@@ -2443,6 +2533,22 @@ export class PostHogAPIClient {return Array.isArray(data) ? data : (data.results ?? []);}+ async listRecentScoutRuns(projectId: number): Promise<ScoutRun[]> {+ return await this.scoutGet<ScoutRun[]>(+ projectId,+ "runs/recent-per-scout/",+ { per_scout_limit: 18 },+ );+ }++ async getScoutOutputSummary(projectId: number): Promise<ScoutOutputSummary> {+ return await this.scoutGet<ScoutOutputSummary>(+ projectId,+ "runs/findings/summary/",+ { window_hours: 72 },+ );+ }+async getScoutRun(projectId: number, runId: string): Promise<ScoutRun> {return await this.scoutGet<ScoutRun>(projectId, `runs/${runId}/`);}diff --git a/products/desktop/packages/core/src/scouts/scoutDetailTabs.ts b/products/desktop/packages/core/src/scouts/scoutDetailTabs.tsnew file mode 100644index 000000000000..7a4d035df229--- /dev/null+++ b/products/desktop/packages/core/src/scouts/scoutDetailTabs.ts@@ -0,0 +1,3 @@+export const SCOUT_DETAIL_TABS = ["activity", "output", "settings"] as const;++export type ScoutDetailTab = (typeof SCOUT_DETAIL_TABS)[number];diff --git a/products/desktop/packages/core/src/scouts/scoutFindings.test.ts b/products/desktop/packages/core/src/scouts/scoutFindings.test.tsdeleted file mode 100644index 425662e46285..000000000000--- a/products/desktop/packages/core/src/scouts/scoutFindings.test.ts+++ /dev/null@@ -1,287 +0,0 @@-import type {- ScoutEmission,- ScoutEmissionReportLink,- ScoutRun,-} from "@posthog/api-client/posthog-client";-import { describe, expect, it } from "vitest";-import {- availableScoutsFromRows,- buildScoutFindingRows,- filterAndSortScoutFindings,- MAX_FLEET_EMITTED_RUNS,- mostRecentEmittedRuns,- SCOUT_FINDINGS_SCOUT_FILTER_ALL,- SCOUT_FINDINGS_SEVERITY_FILTER_ALL,- type ScoutFindingsFilter,- type ScoutFindingsSortKey,- summarizeEmittedRuns,- summarizeScoutFindingRows,-} from "./scoutFindings";--function makeRun(overrides: Partial<ScoutRun> = {}): ScoutRun {- return {- run_id: "run-1",- skill_name: "signals-scout-error-tracking",- skill_version: 3,- status: "completed",- started_at: "2026-06-10T11:00:00Z",- completed_at: "2026-06-10T11:02:00Z",- task_id: null,- task_run_id: null,- task_url: null,- summary: "EMITTED a finding.",- emitted_count: 1,- emitted_finding_ids: [],- ...overrides,- };-}--function makeEmission(overrides: Partial<ScoutEmission> = {}): ScoutEmission {- return {- id: "em-1",- run_id: "run-1",- finding_id: "finding-1",- description: "Error rate spiked on checkout",- weight: 1,- confidence: 0.8,- severity: "P1",- tags: [],- source_id: "src-1",- emitted_at: "2026-06-10T11:02:00Z",- ...overrides,- };-}--const ALL_FILTER: ScoutFindingsFilter = {- search: "",- scout: SCOUT_FINDINGS_SCOUT_FILTER_ALL,- severity: SCOUT_FINDINGS_SEVERITY_FILTER_ALL,- sort: "newest",-};--describe("mostRecentEmittedRuns", () => {- it("drops runs that emitted nothing", () => {- const runs = [- makeRun({ run_id: "a", emitted_count: 2 }),- makeRun({ run_id: "b", emitted_count: 0 }),- makeRun({ run_id: "c", emitted_count: null }),- ];- expect(mostRecentEmittedRuns(runs).map((r) => r.run_id)).toEqual(["a"]);- });-- it("orders by completion, falling back to start time", () => {- const runs = [- makeRun({ run_id: "older", completed_at: "2026-06-10T10:00:00Z" }),- makeRun({ run_id: "newer", completed_at: "2026-06-10T11:30:00Z" }),- makeRun({- run_id: "no-complete",- completed_at: null,- started_at: "2026-06-10T12:00:00Z",- }),- ];- expect(mostRecentEmittedRuns(runs).map((r) => r.run_id)).toEqual([- "no-complete",- "newer",- "older",- ]);- });-- it("caps the result", () => {- const runs = Array.from({ length: MAX_FLEET_EMITTED_RUNS + 10 }, (_, i) =>- makeRun({- run_id: `run-${i}`,- completed_at: `2026-06-10T${String(i % 24).padStart(2, "0")}:00:00Z`,- }),- );- expect(mostRecentEmittedRuns(runs)).toHaveLength(MAX_FLEET_EMITTED_RUNS);- });-});--describe("buildScoutFindingRows", () => {- it("joins emissions to their run and report by source_id", () => {- const run = makeRun({ run_id: "run-1" });- const emission = makeEmission({ run_id: "run-1", source_id: "src-1" });- const links: ScoutEmissionReportLink[] = [- {- finding_id: "finding-1",- source_id: "src-1",- report: { id: "rep-1", title: "Checkout errors", status: "potential" },- },- ];- const rows = buildScoutFindingRows([emission], [run], links);- expect(rows).toHaveLength(1);- expect(rows[0].run.run_id).toBe("run-1");- expect(rows[0].linkedReport?.id).toBe("rep-1");- });-- it("drops emissions whose run is not in the window", () => {- const rows = buildScoutFindingRows(- [makeEmission({ run_id: "missing" })],- [makeRun({ run_id: "run-1" })],- [],- );- expect(rows).toEqual([]);- });-- it("leaves linkedReport null when there is no matching link or report", () => {- const rows = buildScoutFindingRows(- [makeEmission({ run_id: "run-1", source_id: "src-1" })],- [makeRun({ run_id: "run-1" })],- [{ finding_id: "finding-1", source_id: "src-1", report: null }],- );- expect(rows[0].linkedReport).toBeNull();- });-});--describe("filterAndSortScoutFindings", () => {- const run = makeRun({ run_id: "run-1", skill_name: "signals-scout-apm" });- const other = makeRun({- run_id: "run-2",- skill_name: "signals-scout-logs",- });- const rows = buildScoutFindingRows(- [- makeEmission({- id: "a",- run_id: "run-1",- source_id: "s-a",- severity: "P0",- confidence: 0.4,- description: "latency regression",- emitted_at: "2026-06-10T09:00:00Z",- }),- makeEmission({- id: "b",- run_id: "run-2",- source_id: "s-b",- severity: "P3",- confidence: 0.9,- description: "noisy log volume",- emitted_at: "2026-06-10T11:00:00Z",- }),- ],- [run, other],- [],- );-- it.each<{- name: string;- sort: ScoutFindingsSortKey;- expected: string[];- }>([- { name: "newest first (default)", sort: "newest", expected: ["b", "a"] },- { name: "oldest first", sort: "oldest", expected: ["a", "b"] },- {- name: "severity (most severe first)",- sort: "severity",- expected: ["a", "b"],- },- {- name: "confidence (highest first)",- sort: "confidence",- expected: ["b", "a"],- },- ])("sorts by $name", ({ sort, expected }) => {- expect(- filterAndSortScoutFindings(rows, { ...ALL_FILTER, sort }).map(- (r) => r.emission.id,- ),- ).toEqual(expected);- });-- it("filters by scout", () => {- expect(- filterAndSortScoutFindings(rows, {- ...ALL_FILTER,- scout: "signals-scout-logs",- }).map((r) => r.emission.id),- ).toEqual(["b"]);- });-- it("filters by severity", () => {- expect(- filterAndSortScoutFindings(rows, {- ...ALL_FILTER,- severity: "P0",- }).map((r) => r.emission.id),- ).toEqual(["a"]);- });-- it("searches finding text and prettified scout name", () => {- expect(- filterAndSortScoutFindings(rows, {- ...ALL_FILTER,- search: "latency",- }).map((r) => r.emission.id),- ).toEqual(["a"]);- // "Apm" comes from prettifying signals-scout-apm.- expect(- filterAndSortScoutFindings(rows, { ...ALL_FILTER, search: "apm" }).map(- (r) => r.emission.id,- ),- ).toEqual(["a"]);- });-});--describe("summaries", () => {- it("summarizeEmittedRuns sums emitted counts and distinct scouts", () => {- const summary = summarizeEmittedRuns([- makeRun({ run_id: "a", skill_name: "x", emitted_count: 2 }),- makeRun({ run_id: "b", skill_name: "x", emitted_count: 1 }),- makeRun({ run_id: "c", skill_name: "y", emitted_count: 3 }),- makeRun({ run_id: "d", skill_name: "z", emitted_count: 0 }),- ]);- expect(summary.totalCount).toBe(6);- expect(summary.scoutCount).toBe(2);- });-- it("summarizeScoutFindingRows counts rows, distinct scouts, latest", () => {- const rows = buildScoutFindingRows(- [- makeEmission({- id: "a",- run_id: "run-1",- emitted_at: "2026-06-10T09:00:00Z",- }),- makeEmission({- id: "b",- run_id: "run-2",- emitted_at: "2026-06-10T12:00:00Z",- }),- ],- [- makeRun({ run_id: "run-1", skill_name: "x" }),- makeRun({ run_id: "run-2", skill_name: "y" }),- ],- [],- );- const summary = summarizeScoutFindingRows(rows);- expect(summary.totalCount).toBe(2);- expect(summary.scoutCount).toBe(2);- expect(summary.latestEmittedAt).toBe("2026-06-10T12:00:00Z");- });-- it("availableScoutsFromRows returns per-scout counts sorted by label", () => {- const rows = buildScoutFindingRows(- [- makeEmission({ id: "a", run_id: "run-1" }),- makeEmission({ id: "b", run_id: "run-1" }),- makeEmission({ id: "c", run_id: "run-2" }),- ],- [- makeRun({ run_id: "run-1", skill_name: "signals-scout-logs" }),- makeRun({ run_id: "run-2", skill_name: "signals-scout-apm" }),- ],- [],- );- const scouts = availableScoutsFromRows(rows);- // Sorted by prettified label: "Apm" before "Logs".- expect(scouts.map((s) => s.skillName)).toEqual([- "signals-scout-apm",- "signals-scout-logs",- ]);- expect(- scouts.find((s) => s.skillName === "signals-scout-logs")?.count,- ).toBe(2);- });-});diff --git a/products/desktop/packages/core/src/scouts/scoutFindings.ts b/products/desktop/packages/core/src/scouts/scoutFindings.tsdeleted file mode 100644index 1def6920c617..000000000000--- a/products/desktop/packages/core/src/scouts/scoutFindings.ts+++ /dev/null@@ -1,228 +0,0 @@-import type {- LinkedSignalReport,- ScoutEmission,- ScoutEmissionReportLink,- ScoutRun,-} from "@posthog/api-client/posthog-client";-import { prettifyScoutSkillName } from "./scoutPresentation";--/**- * Cross-fleet findings logic — the pure counterpart of the cloud `findingsLogic`.- * Joins every recently-emitted scout finding to its run and the inbox report it- * grouped into, then filters/sorts the flattened list. Kept host-agnostic so the- * UI hook only wires queries; everything decision-shaped lives here and is unit- * tested.- */--/**- * Fleet-wide cap on emitted runs we pull findings for. The runs window already- * bounds this by time; this is a belt-and-braces ceiling so a burst of emitting- * runs can't fan out into an unbounded batch request.- */-export const MAX_FLEET_EMITTED_RUNS = 120;--export const SCOUT_FINDINGS_SCOUT_FILTER_ALL = "all";-export const SCOUT_FINDINGS_SEVERITY_FILTER_ALL = "all";--/** Severity options offered in the filter, most severe first. */-export const SCOUT_FINDINGS_SEVERITY_OPTIONS = [- "P0",- "P1",- "P2",- "P3",- "P4",-] as const;--export type ScoutFindingsSortKey =- | "newest"- | "oldest"- | "severity"- | "confidence";--export interface ScoutFindingRow {- emission: ScoutEmission;- /** The run that emitted the finding — carries skill_name + the task-run link. */- run: ScoutRun;- /** The inbox report this finding's signal grouped into, when resolved. */- linkedReport: LinkedSignalReport | null;-}--export interface ScoutFindingsFilter {- search: string;- /** A `skill_name`, or {@link SCOUT_FINDINGS_SCOUT_FILTER_ALL}. */- scout: string;- /** A severity (`P0`–`P4`), or {@link SCOUT_FINDINGS_SEVERITY_FILTER_ALL}. */- severity: string;- sort: ScoutFindingsSortKey;-}--export interface ScoutFilterOption {- skillName: string;- label: string;- count: number;-}--export interface ScoutFindingsSummary {- totalCount: number;- scoutCount: number;- latestEmittedAt: string | null;-}--/** Lowest number = most severe, so the severity sort is a plain ascending compare. */-const SEVERITY_RANK: Record<string, number> = {- P0: 0,- P1: 1,- P2: 2,- P3: 3,- P4: 4,-};--/** Null/unknown severity sinks below the explicit ranks. */-function severityRank(severity: string | null): number {- if (severity == null) return 5;- return SEVERITY_RANK[severity] ?? 5;-}--/**- * The most-recently-emitted runs across the fleet, newest first, capped at- * {@link MAX_FLEET_EMITTED_RUNS}. A run can complete (and emit) later than one- * started after it, so order by completion and fall back to start time.- */-export function mostRecentEmittedRuns(runs: ScoutRun[]): ScoutRun[] {- return runs- .filter((run) => (run.emitted_count ?? 0) > 0)- .sort((a, b) =>- (b.completed_at ?? b.started_at ?? "").localeCompare(- a.completed_at ?? a.started_at ?? "",- ),- )- .slice(0, MAX_FLEET_EMITTED_RUNS);-}--/**- * Cheap summary for the fleet callout — derived from the runs window alone, so- * it never triggers the per-run emissions fetch the findings page does on open.- */-export function summarizeEmittedRuns(runs: ScoutRun[]): ScoutFindingsSummary {- const emitted = mostRecentEmittedRuns(runs);- let totalCount = 0;- const scouts = new Set<string>();- let latestEmittedAt: string | null = null;- for (const run of emitted) {- totalCount += run.emitted_count ?? 0;- scouts.add(run.skill_name);- const at = run.completed_at ?? run.started_at;- if (at && (!latestEmittedAt || at > latestEmittedAt)) latestEmittedAt = at;- }- return { totalCount, scoutCount: scouts.size, latestEmittedAt };-}--/**- * Join emissions back to their run and the report their signal grouped into.- * Emissions whose run isn't in the window are dropped (the run set is the source- * of truth for what's shown). Reports are keyed by `source_id`.- */-export function buildScoutFindingRows(- emissions: ScoutEmission[],- emittedRuns: ScoutRun[],- reportLinks: ScoutEmissionReportLink[],-): ScoutFindingRow[] {- const runsById = new Map(emittedRuns.map((run) => [run.run_id, run]));- const reportBySourceId = new Map<string, LinkedSignalReport>();- for (const link of reportLinks) {- if (link.report) reportBySourceId.set(link.source_id, link.report);- }- const rows: ScoutFindingRow[] = [];- for (const emission of emissions) {- const run = runsById.get(emission.run_id);- if (!run) continue;- rows.push({- emission,- run,- linkedReport: reportBySourceId.get(emission.source_id) ?? null,- });- }- return rows;-}--/** Distinct scouts present in the rows, with a per-scout count, for the filter. */-export function availableScoutsFromRows(- rows: ScoutFindingRow[],-): ScoutFilterOption[] {- const counts = new Map<string, number>();- for (const row of rows) {- counts.set(row.run.skill_name, (counts.get(row.run.skill_name) ?? 0) + 1);- }- return [...counts.entries()]- .map(([skillName, count]) => ({- skillName,- label: prettifyScoutSkillName(skillName),- count,- }))- .sort((a, b) => a.label.localeCompare(b.label));-}--const byNewest = (a: ScoutFindingRow, b: ScoutFindingRow): number =>- (b.emission.emitted_at ?? "").localeCompare(a.emission.emitted_at ?? "");--/**- * Visible set: search (over finding text + prettified scout name) + scout +- * severity, then sort by the chosen key.- */-export function filterAndSortScoutFindings(- rows: ScoutFindingRow[],- filter: ScoutFindingsFilter,-): ScoutFindingRow[] {- const needle = filter.search.trim().toLowerCase();- const filtered = rows.filter((row) => {- if (- filter.scout !== SCOUT_FINDINGS_SCOUT_FILTER_ALL &&- row.run.skill_name !== filter.scout- ) {- return false;- }- if (- filter.severity !== SCOUT_FINDINGS_SEVERITY_FILTER_ALL &&- row.emission.severity !== filter.severity- ) {- return false;- }- if (needle) {- const haystack =- `${row.emission.description ?? ""} ${prettifyScoutSkillName(row.run.skill_name)}`.toLowerCase();- if (!haystack.includes(needle)) return false;- }- return true;- });- return filtered.sort((a, b) => {- if (filter.sort === "oldest") return -byNewest(a, b);- if (filter.sort === "severity") {- const diff =- severityRank(a.emission.severity) - severityRank(b.emission.severity);- return diff !== 0 ? diff : byNewest(a, b);- }- if (filter.sort === "confidence") {- const diff = (b.emission.confidence ?? 0) - (a.emission.confidence ?? 0);- return diff !== 0 ? diff : byNewest(a, b);- }- return byNewest(a, b);- });-}--/** Header tallies, computed from the joined rows (not the cheap window sum). */-export function summarizeScoutFindingRows(- rows: ScoutFindingRow[],-): ScoutFindingsSummary {- const scouts = new Set<string>();- let latestEmittedAt: string | null = null;- for (const row of rows) {- scouts.add(row.run.skill_name);- const at = row.emission.emitted_at;- if (at && (!latestEmittedAt || at > latestEmittedAt)) latestEmittedAt = at;- }- return {- totalCount: rows.length,- scoutCount: scouts.size,- latestEmittedAt,- };-}diff --git a/products/desktop/packages/core/src/scouts/scoutPresentation.test.ts b/products/desktop/packages/core/src/scouts/scoutPresentation.test.tsindex dd13803e43a0..54222d74ccf1 100644--- a/products/desktop/packages/core/src/scouts/scoutPresentation.test.ts+++ b/products/desktop/packages/core/src/scouts/scoutPresentation.test.ts@@ -14,9 +14,12 @@ import {formatScoutScheduleShort,getScoutOrigin,getScoutScheduleMode,+ hasPendingScoutRun,isRunStuck,isScoutCreatedByUser,listScoutCreatorOptions,+ listScoutsNeedingAttention,+ nextRunAt,normalizeRunStatus,prettifyScoutSkillName,runDurationSeconds,@@ -33,6 +36,7 @@ import {scoutSkillNameFromSlug,scoutSkillSlug,sortConfigsForDisplay,+ summarizeRunWindow,weeklyCronToDayTime,} from "./scoutPresentation";@@ -174,6 +178,14 @@ describe("run outcomes", () => {outcome: ReturnType<typeof deriveRunOutcome>;}>([{ overrides: { emitted_count: 2 }, outcome: "emitted" },+ {+ overrides: { emitted_count: 0, emitted_report_ids: ["report-1"] },+ outcome: "emitted",+ },+ {+ overrides: { emitted_count: 0, edited_report_ids: ["report-1"] },+ outcome: "emitted",+ },{ overrides: { emitted_count: 0 }, outcome: "quiet" },{overrides: { status: "failed", completed_at: "2026-06-10T11:00:30Z" },@@ -205,8 +217,8 @@ describe("run outcomes", () => {});it.each<{ overrides: Partial<ScoutRun>; label: string }>([- { overrides: { emitted_count: 1 }, label: "1 signal emitted" },- { overrides: { emitted_count: 0 }, label: "0 signals emitted" },+ { overrides: { emitted_count: 1 }, label: "1 output" },+ { overrides: { emitted_count: 0 }, label: "no output" },{overrides: { status: "failed", completed_at: "2026-06-10T11:30:10Z" },label: "timed out",@@ -294,7 +306,7 @@ describe("rollups", () => {makeRun({ emitted_count: 2 }),makeRun({ run_id: "x", status: "failed" }),]);- const summary = computeFleetSummary(configs, rollups);+ const summary = computeFleetSummary(configs, rollups, NOW);expect(summary).toMatchObject({totalCount: 2,enabledCount: 1,@@ -407,8 +419,8 @@ describe("intervals and ordering", () => {describe("lifecycle", () => {it.each([- ["ignored", "unacted on"],- ["no_output", "stopped emitting"],+ ["ignored", "nobody acted"],+ ["no_output", "stopped sending"],["repeated_failures", "3 runs in a row failed"],] as const)("explains a %s system pause", (reason, fragment) => {const state = deriveScoutLifecycle(@@ -442,7 +454,7 @@ describe("lifecycle", () => {pause_reason: "ignored",}),);- expect(state.explanation).toContain("can pause again later");+ expect(state.explanation).toContain("Switch it back on");expect(state.explanation).not.toMatch(/retries|on its own|exempt/i);});@@ -457,7 +469,7 @@ describe("lifecycle", () => {consecutive_failure_count: 6,}),);- expect(state.explanation).toContain("resumes on its own");+ expect(state.explanation).toContain("resumes when a run succeeds");});it("flags an ignored warning as heading for a pause", () => {@@ -774,3 +786,46 @@ describe("schedule modes", () => {expect(scoutCronScheduleError(expression)).toBe(expected);});});++describe("agent schedule and history", () => {+ it.each([+ { overrides: { run_cron_schedule: "0 9 * * *" }, expected: null },+ { overrides: { run_cron_schedule: "30 8 * * 4" }, expected: null },+ { overrides: { last_run_at: null }, expected: NOW },+ { overrides: { enabled: false, last_run_at: null }, expected: null },+ { overrides: {}, expected: NOW },+ ])(+ "uses the available schedule fields: $overrides",+ ({ overrides, expected }) => {+ expect(nextRunAt(makeConfig(overrides), NOW)).toEqual(expected);+ },+ );++ it.each(["in_progress", "queued"])(+ "does not call a mixed %s window finished",+ (status) => {+ const runs = [+ makeRun(),+ makeRun({+ run_id: "pending",+ status,+ started_at: "2026-06-10T11:59:00Z",+ completed_at: null,+ }),+ ];+ const rollup = computeScoutRollups(runs).get(runs[0].skill_name);+ expect(summarizeRunWindow(rollup, NOW)).not.toContain("all finished");+ expect(hasPendingScoutRun(rollup)).toBe(true);+ },+ );++ it("keeps a failure streak visible without a loaded run", () => {+ const attention = listScoutsNeedingAttention(+ [makeConfig({ consecutive_failure_count: 3 })],+ new Map(),+ NOW,+ );+ expect(attention).toHaveLength(1);+ expect(attention[0].kind).toBe("failing");+ });+});diff --git a/products/desktop/packages/core/src/scouts/scoutPresentation.ts b/products/desktop/packages/core/src/scouts/scoutPresentation.tsindex 81a7f08b74cb..0fe5df80699d 100644--- a/products/desktop/packages/core/src/scouts/scoutPresentation.ts+++ b/products/desktop/packages/core/src/scouts/scoutPresentation.ts@@ -77,27 +77,27 @@ function warnedCopy(return {label: "Pausing soon",explanation:- "Its findings have been going unacted on, so the inactivity sweep will pause this scout soon. Act on a finding, or exempt it from inactivity pauses, to keep it running.",+ "Nobody acted on its signals, so PostHog pauses this agent soon. Act on a signal, or exempt it from inactivity pauses, to keep it running.",willPause: true,};case "no_output":return {label: "Quiet",explanation:- "This scout has surfaced nothing lately, so the inactivity sweep flagged it for a look. Staying quiet on its own never pauses a scout, so nothing happens unless someone acts.",+ "This agent has sent nothing lately, so PostHog flagged it for a look. Staying quiet never pauses an agent on its own.",willPause: false,};case "repeated_failures":return {label: "Pausing soon",- explanation: `PostHog will pause this scout soon because ${failureCountClause(failureCount)}. Fix the skill to keep it running.`,+ explanation: `PostHog pauses this agent soon because ${failureCountClause(failureCount)}. Fix the skill to keep it running.`,willPause: true,};default:return {label: "Pausing soon",explanation:- "PostHog is about to pause this scout. Exempt it from inactivity pauses to keep it running.",+ "PostHog is about to pause this agent. Exempt it from inactivity pauses to keep it running.",willPause: true,};}@@ -109,15 +109,15 @@ function systemPausedExplanation(): string {switch (reason) {case "ignored":- return "PostHog paused this scout because its findings were going unacted on. Switch it back on to resume. It can pause again later unless its findings get acted on.";+ return "PostHog paused this agent because nobody acted on its signals. Switch it back on to resume. It can pause again if nobody acts on its signals. Enable Never pause for inactivity to prevent inactivity pauses.";case "no_output":- return "PostHog paused this scout because it stopped emitting findings. Switch it back on to resume. Staying quiet on its own will not pause it again.";+ return "PostHog paused this agent because it stopped sending signals. Switch it back on to resume.";case "repeated_failures":// The breaker keeps a half-open probe on this reason, so this one recovers// without anyone touching it. Say so, or the badge reads as terminal.- return `PostHog paused this scout because ${failureCountClause(failureCount)}. It retries about once a day and resumes on its own once a run succeeds. Fix the skill, or switch it back on to retry right away.`;+ return `PostHog paused this agent because ${failureCountClause(failureCount)}. It retries about once a day and resumes when a run succeeds. Fix the skill, or switch it back on to retry now.`;default:- return "PostHog paused this scout. Switch it back on to resume.";+ return "PostHog paused this agent. Switch it back on to resume.";}}@@ -176,6 +176,108 @@ export function deriveScoutLifecycle(config: ScoutConfig): ScoutLifecycleState {};}+export interface ScoutHealthNotice {+ text: string;+ tone: "warning" | "destructive";+ /** The one config change that clears the notice, when there is one. */+ action: "resume" | "keep_running" | null;+ /** Where to look for the cause. */+ link: "output" | "activity" | null;+}++/**+ * The banner on the agent page. Shorter than `explanation` because the+ * buttons beside it carry the instruction. Null when the agent is healthy.+ */+export function scoutHealthNotice(+ config: ScoutConfig,+): ScoutHealthNotice | null {+ const lifecycle = deriveScoutLifecycle(config);+ const failures = failureCountClause(lifecycle.consecutiveFailureCount);+ if (lifecycle.isSystemPaused) {+ switch (lifecycle.reason) {+ case "ignored":+ return {+ text: "PostHog paused this agent because nobody acted on its signals. Resume starts a new grace period. Enable Never pause for inactivity to prevent another inactivity pause.",+ tone: "destructive",+ action: "resume",+ link: "output",+ };+ case "no_output":+ return {+ text: "PostHog paused this agent because it stopped sending signals.",+ tone: "destructive",+ action: "resume",+ link: "activity",+ };+ case "repeated_failures":+ return {+ text: `PostHog paused this agent because ${failures}. It retries about once a day.`,+ tone: "destructive",+ action: "resume",+ link: "activity",+ };+ default:+ return {+ text: "PostHog paused this agent.",+ tone: "destructive",+ action: "resume",+ link: null,+ };+ }+ }+ if (!lifecycle.isWarned) return null;+ const canExempt = lifecycle.autoPauseExempt === false;+ switch (lifecycle.reason) {+ case "ignored":+ return {+ text: "Nobody acted on its signals. PostHog pauses this agent soon.",+ tone: "warning",+ action: canExempt ? "keep_running" : null,+ link: "output",+ };+ case "no_output":+ return {+ text: "This agent has sent nothing lately. Staying quiet never pauses an agent on its own.",+ tone: "warning",+ action: canExempt ? "keep_running" : null,+ link: "activity",+ };+ case "repeated_failures":+ return {+ text: `${failures.charAt(0).toUpperCase()}${failures.slice(1)}. PostHog pauses this agent soon.`,+ tone: "warning",+ action: null,+ link: "activity",+ };+ default:+ return {+ text: "PostHog pauses this agent soon.",+ tone: "warning",+ action: canExempt ? "keep_running" : null,+ link: null,+ };+ }+}++const SUMMARY_MAX_CHARS = 140;++/**+ * One line for the agent header. Descriptions are skill prose written for a+ * model, so take the first sentence and cut it at a word when it still runs long.+ */+export function scoutSummarySentence(+ description: string | undefined,+): string | null {+ const text = description?.trim().replace(/\s+/g, " ");+ if (!text) return null;+ const sentenceEnd = text.search(/[.!?](\s|$)/);+ const sentence = sentenceEnd === -1 ? text : text.slice(0, sentenceEnd + 1);+ if (sentence.length <= SUMMARY_MAX_CHARS) return sentence;+ const cut = sentence.slice(0, SUMMARY_MAX_CHARS);+ return `${cut.slice(0, cut.lastIndexOf(" "))}…`;+}+/** "signals-scout-error-tracking" → "Error tracking" */export function prettifyScoutSkillName(skillName: string): string {const cleaned = skillName@@ -384,10 +486,35 @@ export type ScoutRunOutcome =| "queued"| "unknown";+export function scoutRunOutputCount(run: ScoutRun): number {+ return (run.emitted_count ?? 0) + scoutRunReports(run).length;+}++export function scoutRunReports(+ run: ScoutRun,+): { id: string; action: "created" | "updated" }[] {+ const created = new Set(run.emitted_report_ids ?? []);+ const updated = new Set(run.edited_report_ids ?? []);+ return [+ ...[...created].map((id) => ({ id, action: "created" as const })),+ ...[...updated]+ .filter((id) => !created.has(id))+ .map((id) => ({ id, action: "updated" as const })),+ ];+}++export function hasPendingScoutRun(rollup: ScoutRollup | undefined): boolean {+ return (+ rollup?.runs.some((run) =>+ ["running", "queued"].includes(normalizeRunStatus(run.status)),+ ) ?? false+ );+}+export function deriveRunOutcome(run: ScoutRun, now: Date): ScoutRunOutcome {const status = normalizeRunStatus(run.status);if (status === "completed") {- return (run.emitted_count ?? 0) > 0 ? "emitted" : "quiet";+ return scoutRunOutputCount(run) > 0 ? "emitted" : "quiet";}if (status === "failed") {return deriveRunFailureKind(run, now) === "timed_out"@@ -402,11 +529,11 @@ export function deriveRunOutcome(run: ScoutRun, now: Date): ScoutRunOutcome {export function scoutRunOutcomeLabel(run: ScoutRun, now: Date): string {switch (deriveRunOutcome(run, now)) {case "emitted": {- const count = run.emitted_count ?? 0;- return `${count} signal${count === 1 ? "" : "s"} emitted`;+ const count = scoutRunOutputCount(run);+ return `${count} output${count === 1 ? "" : "s"}`;}case "quiet":- return "0 signals emitted";+ return "no output";case "error":return "failed";case "timed_out":@@ -414,7 +541,7 @@ export function scoutRunOutcomeLabel(run: ScoutRun, now: Date): string {case "running":return "running now";case "stuck":- return "running past the deadline – may be stuck";+ return "running past the deadline, may be stuck";case "queued":return "queued";case "unknown":@@ -433,9 +560,9 @@ export function runMatchesFilter(case "all":return true;case "emitted":- return (run.emitted_count ?? 0) > 0;+ return scoutRunOutputCount(run) > 0;case "quiet":- return status === "completed" && (run.emitted_count ?? 0) === 0;+ return status === "completed" && scoutRunOutputCount(run) === 0;case "failed":return status === "failed";}@@ -484,7 +611,7 @@ export function computeScoutRollups(const status = normalizeRunStatus(run.status);if (status === "completed") rollup.completedCount += 1;if (status === "failed") rollup.failedCount += 1;- rollup.emittedCount += run.emitted_count ?? 0;+ rollup.emittedCount += scoutRunOutputCount(run);rollup.runs.push(run);const startedAt = run.started_at ? new Date(run.started_at).getTime() : 0;const latestStartedAt = rollup.latestRun?.started_at@@ -525,6 +652,7 @@ export interface FleetSummary {export function computeFleetSummary(configs: ScoutConfig[],rollups: Map<string, ScoutRollup>,+ now: Date = new Date(),): FleetSummary {let runningCount = 0;let emittedCount = 0;@@ -533,13 +661,17 @@ export function computeFleetSummary(let runCount = 0;let emittedRunCount = 0;for (const rollup of rollups.values()) {- if (rollup.runningRun) runningCount += 1;+ if (+ rollup.runningRun &&+ deriveRunOutcome(rollup.runningRun, now) === "running"+ )+ 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;+ if (scoutRunOutputCount(run) > 0) emittedRunCount += 1;}}const lifecycles = configs.map(deriveScoutLifecycle);@@ -873,3 +1005,156 @@ export function sortConfigsForDisplay(configs: ScoutConfig[]): ScoutConfig[] {}).map((entry) => entry.config);}++// Cron times need the project timezone, which this response does not include.+export function nextRunAt(+ config: ScoutConfig,+ now: Date = new Date(),+): Date | null {+ if (!config.enabled || config.run_cron_schedule) return null;+ if (!config.last_run_at) return now;+ const last = new Date(config.last_run_at).getTime();+ if (Number.isNaN(last)) return null;+ return new Date(last + config.run_interval_minutes * 60 * 1000);+}++export function medianRunDurationSeconds(+ runs: ScoutRun[],+ now: Date,+): number | null {+ const durations = runs+ .filter((run) => normalizeRunStatus(run.status) === "completed")+ .map((run) => runDurationSeconds(run, now))+ .filter((seconds): seconds is number => seconds !== null)+ .sort((a, b) => a - b);+ if (durations.length === 0) return null;+ const middle = Math.floor(durations.length / 2);+ return durations.length % 2 === 0+ ? (durations[middle - 1] + durations[middle]) / 2+ : durations[middle];+}++function plural(count: number, noun: string): string {+ return `${count} ${noun}${count === 1 ? "" : "s"}`;+}++/** "3 runs · all finished · no signals · about 3m each" for the activity tab. */+export function summarizeRunWindow(+ rollup: ScoutRollup | undefined,+ now: Date,+): string | null {+ if (!rollup || rollup.runCount === 0) return null;+ const parts = [plural(rollup.runCount, "run")];+ const finished = rollup.completedCount + rollup.failedCount;+ if (rollup.failedCount > 0) parts.push(`${rollup.failedCount} failed`);+ else if (finished === rollup.runCount) parts.push("all finished");+ const runningCount = rollup.runs.filter(+ (run) => deriveRunOutcome(run, now) === "running",+ ).length;+ if (runningCount > 0) parts.push(`${runningCount} running now`);+ parts.push(+ rollup.emittedCount > 0+ ? plural(rollup.emittedCount, "output")+ : "no output",+ );+ const median = formatRunDuration(medianRunDurationSeconds(rollup.runs, now));+ if (median) parts.push(`about ${median} each`);+ return parts.join(" · ");+}++export type ScoutAttentionKind = "auto_paused" | "pausing_soon" | "failing";++export interface ScoutAttention {+ kind: ScoutAttentionKind;+ config: ScoutConfig;+ detail: string;+}++function attentionReason(+ reason: ScoutPauseReason | null,+ failureCount: number,+): string {+ switch (reason) {+ case "ignored":+ return "Nobody acted on its signals.";+ case "no_output":+ return "It stopped sending signals.";+ case "repeated_failures":+ return `${failureCount > 1 ? `${failureCount} runs` : "Its runs"} in a row failed.`;+ default:+ return "PostHog flagged it.";+ }+}++/** Runs failed back to back before the row reads as failing. */+const FAILING_STREAK = 2;++/**+ * The scouts a person should look at before anything else: the ones the+ * system stopped, is about to stop, or that keep failing. Ordered by urgency.+ */+export function listScoutsNeedingAttention(+ configs: ScoutConfig[],+ rollups: Map<string, ScoutRollup>,+ now: Date,+): ScoutAttention[] {+ const out: ScoutAttention[] = [];+ for (const config of configs) {+ const lifecycle = deriveScoutLifecycle(config);+ if (lifecycle.isSystemPaused) {+ out.push({+ kind: "auto_paused",+ config,+ detail: attentionReason(+ lifecycle.reason,+ lifecycle.consecutiveFailureCount,+ ),+ });+ continue;+ }+ if (lifecycle.willPause) {+ out.push({+ kind: "pausing_soon",+ config,+ detail: `${attentionReason(lifecycle.reason, lifecycle.consecutiveFailureCount)} PostHog pauses it soon.`,+ });+ continue;+ }+ const streak = config.consecutive_failure_count ?? 0;+ const latestRun = rollups.get(config.skill_name)?.latestRun ?? null;+ const latestFailed =+ latestRun !== null && normalizeRunStatus(latestRun.status) === "failed";+ if (+ config.enabled &&+ (!latestRun || latestFailed) &&+ streak >= FAILING_STREAK+ ) {+ const kind = latestRun ? deriveRunFailureKind(latestRun, now) : null;+ out.push({+ kind: "failing",+ config,+ detail: `${streak} runs in a row ${kind === "timed_out" ? "timed out" : "failed"}. PostHog pauses it after a few more.`,+ });+ }+ }+ const order: Record<ScoutAttentionKind, number> = {+ auto_paused: 0,+ failing: 1,+ pausing_soon: 2,+ };+ return out.sort((a, b) => order[a.kind] - order[b.kind]);+}++/** "in 4h", "in 12m", "due now"; null when there is no next run. */+export function formatNextRun(next: Date | null, now: Date): string | null {+ if (!next) return null;+ const minutes = Math.round((next.getTime() - now.getTime()) / 60000);+ if (minutes <= 0) return "due now";+ if (minutes < 60) return `in ${minutes}m`;+ const hours = Math.floor(minutes / 60);+ if (hours < 24) {+ const rest = minutes % 60;+ return rest > 0 ? `in ${hours}h ${rest}m` : `in ${hours}h`;+ }+ return `in ${Math.round(hours / 24)}d`;+}diff --git a/products/desktop/packages/core/src/scouts/scoutPrompts.test.ts b/products/desktop/packages/core/src/scouts/scoutPrompts.test.tsindex 443e86af9aac..6f92e9bf89f7 100644--- a/products/desktop/packages/core/src/scouts/scoutPrompts.test.ts+++ b/products/desktop/packages/core/src/scouts/scoutPrompts.test.ts@@ -22,7 +22,7 @@ describe("buildScoutFindingDiscussPrompt", () => {expect(prompt).toContain("Severity: high");expect(prompt).toContain("Confidence: 82%");expect(prompt).toContain(base.description);- expect(prompt).toContain("exploring-signals-scouts");+ expect(prompt).toContain("exploring-scouts");});it.each([diff --git a/products/desktop/packages/core/src/scouts/scoutPrompts.ts b/products/desktop/packages/core/src/scouts/scoutPrompts.tsindex 5418b578e8d0..9463e9c63824 100644--- a/products/desktop/packages/core/src/scouts/scoutPrompts.ts+++ b/products/desktop/packages/core/src/scouts/scoutPrompts.ts@@ -1,10 +1,10 @@// Templated prompts behind the scout chat CTA chips. The agent leans on the-// exploring-signals-scouts and authoring-signals-scouts skills from the+// exploring-scouts and authoring-scouts skills from the// PostHog MCP.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.+Use the authoring-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.@@ -12,9 +12,25 @@ Then ask me what sort of scout I'd like to make, and offer a few concrete suggesIf 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.`;+/**+ * The authoring prompt, led by what the person typed in the New agent dialog.+ * An empty brief falls back to the open-ended template.+ */+export function buildScoutAuthorPrompt(brief: string): string {+ const trimmed = brief.trim();+ if (!trimmed) return SCOUT_AUTHOR_PROMPT;+ return `I'd like to make a new scout for this PostHog project. Here is what it should do:++${trimmed}++Use the authoring-scouts skill from the PostHog MCP to author this scout end to end. Take a quick scan of the project first (events, insights, existing scouts, recent signals) so the scout's thresholds and scope fit the data. Ask me only what you cannot infer, then create the scout as a dry run and tell me how to review its first output.++If the skill is unavailable, fall back to the signals-scout MCP tools directly.`;+}+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:+Use the exploring-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@@ -26,7 +42,7 @@ Lead with a short overall verdict, then per-scout notes only where something isexport 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:+Use the exploring-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@@ -82,7 +98,7 @@ ${: "Give me a brief readout on what this finding means and whether it looks genuinely actionable or like noise, then ask what I want to dig into."}-Use the exploring-signals-scouts skill from the PostHog MCP to ground your investigation: fetch this exact run's emissions (run ${runId}) for the finding's full context, pull the \`${skillName}\` scout's recent runs, cross-reference the relevant product data, and assess whether it's real and worth acting on. If the skill is unavailable, fall back to the signals-scout MCP tools directly (config list, runs list, run emissions) plus the read-data and insight tools.`;+Use the exploring-scouts skill from the PostHog MCP to ground your investigation: fetch this exact run's emissions (run ${runId}) for the finding's full context, pull the \`${skillName}\` scout's recent runs, cross-reference the relevant product data, and assess whether it's real and worth acting on. If the skill is unavailable, fall back to the signals-scout MCP tools directly (config list, runs list, run emissions) plus the read-data and insight tools.`;}/** Per-scout variant of the templated questions, scoped to one skill. */@@ -92,7 +108,7 @@ export function buildScoutCheckinPrompt(): 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:+Use the exploring-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, durationsdiff --git a/products/desktop/packages/core/src/scouts/scoutRunsWindow.test.ts b/products/desktop/packages/core/src/scouts/scoutRunsWindow.test.tsindex 6c09d0222cc9..9d84294ff018 100644--- a/products/desktop/packages/core/src/scouts/scoutRunsWindow.test.ts+++ b/products/desktop/packages/core/src/scouts/scoutRunsWindow.test.ts@@ -1,4 +1,7 @@-import type { ScoutRun } from "@posthog/api-client/posthog-client";+import type {+ ScoutRun,+ ScoutRunsQueryParams,+} from "@posthog/api-client/posthog-client";import { describe, expect, it } from "vitest";import {fetchScoutRunsWindow,@@ -17,6 +20,9 @@ function makeRun(id: string, startedAt: string | null): ScoutRun {skill_version: 1,status: "completed",started_at: startedAt,+ created_at: startedAt+ ? new Date(new Date(startedAt).getTime() + 30_000).toISOString()+ : undefined,completed_at: startedAt,task_id: null,task_run_id: null,@@ -29,10 +35,9 @@ function makeRun(id: string, startedAt: string | null): ScoutRun {function clientFromPages(pages: ScoutRun[][]): {client: ScoutRunsClient;- calls: Array<{ date_from?: string; date_to?: string; limit?: number }>;+ calls: ScoutRunsQueryParams[];} {- const calls: Array<{ date_from?: string; date_to?: string; limit?: number }> =- [];+ const calls: ScoutRunsQueryParams[] = [];let index = 0;return {calls,@@ -85,12 +90,22 @@ describe("fetchScoutRunsWindow", () => {const second = [boundary, makeRun("p2-0", "2026-06-10T01:00:00.000Z")];const { client, calls } = clientFromPages([first, second]);- const window = await fetchScoutRunsWindow(client, 1, NOW);+ const window = await fetchScoutRunsWindow(+ client,+ 1,+ NOW,+ undefined,+ "signals-scout-general",+ );expect(window.complete).toBe(true);expect(window.runs).toHaveLength(101);expect(calls).toHaveLength(2);- expect(calls[1]?.date_to).toBe(boundary.started_at);+ expect(calls.map((call) => call.skill_name)).toEqual([+ "signals-scout-general",+ "signals-scout-general",+ ]);+ expect(calls[1]?.date_to).toBe(boundary.created_at);});it("reports an incomplete window when the cursor cannot advance", async () => {diff --git a/products/desktop/packages/core/src/scouts/scoutRunsWindow.ts b/products/desktop/packages/core/src/scouts/scoutRunsWindow.tsindex 7b2a11f1e180..044b9191d929 100644--- a/products/desktop/packages/core/src/scouts/scoutRunsWindow.ts+++ b/products/desktop/packages/core/src/scouts/scoutRunsWindow.ts@@ -39,24 +39,22 @@ export interface ScoutRunsWindow {complete: boolean;}+/** The window as a span, e.g. "last 3 days", with no completeness suffix. */+export const SCOUT_RUNS_WINDOW_LABEL = `last ${SCOUT_RUNS_WINDOW_SPAN}`;+/** Label for stats derived from a window, e.g. "last 3 days". */export function scoutRunsWindowLabel(window?: ScoutRunsWindow): string {const base = `last ${SCOUT_RUNS_WINDOW_SPAN}`;return window && !window.complete ? `${base} · truncated` : base;}-/**- * Fetch every fleet run from the last SCOUT_RUNS_WINDOW_HOURS hours.- *- * The backend filters and orders on `created_at` but does not serialize it;- * `started_at` (the linked TaskRun's creation time) is the closest available- * cursor, so pages are deduped by run_id to absorb boundary drift between the- * two timestamps.- */export async function fetchScoutRunsWindow(client: ScoutRunsClient,projectId: number,now: Date = new Date(),+ /** Called with the runs collected so far after each page, newest page first. */+ onPage?: (partial: ScoutRunsWindow) => void,+ skillName?: string,): Promise<ScoutRunsWindow> {const dateFrom = new Date(now.getTime() - SCOUT_RUNS_WINDOW_HOURS * 60 * 60 * 1000,@@ -67,34 +65,36 @@ export async function fetchScoutRunsWindow(for (let page = 0; page < MAX_PAGES; page++) {const batch = await client.listScoutRuns(projectId, {+ skill_name: skillName,date_from: dateFrom,date_to: dateTo,limit: PAGE_LIMIT,});let added = 0;- let oldestStartedAt: string | undefined;+ let oldestCreatedAt: string | undefined;for (const run of batch) {if (!runsById.has(run.run_id)) {runsById.set(run.run_id, run);added++;}if (- run.started_at &&- (!oldestStartedAt || run.started_at < oldestStartedAt)+ run.created_at &&+ (!oldestCreatedAt || run.created_at < oldestCreatedAt)) {- oldestStartedAt = run.started_at;+ oldestCreatedAt = run.created_at;}}if (batch.length < PAGE_LIMIT) {return { runs: [...runsById.values()], complete: true };}- if (added === 0 || !oldestStartedAt || oldestStartedAt === dateTo) {- // Cursor cannot move: either pure duplicates or runs without started_at.+ if (added === 0 || !oldestCreatedAt || oldestCreatedAt === dateTo) {+ // Cursor cannot move: either pure duplicates or runs without created_at.return { runs: [...runsById.values()], complete: false };}- dateTo = oldestStartedAt;+ dateTo = oldestCreatedAt;+ onPage?.({ runs: [...runsById.values()], complete: false });}return { runs: [...runsById.values()], complete: false };diff --git a/products/desktop/packages/core/src/scouts/scoutSuggestions.test.ts b/products/desktop/packages/core/src/scouts/scoutSuggestions.test.tsnew file mode 100644index 000000000000..0e80084c8225--- /dev/null+++ b/products/desktop/packages/core/src/scouts/scoutSuggestions.test.ts@@ -0,0 +1,64 @@+import type { ScoutSuggestionItem } from "@posthog/api-client/posthog-client";+import { describe, expect, it } from "vitest";+import { suggestionBrief, suggestionMetaLine } from "./scoutSuggestions";++describe("suggestionMetaLine", () => {+ it.each([+ [+ "a daily cron",+ {+ run_cron_schedule: "0 9 * * *",+ run_interval_minutes: null,+ emit: true,+ },+ "Runs daily at 09:00 · sends what it finds to Self-driving",+ ],+ [+ "no schedule at all",+ { run_cron_schedule: null, run_interval_minutes: null, emit: true },+ "Runs daily · sends what it finds to Self-driving",+ ],+ [+ "a dry run",+ {+ run_cron_schedule: null,+ run_interval_minutes: 180,+ emit: false,+ },+ "Runs every 3h · dry run, sends nothing",+ ],+ ])("reads back %s", (_name, config, expected) => {+ expect(suggestionMetaLine(config)).toBe(expected);+ });+});++describe("suggestionBrief", () => {+ const item = (description: string): ScoutSuggestionItem => ({+ id: "s1",+ kind: "custom",+ skill_name: "signals-scout-checkout-funnel",+ title: "Watch the checkout funnel for step drops",+ why_here: "This project sends checkout events every day.",+ description,+ draft_body: "",+ proposed_config: {+ run_cron_schedule: null,+ run_interval_minutes: null,+ emit: true,+ },+ gap: true,+ confidence: "high",+ });++ it("carries the description when there is one", () => {+ expect(suggestionBrief(item("Compare each step against last week."))).toBe(+ "Watch the checkout funnel for step drops. Compare each step against last week.",+ );+ });++ it("falls back to the title alone", () => {+ expect(suggestionBrief(item(" "))).toBe(+ "Watch the checkout funnel for step drops",+ );+ });+});diff --git a/products/desktop/packages/core/src/scouts/scoutSuggestions.ts b/products/desktop/packages/core/src/scouts/scoutSuggestions.tsnew file mode 100644index 000000000000..8e13fb7b6f53--- /dev/null+++ b/products/desktop/packages/core/src/scouts/scoutSuggestions.ts@@ -0,0 +1,44 @@+import type {+ ScoutSuggestionItem,+ ScoutSuggestionProposedConfig,+} from "@posthog/api-client/posthog-client";+import { formatScoutScheduleShort } from "./scoutPresentation";++/** Minutes between runs for a suggestion that names no schedule of its own. */+export const DEFAULT_SUGGESTION_INTERVAL_MINUTES = 1440;++/** How often the suggested agent would run, in the roster's own words. */+export function suggestionCadenceLabel(+ config: ScoutSuggestionProposedConfig,+): string {+ return formatScoutScheduleShort({+ run_cron_schedule: config.run_cron_schedule,+ run_interval_minutes:+ config.run_interval_minutes ?? DEFAULT_SUGGESTION_INTERVAL_MINUTES,+ });+}++/** One line on what the agent would do: how often, and where its output goes. */+export function suggestionMetaLine(+ config: ScoutSuggestionProposedConfig,+): string {+ const output = config.emit+ ? "sends what it finds to Self-driving"+ : "dry run, sends nothing";+ return `Runs ${suggestionCadenceLabel(config)} · ${output}`;+}++/** What the primary action on a suggestion does. */+export function suggestionActionLabel(item: ScoutSuggestionItem): string {+ return item.kind === "canonical" ? "Turn on" : "Draft it";+}++/**+ * The brief a custom draft hands the authoring chat. The title says what to+ * watch and the description carries the shape, so the chat starts from the+ * suggestion rather than from an empty box.+ */+export function suggestionBrief(item: ScoutSuggestionItem): string {+ const description = item.description.trim();+ return description ? `${item.title}. ${description}` : item.title;+}diff --git a/products/desktop/packages/shared/src/analytics-events.ts b/products/desktop/packages/shared/src/analytics-events.tsindex 9bd7a2024a9a..08c3599023ca 100644--- a/products/desktop/packages/shared/src/analytics-events.ts+++ b/products/desktop/packages/shared/src/analytics-events.ts@@ -949,7 +949,15 @@ type ScoutActionType =| "close_settings"| "open_findings"| "filter_findings"- | "sort_findings";+ | "sort_findings"+ | "run_now"+ | "open_new_agent"+ | "accept_suggestion"+ | "draft_suggestion"+ | "dismiss_suggestion"+ | "filter_origin"+ | "search_agents"+ | "switch_detail_tab";/*** How the fleet materialization that preceded this view ended. Without it andiff --git a/products/desktop/packages/ui/src/features/agents/agentsPageStore.test.tsx b/products/desktop/packages/ui/src/features/agents/agentsPageStore.test.tsxnew file mode 100644index 000000000000..850042c43fe4--- /dev/null+++ b/products/desktop/packages/ui/src/features/agents/agentsPageStore.test.tsx@@ -0,0 +1,55 @@+import { act, renderHook } from "@testing-library/react";+import { describe, expect, it, vi } from "vitest";++const location = vi.hoisted(() => ({+ state: { tabId: "first" },+ href: "/settings/agents",+}));+vi.mock("@tanstack/react-router", () => ({+ useRouterState: ({+ select,+ }: {+ select: (state: { location: typeof location }) => unknown;+ }) => select({ location }),+}));+vi.mock("@posthog/ui/router/routerRef", () => ({+ getRouterOrNull: () => ({ history: { location } }),+}));++import {+ agentsPageActions,+ useAgentsPageActions,+ useAgentsTab,+ useOpenAgent,+} from "./agentsPageStore";++describe("agent browser tab selection", () => {+ it("restores a separate selection when tabs have the same href", () => {+ const { result, rerender } = renderHook(() => ({+ tab: useAgentsTab(),+ agent: useOpenAgent(),+ actions: useAgentsPageActions(),+ }));+ act(() =>+ result.current.actions.openAgent("first-agent", {+ findingId: "finding-1",+ }),+ );+ location.state.tabId = "second";+ rerender();+ expect(result.current.agent).toBeNull();+ act(() => result.current.actions.showTab("memory"));+ location.state.tabId = "first";+ rerender();+ expect(result.current.agent).toMatchObject({+ slug: "first-agent",+ tab: "output",+ findingId: "finding-1",+ });+ act(() => agentsPageActions().showTab("agents"));+ expect(result.current.agent).toBeNull();+ location.state.tabId = "second";+ rerender();+ expect(result.current.tab).toBe("memory");+ });+});diff --git a/products/desktop/packages/ui/src/features/agents/agentsPageStore.ts b/products/desktop/packages/ui/src/features/agents/agentsPageStore.tsnew file mode 100644index 000000000000..8ced00bca51d--- /dev/null+++ b/products/desktop/packages/ui/src/features/agents/agentsPageStore.ts@@ -0,0 +1,78 @@+import type { ScoutDetailTab } from "@posthog/core/scouts/scoutDetailTabs";+import { getRouterOrNull } from "@posthog/ui/router/routerRef";+import { useRouterState } from "@tanstack/react-router";+import { useMemo } from "react";+import { create } from "zustand";++export type AgentsTab = "agents" | "memory" | "setup";++interface OpenAgent {+ slug: string;+ tab: ScoutDetailTab;+ findingId?: string;+}++interface AgentsPageState {+ tab: AgentsTab;+ agent: OpenAgent | null;+}++const DEFAULT_STATE: AgentsPageState = { tab: "agents", agent: null };+const useStore = create<{ pages: Record<string, AgentsPageState> }>(() => ({+ pages: {},+}));++function usePageKey(): string {+ return useRouterState({+ select: (state) => state.location.state.tabId ?? "default",+ });+}++export function agentsPageActions(+ key = getRouterOrNull()?.history.location.state.tabId ?? "default",+) {+ const update = (change: (state: AgentsPageState) => AgentsPageState) => {+ useStore.setState((state) => ({+ pages: {+ ...state.pages,+ [key]: change(state.pages[key] ?? DEFAULT_STATE),+ },+ }));+ };+ return {+ showTab: (tab: AgentsTab) => update(() => ({ tab, agent: null })),+ openAgent: (+ slug: string,+ options?: { tab?: ScoutDetailTab; findingId?: string },+ ) =>+ update(() => ({+ tab: "agents",+ agent: {+ slug,+ tab: options?.tab ?? (options?.findingId ? "output" : "activity"),+ findingId: options?.findingId,+ },+ })),+ showAgentTab: (tab: ScoutDetailTab) =>+ update((state) =>+ state.agent+ ? { ...state, agent: { ...state.agent, tab, findingId: undefined } }+ : state,+ ),+ };+}++export function useAgentsTab() {+ const key = usePageKey();+ return useStore((state) => (state.pages[key] ?? DEFAULT_STATE).tab);+}++export function useOpenAgent() {+ const key = usePageKey();+ return useStore((state) => (state.pages[key] ?? DEFAULT_STATE).agent);+}++export function useAgentsPageActions() {+ const key = usePageKey();+ return useMemo(() => agentsPageActions(key), [key]);+}diff --git a/products/desktop/packages/ui/src/features/agents/components/AgentsTabLayout.tsx b/products/desktop/packages/ui/src/features/agents/components/AgentsTabLayout.tsxindex 746672d2bf80..111f01a74864 100644--- a/products/desktop/packages/ui/src/features/agents/components/AgentsTabLayout.tsx+++ b/products/desktop/packages/ui/src/features/agents/components/AgentsTabLayout.tsx@@ -1,41 +1,81 @@-import { RobotIcon } from "@phosphor-icons/react";-import { useSetHeaderContent } from "@posthog/ui/hooks/useSetHeaderContent";-import { type ReactNode, useMemo } from "react";+import {+ type AgentsTab,+ useAgentsPageActions,+} from "@posthog/ui/features/agents/agentsPageStore";+import { leaveSettings } from "@posthog/ui/features/settings/hooks/useOpenSettings";+import { TabStrip } from "@posthog/ui/primitives/TabStrip";+import { Link } from "@tanstack/react-router";+import type { ReactNode } from "react";-export function AgentsTabLayout({ children }: { children: ReactNode }) {- const headerContent = useMemo(- () => (- <div className="flex w-full min-w-0 items-center gap-2">- <RobotIcon size={12} className="shrink-0 text-gray-10" />- <span- className="truncate whitespace-nowrap font-medium text-[13px]"- title="Agents"- >- Agents- </span>- </div>- ),- [],- );- useSetHeaderContent(headerContent);+const TABS: readonly { key: AgentsTab; label: string }[] = [+ { key: "agents", label: "Agents" },+ { key: "memory", label: "Memory" },+ { key: "setup", label: "Setup" },+];++const TAB_DESCRIPTION: Record<AgentsTab, ReactNode> = {+ agents: (+ <>+ Scheduled agents that watch this project and write reports in{" "}+ <Link to="/inbox" onClick={leaveSettings} className="underline">+ Self-driving+ </Link>+ .+ </>+ ),+ memory:+ "Notes your agents keep about this project as they scan it: what they classified, ruled out, or named.",+ setup:+ "What your agents watch, what they can reach, and where their reports land.",+};++/** Page chrome shared by the tabs of the Agents settings page. */+export function AgentsTabLayout({+ tab,+ actions,+ fill = false,+ children,+}: {+ tab: AgentsTab;+ actions?: ReactNode;+ /** The tab owns the height and scrolls its own list, as the agent table does. */+ fill?: boolean;+ children: ReactNode;+}) {+ const { showTab } = useAgentsPageActions();return (<div className="flex h-full min-h-0 flex-col">- <div className="cursor-default select-none border-(--gray-5) border-b px-6 py-5">- <div className="flex flex-col gap-0.5">- <h1 className="font-bold text-[22px] text-gray-12 leading-tight tracking-tight">- Agents- </h1>+ <div className="flex shrink-0 items-end gap-3 border-(--gray-5) border-b px-6">+ <TabStrip+ tabs={TABS}+ value={tab}+ onValueChange={showTab}+ dataAttrPrefix="agents-tab"+ className="min-w-0 flex-1 overflow-x-auto"+ />+ {actions ? (+ <div className="flex shrink-0 items-center gap-2 pb-1.5">+ {actions}+ </div>+ ) : null}+ </div>++ {/* A filling tab scrolls its own list, so the page itself must not scroll. */}+ <div+ className={+ fill ? "flex min-h-0 flex-1 flex-col" : "min-h-0 flex-1 overflow-auto"+ }+ >+ <div+ className={`mx-auto flex w-full max-w-[90rem] flex-col gap-3 px-6 py-5 ${fill ? "min-h-0 flex-1" : ""}`}+ ><p className="max-w-3xl text-[12.5px] text-gray-11 leading-snug">- Self-driving agents that watch your project and surface work for- review.+ {TAB_DESCRIPTION[tab]}</p>+ {children}</div></div>-- <div className="min-h-0 flex-1 overflow-auto">- <div className="mx-auto max-w-4xl px-6 py-6">{children}</div>- </div></div>);}diff --git a/products/desktop/packages/ui/src/features/agents/components/AgentsView.tsx b/products/desktop/packages/ui/src/features/agents/components/AgentsView.tsxindex 1a8733d189e3..bf013b176a7c 100644--- a/products/desktop/packages/ui/src/features/agents/components/AgentsView.tsx+++ b/products/desktop/packages/ui/src/features/agents/components/AgentsView.tsx@@ -1,10 +1,117 @@+import { PlusIcon } from "@phosphor-icons/react";+import { Button } from "@posthog/quill";+import { ANALYTICS_EVENTS } from "@posthog/shared";+import {+ useAgentsPageActions,+ useAgentsTab,+ useOpenAgent,+} from "@posthog/ui/features/agents/agentsPageStore";import { ConfigureAgentsSection } from "@posthog/ui/features/inbox/components/ConfigureAgentsSection";+import { FleetOverviewButton } from "@posthog/ui/features/scouts/components/FleetOverviewButton";+import { NewAgentDialog } from "@posthog/ui/features/scouts/components/NewAgentDialog";+import { ScoutDetailView } from "@posthog/ui/features/scouts/components/ScoutDetailView";+import { ScoutsFleetView } from "@posthog/ui/features/scouts/components/ScoutsFleetView";+import { ScratchpadView } from "@posthog/ui/features/scouts/components/ScratchpadView";+import { getRouterOrNull } from "@posthog/ui/router/routerRef";+import { track } from "@posthog/ui/shell/analytics";+import { useEffect, useRef, useState } from "react";import { AgentsTabLayout } from "./AgentsTabLayout";+/** The Agents settings page: the fleet, what it found, and what it connects to. */export function AgentsView() {+ const tab = useAgentsTab();+ const agent = useOpenAgent();+ const { showTab } = useAgentsPageActions();++ const mounted = useRef(false);+ useEffect(() => {+ mounted.current = true;+ return () => {+ mounted.current = false;+ // StrictMode mounts again before this check. A real exit resets only this tab.+ queueMicrotask(() => {+ if (+ !mounted.current &&+ getRouterOrNull()?.state.location.pathname !== "/settings/agents"+ )+ showTab("agents");+ });+ };+ }, [showTab]);++ if (agent) {+ return (+ <ScoutDetailView+ skillSlug={agent.slug}+ highlightFindingId={agent.findingId}+ tab={agent.tab}+ />+ );+ }++ if (tab === "memory") return <MemoryTab />;+ if (tab === "setup") return <SetupTab />;+ return <FleetTab />;+}++function FleetTab() {+ const [newAgent, setNewAgent] = useState<{ brief: string } | null>(null);++ const openNewAgent = (brief = "") => {+ track(ANALYTICS_EVENTS.SCOUT_ACTION, {+ action_type: "open_new_agent",+ surface: "fleet_list",+ });+ setNewAgent({ brief });+ };++ return (+ <AgentsTabLayout+ tab="agents"+ fill+ actions={+ <>+ <FleetOverviewButton />+ <Button+ type="button"+ variant="primary"+ size="sm"+ onClick={() => openNewAgent()}+ data-attr="agents-new-agent"+ >+ <PlusIcon size={13} weight="bold" />+ New agent+ </Button>+ </>+ }+ >+ <ScoutsFleetView onNewAgent={openNewAgent} />+ <NewAgentDialog+ key={newAgent?.brief ?? ""}+ open={newAgent !== null}+ initialBrief={newAgent?.brief ?? ""}+ onOpenChange={(open) => {+ if (!open) setNewAgent(null);+ }}+ />+ </AgentsTabLayout>+ );+}++function MemoryTab() {+ return (+ <AgentsTabLayout tab="memory" fill>+ <ScratchpadView />+ </AgentsTabLayout>+ );+}++function SetupTab() {return (- <AgentsTabLayout>- <ConfigureAgentsSection />+ <AgentsTabLayout tab="setup">+ <div className="max-w-[800px]">+ <ConfigureAgentsSection />+ </div></AgentsTabLayout>);}diff --git a/products/desktop/packages/ui/src/features/auth/authQueries.ts b/products/desktop/packages/ui/src/features/auth/authQueries.tsindex 942d58b659fe..f07445aef8d8 100644--- a/products/desktop/packages/ui/src/features/auth/authQueries.ts+++ b/products/desktop/packages/ui/src/features/auth/authQueries.ts@@ -4,6 +4,7 @@ import {HOST_TRPC_CLIENT,type HostTrpcClient,} from "@posthog/host-router/client";+import { clearQuerySnapshots } from "@posthog/ui/hooks/useQuerySnapshot";import {IMPERATIVE_QUERY_CLIENT,type ImperativeQueryClient,@@ -37,4 +38,5 @@ export function clearAuthScopedQueries(): void {queryClient().removeQueries({predicate: (query) => query.meta?.authScoped === true,});+ clearQuerySnapshots();}diff --git a/products/desktop/packages/ui/src/features/browser-tabs/BrowserTabStrip.tsx b/products/desktop/packages/ui/src/features/browser-tabs/BrowserTabStrip.tsxindex 8763bce5cdf1..47397630d788 100644--- a/products/desktop/packages/ui/src/features/browser-tabs/BrowserTabStrip.tsx+++ b/products/desktop/packages/ui/src/features/browser-tabs/BrowserTabStrip.tsx@@ -745,7 +745,11 @@ function BrowserTabStripImpl() {});break;case "agents":- navigate({ to: "/agents", state });+ navigate({+ to: "/settings/$category",+ params: { category: "agents" },+ state,+ });break;case "loops":navigate({ to: "/loops", state });diff --git a/products/desktop/packages/ui/src/features/inbox/AGENTS.md b/products/desktop/packages/ui/src/features/inbox/AGENTS.mdindex e75072681569..35cd10644da1 100644--- a/products/desktop/packages/ui/src/features/inbox/AGENTS.md+++ b/products/desktop/packages/ui/src/features/inbox/AGENTS.md@@ -53,7 +53,7 @@ same artefact-lift pattern as `priority`/`actionability`/`already_addressed` —so cards avoid an N+1 per-card artefact fetch. Unknown reason codes fall back tothe raw value; cards with no dismissal artefact simply omit the label.-Responder configuration is **not** an Inbox tab. It is the top-level Responders sidebar item at `/agents`. The legacy `/inbox/agents` route redirects there.+Responder configuration is **not** an Inbox tab. It lives in Settings under the `agents` category (`/settings/agents`), on the Connections tab beside the scout fleet (`features/scouts/`). The legacy `/agents` and `/inbox/agents` routes redirect there.Reviewer scope is a UI preference stored in `inboxReviewerScopeStore`. It filters the list between reports suggested for the current user and reports for someone else. It does not change tab membership; the tab predicates are independent.@@ -124,7 +124,7 @@ Card headlines are derived client-side from `summary` by `utils/reportPresentati## Configuration Surface-Responder setup lives in `features/agents/components/AgentsView.tsx`, which mounts `ConfigureAgentsSection`. This surface composes existing GitHub, Slack, source-toggle, and MCP configuration pieces. Keep setup copy outcome-focused: the user is asking Self-driving to figure out what matters, not choosing internal artefact types.+Responder setup lives in `features/agents/components/AgentsView.tsx`, the Agents settings page, which mounts `ConfigureAgentsSection` on its Connections tab and the scout fleet on the others. This surface composes existing GitHub, Slack, source-toggle, and MCP configuration pieces. Keep setup copy outcome-focused: the user is asking Self-driving to figure out what matters, not choosing internal artefact types.Onboarding/setup should be task-backed when it starts work. Do not model it as a static checklist if the intended behavior is to launch an agent task.@@ -151,7 +151,7 @@ Components come from `@posthog/quill`; layout is `div`s with Tailwind. Radix is- Do not add any `@radix-ui/*` import. Use `@posthog/quill` plus `div` + Tailwind.- Do not reuse the deleted legacy `ReportListRow`, `ReportDetailPane`, or old list/detail stores.- Do not put page-level Inbox title or navigation into the global app header; `InboxView` owns the Inbox page chrome.-- Responder configuration stays at `/agents`. The Inbox header carries a "Configure agents" link to it, but do not embed configuration UI in the Inbox itself.+- Responder configuration stays in Settings (`/settings/agents`). The Inbox header carries a "Configure agents" link toward it, but do not embed configuration UI in the Inbox itself.- Scout (`signals_scout`) is a real Cloud source product. Keep it covered wherever source products surface: `INBOX_SOURCE_OPTIONS`, `SOURCE_PRODUCT_META`, and the scout-name display in `SignalCard`.- Scout management UI (fleet configuration, run history) lives in `features/scouts/` and is backed by the PostHog Cloud scout endpoints (`/api/projects/{teamId}/signals/scout/`). Do not add scout controls that have no backing endpoint there.- Do not put preview shims or mock report data in `apps/code/index.html`; the app shell should stay minimal.diff --git a/products/desktop/packages/ui/src/features/inbox/components/ConfigureAgentsSection.tsx b/products/desktop/packages/ui/src/features/inbox/components/ConfigureAgentsSection.tsxindex cd46228e3cac..f7bc070dc85f 100644--- a/products/desktop/packages/ui/src/features/inbox/components/ConfigureAgentsSection.tsx+++ b/products/desktop/packages/ui/src/features/inbox/components/ConfigureAgentsSection.tsx@@ -37,7 +37,6 @@ import {useUserRepositoryIntegration,} from "@posthog/ui/features/integrations/useIntegrations";import { toastError } from "@posthog/ui/features/notifications/errorDetails";-import { ScoutsFleetSection } from "@posthog/ui/features/scouts/components/ScoutsFleetSection";import { SettingsSubsection } from "@posthog/ui/features/settings/components/SettingsSubsection";import { DailyReportLimitSettings } from "@posthog/ui/features/settings/sections/DailyReportLimitSettings";import { GitHubIntegrationSection } from "@posthog/ui/features/settings/sections/GitHubIntegrationSection";@@ -138,27 +137,6 @@ export function ConfigureAgentsSection() {/></SettingsSubsection>- <SettingsSubsection- title="Scouts"- description={- <>- Scheduled agents that sweep this project on a cadence and emit- signals to Self-driving.{" "}- {/* Placeholder docs link until a dedicated scouts page exists. */}- <a- href="https://posthog.com/blog/self-driving-product"- target="_blank"- rel="noreferrer"- className="text-accent-11 no-underline hover:text-accent-12"- >- Learn more- </a>- </>- }- >- <ScoutsFleetSection />- </SettingsSubsection>-<SettingsSubsectiontitle="Signal sources"description="Each source watches for signals and spins up work when something matters."diff --git a/products/desktop/packages/ui/src/features/inbox/components/InboxPageHeader.tsx b/products/desktop/packages/ui/src/features/inbox/components/InboxPageHeader.tsxindex 0340b3ef44c3..ccd06eb8c3c3 100644--- a/products/desktop/packages/ui/src/features/inbox/components/InboxPageHeader.tsx+++ b/products/desktop/packages/ui/src/features/inbox/components/InboxPageHeader.tsx@@ -28,7 +28,7 @@ interface InboxPageHeaderProps {}/**- * Responder configuration lives at /agents, not in the inbox. The header+ * Responder configuration lives in Settings, not in the inbox. The header* carries this always-visible way there so the config surface stays one click* away from the work it powers.*/@@ -37,7 +37,7 @@ function ConfigureAgentsButton() {<Buttonvariant="primary"size="sm"- render={<Link to="/agents" />}+ render={<Link to="/settings/$category" params={{ category: "agents" }} />}className="shrink-0"><RobotIcon size={14} />diff --git a/products/desktop/packages/ui/src/features/inbox/components/ReportsInboxView.test.tsx b/products/desktop/packages/ui/src/features/inbox/components/ReportsInboxView.test.tsxindex 475799a0717f..f1c2654ec238 100644--- a/products/desktop/packages/ui/src/features/inbox/components/ReportsInboxView.test.tsx+++ b/products/desktop/packages/ui/src/features/inbox/components/ReportsInboxView.test.tsx@@ -9,7 +9,7 @@ const mocks = vi.hoisted(() => ({activeReports: [] as SignalReport[],setupStatusLoading: false,setupConfigured: true,- navigateToAgents: vi.fn(),+ navigateToSettings: vi.fn(),navigateToInboxReportDetail: vi.fn(),prefetchReport: vi.fn(),prefetchRoute: vi.fn(),@@ -149,7 +149,7 @@ vi.mock();vi.mock("@posthog/ui/router/navigationBridge", () => ({- navigateToAgents: mocks.navigateToAgents,+ navigateToSettings: mocks.navigateToSettings,navigateToInboxReportDetail: mocks.navigateToInboxReportDetail,}));@@ -266,7 +266,7 @@ describe("ReportsInboxView", () => {expect(screen.getByText("Ship fixes while you sleep")).toBeTruthy();expect(screen.getAllByText("Configure agents")).toHaveLength(1);await userEvent.click(screen.getByText("Configure agents"));- expect(mocks.navigateToAgents).toHaveBeenCalledOnce();+ expect(mocks.navigateToSettings).toHaveBeenCalledWith("agents");});it("shows the plain empty state instead of the welcome when something is configured", () => {diff --git a/products/desktop/packages/ui/src/features/inbox/components/ReportsInboxView.tsx b/products/desktop/packages/ui/src/features/inbox/components/ReportsInboxView.tsxindex 7b023b0be2b5..adac25507531 100644--- a/products/desktop/packages/ui/src/features/inbox/components/ReportsInboxView.tsx+++ b/products/desktop/packages/ui/src/features/inbox/components/ReportsInboxView.tsx@@ -21,7 +21,7 @@ import {hasActiveInboxFilters,useInboxSignalsFilterStore,} from "@posthog/ui/features/inbox/stores/inboxSignalsFilterStore";-import { navigateToAgents } from "@posthog/ui/router/navigationBridge";+import { navigateToSettings } from "@posthog/ui/router/navigationBridge";import { useNavigate } from "@tanstack/react-router";import { useCallback, useEffect, useMemo, useState } from "react";@@ -317,7 +317,7 @@ export function ReportsInboxView(): React.JSX.Element {renderReport={(report) => (<InboxReportRow key={report.id} report={report} />)}- onConfigureAgents={navigateToAgents}+ onConfigureAgents={() => navigateToSettings("agents")}onEnterTriage={() => setFocusMode(true)}onClearFilters={resetFilters}onLoadMore={loadMore}diff --git a/products/desktop/packages/ui/src/features/inbox/hooks/useInboxCloudTaskRunner.ts b/products/desktop/packages/ui/src/features/inbox/hooks/useInboxCloudTaskRunner.tsindex 7ff496b0760b..3190c9a91312 100644--- a/products/desktop/packages/ui/src/features/inbox/hooks/useInboxCloudTaskRunner.ts+++ b/products/desktop/packages/ui/src/features/inbox/hooks/useInboxCloudTaskRunner.ts@@ -117,7 +117,7 @@ export interface UseInboxCloudTaskRunnerOptions {export interface UseInboxCloudTaskRunnerReturn {/** Kick off the cloud-task flow. Resolves after the task is created (or failed). */- run: () => Promise<void>;+ run: () => Promise<boolean>;/** True while a task is being created. */isRunning: boolean;}@@ -151,7 +151,7 @@ export function useInboxCloudTaskRunner({const { isOnline } = useConnectivity();const run = useCallback(async () => {- if (isRunning) return;+ if (isRunning) return false;const log = logger.scope(loggerScope);const startedAt = Date.now();const trackActionResult = (@@ -177,13 +177,13 @@ export function useInboxCloudTaskRunner({if (!isOnline) {showOfflineToast();trackActionResult("failed", "offline");- return;+ return false;}if (!cloudRepository && !allowMissingRepository) {toast.error(copy.errorTitle, { description: copy.missingRepository });trackActionResult("failed", "missing_repository");- return;+ return false;}// A repo-less run has no GitHub identity; only resolve/require the user@@ -194,13 +194,13 @@ export function useInboxCloudTaskRunner({if (cloudRepository && !githubUserIntegrationId) {toast.error(copy.errorTitle, { description: copy.missingIntegration });trackActionResult("failed", "missing_integration");- return;+ return false;}if (!cloudRegion) {toast.error(copy.errorTitle, { description: copy.signedOut });trackActionResult("failed", "signed_out");- return;+ return false;}setIsRunning(true);@@ -231,7 +231,7 @@ export function useInboxCloudTaskRunner({toast.error(copy.errorTitle, { description: copy.missingModel });setIsRunning(false);trackActionResult("failed", "missing_model");- return;+ return false;}// The persisted effort belongs to `lastUsedModel`; if the resolver swapped in@@ -346,6 +346,7 @@ export function useInboxCloudTaskRunner({});}}+ return result.success;} catch (error) {trackActionResult("failed", "unexpected_error");toast.dismiss(toastId);@@ -354,6 +355,7 @@ export function useInboxCloudTaskRunner({error,reportId,});+ return false;} finally {setIsRunning(false);}diff --git a/products/desktop/packages/ui/src/features/scouts/components/AgentNameLink.tsx b/products/desktop/packages/ui/src/features/scouts/components/AgentNameLink.tsxnew file mode 100644index 000000000000..af8a4b60bf32--- /dev/null+++ b/products/desktop/packages/ui/src/features/scouts/components/AgentNameLink.tsx@@ -0,0 +1,30 @@+import type { ScoutConfig } from "@posthog/api-client/posthog-client";+import { prettifyScoutSkillName } from "@posthog/core/scouts/scoutPresentation";+import { ScoutNameHoverCard } from "./ScoutNameHoverCard";++/** The agent's name, opening its page. Resting on it shows what the agent does. */+export function AgentNameLink({+ config,+ onOpen,+ dataAttr,+}: {+ config: ScoutConfig;+ onOpen: () => void;+ dataAttr?: string;+}) {+ return (+ <ScoutNameHoverCard+ config={config}+ trigger={+ <button+ type="button"+ onClick={onOpen}+ className="cursor-pointer truncate border-0 bg-transparent p-0 text-left font-medium text-[13px] text-gray-12 hover:underline"+ data-attr={dataAttr}+ >+ {prettifyScoutSkillName(config.skill_name)}+ </button>+ }+ />+ );+}diff --git a/products/desktop/packages/ui/src/features/scouts/components/FleetFindingsCallout.tsx b/products/desktop/packages/ui/src/features/scouts/components/FleetFindingsCallout.tsxdeleted file mode 100644index ba2ee222c293..000000000000--- a/products/desktop/packages/ui/src/features/scouts/components/FleetFindingsCallout.tsx+++ /dev/null@@ -1,69 +0,0 @@-import { ArrowRightIcon, SparkleIcon } from "@phosphor-icons/react";-import { summarizeEmittedRuns } from "@posthog/core/scouts/scoutFindings";-import { ANALYTICS_EVENTS } from "@posthog/shared";-import { RelativeTimestamp } from "@posthog/ui/primitives/RelativeTimestamp";-import { navigateToScoutFindings } from "@posthog/ui/router/navigationBridge";-import { track } from "@posthog/ui/shell/analytics";-import { Flex, Text } from "@radix-ui/themes";-import { useMemo } from "react";-import { useScoutRuns } from "../hooks/useScoutRuns";--/**- * Findings entry point for the scout fleet section. Advertises the troop's recent- * findings (count · scouts · recency) and links into the cross-fleet findings- * page. Reads the cheap runs-window summary so it never triggers the per-run- * emissions fetch the page does on open. Renders nothing until there's at least- * one finding.- *- * Mirrors the PostHog Cloud `FleetFindingsCallout`.- */-export function FleetFindingsCallout() {- const { data: runsWindow, isLoading } = useScoutRuns();- const summary = useMemo(- () => summarizeEmittedRuns(runsWindow?.runs ?? []),- [runsWindow],- );-- // Hold until the first runs load settles, then only show when there's- // something to read.- if (isLoading || summary.totalCount === 0) {- return null;- }-- return (- <button- type="button"- onClick={() => {- track(ANALYTICS_EVENTS.SCOUT_ACTION, {- action_type: "open_findings",- surface: "fleet_list",- });- navigateToScoutFindings();- }}- className="flex w-full items-center gap-3 rounded-(--radius-2) border border-border bg-(--color-panel-solid) px-4 py-3.5 text-left transition-colors duration-150 hover:border-(--gray-6) hover:bg-(--gray-2)"- >- <SparkleIcon size={20} className="shrink-0 text-(--iris-9)" />- <Flex direction="column" gap="0" className="min-w-0">- <Text className="font-medium text-[13px] text-gray-12">- Scout signals- </Text>- <Text className="truncate text-[12px] text-gray-11 leading-snug">- {summary.totalCount} signal{summary.totalCount === 1 ? "" : "s"}{" "}- across {summary.scoutCount} scout- {summary.scoutCount === 1 ? "" : "s"}- {summary.latestEmittedAt ? (- <>- {" · latest "}- <RelativeTimestamp- timestamp={summary.latestEmittedAt}- className="inline text-[12px] text-gray-11"- />- </>- ) : null}- </Text>- </Flex>- <span className="flex-1" />- <ArrowRightIcon size={14} className="shrink-0 text-gray-10" />- </button>- );-}diff --git a/products/desktop/packages/ui/src/features/scouts/components/FleetMemoryCallout.tsx b/products/desktop/packages/ui/src/features/scouts/components/FleetMemoryCallout.tsxdeleted file mode 100644index e05cd69e2701..000000000000--- a/products/desktop/packages/ui/src/features/scouts/components/FleetMemoryCallout.tsx+++ /dev/null@@ -1,54 +0,0 @@-import { ArrowRightIcon, NotebookIcon } from "@phosphor-icons/react";-import { RelativeTimestamp } from "@posthog/ui/primitives/RelativeTimestamp";-import { Flex, Text } from "@radix-ui/themes";-import { Link } from "@tanstack/react-router";-import { useScoutScratchpad } from "../hooks/useScoutScratchpad";--/**- * Scratchpad stat card for the scout fleet section. Surfaces that the scouts- * have jotted down context about this project — count + recency hint at what- * they're picking up — and links into the full scratchpad browse/search surface.- * Renders nothing until there is at least one note, so a fresh project isn't- * nudged toward an empty page.- */-export function FleetMemoryCallout() {- const { data: entries } = useScoutScratchpad();-- // Hold until the first load settles, then only show when there's something to- // read. Entries arrive newest-first, so the head drives the "updated" hint.- if (!entries || entries.length === 0) {- return null;- }-- const totalCount = entries.length;- const lastUpdatedAt = entries[0]?.updated_at ?? null;-- return (- <Link- to="/agents/scouts/scratchpad"- className="flex w-full items-center gap-3 rounded-(--radius-2) border border-border bg-(--color-panel-solid) px-4 py-3.5 text-left no-underline transition-colors duration-150 hover:border-(--gray-6) hover:bg-(--gray-2)"- >- <NotebookIcon size={20} className="shrink-0 text-(--iris-9)" />- <Flex direction="column" className="min-w-0">- <Text className="font-medium text-[13px] text-gray-12">- Scout scratchpad- </Text>- <Text className="truncate text-[12px] text-gray-11 leading-snug">- {totalCount} note{totalCount === 1 ? "" : "s"} your scouts have jotted- down about this project- {lastUpdatedAt ? (- <>- {" · updated "}- <RelativeTimestamp- timestamp={lastUpdatedAt}- className="inline text-[12px] text-gray-11"- />- </>- ) : null}- </Text>- </Flex>- <span className="flex-1" />- <ArrowRightIcon size={14} className="shrink-0 text-gray-10" />- </Link>- );-}diff --git a/products/desktop/packages/ui/src/features/scouts/components/FleetOverviewButton.tsx b/products/desktop/packages/ui/src/features/scouts/components/FleetOverviewButton.tsxnew file mode 100644index 000000000000..8077456cff37--- /dev/null+++ b/products/desktop/packages/ui/src/features/scouts/components/FleetOverviewButton.tsx@@ -0,0 +1,28 @@+import { SparkleIcon } from "@phosphor-icons/react";+import { SCOUT_FLEET_OVERVIEW_PROMPT } from "@posthog/core/scouts/scoutPrompts";+import { Button } from "@posthog/quill";+import { useScoutChatTask } from "../hooks/useScoutChatTask";++/** Starts a cloud task that reviews the whole fleet and opens it. */+export function FleetOverviewButton() {+ const { runTask, isRunning } = useScoutChatTask({+ prompt: SCOUT_FLEET_OVERVIEW_PROMPT,+ taskLabel: "fleet overview",+ loggerScope: "scout-fleet-overview",+ chatType: "fleet_overview",+ surface: "fleet_list",+ });+ return (+ <Button+ type="button"+ variant="outline"+ size="sm"+ onClick={() => void runTask()}+ disabled={isRunning}+ data-attr="agents-ask-about-fleet"+ >+ <SparkleIcon size={13} />+ {isRunning ? "Starting…" : "Ask about the fleet"}+ </Button>+ );+}diff --git a/products/desktop/packages/ui/src/features/scouts/components/NewAgentDialog.tsx b/products/desktop/packages/ui/src/features/scouts/components/NewAgentDialog.tsxnew file mode 100644index 000000000000..7355087a8795--- /dev/null+++ b/products/desktop/packages/ui/src/features/scouts/components/NewAgentDialog.tsx@@ -0,0 +1,120 @@+import { SparkleIcon } from "@phosphor-icons/react";+import { buildScoutAuthorPrompt } from "@posthog/core/scouts/scoutPrompts";+import {+ Button,+ Dialog,+ DialogBody,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+ Textarea,+} from "@posthog/quill";+import { useMemo, useState } from "react";+import { useScoutChatTask } from "../hooks/useScoutChatTask";++const EXAMPLES = [+ "Errors that spike after a deploy",+ "Experiments past their end date",+ "Support tickets about billing",+];++/**+ * Describe an agent in a sentence; PostHog drafts it as a `signals-scout-*`+ * skill in a cloud task and opens that task for review.+ */+export function NewAgentDialog({+ open,+ onOpenChange,+ initialBrief = "",+}: {+ open: boolean;+ onOpenChange: (open: boolean) => void;+ /** What the box starts with, so a suggestion opens with its own brief in it. */+ initialBrief?: string;+}) {+ // Keyed on the brief by the caller, so a second suggestion refills the box+ // rather than leaving the first one in it.+ const [brief, setBrief] = useState(initialBrief);+ const prompt = useMemo(() => buildScoutAuthorPrompt(brief), [brief]);+ const { runTask, isRunning } = useScoutChatTask({+ prompt,+ taskLabel: "agent draft",+ loggerScope: "scout-author",+ chatType: "author_scout",+ surface: "fleet_list",+ });++ const submit = async () => {+ if (await runTask()) {+ onOpenChange(false);+ setBrief("");+ }+ };++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent className="max-w-xl">+ <DialogHeader>+ <DialogTitle>New agent</DialogTitle>+ <DialogDescription>+ Say what to watch and what to do when it finds something. PostHog+ drafts the agent in a task and opens it for you.+ </DialogDescription>+ </DialogHeader>+ <DialogBody className="flex flex-col gap-2 bg-transparent">+ <Textarea+ value={brief}+ onChange={(event) => setBrief(event.target.value)}+ placeholder="Watch accounts on the Scale plan whose weekly active users drop 30% in two weeks. Send one signal per account with a suggested play."+ rows={4}+ autoFocus+ aria-label="What the agent should do"+ className="bg-(--color-panel-solid) placeholder:text-gray-9"+ data-attr="new-agent-brief"+ />+ <p className="text-[11.5px] text-gray-10">+ Try:{" "}+ {EXAMPLES.map((example, index) => (+ <span key={example}>+ {index > 0 ? " · " : null}+ <button+ type="button"+ onClick={() => setBrief(example)}+ className="text-gray-11 underline decoration-(--gray-7) underline-offset-2 hover:text-gray-12"+ >+ {example}+ </button>+ </span>+ ))}+ </p>+ </DialogBody>+ <DialogFooter>+ <span className="mr-auto text-[11.5px] text-gray-10">+ New agents start as a dry run.+ </span>+ <Button+ type="button"+ variant="default"+ size="sm"+ onClick={() => onOpenChange(false)}+ >+ Cancel+ </Button>+ <Button+ type="button"+ variant="primary"+ size="sm"+ onClick={() => void submit()}+ disabled={isRunning || !brief.trim()}+ data-attr="new-agent-draft"+ >+ <SparkleIcon size={13} />+ {isRunning ? "Starting…" : "Draft agent"}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+}diff --git a/products/desktop/packages/ui/src/features/scouts/components/ScoutActivityTab.tsx b/products/desktop/packages/ui/src/features/scouts/components/ScoutActivityTab.tsxnew file mode 100644index 000000000000..8772ff0cb9ee--- /dev/null+++ b/products/desktop/packages/ui/src/features/scouts/components/ScoutActivityTab.tsx@@ -0,0 +1,160 @@+import type { ScoutRun } from "@posthog/api-client/posthog-client";+import {+ runMatchesFilter,+ type ScoutRollup,+ type ScoutRunFilter,+ summarizeRunWindow,+} from "@posthog/core/scouts/scoutPresentation";+import { SCOUT_RUNS_WINDOW_LABEL } from "@posthog/core/scouts/scoutRunsWindow";+import { Skeleton, Tabs, TabsList, TabsTrigger } from "@posthog/quill";+import { ANALYTICS_EVENTS } from "@posthog/shared";+import { useMinuteNow } from "@posthog/ui/hooks/useMinuteNow";+import { track } from "@posthog/ui/shell/analytics";+import { useMemo, useState } from "react";+import { ScoutRunBoxes } from "./ScoutRunBoxes";+import { ScoutRunsList } from "./ScoutRunsList";++const FILTERS: { value: ScoutRunFilter; label: string }[] = [+ { value: "all", label: "All" },+ { value: "emitted", label: "Output" },+ { value: "quiet", label: "Quiet" },+ { value: "failed", label: "Failed" },+];++/** Filters only earn their row once the list is long enough to need them. */+const FILTERS_FROM = 6;++/** Every run in the window, newest first, with one line that sums them up. */+export function ScoutActivityTab({+ skillName,+ rollup,+ runs,+ incomplete,+ loading,+ loadingMore,+ error,+}: {+ skillName: string;+ rollup: ScoutRollup | undefined;+ runs: ScoutRun[];+ incomplete: boolean;+ loading: boolean;+ /** More pages of the run window are still on their way. */+ loadingMore: boolean;+ error: boolean;+}) {+ const [filter, setFilter] = useState<ScoutRunFilter>("all");+ const now = useMinuteNow();+ const sorted = useMemo(+ () =>+ [...runs].sort((a, b) =>+ (b.started_at ?? "").localeCompare(a.started_at ?? ""),+ ),+ [runs],+ );+ const filtered = useMemo(+ () => sorted.filter((run) => runMatchesFilter(run, filter)),+ [sorted, filter],+ );+ const counts = useMemo(() => {+ const map = new Map<ScoutRunFilter, number>();+ for (const entry of FILTERS) {+ map.set(+ entry.value,+ runs.filter((run) => runMatchesFilter(run, entry.value)).length,+ );+ }+ return map;+ }, [runs]);+ const summary = useMemo(() => summarizeRunWindow(rollup, now), [rollup, now]);++ return (+ <div className="flex flex-col gap-4">+ {loading ? (+ <Skeleton className="h-5 w-96" />+ ) : (+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1">+ {rollup && rollup.runs.length > 0 ? (+ <ScoutRunBoxes runs={rollup.runs} />+ ) : null}+ <span className="text-[12.5px] text-gray-12">+ {summary ??+ (error+ ? "Run history is unavailable."+ : loadingMore+ ? "Loading runs."+ : incomplete+ ? "No runs loaded. The run history is incomplete."+ : `No runs in the ${SCOUT_RUNS_WINDOW_LABEL}.`)}+ </span>+ <span className="flex-1" />+ <span className="text-[11.5px] text-gray-10">+ {loadingMore+ ? `${capitalize(SCOUT_RUNS_WINDOW_LABEL)} · loading more runs`+ : incomplete+ ? `${capitalize(SCOUT_RUNS_WINDOW_LABEL)}. Some runs in this window did not load.`+ : capitalize(SCOUT_RUNS_WINDOW_LABEL)}+ </span>+ </div>+ )}++ {runs.length >= FILTERS_FROM || filter !== "all" ? (+ <Tabs+ value={filter}+ onValueChange={(value: string) => {+ const next = value as ScoutRunFilter;+ setFilter(next);+ track(ANALYTICS_EVENTS.SCOUT_ACTION, {+ action_type: "filter_runs",+ surface: "scout_detail",+ skill_name: skillName,+ filter: next,+ filter_match_count: counts.get(next) ?? 0,+ });+ }}+ >+ <TabsList className="h-8">+ {FILTERS.map((entry) => {+ const count = counts.get(entry.value) ?? 0;+ if (+ entry.value !== "all" &&+ entry.value !== filter &&+ count === 0+ )+ return null;+ return (+ <TabsTrigger+ key={entry.value}+ value={entry.value}+ className="gap-1.5 px-2.5"+ >+ {entry.label}+ <span className="text-[11px] text-gray-10 tabular-nums">+ {count}+ </span>+ </TabsTrigger>+ );+ })}+ </TabsList>+ </Tabs>+ ) : null}++ <ScoutRunsList+ runs={filtered}+ loading={loading}+ error={error}+ emptyMessage={+ runs.length > 0+ ? `No runs match this filter in the ${SCOUT_RUNS_WINDOW_LABEL}.`+ : incomplete+ ? `No runs loaded for the ${SCOUT_RUNS_WINDOW_LABEL}. Runs may exist beyond what was fetched.`+ : `No runs in the ${SCOUT_RUNS_WINDOW_LABEL}. Use Run now to start one.`+ }+ />+ </div>+ );+}++function capitalize(value: string): string {+ return value.charAt(0).toUpperCase() + value.slice(1);+}diff --git a/products/desktop/packages/ui/src/features/scouts/components/ScoutAttentionStrip.tsx b/products/desktop/packages/ui/src/features/scouts/components/ScoutAttentionStrip.tsxnew file mode 100644index 000000000000..c80506d53ec7--- /dev/null+++ b/products/desktop/packages/ui/src/features/scouts/components/ScoutAttentionStrip.tsx@@ -0,0 +1,117 @@+import { ClockIcon, PauseIcon, WarningIcon } from "@phosphor-icons/react";+import {+ deriveScoutLifecycle,+ type ScoutAttention,+ type ScoutAttentionKind,+ scoutSkillSlug,+} from "@posthog/core/scouts/scoutPresentation";+import { Badge, Button } from "@posthog/quill";+import { useAgentsPageActions } from "@posthog/ui/features/agents/agentsPageStore";+import type { ScoutConfigUpdate } from "../hooks/useScoutConfigMutations";+import { AgentNameLink } from "./AgentNameLink";++const MAX_CARDS = 3;++const KIND_META: Record<+ ScoutAttentionKind,+ { label: string; tone: "warning" | "destructive"; Icon: typeof PauseIcon }+> = {+ auto_paused: { label: "Auto-paused", tone: "warning", Icon: PauseIcon },+ failing: { label: "Failing", tone: "destructive", Icon: WarningIcon },+ pausing_soon: { label: "Pausing soon", tone: "warning", Icon: ClockIcon },+};++/**+ * The agents that need a person before anything else, each with the one+ * action that resolves it. Renders nothing when the fleet is healthy.+ */+export function ScoutAttentionStrip({+ items,+ onUpdateConfig,+}: {+ items: ScoutAttention[];+ onUpdateConfig: (configId: string, updates: ScoutConfigUpdate) => void;+}) {+ const { openAgent } = useAgentsPageActions();+ const shown = items.slice(0, MAX_CARDS);+ const hidden = items.length - shown.length;++ return (+ <div className="flex flex-col gap-2">+ <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">+ {shown.map(({ kind, config, detail }) => {+ const { label, tone, Icon } = KIND_META[kind];+ const slug = scoutSkillSlug(config.skill_name);+ const lifecycle = deriveScoutLifecycle(config);+ const iconTone =+ tone === "destructive" ? "text-(--red-11)" : "text-(--amber-11)";+ return (+ <div+ key={config.id}+ className="flex gap-3 rounded-(--radius-md) border border-border bg-(--color-panel-solid) px-3.5 py-3"+ >+ <Icon size={16} className={`mt-0.5 shrink-0 ${iconTone}`} />+ <div className="flex min-w-0 flex-1 flex-col gap-1">+ <div className="flex min-w-0 items-center gap-2">+ <AgentNameLink+ config={config}+ onOpen={() => openAgent(slug)}+ />+ <Badge variant={tone}>{label}</Badge>+ </div>+ <p className="line-clamp-2 text-[11.5px] text-gray-10 leading-snug">+ {detail}+ </p>+ <div className="mt-1.5 flex items-center gap-1.5">+ {kind === "auto_paused" ? (+ <Button+ type="button"+ variant="outline"+ size="xs"+ onClick={() =>+ onUpdateConfig(config.id, { enabled: true })+ }+ data-attr="scout-attention-resume"+ >+ Resume+ </Button>+ ) : null}+ {kind === "pausing_soon" &&+ lifecycle.autoPauseExempt === false ? (+ <Button+ type="button"+ variant="outline"+ size="xs"+ onClick={() =>+ onUpdateConfig(config.id, { auto_pause_exempt: true })+ }+ data-attr="scout-attention-keep-running"+ >+ Keep running+ </Button>+ ) : null}+ <Button+ type="button"+ variant="outline"+ size="xs"+ onClick={() => openAgent(slug, { tab: "activity" })}+ data-attr="scout-attention-open-runs"+ >+ {kind === "failing" ? "Open last run" : "Review runs"}+ </Button>+ </div>+ </div>+ </div>+ );+ })}+ </div>+ {hidden > 0 ? (+ <p className="text-[11.5px] text-gray-10">+ {hidden} more agent{hidden === 1 ? "" : "s"} need+ {hidden === 1 ? "s" : ""} attention. Select All and clear the table+ filters to find them.+ </p>+ ) : null}+ </div>+ );+}diff --git a/products/desktop/packages/ui/src/features/scouts/components/ScoutBadges.tsx b/products/desktop/packages/ui/src/features/scouts/components/ScoutBadges.tsxindex 5b0cd63d24bb..734446739d61 100644--- a/products/desktop/packages/ui/src/features/scouts/components/ScoutBadges.tsx+++ b/products/desktop/packages/ui/src/features/scouts/components/ScoutBadges.tsx@@ -1,60 +1,45 @@import type { ScoutConfig } from "@posthog/api-client/posthog-client";-import { getScoutOrigin } from "@posthog/core/scouts/scoutPresentation";-import { Badge, Tooltip } from "@radix-ui/themes";--export function ScoutOriginBadge({ config }: { config: ScoutConfig }) {- const origin = getScoutOrigin(config);- return (- <Tooltip- content={- origin === "canonical"- ? "Part of the standard scout fleet built and maintained by PostHog"- : "A scout your team created as a signals-scout-* skill in this project"- }- >- <Badge- variant="soft"- color={origin === "canonical" ? "gray" : "iris"}- size="1"- className="relative text-[11px]"- >- {origin === "canonical" ? "Canonical" : "Custom"}- </Badge>- </Tooltip>- );-}+import {+ Badge,+ Tooltip,+ TooltipContent,+ TooltipProvider,+ TooltipTrigger,+} from "@posthog/quill";export function DryRunBadge({ config }: { config: ScoutConfig }) {if (config.emit) return null;return (- <Tooltip content="Runs on schedule but signals are not emitted to Self-driving">- <Badge- variant="soft"- color="amber"- size="1"- className="relative text-[11px]"- >- Dry run- </Badge>- </Tooltip>+ <TooltipProvider>+ <Tooltip>+ <TooltipTrigger+ render={+ <Badge variant="warning" className="relative text-[11px]">+ Dry run+ </Badge>+ }+ />+ <TooltipContent>+ Runs on schedule, but its signals do not reach Self-driving+ </TooltipContent>+ </Tooltip>+ </TooltipProvider>);}-const SEVERITY_COLORS: Record<string, "red" | "orange" | "amber" | "gray"> = {- P0: "red",- P1: "red",- P2: "orange",- P3: "amber",- P4: "gray",+const SEVERITY_COLORS: Record<string, "destructive" | "warning" | "default"> = {+ P0: "destructive",+ P1: "destructive",+ P2: "warning",+ P3: "warning",+ P4: "default",};export function SeverityBadge({ severity }: { severity: string | null }) {if (!severity) return null;return (<Badge- variant="soft"- color={SEVERITY_COLORS[severity] ?? "gray"}- size="1"+ variant={SEVERITY_COLORS[severity] ?? "default"}className="text-[11px]">{severity}diff --git a/products/desktop/packages/ui/src/features/scouts/components/ScoutChatButton.tsx b/products/desktop/packages/ui/src/features/scouts/components/ScoutChatButton.tsxnew file mode 100644index 000000000000..983a6e1bf19f--- /dev/null+++ b/products/desktop/packages/ui/src/features/scouts/components/ScoutChatButton.tsx@@ -0,0 +1,68 @@+import { SparkleIcon } from "@phosphor-icons/react";+import { prettifyScoutSkillName } from "@posthog/core/scouts/scoutPresentation";+import { buildScoutCheckinPrompt } from "@posthog/core/scouts/scoutPrompts";+import { Button } from "@posthog/quill";+import type { ScoutSurface } from "@posthog/shared";+import { Tooltip } from "@posthog/ui/primitives/Tooltip";+import { useMemo } from "react";+import { useScoutChatTask } from "../hooks/useScoutChatTask";++/**+ * One-click check-in on a scout: creates an auto-mode cloud task that asks+ * PostHog about this scout and opens it. Icon-only unless a label is given.+ */+export function ScoutChatButton({+ skillName,+ surface,+ label,+}: {+ skillName: string;+ surface: ScoutSurface;+ label?: string;+}) {+ const prompt = useMemo(+ () => buildScoutCheckinPrompt(skillName, prettifyScoutSkillName(skillName)),+ [skillName],+ );+ const { runTask, isRunning } = useScoutChatTask({+ prompt,+ taskLabel: "agent check-in",+ loggerScope: "scout-checkin",+ chatType: "scout_checkin",+ surface,+ skillName,+ });++ if (label) {+ return (+ <Button+ type="button"+ variant="outline"+ size="sm"+ onClick={() => void runTask()}+ disabled={isRunning}+ data-attr="scout-discuss"+ >+ <SparkleIcon size={13} />+ {isRunning ? "Starting…" : label}+ </Button>+ );+ }++ return (+ <Tooltip content="Ask PostHog about this agent">+ <Button+ type="button"+ variant="default"+ size="icon-sm"+ onClick={() => void runTask()}+ disabled={isRunning}+ aria-label={`Ask PostHog about the ${skillName} agent`}+ className={isRunning ? "animate-pulse text-(--iris-9)" : undefined}+ data-attr="scout-discuss"+ >+ <SparkleIcon size={14} />+ </Button>+ </Tooltip>+ );+}diff --git a/products/desktop/packages/ui/src/features/scouts/components/ScoutConfigControls.tsx b/products/desktop/packages/ui/src/features/scouts/components/ScoutConfigControls.tsxindex 654287f7348b..d132f9ce9ca9 100644--- a/products/desktop/packages/ui/src/features/scouts/components/ScoutConfigControls.tsx+++ b/products/desktop/packages/ui/src/features/scouts/components/ScoutConfigControls.tsx@@ -1,3 +1,4 @@+import { ArrowSquareOutIcon } from "@phosphor-icons/react";import type { ScoutConfig } from "@posthog/api-client/posthog-client";import {DEFAULT_SCOUT_DAILY_TIME,@@ -5,8 +6,11 @@ import {dailyCronToTime,dayTimeToWeeklyCron,deriveScoutLifecycle,+ formatNextRun,+ getScoutOrigin,getScoutScheduleMode,getScoutScheduleOptions,+ nextRunAt,SCOUT_CRON_MAX_LENGTH,SCOUT_CUSTOM_CRON_SCHEDULE_MODE,SCOUT_DAILY_AT_SCHEDULE_MODE,@@ -16,20 +20,30 @@ import {timeToDailyCron,weeklyCronToDayTime,} from "@posthog/core/scouts/scoutPresentation";-import {- Input as QuillInput,- Switch as QuillSwitch,- Text as QuillText,-} from "@posthog/quill";+import { Button, Input, Switch } from "@posthog/quill";+import { ANALYTICS_EVENTS } from "@posthog/shared";import { SettingsOptionSelect } from "@posthog/ui/features/settings/SettingsOptionSelect";-import { Flex, Switch, Text, Tooltip } from "@radix-ui/themes";-import { useId, useState } from "react";+import { RadioCards } from "@posthog/ui/primitives/RadioCards";+import { Tooltip } from "@posthog/ui/primitives/Tooltip";+import { track } from "@posthog/ui/shell/analytics";+import { skillUrl } from "@posthog/ui/utils/posthogLinks";+import { type ReactNode, useId, useState } from "react";import type { ScoutConfigUpdate } from "../hooks/useScoutConfigMutations";+import { ScoutHelperSkillLinks } from "./ScoutHelperSkillLinks";const MODE_OPTIONS = [- { value: "live", label: "Live" },- { value: "dry_run", label: "Dry run" },-];+ {+ value: "live",+ title: "Live",+ description: "Signals reach Self-driving as soon as the agent finds them.",+ },+ {+ value: "dry_run",+ title: "Dry run",+ description:+ "Runs on schedule and records what it would send. Nothing leaves this page.",+ },+] as const;interface ScoutConfigControlsProps {config: ScoutConfig;@@ -44,38 +58,38 @@ export function ScoutEnabledSwitch({// "resume" rather than the generic "enable"; the badge beside it explains why// the scout stopped.const tooltip = config.enabled- ? "Disable scout"+ ? "Switch this agent off": deriveScoutLifecycle(config).isSystemPaused- ? "Resume scout"- : "Enable scout";+ ? "Resume this agent"+ : "Switch this agent on";return (<Tooltip content={tooltip}>- {/* Tooltip stamps its own data-state on its child, which would overwrite- the Switch's checked/unchecked state and leave the track stuck on the- accent color. Give it a span to stamp. */}<span className="inline-flex"><Switch- size="1"+ size="sm"checked={config.enabled}onCheckedChange={(checked) =>onUpdate(config.id, { enabled: checked })}aria-label={`${config.skill_name} enabled`}+ data-attr="scout-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.- */+/** The Settings tab of the agent page. Every change saves as it is made. */export function ScoutConfigForm({config,onUpdate,}: ScoutConfigControlsProps) {const lifecycle = deriveScoutLifecycle(config);+ const cloudSkillUrl = skillUrl(config.skill_name);+ const next = formatNextRun(nextRunAt(config), new Date());+ const canonical = getScoutOrigin(config) === "canonical";+ const instructions = config.description?.trim();+const weekly = weeklyCronToDayTime(config.run_cron_schedule);const runTime =dailyCronToTime(config.run_cron_schedule) ??@@ -92,148 +106,192 @@ export function ScoutConfigForm({: savedScheduleMode;return (- <Flex direction="column" gap="2">- <Flex align="center" justify="between" gap="4">- <Flex direction="column" className="min-w-0">- <Text className="text-[12px] text-gray-12">Mode</Text>- <Text className="text-[11.5px] text-gray-10">- Dry run executes the scout but holds back its signals- </Text>- </Flex>- <SettingsOptionSelect+ <div className="mx-auto flex max-w-2xl flex-col gap-7">+ <SettingBlock+ title="Instructions"+ help={+ canonical+ ? "What this agent looks for. PostHog maintains built-in agents. To change one, ask PostHog to create a custom agent based on it."+ : "What this agent looks for. Edit the skill in PostHog to change what it watches and when it sends a signal."+ }+ >+ <div className="flex flex-col rounded-(--radius-md) border border-border bg-(--color-panel-solid)">+ {instructions ? (+ <p className="whitespace-pre-wrap px-3.5 py-3 text-[12.5px] text-gray-11 leading-relaxed">+ {instructions}+ </p>+ ) : (+ <p className="px-3.5 py-3 text-[12.5px] text-gray-10">+ This skill has no description.+ </p>+ )}+ <div className="flex items-center justify-between gap-3 border-(--gray-4) border-t px-3.5 py-2.5">+ <div className="flex min-w-0 flex-col gap-1">+ <code className="truncate text-[11.5px] text-gray-11">+ {config.skill_name}+ </code>+ <ScoutHelperSkillLinks surface="scout_detail" />+ </div>+ {cloudSkillUrl ? (+ <Button+ type="button"+ variant="outline"+ size="sm"+ className="shrink-0"+ onClick={() => {+ track(ANALYTICS_EVENTS.SCOUT_ACTION, {+ action_type: "open_skill_in_posthog",+ surface: "scout_detail",+ skill_name: config.skill_name,+ });+ window.open(cloudSkillUrl, "_blank", "noreferrer");+ }}+ >+ <ArrowSquareOutIcon size={13} />+ {canonical ? "Open in PostHog" : "Edit in PostHog"}+ </Button>+ ) : null}+ </div>+ </div>+ </SettingBlock>++ <SettingBlock+ title="Mode"+ help="Use Dry run to check a new or changed agent before its signals reach anyone."+ >+ <RadioCardsvalue={config.emit ? "live" : "dry_run"}options={MODE_OPTIONS}+ onChange={(value) => onUpdate(config.id, { emit: value === "live" })}ariaLabel={`${config.skill_name} mode`}- disabled={!config.enabled}- className="w-24"- onValueChange={(value) =>- onUpdate(config.id, { emit: value === "live" })- }+ dataAttrPrefix="scout-mode"/>- </Flex>- <Flex align="center" justify="between" gap="4">- <Flex direction="column" className="min-w-0">- <Text className="text-[12px] text-gray-12">Cadence</Text>- <Text className="text-[11.5px] text-gray-10">- A rolling cadence, a set time each day or week, or a cron expression- </Text>- </Flex>- <SettingsOptionSelect- value={scheduleMode}- options={getScoutScheduleOptions(config)}- ariaLabel={`${config.skill_name} run interval`}- disabled={!config.enabled}- className="w-36"- onValueChange={(value) => {- setCustomModePicked(value === SCOUT_CUSTOM_CRON_SCHEDULE_MODE);- if (- value === savedScheduleMode ||- value === SCOUT_CUSTOM_CRON_SCHEDULE_MODE- ) {- return;- }- if (value === SCOUT_DAILY_AT_SCHEDULE_MODE) {- onUpdate(config.id, {- run_cron_schedule: timeToDailyCron(runTime),- });- return;- }- if (value === SCOUT_WEEKLY_ON_SCHEDULE_MODE) {- onUpdate(config.id, {- run_cron_schedule: dayTimeToWeeklyCron(weeklyDay, runTime),- });- return;- }- // A rolling cadence replaces any cron — the schedule is one or the other.- onUpdate(config.id, {- run_interval_minutes: Number(value),- run_cron_schedule: null,- });- }}- />- </Flex>- {scheduleMode === SCOUT_WEEKLY_ON_SCHEDULE_MODE ? (- <Flex align="center" justify="between" gap="4">- <Flex direction="column" className="min-w-0">- <Text className="text-[12px] text-gray-12">Run day</Text>- <Text className="text-[11.5px] text-gray-10">- The scout runs once a week, on this day- </Text>- </Flex>- <SettingsOptionSelect- value={weeklyDay}- options={SCOUT_WEEKDAY_OPTIONS}- ariaLabel={`${config.skill_name} run day`}- disabled={!config.enabled}- className="w-36"- onValueChange={(day) =>- onUpdate(config.id, {- run_cron_schedule: dayTimeToWeeklyCron(day, runTime),- })- }- />- </Flex>- ) : null}- {scheduleMode === SCOUT_DAILY_AT_SCHEDULE_MODE ||- scheduleMode === SCOUT_WEEKLY_ON_SCHEDULE_MODE ? (- <Flex align="center" justify="between" gap="4">- <Flex direction="column" className="min-w-0">- <Text className="text-[12px] text-gray-12">Run time</Text>- <Text className="text-[11.5px] text-gray-10">- Uses the project timezone- </Text>- </Flex>- <QuillInput- key={config.run_cron_schedule ?? "unset"}- type="time"- step={60}- defaultValue={runTime}- disabled={!config.enabled}- className="w-36"- aria-label={`${config.skill_name} run time`}- onBlur={(event) => {- const value = event.currentTarget.value;- // Empty means a half-finished edit, never "clear" — switching the schedule- // off is the cadence picker's job, so fall back to the saved time.- if (!value) return;- const runCronSchedule =- scheduleMode === SCOUT_WEEKLY_ON_SCHEDULE_MODE- ? dayTimeToWeeklyCron(weeklyDay, value)- : timeToDailyCron(value);- if (runCronSchedule !== config.run_cron_schedule) {- onUpdate(config.id, { run_cron_schedule: runCronSchedule });- }- }}- />- </Flex>- ) : null}- {scheduleMode === SCOUT_CUSTOM_CRON_SCHEDULE_MODE ? (- <ScoutCustomCronField config={config} onUpdate={onUpdate} />- ) : null}+ </SettingBlock>++ <SettingBlock+ title="Schedule"+ help={+ next+ ? `Next run ${next}. A schedule change applies immediately.`+ : "A rolling cadence, a set time each day or week, or a cron expression."+ }+ >+ <div className="flex flex-col gap-3 rounded-(--radius-md) border border-border bg-(--color-panel-solid) px-3.5 py-3">+ <SettingRow label="Cadence">+ <SettingsOptionSelect+ value={scheduleMode}+ options={getScoutScheduleOptions(config)}+ ariaLabel={`${config.skill_name} run interval`}+ disabled={!config.enabled}+ size="default"+ onValueChange={(value) => {+ setCustomModePicked(value === SCOUT_CUSTOM_CRON_SCHEDULE_MODE);+ if (+ value === savedScheduleMode ||+ value === SCOUT_CUSTOM_CRON_SCHEDULE_MODE+ ) {+ return;+ }+ if (value === SCOUT_DAILY_AT_SCHEDULE_MODE) {+ onUpdate(config.id, {+ run_cron_schedule: timeToDailyCron(runTime),+ });+ return;+ }+ if (value === SCOUT_WEEKLY_ON_SCHEDULE_MODE) {+ onUpdate(config.id, {+ run_cron_schedule: dayTimeToWeeklyCron(weeklyDay, runTime),+ });+ return;+ }+ // A rolling cadence replaces any cron — the schedule is one or the other.+ onUpdate(config.id, {+ run_interval_minutes: Number(value),+ run_cron_schedule: null,+ });+ }}+ />+ </SettingRow>++ {scheduleMode === SCOUT_WEEKLY_ON_SCHEDULE_MODE ? (+ <SettingRow label="Run day" help="The agent runs once a week.">+ <SettingsOptionSelect+ value={weeklyDay}+ options={SCOUT_WEEKDAY_OPTIONS}+ ariaLabel={`${config.skill_name} run day`}+ disabled={!config.enabled}+ size="default"+ onValueChange={(day) =>+ onUpdate(config.id, {+ run_cron_schedule: dayTimeToWeeklyCron(day, runTime),+ })+ }+ />+ </SettingRow>+ ) : null}++ {scheduleMode === SCOUT_DAILY_AT_SCHEDULE_MODE ||+ scheduleMode === SCOUT_WEEKLY_ON_SCHEDULE_MODE ? (+ <SettingRow label="Run time" help="Uses the project timezone.">+ <Input+ key={config.run_cron_schedule ?? "unset"}+ type="time"+ step={60}+ defaultValue={runTime}+ disabled={!config.enabled}+ aria-label={`${config.skill_name} run time`}+ onBlur={(event) => {+ const value = event.currentTarget.value;+ // Empty means a half-finished edit, never "clear" — switching the schedule+ // off is the cadence picker's job, so fall back to the saved time.+ if (!value) return;+ const runCronSchedule =+ scheduleMode === SCOUT_WEEKLY_ON_SCHEDULE_MODE+ ? dayTimeToWeeklyCron(weeklyDay, value)+ : timeToDailyCron(value);+ if (runCronSchedule !== config.run_cron_schedule) {+ onUpdate(config.id, { run_cron_schedule: runCronSchedule });+ }+ }}+ />+ </SettingRow>+ ) : null}++ {scheduleMode === SCOUT_CUSTOM_CRON_SCHEDULE_MODE ? (+ <ScoutCustomCronField config={config} onUpdate={onUpdate} />+ ) : null}+ </div>+ </SettingBlock>+{/* Null means the backend never sent the field, so a PATCH carrying itcould not persist. Offer the control only where it writes. */}{lifecycle.autoPauseExempt !== null ? (- <div className="flex items-center justify-between gap-4">- <div className="flex min-w-0 flex-col">- <QuillText size="xs" className="text-gray-12">- Never pause for inactivity- </QuillText>- <QuillText size="xxs" className="text-gray-10">- Keep running when the scout goes quiet or its findings go unacted- on. Repeated failures still pause it.- </QuillText>+ <SettingBlock+ title="Auto-pause"+ help="PostHog can pause agents when nobody acts on their signals. Silence alone does not cause a pause. Repeated failures can pause an agent in either mode."+ >+ <div className="flex items-center justify-between gap-4 rounded-(--radius-md) border border-border bg-(--color-panel-solid) px-3.5 py-3">+ <span className="flex min-w-0 flex-col">+ <span className="text-[12.5px] text-gray-12">+ Never pause for inactivity+ </span>+ <span className="text-[11.5px] text-gray-10">+ For agents whose job is to stay quiet until something breaks.+ </span>+ </span>+ <Switch+ size="sm"+ checked={lifecycle.autoPauseExempt}+ onCheckedChange={(checked) =>+ onUpdate(config.id, { auto_pause_exempt: checked })+ }+ aria-label={`${config.skill_name} exempt from inactivity pauses`}+ data-attr="scout-auto-pause-exempt"+ /></div>- <QuillSwitch- size="sm"- checked={lifecycle.autoPauseExempt}- onCheckedChange={(checked) =>- onUpdate(config.id, { auto_pause_exempt: checked })- }- aria-label={`${config.skill_name} exempt from inactivity pauses`}- />- </div>+ </SettingBlock>) : null}- </Flex>+ </div>);}@@ -254,16 +312,12 @@ function ScoutCustomCronField({ config, onUpdate }: ScoutConfigControlsProps) {};return (- <Flex align="start" justify="between" gap="4">- <Flex direction="column" className="min-w-0">- <Text className="text-[12px] text-gray-12">Cron expression</Text>- <Text className="text-[11.5px] text-gray-10">- Minute, hour, day of month, month, day of week, in the project- timezone- </Text>- </Flex>- <Flex direction="column" gap="1" className="w-36 shrink-0">- <QuillInput+ <SettingRow+ label="Cron expression"+ help="Minute, hour, day of month, month, day of week, in the project timezone."+ >+ <div className="flex flex-col gap-1">+ <Inputvalue={draft}placeholder="0 9 * * 1-5"maxLength={SCOUT_CRON_MAX_LENGTH}@@ -279,11 +333,53 @@ function ScoutCustomCronField({ config, onUpdate }: ScoutConfigControlsProps) {}}/>{error ? (- <QuillText id={errorId} size="xxs" className="text-red-11">+ <span id={errorId} className="text-(--red-11) text-[11.5px]">{error}- </QuillText>+ </span>) : null}- </Flex>- </Flex>+ </div>+ </SettingRow>+ );+}++function SettingRow({+ label,+ help,+ children,+}: {+ label: string;+ help?: string;+ children: ReactNode;+}) {+ return (+ <div className="flex items-start justify-between gap-4">+ <span className="flex min-w-0 flex-col">+ <span className="text-[12.5px] text-gray-12">{label}</span>+ {help ? (+ <span className="text-[11.5px] text-gray-10">{help}</span>+ ) : null}+ </span>+ <div className="w-44 shrink-0">{children}</div>+ </div>+ );+}++function SettingBlock({+ title,+ help,+ children,+}: {+ title: string;+ help: string;+ children: ReactNode;+}) {+ return (+ <section className="flex flex-col gap-2">+ <div className="flex flex-col gap-0.5">+ <h2 className="font-semibold text-[13px] text-gray-12">{title}</h2>+ <p className="text-[11.5px] text-gray-10 leading-snug">{help}</p>+ </div>+ {children}+ </section>);}diff --git a/products/desktop/packages/ui/src/features/scouts/components/ScoutDetailHeader.stories.tsx b/products/desktop/packages/ui/src/features/scouts/components/ScoutDetailHeader.stories.tsxnew file mode 100644index 000000000000..af39ba175451--- /dev/null+++ b/products/desktop/packages/ui/src/features/scouts/components/ScoutDetailHeader.stories.tsx@@ -0,0 +1,95 @@+import type { ScoutConfig, ScoutRun } from "@posthog/api-client/posthog-client";+import { computeScoutRollups } from "@posthog/core/scouts/scoutPresentation";+import {+ ANONYMOUS_AUTH_STATE,+ useAuthStore,+} from "@posthog/ui/features/auth/store";+import type { Meta, StoryObj } from "@storybook/react-vite";+import type { ReactNode } from "react";+import { ScoutDetailHeader } from "./ScoutDetailHeader";++const NOW = new Date("2026-07-09T09:00:00Z");++// An invented agent. Nothing here comes from a real project.+const CONFIG: ScoutConfig = {+ id: "config-checkout-funnel",+ skill_name: "signals-scout-checkout-funnel",+ enabled: true,+ emit: true,+ scout_origin: "custom",+ run_interval_minutes: 480,+ auto_pause_exempt: false,+ created_at: "2026-06-01T00:00:00Z",+ last_run_at: "2026-07-09T06:30:00Z",+ description:+ "Watches conversion through the checkout funnel and sends a signal when a step drops against its own two-week baseline.",+};++const RUNS: ScoutRun[] = Array.from({ length: 14 }, (_, index) => ({+ run_id: `run-${index}`,+ skill_name: CONFIG.skill_name,+ skill_version: 1,+ status: "completed",+ started_at: new Date(NOW.getTime() - index * 28_800_000).toISOString(),+ completed_at: new Date(+ NOW.getTime() - index * 28_800_000 + 240_000,+ ).toISOString(),+ task_id: null,+ task_run_id: null,+ task_url: null,+ summary: "Checked every step. Nothing moved outside the baseline.",+ emitted_count: index % 5 === 0 ? 1 : 0,+ emitted_finding_ids: [],+}));++const ROLLUP = computeScoutRollups(RUNS).get(CONFIG.skill_name);++/** The header builds a "run now" action, which needs a signed-in client to exist. */+function SignedIn({ children }: { children: ReactNode }) {+ useAuthStore.setState({+ authState: {+ ...ANONYMOUS_AUTH_STATE,+ status: "authenticated",+ cloudRegion: "us",+ currentProjectId: 1,+ },+ });+ return <>{children}</>;+}++const noop = () => undefined;++const meta = {+ title: "Scouts/ScoutDetailHeader",+ component: ScoutDetailHeader,+ parameters: { layout: "fullscreen" },+ decorators: [+ (Story) => (+ <SignedIn>+ <Story />+ </SignedIn>+ ),+ ],+ args: {+ config: CONFIG,+ configLoading: false,+ displayName: "Checkout funnel",+ rollup: ROLLUP,+ onUpdate: noop,+ tab: "activity" as const,+ onTabChange: noop,+ onBack: noop,+ },+} satisfies Meta<typeof ScoutDetailHeader>;++export default meta;++type Story = StoryObj<typeof meta>;++/** What one agent's page opens on: who it is, when it runs, and how it has been doing. */+export const Header: Story = {};++/** The config request has not answered yet. */+export const Loading: Story = {+ args: { config: undefined, configLoading: true, rollup: undefined },+};diff --git a/products/desktop/packages/ui/src/features/scouts/components/ScoutDetailHeader.tsx b/products/desktop/packages/ui/src/features/scouts/components/ScoutDetailHeader.tsxindex 17471b67f3f0..ea17ef4439a8 100644--- a/products/desktop/packages/ui/src/features/scouts/components/ScoutDetailHeader.tsx+++ b/products/desktop/packages/ui/src/features/scouts/components/ScoutDetailHeader.tsx@@ -1,135 +1,303 @@-import { ArrowSquareOutIcon, GearSixIcon } from "@phosphor-icons/react";+import { ArrowLeftIcon, PlayIcon } from "@phosphor-icons/react";import type { ScoutConfig } from "@posthog/api-client/posthog-client";import {+ SCOUT_DETAIL_TABS,+ type ScoutDetailTab,+} from "@posthog/core/scouts/scoutDetailTabs";+import {+ deriveRunOutcome,+ deriveScoutLifecycle,+ formatNextRun,+ formatRunDuration,formatScoutScheduleShort,+ getScoutOrigin,+ hasPendingScoutRun,+ nextRunAt,+ runDurationSeconds,type ScoutRollup,+ scoutCreatorDisplayName,+ scoutRunOutcomeLabel,+ scoutSummarySentence,} from "@posthog/core/scouts/scoutPresentation";-import { ANALYTICS_EVENTS } from "@posthog/shared";-import { track } from "@posthog/ui/shell/analytics";-import { skillUrl } from "@posthog/ui/utils/posthogLinks";-import { Box, Flex, Text, Tooltip } from "@radix-ui/themes";-import { useState } from "react";+import { Button, Skeleton } from "@posthog/quill";+import { RelativeTimestamp } from "@posthog/ui/primitives/RelativeTimestamp";+import { TabStrip } from "@posthog/ui/primitives/TabStrip";+import { Fragment, type ReactNode } from "react";import type { ScoutConfigUpdate } from "../hooks/useScoutConfigMutations";-import { DryRunBadge, ScoutOriginBadge } from "./ScoutBadges";-import { ScoutConfigForm, ScoutEnabledSwitch } from "./ScoutConfigControls";-import {- ScoutLifecycleBadge,- ScoutLifecycleNotice,-} from "./ScoutLifecycleBadges";-import { ScoutChatButton } from "./ScoutRowCard";-import { ScoutRunBoxes } from "./ScoutRunBoxes";+import { useScoutRunNow } from "../hooks/useScoutRunNow";+import { useScoutSkillCreators } from "../hooks/useScoutSkillCreators";+import { ScoutChatButton } from "./ScoutChatButton";+import { ScoutEnabledSwitch } from "./ScoutConfigControls";+import { ScoutHealthBanner } from "./ScoutLifecycleBadges";++const TAB_LABEL: Record<ScoutDetailTab, string> = {+ activity: "Activity",+ output: "Output",+ settings: "Settings",+};++const TABS = SCOUT_DETAIL_TABS.map((key) => ({ key, label: TAB_LABEL[key] }));/**- * Header for the scout detail screen. Unlike the fleet-list `ScoutRowCard`,- * this is not a card: the agent name, badges, skill link and cadence sit on the- * page-title row with chat/settings/enable controls aligned right, then the- * runs-window stats and the recent-runs boxes read as plain page content.+ * Header for the agent page: name and health, one line on what it does, the+ * heartbeat (next run, last run), the actions, and the tab strip.*/export function ScoutDetailHeader({config,+ configLoading,+ displayName,rollup,onUpdate,- windowLabel,+ tab,+ onTabChange,+ onBack,+}: {+ config: ScoutConfig | undefined;+ configLoading: boolean;+ displayName: string;+ rollup: ScoutRollup | undefined;+ onUpdate: (configId: string, updates: ScoutConfigUpdate) => void;+ tab: ScoutDetailTab;+ onTabChange: (tab: ScoutDetailTab) => void;+ onBack: () => void;+}) {+ return (+ <div className="flex shrink-0 cursor-default flex-col gap-3 border-(--gray-5) border-b px-6 pt-4">+ <button+ type="button"+ onClick={onBack}+ className="flex w-fit cursor-pointer items-center gap-1 border-0 bg-transparent p-0 text-[12px] text-gray-10 hover:text-gray-12"+ data-attr="scout-detail-back"+ >+ <ArrowLeftIcon size={12} />+ Agents+ </button>++ {configLoading || !config ? (+ <div className="flex flex-col gap-2">+ <span className="font-bold text-[22px] text-gray-12 leading-tight tracking-tight">+ {displayName}+ </span>+ {configLoading ? <Skeleton className="h-4 w-80" /> : null}+ </div>+ ) : (+ <ScoutDetailHeading+ config={config}+ displayName={displayName}+ rollup={rollup}+ onUpdate={onUpdate}+ onShowTab={onTabChange}+ />+ )}++ <TabStrip+ tabs={TABS}+ value={tab}+ onValueChange={onTabChange}+ dataAttrPrefix="scout-tab"+ className="-mb-px min-w-0 overflow-x-auto"+ />+ </div>+ );+}++function ScoutDetailHeading({+ config,displayName,- runsLoading,+ rollup,+ onUpdate,+ onShowTab,}: {config: ScoutConfig;+ displayName: string;rollup: ScoutRollup | undefined;onUpdate: (configId: string, updates: ScoutConfigUpdate) => void;- /** Label for the runs window (e.g. "last 3 days") shown in the stats line. */- windowLabel: string;- displayName: string;- /** Runs load separately from the config; reserve the stats row while pending. */- runsLoading: boolean;+ onShowTab: (tab: ScoutDetailTab) => void;}) {- const [settingsOpen, setSettingsOpen] = useState(false);- const cloudSkillUrl = skillUrl(config.skill_name);+ const now = new Date();+ const { runNow, isStarting } = useScoutRunNow(config, "scout_detail");+ const { data: creators } = useScoutSkillCreators();+ const creator = creators?.get(config.skill_name);+ const summary = scoutSummarySentence(config.description);+ const latest = rollup?.latestRun ?? null;+ const pendingRun = rollup?.runningRun;+ const running =+ pendingRun && deriveRunOutcome(pendingRun, now) === "running"+ ? pendingRun+ : null;+ const next = formatNextRun(nextRunAt(config, now), now);+ const latestDuration = latest+ ? formatRunDuration(runDurationSeconds(latest, now))+ : "";+ const latestOutcome = latest ? deriveRunOutcome(latest, now) : null;+ const origin = getScoutOrigin(config) === "canonical" ? "Built in" : "Custom";- return (- <Flex direction="column" gap="2">- <Flex align="center" gap="2">- <Text className="min-w-0 truncate font-bold text-[22px] text-gray-12 leading-tight tracking-tight">- {displayName}- </Text>- <ScoutOriginBadge config={config} />- <DryRunBadge config={config} />- <ScoutLifecycleBadge config={config} />- {cloudSkillUrl ? (- <Tooltip content="View skill in PostHog">- <a- href={cloudSkillUrl}- target="_blank"- rel="noreferrer"- aria-label={`${config.skill_name} skill in PostHog`}- onClick={() =>- track(ANALYTICS_EVENTS.SCOUT_ACTION, {- action_type: "open_skill_in_posthog",- surface: "scout_detail",- skill_name: config.skill_name,- })- }- className="text-gray-9 transition-colors hover:text-accent-11"- >- <ArrowSquareOutIcon size={14} />- </a>- </Tooltip>+ const meta: ReactNode[] = [+ creator ? `${origin} · by ${scoutCreatorDisplayName(creator)}` : origin,+ ];+ if (!config.emit) meta.push("Dry run");+ meta.push(formatScoutScheduleShort(config));+ if (running) {+ meta.push(+ <span className="text-(--blue-11)">+ Running now+ {running.started_at ? (+ <>+ , started{" "}+ <RelativeTimestamp+ timestamp={running.started_at}+ className="text-(--blue-11) text-[12px]"+ />+ </>) : null}- <Text className="max-w-[14rem] truncate text-[12px] text-gray-10">- {formatScoutScheduleShort(config)}- </Text>- <span className="flex-1" />- <ScoutChatButton skillName={config.skill_name} surface="scout_detail" />- <Tooltip content="Scout settings">- <button+ </span>,+ );+ } else if (next) {+ meta.push(+ <>+ Next run <span className="text-gray-12">{next}</span>+ </>,+ );+ } else {+ meta.push(+ !config.enabled+ ? "Switched off"+ : config.run_cron_schedule+ ? "Uses the project timezone"+ : "Next run time is unavailable",+ );+ }+ if (latest && latestOutcome !== "running") {+ meta.push(+ <>+ Last run{" "}+ <RelativeTimestamp+ timestamp={latest.started_at}+ className="text-[12px] text-gray-12"+ />+ {latestDuration ? `, ${latestDuration}` : ""}+ {", "}+ <span+ className={+ latestOutcome === "error" || latestOutcome === "stuck"+ ? "text-(--red-11)"+ : latestOutcome === "timed_out"+ ? "text-(--amber-11)"+ : undefined+ }+ >+ {scoutRunOutcomeLabel(latest, now)}+ </span>+ </>,+ );+ }++ return (+ <div className="flex flex-col gap-3">+ <div className="flex items-start gap-4">+ <div className="flex min-w-0 flex-1 flex-col gap-1">+ <div className="flex min-w-0 items-center gap-2.5">+ <h1 className="min-w-0 truncate font-bold text-[22px] text-gray-12 leading-tight tracking-tight">+ {displayName}+ </h1>+ <HealthMark config={config} running={Boolean(running)} />+ </div>+ <p className="flex flex-wrap items-center gap-x-1.5 text-[12px] text-gray-10">+ {meta.map((item, index) => (+ // biome-ignore lint/suspicious/noArrayIndexKey: static list built per render+ <Fragment key={index}>+ {index > 0 ? <span className="text-gray-8">·</span> : null}+ <span>{item}</span>+ </Fragment>+ ))}+ </p>+ </div>+ <div className="flex shrink-0 items-center gap-2">+ <Buttontype="button"- onClick={() => {- const next = !settingsOpen;- setSettingsOpen(next);- track(ANALYTICS_EVENTS.SCOUT_ACTION, {- action_type: next ? "open_settings" : "close_settings",- surface: "scout_detail",- skill_name: config.skill_name,- });- }}- aria-expanded={settingsOpen}- aria-label={`${config.skill_name} settings`}- className={`flex h-6 w-6 items-center justify-center rounded transition-colors ${- settingsOpen- ? "bg-(--gray-4) text-gray-12"- : "text-gray-10 hover:bg-(--gray-3) hover:text-gray-12"- }`}+ variant="outline"+ size="sm"+ onClick={() => void runNow()}+ disabled={isStarting || hasPendingScoutRun(rollup)}+ data-attr="scout-run-now">- <GearSixIcon size={15} />- </button>- </Tooltip>- <ScoutEnabledSwitch config={config} onUpdate={onUpdate} />- </Flex>+ <PlayIcon size={13} />+ {isStarting ? "Starting…" : running ? "Running" : "Run now"}+ </Button>+ <ScoutChatButton+ skillName={config.skill_name}+ surface="scout_detail"+ label="Discuss"+ />+ <ScoutEnabledSwitch config={config} onUpdate={onUpdate} />+ </div>+ </div>- <ScoutLifecycleNotice config={config} />-- {runsLoading ? (- <Box className="h-[18px] w-80 max-w-full animate-pulse rounded bg-(--gray-3)" />- ) : rollup && rollup.runCount > 0 ? (- <Flex align="center" gap="3" wrap="wrap">- <Text className="text-[12.5px] text-gray-11">- {capitalize(windowLabel)}: {rollup.runCount} runs ·{" "}- {rollup.completedCount} completed · {rollup.failedCount} failed ·{" "}- {rollup.emittedCount} signal{rollup.emittedCount === 1 ? "" : "s"}{" "}- emitted- </Text>- {rollup.runs.length > 0 ? <ScoutRunBoxes runs={rollup.runs} /> : null}- </Flex>+ {summary ? (+ <p className="flex max-w-3xl flex-wrap items-baseline gap-x-2 text-[13px] text-gray-11 leading-snug">+ <span className="min-w-0">{summary}</span>+ <Button+ type="button"+ variant="link-muted"+ size="xs"+ className="h-auto px-0"+ onClick={() => onShowTab("settings")}+ data-attr="scout-open-instructions"+ >+ Read instructions+ </Button>+ </p>) : null}- {settingsOpen ? (- <Box className="mt-1 border-(--gray-4) border-t pt-3">- <ScoutConfigForm config={config} onUpdate={onUpdate} />- </Box>- ) : null}- </Flex>+ <ScoutHealthBanner+ config={config}+ onUpdate={onUpdate}+ onShowTab={onShowTab}+ />+ </div>);}-function capitalize(value: string): string {- return value.charAt(0).toUpperCase() + value.slice(1);+/** One word on the agent's state. Nothing when it is on and healthy. */+function HealthMark({+ config,+ running,+}: {+ config: ScoutConfig;+ running: boolean;+}) {+ const lifecycle = deriveScoutLifecycle(config);+ const mark = running+ ? {+ dot: "bg-(--blue-9) animate-pulse",+ text: "text-(--blue-11)",+ label: "Running",+ }+ : lifecycle.isSystemPaused+ ? { dot: "bg-(--red-9)", text: "text-(--red-11)", label: lifecycle.label }+ : lifecycle.isWarned+ ? {+ dot: "bg-(--amber-9)",+ text: "text-(--amber-11)",+ label: lifecycle.label,+ }+ : !config.enabled+ ? {+ dot: "border-[1.5px] border-(--gray-8)",+ text: "text-gray-10",+ label: "Off",+ }+ : null;+ if (!mark) return null;+ return (+ <span+ className={`flex shrink-0 items-center gap-1.5 font-medium text-[12px] ${mark.text}`}+ >+ <span+ className={`inline-block h-2 w-2 rounded-full ${mark.dot}`}+ aria-hidden+ />+ {mark.label}+ </span>+ );}diff --git a/products/desktop/packages/ui/src/features/scouts/components/ScoutDetailView.tsx b/products/desktop/packages/ui/src/features/scouts/components/ScoutDetailView.tsxindex 6f7750241adf..c3f8b501ddc6 100644--- a/products/desktop/packages/ui/src/features/scouts/components/ScoutDetailView.tsx+++ b/products/desktop/packages/ui/src/features/scouts/components/ScoutDetailView.tsx@@ -1,91 +1,55 @@-import {- ArrowLeftIcon,- CaretRightIcon,- CompassIcon,-} from "@phosphor-icons/react";-import type { ScoutRun } from "@posthog/api-client/posthog-client";+import type { ScoutDetailTab } from "@posthog/core/scouts/scoutDetailTabs";import {computeScoutRollups,- deriveRunFailureKind,- formatRunDuration,getScoutOrigin,- normalizeRunStatus,prettifyScoutSkillName,- runDurationSeconds,- runMatchesFilter,- type ScoutRunFilter,scoutSkillNameFromSlug,} from "@posthog/core/scouts/scoutPresentation";-import {- SCOUT_RUNS_WINDOW_SPAN,- scoutRunsWindowLabel,-} from "@posthog/core/scouts/scoutRunsWindow";import { ANALYTICS_EVENTS } from "@posthog/shared";-import { MarkdownRenderer } from "@posthog/ui/features/editor/components/MarkdownRenderer";-import { useSetHeaderContent } from "@posthog/ui/hooks/useSetHeaderContent";-import { RelativeTimestamp } from "@posthog/ui/primitives/RelativeTimestamp";+import { useAgentsPageActions } from "@posthog/ui/features/agents/agentsPageStore";import { track } from "@posthog/ui/shell/analytics";-import { getPostHogUrl } from "@posthog/ui/utils/urls";-import { Badge, Box, Flex, Text } from "@radix-ui/themes";-import { Link } from "@tanstack/react-router";-import { useEffect, useMemo, useRef, useState } from "react";+import { useEffect, useMemo, useRef } from "react";+import { useAuthStateValue } from "../../auth/store";import { useScoutConfigMutations } from "../hooks/useScoutConfigMutations";import { useScoutConfigs } from "../hooks/useScoutConfigs";import { useScoutRuns } from "../hooks/useScoutRuns";+import { ScoutActivityTab } from "./ScoutActivityTab";+import { ScoutConfigForm } from "./ScoutConfigControls";import { ScoutDetailHeader } from "./ScoutDetailHeader";-import { ScoutSignalsSection } from "./ScoutSignalsSection";-import { ScoutTaskRunLink } from "./ScoutTaskRunLink";--const FILTERS: { value: ScoutRunFilter; label: string }[] = [- { value: "all", label: "All" },- { value: "emitted", label: "Emitted" },- { value: "quiet", label: "Quiet" },- { value: "failed", label: "Failed" },-];+import { ScoutOutputSection } from "./ScoutOutputSection";export function ScoutDetailView({skillSlug,highlightFindingId,+ tab,}: {skillSlug: string;/** Emission id from a shared finding link – expanded and scrolled to when present. */highlightFindingId?: string;+ tab: ScoutDetailTab;}) {+ const projectId = useAuthStateValue((state) => state.currentProjectId);const skillName = scoutSkillNameFromSlug(skillSlug);const displayName = prettifyScoutSkillName(skillName);+ const { showAgentTab, showTab } = useAgentsPageActions();- const headerContent = useMemo(- () => (- <Flex align="center" gap="2" className="w-full min-w-0">- <CompassIcon size={12} className="shrink-0 text-gray-10" />- <Text- className="truncate whitespace-nowrap font-medium text-[13px]"- title={displayName}- >- {displayName}- </Text>- </Flex>- ),- [displayName],- );- useSetHeaderContent(headerContent);-+ const configsQuery = useScoutConfigs();const {data: configs,isLoading: configsLoading,isError: configsError,- } = useScoutConfigs();+ } = configsQuery;+ const runsQuery = useScoutRuns(skillName);const {data: runsWindow,isLoading: runsLoading,+ isFetching: runsLoadingMore,isError: runsError,- } = useScoutRuns();+ } = runsQuery;+ const incomplete = runsWindow ? !runsWindow.complete : false;const { updateConfig } = useScoutConfigMutations();- const [filter, setFilter] = useState<ScoutRunFilter>("all");const config = configs?.find((entry) => entry.skill_name === skillName);- // The runs endpoint has no skill_name filter yet (scouts-ui api gap 1), so- // select this scout's runs from the fleet window client-side.const scoutRuns = useMemo(() =>(runsWindow?.runs ?? []).filter((run) => run.skill_name === skillName),@@ -95,28 +59,36 @@ export function ScoutDetailView({() => computeScoutRollups(scoutRuns).get(skillName),[scoutRuns, skillName],);- const filteredRuns = useMemo(- () => scoutRuns.filter((run) => runMatchesFilter(run, filter)),- [scoutRuns, filter],- );- const filterCounts = useMemo(() => {- const counts = new Map<ScoutRunFilter, number>();- for (const entry of FILTERS) {- counts.set(- entry.value,- scoutRuns.filter((run) => runMatchesFilter(run, entry.value)).length,- );- }- return counts;- }, [scoutRuns]);+ // Pages arrive newest first, so an agent with nothing yet may still be in a+ // page that has not landed. That reads as loading, never as "no runs".+ const runsUnknown =+ runsLoading || (runsLoadingMore && scoutRuns.length === 0);++ const showDetailTab = (next: ScoutDetailTab) => {+ track(ANALYTICS_EVENTS.SCOUT_ACTION, {+ action_type: "switch_detail_tab",+ surface: "scout_detail",+ skill_name: skillName,+ filter: next,+ });+ showAgentTab(next);+ };// Fire the viewed event once per scout, after both queries settle so the// config and run-window stats are real rather than loading-state zeros.const viewTrackedFor = useRef<string | null>(null);useEffect(() => {- if (configsLoading || runsLoading) return;- if (viewTrackedFor.current === skillName) return;- viewTrackedFor.current = skillName;+ if (+ !configsQuery.isFetchedAfterMount ||+ configsQuery.isFetching ||+ configsError ||+ !runsQuery.isFetchedAfterMount ||+ runsQuery.isFetching ||+ runsError+ )+ return;+ if (viewTrackedFor.current === `${projectId}:${skillName}`) return;+ viewTrackedFor.current = `${projectId}:${skillName}`;track(ANALYTICS_EVENTS.SCOUT_DETAIL_VIEWED, {skill_name: skillName,scout_origin: getScoutOrigin(config),@@ -128,248 +100,72 @@ export function ScoutDetailView({emitted_signal_count: rollup?.emittedCount ?? 0,failed_run_count: rollup?.failedCount ?? 0,});- }, [configsLoading, runsLoading, skillName, config, rollup]);+ }, [+ configsQuery.isFetchedAfterMount,+ configsQuery.isFetching,+ configsError,+ runsQuery.isFetchedAfterMount,+ runsQuery.isFetching,+ runsError,+ projectId,+ skillName,+ config,+ rollup,+ ]);return (- <Flex direction="column" className="h-full min-h-0">- <Flex- direction="column"- gap="2"- className="border-(--gray-5) border-b px-6 pt-5 pb-5"- >- <Link- to="/agents"- className="flex w-fit items-center gap-1 text-[12px] text-gray-10 no-underline hover:text-gray-12"- >- <ArrowLeftIcon size={12} />- Agents- </Link>- {configsLoading ? (- <Box className="h-7 w-64 animate-pulse rounded bg-(--gray-3)" />- ) : config ? (- <ScoutDetailHeader- config={config}- rollup={rollup}- onUpdate={updateConfig}- windowLabel={scoutRunsWindowLabel(runsWindow)}- displayName={displayName}- runsLoading={runsLoading}- />- ) : (- <Text className="font-bold text-[22px] text-gray-12 leading-tight tracking-tight">- {displayName}- </Text>- )}- </Flex>+ <div className="flex h-full min-h-0 flex-col">+ <ScoutDetailHeader+ config={config}+ configLoading={configsLoading}+ displayName={displayName}+ rollup={rollup}+ onUpdate={updateConfig}+ tab={tab}+ onTabChange={showDetailTab}+ onBack={() => showTab("agents")}+ /><div className="min-h-0 flex-1 overflow-auto">- <div className="mx-auto max-w-4xl px-6 py-6">- <Flex direction="column" gap="5">- {configsError ? (- <Text className="text-(--red-11) text-[12.5px]">- Couldn't load this scout's config.- </Text>- ) : !configsLoading && !config ? (- <Text className="text-[12.5px] text-gray-11">- No config found for this scout on the current project.- </Text>- ) : config?.description?.trim() ? (- <Text className="text-pretty text-[12.5px] text-gray-11 leading-relaxed">- {config.description.trim()}- </Text>- ) : null}-- <ScoutSignalsSection+ <div className="mx-auto max-w-[90rem] px-6 py-6">+ {runsError && runsWindow ? (+ <output className="text-(--amber-11) text-[12.5px]">+ Run history could not refresh. Available data remains visible.+ </output>+ ) : null}+ {configsError && !configs ? (+ <p className="text-(--red-11) text-[12.5px]">+ Couldn't load this agent's configuration.+ </p>+ ) : !configsLoading && !config ? (+ <p className="text-[12.5px] text-gray-11">+ No configuration found for this agent on the current project.+ </p>+ ) : tab === "activity" ? (+ <ScoutActivityTab+ skillName={skillName}+ rollup={rollup}+ runs={scoutRuns}+ incomplete={incomplete}+ loading={runsUnknown}+ loadingMore={runsLoadingMore}+ error={runsError && !runsWindow}+ />+ ) : tab === "output" ? (+ <ScoutOutputSection+ key={skillName}runs={scoutRuns}- windowLabel={scoutRunsWindowLabel(runsWindow)}loading={runsLoading}- error={runsError}+ loadingMore={runsLoadingMore}+ incomplete={incomplete}+ error={runsError && !runsWindow}highlightFindingId={highlightFindingId}/>-- <Flex direction="column" gap="3">- <Flex align="center" gap="2" wrap="wrap">- <Text className="font-semibold text-[13px] text-gray-12">- Runs- </Text>- <span className="flex-1" />- {FILTERS.map((entry) => (- <button- key={entry.value}- type="button"- onClick={() => {- setFilter(entry.value);- track(ANALYTICS_EVENTS.SCOUT_ACTION, {- action_type: "filter_runs",- surface: "scout_detail",- skill_name: skillName,- filter: entry.value,- filter_match_count: filterCounts.get(entry.value) ?? 0,- });- }}- className={`rounded-full px-2.5 py-0.5 text-[11.5px] transition-colors ${- filter === entry.value- ? "bg-(--accent-4) text-accent-12"- : "text-gray-10 hover:bg-gray-3 hover:text-gray-12"- }`}- >- {entry.label} {filterCounts.get(entry.value) ?? 0}- </button>- ))}- </Flex>-- {runsLoading ? (- <RunListSkeleton />- ) : runsError ? (- <Text className="text-(--red-11) text-[12.5px]">- Couldn't load runs for this scout. The scout API may be- unavailable or this token may lack the{" "}- <code>signal_scout</code> scope.- </Text>- ) : filteredRuns.length === 0 ? (- <Text className="text-[12.5px] text-gray-11">- {scoutRuns.length > 0- ? `No runs match this filter in the ${scoutRunsWindowLabel(runsWindow)}.`- : runsWindow && !runsWindow.complete- ? `No runs fetched in the last ${SCOUT_RUNS_WINDOW_SPAN} – the fleet window was truncated before it could cover this scout, so runs may exist beyond what was fetched.`- : `No runs in the ${scoutRunsWindowLabel(runsWindow)}.`}- </Text>- ) : (- <Flex direction="column" gap="2">- {filteredRuns.map((run) => (- <ScoutRunListItem key={run.run_id} run={run} />- ))}- </Flex>- )}-- <Text className="text-[12px] text-gray-10">- Showing this scout's runs from the last{" "}- {SCOUT_RUNS_WINDOW_SPAN}.- </Text>- </Flex>- </Flex>+ ) : config ? (+ <ScoutConfigForm config={config} onUpdate={updateConfig} />+ ) : null}</div></div>- </Flex>- );-}--function ScoutRunListItem({ run }: { run: ScoutRun }) {- const [expanded, setExpanded] = useState(false);- const taskRunUrl = run.task_url ? getPostHogUrl(run.task_url) : null;- const now = new Date();- const status = normalizeRunStatus(run.status);- const failureKind = deriveRunFailureKind(run, now);- const duration = formatRunDuration(runDurationSeconds(run, now));- const emitted = run.emitted_count ?? 0;-- return (- <Box className="rounded-(--radius-3) border border-border bg-(--color-panel-solid) px-4 py-3 transition duration-150 hover:border-(--gray-6)">- <button- type="button"- onClick={() => {- const next = !expanded;- setExpanded(next);- track(ANALYTICS_EVENTS.SCOUT_ACTION, {- action_type: next ? "expand_run" : "collapse_run",- surface: "scout_detail",- skill_name: run.skill_name,- run_id: run.run_id,- run_status: status,- emitted_count: emitted,- });- }}- aria-expanded={expanded}- className="flex w-full select-none items-center gap-2 text-left"- >- <CaretRightIcon- size={11}- className={`shrink-0 text-gray-9 transition-transform duration-150 ${expanded ? "rotate-90" : ""}`}- />- <RunGlyph status={status} emitted={emitted} />- <RelativeTimestamp timestamp={run.started_at} />- {duration ? (- <Text className="text-[11.5px] text-gray-10">· {duration}</Text>- ) : null}- {failureKind ? (- <Text className="text-(--amber-11) text-[11.5px]">- · {failureKind === "timed_out" ? "timed out" : "failed"}- </Text>- ) : null}- <span className="flex-1" />- {emitted > 0 ? (- <Badge variant="soft" color="iris" size="1" className="text-[11px]">- {emitted} signal{emitted === 1 ? "" : "s"} emitted- </Badge>- ) : status === "completed" ? (- <Text className="text-[11.5px] text-gray-9">0 signals emitted</Text>- ) : null}- </button>- {run.summary ? (- <Box- className={`mt-1.5 text-pretty break-words text-[12.5px] text-gray-11 leading-snug [&_code]:text-[11px] [&_p:last-child]:mb-0 [&_p]:mb-1 [&_pre]:text-[11px] ${- expanded ? "" : "line-clamp-2"- }`}- >- <MarkdownRenderer content={run.summary} />- </Box>- ) : status === "failed" ? (- <Text className="mt-1.5 block text-[12.5px] text-gray-10 italic leading-snug">- No summary – the run ended before writing its close-out. The task run- in PostHog is the only diagnostic.- </Text>- ) : null}- {expanded ? (- <Flex- align="center"- gap="2"- mt="2"- pt="2"- className="border-t border-t-(--gray-5) text-[11px] text-gray-10"- >- <Text className="font-mono text-[11px]">{run.run_id}</Text>- <span className="flex-1" />- {taskRunUrl ? (- <ScoutTaskRunLink- run={run}- taskRunUrl={taskRunUrl}- runStatus={status}- />- ) : (- <Text className="shrink-0 text-[11px] text-gray-9">- No task link available- </Text>- )}- </Flex>- ) : null}- </Box>- );-}--function RunGlyph({ status, emitted }: { status: string; emitted: number }) {- if (status === "failed") {- return <Text className="font-medium text-(--red-9) text-[12px]">✗</Text>;- }- if (status === "running" || status === "queued") {- return (- <span className="inline-block h-2 w-2 animate-pulse rounded-full bg-(--blue-9)" />- );- }- if (emitted > 0) {- return <Text className="font-medium text-(--iris-9) text-[12px]">◆</Text>;- }- return <Text className="text-[12px] text-gray-8">·</Text>;-}--function RunListSkeleton() {- return (- <Flex direction="column" gap="2">- {[0, 1, 2].map((index) => (- <Box- key={index}- className="h-14 w-full animate-pulse rounded-(--radius-3) bg-(--gray-3)"- />- ))}- </Flex>+ </div>);}diff --git a/products/desktop/packages/ui/src/features/scouts/components/ScoutEmissionCard.tsx b/products/desktop/packages/ui/src/features/scouts/components/ScoutEmissionCard.tsxindex cf1e3fbb85f2..faa4f179804a 100644--- a/products/desktop/packages/ui/src/features/scouts/components/ScoutEmissionCard.tsx+++ b/products/desktop/packages/ui/src/features/scouts/components/ScoutEmissionCard.tsx@@ -3,11 +3,11 @@ import type {LinkedSignalReport,ScoutEmission,} from "@posthog/api-client/posthog-client";+import { Badge } from "@posthog/quill";import { ANALYTICS_EVENTS } from "@posthog/shared";import { MarkdownRenderer } from "@posthog/ui/features/editor/components/MarkdownRenderer";import { RelativeTimestamp } from "@posthog/ui/primitives/RelativeTimestamp";import { track } from "@posthog/ui/shell/analytics";-import { Badge, Box, Flex, Text } from "@radix-ui/themes";import { type ReactNode, useEffect, useRef, useState } from "react";import { SeverityBadge } from "./ScoutBadges";import { ScoutLinkedReportChip } from "./ScoutLinkedReportChip";@@ -15,22 +15,14 @@ import { ScoutLinkedReportChip } from "./ScoutLinkedReportChip";export function ScoutEmissionCard({emission,skillName,- scoutLabel,actions,footerEnd,linkedReport,- defaultExpanded = false,highlighted = false,}: {emission: ScoutEmission;/** The emitting scout, attached to analytics events when known. */skillName?: string;- /**- * Prettified emitting-scout name, shown in the header. Set on cross-fleet- * surfaces (the findings page) where cards from different scouts are mixed;- * omit on a single-scout surface where the scout is already obvious.- */- scoutLabel?: string;/** Interactive controls shown after the finding id at the footer's left. */actions?: ReactNode;/** Content pinned to the footer's right edge, e.g. the task-run link. */@@ -41,15 +33,12 @@ export function ScoutEmissionCard({* renders nothing – an unlinked finding shows no report indicator.*/linkedReport?: LinkedSignalReport | null;- defaultExpanded?: boolean;/** True when a shared finding link targets this card – scrolls it into view. */highlighted?: boolean;}) {- const [expanded, setExpanded] = useState(defaultExpanded);+ const [expanded, setExpanded] = useState(highlighted);const cardRef = useRef<HTMLDivElement>(null);- // setExpanded too: when a shared link targets a different finding on an- // already-mounted route, only the search param changes, so the useState- // initializer's defaultExpanded never re-runs.+ // A shared link can target a card that is already mounted and collapsed.useEffect(() => {if (highlighted) {setExpanded(true);@@ -57,7 +46,7 @@ export function ScoutEmissionCard({}}, [highlighted]);return (- <Box+ <divref={cardRef}className={`min-w-0 overflow-hidden rounded-(--radius-2) border bg-gray-1 p-3 ${highlighted ? "border-(--accent-8)" : "border-(--gray-6)"@@ -83,56 +72,31 @@ export function ScoutEmissionCard({className={`shrink-0 text-gray-9 transition-transform duration-150 ${expanded ? "rotate-90" : ""}`}/><CompassIcon size={14} className="shrink-0 text-(--iris-9)" />- <Text className="font-medium text-[13px] text-gray-10">Signal</Text><SeverityBadge severity={emission.severity} />- <Text className="text-[11px] text-gray-10">+ <span className="text-[11px] text-gray-10">confidence {Math.round(emission.confidence * 100)}%- </Text>- {scoutLabel ? (- <Flex align="center" gap="1" className="min-w-0">- <CompassIcon size={11} className="shrink-0 text-gray-9" />- <Text- className="truncate text-[11px] text-gray-9"- title={scoutLabel}- >- {scoutLabel}- </Text>- </Flex>- ) : null}+ </span><span className="flex-1" /><RelativeTimestamp timestamp={emission.emitted_at} /></button>- <Box+ <divclassName={`mt-2 text-pretty break-words text-[13px] text-gray-11 leading-relaxed [&_code]:text-[11px] [&_p:last-child]:mb-0 [&_p]:mb-1 [&_pre]:text-[11px] ${expanded ? "" : "line-clamp-2"}`}><MarkdownRenderer content={emission.description} />- </Box>+ </div>{emission.tags?.length ? (- <Flex gap="1" mt="2" wrap="wrap">+ <div className="mt-2 flex flex-wrap gap-1">{emission.tags.map((tag) => (- <Badge- key={tag}- variant="soft"- color="gray"- size="1"- className="text-[11px]"- >+ <Badge key={tag} variant="default" className="text-[11px]">{tag}</Badge>))}- </Flex>+ </div>) : null}{expanded ? (- <Flex- align="center"- gap="2"- mt="2"- pt="2"- className="border-t border-t-(--gray-5) text-[11px] text-gray-10"- >- <Text className="font-mono text-[11px]">{emission.finding_id}</Text>+ <div className="mt-2 flex items-center gap-2 border-t border-t-(--gray-5) pt-2 text-[11px] text-gray-10">{actions}<span className="flex-1" />{linkedReport ? (@@ -142,8 +106,8 @@ export function ScoutEmissionCard({/>) : null}{footerEnd}- </Flex>+ </div>) : null}- </Box>+ </div>);}diff --git a/products/desktop/packages/ui/src/features/scouts/components/ScoutFindingsView.tsx b/products/desktop/packages/ui/src/features/scouts/components/ScoutFindingsView.tsxdeleted file mode 100644index 4e83352f92f2..000000000000--- a/products/desktop/packages/ui/src/features/scouts/components/ScoutFindingsView.tsx+++ /dev/null@@ -1,366 +0,0 @@-import {- ArrowLeftIcon,- MagnifyingGlassIcon,- SparkleIcon,-} from "@phosphor-icons/react";-import {- availableScoutsFromRows,- filterAndSortScoutFindings,- SCOUT_FINDINGS_SCOUT_FILTER_ALL,- SCOUT_FINDINGS_SEVERITY_FILTER_ALL,- SCOUT_FINDINGS_SEVERITY_OPTIONS,- type ScoutFindingsSortKey,- summarizeScoutFindingRows,-} from "@posthog/core/scouts/scoutFindings";-import { prettifyScoutSkillName } from "@posthog/core/scouts/scoutPresentation";-import { SCOUT_RUNS_WINDOW_SPAN } from "@posthog/core/scouts/scoutRunsWindow";-import { ANALYTICS_EVENTS } from "@posthog/shared";-import { useSetHeaderContent } from "@posthog/ui/hooks/useSetHeaderContent";-import { RelativeTimestamp } from "@posthog/ui/primitives/RelativeTimestamp";-import { track } from "@posthog/ui/shell/analytics";-import { Box, Flex, Select, Text, TextField } from "@radix-ui/themes";-import { Link } from "@tanstack/react-router";-import { useMemo, useState } from "react";-import { useScoutFindings } from "../hooks/useScoutFindings";-import { ScoutEmissionCard } from "./ScoutEmissionCard";--const SORT_OPTIONS: { value: ScoutFindingsSortKey; label: string }[] = [- { value: "newest", label: "Newest" },- { value: "oldest", label: "Oldest" },- { value: "severity", label: "Severity" },- { value: "confidence", label: "Confidence" },-];--/**- * Cross-fleet findings browser — every finding the troop emitted recently in one- * place, newest first, searchable and filterable by scout/severity with a sort- * toggle. Reuses the per-scout {@link ScoutEmissionCard} with the emitting- * scout's name shown. Read-only: acting on a finding happens in its inbox report.- *- * Mirrors the PostHog Cloud `FindingsPanel`, kept structurally aligned so the two- * surfaces stay in parity as the backend evolves.- */-export function ScoutFindingsView() {- const {- rows,- hasLoadedOnce,- runsError,- emissionsError,- emissionsFetching,- refetch,- } = useScoutFindings();-- const [searchText, setSearchText] = useState("");- const [scoutFilter, setScoutFilter] = useState<string>(- SCOUT_FINDINGS_SCOUT_FILTER_ALL,- );- const [severityFilter, setSeverityFilter] = useState<string>(- SCOUT_FINDINGS_SEVERITY_FILTER_ALL,- );- const [sortKey, setSortKey] = useState<ScoutFindingsSortKey>("newest");-- const headerContent = useMemo(- () => (- <Flex align="center" gap="2" className="w-full min-w-0">- <SparkleIcon size={12} className="shrink-0 text-gray-10" />- <Text- className="truncate whitespace-nowrap font-medium text-[13px]"- title="Scout signals"- >- Scout signals- </Text>- </Flex>- ),- [],- );- useSetHeaderContent(headerContent);-- const availableScouts = useMemo(() => availableScoutsFromRows(rows), [rows]);- const summary = useMemo(() => summarizeScoutFindingRows(rows), [rows]);- const filteredRows = useMemo(- () =>- filterAndSortScoutFindings(rows, {- search: searchText,- scout: scoutFilter,- severity: severityFilter,- sort: sortKey,- }),- [rows, searchText, scoutFilter, severityFilter, sortKey],- );-- const isFiltering =- searchText.trim().length > 0 ||- scoutFilter !== SCOUT_FINDINGS_SCOUT_FILTER_ALL ||- severityFilter !== SCOUT_FINDINGS_SEVERITY_FILTER_ALL;-- // A failed initial load with nothing on screen, vs a stale list whose later- // refresh failed — the former is a full error state, the latter a warning that- // the list may be incomplete.- const loadFailed = emissionsError || runsError;-- return (- <Flex direction="column" className="h-full min-h-0">- <Flex- direction="column"- gap="2"- className="border-(--gray-5) border-b px-6 pt-5 pb-5"- >- <Link- to="/agents/scouts"- className="flex w-fit items-center gap-1 text-[12px] text-gray-10 no-underline hover:text-gray-12"- >- <ArrowLeftIcon size={12} />- Scouts- </Link>- <Flex align="center" gap="2">- <SparkleIcon size={20} className="shrink-0 text-(--iris-9)" />- <Text className="font-bold text-[22px] text-gray-12 leading-tight tracking-tight">- Scout signals- </Text>- </Flex>- <Text className="max-w-2xl text-pretty text-[12.5px] text-gray-11 leading-relaxed">- Every signal your scouts have emitted recently, in one place — newest- first. See what's been surfaced across the whole troop, which- scout found it, and the Self-driving report it fed into.- </Text>- <Flex- align="center"- gap="1"- className="text-[12px] text-gray-10"- wrap="wrap"- >- {summary.totalCount > 0 ? (- <>- <Text className="text-[12px] text-gray-10">- {summary.totalCount} signal- {summary.totalCount === 1 ? "" : "s"} · {summary.scoutCount}{" "}- scout{summary.scoutCount === 1 ? "" : "s"}- </Text>- {summary.latestEmittedAt ? (- <>- <Text className="text-[12px] text-gray-9">· latest</Text>- <RelativeTimestamp- timestamp={summary.latestEmittedAt}- className="text-[12px] text-gray-10"- />- </>- ) : null}- </>- ) : null}- </Flex>- <Text className="text-[12px] text-gray-9">- Covers signals from the most recent {SCOUT_RUNS_WINDOW_SPAN} of troop- runs. Older signals live on in the Self-driving reports they produced.- </Text>- </Flex>-- <div className="min-h-0 flex-1 overflow-auto">- <div className="mx-auto max-w-4xl px-6 py-6">- <Flex direction="column" gap="4">- <Flex align="center" gap="2" wrap="wrap">- <TextField.Root- type="search"- placeholder="Search signals…"- value={searchText}- onChange={(event) => setSearchText(event.target.value)}- size="2"- className="min-w-[12rem] flex-1"- >- <TextField.Slot>- <MagnifyingGlassIcon size={14} className="text-gray-10" />- </TextField.Slot>- </TextField.Root>-- <Select.Root- value={scoutFilter}- size="2"- onValueChange={(value) => {- setScoutFilter(value);- track(ANALYTICS_EVENTS.SCOUT_ACTION, {- action_type: "filter_findings",- surface: "scout_findings",- filter: value,- });- }}- >- <Select.Trigger- aria-label="Filter by scout"- className="min-w-[9rem]"- />- <Select.Content>- <Select.Item value={SCOUT_FINDINGS_SCOUT_FILTER_ALL}>- All scouts- </Select.Item>- {availableScouts.map((scout) => (- <Select.Item key={scout.skillName} value={scout.skillName}>- {scout.label} ({scout.count})- </Select.Item>- ))}- </Select.Content>- </Select.Root>-- <Select.Root- value={severityFilter}- size="2"- onValueChange={(value) => {- setSeverityFilter(value);- track(ANALYTICS_EVENTS.SCOUT_ACTION, {- action_type: "filter_findings",- surface: "scout_findings",- filter: `severity:${value}`,- });- }}- >- <Select.Trigger aria-label="Filter by severity" />- <Select.Content>- <Select.Item value={SCOUT_FINDINGS_SEVERITY_FILTER_ALL}>- All severities- </Select.Item>- {SCOUT_FINDINGS_SEVERITY_OPTIONS.map((severity) => (- <Select.Item key={severity} value={severity}>- {severity}- </Select.Item>- ))}- </Select.Content>- </Select.Root>-- <Select.Root- value={sortKey}- size="2"- onValueChange={(value) => {- const next = value as ScoutFindingsSortKey;- setSortKey(next);- track(ANALYTICS_EVENTS.SCOUT_ACTION, {- action_type: "sort_findings",- surface: "scout_findings",- filter: next,- });- }}- >- <Select.Trigger aria-label="Sort signals" />- <Select.Content>- {SORT_OPTIONS.map((option) => (- <Select.Item key={option.value} value={option.value}>- Sort: {option.label}- </Select.Item>- ))}- </Select.Content>- </Select.Root>- </Flex>-- {hasLoadedOnce &&- (emissionsError || runsError) &&- emissionsFetching === false &&- rows.length > 0 ? (- // A later poll/retry failed while a prior set is still on screen.- // The list may be incomplete — warn rather than show it silently.- <Flex- align="center"- gap="3"- className="rounded-(--radius-2) border border-(--amber-6) bg-(--amber-2) px-4 py-3 text-[12.5px]"- >- <Text className="flex-1 text-(--amber-11)">- Some signals couldn't be loaded, so this list may be- incomplete.- </Text>- <button- type="button"- onClick={() => refetch()}- className="shrink-0 rounded-(--radius-2) border border-(--amber-7) px-2.5 py-1 text-(--amber-11) transition-colors hover:bg-(--amber-3)"- >- Retry- </button>- </Flex>- ) : null}-- <FindingsBody- hasLoadedOnce={hasLoadedOnce}- loadFailed={loadFailed}- rowCount={rows.length}- filteredRows={filteredRows}- isFiltering={isFiltering}- onRetry={refetch}- />- </Flex>- </div>- </div>- </Flex>- );-}--function FindingsBody({- hasLoadedOnce,- loadFailed,- rowCount,- filteredRows,- isFiltering,- onRetry,-}: {- hasLoadedOnce: boolean;- loadFailed: boolean;- rowCount: number;- filteredRows: ReturnType<typeof filterAndSortScoutFindings>;- isFiltering: boolean;- onRetry: () => void;-}) {- if (!hasLoadedOnce) {- return (- <Flex direction="column" gap="2">- {[0, 1, 2].map((key) => (- <Box- key={key}- className="h-14 w-full animate-pulse rounded-(--radius-2) bg-(--gray-3)"- />- ))}- </Flex>- );- }-- if (loadFailed && rowCount === 0) {- return (- <Flex- direction="column"- align="center"- gap="2"- className="rounded-(--radius-2) border border-(--gray-6) border-dashed bg-gray-1 px-4 py-8 text-center text-[12.5px] text-gray-11"- >- <Text className="text-[12.5px] text-gray-11">- Couldn't load signals. The scout API may be unavailable or this- project may not be enrolled yet.- </Text>- <button- type="button"- onClick={onRetry}- className="rounded-(--radius-2) border border-(--gray-7) px-2.5 py-1 text-[12px] text-gray-11 transition-colors hover:bg-(--gray-3)"- >- Retry- </button>- </Flex>- );- }-- if (filteredRows.length === 0) {- return (- <Box className="rounded-(--radius-2) border border-(--gray-6) border-dashed bg-gray-1 px-4 py-8 text-center text-[12.5px] text-gray-11">- {isFiltering- ? "No signals match your search and filters."- : "Your scouts haven't emitted any signals yet. As they scan your project, what they surface shows up here."}- </Box>- );- }-- return (- <Flex direction="column" gap="2">- {filteredRows.map((row) => (- <ScoutEmissionCard- // emission.id, not source_id — a run can re-emit a finding_id, sharing source_id.- key={row.emission.id}- emission={row.emission}- skillName={row.run.skill_name}- scoutLabel={prettifyScoutSkillName(row.run.skill_name)}- linkedReport={row.linkedReport}- />- ))}- </Flex>- );-}diff --git a/products/desktop/packages/ui/src/features/scouts/components/ScoutHelperSkillLinks.tsx b/products/desktop/packages/ui/src/features/scouts/components/ScoutHelperSkillLinks.tsxindex b7fe4d6f4929..8d7c9543a9fb 100644--- a/products/desktop/packages/ui/src/features/scouts/components/ScoutHelperSkillLinks.tsx+++ b/products/desktop/packages/ui/src/features/scouts/components/ScoutHelperSkillLinks.tsx@@ -9,8 +9,8 @@ import { Link } from "@tanstack/react-router";// they open in the in-app Skills view rather than linking out to GitHub. `name`// is the skill's frontmatter name, used to select it once Skills loads.const HELPER_SKILLS = [- { label: "authoring scouts", name: "authoring-signals-scouts" },- { label: "exploring scouts", name: "exploring-signals-scouts" },+ { label: "writing agents", name: "authoring-scouts" },+ { label: "exploring agents", name: "exploring-scouts" },];/** One-line pointer to the two official scout helper skills, opened in-app. */@@ -18,7 +18,7 @@ export function ScoutHelperSkillLinks({ surface }: { surface: ScoutSurface }) {const { requestSkill } = useSkillsSelectionActions();return (<Text className="text-[12px] text-gray-10">- Helper skills:{" "}+ Skills:{" "}{HELPER_SKILLS.map((skill, index) => (<span key={skill.name}>{index > 0 ? " · " : null}diff --git a/products/desktop/packages/ui/src/features/scouts/components/ScoutLifecycleBadges.tsx b/products/desktop/packages/ui/src/features/scouts/components/ScoutLifecycleBadges.tsxindex 0098d44b7155..50c27c870914 100644--- a/products/desktop/packages/ui/src/features/scouts/components/ScoutLifecycleBadges.tsx+++ b/products/desktop/packages/ui/src/features/scouts/components/ScoutLifecycleBadges.tsx@@ -1,14 +1,19 @@import type { ScoutConfig } from "@posthog/api-client/posthog-client";-import { deriveScoutLifecycle } from "@posthog/core/scouts/scoutPresentation";+import type { ScoutDetailTab } from "@posthog/core/scouts/scoutDetailTabs";+import {+ deriveScoutLifecycle,+ scoutHealthNotice,+} from "@posthog/core/scouts/scoutPresentation";import {Badge,- Text,+ Button,Tooltip,TooltipContent,TooltipProvider,TooltipTrigger,} from "@posthog/quill";import { RelativeTimestamp } from "@posthog/ui/primitives/RelativeTimestamp";+import type { ScoutConfigUpdate } from "../hooks/useScoutConfigMutations";/*** Why a scout is stopped, or about to be. Renders nothing for the healthy@@ -40,32 +45,82 @@ export function ScoutLifecycleBadge({ config }: { config: ScoutConfig }) {}/**- * The full lifecycle story for surfaces with room for a sentence: what the- * system did and what gets the scout running again. The fleet list makes do- * with `ScoutLifecycleBadge`'s tooltip; this is for the scout detail screen.+ * The banner on the agent page: what the system did, when, and the buttons+ * that resolve it. Renders nothing when the agent is healthy.*/-export function ScoutLifecycleNotice({ config }: { config: ScoutConfig }) {- const lifecycle = deriveScoutLifecycle(config);- if (!lifecycle.explanation) return null;+export function ScoutHealthBanner({+ config,+ onUpdate,+ onShowTab,+}: {+ config: ScoutConfig;+ onUpdate: (configId: string, updates: ScoutConfigUpdate) => void;+ onShowTab: (tab: ScoutDetailTab) => void;+}) {+ const notice = scoutHealthNotice(config);+ if (!notice) return null;+ const changedAt = deriveScoutLifecycle(config).changedAt;+ const destructive = notice.tone === "destructive";return (<div- className={`flex flex-wrap items-center gap-2 rounded-(--radius-2) border px-3 py-2 ${- lifecycle.isSystemPaused+ className={`flex flex-wrap items-center gap-x-3 gap-y-2 rounded-(--radius-md) border px-3.5 py-2.5 ${+ destructive? "border-(--red-6) bg-(--red-2)": "border-(--amber-6) bg-(--amber-2)"}`}+ data-attr="scout-health-banner">- <Text- size="xs"- className={`leading-snug ${- lifecycle.isSystemPaused ? "text-(--red-11)" : "text-(--amber-11)"+ <p+ className={`min-w-0 flex-1 text-[12.5px] leading-snug ${+ destructive ? "text-(--red-11)" : "text-(--amber-11)"}`}>- {lifecycle.explanation}- </Text>- {lifecycle.changedAt ? (- <RelativeTimestamp timestamp={lifecycle.changedAt} />- ) : null}+ {notice.text}+ {changedAt ? (+ <>+ {" "}+ <RelativeTimestamp+ timestamp={changedAt}+ className={`text-[12px] ${destructive ? "text-(--red-10)" : "text-(--amber-10)"}`}+ />+ </>+ ) : null}+ </p>+ <div className="flex shrink-0 items-center gap-1.5">+ {notice.action === "resume" ? (+ <Button+ type="button"+ variant="outline"+ size="xs"+ onClick={() => onUpdate(config.id, { enabled: true })}+ data-attr="scout-health-resume"+ >+ Resume+ </Button>+ ) : null}+ {notice.action === "keep_running" ? (+ <Button+ type="button"+ variant="outline"+ size="xs"+ onClick={() => onUpdate(config.id, { auto_pause_exempt: true })}+ data-attr="scout-health-keep-running"+ >+ Keep running+ </Button>+ ) : null}+ {notice.link ? (+ <Button+ type="button"+ variant="outline"+ size="xs"+ onClick={() => onShowTab(notice.link as ScoutDetailTab)}+ data-attr="scout-health-open-tab"+ >+ {notice.link === "output" ? "Open output" : "Open runs"}+ </Button>+ ) : null}+ </div></div>);}diff --git a/products/desktop/packages/ui/src/features/scouts/components/ScoutNameHoverCard.tsx b/products/desktop/packages/ui/src/features/scouts/components/ScoutNameHoverCard.tsxnew file mode 100644index 000000000000..cc3e780b20cc--- /dev/null+++ b/products/desktop/packages/ui/src/features/scouts/components/ScoutNameHoverCard.tsx@@ -0,0 +1,58 @@+import { PreviewCard } from "@base-ui/react/preview-card";+import type { ScoutConfig } from "@posthog/api-client/posthog-client";+import { Card } from "@posthog/quill";+import type { ReactElement } from "react";++const OPEN_DELAY_MS = 400;+const CLOSE_DELAY_MS = 100;++/**+ * The agent's full description, shown while the pointer rests on its name in+ * the list. The row itself stays one line; the card carries the prose.+ */+export function ScoutNameHoverCard({+ config,+ trigger,+}: {+ config: ScoutConfig;+ /** The name link. Rendered as the card's trigger. */+ trigger: ReactElement;+}) {+ const description = config.description?.trim();+ if (!description) return trigger;+ return (+ <PreviewCard.Root>+ <PreviewCard.Trigger+ render={trigger}+ delay={OPEN_DELAY_MS}+ closeDelay={CLOSE_DELAY_MS}+ />+ <PreviewCard.Portal>+ <PreviewCard.Positioner+ side="bottom"+ align="start"+ sideOffset={6}+ className="z-50"+ >+ <PreviewCard.Popup+ render={+ <Card+ size="sm"+ className="w-96 gap-0 border border-border py-0 shadow-md"+ />+ }+ >+ <div className="flex flex-col gap-2 px-3.5 py-3">+ <p className="max-h-80 overflow-y-auto text-pretty text-[12.5px] text-gray-12 leading-relaxed">+ {description}+ </p>+ <code className="truncate text-[11px] text-gray-10">+ {config.skill_name}+ </code>+ </div>+ </PreviewCard.Popup>+ </PreviewCard.Positioner>+ </PreviewCard.Portal>+ </PreviewCard.Root>+ );+}diff --git a/products/desktop/packages/ui/src/features/scouts/components/ScoutOutputSection.test.tsx b/products/desktop/packages/ui/src/features/scouts/components/ScoutOutputSection.test.tsxnew file mode 100644index 000000000000..40fa996c1f22--- /dev/null+++ b/products/desktop/packages/ui/src/features/scouts/components/ScoutOutputSection.test.tsx@@ -0,0 +1,161 @@+import type { ScoutRun } from "@posthog/api-client/posthog-client";+import { fireEvent, render, screen, waitFor } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++const mocks = vi.hoisted(() => ({+ openReport: vi.fn().mockResolvedValue(undefined),+ emissions: vi.fn(),+ reports: vi.fn(),+}));+vi.mock("@posthog/ui/features/inbox/hooks/useOpenInboxReport", () => ({+ useOpenInboxReport: () => mocks.openReport,+}));+vi.mock("@posthog/ui/features/inbox/hooks/useInboxReports", () => ({+ useInboxReportById: (id: string) => ({+ data: {+ title:+ id === "report-created" ? "Check checkout errors" : "Review slow pages",+ summary: "A short report summary.",+ priority: "P2",+ },+ isLoading: false,+ isError: false,+ }),+}));+vi.mock("framer-motion", () => ({ useInView: () => true }));+vi.mock("@posthog/ui/shell/analytics", () => ({ track: vi.fn() }));+vi.mock("../hooks/useScoutRunEmissions", () => ({+ useScoutRunEmissions: mocks.emissions,+}));+vi.mock("../hooks/useScoutEmissionReports", () => ({+ useScoutEmissionReports: mocks.reports,+}));+vi.mock("@posthog/ui/primitives/RelativeTimestamp", () => ({+ RelativeTimestamp: () => <span>Run time</span>,+}));+vi.mock("@posthog/ui/features/editor/components/MarkdownRenderer", () => ({+ MarkdownRenderer: ({ content }: { content: string }) => <p>{content}</p>,+}));+vi.mock("./ScoutFindingDiscussButton", () => ({+ ScoutFindingDiscussButton: () => null,+}));+vi.mock("./ScoutFindingShareButton", () => ({+ ScoutFindingShareButton: () => null,+}));++import { ScoutOutputSection } from "./ScoutOutputSection";++describe("ScoutOutputSection", () => {+ afterEach(() => vi.restoreAllMocks());+ beforeEach(() => {+ vi.clearAllMocks();+ mocks.emissions.mockReturnValue({+ data: undefined,+ isLoading: false,+ isError: true,+ });+ mocks.reports.mockReturnValue({ data: undefined });+ });++ it("expands a shared finding and lets the user collapse it", () => {+ const run: ScoutRun = {+ run_id: "run-example",+ skill_name: "signals-scout-example",+ skill_version: 1,+ status: "completed",+ started_at: null,+ completed_at: null,+ task_id: null,+ task_run_id: null,+ task_url: "https://example.com/run",+ summary: "",+ emitted_count: 1,+ emitted_finding_ids: ["finding-example"],+ };+ mocks.emissions.mockReturnValue({+ data: [+ {+ id: "finding-example",+ finding_id: "finding-example",+ weight: 1,+ run_id: run.run_id,+ source_id: "source-example",+ description: "A sample finding.",+ confidence: 1,+ severity: null,+ emitted_at: "2026-01-01T00:00:00Z",+ },+ ],+ isLoading: false,+ isError: false,+ });+ const scrollIntoView = vi+ .spyOn(Element.prototype, "scrollIntoView")+ .mockImplementation(() => {});+ const { rerender } = render(+ <ScoutOutputSection runs={[run]} loading={false} />,+ );+ const toggle = screen.getByRole("button", { name: /confidence/ });+ expect(toggle).toHaveAttribute("aria-expanded", "false");+ expect(screen.queryByRole("link", { name: "Open task run" })).toBeNull();++ rerender(+ <ScoutOutputSection+ runs={[run]}+ loading={false}+ highlightFindingId="finding-example"+ />,+ );+ expect(toggle).toHaveAttribute("aria-expanded", "true");+ expect(screen.getByRole("link", { name: "Open task run" })).toHaveAttribute(+ "href",+ run.task_url,+ );+ expect(scrollIntoView).toHaveBeenCalled();++ fireEvent.click(toggle);+ expect(toggle).toHaveAttribute("aria-expanded", "false");+ fireEvent.click(toggle);+ expect(toggle).toHaveAttribute("aria-expanded", "true");+ });++ it.each([0, 1])(+ "opens reports when the old signal count is %s and emissions are unavailable",+ async (emittedCount) => {+ const run: ScoutRun = {+ run_id: "run-example",+ skill_name: "signals-scout-example",+ skill_version: 1,+ status: "completed",+ started_at: null,+ completed_at: null,+ task_id: null,+ task_run_id: null,+ task_url: null,+ summary: "",+ emitted_count: emittedCount,+ emitted_finding_ids: [],+ emitted_report_ids: ["report-created", "report-created"],+ edited_report_ids: ["report-created", "report-updated"],+ };++ render(<ScoutOutputSection runs={[run]} loading={false} />);++ expect(screen.queryByText(/No output/)).toBeNull();+ const created = screen.getByRole("button", {+ name: /Check checkout errors/,+ });+ const updated = screen.getByRole("button", { name: /Review slow pages/ });+ expect(screen.getAllByText("A short report summary.")).toHaveLength(2);+ fireEvent.click(created);+ await waitFor(() => expect(created).not.toBeDisabled());+ expect(mocks.openReport).toHaveBeenLastCalledWith("report-created");+ fireEvent.click(updated);+ await waitFor(() => expect(updated).not.toBeDisabled());+ expect(mocks.openReport).toHaveBeenLastCalledWith("report-updated");+ expect(mocks.emissions).toHaveBeenCalledWith(+ emittedCount ? ["run-example"] : [],+ );+ },+ );+});diff --git a/products/desktop/packages/ui/src/features/scouts/components/ScoutSignalsSection.tsx b/products/desktop/packages/ui/src/features/scouts/components/ScoutOutputSection.tsxsimilarity index 64%rename from products/desktop/packages/ui/src/features/scouts/components/ScoutSignalsSection.tsxrename to products/desktop/packages/ui/src/features/scouts/components/ScoutOutputSection.tsxindex ba046638facb..243a8363c15e 100644--- a/products/desktop/packages/ui/src/features/scouts/components/ScoutSignalsSection.tsx+++ b/products/desktop/packages/ui/src/features/scouts/components/ScoutOutputSection.tsx@@ -3,16 +3,19 @@ import type {ScoutEmission,ScoutRun,} from "@posthog/api-client/posthog-client";+import { scoutRunOutputCount } from "@posthog/core/scouts/scoutPresentation";+import { SCOUT_RUNS_WINDOW_LABEL } from "@posthog/core/scouts/scoutRunsWindow";import { ANALYTICS_EVENTS } from "@posthog/shared";+import { RelativeTimestamp } from "@posthog/ui/primitives/RelativeTimestamp";import { track } from "@posthog/ui/shell/analytics";import { getPostHogUrl } from "@posthog/ui/utils/urls";-import { Box, Flex, Text } from "@radix-ui/themes";import { useMemo, useState } from "react";import { useScoutEmissionReports } from "../hooks/useScoutEmissionReports";import { useScoutRunEmissions } from "../hooks/useScoutRunEmissions";import { ScoutEmissionCard } from "./ScoutEmissionCard";import { ScoutFindingDiscussButton } from "./ScoutFindingDiscussButton";import { ScoutFindingShareButton } from "./ScoutFindingShareButton";+import { ScoutRunReportLinks } from "./ScoutRunReportLinks";import { ScoutTaskRunLink } from "./ScoutTaskRunLink";/**@@ -23,28 +26,28 @@ import { ScoutTaskRunLink } from "./ScoutTaskRunLink";const INITIAL_EMITTED_RUNS = 10;/**- * The signals this scout emitted in the runs window, newest first. The visible- * runs' emissions and report links are fetched in two batched requests (one each)- * rather than one request per run; "Show more" widens the window and refetches,- * keeping the already-rendered cards in place while the larger batch loads.+ * Report ids are on the run itself. Only legacy findings need the emissions+ * and reverse-report lookup requests.*/-export function ScoutSignalsSection({+export function ScoutOutputSection({runs,- windowLabel,loading,+ loadingMore = false,+ incomplete = false,error,highlightFindingId,}: {runs: ScoutRun[];- windowLabel: string;loading: boolean;+ loadingMore?: boolean;+ incomplete?: boolean;error?: boolean;/** Emission id from a shared finding link – expanded and scrolled to when present. */highlightFindingId?: string;}) {const [showAll, setShowAll] = useState(false);const emittedRuns = useMemo(- () => runs.filter((run) => (run.emitted_count ?? 0) > 0),+ () => runs.filter((run) => scoutRunOutputCount(run) > 0),[runs],);const visibleRuns = useMemo(@@ -53,7 +56,10 @@ export function ScoutSignalsSection({);const hiddenCount = emittedRuns.length - visibleRuns.length;const visibleRunIds = useMemo(- () => visibleRuns.map((run) => run.run_id),+ () =>+ visibleRuns+ .filter((run) => (run.emitted_count ?? 0) > 0)+ .map((run) => run.run_id),[visibleRuns],);@@ -85,31 +91,52 @@ export function ScoutSignalsSection({}, [emissionReports]);return (- <Flex direction="column" gap="3">- <Text className="font-semibold text-[13px] text-gray-12">Signals</Text>+ <div className="flex flex-col gap-3">+ {loadingMore || incomplete ? (+ <output className="text-[12.5px] text-gray-11">+ {loadingMore+ ? "Loading more runs. More output can appear."+ : "The run history is incomplete. More output can exist."}+ </output>+ ) : null}{loading ? (- <Box className="h-24 w-full animate-pulse rounded-(--radius-2) bg-(--gray-3)" />+ <div className="h-24 w-full animate-pulse rounded-(--radius-2) bg-(--gray-3)" />) : error ? (- <Text className="text-(--red-11) text-[12.5px]">- Couldn't load this scout's runs, so signals for the{" "}- {windowLabel} are unavailable.- </Text>+ <p className="text-(--red-11) text-[12.5px]">+ Couldn't load this agent's runs, so output for the{" "}+ {SCOUT_RUNS_WINDOW_LABEL} are unavailable.+ </p>) : emittedRuns.length === 0 ? (- <Text className="text-[12.5px] text-gray-11">- No signals emitted in the {windowLabel}.- </Text>+ <p className="text-[12.5px] text-gray-11">+ {loadingMore+ ? "Loading output."+ : incomplete+ ? "No output loaded from the available runs."+ : `No output in the ${SCOUT_RUNS_WINDOW_LABEL}. Use Run now to check the agent.`}+ </p>) : (- <Flex direction="column" gap="2">+ <div className="flex flex-col gap-2">{visibleRuns.map((run) => (- <RunEmissions+ <divkey={run.run_id}- run={run}- emissions={emissionsByRunId.get(run.run_id)}- reportBySourceId={reportBySourceId}- loading={emissionsLoading}- error={emissionsError}- highlightFindingId={highlightFindingId}- />+ className="flex flex-col gap-2 rounded-(--radius-md) border border-border p-3"+ >+ <RelativeTimestamp+ timestamp={run.completed_at ?? run.started_at}+ className="text-[12px] text-gray-10"+ />+ <ScoutRunReportLinks run={run} />+ {(run.emitted_count ?? 0) > 0 ? (+ <RunEmissions+ run={run}+ emissions={emissionsByRunId.get(run.run_id)}+ reportBySourceId={reportBySourceId}+ loading={emissionsLoading}+ error={emissionsError}+ highlightFindingId={highlightFindingId}+ />+ ) : null}+ </div>))}{hiddenCount > 0 ? (<button@@ -125,12 +152,13 @@ export function ScoutSignalsSection({}}className="w-fit rounded-full px-2.5 py-0.5 text-[11.5px] text-gray-10 transition-colors hover:bg-gray-3 hover:text-gray-12">- Show {hiddenCount} more emitted run{hiddenCount === 1 ? "" : "s"}+ Show {hiddenCount} more run{hiddenCount === 1 ? "" : "s"} with+ output</button>) : null}- </Flex>+ </div>)}- </Flex>+ </div>);}@@ -153,7 +181,7 @@ function RunEmissions({if (loading) {return (- <Box className="h-24 w-full animate-pulse rounded-(--radius-2) bg-(--gray-3)" />+ <div className="h-24 w-full animate-pulse rounded-(--radius-2) bg-(--gray-3)" />);}@@ -161,32 +189,27 @@ function RunEmissions({// emissions response must say so rather than render nothing.if (error || !emissions || emissions.length === 0) {return (- <Flex- align="center"- gap="2"- className="rounded-(--radius-2) border border-border bg-(--color-panel-solid) px-4 py-3"- >- <Text className="flex-1 text-[12.5px] text-gray-10">+ <div className="flex items-center gap-2 rounded-(--radius-2) border border-border bg-(--color-panel-solid) px-4 py-3">+ <p className="flex-1 text-[12.5px] text-gray-10">{error? "Couldn't load this run's signals.": "No signal details available for this run."}- </Text>+ </p>{taskRunUrl ? (<ScoutTaskRunLink run={run} taskRunUrl={taskRunUrl} />) : null}- </Flex>+ </div>);}return (- <Flex direction="column" gap="2">+ <div className="flex flex-col gap-2">{emissions.map((emission) => (<ScoutEmissionCardkey={emission.id}emission={emission}skillName={run.skill_name}linkedReport={reportBySourceId.get(emission.source_id)}- defaultExpanded={emission.id === highlightFindingId}highlighted={emission.id === highlightFindingId}actions={<>@@ -207,6 +230,6 @@ function RunEmissions({}/>))}- </Flex>+ </div>);}diff --git a/products/desktop/packages/ui/src/features/scouts/components/ScoutRowCard.tsx b/products/desktop/packages/ui/src/features/scouts/components/ScoutRowCard.tsxdeleted file mode 100644index bced92b66c78..000000000000--- a/products/desktop/packages/ui/src/features/scouts/components/ScoutRowCard.tsx+++ /dev/null@@ -1,199 +0,0 @@-import {- ArrowSquareOutIcon,- GearSixIcon,- SparkleIcon,-} from "@phosphor-icons/react";-import type { ScoutConfig } from "@posthog/api-client/posthog-client";-import {- formatScoutScheduleShort,- prettifyScoutSkillName,- type ScoutRollup,- scoutSkillSlug,-} from "@posthog/core/scouts/scoutPresentation";-import { buildScoutCheckinPrompt } from "@posthog/core/scouts/scoutPrompts";-import type { ScoutSurface } from "@posthog/shared";-import { ANALYTICS_EVENTS } from "@posthog/shared";-import { track } from "@posthog/ui/shell/analytics";-import { skillUrl } from "@posthog/ui/utils/posthogLinks";-import { Box, Flex, Text, Tooltip } from "@radix-ui/themes";-import { Link } from "@tanstack/react-router";-import { useMemo, useState } from "react";-import { useScoutChatTask } from "../hooks/useScoutChatTask";-import type { ScoutConfigUpdate } from "../hooks/useScoutConfigMutations";-import { DryRunBadge, ScoutOriginBadge } from "./ScoutBadges";-import { ScoutConfigForm, ScoutEnabledSwitch } from "./ScoutConfigControls";-import { ScoutLifecycleBadge } from "./ScoutLifecycleBadges";-import { ScoutRunBoxes } from "./ScoutRunBoxes";--/**- * The one scout card: name, badges, cadence, emitted count, run boxes,- * enable switch, and a gear that expands the settings form. Used as the fleet- * list row; the scout detail screen builds its own header from the same parts.- */-export function ScoutRowCard({- config,- rollup,- onUpdate,- linkToDetail = true,-}: {- config: ScoutConfig;- rollup: ScoutRollup | undefined;- onUpdate: (configId: string, updates: ScoutConfigUpdate) => void;- linkToDetail?: boolean;-}) {- const [settingsOpen, setSettingsOpen] = useState(false);- const cloudSkillUrl = skillUrl(config.skill_name);- const surface: ScoutSurface = linkToDetail ? "fleet_list" : "scout_detail";-- const description = config.description?.trim();- // `relative z-[1]` lifts the name above the Link's full-card `after:inset-0`- // overlay so the tooltip's pointer-enter fires; clicks still bubble to the Link.- const titleText = (- <Text className="relative z-[1] truncate font-medium text-[13px] text-gray-12">- {prettifyScoutSkillName(config.skill_name)}- </Text>- );- const title = description ? (- <Tooltip content={description}>{titleText}</Tooltip>- ) : (- titleText- );-- return (- <Flex- direction="column"- className={`group relative rounded-(--radius-3) border border-border bg-(--color-panel-solid) px-4 py-3 transition duration-150 hover:border-(--gray-6) hover:bg-(--gray-2) ${- config.enabled ? "" : "opacity-65"- }`}- >- <Flex align="center" gap="4">- <Flex align="center" gap="2" className="min-w-0 flex-1">- {linkToDetail ? (- <Link- to="/agents/scouts/$skillName"- params={{ skillName: scoutSkillSlug(config.skill_name) }}- className={`flex min-w-0 items-center gap-2 no-underline ${- settingsOpen ? "" : "after:absolute after:inset-0"- }`}- >- {title}- </Link>- ) : (- <Flex align="center" gap="2" className="min-w-0">- {title}- </Flex>- )}- {cloudSkillUrl ? (- <Tooltip content="View skill in PostHog">- <a- href={cloudSkillUrl}- target="_blank"- rel="noreferrer"- aria-label={`${config.skill_name} skill in PostHog`}- onClick={() =>- track(ANALYTICS_EVENTS.SCOUT_ACTION, {- action_type: "open_skill_in_posthog",- surface,- skill_name: config.skill_name,- })- }- className="relative text-gray-9 transition-colors hover:text-accent-11"- >- <ArrowSquareOutIcon size={12} />- </a>- </Tooltip>- ) : null}- <ScoutOriginBadge config={config} />- <DryRunBadge config={config} />- <ScoutLifecycleBadge config={config} />- <Text className="max-w-[14rem] truncate text-[11px] text-gray-10">- {formatScoutScheduleShort(config)}- </Text>- {rollup && rollup.emittedCount > 0 ? (- <Text className="whitespace-nowrap text-[11px] text-gray-10">- · {rollup.emittedCount} signal- {rollup.emittedCount === 1 ? "" : "s"} emitted- </Text>- ) : null}- </Flex>- <Box className="relative shrink-0">- <ScoutRunBoxes runs={rollup?.runs ?? []} />- </Box>- <Flex align="center" gap="3" className="relative shrink-0">- <ScoutEnabledSwitch config={config} onUpdate={onUpdate} />- <ScoutChatButton skillName={config.skill_name} surface={surface} />- <Tooltip content="Scout settings">- <button- type="button"- onClick={() => {- const next = !settingsOpen;- setSettingsOpen(next);- track(ANALYTICS_EVENTS.SCOUT_ACTION, {- action_type: next ? "open_settings" : "close_settings",- surface,- skill_name: config.skill_name,- });- }}- aria-expanded={settingsOpen}- aria-label={`${config.skill_name} settings`}- className={`flex h-6 w-6 items-center justify-center rounded transition-colors ${- settingsOpen- ? "bg-(--gray-4) text-gray-12"- : "text-gray-10 hover:bg-(--gray-3) hover:text-gray-12"- }`}- >- <GearSixIcon size={14} />- </button>- </Tooltip>- </Flex>- </Flex>- {settingsOpen ? (- <Box className="mt-3 border-(--gray-4) border-t pt-3">- <ScoutConfigForm config={config} onUpdate={onUpdate} />- </Box>- ) : null}- </Flex>- );-}--/**- * Icon-only chat CTA on the row: fires a one-click auto-mode cloud task asking- * the exploring-signals-scouts skill about this specific scout.- */-export function ScoutChatButton({- skillName,- surface,-}: {- skillName: string;- surface: ScoutSurface;-}) {- const prompt = useMemo(- () => buildScoutCheckinPrompt(skillName, prettifyScoutSkillName(skillName)),- [skillName],- );- const { runTask, isRunning } = useScoutChatTask({- prompt,- taskLabel: "scout check-in",- loggerScope: "scout-checkin",- chatType: "scout_checkin",- surface,- skillName,- });- return (- <Tooltip content="Chat with PostHog about this scout">- <button- type="button"- onClick={() => void runTask()}- disabled={isRunning}- aria-label={`Chat with PostHog about the ${skillName} scout`}- className={`flex h-6 w-6 items-center justify-center rounded transition-colors disabled:cursor-default ${- isRunning- ? "animate-pulse text-(--iris-9)"- : "text-gray-10 hover:bg-(--gray-3) hover:text-gray-12"- }`}- >- <SparkleIcon size={14} />- </button>- </Tooltip>- );-}diff --git a/products/desktop/packages/ui/src/features/scouts/components/ScoutRunBoxes.tsx b/products/desktop/packages/ui/src/features/scouts/components/ScoutRunBoxes.tsxindex 88028e17c15e..e7088b932b09 100644--- a/products/desktop/packages/ui/src/features/scouts/components/ScoutRunBoxes.tsx+++ b/products/desktop/packages/ui/src/features/scouts/components/ScoutRunBoxes.tsx@@ -6,9 +6,14 @@ import {type ScoutRunOutcome,scoutRunOutcomeLabel,} from "@posthog/core/scouts/scoutPresentation";+import {+ Tooltip,+ TooltipContent,+ TooltipProvider,+ TooltipTrigger,+} from "@posthog/quill";import { formatRelativeTimeLong } from "@posthog/shared";import { getPostHogUrl } from "@posthog/ui/utils/urls";-import { Flex, Text, Tooltip } from "@radix-ui/themes";// Quiet is the common, healthy baseline so it recedes to gray; saturated// color only means something happened – iris payoff, red/amber trouble.@@ -27,7 +32,7 @@ const MAX_BOXES = 24;const BOX_CLASS ="block h-3 w-2 rounded-[2px] transition-transform duration-100 hover:scale-y-125 hover:ring-(--gray-8) hover:ring-1";-function runTooltip(run: ScoutRun, now: Date): string {+function runTitle(run: ScoutRun, now: Date): string {const parts = [scoutRunOutcomeLabel(run, now)];const duration = formatRunDuration(runDurationSeconds(run, now));if (duration) parts.push(duration);@@ -39,50 +44,65 @@ function runTooltip(run: ScoutRun, now: Date): string {/*** One small box per run in the visible window, oldest on the left. Each box- * opens the backing task run in PostHog cloud; runs without a task link are- * tooltip-only.+ * opens the backing task run in PostHog cloud; runs without a task link carry+ * their label only.*/-export function ScoutRunBoxes({ runs }: { runs: ScoutRun[] }) {+export function ScoutRunBoxes({+ runs,+ max = MAX_BOXES,+}: {+ runs: ScoutRun[];+ max?: number;+}) {if (runs.length === 0) return null;- const visible = runs.slice(-MAX_BOXES);+ const visible = runs.slice(-max);const hidden = runs.length - visible.length;const now = new Date();return (- <Flex align="center" gap="2" className="shrink-0">- {hidden > 0 ? (- <Text className="text-[10px] text-gray-9">+{hidden}</Text>- ) : null}- <Flex align="center" gap="1">- {visible.map((run) => {- const outcome = deriveRunOutcome(run, now);- const boxClass = `${BOX_CLASS} ${OUTCOME_BOX_CLASS[outcome]}`;- const taskRunUrl = run.task_url ? getPostHogUrl(run.task_url) : null;- if (taskRunUrl) {- const tooltip = `${runTooltip(run, now)} · open task run in PostHog`;+ <TooltipProvider>+ <span className="flex shrink-0 items-center gap-2">+ {hidden > 0 ? (+ <span className="text-[10px] text-gray-9">+{hidden}</span>+ ) : null}+ <span className="flex items-center gap-1">+ {visible.map((run) => {+ const outcome = deriveRunOutcome(run, now);+ const boxClass = `${BOX_CLASS} ${OUTCOME_BOX_CLASS[outcome]}`;+ const taskRunUrl = run.task_url+ ? getPostHogUrl(run.task_url)+ : null;+ const label = runTitle(run, now);+ if (taskRunUrl) {+ return (+ <Tooltip key={run.run_id}>+ <TooltipTrigger+ render={+ <a+ href={taskRunUrl}+ target="_blank"+ rel="noreferrer"+ className={boxClass}+ title={`${label} · open task run in PostHog`}+ >+ <span className="sr-only">Run {label}</span>+ </a>+ }+ />+ <TooltipContent>+ {label} · open task run in PostHog+ </TooltipContent>+ </Tooltip>+ );+ }return (- <Tooltip key={run.run_id} content={tooltip}>- <a- href={taskRunUrl}- target="_blank"- rel="noreferrer"- className={boxClass}- >- <span className="sr-only">Run {tooltip}</span>- </a>- </Tooltip>- );- }- const tooltip = runTooltip(run, now);- return (- <Tooltip key={run.run_id} content={tooltip}>- <span className={boxClass}>- <span className="sr-only">Run {tooltip}</span>+ <span key={run.run_id} className={boxClass} title={label}>+ <span className="sr-only">Run {label}</span></span>- </Tooltip>- );- })}- </Flex>- </Flex>+ );+ })}+ </span>+ </span>+ </TooltipProvider>);}diff --git a/products/desktop/packages/ui/src/features/scouts/components/ScoutRunListItem.tsx b/products/desktop/packages/ui/src/features/scouts/components/ScoutRunListItem.tsxnew file mode 100644index 000000000000..ea673a7903af--- /dev/null+++ b/products/desktop/packages/ui/src/features/scouts/components/ScoutRunListItem.tsx@@ -0,0 +1,153 @@+import { CaretRightIcon } from "@phosphor-icons/react";+import type { ScoutRun } from "@posthog/api-client/posthog-client";+import {+ deriveRunOutcome,+ formatRunDuration,+ normalizeRunStatus,+ runDurationSeconds,+ type ScoutRunOutcome,+ scoutRunOutcomeLabel,+ scoutRunOutputCount,+ scoutSummarySentence,+} from "@posthog/core/scouts/scoutPresentation";+import { Badge } from "@posthog/quill";+import { ANALYTICS_EVENTS } from "@posthog/shared";+import { MarkdownRenderer } from "@posthog/ui/features/editor/components/MarkdownRenderer";+import { RelativeTimestamp } from "@posthog/ui/primitives/RelativeTimestamp";+import { track } from "@posthog/ui/shell/analytics";+import { getPostHogUrl } from "@posthog/ui/utils/urls";+import { useState } from "react";+import { ScoutRunReportLinks } from "./ScoutRunReportLinks";+import { ScoutTaskRunLink } from "./ScoutTaskRunLink";++const OUTCOME_DOT: Record<ScoutRunOutcome, string> = {+ emitted: "bg-(--iris-9)",+ quiet: "border-[1.5px] border-(--gray-7)",+ error: "bg-(--red-9)",+ timed_out: "bg-(--amber-9)",+ running: "bg-(--blue-9) animate-pulse",+ stuck: "bg-(--red-9) animate-pulse",+ queued: "border border-dashed border-(--gray-7)",+ unknown: "bg-(--gray-6)",+};++/**+ * One row per run. Collapsed, it is a single line: when, how long, the first+ * sentence of the close-out, and the outcome. Expanded, the full close-out.+ */+export function ScoutRunListItem({+ run,+ defaultExpanded = false,+}: {+ run: ScoutRun;+ defaultExpanded?: boolean;+}) {+ const [expanded, setExpanded] = useState(defaultExpanded);+ const now = new Date();+ const taskRunUrl = run.task_url ? getPostHogUrl(run.task_url) : null;+ const status = normalizeRunStatus(run.status);+ const outcome = deriveRunOutcome(run, now);+ const duration = formatRunDuration(runDurationSeconds(run, now));+ const emitted = scoutRunOutputCount(run);+ const title = scoutSummarySentence(run.summary);++ return (+ <div className="border-(--gray-4) border-b px-4 py-2.5 last:border-b-0">+ <button+ type="button"+ onClick={() => {+ const next = !expanded;+ setExpanded(next);+ track(ANALYTICS_EVENTS.SCOUT_ACTION, {+ action_type: next ? "expand_run" : "collapse_run",+ surface: "scout_detail",+ skill_name: run.skill_name,+ run_id: run.run_id,+ run_status: status,+ emitted_count: emitted,+ });+ }}+ aria-expanded={expanded}+ className="flex w-full min-w-0 select-none items-center gap-2 rounded-sm text-left outline-none focus-visible:ring-(--gray-8) focus-visible:ring-1"+ >+ <CaretRightIcon+ size={11}+ className={`shrink-0 text-gray-9 transition-transform duration-150 motion-reduce:transition-none ${expanded ? "rotate-90" : ""}`}+ />+ <span+ className={`inline-block h-2 w-2 shrink-0 rounded-full ${OUTCOME_DOT[outcome]}`}+ aria-hidden+ />+ <RelativeTimestamp+ timestamp={run.started_at}+ className="shrink-0 text-[12px] text-gray-12"+ />+ {duration ? (+ <span className="shrink-0 text-[11.5px] text-gray-10">+ · {duration}+ </span>+ ) : null}+ {outcome === "error" || outcome === "timed_out" ? (+ <span+ className={`shrink-0 text-[11.5px] ${outcome === "timed_out" ? "text-(--amber-11)" : "text-(--red-11)"}`}+ >+ · {outcome === "timed_out" ? "timed out" : "failed"}+ </span>+ ) : null}+ {outcome === "stuck" ? (+ <span className="shrink-0 text-(--red-11) text-[11.5px]">+ · running past the deadline+ </span>+ ) : null}+ {["running", "queued", "unknown"].includes(outcome) ? (+ <span className="shrink-0 text-[11.5px] text-gray-11">+ {scoutRunOutcomeLabel(run, now)}+ </span>+ ) : null}+ {!expanded && title ? (+ <span className="min-w-0 flex-1 truncate pl-1 text-[12px] text-gray-11">+ {title}+ </span>+ ) : (+ <span className="flex-1" />+ )}+ {emitted > 0 ? (+ <Badge variant="info" className="shrink-0">+ {emitted} output{emitted === 1 ? "" : "s"}+ </Badge>+ ) : status === "completed" ? (+ <span className="shrink-0 text-[11.5px] text-gray-9">quiet</span>+ ) : null}+ </button>+ {expanded ? (+ run.summary ? (+ <div className="mt-2 text-pretty break-words pl-[21px] text-[12.5px] text-gray-11 leading-snug [&_code]:text-[11px] [&_p:last-child]:mb-0 [&_p]:mb-1 [&_pre]:text-[11px]">+ <MarkdownRenderer+ content={run.summary}+ componentsOverride={{ img: ({ alt }) => <span>{alt}</span> }}+ />+ </div>+ ) : status === "failed" ? (+ <p className="mt-2 pl-[21px] text-[12.5px] text-gray-10 italic leading-snug">+ No summary. The run ended before it wrote a close-out. The task run+ in PostHog is the only diagnostic.+ </p>+ ) : null+ ) : null}+ {expanded ? (+ <div className="mt-2 pl-[21px]">+ <ScoutRunReportLinks run={run} />+ </div>+ ) : null}+ {expanded && taskRunUrl ? (+ <div className="mt-2 flex justify-end border-(--gray-4) border-t pt-2 text-[11px] text-gray-10">+ <ScoutTaskRunLink+ run={run}+ taskRunUrl={taskRunUrl}+ runStatus={status}+ />+ </div>+ ) : null}+ </div>+ );+}diff --git a/products/desktop/packages/ui/src/features/scouts/components/ScoutRunReportLinks.tsx b/products/desktop/packages/ui/src/features/scouts/components/ScoutRunReportLinks.tsxnew file mode 100644index 000000000000..62b12c9fc76c--- /dev/null+++ b/products/desktop/packages/ui/src/features/scouts/components/ScoutRunReportLinks.tsx@@ -0,0 +1,103 @@+import type { ScoutRun } from "@posthog/api-client/posthog-client";+import { deriveHeadline } from "@posthog/core/inbox/reportPresentation";+import { scoutRunReports } from "@posthog/core/scouts/scoutPresentation";+import { Badge, Button, Skeleton } from "@posthog/quill";+import { useInboxReportById } from "@posthog/ui/features/inbox/hooks/useInboxReports";+import { useOpenInboxReport } from "@posthog/ui/features/inbox/hooks/useOpenInboxReport";+import { useInView } from "framer-motion";+import { useRef, useState } from "react";++export function ScoutRunReportLinks({ run }: { run: ScoutRun }) {+ const reports = scoutRunReports(run);+ if (reports.length === 0) return null;++ return (+ <div className="flex flex-col gap-2">+ {reports.map((report) => (+ <ScoutReportLink+ key={report.id}+ reportId={report.id}+ action={report.action}+ />+ ))}+ </div>+ );+}++function ScoutReportLink({+ reportId,+ action,+}: {+ reportId: string;+ action: "created" | "updated";+}) {+ const ref = useRef<HTMLDivElement>(null);+ const visible = useInView(ref, { once: true, margin: "200px" });+ const {+ data: report,+ isLoading,+ isError,+ refetch,+ } = useInboxReportById(reportId, { enabled: visible });+ const openReport = useOpenInboxReport();+ const [opening, setOpening] = useState(false);+ const headline = deriveHeadline(report?.summary);++ return (+ <div+ ref={ref}+ className="rounded-(--radius-md) border border-border bg-(--color-panel-solid)"+ >+ <button+ type="button"+ data-attr="scout-report-link"+ disabled={opening}+ onClick={async () => {+ setOpening(true);+ try {+ await openReport(reportId);+ } finally {+ setOpening(false);+ }+ }}+ className="flex w-full items-start gap-3 rounded-(--radius-md) px-3 py-3 text-left hover:bg-(--gray-3) focus-visible:outline focus-visible:outline-(--gray-8) focus-visible:outline-2 disabled:opacity-60"+ >+ <span className="flex min-w-0 flex-1 flex-col gap-1">+ {isLoading || (!visible && !report) ? (+ <Skeleton className="h-4 w-64 max-w-full" />+ ) : (+ <span className="break-words font-medium text-[13px] text-gray-12">+ {report?.title ||+ (isError+ ? "Could not load report"+ : report+ ? "Untitled report"+ : "Report unavailable")}+ </span>+ )}+ {headline ? (+ <span className="line-clamp-2 break-words text-[12px] text-gray-11">+ {headline}+ </span>+ ) : null}+ {!report ? (+ <span className="text-[11px] text-gray-10">+ Report {reportId.slice(0, 8)}+ </span>+ ) : null}+ </span>+ <Badge variant="default">+ {action === "created" ? "Created" : "Updated"}+ </Badge>+ {report?.priority ? (+ <Badge variant="default">{report.priority}</Badge>+ ) : null}+ </button>+ {isError ? (+ <Button variant="link-muted" size="sm" onClick={() => void refetch()}>+ Retry+ </Button>+ ) : null}+ </div>+ );+}diff --git a/products/desktop/packages/ui/src/features/scouts/components/ScoutRunsList.tsx b/products/desktop/packages/ui/src/features/scouts/components/ScoutRunsList.tsxnew file mode 100644index 000000000000..e2baf2f87291--- /dev/null+++ b/products/desktop/packages/ui/src/features/scouts/components/ScoutRunsList.tsx@@ -0,0 +1,47 @@+import type { ScoutRun } from "@posthog/api-client/posthog-client";+import { Skeleton } from "@posthog/quill";+import { ScoutRunListItem } from "./ScoutRunListItem";++export function ScoutRunsList({+ runs,+ loading,+ error,+ emptyMessage,+}: {+ runs: ScoutRun[];+ loading: boolean;+ error: boolean;+ emptyMessage: string;+}) {+ if (loading) {+ return (+ <div className="flex flex-col gap-2">+ {[0, 1, 2].map((index) => (+ <Skeleton key={index} className="h-14 w-full" />+ ))}+ </div>+ );+ }+ if (error && runs.length === 0) {+ return (+ <p className="text-(--red-11) text-[12.5px]">+ Couldn't load runs for this agent. The agent API may be unavailable+ or this token may lack the <code>signal_scout</code> scope.+ </p>+ );+ }+ if (runs.length === 0) {+ return <p className="text-[12.5px] text-gray-11">{emptyMessage}</p>;+ }+ return (+ <div className="overflow-hidden rounded-(--radius-md) border border-border bg-(--color-panel-solid)">+ {runs.map((run, index) => (+ <ScoutRunListItem+ key={run.run_id}+ run={run}+ defaultExpanded={index === 0}+ />+ ))}+ </div>+ );+}diff --git a/products/desktop/packages/ui/src/features/scouts/components/ScoutSuggestions.stories.tsx b/products/desktop/packages/ui/src/features/scouts/components/ScoutSuggestions.stories.tsxnew file mode 100644index 000000000000..f7d2c2dfac85--- /dev/null+++ b/products/desktop/packages/ui/src/features/scouts/components/ScoutSuggestions.stories.tsx@@ -0,0 +1,115 @@+import type {+ ScoutConfig,+ ScoutSuggestionItem,+} from "@posthog/api-client/posthog-client";+import { AgentsTabLayout } from "@posthog/ui/features/agents/components/AgentsTabLayout";+import type { Meta, StoryObj } from "@storybook/react-vite";+import { ScoutSuggestions } from "./ScoutSuggestions";++// Invented suggestions for an invented project.+const ITEMS: ScoutSuggestionItem[] = [+ {+ id: "s1",+ kind: "canonical",+ skill_name: "signals-scout-web-vitals",+ title: "Watch web vitals on the pages people land on",+ why_here:+ "This project records web vitals, and the landing pages moved twice this month. Nothing in the fleet reads them yet.",+ description: "",+ draft_body: "",+ proposed_config: {+ run_cron_schedule: "0 9 * * *",+ run_interval_minutes: null,+ emit: true,+ },+ gap: true,+ confidence: "high",+ },+ {+ id: "s2",+ kind: "canonical",+ skill_name: "signals-scout-revenue-analytics",+ title: "Watch revenue for a drop against its own baseline",+ why_here:+ "Revenue events arrive every day, and this agent already exists on the project with its switch off.",+ description: "",+ draft_body: "",+ proposed_config: {+ run_cron_schedule: null,+ run_interval_minutes: 720,+ emit: true,+ },+ gap: false,+ confidence: "medium",+ },+ {+ id: "s3",+ kind: "custom",+ skill_name: "signals-scout-checkout-abandonment",+ title: "Watch checkout abandonment after a deploy",+ why_here:+ "Checkout events and deploy markers both land here, and no agent reads them together.",+ description:+ "Compare checkout completion in the hour after each deploy against the day before.",+ draft_body: "# Checkout abandonment after a deploy…",+ proposed_config: {+ run_cron_schedule: null,+ run_interval_minutes: 180,+ emit: false,+ },+ gap: true,+ confidence: "medium",+ },+];++const CONFIGS: ScoutConfig[] = [+ {+ id: "config-web-vitals",+ skill_name: "signals-scout-web-vitals",+ enabled: false,+ emit: true,+ scout_origin: "canonical",+ run_interval_minutes: 1440,+ created_at: "2026-06-01T00:00:00Z",+ },+ {+ id: "config-revenue",+ skill_name: "signals-scout-revenue-analytics",+ enabled: false,+ emit: true,+ scout_origin: "canonical",+ run_interval_minutes: 720,+ created_at: "2026-06-01T00:00:00Z",+ },+];++const noop = () => undefined;++const meta = {+ title: "Scouts/ScoutSuggestions",+ component: ScoutSuggestions,+ parameters: { layout: "fullscreen" },+ args: {+ items: ITEMS,+ configs: CONFIGS,+ onTurnOn: noop,+ onDraft: noop,+ onDismiss: noop,+ },+ decorators: [+ (Story) => (+ <div className="h-[30rem]">+ <AgentsTabLayout tab="agents" fill count={2}>+ <Story />+ </AgentsTabLayout>+ </div>+ ),+ ],+} satisfies Meta<typeof ScoutSuggestions>;++export default meta;++type Story = StoryObj<typeof meta>;++/** What PostHog would add to this project, and why it thinks so. */+export const Suggested: Story = {};diff --git a/products/desktop/packages/ui/src/features/scouts/components/ScoutSuggestions.tsx b/products/desktop/packages/ui/src/features/scouts/components/ScoutSuggestions.tsxnew file mode 100644index 000000000000..22bb3384e612--- /dev/null+++ b/products/desktop/packages/ui/src/features/scouts/components/ScoutSuggestions.tsx@@ -0,0 +1,136 @@+import { SparkleIcon } from "@phosphor-icons/react";+import type {+ ScoutConfig,+ ScoutSuggestionItem,+} from "@posthog/api-client/posthog-client";+import { scoutSkillSlug } from "@posthog/core/scouts/scoutPresentation";+import {+ suggestionActionLabel,+ suggestionMetaLine,+} from "@posthog/core/scouts/scoutSuggestions";+import { Badge, Button } from "@posthog/quill";+import { ANALYTICS_EVENTS } from "@posthog/shared";+import { track } from "@posthog/ui/shell/analytics";+import type { ScoutConfigUpdate } from "../hooks/useScoutConfigMutations";++/**+ * What PostHog thinks should watch this project, with the evidence it found.+ * A canonical pick turns an agent that already exists back on; a custom draft+ * hands its brief to the authoring chat. Both leave the list once acted on.+ */+export function ScoutSuggestions({+ items,+ configs,+ onTurnOn,+ onDraft,+ onDismiss,+}: {+ items: ScoutSuggestionItem[];+ /** The fleet, for resolving which agent a canonical pick would switch on. */+ configs: ScoutConfig[];+ onTurnOn: (configId: string, updates: ScoutConfigUpdate) => void;+ onDraft: (item: ScoutSuggestionItem) => void;+ onDismiss: (item: ScoutSuggestionItem) => void;+}) {+ if (items.length === 0) return null;++ return (+ <section className="flex flex-col gap-2">+ <div className="flex items-center gap-2">+ <SparkleIcon size={13} className="text-(--iris-11)" />+ <h2 className="font-semibold text-[13px] text-gray-12">+ Suggested for this project+ </h2>+ </div>+ <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">+ {items.map((item) => (+ <SuggestionCard+ key={item.id}+ item={item}+ config={configs.find(+ (config) => config.skill_name === item.skill_name,+ )}+ onTurnOn={onTurnOn}+ onDraft={onDraft}+ onDismiss={onDismiss}+ />+ ))}+ </div>+ </section>+ );+}++function SuggestionCard({+ item,+ config,+ onTurnOn,+ onDraft,+ onDismiss,+}: {+ item: ScoutSuggestionItem;+ config: ScoutConfig | undefined;+ onTurnOn: (configId: string, updates: ScoutConfigUpdate) => void;+ onDraft: (item: ScoutSuggestionItem) => void;+ onDismiss: (item: ScoutSuggestionItem) => void;+}) {+ // A canonical pick names an agent this project already has, off. Without that+ // agent there is nothing to switch on, so the card offers the draft instead.+ const canTurnOn = item.kind === "canonical" && config !== undefined;++ const act = () => {+ track(ANALYTICS_EVENTS.SCOUT_ACTION, {+ action_type: canTurnOn ? "accept_suggestion" : "draft_suggestion",+ surface: "fleet_list",+ skill_name: item.skill_name,+ });+ if (canTurnOn && config) {+ onTurnOn(config.id, { enabled: true });+ } else {+ onDraft(item);+ }+ onDismiss(item);+ };++ return (+ <div className="flex flex-col gap-2 rounded-(--radius-md) border border-border bg-(--color-panel-solid) px-3.5 py-3">+ <div className="flex min-w-0 items-start gap-2">+ <span className="min-w-0 flex-1 font-medium text-[13px] text-gray-12 leading-snug">+ {item.title}+ </span>+ {item.gap ? <Badge variant="info">New ground</Badge> : null}+ </div>+ <p className="line-clamp-3 text-[11.5px] text-gray-10 leading-snug">+ {item.why_here}+ </p>+ <span className="text-[11px] text-gray-9">+ {suggestionMetaLine(item.proposed_config)}+ </span>+ <div className="mt-1 flex items-center gap-1.5">+ <Button+ type="button"+ variant="outline"+ size="xs"+ onClick={act}+ data-attr={`scout-suggestion-${scoutSkillSlug(item.skill_name)}`}+ >+ {canTurnOn ? suggestionActionLabel(item) : "Draft it"}+ </Button>+ <Button+ type="button"+ variant="link-muted"+ size="xs"+ onClick={() => {+ track(ANALYTICS_EVENTS.SCOUT_ACTION, {+ action_type: "dismiss_suggestion",+ surface: "fleet_list",+ skill_name: item.skill_name,+ });+ onDismiss(item);+ }}+ >+ Not now+ </Button>+ </div>+ </div>+ );+}diff --git a/products/desktop/packages/ui/src/features/scouts/components/ScoutTable.stories.tsx b/products/desktop/packages/ui/src/features/scouts/components/ScoutTable.stories.tsxnew file mode 100644index 000000000000..947e3683a082--- /dev/null+++ b/products/desktop/packages/ui/src/features/scouts/components/ScoutTable.stories.tsx@@ -0,0 +1,233 @@+import type { ScoutConfig, ScoutRun } from "@posthog/api-client/posthog-client";+import {+ buildScoutCreatorIndex,+ computeScoutRollups,+ listScoutsNeedingAttention,+ sortConfigsForDisplay,+} from "@posthog/core/scouts/scoutPresentation";+import { AgentsTabLayout } from "@posthog/ui/features/agents/components/AgentsTabLayout";+import {+ ANONYMOUS_AUTH_STATE,+ useAuthStore,+} from "@posthog/ui/features/auth/store";+import type { Meta, StoryObj } from "@storybook/react-vite";+import type { ReactNode } from "react";+import { ScoutAttentionStrip } from "./ScoutAttentionStrip";+import { ScoutTable } from "./ScoutTable";++// Invented agents on invented people. Nothing here comes from a real project.+const ROBIN = {+ id: 1,+ first_name: "Robin",+ last_name: "Hedge",+ email: "[email protected]",+};+const ALEX = {+ id: 2,+ first_name: "Alex",+ last_name: "Doe",+ email: "[email protected]",+};++const NOW = new Date("2026-07-09T09:00:00Z");++function config(overrides: Partial<ScoutConfig> = {}): ScoutConfig {+ return {+ id: `config-${overrides.skill_name ?? "x"}`,+ skill_name: "signals-scout-error-tracking",+ enabled: true,+ emit: true,+ scout_origin: "canonical",+ run_interval_minutes: 180,+ auto_pause_exempt: false,+ created_at: "2026-06-01T00:00:00Z",+ ...overrides,+ };+}++const CONFIGS: ScoutConfig[] = [+ config({+ skill_name: "signals-scout-checkout-funnel",+ scout_origin: "custom",+ run_interval_minutes: 480,+ description: "Tracks conversion through the checkout funnel.",+ }),+ config({+ skill_name: "signals-scout-ad-spend",+ scout_origin: "custom",+ emit: false,+ description: "Watches ad spend events for runaway campaigns.",+ }),+ config({+ skill_name: "signals-scout-error-tracking",+ description: "Sweeps error tracking for new and spiking issues.",+ }),+ config({+ skill_name: "signals-scout-web-analytics",+ run_cron_schedule: "0 8 * * 4",+ description: "Looks for traffic anomalies across web analytics.",+ }),+ config({+ skill_name: "signals-scout-session-replay",+ run_interval_minutes: 1440,+ description: "Reads replays for friction on the newest release.",+ }),+ config({+ skill_name: "signals-scout-weekly-digest",+ scout_origin: "custom",+ enabled: false,+ status: "paused_by_system",+ pause_reason: "repeated_failures",+ consecutive_failure_count: 3,+ description: "Sums up the week for the product team.",+ }),+];++function run(overrides: Partial<ScoutRun> & { skill_name: string }): ScoutRun {+ return {+ run_id: `run-${Math.random().toString(36).slice(2)}`,+ skill_version: 1,+ status: "completed",+ started_at: "2026-07-09T06:30:00Z",+ completed_at: "2026-07-09T06:34:00Z",+ task_id: null,+ task_run_id: null,+ task_url: "/project/1/tasks/example-task?runId=example-run",+ summary: "Nothing worth sending this time.",+ emitted_count: 0,+ emitted_finding_ids: [],+ ...overrides,+ };+}++const RUNS: ScoutRun[] = [+ ...Array.from({ length: 12 }, (_, index) =>+ run({+ skill_name: "signals-scout-checkout-funnel",+ emitted_count: index % 4 === 0 ? 1 : 0,+ started_at: new Date(NOW.getTime() - index * 3_600_000).toISOString(),+ }),+ ),+ ...Array.from({ length: 9 }, (_, index) =>+ run({+ skill_name: "signals-scout-error-tracking",+ status: index === 0 ? "in_progress" : "completed",+ completed_at: index === 0 ? null : "2026-07-09T05:20:00Z",+ emitted_count: index % 3 === 0 ? 2 : 0,+ started_at: new Date(NOW.getTime() - index * 7_200_000).toISOString(),+ }),+ ),+ ...Array.from({ length: 6 }, (_, index) =>+ run({+ skill_name: "signals-scout-weekly-digest",+ status: "failed",+ summary: "The query timed out.",+ started_at: new Date(NOW.getTime() - index * 86_400_000).toISOString(),+ }),+ ),+ ...Array.from({ length: 4 }, (_, index) =>+ run({+ skill_name: "signals-scout-web-analytics",+ started_at: new Date(NOW.getTime() - index * 86_400_000).toISOString(),+ }),+ ),+];++const ROLLUPS = computeScoutRollups(RUNS);+const CREATORS = buildScoutCreatorIndex([+ {+ name: "signals-scout-checkout-funnel",+ created_by: ROBIN,+ is_latest: true,+ },+ { name: "signals-scout-ad-spend", created_by: ALEX, is_latest: true },+ { name: "signals-scout-weekly-digest", created_by: ROBIN, is_latest: true },+]);+const ORDERED = sortConfigsForDisplay(CONFIGS);+const ATTENTION = listScoutsNeedingAttention(CONFIGS, ROLLUPS, NOW);++/**+ * A row builds a "run now" action, which needs a signed-in client to exist.+ * The story never calls it, so a region and a project are enough.+ */+function SignedIn({ children }: { children: ReactNode }) {+ useAuthStore.setState({+ authState: {+ ...ANONYMOUS_AUTH_STATE,+ status: "authenticated",+ cloudRegion: "us",+ currentProjectId: 1,+ },+ });+ return <>{children}</>;+}++const meta = {+ title: "Scouts/ScoutTable",+ component: ScoutTable,+ parameters: { layout: "fullscreen" },+ decorators: [+ (Story) => (+ <SignedIn>+ <Story />+ </SignedIn>+ ),+ ],+} satisfies Meta<typeof ScoutTable>;++export default meta;++type Story = StoryObj<typeof meta>;++const noop = () => undefined;++/** The Agents tab of the Agents settings page: what needs a decision, then the fleet. */+export const AgentsTab: Story = {+ render: () => (+ <div className="h-[42rem]">+ <AgentsTabLayout tab="agents" fill count={CONFIGS.length}>+ <ScoutAttentionStrip items={ATTENTION} onUpdateConfig={noop} />+ <ScoutTable+ configs={ORDERED}+ rollups={ROLLUPS}+ runsPending={false}+ creators={CREATORS}+ onUpdateConfig={noop}+ emptyMessage="No agents match these filters."+ />+ </AgentsTabLayout>+ </div>+ ),+};++/** The table on its own, with run history still on its way. */+export const RunsLoading: Story = {+ render: () => (+ <div className="h-[32rem] p-6">+ <ScoutTable+ configs={ORDERED}+ rollups={new Map()}+ runsPending+ creators={CREATORS}+ onUpdateConfig={noop}+ emptyMessage="No agents match these filters."+ />+ </div>+ ),+};++/** Every agent filtered out. */+export const NoMatches: Story = {+ render: () => (+ <div className="h-[20rem] p-6">+ <ScoutTable+ configs={[]}+ rollups={ROLLUPS}+ runsPending={false}+ creators={CREATORS}+ onUpdateConfig={noop}+ emptyMessage="No agents match these filters."+ />+ </div>+ ),+};diff --git a/products/desktop/packages/ui/src/features/scouts/components/ScoutTable.tsx b/products/desktop/packages/ui/src/features/scouts/components/ScoutTable.tsxnew file mode 100644index 000000000000..273b6f7dfc14--- /dev/null+++ b/products/desktop/packages/ui/src/features/scouts/components/ScoutTable.tsx@@ -0,0 +1,134 @@+import type { ScoutConfig } from "@posthog/api-client/posthog-client";+import type {+ ScoutCreatorIndex,+ ScoutRollup,+} from "@posthog/core/scouts/scoutPresentation";+import {+ Table,+ TableBody,+ TableCell,+ TableHead,+ TableHeader,+ TableRow,+} from "@posthog/quill";+import { useMinuteNow } from "@posthog/ui/hooks/useMinuteNow";+import { useVirtualizer } from "@tanstack/react-virtual";+import { useRef } from "react";+import type { ScoutConfigUpdate } from "../hooks/useScoutConfigMutations";+import { ScoutTableRow } from "./ScoutTableRow";++/** Close enough for the scrollbar; each row measures itself once it renders. */+const ESTIMATED_ROW_HEIGHT = 52;++/**+ * The fleet, one agent per row. A project can hold hundreds of agents, so only+ * the rows in view are rendered: drawing them all costs about a second of+ * frozen screen every time the page opens.+ */+export function ScoutTable({+ configs,+ rollups,+ runsPending,+ creators,+ onUpdateConfig,+ emptyMessage,+}: {+ configs: ScoutConfig[];+ rollups: Map<string, ScoutRollup>;+ /** Run history has not answered yet, so the runs column waits rather than reads empty. */+ runsPending: boolean;+ creators: ScoutCreatorIndex | null | undefined;+ onUpdateConfig: (configId: string, updates: ScoutConfigUpdate) => void;+ emptyMessage: string;+}) {+ // One `now` for every row, changing on the minute: a fresh Date each render+ // would re-do the work of every visible row on every scroll frame.+ const now = useMinuteNow();+ const viewportRef = useRef<HTMLDivElement>(null);+ const virtualizer = useVirtualizer({+ count: configs.length,+ getScrollElement: () => viewportRef.current,+ estimateSize: () => ESTIMATED_ROW_HEIGHT,+ overscan: 8,+ getItemKey: (index) => configs[index]?.id ?? index,+ });+ const virtualRows = virtualizer.getVirtualItems();+ const topSpacer = virtualRows[0]?.start ?? 0;+ const bottomSpacer =+ virtualizer.getTotalSize() -+ (virtualRows[virtualRows.length - 1]?.end ?? 0);++ return (+ <Table+ viewportRef={viewportRef}+ stickyHeader+ fullWidth+ tableClassName="table-fixed"+ className="@container h-full rounded-(--radius-md) border border-border bg-(--color-panel-solid)"+ >+ <TableHeader>+ <TableRow className="hover:bg-transparent">+ {/* Percentages per breakpoint. A `table-fixed` column with no width+ of its own takes every spare pixel, and a hidden column keeps its+ share, so each set has to add up to 100 on its own. */}+ <TableHead className="@2xl:w-[44%] @4xl:w-[32%] w-[66%]">+ Agent+ </TableHead>+ <TableHead className="@2xl:w-[16%] @4xl:w-[13%] w-[22%]">+ Schedule+ </TableHead>+ <TableHead className="@4xl:table-cell hidden @4xl:w-[27%]">+ Recent runs+ </TableHead>+ <TableHead className="@2xl:table-cell hidden @2xl:w-[28%] @4xl:w-[18%]">+ Last run+ </TableHead>+ <TableHead className="@4xl:w-[6%] w-[7%]" />+ <TableHead className="@4xl:w-[4%] w-[5%]" />+ </TableRow>+ </TableHeader>+ <TableBody>+ {configs.length === 0 ? (+ <TableRow className="hover:bg-transparent">+ <TableCell+ colSpan={6}+ className="py-10 text-center text-[12.5px] text-gray-10"+ >+ {emptyMessage}+ </TableCell>+ </TableRow>+ ) : (+ <>+ {topSpacer > 0 ? (+ <TableRow aria-hidden className="hover:bg-transparent">+ <TableCell colSpan={6} style={{ height: topSpacer }} />+ </TableRow>+ ) : null}+ {virtualRows.map((virtualRow) => {+ const config = configs[virtualRow.index];+ if (!config) return null;+ return (+ <ScoutTableRow+ key={config.id}+ measureRef={virtualizer.measureElement}+ index={virtualRow.index}+ config={config}+ rollup={rollups.get(config.skill_name)}+ runsPending={runsPending}+ creator={creators?.get(config.skill_name)}+ now={now}+ onUpdate={onUpdateConfig}+ />+ );+ })}+ {bottomSpacer > 0 ? (+ <TableRow aria-hidden className="hover:bg-transparent">+ <TableCell colSpan={6} style={{ height: bottomSpacer }} />+ </TableRow>+ ) : null}+ </>+ )}+ </TableBody>+ </Table>+ );+}diff --git a/products/desktop/packages/ui/src/features/scouts/components/ScoutTableRow.tsx b/products/desktop/packages/ui/src/features/scouts/components/ScoutTableRow.tsxnew file mode 100644index 000000000000..a5d797dd7be5--- /dev/null+++ b/products/desktop/packages/ui/src/features/scouts/components/ScoutTableRow.tsx@@ -0,0 +1,284 @@+import {+ ArrowSquareOutIcon,+ DotsThreeIcon,+ GearSixIcon,+ PlayIcon,+} from "@phosphor-icons/react";+import type {+ LlmSkillCreatedBy,+ ScoutConfig,+} from "@posthog/api-client/posthog-client";+import { getUserInitials } from "@posthog/core/auth/userInitials";+import {+ deriveRunOutcome,+ deriveScoutLifecycle,+ formatNextRun,+ formatRunDuration,+ formatScoutScheduleShort,+ hasPendingScoutRun,+ nextRunAt,+ prettifyScoutSkillName,+ runDurationSeconds,+ type ScoutRollup,+ type ScoutRunOutcome,+ scoutCreatorDisplayName,+ scoutRunOutcomeLabel,+ scoutSkillSlug,+} from "@posthog/core/scouts/scoutPresentation";+import {+ Avatar,+ AvatarFallback,+ Button,+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+ Skeleton,+ TableCell,+ TableRow,+} from "@posthog/quill";+import { ANALYTICS_EVENTS } from "@posthog/shared";+import { useAgentsPageActions } from "@posthog/ui/features/agents/agentsPageStore";+import { RelativeTimestamp } from "@posthog/ui/primitives/RelativeTimestamp";+import { Tooltip } from "@posthog/ui/primitives/Tooltip";+import { track } from "@posthog/ui/shell/analytics";+import { skillUrl } from "@posthog/ui/utils/posthogLinks";+import { memo } from "react";+import type { ScoutConfigUpdate } from "../hooks/useScoutConfigMutations";+import { useScoutRunNow } from "../hooks/useScoutRunNow";+import { AgentNameLink } from "./AgentNameLink";+import { DryRunBadge } from "./ScoutBadges";+import { ScoutEnabledSwitch } from "./ScoutConfigControls";+import { ScoutLifecycleBadge } from "./ScoutLifecycleBadges";+import { ScoutRunBoxes } from "./ScoutRunBoxes";++const ROW_BOXES = 18;+const PLACEHOLDER_BOXES = Array.from({ length: 14 }, (_, index) => index);++/** Holds the run column's ground while the run history is on its way. */+function RunBoxesPlaceholder() {+ return (+ <span className="flex animate-pulse items-center gap-1" aria-hidden>+ {PLACEHOLDER_BOXES.map((box) => (+ <span key={box} className="block h-3 w-2 rounded-[2px] bg-(--gray-3)" />+ ))}+ </span>+ );+}++const OUTCOME_TEXT: Partial<Record<ScoutRunOutcome, string>> = {+ running: "text-(--blue-11)",+ stuck: "text-(--red-11)",+ error: "text-(--red-11)",+ timed_out: "text-(--amber-11)",+ emitted: "text-(--iris-11)",+};++function statusDotClass(+ config: ScoutConfig,+ rollup: ScoutRollup | undefined,+ now: Date,+): string {+ const lifecycle = deriveScoutLifecycle(config);+ if (+ rollup?.runningRun &&+ deriveRunOutcome(rollup.runningRun, now) === "running"+ ) {+ return "bg-(--blue-9) shadow-[0_0_0_3px_var(--blue-a4)]";+ }+ if (lifecycle.isSystemPaused) return "border-[1.5px] border-(--amber-9)";+ if (!config.enabled) return "border-[1.5px] border-(--gray-7)";+ if (lifecycle.isWarned) return "bg-(--amber-9)";+ const latest = rollup?.latestRun;+ if (latest) {+ const outcome = deriveRunOutcome(latest, now);+ if (outcome === "error" || outcome === "timed_out" || outcome === "stuck")+ return "bg-(--red-9)";+ }+ return "bg-(--green-9)";+}++function ScoutTableRowInner({+ config,+ rollup,+ runsPending,+ creator,+ now,+ onUpdate,+ measureRef,+ index,+}: {+ config: ScoutConfig;+ rollup: ScoutRollup | undefined;+ /** Run history has not answered yet, so the runs column waits rather than reads empty. */+ runsPending: boolean;+ creator: LlmSkillCreatedBy | undefined;+ now: Date;+ onUpdate: (configId: string, updates: ScoutConfigUpdate) => void;+ /** Reports the rendered row height back to the virtualizer. */+ measureRef?: (node: HTMLTableRowElement | null) => void;+ index?: number;+}) {+ const { openAgent } = useAgentsPageActions();+ const { runNow, isStarting } = useScoutRunNow(config, "fleet_list");+ const slug = scoutSkillSlug(config.skill_name);+ const name = prettifyScoutSkillName(config.skill_name);+ const latest = rollup?.latestRun ?? null;+ const latestOutcome = latest ? deriveRunOutcome(latest, now) : null;+ const latestDuration = latest+ ? formatRunDuration(runDurationSeconds(latest, now))+ : "";+ const next = formatNextRun(nextRunAt(config, now), now);+ const cloudSkillUrl = skillUrl(config.skill_name);+ const dimmed =+ !config.enabled && !deriveScoutLifecycle(config).isSystemPaused;++ return (+ <TableRow+ ref={measureRef}+ data-index={index}+ className={dimmed ? "opacity-60" : undefined}+ >+ <TableCell className="py-2">+ <div className="flex min-w-0 items-center gap-2">+ <span+ className={`inline-block h-2 w-2 shrink-0 rounded-full ${statusDotClass(config, rollup, now)}`}+ aria-hidden+ />+ <AgentNameLink+ config={config}+ onOpen={() => openAgent(slug)}+ dataAttr="scout-row-open"+ />+ <span className="sr-only @xl:not-sr-only @xl:contents">+ <DryRunBadge config={config} />+ <ScoutLifecycleBadge config={config} />+ </span>+ {creator ? (+ <Tooltip content={`Created by ${scoutCreatorDisplayName(creator)}`}>+ <Avatar size="xs" className="ml-auto shrink-0">+ <AvatarFallback>{getUserInitials(creator)}</AvatarFallback>+ </Avatar>+ </Tooltip>+ ) : null}+ </div>+ </TableCell>++ <TableCell>+ <div className="flex flex-col gap-0.5 truncate">+ <span className="text-[12.5px] text-gray-12">+ {formatScoutScheduleShort(config)}+ </span>+ {rollup?.runningRun &&+ deriveRunOutcome(rollup.runningRun, now) === "running" ? (+ <span className="text-(--blue-11) text-[11px]">running now</span>+ ) : next ? (+ <span className="text-[11px] text-gray-10">next {next}</span>+ ) : null}+ </div>+ </TableCell>++ <TableCell className="@4xl:table-cell hidden overflow-hidden">+ {rollup && rollup.runs.length > 0 ? (+ <ScoutRunBoxes runs={rollup.runs} max={ROW_BOXES} />+ ) : runsPending ? (+ <RunBoxesPlaceholder />+ ) : (+ <span className="text-[11px] text-gray-11">+ No recent runs loaded+ </span>+ )}+ </TableCell>++ <TableCell className="@2xl:table-cell hidden">+ {latest ? (+ <div className="flex flex-col gap-0.5 truncate">+ <RelativeTimestamp+ timestamp={latest.started_at}+ className="text-[12.5px] text-gray-12"+ />+ <span className="text-[11px] text-gray-10">+ <span+ className={+ latestOutcome ? OUTCOME_TEXT[latestOutcome] : undefined+ }+ >+ {scoutRunOutcomeLabel(latest, now)}+ </span>+ {latestDuration ? ` · ${latestDuration}` : ""}+ </span>+ </div>+ ) : config.last_run_at ? (+ <RelativeTimestamp+ timestamp={config.last_run_at}+ className="text-[12.5px] text-gray-12"+ />+ ) : runsPending ? (+ <Skeleton className="h-4 w-24" />+ ) : (+ <span className="text-[11px] text-gray-11">—</span>+ )}+ </TableCell>++ <TableCell>+ <ScoutEnabledSwitch config={config} onUpdate={onUpdate} />+ </TableCell>++ <TableCell>+ <DropdownMenu>+ <DropdownMenuTrigger+ render={+ <Button+ type="button"+ variant="default"+ size="icon-sm"+ aria-label={`${name} actions`}+ data-attr="scout-row-menu"+ >+ <DotsThreeIcon size={16} weight="bold" />+ </Button>+ }+ />+ <DropdownMenuContent align="end">+ <DropdownMenuItem+ disabled={isStarting || hasPendingScoutRun(rollup)}+ onClick={() => void runNow()}+ >+ <PlayIcon size={13} />+ Run now+ </DropdownMenuItem>+ <DropdownMenuItem+ onClick={() => openAgent(slug, { tab: "settings" })}+ >+ <GearSixIcon size={13} />+ Settings+ </DropdownMenuItem>+ {cloudSkillUrl ? (+ <>+ <DropdownMenuSeparator />+ <DropdownMenuItem+ onClick={() => {+ track(ANALYTICS_EVENTS.SCOUT_ACTION, {+ action_type: "open_skill_in_posthog",+ surface: "fleet_list",+ skill_name: config.skill_name,+ });+ window.open(cloudSkillUrl, "_blank", "noreferrer");+ }}+ >+ <ArrowSquareOutIcon size={13} />+ Open skill in PostHog+ </DropdownMenuItem>+ </>+ ) : null}+ </DropdownMenuContent>+ </DropdownMenu>+ </TableCell>+ </TableRow>+ );+}++// The fleet can hold hundreds of agents. Rows re-render on every scroll frame+// without this, and each one re-derives its schedule, outcome and run boxes.+export const ScoutTableRow = memo(ScoutTableRowInner);diff --git a/products/desktop/packages/ui/src/features/scouts/components/ScoutsEmptyState.tsx b/products/desktop/packages/ui/src/features/scouts/components/ScoutsEmptyState.tsxnew file mode 100644index 000000000000..6c7751df437a--- /dev/null+++ b/products/desktop/packages/ui/src/features/scouts/components/ScoutsEmptyState.tsx@@ -0,0 +1,42 @@+import { PlusIcon, RobotIcon } from "@phosphor-icons/react";+import {+ Button,+ Empty,+ EmptyContent,+ EmptyDescription,+ EmptyHeader,+ EmptyMedia,+ EmptyTitle,+} from "@posthog/quill";+import { ScoutHelperSkillLinks } from "./ScoutHelperSkillLinks";++export function ScoutsEmptyState({ onNewAgent }: { onNewAgent: () => void }) {+ return (+ <Empty className="py-16">+ <EmptyHeader>+ <EmptyMedia variant="icon">+ <RobotIcon size={20} />+ </EmptyMedia>+ <EmptyTitle>No agents on this project yet</EmptyTitle>+ <EmptyDescription>+ Agents run on a schedule, watch one thing about your product, and send+ what they find to Self-driving. Describe the first one in a sentence+ and PostHog drafts it for you.+ </EmptyDescription>+ </EmptyHeader>+ <EmptyContent>+ <Button+ type="button"+ variant="primary"+ size="default"+ onClick={onNewAgent}+ data-attr="agents-empty-new-agent"+ >+ <PlusIcon size={13} weight="bold" />+ New agent+ </Button>+ <ScoutHelperSkillLinks surface="empty_state" />+ </EmptyContent>+ </Empty>+ );+}diff --git a/products/desktop/packages/ui/src/features/scouts/components/ScoutsFleetSection.stories.tsx b/products/desktop/packages/ui/src/features/scouts/components/ScoutsFleetSection.stories.tsxdeleted file mode 100644index b6c43147e997..000000000000--- a/products/desktop/packages/ui/src/features/scouts/components/ScoutsFleetSection.stories.tsx+++ /dev/null@@ -1,206 +0,0 @@-import type { ScoutConfig, ScoutRun } from "@posthog/api-client/posthog-client";-import { buildScoutCreatorIndex } from "@posthog/core/scouts/scoutPresentation";-import type { ScoutRunsWindow } from "@posthog/core/scouts/scoutRunsWindow";-import type { Meta, StoryObj } from "@storybook/react-vite";-import { ScoutsFleetListView } from "./ScoutsFleetSection";--const YOU = {- id: 1,- first_name: "Robbie",- last_name: "Hedgehog",- email: "[email protected]",-};-const ALEX = {- id: 2,- first_name: "Alex",- last_name: "Doe",- email: "[email protected]",-};-const SAM = { id: 3, first_name: "Sam", email: "[email protected]" };--const config = (overrides: Partial<ScoutConfig> = {}): ScoutConfig => ({- id: `config-${overrides.skill_name ?? "x"}`,- skill_name: "signals-scout-error-tracking",- enabled: true,- emit: true,- scout_origin: "canonical",- run_interval_minutes: 180,- last_run_at: "2026-07-09T06:30:00Z",- auto_pause_exempt: false,- created_at: "2026-06-01T00:00:00Z",- ...overrides,-});--const CONFIGS: ScoutConfig[] = [- config({- skill_name: "signals-scout-ad-spend",- scout_origin: "custom",- emit: false,- description: "Watches ad spend events for runaway campaigns.",- }),- config({- skill_name: "signals-scout-error-tracking",- description: "Sweeps error tracking for new and spiking issues.",- }),- config({- skill_name: "signals-scout-web-analytics",- run_interval_minutes: 1440,- description: "Looks for traffic anomalies across web analytics.",- }),- config({- skill_name: "signals-scout-checkout-funnel",- scout_origin: "custom",- run_interval_minutes: 480,- description: "Tracks conversion through the checkout funnel.",- }),- config({- skill_name: "signals-scout-weekly-digest",- scout_origin: "custom",- enabled: false,- status: "paused_by_user",- run_interval_minutes: 10080,- description: "Posts a weekly digest of notable product metrics.",- }),-];--/** The lifecycle states the platform drives, not the user. */-const LIFECYCLE_CONFIGS: ScoutConfig[] = [- ...CONFIGS,- // Quiet, so flagged for a look — but silence alone never pauses a scout.- config({- id: "config-quiet-watchdog",- skill_name: "signals-scout-quiet-watchdog",- scout_origin: "custom",- status: "pending_pause",- pause_reason: "no_output",- status_changed_at: "2026-07-08T06:15:00Z",- description: "Watches for a failure mode that has not fired in a while.",- }),- // Findings nobody picked up: this is the warning that does advance to a pause.- config({- id: "config-ignored-digest",- skill_name: "signals-scout-ignored-digest",- scout_origin: "custom",- status: "pending_pause",- pause_reason: "ignored",- status_changed_at: "2026-07-08T06:15:00Z",- description: "Files a digest of product metrics nobody has acted on.",- }),- config({- id: "config-flaky-import",- skill_name: "signals-scout-flaky-import",- scout_origin: "custom",- enabled: false,- status: "paused_by_system",- pause_reason: "repeated_failures",- consecutive_failure_count: 6,- status_changed_at: "2026-07-07T00:45:00Z",- description: "Sweeps warehouse imports for stuck or failing syncs.",- }),-];--// Authorship joins from the backing skills: canonical scouts carry no author.-const CREATORS = buildScoutCreatorIndex([- { name: "signals-scout-ad-spend", created_by: YOU, is_latest: true },- { name: "signals-scout-error-tracking", created_by: null, is_latest: true },- { name: "signals-scout-web-analytics", created_by: null, is_latest: true },- { name: "signals-scout-checkout-funnel", created_by: ALEX, is_latest: true },- { name: "signals-scout-weekly-digest", created_by: SAM, is_latest: true },-]);--let runSeq = 0;-const run = (- skillName: string,- overrides: Partial<ScoutRun> = {},-): ScoutRun => ({- run_id: `run-${++runSeq}`,- skill_name: skillName,- skill_version: 3,- status: "completed",- started_at: "2026-07-09T05:00:00Z",- completed_at: "2026-07-09T05:03:00Z",- task_id: null,- task_run_id: null,- task_url: null,- summary: "EMITTED nothing.",- emitted_count: 0,- emitted_finding_ids: [],- ...overrides,-});--const RUNS_WINDOW: ScoutRunsWindow = {- complete: true,- runs: [- ...Array.from({ length: 6 }, (_, i) =>- run("signals-scout-error-tracking", {- emitted_count: i === 2 ? 1 : 0,- ...(i === 4- ? { status: "failed", completed_at: "2026-07-09T05:00:40Z" }- : {}),- }),- ),- ...Array.from({ length: 4 }, () => run("signals-scout-web-analytics")),- ...Array.from({ length: 5 }, (_, i) =>- run("signals-scout-ad-spend", { emitted_count: i === 0 ? 2 : 0 }),- ),- run("signals-scout-checkout-funnel"),- run("signals-scout-checkout-funnel", {- status: "failed",- // Past the ~30m activity deadline, so it reads as a timeout.- completed_at: "2026-07-09T05:31:00Z",- }),- ],-};--const meta: Meta<typeof ScoutsFleetListView> = {- title: "Scouts/ScoutsFleetList",- component: ScoutsFleetListView,- args: {- configs: CONFIGS,- runsWindow: RUNS_WINDOW,- creators: CREATORS,- currentUser: YOU,- onUpdateConfig: () => {},- },- decorators: [- (Story) => (- <div style={{ maxWidth: 1160, margin: "2rem auto", padding: "0 1rem" }}>- <Story />- </div>- ),- ],-};--export default meta;-type Story = StoryObj<typeof ScoutsFleetListView>;--/** The expanded fleet: summary, filters (Created by + Hide disabled), CTAs, rows. */-export const Fleet: Story = {};--/** "Created by" preset to the current user → only their hand-authored scouts. */-export const FilteredToYou: Story = {- args: { initialCreatorKey: `id:${YOU.id}` },-};--/** The current user has authored nothing → picker still offers them, list explains. */-export const NothingOfYours: Story = {- args: {- currentUser: { id: 99, first_name: "Newbie", email: "[email protected]" },- initialCreatorKey: "id:99",- },-};--/** Skills API gated for the org (creators = null) → no creator picker at all. */-export const WithoutCreatorData: Story = {- args: { creators: null },-};--/**- * The three system-driven states side by side: a quiet scout (flagged only), one- * whose ignored findings will pause it, and one the failure breaker already- * paused. Only the latter two are counted in the summary line, and the paused- * one stays out of the "hide disabled" filter so it remains recoverable.- */-export const SystemPaused: Story = {- args: { configs: LIFECYCLE_CONFIGS },-};diff --git a/products/desktop/packages/ui/src/features/scouts/components/ScoutsFleetSection.tsx b/products/desktop/packages/ui/src/features/scouts/components/ScoutsFleetSection.tsxdeleted file mode 100644index 91cf62803f43..000000000000--- a/products/desktop/packages/ui/src/features/scouts/components/ScoutsFleetSection.tsx+++ /dev/null@@ -1,495 +0,0 @@-import type { Icon } from "@phosphor-icons/react";-import {- CaretDownIcon,- CompassIcon,- PlusIcon,- SparkleIcon,-} from "@phosphor-icons/react";-import type { ScoutConfig } from "@posthog/api-client/posthog-client";-import {- computeFleetSummary,- computeScoutRollups,- deriveScoutLifecycle,- getScoutOrigin,- listScoutCreatorOptions,- type ScoutCreatorIndex,- type ScoutCreatorUser,- scoutCreatorKey,- sortConfigsForDisplay,-} from "@posthog/core/scouts/scoutPresentation";-import {- SCOUT_AUTHOR_PROMPT,- SCOUT_FLEET_OVERVIEW_PROMPT,- SCOUT_RECENT_SIGNALS_PROMPT,-} from "@posthog/core/scouts/scoutPrompts";-import {- SCOUT_RUNS_WINDOW_SPAN,- type ScoutRunsWindow,- scoutRunsWindowLabel,-} from "@posthog/core/scouts/scoutRunsWindow";-import type { ScoutChatType, ScoutFleetSyncOutcome } from "@posthog/shared";-import { ANALYTICS_EVENTS } from "@posthog/shared";-import { SettingsOptionSelect } from "@posthog/ui/features/settings/SettingsOptionSelect";-import { RelativeTimestamp } from "@posthog/ui/primitives/RelativeTimestamp";-import { track } from "@posthog/ui/shell/analytics";-import { Box, Flex, Text } from "@radix-ui/themes";-import { useEffect, useMemo, useRef, useState } from "react";-import { useMeQuery } from "../../auth/useMeQuery";-import { useScoutChatTask } from "../hooks/useScoutChatTask";-import type { ScoutConfigUpdate } from "../hooks/useScoutConfigMutations";-import { useScoutConfigMutations } from "../hooks/useScoutConfigMutations";-import { useScoutConfigs } from "../hooks/useScoutConfigs";-import { useScoutFleetSync } from "../hooks/useScoutFleetSync";-import { useScoutRuns } from "../hooks/useScoutRuns";-import { useScoutSkillCreators } from "../hooks/useScoutSkillCreators";-import { FleetFindingsCallout } from "./FleetFindingsCallout";-import { FleetMemoryCallout } from "./FleetMemoryCallout";-import { ScoutHelperSkillLinks } from "./ScoutHelperSkillLinks";-import { ScoutRowCard } from "./ScoutRowCard";--const EMPTY_CONFIGS: ScoutConfig[] = [];--/**- * Expandable scout fleet manager for the agents config page. Collapsed it is- * a one-line pulse; expanded it lists every scout with inline config controls.- * Per-scout drill-down (run history, run detail) stays on its own routes.- */-export function ScoutsFleetSection() {- const { data: configs, isLoading, isError, refetch } = useScoutConfigs();- // Opening this section is what materializes the fleet, so a project the- // coordinator never reached still gets its scouts.- const { isSyncing, syncOutcome } = useScoutFleetSync();- const [expanded, setExpanded] = useState(false);-- const lastRunAt = useMemo(() => {- let latest: string | null = null;- for (const config of configs ?? []) {- if (config.last_run_at && (!latest || config.last_run_at > latest)) {- latest = config.last_run_at;- }- }- return latest;- }, [configs]);-- // An empty fleet while the sync is still running is a fleet being assembled,- // not an empty one — the pulse holds until we know which it is.- if (isLoading || (isSyncing && !configs?.length)) {- return (- <Box className="h-12 w-full animate-pulse rounded-(--radius-2) bg-(--gray-3)" />- );- }-- // A failed request must not masquerade as an empty fleet – a missing scope- // or regional rollout gap would otherwise be indistinguishable from- // "no scouts yet".- if (isError) {- return (- <Flex- align="center"- gap="3"- className="rounded-(--radius-2) border border-(--red-6) bg-(--red-2) px-4 py-3.5"- >- <Text className="flex-1 text-(--red-11) text-[12.5px]">- Couldn't load the scout fleet. The scout API may be unavailable- or this token may lack the <code>signal_scout</code> scope.- </Text>- <button- type="button"- onClick={() => refetch()}- className="shrink-0 rounded-(--radius-2) border border-(--red-7) px-2.5 py-1 text-(--red-11) text-[12px] transition-colors hover:bg-(--red-3)"- >- Retry- </button>- </Flex>- );- }-- if (!configs || configs.length === 0) {- return <ScoutsEmptyState syncOutcome={syncOutcome} />;- }-- const enabledCount = configs.filter((config) => config.enabled).length;- const systemPausedCount = configs.filter(- (config) => deriveScoutLifecycle(config).isSystemPaused,- ).length;-- return (- <Flex direction="column" gap="3">- <button- type="button"- onClick={() => setExpanded((value) => !value)}- aria-expanded={expanded}- className="flex w-full items-center justify-between gap-3 rounded-(--radius-2) border border-border bg-(--color-panel-solid) px-4 py-3.5 text-left transition-colors duration-150 hover:border-(--gray-6) hover:bg-(--gray-2)"- >- <Flex align="center" gap="3" className="min-w-0">- <CompassIcon size={20} className="shrink-0 text-(--iris-9)" />- <Flex direction="column" gap="0" className="min-w-0">- <Text className="font-medium text-[13px] text-gray-12">- Scout fleet- </Text>- <Text className="text-[12px] text-gray-11 leading-snug">- {enabledCount} of {configs.length} scouts enabled- {systemPausedCount > 0 ? (- <span className="text-(--red-11)">- {` · ${systemPausedCount} auto-paused`}- </span>- ) : null}- {lastRunAt ? (- <>- {" · last dispatched "}- <RelativeTimestamp timestamp={lastRunAt} />- </>- ) : null}- </Text>- </Flex>- </Flex>- <CaretDownIcon- size={14}- className={`shrink-0 text-gray-10 transition-transform duration-150 ${- expanded ? "" : "-rotate-90"- }`}- />- </button>- {expanded ? (- <ScoutsFleetList configs={configs} syncOutcome={syncOutcome} />- ) : null}- </Flex>- );-}--function useTrackFleetViewed(- configs: ScoutConfig[],- syncOutcome: ScoutFleetSyncOutcome | null,-) {- const tracked = useRef(false);- useEffect(() => {- // Wait for the sync to settle, so a fleet the sync is about to change is- // never reported against an outcome the request has not reached yet.- if (tracked.current || syncOutcome === null) return;- tracked.current = true;- track(ANALYTICS_EVENTS.SCOUT_FLEET_VIEWED, {- scout_count: configs.length,- enabled_count: configs.filter((config) => config.enabled).length,- dry_run_count: configs.filter((config) => !config.emit).length,- custom_count: configs.filter(- (config) => getScoutOrigin(config) === "custom",- ).length,- is_empty: configs.length === 0,- sync_outcome: syncOutcome,- });- }, [configs, syncOutcome]);-}--function ScoutsFleetList({- configs,- syncOutcome,-}: {- configs: ScoutConfig[];- syncOutcome: ScoutFleetSyncOutcome | null;-}) {- const { data: runsWindow } = useScoutRuns();- const { updateConfig } = useScoutConfigMutations();- const { data: creators } = useScoutSkillCreators();- const { data: currentUser } = useMeQuery();- useTrackFleetViewed(configs, syncOutcome);-- return (- <ScoutsFleetListView- configs={configs}- runsWindow={runsWindow}- creators={creators}- currentUser={currentUser ?? null}- onUpdateConfig={updateConfig}- />- );-}--/**- * Pure fleet list: summary line, filters, chat CTAs, and the scout rows. Data- * and mutations come in as props (Storybook renders this directly — the- * container's hooks never resolve there).- */-export function ScoutsFleetListView({- configs,- runsWindow,- creators,- currentUser,- onUpdateConfig,- initialCreatorKey = "",-}: {- configs: ScoutConfig[];- runsWindow: ScoutRunsWindow | undefined;- /** Undefined while loading; null when the skills API is unavailable for the org. */- creators: ScoutCreatorIndex | null | undefined;- currentUser: ScoutCreatorUser | null;- onUpdateConfig: (configId: string, updates: ScoutConfigUpdate) => void;- /** Start with a creator preselected (Storybook seam). */- initialCreatorKey?: string;-}) {- const [hideDisabled, setHideDisabled] = useState(false);- const [creatorKey, setCreatorKey] = useState(initialCreatorKey);-- const runs = runsWindow?.runs;- const rollups = useMemo(() => computeScoutRollups(runs ?? []), [runs]);- const summary = useMemo(- () => computeFleetSummary(configs, rollups),- [configs, rollups],- );- // Null/undefined creators = the skills API is gated for this org (or still- // loading), so authorship is unknowable; render no picker instead of an- // always-empty filter.- const creatorOptions = useMemo(- () => (creators ? listScoutCreatorOptions(creators, currentUser) : []),- [creators, currentUser],- );- const selectedCreator = creatorOptions.find(- (option) => option.key === creatorKey,- );- const visibleConfigs = useMemo(() => {- let sorted = sortConfigsForDisplay(configs);- if (hideDisabled) {- // "Disabled" means the scouts a person switched off. The ones PostHog- // switched off are exactly what this view has to keep in front of them,- // since switching them back on is the only way to recover them.- sorted = sorted.filter(- (config) =>- config.enabled || deriveScoutLifecycle(config).isSystemPaused,- );- }- if (creatorKey && creators) {- sorted = sorted.filter(- (config) =>- scoutCreatorKey(creators.get(config.skill_name)) === creatorKey,- );- }- return sorted;- }, [configs, hideDisabled, creatorKey, creators]);-- return (- <Flex direction="column" gap="3">- <Flex align="center" gap="2" wrap="wrap">- <Text className="text-[12.5px] text-gray-11">- {summary.runningCount > 0- ? `${summary.runningCount} running now`- : "None running now"}- {summary.successRate !== null- ? ` · ${Math.round(summary.successRate * 100)}% success`- : ""}- {` · ${summary.emittedCount} signal${summary.emittedCount === 1 ? "" : "s"} emitted`}- {summary.emitRate !== null- ? ` (${Math.round(summary.emitRate * 100)}%)`- : ""}- <span className="text-gray-9">- {" "}- · {scoutRunsWindowLabel(runsWindow)}- </span>- </Text>- {/* Auto-paused scouts sink below the enabled ones and vanish entirely- under "Hide disabled", so the count has to lead here. */}- {summary.systemPausedCount > 0 ? (- <span className="whitespace-nowrap text-(--red-11) text-[12.5px]">- {summary.systemPausedCount} auto-paused- </span>- ) : null}- {summary.pausingSoonCount > 0 ? (- <span className="whitespace-nowrap text-(--amber-11) text-[12.5px]">- {summary.pausingSoonCount} pausing soon- </span>- ) : null}- <span className="flex-1" />- {creatorOptions.length > 0 ? (- <Flex align="center" gap="2">- <Text className="whitespace-nowrap text-[12px] text-gray-10">- Created by- </Text>- <div className="w-44">- <SettingsOptionSelect- value={creatorKey}- options={[- { value: "", label: "Any user" },- ...creatorOptions.map((option) => ({- value: option.key,- label: option.label,- })),- ]}- onValueChange={(next) => {- setCreatorKey(next);- const option = creatorOptions.find(- (candidate) => candidate.key === next,- );- track(ANALYTICS_EVENTS.SCOUT_ACTION, {- action_type: "filter_created_by",- surface: "fleet_list",- created_by_me: option?.isCurrentUser ?? false,- filter_match_count: next- ? configs.filter(- (config) =>- scoutCreatorKey(- creators?.get(config.skill_name),- ) === next,- ).length- : undefined,- });- }}- ariaLabel="Filter scouts by creator"- placeholder="Any user"- />- </div>- </Flex>- ) : null}- <button- type="button"- onClick={() => {- const next = !hideDisabled;- setHideDisabled(next);- track(ANALYTICS_EVENTS.SCOUT_ACTION, {- action_type: "toggle_hide_disabled",- surface: "fleet_list",- hide_disabled: next,- });- }}- className="rounded px-1.5 py-0.5 text-[12px] text-gray-10 hover:bg-gray-3 hover:text-gray-12"- >- {hideDisabled ? "Show disabled" : "Hide disabled"}- </button>- </Flex>-- <Flex align="center" gap="2" wrap="wrap">- <ScoutChatCta- label="How is my scout fleet performing?"- prompt={SCOUT_FLEET_OVERVIEW_PROMPT}- taskLabel="fleet overview"- loggerScope="scout-fleet-overview"- chatType="fleet_overview"- />- <ScoutChatCta- label="What signals were emitted recently?"- prompt={SCOUT_RECENT_SIGNALS_PROMPT}- taskLabel="recent signals recap"- loggerScope="scout-recent-signals"- chatType="recent_signals"- />- <ScoutChatCta- label="Make a scout"- prompt={SCOUT_AUTHOR_PROMPT}- taskLabel="scout authoring"- loggerScope="scout-author"- chatType="author_scout"- icon={PlusIcon}- />- </Flex>-- {/* Findings: renders only once scouts have emitted something. */}- <FleetFindingsCallout />-- {/* Fleet memory: renders only once scouts have written scratchpad notes. */}- <FleetMemoryCallout />-- {/* Bounded to roughly 10 rows; larger fleets scroll within the section. */}- <div className="max-h-[710px] overflow-y-auto">- <Flex direction="column" gap="2">- {visibleConfigs.length === 0 ? (- <Text className="px-1 py-2 text-[12.5px] text-gray-10">- {creatorKey- ? selectedCreator?.isCurrentUser- ? "No scouts created by you match the current filters."- : "No scouts created by the selected user match the current filters."- : "No scouts match the current filters."}- </Text>- ) : (- visibleConfigs.map((config) => (- <ScoutRowCard- key={config.id}- config={config}- rollup={rollups.get(config.skill_name)}- onUpdate={onUpdateConfig}- />- ))- )}- </Flex>- </div>-- <Flex direction="column" gap="1">- <Text className="text-[12px] text-gray-10">- Run counts and emitted totals cover the last {SCOUT_RUNS_WINDOW_SPAN}{" "}- of fleet runs. New scouts are created as{" "}- <span className="font-mono text-[11px]">signals-scout-*</span> skills- in your PostHog project.- </Text>- <ScoutHelperSkillLinks surface="fleet_list" />- </Flex>- </Flex>- );-}--/**- * Suggestion-chip CTA that fires an auto-mode cloud task asking the- * exploring-signals-scouts skill a templated question, then navigates to it –- * same one-click shape as the inbox discuss / create-PR flows.- */-function ScoutChatCta({- label,- prompt,- taskLabel,- loggerScope,- chatType,- icon: IconComponent = SparkleIcon,-}: {- label: string;- prompt: string;- taskLabel: string;- loggerScope: string;- chatType: ScoutChatType;- icon?: Icon;-}) {- const { runTask, isRunning } = useScoutChatTask({- prompt,- taskLabel,- loggerScope,- chatType,- surface: "fleet_list",- });- return (- <button- type="button"- onClick={() => void runTask()}- disabled={isRunning}- className="flex w-fit items-center gap-1.5 rounded-full border border-border bg-(--color-panel-solid) px-3 py-1 text-[12px] text-gray-11 transition-colors duration-150 hover:border-(--gray-6) hover:bg-(--gray-2) hover:text-gray-12 disabled:cursor-default disabled:opacity-60 disabled:hover:border-border disabled:hover:bg-(--color-panel-solid)"- >- <IconComponent size={12} className="text-(--iris-9)" />- {isRunning ? `Starting ${taskLabel}...` : label}- </button>- );-}--function ScoutsEmptyState({- syncOutcome,-}: {- syncOutcome: ScoutFleetSyncOutcome | null;-}) {- useTrackFleetViewed(EMPTY_CONFIGS, syncOutcome);- return (- <Flex direction="column" gap="3">- <Flex- direction="column"- gap="2"- align="start"- className="rounded-(--radius-3) border border-border bg-(--color-panel-solid) px-5 py-5"- >- <Flex align="center" gap="2">- <CompassIcon size={18} className="text-(--iris-9)" />- <Text className="font-medium text-[13px] text-gray-12">- No scouts on this project yet- </Text>- </Flex>- <Text className="max-w-2xl text-[12.5px] text-gray-11 leading-snug">- Scouts run on a schedule to investigate a recurring signal or- behavior. Add one by creating a{" "}- <span className="font-mono text-[11px]">signals-scout-*</span> skill- in your PostHog project.- </Text>- <ScoutHelperSkillLinks surface="empty_state" />- </Flex>- </Flex>- );-}diff --git a/products/desktop/packages/ui/src/features/scouts/components/ScoutsFleetView.tsx b/products/desktop/packages/ui/src/features/scouts/components/ScoutsFleetView.tsxnew file mode 100644index 000000000000..dd1b6718a7d2--- /dev/null+++ b/products/desktop/packages/ui/src/features/scouts/components/ScoutsFleetView.tsx@@ -0,0 +1,457 @@+import { CheckIcon } from "@phosphor-icons/react";+import type { ScoutConfig } from "@posthog/api-client/posthog-client";+import {+ computeFleetSummary,+ computeScoutRollups,+ deriveScoutLifecycle,+ getScoutOrigin,+ listScoutCreatorOptions,+ listScoutsNeedingAttention,+ prettifyScoutSkillName,+ type ScoutOrigin,+ scoutCreatorKey,+ sortConfigsForDisplay,+} from "@posthog/core/scouts/scoutPresentation";+import { SCOUT_RUNS_WINDOW_LABEL } from "@posthog/core/scouts/scoutRunsWindow";+import { suggestionBrief } from "@posthog/core/scouts/scoutSuggestions";+import { Button, Skeleton, Tabs, TabsList, TabsTrigger } from "@posthog/quill";+import { ANALYTICS_EVENTS } from "@posthog/shared";+import { leaveSettings } from "@posthog/ui/features/settings/hooks/useOpenSettings";+import { SettingsOptionSelect } from "@posthog/ui/features/settings/SettingsOptionSelect";+import { useMinuteNow } from "@posthog/ui/hooks/useMinuteNow";+import { SearchInput } from "@posthog/ui/primitives/SearchInput";+import { track } from "@posthog/ui/shell/analytics";+import { Link } from "@tanstack/react-router";+import { useMemo, useState } from "react";+import { useMeQuery } from "../../auth/useMeQuery";+import { useScoutConfigMutations } from "../hooks/useScoutConfigMutations";+import { useScoutConfigs } from "../hooks/useScoutConfigs";+import { useScoutFleetSync } from "../hooks/useScoutFleetSync";+import {+ useScoutOutputSummary,+ useScoutRecentRuns,+} from "../hooks/useScoutRecentRuns";+import { useScoutSkillCreators } from "../hooks/useScoutSkillCreators";+import {+ useDismissScoutSuggestion,+ useScoutSuggestions,+} from "../hooks/useScoutSuggestions";+import { useTrackFleetViewed } from "../hooks/useTrackFleetViewed";+import { ScoutAttentionStrip } from "./ScoutAttentionStrip";+import { ScoutSuggestions } from "./ScoutSuggestions";+import { ScoutsEmptyState } from "./ScoutsEmptyState";+import { ScoutTable } from "./ScoutTable";++const EMPTY_CONFIGS: ScoutConfig[] = [];++type OriginFilter = ScoutOrigin | "all";++const ORIGIN_TABS: { value: OriginFilter; label: string }[] = [+ { value: "custom", label: "Custom" },+ { value: "canonical", label: "Built-in" },+ { value: "all", label: "All" },+];++/** The fleet index: what needs a decision, then every agent in a table. */+export function ScoutsFleetView({+ onNewAgent,+}: {+ onNewAgent: (brief?: string) => void;+}) {+ const now = useMinuteNow();+ const configsQuery = useScoutConfigs();+ const { data: configs, isLoading, isError, refetch } = configsQuery;+ // Opening this page is what materializes the fleet, so a project the+ // coordinator never reached still gets its scouts.+ const { isSyncing, syncOutcome } = useScoutFleetSync();+ const runsQuery = useScoutRecentRuns();+ const outputQuery = useScoutOutputSummary();+ const recentRuns = runsQuery.data;+ // Run history arrives after the fleet, so the columns it feeds say "loading",+ // never "none", until the window has answered.+ const runsPending = runsQuery.isLoading;+ const runsLoadingMore = runsQuery.isFetching;+ const { data: creators } = useScoutSkillCreators();+ const { data: currentUser } = useMeQuery();+ const { updateConfig } = useScoutConfigMutations();+ const { data: suggestions } = useScoutSuggestions();+ const dismissSuggestion = useDismissScoutSuggestion();+ useTrackFleetViewed(+ configs,+ syncOutcome,+ configsQuery.isFetchedAfterMount && !configsQuery.isFetching && !isError,+ );++ const [originChoice, setOriginChoice] = useState<OriginFilter | null>(null);+ const [search, setSearch] = useState("");+ const [creatorKey, setCreatorKey] = useState("");+ const [hideDisabled, setHideDisabled] = useState(false);++ const allConfigs = configs ?? EMPTY_CONFIGS;+ const rollups = useMemo(+ () => computeScoutRollups(recentRuns ?? []),+ [recentRuns],+ );+ const summary = useMemo(+ () => computeFleetSummary(allConfigs, rollups, now),+ [allConfigs, rollups, now],+ );+ const attention = useMemo(+ () => listScoutsNeedingAttention(allConfigs, rollups, now),+ [allConfigs, rollups, now],+ );+ const originCounts = useMemo(() => {+ const counts: Record<OriginFilter, number> = {+ custom: 0,+ canonical: 0,+ all: 0,+ };+ for (const config of allConfigs) {+ counts[getScoutOrigin(config)] += 1;+ counts.all += 1;+ }+ return counts;+ }, [allConfigs]);+ // Custom agents are the ones a person wrote, so they lead when there are any.+ const origin: OriginFilter =+ originChoice ?? (originCounts.custom > 0 ? "custom" : "all");++ const creatorOptions = useMemo(+ () => (creators ? listScoutCreatorOptions(creators, currentUser) : []),+ [creators, currentUser],+ );++ // The order depends on the fleet alone, so a keystroke in the search box+ // filters what is already sorted rather than sorting it again.+ const orderedConfigs = useMemo(() => {+ const urgent = new Set(attention.map((item) => item.config.id));+ return sortConfigsForDisplay(allConfigs).sort(+ (a, b) => Number(urgent.has(b.id)) - Number(urgent.has(a.id)),+ );+ }, [allConfigs, attention]);++ const visibleConfigs = useMemo(() => {+ const needle = search.trim().toLowerCase();+ return orderedConfigs.filter((config) => {+ if (origin !== "all" && getScoutOrigin(config) !== origin) return false;+ if (+ hideDisabled &&+ !config.enabled &&+ !deriveScoutLifecycle(config).isSystemPaused+ ) {+ return false;+ }+ if (+ creatorKey &&+ creators &&+ scoutCreatorKey(creators.get(config.skill_name)) !== creatorKey+ ) {+ return false;+ }+ if (!needle) return true;+ return (+ prettifyScoutSkillName(config.skill_name)+ .toLowerCase()+ .includes(needle) ||+ (config.description ?? "").toLowerCase().includes(needle)+ );+ });+ }, [orderedConfigs, origin, hideDisabled, creatorKey, creators, search]);++ if (isLoading || (isSyncing && !configs?.length)) {+ return <FleetSkeleton />;+ }++ if (isError && !configs) {+ return (+ <div className="flex items-center gap-3 rounded-(--radius-md) border border-(--red-6) bg-(--red-2) px-4 py-3.5">+ <p className="flex-1 text-(--red-11) text-[12.5px]">+ Couldn't load your agents. The agent API may be unavailable or+ this token may lack the <code>signal_scout</code> scope.+ </p>+ <Button+ type="button"+ variant="outline"+ size="sm"+ onClick={() => refetch()}+ >+ Retry+ </Button>+ </div>+ );+ }++ const suggestionCards = (+ <ScoutSuggestions+ items={suggestions?.items ?? []}+ configs={allConfigs}+ onTurnOn={updateConfig}+ onDraft={(item) => onNewAgent(suggestionBrief(item))}+ onDismiss={dismissSuggestion}+ />+ );++ if (!configs || configs.length === 0) {+ return (+ <div className="flex flex-col gap-6">+ {suggestionCards}+ <ScoutsEmptyState onNewAgent={onNewAgent} />+ </div>+ );+ }++ return (+ <div className="flex h-full min-h-0 flex-col gap-5">+ {isError || runsQuery.isError || outputQuery.isError ? (+ <output className="text-(--amber-11) text-[12.5px]">+ Some agent data could not refresh. Available data remains visible.{" "}+ <button+ type="button"+ className="underline"+ onClick={() => {+ void refetch();+ void runsQuery.refetch();+ void outputQuery.refetch();+ }}+ >+ Retry+ </button>+ </output>+ ) : null}+ <p className="flex flex-wrap items-center gap-x-1.5 text-[12.5px] text-gray-10">+ <span>+ <Stat value={summary.enabledCount} /> of {summary.totalCount} enabled+ </span>+ <Dot />+ {runsPending ? (+ <Skeleton className="h-3.5 w-52" />+ ) : (+ <>+ {summary.runningCount > 0 ? (+ <>+ <span className="flex items-center gap-1.5">+ <span className="inline-block h-2 w-2 animate-pulse rounded-full bg-(--blue-9)" />+ <Stat value={summary.runningCount} /> running now+ </span>+ <Dot />+ </>+ ) : null}+ {summary.successRate !== null ? (+ <>+ <span>+ <Stat value={`${Math.round(summary.successRate * 100)}%`} />{" "}+ success in shown runs+ </span>+ <Dot />+ </>+ ) : null}+ <span>+ {outputQuery.data ? (+ <>+ <Link+ to="/inbox"+ onClick={leaveSettings}+ className="underline"+ >+ <Stat+ value={+ outputQuery.data.authored_report_count ++ outputQuery.data.edited_report_count+ }+ />{" "}+ reports+ </Link>{" "}+ from recent output runs in the {SCOUT_RUNS_WINDOW_LABEL}+ </>+ ) : outputQuery.isError ? (+ "Output totals are unavailable"+ ) : (+ "Loading output totals"+ )}+ </span>+ {runsLoadingMore ? (+ <span className="animate-pulse text-gray-9">· refreshing</span>+ ) : null}+ </>+ )}+ <span className="flex-1" />+ {/* One span, so a wrap never leaves its separator hanging on a line. */}+ {summary.systemPausedCount > 0 || summary.pausingSoonCount > 0 ? (+ <span className="text-(--amber-11)">+ {[+ summary.systemPausedCount > 0+ ? `${summary.systemPausedCount} auto-paused`+ : null,+ summary.pausingSoonCount > 0+ ? `${summary.pausingSoonCount} pausing soon`+ : null,+ ]+ .filter(Boolean)+ .join(" · ")}+ </span>+ ) : null}+ </p>++ {suggestionCards}+ {attention.length > 0 ? (+ <ScoutAttentionStrip items={attention} onUpdateConfig={updateConfig} />+ ) : null}++ <div className="flex flex-wrap items-center gap-2">+ <Tabs+ value={origin}+ onValueChange={(value: string) => {+ setOriginChoice(value as OriginFilter);+ track(ANALYTICS_EVENTS.SCOUT_ACTION, {+ action_type: "filter_origin",+ surface: "fleet_list",+ filter: value,+ });+ }}+ >+ <TabsList className="h-8">+ {ORIGIN_TABS.map(({ value, label }) => (+ <TabsTrigger key={value} value={value} className="px-2.5">+ {label}+ </TabsTrigger>+ ))}+ </TabsList>+ </Tabs>+ <SearchInput+ className="w-52"+ value={search}+ onValueChange={setSearch}+ onBlur={() => {+ if (search.trim()) {+ track(ANALYTICS_EVENTS.SCOUT_ACTION, {+ action_type: "search_agents",+ surface: "fleet_list",+ filter_match_count: visibleConfigs.length,+ });+ }+ }}+ placeholder="Search agents"+ />+ {creatorOptions.length > 0 ? (+ <div className="w-44">+ <SettingsOptionSelect+ value={creatorKey}+ options={[+ { value: "", label: "Created by anyone" },+ ...creatorOptions.map((option) => ({+ value: option.key,+ label: option.label,+ })),+ ]}+ onValueChange={(next) => {+ setCreatorKey(next);+ track(ANALYTICS_EVENTS.SCOUT_ACTION, {+ action_type: "filter_created_by",+ surface: "fleet_list",+ created_by_me:+ creatorOptions.find((option) => option.key === next)+ ?.isCurrentUser ?? false,+ });+ }}+ size="default"+ ariaLabel="Filter agents by creator"+ placeholder="Created by anyone"+ />+ </div>+ ) : null}+ <Button+ type="button"+ variant={hideDisabled ? "outline" : "link-muted"}+ size="sm"+ onClick={() => {+ const next = !hideDisabled;+ setHideDisabled(next);+ track(ANALYTICS_EVENTS.SCOUT_ACTION, {+ action_type: "toggle_hide_disabled",+ surface: "fleet_list",+ hide_disabled: next,+ });+ }}+ >+ {hideDisabled ? <CheckIcon size={12} /> : null}+ Hide disabled+ </Button>+ </div>++ <div className="min-h-0 flex-1">+ <ScoutTable+ configs={visibleConfigs}+ rollups={rollups}+ runsPending={runsPending}+ creators={creators}+ onUpdateConfig={updateConfig}+ emptyMessage={+ search.trim()+ ? "No agents match your search."+ : "No agents match the current filters."+ }+ />+ </div>++ <div className="flex flex-wrap items-center gap-x-4 gap-y-1 text-[12px] text-gray-10">+ <span className="flex items-center gap-3">+ <Legend className="bg-(--iris-9)" label="output" />+ <Legend className="bg-(--gray-6)" label="quiet" />+ <Legend className="bg-(--red-9)" label="failed" />+ </span>+ <span>+ Showing {visibleConfigs.length} of {configs.length} agents. Each row+ shows up to 18 recent runs.+ </span>+ {origin !== "custom" ? (+ <span>+ PostHog owns the built-in agents. You can switch them on or off. You+ cannot edit them.+ </span>+ ) : null}+ </div>+ </div>+ );+}++const SKELETON_ROWS = [0, 1, 2, 3, 4, 5];++/** The shape of the loaded page, so the layout does not jump when it lands. */+function FleetSkeleton() {+ return (+ <div className="flex flex-col gap-5">+ <Skeleton className="h-4 w-96" />+ <div className="flex items-center gap-2">+ <Skeleton className="h-8 w-56" />+ <Skeleton className="h-8 w-52" />+ </div>+ <div className="flex flex-col gap-px overflow-hidden rounded-(--radius-md) border border-border bg-(--color-panel-solid) p-3">+ {SKELETON_ROWS.map((row) => (+ <div key={row} className="flex items-center gap-4 py-2.5">+ <Skeleton className="h-4 w-64" />+ <Skeleton className="h-4 w-24" />+ <Skeleton className="h-4 flex-1" />+ <Skeleton className="h-4 w-32" />+ </div>+ ))}+ </div>+ </div>+ );+}++function Stat({ value }: { value: number | string }) {+ return <span className="font-medium text-gray-12 tabular-nums">{value}</span>;+}++function Dot() {+ return <span className="text-gray-8">·</span>;+}++function Legend({ className, label }: { className: string; label: string }) {+ return (+ <span className="flex items-center gap-1">+ <i className={`inline-block h-2.5 w-1.5 rounded-[1.5px] ${className}`} />+ {label}+ </span>+ );+}diff --git a/products/desktop/packages/ui/src/features/scouts/components/ScratchpadEntryCard.tsx b/products/desktop/packages/ui/src/features/scouts/components/ScratchpadEntryCard.tsxindex 29717f4e1d8f..84b2546656d9 100644--- a/products/desktop/packages/ui/src/features/scouts/components/ScratchpadEntryCard.tsx+++ b/products/desktop/packages/ui/src/features/scouts/components/ScratchpadEntryCard.tsx@@ -1,26 +1,29 @@import { CaretRightIcon, ClockIcon } from "@phosphor-icons/react";import type { ScoutScratchpadEntry } from "@posthog/api-client/posthog-client";import { splitScratchpadKey } from "@posthog/core/scouts/scoutScratchpad";+import { Badge } from "@posthog/quill";import { MarkdownRenderer } from "@posthog/ui/features/editor/components/MarkdownRenderer";import { RelativeTimestamp } from "@posthog/ui/primitives/RelativeTimestamp";-import { Badge, type BadgeProps, Box, Flex, Text } from "@radix-ui/themes";-import { useState } from "react";// The key prefix (everything before the first colon) encodes the note's *kind* —// what the scout was doing when it wrote it. Surface it as a colored tag so the// list scans at a glance.-const KIND_TAG_COLOR: Record<string, BadgeProps["color"]> = {- pattern: "iris",- dedupe: "gray",- noise: "gray",- baseline: "green",- watch: "amber",- watchlist: "amber",- coverage: "blue",- emerging: "purple",- explore: "cyan",- tags: "cyan",- recheck: "orange",++const KIND_TAG_VARIANT: Record<+ string,+ "info" | "default" | "success" | "warning"+> = {+ pattern: "info",+ dedupe: "default",+ noise: "default",+ baseline: "success",+ watch: "warning",+ watchlist: "warning",+ coverage: "info",+ emerging: "info",+ explore: "info",+ tags: "info",+ recheck: "warning",};/**@@ -31,18 +34,20 @@ const KIND_TAG_COLOR: Record<string, BadgeProps["color"]> = {*/export function ScratchpadEntryCard({entry,+ expanded,+ onExpandedChange,}: {entry: ScoutScratchpadEntry;+ expanded: boolean;+ onExpandedChange: (expanded: boolean) => void;}) {- const [expanded, setExpanded] = useState(false);-const { kind, body } = splitScratchpadKey(entry.key);return (- <Box className="min-w-0 overflow-hidden rounded-(--radius-2) border border-(--gray-6) bg-gray-1">+ <div className="min-w-0 overflow-hidden rounded-(--radius-2) border border-(--gray-6) bg-gray-1"><buttontype="button"- onClick={() => setExpanded((value) => !value)}+ onClick={() => onExpandedChange(!expanded)}aria-expanded={expanded}className="flex w-full select-none items-center gap-2 px-3 py-2 text-left">@@ -52,49 +57,40 @@ export function ScratchpadEntryCard({/>{kind ? (<Badge- variant="soft"- color={KIND_TAG_COLOR[kind] ?? "gray"}- size="1"+ variant={KIND_TAG_VARIANT[kind] ?? "default"}className="shrink-0 text-[11px]">{kind}</Badge>) : null}- <Text className="truncate font-mono text-[12px] text-gray-12">+ <span className="truncate font-mono text-[12px] text-gray-12">{body}- </Text>+ </span><span className="flex-1" />{entry.updated_at ? (- <Flex align="center" gap="1" className="shrink-0 text-gray-10">+ <div className="flex shrink-0 items-center gap-1 text-gray-10"><ClockIcon size={11} className="text-gray-9" /><RelativeTimestamp timestamp={entry.updated_at} />- </Flex>+ </div>) : null}</button>- <Box className="px-3 pb-2 pl-9">- <Box- className={`text-pretty break-words text-[13px] text-gray-11 leading-relaxed [&_code]:text-[11px] [&_p:last-child]:mb-0 [&_p]:mb-1 [&_pre]:text-[11px] ${- expanded ? "" : "line-clamp-2"+ <div className="px-3 pb-2 pl-9">+ <div+ className={`text-pretty break-words text-[12.5px] text-gray-11 leading-relaxed [&_code]:text-[11px] [&_p:last-child]:mb-0 [&_p]:mb-1 [&_pre]:text-[11px] ${+ expanded ? "max-h-72 overflow-y-auto pr-2" : "line-clamp-2"}`}><MarkdownRenderer content={entry.content || "_No content._"} />- </Box>+ </div>{expanded && entry.created_at ? (- <Flex- align="center"- gap="2"- mt="2"- pt="2"- wrap="wrap"- className="border-t border-t-(--gray-5) text-[11px] text-gray-10"- >- <Text className="text-[11px] text-gray-10">Created</Text>+ <div className="mt-2 flex flex-wrap items-center gap-2 border-t border-t-(--gray-5) pt-2 text-[11px] text-gray-10">+ <span className="text-[11px] text-gray-10">Created</span><RelativeTimestamp timestamp={entry.created_at} />- </Flex>+ </div>) : null}- </Box>- </Box>+ </div>+ </div>);}diff --git a/products/desktop/packages/ui/src/features/scouts/components/ScratchpadView.tsx b/products/desktop/packages/ui/src/features/scouts/components/ScratchpadView.tsxindex 9a0045af98a8..711ca445b202 100644--- a/products/desktop/packages/ui/src/features/scouts/components/ScratchpadView.tsx+++ b/products/desktop/packages/ui/src/features/scouts/components/ScratchpadView.tsx@@ -1,23 +1,34 @@-import {- ArrowLeftIcon,- CaretDownIcon,- ClockIcon,- MagnifyingGlassIcon,- NotebookIcon,- StackIcon,-} from "@phosphor-icons/react";+import { CaretDownIcon, ClockIcon, StackIcon } from "@phosphor-icons/react";+import type { ScoutScratchpadEntry } from "@posthog/api-client/posthog-client";import {filterScratchpadEntries,groupScratchpadEntries,type ScratchpadGrouping,} from "@posthog/core/scouts/scoutScratchpad";-import { useSetHeaderContent } from "@posthog/ui/hooks/useSetHeaderContent";+import {+ Button,+ Empty,+ EmptyContent,+ EmptyDescription,+ EmptyHeader,+ EmptyTitle,+ Skeleton,+ Tabs,+ TabsList,+ TabsTrigger,+} from "@posthog/quill";import { RelativeTimestamp } from "@posthog/ui/primitives/RelativeTimestamp";-import { Box, Flex, SegmentedControl, Text, TextField } from "@radix-ui/themes";-import { Link } from "@tanstack/react-router";+import { SearchInput } from "@posthog/ui/primitives/SearchInput";import { useMemo, useState } from "react";import { useScoutScratchpad } from "../hooks/useScoutScratchpad";import { ScratchpadEntryCard } from "./ScratchpadEntryCard";+import { VirtualCardList } from "./VirtualCardList";++/** A collapsed note: header line plus a two-line preview. */+const NOTE_CARD_HEIGHT = 84;++const EMPTY_ENTRIES: ScoutScratchpadEntry[] = [];+const NO_GROUPS: ReturnType<typeof groupScratchpadEntries> = [];/*** Browse + search surface for the scout fleet's scratchpad (`SignalScratchpad`).@@ -30,264 +41,179 @@ import { ScratchpadEntryCard } from "./ScratchpadEntryCard";*/export function ScratchpadView() {const { data: entries, isLoading, isError, refetch } = useScoutScratchpad();+ const [expandedNotes, setExpandedNotes] = useState<Record<string, boolean>>(+ {},+ );+ const [expandedTopics, setExpandedTopics] = useState<Record<string, boolean>>(+ {},+ );const [searchText, setSearchText] = useState("");const [grouping, setGrouping] = useState<ScratchpadGrouping>("recent");- const headerContent = useMemo(- () => (- <Flex align="center" gap="2" className="w-full min-w-0">- <NotebookIcon size={12} className="shrink-0 text-gray-10" />- <Text- className="truncate whitespace-nowrap font-medium text-[13px]"- title="Scout scratchpad"- >- Scout scratchpad- </Text>- </Flex>- ),- [],- );- useSetHeaderContent(headerContent);-const isSearching = searchText.trim().length > 0;- const allEntries = entries ?? [];+ const allEntries = entries ?? EMPTY_ENTRIES;const visibleEntries = useMemo(() => filterScratchpadEntries(allEntries, searchText),[allEntries, searchText],);+ // Only the topic view reads the groups, and "recent" is where people land.const groups = useMemo(- () => groupScratchpadEntries(visibleEntries),- [visibleEntries],+ () =>+ grouping === "topic" ? groupScratchpadEntries(visibleEntries) : NO_GROUPS,+ [visibleEntries, grouping],);const totalCount = entries?.length ?? null;const lastUpdatedAt = entries?.[0]?.updated_at ?? null;return (- <Flex direction="column" className="h-full min-h-0">- <Flex- direction="column"- gap="2"- className="border-(--gray-5) border-b px-6 pt-5 pb-5"- >- <Link- to="/agents/scouts"- className="flex w-fit items-center gap-1 text-[12px] text-gray-10 no-underline hover:text-gray-12"+ <div className="flex h-full min-h-0 flex-col gap-4">+ {totalCount !== null && totalCount > 0 ? (+ <div className="flex items-center gap-1 text-[12px] text-gray-10">+ <span>+ {totalCount >= 500+ ? "Latest 500 notes"+ : `${totalCount} note${totalCount === 1 ? "" : "s"}`}+ </span>+ {lastUpdatedAt ? (+ <>+ <span className="text-gray-9">· last updated</span>+ <RelativeTimestamp+ timestamp={lastUpdatedAt}+ className="text-[12px] text-gray-10"+ />+ </>+ ) : null}+ </div>+ ) : null}+ <div className="flex flex-wrap items-center gap-2">+ <SearchInput+ value={searchText}+ onValueChange={setSearchText}+ placeholder="Search notes"+ />+ <span className="flex-1" />+ <Tabs+ value={grouping}+ onValueChange={(value: string) =>+ setGrouping(value as ScratchpadGrouping)+ }>- <ArrowLeftIcon size={12} />- Scouts- </Link>- <Flex align="center" gap="2">- <NotebookIcon size={20} className="shrink-0 text-(--iris-9)" />- <Text className="font-bold text-[22px] text-gray-12 leading-tight tracking-tight">- Scout scratchpad- </Text>- </Flex>- <Text className="max-w-2xl text-pretty text-[12.5px] text-gray-11 leading-relaxed">- Where your scouts jot down useful context as they scan your project —- things they've classified, ruled out, or the vocabulary- they've settled on. Browse it to see what they're picking up- about your setup.- </Text>- {totalCount !== null && totalCount > 0 ? (- <Flex align="center" gap="1" className="text-[12px] text-gray-10">- <Text className="text-[12px] text-gray-10">- {totalCount} note{totalCount === 1 ? "" : "s"}- </Text>- {lastUpdatedAt ? (- <>- <Text className="text-[12px] text-gray-9">· last updated</Text>- <RelativeTimestamp- timestamp={lastUpdatedAt}- className="text-[12px] text-gray-10"- />- </>- ) : null}- </Flex>- ) : null}- </Flex>+ <TabsList className="h-8" aria-label="Group notes">+ <TabsTrigger value="recent" className="gap-1.5 px-2.5">+ <ClockIcon size={12} />+ Recent+ </TabsTrigger>+ <TabsTrigger value="topic" className="gap-1.5 px-2.5">+ <StackIcon size={12} />+ By topic+ </TabsTrigger>+ </TabsList>+ </Tabs>+ </div>- <div className="min-h-0 flex-1 overflow-auto">- <div className="mx-auto max-w-4xl px-6 py-6">- <Flex direction="column" gap="4">- <Flex align="center" gap="2" wrap="wrap">- <TextField.Root- type="search"- placeholder="Search the scratchpad…"- value={searchText}- onChange={(event) => setSearchText(event.target.value)}- size="2"- className="min-w-[14rem] flex-1"- >- <TextField.Slot>- <MagnifyingGlassIcon size={14} className="text-gray-10" />- </TextField.Slot>- </TextField.Root>- <SegmentedControl.Root- value={grouping}- size="1"- onValueChange={(value) =>- setGrouping(value as ScratchpadGrouping)+ {isLoading ? (+ <div className="flex flex-col gap-2">+ {[0, 1, 2].map((row) => (+ <Skeleton key={row} className="h-14 w-full" />+ ))}+ </div>+ ) : isError && entries === undefined ? (+ <Empty className="py-10">+ <EmptyHeader>+ <EmptyDescription>+ Couldn't load these notes. PostHog may be unavailable, or this+ project may not be set up for agents yet.+ </EmptyDescription>+ </EmptyHeader>+ <EmptyContent>+ <Button+ type="button"+ variant="outline"+ size="sm"+ onClick={() => refetch()}+ >+ Retry+ </Button>+ </EmptyContent>+ </Empty>+ ) : visibleEntries.length === 0 ? (+ <Empty className="py-10">+ <EmptyHeader>+ <EmptyTitle>+ {isSearching+ ? "No notes match your search."+ : "Your agents haven't written anything down yet. As they scan your project, their notes show up here."}+ </EmptyTitle>+ </EmptyHeader>+ </Empty>+ ) : (+ <VirtualCardList+ resetKey={`${grouping}:${searchText}`}+ items={+ grouping === "topic"+ ? groups.flatMap((group): MemoryRow[] => [+ { kind: "topic", group },+ ...(isSearching || expandedTopics[group.namespace]+ ? group.entries.map(+ (entry): MemoryRow => ({ kind: "note", entry }),+ )+ : []),+ ])+ : visibleEntries.map(+ (entry): MemoryRow => ({ kind: "note", entry }),+ )+ }+ getKey={(row) =>+ row.kind === "topic"+ ? `topic:${row.group.namespace}`+ : `note:${row.entry.key}`+ }+ estimateSize={NOTE_CARD_HEIGHT}+ renderItem={(row) =>+ row.kind === "topic" ? (+ <button+ type="button"+ onClick={() =>+ setExpandedTopics((state) => ({+ ...state,+ [row.group.namespace]: !state[row.group.namespace],+ }))+ }+ aria-expanded={+ isSearching || !!expandedTopics[row.group.namespace]}- aria-label="Scratchpad grouping"+ className="flex w-full items-center gap-2 py-2 text-left text-[12px] text-gray-11">- <SegmentedControl.Item value="recent">- <span className="inline-flex items-center gap-1.5">- <ClockIcon size={12} />- Recent- </span>- </SegmentedControl.Item>- <SegmentedControl.Item value="topic">- <span className="inline-flex items-center gap-1.5">- <StackIcon size={12} />- By topic- </span>- </SegmentedControl.Item>- </SegmentedControl.Root>- </Flex>-- <ScratchpadBody- isLoading={isLoading}- isError={isError}- onRetry={() => refetch()}- entries={visibleEntries}- groups={groups}- grouping={grouping}- isSearching={isSearching}- />- </Flex>- </div>- </div>- </Flex>- );-}--function ScratchpadBody({- isLoading,- isError,- onRetry,- entries,- groups,- grouping,- isSearching,-}: {- isLoading: boolean;- isError: boolean;- onRetry: () => void;- entries: ReturnType<typeof filterScratchpadEntries>;- groups: ReturnType<typeof groupScratchpadEntries>;- grouping: ScratchpadGrouping;- isSearching: boolean;-}) {- if (isLoading) {- return (- <Flex direction="column" gap="2">- {[0, 1, 2].map((key) => (- <Box- key={key}- className="h-12 w-full animate-pulse rounded-(--radius-2) bg-(--gray-3)"- />- ))}- </Flex>- );- }-- if (isError) {- return (- <Flex- direction="column"- align="center"- gap="2"- className="rounded-(--radius-2) border border-(--gray-6) border-dashed bg-gray-1 px-4 py-8 text-center text-[12.5px] text-gray-11"- >- <Text className="text-[12.5px] text-gray-11">- Couldn't load the scratchpad. The scout API may be unavailable or- this project may not be enrolled yet.- </Text>- <button- type="button"- onClick={onRetry}- className="rounded-(--radius-2) border border-(--gray-7) px-2.5 py-1 text-[12px] text-gray-11 transition-colors hover:bg-(--gray-3)"- >- Retry- </button>- </Flex>- );- }-- if (entries.length === 0) {- return (- <Box className="rounded-(--radius-2) border border-(--gray-6) border-dashed bg-gray-1 px-4 py-8 text-center text-[12.5px] text-gray-11">- {isSearching- ? "No notes match your search."- : "Your scouts haven't jotted anything down yet. As they scan your project, their notes show up here."}- </Box>- );- }-- if (grouping === "topic") {- return (- <Flex direction="column" gap="3">- {groups.map((group) => (- <ScratchpadTopicGroup- key={group.namespace}- label={group.label}- entries={group.entries}- // A search forces every matching topic open so results stay visible- // without a click.- forceOpen={isSearching}- />- ))}- </Flex>- );- }-- return (- <Flex direction="column" gap="2">- {entries.map((entry) => (- <ScratchpadEntryCard key={entry.key} entry={entry} />- ))}- </Flex>- );-}--function ScratchpadTopicGroup({- label,- entries,- forceOpen,-}: {- label: string;- entries: ReturnType<typeof filterScratchpadEntries>;- forceOpen: boolean;-}) {- // Collapsed by default for a high-level scan; a search forces it open.- const [expanded, setExpanded] = useState(false);- const isExpanded = forceOpen || expanded;-- return (- <Flex direction="column" gap="2">- <button- type="button"- onClick={() => setExpanded((value) => !value)}- aria-expanded={isExpanded}- className="flex items-center gap-2 text-left"- >- <CaretDownIcon- size={14}- className={`shrink-0 text-gray-9 transition-transform ${isExpanded ? "" : "-rotate-90"}`}+ <CaretDownIcon+ size={14}+ className={+ isSearching || expandedTopics[row.group.namespace]+ ? ""+ : "-rotate-90"+ }+ />+ {row.group.label} · {row.group.entries.length} notes+ </button>+ ) : (+ <ScratchpadEntryCard+ entry={row.entry}+ expanded={expandedNotes[row.entry.key] ?? false}+ onExpandedChange={(value) =>+ setExpandedNotes((state) => ({+ ...state,+ [row.entry.key]: value,+ }))+ }+ />+ )+ }/>- <Text className="font-medium text-[12px] text-gray-11 uppercase tracking-wide">- {label}- </Text>- <Text className="text-[11px] text-gray-10">- {entries.length} note{entries.length === 1 ? "" : "s"}- </Text>- </button>- {isExpanded- ? entries.map((entry) => (- <ScratchpadEntryCard key={entry.key} entry={entry} />- ))- : null}- </Flex>+ )}+ </div>);}++type MemoryRow =+ | { kind: "topic"; group: ReturnType<typeof groupScratchpadEntries>[number] }+ | { kind: "note"; entry: ScoutScratchpadEntry };diff --git a/products/desktop/packages/ui/src/features/scouts/components/VirtualCardList.tsx b/products/desktop/packages/ui/src/features/scouts/components/VirtualCardList.tsxnew file mode 100644index 000000000000..3e1e9858bd27--- /dev/null+++ b/products/desktop/packages/ui/src/features/scouts/components/VirtualCardList.tsx@@ -0,0 +1,68 @@+import { useVirtualizer } from "@tanstack/react-virtual";+import { type ReactNode, useLayoutEffect, useRef } from "react";++const OVERSCAN = 6;++/**+ * A scrolling column of cards that renders only what is in view. The signal and+ * memory lists hold hundreds of cards, each one a rendered markdown note, so+ * drawing them all freezes the screen for about a second when the page opens.+ */+export function VirtualCardList<T>({+ items,+ getKey,+ renderItem,+ estimateSize,+ gap = 8,+ resetKey,+}: {+ items: T[];+ getKey: (item: T, index: number) => string;+ renderItem: (item: T, index: number) => ReactNode;+ /** First guess at a card's height; each card measures itself once it renders. */+ estimateSize: number;+ gap?: number;+ resetKey?: string;+}) {+ const viewportRef = useRef<HTMLDivElement>(null);+ const virtualizer = useVirtualizer({+ count: items.length,+ getScrollElement: () => viewportRef.current,+ estimateSize: () => estimateSize,+ getItemKey: (index) => {+ const item = items[index];+ return item === undefined ? index : getKey(item, index);+ },+ overscan: OVERSCAN,+ gap,+ });++ useLayoutEffect(() => {+ if (resetKey !== undefined) virtualizer.scrollToOffset(0);+ }, [resetKey, virtualizer]);++ return (+ <div ref={viewportRef} className="min-h-0 flex-1 overflow-y-auto">+ <div+ className="relative w-full"+ style={{ height: virtualizer.getTotalSize() }}+ >+ {virtualizer.getVirtualItems().map((virtualItem) => {+ const item = items[virtualItem.index];+ if (item === undefined) return null;+ return (+ <div+ key={virtualItem.key}+ ref={virtualizer.measureElement}+ data-index={virtualItem.index}+ className="absolute top-0 left-0 w-full"+ style={{ transform: `translateY(${virtualItem.start}px)` }}+ >+ {renderItem(item, virtualItem.index)}+ </div>+ );+ })}+ </div>+ </div>+ );+}diff --git a/products/desktop/packages/ui/src/features/scouts/hooks/scoutQueryKeys.ts b/products/desktop/packages/ui/src/features/scouts/hooks/scoutQueryKeys.tsindex a865b4845c63..21b020e0130d 100644--- a/products/desktop/packages/ui/src/features/scouts/hooks/scoutQueryKeys.ts+++ b/products/desktop/packages/ui/src/features/scouts/hooks/scoutQueryKeys.ts@@ -6,6 +6,8 @@ export const scoutQueryKeys = {runs: (projectId: number | null) => ["scouts", "runs", projectId] as const,skillCreators: (projectId: number | null) =>["scouts", "skillCreators", projectId] as const,+ suggestions: (projectId: number | null) =>+ ["scouts", "suggestions", projectId] as const,scratchpad: (projectId: number | null) =>["scouts", "scratchpad", projectId] as const,emissions: (projectId: number | null, runIds: string[]) =>diff --git a/products/desktop/packages/ui/src/features/scouts/hooks/useScoutChatTask.test.tsx b/products/desktop/packages/ui/src/features/scouts/hooks/useScoutChatTask.test.tsxindex 84254aadecf8..68ec23fa118c 100644--- a/products/desktop/packages/ui/src/features/scouts/hooks/useScoutChatTask.test.tsx+++ b/products/desktop/packages/ui/src/features/scouts/hooks/useScoutChatTask.test.tsx@@ -1,5 +1,5 @@import { QueryClient, QueryClientProvider } from "@tanstack/react-query";-import { renderHook } from "@testing-library/react";+import { act, renderHook } from "@testing-library/react";import type { ReactNode } from "react";import { beforeEach, describe, expect, it, vi } from "vitest";@@ -128,3 +128,26 @@ describe("useScoutChatTask", () => {expect(input.githubUserIntegrationId).toBe("ghu_1");});});++describe("scout task result", () => {+ it.each([true, false])(+ "returns task creation success: %s",+ async (success) => {+ createTask.mockResolvedValueOnce({ success, task: { id: "task-1" } });+ const { result } = renderHook(+ () =>+ useScoutChatTask({+ prompt: "Create a test agent",+ taskLabel: "agent",+ loggerScope: "test",+ chatType: "author_scout",+ surface: "fleet_list",+ }),+ { wrapper: createWrapper() },+ );+ await act(async () => {+ expect(await result.current.runTask()).toBe(success);+ });+ },+ );+});diff --git a/products/desktop/packages/ui/src/features/scouts/hooks/useScoutChatTask.ts b/products/desktop/packages/ui/src/features/scouts/hooks/useScoutChatTask.tsindex 52732d888329..648e305bbb44 100644--- a/products/desktop/packages/ui/src/features/scouts/hooks/useScoutChatTask.ts+++ b/products/desktop/packages/ui/src/features/scouts/hooks/useScoutChatTask.ts@@ -30,7 +30,7 @@ interface UseScoutChatTaskOptions {interface UseScoutChatTaskReturn {/** Create the auto-mode scout chat task and navigate to it on success. */- runTask: () => Promise<void>;+ runTask: () => Promise<boolean>;/** True while the task is being created. */isRunning: boolean;}@@ -108,7 +108,7 @@ export function useScoutChatTask({surface,...(skillName ? { skill_name: skillName } : {}),});- await run();+ return await run();}, [run, chatType, surface, skillName]);return { runTask, isRunning };diff --git a/products/desktop/packages/ui/src/features/scouts/hooks/useScoutConfigs.ts b/products/desktop/packages/ui/src/features/scouts/hooks/useScoutConfigs.tsindex 9a2577cc8ba7..cc9aeba567cc 100644--- a/products/desktop/packages/ui/src/features/scouts/hooks/useScoutConfigs.ts+++ b/products/desktop/packages/ui/src/features/scouts/hooks/useScoutConfigs.ts@@ -1,17 +1,32 @@import type { ScoutConfig } from "@posthog/api-client/posthog-client";import { useAuthenticatedQuery } from "@posthog/ui/hooks/useAuthenticatedQuery";+import {+ readQuerySnapshot,+ useWriteQuerySnapshot,+} from "@posthog/ui/hooks/useQuerySnapshot";import { useAuthStateValue } from "../../auth/store";import { scoutQueryKeys } from "./scoutQueryKeys";export function useScoutConfigs() {const projectId = useAuthStateValue((state) => state.currentProjectId);- return useAuthenticatedQuery<ScoutConfig[]>(+ const snapshot = `scouts.configs.${projectId ?? "none"}`;+ const query = useAuthenticatedQuery<ScoutConfig[]>(scoutQueryKeys.configs(projectId),(client) =>projectId ? client.listScoutConfigs(projectId) : Promise.resolve([]),// Polled like the sibling runs query: the inactivity sweep and the failure// breaker move `status` with no client involvement, so a fleet page left// open would otherwise show a stale lifecycle until it regained focus.- { enabled: !!projectId, staleTime: 30_000, refetchInterval: 60_000 },+ // The snapshot paints the last known fleet at once; `0` marks it stale, so+ // a refresh always follows it.+ {+ enabled: !!projectId,+ staleTime: 30_000,+ refetchInterval: 60_000,+ initialData: () => readQuerySnapshot<ScoutConfig[]>(snapshot),+ initialDataUpdatedAt: 0,+ },);+ useWriteQuerySnapshot(snapshot, query.data, !query.isFetching);+ return query;}diff --git a/products/desktop/packages/ui/src/features/scouts/hooks/useScoutDeepLink.ts b/products/desktop/packages/ui/src/features/scouts/hooks/useScoutDeepLink.tsindex 84c8dfb58dcc..be3c2d647265 100644--- a/products/desktop/packages/ui/src/features/scouts/hooks/useScoutDeepLink.ts+++ b/products/desktop/packages/ui/src/features/scouts/hooks/useScoutDeepLink.ts@@ -1,6 +1,7 @@import { useHostTRPC } from "@posthog/host-router/react";+import { agentsPageActions } from "@posthog/ui/features/agents/agentsPageStore";import { useAuthStateValue } from "@posthog/ui/features/auth/store";-import { navigateToScoutDetail } from "@posthog/ui/router/navigationBridge";+import { openSettings } from "@posthog/ui/features/settings/hooks/useOpenSettings";import { logger } from "@posthog/ui/shell/logger";import { useQuery } from "@tanstack/react-query";import { useSubscription } from "@trpc/tanstack-react-query";@@ -11,7 +12,7 @@ const log = logger.scope("scout-deep-link");/*** Hook that handles scout detail deep links (`<scheme>://scout/{skillSlug}?finding={id}`,* e.g. `posthog-code://…` in production and `posthog-code-dev://…` in local dev)- * and opens the scout detail page, expanding the finding when one is supplied.+ * and opens the agent in Settings, expanding the finding when one is supplied.** Mirrors `useInboxDeepLink`: drains any link that arrived before the renderer* was ready (the main process clears its pending entry on read) and also@@ -37,7 +38,8 @@ export function useScoutDeepLink() {log.info(`Opening scout from deep link: skillSlug=${skillSlug} findingId=${findingId ?? "(none)"}`,);- navigateToScoutDetail(skillSlug, findingId);+ agentsPageActions().openAgent(skillSlug, { findingId });+ openSettings("agents");}, []);useEffect(() => {diff --git a/products/desktop/packages/ui/src/features/scouts/hooks/useScoutFindings.ts b/products/desktop/packages/ui/src/features/scouts/hooks/useScoutFindings.tsdeleted file mode 100644index 03a7a2069c16..000000000000--- a/products/desktop/packages/ui/src/features/scouts/hooks/useScoutFindings.ts+++ /dev/null@@ -1,84 +0,0 @@-import {- buildScoutFindingRows,- mostRecentEmittedRuns,- type ScoutFindingRow,-} from "@posthog/core/scouts/scoutFindings";-import type { ScoutRunsWindow } from "@posthog/core/scouts/scoutRunsWindow";-import { useMemo } from "react";-import { useScoutEmissionReports } from "./useScoutEmissionReports";-import { useScoutRunEmissions } from "./useScoutRunEmissions";-import { useScoutRuns } from "./useScoutRuns";--export interface ScoutFindingsData {- rows: ScoutFindingRow[];- runsWindow: ScoutRunsWindow | undefined;- /** True once the runs window and (if any) emissions have settled at least once. */- hasLoadedOnce: boolean;- /** The runs window load failed — the page has no run set to fetch findings for. */- runsError: boolean;- /** The batched emissions fetch (the page's actual content) failed. */- emissionsError: boolean;- /** A poll/retry of emissions is in flight while a prior set may still be shown. */- emissionsFetching: boolean;- /** Re-run the runs window plus the emissions + report-link batches. */- refetch: () => void;-}--/**- * Fleet-wide findings — the cross-troop counterpart of the per-scout view.- * Reuses the shared {@link useScoutRuns} window, narrows it to recently-emitted- * runs in core, then fetches their findings + report links in two batched- * requests and flattens them into one list the page filters/sorts. The runs- * query is cache-shared with the fleet section, so opening this page never- * double-fetches the window.- */-export function useScoutFindings(): ScoutFindingsData {- const {- data: runsWindow,- isLoading: runsLoading,- isError: runsError,- refetch: refetchRuns,- } = useScoutRuns();-- const emittedRuns = useMemo(- () => mostRecentEmittedRuns(runsWindow?.runs ?? []),- [runsWindow],- );- const runIds = useMemo(- () => emittedRuns.map((run) => run.run_id),- [emittedRuns],- );-- const emissionsQuery = useScoutRunEmissions(runIds);- const reportsQuery = useScoutEmissionReports(runIds);-- const rows = useMemo(- () =>- buildScoutFindingRows(- emissionsQuery.data ?? [],- emittedRuns,- reportsQuery.data ?? [],- ),- [emissionsQuery.data, emittedRuns, reportsQuery.data],- );-- // "Loaded once" distinguishes "not loaded yet" (skeleton) from "loaded, empty".- // With no emitted runs there's nothing to fetch, so the runs load alone settles- // it; otherwise wait for the emissions batch to have fetched at least once.- const hasLoadedOnce =- !runsLoading && (runIds.length === 0 || emissionsQuery.isFetched);-- return {- rows,- runsWindow,- hasLoadedOnce,- runsError,- emissionsError: emissionsQuery.isError,- emissionsFetching: emissionsQuery.isFetching,- refetch: () => {- void refetchRuns();- void emissionsQuery.refetch();- void reportsQuery.refetch();- },- };-}diff --git a/products/desktop/packages/ui/src/features/scouts/hooks/useScoutRecentRuns.ts b/products/desktop/packages/ui/src/features/scouts/hooks/useScoutRecentRuns.tsnew file mode 100644index 000000000000..21e86cd7d778--- /dev/null+++ b/products/desktop/packages/ui/src/features/scouts/hooks/useScoutRecentRuns.ts@@ -0,0 +1,25 @@+import { useAuthenticatedQuery } from "@posthog/ui/hooks/useAuthenticatedQuery";+import { useAuthStateValue } from "../../auth/store";+import { scoutQueryKeys } from "./scoutQueryKeys";++export function useScoutRecentRuns() {+ const projectId = useAuthStateValue((state) => state.currentProjectId);+ return useAuthenticatedQuery(+ [...scoutQueryKeys.runs(projectId), "recent-per-scout"],+ (client) =>+ projectId ? client.listRecentScoutRuns(projectId) : Promise.resolve([]),+ { enabled: !!projectId, staleTime: 30_000, refetchInterval: 60_000 },+ );+}++export function useScoutOutputSummary() {+ const projectId = useAuthStateValue((state) => state.currentProjectId);+ return useAuthenticatedQuery(+ [...scoutQueryKeys.runs(projectId), "output-summary"],+ (client) =>+ projectId+ ? client.getScoutOutputSummary(projectId)+ : Promise.resolve(null),+ { enabled: !!projectId, staleTime: 30_000, refetchInterval: 60_000 },+ );+}diff --git a/products/desktop/packages/ui/src/features/scouts/hooks/useScoutRunNow.ts b/products/desktop/packages/ui/src/features/scouts/hooks/useScoutRunNow.tsnew file mode 100644index 000000000000..3a1c7c4d6ec8--- /dev/null+++ b/products/desktop/packages/ui/src/features/scouts/hooks/useScoutRunNow.ts@@ -0,0 +1,67 @@+import {+ type ScoutConfig,+ ScoutRequestError,+} from "@posthog/api-client/posthog-client";+import type { ScoutSurface } from "@posthog/shared";+import { ANALYTICS_EVENTS } from "@posthog/shared";+import { useAuthenticatedClient } from "@posthog/ui/features/auth/authClient";+import { toast } from "@posthog/ui/primitives/toast";+import { track } from "@posthog/ui/shell/analytics";+import { useQueryClient } from "@tanstack/react-query";+import { useCallback, useState } from "react";+import { useAuthStateValue } from "../../auth/store";+import { scoutQueryKeys } from "./scoutQueryKeys";++function runNowErrorMessage(error: unknown): string {+ if (error instanceof ScoutRequestError) {+ if (error.status === 409) return "This agent is already running.";+ if (error.status === 429) {+ return "This project has reached a run, report, or Signals limit. Try again after the limit resets.";+ }+ if (error.status === 403) {+ return "This project does not permit this run. Check agent settings and your access.";+ }+ }+ return "Couldn't start the run.";+}++/** Queue one run of a scout outside its schedule. */+export function useScoutRunNow(config: ScoutConfig, surface: ScoutSurface) {+ const client = useAuthenticatedClient();+ const queryClient = useQueryClient();+ const projectId = useAuthStateValue((state) => state.currentProjectId);+ const [isStarting, setIsStarting] = useState(false);++ const runNow = useCallback(async () => {+ if (!client || !projectId || isStarting) return;+ setIsStarting(true);+ try {+ await client.runScoutNow(projectId, config.id);+ track(ANALYTICS_EVENTS.SCOUT_ACTION, {+ action_type: "run_now",+ surface,+ skill_name: config.skill_name,+ });+ toast.success("Run started", {+ description: "It shows up under Runs within a minute.",+ });+ void queryClient.invalidateQueries({+ queryKey: scoutQueryKeys.runs(projectId),+ });+ } catch (error: unknown) {+ toast.error(runNowErrorMessage(error));+ } finally {+ setIsStarting(false);+ }+ }, [+ client,+ projectId,+ isStarting,+ config.id,+ config.skill_name,+ surface,+ queryClient,+ ]);++ return { runNow, isStarting };+}diff --git a/products/desktop/packages/ui/src/features/scouts/hooks/useScoutRuns.ts b/products/desktop/packages/ui/src/features/scouts/hooks/useScoutRuns.tsindex 9d0aaa2e22c6..b6a5f088e253 100644--- a/products/desktop/packages/ui/src/features/scouts/hooks/useScoutRuns.ts+++ b/products/desktop/packages/ui/src/features/scouts/hooks/useScoutRuns.ts@@ -3,27 +3,57 @@ import {type ScoutRunsWindow,} from "@posthog/core/scouts/scoutRunsWindow";import { useAuthenticatedQuery } from "@posthog/ui/hooks/useAuthenticatedQuery";+import {+ readQuerySnapshot,+ useWriteQuerySnapshot,+} from "@posthog/ui/hooks/useQuerySnapshot";+import { useQueryClient } from "@tanstack/react-query";import { useAuthStateValue } from "../../auth/store";import { scoutQueryKeys } from "./scoutQueryKeys";/**- * Fleet-wide scout runs from the recent window (newest first), assembled in- * core by walking the backend's 100-row pages. The backend has no per-scout- * filter yet (scouts-ui api gap 1), so per-scout views filter this window- * client-side. `complete` is false if pagination had to stop early.+ * Scope the window to one scout so busy siblings cannot consume its page limit.+ * `complete` is false if pagination had to stop early.+ *+ * A first load publishes the first page as soon as it lands, so the newest runs+ * are on screen after one round trip instead of after the last one. A load over+ * runs already on screen swaps them in one step, so the list never shrinks.*/-export function useScoutRuns() {+export function useScoutRuns(skillName: string) {const projectId = useAuthStateValue((state) => state.currentProjectId);- return useAuthenticatedQuery<ScoutRunsWindow>(- scoutQueryKeys.runs(projectId),- (client) =>- projectId- ? fetchScoutRunsWindow(client, projectId)- : Promise.resolve({ runs: [], complete: true }),+ const queryClient = useQueryClient();+ const queryKey = [...scoutQueryKeys.runs(projectId), skillName];+ const snapshot = `scouts.runs.${projectId ?? "none"}.${skillName}`;+ const query = useAuthenticatedQuery<ScoutRunsWindow>(+ queryKey,+ (client) => {+ if (!projectId) return Promise.resolve({ runs: [], complete: true });+ let published =+ (queryClient.getQueryData<ScoutRunsWindow>(queryKey)?.runs.length ??+ 0) > 0;+ return fetchScoutRunsWindow(+ client,+ projectId,+ new Date(),+ (partial) => {+ // The newest runs sit in the first page. Publishing that one page fills+ // the screen; publishing every page would make each view that reads the+ // window fetch again for each one.+ if (published) return;+ published = true;+ queryClient.setQueryData(queryKey, partial);+ },+ skillName,+ );+ },{enabled: !!projectId,staleTime: 15_000,refetchInterval: 60_000,+ initialData: () => readQuerySnapshot<ScoutRunsWindow>(snapshot),+ initialDataUpdatedAt: 0,},);+ useWriteQuerySnapshot(snapshot, query.data, !query.isFetching);+ return query;}diff --git a/products/desktop/packages/ui/src/features/scouts/hooks/useScoutScratchpad.ts b/products/desktop/packages/ui/src/features/scouts/hooks/useScoutScratchpad.tsindex 3fc2e38b47c9..cf0ca4e640d5 100644--- a/products/desktop/packages/ui/src/features/scouts/hooks/useScoutScratchpad.ts+++ b/products/desktop/packages/ui/src/features/scouts/hooks/useScoutScratchpad.ts@@ -1,5 +1,9 @@import type { ScoutScratchpadEntry } from "@posthog/api-client/posthog-client";import { useAuthenticatedQuery } from "@posthog/ui/hooks/useAuthenticatedQuery";+import {+ readQuerySnapshot,+ useWriteQuerySnapshot,+} from "@posthog/ui/hooks/useQuerySnapshot";import { useAuthStateValue } from "../../auth/store";import { scoutQueryKeys } from "./scoutQueryKeys";@@ -19,7 +23,8 @@ const SCRATCHPAD_FETCH_LIMIT = 500;*/export function useScoutScratchpad() {const projectId = useAuthStateValue((state) => state.currentProjectId);- return useAuthenticatedQuery<ScoutScratchpadEntry[]>(+ const snapshot = `scouts.scratchpad.${projectId ?? "none"}`;+ const query = useAuthenticatedQuery<ScoutScratchpadEntry[]>(scoutQueryKeys.scratchpad(projectId),(client) =>projectId@@ -30,6 +35,10 @@ export function useScoutScratchpad() {{enabled: !!projectId,staleTime: 30_000,+ initialData: () => readQuerySnapshot<ScoutScratchpadEntry[]>(snapshot),+ initialDataUpdatedAt: 0,},);+ useWriteQuerySnapshot(snapshot, query.data, !query.isFetching);+ return query;}diff --git a/products/desktop/packages/ui/src/features/scouts/hooks/useScoutSuggestions.ts b/products/desktop/packages/ui/src/features/scouts/hooks/useScoutSuggestions.tsnew file mode 100644index 000000000000..decca91da680--- /dev/null+++ b/products/desktop/packages/ui/src/features/scouts/hooks/useScoutSuggestions.ts@@ -0,0 +1,74 @@+import type {+ ScoutSuggestionItem,+ ScoutSuggestionSet,+} from "@posthog/api-client/posthog-client";+import { useOptionalAuthenticatedClient } from "@posthog/ui/features/auth/authClient";+import { useAuthenticatedQuery } from "@posthog/ui/hooks/useAuthenticatedQuery";+import { logger } from "@posthog/ui/shell/logger";+import { useQueryClient } from "@tanstack/react-query";+import { useCallback } from "react";+import { useAuthStateValue } from "../../auth/store";+import { scoutQueryKeys } from "./scoutQueryKeys";++const log = logger.scope("scout-suggestions");++const EMPTY_SET: ScoutSuggestionSet = {+ status: "empty",+ generated_at: null,+ model: "",+ fleet_snapshot: [],+ items: [],+};++/**+ * The pre-computed batch of agents worth adding to this project. A coordinator+ * refreshes it on its own schedule, so this is a plain read: nothing here waits+ * on a model, and a project with no batch reads as an empty list.+ */+export function useScoutSuggestions() {+ const projectId = useAuthStateValue((state) => state.currentProjectId);+ return useAuthenticatedQuery<ScoutSuggestionSet>(+ scoutQueryKeys.suggestions(projectId),+ (client) =>+ projectId+ ? client.listScoutSuggestions(projectId)+ : Promise.resolve(EMPTY_SET),+ { enabled: !!projectId, staleTime: 5 * 60_000 },+ );+}++/**+ * Take a suggestion off the list. Acting on one and passing on it both end with+ * it gone, so the card leaves at once and the server catches up. A failed write+ * is not worth a toast: the batch is a recommendation, and the next refresh+ * settles it either way.+ */+export function useDismissScoutSuggestion(): (+ item: ScoutSuggestionItem,+) => void {+ const projectId = useAuthStateValue((state) => state.currentProjectId);+ const client = useOptionalAuthenticatedClient();+ const queryClient = useQueryClient();++ return useCallback(+ (item: ScoutSuggestionItem) => {+ queryClient.setQueryData<ScoutSuggestionSet>(+ scoutQueryKeys.suggestions(projectId),+ (set) =>+ set+ ? { ...set, items: set.items.filter((one) => one.id !== item.id) }+ : set,+ );+ if (!client || !projectId) return;+ void client+ .dismissScoutSuggestion(projectId, item.id)+ .catch((error: unknown) => {+ log.warn("Dismissing a scout suggestion failed", {+ suggestionId: item.id,+ error,+ });+ });+ },+ [client, projectId, queryClient],+ );+}diff --git a/products/desktop/packages/ui/src/features/scouts/hooks/useTrackFleetViewed.ts b/products/desktop/packages/ui/src/features/scouts/hooks/useTrackFleetViewed.tsnew file mode 100644index 000000000000..813131d2656b--- /dev/null+++ b/products/desktop/packages/ui/src/features/scouts/hooks/useTrackFleetViewed.ts@@ -0,0 +1,39 @@+import type { ScoutConfig } from "@posthog/api-client/posthog-client";+import { getScoutOrigin } from "@posthog/core/scouts/scoutPresentation";+import type { ScoutFleetSyncOutcome } from "@posthog/shared";+import { ANALYTICS_EVENTS } from "@posthog/shared";+import { track } from "@posthog/ui/shell/analytics";+import { useEffect, useRef } from "react";+import { useAuthStateValue } from "../../auth/store";++export function useTrackFleetViewed(+ configs: ScoutConfig[] | undefined,+ syncOutcome: ScoutFleetSyncOutcome | null,+ ready = true,+) {+ const projectId = useAuthStateValue((state) => state.currentProjectId);+ const tracked = useRef<number | null>(null);+ useEffect(() => {+ // Wait for the sync to settle, so a fleet the sync is about to change is+ // never reported against an outcome the request has not reached yet.+ if (+ !projectId ||+ tracked.current === projectId ||+ syncOutcome === null ||+ !ready ||+ !configs+ )+ return;+ tracked.current = projectId;+ track(ANALYTICS_EVENTS.SCOUT_FLEET_VIEWED, {+ scout_count: configs.length,+ enabled_count: configs.filter((config) => config.enabled).length,+ dry_run_count: configs.filter((config) => !config.emit).length,+ custom_count: configs.filter(+ (config) => getScoutOrigin(config) === "custom",+ ).length,+ is_empty: configs.length === 0,+ sync_outcome: syncOutcome,+ });+ }, [configs, syncOutcome, ready, projectId]);+}diff --git a/products/desktop/packages/ui/src/features/settings/components/SettingsPageContent.tsx b/products/desktop/packages/ui/src/features/settings/components/SettingsPageContent.tsxindex ac4afcca7496..36e8168a7d01 100644--- a/products/desktop/packages/ui/src/features/settings/components/SettingsPageContent.tsx+++ b/products/desktop/packages/ui/src/features/settings/components/SettingsPageContent.tsx@@ -59,7 +59,11 @@ const SETTINGS_PAGES: Record<SettingsCategory, SettingsPageDefinition> = {"Environments",EnvironmentsSettings,),- agents: defineSettingsPage("Agents", AgentsSettings),+ agents: defineSettingsPage(+ "Agents",+ AgentsSettings,+ SETTINGS_PAGE_LAYOUT.FULL_BLEED,+ ),"task-agent-defaults": defineSettingsPage("Model", TaskAgentDefaultsSettings),skills: defineSettingsPage("Skills",diff --git a/products/desktop/packages/ui/src/features/settings/sections/AgentsSettings.tsx b/products/desktop/packages/ui/src/features/settings/sections/AgentsSettings.tsxindex 459e1fbdac8d..ea963bbca4db 100644--- a/products/desktop/packages/ui/src/features/settings/sections/AgentsSettings.tsx+++ b/products/desktop/packages/ui/src/features/settings/sections/AgentsSettings.tsx@@ -1,5 +1,5 @@-import { ConfigureAgentsSection } from "@posthog/ui/features/inbox/components/ConfigureAgentsSection";+import { AgentsView } from "@posthog/ui/features/agents/components/AgentsView";export function AgentsSettings() {- return <ConfigureAgentsSection />;+ return <AgentsView />;}diff --git a/products/desktop/packages/ui/src/features/sidebar/components/SidebarNavSection.test.tsx b/products/desktop/packages/ui/src/features/sidebar/components/SidebarNavSection.test.tsxindex 05af51bd3b01..bea87e5952dc 100644--- a/products/desktop/packages/ui/src/features/sidebar/components/SidebarNavSection.test.tsx+++ b/products/desktop/packages/ui/src/features/sidebar/components/SidebarNavSection.test.tsx@@ -16,7 +16,6 @@ const {track,useAppView,navigateToInbox,- navigateToAgents,navigateToSkills,navigateToMcpServers,navigateToCommandCenter,@@ -28,7 +27,6 @@ const {track: vi.fn(),useAppView: vi.fn(),navigateToInbox: vi.fn(),- navigateToAgents: vi.fn(),navigateToSkills: vi.fn(),navigateToMcpServers: vi.fn(),navigateToCommandCenter: vi.fn(),@@ -65,7 +63,6 @@ vi.mock("@posthog/ui/features/canvas/hooks/useChannelsLayout", () => ({}));vi.mock("@posthog/ui/router/navigationBridge", () => ({navigateToActivity,- navigateToAgents,navigateToCommandCenter,navigateToContext: vi.fn(),navigateToInbox,diff --git a/products/desktop/packages/ui/src/hooks/useMinuteNow.ts b/products/desktop/packages/ui/src/hooks/useMinuteNow.tsnew file mode 100644index 000000000000..94858c1c8dc2--- /dev/null+++ b/products/desktop/packages/ui/src/hooks/useMinuteNow.ts@@ -0,0 +1,19 @@+import { useEffect, useState } from "react";++const MINUTE_MS = 60_000;++/**+ * The current time, changing once a minute. Lists that show "next run in 3m"+ * need a `now`, and `new Date()` in the render body gives every scroll frame a+ * new one, which re-does the work of every visible row.+ */+export function useMinuteNow(): Date {+ const [now, setNow] = useState(() => new Date());++ useEffect(() => {+ const timer = setInterval(() => setNow(new Date()), MINUTE_MS);+ return () => clearInterval(timer);+ }, []);++ return now;+}diff --git a/products/desktop/packages/ui/src/hooks/useQuerySnapshot.ts b/products/desktop/packages/ui/src/hooks/useQuerySnapshot.tsnew file mode 100644index 000000000000..b7fe3aecd861--- /dev/null+++ b/products/desktop/packages/ui/src/hooks/useQuerySnapshot.ts@@ -0,0 +1,53 @@+import { useEffect } from "react";++const PREFIX = "posthog.query-snapshot.v1.";++const MAX_SNAPSHOTS = 12;+const snapshots = new Map<string, unknown>();++/**+ * Keep project content in memory so that it never reaches plaintext disk storage.+ * Query observers share references to avoid serialization during a render.+ */+export function readQuerySnapshot<T>(name: string): T | undefined {+ return snapshots.get(name) as T | undefined;+}++function writeQuerySnapshot(name: string, value: unknown): void {+ if (snapshots.get(name) === value) return;+ snapshots.delete(name);+ snapshots.set(name, value);+ if (snapshots.size > MAX_SNAPSHOTS) {+ const oldest = snapshots.keys().next().value;+ if (oldest !== undefined) snapshots.delete(oldest);+ }+}++/** Snapshots hold project data, so a sign-out must drop them. */+export function clearQuerySnapshots(): void {+ snapshots.clear();+ try {+ for (const key of Object.keys(localStorage)) {+ if (key.startsWith(PREFIX)) localStorage.removeItem(key);+ }+ } catch {+ // Storage can be unavailable when the host denies access.+ }+}++// Remove plaintext snapshots from older builds without reading project content.+clearQuerySnapshots();++/**+ * Wait for pagination to settle so that later visits start with the full result.+ */+export function useWriteQuerySnapshot(+ name: string,+ data: unknown,+ settled: boolean,+): void {+ useEffect(() => {+ if (!settled || data === undefined) return;+ writeQuerySnapshot(name, data);+ }, [name, data, settled]);+}diff --git a/products/desktop/packages/ui/src/primitives/SearchInput.tsx b/products/desktop/packages/ui/src/primitives/SearchInput.tsxnew file mode 100644index 000000000000..583dc9884e7a--- /dev/null+++ b/products/desktop/packages/ui/src/primitives/SearchInput.tsx@@ -0,0 +1,39 @@+import { MagnifyingGlassIcon } from "@phosphor-icons/react";+import { Input } from "@posthog/quill";++/** A search field with the glass on the left. One offset, one height, one place. */+export function SearchInput({+ value,+ onValueChange,+ placeholder,+ ariaLabel,+ onBlur,+ className = "w-64",+}: {+ value: string;+ onValueChange: (value: string) => void;+ placeholder: string;+ /** Defaults to the placeholder, which reads the same to a screen reader. */+ ariaLabel?: string;+ onBlur?: () => void;+ /** The width of the field. */+ className?: string;+}) {+ return (+ <div className={`relative ${className}`}>+ <MagnifyingGlassIcon+ size={13}+ className="-translate-y-1/2 pointer-events-none absolute top-1/2 left-2.5 text-gray-10"+ />+ <Input+ type="search"+ value={value}+ onChange={(event) => onValueChange(event.target.value)}+ onBlur={onBlur}+ placeholder={placeholder}+ aria-label={ariaLabel ?? placeholder}+ className="h-8 pl-7"+ />+ </div>+ );+}diff --git a/products/desktop/packages/ui/src/primitives/TabStrip.tsx b/products/desktop/packages/ui/src/primitives/TabStrip.tsxnew file mode 100644index 000000000000..13c4059f244a--- /dev/null+++ b/products/desktop/packages/ui/src/primitives/TabStrip.tsx@@ -0,0 +1,36 @@+import { Tabs, TabsList, TabsTrigger } from "@posthog/quill";++/** An underlined tab strip, on the design system's own sizing. */+export function TabStrip<T extends string>({+ tabs,+ value,+ onValueChange,+ dataAttrPrefix,+ className,+}: {+ tabs: readonly { key: T; label: string }[];+ value: T;+ onValueChange: (tab: T) => void;+ dataAttrPrefix: string;+ className?: string;+}) {+ return (+ <Tabs+ value={value}+ className={className}+ onValueChange={(next: string) => onValueChange(next as T)}+ >+ <TabsList variant="line">+ {tabs.map(({ key, label }) => (+ <TabsTrigger+ key={key}+ value={key}+ data-attr={`${dataAttrPrefix}-${key}`}+ >+ {label}+ </TabsTrigger>+ ))}+ </TabsList>+ </Tabs>+ );+}diff --git a/products/desktop/packages/ui/src/router/navigationBridge.ts b/products/desktop/packages/ui/src/router/navigationBridge.tsindex f6dbe4e0e8af..7f43a27dce1d 100644--- a/products/desktop/packages/ui/src/router/navigationBridge.ts+++ b/products/desktop/packages/ui/src/router/navigationBridge.ts@@ -181,21 +181,6 @@ export function navigateToChannelReportDetail(});}-export function navigateToScoutDetail(- skillSlug: string,- findingId?: string,-): void {- void getRouterOrNull()?.navigate({- to: "/agents/scouts/$skillName",- params: { skillName: skillSlug },- search: findingId ? { finding: findingId } : {},- });-}--export function navigateToScoutFindings(): void {- void getRouterOrNull()?.navigate({ to: "/agents/scouts/findings" });-}-export function navigateToLoops(options?: { ignoreBlocker?: boolean }): void {void getRouterOrNull()?.navigate({to: "/loops",@@ -219,10 +204,6 @@ export function navigateToLoopDetail(});}-export function navigateToAgents(): void {- void getRouterOrNull()?.navigate({ to: "/agents" });-}-export function navigateToArchived(): void {void getRouterOrNull()?.navigate({ to: "/archived" });}diff --git a/products/desktop/packages/ui/src/router/routeTree.gen.ts b/products/desktop/packages/ui/src/router/routeTree.gen.tsindex 330cf25cc80c..7aac9eb6bf40 100644--- a/products/desktop/packages/ui/src/router/routeTree.gen.ts+++ b/products/desktop/packages/ui/src/router/routeTree.gen.ts@@ -14,13 +14,12 @@ import { Route as PrRouteImport } from './routes/pr'import { Route as InboxRouteImport } from './routes/inbox'import { Route as ContextRouteImport } from './routes/context'import { Route as ArchivedRouteImport } from './routes/archived'-import { Route as AgentsRouteImport } from './routes/agents'import { Route as ShellRouteImport } from './routes/_shell'import { Route as WebsiteIndexRouteImport } from './routes/website.index'import { Route as LoopsIndexRouteImport } from './routes/loops/index'import { Route as InboxIndexRouteImport } from './routes/inbox/index'import { Route as CodeIndexRouteImport } from './routes/code.index'-import { Route as AgentsIndexRouteImport } from './routes/agents/index'+import { Route as AgentsIndexRouteImport } from './routes/agents.index'import { Route as ShellIndexRouteImport } from './routes/_shell/index'import { Route as WebsiteSplatRouteImport } from './routes/website.$'import { Route as TasksTaskIdRouteImport } from './routes/tasks/$taskId'@@ -33,7 +32,7 @@ import { Route as InboxDismissedRouteImport } from './routes/inbox/dismissed'import { Route as InboxAgentsRouteImport } from './routes/inbox/agents'import { Route as FoldersFolderIdRouteImport } from './routes/folders/$folderId'import { Route as CodeSplatRouteImport } from './routes/code.$'-import { Route as AgentsScoutsRouteImport } from './routes/agents/scouts'+import { Route as AgentsSplatRouteImport } from './routes/agents.$'import { Route as ShellSkillsRouteImport } from './routes/_shell/skills'import { Route as ShellNewRouteImport } from './routes/_shell/new'import { Route as ShellMcpServersRouteImport } from './routes/_shell/mcp-servers'@@ -45,7 +44,6 @@ import { Route as InboxRunsIndexRouteImport } from './routes/inbox/runs.index'import { Route as InboxReportsIndexRouteImport } from './routes/inbox/reports.index'import { Route as InboxPullsIndexRouteImport } from './routes/inbox/pulls.index'import { Route as InboxDismissedIndexRouteImport } from './routes/inbox/dismissed.index'-import { Route as AgentsScoutsIndexRouteImport } from './routes/agents/scouts.index'import { Route as ShellSpacesIndexRouteImport } from './routes/_shell/spaces/index'import { Route as ShellSettingsIndexRouteImport } from './routes/_shell/settings/index'import { Route as ShellFeedsIndexRouteImport } from './routes/_shell/feeds/index'@@ -54,13 +52,9 @@ import { Route as InboxRunsReportIdRouteImport } from './routes/inbox/runs.$repoimport { Route as InboxReportsReportIdRouteImport } from './routes/inbox/reports.$reportId'import { Route as InboxPullsReportIdRouteImport } from './routes/inbox/pulls.$reportId'import { Route as InboxDismissedReportIdRouteImport } from './routes/inbox/dismissed.$reportId'-import { Route as AgentsScoutsScratchpadRouteImport } from './routes/agents/scouts.scratchpad'-import { Route as AgentsScoutsFindingsRouteImport } from './routes/agents/scouts.findings'-import { Route as AgentsScoutsSkillNameRouteImport } from './routes/agents/scouts.$skillName'import { Route as ShellSpacesContextRouteImport } from './routes/_shell/spaces/context'import { Route as ShellSettingsCategoryRouteImport } from './routes/_shell/settings/$category'import { Route as ShellFeedsFeedIdRouteImport } from './routes/_shell/feeds/$feedId'-import { Route as AgentsScoutsSkillNameIndexRouteImport } from './routes/agents/scouts.$skillName.index'import { Route as ShellSpacesChannelIdIndexRouteImport } from './routes/_shell/spaces/$channelId/index'import { Route as ShellSpacesChannelIdNewRouteImport } from './routes/_shell/spaces/$channelId/new'import { Route as ShellSpacesChannelIdLoopsRouteImport } from './routes/_shell/spaces/$channelId/loops'@@ -97,11 +91,6 @@ const ArchivedRoute = ArchivedRouteImport.update({path: '/archived',getParentRoute: () => rootRouteImport,} as any)-const AgentsRoute = AgentsRouteImport.update({- id: '/agents',- path: '/agents',- getParentRoute: () => rootRouteImport,-} as any)const ShellRoute = ShellRouteImport.update({id: '/_shell',getParentRoute: () => rootRouteImport,@@ -127,9 +116,9 @@ const CodeIndexRoute = CodeIndexRouteImport.update({getParentRoute: () => rootRouteImport,} as any)const AgentsIndexRoute = AgentsIndexRouteImport.update({- id: '/',- path: '/',- getParentRoute: () => AgentsRoute,+ id: '/agents/',+ path: '/agents/',+ getParentRoute: () => rootRouteImport,} as any)const ShellIndexRoute = ShellIndexRouteImport.update({id: '/',@@ -191,10 +180,10 @@ const CodeSplatRoute = CodeSplatRouteImport.update({path: '/code/$',getParentRoute: () => rootRouteImport,} as any)-const AgentsScoutsRoute = AgentsScoutsRouteImport.update({- id: '/scouts',- path: '/scouts',- getParentRoute: () => AgentsRoute,+const AgentsSplatRoute = AgentsSplatRouteImport.update({+ id: '/agents/$',+ path: '/agents/$',+ getParentRoute: () => rootRouteImport,} as any)const ShellSkillsRoute = ShellSkillsRouteImport.update({id: '/skills',@@ -251,11 +240,6 @@ const InboxDismissedIndexRoute = InboxDismissedIndexRouteImport.update({path: '/',getParentRoute: () => InboxDismissedRoute,} as any)-const AgentsScoutsIndexRoute = AgentsScoutsIndexRouteImport.update({- id: '/',- path: '/',- getParentRoute: () => AgentsScoutsRoute,-} as any)const ShellSpacesIndexRoute = ShellSpacesIndexRouteImport.update({id: '/spaces/',path: '/spaces/',@@ -296,21 +280,6 @@ const InboxDismissedReportIdRoute = InboxDismissedReportIdRouteImport.update({path: '/$reportId',getParentRoute: () => InboxDismissedRoute,} as any)-const AgentsScoutsScratchpadRoute = AgentsScoutsScratchpadRouteImport.update({- id: '/scratchpad',- path: '/scratchpad',- getParentRoute: () => AgentsScoutsRoute,-} as any)-const AgentsScoutsFindingsRoute = AgentsScoutsFindingsRouteImport.update({- id: '/findings',- path: '/findings',- getParentRoute: () => AgentsScoutsRoute,-} as any)-const AgentsScoutsSkillNameRoute = AgentsScoutsSkillNameRouteImport.update({- id: '/$skillName',- path: '/$skillName',- getParentRoute: () => AgentsScoutsRoute,-} as any)const ShellSpacesContextRoute = ShellSpacesContextRouteImport.update({id: '/spaces/context',path: '/spaces/context',@@ -326,12 +295,6 @@ const ShellFeedsFeedIdRoute = ShellFeedsFeedIdRouteImport.update({path: '/feeds/$feedId',getParentRoute: () => ShellRoute,} as any)-const AgentsScoutsSkillNameIndexRoute =- AgentsScoutsSkillNameIndexRouteImport.update({- id: '/',- path: '/',- getParentRoute: () => AgentsScoutsSkillNameRoute,- } as any)const ShellSpacesChannelIdIndexRoute =ShellSpacesChannelIdIndexRouteImport.update({id: '/spaces/$channelId/',@@ -394,7 +357,6 @@ const ShellSpacesChannelIdDashboardsDashboardIdRoute =export interface FileRoutesByFullPath {'/': typeof ShellIndexRoute- '/agents': typeof AgentsRouteWithChildren'/archived': typeof ArchivedRoute'/context': typeof ContextRoute'/inbox': typeof InboxRouteWithChildren@@ -406,7 +368,7 @@ export interface FileRoutesByFullPath {'/mcp-servers': typeof ShellMcpServersRoute'/new': typeof ShellNewRoute'/skills': typeof ShellSkillsRoute- '/agents/scouts': typeof AgentsScoutsRouteWithChildren+ '/agents/$': typeof AgentsSplatRoute'/code/$': typeof CodeSplatRoute'/folders/$folderId': typeof FoldersFolderIdRoute'/inbox/agents': typeof InboxAgentsRoute@@ -426,9 +388,6 @@ export interface FileRoutesByFullPath {'/feeds/$feedId': typeof ShellFeedsFeedIdRoute'/settings/$category': typeof ShellSettingsCategoryRoute'/spaces/context': typeof ShellSpacesContextRoute- '/agents/scouts/$skillName': typeof AgentsScoutsSkillNameRouteWithChildren- '/agents/scouts/findings': typeof AgentsScoutsFindingsRoute- '/agents/scouts/scratchpad': typeof AgentsScoutsScratchpadRoute'/inbox/dismissed/$reportId': typeof InboxDismissedReportIdRoute'/inbox/pulls/$reportId': typeof InboxPullsReportIdRoute'/inbox/reports/$reportId': typeof InboxReportsReportIdRoute@@ -437,7 +396,6 @@ export interface FileRoutesByFullPath {'/feeds/': typeof ShellFeedsIndexRoute'/settings/': typeof ShellSettingsIndexRoute'/spaces/': typeof ShellSpacesIndexRoute- '/agents/scouts/': typeof AgentsScoutsIndexRoute'/inbox/dismissed/': typeof InboxDismissedIndexRoute'/inbox/pulls/': typeof InboxPullsIndexRoute'/inbox/reports/': typeof InboxReportsIndexRoute@@ -450,7 +408,6 @@ export interface FileRoutesByFullPath {'/spaces/$channelId/loops': typeof ShellSpacesChannelIdLoopsRoute'/spaces/$channelId/new': typeof ShellSpacesChannelIdNewRoute'/spaces/$channelId/': typeof ShellSpacesChannelIdIndexRoute- '/agents/scouts/$skillName/': typeof AgentsScoutsSkillNameIndexRoute'/spaces/$channelId/dashboards/$dashboardId': typeof ShellSpacesChannelIdDashboardsDashboardIdRoute'/spaces/$channelId/reports/$reportId': typeof ShellSpacesChannelIdReportsReportIdRoute'/spaces/$channelId/tasks/$taskId': typeof ShellSpacesChannelIdTasksTaskIdRoute@@ -466,6 +423,7 @@ export interface FileRoutesByTo {'/mcp-servers': typeof ShellMcpServersRoute'/new': typeof ShellNewRoute'/skills': typeof ShellSkillsRoute+ '/agents/$': typeof AgentsSplatRoute'/code/$': typeof CodeSplatRoute'/folders/$folderId': typeof FoldersFolderIdRoute'/inbox/agents': typeof InboxAgentsRoute@@ -481,8 +439,6 @@ export interface FileRoutesByTo {'/feeds/$feedId': typeof ShellFeedsFeedIdRoute'/settings/$category': typeof ShellSettingsCategoryRoute'/spaces/context': typeof ShellSpacesContextRoute- '/agents/scouts/findings': typeof AgentsScoutsFindingsRoute- '/agents/scouts/scratchpad': typeof AgentsScoutsScratchpadRoute'/inbox/dismissed/$reportId': typeof InboxDismissedReportIdRoute'/inbox/pulls/$reportId': typeof InboxPullsReportIdRoute'/inbox/reports/$reportId': typeof InboxReportsReportIdRoute@@ -491,7 +447,6 @@ export interface FileRoutesByTo {'/feeds': typeof ShellFeedsIndexRoute'/settings': typeof ShellSettingsIndexRoute'/spaces': typeof ShellSpacesIndexRoute- '/agents/scouts': typeof AgentsScoutsIndexRoute'/inbox/dismissed': typeof InboxDismissedIndexRoute'/inbox/pulls': typeof InboxPullsIndexRoute'/inbox/reports': typeof InboxReportsIndexRoute@@ -504,7 +459,6 @@ export interface FileRoutesByTo {'/spaces/$channelId/loops': typeof ShellSpacesChannelIdLoopsRoute'/spaces/$channelId/new': typeof ShellSpacesChannelIdNewRoute'/spaces/$channelId': typeof ShellSpacesChannelIdIndexRoute- '/agents/scouts/$skillName': typeof AgentsScoutsSkillNameIndexRoute'/spaces/$channelId/dashboards/$dashboardId': typeof ShellSpacesChannelIdDashboardsDashboardIdRoute'/spaces/$channelId/reports/$reportId': typeof ShellSpacesChannelIdReportsReportIdRoute'/spaces/$channelId/tasks/$taskId': typeof ShellSpacesChannelIdTasksTaskIdRoute@@ -512,7 +466,6 @@ export interface FileRoutesByTo {export interface FileRoutesById {__root__: typeof rootRouteImport'/_shell': typeof ShellRouteWithChildren- '/agents': typeof AgentsRouteWithChildren'/archived': typeof ArchivedRoute'/context': typeof ContextRoute'/inbox': typeof InboxRouteWithChildren@@ -524,7 +477,7 @@ export interface FileRoutesById {'/_shell/mcp-servers': typeof ShellMcpServersRoute'/_shell/new': typeof ShellNewRoute'/_shell/skills': typeof ShellSkillsRoute- '/agents/scouts': typeof AgentsScoutsRouteWithChildren+ '/agents/$': typeof AgentsSplatRoute'/code/$': typeof CodeSplatRoute'/folders/$folderId': typeof FoldersFolderIdRoute'/inbox/agents': typeof InboxAgentsRoute@@ -545,9 +498,6 @@ export interface FileRoutesById {'/_shell/feeds/$feedId': typeof ShellFeedsFeedIdRoute'/_shell/settings/$category': typeof ShellSettingsCategoryRoute'/_shell/spaces/context': typeof ShellSpacesContextRoute- '/agents/scouts/$skillName': typeof AgentsScoutsSkillNameRouteWithChildren- '/agents/scouts/findings': typeof AgentsScoutsFindingsRoute- '/agents/scouts/scratchpad': typeof AgentsScoutsScratchpadRoute'/inbox/dismissed/$reportId': typeof InboxDismissedReportIdRoute'/inbox/pulls/$reportId': typeof InboxPullsReportIdRoute'/inbox/reports/$reportId': typeof InboxReportsReportIdRoute@@ -556,7 +506,6 @@ export interface FileRoutesById {'/_shell/feeds/': typeof ShellFeedsIndexRoute'/_shell/settings/': typeof ShellSettingsIndexRoute'/_shell/spaces/': typeof ShellSpacesIndexRoute- '/agents/scouts/': typeof AgentsScoutsIndexRoute'/inbox/dismissed/': typeof InboxDismissedIndexRoute'/inbox/pulls/': typeof InboxPullsIndexRoute'/inbox/reports/': typeof InboxReportsIndexRoute@@ -569,7 +518,6 @@ export interface FileRoutesById {'/_shell/spaces/$channelId/loops': typeof ShellSpacesChannelIdLoopsRoute'/_shell/spaces/$channelId/new': typeof ShellSpacesChannelIdNewRoute'/_shell/spaces/$channelId/': typeof ShellSpacesChannelIdIndexRoute- '/agents/scouts/$skillName/': typeof AgentsScoutsSkillNameIndexRoute'/_shell/spaces/$channelId/dashboards/$dashboardId': typeof ShellSpacesChannelIdDashboardsDashboardIdRoute'/_shell/spaces/$channelId/reports/$reportId': typeof ShellSpacesChannelIdReportsReportIdRoute'/_shell/spaces/$channelId/tasks/$taskId': typeof ShellSpacesChannelIdTasksTaskIdRoute@@ -578,7 +526,6 @@ export interface FileRouteTypes {fileRoutesByFullPath: FileRoutesByFullPathfullPaths:| '/'- | '/agents'| '/archived'| '/context'| '/inbox'@@ -590,7 +537,7 @@ export interface FileRouteTypes {| '/mcp-servers'| '/new'| '/skills'- | '/agents/scouts'+ | '/agents/$'| '/code/$'| '/folders/$folderId'| '/inbox/agents'@@ -610,9 +557,6 @@ export interface FileRouteTypes {| '/feeds/$feedId'| '/settings/$category'| '/spaces/context'- | '/agents/scouts/$skillName'- | '/agents/scouts/findings'- | '/agents/scouts/scratchpad'| '/inbox/dismissed/$reportId'| '/inbox/pulls/$reportId'| '/inbox/reports/$reportId'@@ -621,7 +565,6 @@ export interface FileRouteTypes {| '/feeds/'| '/settings/'| '/spaces/'- | '/agents/scouts/'| '/inbox/dismissed/'| '/inbox/pulls/'| '/inbox/reports/'@@ -634,7 +577,6 @@ export interface FileRouteTypes {| '/spaces/$channelId/loops'| '/spaces/$channelId/new'| '/spaces/$channelId/'- | '/agents/scouts/$skillName/'| '/spaces/$channelId/dashboards/$dashboardId'| '/spaces/$channelId/reports/$reportId'| '/spaces/$channelId/tasks/$taskId'@@ -650,6 +592,7 @@ export interface FileRouteTypes {| '/mcp-servers'| '/new'| '/skills'+ | '/agents/$'| '/code/$'| '/folders/$folderId'| '/inbox/agents'@@ -665,8 +608,6 @@ export interface FileRouteTypes {| '/feeds/$feedId'| '/settings/$category'| '/spaces/context'- | '/agents/scouts/findings'- | '/agents/scouts/scratchpad'| '/inbox/dismissed/$reportId'| '/inbox/pulls/$reportId'| '/inbox/reports/$reportId'@@ -675,7 +616,6 @@ export interface FileRouteTypes {| '/feeds'| '/settings'| '/spaces'- | '/agents/scouts'| '/inbox/dismissed'| '/inbox/pulls'| '/inbox/reports'@@ -688,14 +628,12 @@ export interface FileRouteTypes {| '/spaces/$channelId/loops'| '/spaces/$channelId/new'| '/spaces/$channelId'- | '/agents/scouts/$skillName'| '/spaces/$channelId/dashboards/$dashboardId'| '/spaces/$channelId/reports/$reportId'| '/spaces/$channelId/tasks/$taskId'id:| '__root__'| '/_shell'- | '/agents'| '/archived'| '/context'| '/inbox'@@ -707,7 +645,7 @@ export interface FileRouteTypes {| '/_shell/mcp-servers'| '/_shell/new'| '/_shell/skills'- | '/agents/scouts'+ | '/agents/$'| '/code/$'| '/folders/$folderId'| '/inbox/agents'@@ -728,9 +666,6 @@ export interface FileRouteTypes {| '/_shell/feeds/$feedId'| '/_shell/settings/$category'| '/_shell/spaces/context'- | '/agents/scouts/$skillName'- | '/agents/scouts/findings'- | '/agents/scouts/scratchpad'| '/inbox/dismissed/$reportId'| '/inbox/pulls/$reportId'| '/inbox/reports/$reportId'@@ -739,7 +674,6 @@ export interface FileRouteTypes {| '/_shell/feeds/'| '/_shell/settings/'| '/_shell/spaces/'- | '/agents/scouts/'| '/inbox/dismissed/'| '/inbox/pulls/'| '/inbox/reports/'@@ -752,7 +686,6 @@ export interface FileRouteTypes {| '/_shell/spaces/$channelId/loops'| '/_shell/spaces/$channelId/new'| '/_shell/spaces/$channelId/'- | '/agents/scouts/$skillName/'| '/_shell/spaces/$channelId/dashboards/$dashboardId'| '/_shell/spaces/$channelId/reports/$reportId'| '/_shell/spaces/$channelId/tasks/$taskId'@@ -760,18 +693,19 @@ export interface FileRouteTypes {}export interface RootRouteChildren {ShellRoute: typeof ShellRouteWithChildren- AgentsRoute: typeof AgentsRouteWithChildrenArchivedRoute: typeof ArchivedRouteContextRoute: typeof ContextRouteInboxRoute: typeof InboxRouteWithChildrenPrRoute: typeof PrRouteUsageRoute: typeof UsageRoute+ AgentsSplatRoute: typeof AgentsSplatRouteCodeSplatRoute: typeof CodeSplatRouteFoldersFolderIdRoute: typeof FoldersFolderIdRouteLoopsLoopIdRoute: typeof LoopsLoopIdRouteWithChildrenLoopsNewRoute: typeof LoopsNewRouteTasksTaskIdRoute: typeof TasksTaskIdRouteWebsiteSplatRoute: typeof WebsiteSplatRoute+ AgentsIndexRoute: typeof AgentsIndexRouteCodeIndexRoute: typeof CodeIndexRouteLoopsIndexRoute: typeof LoopsIndexRouteWebsiteIndexRoute: typeof WebsiteIndexRoute@@ -814,13 +748,6 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof ArchivedRouteImportparentRoute: typeof rootRouteImport}- '/agents': {- id: '/agents'- path: '/agents'- fullPath: '/agents'- preLoaderRoute: typeof AgentsRouteImport- parentRoute: typeof rootRouteImport- }'/_shell': {id: '/_shell'path: ''@@ -858,10 +785,10 @@ declare module '@tanstack/react-router' {}'/agents/': {id: '/agents/'- path: '/'+ path: '/agents'fullPath: '/agents/'preLoaderRoute: typeof AgentsIndexRouteImport- parentRoute: typeof AgentsRoute+ parentRoute: typeof rootRouteImport}'/_shell/': {id: '/_shell/'@@ -947,12 +874,12 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof CodeSplatRouteImportparentRoute: typeof rootRouteImport}- '/agents/scouts': {- id: '/agents/scouts'- path: '/scouts'- fullPath: '/agents/scouts'- preLoaderRoute: typeof AgentsScoutsRouteImport- parentRoute: typeof AgentsRoute+ '/agents/$': {+ id: '/agents/$'+ path: '/agents/$'+ fullPath: '/agents/$'+ preLoaderRoute: typeof AgentsSplatRouteImport+ parentRoute: typeof rootRouteImport}'/_shell/skills': {id: '/_shell/skills'@@ -1031,13 +958,6 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof InboxDismissedIndexRouteImportparentRoute: typeof InboxDismissedRoute}- '/agents/scouts/': {- id: '/agents/scouts/'- path: '/'- fullPath: '/agents/scouts/'- preLoaderRoute: typeof AgentsScoutsIndexRouteImport- parentRoute: typeof AgentsScoutsRoute- }'/_shell/spaces/': {id: '/_shell/spaces/'path: '/spaces'@@ -1094,27 +1014,6 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof InboxDismissedReportIdRouteImportparentRoute: typeof InboxDismissedRoute}- '/agents/scouts/scratchpad': {- id: '/agents/scouts/scratchpad'- path: '/scratchpad'- fullPath: '/agents/scouts/scratchpad'- preLoaderRoute: typeof AgentsScoutsScratchpadRouteImport- parentRoute: typeof AgentsScoutsRoute- }- '/agents/scouts/findings': {- id: '/agents/scouts/findings'- path: '/findings'- fullPath: '/agents/scouts/findings'- preLoaderRoute: typeof AgentsScoutsFindingsRouteImport- parentRoute: typeof AgentsScoutsRoute- }- '/agents/scouts/$skillName': {- id: '/agents/scouts/$skillName'- path: '/$skillName'- fullPath: '/agents/scouts/$skillName'- preLoaderRoute: typeof AgentsScoutsSkillNameRouteImport- parentRoute: typeof AgentsScoutsRoute- }'/_shell/spaces/context': {id: '/_shell/spaces/context'path: '/spaces/context'@@ -1136,13 +1035,6 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof ShellFeedsFeedIdRouteImportparentRoute: typeof ShellRoute}- '/agents/scouts/$skillName/': {- id: '/agents/scouts/$skillName/'- path: '/'- fullPath: '/agents/scouts/$skillName/'- preLoaderRoute: typeof AgentsScoutsSkillNameIndexRouteImport- parentRoute: typeof AgentsScoutsSkillNameRoute- }'/_shell/spaces/$channelId/': {id: '/_shell/spaces/$channelId/'path: '/spaces/$channelId'@@ -1272,50 +1164,6 @@ const ShellRouteChildren: ShellRouteChildren = {const ShellRouteWithChildren = ShellRoute._addFileChildren(ShellRouteChildren)-interface AgentsScoutsSkillNameRouteChildren {- AgentsScoutsSkillNameIndexRoute: typeof AgentsScoutsSkillNameIndexRoute-}--const AgentsScoutsSkillNameRouteChildren: AgentsScoutsSkillNameRouteChildren = {- AgentsScoutsSkillNameIndexRoute: AgentsScoutsSkillNameIndexRoute,-}--const AgentsScoutsSkillNameRouteWithChildren =- AgentsScoutsSkillNameRoute._addFileChildren(- AgentsScoutsSkillNameRouteChildren,- )--interface AgentsScoutsRouteChildren {- AgentsScoutsSkillNameRoute: typeof AgentsScoutsSkillNameRouteWithChildren- AgentsScoutsFindingsRoute: typeof AgentsScoutsFindingsRoute- AgentsScoutsScratchpadRoute: typeof AgentsScoutsScratchpadRoute- AgentsScoutsIndexRoute: typeof AgentsScoutsIndexRoute-}--const AgentsScoutsRouteChildren: AgentsScoutsRouteChildren = {- AgentsScoutsSkillNameRoute: AgentsScoutsSkillNameRouteWithChildren,- AgentsScoutsFindingsRoute: AgentsScoutsFindingsRoute,- AgentsScoutsScratchpadRoute: AgentsScoutsScratchpadRoute,- AgentsScoutsIndexRoute: AgentsScoutsIndexRoute,-}--const AgentsScoutsRouteWithChildren = AgentsScoutsRoute._addFileChildren(- AgentsScoutsRouteChildren,-)--interface AgentsRouteChildren {- AgentsScoutsRoute: typeof AgentsScoutsRouteWithChildren- AgentsIndexRoute: typeof AgentsIndexRoute-}--const AgentsRouteChildren: AgentsRouteChildren = {- AgentsScoutsRoute: AgentsScoutsRouteWithChildren,- AgentsIndexRoute: AgentsIndexRoute,-}--const AgentsRouteWithChildren =- AgentsRoute._addFileChildren(AgentsRouteChildren)-interface InboxDismissedRouteChildren {InboxDismissedReportIdRoute: typeof InboxDismissedReportIdRouteInboxDismissedIndexRoute: typeof InboxDismissedIndexRoute@@ -1408,18 +1256,19 @@ const LoopsLoopIdRouteWithChildren = LoopsLoopIdRoute._addFileChildren(const rootRouteChildren: RootRouteChildren = {ShellRoute: ShellRouteWithChildren,- AgentsRoute: AgentsRouteWithChildren,ArchivedRoute: ArchivedRoute,ContextRoute: ContextRoute,InboxRoute: InboxRouteWithChildren,PrRoute: PrRoute,UsageRoute: UsageRoute,+ AgentsSplatRoute: AgentsSplatRoute,CodeSplatRoute: CodeSplatRoute,FoldersFolderIdRoute: FoldersFolderIdRoute,LoopsLoopIdRoute: LoopsLoopIdRouteWithChildren,LoopsNewRoute: LoopsNewRoute,TasksTaskIdRoute: TasksTaskIdRoute,WebsiteSplatRoute: WebsiteSplatRoute,+ AgentsIndexRoute: AgentsIndexRoute,CodeIndexRoute: CodeIndexRoute,LoopsIndexRoute: LoopsIndexRoute,WebsiteIndexRoute: WebsiteIndexRoute,diff --git a/products/desktop/packages/ui/src/router/routes/agents.$.tsx b/products/desktop/packages/ui/src/router/routes/agents.$.tsxnew file mode 100644index 000000000000..4792f7b47e43--- /dev/null+++ b/products/desktop/packages/ui/src/router/routes/agents.$.tsx@@ -0,0 +1,32 @@+import { agentsPageActions } from "@posthog/ui/features/agents/agentsPageStore";+import { createFileRoute, redirect } from "@tanstack/react-router";++// The agents pages became the Agents settings page, which has one URL for all+// of its tabs. Old hrefs still arrive from deep links, notifications and+// restored history. Findings links open Self-driving; other links open the+// tab or the agent they named.+export const Route = createFileRoute("/agents/$")({+ beforeLoad: ({ params, location }) => {+ const rest = (params._splat ?? "").replace(/^scouts\/?/, "");+ const actions = agentsPageActions();++ if (rest === "findings") {+ throw redirect({ to: "/inbox", replace: true });+ } else if (rest === "scratchpad") {+ actions.showTab("memory");+ } else if (rest) {+ const finding = (location.search as { finding?: unknown }).finding;+ actions.openAgent(rest.split("/")[0], {+ findingId: typeof finding === "string" ? finding : undefined,+ });+ } else {+ actions.showTab("agents");+ }++ throw redirect({+ to: "/settings/$category",+ params: { category: "agents" },+ replace: true,+ });+ },+});diff --git a/products/desktop/packages/ui/src/router/routes/agents.index.tsx b/products/desktop/packages/ui/src/router/routes/agents.index.tsxnew file mode 100644index 000000000000..8fb0c7d69f3b--- /dev/null+++ b/products/desktop/packages/ui/src/router/routes/agents.index.tsx@@ -0,0 +1,13 @@+import { agentsPageActions } from "@posthog/ui/features/agents/agentsPageStore";+import { createFileRoute, redirect } from "@tanstack/react-router";++export const Route = createFileRoute("/agents/")({+ beforeLoad: () => {+ agentsPageActions().showTab("agents");+ throw redirect({+ to: "/settings/$category",+ params: { category: "agents" },+ replace: true,+ });+ },+});diff --git a/products/desktop/packages/ui/src/router/routes/agents.tsx b/products/desktop/packages/ui/src/router/routes/agents.tsxdeleted file mode 100644index 56f6602df3fa..000000000000--- a/products/desktop/packages/ui/src/router/routes/agents.tsx+++ /dev/null@@ -1,14 +0,0 @@-import {- AppPageSkeleton,- withRouteSkeleton,-} from "@posthog/ui/router/routeSkeletons";-import { createFileRoute, Outlet } from "@tanstack/react-router";--export const Route = createFileRoute("/agents")({- component: AgentsLayout,- ...withRouteSkeleton(AppPageSkeleton),-});--function AgentsLayout() {- return <Outlet />;-}diff --git a/products/desktop/packages/ui/src/router/routes/agents/index.tsx b/products/desktop/packages/ui/src/router/routes/agents/index.tsxdeleted file mode 100644index d3f555862395..000000000000--- a/products/desktop/packages/ui/src/router/routes/agents/index.tsx+++ /dev/null@@ -1,7 +0,0 @@-import { createFileRoute, redirect } from "@tanstack/react-router";--export const Route = createFileRoute("/agents/")({- beforeLoad: () => {- throw redirect({ to: "/agents/scouts" });- },-});diff --git a/products/desktop/packages/ui/src/router/routes/agents/scouts.$skillName.index.tsx b/products/desktop/packages/ui/src/router/routes/agents/scouts.$skillName.index.tsxdeleted file mode 100644index e08ef072523e..000000000000--- a/products/desktop/packages/ui/src/router/routes/agents/scouts.$skillName.index.tsx+++ /dev/null@@ -1,15 +0,0 @@-import { ScoutDetailView } from "@posthog/ui/features/scouts/components/ScoutDetailView";-import { createFileRoute } from "@tanstack/react-router";--export const Route = createFileRoute("/agents/scouts/$skillName/")({- validateSearch: (search: Record<string, unknown>): { finding?: string } => ({- finding: typeof search.finding === "string" ? search.finding : undefined,- }),- component: ScoutDetailRoute,-});--function ScoutDetailRoute() {- const { skillName } = Route.useParams();- const { finding } = Route.useSearch();- return <ScoutDetailView skillSlug={skillName} highlightFindingId={finding} />;-}diff --git a/products/desktop/packages/ui/src/router/routes/agents/scouts.$skillName.tsx b/products/desktop/packages/ui/src/router/routes/agents/scouts.$skillName.tsxdeleted file mode 100644index 8c6b34709c7c..000000000000--- a/products/desktop/packages/ui/src/router/routes/agents/scouts.$skillName.tsx+++ /dev/null@@ -1,5 +0,0 @@-import { createFileRoute, Outlet } from "@tanstack/react-router";--export const Route = createFileRoute("/agents/scouts/$skillName")({- component: Outlet,-});diff --git a/products/desktop/packages/ui/src/router/routes/agents/scouts.findings.tsx b/products/desktop/packages/ui/src/router/routes/agents/scouts.findings.tsxdeleted file mode 100644index 14afedcb1a86..000000000000--- a/products/desktop/packages/ui/src/router/routes/agents/scouts.findings.tsx+++ /dev/null@@ -1,6 +0,0 @@-import { ScoutFindingsView } from "@posthog/ui/features/scouts/components/ScoutFindingsView";-import { createFileRoute } from "@tanstack/react-router";--export const Route = createFileRoute("/agents/scouts/findings")({- component: ScoutFindingsView,-});diff --git a/products/desktop/packages/ui/src/router/routes/agents/scouts.index.tsx b/products/desktop/packages/ui/src/router/routes/agents/scouts.index.tsxdeleted file mode 100644index f45ea5b130bd..000000000000--- a/products/desktop/packages/ui/src/router/routes/agents/scouts.index.tsx+++ /dev/null@@ -1,6 +0,0 @@-import { AgentsView } from "@posthog/ui/features/agents/components/AgentsView";-import { createFileRoute } from "@tanstack/react-router";--export const Route = createFileRoute("/agents/scouts/")({- component: AgentsView,-});diff --git a/products/desktop/packages/ui/src/router/routes/agents/scouts.scratchpad.tsx b/products/desktop/packages/ui/src/router/routes/agents/scouts.scratchpad.tsxdeleted file mode 100644index 9c4a9d28ba00..000000000000--- a/products/desktop/packages/ui/src/router/routes/agents/scouts.scratchpad.tsx+++ /dev/null@@ -1,6 +0,0 @@-import { ScratchpadView } from "@posthog/ui/features/scouts/components/ScratchpadView";-import { createFileRoute } from "@tanstack/react-router";--export const Route = createFileRoute("/agents/scouts/scratchpad")({- component: ScratchpadView,-});diff --git a/products/desktop/packages/ui/src/router/routes/agents/scouts.tsx b/products/desktop/packages/ui/src/router/routes/agents/scouts.tsxdeleted file mode 100644index 4aa03dd25cbe..000000000000--- a/products/desktop/packages/ui/src/router/routes/agents/scouts.tsx+++ /dev/null@@ -1,5 +0,0 @@-import { createFileRoute, Outlet } from "@tanstack/react-router";--export const Route = createFileRoute("/agents/scouts")({- component: Outlet,-});diff --git a/products/desktop/packages/ui/src/router/useAppView.ts b/products/desktop/packages/ui/src/router/useAppView.tsindex b30c2edebf51..01b302d5eb7e 100644--- a/products/desktop/packages/ui/src/router/useAppView.ts+++ b/products/desktop/packages/ui/src/router/useAppView.ts@@ -14,6 +14,8 @@ export type AppViewType =| "activity"| "home"| "inbox"+ // The Agents page moved into Settings, so no route yields this view any+ // more. It stays for tabs that were opened on the old page.| "agents"| "loops"| "archived"@@ -67,8 +69,6 @@ function deriveFromMatches(matches: Match[]): AppView {return { type: "home" };case "/inbox":return { type: "inbox" };- case "/agents":- return { type: "agents" };case "/loops":return { type: "loops" };case "/archived":@@ -89,12 +89,6 @@ function deriveFromMatches(matches: Match[]): AppView {if (last.fullPath.startsWith("/inbox")) {return { type: "inbox" };}- // /agents is an Outlet layout; the view lives at the index child and- // scout detail routes nest deeper, so match the whole subtree rather- // than only the bare layout route.- if (last.fullPath.startsWith("/agents")) {- return { type: "agents" };- }// /loops covers the list, create form, and the per-loop detail / edit// subtree ($loopId is an Outlet layout), so match the prefix.if (last.fullPath.startsWith("/loops")) {