Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
130 changes: 130 additions & 0 deletions packages/api-client/src/posthog-client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1147,6 +1147,136 @@ describe("PostHogAPIClient", () => {
await expect(client.getSignalReport("abc")).resolves.toEqual({
id: "abc",
title: "hi",
charts: [],
});
});

// A chart's `query` is POSTed back to `/api/projects/:id/query/` to draw it,
// so normalization is the gate on what the app is willing to execute.
describe("charts", () => {
const trendsQuery = {
kind: "InsightVizNode",
source: { kind: "TrendsQuery" },
};

async function fetchCharts(charts: unknown) {
const fetch = vi.fn().mockResolvedValue({
json: async () => ({ id: "abc", title: "hi", charts }),
});
const report = await makeClient(fetch).getSignalReport("abc");
return report?.charts;
}

it("keeps a well-formed chart", async () => {
await expect(
fetchCharts([
{
chart_id: "signups",
title: "Daily signups",
query: trendsQuery,
caption: "Since Friday",
size: "large",
},
]),
).resolves.toEqual([
{
chart_id: "signups",
title: "Daily signups",
query: trendsQuery,
caption: "Since Friday",
size: "large",
},
]);
});

it("normalizes an absent caption and size to null", async () => {
await expect(
fetchCharts([{ chart_id: "a", title: "A", query: trendsQuery }]),
).resolves.toEqual([
{
chart_id: "a",
title: "A",
query: trendsQuery,
caption: null,
size: null,
},
]);
});

it.each([
{ name: "a missing id", chart: { title: "A", query: trendsQuery } },
{
name: "a malformed id",
chart: { chart_id: "Not Valid", title: "A", query: trendsQuery },
},
{
name: "a blank title",
chart: { chart_id: "a", title: " ", query: trendsQuery },
},
{
name: "a missing query",
chart: { chart_id: "a", title: "A" },
},
{
name: "an unrenderable query kind",
chart: { chart_id: "a", title: "A", query: { kind: "TrendsQuery" } },
},
{
name: "an executable query nested in the node",
chart: {
chart_id: "a",
title: "A",
query: { kind: "InsightVizNode", source: { kind: "HogQuery" } },
},
},
{
name: "bytecode smuggled into the node",
chart: {
chart_id: "a",
title: "A",
query: { kind: "InsightVizNode", source: { bytecode: ["_H", 1] } },
},
},
])("drops a chart with $name", async ({ chart }) => {
await expect(fetchCharts([chart])).resolves.toEqual([]);
});

it("keeps the good charts when one entry is malformed", async () => {
const charts = await fetchCharts([
{ chart_id: "bad" },
{ chart_id: "good", title: "Good", query: trendsQuery },
]);

expect(charts?.map((chart) => chart.chart_id)).toEqual(["good"]);
});

it("collapses a duplicate id to its first occurrence", async () => {
const charts = await fetchCharts([
{ chart_id: "a", title: "First", query: trendsQuery },
{ chart_id: "a", title: "Second", query: trendsQuery },
]);

expect(charts).toHaveLength(1);
expect(charts?.[0].title).toBe("First");
});

it("caps the chart list at the backend's limit", async () => {
const charts = await fetchCharts(
Array.from({ length: 25 }, (_entry, index) => ({
chart_id: `c${index}`,
title: `Chart ${index}`,
query: trendsQuery,
})),
);

expect(charts).toHaveLength(20);
});

it.each([
{ name: "absent", charts: undefined },
{ name: "not an array", charts: "nope" },
])("yields no charts when the field is $name", async ({ charts }) => {
await expect(fetchCharts(charts)).resolves.toEqual([]);
});
});

Expand Down
110 changes: 106 additions & 4 deletions packages/api-client/src/posthog-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import type {
CreateTaskAutomationOptions,
ExecutionMode,
PrAuthorshipMode,
ReportChart,
SourceProduct,
SourceType,
StoredLogEntry,
Expand All @@ -21,7 +22,14 @@ import {
DISMISSAL_REASON_OPTIONS,
type DismissalReasonOptionValue,
getCloudTaskGatewayUrl,
hasForbiddenReportChartQueryNode,
isReportChartId,
isReportChartQueryKind,
isReportChartSize,
isSupportedReasoningEffort,
MAX_REPORT_CHART_CAPTION_LENGTH,
MAX_REPORT_CHART_TITLE_LENGTH,
MAX_REPORT_CHARTS,
normalizeGatewayModelsResponse,
resolveCloudInitialPermissionMode,
taskAutomationListSchema,
Expand Down Expand Up @@ -1397,6 +1405,71 @@ function parseSignalReportArtefactsPayload(
};
}

// ── Report charts ─────────────────────────────────────────────────────────
// A chart's `query` is POSTed back to `/api/projects/:id/query/` to draw it, so
// this is a trust boundary rather than a cosmetic parse: a chart missing its id,
// carrying a query kind we don't render, or nesting an executable node is
// dropped here and never reaches `runInsightQuery`. Malformed entries drop
// individually — one bad chart shouldn't cost the report its other evidence.

function normalizeReportChart(value: unknown): ReportChart | null {
if (!isObjectRecord(value)) return null;

const chartId = optionalString(value.chart_id);
if (!chartId || !isReportChartId(chartId)) return null;

const title = optionalString(value.title)?.trim();
if (!title || title.length > MAX_REPORT_CHART_TITLE_LENGTH) return null;

if (!isObjectRecord(value.query) || Array.isArray(value.query)) return null;
const query = value.query as Record<string, unknown>;
if (!isReportChartQueryKind(query.kind)) return null;
if (hasForbiddenReportChartQueryNode(query)) return null;

const caption = optionalString(value.caption);
return {
chart_id: chartId,
title,
query,
caption:
caption && caption.length <= MAX_REPORT_CHART_CAPTION_LENGTH
? caption
: null,
size: isReportChartSize(value.size) ? value.size : null,
};
}

/**
* The renderable charts on a report payload. Duplicate ids collapse to the first
* occurrence, since the summary places charts by id and a repeat would be
* unreachable anyway.
*/
function normalizeReportCharts(value: unknown): ReportChart[] {
if (!Array.isArray(value)) return [];
const charts: ReportChart[] = [];
const seen = new Set<string>();
for (const entry of value) {
if (charts.length >= MAX_REPORT_CHARTS) break;
const chart = normalizeReportChart(entry);
if (!chart || seen.has(chart.chart_id)) continue;
seen.add(chart.chart_id);
charts.push(chart);
}
return charts;
}

/**
* Report rows arrive as raw JSON casts; this replaces just the `charts` field
* with its validated form, leaving every other field as the backend sent it.
*/
function withNormalizedReportCharts<T>(report: T): T {
if (!isObjectRecord(report)) return report;
return {
...report,
charts: normalizeReportCharts((report as Record<string, unknown>).charts),
} as T;
}

function normalizeAvailableSuggestedReviewer(
uuid: string,
value: unknown,
Expand Down Expand Up @@ -3985,7 +4058,9 @@ export class PostHogAPIClient {
url,
path,
});
return (await response.json()) as SignalReport;
return withNormalizedReportCharts(
(await response.json()) as SignalReport,
);
} catch (error) {
// The shared fetcher throws "Failed request: [<status>] <body>" for any
// non-2xx. Treat missing / forbidden as "not available in the current
Expand Down Expand Up @@ -4049,7 +4124,7 @@ export class PostHogAPIClient {
count?: number;
};
return {
results: data.results ?? [],
results: (data.results ?? []).map(withNormalizedReportCharts),
count: data.count ?? data.results?.length ?? 0,
};
}
Expand Down Expand Up @@ -4135,7 +4210,7 @@ export class PostHogAPIClient {
signals?: Signal[];
};
return {
report: data.report ?? null,
report: data.report ? withNormalizedReportCharts(data.report) : null,
signals: data.signals ?? [],
};
} catch (error) {
Expand Down Expand Up @@ -4269,7 +4344,7 @@ export class PostHogAPIClient {
throw new Error(errorText || "Failed to update signal report state");
}

return (await response.json()) as SignalReport;
return withNormalizedReportCharts((await response.json()) as SignalReport);
}

/**
Expand Down Expand Up @@ -6510,6 +6585,33 @@ export class PostHogAPIClient {
return { results: data.results ?? [], columns: data.columns ?? [] };
}

/**
* Executes a query node (an `InsightVizNode`, `DataVisualizationNode`, …)
* against the team's project and returns the raw response for the caller to
* shape. Backs report-chart rendering, where the node comes from the report
* payload rather than being built here — callers must have validated the kind
* first (`normalizeReportCharts` is the gate on the inbox path). As with
* `runHogQLQuery`, a 200 carrying an `error` field is surfaced as a throw.
*/
async runInsightQuery(
query: Record<string, unknown>,
): Promise<Record<string, unknown>> {
const teamId = await this.getTeamId();
const path = `/api/projects/${teamId}/query/`;
const url = new URL(`${this.api.baseUrl}${path}`);
const response = await this.api.fetcher.fetch({
method: "post",
url,
path,
overrides: { body: JSON.stringify({ query }) },
});
const data = (await response.json()) as Record<string, unknown>;
if (typeof data.error === "string" && data.error) {
throw new Error(data.error);
}
return data;
}

/**
* Agent observability rollup over the agents' `$ai_*` events — KPIs (spend,
* sessions, failure rate, p95), a 14-day daily trend + WoW deltas, and
Expand Down
18 changes: 18 additions & 0 deletions packages/core/src/inbox/inboxQuery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,24 @@ export const inboxReportKeys = {
[...inboxReportKeys.all, reportId, "artefacts"] as const,
signals: (reportId: string) =>
[...inboxReportKeys.all, reportId, "signals"] as const,
/**
* `queryHash` keeps a revised chart query from reading the previous query's
* cached result — the `chart_id` stays the same across such an edit.
*/
chart: (
projectId: number | null,
reportId: string,
chartId: string,
queryHash: string,
) =>
[
...inboxReportKeys.all,
reportId,
"chart",
chartId,
queryHash,
projectId ?? "no-project",
] as const,
availableSuggestedReviewers: (authIdentity: string | null) =>
[
...inboxReportKeys.all,
Expand Down
Loading
Loading