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): describe a canvas widget in the task composer (#85411)

Adam Leith2dd790a6e7c3
diff --git a/products/desktop/packages/ui/src/features/canvas/grid/GridCanvasView.tsx b/products/desktop/packages/ui/src/features/canvas/grid/GridCanvasView.tsx
index b799459f7db4..6afbc89f359e 100644
--- a/products/desktop/packages/ui/src/features/canvas/grid/GridCanvasView.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/grid/GridCanvasView.tsx
@@ -32,7 +32,12 @@ import {
GridPlacementTile,
type PlacementTileActions,
} from "./GridPlacementTile";
-import { collides, type GridRect, surfaceRows } from "./gridGeometry";
+import {
+ collides,
+ type GridRect,
+ rectFromCells,
+ surfaceRows,
+} from "./gridGeometry";
import { type GridDragOutcome, useGridDrag } from "./useGridDrag";
import { useGridLayout, usePatchLayout } from "./useGridLayout";
@@ -179,6 +184,8 @@ export function GridCanvasView({
const {
drag,
+ hover,
+ onPointerLeave,
onSurfacePointerDown,
onPointerMove,
onPointerUp,
@@ -289,6 +296,10 @@ export function GridCanvasView({
// layout; horizontal comes from the measured surface width (1fr columns).
const pitchX = (surfaceWidth + grid.gap) / grid.columns;
const pitchY = grid.rowHeight + grid.gap;
+ // A cell already under a tile is not free to draw on, so it stays unlit.
+ const hoveredRect = hover && rectFromCells(hover, hover);
+ const hoveredCell =
+ hoveredRect && !collides(hoveredRect, placements) ? hoveredRect : null;
return (
<div className="flex h-full">
@@ -333,6 +344,7 @@ export function GridCanvasView({
onPointerMove={onPointerMove}
onPointerUp={onPointerUp}
onPointerCancel={onPointerCancel}
+ onPointerLeave={onPointerLeave}
onLostPointerCapture={onPointerCancel}
>
{interactive && surfaceWidth > 0 ? (
@@ -353,6 +365,15 @@ export function GridCanvasView({
}}
/>
) : null}
+ {hoveredCell ? (
+ // The cell a click would fill, so the empty surface says it is
+ // drawable before the pointer goes down.
+ <div
+ aria-hidden
+ className="pointer-events-none rounded-(--radius-3) bg-fill-hover"
+ style={gridItemStyle(hoveredCell)}
+ />
+ ) : null}
{placements.length === 0 && !drag ? (
// How-to placed on the grid as a tile of its own, instead of a
// full-width overlay that looks like broken chrome. Pointer events
diff --git a/products/desktop/packages/ui/src/features/canvas/grid/GridPlacementTile.stories.tsx b/products/desktop/packages/ui/src/features/canvas/grid/GridPlacementTile.stories.tsx
new file mode 100644
index 000000000000..f126395a452a
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/canvas/grid/GridPlacementTile.stories.tsx
@@ -0,0 +1,78 @@
+import type { GridPlacement } from "@posthog/core/canvas/gridLayoutSchemas";
+import type { Meta, StoryObj } from "@storybook/react-vite";
+import {
+ GridPlacementTile,
+ type PlacementTileActions,
+} from "./GridPlacementTile";
+
+const PLACEMENT: GridPlacement = {
+ id: "p1",
+ status: "pending",
+ x: 0,
+ y: 0,
+ w: 2,
+ h: 2,
+};
+
+const actions: PlacementTileActions = {
+ describe: async () => {},
+ reset: () => {},
+ remove: () => {},
+ discuss: () => {},
+};
+
+// A drawn box sits on the grid at the size it was drawn, so the stories frame
+// the tile the way the canvas does rather than letting it fill the page. The
+// chrome mirrors the wrapper in GridCanvasView; keep the two in step, since
+// these stories are what say the smallest box still fits its contents.
+function Tile({
+ height,
+ placement,
+}: {
+ height: number;
+ placement: GridPlacement;
+}) {
+ return (
+ <div
+ className="overflow-hidden rounded-(--radius-3) border border-(--gray-5) bg-(--color-panel-solid)"
+ style={{ width: 320, height }}
+ >
+ <GridPlacementTile
+ placement={placement}
+ interactive
+ patching={false}
+ actions={actions}
+ />
+ </div>
+ );
+}
+
+const meta = {
+ title: "Canvas/GridPlacementTile",
+ component: Tile,
+} satisfies Meta<typeof Tile>;
+
+export default meta;
+type Story = StoryObj<typeof meta>;
+
+/** A box waiting for its description, drawn two rows tall. */
+export const Pending: Story = {
+ args: { height: 200, placement: PLACEMENT },
+};
+
+/** The smallest box the grid draws: one column, one row. */
+export const PendingSingleCell: Story = {
+ args: { height: 96, placement: { ...PLACEMENT, w: 1, h: 1 } },
+};
+
+/** A fill that failed keeps the prompt and offers a retry. */
+export const Failed: Story = {
+ args: {
+ height: 200,
+ placement: {
+ ...PLACEMENT,
+ status: "failed",
+ prompt: "Weekly signups by source",
+ },
+ },
+};
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 46d5cbb8af19..3cb254d4c154 100644
--- a/products/desktop/packages/ui/src/features/canvas/grid/GridPlacementTile.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/grid/GridPlacementTile.tsx
@@ -1,6 +1,7 @@
import type { GridPlacement } from "@posthog/core/canvas/gridLayoutSchemas";
-import { Button, Input, Spinner, Text } from "@posthog/quill";
+import { Button, Spinner, Text } from "@posthog/quill";
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 { useQuery } from "@tanstack/react-query";
@@ -170,7 +171,7 @@ function GeneratingTile({
{viewTask}
{interactive ? (
<Button
- variant="default"
+ variant="destructive"
size="sm"
disabled={patching}
onClick={() => actions.remove(placement)}
@@ -196,7 +197,6 @@ function DescribeTile({
patching: boolean;
actions: PlacementTileActions;
}) {
- const [prompt, setPrompt] = useState(placement.prompt ?? "");
const [isSubmitting, setIsSubmitting] = useState(false);
if (!interactive) {
@@ -208,51 +208,49 @@ function DescribeTile({
</div>
);
}
- const submit = async () => {
- if (!prompt.trim() || isSubmitting) return;
+ const submit = async (text: string) => {
+ const instruction = text.trim();
+ if (!instruction || isSubmitting) return;
setIsSubmitting(true);
try {
- await actions.describe(placement, prompt.trim());
+ await actions.describe(placement, instruction);
} finally {
setIsSubmitting(false);
}
};
return (
- <div className="flex h-full w-full flex-col items-center justify-center gap-2 p-3 text-center">
+ <div className="flex h-full w-full flex-col justify-center gap-2 p-3">
{failed ? (
<Text size="sm">This widget failed to build. Describe it again:</Text>
) : null}
- <form
- className="flex w-full items-center gap-1"
- onSubmit={(event) => {
- event.preventDefault();
- void submit();
- }}
- >
- <Input
- autoFocus
- value={prompt}
- onChange={(event) => setPrompt(event.target.value)}
- placeholder="What should go here?"
- disabled={isSubmitting}
- />
- <Button
- type="submit"
- size="sm"
- loading={isSubmitting}
- disabled={!prompt.trim() || isSubmitting}
- >
- {failed ? "Retry" : "Create"}
- </Button>
- </form>
- <Button
- variant="default"
- size="sm"
- disabled={patching}
- onClick={() => actions.remove(placement)}
- >
- Remove
- </Button>
+ {/* The task composer's editor, as the freeform canvas uses it: markdown
+ as you type, shift+enter for a new line, @ for files and / for
+ skills. Its own toolbar stays hidden — the only control this box
+ needs beside send is the one that takes the box away. */}
+ <PromptInput
+ sessionId={`grid-placement-${placement.id}`}
+ placeholder="What should go here?"
+ // A failed fill keeps what was asked for, so the retry starts from it
+ // unless a draft is already waiting in the box.
+ initialContent={placement.prompt ?? undefined}
+ autoFocus
+ disabled={isSubmitting}
+ isLoading={isSubmitting}
+ enableCommands
+ enableBashMode={false}
+ hideDefaultToolbar
+ onSubmit={(text) => void submit(text)}
+ toolbarEndSlot={
+ <Button
+ variant="destructive"
+ size="sm"
+ disabled={patching}
+ onClick={() => actions.remove(placement)}
+ >
+ Remove
+ </Button>
+ }
+ />
</div>
);
}
diff --git a/products/desktop/packages/ui/src/features/canvas/grid/gridGeometry.ts b/products/desktop/packages/ui/src/features/canvas/grid/gridGeometry.ts
index ab668b0dd5d9..72f6db8a58db 100644
--- a/products/desktop/packages/ui/src/features/canvas/grid/gridGeometry.ts
+++ b/products/desktop/packages/ui/src/features/canvas/grid/gridGeometry.ts
@@ -3,6 +3,17 @@ import type {
GridPlacement,
} from "@posthog/core/canvas/gridLayoutSchemas";
+/** A single cell of the grid, by column and row. */
+export interface GridCell {
+ col: number;
+ row: number;
+}
+
+export function sameCell(a: GridCell | null, b: GridCell | null): boolean {
+ if (!a || !b) return a === b;
+ return a.col === b.col && a.row === b.row;
+}
+
export interface GridRect {
x: number;
y: number;
@@ -46,7 +57,7 @@ export function cellFromPoint(
pointerY: number,
surface: { left: number; top: number; width: number },
grid: GridDefinition,
-): { col: number; row: number } {
+): GridCell {
const cellWidth = (surface.width + grid.gap) / grid.columns;
const col = Math.floor((pointerX - surface.left) / cellWidth);
const row = Math.floor(
@@ -59,10 +70,7 @@ export function cellFromPoint(
}
// The normalized rect spanned by two cells (a drag's anchor and current cell).
-export function rectFromCells(
- anchor: { col: number; row: number },
- current: { col: number; row: number },
-): GridRect {
+export function rectFromCells(anchor: GridCell, current: GridCell): GridRect {
const x = Math.min(anchor.col, current.col);
const y = Math.min(anchor.row, current.row);
return {
diff --git a/products/desktop/packages/ui/src/features/canvas/grid/useGridDrag.ts b/products/desktop/packages/ui/src/features/canvas/grid/useGridDrag.ts
index 0caa54384776..a56ab58cc90d 100644
--- a/products/desktop/packages/ui/src/features/canvas/grid/useGridDrag.ts
+++ b/products/desktop/packages/ui/src/features/canvas/grid/useGridDrag.ts
@@ -6,16 +6,18 @@ import { type RefObject, useState } from "react";
import {
cellFromPoint,
clampRect,
+ type GridCell,
type GridRect,
rectFromCells,
+ sameCell,
} from "./gridGeometry";
export type GridDragState =
- | { kind: "draw"; anchor: { col: number; row: number }; rect: GridRect }
+ | { kind: "draw"; anchor: GridCell; rect: GridRect }
| {
kind: "move";
placementId: string;
- grabbed: { col: number; row: number };
+ grabbed: GridCell;
origin: GridRect;
rect: GridRect;
}
@@ -46,6 +48,10 @@ export function useGridDrag({
onComplete: (outcome: GridDragOutcome) => void;
}) {
const [drag, setDrag] = useState<GridDragState | null>(null);
+ // The empty cell under a resting pointer, so the surface can show where a
+ // click would put a box. Only the surface itself reports one: a tile handles
+ // its own presses, and hovering it is not an offer to draw.
+ const [hover, setHover] = useState<GridCell | null>(null);
const cellAt = (event: React.PointerEvent) => {
const surface = surfaceRef.current?.getBoundingClientRect();
@@ -62,6 +68,7 @@ export function useGridDrag({
if (event.target !== surfaceRef.current) return;
const anchor = cellAt(event);
capture(event);
+ setHover(null);
setDrag({ kind: "draw", anchor, rect: rectFromCells(anchor, anchor) });
};
@@ -70,6 +77,7 @@ export function useGridDrag({
if (!interactive || event.button !== 0) return;
event.stopPropagation();
capture(event);
+ setHover(null);
setDrag({
kind: "move",
placementId: placement.id,
@@ -89,6 +97,7 @@ export function useGridDrag({
if (!interactive || event.button !== 0) return;
event.stopPropagation();
capture(event);
+ setHover(null);
setDrag({
kind: "resize",
placementId: placement.id,
@@ -103,7 +112,17 @@ export function useGridDrag({
};
const onPointerMove = (event: React.PointerEvent) => {
- if (!drag) return;
+ if (!drag) {
+ const cell =
+ interactive && event.target === surfaceRef.current
+ ? cellAt(event)
+ : null;
+ // Every pointer move crosses this, and the surface renders a widget per
+ // tile — so hold the same cell rather than re-rendering the canvas at
+ // pointer rate.
+ setHover((current) => (sameCell(current, cell) ? current : cell));
+ return;
+ }
const cell = cellAt(event);
if (drag.kind === "draw") {
setDrag({ ...drag, rect: rectFromCells(drag.anchor, cell) });
@@ -153,8 +172,17 @@ export function useGridDrag({
setDrag(null);
};
+ const onPointerLeave = () => {
+ setHover(null);
+ };
+
return {
drag,
+ // Derived rather than reset: a hover left behind by the pointer resting on
+ // the surface when edit mode ends would otherwise paint a cell the canvas
+ // no longer lets you fill.
+ hover: interactive ? hover : null,
+ onPointerLeave,
onSurfacePointerDown,
onPointerMove,
onPointerUp,
diff --git a/products/desktop/packages/ui/src/features/message-editor/components/PromptInput.tsx b/products/desktop/packages/ui/src/features/message-editor/components/PromptInput.tsx
index 56e100177909..0b3aaa20f5a9 100644
--- a/products/desktop/packages/ui/src/features/message-editor/components/PromptInput.tsx
+++ b/products/desktop/packages/ui/src/features/message-editor/components/PromptInput.tsx
@@ -51,6 +51,8 @@ export interface PromptInputProps {
isActiveSession?: boolean;
submitDisabledExternal?: boolean;
clearOnSubmit?: boolean;
+ /** What the composer starts from when this session has no draft yet. */
+ initialContent?: string;
// session context
taskId?: string;
repoPath?: string | null;
@@ -142,6 +144,7 @@ export const PromptInput = forwardRef<EditorHandle, PromptInputProps>(
isActiveSession = true,
submitDisabledExternal = false,
clearOnSubmit,
+ initialContent,
taskId,
repoPath,
modeOption,
@@ -233,6 +236,7 @@ export const PromptInput = forwardRef<EditorHandle, PromptInputProps>(
isLoading,
autoFocus,
clearOnSubmit,
+ initialContent,
context: { taskId, repoPath: repoPath ?? undefined },
capabilities: {
bashMode: enableBashMode,
diff --git a/products/desktop/packages/ui/src/features/message-editor/tiptap/useDraftSync.test.tsx b/products/desktop/packages/ui/src/features/message-editor/tiptap/useDraftSync.test.tsx
index deb88de31cb4..56921c876d53 100644
--- a/products/desktop/packages/ui/src/features/message-editor/tiptap/useDraftSync.test.tsx
+++ b/products/desktop/packages/ui/src/features/message-editor/tiptap/useDraftSync.test.tsx
@@ -10,8 +10,21 @@ vi.mock("@posthog/ui/shell/rendererStorage", () => ({
}));
import { useDraftStore } from "@posthog/ui/features/message-editor/draftStore";
+import { Editor } from "@tiptap/core";
+import { getEditorExtensions } from "./extensions";
import { useDraftSync } from "./useDraftSync";
+// A real editor rather than a stub of the commands the hook calls: what the
+// restore path is worth testing for is the text a user would see in the box.
+function makeEditor(): Editor {
+ const element = document.createElement("div");
+ document.body.appendChild(element);
+ return new Editor({
+ element,
+ extensions: getEditorExtensions({ sessionId: "session-1" }),
+ });
+}
+
function DraftAttachmentsProbe({ sessionId }: { sessionId: string }) {
const { restoredAttachments } = useDraftSync(null, sessionId);
return (
@@ -21,6 +34,19 @@ function DraftAttachmentsProbe({ sessionId }: { sessionId: string }) {
);
}
+function RestoreProbe({
+ editor,
+ sessionId,
+ initialContent,
+}: {
+ editor: Editor;
+ sessionId: string;
+ initialContent?: string;
+}) {
+ useDraftSync(editor, sessionId, undefined, initialContent);
+ return null;
+}
+
describe("useDraftSync", () => {
beforeEach(() => {
vi.clearAllMocks();
@@ -35,6 +61,56 @@ describe("useDraftSync", () => {
}));
});
+ // The composer is what a user sees on open, and two things want to fill it.
+ it.each([
+ [
+ "starts from initialContent when the session has no draft",
+ null,
+ "Sales by week",
+ ],
+ [
+ "leaves a saved draft alone",
+ { segments: [{ type: "text" as const, text: "half a thought" }] },
+ "half a thought",
+ ],
+ ])("%s", (_name, draft, expected) => {
+ const editor = makeEditor();
+ if (draft) {
+ useDraftStore.getState().actions.setDraft("session-restore", draft);
+ }
+
+ render(
+ <RestoreProbe
+ editor={editor}
+ sessionId="session-restore"
+ initialContent="Sales by week"
+ />,
+ );
+
+ expect(editor.getText()).toBe(expected);
+ });
+
+ // Drafts land only once the store hydrates, so filling the box before that
+ // would show the caller's text and then swap it for what the user had typed.
+ it("holds initialContent until the draft store hydrates", () => {
+ useDraftStore.setState((state) => ({ ...state, _hasHydrated: false }));
+ const editor = makeEditor();
+
+ render(
+ <RestoreProbe
+ editor={editor}
+ sessionId="session-hydration"
+ initialContent="Sales by week"
+ />,
+ );
+ expect(editor.getText()).toBe("");
+
+ act(() => {
+ useDraftStore.getState().actions.setHasHydrated(true);
+ });
+ expect(editor.getText()).toBe("Sales by week");
+ });
+
it("clears restored attachments when a draft no longer has attachments", () => {
const { rerender } = render(
<DraftAttachmentsProbe sessionId="session-1" />,
diff --git a/products/desktop/packages/ui/src/features/message-editor/tiptap/useDraftSync.ts b/products/desktop/packages/ui/src/features/message-editor/tiptap/useDraftSync.ts
index 1968aa957963..fd66ef158056 100644
--- a/products/desktop/packages/ui/src/features/message-editor/tiptap/useDraftSync.ts
+++ b/products/desktop/packages/ui/src/features/message-editor/tiptap/useDraftSync.ts
@@ -20,6 +20,8 @@ export function useDraftSync(
editor: Editor | null,
sessionId: string,
context?: DraftContext,
+ /** What the composer starts from when this session has no draft yet. */
+ initialContent?: string,
) {
const hasRestoredRef = useRef(false);
const lastSessionIdRef = useRef(sessionId);
@@ -63,7 +65,16 @@ export function useDraftSync(
// Restore draft on mount or when sessionId/editor changes
useLayoutEffect(() => {
if (!hasHydrated || !editor || hasRestoredRef.current) return;
- if (!draft || isContentEmpty(draft)) return;
+ if (!draft || isContentEmpty(draft)) {
+ // A caller's starting point fills the box only when nothing was left in
+ // it. It waits for hydration like the draft does, so the two can't race
+ // and flash one over the other.
+ if (initialContent) {
+ hasRestoredRef.current = true;
+ editor.commands.setContent(initialContent);
+ }
+ return;
+ }
hasRestoredRef.current = true;
@@ -72,7 +83,7 @@ export function useDraftSync(
} else {
editor.commands.setContent(editorContentToTiptapJson(draft));
}
- }, [hasHydrated, draft, editor]);
+ }, [hasHydrated, draft, editor, initialContent]);
// Handle pending content (e.g., restoring queued messages after cancel)
useLayoutEffect(() => {
diff --git a/products/desktop/packages/ui/src/features/message-editor/tiptap/useTiptapEditor.ts b/products/desktop/packages/ui/src/features/message-editor/tiptap/useTiptapEditor.ts
index 76936b3612ac..468a2e93fd61 100644
--- a/products/desktop/packages/ui/src/features/message-editor/tiptap/useTiptapEditor.ts
+++ b/products/desktop/packages/ui/src/features/message-editor/tiptap/useTiptapEditor.ts
@@ -68,6 +68,8 @@ export interface UseTiptapEditorOptions {
bashMode?: boolean;
};
clearOnSubmit?: boolean;
+ /** What the composer starts from when this session has no draft yet. */
+ initialContent?: string;
getPromptHistory?: () => string[];
onPromptRecall?: PromptRecallHandler;
onBeforeSubmit?: (text: string, clearEditor: () => void) => boolean;
@@ -246,6 +248,7 @@ export function useTiptapEditor(options: UseTiptapEditorOptions) {
context,
capabilities = {},
clearOnSubmit = true,
+ initialContent,
getPromptHistory,
onPromptRecall,
onBeforeSubmit,
@@ -737,7 +740,7 @@ export function useTiptapEditor(options: UseTiptapEditorOptions) {
[sessionId, disabled, fileMentions, commands, placeholder],
);
- const draft = useDraftSync(editor, sessionId, context);
+ const draft = useDraftSync(editor, sessionId, context, initialContent);
draftRef.current = draft;
// biome-ignore lint/correctness/useExhaustiveDependencies: `editor` is the trigger: a recreated editor brings a new schema, and restoring a snapshot taken against the old one would throw on replaceWith.