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.

fix(desktop): canvas home optimistic resizing (#85375)

Adam Leith044ccefabfea
diff --git a/products/desktop/packages/core/src/canvas/gridLayoutOperations.test.ts b/products/desktop/packages/core/src/canvas/gridLayoutOperations.test.ts
new file mode 100644
index 000000000000..e956db24120f
--- /dev/null
+++ b/products/desktop/packages/core/src/canvas/gridLayoutOperations.test.ts
@@ -0,0 +1,65 @@
+import { describe, expect, it } from "vitest";
+import { applyLayoutOperations } from "./gridLayoutOperations";
+import type { CanvasLayout, LayoutOperation } from "./gridLayoutSchemas";
+
+const LAYOUT: CanvasLayout = {
+ schemaVersion: 1,
+ grid: { columns: 6, rowHeight: 96, gap: 8 },
+ placements: [
+ { id: "p1", status: "live", x: 0, y: 0, w: 2, h: 2 },
+ { id: "p2", status: "pending", x: 2, y: 0, w: 1, h: 1 },
+ ],
+};
+
+describe("applyLayoutOperations", () => {
+ // What a surface shows between a gesture and its patch answering, so each op
+ // has to land the same way the server lands it.
+ it.each([
+ [
+ "moves a placement",
+ [
+ {
+ op: "update_placement",
+ id: "p1",
+ changes: { x: 3, y: 1 },
+ },
+ ] satisfies LayoutOperation[],
+ { p1: { x: 3, y: 1, w: 2, h: 2 }, p2: { x: 2, y: 0, w: 1, h: 1 } },
+ ],
+ [
+ "removes a placement",
+ [{ op: "remove_placement", id: "p2" }] satisfies LayoutOperation[],
+ { p1: { x: 0, y: 0, w: 2, h: 2 } },
+ ],
+ [
+ "adds a placement",
+ [
+ {
+ op: "add_placement",
+ placement: { id: "p3", status: "pending", x: 4, y: 0, w: 2, h: 2 },
+ },
+ ] satisfies LayoutOperation[],
+ {
+ p1: { x: 0, y: 0, w: 2, h: 2 },
+ p2: { x: 2, y: 0, w: 1, h: 1 },
+ p3: { x: 4, y: 0, w: 2, h: 2 },
+ },
+ ],
+ ])("%s", (_name, operations, expected) => {
+ const result = applyLayoutOperations(LAYOUT, operations);
+ expect(
+ Object.fromEntries(
+ result.placements.map(({ id, x, y, w, h }) => [id, { x, y, w, h }]),
+ ),
+ ).toEqual(expected);
+ });
+
+ it("leaves the document it was given untouched", () => {
+ applyLayoutOperations(LAYOUT, [
+ { op: "remove_placement", id: "p1" },
+ { op: "set_grid", grid: { columns: 12, rowHeight: 96, gap: 8 } },
+ ]);
+ expect(LAYOUT.placements).toHaveLength(2);
+ expect(LAYOUT.grid.columns).toBe(6);
+ });
+});
diff --git a/products/desktop/packages/core/src/canvas/gridLayoutOperations.ts b/products/desktop/packages/core/src/canvas/gridLayoutOperations.ts
new file mode 100644
index 000000000000..4f09ac17d33f
--- /dev/null
+++ b/products/desktop/packages/core/src/canvas/gridLayoutOperations.ts
@@ -0,0 +1,45 @@
+import type { CanvasLayout, LayoutOperation } from "./gridLayoutSchemas";
+
+/**
+ * A layout document with the server's own operations applied to it. The server
+ * stays the authority — it validates geometry and overlaps and mints the next
+ * version — so this exists for what a surface shows while its patch is in
+ * flight, and has to stay a pure function of the document it is handed.
+ */
+export function applyLayoutOperations(
+ layout: CanvasLayout,
+ operations: LayoutOperation[],
+): CanvasLayout {
+ return operations.reduce(applyOperation, layout);
+}
+
+function applyOperation(
+ layout: CanvasLayout,
+ operation: LayoutOperation,
+): CanvasLayout {
+ switch (operation.op) {
+ case "set_grid":
+ return { ...layout, grid: operation.grid };
+ case "add_placement":
+ return {
+ ...layout,
+ placements: [...layout.placements, operation.placement],
+ };
+ case "update_placement":
+ return {
+ ...layout,
+ placements: layout.placements.map((placement) =>
+ placement.id === operation.id
+ ? { ...placement, ...operation.changes }
+ : placement,
+ ),
+ };
+ case "remove_placement":
+ return {
+ ...layout,
+ placements: layout.placements.filter(
+ (placement) => placement.id !== operation.id,
+ ),
+ };
+ }
+}
diff --git a/products/desktop/packages/ui/src/features/canvas/grid/useGridLayout.test.tsx b/products/desktop/packages/ui/src/features/canvas/grid/useGridLayout.test.tsx
index d0bce84bd1d0..dbea840be0d1 100644
--- a/products/desktop/packages/ui/src/features/canvas/grid/useGridLayout.test.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/grid/useGridLayout.test.tsx
@@ -38,17 +38,22 @@ const MOVE: LayoutOperation[] = [
{ op: "update_placement", id: "p1", changes: { x: 1 } },
];
-function layoutAt(versionId: string): CanvasLayoutResult {
+function layoutAt(versionId: string, x = 0): CanvasLayoutResult {
return {
layout: {
schemaVersion: 1,
grid: { columns: 6, rowHeight: 96, gap: 8 },
- placements: [],
+ placements: [{ id: "p1", status: "live", x, y: 0, w: 1, h: 1 }],
},
currentVersionId: versionId,
};
}
+function placedX(): number | undefined {
+ return queryClient.getQueryData<CanvasLayoutResult>(LAYOUT_KEY)?.layout
+ .placements[0]?.x;
+}
+
let queryClient: QueryClient;
function wrapper({ children }: { children: ReactNode }) {
@@ -103,6 +108,58 @@ describe("usePatchLayout", () => {
expect(queryClient.getQueryData(LAYOUT_KEY)).toEqual(layoutAt("v3"));
});
+ // The canvas renders the layout cache, so an edit that waits for its patch
+ // is an edit the user watches snap back for the length of a round trip.
+ it("shows an edit before its patch is sent", async () => {
+ let releasePatch = (): void => {};
+ const inFlight = new Promise<void>((resolve) => {
+ releasePatch = resolve;
+ });
+ mocks.patchLayout.mockImplementationOnce(async () => {
+ await inFlight;
+ return layoutAt("v2", 1);
+ });
+
+ const { result } = renderHook(() => usePatchLayout("canvas-1"), {
+ wrapper,
+ });
+ await act(async () => {
+ const patched = result.current.patch(MOVE);
+ expect(placedX()).toBe(1);
+ releasePatch();
+ await patched;
+ });
+ });
+
+ // Two drags inside one round trip: adopting the first patch's document bare
+ // would drop the second drag back to the first one's cell until it answers.
+ it("keeps a later gesture when an earlier patch answers", async () => {
+ let releaseFirst = (): void => {};
+ const firstInFlight = new Promise<void>((resolve) => {
+ releaseFirst = resolve;
+ });
+ mocks.patchLayout
+ .mockImplementationOnce(async () => {
+ await firstInFlight;
+ return layoutAt("v2", 1);
+ })
+ .mockImplementationOnce(async () => layoutAt("v3", 2));
+
+ const { result } = renderHook(() => usePatchLayout("canvas-1"), {
+ wrapper,
+ });
+ await act(async () => {
+ const first = result.current.patch(MOVE);
+ const second = result.current.patch([
+ { op: "update_placement", id: "p1", changes: { x: 2 } },
+ ]);
+ releaseFirst();
+ await first;
+ expect(placedX()).toBe(2);
+ await second;
+ });
+ });
+
// A rejected patch must not wedge the queue: the next gesture still runs.
it("reports a rejected patch as null and keeps accepting later ones", async () => {
mocks.patchLayout
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 3e11f97fe1c0..e0ef8148d5aa 100644
--- a/products/desktop/packages/ui/src/features/canvas/grid/useGridLayout.ts
+++ b/products/desktop/packages/ui/src/features/canvas/grid/useGridLayout.ts
@@ -1,4 +1,5 @@
import type { DashboardRecord } from "@posthog/core/canvas/dashboardSchemas";
+import { applyLayoutOperations } from "@posthog/core/canvas/gridLayoutOperations";
import type {
CanvasLayoutResult,
LayoutOperation,
@@ -42,10 +43,13 @@ export function useGridLayout(canvasId: string | undefined): {
}
/**
- * Guarded surgical writes to a grid canvas's layout. On success the layout
- * cache adopts the server's document; on any failure (including a 409 from a
- * concurrent edit) the layout is refetched so the surface rebases on the real
- * head instead of retrying blind.
+ * Guarded surgical writes to a grid canvas's layout. The edit shows the moment
+ * it is made: the operations are applied to the layout cache on the way out,
+ * because rendering the server's document for the length of the round trip
+ * snaps a dragged tile back to where it started. On success the cache adopts
+ * the server's document; on any failure (including a 409 from a concurrent
+ * edit) the layout is refetched so the surface rebases on the real head
+ * instead of retrying blind.
*
* Patches run one at a time, each reading the head from the layout cache when
* it is actually sent. Two gestures can finish before the first patch answers,
@@ -61,32 +65,58 @@ export function usePatchLayout(canvasId: string): {
} {
const trpc = useHostTRPC();
const queryClient = useQueryClient();
- const layoutKey = trpc.dashboards.layout.queryKey({ id: canvasId });
const { mutateAsync, isPending } = useMutation(
- trpc.dashboards.patchLayout.mutationOptions({
- onSuccess: (result) => {
- queryClient.setQueryData(layoutKey, result);
- },
- }),
+ trpc.dashboards.patchLayout.mutationOptions(),
);
// The tail of the patch queue. It never rejects, so one failed patch cannot
// wedge the gestures behind it.
const queue = useRef<Promise<CanvasLayoutResult | null>>(
Promise.resolve(null),
);
+ // Edits the canvas already shows and the server has not acknowledged, oldest
+ // first.
+ const unacknowledged = useRef<LayoutOperation[][]>([]);
const patch = useCallback(
(operations: LayoutOperation[], prompt?: string) => {
const key = trpc.dashboards.layout.queryKey({ id: canvasId });
+ queryClient.setQueryData<CanvasLayoutResult>(key, (current) =>
+ current
+ ? {
+ ...current,
+ layout: applyLayoutOperations(current.layout, operations),
+ }
+ : current,
+ );
+ unacknowledged.current = [...unacknowledged.current, operations];
+ const settled = () => {
+ unacknowledged.current = unacknowledged.current.filter(
+ (entry) => entry !== operations,
+ );
+ };
const queued = queue.current.then(async () => {
const head = queryClient.getQueryData<CanvasLayoutResult>(key);
try {
- return await mutateAsync({
+ const result = await mutateAsync({
id: canvasId,
operations,
prompt,
+ // The optimistic write above leaves this field alone, so the guard
+ // still names the head the server itself last minted.
expectedCurrentVersionId: head?.currentVersionId ?? null,
});
+ 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, {
+ ...result,
+ layout: unacknowledged.current.reduce(
+ (layout, entry) => applyLayoutOperations(layout, entry),
+ result.layout,
+ ),
+ });
+ return result;
} catch (error) {
+ settled();
toastError("Couldn't update the canvas layout", error);
// Rebase before the next queued gesture is sent, and let callers
// treat null as "this edit didn't land".