Skip to content

: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.

feat(desktop): persist PostHog references as artifacts (#86334)

Shy Alter636c1acabfaf
diff --git a/products/desktop/docs/CLOUD-TASK-ARTIFACTS.md b/products/desktop/docs/CLOUD-TASK-ARTIFACTS.md
index 27bcfc757e84..39acb832ad7c 100644
--- a/products/desktop/docs/CLOUD-TASK-ARTIFACTS.md
+++ b/products/desktop/docs/CLOUD-TASK-ARTIFACTS.md
@@ -8,6 +8,16 @@ On success the tool returns a presigned download URL for the uploaded file (mint
Repository changes should continue to be delivered through git rather than duplicated as task artifacts. A single uploaded artifact is limited to 30 MB.
+## PostHog object references
+
+A completed assistant message can reference a PostHog object with an object tag, such as `<insight id="9pQx3">Checkout funnel</insight>`. Desktop extracts these tags after the turn completes and registers them in the same run artifact manifest with `type: reference` and `source: posthog_object`.
+
+Reference artifacts do not upload a file and do not have a storage path, size, or download URL. Their metadata stores the object kind, exact identifier, source message IDs, and occurrence count. Replaying the same completed message updates the existing entry instead of creating another one.
+
+Registration failure does not block the completed turn or replace the current artifact list. Desktop retries when it hydrates the completed turn again, so the client and backend can deploy in either order.
+
+The Artifacts pane shows file and reference artifacts in one list. The Timeline announces a new reference as an added artifact. Both surfaces open the same artifact tab, which resolves the current object data from the active PostHog project.
+
The desktop app runs scripts embedded in HTML artifacts inside an isolated preview process. The preview cannot access Node.js, Electron, PostHog credentials, remote resources, downloads, or device permissions. Use **Stop preview** if a script becomes unresponsive, then use **Restart preview** to load it in a fresh process.
## Versions and dismissal
diff --git a/products/desktop/packages/agent/src/server/agent-server.ts b/products/desktop/packages/agent/src/server/agent-server.ts
index 8d52be087928..eed45220e460 100644
--- a/products/desktop/packages/agent/src/server/agent-server.ts
+++ b/products/desktop/packages/agent/src/server/agent-server.ts
@@ -22,6 +22,7 @@ import {
buildPrOutput,
getErrorMessage,
isIgnoredSkillPath,
+ isSkillBundleArtifactMetadata,
type McpServerConnection,
mergePrUrls,
parseMcpToolName,
@@ -3055,7 +3056,8 @@ export class AgentServer {
const hasMatchingArtifact = artifacts.some(
(artifact) =>
artifact.type === "skill_bundle" &&
- artifact.metadata?.skill_name === invocation.skillName,
+ isSkillBundleArtifactMetadata(artifact.metadata) &&
+ artifact.metadata.skill_name === invocation.skillName,
);
const installedSkill = hasMatchingArtifact
? this.installedSkillBundleInfo.get(
@@ -3096,8 +3098,16 @@ export class AgentServer {
messageText: string,
): LocalSkillPromptContext | null {
const installed = artifacts
- .filter((artifact) => artifact.type === "skill_bundle")
- .map((artifact) => artifact.metadata?.skill_name)
+ .filter(
+ (artifact) =>
+ artifact.type === "skill_bundle" &&
+ isSkillBundleArtifactMetadata(artifact.metadata),
+ )
+ .map((artifact) =>
+ isSkillBundleArtifactMetadata(artifact.metadata)
+ ? artifact.metadata.skill_name
+ : null,
+ )
.filter((name): name is string => typeof name === "string")
.map((name) =>
this.installedSkillBundleInfo.get(
@@ -3218,15 +3228,14 @@ export class AgentServer {
artifact: TaskRunArtifact,
): Promise<void> {
const metadata = artifact.metadata;
- const skillName = metadata?.skill_name;
- const expectedSha256 = metadata?.content_sha256;
-
- if (!artifact.storage_path || !skillName || !expectedSha256) {
+ if (!artifact.storage_path || !isSkillBundleArtifactMetadata(metadata)) {
throw new Error(
`Skill bundle artifact ${artifact.name} is missing metadata`,
);
}
+ const skillName = metadata.skill_name;
+ const expectedSha256 = metadata.content_sha256;
const installKey = `${runId}:${expectedSha256}:${skillName}`;
if (
this.installedSkillBundles.has(installKey) &&
diff --git a/products/desktop/packages/api-client/src/posthog-client.test.ts b/products/desktop/packages/api-client/src/posthog-client.test.ts
index 2269b534960d..91705757da10 100644
--- a/products/desktop/packages/api-client/src/posthog-client.test.ts
+++ b/products/desktop/packages/api-client/src/posthog-client.test.ts
@@ -999,6 +999,80 @@ describe("PostHogAPIClient", () => {
);
});
+ it("registers PostHog references without file upload fields", async () => {
+ const fetch = vi.fn().mockResolvedValue({
+ ok: true,
+ json: async () => ({
+ artifacts: [
+ {
+ id: "phref-1",
+ name: "Checkout funnel",
+ type: "reference",
+ source: "posthog_object",
+ uploaded_at: "2026-08-19T00:00:00Z",
+ metadata: {
+ reference_type: "posthog_object",
+ object_kind: "insight",
+ object_id: "9pQx3",
+ source_message_ids: ["turn-1"],
+ occurrence_count: 1,
+ },
+ },
+ ],
+ }),
+ });
+ const client = new PostHogAPIClient(
+ "http://localhost:8000",
+ async () => "token",
+ async () => "token",
+ 123,
+ );
+ (
+ client as unknown as {
+ api: { baseUrl: string; fetcher: { fetch: typeof fetch } };
+ }
+ ).api = {
+ baseUrl: "http://localhost:8000",
+ fetcher: { fetch },
+ };
+
+ await expect(
+ client.registerTaskRunPostHogReferences("task-123", "run-123", [
+ {
+ name: "Checkout funnel",
+ object_kind: "insight",
+ object_id: "9pQx3",
+ source_message_id: "turn-1",
+ },
+ ]),
+ ).resolves.toEqual([
+ expect.objectContaining({
+ id: "phref-1",
+ type: "reference",
+ source: "posthog_object",
+ metadata: expect.objectContaining({ object_id: "9pQx3" }),
+ }),
+ ]);
+ expect(fetch).toHaveBeenCalledWith(
+ expect.objectContaining({
+ method: "post",
+ path: "/api/projects/123/tasks/task-123/runs/run-123/artifacts/references/",
+ overrides: {
+ body: JSON.stringify({
+ references: [
+ {
+ name: "Checkout funnel",
+ object_kind: "insight",
+ object_id: "9pQx3",
+ source_message_id: "turn-1",
+ },
+ ],
+ }),
+ },
+ }),
+ );
+ });
+
it("presigns a task run artifact for preview", async () => {
const fetch = vi.fn().mockResolvedValue({
ok: true,
diff --git a/products/desktop/packages/api-client/src/posthog-client.ts b/products/desktop/packages/api-client/src/posthog-client.ts
index 8aee967cea28..7e925b7e3c9c 100644
--- a/products/desktop/packages/api-client/src/posthog-client.ts
+++ b/products/desktop/packages/api-client/src/posthog-client.ts
@@ -733,6 +733,13 @@ export class FolderInstructionsConflictError extends Error {
}
}
+export interface PostHogObjectReferenceInput {
+ name: string;
+ object_kind: string;
+ object_id: string;
+ source_message_id: string;
+}
+
export interface TaskArtifactUploadRequest {
name: string;
type: "output" | "user_attachment" | "skill_bundle";
@@ -3442,6 +3449,29 @@ export class PostHogAPIClient {
return data.artifacts ?? [];
}
+ async registerTaskRunPostHogReferences(
+ taskId: string,
+ runId: string,
+ references: PostHogObjectReferenceInput[],
+ ): Promise<TaskRunArtifact[]> {
+ if (references.length === 0) return [];
+ const teamId = await this.getTeamId();
+ const path = `/api/projects/${teamId}/tasks/${taskId}/runs/${runId}/artifacts/references/`;
+ const response = await this.api.fetcher.fetch({
+ method: "post",
+ url: new URL(`${this.api.baseUrl}${path}`),
+ path,
+ overrides: { body: JSON.stringify({ references }) },
+ });
+ if (!response.ok) {
+ throw new Error(`Failed to register references: ${response.statusText}`);
+ }
+ const data = (await response.json()) as {
+ artifacts?: TaskRunArtifactDTO[];
+ };
+ return (data.artifacts ?? []).map(normalizeTaskRunArtifact);
+ }
+
async presignTaskRunArtifact(
taskId: string,
runId: string,
diff --git a/products/desktop/packages/api-client/src/task-normalization.test.ts b/products/desktop/packages/api-client/src/task-normalization.test.ts
index 928b641a9da3..706ed71e2ce7 100644
--- a/products/desktop/packages/api-client/src/task-normalization.test.ts
+++ b/products/desktop/packages/api-client/src/task-normalization.test.ts
@@ -69,6 +69,48 @@ describe("task response normalization", () => {
});
});
+ it("keeps PostHog reference metadata without requiring file storage", () => {
+ expect(
+ normalizeTaskRunResponse(
+ {
+ id: "run-1",
+ artifacts: [
+ {
+ id: "phref-1",
+ name: "Checkout funnel",
+ type: "reference",
+ source: "posthog_object",
+ uploaded_at: "2026-08-19T00:00:00Z",
+ metadata: {
+ reference_type: "posthog_object",
+ object_kind: "insight",
+ object_id: "9pQx3",
+ source_message_ids: ["turn-1"],
+ occurrence_count: 1,
+ },
+ },
+ ],
+ },
+ { teamId: 123, taskId: "task-1" },
+ ).artifacts,
+ ).toEqual([
+ {
+ id: "phref-1",
+ name: "Checkout funnel",
+ type: "reference",
+ source: "posthog_object",
+ uploaded_at: "2026-08-19T00:00:00Z",
+ metadata: {
+ reference_type: "posthog_object",
+ object_kind: "insight",
+ object_id: "9pQx3",
+ source_message_ids: ["turn-1"],
+ occurrence_count: 1,
+ },
+ },
+ ]);
+ });
+
it("normalizes task responses and their generated latest-run records", () => {
expect(
normalizeTaskResponse(
diff --git a/products/desktop/packages/api-client/src/task-normalization.ts b/products/desktop/packages/api-client/src/task-normalization.ts
index ba36199bffbe..4dd0e605745a 100644
--- a/products/desktop/packages/api-client/src/task-normalization.ts
+++ b/products/desktop/packages/api-client/src/task-normalization.ts
@@ -8,8 +8,12 @@ import type {
} from "@posthog/shared/domain-types";
import type { Schemas } from "./generated";
-export type TaskRunArtifactDTO = Schemas.TaskRunArtifactResponse & {
+export type TaskRunArtifactDTO = Omit<
+ Schemas.TaskRunArtifactResponse,
+ "metadata" | "storage_path"
+> & {
metadata?: unknown;
+ storage_path?: string;
uploaded_by?: "agent" | "user";
uploaded_by_user_id?: number;
dismissed_at?: string | null;
@@ -80,8 +84,24 @@ function normalizeArtifactType(type: string): ArtifactType {
function normalizeArtifactMetadata(
value: unknown,
): TaskRunArtifactMetadata | undefined {
+ if (!isRecord(value)) return undefined;
+ if (
+ value.reference_type === "posthog_object" &&
+ typeof value.object_kind === "string" &&
+ typeof value.object_id === "string" &&
+ Array.isArray(value.source_message_ids) &&
+ value.source_message_ids.every((entry) => typeof entry === "string") &&
+ typeof value.occurrence_count === "number"
+ ) {
+ return {
+ reference_type: "posthog_object",
+ object_kind: value.object_kind,
+ object_id: value.object_id,
+ source_message_ids: value.source_message_ids,
+ occurrence_count: value.occurrence_count,
+ };
+ }
if (
- !isRecord(value) ||
typeof value.skill_name !== "string" ||
(value.skill_source !== "user" &&
value.skill_source !== "repo" &&
@@ -118,7 +138,8 @@ export function normalizeTaskRunArtifact(
type: normalizeArtifactType(artifact.type),
...(artifact.source === "agent_output" ||
artifact.source === "user_attachment" ||
- artifact.source === "posthog_code_skill"
+ artifact.source === "posthog_code_skill" ||
+ artifact.source === "posthog_object"
? { source: artifact.source }
: {}),
...(artifact.size === undefined ? {} : { size: artifact.size }),
diff --git a/products/desktop/packages/core/src/canvas/activityEvents.ts b/products/desktop/packages/core/src/canvas/activityEvents.ts
index 4b7cf3c460e2..3a385ffcad48 100644
--- a/products/desktop/packages/core/src/canvas/activityEvents.ts
+++ b/products/desktop/packages/core/src/canvas/activityEvents.ts
@@ -70,6 +70,8 @@ export interface ArtifactPayload {
version: number;
/** Names the run whose artifact tab can open this; null on rows that predate it. */
runId: string | null;
+ referenceType: string | null;
+ objectKind: string | null;
}
export interface CanvasCreatedPayload {
@@ -155,6 +157,8 @@ function artifactPayload(payload: Record<string, unknown>): ArtifactPayload {
artifactType: str(payload.artifact_type),
version: num(payload.version, 1),
runId: optionalStr(payload.run_id),
+ referenceType: optionalStr(payload.reference_type),
+ objectKind: optionalStr(payload.object_kind),
};
}
@@ -226,7 +230,12 @@ export function parseActivityEvent(message: {
case "artifact_created":
case "artifact_revised": {
const parsed = artifactPayload(payload);
- return RUN_ARTIFACT_TYPES_WITHOUT_TIMELINE_EVENTS.has(parsed.artifactType)
+ const visiblePostHogReference =
+ parsed.artifactType === "reference" &&
+ parsed.referenceType === "posthog_object";
+ return RUN_ARTIFACT_TYPES_WITHOUT_TIMELINE_EVENTS.has(
+ parsed.artifactType,
+ ) && !visiblePostHogReference
? null
: { kind: event, payload: parsed };
}
diff --git a/products/desktop/packages/core/src/canvas/activityTimeline.test.ts b/products/desktop/packages/core/src/canvas/activityTimeline.test.ts
index 269fc1b6663a..ea0759c73007 100644
--- a/products/desktop/packages/core/src/canvas/activityTimeline.test.ts
+++ b/products/desktop/packages/core/src/canvas/activityTimeline.test.ts
@@ -318,6 +318,8 @@ describe("activity events", () => {
artifactType: "",
version: 1,
runId: null,
+ referenceType: null,
+ objectKind: null,
},
});
});
@@ -346,6 +348,33 @@ describe("activity events", () => {
},
);
+ it("keeps PostHog reference artifacts in the timeline", () => {
+ expect(
+ parseActivityEvent({
+ event: "artifact_created",
+ payload: {
+ artifact_id: "phref-1",
+ name: "Checkout funnel",
+ artifact_type: "reference",
+ reference_type: "posthog_object",
+ object_kind: "insight",
+ run_id: "run-1",
+ },
+ }),
+ ).toEqual({
+ kind: "artifact_created",
+ payload: {
+ artifactId: "phref-1",
+ name: "Checkout funnel",
+ artifactType: "reference",
+ version: 1,
+ runId: "run-1",
+ referenceType: "posthog_object",
+ objectKind: "insight",
+ },
+ });
+ });
+
it("drops a pull request event with no url, since it can't be opened", () => {
expect(parseActivityEvent({ event: "pr_merged", payload: {} })).toBeNull();
});
diff --git a/products/desktop/packages/core/src/canvas/runArtifactSchemas.test.ts b/products/desktop/packages/core/src/canvas/runArtifactSchemas.test.ts
index cb81f4ce1ca6..5aef4d874d52 100644
--- a/products/desktop/packages/core/src/canvas/runArtifactSchemas.test.ts
+++ b/products/desktop/packages/core/src/canvas/runArtifactSchemas.test.ts
@@ -1,5 +1,6 @@
import { describe, expect, it } from "vitest";
import {
+ getPostHogObjectArtifactMetadata,
groupRunArtifactVersions,
OUTPUT_ARTIFACT_TYPES,
parseRunArtifacts,
@@ -73,6 +74,29 @@ describe("parseRunArtifacts", () => {
});
});
+describe("getPostHogObjectArtifactMetadata", () => {
+ it("accepts PostHog references without file storage fields", () => {
+ expect(
+ getPostHogObjectArtifactMetadata({
+ type: "reference",
+ metadata: {
+ reference_type: "posthog_object",
+ object_kind: "insight",
+ object_id: "9pQx3",
+ source_message_ids: ["turn-1"],
+ occurrence_count: 1,
+ },
+ }),
+ ).toEqual({
+ reference_type: "posthog_object",
+ object_kind: "insight",
+ object_id: "9pQx3",
+ source_message_ids: ["turn-1"],
+ occurrence_count: 1,
+ });
+ });
+});
+
describe("groupRunArtifactVersions", () => {
it("collapses re-uploads of a name into one newest-first group", () => {
const groups = groupRunArtifactVersions([
diff --git a/products/desktop/packages/core/src/canvas/runArtifactSchemas.ts b/products/desktop/packages/core/src/canvas/runArtifactSchemas.ts
index 9ac89108a368..ab3981a35249 100644
--- a/products/desktop/packages/core/src/canvas/runArtifactSchemas.ts
+++ b/products/desktop/packages/core/src/canvas/runArtifactSchemas.ts
@@ -1,12 +1,24 @@
import { formatRelativeTimeLong } from "@posthog/shared";
import { z } from "zod";
+export const postHogObjectArtifactMetadataSchema = z.object({
+ reference_type: z.literal("posthog_object"),
+ object_kind: z.string().min(1),
+ object_id: z.string().min(1),
+ source_message_ids: z.array(z.string()),
+ occurrence_count: z.number().int().positive(),
+});
+export type PostHogObjectArtifactMetadata = z.infer<
+ typeof postHogObjectArtifactMetadataSchema
+>;
+
export const runArtifactSchema = z.object({
id: z.string().optional(),
name: z.string().optional(),
type: z.string().optional(),
size: z.number().optional(),
content_type: z.string().optional(),
+ metadata: z.record(z.string(), z.unknown()).optional(),
storage_path: z.string().optional(),
uploaded_at: z.string().optional(),
uploaded_by: z.enum(["agent", "user"]).optional(),
@@ -15,6 +27,17 @@ export const runArtifactSchema = z.object({
});
export type RunArtifact = z.infer<typeof runArtifactSchema>;
+export function getPostHogObjectArtifactMetadata(artifact: {
+ type?: string;
+ metadata?: unknown;
+}): PostHogObjectArtifactMetadata | null {
+ if (artifact.type !== "reference") return null;
+ const parsed = postHogObjectArtifactMetadataSchema.safeParse(
+ artifact.metadata,
+ );
+ return parsed.success ? parsed.data : null;
+}
+
/** Artifacts the agent hands back as deliverables, via the `upload_artifact` tool. */
export const OUTPUT_ARTIFACT_TYPES = ["output"] as const;
diff --git a/products/desktop/packages/core/src/inbox/objectTags.ts b/products/desktop/packages/core/src/inbox/objectTags.ts
index c945cacf9386..a14f90dbe4f6 100644
--- a/products/desktop/packages/core/src/inbox/objectTags.ts
+++ b/products/desktop/packages/core/src/inbox/objectTags.ts
@@ -113,6 +113,7 @@ const OBJECT_KIND_ALIASES: Record<string, string> = {
"session-replay": "replay",
recording: "replay",
"feature-flag": "flag",
+ feature_flag: "flag",
sql: "hogql",
};
@@ -156,7 +157,7 @@ const COMPLETE_TAG_RE =
const ATTR_RE = /([a-z][\w-]*)\s*=\s*"([^"]*)"/g;
const KNOWN_TAG_START_RE = /<([a-z][\w-]*)/g;
-function parseAttrs(raw: string): Record<string, string> {
+export function parseObjectTagAttrs(raw: string): Record<string, string> {
const attrs: Record<string, string> = {};
for (const match of raw.matchAll(ATTR_RE)) {
attrs[match[1]] = unescapeXmlAttr(match[2]);
@@ -164,7 +165,7 @@ function parseAttrs(raw: string): Record<string, string> {
return attrs;
}
-function buildRef(
+export function buildObjectTagRef(
kind: string,
attrs: Record<string, string>,
body: string | undefined,
@@ -211,7 +212,11 @@ export function parseObjectTags(text: string): ObjectTagSegment[] {
while ((match = COMPLETE_TAG_RE.exec(text)) !== null) {
const kind = resolveObjectKindName(match[1]);
if (!kind) continue;
- const ref = buildRef(kind, parseAttrs(match[2]), match[3]);
+ const ref = buildObjectTagRef(
+ kind,
+ parseObjectTagAttrs(match[2]),
+ match[3],
+ );
if (!ref) continue;
if (match.index > cursor) {
segments.push({ type: "text", value: text.slice(cursor, match.index) });
diff --git a/products/desktop/packages/core/src/posthog-objects/references.test.ts b/products/desktop/packages/core/src/posthog-objects/references.test.ts
new file mode 100644
index 000000000000..25bb455785bb
--- /dev/null
+++ b/products/desktop/packages/core/src/posthog-objects/references.test.ts
@@ -0,0 +1,95 @@
+import { describe, expect, it } from "vitest";
+import { extractPostHogObjectReferences } from "./references";
+
+describe("extractPostHogObjectReferences", () => {
+ it.each([
+ [
+ '<insight id="9pQx3">Checkout funnel</insight>',
+ [{ kind: "insight", id: "9pQx3", label: "Checkout funnel" }],
+ ],
+ [
+ '<feature-flag id="new-checkout" display="block" />',
+ [{ kind: "flag", id: "new-checkout", label: "new-checkout" }],
+ ],
+ [
+ '<hogql label="Errors today">SELECT count() FROM events</hogql>',
+ [
+ {
+ kind: "hogql",
+ id: "SELECT count() FROM events",
+ label: "Errors today",
+ },
+ ],
+ ],
+ ] as const)("extracts a complete object tag", (markdown, expected) => {
+ expect(extractPostHogObjectReferences(markdown)).toEqual(expected);
+ });
+
+ it("ignores tags in code and deduplicates the completed message", () => {
+ const tag = '<insight id="9pQx3">Checkout funnel</insight>';
+ expect(
+ extractPostHogObjectReferences(
+ [`\`${tag}\``, "```xml", tag, "```", tag, tag].join("\n"),
+ ),
+ ).toEqual([{ kind: "insight", id: "9pQx3", label: "Checkout funnel" }]);
+ });
+
+ it.each([
+ [
+ "tilde fence",
+ ["~~~", '<insight id="9pQx3">Checkout funnel</insight>', "~~~"],
+ ],
+ [
+ "nested longer backtick fence",
+ [
+ "````",
+ "```",
+ '<insight id="9pQx3">Checkout funnel</insight>',
+ "```",
+ "````",
+ ],
+ ],
+ [
+ "multi-backtick inline span",
+ ['``<insight id="9pQx3">Checkout funnel</insight>``'],
+ ],
+ ] as const)(
+ "ignores tags the renderer shows as code inside a %s",
+ (_label, lines) => {
+ expect(extractPostHogObjectReferences(lines.join("\n"))).toEqual([]);
+ },
+ );
+
+ it("stays fast on many unmatched opening tags", () => {
+ const hostile = `${'<insight id="x">'.repeat(20_000)}\n<flag id="real" />`;
+ const start = performance.now();
+ const references = extractPostHogObjectReferences(hostile);
+ expect(performance.now() - start).toBeLessThan(1_000);
+ expect(references).toEqual([{ kind: "flag", id: "real", label: "real" }]);
+ });
+
+ it("stays fast on many unmatched backtick runs", () => {
+ const hostile = Array.from(
+ { length: 400 },
+ (_, index) => `${"`".repeat(index + 1)}a`,
+ ).join("");
+ const start = performance.now();
+ const references = extractPostHogObjectReferences(
+ `${hostile.repeat(4)}\n<flag id="real" />`,
+ );
+ expect(performance.now() - start).toBeLessThan(1_000);
+ expect(references).toEqual([{ kind: "flag", id: "real", label: "real" }]);
+ });
+
+ it("ignores partial, unknown, and oversized references", () => {
+ expect(
+ extractPostHogObjectReferences(
+ [
+ '<insight id="partial">Checkout',
+ '<unknown id="1">Unknown</unknown>',
+ `<event id="${"x".repeat(16_385)}" />`,
+ ].join("\n"),
+ ),
+ ).toEqual([]);
+ });
+});
diff --git a/products/desktop/packages/core/src/posthog-objects/references.ts b/products/desktop/packages/core/src/posthog-objects/references.ts
new file mode 100644
index 000000000000..1fda3ef320f2
--- /dev/null
+++ b/products/desktop/packages/core/src/posthog-objects/references.ts
@@ -0,0 +1,176 @@
+import {
+ buildObjectTagRef,
+ parseObjectTagAttrs,
+ resolveObjectKindName,
+} from "@posthog/core/inbox/objectTags";
+
+// Opening tags and closing tags are matched separately so an unmatched opener
+// costs one regex step instead of a lazy scan to the end of the message; the
+// closer for each opener comes from a precomputed per-tag position index.
+const OPEN_TAG_PATTERN =
+ /<([a-z][\w-]*)((?:\s+[a-z][\w-]*\s*=\s*"[^"]*")*)\s*(\/>|>)/g;
+const CLOSE_TAG_PATTERN = /<\/([a-z][\w-]*)\s*>/g;
+const MAX_REFERENCES = 50;
+const MAX_OBJECT_ID_LENGTH = 16_384;
+const MAX_LABEL_LENGTH = 255;
+
+export interface PostHogObjectReference {
+ kind: string;
+ id: string;
+ label: string;
+}
+
+// Remove inline code spans, matching CommonMark: an opening run of N backticks
+// closes on the next run of exactly N, so a tag inside `code` or ``co`de`` stays
+// literal. Runs are collected once and matched through per-length cursors, so a
+// line full of unmatched runs costs one pass instead of a rescan per run.
+function stripInlineCode(line: string): string {
+ const runs: { start: number; end: number }[] = [];
+ for (let i = 0; i < line.length; i++) {
+ if (line[i] !== "`") continue;
+ let j = i + 1;
+ while (j < line.length && line[j] === "`") j++;
+ runs.push({ start: i, end: j });
+ i = j - 1;
+ }
+ if (runs.length < 2) return line;
+ const runsByLength = new Map<number, number[]>();
+ runs.forEach((run, index) => {
+ const length = run.end - run.start;
+ let list = runsByLength.get(length);
+ if (!list) {
+ list = [];
+ runsByLength.set(length, list);
+ }
+ list.push(index);
+ });
+ const cursors = new Map<number, number>();
+ let result = "";
+ let copied = 0;
+ let index = 0;
+ while (index < runs.length) {
+ const opener = runs[index];
+ const length = opener.end - opener.start;
+ const list = runsByLength.get(length) ?? [];
+ let cursor = cursors.get(length) ?? 0;
+ while (cursor < list.length && list[cursor] <= index) cursor++;
+ cursors.set(length, cursor);
+ if (cursor >= list.length) {
+ index++;
+ continue;
+ }
+ const closerIndex = list[cursor];
+ result += line.slice(copied, opener.start);
+ copied = runs[closerIndex].end;
+ cursors.set(length, cursor + 1);
+ index = closerIndex + 1;
+ }
+ return result + line.slice(copied);
+}
+
+// Blank out fenced code blocks so the tag parser never reads a citation the
+// renderer shows as code. Mirrors the fence rules react-markdown applies:
+// backtick or tilde fences of three or more, up to three leading spaces, closed
+// only by a same-character run at least as long as the opener. Indented code
+// blocks are left alone on purpose — a line-based strip would also drop real
+// tags nested under list items; full parsing lives in the AST plugin instead.
+function stripCode(markdown: string): string {
+ let fence: { char: string; length: number } | null = null;
+ return markdown
+ .split("\n")
+ .map((line) => {
+ const fenceMatch = /^ {0,3}(`{3,}|~{3,})/.exec(line);
+ if (fence) {
+ const closes =
+ fenceMatch !== null &&
+ fenceMatch[1][0] === fence.char &&
+ fenceMatch[1].length >= fence.length &&
+ line.slice(fenceMatch[0].length).trim() === "";
+ if (closes) fence = null;
+ return "";
+ }
+ if (fenceMatch) {
+ fence = { char: fenceMatch[1][0], length: fenceMatch[1].length };
+ return "";
+ }
+ return stripInlineCode(line);
+ })
+ .join("\n");
+}
+
+interface TagMatch {
+ name: string;
+ rawAttributes: string;
+ body: string;
+ end: number;
+}
+
+// One pass over openers plus one over closers keeps parsing linear in the
+// input size, where a single backreferencing regex retried the closing-tag
+// search from every unmatched opener (quadratic on crafted input).
+function* scanTags(text: string): Generator<TagMatch> {
+ const closersByName = new Map<string, number[][]>();
+ for (const close of text.matchAll(CLOSE_TAG_PATTERN)) {
+ let positions = closersByName.get(close[1]);
+ if (!positions) {
+ positions = [];
+ closersByName.set(close[1], positions);
+ }
+ positions.push([close.index, close.index + close[0].length]);
+ }
+ const cursors = new Map<string, number>();
+ let nextAllowed = 0;
+ for (const open of text.matchAll(OPEN_TAG_PATTERN)) {
+ if (open.index < nextAllowed) continue;
+ const name = open[1];
+ const openEnd = open.index + open[0].length;
+ if (open[3] === "/>") {
+ nextAllowed = openEnd;
+ yield { name, rawAttributes: open[2], body: "", end: openEnd };
+ continue;
+ }
+ const positions = closersByName.get(name);
+ if (!positions) continue;
+ let cursor = cursors.get(name) ?? 0;
+ while (cursor < positions.length && positions[cursor][0] < openEnd) {
+ cursor++;
+ }
+ cursors.set(name, cursor);
+ if (cursor >= positions.length) continue;
+ const [closeStart, closeEnd] = positions[cursor];
+ nextAllowed = closeEnd;
+ yield {
+ name,
+ rawAttributes: open[2],
+ body: text.slice(openEnd, closeStart),
+ end: closeEnd,
+ };
+ }
+}
+
+export function extractPostHogObjectReferences(
+ markdown: string,
+): PostHogObjectReference[] {
+ const references: PostHogObjectReference[] = [];
+ const seen = new Set<string>();
+ for (const match of scanTags(stripCode(markdown))) {
+ const kind = resolveObjectKindName(match.name);
+ if (!kind) continue;
+ const ref = buildObjectTagRef(
+ kind,
+ parseObjectTagAttrs(match.rawAttributes),
+ match.body,
+ );
+ if (!ref || ref.id.length > MAX_OBJECT_ID_LENGTH) continue;
+ const key = `${ref.kind}\0${ref.id}`;
+ if (seen.has(key)) continue;
+ seen.add(key);
+ references.push({
+ kind: ref.kind,
+ id: ref.id,
+ label: ref.label.replace(/\s+/g, " ").trim().slice(0, MAX_LABEL_LENGTH),
+ });
+ if (references.length >= MAX_REFERENCES) break;
+ }
+ return references;
+}
diff --git a/products/desktop/packages/core/src/sessions/sessionService.ts b/products/desktop/packages/core/src/sessions/sessionService.ts
index 38695fe51922..ae494c8fead3 100644
--- a/products/desktop/packages/core/src/sessions/sessionService.ts
+++ b/products/desktop/packages/core/src/sessions/sessionService.ts
@@ -13,6 +13,7 @@ import { requestErrorStatus } from "@posthog/api-client/fetcher";
import {
type CreateResourceCommentRequest,
type PostHogAPIClient,
+ type PostHogObjectReferenceInput,
type ResourceComment,
SESSION_LOGS_MAX_PAGE_SIZE,
type TaskRunSessionLogsResult,
@@ -62,6 +63,7 @@ import {
} from "@posthog/shared/domain-types";
import type { CommentTarget } from "../comments/anchors";
import type { AgentSessionNotification } from "../notification/agentSessionNotifications";
+import { extractPostHogObjectReferences } from "../posthog-objects/references";
import type { SpeechKind, SpeechSource } from "../speech/identifiers";
import {
CONTEXT_WINDOW_OPTION_CATEGORY,
@@ -1674,7 +1676,27 @@ function readSteering(result: unknown): string | undefined {
return (result as { steering?: string } | undefined)?.steering;
}
-function classifyTurnEventKind(
+// Live streaming emits agent_message_chunk; SessionLogWriter coalesces a chunk
+// run into a single agent_message, so hydration and cloud replay read the same
+// text back as that final. Both forms carry { type: "text", text }, so both
+// must count toward a turn's agent text (see agentMessageUpdateKind).
+export function readTurnAgentText(msg: AcpMessage["message"]): string {
+ if (!("method" in msg) || msg.method !== "session/update") return "";
+ const update = (msg as { params?: { update?: Record<string, unknown> } })
+ .params?.update;
+ if (
+ update?.sessionUpdate !== "agent_message_chunk" &&
+ update?.sessionUpdate !== "agent_message"
+ ) {
+ return "";
+ }
+ const content = update.content as
+ | { type?: string; text?: string }
+ | undefined;
+ return content?.type === "text" ? (content.text ?? "") : "";
+}
+
+export function classifyTurnEventKind(
msg: AcpMessage["message"],
): "text" | "output" | "other" {
if (!("method" in msg) || msg.method !== "session/update") return "other";
@@ -1682,7 +1704,10 @@ function classifyTurnEventKind(
.params?.update;
if (!update) return "other";
const sessionUpdate = update.sessionUpdate;
- if (sessionUpdate === "agent_message_chunk") {
+ if (
+ sessionUpdate === "agent_message_chunk" ||
+ sessionUpdate === "agent_message"
+ ) {
const content = update.content as { type?: string } | undefined;
return content?.type === "text" ? "text" : "output";
}
@@ -1771,9 +1796,23 @@ export class SessionService {
private respondedCloudPermissionRequestIds = new Set<string>();
private liveTurnContent = new Map<
string,
- { startedAtTs: number; agentTextChunks: number; agentOutputEvents: number }
+ {
+ startedAtTs: number;
+ agentTextChunks: number;
+ agentOutputEvents: number;
+ agentText: string;
+ }
>();
private pendingPermissionHydratedRuns = new Set<string>();
+ /** References whose registration failed, kept for retry keyed by task run. */
+ private pendingReferenceRegistrations = new Map<
+ string,
+ {
+ taskId: string;
+ references: Map<string, PostHogObjectReferenceInput>;
+ inflight: Promise<void> | null;
+ }
+ >();
/** In-flight hydrations keyed by `${taskRunId}:${hydrationMode}` */
private cloudHydrationPromises = new Map<
string,
@@ -2370,6 +2409,10 @@ export class SessionService {
this.d.store.removeSession(taskRunId);
this.cloudRunIdleTracker.delete(taskRunId);
this.cloudLogGapReconciler.forgetDeficiency(taskRunId);
+ // The run is gone, so nothing is left to retry against. Any references
+ // still pending here are dead weight; drop them so a removed run cannot
+ // leave its failed registrations resident.
+ this.pendingReferenceRegistrations.delete(taskRunId);
if (session) {
this.localRepoPaths.delete(session.taskId);
this.localRecoveryAttempts.delete(session.taskId);
@@ -3154,6 +3197,7 @@ export class SessionService {
this.sessionEventFlushHandle = null;
}
this.pendingSessionEvents.clear();
+ this.pendingReferenceRegistrations.clear();
this.hostEndedResubscribes.clear();
this.lastSessionEventAt.clear();
this.sessionEventStats.clear();
@@ -3226,6 +3270,92 @@ export class SessionService {
} else {
this.d.log.info("Turn completed", payload);
}
+
+ if (!session?.taskId || !tally.agentText) return;
+ const references = extractPostHogObjectReferences(tally.agentText);
+ if (references.length === 0) return;
+ const sourceMessageId = `turn-${tally.startedAtTs}`;
+ const inputs: PostHogObjectReferenceInput[] = references.map(
+ (reference) => ({
+ name: reference.label,
+ object_kind: reference.kind,
+ object_id: reference.id,
+ source_message_id: sourceMessageId,
+ }),
+ );
+ this.registerPostHogReferences(session.taskId, taskRunId, inputs);
+ }
+
+ // References enter the pending map before the attempt and leave it only on
+ // a confirmed registration, so an offline endpoint, a transient network
+ // error, or auth that is not ready yet loses nothing: the next turn on the
+ // run and the next hydration both retry whatever is still pending.
+ private registerPostHogReferences(
+ taskId: string,
+ taskRunId: string,
+ references: PostHogObjectReferenceInput[],
+ ): void {
+ const pending = this.pendingReferenceRegistrations.get(taskRunId) ?? {
+ taskId,
+ references: new Map<string, PostHogObjectReferenceInput>(),
+ inflight: null,
+ };
+ for (const reference of references) {
+ pending.references.set(
+ `${reference.object_kind}\0${reference.object_id}\0${reference.source_message_id}`,
+ reference,
+ );
+ }
+ this.pendingReferenceRegistrations.set(taskRunId, pending);
+ this.flushPendingReferenceRegistrations(taskRunId);
+ }
+
+ private flushPendingReferenceRegistrations(taskRunId: string): void {
+ const pending = this.pendingReferenceRegistrations.get(taskRunId);
+ if (!pending || pending.inflight || pending.references.size === 0) return;
+ const batch = new Map(pending.references);
+ pending.inflight = (async () => {
+ let registered = false;
+ try {
+ const authStatus = await this.getAuthCredentialsStatus();
+ if (authStatus.kind !== "ready") return;
+ const artifacts =
+ await authStatus.auth.client.registerTaskRunPostHogReferences(
+ pending.taskId,
+ taskRunId,
+ [...batch.values()],
+ );
+ registered = true;
+ const current = this.pendingReferenceRegistrations.get(taskRunId);
+ if (current) {
+ for (const key of batch.keys()) current.references.delete(key);
+ if (current.references.size === 0 && !current.inflight) {
+ this.pendingReferenceRegistrations.delete(taskRunId);
+ }
+ }
+ this.d.store.updateSession(taskRunId, { cloudArtifacts: artifacts });
+ } catch (error) {
+ this.d.log.warn("Failed to register PostHog object references", {
+ taskId: pending.taskId,
+ taskRunId,
+ error: String(error),
+ });
+ } finally {
+ const current = this.pendingReferenceRegistrations.get(taskRunId);
+ if (current) {
+ current.inflight = null;
+ if (current.references.size === 0) {
+ this.pendingReferenceRegistrations.delete(taskRunId);
+ } else if (registered) {
+ this.flushPendingReferenceRegistrations(taskRunId);
+ }
+ }
+ }
+ })();
+ }
+
+ private retryPendingReferenceRegistrations(taskRunId: string): void {
+ this.flushPendingReferenceRegistrations(taskRunId);
}
private updatePromptStateFromEvents(
@@ -3241,13 +3371,13 @@ export class SessionService {
if (this.isSteerMessage(msg)) {
continue;
}
- const turnTally = isLive
- ? this.liveTurnContent.get(taskRunId)
- : undefined;
+ const turnTally = this.liveTurnContent.get(taskRunId);
if (turnTally) {
const kind = classifyTurnEventKind(msg);
- if (kind === "text") turnTally.agentTextChunks += 1;
- else if (kind === "output") turnTally.agentOutputEvents += 1;
+ if (kind === "text") {
+ turnTally.agentTextChunks += 1;
+ turnTally.agentText += readTurnAgentText(msg);
+ } else if (kind === "output") turnTally.agentOutputEvents += 1;
}
if (isJsonRpcRequest(msg) && msg.method === "session/prompt") {
this.d.store.updateSession(taskRunId, {
@@ -3256,13 +3386,12 @@ export class SessionService {
pausedDurationMs: 0,
currentPromptId: msg.id,
});
- if (isLive) {
- this.liveTurnContent.set(taskRunId, {
- startedAtTs: acpMsg.ts,
- agentTextChunks: 0,
- agentOutputEvents: 0,
- });
- }
+ this.liveTurnContent.set(taskRunId, {
+ startedAtTs: acpMsg.ts,
+ agentTextChunks: 0,
+ agentOutputEvents: 0,
+ agentText: "",
+ });
const promptSession = this.d.store.getSessions()[taskRunId];
if (promptSession?.isCloud) {
this.cloudRunIdleTracker.markBusy(promptSession);
@@ -3302,9 +3431,7 @@ export class SessionService {
promptStartedAt: null,
currentPromptId: null,
});
- if (isLive) {
- this.finalizeTurnContent(taskRunId, "stop_reason", acpMsg.ts);
- }
+ this.finalizeTurnContent(taskRunId, "stop_reason", acpMsg.ts);
}
if (isTurnCompleteEvent(acpMsg)) {
// Local sessions use the JSON-RPC response as the canonical turn-done
@@ -3340,8 +3467,8 @@ export class SessionService {
);
}
this.d.taskViewedApi.markActivity(session.taskId);
- this.finalizeTurnContent(taskRunId, "turn_complete", acpMsg.ts);
}
+ this.finalizeTurnContent(taskRunId, "turn_complete", acpMsg.ts);
}
}
// Lifecycle handshake from the agent — flip status to "connected"
@@ -7153,6 +7280,7 @@ export class SessionService {
session.processedLineCount > 0 &&
!isResumeRun;
if (alreadyApplied) {
+ this.retryPendingReferenceRegistrations(taskRunId);
this.surfacePersistedPendingPermissions(taskRunId, rawEntries);
this.pendingPermissionHydratedRuns.add(taskRunId);
return {
@@ -7188,6 +7316,7 @@ export class SessionService {
// baseline already contains an in-flight session/prompt — the live delta
// path otherwise sees delta <= 0 and never re-evaluates the tail.
this.updatePromptStateFromEvents(taskRunId, events);
+ this.retryPendingReferenceRegistrations(taskRunId);
if (isTerminalRun) {
this.clearTerminalCloudPromptState(taskRunId);
}
diff --git a/products/desktop/packages/core/src/sessions/turnAgentText.test.ts b/products/desktop/packages/core/src/sessions/turnAgentText.test.ts
new file mode 100644
index 000000000000..51bda5f7f632
--- /dev/null
+++ b/products/desktop/packages/core/src/sessions/turnAgentText.test.ts
@@ -0,0 +1,67 @@
+import type { AcpMessage } from "@posthog/shared";
+import { describe, expect, it } from "vitest";
+import { classifyTurnEventKind, readTurnAgentText } from "./sessionService";
+
+function update(
+ sessionUpdate: string,
+ content?: { type: string; text?: string },
+): AcpMessage["message"] {
+ return {
+ jsonrpc: "2.0",
+ method: "session/update",
+ params: { update: { sessionUpdate, ...(content ? { content } : {}) } },
+ } as AcpMessage["message"];
+}
+
+const AGENT_TEXT = { type: "text", text: "hello" };
+
+describe("turn agent-text classification", () => {
+ it.each([
+ [
+ "live agent_message_chunk",
+ update("agent_message_chunk", AGENT_TEXT),
+ "text",
+ "hello",
+ ],
+ // SessionLogWriter coalesces a chunk run into one agent_message, so
+ // hydration and cloud replay read the turn's text back as this final.
+ [
+ "hydrated agent_message",
+ update("agent_message", AGENT_TEXT),
+ "text",
+ "hello",
+ ],
+ [
+ "agent_thought_chunk",
+ update("agent_thought_chunk", { type: "text", text: "thinking" }),
+ "output",
+ "",
+ ],
+ ["tool_call", update("tool_call"), "output", ""],
+ [
+ "non-text agent_message",
+ update("agent_message", { type: "image" }),
+ "output",
+ "",
+ ],
+ [
+ "user_message_chunk",
+ update("user_message_chunk", { type: "text", text: "hi" }),
+ "other",
+ "",
+ ],
+ ] as const)("classifies %s", (_label, msg, kind, text) => {
+ expect(classifyTurnEventKind(msg)).toBe(kind);
+ expect(readTurnAgentText(msg)).toBe(text);
+ });
+
+ it("treats a turn response as neither text nor output", () => {
+ const response = {
+ jsonrpc: "2.0",
+ id: 1,
+ result: { stopReason: "end_turn" },
+ } as AcpMessage["message"];
+ expect(classifyTurnEventKind(response)).toBe("other");
+ expect(readTurnAgentText(response)).toBe("");
+ });
+});
diff --git a/products/desktop/packages/shared/src/domain-types.ts b/products/desktop/packages/shared/src/domain-types.ts
index ec06fc0eeb00..77b68303950d 100644
--- a/products/desktop/packages/shared/src/domain-types.ts
+++ b/products/desktop/packages/shared/src/domain-types.ts
@@ -300,9 +300,10 @@ export type ArtifactType =
export type ArtifactSource =
| "agent_output"
| "user_attachment"
- | "posthog_code_skill";
+ | "posthog_code_skill"
+ | "posthog_object";
-export interface TaskRunArtifactMetadata {
+export interface SkillBundleArtifactMetadata {
skill_name: string;
skill_source: UploadableSkillSource;
content_sha256: string;
@@ -310,6 +311,24 @@ export interface TaskRunArtifactMetadata {
schema_version: number;
}
+export interface PostHogObjectArtifactMetadata {
+ reference_type: "posthog_object";
+ object_kind: string;
+ object_id: string;
+ source_message_ids: string[];
+ occurrence_count: number;
+}
+
+export type TaskRunArtifactMetadata =
+ | SkillBundleArtifactMetadata
+ | PostHogObjectArtifactMetadata;
+
+export function isSkillBundleArtifactMetadata(
+ metadata: TaskRunArtifactMetadata | undefined,
+): metadata is SkillBundleArtifactMetadata {
+ return metadata !== undefined && "skill_name" in metadata;
+}
+
export interface TaskRunArtifact {
id?: string;
name: string;
diff --git a/products/desktop/packages/shared/src/index.ts b/products/desktop/packages/shared/src/index.ts
index 724c2beb6c3c..177679dcb4c0 100644
--- a/products/desktop/packages/shared/src/index.ts
+++ b/products/desktop/packages/shared/src/index.ts
@@ -133,7 +133,9 @@ export {
type CloudTaskSnapshotUpdate,
type CloudTaskStatusUpdate,
type CloudTaskUpdatePayload,
+ isSkillBundleArtifactMetadata,
isTerminalStatus,
+ type PostHogObjectArtifactMetadata,
type SignalReportPriority,
type Task,
type TaskRun,
diff --git a/products/desktop/packages/ui/src/features/canvas/components/TaskArtifactsList.test.tsx b/products/desktop/packages/ui/src/features/canvas/components/TaskArtifactsList.test.tsx
index eaa2d5b2be4c..9cb62d9e770e 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/TaskArtifactsList.test.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/TaskArtifactsList.test.tsx
@@ -17,6 +17,7 @@ const mocks = vi.hoisted(() => ({
getCloudAttachmentPreviewUrl: vi.fn(),
commentsError: false,
sessionEvents: [] as unknown[],
+ sessionArtifacts: [] as TaskRunArtifact[],
taskRunsRefreshKeys: [] as number[],
}));
@@ -45,7 +46,10 @@ vi.mock("@posthog/ui/features/canvas/hooks/useTaskRuns", () => ({
vi.mock("@posthog/ui/features/sessions/sessionStore", () => ({
useSessionSelector: (_taskId: string, select: (s: unknown) => unknown) =>
- select({ events: mocks.sessionEvents }),
+ select({
+ events: mocks.sessionEvents,
+ cloudArtifacts: mocks.sessionArtifacts,
+ }),
}));
vi.mock("@posthog/ui/features/panels/panelLayoutStore", () => ({
usePanelLayoutStore: () => mocks.openArtifactTab,
@@ -133,6 +137,7 @@ describe("TaskArtifactsList", () => {
beforeEach(() => {
mocks.commentsError = false;
mocks.sessionEvents = [];
+ mocks.sessionArtifacts = [];
mocks.taskRunsRefreshKeys = [];
mocks.runs = [run("run-1", { prNumber: 1 }), run("run-2", { prNumber: 2 })];
mocks.openArtifactTab.mockReset();
@@ -235,6 +240,47 @@ describe("TaskArtifactsList", () => {
expect(within(row as HTMLElement).getByText("Agent · 17 KB")).toBeTruthy();
});
+ it("lists a PostHog reference beside file artifacts and opens its artifact tab", () => {
+ mocks.runs = [
+ run("run-1", {
+ artifacts: [
+ outputFile({ id: "a" }),
+ {
+ id: "phref-1",
+ name: "Checkout funnel",
+ type: "reference",
+ source: "posthog_object",
+ uploaded_at: "2026-08-19T00:00:00Z",
+ metadata: {
+ reference_type: "posthog_object",
+ object_kind: "insight",
+ object_id: "9pQx3",
+ source_message_ids: ["turn-1", "turn-2"],
+ occurrence_count: 2,
+ },
+ },
+ ],
+ }),
+ ];
+
+ render(<TaskArtifactsList task={task} timeline={[]} />);
+
+ expect(screen.getByText("report.md")).toBeInTheDocument();
+ expect(screen.getByText("Checkout funnel")).toBeInTheDocument();
+ expect(
+ screen.getByText(/^Insight · Product analytics · Referenced 2 times/),
+ ).toBeInTheDocument();
+ fireEvent.click(screen.getByText("Checkout funnel"));
+ expect(mocks.openArtifactTab).toHaveBeenCalledWith("task-1", {
+ runId: "run-1",
+ artifactId: "phref-1",
+ name: "Checkout funnel",
+ });
+ expect(
+ screen.queryByRole("button", { name: "Download Checkout funnel" }),
+ ).toBeNull();
+ });
+
it("keeps artifacts visible when comment counts fail", () => {
mocks.commentsError = true;
mocks.runs = [
@@ -508,6 +554,47 @@ describe("TaskArtifactsList", () => {
expect(mocks.taskRunsRefreshKeys.at(-1)).toBe(1);
});
+ it("refreshes the runs query when a PostHog reference is registered", () => {
+ mocks.sessionArtifacts = [
+ {
+ id: "phref-1",
+ name: "Checkout funnel",
+ type: "reference",
+ source: "posthog_object",
+ metadata: {
+ reference_type: "posthog_object",
+ object_kind: "insight",
+ object_id: "9pQx3",
+ source_message_ids: ["turn-1"],
+ occurrence_count: 1,
+ },
+ },
+ ];
+
+ render(<TaskArtifactsList task={task} timeline={[]} />);
+
+ // Entry plus its occurrence count, so an in-place update re-keys too.
+ expect(mocks.taskRunsRefreshKeys.at(-1)).toBe(2);
+
+ mocks.sessionArtifacts = [
+ {
+ id: "phref-1",
+ name: "Checkout funnel",
+ type: "reference",
+ source: "posthog_object",
+ metadata: {
+ reference_type: "posthog_object",
+ object_kind: "insight",
+ object_id: "9pQx3",
+ source_message_ids: ["turn-1", "turn-2"],
+ occurrence_count: 2,
+ },
+ },
+ ];
+ render(<TaskArtifactsList task={task} timeline={[]} />);
+ expect(mocks.taskRunsRefreshKeys.at(-1)).toBe(3);
+ });
+
it.each([
{ name: "a plan", type: "plan" as const },
{ name: "a user attachment", type: "user_attachment" as const },
diff --git a/products/desktop/packages/ui/src/features/canvas/components/TaskArtifactsList.tsx b/products/desktop/packages/ui/src/features/canvas/components/TaskArtifactsList.tsx
index f72dc50ece1f..4e0a5a35ace9 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/TaskArtifactsList.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/TaskArtifactsList.tsx
@@ -8,6 +8,7 @@ import {
} from "@phosphor-icons/react";
import type { ResourceComment } from "@posthog/api-client/posthog-client";
import {
+ getPostHogObjectArtifactMetadata,
type RunArtifactVersions,
runArtifactVersionKey,
} from "@posthog/core/canvas/runArtifactSchemas";
@@ -56,6 +57,7 @@ import {
import { FileIcon } from "@posthog/ui/primitives/FileIcon";
import { openExternalUrl } from "@posthog/ui/shell/openExternal";
import { formatFileSize } from "@posthog/ui/utils/formatFileSize";
+import { getObjectKind } from "@posthog/ui/utils/objectKinds";
import { useMemo, useState } from "react";
const EMPTY_COMMENTS: ResourceComment[] = [];
@@ -335,6 +337,48 @@ function FileRow({
);
}
+function PostHogObjectRow({
+ taskId,
+ artifactId,
+ runId,
+ name,
+ objectKind,
+ occurrenceCount,
+ uploadedAt,
+ commentCount,
+}: {
+ taskId: string;
+ artifactId: string;
+ runId: string;
+ name: string;
+ objectKind: string;
+ occurrenceCount: number;
+ uploadedAt: string | undefined;
+ commentCount: number;
+}) {
+ const openArtifactTab = usePanelLayoutStore((state) => state.openArtifactTab);
+ const object = getObjectKind(objectKind);
+ const ObjectIcon = object.icon;
+ const meta = [
+ object.kindLabel,
+ object.source,
+ occurrenceCount > 1 ? `Referenced ${occurrenceCount} times` : null,
+ uploadedAt ? formatRelativeTimeShort(uploadedAt) : null,
+ ]
+ .filter(Boolean)
+ .join(" · ");
+
+ return (
+ <ArtifactCard
+ icon={<ObjectIcon size={16} />}
+ title={name}
+ meta={meta}
+ onOpen={() => openArtifactTab(taskId, { runId, artifactId, name })}
+ actions={<CommentCountBadge count={commentCount} />}
+ />
+ );
+}
+
export function TaskArtifactsList({
task,
timeline,
@@ -350,7 +394,15 @@ export function TaskArtifactsList({
// the agent just delivered shows up now rather than on the next poll.
const events = useSessionSelector(task.id, (session) => session?.events);
const completedUploads = useCompletedArtifactUploads(events ?? []);
- const { runs } = useTaskRuns(task.id, completedUploads);
+ // Occurrence counts move without changing the entry count when a turn
+ // re-cites an already registered object, so the key sums them too.
+ const referenceRefreshKey = useSessionSelector(task.id, (session) =>
+ (session?.cloudArtifacts ?? []).reduce((sum, artifact) => {
+ const reference = getPostHogObjectArtifactMetadata(artifact);
+ return reference ? sum + 1 + reference.occurrence_count : sum;
+ }, 0),
+ );
+ const { runs } = useTaskRuns(task.id, completedUploads + referenceRefreshKey);
const { data: currentUser } = useMeQuery();
const rows = useMemo(
() => buildRows(task, timeline, runs),
@@ -420,6 +472,18 @@ export function TaskArtifactsList({
}
currentUser={currentUser}
/>
+ ) : row.kind === "posthog_object" ? (
+ <PostHogObjectRow
+ key={row.key}
+ taskId={task.id}
+ artifactId={row.artifactId}
+ runId={row.runId}
+ name={row.name}
+ objectKind={row.metadata.object_kind}
+ occurrenceCount={row.metadata.occurrence_count}
+ uploadedAt={row.uploadedAt}
+ commentCount={openCountByItem.get(row.artifactId) ?? 0}
+ />
) : (
<ArtifactCard
key={row.key}
diff --git a/products/desktop/packages/ui/src/features/canvas/components/activityRows.tsx b/products/desktop/packages/ui/src/features/canvas/components/activityRows.tsx
index 55af3416d976..83d3ed3dd896 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/activityRows.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/activityRows.tsx
@@ -53,6 +53,7 @@ import { useCommentsQuery } from "@posthog/ui/features/sessions/components/useCo
import { useArtifactDownload } from "@posthog/ui/features/sessions/useArtifactDownload";
import { ArtifactChip } from "@posthog/ui/primitives/ArtifactChip";
import { openExternalUrl } from "@posthog/ui/shell/openExternal";
+import { getObjectKind } from "@posthog/ui/utils/objectKinds";
import { parseHttpsUrl } from "@posthog/ui/utils/posthogLinks";
import { type ReactNode, useMemo, useState } from "react";
@@ -304,7 +305,10 @@ function eventLabel(
case "artifact_created":
return (
<>
- Agent created{" "}
+ Agent{" "}
+ {event.payload.referenceType === "posthog_object"
+ ? "added"
+ : "created"}{" "}
<span className="font-medium">{event.payload.name}</span>
</>
);
@@ -527,13 +531,21 @@ export function ArtifactEventDetail({
}) {
const { download, downloadingId } = useArtifactDownload();
const runId = payload.runId;
- const canDownload = Boolean(taskId && runId && payload.artifactId);
+ const isPostHogReference = payload.referenceType === "posthog_object";
+ const objectKind = getObjectKind(payload.objectKind ?? "");
+ const canDownload = Boolean(
+ !isPostHogReference && taskId && runId && payload.artifactId,
+ );
return (
<ArtifactChip
label={payload.name}
name={payload.name}
- meta={`v${payload.version}`}
+ meta={
+ isPostHogReference
+ ? `${objectKind.kindLabel} · ${objectKind.source}`
+ : `v${payload.version}`
+ }
onOpen={onOpen}
onDownload={
canDownload && taskId && runId
@@ -708,13 +720,18 @@ export function ActivityEventRow({
runOrdinal?: number;
detail?: ReactNode;
}) {
+ const ObjectIcon =
+ event.kind === "artifact_created" &&
+ event.payload.referenceType === "posthog_object"
+ ? getObjectKind(event.payload.objectKind ?? "").icon
+ : null;
return (
<TimelineRow
connectedAbove={connectedAbove}
connectedBelow={connectedBelow}
gutter={
<EventBead tone={EVENT_TONES[event.kind]}>
- {EVENT_ICONS[event.kind]}
+ {ObjectIcon ? <ObjectIcon size={11} /> : EVENT_ICONS[event.kind]}
</EventBead>
}
timestamp={timestamp}
diff --git a/products/desktop/packages/ui/src/features/canvas/components/taskArtifactRows.test.ts b/products/desktop/packages/ui/src/features/canvas/components/taskArtifactRows.test.ts
new file mode 100644
index 000000000000..7417462aa982
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/canvas/components/taskArtifactRows.test.ts
@@ -0,0 +1,85 @@
+import type { Task, TaskRun } from "@posthog/shared";
+import { describe, expect, it } from "vitest";
+import {
+ type ArtifactRow,
+ buildRows,
+ commentSources,
+ commentTargets,
+} from "./taskArtifactRows";
+
+describe("commentSources", () => {
+ it("makes reference rows commentable, agreeing with commentTargets", () => {
+ const row: ArtifactRow = {
+ kind: "posthog_object",
+ key: "posthog-object:art-1",
+ artifactId: "art-1",
+ name: "Checkout funnel",
+ runId: "run-1",
+ metadata: {
+ reference_type: "posthog_object",
+ object_kind: "insight",
+ object_id: "9pQx3",
+ source_message_ids: ["msg-1"],
+ occurrence_count: 1,
+ },
+ uploadedAt: undefined,
+ };
+
+ const referenceSource = commentSources("task-1", [row]).find(
+ (source) => source.kind === "posthog_object",
+ );
+
+ expect(referenceSource).toEqual({
+ kind: "posthog_object",
+ target: { scope: "task_artifact", itemId: "art-1" },
+ name: "Checkout funnel",
+ runId: "run-1",
+ });
+ // The Artifacts pane badge (commentTargets) and the Comments pane
+ // (commentSources) must agree on which resources can hold threads.
+ expect(commentTargets([row])).toContainEqual(referenceSource?.target);
+ });
+});
+
+describe("buildRows", () => {
+ it("counts a reference cited by several runs across the whole task", () => {
+ const reference = (uploadedAt: string, messageIds: string[]) => ({
+ id: "phref-1",
+ name: "Checkout funnel",
+ type: "reference",
+ uploaded_at: uploadedAt,
+ metadata: {
+ reference_type: "posthog_object",
+ object_kind: "insight",
+ object_id: "9pQx3",
+ source_message_ids: messageIds,
+ occurrence_count: messageIds.length,
+ },
+ });
+ const runs = [
+ {
+ id: "run-1",
+ updated_at: "2026-08-01T00:00:00Z",
+ artifacts: [reference("2026-08-01T00:00:00Z", ["msg-1", "msg-2"])],
+ },
+ {
+ id: "run-2",
+ updated_at: "2026-08-02T00:00:00Z",
+ artifacts: [reference("2026-08-02T00:00:00Z", ["msg-2", "msg-3"])],
+ },
+ ] as unknown as TaskRun[];
+
+ const rows = buildRows({ id: "task-1" } as Task, [], runs).filter(
+ (row) => row.kind === "posthog_object",
+ );
+
+ expect(rows).toHaveLength(1);
+ expect(rows[0]).toMatchObject({
+ runId: "run-2",
+ metadata: {
+ source_message_ids: ["msg-1", "msg-2", "msg-3"],
+ occurrence_count: 3,
+ },
+ });
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/canvas/components/taskArtifactRows.ts b/products/desktop/packages/ui/src/features/canvas/components/taskArtifactRows.ts
index 3f88d4db2f47..105b899c47bd 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/taskArtifactRows.ts
+++ b/products/desktop/packages/ui/src/features/canvas/components/taskArtifactRows.ts
@@ -1,6 +1,8 @@
import {
+ getPostHogObjectArtifactMetadata,
groupRunArtifactVersions,
OUTPUT_ARTIFACT_TYPES,
+ type PostHogObjectArtifactMetadata,
parseRunArtifacts,
type RunArtifact,
type RunArtifactVersions,
@@ -40,6 +42,15 @@ export type ArtifactRow =
size: number | undefined;
group: RunArtifactVersions<RunFile>;
}
+ | {
+ kind: "posthog_object";
+ key: string;
+ artifactId: string;
+ name: string;
+ runId: string;
+ metadata: PostHogObjectArtifactMetadata;
+ uploadedAt: string | undefined;
+ }
| { kind: "slack"; key: string; url: string };
/**
@@ -49,6 +60,12 @@ export type ArtifactRow =
*/
export type CommentSource =
| { kind: "file"; target: CommentTarget; name: string; runId: string | null }
+ | {
+ kind: "posthog_object";
+ target: CommentTarget;
+ name: string;
+ runId: string;
+ }
| { kind: "canvas"; target: CommentTarget; name: string; url: string | null }
| { kind: "task"; target: CommentTarget; name: string };
@@ -70,6 +87,13 @@ export function commentSources(
seen.add(commentTargetKey(target));
if (row.kind === "file") {
sources.push({ kind: "file", target, name: row.name, runId: row.runId });
+ } else if (row.kind === "posthog_object") {
+ sources.push({
+ kind: "posthog_object",
+ target,
+ name: row.name,
+ runId: row.runId,
+ });
} else if (row.kind === "canvas") {
sources.push({ kind: "canvas", target, name: row.name, url: row.url });
}
@@ -106,7 +130,10 @@ function canvasDashboardId(url: string | null): string | null {
/** Where a row's comments live, or null when the row can't carry any. */
function targetForRow(row: ArtifactRow): CommentTarget | null {
- if (row.kind === "file" && row.artifactId) {
+ if (
+ (row.kind === "file" || row.kind === "posthog_object") &&
+ row.artifactId
+ ) {
return { scope: "task_artifact", itemId: row.artifactId };
}
if (row.kind === "canvas" && row.dashboardId) {
@@ -137,6 +164,25 @@ function readRunOutputs(run: TaskRun): RunArtifact[] {
);
}
+function readRunPostHogReferences(run: TaskRun): Array<{
+ artifact: RunArtifact & { id: string; name: string };
+ metadata: PostHogObjectArtifactMetadata;
+}> {
+ return parseRunArtifacts((run as { artifacts?: unknown }).artifacts, [
+ "reference",
+ ]).flatMap((artifact) => {
+ const metadata = getPostHogObjectArtifactMetadata(artifact);
+ return artifact.id && artifact.name && metadata
+ ? [
+ {
+ artifact: { ...artifact, id: artifact.id, name: artifact.name },
+ metadata,
+ },
+ ]
+ : [];
+ });
+}
+
export function buildRows(
task: Task,
timeline: ThreadTimelineRow<TaskThreadMessage>[],
@@ -172,6 +218,14 @@ export function buildRows(
runs.length > 0 ? runs : task.latest_run ? [task.latest_run] : [];
const files: RunFile[] = [];
+ const postHogReferences = new Map<
+ string,
+ {
+ artifact: RunArtifact & { id: string; name: string };
+ metadata: PostHogObjectArtifactMetadata;
+ runId: string;
+ }
+ >();
for (const run of allRuns) {
// Runs added straight from output have no announcing timeline message, so
// the run's own updated_at is the closest stand-in for the PR's age.
@@ -182,6 +236,29 @@ export function buildRows(
files.push(
...readRunOutputs(run).map((file) => ({ ...file, runId: run.id })),
);
+ for (const reference of readRunPostHogReferences(run)) {
+ const existing = postHogReferences.get(reference.artifact.id);
+ const sourceMessageIds = [
+ ...new Set([
+ ...(existing?.metadata.source_message_ids ?? []),
+ ...reference.metadata.source_message_ids,
+ ]),
+ ];
+ const newest =
+ existing &&
+ (existing.artifact.uploaded_at ?? "") >=
+ (reference.artifact.uploaded_at ?? "")
+ ? existing
+ : { ...reference, runId: run.id };
+ postHogReferences.set(reference.artifact.id, {
+ ...newest,
+ metadata: {
+ ...newest.metadata,
+ source_message_ids: sourceMessageIds,
+ occurrence_count: sourceMessageIds.length,
+ },
+ });
+ }
}
for (const group of groupRunArtifactVersions(files)) {
if (group.dismissed) continue;
@@ -196,6 +273,19 @@ export function buildRows(
});
}
+ for (const { artifact, metadata, runId } of postHogReferences.values()) {
+ if (artifact.dismissed_at) continue;
+ rows.push({
+ kind: "posthog_object",
+ key: `posthog-object:${artifact.id}`,
+ artifactId: artifact.id,
+ name: artifact.name,
+ runId,
+ metadata,
+ uploadedAt: artifact.uploaded_at,
+ });
+ }
+
const slackUrl = task.latest_run?.state?.slack_thread_url;
if (typeof slackUrl === "string" && slackUrl) {
rows.push({ kind: "slack", key: "slack-thread", url: slackUrl });
diff --git a/products/desktop/packages/ui/src/features/canvas/components/taskCommentThreads.ts b/products/desktop/packages/ui/src/features/canvas/components/taskCommentThreads.ts
index 27972a40bd92..b8920a9b427c 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/taskCommentThreads.ts
+++ b/products/desktop/packages/ui/src/features/canvas/components/taskCommentThreads.ts
@@ -50,7 +50,7 @@ export type TaskCommentThread = {
/** Groups threads for the source filter. */
sourceKey: string;
sourceLabel: string;
- sourceKind: "file" | "canvas" | "task" | "pr";
+ sourceKind: "file" | "canvas" | "task" | "posthog_object" | "pr";
entries: CommentEntry[];
resolved: boolean;
/** When the thread was opened, for ordering the list. Ordering on the newest
diff --git a/products/desktop/packages/ui/src/features/posthog-objects/PostHogObjectPage.stories.tsx b/products/desktop/packages/ui/src/features/posthog-objects/PostHogObjectPage.stories.tsx
new file mode 100644
index 000000000000..d06603791211
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/posthog-objects/PostHogObjectPage.stories.tsx
@@ -0,0 +1,40 @@
+import {
+ ANONYMOUS_AUTH_STATE,
+ useAuthStore,
+} from "@posthog/ui/features/auth/store";
+import { PostHogObjectPage } from "@posthog/ui/features/posthog-objects/PostHogObjectPage";
+import type { Meta, StoryObj } from "@storybook/react-vite";
+
+const meta: Meta<typeof PostHogObjectPage> = {
+ title: "Features/PostHog objects/PostHogObjectPage",
+ component: PostHogObjectPage,
+ parameters: { layout: "fullscreen" },
+ decorators: [
+ (Story) => {
+ useAuthStore.setState({
+ authState: {
+ ...ANONYMOUS_AUTH_STATE,
+ cloudRegion: "us",
+ currentProjectId: 2,
+ },
+ });
+ return <Story />;
+ },
+ ],
+};
+
+export default meta;
+type Story = StoryObj<typeof PostHogObjectPage>;
+
+export const InsightReference: Story = {
+ args: {
+ fallbackName: "Checkout funnel",
+ metadata: {
+ reference_type: "posthog_object",
+ object_kind: "insight",
+ object_id: "9pQx3",
+ source_message_ids: ["turn-1"],
+ occurrence_count: 2,
+ },
+ },
+};
diff --git a/products/desktop/packages/ui/src/features/posthog-objects/PostHogObjectPage.test.tsx b/products/desktop/packages/ui/src/features/posthog-objects/PostHogObjectPage.test.tsx
new file mode 100644
index 000000000000..8f899b80fb4a
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/posthog-objects/PostHogObjectPage.test.tsx
@@ -0,0 +1,67 @@
+import { Theme } from "@radix-ui/themes";
+import { fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { describe, expect, it, vi } from "vitest";
+import { PostHogObjectPage } from "./PostHogObjectPage";
+
+const writeText = vi.fn().mockResolvedValue(undefined);
+
+vi.mock("@posthog/ui/hooks/useAuthenticatedQuery", () => ({
+ useAuthenticatedQuery: () => ({
+ isPending: false,
+ isError: false,
+ data: {
+ title: "new-checkout-flow",
+ detail: "Enabled",
+ facts: ["100% rollout", "Used by 1 experiment"],
+ // The preview resolves the flag key to its numeric id.
+ resolvedId: "42",
+ },
+ }),
+}));
+
+vi.mock("@posthog/ui/features/editor/components/EvidenceRefChip", () => ({
+ // Mirror the real hook: a flag page resolves only from a numeric id, so the
+ // link is available only if the page passes the resolved id, not the key.
+ useEvidenceUrl: (_kind: string, id: string) =>
+ /^\d+$/.test(id)
+ ? `https://us.posthog.com/project/2/feature_flags/${id}`
+ : null,
+}));
+
+describe("PostHogObjectPage", () => {
+ it("renders live reference details and copies the exact identifier", async () => {
+ Object.defineProperty(navigator, "clipboard", {
+ configurable: true,
+ value: { writeText },
+ });
+ render(
+ <Theme>
+ <PostHogObjectPage
+ fallbackName="Flag fallback"
+ metadata={{
+ reference_type: "posthog_object",
+ object_kind: "flag",
+ object_id: "new-checkout-flow",
+ source_message_ids: ["turn-1", "turn-2"],
+ occurrence_count: 2,
+ }}
+ />
+ </Theme>,
+ );
+
+ expect(screen.getAllByText("new-checkout-flow")).toHaveLength(2);
+ expect(screen.getByText("100% rollout")).toBeInTheDocument();
+ expect(
+ screen.getByText("Referenced 2 times in this task"),
+ ).toBeInTheDocument();
+ // A flag cited by key still links out, via the resolved numeric id.
+ expect(screen.getByText(/Open in PostHog/)).toBeInTheDocument();
+ fireEvent.click(screen.getByRole("button", { name: "Copy reference" }));
+ expect(writeText).toHaveBeenCalledWith("new-checkout-flow");
+ await waitFor(() =>
+ expect(
+ screen.getByRole("button", { name: "Reference copied" }),
+ ).toBeInTheDocument(),
+ );
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/posthog-objects/PostHogObjectPage.tsx b/products/desktop/packages/ui/src/features/posthog-objects/PostHogObjectPage.tsx
new file mode 100644
index 000000000000..772d04a74c06
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/posthog-objects/PostHogObjectPage.tsx
@@ -0,0 +1,171 @@
+import { CheckIcon, CopyIcon } from "@phosphor-icons/react";
+import type { PostHogObjectArtifactMetadata } from "@posthog/core/canvas/runArtifactSchemas";
+import { Button, Heading, Skeleton, Text } from "@posthog/quill";
+import { useEvidenceUrl } from "@posthog/ui/features/editor/components/EvidenceRefChip";
+import { MessageChartCard } from "@posthog/ui/features/editor/components/MessageChartCard";
+import {
+ type EvidenceCardData,
+ fetchEvidencePreview,
+} from "@posthog/ui/features/editor/evidencePreview";
+import { useAuthenticatedQuery } from "@posthog/ui/hooks/useAuthenticatedQuery";
+import { useCopy } from "@posthog/ui/primitives/useCopy";
+import { openExternalUrl } from "@posthog/ui/shell/openExternal";
+import { getObjectKind } from "@posthog/ui/utils/objectKinds";
+
+function ObjectContent({
+ metadata,
+ preview,
+}: {
+ metadata: PostHogObjectArtifactMetadata;
+ preview: EvidenceCardData | null;
+}) {
+ if (metadata.object_kind === "insight") {
+ return (
+ <MessageChartCard
+ spec={{ mode: "insight", shortId: metadata.object_id }}
+ blockKey={`artifact:${metadata.object_kind}:${metadata.object_id}`}
+ />
+ );
+ }
+ if (metadata.object_kind === "hogql") {
+ return (
+ <MessageChartCard
+ spec={{ mode: "hogql", query: metadata.object_id }}
+ blockKey={`artifact:${metadata.object_kind}:${metadata.object_id}`}
+ />
+ );
+ }
+ if (metadata.object_kind === "replay") {
+ return (
+ <MessageChartCard
+ spec={{ mode: "replay", sessionId: metadata.object_id }}
+ blockKey={`artifact:${metadata.object_kind}:${metadata.object_id}`}
+ />
+ );
+ }
+ if (!preview) {
+ return (
+ <div className="rounded-md border border-border bg-muted p-4">
+ <Text>This object is not available in the current project.</Text>
+ <Text className="mt-1 text-muted-foreground text-sm">
+ Check the identifier or open PostHog to review access.
+ </Text>
+ </div>
+ );
+ }
+ return (
+ <div className="rounded-md border border-border bg-card p-4">
+ {preview.detail && (
+ <Text className="text-muted-foreground">{preview.detail}</Text>
+ )}
+ {preview.facts && preview.facts.length > 0 && (
+ <div className="mt-3 flex flex-wrap gap-1.5">
+ {preview.facts.map((fact) => (
+ <span
+ key={fact}
+ className="rounded-sm bg-muted px-2 py-1 text-muted-foreground text-xs"
+ >
+ {fact}
+ </span>
+ ))}
+ </div>
+ )}
+ </div>
+ );
+}
+
+export function PostHogObjectPage({
+ metadata,
+ fallbackName,
+}: {
+ metadata: PostHogObjectArtifactMetadata;
+ fallbackName: string;
+}) {
+ const object = getObjectKind(metadata.object_kind);
+ const ObjectIcon = object.icon;
+ const { copied, copy } = useCopy();
+ const usesBlockRenderer =
+ metadata.object_kind === "insight" ||
+ metadata.object_kind === "hogql" ||
+ metadata.object_kind === "replay";
+ const query = useAuthenticatedQuery(
+ ["evidence-preview", metadata.object_kind, metadata.object_id],
+ (client) =>
+ fetchEvidencePreview(client, {
+ kind: metadata.object_kind,
+ id: metadata.object_id,
+ }),
+ {
+ enabled: !usesBlockRenderer,
+ staleTime: 5 * 60 * 1000,
+ refetchOnWindowFocus: false,
+ retry: 1,
+ },
+ );
+ // A flag cited by key or an event cited by name has no page under the cited
+ // id; link out via the id the preview resolved, as EvidenceRefChip does.
+ const url = useEvidenceUrl(
+ metadata.object_kind,
+ query.data?.resolvedId ?? metadata.object_id,
+ );
+ const title = query.data?.title ?? fallbackName;
+
+ return (
+ <div className="h-full overflow-y-auto">
+ <div className="mx-auto flex w-full max-w-4xl flex-col gap-5 px-6 py-7">
+ <header className="flex items-start justify-between gap-4">
+ <div className="min-w-0">
+ <div className="mb-2 flex items-center gap-1.5 text-muted-foreground text-xs uppercase tracking-wide">
+ <ObjectIcon size={14} />
+ <span>{object.kindLabel}</span>
+ <span>·</span>
+ <span>{object.source}</span>
+ </div>
+ <Heading size="xl" className="truncate">
+ {title}
+ </Heading>
+ <div className="mt-2 flex items-center gap-1 font-mono text-muted-foreground text-xs">
+ <span className="max-w-xl truncate">{metadata.object_id}</span>
+ <button
+ type="button"
+ data-attr="posthog-object-copy-reference"
+ aria-label={copied ? "Reference copied" : "Copy reference"}
+ onClick={() => copy(metadata.object_id)}
+ className="inline-flex size-6 cursor-pointer items-center justify-center rounded-sm border-0 bg-transparent hover:bg-fill-hover hover:text-foreground"
+ >
+ {copied ? <CheckIcon size={12} /> : <CopyIcon size={12} />}
+ </button>
+ </div>
+ </div>
+ {url && (
+ <Button
+ variant="outline"
+ data-attr="posthog-object-open-in-posthog"
+ onClick={() => openExternalUrl(url)}
+ >
+ Open in PostHog ↗
+ </Button>
+ )}
+ </header>
+
+ {usesBlockRenderer ? (
+ <ObjectContent metadata={metadata} preview={null} />
+ ) : query.isPending ? (
+ <div className="space-y-3">
+ <Skeleton className="h-44 w-full" />
+ <Skeleton className="h-16 w-full" />
+ </div>
+ ) : query.isError ? (
+ <ObjectContent metadata={metadata} preview={null} />
+ ) : (
+ <ObjectContent metadata={metadata} preview={query.data ?? null} />
+ )}
+
+ <div className="border-border border-t pt-4 text-muted-foreground text-xs">
+ Referenced {metadata.occurrence_count.toLocaleString()}{" "}
+ {metadata.occurrence_count === 1 ? "time" : "times"} in this task
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/products/desktop/packages/ui/src/features/sessions/components/ArtifactPreview.test.tsx b/products/desktop/packages/ui/src/features/sessions/components/ArtifactPreview.test.tsx
index 923ac6998332..d7bea66dea77 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/ArtifactPreview.test.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/ArtifactPreview.test.tsx
@@ -74,6 +74,12 @@ vi.mock("@posthog/ui/features/panels/panelLayoutStore", () => ({
usePanelLayoutStore: () => artifactMocks.openArtifactTab,
}));
+vi.mock("@posthog/ui/features/posthog-objects/PostHogObjectPage", () => ({
+ PostHogObjectPage: ({ fallbackName }: { fallbackName: string }) => (
+ <div data-testid="posthog-object-page">{fallbackName}</div>
+ ),
+}));
+
vi.mock("@posthog/ui/features/canvas/hooks/useTaskRuns", () => ({
useTaskRuns: () => ({
runs: taskRuns.data,
@@ -284,7 +290,7 @@ describe("ArtifactPreview", () => {
).toBeUndefined();
});
- it("starts the manifest and preview URL requests together", async () => {
+ it("requests the manifest and the preview URL in parallel", async () => {
let resolveArtifacts: (artifacts: unknown[]) => void = () => undefined;
artifactMocks.getCloudRunArtifacts.mockReturnValue(
new Promise((resolve) => {
@@ -305,15 +311,79 @@ describe("ArtifactPreview", () => {
const queryFn = useQuery.mock.calls[0]?.[0]
.queryFn as () => Promise<unknown>;
const result = queryFn();
+ // The URL request must not wait for the manifest to resolve.
expect(artifactMocks.getCloudAttachmentPreviewUrl).toHaveBeenCalledWith(
"task-1",
"run-1",
"artifact-1",
);
- resolveArtifacts([]);
+ resolveArtifacts([
+ {
+ id: "artifact-1",
+ name: "report.html",
+ type: "output",
+ storage_path: "runs/1/report.html",
+ },
+ ]);
await expect(result).rejects.toThrow("Artifact is unavailable");
});
+ it("renders PostHog references even when no preview URL exists", async () => {
+ const metadata = {
+ reference_type: "posthog_object",
+ object_kind: "insight",
+ object_id: "9pQx3",
+ source_message_ids: ["turn-1"],
+ occurrence_count: 1,
+ } as const;
+ const artifact = {
+ id: "phref-1",
+ name: "Checkout funnel",
+ type: "reference",
+ metadata,
+ };
+ artifactMocks.getCloudRunArtifacts.mockResolvedValue([artifact]);
+ // A reference has no storage path, so the parallel URL read is a no-op.
+ artifactMocks.getCloudAttachmentPreviewUrl.mockResolvedValue(null);
+
+ render(
+ <ArtifactPreview
+ taskId="task-1"
+ runId="run-1"
+ artifactId="phref-1"
+ name="Checkout funnel"
+ />,
+ );
+ const queryFn = useQuery.mock.calls[0]?.[0]
+ .queryFn as () => Promise<unknown>;
+ await expect(queryFn()).resolves.toEqual({
+ artifact,
+ artifacts: [artifact],
+ preview: { kind: "posthog-object", metadata },
+ });
+
+ useQuery.mockReturnValue({
+ data: {
+ artifact,
+ artifacts: [artifact],
+ preview: { kind: "posthog-object", metadata },
+ },
+ isLoading: false,
+ isError: false,
+ });
+ render(
+ <ArtifactPreview
+ taskId="task-1"
+ runId="run-1"
+ artifactId="phref-1"
+ name="Checkout funnel"
+ />,
+ );
+ expect(screen.getByTestId("posthog-object-page")).toHaveTextContent(
+ "Checkout funnel",
+ );
+ });
+
it("keeps the artifact visible when comments fail to load", () => {
artifactComments.isError = true;
useQuery.mockReturnValue({
diff --git a/products/desktop/packages/ui/src/features/sessions/components/ArtifactPreview.tsx b/products/desktop/packages/ui/src/features/sessions/components/ArtifactPreview.tsx
index 01b9a6ad427d..4e9487bed69e 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/ArtifactPreview.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/ArtifactPreview.tsx
@@ -1,6 +1,7 @@
import { CaretLeftIcon, CaretRightIcon } from "@phosphor-icons/react";
import type { ResourceComment } from "@posthog/api-client/posthog-client";
import {
+ getPostHogObjectArtifactMetadata,
groupRunArtifactVersions,
OUTPUT_ARTIFACT_TYPES,
parseRunArtifacts,
@@ -24,6 +25,7 @@ import {
import { useOrgMembers } from "@posthog/ui/features/canvas/hooks/useOrgMembers";
import { useTaskRuns } from "@posthog/ui/features/canvas/hooks/useTaskRuns";
import { usePanelLayoutStore } from "@posthog/ui/features/panels/panelLayoutStore";
+import { PostHogObjectPage } from "@posthog/ui/features/posthog-objects/PostHogObjectPage";
import { useCommentNavigationStore } from "@posthog/ui/features/sessions/commentNavigationStore";
import { useSessionSelector } from "@posthog/ui/features/sessions/sessionStore";
import {
@@ -48,12 +50,25 @@ import { useCompletedArtifactUploads } from "./countArtifactUploads";
import { useArtifactEditing } from "./useArtifactEditing";
import {
editorFilePath,
+ type PostHogObjectPreview,
+ type PreviewData,
useArtifactPreviewData,
} from "./useArtifactPreviewData";
import { useCommentsQuery, useCreateComment } from "./useComments";
const EMPTY_COMMENTS: ResourceComment[] = [];
+function isPostHogObjectPreview(
+ previewData: PreviewData | undefined,
+): previewData is PostHogObjectPreview {
+ return (
+ !!previewData &&
+ typeof previewData === "object" &&
+ !(previewData instanceof Blob) &&
+ previewData.kind === "posthog-object"
+ );
+}
+
type ArtifactVersion = TaskRunArtifact & { runId: string };
function artifactVersionsFromRuns(
@@ -61,19 +76,19 @@ function artifactVersionsFromRuns(
name: string,
): ArtifactVersion[] {
const files = runs.flatMap((run) =>
- parseRunArtifacts(run.artifacts, OUTPUT_ARTIFACT_TYPES).flatMap((file) =>
- file.name === name && file.id
- ? [
- {
- ...file,
- id: file.id,
- name: file.name,
- type: file.type as TaskRunArtifact["type"],
- runId: run.id,
- },
- ]
- : [],
- ),
+ parseRunArtifacts(run.artifacts, OUTPUT_ARTIFACT_TYPES).flatMap((file) => {
+ if (file.name !== name || !file.id) return [];
+ const { metadata: _metadata, ...fileFields } = file;
+ return [
+ {
+ ...fileFields,
+ id: file.id,
+ name: file.name,
+ type: file.type as TaskRunArtifact["type"],
+ runId: run.id,
+ },
+ ];
+ }),
);
return (
groupRunArtifactVersions(files).find((candidate) => candidate.name === name)
@@ -104,6 +119,16 @@ export function ArtifactPreview({
// right away.
const events = useSessionSelector(taskId, (session) => session?.events);
const completedUploads = useCompletedArtifactUploads(events ?? []);
+ // The preview query caches forever under a stable artifact id, but a
+ // reference entry updates in place as later turns cite it again; the store's
+ // cloudArtifacts refresh on every successful registration, so its copy of
+ // the metadata is the live one.
+ const liveReferenceMetadata = useSessionSelector(taskId, (session) => {
+ const entry = session?.cloudArtifacts?.find(
+ (artifact) => artifact.id === artifactId,
+ );
+ return entry ? getPostHogObjectArtifactMetadata(entry) : null;
+ });
const {
runs,
isLoading: runsLoading,
@@ -147,6 +172,9 @@ export function ArtifactPreview({
artifactId: activeArtifactId,
name,
});
+ // An object reference renders its own page below and uses none of the
+ // file-only comment data, so its tab shouldn't run the comments poll.
+ const isObjectPreview = isPostHogObjectPreview(previewData);
const displayedArtifactId = artifactResult?.artifact.id ?? activeArtifactId;
const versionIndex = versions.findIndex(
(version) => version.id === displayedArtifactId,
@@ -157,7 +185,9 @@ export function ArtifactPreview({
() => ({ scope: "task_artifact", itemId: displayedArtifactId }),
[displayedArtifactId],
);
- const commentsQuery = useCommentsQuery(commentTarget, taskId);
+ const commentsQuery = useCommentsQuery(commentTarget, taskId, {
+ enabled: !isObjectPreview,
+ });
const { members } = useOrgMembers();
const createComment = useCreateComment(commentTarget, taskId);
const requestCommentFocus = useCommentNavigationStore(
@@ -311,6 +341,15 @@ export function ArtifactPreview({
}
if (isError || imageError) return <ArtifactPreviewError />;
+ if (isPostHogObjectPreview(previewData)) {
+ return (
+ <PostHogObjectPage
+ metadata={liveReferenceMetadata ?? previewData.metadata}
+ fallbackName={name}
+ />
+ );
+ }
+
if (
editing.isEditing &&
artifactResult?.source !== undefined &&
diff --git a/products/desktop/packages/ui/src/features/sessions/components/useArtifactPreviewData.ts b/products/desktop/packages/ui/src/features/sessions/components/useArtifactPreviewData.ts
index 197ad2ef8647..949daa3709b7 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/useArtifactPreviewData.ts
+++ b/products/desktop/packages/ui/src/features/sessions/components/useArtifactPreviewData.ts
@@ -1,4 +1,8 @@
-import { groupRunArtifactVersions } from "@posthog/core/canvas/runArtifactSchemas";
+import {
+ getPostHogObjectArtifactMetadata,
+ groupRunArtifactVersions,
+ type PostHogObjectArtifactMetadata,
+} from "@posthog/core/canvas/runArtifactSchemas";
import type { SessionService } from "@posthog/core/sessions/sessionService";
import type { TaskRunArtifact } from "@posthog/shared";
import { AUTH_SCOPED_QUERY_META } from "@posthog/ui/features/auth/useCurrentUser";
@@ -10,7 +14,11 @@ const MARKDOWN_EXTENSIONS = new Set(["md", "mdx", "markdown"]);
const HTML_EXTENSIONS = new Set(["html", "htm"]);
export type HtmlPreview = { kind: "html"; html: string };
-export type PreviewData = string | Blob | HtmlPreview;
+export type PostHogObjectPreview = {
+ kind: "posthog-object";
+ metadata: PostHogObjectArtifactMetadata;
+};
+export type PreviewData = string | Blob | HtmlPreview | PostHogObjectPreview;
export type EditableArtifactKind = "html" | "markdown" | "plain-text";
export interface ArtifactPreviewResult {
@@ -103,6 +111,9 @@ export function useArtifactPreviewData({
artifactId,
],
queryFn: async () => {
+ // The parallel pair shares one in-flight manifest read; a reference
+ // artifact resolves to a null URL there without a presign, so checking
+ // its metadata after the pair costs no extra request.
const [artifacts, url] = await Promise.all([
sessionService.getCloudRunArtifacts(taskId, runId),
sessionService.getCloudAttachmentPreviewUrl(taskId, runId, artifactId),
@@ -111,6 +122,14 @@ export function useArtifactPreviewData({
(candidate) => candidate.id === artifactId,
);
if (!artifact) throw new Error("Artifact is unavailable");
+ const reference = getPostHogObjectArtifactMetadata(artifact);
+ if (reference) {
+ return {
+ artifact,
+ artifacts,
+ preview: { kind: "posthog-object", metadata: reference },
+ };
+ }
if (!url) throw new Error("Artifact is unavailable");
const response = await fetch(url);
if (!response.ok) throw new Error("Artifact preview failed");
diff --git a/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.test.ts b/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.test.ts
index f00f8733f722..42dd750fda3f 100644
--- a/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.test.ts
+++ b/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.test.ts
@@ -134,6 +134,7 @@ const mockAuthenticatedClient = vi.hoisted(() => ({
finalizeTaskRunArtifactUploads: vi.fn(),
prepareTaskStagedArtifactUploads: vi.fn(),
finalizeTaskStagedArtifactUploads: vi.fn(),
+ registerTaskRunPostHogReferences: vi.fn(),
presignTaskRunArtifact: vi.fn(),
startGithubUserIntegrationConnect: vi.fn(),
getTaskRunSessionLogsResult: vi.fn(),
@@ -562,6 +563,9 @@ describe("SessionService", () => {
mockAuthenticatedClient.finalizeTaskStagedArtifactUploads.mockResolvedValue(
[],
);
+ mockAuthenticatedClient.registerTaskRunPostHogReferences.mockResolvedValue(
+ [],
+ );
mockAuthenticatedClient.startGithubUserIntegrationConnect.mockResolvedValue(
{
install_url: "https://github.com/login/oauth/authorize",
@@ -2970,6 +2974,130 @@ describe("SessionService", () => {
expect(disarmed).toBe(false);
});
+ it("registers object references from a completed hydrated turn", async () => {
+ const service = getSessionService();
+ const session = createMockSession({
+ taskRunId: "run-123",
+ taskId: "task-123",
+ isCloud: true,
+ currentPromptId: 42,
+ });
+ mockSessionStoreSetters.getSessionByTaskId.mockReturnValue(session);
+ mockSessionStoreSetters.getSessions.mockReturnValue({
+ "run-123": session,
+ });
+ mockTrpcLogs.readLocalLogs.query.mockResolvedValue("");
+ mockTrpcLogs.fetchS3Logs.query.mockResolvedValue("{}");
+ mockTrpcLogs.writeLocalLogs.mutate.mockResolvedValue(undefined);
+ mockConvertStoredEntriesToEvents.mockReturnValueOnce([
+ {
+ type: "acp_message",
+ ts: 1700000000,
+ message: {
+ jsonrpc: "2.0",
+ id: 42,
+ method: "session/prompt",
+ params: { prompt: [{ type: "text", text: "check the funnel" }] },
+ },
+ },
+ {
+ type: "acp_message",
+ ts: 1700000001,
+ message: {
+ jsonrpc: "2.0",
+ method: "session/update",
+ params: {
+ update: {
+ sessionUpdate: "agent_message_chunk",
+ content: {
+ type: "text",
+ text: '<insight id="9pQx3">Checkout funnel</insight>',
+ },
+ },
+ },
+ },
+ },
+ {
+ type: "acp_message",
+ ts: 1700000002,
+ message: {
+ jsonrpc: "2.0",
+ method: "_posthog/turn_complete",
+ params: { sessionId: "acp-session", stopReason: "end_turn" },
+ },
+ },
+ ] as AcpMessage[]);
+
+ service.watchCloudTask(
+ "task-123",
+ "run-123",
+ "https://api.anthropic.com",
+ 123,
+ undefined,
+ "https://logs.example.com/run-123",
+ );
+
+ await vi.waitFor(() => {
+ expect(
+ mockAuthenticatedClient.registerTaskRunPostHogReferences,
+ ).toHaveBeenCalledWith("task-123", "run-123", [
+ {
+ name: "Checkout funnel",
+ object_kind: "insight",
+ object_id: "9pQx3",
+ source_message_id: "turn-1700000000",
+ },
+ ]);
+ });
+ });
+
+ it("retries a failed registration batch on the next flush", async () => {
+ const service = getSessionService() as unknown as {
+ registerPostHogReferences(
+ taskId: string,
+ taskRunId: string,
+ references: Array<Record<string, string>>,
+ ): void;
+ };
+ mockBuildAuthenticatedClient.mockReturnValue(mockAuthenticatedClient);
+ mockAuthenticatedClient.registerTaskRunPostHogReferences
+ .mockRejectedValueOnce(new Error("endpoint missing"))
+ .mockResolvedValue([]);
+ const reference = (id: string) => ({
+ name: id,
+ object_kind: "insight",
+ object_id: id,
+ source_message_id: "turn-1",
+ });
+
+ service.registerPostHogReferences("task-retry", "run-retry", [
+ reference("9pQx3"),
+ ]);
+ await vi.waitFor(() => {
+ expect(
+ mockAuthenticatedClient.registerTaskRunPostHogReferences,
+ ).toHaveBeenCalledTimes(1);
+ });
+ service.registerPostHogReferences("task-retry", "run-retry", [
+ reference("new-flow"),
+ ]);
+
+ await vi.waitFor(() => {
+ expect(
+ mockAuthenticatedClient.registerTaskRunPostHogReferences,
+ ).toHaveBeenCalledTimes(2);
+ });
+ expect(
+ mockAuthenticatedClient.registerTaskRunPostHogReferences.mock
+ .calls[1][2],
+ ).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ object_id: "9pQx3" }),
+ expect.objectContaining({ object_id: "new-flow" }),
+ ]),
+ );
+ });
+
it("flushes queued cloud messages on _posthog/turn_complete", async () => {
const service = getSessionService();
// Reset auth client (a prior test may have set it to null).
diff --git a/products/desktop/packages/ui/src/features/sessions/useSessionArtifactCount.test.ts b/products/desktop/packages/ui/src/features/sessions/useSessionArtifactCount.test.ts
index 830a63c14ee1..bd53528353e6 100644
--- a/products/desktop/packages/ui/src/features/sessions/useSessionArtifactCount.test.ts
+++ b/products/desktop/packages/ui/src/features/sessions/useSessionArtifactCount.test.ts
@@ -88,6 +88,27 @@ describe("countArtifacts", () => {
cloudOutput: null,
expected: 2,
},
+ {
+ name: "adds PostHog references to the artifact count",
+ manifest: [
+ {
+ id: "phref-1",
+ name: "Checkout funnel",
+ type: "reference" as const,
+ source: "posthog_object" as const,
+ metadata: {
+ reference_type: "posthog_object" as const,
+ object_kind: "insight",
+ object_id: "9pQx3",
+ source_message_ids: ["turn-1"],
+ occurrence_count: 1,
+ },
+ },
+ ],
+ taskOutput: null,
+ cloudOutput: null,
+ expected: 1,
+ },
])("$name", ({ manifest, taskOutput, cloudOutput, expected }) => {
expect(countArtifacts({ manifest, taskOutput, cloudOutput })).toBe(
expected,
diff --git a/products/desktop/packages/ui/src/features/sessions/useSessionArtifactCount.ts b/products/desktop/packages/ui/src/features/sessions/useSessionArtifactCount.ts
index 56a210d7c55a..d8f208811a37 100644
--- a/products/desktop/packages/ui/src/features/sessions/useSessionArtifactCount.ts
+++ b/products/desktop/packages/ui/src/features/sessions/useSessionArtifactCount.ts
@@ -1,4 +1,7 @@
-import { groupRunArtifactVersions } from "@posthog/core/canvas/runArtifactSchemas";
+import {
+ getPostHogObjectArtifactMetadata,
+ groupRunArtifactVersions,
+} from "@posthog/core/canvas/runArtifactSchemas";
import { mergePrUrls, readPrUrls, type TaskRunArtifact } from "@posthog/shared";
import type { Task } from "@posthog/shared/domain-types";
import { useSessionSelector } from "@posthog/ui/features/sessions/sessionStore";
@@ -66,6 +69,13 @@ export function countArtifacts({
const files = groupRunArtifactVersions(
manifest.filter((artifact) => artifact.type === "output"),
).filter((group) => !group.dismissed).length;
+ const references = new Set(
+ manifest.flatMap((artifact) =>
+ !artifact.dismissed_at && getPostHogObjectArtifactMetadata(artifact)
+ ? [artifact.id ?? `${artifact.type}:${artifact.name}`]
+ : [],
+ ),
+ ).size;
// A PR the run just opened lands in the session's live output before the task
// query refetches, so read both sources and dedupe rather than the task alone,
// or the count misses the PR at the turn boundary the tip waits on.
@@ -73,7 +83,7 @@ export function countArtifacts({
readPrUrls(taskOutput),
readPrUrls(cloudOutput),
).length;
- return files + prs;
+ return files + references + prs;
}
/**
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.py
index b34af8dcfa7f..6de746ca0f2a 100644
--- a/products/tasks/backend/facade/api.py
+++ b/products/tasks/backend/facade/api.py
@@ -3096,7 +3096,7 @@ def upload_task_run_artifacts(
# after the save so it stays off the persisted manifest.
response_manifest = [
{**entry, "url": absolute_uri(_build_artifact_download_path(run, entry["id"]))}
- if entry.get("id")
+ if entry.get("id") and entry.get("storage_path")
else dict(entry)
for entry in manifest
]
@@ -3104,6 +3104,101 @@ def upload_task_run_artifacts(
return uploaded, response_manifest
+# Each request is capped by the serializer, but entries accumulate across requests on
+# one TaskRun.artifacts JSON value; without a total budget a caller could grow that row
+# (and every later read of it) without bound.
+MAX_RUN_REFERENCE_ARTIFACTS = 100
+
+
+def register_task_run_posthog_references(
+ run_id: str | UUID,
+ task_id: str | UUID,
+ team_id: int,
+ *,
+ references: list[dict[str, Any]],
+ caller_is_agent: bool = False,
+ acting_user_id: int | None = None,
+) -> list[dict[str, Any]] | None:
+ run = _get_visible_run(run_id, task_id, team_id)
+ if run is None:
+ return None
+
+ # Only the task-bound sandbox identity is a verified agent; every other
+ # caller is recorded as themselves and posts no agent-authored thread event.
+ attribute_as_agent = caller_is_agent
+
+ created: list[dict[str, Any]] = []
+ with transaction.atomic():
+ run = TaskRun.objects.select_for_update().get(pk=run.pk)
+ manifest = [dict(entry) for entry in (run.artifacts or []) if isinstance(entry, dict)]
+ by_id = {str(entry.get("id")): entry for entry in manifest if entry.get("id")}
+ reference_count = sum(1 for entry in manifest if entry.get("type") == "reference")
+ now = django_timezone.now().isoformat()
+
+ for reference in references:
+ object_kind = str(reference["object_kind"])
+ object_id = str(reference["object_id"])
+ source_message_id = str(reference["source_message_id"])
+ digest = hashlib.sha256(f"{object_kind}\0{object_id}".encode()).hexdigest()[:24]
+ artifact_id = f"phref_{digest}"
+ existing = by_id.get(artifact_id)
+ if existing is not None:
+ metadata = dict(existing.get("metadata") or {})
+ source_message_ids = list(metadata.get("source_message_ids") or [])
+ if source_message_id in source_message_ids or len(source_message_ids) >= 100:
+ continue
+ source_message_ids.append(source_message_id)
+ metadata["source_message_ids"] = source_message_ids
+ metadata["occurrence_count"] = len(source_message_ids)
+ existing["metadata"] = metadata
+ continue
+
+ if reference_count >= MAX_RUN_REFERENCE_ARTIFACTS:
+ continue
+ reference_count += 1
+ name = re.sub(r"[\[\]\n]", " ", str(reference["name"])).strip()[:255] or object_id[:255]
+ entry = {
+ "id": artifact_id,
+ "name": name,
+ "type": "reference",
+ "source": "posthog_object",
+ "uploaded_at": now,
+ "uploaded_by": "agent" if attribute_as_agent else "user",
+ **({} if attribute_as_agent or acting_user_id is None else {"uploaded_by_user_id": acting_user_id}),
+ "metadata": {
+ "reference_type": "posthog_object",
+ "object_kind": object_kind,
+ "object_id": object_id,
+ "source_message_ids": [source_message_id],
+ "occurrence_count": 1,
+ },
+ }
+ manifest.append(entry)
+ by_id[artifact_id] = entry
+ created.append(entry)
+
+ _save_artifact_manifest(run, manifest)
+
+ for entry in created if attribute_as_agent else []:
+ reference_metadata = entry.get("metadata")
+ if not isinstance(reference_metadata, dict):
+ continue
+ post_artifact_thread_update(
+ run,
+ {
+ "id": entry["id"],
+ "name": entry["name"],
+ "artifact_type": entry["type"],
+ "reference_type": reference_metadata["reference_type"],
+ "object_kind": reference_metadata["object_kind"],
+ "current_version": 1,
+ },
+ revised=False,
+ )
+
+ return manifest
+
+
def prepare_task_run_artifact_uploads(
run_id: str | UUID,
task_id: str | UUID,
@@ -3459,7 +3554,8 @@ def presign_task_run_artifact_download(
return None, None
entry = next((a for a in run.artifacts or [] if a.get("id") == artifact_id), None)
- if entry is None:
+ # Reference entries carry no file, so there is nothing to download for them.
+ if entry is None or not entry.get("storage_path"):
return None, "not_found"
filename = str(entry.get("name") or "artifact")
@@ -7999,6 +8095,8 @@ def post_artifact_thread_update(run: TaskRun, artifact: dict, *, revised: bool)
task = Task.objects.select_related("created_by").filter(id=run.task_id, team_id=run.team_id).first()
if task is None or not _agent_thread_updates_enabled(task.created_by):
return
+ reference_type = str(artifact.get("reference_type") or "")[:64]
+ object_kind = str(artifact.get("object_kind") or "")[:64]
event = "artifact_revised" if revised else "artifact_created"
with transaction.atomic():
Task.objects.select_for_update().filter(id=task.id).first()
@@ -8008,18 +8106,19 @@ def post_artifact_thread_update(run: TaskRun, artifact: dict, *, revised: bool)
.exists()
):
return
- _create_agent_thread_message(
- task,
- f"{'Revised' if revised else 'Created'} {name}",
- event=event,
- payload={
- "run_id": str(run.id),
- "artifact_id": artifact_id,
- "name": name,
- "artifact_type": str(artifact.get("artifact_type") or "")[:64],
- "version": version,
- },
- )
+ verb = "Revised" if revised else "Added" if reference_type == "posthog_object" else "Created"
+ payload = {
+ "run_id": str(run.id),
+ "artifact_id": artifact_id,
+ "name": name,
+ "artifact_type": str(artifact.get("artifact_type") or "")[:64],
+ "version": version,
+ }
+ if reference_type:
+ payload["reference_type"] = reference_type
+ if object_kind:
+ payload["object_kind"] = object_kind
+ _create_agent_thread_message(task, f"{verb} {name}", event=event, payload=payload)
except Exception:
logger.exception("Failed to post artifact thread update", extra={"task_id": str(run.task_id)})
diff --git a/products/tasks/backend/presentation/serializers.py b/products/tasks/backend/presentation/serializers.py
index 388fdc29182e..f9315dd306c6 100644
--- a/products/tasks/backend/presentation/serializers.py
+++ b/products/tasks/backend/presentation/serializers.py
@@ -164,6 +164,23 @@ TASK_RUN_ARTIFACT_TYPE_CHOICES = [
TASK_RUN_ARTIFACT_CONTENT_ENCODING_CHOICES = ["utf-8", "base64"]
TASK_RUN_SKILL_BUNDLE_FORMAT_CHOICES = ["zip"]
TASK_RUN_SKILL_SOURCE_CHOICES = ["user", "repo", "marketplace", "codex"]
+POSTHOG_OBJECT_KIND_CHOICES = [
+ "insight",
+ "hogql",
+ "dashboard",
+ "error",
+ "replay",
+ "flag",
+ "experiment",
+ "survey",
+ "ticket",
+ "trace",
+ "eval",
+ "event",
+ "cohort",
+ "action",
+ "person",
+]
TASK_RUN_LIVING_ARTIFACT_TYPE_CHOICES = [choice for choice, _label in TaskArtifactType.choices]
TASK_RUN_LIVING_ARTIFACT_ADAPTER_CHOICES = [choice for choice, _label in TaskArtifactAdapter.choices]
TASK_RUN_LIVING_ARTIFACT_WRITE_ADAPTER_CHOICES = TASK_RUN_LIVING_ARTIFACT_ADAPTER_CHOICES
@@ -239,7 +256,7 @@ class TaskRunUpdateSerializer(serializers.Serializer):
)
-class TaskRunArtifactMetadataSerializer(serializers.Serializer):
+class TaskRunSkillBundleMetadataSerializer(serializers.Serializer):
skill_name = serializers.CharField(
allow_blank=False,
max_length=255,
@@ -263,6 +280,41 @@ class TaskRunArtifactMetadataSerializer(serializers.Serializer):
)
+class TaskRunPostHogReferenceMetadataSerializer(serializers.Serializer):
+ reference_type = serializers.ChoiceField(
+ choices=["posthog_object"],
+ help_text="Reference metadata type. posthog_object identifies a live PostHog object.",
+ )
+ object_kind = serializers.ChoiceField(
+ choices=POSTHOG_OBJECT_KIND_CHOICES,
+ help_text="PostHog object kind used to resolve the reference.",
+ )
+ object_id = serializers.CharField(
+ max_length=16384,
+ help_text="Exact PostHog object identifier, flag key, event name, or SQL query.",
+ )
+ source_message_ids = serializers.ListField(
+ child=serializers.CharField(max_length=255),
+ max_length=100,
+ help_text="Completed assistant message identifiers that referenced the object.",
+ )
+ occurrence_count = serializers.IntegerField(
+ min_value=1,
+ help_text="Number of distinct completed assistant messages that referenced the object.",
+ )
+
+
+@extend_schema_field(
+ PolymorphicProxySerializer(
+ component_name="TaskRunArtifactMetadata",
+ serializers=[TaskRunSkillBundleMetadataSerializer, TaskRunPostHogReferenceMetadataSerializer],
+ resource_type_field_name=None,
+ )
+)
+class TaskRunArtifactMetadataField(serializers.JSONField):
+ pass
+
+
def validate_task_run_artifact_metadata(attrs: dict[str, Any]) -> dict[str, Any]:
artifact_type = attrs.get("type")
metadata = attrs.get("metadata")
@@ -287,12 +339,15 @@ class TaskRunArtifactResponseSerializer(serializers.Serializer):
)
size = serializers.IntegerField(required=False, help_text="Artifact size in bytes")
content_type = serializers.CharField(required=False, allow_blank=True, help_text="Optional MIME type")
- metadata = TaskRunArtifactMetadataSerializer(
+ metadata = TaskRunArtifactMetadataField(
required=False,
- help_text="Optional structured metadata for special artifact types, such as skill bundles.",
+ help_text="Structured metadata for a skill bundle or a PostHog object reference.",
)
- storage_path = serializers.CharField(help_text="S3 object key for the artifact")
- uploaded_at = serializers.CharField(help_text="Timestamp when the artifact was uploaded")
+ storage_path = serializers.CharField(
+ required=False,
+ help_text="S3 object key for file artifacts. Reference artifacts do not have one.",
+ )
+ uploaded_at = serializers.CharField(help_text="Timestamp when the artifact was uploaded or registered")
uploaded_by = serializers.ChoiceField(
choices=["agent", "user"],
required=False,
@@ -936,9 +991,9 @@ class TaskRunArtifactUploadSerializer(serializers.Serializer):
allow_blank=True,
help_text="Optional MIME type for the artifact",
)
- metadata = TaskRunArtifactMetadataSerializer(
+ metadata = TaskRunSkillBundleMetadataSerializer(
required=False,
- help_text="Optional structured metadata for special artifact types, such as skill bundles.",
+ help_text="Skill bundle metadata, required when the artifact type is skill_bundle.",
)
def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:
@@ -980,6 +1035,35 @@ class TaskRunArtifactsUploadResponseSerializer(serializers.Serializer):
artifacts = TaskRunArtifactResponseSerializer(many=True, help_text="Updated list of artifacts on the run")
+class TaskRunPostHogReferenceSerializer(serializers.Serializer):
+ name = serializers.CharField(max_length=255, help_text="Fallback display name for the referenced object.")
+ object_kind = serializers.ChoiceField(
+ choices=POSTHOG_OBJECT_KIND_CHOICES,
+ help_text="PostHog object kind used to resolve the reference.",
+ )
+ object_id = serializers.CharField(
+ max_length=16384,
+ help_text="Exact PostHog object identifier, flag key, event name, or SQL query.",
+ )
+ source_message_id = serializers.CharField(
+ max_length=255,
+ help_text="Stable identifier of the completed assistant message containing the reference.",
+ )
+
+
+class TaskRunPostHogReferencesRequestSerializer(serializers.Serializer):
+ references = serializers.ListField(
+ child=TaskRunPostHogReferenceSerializer(),
+ allow_empty=False,
+ max_length=50,
+ help_text="PostHog object references extracted from one completed assistant message.",
+ )
+
+
+class TaskRunPostHogReferencesResponseSerializer(serializers.Serializer):
+ artifacts = TaskRunArtifactResponseSerializer(many=True, help_text="Updated list of artifacts on the run.")
+
+
class TaskRunLivingArtifactResponseSerializer(serializers.Serializer):
id = serializers.CharField(help_text="Stable living artifact id. Use this id when editing the artifact.")
task_id = serializers.CharField(help_text="Task id this living artifact belongs to.")
@@ -1223,9 +1307,9 @@ class TaskRunArtifactPrepareUploadSerializer(serializers.Serializer):
allow_blank=True,
help_text="Optional MIME type for the artifact upload",
)
- metadata = TaskRunArtifactMetadataSerializer(
+ metadata = TaskRunSkillBundleMetadataSerializer(
required=False,
- help_text="Optional structured metadata for special artifact types, such as skill bundles.",
+ help_text="Skill bundle metadata, required when the artifact type is skill_bundle.",
)
def validate(self, attrs):
@@ -1270,9 +1354,9 @@ class TaskRunArtifactPrepareUploadResponseSerializer(serializers.Serializer):
)
size = serializers.IntegerField(help_text="Expected upload size in bytes")
content_type = serializers.CharField(required=False, allow_blank=True, help_text="Optional MIME type")
- metadata = TaskRunArtifactMetadataSerializer(
+ metadata = TaskRunSkillBundleMetadataSerializer(
required=False,
- help_text="Optional structured metadata for special artifact types, such as skill bundles.",
+ help_text="Skill bundle metadata, required when the artifact type is skill_bundle.",
)
storage_path = serializers.CharField(help_text="S3 object key reserved for the artifact")
expires_in = serializers.IntegerField(help_text="Presigned POST expiry in seconds")
@@ -1303,9 +1387,9 @@ class TaskRunArtifactFinalizeUploadSerializer(serializers.Serializer):
allow_blank=True,
help_text="Optional MIME type recorded for the artifact",
)
- metadata = TaskRunArtifactMetadataSerializer(
+ metadata = TaskRunSkillBundleMetadataSerializer(
required=False,
- help_text="Optional structured metadata for special artifact types, such as skill bundles.",
+ help_text="Skill bundle metadata, required when the artifact type is skill_bundle.",
)
def validate(self, attrs):
@@ -1346,9 +1430,9 @@ class TaskStagedArtifactPrepareUploadSerializer(serializers.Serializer):
allow_blank=True,
help_text="Optional MIME type for the artifact upload",
)
- metadata = TaskRunArtifactMetadataSerializer(
+ metadata = TaskRunSkillBundleMetadataSerializer(
required=False,
- help_text="Optional structured metadata for special artifact types, such as skill bundles.",
+ help_text="Skill bundle metadata, required when the artifact type is skill_bundle.",
)
def validate(self, attrs):
@@ -1387,9 +1471,9 @@ class TaskStagedArtifactPrepareUploadResponseSerializer(serializers.Serializer):
)
size = serializers.IntegerField(help_text="Expected upload size in bytes")
content_type = serializers.CharField(required=False, allow_blank=True, help_text="Optional MIME type")
- metadata = TaskRunArtifactMetadataSerializer(
+ metadata = TaskRunSkillBundleMetadataSerializer(
required=False,
- help_text="Optional structured metadata for special artifact types, such as skill bundles.",
+ help_text="Skill bundle metadata, required when the artifact type is skill_bundle.",
)
storage_path = serializers.CharField(help_text="S3 object key reserved for the staged artifact")
expires_in = serializers.IntegerField(help_text="Presigned POST expiry in seconds")
@@ -1426,9 +1510,9 @@ class TaskStagedArtifactFinalizeUploadSerializer(serializers.Serializer):
allow_blank=True,
help_text="Optional MIME type recorded for the artifact",
)
- metadata = TaskRunArtifactMetadataSerializer(
+ metadata = TaskRunSkillBundleMetadataSerializer(
required=False,
- help_text="Optional structured metadata for special artifact types, such as skill bundles.",
+ help_text="Skill bundle metadata, required when the artifact type is skill_bundle.",
)
def validate(self, attrs):
diff --git a/products/tasks/backend/presentation/views/api.py b/products/tasks/backend/presentation/views/api.py
index 72730477e852..bbb78aa68aa3 100644
--- a/products/tasks/backend/presentation/views/api.py
+++ b/products/tasks/backend/presentation/views/api.py
@@ -153,6 +153,8 @@ from products.tasks.backend.presentation.serializers import (
TaskRunPeerMessageRequestSerializer,
TaskRunPeerMessageResponseSerializer,
TaskRunPeersResponseSerializer,
+ TaskRunPostHogReferencesRequestSerializer,
+ TaskRunPostHogReferencesResponseSerializer,
TaskRunRelayMessageRequestSerializer,
TaskRunRelayMessageResponseSerializer,
TaskRunSessionLogsQuerySerializer,
@@ -1797,6 +1799,40 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
serializer = TaskRunArtifactsUploadResponseSerializer({"artifacts": manifest})
return Response(serializer.data)
+ @validated_request(
+ request_serializer=TaskRunPostHogReferencesRequestSerializer,
+ responses={
+ 200: OpenApiResponse(
+ response=TaskRunPostHogReferencesResponseSerializer,
+ description="Run with updated reference artifacts",
+ ),
+ 404: OpenApiResponse(description="Run not found"),
+ },
+ summary="Register PostHog object references for a task run",
+ description="Attach live PostHog object references to the run artifact manifest without uploading files.",
+ strict_request_validation=True,
+ )
+ @action(
+ detail=True,
+ methods=["post"],
+ url_path="artifacts/references",
+ required_scopes=["task:write"],
+ )
+ def artifacts_references(self, request, pk=None, **kwargs):
+ task_id = self._ensure_task_accessible()
+ manifest = tasks_facade.register_task_run_posthog_references(
+ pk,
+ task_id,
+ self.team_id,
+ references=request.validated_data["references"],
+ caller_is_agent=is_sandbox_agent_request(request, task_id),
+ acting_user_id=self._user_id(),
+ )
+ if manifest is None:
+ raise NotFound()
+ serializer = TaskRunPostHogReferencesResponseSerializer({"artifacts": manifest})
+ return Response(serializer.data)
+
@validated_request(
request_serializer=TaskRunArtifactsPrepareUploadRequestSerializer,
responses={
diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.py
index d5047ab4653b..73c455488c55 100644
--- a/products/tasks/backend/tests/test_api.py
+++ b/products/tasks/backend/tests/test_api.py
@@ -6336,6 +6336,46 @@ class TestTaskRunAPI(BaseTaskAPITest):
self.assertIn(f"tasks/artifacts/team_{self.team.id}/task_{task.id}/run_{run.id}/", artifact["storage_path"])
self.assertFalse(TaskArtifact.objects.for_team(self.team.id).filter(task_run=run).exists())
+ @patch("posthog.storage.object_storage.write")
+ @patch("posthog.storage.object_storage.tag")
+ def test_upload_artifacts_response_omits_url_for_reference_entries(self, mock_tag, mock_write):
+ task = self.create_task()
+ run = TaskRun.objects.create(
+ task=task,
+ team=self.team,
+ status=TaskRun.Status.IN_PROGRESS,
+ artifacts=[
+ {
+ "id": "phref_checkout",
+ "name": "Checkout funnel",
+ "type": "reference",
+ "source": "posthog_object",
+ "uploaded_at": "2026-08-20T00:00:00+00:00",
+ "uploaded_by": "agent",
+ "metadata": {
+ "reference_type": "posthog_object",
+ "object_kind": "insight",
+ "object_id": "9pQx3",
+ "source_message_ids": ["turn-1-message-1"],
+ "occurrence_count": 1,
+ },
+ }
+ ],
+ )
+
+ response = self.client.post(
+ f"/api/projects/@current/tasks/{task.id}/runs/{run.id}/artifacts/",
+ {"artifacts": [{"name": "plan.md", "type": "plan", "content": "# Plan", "content_type": "text/markdown"}]},
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ entries = {entry["id"]: entry for entry in response.json()["artifacts"]}
+ # A reference artifact has no file behind it, so the response must not advertise a download link.
+ self.assertNotIn("url", entries["phref_checkout"])
+ uploaded = next(entry for entry in response.json()["artifacts"] if entry["type"] == "plan")
+ self.assertIn("url", uploaded)
+
@patch("posthog.storage.object_storage.write")
@patch("posthog.storage.object_storage.tag")
def test_upload_artifacts_accepts_base64_content(self, mock_tag, mock_write):
@@ -6417,7 +6457,22 @@ class TestTaskRunAPI(BaseTaskAPITest):
self.assertEqual(artifact["type"], "skill_bundle")
self.assertEqual(artifact["metadata"], metadata)
- def test_upload_artifacts_rejects_skill_bundle_without_metadata(self):
+ @parameterized.expand(
+ [
+ ("without_metadata", None),
+ (
+ "with_reference_metadata",
+ {
+ "reference_type": "posthog_object",
+ "object_kind": "insight",
+ "object_id": "9pQx3",
+ "source_message_ids": ["turn-1"],
+ "occurrence_count": 1,
+ },
+ ),
+ ]
+ )
+ def test_upload_artifacts_rejects_skill_bundle(self, _name, metadata):
task = self.create_task()
run = TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.IN_PROGRESS)
@@ -6432,6 +6487,7 @@ class TestTaskRunAPI(BaseTaskAPITest):
"content": "c2tpbGw=",
"content_encoding": "base64",
"content_type": "application/zip",
+ **({"metadata": metadata} if metadata else {}),
}
]
},
@@ -8206,6 +8262,182 @@ class TestTaskRunCancelAPI(BaseTaskAPITest):
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+class TestTaskRunPostHogReferencesAPI(BaseTaskAPITest):
+ @patch("products.tasks.backend.presentation.views.api.is_sandbox_agent_request", return_value=True)
+ @patch("products.tasks.backend.facade.api._agent_thread_updates_enabled", return_value=True)
+ def test_registers_idempotent_reference_artifacts_and_announces_them_once(
+ self, _enabled: MagicMock, _agent: MagicMock
+ ) -> None:
+ task = self.create_task()
+ run = task.create_run(environment=TaskRun.Environment.CLOUD)
+ url = f"/api/projects/@current/tasks/{task.id}/runs/{run.id}/artifacts/references/"
+ reference = {
+ "name": "Checkout funnel",
+ "object_kind": "insight",
+ "object_id": "9pQx3",
+ "source_message_id": "turn-1-message-1",
+ }
+
+ first = self.client.post(url, {"references": [reference]}, format="json")
+ retry = self.client.post(url, {"references": [reference]}, format="json")
+ second_message = self.client.post(
+ url,
+ {"references": [{**reference, "source_message_id": "turn-2-message-1"}]},
+ format="json",
+ )
+
+ self.assertEqual(first.status_code, status.HTTP_200_OK)
+ self.assertEqual(retry.status_code, status.HTTP_200_OK)
+ self.assertEqual(second_message.status_code, status.HTTP_200_OK)
+ run.refresh_from_db()
+ self.assertEqual(len(run.artifacts), 1)
+ artifact = run.artifacts[0]
+ self.assertEqual(artifact["type"], "reference")
+ self.assertEqual(artifact["source"], "posthog_object")
+ self.assertNotIn("storage_path", artifact)
+ self.assertEqual(artifact["metadata"]["occurrence_count"], 2)
+ self.assertEqual(
+ artifact["metadata"]["source_message_ids"],
+ ["turn-1-message-1", "turn-2-message-1"],
+ )
+ events = TaskThreadMessage.objects.for_team(self.team.id).filter(
+ task=task,
+ event="artifact_created",
+ payload__artifact_id=artifact["id"],
+ )
+ self.assertEqual(events.count(), 1)
+ self.assertEqual(events.get().payload["reference_type"], "posthog_object")
+
+ @patch("products.tasks.backend.facade.api._agent_thread_updates_enabled", return_value=True)
+ def test_non_creator_cannot_register_references(self, _enabled: MagicMock) -> None:
+ task = self.create_task()
+ run = task.create_run(environment=TaskRun.Environment.CLOUD)
+ other = self.create_organization_user()
+ self.client.force_authenticate(other)
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/tasks/{task.id}/runs/{run.id}/artifacts/references/",
+ {
+ "references": [
+ {
+ "name": "Checkout funnel",
+ "object_kind": "insight",
+ "object_id": "9pQx3",
+ "source_message_id": "turn-1-message-1",
+ }
+ ]
+ },
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+ run.refresh_from_db()
+ self.assertEqual(run.artifacts or [], [])
+ self.assertFalse(
+ TaskThreadMessage.objects.for_team(self.team.id).filter(task=task, event="artifact_created").exists()
+ )
+
+ @patch("products.tasks.backend.facade.api._agent_thread_updates_enabled", return_value=True)
+ def test_user_registered_reference_is_user_attributed_and_silent(self, _enabled: MagicMock) -> None:
+ task = self.create_task()
+ run = task.create_run(environment=TaskRun.Environment.CLOUD)
+
+ response = self.client.post(
+ f"/api/projects/@current/tasks/{task.id}/runs/{run.id}/artifacts/references/",
+ {
+ "references": [
+ {
+ "name": "Checkout funnel",
+ "object_kind": "insight",
+ "object_id": "9pQx3",
+ "source_message_id": "turn-1-message-1",
+ }
+ ]
+ },
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ run.refresh_from_db()
+ artifact = run.artifacts[0]
+ self.assertEqual(artifact["uploaded_by"], "user")
+ self.assertEqual(artifact["uploaded_by_user_id"], self.user.id)
+ self.assertFalse(
+ TaskThreadMessage.objects.for_team(self.team.id).filter(task=task, event="artifact_created").exists()
+ )
+
+ def test_reference_artifacts_are_capped_per_run(self) -> None:
+ from products.tasks.backend.facade.api import MAX_RUN_REFERENCE_ARTIFACTS
+
+ task = self.create_task()
+ run = task.create_run(environment=TaskRun.Environment.CLOUD)
+ url = f"/api/projects/@current/tasks/{task.id}/runs/{run.id}/artifacts/references/"
+
+ for batch_start in range(0, MAX_RUN_REFERENCE_ARTIFACTS + 10, 50):
+ references = [
+ {
+ "name": f"Insight {index}",
+ "object_kind": "insight",
+ "object_id": f"id-{index}",
+ "source_message_id": "turn-1-message-1",
+ }
+ for index in range(batch_start, batch_start + 50)
+ ]
+ response = self.client.post(url, {"references": references}, format="json")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+
+ run.refresh_from_db()
+ reference_entries = [entry for entry in run.artifacts if entry.get("type") == "reference"]
+ self.assertEqual(len(reference_entries), MAX_RUN_REFERENCE_ARTIFACTS)
+
+ # An update to an existing entry still lands once the cap is reached.
+ update = self.client.post(
+ url,
+ {
+ "references": [
+ {
+ "name": "Insight 0",
+ "object_kind": "insight",
+ "object_id": "id-0",
+ "source_message_id": "turn-2-message-1",
+ }
+ ]
+ },
+ format="json",
+ )
+ self.assertEqual(update.status_code, status.HTTP_200_OK)
+ run.refresh_from_db()
+ updated = next(entry for entry in run.artifacts if entry["metadata"].get("object_id") == "id-0")
+ self.assertEqual(updated["metadata"]["occurrence_count"], 2)
+
+ def test_download_of_reference_artifact_returns_404(self) -> None:
+ task = self.create_task()
+ run = task.create_run(environment=TaskRun.Environment.CLOUD)
+ url = f"/api/projects/@current/tasks/{task.id}/runs/{run.id}/artifacts/references/"
+ self.client.post(
+ url,
+ {
+ "references": [
+ {
+ "name": "Checkout funnel",
+ "object_kind": "insight",
+ "object_id": "9pQx3",
+ "source_message_id": "turn-1-message-1",
+ }
+ ]
+ },
+ format="json",
+ )
+ run.refresh_from_db()
+ artifact_id = run.artifacts[0]["id"]
+
+ response = self.client.get(
+ f"/api/projects/@current/tasks/{task.id}/runs/{run.id}/artifacts/{artifact_id}/download/"
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+
+
class TestTaskRunArtifactDismissAPI(BaseTaskAPITest):
def _create_run_with_artifacts(self) -> tuple[Task, TaskRun]:
task = self.create_task()
diff --git a/products/tasks/frontend/generated/api.schemas.ts b/products/tasks/frontend/generated/api.schemas.ts
index 4b921a700e16..cc4bd76abbb3 100644
--- a/products/tasks/frontend/generated/api.schemas.ts
+++ b/products/tasks/frontend/generated/api.schemas.ts
@@ -1344,7 +1344,7 @@ export const TaskRunReasoningEffortEnumApi = {
Ultracode: 'ultracode',
} as const
-export interface TaskRunArtifactMetadataApi {
+export interface TaskRunSkillBundleMetadataApi {
/**
* Name of the local skill included in a skill_bundle artifact.
* @maxLength 255
@@ -1373,6 +1373,95 @@ export interface TaskRunArtifactMetadataApi {
schema_version: number
}
+/**
+ * * `posthog_object` - posthog_object
+ */
+export type ReferenceTypeEnumApi = (typeof ReferenceTypeEnumApi)[keyof typeof ReferenceTypeEnumApi]
+
+export const ReferenceTypeEnumApi = {
+ PosthogObject: 'posthog_object',
+} as const
+
+/**
+ * * `insight` - insight
+ * * `hogql` - hogql
+ * * `dashboard` - dashboard
+ * * `error` - error
+ * * `replay` - replay
+ * * `flag` - flag
+ * * `experiment` - experiment
+ * * `survey` - survey
+ * * `ticket` - ticket
+ * * `trace` - trace
+ * * `eval` - eval
+ * * `event` - event
+ * * `cohort` - cohort
+ * * `action` - action
+ * * `person` - person
+ */
+export type ObjectKindEnumApi = (typeof ObjectKindEnumApi)[keyof typeof ObjectKindEnumApi]
+
+export const ObjectKindEnumApi = {
+ Insight: 'insight',
+ Hogql: 'hogql',
+ Dashboard: 'dashboard',
+ Error: 'error',
+ Replay: 'replay',
+ Flag: 'flag',
+ Experiment: 'experiment',
+ Survey: 'survey',
+ Ticket: 'ticket',
+ Trace: 'trace',
+ Eval: 'eval',
+ Event: 'event',
+ Cohort: 'cohort',
+ Action: 'action',
+ Person: 'person',
+} as const
+
+export interface TaskRunPostHogReferenceMetadataApi {
+ /** Reference metadata type. posthog_object identifies a live PostHog object.
+ *
+ * * `posthog_object` - posthog_object */
+ reference_type: ReferenceTypeEnumApi
+ /** PostHog object kind used to resolve the reference.
+ *
+ * * `insight` - insight
+ * * `hogql` - hogql
+ * * `dashboard` - dashboard
+ * * `error` - error
+ * * `replay` - replay
+ * * `flag` - flag
+ * * `experiment` - experiment
+ * * `survey` - survey
+ * * `ticket` - ticket
+ * * `trace` - trace
+ * * `eval` - eval
+ * * `event` - event
+ * * `cohort` - cohort
+ * * `action` - action
+ * * `person` - person */
+ object_kind: ObjectKindEnumApi
+ /**
+ * Exact PostHog object identifier, flag key, event name, or SQL query.
+ * @maxLength 16384
+ */
+ object_id: string
+ /**
+ * Completed assistant message identifiers that referenced the object.
+ * @maxItems 100
+ * @items.maxLength 255
+ */
+ source_message_ids: string[]
+ /**
+ * Number of distinct completed assistant messages that referenced the object.
+ * @minimum 1
+ */
+ occurrence_count: number
+}
+
+export type TaskRunArtifactMetadataApi = TaskRunSkillBundleMetadataApi | TaskRunPostHogReferenceMetadataApi
+
/**
* * `agent` - agent
* * `user` - user
@@ -1397,11 +1486,11 @@ export interface TaskRunArtifactResponseApi {
size?: number
/** Optional MIME type */
content_type?: string
- /** Optional structured metadata for special artifact types, such as skill bundles. */
+ /** Structured metadata for a skill bundle or a PostHog object reference. */
metadata?: TaskRunArtifactMetadataApi
- /** S3 object key for the artifact */
- storage_path: string
- /** Timestamp when the artifact was uploaded */
+ /** S3 object key for file artifacts. Reference artifacts do not have one. */
+ storage_path?: string
+ /** Timestamp when the artifact was uploaded or registered */
uploaded_at: string
/** Whether the artifact version was uploaded by the task agent or an interactive user.
*
@@ -2608,8 +2697,8 @@ export interface TaskStagedArtifactFinalizeUploadApi {
* @maxLength 255
*/
content_type?: string
- /** Optional structured metadata for special artifact types, such as skill bundles. */
- metadata?: TaskRunArtifactMetadataApi
+ /** Skill bundle metadata, required when the artifact type is skill_bundle. */
+ metadata?: TaskRunSkillBundleMetadataApi
}
export interface TaskStagedArtifactsFinalizeUploadRequestApi {
@@ -2655,8 +2744,8 @@ export interface TaskStagedArtifactPrepareUploadApi {
* @maxLength 255
*/
content_type?: string
- /** Optional structured metadata for special artifact types, such as skill bundles. */
- metadata?: TaskRunArtifactMetadataApi
+ /** Skill bundle metadata, required when the artifact type is skill_bundle. */
+ metadata?: TaskRunSkillBundleMetadataApi
}
export interface TaskStagedArtifactsPrepareUploadRequestApi {
@@ -2689,8 +2778,8 @@ export interface TaskStagedArtifactPrepareUploadResponseApi {
size: number
/** Optional MIME type */
content_type?: string
- /** Optional structured metadata for special artifact types, such as skill bundles. */
- metadata?: TaskRunArtifactMetadataApi
+ /** Skill bundle metadata, required when the artifact type is skill_bundle. */
+ metadata?: TaskRunSkillBundleMetadataApi
/** S3 object key reserved for the staged artifact */
storage_path: string
/** Presigned POST expiry in seconds */
@@ -2972,8 +3061,8 @@ export interface TaskRunArtifactUploadApi {
* @maxLength 255
*/
content_type?: string
- /** Optional structured metadata for special artifact types, such as skill bundles. */
- metadata?: TaskRunArtifactMetadataApi
+ /** Skill bundle metadata, required when the artifact type is skill_bundle. */
+ metadata?: TaskRunSkillBundleMetadataApi
}
export interface TaskRunArtifactsUploadRequestApi {
@@ -3044,8 +3133,8 @@ export interface TaskRunArtifactFinalizeUploadApi {
* @maxLength 255
*/
content_type?: string
- /** Optional structured metadata for special artifact types, such as skill bundles. */
- metadata?: TaskRunArtifactMetadataApi
+ /** Skill bundle metadata, required when the artifact type is skill_bundle. */
+ metadata?: TaskRunSkillBundleMetadataApi
}
export interface TaskRunArtifactsFinalizeUploadRequestApi {
@@ -3091,8 +3180,8 @@ export interface TaskRunArtifactPrepareUploadApi {
* @maxLength 255
*/
content_type?: string
- /** Optional structured metadata for special artifact types, such as skill bundles. */
- metadata?: TaskRunArtifactMetadataApi
+ /** Skill bundle metadata, required when the artifact type is skill_bundle. */
+ metadata?: TaskRunSkillBundleMetadataApi
}
export interface TaskRunArtifactsPrepareUploadRequestApi {
@@ -3113,8 +3202,8 @@ export interface TaskRunArtifactPrepareUploadResponseApi {
size: number
/** Optional MIME type */
content_type?: string
- /** Optional structured metadata for special artifact types, such as skill bundles. */
- metadata?: TaskRunArtifactMetadataApi
+ /** Skill bundle metadata, required when the artifact type is skill_bundle. */
+ metadata?: TaskRunSkillBundleMetadataApi
/** S3 object key reserved for the artifact */
storage_path: string
/** Presigned POST expiry in seconds */
@@ -3135,6 +3224,55 @@ export interface TaskRunArtifactPresignResponseApi {
expires_in: number
}
+export interface TaskRunPostHogReferenceApi {
+ /**
+ * Fallback display name for the referenced object.
+ * @maxLength 255
+ */
+ name: string
+ /** PostHog object kind used to resolve the reference.
+ *
+ * * `insight` - insight
+ * * `hogql` - hogql
+ * * `dashboard` - dashboard
+ * * `error` - error
+ * * `replay` - replay
+ * * `flag` - flag
+ * * `experiment` - experiment
+ * * `survey` - survey
+ * * `ticket` - ticket
+ * * `trace` - trace
+ * * `eval` - eval
+ * * `event` - event
+ * * `cohort` - cohort
+ * * `action` - action
+ * * `person` - person */
+ object_kind: ObjectKindEnumApi
+ /**
+ * Exact PostHog object identifier, flag key, event name, or SQL query.
+ * @maxLength 16384
+ */
+ object_id: string
+ /**
+ * Stable identifier of the completed assistant message containing the reference.
+ * @maxLength 255
+ */
+ source_message_id: string
+}
+
+export interface TaskRunPostHogReferencesRequestApi {
+ /**
+ * PostHog object references extracted from one completed assistant message.
+ * @maxItems 50
+ */
+ references: TaskRunPostHogReferenceApi[]
+}
+
+export interface TaskRunPostHogReferencesResponseApi {
+ /** Updated list of artifacts on the run. */
+ artifacts: TaskRunArtifactResponseApi[]
+}
+
export interface TaskRunCancelRequestApi {
/**
* Optional reason for the cancellation, recorded on the run and shown to run watchers.
diff --git a/products/tasks/frontend/generated/api.ts b/products/tasks/frontend/generated/api.ts
index 2efb175eba8a..b83b62bc71cc 100644
--- a/products/tasks/frontend/generated/api.ts
+++ b/products/tasks/frontend/generated/api.ts
@@ -108,6 +108,8 @@ import type {
TaskRunPeerMessageRequestApi,
TaskRunPeerMessageResponseApi,
TaskRunPeersResponseApi,
+ TaskRunPostHogReferencesRequestApi,
+ TaskRunPostHogReferencesResponseApi,
TaskRunRelayMessageRequestApi,
TaskRunRelayMessageResponseApi,
TaskRunStartRequestApi,
@@ -1805,6 +1807,32 @@ export const tasksRunsArtifactsPresignCreate = async (
})
}
+export const getTasksRunsArtifactsReferencesCreateUrl = (projectId: string, taskId: string, id: string) => {
+ return `/api/projects/${projectId}/tasks/${taskId}/runs/${id}/artifacts/references/`
+}
+
+/**
+ * Attach live PostHog object references to the run artifact manifest without uploading files.
+ * @summary Register PostHog object references for a task run
+ */
+export const tasksRunsArtifactsReferencesCreate = async (
+ projectId: string,
+ taskId: string,
+ id: string,
+ taskRunPostHogReferencesRequestApi: TaskRunPostHogReferencesRequestApi,
+ options?: RequestInit
+): Promise<TaskRunPostHogReferencesResponseApi> => {
+ return apiMutator<TaskRunPostHogReferencesResponseApi>(
+ getTasksRunsArtifactsReferencesCreateUrl(projectId, taskId, id),
+ {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(taskRunPostHogReferencesRequestApi),
+ }
+ )
+}
+
export const getTasksRunsCancelCreateUrl = (projectId: string, taskId: string, id: string) => {
return `/api/projects/${projectId}/tasks/${taskId}/runs/${id}/cancel/`
}
diff --git a/products/tasks/frontend/generated/api.zod.ts b/products/tasks/frontend/generated/api.zod.ts
index 8e3f1cdeaa7a..d6a958550e72 100644
--- a/products/tasks/frontend/generated/api.zod.ts
+++ b/products/tasks/frontend/generated/api.zod.ts
@@ -2026,7 +2026,7 @@ export const TasksStagedArtifactsFinalizeUploadCreateBody = /* @__PURE__ */ zod.
.describe('Version of the local skill bundle metadata schema.'),
})
.optional()
- .describe('Optional structured metadata for special artifact types, such as skill bundles.'),
+ .describe('Skill bundle metadata, required when the artifact type is skill_bundle.'),
})
)
.describe('Array of staged artifacts to finalize after upload'),
@@ -2121,7 +2121,7 @@ export const TasksStagedArtifactsPrepareUploadCreateBody = /* @__PURE__ */ zod.o
.describe('Version of the local skill bundle metadata schema.'),
})
.optional()
- .describe('Optional structured metadata for special artifact types, such as skill bundles.'),
+ .describe('Skill bundle metadata, required when the artifact type is skill_bundle.'),
})
)
.describe('Array of staged artifacts to prepare before creating a run'),
@@ -2408,7 +2408,7 @@ export const TasksRunsArtifactsCreateBody = /* @__PURE__ */ zod.object({
.describe('Version of the local skill bundle metadata schema.'),
})
.optional()
- .describe('Optional structured metadata for special artifact types, such as skill bundles.'),
+ .describe('Skill bundle metadata, required when the artifact type is skill_bundle.'),
})
)
.describe('Array of artifacts to upload'),
@@ -2539,7 +2539,7 @@ export const TasksRunsArtifactsFinalizeUploadCreateBody = /* @__PURE__ */ zod.ob
.describe('Version of the local skill bundle metadata schema.'),
})
.optional()
- .describe('Optional structured metadata for special artifact types, such as skill bundles.'),
+ .describe('Skill bundle metadata, required when the artifact type is skill_bundle.'),
})
)
.describe('Array of uploaded artifacts to finalize'),
@@ -2632,7 +2632,7 @@ export const TasksRunsArtifactsPrepareUploadCreateBody = /* @__PURE__ */ zod.obj
.describe('Version of the local skill bundle metadata schema.'),
})
.optional()
- .describe('Optional structured metadata for special artifact types, such as skill bundles.'),
+ .describe('Skill bundle metadata, required when the artifact type is skill_bundle.'),
})
)
.describe('Array of artifacts to prepare'),
@@ -2651,6 +2651,64 @@ export const TasksRunsArtifactsPresignCreateBody = /* @__PURE__ */ zod.object({
.describe('S3 storage path returned in the artifact manifest'),
})
+/**
+ * Attach live PostHog object references to the run artifact manifest without uploading files.
+ * @summary Register PostHog object references for a task run
+ */
+export const tasksRunsArtifactsReferencesCreateBodyReferencesItemNameMax = 255
+
+export const tasksRunsArtifactsReferencesCreateBodyReferencesItemObjectIdMax = 16384
+
+export const tasksRunsArtifactsReferencesCreateBodyReferencesItemSourceMessageIdMax = 255
+
+export const tasksRunsArtifactsReferencesCreateBodyReferencesMax = 50
+
+export const TasksRunsArtifactsReferencesCreateBody = /* @__PURE__ */ zod.object({
+ references: zod
+ .array(
+ zod.object({
+ name: zod
+ .string()
+ .max(tasksRunsArtifactsReferencesCreateBodyReferencesItemNameMax)
+ .describe('Fallback display name for the referenced object.'),
+ object_kind: zod
+ .enum([
+ 'insight',
+ 'hogql',
+ 'dashboard',
+ 'error',
+ 'replay',
+ 'flag',
+ 'experiment',
+ 'survey',
+ 'ticket',
+ 'trace',
+ 'eval',
+ 'event',
+ 'cohort',
+ 'action',
+ 'person',
+ ])
+ .describe(
+ '\* `insight` - insight\n\* `hogql` - hogql\n\* `dashboard` - dashboard\n\* `error` - error\n\* `replay` - replay\n\* `flag` - flag\n\* `experiment` - experiment\n\* `survey` - survey\n\* `ticket` - ticket\n\* `trace` - trace\n\* `eval` - eval\n\* `event` - event\n\* `cohort` - cohort\n\* `action` - action\n\* `person` - person'
+ )
+ .describe(
+ 'PostHog object kind used to resolve the reference.\n\n\* `insight` - insight\n\* `hogql` - hogql\n\* `dashboard` - dashboard\n\* `error` - error\n\* `replay` - replay\n\* `flag` - flag\n\* `experiment` - experiment\n\* `survey` - survey\n\* `ticket` - ticket\n\* `trace` - trace\n\* `eval` - eval\n\* `event` - event\n\* `cohort` - cohort\n\* `action` - action\n\* `person` - person'
+ ),
+ object_id: zod
+ .string()
+ .max(tasksRunsArtifactsReferencesCreateBodyReferencesItemObjectIdMax)
+ .describe('Exact PostHog object identifier, flag key, event name, or SQL query.'),
+ source_message_id: zod
+ .string()
+ .max(tasksRunsArtifactsReferencesCreateBodyReferencesItemSourceMessageIdMax)
+ .describe('Stable identifier of the completed assistant message containing the reference.'),
+ })
+ )
+ .max(tasksRunsArtifactsReferencesCreateBodyReferencesMax)
+ .describe('PostHog object references extracted from one completed assistant message.'),
+})
+
/**
* Stop an active cloud run. Interrupts the agent, snapshots interactive sessions for later resume, tears down the sandbox, and marks the run cancelled. Idempotent: cancelling a finished run returns it unchanged.
* @summary Cancel task run
diff --git a/products/tasks/mcp/tools.yaml b/products/tasks/mcp/tools.yaml
index 72ddf4bbff74..84cbb374ef0a 100644
--- a/products/tasks/mcp/tools.yaml
+++ b/products/tasks/mcp/tools.yaml
@@ -486,6 +486,9 @@ tools:
tasks-runs-artifacts-presign-create:
operation: tasks_runs_artifacts_presign_create
enabled: false
+ tasks-runs-artifacts-references-create:
+ operation: tasks_runs_artifacts_references_create
+ enabled: false
tasks-runs-cancel-create:
operation: tasks_runs_cancel_create
enabled: false
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 1e9113279998..7000910f9080 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -49456,6 +49456,44 @@ export namespace Schemas {
redirect_url: string;
}
+ /**
+ * * `insight` - insight
+ * * `hogql` - hogql
+ * * `dashboard` - dashboard
+ * * `error` - error
+ * * `replay` - replay
+ * * `flag` - flag
+ * * `experiment` - experiment
+ * * `survey` - survey
+ * * `ticket` - ticket
+ * * `trace` - trace
+ * * `eval` - eval
+ * * `event` - event
+ * * `cohort` - cohort
+ * * `action` - action
+ * * `person` - person
+ */
+ export type ObjectKindEnum = typeof ObjectKindEnum[keyof typeof ObjectKindEnum];
+
+
+ export const ObjectKindEnum = {
+ Insight: 'insight',
+ Hogql: 'hogql',
+ Dashboard: 'dashboard',
+ Error: 'error',
+ Replay: 'replay',
+ Flag: 'flag',
+ Experiment: 'experiment',
+ Survey: 'survey',
+ Ticket: 'ticket',
+ Trace: 'trace',
+ Eval: 'eval',
+ Event: 'event',
+ Cohort: 'cohort',
+ Action: 'action',
+ Person: 'person',
+ } as const;
+
export interface ObjectMediaPreview {
readonly id: string;
readonly created_at: string;
@@ -54742,7 +54780,7 @@ export namespace Schemas {
Ultracode: 'ultracode',
} as const;
- export interface TaskRunArtifactMetadata {
+ export interface TaskRunSkillBundleMetadata {
/**
* Name of the local skill included in a skill_bundle artifact.
* @maxLength 255
@@ -54771,6 +54809,59 @@ export namespace Schemas {
schema_version: number;
}
+ /**
+ * * `posthog_object` - posthog_object
+ */
+ export type ReferenceTypeEnum = typeof ReferenceTypeEnum[keyof typeof ReferenceTypeEnum];
+
+
+ export const ReferenceTypeEnum = {
+ PosthogObject: 'posthog_object',
+ } as const;
+
+ export interface TaskRunPostHogReferenceMetadata {
+ /** Reference metadata type. posthog_object identifies a live PostHog object.
+ *
+ * * `posthog_object` - posthog_object */
+ reference_type: ReferenceTypeEnum;
+ /** PostHog object kind used to resolve the reference.
+ *
+ * * `insight` - insight
+ * * `hogql` - hogql
+ * * `dashboard` - dashboard
+ * * `error` - error
+ * * `replay` - replay
+ * * `flag` - flag
+ * * `experiment` - experiment
+ * * `survey` - survey
+ * * `ticket` - ticket
+ * * `trace` - trace
+ * * `eval` - eval
+ * * `event` - event
+ * * `cohort` - cohort
+ * * `action` - action
+ * * `person` - person */
+ object_kind: ObjectKindEnum;
+ /**
+ * Exact PostHog object identifier, flag key, event name, or SQL query.
+ * @maxLength 16384
+ */
+ object_id: string;
+ /**
+ * Completed assistant message identifiers that referenced the object.
+ * @maxItems 100
+ * @items.maxLength 255
+ */
+ source_message_ids: string[];
+ /**
+ * Number of distinct completed assistant messages that referenced the object.
+ * @minimum 1
+ */
+ occurrence_count: number;
+ }
+
+ export type TaskRunArtifactMetadata = TaskRunSkillBundleMetadata | TaskRunPostHogReferenceMetadata;
+
/**
* * `agent` - agent
* * `user` - user
@@ -54796,11 +54887,11 @@ export namespace Schemas {
size?: number;
/** Optional MIME type */
content_type?: string;
- /** Optional structured metadata for special artifact types, such as skill bundles. */
+ /** Structured metadata for a skill bundle or a PostHog object reference. */
metadata?: TaskRunArtifactMetadata;
- /** S3 object key for the artifact */
- storage_path: string;
- /** Timestamp when the artifact was uploaded */
+ /** S3 object key for file artifacts. Reference artifacts do not have one. */
+ storage_path?: string;
+ /** Timestamp when the artifact was uploaded or registered */
uploaded_at: string;
/** Whether the artifact version was uploaded by the task agent or an interactive user.
*
@@ -79641,8 +79732,8 @@ export namespace Schemas {
* @maxLength 255
*/
content_type?: string;
- /** Optional structured metadata for special artifact types, such as skill bundles. */
- metadata?: TaskRunArtifactMetadata;
+ /** Skill bundle metadata, required when the artifact type is skill_bundle. */
+ metadata?: TaskRunSkillBundleMetadata;
}
export interface TaskRunArtifactPrepareUpload {
@@ -79678,8 +79769,8 @@ export namespace Schemas {
* @maxLength 255
*/
content_type?: string;
- /** Optional structured metadata for special artifact types, such as skill bundles. */
- metadata?: TaskRunArtifactMetadata;
+ /** Skill bundle metadata, required when the artifact type is skill_bundle. */
+ metadata?: TaskRunSkillBundleMetadata;
}
export interface TaskRunArtifactPrepareUploadResponse {
@@ -79695,8 +79786,8 @@ export namespace Schemas {
size: number;
/** Optional MIME type */
content_type?: string;
- /** Optional structured metadata for special artifact types, such as skill bundles. */
- metadata?: TaskRunArtifactMetadata;
+ /** Skill bundle metadata, required when the artifact type is skill_bundle. */
+ metadata?: TaskRunSkillBundleMetadata;
/** S3 object key reserved for the artifact */
storage_path: string;
/** Presigned POST expiry in seconds */
@@ -79754,8 +79845,8 @@ export namespace Schemas {
* @maxLength 255
*/
content_type?: string;
- /** Optional structured metadata for special artifact types, such as skill bundles. */
- metadata?: TaskRunArtifactMetadata;
+ /** Skill bundle metadata, required when the artifact type is skill_bundle. */
+ metadata?: TaskRunSkillBundleMetadata;
}
export interface TaskRunArtifactsDismissRequest {
@@ -80392,6 +80483,55 @@ export namespace Schemas {
peers: TaskRunPeer[];
}
+ export interface TaskRunPostHogReference {
+ /**
+ * Fallback display name for the referenced object.
+ * @maxLength 255
+ */
+ name: string;
+ /** PostHog object kind used to resolve the reference.
+ *
+ * * `insight` - insight
+ * * `hogql` - hogql
+ * * `dashboard` - dashboard
+ * * `error` - error
+ * * `replay` - replay
+ * * `flag` - flag
+ * * `experiment` - experiment
+ * * `survey` - survey
+ * * `ticket` - ticket
+ * * `trace` - trace
+ * * `eval` - eval
+ * * `event` - event
+ * * `cohort` - cohort
+ * * `action` - action
+ * * `person` - person */
+ object_kind: ObjectKindEnum;
+ /**
+ * Exact PostHog object identifier, flag key, event name, or SQL query.
+ * @maxLength 16384
+ */
+ object_id: string;
+ /**
+ * Stable identifier of the completed assistant message containing the reference.
+ * @maxLength 255
+ */
+ source_message_id: string;
+ }
+
+ export interface TaskRunPostHogReferencesRequest {
+ /**
+ * PostHog object references extracted from one completed assistant message.
+ * @maxItems 50
+ */
+ references: TaskRunPostHogReference[];
+ }
+
+ export interface TaskRunPostHogReferencesResponse {
+ /** Updated list of artifacts on the run. */
+ artifacts: TaskRunArtifactResponse[];
+ }
+
export interface TaskRunRelayMessageRequest {
/**
* Joined message body. Used when text_parts is absent.
@@ -80533,8 +80673,8 @@ export namespace Schemas {
* @maxLength 255
*/
content_type?: string;
- /** Optional structured metadata for special artifact types, such as skill bundles. */
- metadata?: TaskRunArtifactMetadata;
+ /** Skill bundle metadata, required when the artifact type is skill_bundle. */
+ metadata?: TaskRunSkillBundleMetadata;
}
export interface TaskStagedArtifactPrepareUpload {
@@ -80570,8 +80710,8 @@ export namespace Schemas {
* @maxLength 255
*/
content_type?: string;
- /** Optional structured metadata for special artifact types, such as skill bundles. */
- metadata?: TaskRunArtifactMetadata;
+ /** Skill bundle metadata, required when the artifact type is skill_bundle. */
+ metadata?: TaskRunSkillBundleMetadata;
}
export interface TaskStagedArtifactPrepareUploadResponse {
@@ -80587,8 +80727,8 @@ export namespace Schemas {
size: number;
/** Optional MIME type */
content_type?: string;
- /** Optional structured metadata for special artifact types, such as skill bundles. */
- metadata?: TaskRunArtifactMetadata;
+ /** Skill bundle metadata, required when the artifact type is skill_bundle. */
+ metadata?: TaskRunSkillBundleMetadata;
/** S3 object key reserved for the staged artifact */
storage_path: string;
/** Presigned POST expiry in seconds */