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): improve command center task placement (#76694)

Ben White68bbbe07e554
diff --git a/products/desktop/packages/core/src/command-center/grid.test.ts b/products/desktop/packages/core/src/command-center/grid.test.ts
index c046a0a17faa..a69414fba729 100644
--- a/products/desktop/packages/core/src/command-center/grid.test.ts
+++ b/products/desktop/packages/core/src/command-center/grid.test.ts
@@ -5,12 +5,16 @@ import {
countActiveTaskCells,
getCellCount,
getCellSessionId,
+ getExpandedLayout,
+ getExpansionCellIndex,
getGridDimensions,
+ getOptimalLayout,
getTerminalCellCwd,
getTerminalCellId,
isBrainrotCell,
isTerminalCell,
makeTerminalCellValue,
+ reflowCells,
resizeCells,
} from "./grid";
@@ -32,6 +36,87 @@ describe("getGridDimensions / getCellCount", () => {
);
});
+describe("getExpansionCellIndex", () => {
+ // Widening 2x2 to 3x2 puts the new column at indices 2 and 5; growing it to
+ // 2x3 puts the new row at 4 and 5.
+ it.each([
+ { expanded: "3x2", direction: "horizontal", slot: 0, expected: 2 },
+ { expanded: "3x2", direction: "horizontal", slot: 1, expected: 5 },
+ { expanded: "2x3", direction: "vertical", slot: 0, expected: 4 },
+ { expanded: "2x3", direction: "vertical", slot: 1, expected: 5 },
+ ] as const)(
+ "$expanded $direction slot $slot -> $expected",
+ ({ expanded, direction, slot, expected }) => {
+ expect(getExpansionCellIndex(expanded, direction, slot)).toBe(expected);
+ },
+ );
+});
+
+describe("getOptimalLayout", () => {
+ it.each([
+ [0, "1x1"],
+ [1, "1x1"],
+ [2, "2x1"],
+ [3, "2x2"],
+ [4, "2x2"],
+ [5, "3x2"],
+ [6, "3x2"],
+ [7, "3x3"],
+ [9, "3x3"],
+ [12, "3x3"],
+ ] as const)("fits %i tiles in %s", (count, expected) => {
+ expect(getOptimalLayout(count)).toBe(expected);
+ });
+});
+
+describe("getExpandedLayout", () => {
+ it.each([
+ ["1x1", "horizontal", "2x1"],
+ ["1x1", "vertical", "1x2"],
+ ["2x2", "horizontal", "3x2"],
+ ["2x2", "vertical", "2x3"],
+ ["3x1", "horizontal", null],
+ ["1x3", "vertical", null],
+ ["3x3", "horizontal", null],
+ ["3x3", "vertical", null],
+ ] as const)("expands %s %s to %s", (layout, direction, expected) => {
+ expect(getExpandedLayout(layout, direction)).toBe(expected);
+ });
+});
+
+describe("reflowCells", () => {
+ // Row-major storage means a column change moves every row's start: 2x2
+ // [a,b / c,d] widening to 3x2 must keep c and d on row two.
+ it("keeps cells in the same row and column when a column is added", () => {
+ expect(reflowCells(["a", "b", "c", "d"], "2x2", "3x2")).toEqual([
+ "a",
+ "b",
+ null,
+ "c",
+ "d",
+ null,
+ ]);
+ });
+
+ it("appends empty cells when a row is added", () => {
+ expect(reflowCells(["a", "b"], "2x1", "2x2")).toEqual([
+ "a",
+ "b",
+ null,
+ null,
+ ]);
+ });
+
+ it("drops cells that fall outside a narrower grid", () => {
+ expect(reflowCells(["a", "b", "c", "d", "e", "f"], "3x2", "2x2")).toEqual([
+ "a",
+ "b",
+ "d",
+ "e",
+ ]);
+ });
+});
+
describe("resizeCells", () => {
it("returns same array when count matches", () => {
const cells = ["a", null, "b"];
diff --git a/products/desktop/packages/core/src/command-center/grid.ts b/products/desktop/packages/core/src/command-center/grid.ts
index a0aaa153e306..60d3b135a9fe 100644
--- a/products/desktop/packages/core/src/command-center/grid.ts
+++ b/products/desktop/packages/core/src/command-center/grid.ts
@@ -5,8 +5,15 @@ export type LayoutPreset =
| "1x2"
| "2x2"
| "3x2"
+ | "1x3"
+ | "2x3"
| "3x3";
+export type ExpandDirection = "horizontal" | "vertical";
+
+// Both axes cap at 3, so every preset is a cols/rows pair within that square.
+const MAX_SPAN = 3;
+
export interface GridDimensions {
cols: number;
rows: number;
@@ -81,6 +88,48 @@ export function getCellCount(preset: LayoutPreset): number {
return cols * rows;
}
+/** The preset one column wider or one row taller, or null at the 3x3 ceiling. */
+export function getExpandedLayout(
+ preset: LayoutPreset,
+ direction: ExpandDirection,
+): LayoutPreset | null {
+ const { cols, rows } = getGridDimensions(preset);
+ const grown =
+ direction === "horizontal"
+ ? { cols: cols + 1, rows }
+ : { cols, rows: rows + 1 };
+ if (grown.cols > MAX_SPAN || grown.rows > MAX_SPAN) return null;
+ return `${grown.cols}x${grown.rows}` as LayoutPreset;
+}
+
+/**
+ * The cell at `slot` of the column or row an expansion adds, in the expanded
+ * layout's indices — the rightmost cell of row `slot`, or the bottom cell of
+ * column `slot`. Picking an expand slot has to land in the space that just
+ * opened, not in some empty tile elsewhere in the grid.
+ */
+export function getExpansionCellIndex(
+ expanded: LayoutPreset,
+ direction: ExpandDirection,
+ slot: number,
+): number {
+ const { cols, rows } = getGridDimensions(expanded);
+ return direction === "horizontal"
+ ? slot * cols + (cols - 1)
+ : (rows - 1) * cols + slot;
+}
+
+/**
+ * The tightest layout that holds `count` tiles, kept as square as the presets
+ * allow and never taller than it is wide: 3 tiles fit 2x2 rather than 3x1, and
+ * 5 fit 3x2. Above 9 it saturates at the largest grid.
+ */
+export function getOptimalLayout(count: number): LayoutPreset {
+ const cols = Math.min(MAX_SPAN, Math.max(1, Math.ceil(Math.sqrt(count))));
+ const rows = Math.min(MAX_SPAN, Math.max(1, Math.ceil(count / cols)));
+ return `${cols}x${rows}` as LayoutPreset;
+}
+
export function resizeCells(
current: (string | null)[],
newCount: number,
@@ -90,6 +139,33 @@ export function resizeCells(
return [...current, ...Array(newCount - current.length).fill(null)];
}
+/**
+ * Cells for a new grid shape, keeping each one in the same row and column.
+ * Cells are stored row-major, so a column change moves every row's start —
+ * padding the tail instead would shuffle tiles between rows. Cells outside the
+ * new shape are dropped.
+ */
+export function reflowCells(
+ cells: readonly (string | null)[],
+ from: LayoutPreset,
+ to: LayoutPreset,
+): (string | null)[] {
+ const source = getGridDimensions(from);
+ const target = getGridDimensions(to);
+ if (source.cols === target.cols)
+ return resizeCells([...cells], getCellCount(to));
+
+ const next: (string | null)[] = Array(getCellCount(to)).fill(null);
+ const rows = Math.min(source.rows, target.rows);
+ const cols = Math.min(source.cols, target.cols);
+ for (let row = 0; row < rows; row++) {
+ for (let col = 0; col < cols; col++) {
+ next[row * target.cols + col] = cells[row * source.cols + col] ?? null;
+ }
+ }
+ return next;
+}
+
export function clampZoom(value: number): number {
return Math.round(Math.min(ZOOM_MAX, Math.max(ZOOM_MIN, value)) * 10) / 10;
}
diff --git a/products/desktop/packages/core/src/sessions/sessionEviction.test.ts b/products/desktop/packages/core/src/sessions/sessionEviction.test.ts
index b8f98de3c617..ddc636cc931b 100644
--- a/products/desktop/packages/core/src/sessions/sessionEviction.test.ts
+++ b/products/desktop/packages/core/src/sessions/sessionEviction.test.ts
@@ -132,6 +132,8 @@ describe("MAX_CONNECTED_SESSIONS", () => {
"1x2": true,
"2x2": true,
"3x2": true,
+ "1x3": true,
+ "2x3": true,
"3x3": true,
};
const largestGrid = Math.max(
diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelSidebar.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelSidebar.tsx
index a2e8bb520bac..5c59fd06d2dc 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelSidebar.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelSidebar.tsx
@@ -39,11 +39,10 @@ import { useChannelItems } from "@posthog/ui/features/canvas/hooks/useChannelIte
import { useChannels } from "@posthog/ui/features/canvas/hooks/useChannels";
import { PERSONAL_CHANNEL_NAME } from "@posthog/ui/features/canvas/hooks/useTaskChannels";
import { useCommandCenterStore } from "@posthog/ui/features/command-center/commandCenterStore";
+import { placeTaskInCommandCenter } from "@posthog/ui/features/command-center/placeTaskInCommandCenter";
import { useFeatureFlag } from "@posthog/ui/features/feature-flags/useFeatureFlag";
import { SidebarItem } from "@posthog/ui/features/sidebar/components/SidebarItem";
import { useRenameTask } from "@posthog/ui/features/tasks/useTaskMutations";
-import { useTasks } from "@posthog/ui/features/tasks/useTasks";
-import { navigateToCommandCenter } from "@posthog/ui/router/navigationBridge";
import { logger } from "@posthog/ui/shell/logger";
import { useNavigate, useRouterState } from "@tanstack/react-router";
import { useMemo, useState } from "react";
@@ -259,14 +258,6 @@ export function ChannelSidebar({ channelId }: { channelId: string }) {
const [editingTaskId, setEditingTaskId] = useState<string | null>(null);
const { renameTask } = useRenameTask();
const commandCenterCells = useCommandCenterStore((state) => state.cells);
- const assignTaskToCommandCenter = useCommandCenterStore(
- (state) => state.assignTask,
- );
- const { data: allTasks = [] } = useTasks({ showAllUsers: true });
- const allTaskIds = useMemo(
- () => new Set(allTasks.map((task) => task.id)),
- [allTasks],
- );
const [searchOpen, setSearchOpen] = useState(false);
const [query, setQuery] = useState("");
@@ -323,18 +314,8 @@ export function ChannelSidebar({ channelId }: { channelId: string }) {
// stays while the list is narrowed, so you can undo whatever emptied it.
const showRecent = listState === "ready";
- // The first free command-centre cell, or nothing if every cell is taken by a
- // task that still exists.
- const commandCenterAssigner = (taskId: string) => {
- const cellIndex = commandCenterCells.findIndex(
- (cellTaskId) => cellTaskId == null || !allTaskIds.has(cellTaskId),
- );
- if (cellIndex === -1) return undefined;
- return () => {
- assignTaskToCommandCenter(cellIndex, taskId);
- navigateToCommandCenter();
- };
- };
+ const commandCenterAssigner = (taskId: string, taskTitle: string) => () =>
+ placeTaskInCommandCenter(taskId, taskTitle);
const taskRow = (item: (typeof items)[number]) => (
<ChannelItemRow
@@ -352,7 +333,7 @@ export function ChannelSidebar({ channelId }: { channelId: string }) {
// greyed-out one.
onAddToCommandCenter={
item.kind === "task" && !commandCenterCells.includes(item.id)
- ? commandCenterAssigner(item.id)
+ ? commandCenterAssigner(item.id, item.title)
: undefined
}
onEditSubmit={
diff --git a/products/desktop/packages/ui/src/features/command-center/commandCenterStore.test.ts b/products/desktop/packages/ui/src/features/command-center/commandCenterStore.test.ts
index db159c30399e..8b28a62ba279 100644
--- a/products/desktop/packages/ui/src/features/command-center/commandCenterStore.test.ts
+++ b/products/desktop/packages/ui/src/features/command-center/commandCenterStore.test.ts
@@ -180,4 +180,24 @@ describe("commandCenterStore", () => {
expect(useCommandCenterStore.getState().hasAutofilled).toBe(true);
});
});
+
+ describe("pending placement", () => {
+ it("keeps the requested task available until placement is canceled", () => {
+ useCommandCenterStore.getState().requestPlacement("t1", "Fix signup");
+ expect(useCommandCenterStore.getState().pendingPlacement).toEqual({
+ taskId: "t1",
+ taskTitle: "Fix signup",
+ });
+
+ useCommandCenterStore.getState().cancelPlacement();
+ expect(useCommandCenterStore.getState().pendingPlacement).toBeNull();
+ });
+
+ it("clears the request when the task is assigned", () => {
+ useCommandCenterStore.getState().requestPlacement("t1", "Fix signup");
+ useCommandCenterStore.getState().assignTask(2, "t1");
+ expect(useCommandCenterStore.getState().pendingPlacement).toBeNull();
+ expect(useCommandCenterStore.getState().cells[2]).toBe("t1");
+ });
+ });
});
diff --git a/products/desktop/packages/ui/src/features/command-center/commandCenterStore.ts b/products/desktop/packages/ui/src/features/command-center/commandCenterStore.ts
index 14f32f66ab8d..137d66953023 100644
--- a/products/desktop/packages/ui/src/features/command-center/commandCenterStore.ts
+++ b/products/desktop/packages/ui/src/features/command-center/commandCenterStore.ts
@@ -2,8 +2,10 @@ import {
BRAINROT_CELL,
clampZoom,
getCellCount,
+ getOptimalLayout,
type LayoutPreset,
makeTerminalCellValue,
+ reflowCells,
resizeCells,
ZOOM_STEP,
} from "@posthog/core/command-center/grid";
@@ -26,6 +28,7 @@ interface CommandCenterStoreState {
creatingCells: number[];
// Persisted so autofill bootstraps the grid only once, not on every remount.
hasAutofilled: boolean;
+ pendingPlacement: { taskId: string; taskTitle: string } | null;
}
interface CommandCenterStoreActions {
@@ -40,6 +43,7 @@ interface CommandCenterStoreActions {
cwd?: string,
) => void;
autofillCells: (taskIds: string[]) => void;
+ optimizeLayout: (keepIndices: number[]) => void;
clearCell: (cellIndex: number) => void;
removeTaskById: (taskId: string) => void;
clearAll: () => void;
@@ -48,6 +52,8 @@ interface CommandCenterStoreActions {
zoomOut: () => void;
startCreating: (cellIndex: number) => void;
stopCreating: (cellIndex: number) => void;
+ requestPlacement: (taskId: string, taskTitle: string) => void;
+ cancelPlacement: () => void;
}
export const COMMAND_CENTER_INITIAL_STATE: CommandCenterStoreState = {
@@ -58,6 +64,7 @@ export const COMMAND_CENTER_INITIAL_STATE: CommandCenterStoreState = {
zoom: 1,
creatingCells: [],
hasAutofilled: false,
+ pendingPlacement: null,
};
type CommandCenterStore = CommandCenterStoreState & CommandCenterStoreActions;
@@ -70,18 +77,22 @@ export const useCommandCenterStore = create<CommandCenterStore>()(
setLayout: (preset) =>
set((state) => {
const newCount = getCellCount(preset);
+ const cells = reflowCells(state.cells, state.layout, preset);
+ const activeTaskId = cells.includes(state.activeTaskId)
+ ? state.activeTaskId
+ : null;
return {
- activeTaskId: resizeCells(state.cells, newCount).includes(
- state.activeTaskId,
- )
- ? state.activeTaskId
- : null,
- activeCellIndex:
- state.activeCellIndex !== null && state.activeCellIndex < newCount
+ activeTaskId,
+ // A column change moves cells between indices, so the highlight
+ // follows the active task rather than its old index.
+ activeCellIndex: activeTaskId
+ ? cells.indexOf(activeTaskId)
+ : state.activeCellIndex !== null &&
+ state.activeCellIndex < newCount
? state.activeCellIndex
: null,
layout: preset,
- cells: resizeCells(state.cells, newCount),
+ cells,
creatingCells: state.creatingCells.filter((i) => i < newCount),
};
}),
@@ -102,9 +113,13 @@ export const useCommandCenterStore = create<CommandCenterStore>()(
return {
cells,
activeTaskId: taskId,
+ // Highlight where it landed — otherwise a task dropped into an
+ // empty tile of a busy grid is easy to miss.
+ activeCellIndex: cellIndex,
creatingCells: state.creatingCells.filter((i) => i !== cellIndex),
// Manually placing a task counts as curating the grid.
hasAutofilled: true,
+ pendingPlacement: null,
};
}),
@@ -153,6 +168,28 @@ export const useCommandCenterStore = create<CommandCenterStore>()(
return { cells, hasAutofilled: true };
}),
+ // Packs the tiles worth keeping into the smallest grid that holds them.
+ // Resizing alone would drop whatever sat past the new bounds, so the kept
+ // cells move to the front first — the caller decides what's worth keeping.
+ optimizeLayout: (keepIndices) =>
+ set((state) => {
+ const kept = keepIndices
+ .map((index) => state.cells[index])
+ .filter((cell): cell is string => cell != null);
+ const layout = getOptimalLayout(kept.length);
+ const cells = resizeCells(kept, getCellCount(layout));
+ const activeTaskId = cells.includes(state.activeTaskId)
+ ? state.activeTaskId
+ : null;
+ return {
+ layout,
+ cells,
+ activeTaskId,
+ activeCellIndex: activeTaskId ? cells.indexOf(activeTaskId) : null,
+ creatingCells: [],
+ };
+ }),
+
clearCell: (cellIndex) =>
set((state) => {
const cells = [...state.cells];
@@ -205,6 +242,10 @@ export const useCommandCenterStore = create<CommandCenterStore>()(
set((state) => ({
creatingCells: state.creatingCells.filter((i) => i !== cellIndex),
})),
+
+ requestPlacement: (taskId, taskTitle) =>
+ set({ pendingPlacement: { taskId, taskTitle } }),
+ cancelPlacement: () => set({ pendingPlacement: null }),
}),
{
name: "command-center-storage",
diff --git a/products/desktop/packages/ui/src/features/command-center/components/CommandCenterGrid.tsx b/products/desktop/packages/ui/src/features/command-center/components/CommandCenterGrid.tsx
index 32254d828e58..22e099186b61 100644
--- a/products/desktop/packages/ui/src/features/command-center/components/CommandCenterGrid.tsx
+++ b/products/desktop/packages/ui/src/features/command-center/components/CommandCenterGrid.tsx
@@ -1,3 +1,10 @@
+import { Plus } from "@phosphor-icons/react";
+import {
+ type ExpandDirection,
+ getExpandedLayout,
+ getExpansionCellIndex,
+} from "@posthog/core/command-center/grid";
+import { Button } from "@posthog/quill";
import { destroyShellTerminal } from "@posthog/ui/features/terminal/destroyShellTerminal";
import { useCallback, useEffect, useRef, useState } from "react";
import { FOCUSABLE_SELECTOR } from "../../../utils/overlay";
@@ -7,9 +14,22 @@ import {
useCommandCenterStore,
} from "../commandCenterStore";
import type { CommandCenterCellData } from "../hooks/useCommandCenterData";
+import { expandCommandCenterInto } from "../placeTaskInCommandCenter";
import { getTerminalCellStateKey } from "../terminalCells";
import { CommandCenterPanel } from "./CommandCenterPanel";
+const TASK_DRAG_TYPE = "text/x-task-id";
+
+/**
+ * Picking a tile by clicking and by dropping are the same interaction, so they
+ * render the same targets: every tile plus the expand zones. Only how the task
+ * arrives differs — a click carries the task the picker was opened with, a drop
+ * carries whatever was dragged.
+ */
+type PlacementState =
+ | { mode: "pick"; taskId: string; taskTitle: string }
+ | { mode: "drag" };
+
interface CommandCenterGridProps {
layout: LayoutPreset;
cells: CommandCenterCellData[];
@@ -20,7 +40,7 @@ function useTaskDragActive() {
useEffect(() => {
const onDragStart = (e: DragEvent) => {
- if (e.dataTransfer?.types.includes("text/x-task-id")) {
+ if (e.dataTransfer?.types.includes(TASK_DRAG_TYPE)) {
setActive(true);
}
};
@@ -45,19 +65,73 @@ function useTaskDragActive() {
return active;
}
+function useTaskDropTarget(onTask: (taskId: string) => void) {
+ const [isOver, setIsOver] = useState(false);
+
+ return {
+ isOver,
+ onDragOver: (e: React.DragEvent) => {
+ if (!e.dataTransfer.types.includes(TASK_DRAG_TYPE)) return;
+ e.preventDefault();
+ e.dataTransfer.dropEffect = "copy";
+ setIsOver(true);
+ },
+ onDragLeave: () => setIsOver(false),
+ onDrop: (e: React.DragEvent) => {
+ e.preventDefault();
+ setIsOver(false);
+ const taskId = e.dataTransfer.getData(TASK_DRAG_TYPE);
+ if (taskId) onTask(taskId);
+ },
+ };
+}
+
+const TARGET_CLASSES =
+ "group flex cursor-pointer items-center justify-center transition-colors focus-visible:outline-none";
+
+// Targets are outlined, never dimmed: a scrim over every tile buries the grid
+// you're picking from, and its label had to fight the tile behind it.
+function targetOutline(isOver: boolean): string {
+ return isOver
+ ? "ring-2 ring-accent-9 ring-inset"
+ : "ring-1 ring-gray-7 ring-inset hover:ring-2 hover:ring-accent-9 focus-visible:ring-2 focus-visible:ring-accent-9";
+}
+
+/** Shown only on the target under the cursor, so the grid stays legible. */
+function hoverTextTone(isOver: boolean): string {
+ return isOver
+ ? "opacity-100"
+ : "opacity-0 group-hover:opacity-100 group-focus-visible:opacity-100";
+}
+
+function TargetLabel({
+ isOver,
+ children,
+}: {
+ isOver: boolean;
+ children: React.ReactNode;
+}) {
+ return (
+ <span
+ className={`flex items-center gap-1.5 rounded-md bg-accent-9 px-2 py-1 text-center font-medium text-[11px] text-white shadow-sm transition-opacity ${hoverTextTone(isOver)}`}
+ >
+ {children}
+ </span>
+ );
+}
+
function GridCell({
cell,
zoom,
- isDragActive,
isActive,
+ placement,
}: {
cell: CommandCenterCellData;
zoom: number;
- isDragActive: boolean;
isActive: boolean;
+ placement: PlacementState | null;
}) {
const cellRef = useRef<HTMLDivElement>(null);
- const [isDragOver, setIsDragOver] = useState(false);
const setActiveTask = useCommandCenterStore((s) => s.setActiveTask);
const setActiveCell = useCommandCenterStore((s) => s.setActiveCell);
@@ -89,33 +163,28 @@ function GridCell({
[markActive],
);
- const handleDragOver = useCallback((e: React.DragEvent) => {
- if (e.dataTransfer.types.includes("text/x-task-id")) {
- e.preventDefault();
- e.dataTransfer.dropEffect = "copy";
- setIsDragOver(true);
- }
- }, []);
-
- const handleDragLeave = useCallback(() => {
- setIsDragOver(false);
- }, []);
-
- const handleDrop = useCallback(
- (e: React.DragEvent) => {
- e.preventDefault();
- setIsDragOver(false);
- const taskId = e.dataTransfer.getData("text/x-task-id");
- if (taskId) {
- if (cell.terminalId) {
- destroyShellTerminal(getTerminalCellStateKey(cell.terminalId));
- }
- useCommandCenterStore.getState().assignTask(cell.cellIndex, taskId);
+ const placeInCell = useCallback(
+ (taskId: string) => {
+ if (cell.terminalId) {
+ destroyShellTerminal(getTerminalCellStateKey(cell.terminalId));
}
+ useCommandCenterStore.getState().assignTask(cell.cellIndex, taskId);
},
[cell.cellIndex, cell.terminalId],
);
+ const dropTarget = useTaskDropTarget(placeInCell);
+
+ const isEmpty = !cell.task && !cell.terminalId && !cell.isBrainrot;
+
+ const targetLabel = cell.terminalId
+ ? "Replace terminal"
+ : cell.isBrainrot
+ ? "Replace Brainrot"
+ : cell.task?.title
+ ? `Replace ${cell.task.title}`
+ : "Use this tile";
+
return (
// biome-ignore lint/a11y/useKeyWithClickEvents lint/a11y/noStaticElementInteractions: click delegates focus to ActionSelector within
<div
@@ -127,7 +196,9 @@ function GridCell({
onFocusCapture={markActive}
>
<div
- className="h-full w-full origin-top-left"
+ // An empty tile's "Add task" prompt would sit right under the target
+ // label, so it steps aside while a placement is in flight.
+ className={`h-full w-full origin-top-left ${placement && isEmpty ? "invisible" : ""}`}
style={{
zoom: zoom !== 1 ? zoom : undefined,
}}
@@ -137,46 +208,191 @@ function GridCell({
{isActive && (
<div className="pointer-events-none absolute inset-0 border-2 border-accent-9" />
)}
- {isDragActive && (
- // biome-ignore lint/a11y/noStaticElementInteractions: transparent overlay to capture drag events over session content
- <div
- className="absolute inset-0"
- style={{
- outline: isDragOver ? "2px solid var(--accent-9)" : undefined,
- outlineOffset: "-2px",
- }}
- onDragOver={handleDragOver}
- onDragLeave={handleDragLeave}
- onDrop={handleDrop}
- />
+ {placement && (
+ <button
+ type="button"
+ className={`absolute inset-0 z-10 p-4 ${TARGET_CLASSES} ${targetOutline(dropTarget.isOver)}`}
+ onClick={
+ placement.mode === "pick"
+ ? () => placeInCell(placement.taskId)
+ : undefined
+ }
+ onDragOver={dropTarget.onDragOver}
+ onDragLeave={dropTarget.onDragLeave}
+ onDrop={dropTarget.onDrop}
+ aria-label={
+ placement.mode === "pick"
+ ? `${targetLabel} with ${placement.taskTitle}`
+ : targetLabel
+ }
+ >
+ <TargetLabel isOver={dropTarget.isOver}>{targetLabel}</TargetLabel>
+ </button>
)}
</div>
);
}
-export function CommandCenterGrid({ layout, cells }: CommandCenterGridProps) {
+function ExpandSlot({
+ direction,
+ expanded,
+ slot,
+ placement,
+}: {
+ direction: ExpandDirection;
+ expanded: LayoutPreset;
+ slot: number;
+ placement: PlacementState;
+}) {
+ const expand = useCallback(
+ (taskId: string) => expandCommandCenterInto(direction, slot, taskId),
+ [direction, slot],
+ );
+ const dropTarget = useTaskDropTarget(expand);
+ const { cols, rows } = getGridDimensions(expanded);
+
+ return (
+ <button
+ type="button"
+ className={`flex-1 p-1 text-accent-11 ${TARGET_CLASSES} ${targetOutline(dropTarget.isOver)}`}
+ onClick={
+ placement.mode === "pick" ? () => expand(placement.taskId) : undefined
+ }
+ onDragOver={dropTarget.onDragOver}
+ onDragLeave={dropTarget.onDragLeave}
+ onDrop={dropTarget.onDrop}
+ aria-label={
+ direction === "horizontal"
+ ? `Expand into a new column, row ${slot + 1} of ${rows}`
+ : `Expand into a new row, column ${slot + 1} of ${cols}`
+ }
+ >
+ <span className="flex flex-col items-center gap-1">
+ <Plus size={14} weight="bold" />
+ <span
+ className={`text-[10px] leading-tight transition-opacity ${hoverTextTone(dropTarget.isOver)}`}
+ >
+ Expand into this tile
+ </span>
+ </span>
+ </button>
+ );
+}
+
+/**
+ * The column or row an expansion would add, drawn as one target per tile so the
+ * pick says which new tile the task goes in.
+ */
+function ExpandStrip({
+ direction,
+ layout,
+ placement,
+}: {
+ direction: ExpandDirection;
+ layout: LayoutPreset;
+ placement: PlacementState;
+}) {
+ const expanded = getExpandedLayout(layout, direction);
+ if (!expanded) return null;
+
const { cols, rows } = getGridDimensions(layout);
- const zoom = useCommandCenterStore((s) => s.zoom);
- const activeCellIndex = useCommandCenterStore((s) => s.activeCellIndex);
- const isDragActive = useTaskDragActive();
+ const isHorizontal = direction === "horizontal";
+ // One target per new tile, keyed by the cell each would fill.
+ const slotCells = Array.from({ length: isHorizontal ? rows : cols }, (_, i) =>
+ getExpansionCellIndex(expanded, direction, i),
+ );
return (
<div
- className="grid h-full gap-[1px] bg-gray-6"
- style={{
- gridTemplateColumns: `repeat(${cols}, 1fr)`,
- gridTemplateRows: `repeat(${rows}, 1fr)`,
- }}
+ className={`flex shrink-0 gap-px bg-gray-2 ${
+ isHorizontal ? "w-14 flex-col" : "h-14"
+ }`}
>
- {cells.map((cell) => (
- <GridCell
- key={cell.cellIndex}
- cell={cell}
- zoom={zoom}
- isDragActive={isDragActive}
- isActive={activeCellIndex === cell.cellIndex}
+ {slotCells.map((cellIndex, slot) => (
+ <ExpandSlot
+ key={cellIndex}
+ direction={direction}
+ expanded={expanded}
+ slot={slot}
+ placement={placement}
/>
))}
</div>
);
}
+
+export function CommandCenterGrid({ layout, cells }: CommandCenterGridProps) {
+ const { cols, rows } = getGridDimensions(layout);
+ const zoom = useCommandCenterStore((s) => s.zoom);
+ const activeCellIndex = useCommandCenterStore((s) => s.activeCellIndex);
+ const isDragActive = useTaskDragActive();
+ const pendingPlacement = useCommandCenterStore((s) => s.pendingPlacement);
+ const cancelPlacement = useCommandCenterStore((s) => s.cancelPlacement);
+
+ const placement: PlacementState | null = pendingPlacement
+ ? { mode: "pick", ...pendingPlacement }
+ : isDragActive
+ ? { mode: "drag" }
+ : null;
+
+ useEffect(() => {
+ if (!pendingPlacement) return;
+ const handleKeyDown = (event: KeyboardEvent) => {
+ if (event.key === "Escape") cancelPlacement();
+ };
+ document.addEventListener("keydown", handleKeyDown);
+ return () => document.removeEventListener("keydown", handleKeyDown);
+ }, [cancelPlacement, pendingPlacement]);
+
+ return (
+ <div className="relative flex h-full flex-col">
+ {pendingPlacement && (
+ // Accent-tinted so the bar reads as a mode you're in, not a panel
+ // floating over the grid.
+ <div className="-translate-x-1/2 absolute top-3 left-1/2 z-20 flex items-center gap-3 rounded-full border border-accent-7 bg-accent-3 px-3 py-1.5 shadow-md">
+ <span className="whitespace-nowrap text-[12px] text-accent-12">
+ Choose a tile for {pendingPlacement.taskTitle}
+ </span>
+ <Button variant="link-muted" size="xs" onClick={cancelPlacement}>
+ Cancel
+ </Button>
+ </div>
+ )}
+ <div className="flex min-h-0 flex-1">
+ <div className="flex min-w-0 flex-1 flex-col">
+ <div
+ className="grid min-h-0 flex-1 gap-[1px] bg-gray-6"
+ style={{
+ gridTemplateColumns: `repeat(${cols}, 1fr)`,
+ gridTemplateRows: `repeat(${rows}, 1fr)`,
+ }}
+ >
+ {cells.map((cell) => (
+ <GridCell
+ key={cell.cellIndex}
+ cell={cell}
+ zoom={zoom}
+ isActive={activeCellIndex === cell.cellIndex}
+ placement={placement}
+ />
+ ))}
+ </div>
+ {placement && (
+ <ExpandStrip
+ direction="vertical"
+ layout={layout}
+ placement={placement}
+ />
+ )}
+ </div>
+ {placement && (
+ <ExpandStrip
+ direction="horizontal"
+ layout={layout}
+ placement={placement}
+ />
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/products/desktop/packages/ui/src/features/command-center/components/CommandCenterToolbar.tsx b/products/desktop/packages/ui/src/features/command-center/components/CommandCenterToolbar.tsx
index aeceeb231325..9e8792108a69 100644
--- a/products/desktop/packages/ui/src/features/command-center/components/CommandCenterToolbar.tsx
+++ b/products/desktop/packages/ui/src/features/command-center/components/CommandCenterToolbar.tsx
@@ -3,7 +3,7 @@ import {
MagnifyingGlassPlus,
Trash,
} from "@phosphor-icons/react";
-import { getCellCount } from "@posthog/core/command-center/grid";
+import { reflowCells } from "@posthog/core/command-center/grid";
import { Flex, Select, Text } from "@radix-ui/themes";
import { useCallback } from "react";
import {
@@ -62,11 +62,15 @@ const LAYOUT_OPTIONS: {
{ value: "1x2", label: "1x2", cols: 1, rows: 2 },
{ value: "2x2", label: "2x2", cols: 2, rows: 2 },
{ value: "3x2", label: "3x2", cols: 3, rows: 2 },
+ { value: "1x3", label: "1x3", cols: 1, rows: 3 },
+ { value: "2x3", label: "2x3", cols: 2, rows: 3 },
{ value: "3x3", label: "3x3", cols: 3, rows: 3 },
];
interface CommandCenterToolbarProps {
summary: StatusSummary;
+ /** Cells holding something worth keeping, so Optimize can pack them. */
+ occupiedCellIndices: number[];
}
function StatusSummaryText({ summary }: { summary: StatusSummary }) {
@@ -83,20 +87,34 @@ function StatusSummaryText({ summary }: { summary: StatusSummary }) {
);
}
-export function CommandCenterToolbar({ summary }: CommandCenterToolbarProps) {
+export function CommandCenterToolbar({
+ summary,
+ occupiedCellIndices,
+}: CommandCenterToolbarProps) {
const layout = useCommandCenterStore((s) => s.layout);
const setLayout = useCommandCenterStore((s) => s.setLayout);
const clearAll = useCommandCenterStore((s) => s.clearAll);
+ const optimizeLayout = useCommandCenterStore((s) => s.optimizeLayout);
const handleSetLayout = useCallback(
(preset: LayoutPreset) => {
- const cells = useCommandCenterStore.getState().cells;
- destroyTerminalCells(cells.slice(getCellCount(preset)));
+ const { cells, layout: current } = useCommandCenterStore.getState();
+ // Cells keep their row and column across a resize, so what falls off is
+ // whatever the reflow didn't keep — not simply the tail.
+ const kept = reflowCells(cells, current, preset);
+ destroyTerminalCells(cells.filter((cell) => !kept.includes(cell)));
setLayout(preset);
},
[setLayout],
);
+ const handleOptimize = useCallback(() => {
+ const cells = useCommandCenterStore.getState().cells;
+ const keep = new Set(occupiedCellIndices);
+ destroyTerminalCells(cells.filter((_, index) => !keep.has(index)));
+ optimizeLayout(occupiedCellIndices);
+ }, [occupiedCellIndices, optimizeLayout]);
+
const handleClearAll = useCallback(() => {
destroyTerminalCells(useCommandCenterStore.getState().cells);
clearAll();
@@ -131,6 +149,15 @@ export function CommandCenterToolbar({ summary }: CommandCenterToolbarProps) {
</Select.Content>
</Select.Root>
+ <button
+ type="button"
+ onClick={handleOptimize}
+ className="rounded px-1.5 py-0.5 text-[12px] text-gray-10 transition-colors hover:bg-gray-4 hover:text-gray-12"
+ title="Resize the grid to fit the tiles in use"
+ >
+ Optimize
+ </button>
+
<StatusSummaryText summary={summary} />
<Flex align="center" gap="1">
diff --git a/products/desktop/packages/ui/src/features/command-center/components/CommandCenterView.tsx b/products/desktop/packages/ui/src/features/command-center/components/CommandCenterView.tsx
index 5dfdef0b6f52..a3e84763686a 100644
--- a/products/desktop/packages/ui/src/features/command-center/components/CommandCenterView.tsx
+++ b/products/desktop/packages/ui/src/features/command-center/components/CommandCenterView.tsx
@@ -1,5 +1,5 @@
import { Box, Flex } from "@radix-ui/themes";
-import { useEffect } from "react";
+import { useEffect, useMemo } from "react";
import { useSetHeaderContent } from "../../../hooks/useSetHeaderContent";
import { useTaskViewed } from "../../sidebar/useTaskViewed";
import { useCommandCenterStore } from "../commandCenterStore";
@@ -15,6 +15,16 @@ export function CommandCenterView() {
useAutofillCommandCenter();
+ // A cell whose task has been deleted holds a dead id, so occupancy is judged
+ // on what actually renders — Optimize then packs the grid and drops the rest.
+ const occupiedCellIndices = useMemo(
+ () =>
+ cells
+ .filter((cell) => cell.task || cell.terminalId || cell.isBrainrot)
+ .map((cell) => cell.cellIndex),
+ [cells],
+ );
+
const visibleTaskIdsKey = cells
.map((c) => c.taskId)
.filter(Boolean)
@@ -35,7 +45,10 @@ export function CommandCenterView() {
return (
<Flex direction="column" height="100%">
- <CommandCenterToolbar summary={summary} />
+ <CommandCenterToolbar
+ summary={summary}
+ occupiedCellIndices={occupiedCellIndices}
+ />
<Box className="min-h-0 flex-1">
<CommandCenterGrid layout={layout} cells={cells} />
</Box>
diff --git a/products/desktop/packages/ui/src/features/command-center/placeTaskInCommandCenter.ts b/products/desktop/packages/ui/src/features/command-center/placeTaskInCommandCenter.ts
new file mode 100644
index 000000000000..b5dac10483c4
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/command-center/placeTaskInCommandCenter.ts
@@ -0,0 +1,36 @@
+import {
+ type ExpandDirection,
+ getExpandedLayout,
+ getExpansionCellIndex,
+} from "@posthog/core/command-center/grid";
+import { navigateToCommandCenter } from "@posthog/ui/router/navigationBridge";
+import { useCommandCenterStore } from "./commandCenterStore";
+
+/**
+ * Opens the command center with the tile picker up. Adding always asks, even
+ * with tiles free: guessing a tile means the task lands somewhere the user
+ * wasn't looking, and picking is one click either way.
+ */
+export function placeTaskInCommandCenter(
+ taskId: string,
+ taskTitle: string,
+): void {
+ useCommandCenterStore.getState().requestPlacement(taskId, taskTitle);
+ navigateToCommandCenter();
+}
+
+/** Grows the grid by one column or row and puts the task in the slot picked. */
+export function expandCommandCenterInto(
+ direction: ExpandDirection,
+ slot: number,
+ taskId: string,
+): void {
+ const state = useCommandCenterStore.getState();
+ const expanded = getExpandedLayout(state.layout, direction);
+ if (!expanded) return;
+
+ state.setLayout(expanded);
+ useCommandCenterStore
+ .getState()
+ .assignTask(getExpansionCellIndex(expanded, direction, slot), taskId);
+}
diff --git a/products/desktop/packages/ui/src/features/sidebar/components/SidebarMenu.tsx b/products/desktop/packages/ui/src/features/sidebar/components/SidebarMenu.tsx
index d915f3ccda9f..2186bcb80b95 100644
--- a/products/desktop/packages/ui/src/features/sidebar/components/SidebarMenu.tsx
+++ b/products/desktop/packages/ui/src/features/sidebar/components/SidebarMenu.tsx
@@ -8,6 +8,7 @@ import {
useArchiveTask,
} from "@posthog/ui/features/archive/useArchiveTask";
import { useCommandCenterStore } from "@posthog/ui/features/command-center/commandCenterStore";
+import { placeTaskInCommandCenter } from "@posthog/ui/features/command-center/placeTaskInCommandCenter";
import { useExternalAppAction } from "@posthog/ui/features/external-apps/useExternalAppAction";
import { useFolders } from "@posthog/ui/features/folders/useFolders";
import { StopCloudRunDialog } from "@posthog/ui/features/sessions/components/StopCloudRunDialog";
@@ -23,10 +24,7 @@ import { useTasks } from "@posthog/ui/features/tasks/useTasks";
import { useWorkspaces } from "@posthog/ui/features/workspace/useWorkspace";
import { DotsCircleSpinner } from "@posthog/ui/primitives/DotsCircleSpinner";
import { toast } from "@posthog/ui/primitives/toast";
-import {
- navigateToCommandCenter,
- navigateToTaskDetail,
-} from "@posthog/ui/router/navigationBridge";
+import { navigateToTaskDetail } from "@posthog/ui/router/navigationBridge";
import { useAppView } from "@posthog/ui/router/useAppView";
import { openTask } from "@posthog/ui/router/useOpenTask";
import { logger } from "@posthog/ui/shell/logger";
@@ -80,7 +78,6 @@ function SidebarMenuComponent() {
);
const commandCenterCells = useCommandCenterStore((s) => s.cells);
- const assignTaskToCommandCenter = useCommandCenterStore((s) => s.assignTask);
const previousTaskIdRef = useRef<string | null>(null);
@@ -308,9 +305,6 @@ function SidebarMenuComponent() {
const isInCommandCenter = commandCenterCells.some(
(id) => id === taskId && taskMap.has(id),
);
- const hasEmptyCommandCenterCell = commandCenterCells.some(
- (id) => id == null || !taskMap.has(id),
- );
showContextMenu(task, e, {
worktreePath: workspace?.worktreePath ?? undefined,
@@ -322,7 +316,7 @@ function SidebarMenuComponent() {
isTaskActivelyRunning(taskData),
runId,
isInCommandCenter,
- hasEmptyCommandCenterCell,
+ hasEmptyCommandCenterCell: true,
onTogglePin: () => handleTaskTogglePin(taskId),
onStop: (stopTaskId, taskTitle, stopRunId) =>
setStopConfirm({
@@ -333,14 +327,7 @@ function SidebarMenuComponent() {
onArchive: handleTaskArchive,
onArchivePrior: handleArchivePrior,
onAddToCommandCenter: () => {
- const cells = useCommandCenterStore.getState().cells;
- const idx = cells.findIndex((id) => id == null || !taskMap.has(id));
- if (idx !== -1) {
- assignTaskToCommandCenter(idx, taskId);
- navigateToCommandCenter();
- } else {
- toast.info("Command center is full");
- }
+ placeTaskInCommandCenter(taskId, task.title);
},
});
}