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): compose new command center tasks in their tile (#91589)

Andrew Maguire065e6da28043
diff --git a/products/desktop/packages/core/src/command-center/grid.ts b/products/desktop/packages/core/src/command-center/grid.ts
index d256804e7aa4..8ffbeb526f92 100644
--- a/products/desktop/packages/core/src/command-center/grid.ts
+++ b/products/desktop/packages/core/src/command-center/grid.ts
@@ -241,3 +241,10 @@ export function resizeCellsForLayout(
export function clampZoom(value: number): number {
return Math.round(Math.min(ZOOM_MAX, Math.max(ZOOM_MIN, value)) * 10) / 10;
}
+
+// Composer draft key for a tile creating its own task. Deliberately outside the
+// "task-input" namespace: those ids drive the sidebar's unsent-draft dot, which
+// must not light up for a draft that lives in the grid.
+export function getCellSessionId(authScope: string, cellIndex: number): string {
+ return `cc-cell-${authScope}-${cellIndex}`;
+}
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 6a9e6b02376e..3c1727e845ea 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
@@ -22,6 +22,8 @@ function resetStore() {
useCommandCenterStore.setState(COMMAND_CENTER_INITIAL_STATE);
}
+const store = () => useCommandCenterStore.getState();
+
describe("commandCenterStore", () => {
beforeEach(resetStore);
@@ -282,4 +284,111 @@ describe("commandCenterStore", () => {
expect(useCommandCenterStore.getState().cells[2]).toBe("t1");
});
});
+
+ describe("in-tile composer", () => {
+ it("keeps the first active composer and marks the grid curated", () => {
+ store().startCreating(2, "session-2");
+ store().startCreating(1, "session-1");
+
+ expect(store().composer).toEqual({
+ cellIndex: 2,
+ sessionId: "session-2",
+ });
+ expect(store().activeCellIndex).toBe(2);
+ expect(store().hasAutofilled).toBe(true);
+
+ store().stopCreating("session-2");
+ expect(store().composer).toBeNull();
+ });
+
+ it("reserves the composing tile from late autofill", () => {
+ store().startCreating(1, "session-1");
+
+ store().autofillCells(["t1", "t2", "t3"]);
+
+ expect(store().cells).toEqual(["t1", null, "t2", "t3"]);
+ expect(store().composer).toEqual({
+ cellIndex: 1,
+ sessionId: "session-1",
+ });
+ });
+
+ it.each([
+ { what: "a task", fill: () => store().assignTask(1, "t1") },
+ { what: "a terminal", fill: () => store().setTerminalCell(1, "term-1") },
+ { what: "brainrot", fill: () => store().setBrainrotCell(1) },
+ { what: "a canvas", fill: () => store().setCanvasCell(1, "canvas-1") },
+ ])("does not replace the composer with $what", ({ fill }) => {
+ store().startCreating(1, "session-1");
+
+ fill();
+
+ expect(store().cells[1]).toBeNull();
+ expect(store().composer).toEqual({
+ cellIndex: 1,
+ sessionId: "session-1",
+ });
+ });
+
+ it("keeps the layout stable while composing", () => {
+ useCommandCenterStore.setState({
+ layout: "2x2",
+ cells: [null, "t1", null, null],
+ });
+ store().startCreating(0, "session-0");
+
+ store().setLayout("3x2", [null, "t1", null, null, null, null]);
+ store().optimizeLayout([1]);
+
+ expect(store().layout).toBe("2x2");
+ expect(store().cells).toEqual([null, "t1", null, null]);
+ expect(store().composer).toEqual({
+ cellIndex: 0,
+ sessionId: "session-0",
+ });
+ });
+
+ it("assigns a created task only to its reserved composer", () => {
+ store().startCreating(2, "session-2");
+
+ expect(store().finishCreating("stale-session", "t1")).toBe(false);
+ expect(store().finishCreating("session-2", "t1")).toBe(true);
+ expect(store().cells[2]).toBe("t1");
+ expect(store().composer).toBeNull();
+ });
+
+ it("does not overwrite a tile replaced while creation was pending", () => {
+ store().startCreating(2, "session-2");
+ store().assignTask(2, "replacement");
+
+ expect(store().cells[2]).toBeNull();
+ expect(store().finishCreating("session-2", "created")).toBe(true);
+ expect(store().cells[2]).toBe("created");
+ });
+
+ it("rejects bulk placement while a tile is composing", () => {
+ store().startCreating(1, "session-1");
+
+ store().applyPlacement({
+ layout: "2x2",
+ cells: ["t1", "t2", null, null],
+ });
+
+ expect(store().cells).toEqual([null, null, null, null]);
+ expect(store().composer).toEqual({
+ cellIndex: 1,
+ sessionId: "session-1",
+ });
+ });
+
+ it("does not clear the grid while a tile is composing", () => {
+ useCommandCenterStore.setState({ cells: ["t1", null, null, null] });
+ store().startCreating(1, "session-1");
+
+ store().clearAll();
+
+ expect(store().cells).toEqual(["t1", null, null, null]);
+ expect(store().composer?.sessionId).toBe("session-1");
+ });
+ });
});
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 35171c0dc3ab..78b2d07f5a74 100644
--- a/products/desktop/packages/ui/src/features/command-center/commandCenterStore.ts
+++ b/products/desktop/packages/ui/src/features/command-center/commandCenterStore.ts
@@ -14,7 +14,10 @@ import { create } from "zustand";
import { persist } from "zustand/middleware";
export type { LayoutPreset } from "@posthog/core/command-center/grid";
-export { getGridDimensions } from "@posthog/core/command-center/grid";
+export {
+ getCellSessionId,
+ getGridDimensions,
+} from "@posthog/core/command-center/grid";
export type CommandCenterPlacement = {
kind: "task" | "canvas";
@@ -28,6 +31,8 @@ interface CommandCenterStoreState {
activeTaskId: string | null;
activeCellIndex: number | null;
zoom: number;
+ // The one tile composing a new task in place.
+ composer: { cellIndex: number; sessionId: string } | null;
// Persisted so autofill bootstraps the grid only once, not on every remount.
hasAutofilled: boolean;
pendingPlacement: CommandCenterPlacement | null;
@@ -58,6 +63,9 @@ interface CommandCenterStoreActions {
setZoom: (zoom: number) => void;
zoomIn: () => void;
zoomOut: () => void;
+ startCreating: (cellIndex: number, sessionId: string) => void;
+ stopCreating: (sessionId: string) => void;
+ finishCreating: (sessionId: string, taskId: string) => boolean;
requestPlacement: (placement: CommandCenterPlacement) => void;
cancelPlacement: () => void;
}
@@ -68,6 +76,7 @@ export const COMMAND_CENTER_INITIAL_STATE: CommandCenterStoreState = {
activeTaskId: null,
activeCellIndex: null,
zoom: 1,
+ composer: null,
hasAutofilled: false,
pendingPlacement: null,
};
@@ -81,6 +90,9 @@ export const useCommandCenterStore = create<CommandCenterStore>()(
setLayout: (preset, cells) =>
set((state) => {
+ // Keep the composing tile and its draft anchored until the user
+ // submits or cancels it.
+ if (state.composer) return state;
const newCount = getCellCount(preset);
const activeTaskId = cells.includes(state.activeTaskId)
? state.activeTaskId
@@ -107,6 +119,7 @@ export const useCommandCenterStore = create<CommandCenterStore>()(
assignTask: (cellIndex, taskId) =>
set((state) => {
if (cellIndex < 0 || cellIndex >= state.cells.length) return state;
+ if (state.composer?.cellIndex === cellIndex) return state;
const cells = [...state.cells];
const existingIndex = cells.indexOf(taskId);
if (existingIndex !== -1) {
@@ -128,6 +141,7 @@ export const useCommandCenterStore = create<CommandCenterStore>()(
setCanvasCell: (cellIndex, canvasId) =>
set((state) => {
if (cellIndex < 0 || cellIndex >= state.cells.length) return state;
+ if (state.composer?.cellIndex === cellIndex) return state;
const cellValue = makeCanvasCellValue(canvasId);
const cells = [...state.cells];
const existingIndex = cells.indexOf(cellValue);
@@ -147,6 +161,7 @@ export const useCommandCenterStore = create<CommandCenterStore>()(
setBrainrotCell: (cellIndex) =>
set((state) => {
if (cellIndex < 0 || cellIndex >= state.cells.length) return state;
+ if (state.composer?.cellIndex === cellIndex) return state;
const cells = [...state.cells];
cells[cellIndex] = BRAINROT_CELL;
return {
@@ -160,6 +175,7 @@ export const useCommandCenterStore = create<CommandCenterStore>()(
setTerminalCell: (cellIndex, terminalId, cwd) =>
set((state) => {
if (cellIndex < 0 || cellIndex >= state.cells.length) return state;
+ if (state.composer?.cellIndex === cellIndex) return state;
const cells = [...state.cells];
cells[cellIndex] = makeTerminalCellValue(terminalId, cwd);
return {
@@ -172,6 +188,7 @@ export const useCommandCenterStore = create<CommandCenterStore>()(
applyPlacement: ({ layout, cells }) =>
set((state) => {
+ if (state.composer) return state;
const activeTaskId =
state.activeTaskId && cells.includes(state.activeTaskId)
? state.activeTaskId
@@ -206,7 +223,7 @@ export const useCommandCenterStore = create<CommandCenterStore>()(
const cells: (string | null)[] = [...state.cells];
const queue = [...taskIds];
for (let i = 0; i < cells.length && queue.length > 0; i++) {
- if (cells[i] == null) {
+ if (cells[i] == null && state.composer?.cellIndex !== i) {
cells[i] = queue.shift() as string;
}
}
@@ -218,6 +235,7 @@ export const useCommandCenterStore = create<CommandCenterStore>()(
// cells move to the front first — the caller decides what's worth keeping.
optimizeLayout: (keepIndices) =>
set((state) => {
+ if (state.composer) return state;
const kept = keepIndices
.map((index) => state.cells[index])
.filter((cell): cell is string => cell != null);
@@ -262,11 +280,15 @@ export const useCommandCenterStore = create<CommandCenterStore>()(
}),
clearAll: () =>
- set((state) => ({
- activeTaskId: null,
- activeCellIndex: null,
- cells: state.cells.map(() => null),
- })),
+ set((state) =>
+ state.composer
+ ? state
+ : {
+ activeTaskId: null,
+ activeCellIndex: null,
+ cells: state.cells.map(() => null),
+ },
+ ),
setZoom: (zoom) => set({ zoom: clampZoom(zoom) }),
zoomIn: () =>
@@ -274,7 +296,58 @@ export const useCommandCenterStore = create<CommandCenterStore>()(
zoomOut: () =>
set((state) => ({ zoom: clampZoom(state.zoom - ZOOM_STEP) })),
- requestPlacement: (placement) => set({ pendingPlacement: placement }),
+ startCreating: (cellIndex, sessionId) =>
+ set((state) => {
+ if (cellIndex < 0 || cellIndex >= state.cells.length) return state;
+ if (state.cells[cellIndex] != null) return state;
+ if (state.composer) return state;
+ return {
+ activeCellIndex: cellIndex,
+ composer: { cellIndex, sessionId },
+ pendingPlacement: null,
+ // Starting to type is curation. It also prevents a late bootstrap
+ // from claiming another empty tile after the user took control.
+ hasAutofilled: true,
+ };
+ }),
+
+ stopCreating: (sessionId) =>
+ set((state) =>
+ state.composer?.sessionId === sessionId ? { composer: null } : state,
+ ),
+
+ finishCreating: (sessionId, taskId) => {
+ let assigned = false;
+ set((state) => {
+ const cellIndex = state.composer?.cellIndex;
+ if (
+ state.composer?.sessionId !== sessionId ||
+ cellIndex === undefined ||
+ state.cells[cellIndex] != null
+ ) {
+ return state;
+ }
+ const cells = [...state.cells];
+ const existingIndex = cells.indexOf(taskId);
+ if (existingIndex !== -1) cells[existingIndex] = null;
+ cells[cellIndex] = taskId;
+ assigned = true;
+ return {
+ cells,
+ activeTaskId: taskId,
+ activeCellIndex: cellIndex,
+ composer: null,
+ hasAutofilled: true,
+ pendingPlacement: null,
+ };
+ });
+ return assigned;
+ },
+
+ requestPlacement: (placement) =>
+ set((state) =>
+ state.composer ? state : { pendingPlacement: placement },
+ ),
cancelPlacement: () => set({ pendingPlacement: null }),
}),
{
@@ -286,6 +359,7 @@ export const useCommandCenterStore = create<CommandCenterStore>()(
activeTaskId: state.activeTaskId,
activeCellIndex: state.activeCellIndex,
zoom: state.zoom,
+ composer: state.composer,
hasAutofilled: state.hasAutofilled,
}),
},
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 195f6894939e..29069f403143 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
@@ -394,13 +394,16 @@ export function CommandCenterGrid({ layout, cells }: CommandCenterGridProps) {
const activeCellIndex = useCommandCenterStore((s) => s.activeCellIndex);
const draggedKind = useCellDragActive();
const pendingPlacement = useCommandCenterStore((s) => s.pendingPlacement);
+ const isComposing = useCommandCenterStore((s) => s.composer !== null);
const cancelPlacement = useCommandCenterStore((s) => s.cancelPlacement);
- const placement: PlacementState | null = pendingPlacement
- ? { mode: "pick", ...pendingPlacement }
- : draggedKind
- ? { mode: "drag", kind: draggedKind }
- : null;
+ const placement: PlacementState | null = isComposing
+ ? null
+ : pendingPlacement
+ ? { mode: "pick", ...pendingPlacement }
+ : draggedKind
+ ? { mode: "drag", kind: draggedKind }
+ : null;
useEffect(() => {
if (!pendingPlacement) return;
diff --git a/products/desktop/packages/ui/src/features/command-center/components/CommandCenterPanel.test.tsx b/products/desktop/packages/ui/src/features/command-center/components/CommandCenterPanel.test.tsx
index 2b3057af3476..67d6d2c8a79f 100644
--- a/products/desktop/packages/ui/src/features/command-center/components/CommandCenterPanel.test.tsx
+++ b/products/desktop/packages/ui/src/features/command-center/components/CommandCenterPanel.test.tsx
@@ -6,6 +6,27 @@ import type { CommandCenterCellData } from "../hooks/useCommandCenterData";
const mocks = vi.hoisted(() => ({
openTask: vi.fn(),
+ setDraft: vi.fn(),
+ clearAutoresearchDraft: vi.fn(),
+ currentUserUuid: "user-1",
+ taskCreatedCallback: null as ((task: Task) => void) | null,
+ authState: {
+ status: "authenticated",
+ cloudRegion: "us",
+ currentProjectId: 2,
+ },
+ createdTask: { id: "task-2", title: "Composed in a tile" },
+ store: {
+ layout: "2x2",
+ cells: [null, null, null, null] as (string | null)[],
+ composer: null as { cellIndex: number; sessionId: string } | null,
+ finishCreating: vi.fn(() => true),
+ clearCell: vi.fn(),
+ setBrainrotCell: vi.fn(),
+ setTerminalCell: vi.fn(),
+ startCreating: vi.fn(),
+ stopCreating: vi.fn(),
+ },
}));
vi.mock("@posthog/ui/router/useOpenTask", () => ({
@@ -55,16 +76,81 @@ vi.mock("../../sidebar/components/items/TaskIcon", () => ({
vi.mock("../../sidebar/useTaskPrStatus", () => ({
useTaskPrStatus: () => ({ prState: null, hasDiff: false }),
}));
+vi.mock("../../message-editor/draftStore", () => {
+ const state = { actions: { setDraft: mocks.setDraft } };
+ return {
+ useDraftStore: Object.assign(
+ (selector: (store: typeof state) => unknown) => selector(state),
+ { getState: () => state },
+ ),
+ };
+});
+vi.mock("../../auth/store", () => ({
+ useAuthStateValue: (selector: (state: typeof mocks.authState) => unknown) =>
+ selector(mocks.authState),
+}));
+vi.mock("../../auth/authClient", () => ({
+ useOptionalAuthenticatedClient: () => ({}),
+}));
+vi.mock("../../auth/useCurrentUser", () => ({
+ useCurrentUser: () => ({ data: { uuid: mocks.currentUserUuid } }),
+}));
+vi.mock("../../autoresearch/autoresearchDraftStore", () => ({
+ useAutoresearchDraftStore: {
+ getState: () => ({ clearDraft: mocks.clearAutoresearchDraft }),
+ },
+}));
+vi.mock("../../settings/settingsStore", () => ({
+ useSettingsStore: (selector: (state: unknown) => unknown) =>
+ selector({ brainrotMode: false }),
+}));
+vi.mock("../../task-detail/components/TaskInput", () => ({
+ TaskInput: ({
+ onTaskCreated,
+ showNewTaskSuggestions,
+ }: {
+ onTaskCreated?: (task: Task) => void;
+ showNewTaskSuggestions?: boolean;
+ }) => {
+ mocks.taskCreatedCallback = onTaskCreated ?? null;
+ return (
+ <div data-suggestions={showNewTaskSuggestions}>
+ <button
+ type="button"
+ onClick={() => onTaskCreated?.(mocks.createdTask as Task)}
+ >
+ Send
+ </button>
+ </div>
+ );
+ },
+}));
vi.mock("../commandCenterStore", () => ({
- useCommandCenterStore: (
- selector: (state: { clearCell: () => void }) => unknown,
- ) => selector({ clearCell: vi.fn() }),
+ useCommandCenterStore: (selector: (state: unknown) => unknown) =>
+ selector(mocks.store),
+ getCellSessionId: (scope: string, cellIndex: number) =>
+ `cc-cell-${scope}-${cellIndex}`,
}));
vi.mock("./CommandCenterPRButton", () => ({
CommandCenterPRButton: () => null,
}));
vi.mock("./TaskSelector", () => ({
- TaskSelector: ({ children }: { children: ReactNode }) => children,
+ TaskSelector: ({
+ children,
+ onNewTask,
+ }: {
+ children: ReactNode;
+ onNewTask?: () => void;
+ }) => (
+ <>
+ {children}
+ {onNewTask && (
+ <button type="button" onClick={onNewTask}>
+ New task
+ </button>
+ )}
+ </>
+ ),
}));
import { CommandCenterPanel } from "./CommandCenterPanel";
@@ -95,9 +181,22 @@ const cell = {
terminalCwd: null,
} satisfies CommandCenterCellData;
+const emptyCell = {
+ ...cell,
+ cellIndex: 2,
+ taskId: null,
+ task: undefined,
+} satisfies CommandCenterCellData;
+
describe("CommandCenterPanel", () => {
beforeEach(() => {
vi.clearAllMocks();
+ mocks.authState.cloudRegion = "us";
+ mocks.authState.currentProjectId = 2;
+ mocks.currentUserUuid = "user-1";
+ mocks.taskCreatedCallback = null;
+ mocks.store.composer = null;
+ mocks.store.finishCreating.mockReturnValue(true);
});
it("preserves the task's space when opening it", () => {
@@ -109,4 +208,105 @@ describe("CommandCenterPanel", () => {
channelId: "channel-1",
});
});
+
+ // Sending the user to the full-page composer instead abandons the grid they
+ // laid out, which is the whole point of working in Command Center.
+ it("starts a new task inside the tile that asked for one", () => {
+ render(<CommandCenterPanel cell={emptyCell} isActiveSession={false} />);
+
+ fireEvent.click(screen.getByRole("button", { name: "New task" }));
+
+ expect(mocks.store.startCreating).toHaveBeenCalledWith(
+ 2,
+ "cc-cell-us:2:user-1-2",
+ );
+ });
+
+ // Without this the task is created but never claims a tile, so its session
+ // renders nowhere.
+ it("keeps a task composed in a tile in that tile", () => {
+ mocks.store.composer = {
+ cellIndex: 2,
+ sessionId: "cc-cell-us:2:user-1-2",
+ };
+ render(<CommandCenterPanel cell={emptyCell} isActiveSession={false} />);
+
+ fireEvent.click(screen.getByRole("button", { name: "Send" }));
+
+ expect(mocks.store.finishCreating).toHaveBeenCalledWith(
+ "cc-cell-us:2:user-1-2",
+ "task-2",
+ );
+ expect(screen.getByText("Send").parentElement).toHaveAttribute(
+ "data-suggestions",
+ "false",
+ );
+ });
+
+ it("does not open a created task when the auth scope changed", () => {
+ mocks.store.composer = {
+ cellIndex: 2,
+ sessionId: "cc-cell-us:2:user-1-2",
+ };
+ const { rerender } = render(
+ <CommandCenterPanel cell={emptyCell} isActiveSession={false} />,
+ );
+ const taskCreated = mocks.taskCreatedCallback;
+ mocks.currentUserUuid = "user-2";
+ rerender(<CommandCenterPanel cell={emptyCell} isActiveSession={false} />);
+
+ taskCreated?.(mocks.createdTask as Task);
+
+ expect(mocks.store.finishCreating).not.toHaveBeenCalled();
+ expect(mocks.store.stopCreating).toHaveBeenCalledWith(
+ "cc-cell-us:2:user-1-2",
+ );
+ expect(mocks.openTask).not.toHaveBeenCalled();
+ });
+
+ it("opens a created task when its tile is no longer reserved", () => {
+ mocks.store.composer = {
+ cellIndex: 2,
+ sessionId: "cc-cell-us:2:user-1-2",
+ };
+ mocks.store.finishCreating.mockReturnValue(false);
+ render(<CommandCenterPanel cell={emptyCell} isActiveSession={false} />);
+
+ fireEvent.click(screen.getByRole("button", { name: "Send" }));
+
+ expect(mocks.openTask).toHaveBeenCalledWith(mocks.createdTask);
+ });
+
+ it("preserves the draft when leaving the command center", () => {
+ mocks.store.composer = {
+ cellIndex: 2,
+ sessionId: "cc-cell-us:2:user-1-2",
+ };
+ const { unmount } = render(
+ <CommandCenterPanel cell={emptyCell} isActiveSession={false} />,
+ );
+
+ unmount();
+
+ expect(mocks.setDraft).not.toHaveBeenCalled();
+ expect(mocks.clearAutoresearchDraft).not.toHaveBeenCalled();
+ });
+
+ it("clears all session drafts when canceling", () => {
+ mocks.store.composer = {
+ cellIndex: 2,
+ sessionId: "cc-cell-us:2:user-1-2",
+ };
+ render(<CommandCenterPanel cell={emptyCell} isActiveSession={false} />);
+
+ fireEvent.click(screen.getByTitle("Cancel"));
+
+ expect(mocks.store.stopCreating).toHaveBeenCalledWith(
+ "cc-cell-us:2:user-1-2",
+ );
+ expect(mocks.setDraft).toHaveBeenCalledWith("cc-cell-us:2:user-1-2", null);
+ expect(mocks.clearAutoresearchDraft).toHaveBeenCalledWith(
+ "cc-cell-us:2:user-1-2",
+ );
+ });
});
diff --git a/products/desktop/packages/ui/src/features/command-center/components/CommandCenterPanel.tsx b/products/desktop/packages/ui/src/features/command-center/components/CommandCenterPanel.tsx
index bdd8ca516219..1cea4c6a6cde 100644
--- a/products/desktop/packages/ui/src/features/command-center/components/CommandCenterPanel.tsx
+++ b/products/desktop/packages/ui/src/features/command-center/components/CommandCenterPanel.tsx
@@ -10,6 +10,7 @@ import {
Terminal,
X,
} from "@phosphor-icons/react";
+import { getAuthIdentity } from "@posthog/core/auth/authIdentity";
import { isBrainrotCell } from "@posthog/core/command-center/grid";
import {
Empty,
@@ -35,12 +36,18 @@ import { secureRandomString } from "@posthog/ui/utils/random";
import { Flex, Text } from "@radix-ui/themes";
import { useNavigate } from "@tanstack/react-router";
import { useCallback, useEffect, useRef, useState } from "react";
+import { useOptionalAuthenticatedClient } from "../../auth/authClient";
+import { useAuthStateValue } from "../../auth/store";
+import { useCurrentUser } from "../../auth/useCurrentUser";
+import { useAutoresearchDraftStore } from "../../autoresearch/autoresearchDraftStore";
import { useFolders } from "../../folders/useFolders";
import { useCloudPrUrl } from "../../git-interaction/useCloudPrUrl";
+import { useDraftStore } from "../../message-editor/draftStore";
import { EmbeddedSessionView } from "../../sessions/components/EmbeddedSessionView";
import { TaskIcon } from "../../sidebar/components/items/TaskIcon";
import { useTaskPrStatus } from "../../sidebar/useTaskPrStatus";
-import { useCommandCenterStore } from "../commandCenterStore";
+import { TaskInput } from "../../task-detail/components/TaskInput";
+import { getCellSessionId, useCommandCenterStore } from "../commandCenterStore";
import type {
CellStatus,
CommandCenterCellData,
@@ -124,11 +131,29 @@ function EmptyCell({ cellIndex }: { cellIndex: number }) {
const [selectorOpen, setSelectorOpen] = useState(false);
// The command-center terminal is unavailable on cloud-only hosts.
const { localWorkspaces } = useHostCapabilities();
+ const composer = useCommandCenterStore((s) => s.composer);
+ const finishCreating = useCommandCenterStore((s) => s.finishCreating);
const setBrainrotCell = useCommandCenterStore((s) => s.setBrainrotCell);
const setTerminalCell = useCommandCenterStore((s) => s.setTerminalCell);
+ const startCreating = useCommandCenterStore((s) => s.startCreating);
+ const stopCreating = useCommandCenterStore((s) => s.stopCreating);
const layout = useCommandCenterStore((s) => s.layout);
const cells = useCommandCenterStore((s) => s.cells);
const brainrotMode = useSettingsStore((s) => s.brainrotMode);
+ const authIdentity = useAuthStateValue(getAuthIdentity);
+ const client = useOptionalAuthenticatedClient();
+ const { data: currentUser } = useCurrentUser({ client });
+ const authScope =
+ authIdentity && currentUser?.uuid
+ ? `${authIdentity}:${currentUser.uuid}`
+ : null;
+ const sessionId = authScope ? getCellSessionId(authScope, cellIndex) : null;
+ const currentSessionIdRef = useRef(sessionId);
+ currentSessionIdRef.current = sessionId;
+ const isCreating =
+ sessionId !== null &&
+ composer?.cellIndex === cellIndex &&
+ composer.sessionId === sessionId;
const handleBrainrot = useCallback(() => {
track(ANALYTICS_EVENTS.BRAINROT_ACTIVATED, {
@@ -145,13 +170,86 @@ function EmptyCell({ cellIndex }: { cellIndex: number }) {
[setTerminalCell, cellIndex],
);
+ const handleNewTask = useCallback(() => {
+ if (sessionId) startCreating(cellIndex, sessionId);
+ }, [startCreating, cellIndex, sessionId]);
+
+ // Claiming the tile is what keeps the run in the grid: without it the task
+ // exists but its session has nowhere to render.
+ const handleTaskCreated = useCallback(
+ (task: Task) => {
+ if (!sessionId) {
+ void openTask(task);
+ return;
+ }
+ if (currentSessionIdRef.current !== sessionId) {
+ stopCreating(sessionId);
+ clearComposerDraft(sessionId);
+ return;
+ }
+ const assigned = finishCreating(sessionId, task.id);
+ clearComposerDraft(sessionId);
+ // Creation may finish after the user replaced or removed the tile. The
+ // task still exists, so open it instead of overwriting newer grid state.
+ if (!assigned) void openTask(task);
+ },
+ [finishCreating, sessionId, stopCreating],
+ );
+
+ const handleCancel = useCallback(() => {
+ if (!sessionId) return;
+ stopCreating(sessionId);
+ clearComposerDraft(sessionId);
+ }, [stopCreating, sessionId]);
+
+ useEffect(() => {
+ if (
+ !composer ||
+ composer.cellIndex !== cellIndex ||
+ !sessionId ||
+ composer.sessionId === sessionId
+ ) {
+ return;
+ }
+ stopCreating(composer.sessionId);
+ clearComposerDraft(composer.sessionId);
+ }, [cellIndex, composer, sessionId, stopCreating]);
+
+ if (isCreating) {
+ return (
+ <div className="flex h-full flex-col">
+ <div className="flex shrink-0 items-center justify-between border-gray-6 border-b px-2 py-1">
+ <QuillText className="font-medium font-mono text-[11px] text-gray-11">
+ New task
+ </QuillText>
+ <button
+ type="button"
+ onClick={handleCancel}
+ className="flex h-5 w-5 items-center justify-center rounded text-gray-10 transition-colors hover:bg-gray-4 hover:text-gray-12"
+ title="Cancel"
+ >
+ <X size={12} />
+ </button>
+ </div>
+ <div className="flex min-h-0 flex-1 flex-col">
+ <TaskInput
+ sessionId={sessionId}
+ onTaskCreated={handleTaskCreated}
+ showNewTaskSuggestions={false}
+ />
+ </div>
+ </div>
+ );
+ }
+
return (
- <Flex align="center" justify="center" height="100%">
- <Flex direction="column" align="center" gap="2" className="select-none">
+ <div className="flex h-full items-center justify-center">
+ <div className="flex select-none flex-col items-center gap-2">
<TaskSelector
cellIndex={cellIndex}
open={selectorOpen}
onOpenChange={setSelectorOpen}
+ onNewTask={!composer && sessionId ? handleNewTask : undefined}
onNewTerminal={localWorkspaces ? handleNewTerminal : undefined}
onBrainrot={brainrotMode ? handleBrainrot : undefined}
>
@@ -164,14 +262,19 @@ function EmptyCell({ cellIndex }: { cellIndex: number }) {
Add task
</button>
</TaskSelector>
- <Text className="text-[11px] text-gray-9">
+ <QuillText className="text-[11px] text-gray-9">
or drag a task from the sidebar
- </Text>
- </Flex>
- </Flex>
+ </QuillText>
+ </div>
+ </div>
);
}
+function clearComposerDraft(sessionId: string): void {
+ useDraftStore.getState().actions.setDraft(sessionId, null);
+ useAutoresearchDraftStore.getState().clearDraft(sessionId);
+}
+
const BRAINROT_PLAYLIST_IDS = [
"PLnOY1RYHjDfw2joBxUPADaadeX5IradbH",
"PLSzOLzwLMqSM",
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 eb9a1b680f98..746f320aa250 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
@@ -95,6 +95,7 @@ export function CommandCenterToolbar({
const setLayout = useCommandCenterStore((s) => s.setLayout);
const clearAll = useCommandCenterStore((s) => s.clearAll);
const optimizeLayout = useCommandCenterStore((s) => s.optimizeLayout);
+ const isComposing = useCommandCenterStore((s) => s.composer !== null);
const handleSetLayout = useCallback(
(preset: LayoutPreset) => {
@@ -137,6 +138,7 @@ export function CommandCenterToolbar({
>
<Select.Root
value={layout}
+ disabled={isComposing}
onValueChange={(v) => handleSetLayout(v as LayoutPreset)}
>
<Select.Trigger variant="ghost" className="text-[12px]" />
@@ -155,7 +157,8 @@ export function CommandCenterToolbar({
<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"
+ disabled={isComposing}
+ className="rounded px-1.5 py-0.5 text-[12px] text-gray-10 transition-colors hover:bg-gray-4 hover:text-gray-12 disabled:opacity-40"
title="Resize the grid to fit the tiles in use"
>
Optimize
@@ -192,7 +195,8 @@ export function CommandCenterToolbar({
<button
type="button"
onClick={handleClearAll}
- className="flex items-center gap-1 rounded px-1.5 py-0.5 text-[12px] text-gray-10 transition-colors hover:bg-gray-4 hover:text-gray-12"
+ disabled={isComposing}
+ className="flex items-center gap-1 rounded px-1.5 py-0.5 text-[12px] text-gray-10 transition-colors hover:bg-gray-4 hover:text-gray-12 disabled:opacity-40"
title="Clear all cells"
>
<Trash size={12} />
diff --git a/products/desktop/packages/ui/src/features/command-center/components/TaskSelector.test.tsx b/products/desktop/packages/ui/src/features/command-center/components/TaskSelector.test.tsx
index e5633ceb5b3e..7a62bb93e5ab 100644
--- a/products/desktop/packages/ui/src/features/command-center/components/TaskSelector.test.tsx
+++ b/products/desktop/packages/ui/src/features/command-center/components/TaskSelector.test.tsx
@@ -3,10 +3,6 @@ import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { beforeEach, describe, expect, it, vi } from "vitest";
-const openTaskInput = vi.hoisted(() => vi.fn());
-
-vi.mock("@posthog/ui/router/useOpenTask", () => ({ openTaskInput }));
-
vi.mock("@posthog/ui/features/command-center/hooks/useAvailableTasks", () => ({
useAvailableTasks: () => [],
}));
@@ -22,6 +18,8 @@ vi.mock("@posthog/ui/features/folders/useFolders", () => ({
import { TaskSelector } from "./TaskSelector";
+const onNewTask = vi.fn();
+
function renderSelector() {
return render(
<Theme>
@@ -29,6 +27,7 @@ function renderSelector() {
cellIndex={0}
open
onOpenChange={() => {}}
+ onNewTask={onNewTask}
onNewTerminal={() => {}}
>
<button type="button">Add task</button>
@@ -62,11 +61,12 @@ describe("TaskSelector", () => {
expectPopupWidth(screen.getByPlaceholderText("Search folders..."));
});
- it("opens the full task composer for a new task", async () => {
+ // Routing this to the full-page composer navigates the whole grid away.
+ it("composes a new task in the tile rather than navigating", async () => {
renderSelector();
await userEvent.click(screen.getByRole("button", { name: "New task" }));
- expect(openTaskInput).toHaveBeenCalledOnce();
+ expect(onNewTask).toHaveBeenCalledOnce();
});
});
diff --git a/products/desktop/packages/ui/src/features/command-center/components/TaskSelector.tsx b/products/desktop/packages/ui/src/features/command-center/components/TaskSelector.tsx
index ce39a2080d0f..465cbbddf363 100644
--- a/products/desktop/packages/ui/src/features/command-center/components/TaskSelector.tsx
+++ b/products/desktop/packages/ui/src/features/command-center/components/TaskSelector.tsx
@@ -5,7 +5,6 @@ import {
Plus,
Terminal,
} from "@phosphor-icons/react";
-import { openTaskInput } from "@posthog/ui/router/useOpenTask";
import { Popover } from "@radix-ui/themes";
import { type ReactNode, useCallback, useState } from "react";
import { Combobox } from "../../../primitives/combobox/Combobox";
@@ -17,6 +16,7 @@ interface TaskSelectorProps {
cellIndex: number;
open: boolean;
onOpenChange: (open: boolean) => void;
+ onNewTask?: () => void;
onNewTerminal?: (cwd?: string) => void;
onBrainrot?: () => void;
children: ReactNode;
@@ -29,6 +29,7 @@ export function TaskSelector({
cellIndex,
open,
onOpenChange,
+ onNewTask,
onNewTerminal,
onBrainrot,
children,
@@ -61,8 +62,8 @@ export function TaskSelector({
const handleNewTask = useCallback(() => {
handleOpenChange(false);
- openTaskInput();
- }, [handleOpenChange]);
+ onNewTask?.();
+ }, [handleOpenChange, onNewTask]);
const handleNewTerminal = useCallback(() => {
if (folders.length > 1) {
@@ -153,14 +154,16 @@ export function TaskSelector({
</div>
)}
<Combobox.Footer>
- <button
- type="button"
- className="combobox-footer-button"
- onClick={handleNewTask}
- >
- <Plus size={11} weight="bold" />
- New task
- </button>
+ {onNewTask && (
+ <button
+ type="button"
+ className="combobox-footer-button"
+ onClick={handleNewTask}
+ >
+ <Plus size={11} weight="bold" />
+ New task
+ </button>
+ )}
{onNewTerminal && (
<button
type="button"
diff --git a/products/desktop/packages/ui/src/features/command-center/placeTaskInCommandCenter.test.ts b/products/desktop/packages/ui/src/features/command-center/placeTaskInCommandCenter.test.ts
index 2ab3956c5a1b..4dfa624f54aa 100644
--- a/products/desktop/packages/ui/src/features/command-center/placeTaskInCommandCenter.test.ts
+++ b/products/desktop/packages/ui/src/features/command-center/placeTaskInCommandCenter.test.ts
@@ -5,8 +5,10 @@ import {
useCommandCenterStore,
} from "./commandCenterStore";
import {
+ expandCanvasInCommandCenterInto,
placeCanvasInCommandCenter,
placeCanvasInCommandCenterCell,
+ placeTasksInCommandCenter,
placeTasksInCommandCenterCell,
} from "./placeTaskInCommandCenter";
@@ -75,3 +77,34 @@ describe("placeTasksInCommandCenterCell", () => {
},
);
});
+
+describe("placement while composing", () => {
+ beforeEach(() => {
+ useCommandCenterStore.setState(COMMAND_CENTER_INITIAL_STATE);
+ useCommandCenterStore.getState().startCreating(1, "session-1");
+ });
+
+ it("rejects bulk placement instead of overwriting the reserved tile", () => {
+ const result = placeTasksInCommandCenter(
+ ["task-1", "task-2"],
+ new Set(["task-1", "task-2"]),
+ );
+
+ expect(result).toEqual({ placed: 0, overflow: 2, alreadyPresent: 0 });
+ expect(useCommandCenterStore.getState().cells).toEqual([
+ null,
+ null,
+ null,
+ null,
+ ]);
+ });
+
+ it("keeps expansion and assignment atomic", () => {
+ expandCanvasInCommandCenterInto("horizontal", 0, "canvas-1");
+
+ const state = useCommandCenterStore.getState();
+ expect(state.layout).toBe("2x2");
+ expect(state.cells).toEqual([null, null, null, null]);
+ expect(state.composer?.sessionId).toBe("session-1");
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/command-center/placeTaskInCommandCenter.ts b/products/desktop/packages/ui/src/features/command-center/placeTaskInCommandCenter.ts
index e8dcfc07b8c0..b06508dc204c 100644
--- a/products/desktop/packages/ui/src/features/command-center/placeTaskInCommandCenter.ts
+++ b/products/desktop/packages/ui/src/features/command-center/placeTaskInCommandCenter.ts
@@ -60,6 +60,15 @@ export function placeTasksInCommandCenter(
liveTaskIds,
});
+ if (state.composer) {
+ navigateToCommandCenter();
+ return {
+ placed: 0,
+ overflow: plan.placed.length + plan.overflow.length,
+ alreadyPresent: plan.alreadyPresent.length,
+ };
+ }
+
if (plan.placed.length > 0) {
state.applyPlacement({ layout: plan.layout, cells: plan.cells });
}
@@ -115,6 +124,7 @@ export function expandCanvasInCommandCenterInto(
canvasId: string,
): void {
const state = useCommandCenterStore.getState();
+ if (state.composer) return;
const expanded = getExpandedLayout(state.layout, direction);
if (!expanded) return;
@@ -137,6 +147,7 @@ export function expandTasksInCommandCenterInto(
if (!firstTaskId) return;
const state = useCommandCenterStore.getState();
+ if (state.composer) return;
const expanded = getExpandedLayout(state.layout, direction);
if (!expanded) return;
diff --git a/products/desktop/packages/ui/src/features/task-detail/components/TaskInput.tsx b/products/desktop/packages/ui/src/features/task-detail/components/TaskInput.tsx
index 9262de095241..0d1f9be7e30a 100644
--- a/products/desktop/packages/ui/src/features/task-detail/components/TaskInput.tsx
+++ b/products/desktop/packages/ui/src/features/task-detail/components/TaskInput.tsx
@@ -144,6 +144,7 @@ interface TaskInputProps {
sessionId?: string;
onTaskCreated?: (task: Task) => void;
onTaskCreatedEffect?: (task: Task) => void;
+ showNewTaskSuggestions?: boolean;
initialPrompt?: string;
/** Full editor content to prefill (chips + attachments), preferred over initialPrompt. */
initialContent?: EditorContent;
@@ -216,6 +217,7 @@ export function TaskInput({
sessionId = "task-input",
onTaskCreated,
onTaskCreatedEffect,
+ showNewTaskSuggestions = true,
initialPrompt,
initialContent,
recoveredFromKey,
@@ -1806,13 +1808,13 @@ export function TaskInput({
</motion.div>
)}
</AnimatePresence>
- ) : (
+ ) : showNewTaskSuggestions ? (
<NewTaskSuggestions
repoPath={selectedDirectory || null}
workspaceMode={effectiveWorkspaceMode}
disabled={isCreatingTask}
/>
- )}
+ ) : null}
</div>
</div>
</Flex>