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): open canvases cache-first and in one round trip (#90084)

Peter Kirkham1e834964aa29
diff --git a/products/desktop/packages/core/src/canvas/canvasBuildSchemas.test.ts b/products/desktop/packages/core/src/canvas/canvasBuildSchemas.test.ts
index aaefda2b3a4e..476dfcfce4d4 100644
--- a/products/desktop/packages/core/src/canvas/canvasBuildSchemas.test.ts
+++ b/products/desktop/packages/core/src/canvas/canvasBuildSchemas.test.ts
@@ -215,8 +215,8 @@ describe("canvas build lifecycle", () => {
),
);
const service = new DashboardsService({
- json: async (path: string) => {
- expect(path).toBe("canvases/canvas-1/builds/");
+ revalidatedJson: async (path: string) => {
+ expect(path).toBe("canvases/canvas-1/builds/?scope=slim");
return (await fetchMock()).json();
},
} as unknown as ProjectApiClient);
diff --git a/products/desktop/packages/core/src/canvas/canvasDataService.test.ts b/products/desktop/packages/core/src/canvas/canvasDataService.test.ts
index 4b5c6a769ffe..74de573fa3e2 100644
--- a/products/desktop/packages/core/src/canvas/canvasDataService.test.ts
+++ b/products/desktop/packages/core/src/canvas/canvasDataService.test.ts
@@ -6,9 +6,12 @@ import type { InsightFetchResult } from "./posthogApi";
// loadInsight reads a saved insight's stored result via posthogApi; stub the
// module so the service never reaches the network.
const fetchInsightByShortId = vi.fn();
+const runQuery = vi.fn();
+const readCachedQuery = vi.fn();
vi.mock("./posthogApi", () => ({
fetchInsightByShortId: (...args: unknown[]) => fetchInsightByShortId(...args),
- runQuery: vi.fn(),
+ runQuery: (...args: unknown[]) => runQuery(...args),
+ readCachedQuery: (...args: unknown[]) => readCachedQuery(...args),
fetchCurrentUser: vi.fn(),
}));
@@ -32,6 +35,82 @@ function insight(partial: Partial<InsightFetchResult>): InsightFetchResult {
};
}
+describe("CanvasDataService.query cache-first", () => {
+ beforeEach(() => {
+ runQuery.mockReset();
+ readCachedQuery.mockReset();
+ });
+
+ const node = { kind: "TrendsQuery" };
+
+ it("serves a cached result inside the declared window without computing", async () => {
+ readCachedQuery.mockResolvedValue({
+ columns: [],
+ results: [{ count: 5 }],
+ lastRefresh: new Date().toISOString(),
+ });
+
+ const result = await makeService().query({ query: node, refresh: 60 });
+
+ expect(result.results).toEqual([{ count: 5 }]);
+ expect(result.stale).toBeUndefined();
+ expect(runQuery).not.toHaveBeenCalled();
+ });
+
+ it("serves a stale cached result immediately and recomputes in the background once", async () => {
+ readCachedQuery.mockResolvedValue({
+ columns: [],
+ results: [{ count: 5 }],
+ lastRefresh: new Date(Date.now() - 10 * 60_000).toISOString(),
+ });
+ runQuery.mockResolvedValue({ columns: [], results: [], lastRefresh: null });
+ const service = makeService();
+
+ const first = await service.query({ query: node, refresh: 60 });
+ const second = await service.query({ query: node, refresh: 60 });
+
+ expect(first.stale).toBe(true);
+ expect(second.stale).toBe(true);
+ // The background recompute is rate-limited per query, so back-to-back
+ // stale reads must not stack ClickHouse runs.
+ expect(runQuery).toHaveBeenCalledTimes(1);
+ expect(runQuery).toHaveBeenCalledWith(expect.anything(), node, {
+ refresh: "force_async",
+ });
+ });
+
+ it("computes blocking on a cache miss", async () => {
+ readCachedQuery.mockResolvedValue(null);
+ runQuery.mockResolvedValue({
+ columns: [],
+ results: [{ count: 9 }],
+ lastRefresh: null,
+ });
+
+ const result = await makeService().query({ query: node, refresh: 60 });
+
+ expect(result.results).toEqual([{ count: 9 }]);
+ expect(runQuery).toHaveBeenCalledWith(expect.anything(), node, {
+ refresh: "blocking",
+ });
+ });
+
+ it("keeps one-shot semantics when no refresh window is declared", async () => {
+ runQuery.mockResolvedValue({
+ columns: [],
+ results: [{ count: 1 }],
+ lastRefresh: null,
+ });
+
+ await makeService().query({ query: node });
+
+ expect(readCachedQuery).not.toHaveBeenCalled();
+ expect(runQuery).toHaveBeenCalledWith(expect.anything(), node, {
+ refresh: "blocking",
+ });
+ });
+});
+
describe("CanvasDataService.loadInsight", () => {
beforeEach(() => {
fetchInsightByShortId.mockReset();
diff --git a/products/desktop/packages/core/src/canvas/canvasDataService.ts b/products/desktop/packages/core/src/canvas/canvasDataService.ts
index 319a02a1ce59..8c31a0be1b13 100644
--- a/products/desktop/packages/core/src/canvas/canvasDataService.ts
+++ b/products/desktop/packages/core/src/canvas/canvasDataService.ts
@@ -17,6 +17,7 @@ import type {
import {
fetchCurrentUser,
fetchInsightByShortId,
+ readCachedQuery,
runQuery,
} from "./posthogApi";
@@ -25,6 +26,9 @@ import {
const FALLBACK_DISTINCT_ID = "freeform-canvas";
const MAX_CANVAS_RESULT_ROWS = 1_000;
const MAX_CANVAS_RESULT_BYTES = 2 * 1024 * 1024;
+// Floor between background recomputes of one stale query (see `revalidate`).
+const REVALIDATE_MIN_INTERVAL_MS = 30_000;
+const MAX_REVALIDATION_ENTRIES = 512;
const utf8Encoder = new TextEncoder();
@@ -107,6 +111,8 @@ export class CanvasDataService {
// The signed-in user's distinct_id, the default attribution in edit mode.
// Per-user (not per-project), so a single cached value is correct.
private userDistinctId: string | undefined;
+ // Epoch ms of each query's last background-recompute kickoff (see `revalidate`).
+ private readonly revalidatedAt = new Map<string, number>();
constructor(
@inject(AUTH_SERVICE)
@@ -120,25 +126,54 @@ export class CanvasDataService {
async query(input: CanvasDataQueryInput): Promise<CanvasDataResult> {
try {
// A typed query node (TrendsQuery/etc.) runs as-is so the numbers match the
- // PostHog UI; an inline HogQL string is the escape hatch. Cache-first
- // execution (the insights avenue): serve a fresh cached result if present,
- // otherwise compute it now.
+ // PostHog UI; an inline HogQL string is the escape hatch.
const isTyped = input.query != null;
const node = isTyped
? (input.query as Record<string, unknown>)
: { kind: "HogQLQuery", query: input.hogql as string };
+ // Shape handling: HogQL returns rows (normalise a bare scalar row to a
+ // 1-cell array); typed nodes return SERIES OBJECTS, passed through
+ // untouched (wrapping them in arrays is what made every value read as 0).
+ const shaped = (results: unknown[]): unknown[] =>
+ isTyped ? results : results.map((r) => (Array.isArray(r) ? r : [r]));
+
+ // A canvas that declared a refresh window is a live surface: it re-reads
+ // on its own cadence, so it gets dashboard semantics. Any cached result
+ // paints immediately, and one older than the window is revalidated in the
+ // background so the NEXT read is fresh. A canvas with no window keeps the
+ // one-shot semantics: a fresh-enough cached result, else a blocking
+ // compute.
+ if (input.refresh != null) {
+ // The cache probe is an optimization; a transient failure on it must
+ // not fail a read that the blocking path below could still serve.
+ const cached = await readCachedQuery(this.authService, node).catch(
+ (err) => {
+ this.log.warn("Canvas cached-read probe failed", {
+ error: err instanceof Error ? err.message : String(err),
+ });
+ return null;
+ },
+ );
+ if (cached) {
+ const age =
+ cached.lastRefresh != null
+ ? Date.now() - Date.parse(cached.lastRefresh)
+ : Number.POSITIVE_INFINITY;
+ const stale = !(age <= input.refresh * 1_000);
+ if (stale) this.revalidate(node);
+ return boundedResult({
+ columns: cached.columns,
+ results: shaped(cached.results),
+ ...(stale ? { stale: true } : {}),
+ });
+ }
+ }
+ // Cache-first execution (the insights avenue): serve a fresh cached
+ // result if present, otherwise compute it now.
const { columns, results } = await runQuery(this.authService, node, {
refresh: "blocking",
});
- return boundedResult({
- columns,
- // HogQL returns rows; normalise a bare scalar row to a 1-cell array.
- // Typed nodes return SERIES OBJECTS — pass them through untouched (wrapping
- // them in arrays is what made every value read as 0).
- results: isTyped
- ? results
- : results.map((r) => (Array.isArray(r) ? r : [r])),
- });
+ return boundedResult({ columns, results: shaped(results) });
} catch (err) {
this.log.warn("Canvas query failed", {
error: err instanceof Error ? err.message : String(err),
@@ -147,6 +182,33 @@ export class CanvasDataService {
}
}
+ // Fire-and-forget background recompute of a stale cached result.
+ // force_async recomputes unconditionally, so kickoffs are rate-limited per
+ // query: a canvas polling faster than the compute finishes must not stack
+ // ClickHouse runs behind it.
+ private revalidate(node: Record<string, unknown>): void {
+ const key = JSON.stringify(node);
+ const last = this.revalidatedAt.get(key);
+ if (last != null && Date.now() - last < REVALIDATE_MIN_INTERVAL_MS) return;
+ // Delete first so a re-set refreshes the key's Map position and the size
+ // cap below always evicts the least recently refreshed query.
+ this.revalidatedAt.delete(key);
+ this.revalidatedAt.set(key, Date.now());
+ // The map only ever holds queries some canvas is actively re-reading;
+ // still, cap it so a long session can't grow it without bound.
+ if (this.revalidatedAt.size > MAX_REVALIDATION_ENTRIES) {
+ const oldest = this.revalidatedAt.keys().next().value;
+ if (oldest !== undefined) this.revalidatedAt.delete(oldest);
+ }
+ void runQuery(this.authService, node, { refresh: "force_async" }).catch(
+ (err) => {
+ this.log.warn("Canvas background refresh failed", {
+ error: err instanceof Error ? err.message : String(err),
+ });
+ },
+ );
+ }
+
// The preferred data avenue: load a SAVED insight by short id and return its
// STORED result from the insights endpoint (not a fresh /query/ run). The
// canvas date picker's window rides along as the insight's date override, and
diff --git a/products/desktop/packages/core/src/canvas/dashboardSchemas.ts b/products/desktop/packages/core/src/canvas/dashboardSchemas.ts
index a1c19e704784..c9f6689019a4 100644
--- a/products/desktop/packages/core/src/canvas/dashboardSchemas.ts
+++ b/products/desktop/packages/core/src/canvas/dashboardSchemas.ts
@@ -3,8 +3,13 @@ import {
canvasBuildStatusSchema,
} from "@posthog/shared";
import { z } from "zod";
+import { canvasBuildRecordSchema } from "./canvasBuildSchemas";
import { canvasAgentRequestInputSchema } from "./freeformSchemas";
-import { componentMetaSchema } from "./gridLayoutSchemas";
+import {
+ canvasLayoutSchema,
+ componentLifecycleSeedSchema,
+ componentMetaSchema,
+} from "./gridLayoutSchemas";
export const canvasCreatorSchema = z.object({
id: z.number().optional(),
@@ -98,6 +103,23 @@ export const canvasSourceSchema = z.object({
});
export type CanvasSource = z.infer<typeof canvasSourceSchema>;
+// Everything the app needs to open a canvas, in one round trip (the `view`
+// endpoint): the record, the live build with its signed artifact URL, and,
+// only when there is nothing built to render, the head source (freeform/
+// component) or layout (grid).
+export const canvasViewSchema = z.object({
+ record: dashboardRecordSchema,
+ publishedBuild: canvasBuildRecordSchema.nullable(),
+ currentVersionId: z.string().nullable(),
+ hasActiveBuild: z.boolean(),
+ source: canvasSourceProjectSchema.nullable(),
+ layout: canvasLayoutSchema.nullable(),
+ // For grids: the placed components' renderable builds, so a primed grid
+ // renders without a builds fetch per placement.
+ componentLifecycles: z.array(componentLifecycleSeedSchema).optional(),
+});
+export type CanvasView = z.infer<typeof canvasViewSchema>;
+
export const listDashboardsInput = z.object({ channelId: z.string().min(1) });
// The component store: component-kind canvases across every channel visible to
diff --git a/products/desktop/packages/core/src/canvas/dashboardsService.test.ts b/products/desktop/packages/core/src/canvas/dashboardsService.test.ts
index 78b821b0f1f2..f118869b1d8f 100644
--- a/products/desktop/packages/core/src/canvas/dashboardsService.test.ts
+++ b/products/desktop/packages/core/src/canvas/dashboardsService.test.ts
@@ -43,6 +43,7 @@ function fakeApi(
json: vi.fn(async (path: string, _label: string, init?: RequestInit) =>
resolve(path, init),
),
+ revalidatedJson: vi.fn(async (path: string) => resolve(path)),
listPaginated: vi.fn(async (path: string) => resolve(path) as unknown[]),
fetch: vi.fn(async (path: string, init?: RequestInit) => {
const body = resolve(path, init);
@@ -82,7 +83,7 @@ describe("DashboardsService.list", () => {
describe("DashboardsService.getBuilds", () => {
it("normalizes the lifecycle payload", async () => {
const { api } = fakeApi({
- "canvases/c1/builds/?version_id=v1": {
+ "canvases/c1/builds/?version_id=v1&scope=slim": {
published_build_id: "b1",
current_version_id: "v1",
builds: [
diff --git a/products/desktop/packages/core/src/canvas/dashboardsService.ts b/products/desktop/packages/core/src/canvas/dashboardsService.ts
index 88463f8a2fd0..508c4a0300d2 100644
--- a/products/desktop/packages/core/src/canvas/dashboardsService.ts
+++ b/products/desktop/packages/core/src/canvas/dashboardsService.ts
@@ -5,18 +5,20 @@ import {
type CanvasBuildRecord,
canvasBuildRecordSchema,
} from "./canvasBuildSchemas";
-import type {
- CanvasActionDefinition,
- CanvasActionResult,
- CanvasConnectorCallResult,
- CanvasCreator,
- CanvasDraft,
- CanvasSource,
- CanvasSourceProject,
- CanvasStateEntry,
- CanvasStateScope,
- CanvasVersion,
- DashboardRecord,
+import {
+ type CanvasActionDefinition,
+ type CanvasActionResult,
+ type CanvasConnectorCallResult,
+ type CanvasCreator,
+ type CanvasDraft,
+ type CanvasSource,
+ type CanvasSourceProject,
+ type CanvasStateEntry,
+ type CanvasStateScope,
+ type CanvasVersion,
+ type CanvasView,
+ canvasSourceProjectSchema,
+ type DashboardRecord,
} from "./dashboardSchemas";
import {
type CanvasAgentRequestResult,
@@ -136,6 +138,33 @@ function tryToBuildRecord(
return parsed.success ? parsed.data : null;
}
+// One placed component's renderable build, as the layout/view endpoints return it.
+interface ApiComponentLifecycle {
+ canvas_id: string;
+ requested_version_id: string | null;
+ published_build_id: string | null;
+ current_version_id: string | null;
+ builds: Record<string, unknown>[];
+}
+
+function toComponentLifecycleSeed(entry: ApiComponentLifecycle): {
+ canvasId: string;
+ requestedVersionId: string | null;
+ lifecycle: CanvasBuildLifecycle;
+} {
+ return {
+ canvasId: entry.canvas_id,
+ requestedVersionId: entry.requested_version_id,
+ lifecycle: {
+ publishedBuildId: entry.published_build_id,
+ currentVersionId: entry.current_version_id,
+ builds: entry.builds
+ .map(tryToBuildRecord)
+ .filter((build): build is CanvasBuildRecord => build !== null),
+ },
+ };
+}
+
/**
* Canvases backed by the PostHog canvases API. A canvas is a first-class row
* filed into a backend channel; its source is versioned per publish
@@ -165,6 +194,36 @@ export class DashboardsService {
return toRecord((await res.json()) as ApiCanvas);
}
+ // Everything needed to open a canvas, in one round trip: the record, the
+ // live build (signed artifact URL included), and, when there is nothing
+ // built to render, the head source (freeform/component) or layout (grid).
+ async view(id: string): Promise<CanvasView> {
+ const body = await this.api.revalidatedJson<{
+ canvas: ApiCanvas;
+ published_build: Record<string, unknown> | null;
+ current_version_id: string | null;
+ has_active_build: boolean;
+ source?: unknown;
+ layout?: CanvasLayout | null;
+ component_lifecycles?: ApiComponentLifecycle[];
+ }>(`canvases/${encodeURIComponent(id)}/view/`, "load canvas view");
+ const publishedBuild = body.published_build
+ ? tryToBuildRecord(body.published_build)
+ : null;
+ const source = canvasSourceProjectSchema.nullish().safeParse(body.source);
+ return {
+ record: toRecord(body.canvas),
+ publishedBuild,
+ currentVersionId: body.current_version_id ?? null,
+ hasActiveBuild: body.has_active_build ?? false,
+ source: source.success ? (source.data ?? null) : null,
+ layout: body.layout ?? null,
+ componentLifecycles: body.component_lifecycles?.map(
+ toComponentLifecycleSeed,
+ ),
+ };
+ }
+
// The component store: component-kind canvases across every channel visible
// to the caller, optionally narrowed by a name/description search.
async listComponents(input: { search?: string }): Promise<DashboardRecord[]> {
@@ -217,21 +276,34 @@ export class DashboardsService {
}
// Read a grid canvas's layout document — the head, or a historical version.
+ // The head read also asks for the placed components' renderable builds, so a
+ // grid renders from this one call instead of one builds fetch per placement.
+ // Version browsing skips them: nothing consumes an old layout's lifecycles,
+ // and an unpinned placement would resolve to TODAY's build anyway.
async getLayout(input: {
id: string;
versionId?: string;
}): Promise<CanvasLayoutResult> {
const suffix = input.versionId
? `?version_id=${encodeURIComponent(input.versionId)}`
- : "";
- const body = await this.api.json<{
+ : "?include_components=true";
+ const body = await this.api.revalidatedJson<{
layout: CanvasLayout;
current_version_id: string | null;
+ component_lifecycles?: ApiComponentLifecycle[];
}>(
`canvases/${encodeURIComponent(input.id)}/layout/${suffix}`,
"load canvas layout",
);
- return { layout: body.layout, currentVersionId: body.current_version_id };
+ return {
+ layout: body.layout,
+ currentVersionId: body.current_version_id,
+ // Absent on servers that predate include_components; tiles then fall
+ // back to their own builds fetch.
+ componentLifecycles: body.component_lifecycles?.map(
+ toComponentLifecycleSeed,
+ ),
+ };
}
// Publish a complete layout document as the grid canvas's new head. Live
@@ -598,10 +670,13 @@ export class DashboardsService {
id: string;
versionId?: string;
}): Promise<CanvasBuildLifecycle> {
+ // slim keeps the payload to render state (live + head + in-flight builds)
+ // because this endpoint is polled every couple of seconds during builds.
+ // Servers that predate the param ignore it and answer in full.
const suffix = input.versionId
- ? `?version_id=${encodeURIComponent(input.versionId)}`
- : "";
- const body = await this.api.json<{
+ ? `?version_id=${encodeURIComponent(input.versionId)}&scope=slim`
+ : "?scope=slim";
+ const body = await this.api.revalidatedJson<{
published_build_id: string | null;
current_version_id: string | null;
builds: Record<string, unknown>[];
diff --git a/products/desktop/packages/core/src/canvas/freeformSchemas.ts b/products/desktop/packages/core/src/canvas/freeformSchemas.ts
index fb7c27c80be9..d65e55cf6271 100644
--- a/products/desktop/packages/core/src/canvas/freeformSchemas.ts
+++ b/products/desktop/packages/core/src/canvas/freeformSchemas.ts
@@ -40,6 +40,11 @@ export type CanvasDataQueryInput = z.infer<typeof canvasDataQueryInput>;
export const canvasDataResultSchema = z.object({
columns: z.array(z.string()),
+ // True when the host served a cached result older than the canvas's declared
+ // refresh window and kicked off a background recompute. The bridge uses it to
+ // shorten its client-cache lifetime so the canvas's next read picks up the
+ // fresh numbers; it is stripped before the result reaches canvas code.
+ stale: z.boolean().optional(),
// The result rows. SHAPE DEPENDS ON THE QUERY KIND (true for both `ph.query`
// and `ph.loadInsight`):
// • HogQLQuery / SQL insight → an array of ROWS, each row an array of cell
diff --git a/products/desktop/packages/core/src/canvas/gridLayoutSchemas.ts b/products/desktop/packages/core/src/canvas/gridLayoutSchemas.ts
index eab8250f88ae..eee13132a073 100644
--- a/products/desktop/packages/core/src/canvas/gridLayoutSchemas.ts
+++ b/products/desktop/packages/core/src/canvas/gridLayoutSchemas.ts
@@ -1,4 +1,5 @@
import { z } from "zod";
+import { canvasBuildLifecycleSchema } from "./canvasBuildSchemas";
// A grid canvas's layout document — its entire "source". Layout is data:
// publishes and patches are live immediately, with no build. The server
@@ -58,10 +59,27 @@ export const canvasLayoutSchema = z.object({
});
export type CanvasLayout = z.infer<typeof canvasLayoutSchema>;
+// The renderable build of one component the layout places, shaped as a build
+// lifecycle so placement tiles reuse the same readers the builds endpoint
+// feeds. One entry per distinct (component, pinned version) pair.
+export const componentLifecycleSeedSchema = z.object({
+ canvasId: z.string(),
+ // The source version the placement pins, or null when it follows the latest.
+ requestedVersionId: z.string().nullable(),
+ lifecycle: canvasBuildLifecycleSchema,
+});
+export type ComponentLifecycleSeed = z.infer<
+ typeof componentLifecycleSeedSchema
+>;
+
export const canvasLayoutResultSchema = z.object({
layout: canvasLayoutSchema,
// The head layout version — pass as expectedCurrentVersionId on writes.
currentVersionId: z.string().nullish(),
+ // Renderable component builds delivered with the layout, so a grid opens on
+ // one round trip instead of one builds fetch per placement. Absent on
+ // servers that predate it.
+ componentLifecycles: z.array(componentLifecycleSeedSchema).optional(),
});
export type CanvasLayoutResult = z.infer<typeof canvasLayoutResultSchema>;
diff --git a/products/desktop/packages/core/src/canvas/posthogApi.ts b/products/desktop/packages/core/src/canvas/posthogApi.ts
index 909481d1afd9..fe239e23ce4e 100644
--- a/products/desktop/packages/core/src/canvas/posthogApi.ts
+++ b/products/desktop/packages/core/src/canvas/posthogApi.ts
@@ -9,12 +9,16 @@ interface HogQLResponse {
results?: unknown[];
columns?: string[];
error?: string | null;
+ last_refresh?: string | null;
}
export interface HogQLResult {
columns: string[];
/** Raw result rows from the query endpoint (each row is typically an array). */
results: unknown[];
+ /** ISO time the returned result was computed, when the endpoint reports it —
+ * what callers judge cached-result freshness by. */
+ lastRefresh: string | null;
}
/**
@@ -31,35 +35,59 @@ export async function runQuery(
query: Record<string, unknown>,
opts?: { refresh?: string },
): Promise<HogQLResult> {
+ const body = await postQuery(authService, query, opts?.refresh);
+ return {
+ columns: Array.isArray(body.columns) ? body.columns.map(String) : [],
+ results: Array.isArray(body.results) ? body.results : [],
+ lastRefresh:
+ typeof body.last_refresh === "string" ? body.last_refresh : null,
+ };
+}
+
+/**
+ * Read a query's CACHED result without ever computing (`refresh: "force_cache"`).
+ * Returns null on a cache miss — the endpoint answers a miss with no `results`
+ * key at all, which is distinct from a computed-but-empty `results: []`.
+ */
+export async function readCachedQuery(
+ authService: AuthService,
+ query: Record<string, unknown>,
+): Promise<HogQLResult | null> {
+ const body = await postQuery(authService, query, "force_cache");
+ if (!Array.isArray(body.results)) return null;
+ return {
+ columns: Array.isArray(body.columns) ? body.columns.map(String) : [],
+ results: body.results,
+ lastRefresh:
+ typeof body.last_refresh === "string" ? body.last_refresh : null,
+ };
+}
+
+async function postQuery(
+ authService: AuthService,
+ query: Record<string, unknown>,
+ refresh: string | undefined,
+): Promise<HogQLResponse> {
const { apiHost } = await authService.getValidAccessToken();
const projectId = authService.getState().currentProjectId;
if (projectId == null) {
throw new Error("No PostHog project selected");
}
-
const response = await authService.authenticatedFetch(
fetch,
`${apiHost}/api/projects/${projectId}/query/`,
{
method: "POST",
headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- query,
- ...(opts?.refresh ? { refresh: opts.refresh } : {}),
- }),
+ body: JSON.stringify({ query, ...(refresh ? { refresh } : {}) }),
},
);
-
if (!response.ok) {
throw new Error(`Query failed (${response.status})`);
}
const body = (await response.json()) as HogQLResponse;
if (body.error) throw new Error(body.error);
-
- return {
- columns: Array.isArray(body.columns) ? body.columns.map(String) : [],
- results: Array.isArray(body.results) ? body.results : [],
- };
+ return body;
}
/** A saved insight's stored result, fetched by short id. */
diff --git a/products/desktop/packages/core/src/canvas/projectApiClient.ts b/products/desktop/packages/core/src/canvas/projectApiClient.ts
index aafa59ec3e3f..87ae7397d6bb 100644
--- a/products/desktop/packages/core/src/canvas/projectApiClient.ts
+++ b/products/desktop/packages/core/src/canvas/projectApiClient.ts
@@ -7,6 +7,8 @@ export const PROJECT_API_CLIENT = Symbol.for(
);
const MAX_PAGES = 50;
+// Bounded per-path store for ETag revalidation (see `revalidatedJson`).
+const MAX_ETAG_ENTRIES = 64;
/** An API call that failed with an HTTP status (so callers can branch on it). */
export class ProjectApiError extends Error {
@@ -85,6 +87,46 @@ export class ProjectApiClient {
return (await res.json()) as T;
}
+ // Last-seen ETag + body per (project, path), for `revalidatedJson`.
+ private readonly etagCache = new Map<
+ string,
+ { etag: string; body: unknown }
+ >();
+
+ /**
+ * GET a JSON resource with ETag revalidation. This process's fetch has no
+ * HTTP cache, so polled endpoints that answer 304 (canvas builds/layout/view)
+ * are revalidated by hand: send the last ETag, and on 304 return the body it
+ * validated. Endpoints without an ETag behave exactly like `json`.
+ */
+ async revalidatedJson<T>(path: string, errorLabel: string): Promise<T> {
+ const projectId = this.authService.getState().currentProjectId;
+ const cacheKey = `${projectId}:${path}`;
+ const cached = this.etagCache.get(cacheKey);
+ const res = await this.fetch(
+ path,
+ cached ? { headers: { "If-None-Match": cached.etag } } : undefined,
+ );
+ if (res.status === 304 && cached) return cached.body as T;
+ if (!res.ok)
+ throw new ProjectApiError(
+ `Failed to ${errorLabel} (${res.status})${await errorBodyDetail(res)}`,
+ res.status,
+ );
+ const body = (await res.json()) as T;
+ const etag = res.headers.get("ETag");
+ if (etag) {
+ // Refresh recency (Map preserves insertion order), then bound the size.
+ this.etagCache.delete(cacheKey);
+ this.etagCache.set(cacheKey, { etag, body });
+ if (this.etagCache.size > MAX_ETAG_ENTRIES) {
+ const oldest = this.etagCache.keys().next().value;
+ if (oldest !== undefined) this.etagCache.delete(oldest);
+ }
+ }
+ return body;
+ }
+
/**
* List a DRF-paginated collection, walking `next` links until exhausted.
* `options.limit` sets the page size on the first request (subsequent pages
diff --git a/products/desktop/packages/core/src/canvas/services.ts b/products/desktop/packages/core/src/canvas/services.ts
index 82f660132793..cab7c44861ad 100644
--- a/products/desktop/packages/core/src/canvas/services.ts
+++ b/products/desktop/packages/core/src/canvas/services.ts
@@ -13,6 +13,7 @@ import type {
CanvasStateEntry,
CanvasStateScope,
CanvasVersion,
+ CanvasView,
DashboardRecord,
} from "./dashboardSchemas";
import type {
@@ -45,6 +46,8 @@ export interface IDashboardsService {
listComponents(input: { search?: string }): Promise<DashboardRecord[]>;
listAll(): Promise<DashboardRecord[]>;
get(id: string): Promise<DashboardRecord | null>;
+ // Everything needed to open a canvas, in one round trip.
+ view(id: string): Promise<CanvasView>;
create(input: {
channelId: string;
name: string;
diff --git a/products/desktop/packages/host-router/src/routers/dashboards.router.ts b/products/desktop/packages/host-router/src/routers/dashboards.router.ts
index fcbaef5537d4..296b3b3b1a8e 100644
--- a/products/desktop/packages/host-router/src/routers/dashboards.router.ts
+++ b/products/desktop/packages/host-router/src/routers/dashboards.router.ts
@@ -17,6 +17,7 @@ import {
canvasStateListInput,
canvasStateSetInput,
canvasVersionSchema,
+ canvasViewSchema,
createDashboardInput,
dashboardIdInput,
dashboardRecordSchema,
@@ -70,6 +71,13 @@ export const dashboardsRouter = router({
.query(({ ctx, input }) =>
ctx.container.get<IDashboardsService>(DASHBOARDS_SERVICE).get(input.id),
),
+ // Everything needed to open a canvas, in one round trip.
+ view: publicProcedure
+ .input(dashboardIdInput)
+ .output(canvasViewSchema)
+ .query(({ ctx, input }) =>
+ ctx.container.get<IDashboardsService>(DASHBOARDS_SERVICE).view(input.id),
+ ),
// A query despite the POST underneath: home is an idempotent get-or-create,
// and query semantics give the surface caching and dedupe for free.
home: publicProcedure
diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelItemRow.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelItemRow.tsx
index eb5278b53d86..f982b730cb7d 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelItemRow.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelItemRow.tsx
@@ -56,10 +56,17 @@ import {
type DragEvent,
type ReactNode,
useCallback,
+ useEffect,
useMemo,
+ useRef,
useState,
} from "react";
+// Pointer-rest delay before a canvas row warms its open-path caches. Matches
+// the space tree's hover-prefetch convention, so arrowing/scrolling rows under
+// a stationary cursor doesn't fire a request per row.
+const CANVAS_HOVER_PRIME_REST_MS = 250;
+
/**
* What a row can do. One object per channel rather than closures per item, so
* the item list stays plain data and doesn't rebuild on every navigation.
@@ -72,6 +79,7 @@ export interface ChannelItemActions {
archive: (item: ChannelItemModel) => void;
remove?: (item: ChannelItemModel) => void;
fileCanvas?: (item: ChannelItemModel, channelId: string) => void;
+ primeCanvas?: (id: string) => void;
}
// The channel sidebar's own chrome. Deliberately not shared with the Code
@@ -277,6 +285,8 @@ export function ChannelItemRowView({
onClick,
onDragStart,
onDragEnd,
+ onMouseEnter,
+ onMouseLeave,
}: {
item: ChannelItemModel;
status: TaskStatusInput | null;
@@ -291,10 +301,14 @@ export function ChannelItemRowView({
onClick?: (e: React.MouseEvent) => void;
onDragStart?: (e: DragEvent) => void;
onDragEnd?: (e: DragEvent) => void;
+ onMouseEnter?: () => void;
+ onMouseLeave?: () => void;
}) {
const pinBadge = item.pinned && showPinBadge;
return (
<SidebarItem
+ onMouseEnter={onMouseEnter}
+ onMouseLeave={onMouseLeave}
// The space's lists follow web conventions — every clickable row shows a
// pointer, like the feed and activity rows — unlike the Code sidebar,
// which keeps SidebarItem's native cursor-default.
@@ -414,6 +428,12 @@ export function ChannelItemRow({
: null,
);
const isArchiving = archivePresentation === "progress";
+ // Warm a canvas's open-path caches once the pointer RESTS on its row (250ms,
+ // the tree's prefetch convention) so the click opens against hot caches.
+ const hoverPrimeTimer = useRef<ReturnType<typeof setTimeout> | undefined>(
+ undefined,
+ );
+ useEffect(() => () => clearTimeout(hoverPrimeTimer.current), []);
const [confirmDeleteOpen, setConfirmDeleteOpen] = useState(false);
const [handoffOpen, setHandoffOpen] = useState(false);
const handoffMounted = useMountedOnceOpened(handoffOpen);
@@ -533,6 +553,22 @@ export function ChannelItemRow({
? undefined
: (e) => (onClick ? onClick(e) : actions.open(item))
}
+ onMouseEnter={
+ item.kind === "canvas" && actions.primeCanvas
+ ? () => {
+ clearTimeout(hoverPrimeTimer.current);
+ hoverPrimeTimer.current = setTimeout(
+ () => actions.primeCanvas?.(item.id),
+ CANVAS_HOVER_PRIME_REST_MS,
+ );
+ }
+ : undefined
+ }
+ onMouseLeave={
+ item.kind === "canvas"
+ ? () => clearTimeout(hoverPrimeTimer.current)
+ : undefined
+ }
/>
);
const row = isArchiving ? (
diff --git a/products/desktop/packages/ui/src/features/canvas/freeform/BuiltCanvas.test.tsx b/products/desktop/packages/ui/src/features/canvas/freeform/BuiltCanvas.test.tsx
index 8901a62ecf99..2771e40aaa24 100644
--- a/products/desktop/packages/ui/src/features/canvas/freeform/BuiltCanvas.test.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/freeform/BuiltCanvas.test.tsx
@@ -51,11 +51,14 @@ describe("BuiltCanvas", () => {
});
it("revokes data access when the artifact document navigates", async () => {
- const onDataRequest = vi.fn().mockResolvedValue({ secret: true });
+ const onDataRequest = vi.fn().mockResolvedValue({ rows: [] });
render(
<BuiltCanvas
artifactUrl="https://usercontent.example/build/index.html"
- capabilities={capabilities}
+ capabilities={{
+ ...capabilities,
+ posthog: { ...capabilities.posthog, inlineQueries: true },
+ }}
onDataRequest={onDataRequest}
/>,
);
diff --git a/products/desktop/packages/ui/src/features/canvas/freeform/FreeformCanvasView.tsx b/products/desktop/packages/ui/src/features/canvas/freeform/FreeformCanvasView.tsx
index 138cfd90ae05..7939098d658a 100644
--- a/products/desktop/packages/ui/src/features/canvas/freeform/FreeformCanvasView.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/freeform/FreeformCanvasView.tsx
@@ -67,6 +67,7 @@ import {
useCanvasSource,
useCanvasVersions,
useDashboardMutations,
+ usePrimeCanvasView,
} from "@posthog/ui/features/canvas/hooks/useDashboards";
import { useCanvasChatPanelStore } from "@posthog/ui/features/canvas/stores/canvasChatPanelStore";
import {
@@ -201,6 +202,15 @@ export function FreeformCanvasView({
const queryClient = useQueryClient();
const authenticatedClient = useOptionalAuthenticatedClient();
+ // One combined round trip (record + live build + head source) that seeds the
+ // per-endpoint caches below where they're empty. On a cold open this removes
+ // the sequential source hop; after a hover prime it makes the whole open a
+ // cache hit. The per-endpoint queries stay authoritative once loaded.
+ const primeCanvasView = usePrimeCanvasView();
+ useEffect(() => {
+ if (dashboardId) primeCanvasView(dashboardId);
+ }, [dashboardId, primeCanvasView]);
+
// The generation-task association lives in the canvas record's meta. Poll it
// while a task is running so the fresh head version + the cleared association
// show up without a manual refresh.
diff --git a/products/desktop/packages/ui/src/features/canvas/freeform/freeformDataBridge.ts b/products/desktop/packages/ui/src/features/canvas/freeform/freeformDataBridge.ts
index c2a79be3318a..e89c3c214985 100644
--- a/products/desktop/packages/ui/src/features/canvas/freeform/freeformDataBridge.ts
+++ b/products/desktop/packages/ui/src/features/canvas/freeform/freeformDataBridge.ts
@@ -43,6 +43,12 @@ function stableStringify(value: unknown): string {
return `{${entries.join(",")}}`;
}
+// How long a STALE host result (served cache-first while the server recomputes
+// in the background) stays in the client cache before the next canvas read
+// re-asks the host: long enough to absorb render-loop reads, short enough
+// that the recomputed numbers arrive promptly.
+const STALE_RESULT_RETRY_SECONDS = 15;
+
// Reads go through the shared QueryClient cache: an iframe re-boot, a canvas
// code-swap, and live edit re-renders all resolve a repeated read from cache
// instead of re-hitting ClickHouse, and concurrent identical reads dedupe. The key
@@ -55,12 +61,20 @@ function cachedRead<T>(
run: (signal: AbortSignal) => Promise<T>,
refreshSeconds?: number,
) {
+ const queryKey = [CANVAS_QUERY_KEY, method, stableStringify(input)] as const;
+ // A stale entry (host said the server cache was older than the canvas's
+ // refresh window) is retried on a short leash instead of sitting for the
+ // whole window; the background recompute it triggered lands in between.
+ const cached = queryClient.getQueryData<{ stale?: boolean }>(queryKey);
+ const lifetimeSeconds = cached?.stale
+ ? STALE_RESULT_RETRY_SECONDS
+ : (refreshSeconds ?? 5 * 60);
return queryClient.fetchQuery({
- queryKey: [CANVAS_QUERY_KEY, method, stableStringify(input)] as const,
+ queryKey,
queryFn: ({ signal }) => run(signal),
...(method === "connectorCall" ? { retry: false } : {}),
meta: method === "connectorCall" ? { authScoped: true } : undefined,
- staleTime: (refreshSeconds ?? 5 * 60) * 1_000,
+ staleTime: lifetimeSeconds * 1_000,
// At least the refresh interval, or GC would evict an inactive entry
// before it goes stale and force an early backend re-read.
gcTime: Math.max(refreshSeconds ?? 5 * 60, 10 * 60) * 1_000,
@@ -160,18 +174,28 @@ export async function handleFreeformDataRequest(
"ph.query requires a typed query node or a HogQL string",
);
}
+ const refresh = refreshSeconds(input.refresh);
+ // `refresh` stays out of the cache key (same data, different lifetime)
+ // but rides the host call: it is the staleness window the host serves
+ // cache-first against.
const args = {
query: input.query,
hogql: input.hogql,
params: input.params,
};
- return cachedRead(
+ const result = await cachedRead(
queryClient,
"query",
args,
- () => hostClient().canvasData.query.mutate(args),
- refreshSeconds(input.refresh),
+ () => hostClient().canvasData.query.mutate({ ...args, refresh }),
+ refresh,
);
+ // The stale marker is bridge-internal cache policy, not canvas data.
+ if (result && typeof result === "object" && "stale" in result) {
+ const { stale: _stale, ...clean } = result;
+ return clean;
+ }
+ return result;
}
case "loadInsight": {
const input = payload as CanvasLoadInsightInput;
diff --git a/products/desktop/packages/ui/src/features/canvas/grid/GridPlacementTile.tsx b/products/desktop/packages/ui/src/features/canvas/grid/GridPlacementTile.tsx
index adb3181304de..08384b91fbb1 100644
--- a/products/desktop/packages/ui/src/features/canvas/grid/GridPlacementTile.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/grid/GridPlacementTile.tsx
@@ -4,8 +4,10 @@ import { isTerminalStatus } from "@posthog/shared/domain-types";
import { PromptInput } from "@posthog/ui/features/message-editor/components/PromptInput";
import { useSessionStore } from "@posthog/ui/features/sessions/sessionStore";
import { taskDetailQuery } from "@posthog/ui/features/tasks/queries";
+import { useInView } from "@posthog/ui/primitives/hooks/useInView";
import { Spinner } from "@posthog/ui/primitives/Spinner";
import { useQuery } from "@tanstack/react-query";
+import type { ReactNode } from "react";
import { useState } from "react";
import { ComponentFrame } from "./ComponentFrame";
import type { PlacementActions } from "./placementActions";
@@ -13,6 +15,26 @@ import type { PlacementActions } from "./placementActions";
// Poll cadence for the fill task's run status while a tile is generating —
// matches the canvas generation poll elsewhere.
const FILL_TASK_POLL_MS = 5_000;
+// How far past the viewport a widget starts booting, so scrolling toward it
+// finds it already mounted.
+const WIDGET_MOUNT_MARGIN = "400px";
+
+/**
+ * Mounts its child once the tile nears the viewport, and keeps it mounted from
+ * then on (unmounting would tear down the widget's iframe on every scroll).
+ * Off-screen widgets on a large grid otherwise all boot, and fetch, at once.
+ */
+function MountNearViewport({ children }: { children: ReactNode }) {
+ const [setElement, inView] = useInView({
+ rootMargin: WIDGET_MOUNT_MARGIN,
+ once: true,
+ });
+ return (
+ <div ref={setElement} className="h-full w-full">
+ {inView ? children : null}
+ </div>
+ );
+}
/**
* One placement on the grid, rendered by lifecycle status: a live widget, a
@@ -33,7 +55,11 @@ export function GridPlacementTile({
actions: PlacementActions;
}) {
if (placement.status === "live" && placement.component) {
- return <ComponentFrame placement={placement} />;
+ return (
+ <MountNearViewport>
+ <ComponentFrame placement={placement} />
+ </MountNearViewport>
+ );
}
if (placement.status === "generating") {
return (
diff --git a/products/desktop/packages/ui/src/features/canvas/grid/useGridLayout.ts b/products/desktop/packages/ui/src/features/canvas/grid/useGridLayout.ts
index 3deacfb48471..90141897ccec 100644
--- a/products/desktop/packages/ui/src/features/canvas/grid/useGridLayout.ts
+++ b/products/desktop/packages/ui/src/features/canvas/grid/useGridLayout.ts
@@ -1,3 +1,7 @@
+import {
+ type CanvasBuildLifecycle,
+ hasActiveCanvasBuild,
+} from "@posthog/core/canvas/canvasBuildSchemas";
import type { DashboardRecord } from "@posthog/core/canvas/dashboardSchemas";
import { applyLayoutOperations } from "@posthog/core/canvas/gridLayoutOperations";
import type {
@@ -7,7 +11,7 @@ import type {
import { useHostTRPC } from "@posthog/host-router/react";
import { toastError } from "@posthog/ui/features/notifications/errorDetails";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
-import { useCallback, useRef } from "react";
+import { useCallback, useEffect, useRef } from "react";
// Poll fast while any placement is being agent-filled (the agent patches the
// layout server-side), otherwise slowly — other viewers/agents can still edit.
@@ -20,7 +24,8 @@ export function useGridLayout(canvasId: string | undefined): {
isLoading: boolean;
} {
const trpc = useHostTRPC();
- const { data, isLoading } = useQuery(
+ const queryClient = useQueryClient();
+ const { data, isLoading, dataUpdatedAt } = useQuery(
trpc.dashboards.layout.queryOptions(
{ id: canvasId ?? "" },
{
@@ -35,6 +40,30 @@ export function useGridLayout(canvasId: string | undefined): {
},
),
);
+ // The layout payload carries each placed component's renderable build. Seed
+ // those into the per-component builds caches (the exact queries the
+ // placement tiles run), so a grid opens on this one call instead of one
+ // builds fetch per placement. Stamped with the layout fetch's own time so a
+ // fresher per-tile fetch (e.g. expired-URL recovery) is never overwritten.
+ useEffect(() => {
+ if (!data?.componentLifecycles) return;
+ for (const entry of data.componentLifecycles) {
+ const queryKey = trpc.dashboards.builds.queryKey({
+ id: entry.canvasId,
+ versionId: entry.requestedVersionId ?? undefined,
+ });
+ const existing = queryClient.getQueryState(queryKey);
+ if (existing && existing.dataUpdatedAt > dataUpdatedAt) continue;
+ // A lifecycle the tile is actively polling (rebuild in flight) must not
+ // be replaced: the seed carries only ready builds, so it would flip
+ // hasActiveCanvasBuild off and stop the tile's poller mid-build.
+ const current = queryClient.getQueryData<CanvasBuildLifecycle>(queryKey);
+ if (current && hasActiveCanvasBuild(current)) continue;
+ queryClient.setQueryData(queryKey, entry.lifecycle, {
+ updatedAt: dataUpdatedAt,
+ });
+ }
+ }, [data, dataUpdatedAt, queryClient, trpc]);
return {
layout: data?.layout,
currentVersionId: data?.currentVersionId ?? null,
@@ -107,13 +136,17 @@ export function usePatchLayout(canvasId: string): {
settled();
// The server's document, with any gesture made since still on top of
// it: adopting it bare would snap those back for their own round trip.
- queryClient.setQueryData(key, {
+ // Patch responses carry no component lifecycles, so the cached ones
+ // (from the layout GET) survive the adoption.
+ queryClient.setQueryData<CanvasLayoutResult>(key, (current) => ({
...result,
+ componentLifecycles:
+ result.componentLifecycles ?? current?.componentLifecycles,
layout: unacknowledged.current.reduce(
(layout, entry) => applyLayoutOperations(layout, entry),
result.layout,
),
- });
+ }));
return result;
} catch (error) {
settled();
diff --git a/products/desktop/packages/ui/src/features/canvas/hooks/invalidateCanvasLifecycle.ts b/products/desktop/packages/ui/src/features/canvas/hooks/invalidateCanvasLifecycle.ts
index 2e0f64e8cae0..4b4d64886b7d 100644
--- a/products/desktop/packages/ui/src/features/canvas/hooks/invalidateCanvasLifecycle.ts
+++ b/products/desktop/packages/ui/src/features/canvas/hooks/invalidateCanvasLifecycle.ts
@@ -17,6 +17,7 @@ export function invalidateCanvasLifecycle(
): Promise<void> {
const id = dashboardId;
return Promise.all([
+ queryClient.invalidateQueries(trpc.dashboards.view.queryFilter({ id })),
queryClient.invalidateQueries(trpc.dashboards.get.queryFilter({ id })),
queryClient.invalidateQueries(trpc.dashboards.builds.queryFilter({ id })),
queryClient.invalidateQueries(trpc.dashboards.versions.queryFilter({ id })),
diff --git a/products/desktop/packages/ui/src/features/canvas/hooks/useChannelItems.test.tsx b/products/desktop/packages/ui/src/features/canvas/hooks/useChannelItems.test.tsx
index 26605261b3b5..20ed6ba1cad4 100644
--- a/products/desktop/packages/ui/src/features/canvas/hooks/useChannelItems.test.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/hooks/useChannelItems.test.tsx
@@ -36,6 +36,7 @@ vi.mock("@posthog/ui/features/canvas/hooks/useChannels", () => ({
vi.mock("@posthog/ui/features/canvas/hooks/useDashboards", () => ({
useDashboards: () => mocks.dashboards,
useDashboardMutations: () => ({ setPinned: mocks.setPinned }),
+ usePrimeCanvasView: () => () => {},
}));
vi.mock("@posthog/ui/features/canvas/hooks/useChannelFeed", () => ({
useChannelFeed: () => mocks.feed,
diff --git a/products/desktop/packages/ui/src/features/canvas/hooks/useChannelItems.tsx b/products/desktop/packages/ui/src/features/canvas/hooks/useChannelItems.tsx
index 5c01257968b9..69043d749c58 100644
--- a/products/desktop/packages/ui/src/features/canvas/hooks/useChannelItems.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/hooks/useChannelItems.tsx
@@ -18,6 +18,7 @@ import { useChannelTasks } from "@posthog/ui/features/canvas/hooks/useChannelTas
import {
useDashboardMutations,
useDashboards,
+ usePrimeCanvasView,
} from "@posthog/ui/features/canvas/hooks/useDashboards";
import { usePinnedTasks } from "@posthog/ui/features/sidebar/usePinnedTasks";
import { useSidebarSessionMap } from "@posthog/ui/features/sidebar/useSidebarSessionMap";
@@ -100,6 +101,7 @@ export function useChannelItems(channelId: string): {
fileDashboard,
invalidateDashboards,
} = useDashboardMutations();
+ const primeCanvasView = usePrimeCanvasView();
const client = useOptionalAuthenticatedClient();
const { data: currentUser, isLoading: viewerLoading } = useCurrentUser({
client,
@@ -243,6 +245,7 @@ export function useChannelItems(channelId: string): {
invalidate: invalidateDashboards,
});
},
+ primeCanvas: primeCanvasView,
}),
[
channelId,
@@ -254,6 +257,7 @@ export function useChannelItems(channelId: string): {
fileDashboard,
channels,
invalidateDashboards,
+ primeCanvasView,
],
);
diff --git a/products/desktop/packages/ui/src/features/canvas/hooks/useDashboards.ts b/products/desktop/packages/ui/src/features/canvas/hooks/useDashboards.ts
index 5f640b205435..9dbd2cf381fc 100644
--- a/products/desktop/packages/ui/src/features/canvas/hooks/useDashboards.ts
+++ b/products/desktop/packages/ui/src/features/canvas/hooks/useDashboards.ts
@@ -69,6 +69,78 @@ export function useAllCanvases(): {
return { dashboards: data ?? [], isLoading };
}
+// How long a primed view payload counts as fresh. Comfortably above the
+// hover→click gap it exists to bridge; re-primes revalidate by ETag anyway.
+const CANVAS_VIEW_PRIME_STALE_MS = 15_000;
+
+/**
+ * Warm a canvas's open-path caches from the combined `view` endpoint — one
+ * round trip carrying the record, the live build (signed artifact URL
+ * included), and the head source when nothing is built yet. Seeds the
+ * record/builds/source caches only where they are empty, so any in-flight or
+ * fresher query stays authoritative. Call on row hover (open-on-click becomes
+ * cache-hot) and on canvas mount (a cold open loses the sequential source hop).
+ */
+export function usePrimeCanvasView(): (id: string) => void {
+ const trpc = useHostTRPC();
+ const queryClient = useQueryClient();
+ return useCallback(
+ (id: string) => {
+ if (!id) return;
+ const seed = (queryKey: readonly unknown[], value: unknown): void => {
+ if (queryClient.getQueryState(queryKey)?.data === undefined) {
+ queryClient.setQueryData(queryKey, value);
+ }
+ };
+ void (async () => {
+ try {
+ const view = await queryClient.fetchQuery(
+ trpc.dashboards.view.queryOptions(
+ { id },
+ { staleTime: CANVAS_VIEW_PRIME_STALE_MS },
+ ),
+ );
+ seed(trpc.dashboards.get.queryKey({ id }), view.record);
+ // Only a settled, head-is-live lifecycle is seedable. With a build
+ // in flight the real fetch must run or the poller that watches it
+ // never starts; with a head that ISN'T the published build (its
+ // build failed, or nothing built yet) the seed would hide the
+ // failed-build banner the real fetch surfaces.
+ const headIsLive =
+ view.currentVersionId == null ||
+ view.publishedBuild?.sourceVersionId === view.currentVersionId;
+ if (!view.hasActiveBuild && headIsLive) {
+ seed(trpc.dashboards.builds.queryKey({ id }), {
+ publishedBuildId: view.record.publishedBuildId,
+ currentVersionId: view.currentVersionId,
+ builds: view.publishedBuild ? [view.publishedBuild] : [],
+ });
+ }
+ if (view.source) {
+ seed(trpc.dashboards.source.queryKey({ id }), {
+ project: view.source,
+ currentVersionId: view.currentVersionId,
+ });
+ }
+ // Grids: the layout (with its component lifecycles) is the whole
+ // open path; useGridLayout's seeding effect fans the lifecycles out
+ // to the per-component builds caches.
+ if (view.layout) {
+ seed(trpc.dashboards.layout.queryKey({ id }), {
+ layout: view.layout,
+ currentVersionId: view.currentVersionId,
+ componentLifecycles: view.componentLifecycles,
+ });
+ }
+ } catch {
+ // Priming is best-effort: the per-endpoint queries still load the canvas.
+ }
+ })();
+ },
+ [trpc, queryClient],
+ );
+}
+
/** A single saved canvas record (metadata + lifecycle pointers). */
export function useDashboard(id: string | undefined): {
dashboard: DashboardRecord | null | undefined;
diff --git a/products/desktop/packages/ui/src/primitives/hooks/useInView.ts b/products/desktop/packages/ui/src/primitives/hooks/useInView.ts
index 033a00d8b5cf..fa80ce0cb400 100644
--- a/products/desktop/packages/ui/src/primitives/hooks/useInView.ts
+++ b/products/desktop/packages/ui/src/primitives/hooks/useInView.ts
@@ -15,6 +15,12 @@ export function useInView<T extends HTMLElement = HTMLDivElement>(
useEffect(() => {
if (!element) return;
+ // No IntersectionObserver (jsdom): everything counts as in view, so
+ // consumers behave as if lazy rendering were disabled.
+ if (typeof IntersectionObserver === "undefined") {
+ setInView(true);
+ return;
+ }
const observer = new IntersectionObserver(
([entry]) => {