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): ask what a new space is for and start its setup task (#103730)

Peter Kirkhamd3baa5c1a3f7
diff --git a/products/desktop/packages/api-client/src/posthog-client.test.ts b/products/desktop/packages/api-client/src/posthog-client.test.ts
index 5c2112c47484..e3e6f29364fc 100644
--- a/products/desktop/packages/api-client/src/posthog-client.test.ts
+++ b/products/desktop/packages/api-client/src/posthog-client.test.ts
@@ -52,6 +52,75 @@ describe("PostHogAPIClient", () => {
},
);
+ it("shows the setup dependency error returned by the server", async () => {
+ const detail =
+ "The workflow action is unavailable. Sync templates and retry setup.";
+ const fetch = vi
+ .fn()
+ .mockResolvedValue(
+ new Response(JSON.stringify({ detail }), { status: 503 }),
+ );
+ const client = new PostHogAPIClient(
+ "https://example.com",
+ async () => "token",
+ async () => "token",
+ 42,
+ { fetch },
+ );
+
+ await expect(
+ client.setupTaskChannel("channel-1", {
+ kind: "goal",
+ goal: {
+ statement: "Improve activation",
+ direction: "at_least",
+ period: "week",
+ },
+ }),
+ ).rejects.toThrow(new Error(detail));
+ });
+ it.each([{}, { task_id: 123 }, { task_id: "invalid" }])(
+ "rejects an invalid setup response: %j",
+ async (body) => {
+ const fetch = vi
+ .fn()
+ .mockResolvedValue(new Response(JSON.stringify(body), { status: 201 }));
+ const client = new PostHogAPIClient(
+ "https://example.com",
+ async () => "token",
+ async () => "token",
+ 42,
+ { fetch },
+ );
+ await expect(
+ client.setupTaskChannel("channel-1", {
+ kind: "feature",
+ feature: { name: "Search" },
+ }),
+ ).rejects.toThrow();
+ },
+ );
+
+ it("returns the validated setup task", async () => {
+ const body = { task_id: "0198cf5c-67dd-7000-8000-000000000001" };
+ const fetch = vi
+ .fn()
+ .mockResolvedValue(new Response(JSON.stringify(body), { status: 201 }));
+ const client = new PostHogAPIClient(
+ "https://example.com",
+ async () => "token",
+ async () => "token",
+ 42,
+ { fetch },
+ );
+ await expect(
+ client.setupTaskChannel("channel-1", {
+ kind: "feature",
+ feature: { name: "Search" },
+ }),
+ ).resolves.toEqual(body);
+ });
+
describe("Desktop beta terms", () => {
it.each([
[
diff --git a/products/desktop/packages/api-client/src/posthog-client.ts b/products/desktop/packages/api-client/src/posthog-client.ts
index ae6134534fa3..3a5a5f9cd6be 100644
--- a/products/desktop/packages/api-client/src/posthog-client.ts
+++ b/products/desktop/packages/api-client/src/posthog-client.ts
@@ -61,6 +61,8 @@ import type {
SignalUserAutonomyConfig,
SlackChannelsQueryParams,
SlackChannelsResponse,
+ SpaceSetupInput,
+ SpaceSetupStarted,
SuggestedReviewersArtefact,
SuggestedReviewerWriteEntry,
Task,
@@ -77,6 +79,10 @@ import type {
UserBasic,
} from "@posthog/shared/domain-types";
import { buildPosthogProjectHeaderRecord } from "@posthog/shared/posthog-property-headers";
+import {
+ spaceSetupInputSchema,
+ spaceSetupStartedSchema,
+} from "@posthog/shared/schemas";
import {
activitySection,
compactCount,
@@ -3854,6 +3860,34 @@ export class PostHogAPIClient {
return (await response.json()) as ChannelFeedMessage[];
}
+ // Start the task that sets a space up for a goal or a feature. The server builds
+ // the prompt and files the task into the channel.
+ async setupTaskChannel(
+ channelId: string,
+ input: SpaceSetupInput,
+ ): Promise<SpaceSetupStarted> {
+ const teamId = await this.getTeamId();
+ const urlPath = `/api/projects/${teamId}/task_channels/${channelId}/setup/`;
+ try {
+ const response = await this.api.fetcher.fetch({
+ method: "post",
+ url: new URL(`${this.api.baseUrl}${urlPath}`),
+ path: urlPath,
+ overrides: {
+ body: JSON.stringify(spaceSetupInputSchema.parse(input)),
+ },
+ });
+ return spaceSetupStartedSchema.parse(await response.json());
+ } catch (error) {
+ throw new Error(
+ extractRequestErrorMessage(
+ error,
+ "Could not start space setup. Try again.",
+ ),
+ );
+ }
+ }
+
// Post a system announcement into a channel's feed. The row is authored by the
// system; the server records the requester as `author` for "Adam …" rendering.
async postChannelFeedMessage(
diff --git a/products/desktop/packages/core/src/canvas/contextDocument.test.ts b/products/desktop/packages/core/src/canvas/contextDocument.test.ts
index b37ba5ee4b53..afef5f00faef 100644
--- a/products/desktop/packages/core/src/canvas/contextDocument.test.ts
+++ b/products/desktop/packages/core/src/canvas/contextDocument.test.ts
@@ -2,7 +2,9 @@ import { describe, expect, it } from "vitest";
import {
parseContextDocument,
parsePostHogObjectUrl,
+ readAutonomy,
serializeContextDocument,
+ withAutonomy,
} from "./contextDocument";
const WIKI_LINES = [
@@ -122,6 +124,24 @@ describe("contextDocument", () => {
expect(serializeContextDocument(doc)).not.toContain("task:");
});
+ it("reads the autonomy level from the wiki's own lines and rewrites it in place", () => {
+ const doc = parseContextDocument(
+ "---\nsummary: Move activation\nautonomy: propose\nchannel_id: abc\n---\n\n# Body\n",
+ );
+
+ expect(readAutonomy(doc)).toBe("propose");
+ const changed = withAutonomy(doc, "ship_drafts");
+ expect(serializeContextDocument(changed)).toBe(
+ "---\nsummary: Move activation\nautonomy: ship_drafts\nchannel_id: abc\n---\n\n# Body\n",
+ );
+ expect(
+ readAutonomy(parseContextDocument("---\nsummary: x\n---\n")),
+ ).toBeNull();
+ expect(
+ readAutonomy(parseContextDocument("---\nautonomy: whatever\n---\n")),
+ ).toBeNull();
+ });
+
it("serializes prose alone without a frontmatter block", () => {
const doc = parseContextDocument("# Just prose\n");
diff --git a/products/desktop/packages/core/src/canvas/contextDocument.ts b/products/desktop/packages/core/src/canvas/contextDocument.ts
index 062875b3ee53..a534db86dd1e 100644
--- a/products/desktop/packages/core/src/canvas/contextDocument.ts
+++ b/products/desktop/packages/core/src/canvas/contextDocument.ts
@@ -75,6 +75,30 @@ export interface ContextDocument {
broken: BrokenBlock[];
}
+/** What the loops of a goal space may do on their own. Set by the setup task, changed by a person. */
+export const AUTONOMY_LEVELS = ["propose", "ship_drafts", "autopilot"] as const;
+export type AutonomyLevel = (typeof AUTONOMY_LEVELS)[number];
+
+const AUTONOMY_LINE = /^autonomy:\s*(.*?)\s*$/m;
+
+/** The page's autonomy level, or null when the page has none (a space that was not set up for a goal). */
+export function readAutonomy(doc: ContextDocument): AutonomyLevel | null {
+ const value = AUTONOMY_LINE.exec(doc.frontmatter)?.[1];
+ return AUTONOMY_LEVELS.find((level) => level === value) ?? null;
+}
+
+/** The document with its autonomy line replaced in place, so the wiki's other lines and their order survive. */
+export function withAutonomy(
+ doc: ContextDocument,
+ level: AutonomyLevel,
+): ContextDocument {
+ const line = `autonomy: ${level}`;
+ const frontmatter = AUTONOMY_LINE.test(doc.frontmatter)
+ ? doc.frontmatter.replace(AUTONOMY_LINE, line)
+ : [doc.frontmatter, line].filter(Boolean).join("\n");
+ return { ...doc, frontmatter };
+}
+
export const CONTEXT_OBJECT_KIND_LABELS: Record<ContextObjectKind, string> = {
insight: "Insight",
dashboard: "Dashboard",
diff --git a/products/desktop/packages/core/src/canvas/invokeCanvasAction.test.ts b/products/desktop/packages/core/src/canvas/invokeCanvasAction.test.ts
new file mode 100644
index 000000000000..772f02f63aa2
--- /dev/null
+++ b/products/desktop/packages/core/src/canvas/invokeCanvasAction.test.ts
@@ -0,0 +1,63 @@
+import { describe, expect, it, vi } from "vitest";
+import { invokeCanvasAction } from "./invokeCanvasAction";
+
+const input = {
+ id: "canvas-1",
+ verb: "workflows.pause",
+ payload: { workflow_ids: ["workflow-1"] },
+};
+const action = {
+ verb: "workflows.pause",
+ summary: "Disable workflows in this project so they stop running.",
+ destructive: true,
+};
+
+describe("invokeCanvasAction", () => {
+ it.each([true, false])(
+ "requires host confirmation for a destructive action (allowed: %s)",
+ async (allowed) => {
+ const confirm = vi.fn().mockReturnValue(allowed);
+ const invoke = vi
+ .fn()
+ .mockResolvedValue({ verb: action.verb, result: {} });
+ const result = invokeCanvasAction(
+ input,
+ async () => [action],
+ confirm,
+ invoke,
+ );
+ if (allowed) {
+ await expect(result).resolves.toEqual({
+ verb: action.verb,
+ result: {},
+ });
+ expect(invoke).toHaveBeenCalledWith(input);
+ } else {
+ await expect(result).rejects.toThrow("Canvas action canceled");
+ expect(invoke).not.toHaveBeenCalled();
+ }
+ expect(confirm).toHaveBeenCalledWith(action);
+ },
+ );
+
+ it("refuses an action absent from the server registry", async () => {
+ const invoke = vi.fn();
+ await expect(
+ invokeCanvasAction(input, async () => [], vi.fn(), invoke),
+ ).rejects.toThrow("Unknown canvas action");
+ expect(invoke).not.toHaveBeenCalled();
+ });
+
+ it("does not ask for confirmation for a non-destructive action", async () => {
+ const confirm = vi.fn();
+ const invoke = vi.fn().mockResolvedValue({ verb: action.verb, result: {} });
+ await invokeCanvasAction(
+ input,
+ async () => [{ ...action, destructive: false }],
+ confirm,
+ invoke,
+ );
+ expect(confirm).not.toHaveBeenCalled();
+ expect(invoke).toHaveBeenCalledWith(input);
+ });
+});
diff --git a/products/desktop/packages/core/src/canvas/invokeCanvasAction.ts b/products/desktop/packages/core/src/canvas/invokeCanvasAction.ts
new file mode 100644
index 000000000000..b66bfa60f9bd
--- /dev/null
+++ b/products/desktop/packages/core/src/canvas/invokeCanvasAction.ts
@@ -0,0 +1,26 @@
+import type { z } from "zod";
+import {
+ type CanvasActionDefinition,
+ type CanvasActionResult,
+ canvasActionDefinitionSchema,
+ type canvasActionInvokeInput,
+} from "./dashboardSchemas";
+
+export async function invokeCanvasAction(
+ input: z.infer<typeof canvasActionInvokeInput>,
+ listActions: () => Promise<CanvasActionDefinition[]>,
+ confirm: (action: CanvasActionDefinition) => boolean,
+ invoke: (
+ input: z.infer<typeof canvasActionInvokeInput>,
+ ) => Promise<CanvasActionResult>,
+): Promise<CanvasActionResult> {
+ const actions = canvasActionDefinitionSchema
+ .array()
+ .parse(await listActions());
+ const action = actions.find((entry) => entry.verb === input.verb);
+ if (!action) throw new Error("Unknown canvas action");
+ if (action.destructive && !confirm(action)) {
+ throw new Error("Canvas action canceled");
+ }
+ return invoke(input);
+}
diff --git a/products/desktop/packages/core/src/canvas/spaceSetup.test.ts b/products/desktop/packages/core/src/canvas/spaceSetup.test.ts
new file mode 100644
index 000000000000..9c1961576aa3
--- /dev/null
+++ b/products/desktop/packages/core/src/canvas/spaceSetup.test.ts
@@ -0,0 +1,73 @@
+import { describe, expect, it } from "vitest";
+import {
+ emptySpaceSetupDraft,
+ type SpaceSetupDraft,
+ spaceSetupDraftMissingField,
+ spaceSetupDraftToInput,
+} from "./spaceSetup";
+
+function draft(overrides: Partial<SpaceSetupDraft>): SpaceSetupDraft {
+ return { ...emptySpaceSetupDraft(), ...overrides };
+}
+
+describe("spaceSetup draft", () => {
+ it.each([
+ ["none is always complete", draft({ choice: "none" }), null],
+ [
+ "a goal needs a statement",
+ draft({
+ choice: "goal",
+ goal: { ...emptySpaceSetupDraft().goal, statement: " " },
+ }),
+ "statement",
+ ],
+ ["a feature needs a name", draft({ choice: "feature" }), "name"],
+ ])("missing field: %s", (_name, value, expected) => {
+ expect(spaceSetupDraftMissingField(value)).toBe(expected);
+ });
+
+ it("turns a goal draft into the request body with blanks as null", () => {
+ const input = spaceSetupDraftToInput(
+ draft({
+ choice: "goal",
+ goal: {
+ statement: " Increase weekly activation ",
+ target: "20%",
+ direction: "at_least",
+ period: "week",
+ deadline: "",
+ },
+ }),
+ "posthog/posthog",
+ );
+
+ expect(input).toEqual({
+ kind: "goal",
+ goal: {
+ statement: "Increase weekly activation",
+ target: "20%",
+ direction: "at_least",
+ period: "week",
+ deadline: null,
+ },
+ repository: "posthog/posthog",
+ });
+ });
+
+ it("turns a feature draft into the request body and none into null", () => {
+ expect(
+ spaceSetupDraftToInput(
+ draft({
+ choice: "feature",
+ feature: { name: "Checklist", flagKey: "", description: "" },
+ }),
+ null,
+ ),
+ ).toEqual({
+ kind: "feature",
+ feature: { name: "Checklist", flag_key: null, description: "" },
+ repository: null,
+ });
+ expect(spaceSetupDraftToInput(draft({ choice: "none" }), null)).toBeNull();
+ });
+});
diff --git a/products/desktop/packages/core/src/canvas/spaceSetup.ts b/products/desktop/packages/core/src/canvas/spaceSetup.ts
new file mode 100644
index 000000000000..f9686f750214
--- /dev/null
+++ b/products/desktop/packages/core/src/canvas/spaceSetup.ts
@@ -0,0 +1,92 @@
+import type {
+ SpaceGoalDirection,
+ SpaceGoalPeriod,
+ SpaceSetupInput,
+ SpaceSetupKind,
+} from "@posthog/shared/domain-types";
+
+/** What the create-space flow asks the space to be set up for. */
+export type SpaceSetupChoice = "none" | SpaceSetupKind;
+
+/** The form fields behind the goal and feature steps, before any trimming. */
+export interface SpaceSetupDraft {
+ choice: SpaceSetupChoice;
+ goal: {
+ statement: string;
+ target: string;
+ direction: SpaceGoalDirection;
+ period: SpaceGoalPeriod;
+ /** YYYY-MM-DD from a date input, or "". */
+ deadline: string;
+ };
+ feature: {
+ name: string;
+ flagKey: string;
+ description: string;
+ };
+}
+
+export function emptySpaceSetupDraft(): SpaceSetupDraft {
+ return {
+ choice: "none",
+ goal: {
+ statement: "",
+ target: "",
+ direction: "at_least",
+ period: "week",
+ deadline: "",
+ },
+ feature: { name: "", flagKey: "", description: "" },
+ };
+}
+
+/**
+ * The field a setup cannot start without, or null when the draft is complete.
+ * A "none" choice is always complete: the space is created without setup.
+ */
+export function spaceSetupDraftMissingField(
+ draft: SpaceSetupDraft,
+): "statement" | "name" | null {
+ if (draft.choice === "goal" && !draft.goal.statement.trim()) {
+ return "statement";
+ }
+ if (draft.choice === "feature" && !draft.feature.name.trim()) return "name";
+ return null;
+}
+
+/** A goal setup needs a repository, because its loops open pull requests. */
+export function spaceSetupNeedsRepository(draft: SpaceSetupDraft): boolean {
+ return draft.choice === "goal";
+}
+
+const blankToNull = (value: string): string | null => value.trim() || null;
+
+/** The request body for `POST task_channels/{id}/setup/`, or null for "none". */
+export function spaceSetupDraftToInput(
+ draft: SpaceSetupDraft,
+ repository: string | null,
+): SpaceSetupInput | null {
+ if (draft.choice === "none") return null;
+ if (draft.choice === "goal") {
+ return {
+ kind: "goal",
+ goal: {
+ statement: draft.goal.statement.trim(),
+ target: blankToNull(draft.goal.target),
+ direction: draft.goal.direction,
+ period: draft.goal.period,
+ deadline: blankToNull(draft.goal.deadline),
+ },
+ repository,
+ };
+ }
+ return {
+ kind: "feature",
+ feature: {
+ name: draft.feature.name.trim(),
+ flag_key: blankToNull(draft.feature.flagKey),
+ description: draft.feature.description.trim(),
+ },
+ repository,
+ };
+}
diff --git a/products/desktop/packages/shared/package.json b/products/desktop/packages/shared/package.json
index 52719fa8b889..6969adeb3e0e 100644
--- a/products/desktop/packages/shared/package.json
+++ b/products/desktop/packages/shared/package.json
@@ -20,6 +20,10 @@
"types": "./dist/hoggies.d.ts",
"import": "./dist/hoggies.js"
},
+ "./schemas": {
+ "types": "./dist/schemas.d.ts",
+ "import": "./dist/schemas.js"
+ },
"./domain-types": {
"types": "./dist/domain-types.d.ts",
"import": "./dist/domain-types.js"
diff --git a/products/desktop/packages/shared/src/analytics-events.ts b/products/desktop/packages/shared/src/analytics-events.ts
index ba1526895072..35f6d00444e4 100644
--- a/products/desktop/packages/shared/src/analytics-events.ts
+++ b/products/desktop/packages/shared/src/analytics-events.ts
@@ -1344,13 +1344,19 @@ export interface CanvasRuntimeErrorProperties {
csp_directive?: string;
}
-export type ContextActionType = "save_version" | "generate_started" | "discard";
+export type ContextActionType =
+ | "save_version"
+ | "generate_started"
+ | "setup_started"
+ | "discard";
export interface ContextActionProperties {
action_type: ContextActionType;
channel_id: string;
/** generate_started only. */
execution_type?: "local" | "cloud";
+ /** setup_started only: what the space was set up for. */
+ setup_kind?: "goal" | "feature";
/** save_version: whether this created the first version vs. an update. */
is_first_version?: boolean;
success?: boolean;
diff --git a/products/desktop/packages/shared/src/domain-types.ts b/products/desktop/packages/shared/src/domain-types.ts
index 31fd8e0fcc36..589df278e423 100644
--- a/products/desktop/packages/shared/src/domain-types.ts
+++ b/products/desktop/packages/shared/src/domain-types.ts
@@ -159,6 +159,16 @@ export interface TaskChannel {
/** Lifecycle events a client may post into a channel's feed. */
export type ChannelFeedMessageEvent = "context_md_building";
+export type {
+ SpaceFeatureInput,
+ SpaceGoalDirection,
+ SpaceGoalInput,
+ SpaceGoalPeriod,
+ SpaceSetupInput,
+ SpaceSetupKind,
+ SpaceSetupStarted,
+} from "./schemas";
+
/**
* A durable, team-visible "PostHog agent" announcement in a channel's feed —
* rendered alongside task cards (e.g. "Adam created this context"). `author` is
diff --git a/products/desktop/packages/shared/src/feature-flag-keys.json b/products/desktop/packages/shared/src/feature-flag-keys.json
index 4e1c030c1fb8..06c1cc11d15b 100644
--- a/products/desktop/packages/shared/src/feature-flag-keys.json
+++ b/products/desktop/packages/shared/src/feature-flag-keys.json
@@ -29,6 +29,7 @@
"SELF_DRIVING_SETUP_TASK_FLAG": "posthog-code-self-driving-setup-task",
"SETTINGS_BACKUP_FLAG": "posthog-desktop-settings-backup",
"SIGNALS_PR_REFUNDS_FLAG": "signals-pr-refunds",
+ "SPACE_SETUP_FLAG": "code-space-setup",
"SPOKEN_NARRATION_FLAG": "posthog-code-spoken-narration",
"TASK_ANALYSIS_FLAG": "posthog-code-task-analysis",
"TASK_COST_VISIBLE_FLAG": "posthog-code-task-cost-visible",
diff --git a/products/desktop/packages/shared/src/flags.ts b/products/desktop/packages/shared/src/flags.ts
index 901f7bd09651..d5a4fe881cab 100644
--- a/products/desktop/packages/shared/src/flags.ts
+++ b/products/desktop/packages/shared/src/flags.ts
@@ -106,6 +106,8 @@ export const BEDROCK_GATEWAY_VARIANTS = ["test", "control"] as const;
export type BedrockGatewayVariant = (typeof BEDROCK_GATEWAY_VARIANTS)[number];
/** Gates the organization context wiki: the Context explorer in the nav rails. */
export const CONTEXT_LAYER_FLAG = featureFlagKeys.CONTEXT_LAYER_FLAG;
+/** Gates the "set up this space for" step in the create-space flow. */
+export const SPACE_SETUP_FLAG = featureFlagKeys.SPACE_SETUP_FLAG;
export const BACKGROUND_AGENT_LOGS_FLAG =
featureFlagKeys.BACKGROUND_AGENT_LOGS_FLAG;
diff --git a/products/desktop/packages/shared/src/schemas.ts b/products/desktop/packages/shared/src/schemas.ts
new file mode 100644
index 000000000000..32b774b82aa7
--- /dev/null
+++ b/products/desktop/packages/shared/src/schemas.ts
@@ -0,0 +1,44 @@
+import { z } from "zod";
+
+const spaceGoalPeriodSchema = z.enum(["day", "week", "month"]);
+const spaceGoalDirectionSchema = z.enum(["at_least", "at_most"]);
+
+export const spaceGoalInputSchema = z.object({
+ statement: z.string().trim().min(1).max(2000),
+ period: spaceGoalPeriodSchema,
+ direction: spaceGoalDirectionSchema,
+ target: z.string().max(64).nullish(),
+ deadline: z.iso.date().nullish(),
+ insight_short_id: z.string().max(64).nullish(),
+});
+
+export const spaceFeatureInputSchema = z.object({
+ name: z.string().trim().min(1).max(200),
+ description: z.string().max(2000).optional(),
+ flag_key: z.string().max(400).nullish(),
+});
+
+const repositorySchema = z.string().max(255).nullish();
+
+export const spaceSetupInputSchema = z.discriminatedUnion("kind", [
+ z.object({
+ kind: z.literal("goal"),
+ goal: spaceGoalInputSchema,
+ repository: repositorySchema,
+ }),
+ z.object({
+ kind: z.literal("feature"),
+ feature: spaceFeatureInputSchema,
+ repository: repositorySchema,
+ }),
+]);
+
+export const spaceSetupStartedSchema = z.object({ task_id: z.uuid() });
+
+export type SpaceGoalPeriod = z.infer<typeof spaceGoalPeriodSchema>;
+export type SpaceGoalDirection = z.infer<typeof spaceGoalDirectionSchema>;
+export type SpaceGoalInput = z.infer<typeof spaceGoalInputSchema>;
+export type SpaceFeatureInput = z.infer<typeof spaceFeatureInputSchema>;
+export type SpaceSetupInput = z.infer<typeof spaceSetupInputSchema>;
+export type SpaceSetupKind = SpaceSetupInput["kind"];
+export type SpaceSetupStarted = z.infer<typeof spaceSetupStartedSchema>;
diff --git a/products/desktop/packages/shared/tsup.config.ts b/products/desktop/packages/shared/tsup.config.ts
index 4a12ee237b1c..f405e495ce50 100644
--- a/products/desktop/packages/shared/tsup.config.ts
+++ b/products/desktop/packages/shared/tsup.config.ts
@@ -9,6 +9,7 @@ export default defineConfig({
"src/deeplink.ts",
"src/dismissalReasons.ts",
"src/domain-types.ts",
+ "src/schemas.ts",
"src/hoggies.ts",
"src/mcp-sandbox-proxy.ts",
"src/model-catalog.ts",
diff --git a/products/desktop/packages/ui/src/features/canvas/components/CreateChannelModal.test.tsx b/products/desktop/packages/ui/src/features/canvas/components/CreateChannelModal.test.tsx
new file mode 100644
index 000000000000..a1e5f30156e3
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/canvas/components/CreateChannelModal.test.tsx
@@ -0,0 +1,211 @@
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { render, screen, waitFor } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ createChannel: vi.fn(),
+ setup: vi.fn(),
+ generate: vi.fn(),
+ setupFlag: vi.fn(),
+ navigate: vi.fn(),
+ track: vi.fn(),
+}));
+vi.mock("@posthog/ui/shell/analytics", () => ({ track: mocks.track }));
+vi.mock("@tanstack/react-router", () => ({
+ useNavigate: () => mocks.navigate,
+}));
+vi.mock("@posthog/ui/features/auth/authClient", () => ({
+ useOptionalAuthenticatedClient: () => ({ setupTaskChannel: mocks.setup }),
+}));
+vi.mock("@posthog/ui/features/auth/useCurrentUser", () => ({
+ useCurrentUser: () => ({ data: null }),
+}));
+vi.mock("@posthog/ui/features/canvas/hooks/useOrgMembers", () => ({
+ useOrgMembers: () => ({ members: [] }),
+}));
+vi.mock("@posthog/ui/features/canvas/hooks/useChannelsLayout", () => ({
+ useChannelsLayout: () => true,
+}));
+vi.mock("@posthog/ui/features/feature-flags/useFeatureFlag", () => ({
+ useFeatureFlag: () => mocks.setupFlag(),
+}));
+vi.mock("@posthog/ui/features/canvas/hooks/useChannels", () => ({
+ useChannelMutations: () => ({
+ createChannel: mocks.createChannel,
+ isCreating: false,
+ }),
+}));
+vi.mock("@posthog/ui/features/canvas/hooks/useGenerateContext", () => ({
+ useGenerateContext: () => ({ generate: mocks.generate, isStarting: false }),
+}));
+vi.mock("@posthog/ui/features/canvas/hooks/useTaskChannels", () => ({
+ useUpdateTaskChannelRepositories: () => ({
+ mutateAsync: vi.fn(),
+ isPending: false,
+ }),
+}));
+vi.mock(
+ "@posthog/ui/features/integrations/components/RepositoriesField",
+ () => ({
+ RepositoriesField: () => <div data-testid="repositories-field" />,
+ }),
+);
+vi.mock("@posthog/ui/features/canvas/components/MemberSearch", () => ({
+ MemberSearch: () => null,
+}));
+vi.mock("@posthog/ui/features/canvas/components/MemberList", () => ({
+ MemberList: () => null,
+}));
+
+import { CreateChannelModal } from "./CreateChannelModal";
+
+// The step transition keeps the leaving step mounted while it animates out, so
+// the newest button of a name is the one on the current step.
+const current = (label: string) => {
+ const matches = screen.getAllByText(label);
+ return matches[matches.length - 1] as HTMLElement;
+};
+
+describe("CreateChannelModal setup steps", () => {
+ beforeEach(() => {
+ for (const mock of Object.values(mocks)) mock.mockReset();
+ mocks.setupFlag.mockReturnValue(true);
+ window.scrollTo = () => {};
+ });
+
+ it("keeps a failed setup and retries it without creating another space", async () => {
+ const user = userEvent.setup();
+ const onOpenChange = vi.fn();
+ mocks.createChannel.mockResolvedValue({ id: "space-1" });
+ mocks.setup.mockRejectedValueOnce(
+ new Error("Setup is unavailable. Try again."),
+ );
+ render(
+ <QueryClientProvider client={new QueryClient()}>
+ <CreateChannelModal open onOpenChange={onOpenChange} />
+ </QueryClientProvider>,
+ );
+
+ await user.type(screen.getByLabelText("Name"), "search");
+ await user.click(current("Next"));
+ await user.click(screen.getByText("A feature"));
+ await user.type(screen.getByLabelText("Feature"), "Search filters");
+ await user.click(current("Next"));
+ await user.click(current("Create"));
+
+ expect(
+ await screen.findByText("Setup is unavailable. Try again."),
+ ).toBeTruthy();
+ expect(onOpenChange).not.toHaveBeenCalled();
+ expect(mocks.navigate).not.toHaveBeenCalled();
+ expect(mocks.track).not.toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({ action_type: "setup_started" }),
+ );
+ const firstInput = mocks.setup.mock.calls[0];
+ expect(firstInput).toEqual([
+ "space-1",
+ expect.objectContaining({
+ kind: "feature",
+ feature: expect.objectContaining({ name: "Search filters" }),
+ }),
+ ]);
+
+ let finish: () => void = () => {};
+ mocks.setup.mockImplementationOnce(
+ () =>
+ new Promise<void>((resolve) => {
+ finish = resolve;
+ }),
+ );
+ await user.dblClick(screen.getByRole("button", { name: "Retry setup" }));
+ expect(mocks.setup).toHaveBeenCalledTimes(2);
+ expect(screen.getByRole("button", { name: /Retry setup/ })).toHaveAttribute(
+ "aria-disabled",
+ "true",
+ );
+ expect(mocks.setup).toHaveBeenLastCalledWith(...firstInput);
+ finish();
+ await waitFor(() => expect(onOpenChange).toHaveBeenCalledWith(false));
+ expect(mocks.createChannel).toHaveBeenCalledOnce();
+ expect(mocks.navigate).toHaveBeenCalledWith({
+ to: "/spaces/$channelId",
+ params: { channelId: "space-1" },
+ });
+ expect(mocks.track).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({
+ action_type: "setup_started",
+ channel_id: "space-1",
+ }),
+ );
+ });
+ it("walks from the name through the setup step to repositories and back", async () => {
+ const user = userEvent.setup();
+ render(
+ <QueryClientProvider client={new QueryClient()}>
+ <CreateChannelModal open onOpenChange={vi.fn()} />
+ </QueryClientProvider>,
+ );
+
+ await user.type(screen.getByLabelText("Name"), "growth");
+ await user.click(current("Next"));
+ expect(screen.getByText("What is this space for?")).toBeTruthy();
+
+ expect(screen.getByLabelText("Describe it")).toBeTruthy();
+
+ await user.click(screen.getByText("A goal"));
+ expect(screen.getByLabelText("Goal")).toBeTruthy();
+ await user.click(current("Next"));
+ expect(screen.queryByText("Repositories")).toBeNull();
+
+ await user.type(screen.getByLabelText("Goal"), "Grow weekly activation");
+ await user.click(current("Next"));
+ expect(screen.getByText("Repositories")).toBeTruthy();
+ expect(screen.getByText(/A goal needs a repository/)).toBeTruthy();
+
+ await user.click(current("Back"));
+ expect(screen.getAllByText("What is this space for?").length).toBe(1);
+ expect(screen.getByLabelText("Goal")).toHaveProperty(
+ "value",
+ "Grow weekly activation",
+ );
+ });
+
+ it("creates a space through the describe step without setup when the flag is off", async () => {
+ const user = userEvent.setup();
+ mocks.setupFlag.mockReturnValue(false);
+ mocks.createChannel.mockResolvedValue({ id: "space-1" });
+ render(
+ <QueryClientProvider client={new QueryClient()}>
+ <CreateChannelModal open onOpenChange={vi.fn()} />
+ </QueryClientProvider>,
+ );
+
+ await user.type(screen.getByLabelText("Name"), "growth");
+ await user.click(current("Next"));
+ expect(screen.queryByText("What is this space for?")).toBeNull();
+ expect(screen.getByText("What's this space about?")).toBeTruthy();
+
+ await user.type(
+ document.getElementById("context-description") as HTMLElement,
+ "Weekly activation work",
+ );
+ await user.click(current("Next"));
+ await user.click(current("Create"));
+
+ await waitFor(() =>
+ expect(mocks.navigate).toHaveBeenCalledWith({
+ to: "/spaces/$channelId",
+ params: { channelId: "space-1" },
+ }),
+ );
+ expect(mocks.generate).toHaveBeenCalledWith({
+ channelId: "space-1",
+ channelName: "growth",
+ description: "Weekly activation work",
+ });
+ expect(mocks.setup).not.toHaveBeenCalled();
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/canvas/components/CreateChannelModal.tsx b/products/desktop/packages/ui/src/features/canvas/components/CreateChannelModal.tsx
index 8f4343e6c5c9..64dd1274ab01 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/CreateChannelModal.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/CreateChannelModal.tsx
@@ -3,6 +3,13 @@ import {
normalizeChannelNameInput,
validateChannelName,
} from "@posthog/core/canvas/channelName";
+import {
+ emptySpaceSetupDraft,
+ type SpaceSetupDraft,
+ spaceSetupDraftMissingField,
+ spaceSetupDraftToInput,
+ spaceSetupNeedsRepository,
+} from "@posthog/core/canvas/spaceSetup";
import {
Button,
Dialog,
@@ -27,20 +34,34 @@ import {
Switch,
Textarea,
} from "@posthog/quill";
+import { SPACE_SETUP_FLAG } from "@posthog/shared";
import {
ANALYTICS_EVENTS,
type ChannelsSurface,
} from "@posthog/shared/analytics-events";
-import type { UserBasic } from "@posthog/shared/domain-types";
+import type { SpaceSetupInput, UserBasic } from "@posthog/shared/domain-types";
import { useOptionalAuthenticatedClient } from "@posthog/ui/features/auth/authClient";
import { useCurrentUser } from "@posthog/ui/features/auth/useCurrentUser";
+import {
+ type CreateStep,
+ type CreateStepContext,
+ createStepDirection,
+ nextCreateStep,
+ previousCreateStep,
+} from "@posthog/ui/features/canvas/components/createChannelSteps";
import { MemberList } from "@posthog/ui/features/canvas/components/MemberList";
import { MemberSearch } from "@posthog/ui/features/canvas/components/MemberSearch";
+import { SpaceFeatureFields } from "@posthog/ui/features/canvas/components/spaceSetup/SpaceFeatureFields";
+import { SpaceGoalFields } from "@posthog/ui/features/canvas/components/spaceSetup/SpaceGoalFields";
+import { SpaceSetupChoiceField } from "@posthog/ui/features/canvas/components/spaceSetup/SpaceSetupChoiceField";
+import { SpaceSetupRetryDialog } from "@posthog/ui/features/canvas/components/spaceSetup/SpaceSetupRetryDialog";
import { useChannelMutations } from "@posthog/ui/features/canvas/hooks/useChannels";
import { useChannelsLayout } from "@posthog/ui/features/canvas/hooks/useChannelsLayout";
import { useGenerateContext } from "@posthog/ui/features/canvas/hooks/useGenerateContext";
import { useOrgMembers } from "@posthog/ui/features/canvas/hooks/useOrgMembers";
+import { useSetupSpace } from "@posthog/ui/features/canvas/hooks/useSetupSpace";
import { useUpdateTaskChannelRepositories } from "@posthog/ui/features/canvas/hooks/useTaskChannels";
+import { useFeatureFlag } from "@posthog/ui/features/feature-flags/useFeatureFlag";
import { RepositoriesField } from "@posthog/ui/features/integrations/components/RepositoriesField";
import { AnimatedHeight } from "@posthog/ui/primitives/AnimatedHeight";
import { toast } from "@posthog/ui/primitives/toast";
@@ -61,9 +82,6 @@ const DESCRIPTION_EXAMPLES = [
const DESCRIPTION_ROTATION_INTERVAL_MS = 5000;
-const CREATE_STEPS = ["name", "describe", "repositories", "members"] as const;
-type CreateStep = (typeof CREATE_STEPS)[number];
-
const EASE_OUT: [number, number, number, number] = [0.215, 0.61, 0.355, 1];
const EASE_IN_OUT: [number, number, number, number] = [0.645, 0.045, 0.355, 1];
const STEP_DURATION = 0.2;
@@ -119,6 +137,10 @@ export function CreateChannelModal({
const spacesLayout = useChannelsLayout();
const { createChannel, isCreating } = useChannelMutations();
const { generate, isStarting } = useGenerateContext();
+ const { setup, isStarting: isSettingUp } = useSetupSpace();
+ // Dev builds default the step on, like the spaces layout, so it can be tried
+ // without flag plumbing; force it off with the ph-dev-flags-off kill switch.
+ const setupEnabled = useFeatureFlag(SPACE_SETUP_FLAG, import.meta.env.DEV);
const linkRepositories = useUpdateTaskChannelRepositories();
const navigate = useNavigate();
const [name, setName] = useState("");
@@ -130,6 +152,13 @@ export function CreateChannelModal({
const [star, setStar] = useState(true);
const [visibility, setVisibility] = useState<"public" | "private">("public");
const [memberIds, setMemberIds] = useState<number[]>([]);
+ const [setupDraft, setSetupDraft] =
+ useState<SpaceSetupDraft>(emptySpaceSetupDraft);
+ const [failedSetup, setFailedSetup] = useState<{
+ channelId: string;
+ input: SpaceSetupInput;
+ error: string;
+ } | null>(null);
const authClient = useOptionalAuthenticatedClient();
const { data: currentUser } = useCurrentUser({ client: authClient });
const { members: orgMembers } = useOrgMembers();
@@ -149,17 +178,24 @@ export function CreateChannelModal({
const reduceMotion = useReducedMotion();
const stepDuration = reduceMotion ? 0 : STEP_DURATION;
- const goToStep = (next: CreateStep) => {
- setDirection(
- CREATE_STEPS.indexOf(next) > CREATE_STEPS.indexOf(step) ? 1 : -1,
- );
+ const stepContext: CreateStepContext = {
+ setupEnabled,
+ choice: setupDraft.choice,
+ visibility,
+ };
+
+ const goToStep = (next: CreateStep | null) => {
+ if (!next) return;
+ setDirection(createStepDirection(step, next));
setStep(next);
};
+ const goBack = () => goToStep(previousCreateStep(step, stepContext));
+ const goForward = () => goToStep(nextCreateStep(step, stepContext));
const [wasOpen, setWasOpen] = useState(open);
if (open !== wasOpen) {
setWasOpen(open);
- if (open) {
+ if (open && !failedSetup) {
setName("");
setDescription("");
setRepositories([]);
@@ -167,6 +203,7 @@ export function CreateChannelModal({
setStar(true);
setVisibility("public");
setMemberIds([]);
+ setSetupDraft(emptySpaceSetupDraft());
setStep("name");
}
}
@@ -176,9 +213,16 @@ export function CreateChannelModal({
const remaining = MAX_CONTEXT_NAME_LENGTH - name.length;
const nameError = isDescribeMode ? null : validateChannelName(trimmedName);
- const busy = isCreating || isStarting || linkRepositories.isPending;
+ const busy =
+ isCreating || isStarting || isSettingUp || linkRepositories.isPending;
const canAdvance = !busy && !!trimmedName && !nameError;
const canDescribe = !busy && !!trimmedDescription;
+ const setupMissingField = spaceSetupDraftMissingField(setupDraft);
+ const repositoryMissing =
+ setupEnabled &&
+ spaceSetupNeedsRepository(setupDraft) &&
+ repositories.length === 0;
+ const canCreate = canAdvance && !repositoryMissing;
const submittingRef = useRef(false);
const submitOnce = async (submit: () => Promise<void>) => {
@@ -191,6 +235,34 @@ export function CreateChannelModal({
}
};
+ const openSpace = (channelId: string): void => {
+ setFailedSetup(null);
+ onOpenChange(false);
+ void navigate({ to: "/spaces/$channelId", params: { channelId } });
+ };
+
+ const startSetup = async (
+ channelId: string,
+ input: SpaceSetupInput,
+ ): Promise<boolean> => {
+ try {
+ await setup({ channelId, setup: input });
+ } catch (error) {
+ setFailedSetup({
+ channelId,
+ input,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ return false;
+ }
+ track(ANALYTICS_EVENTS.CONTEXT_ACTION, {
+ action_type: "setup_started",
+ channel_id: channelId,
+ setup_kind: input.kind,
+ });
+ return true;
+ };
+
const submitCreate = async () => {
let contextId: string;
try {
@@ -232,7 +304,12 @@ export function CreateChannelModal({
}
}
- if (trimmedDescription) {
+ const setupInput = setupEnabled
+ ? spaceSetupDraftToInput(setupDraft, repositories[0] ?? null)
+ : null;
+ if (setupInput) {
+ if (!(await startSetup(contextId, setupInput))) return;
+ } else if (trimmedDescription) {
track(ANALYTICS_EVENTS.CONTEXT_ACTION, {
action_type: "generate_started",
channel_id: contextId,
@@ -244,11 +321,7 @@ export function CreateChannelModal({
});
}
- onOpenChange(false);
- void navigate({
- to: "/spaces/$channelId",
- params: { channelId: contextId },
- });
+ openSpace(contextId);
};
const submitDescribe = async () => {
@@ -277,7 +350,7 @@ export function CreateChannelModal({
await submitDescribe();
return;
}
- if (canDescribe) goToStep("repositories");
+ if (canDescribe) goForward();
};
const aboutTitle = `What's this ${spacesLayout ? "space" : "channel"} about?`;
@@ -285,6 +358,29 @@ export function CreateChannelModal({
spacesLayout ? "space" : "channel"
}. We'll use it to create a CONTEXT.md file with relevant information for future tasks.`;
+ const descriptionTextarea = (
+ <div className="relative">
+ <Textarea
+ id="context-description"
+ aria-describedby={descriptionHelperId}
+ rows={4}
+ className="max-h-[40vh] overflow-y-auto text-xs leading-4"
+ value={description}
+ disabled={busy}
+ onChange={(e) => setDescription(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) {
+ e.preventDefault();
+ void submitOnce(submitDescribeStep);
+ }
+ }}
+ />
+ <RotatingDescriptionPlaceholder
+ visible={description.length === 0 && !busy}
+ />
+ </div>
+ );
+
const descriptionField = (
<Field>
{/* In create mode the step's own header asks the question, so the label
@@ -297,26 +393,7 @@ export function CreateChannelModal({
</FieldDescription>
</>
)}
- <div className="relative">
- <Textarea
- id="context-description"
- aria-describedby={descriptionHelperId}
- rows={4}
- className="max-h-[40vh] overflow-y-auto text-xs leading-4"
- value={description}
- disabled={busy}
- onChange={(e) => setDescription(e.target.value)}
- onKeyDown={(e) => {
- if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) {
- e.preventDefault();
- void submitOnce(submitDescribeStep);
- }
- }}
- />
- <RotatingDescriptionPlaceholder
- visible={description.length === 0 && !busy}
- />
- </div>
+ {descriptionTextarea}
</Field>
);
@@ -357,6 +434,27 @@ export function CreateChannelModal({
);
}
+ if (failedSetup) {
+ return (
+ <SpaceSetupRetryDialog
+ open={open}
+ onOpenChange={(next) => {
+ if (!busy) onOpenChange(next);
+ }}
+ error={failedSetup.error}
+ busy={busy}
+ onOpenSpace={() => openSpace(failedSetup.channelId)}
+ onRetry={() =>
+ void submitOnce(async () => {
+ if (await startSetup(failedSetup.channelId, failedSetup.input)) {
+ openSpace(failedSetup.channelId);
+ }
+ })
+ }
+ />
+ );
+ }
+
const renderStep = () => {
switch (step) {
case "name":
@@ -389,7 +487,7 @@ export function CreateChannelModal({
onKeyDown={(e) => {
if (e.key === "Enter") {
e.preventDefault();
- if (canAdvance) goToStep("describe");
+ if (canAdvance) goForward();
}
}}
/>
@@ -417,7 +515,85 @@ export function CreateChannelModal({
<Button
variant="primary"
disabled={!canAdvance}
- onClick={() => goToStep("describe")}
+ onClick={goForward}
+ >
+ Next
+ </Button>
+ </DialogFooter>
+ </>
+ );
+ case "setup":
+ return (
+ <>
+ <DialogHeader>
+ <DialogTitle>What is this space for?</DialogTitle>
+ <DialogDescription>
+ A goal or a feature gets a context page filled in for you. A
+ goal also gets a tracking canvas and loops that work toward it.
+ </DialogDescription>
+ </DialogHeader>
+
+ <DialogBody
+ className="flex max-h-[60vh] flex-col"
+ viewportClassName="flex flex-col gap-4"
+ >
+ <SpaceSetupChoiceField
+ value={setupDraft.choice}
+ disabled={busy}
+ onChange={(choice) =>
+ setSetupDraft((draft) => ({ ...draft, choice }))
+ }
+ />
+ <AnimatedHeight duration={stepDuration} ease={EASE_IN_OUT}>
+ <div key={setupDraft.choice} className="flex flex-col gap-4">
+ {setupDraft.choice === "goal" && (
+ <SpaceGoalFields
+ value={setupDraft.goal}
+ disabled={busy}
+ onChange={(goal) =>
+ setSetupDraft((draft) => ({ ...draft, goal }))
+ }
+ />
+ )}
+ {setupDraft.choice === "feature" && (
+ <SpaceFeatureFields
+ value={setupDraft.feature}
+ disabled={busy}
+ onChange={(feature) =>
+ setSetupDraft((draft) => ({ ...draft, feature }))
+ }
+ />
+ )}
+ {setupDraft.choice === "none" && (
+ <Field>
+ <FieldLabel htmlFor="context-description">
+ Describe it
+ </FieldLabel>
+ {descriptionTextarea}
+ <FieldDescription id={descriptionHelperId}>
+ Optional. A description starts a task that writes the
+ context page.
+ </FieldDescription>
+ </Field>
+ )}
+ </div>
+ </AnimatedHeight>
+ </DialogBody>
+
+ <DialogFooter>
+ <Button
+ variant="outline"
+ className="sm:mr-auto"
+ disabled={busy}
+ onClick={goBack}
+ >
+ Back
+ </Button>
+ <Button
+ variant="primary"
+ disabled={busy || setupMissingField !== null}
+ onClick={goForward}
+ data-attr="space-setup-next"
>
Next
</Button>
@@ -443,7 +619,7 @@ export function CreateChannelModal({
variant="outline"
className="sm:mr-auto"
disabled={busy}
- onClick={() => goToStep("name")}
+ onClick={goBack}
>
Back
</Button>
@@ -452,7 +628,7 @@ export function CreateChannelModal({
disabled={busy}
onClick={() => {
setDescription("");
- goToStep("repositories");
+ goForward();
}}
>
Skip
@@ -505,6 +681,12 @@ export function CreateChannelModal({
New tasks in this {spacesLayout ? "space" : "channel"} can
use these repositories. You can change them later.
</ItemDescription>
+ {repositoryMissing && (
+ <FieldError>
+ A goal needs a repository. Its loops open pull requests
+ there.
+ </FieldError>
+ )}
</ItemContent>
<ItemActions>
<RepositoriesField
@@ -545,17 +727,17 @@ export function CreateChannelModal({
variant="outline"
className="sm:mr-auto"
disabled={busy}
- onClick={() => goToStep("describe")}
+ onClick={goBack}
>
Back
</Button>
<Button
variant="primary"
- disabled={!canAdvance}
+ disabled={!canCreate}
loading={busy}
onClick={() => {
if (visibility === "private") {
- goToStep("members");
+ goForward();
} else {
void submitOnce(submitCreate);
}
@@ -605,13 +787,13 @@ export function CreateChannelModal({
variant="outline"
className="sm:mr-auto"
disabled={busy}
- onClick={() => goToStep("repositories")}
+ onClick={goBack}
>
Back
</Button>
<Button
variant="primary"
- disabled={!canAdvance}
+ disabled={!canCreate}
loading={busy}
onClick={() => void submitOnce(submitCreate)}
>
@@ -630,7 +812,7 @@ export function CreateChannelModal({
open={open}
onOpenChange={(next) => {
if (busy || next) return;
- const previous = CREATE_STEPS[CREATE_STEPS.indexOf(step) - 1];
+ const previous = previousCreateStep(step, stepContext);
if (previous) {
goToStep(previous);
return;
diff --git a/products/desktop/packages/ui/src/features/canvas/components/context/AutonomySection.stories.tsx b/products/desktop/packages/ui/src/features/canvas/components/context/AutonomySection.stories.tsx
new file mode 100644
index 000000000000..fc8a3f5a9c63
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/canvas/components/context/AutonomySection.stories.tsx
@@ -0,0 +1,30 @@
+import type { AutonomyLevel } from "@posthog/core/canvas/contextDocument";
+import { AutonomySection } from "@posthog/ui/features/canvas/components/context/AutonomySection";
+import type { Meta, StoryObj } from "@storybook/react-vite";
+import { useState } from "react";
+
+const meta: Meta = {
+ title: "Canvas/Spaces/Autonomy section",
+ parameters: { layout: "padded" },
+};
+
+export default meta;
+
+export const Default: StoryObj = {
+ render: () => {
+ const [level, setLevel] = useState<AutonomyLevel>("propose");
+ return (
+ <div className="max-w-lg">
+ <AutonomySection value={level} onChange={setLevel} />
+ </div>
+ );
+ },
+};
+
+export const Saving: StoryObj = {
+ render: () => (
+ <div className="max-w-lg">
+ <AutonomySection value="ship_drafts" disabled onChange={() => {}} />
+ </div>
+ ),
+};
diff --git a/products/desktop/packages/ui/src/features/canvas/components/context/AutonomySection.tsx b/products/desktop/packages/ui/src/features/canvas/components/context/AutonomySection.tsx
new file mode 100644
index 000000000000..a186c21b02bb
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/canvas/components/context/AutonomySection.tsx
@@ -0,0 +1,54 @@
+import type { AutonomyLevel } from "@posthog/core/canvas/contextDocument";
+import { Text } from "@posthog/quill";
+import { SettingsSegmented } from "@posthog/ui/features/settings/components/SettingsSegmented";
+import { SectionHeader } from "./SectionHeader";
+
+const LEVELS: { value: AutonomyLevel; label: string; description: string }[] = [
+ {
+ value: "propose",
+ label: "Propose",
+ description:
+ "Loops measure the goal, rank ideas, and recommend the next change. They open nothing.",
+ },
+ {
+ value: "ship_drafts",
+ label: "Ship drafts",
+ description:
+ "Loops also open draft pull requests and draft experiments for you to review. They never change a live flag.",
+ },
+ {
+ value: "autopilot",
+ label: "Autopilot",
+ description:
+ "Loops also release a winning experiment variant and open its cleanup pull request when the decision rule is met.",
+ },
+];
+
+export function AutonomySection({
+ value,
+ disabled,
+ onChange,
+}: {
+ value: AutonomyLevel;
+ disabled?: boolean;
+ onChange: (level: AutonomyLevel) => void;
+}) {
+ const current = LEVELS.find((level) => level.value === value) ?? LEVELS[0];
+ return (
+ <section className="flex flex-col gap-3">
+ <SectionHeader label="Autonomy" />
+ <div className="flex flex-col gap-2">
+ <SettingsSegmented
+ value={value}
+ options={LEVELS}
+ disabled={disabled}
+ ariaLabel="Autonomy level"
+ onValueChange={(level) => onChange(level as AutonomyLevel)}
+ />
+ <Text size="xs" variant="muted">
+ {current.description} Loops read the level on their next run.
+ </Text>
+ </div>
+ </section>
+ );
+}
diff --git a/products/desktop/packages/ui/src/features/canvas/components/context/SpaceContextPage.tsx b/products/desktop/packages/ui/src/features/canvas/components/context/SpaceContextPage.tsx
index d17261aa8c95..1b1b854b5d51 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/context/SpaceContextPage.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/context/SpaceContextPage.tsx
@@ -4,10 +4,13 @@ import {
type ContextDocument,
type ContextGoal,
parseContextDocument,
+ readAutonomy,
serializeContextDocument,
+ withAutonomy,
} from "@posthog/core/canvas/contextDocument";
import { spaceFilesFolder } from "@posthog/core/canvas/contextFiles";
import { Button, cn, Text } from "@posthog/quill";
+import { SPACE_SETUP_FLAG } from "@posthog/shared";
import { CreateChannelModal } from "@posthog/ui/features/canvas/components/CreateChannelModal";
import {
buildGoalMeasurePrompt,
@@ -18,6 +21,7 @@ import { goalMeasureTasks } from "@posthog/ui/features/canvas/goalMeasureTasks";
import { useChannelFeed } from "@posthog/ui/features/canvas/hooks/useChannelFeed";
import type { ContextDocumentStore } from "@posthog/ui/features/canvas/hooks/useContextDocumentStore";
import { useGenerateContext } from "@posthog/ui/features/canvas/hooks/useGenerateContext";
+import { useFeatureFlag } from "@posthog/ui/features/feature-flags/useFeatureFlag";
import { LoadingState } from "@posthog/ui/primitives/LoadingState";
import {
PageHeader,
@@ -31,6 +35,7 @@ import { RelativeTimestamp } from "@posthog/ui/primitives/RelativeTimestamp";
import { Spinner } from "@posthog/ui/primitives/Spinner";
import { navigateToChannelTask } from "@posthog/ui/router/navigationBridge";
import { useEffect, useMemo, useRef, useState } from "react";
+import { AutonomySection } from "./AutonomySection";
import { ContextEmptyHero } from "./ContextEmptyHero";
import { GoalsList } from "./GoalsList";
import { KnowledgeList } from "./KnowledgeList";
@@ -60,6 +65,7 @@ export function SpaceContextPage({
const [editingContextFile, setEditingContextFile] = useState(false);
const { tasks: channelTasks } = useChannelFeed(channelId);
const { generate } = useGenerateContext();
+ const setupEnabled = useFeatureFlag(SPACE_SETUP_FLAG, import.meta.env.DEV);
const doc = useMemo(
() => parseContextDocument(store.content),
[store.content],
@@ -91,6 +97,9 @@ export function SpaceContextPage({
const saveDoc = (next: ContextDocument) =>
store.save(serializeContextDocument(next));
+ // Only a space set up for a goal carries the key; other spaces have no loops to steer.
+ const autonomy = setupEnabled ? readAutonomy(doc) : null;
+
const knowledgeStore: ContextDocumentStore = {
...store,
content: doc.knowledge,
@@ -183,6 +192,13 @@ export function SpaceContextPage({
isSaving={store.isSaving}
error={brokenIn("goals")}
/>
+ {autonomy ? (
+ <AutonomySection
+ value={autonomy}
+ disabled={store.isSaving}
+ onChange={(level) => saveDoc(withAutonomy(doc, level))}
+ />
+ ) : null}
<KnowledgeList
channelName={channelName}
links={doc.links}
diff --git a/products/desktop/packages/ui/src/features/canvas/components/createChannelSteps.test.ts b/products/desktop/packages/ui/src/features/canvas/components/createChannelSteps.test.ts
new file mode 100644
index 000000000000..197c99c16dbc
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/canvas/components/createChannelSteps.test.ts
@@ -0,0 +1,65 @@
+import { describe, expect, it } from "vitest";
+import {
+ type CreateStep,
+ type CreateStepContext,
+ nextCreateStep,
+ previousCreateStep,
+} from "./createChannelSteps";
+
+const base: CreateStepContext = {
+ setupEnabled: true,
+ choice: "none",
+ visibility: "public",
+};
+
+describe("create channel steps", () => {
+ it.each<[string, CreateStep, Partial<CreateStepContext>, CreateStep | null]>([
+ [
+ "flag off keeps the describe step",
+ "name",
+ { setupEnabled: false },
+ "describe",
+ ],
+ ["flag on asks what the space is for", "name", {}, "setup"],
+ [
+ "the setup step goes to repositories",
+ "setup",
+ { choice: "goal" },
+ "repositories",
+ ],
+ [
+ "describe goes to repositories",
+ "describe",
+ { setupEnabled: false },
+ "repositories",
+ ],
+ ["public ends at repositories", "repositories", {}, null],
+ [
+ "private continues to members",
+ "repositories",
+ { visibility: "private" },
+ "members",
+ ],
+ ])("next: %s", (_name, step, context, expected) => {
+ expect(nextCreateStep(step, { ...base, ...context })).toBe(expected);
+ });
+
+ it.each<[string, CreateStep, Partial<CreateStepContext>, CreateStep | null]>([
+ [
+ "repositories returns to setup when the flag is on",
+ "repositories",
+ {},
+ "setup",
+ ],
+ [
+ "repositories returns to describe when the flag is off",
+ "repositories",
+ { setupEnabled: false },
+ "describe",
+ ],
+ ["setup returns to name", "setup", {}, "name"],
+ ["name is the first step", "name", {}, null],
+ ])("previous: %s", (_name, step, context, expected) => {
+ expect(previousCreateStep(step, { ...base, ...context })).toBe(expected);
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/canvas/components/createChannelSteps.ts b/products/desktop/packages/ui/src/features/canvas/components/createChannelSteps.ts
new file mode 100644
index 000000000000..5a1379e0f816
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/canvas/components/createChannelSteps.ts
@@ -0,0 +1,57 @@
+import type { SpaceSetupChoice } from "@posthog/core/canvas/spaceSetup";
+
+export const CREATE_STEPS = [
+ "name",
+ "setup",
+ "describe",
+ "repositories",
+ "members",
+] as const;
+export type CreateStep = (typeof CREATE_STEPS)[number];
+
+export interface CreateStepContext {
+ /** The "what is this space for" step is flag-gated; off, the flow keeps the describe step. */
+ setupEnabled: boolean;
+ choice: SpaceSetupChoice;
+ visibility: "public" | "private";
+}
+
+/** The step that follows `step` for this draft, or null on the last step. */
+export function nextCreateStep(
+ step: CreateStep,
+ context: CreateStepContext,
+): CreateStep | null {
+ switch (step) {
+ case "name":
+ return context.setupEnabled ? "setup" : "describe";
+ case "setup":
+ case "describe":
+ return "repositories";
+ case "repositories":
+ return context.visibility === "private" ? "members" : null;
+ case "members":
+ return null;
+ }
+}
+
+/** The step before `step` for this draft, or null on the first step. */
+export function previousCreateStep(
+ step: CreateStep,
+ context: CreateStepContext,
+): CreateStep | null {
+ switch (step) {
+ case "name":
+ return null;
+ case "setup":
+ case "describe":
+ return "name";
+ case "repositories":
+ return context.setupEnabled ? "setup" : "describe";
+ case "members":
+ return "repositories";
+ }
+}
+
+export function createStepDirection(from: CreateStep, to: CreateStep): 1 | -1 {
+ return CREATE_STEPS.indexOf(to) > CREATE_STEPS.indexOf(from) ? 1 : -1;
+}
diff --git a/products/desktop/packages/ui/src/features/canvas/components/spaceSetup/SpaceFeatureFields.tsx b/products/desktop/packages/ui/src/features/canvas/components/spaceSetup/SpaceFeatureFields.tsx
new file mode 100644
index 000000000000..3d2d886cc0b6
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/canvas/components/spaceSetup/SpaceFeatureFields.tsx
@@ -0,0 +1,65 @@
+import type { SpaceSetupDraft } from "@posthog/core/canvas/spaceSetup";
+import {
+ Field,
+ FieldDescription,
+ FieldLabel,
+ Input,
+ Textarea,
+} from "@posthog/quill";
+
+export function SpaceFeatureFields({
+ value,
+ disabled,
+ onChange,
+}: {
+ value: SpaceSetupDraft["feature"];
+ disabled?: boolean;
+ onChange: (value: SpaceSetupDraft["feature"]) => void;
+}) {
+ return (
+ <>
+ <Field>
+ <FieldLabel htmlFor="space-feature-name">Feature</FieldLabel>
+ <Input
+ id="space-feature-name"
+ autoFocus
+ value={value.name}
+ disabled={disabled}
+ placeholder="e.g. Onboarding checklist"
+ onChange={(event) => onChange({ ...value, name: event.target.value })}
+ />
+ </Field>
+ <Field>
+ <FieldLabel htmlFor="space-feature-flag">Feature flag key</FieldLabel>
+ <Input
+ id="space-feature-flag"
+ value={value.flagKey}
+ disabled={disabled}
+ placeholder="e.g. onboarding-checklist"
+ onChange={(event) =>
+ onChange({ ...value, flagKey: event.target.value })
+ }
+ />
+ <FieldDescription>
+ Optional. Leave it empty and the setup task proposes a key.
+ </FieldDescription>
+ </Field>
+ <Field>
+ <FieldLabel htmlFor="space-feature-description">
+ What it does
+ </FieldLabel>
+ <Textarea
+ id="space-feature-description"
+ rows={3}
+ className="text-xs leading-4"
+ value={value.description}
+ disabled={disabled}
+ placeholder="One or two sentences. Optional."
+ onChange={(event) =>
+ onChange({ ...value, description: event.target.value })
+ }
+ />
+ </Field>
+ </>
+ );
+}
diff --git a/products/desktop/packages/ui/src/features/canvas/components/spaceSetup/SpaceGoalFields.tsx b/products/desktop/packages/ui/src/features/canvas/components/spaceSetup/SpaceGoalFields.tsx
new file mode 100644
index 000000000000..89cbb0e62689
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/canvas/components/spaceSetup/SpaceGoalFields.tsx
@@ -0,0 +1,115 @@
+import type { SpaceSetupDraft } from "@posthog/core/canvas/spaceSetup";
+import {
+ Field,
+ FieldDescription,
+ FieldLabel,
+ Input,
+ Text,
+ Textarea,
+} from "@posthog/quill";
+import type {
+ SpaceGoalDirection,
+ SpaceGoalPeriod,
+} from "@posthog/shared/domain-types";
+import { SettingsSegmented } from "@posthog/ui/features/settings/components/SettingsSegmented";
+
+const DIRECTIONS: { value: SpaceGoalDirection; label: string }[] = [
+ { value: "at_least", label: "At least" },
+ { value: "at_most", label: "At most" },
+];
+
+const PERIODS: { value: SpaceGoalPeriod; label: string }[] = [
+ { value: "day", label: "Per day" },
+ { value: "week", label: "Per week" },
+ { value: "month", label: "Per month" },
+];
+
+export function SpaceGoalFields({
+ value,
+ disabled,
+ onChange,
+}: {
+ value: SpaceSetupDraft["goal"];
+ disabled?: boolean;
+ onChange: (value: SpaceSetupDraft["goal"]) => void;
+}) {
+ return (
+ <>
+ <Field>
+ <FieldLabel htmlFor="space-goal-statement">Goal</FieldLabel>
+ <Textarea
+ id="space-goal-statement"
+ autoFocus
+ rows={3}
+ className="text-xs leading-4"
+ value={value.statement}
+ disabled={disabled}
+ placeholder="e.g. Increase the weekly activation rate of new desktop users"
+ onChange={(event) =>
+ onChange({ ...value, statement: event.target.value })
+ }
+ />
+ <FieldDescription>
+ Name the metric in plain words. The setup task finds or writes the
+ measure and records a baseline.
+ </FieldDescription>
+ </Field>
+ <Field>
+ <FieldLabel htmlFor="space-goal-target">Target</FieldLabel>
+ <div className="flex flex-wrap items-center gap-2">
+ <SettingsSegmented
+ value={value.direction}
+ options={DIRECTIONS}
+ disabled={disabled}
+ ariaLabel="Target direction"
+ onValueChange={(direction) =>
+ onChange({ ...value, direction: direction as SpaceGoalDirection })
+ }
+ />
+ <Input
+ id="space-goal-target"
+ inputMode="decimal"
+ className="w-28 tabular-nums"
+ value={value.target}
+ disabled={disabled}
+ placeholder="20%"
+ onChange={(event) =>
+ onChange({ ...value, target: event.target.value })
+ }
+ />
+ <SettingsSegmented
+ value={value.period}
+ options={PERIODS}
+ disabled={disabled}
+ ariaLabel="Measurement period"
+ onValueChange={(period) =>
+ onChange({ ...value, period: period as SpaceGoalPeriod })
+ }
+ />
+ </div>
+ <FieldDescription>
+ Optional. Leave the target empty to let the setup task propose one
+ from the baseline.
+ </FieldDescription>
+ </Field>
+ <Field>
+ <FieldLabel htmlFor="space-goal-deadline">Deadline</FieldLabel>
+ <div className="flex items-center gap-2">
+ <Input
+ id="space-goal-deadline"
+ type="date"
+ className="w-40"
+ value={value.deadline}
+ disabled={disabled}
+ onChange={(event) =>
+ onChange({ ...value, deadline: event.target.value })
+ }
+ />
+ <Text size="xs" variant="muted">
+ Optional
+ </Text>
+ </div>
+ </Field>
+ </>
+ );
+}
diff --git a/products/desktop/packages/ui/src/features/canvas/components/spaceSetup/SpaceSetupChoiceField.tsx b/products/desktop/packages/ui/src/features/canvas/components/spaceSetup/SpaceSetupChoiceField.tsx
new file mode 100644
index 000000000000..66e896f5c0c3
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/canvas/components/spaceSetup/SpaceSetupChoiceField.tsx
@@ -0,0 +1,48 @@
+import type { SpaceSetupChoice } from "@posthog/core/canvas/spaceSetup";
+import {
+ type RadioCardOption,
+ RadioCards,
+} from "@posthog/ui/primitives/RadioCards";
+
+const OPTIONS: readonly RadioCardOption<SpaceSetupChoice>[] = [
+ {
+ value: "none",
+ title: "Nothing yet",
+ description:
+ "Keep related work and context together. You can add a goal later.",
+ },
+ {
+ value: "goal",
+ title: "A goal",
+ description:
+ "Move one metric. Loops measure it and recommend changes. Let them open pull requests and experiments from the context page when you are ready.",
+ },
+ {
+ value: "feature",
+ title: "A feature",
+ description:
+ "Ship one feature behind a flag. The context page tracks adoption, the flag, and related errors.",
+ },
+];
+
+export function SpaceSetupChoiceField({
+ value,
+ disabled,
+ onChange,
+}: {
+ value: SpaceSetupChoice;
+ disabled?: boolean;
+ onChange: (value: SpaceSetupChoice) => void;
+}) {
+ return (
+ <RadioCards
+ value={value}
+ options={
+ disabled ? OPTIONS.map((option) => ({ ...option, disabled })) : OPTIONS
+ }
+ onChange={onChange}
+ ariaLabel="What is this space for?"
+ dataAttrPrefix="space-setup-choice"
+ />
+ );
+}
diff --git a/products/desktop/packages/ui/src/features/canvas/components/spaceSetup/SpaceSetupFields.stories.tsx b/products/desktop/packages/ui/src/features/canvas/components/spaceSetup/SpaceSetupFields.stories.tsx
new file mode 100644
index 000000000000..d4651d092b1d
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/canvas/components/spaceSetup/SpaceSetupFields.stories.tsx
@@ -0,0 +1,88 @@
+import {
+ emptySpaceSetupDraft,
+ type SpaceSetupDraft,
+} from "@posthog/core/canvas/spaceSetup";
+import { SpaceFeatureFields } from "@posthog/ui/features/canvas/components/spaceSetup/SpaceFeatureFields";
+import { SpaceGoalFields } from "@posthog/ui/features/canvas/components/spaceSetup/SpaceGoalFields";
+import { SpaceSetupChoiceField } from "@posthog/ui/features/canvas/components/spaceSetup/SpaceSetupChoiceField";
+import type { Meta, StoryObj } from "@storybook/react-vite";
+import { useState } from "react";
+
+const meta: Meta = {
+ title: "Canvas/Spaces/Space setup fields",
+ parameters: { layout: "padded" },
+};
+
+export default meta;
+
+function Frame({ children }: { children: React.ReactNode }) {
+ return <div className="flex max-w-lg flex-col gap-4">{children}</div>;
+}
+
+export const Choice: StoryObj = {
+ render: () => {
+ const [draft, setDraft] = useState<SpaceSetupDraft>(emptySpaceSetupDraft);
+ return (
+ <Frame>
+ <SpaceSetupChoiceField
+ value={draft.choice}
+ onChange={(choice) => setDraft({ ...draft, choice })}
+ />
+ </Frame>
+ );
+ },
+};
+
+export const Goal: StoryObj = {
+ render: () => {
+ const [draft, setDraft] = useState<SpaceSetupDraft>(() => ({
+ ...emptySpaceSetupDraft(),
+ choice: "goal",
+ goal: {
+ statement: "Increase the weekly activation rate of new desktop users",
+ target: "20%",
+ direction: "at_least",
+ period: "week",
+ deadline: "",
+ },
+ }));
+ return (
+ <Frame>
+ <SpaceGoalFields
+ value={draft.goal}
+ onChange={(goal) => setDraft({ ...draft, goal })}
+ />
+ </Frame>
+ );
+ },
+};
+
+export const Feature: StoryObj = {
+ render: () => {
+ const [draft, setDraft] = useState<SpaceSetupDraft>(() => ({
+ ...emptySpaceSetupDraft(),
+ choice: "feature",
+ }));
+ return (
+ <Frame>
+ <SpaceFeatureFields
+ value={draft.feature}
+ onChange={(feature) => setDraft({ ...draft, feature })}
+ />
+ </Frame>
+ );
+ },
+};
+
+export const Disabled: StoryObj = {
+ render: () => (
+ <Frame>
+ <SpaceSetupChoiceField value="goal" disabled onChange={() => {}} />
+ <SpaceGoalFields
+ value={emptySpaceSetupDraft().goal}
+ disabled
+ onChange={() => {}}
+ />
+ </Frame>
+ ),
+};
diff --git a/products/desktop/packages/ui/src/features/canvas/components/spaceSetup/SpaceSetupRetryDialog.stories.tsx b/products/desktop/packages/ui/src/features/canvas/components/spaceSetup/SpaceSetupRetryDialog.stories.tsx
new file mode 100644
index 000000000000..b5ed8b53eb26
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/canvas/components/spaceSetup/SpaceSetupRetryDialog.stories.tsx
@@ -0,0 +1,21 @@
+import type { Meta, StoryObj } from "@storybook/react-vite";
+import { SpaceSetupRetryDialog } from "./SpaceSetupRetryDialog";
+
+const meta = {
+ title: "Spaces/SpaceSetupRetryDialog",
+ component: SpaceSetupRetryDialog,
+ args: {
+ open: true,
+ onOpenChange: () => {},
+ error: "Setup is unavailable. Try again.",
+ busy: false,
+ onRetry: () => {},
+ onOpenSpace: () => {},
+ },
+} satisfies Meta<typeof SpaceSetupRetryDialog>;
+
+export default meta;
+type Story = StoryObj<typeof meta>;
+
+export const Failed: Story = {};
+export const Retrying: Story = { args: { busy: true } };
diff --git a/products/desktop/packages/ui/src/features/canvas/components/spaceSetup/SpaceSetupRetryDialog.tsx b/products/desktop/packages/ui/src/features/canvas/components/spaceSetup/SpaceSetupRetryDialog.tsx
new file mode 100644
index 000000000000..a5b68798f389
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/canvas/components/spaceSetup/SpaceSetupRetryDialog.tsx
@@ -0,0 +1,57 @@
+import {
+ Button,
+ Dialog,
+ DialogBody,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ FieldError,
+} from "@posthog/quill";
+
+export function SpaceSetupRetryDialog({
+ open,
+ onOpenChange,
+ error,
+ busy,
+ onRetry,
+ onOpenSpace,
+}: {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ error: string;
+ busy: boolean;
+ onRetry: () => void;
+ onOpenSpace: () => void;
+}) {
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent showCloseButton={false} className="sm:max-w-lg">
+ <DialogHeader>
+ <DialogTitle>Setup did not start</DialogTitle>
+ <DialogDescription>
+ Your space was created. Retry setup to use the details you entered,
+ or open the space without setup.
+ </DialogDescription>
+ </DialogHeader>
+ <DialogBody>
+ <FieldError className="break-words">{error}</FieldError>
+ </DialogBody>
+ <DialogFooter>
+ <Button variant="outline" disabled={busy} onClick={onOpenSpace}>
+ Open space
+ </Button>
+ <Button
+ variant="primary"
+ disabled={busy}
+ loading={busy}
+ onClick={onRetry}
+ >
+ Retry setup
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/products/desktop/packages/ui/src/features/canvas/freeform/canvasHostMessageRouter.test.ts b/products/desktop/packages/ui/src/features/canvas/freeform/canvasHostMessageRouter.test.ts
index f97b4a0ccdc5..6569b55397b2 100644
--- a/products/desktop/packages/ui/src/features/canvas/freeform/canvasHostMessageRouter.test.ts
+++ b/products/desktop/packages/ui/src/features/canvas/freeform/canvasHostMessageRouter.test.ts
@@ -163,7 +163,7 @@ describe("createCanvasHostMessageRouter", () => {
);
});
- it.each(["agentRequest", "connectorCall"] as const)(
+ it.each(["agentRequest", "connectorCall", "actionInvoke"] as const)(
"does not time out %s while waiting for approval",
async (method) => {
vi.useFakeTimers();
@@ -191,7 +191,12 @@ describe("createCanvasHostMessageRouter", () => {
payload:
method === "agentRequest"
? { prompt: "Change it" }
- : { provider: "mcp:calendar.example.com", tool: "list_events" },
+ : method === "actionInvoke"
+ ? {
+ verb: "workflows.pause",
+ payload: { workflow_ids: ["workflow-1"] },
+ }
+ : { provider: "mcp:calendar.example.com", tool: "list_events" },
});
// Elapse well past the 30s generic data-request timeout: an approval
diff --git a/products/desktop/packages/ui/src/features/canvas/freeform/canvasHostMessageRouter.ts b/products/desktop/packages/ui/src/features/canvas/freeform/canvasHostMessageRouter.ts
index ae918d858032..89c92da5283b 100644
--- a/products/desktop/packages/ui/src/features/canvas/freeform/canvasHostMessageRouter.ts
+++ b/products/desktop/packages/ui/src/features/canvas/freeform/canvasHostMessageRouter.ts
@@ -145,6 +145,7 @@ export function createCanvasHostMessageRouter(
// Do not report a failure while a later approval can still run the call.
const result =
message.method === "agentRequest" ||
+ message.method === "actionInvoke" ||
message.method === "connectorCall"
? await call
: await Promise.race([
diff --git a/products/desktop/packages/ui/src/features/canvas/freeform/freeformDataBridge.ts b/products/desktop/packages/ui/src/features/canvas/freeform/freeformDataBridge.ts
index e89c3c214985..7243092eae2b 100644
--- a/products/desktop/packages/ui/src/features/canvas/freeform/freeformDataBridge.ts
+++ b/products/desktop/packages/ui/src/features/canvas/freeform/freeformDataBridge.ts
@@ -7,6 +7,7 @@ import type {
CanvasLoadInsightInput,
} from "@posthog/core/canvas/freeformSchemas";
import { canvasConnectorCallInput } from "@posthog/core/canvas/freeformSchemas";
+import { invokeCanvasAction } from "@posthog/core/canvas/invokeCanvasAction";
import type { QueryClient } from "@tanstack/react-query";
import { hostClient } from "../hostClient";
@@ -276,11 +277,17 @@ export async function handleFreeformDataRequest(
throw new Error("ph.actions.invoke(verb, payload) requires a verb");
}
// A write into PostHog, never cached.
- return hostClient().dashboards.invokeAction.mutate({
- id: requireDashboardId(),
- verb: input.verb,
- payload: input.payload ?? {},
- });
+ const client = hostClient().dashboards;
+ return invokeCanvasAction(
+ {
+ id: requireDashboardId(),
+ verb: input.verb,
+ payload: input.payload ?? {},
+ },
+ () => client.listActions.query(),
+ (action) => window.confirm(`${action.summary}\n\nContinue?`),
+ (action) => client.invokeAction.mutate(action),
+ );
}
case "connectorCall": {
const dashboardId = requireDashboardId();
diff --git a/products/desktop/packages/ui/src/features/canvas/hooks/useChannelFeedMessages.ts b/products/desktop/packages/ui/src/features/canvas/hooks/useChannelFeedMessages.ts
index 44ed8d9a52b4..28cde46e76fe 100644
--- a/products/desktop/packages/ui/src/features/canvas/hooks/useChannelFeedMessages.ts
+++ b/products/desktop/packages/ui/src/features/canvas/hooks/useChannelFeedMessages.ts
@@ -30,10 +30,12 @@ export function channelFeedMessagesQueryKey(channelId: string | undefined) {
// same thing twice: creation is the intro header's line (channel_created and
// its legacy client-posted context_created twin), and a CONTEXT.md build is
// its own plan-task card in the feed plus the intro card's "Creating…" state.
+// A space setup is likewise its own task card.
const REDUNDANT_EVENTS = new Set([
"channel_created",
"context_created",
"context_md_building",
+ "space_setup_started",
]);
// Render the announcement from its freeform content, with a generic fallback
diff --git a/products/desktop/packages/ui/src/features/canvas/hooks/useSetupSpace.ts b/products/desktop/packages/ui/src/features/canvas/hooks/useSetupSpace.ts
new file mode 100644
index 000000000000..eda582650b45
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/canvas/hooks/useSetupSpace.ts
@@ -0,0 +1,38 @@
+import type {
+ SpaceSetupInput,
+ SpaceSetupStarted,
+} from "@posthog/shared/domain-types";
+import { useOptionalAuthenticatedClient } from "@posthog/ui/features/auth/authClient";
+import { channelFeedQueryKey } from "@posthog/ui/features/canvas/hooks/useChannelFeed";
+import { channelFeedMessagesQueryKey } from "@posthog/ui/features/canvas/hooks/useChannelFeedMessages";
+import { useMutation, useQueryClient } from "@tanstack/react-query";
+
+/**
+ * Starts the server-built task that sets a space up for a goal or a feature.
+ * The backend files the task into the channel and posts the feed row, so this
+ * only has to refresh the feed the user lands on.
+ */
+export function useSetupSpace() {
+ const client = useOptionalAuthenticatedClient();
+ const queryClient = useQueryClient();
+
+ const mutation = useMutation({
+ mutationFn: async (input: {
+ channelId: string;
+ setup: SpaceSetupInput;
+ }): Promise<SpaceSetupStarted> => {
+ if (!client) throw new Error("Not authenticated");
+ return client.setupTaskChannel(input.channelId, input.setup);
+ },
+ onSuccess: (_result, input) => {
+ void queryClient.invalidateQueries({
+ queryKey: channelFeedQueryKey(input.channelId),
+ });
+ void queryClient.invalidateQueries({
+ queryKey: channelFeedMessagesQueryKey(input.channelId),
+ });
+ },
+ });
+
+ return { setup: mutation.mutateAsync, isStarting: mutation.isPending };
+}