: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(desktop): provision a default #general space and land new users there (#83984)
Adam Bowkera2f7366b1344
diff --git a/products/desktop/packages/api-client/src/posthog-client.ts b/products/desktop/packages/api-client/src/posthog-client.tsindex 45fab8306970..f20052068d86 100644--- a/products/desktop/packages/api-client/src/posthog-client.ts+++ b/products/desktop/packages/api-client/src/posthog-client.ts@@ -68,6 +68,7 @@ import type {NoteArtefact,OrganizationMemberBasic,PriorityJudgmentArtefact,+ ProvisionedTaskChannels,RepoSelectionArtefact,SafetyJudgmentArtefact,SandboxCustomImage,@@ -2680,6 +2681,22 @@ export class PostHogAPIClient {return (await response.json()) as TaskChannel;}+ async provisionDefaultTaskChannels(): Promise<ProvisionedTaskChannels> {+ const teamId = await this.getTeamId();+ const urlPath = `/api/projects/${teamId}/task_channels/provision_defaults/`;+ const response = await this.api.fetcher.fetch({+ method: "post",+ url: new URL(`${this.api.baseUrl}${urlPath}`),+ path: urlPath,+ });+ if (!response.ok) {+ throw new Error(+ `Failed to provision default spaces: ${response.statusText}`,+ );+ }+ return (await response.json()) as ProvisionedTaskChannels;+ }+async updateTaskChannelRepositories(id: string,githubIntegration: number | null,diff --git a/products/desktop/packages/core/src/canvas/channelName.test.ts b/products/desktop/packages/core/src/canvas/channelName.test.tsindex 6704a5d17ed9..4d67f9d3c6c1 100644--- a/products/desktop/packages/core/src/canvas/channelName.test.ts+++ b/products/desktop/packages/core/src/canvas/channelName.test.ts@@ -1,12 +1,56 @@import { describe, expect, it } from "vitest";import {+ type ChannelIdentity,channelDisplayLabel,channelDisplayReference,+ isGeneralChannel,+ isPersonalChannel,normalizeChannelName,normalizeChannelNameInput,validateChannelName,} from "./channelName";+describe("isPersonalChannel / isGeneralChannel", () => {+ it.each([+ [+ "system_role wins over channel_type/name when present (personal)",+ { system_role: "personal", channel_type: "public", name: "not-me" },+ true,+ false,+ ],+ [+ "system_role wins over channel_type/name when present (general)",+ { system_role: "general", channel_type: "personal", name: "not-general" },+ false,+ true,+ ],+ [+ "null system_role falls back to the legacy checks and matches",+ { system_role: null, channel_type: "personal", name: "me" },+ true,+ false,+ ],+ [+ "null system_role falls back to the legacy checks and matches general",+ { system_role: null, channel_type: "public", name: "general" },+ false,+ true,+ ],+ [+ "neither system_role nor the legacy checks match",+ { system_role: null, channel_type: "public", name: "growth" },+ false,+ false,+ ],+ ] satisfies [string, ChannelIdentity, boolean, boolean][])(+ "%s",+ (_label, channel, expectedPersonal, expectedGeneral) => {+ expect(isPersonalChannel(channel)).toBe(expectedPersonal);+ expect(isGeneralChannel(channel)).toBe(expectedGeneral);+ },+ );+});+describe("normalizeChannelName", () => {it.each([["My New Space", "my-new-space"],diff --git a/products/desktop/packages/core/src/canvas/channelName.ts b/products/desktop/packages/core/src/canvas/channelName.tsindex 74c93d5175b6..f19bfa3da71c 100644--- a/products/desktop/packages/core/src/canvas/channelName.ts+++ b/products/desktop/packages/core/src/canvas/channelName.ts@@ -1,6 +1,26 @@-/** What the backend calls a user's private channel. */export const PERSONAL_CHANNEL_NAME = "me";+export const GENERAL_CHANNEL_NAME = "general";++export interface ChannelIdentity {+ system_role?: "personal" | "general" | null;+ channel_type: "public" | "personal";+ name: string;+}++export function isPersonalChannel(channel: ChannelIdentity): boolean {+ return channel.system_role != null+ ? channel.system_role === "personal"+ : channel.channel_type === "personal";+}++export function isGeneralChannel(channel: ChannelIdentity): boolean {+ return channel.system_role != null+ ? channel.system_role === "general"+ : channel.channel_type === "public" &&+ channel.name === GENERAL_CHANNEL_NAME;+}+/*** What that channel is called on screen.*@@ -48,8 +68,8 @@ export function channelDisplayReference(: `#${channelDisplayName(name)}`;}-// A channel's name is used verbatim as its server-side filesystem path segment,-// so it must be directory-safe: lowercase letters, numbers, and hyphens only.+// The server normalizes a name to this shape (`normalize_channel_name`), so anything+// else would be stored as something other than what the field showed.export const CHANNEL_NAME_PATTERN = /^[a-z0-9-]+$/;function replaceChannelNameSeparators(name: string): string {diff --git a/products/desktop/packages/shared/src/domain-types.ts b/products/desktop/packages/shared/src/domain-types.tsindex c0ad51f66374..ec06fc0eeb00 100644--- a/products/desktop/packages/shared/src/domain-types.ts+++ b/products/desktop/packages/shared/src/domain-types.ts@@ -114,6 +114,12 @@ export interface TaskSearchResult {* threads, instructions (CONTEXT.md) and filed canvases. `personal` is the* user's private "#me" channel. `starred` is per-user.*/+export interface ProvisionedTaskChannels {+ channels: TaskChannel[];+ personal_created: boolean;+ general_created: boolean;+}+export interface TaskChannel {id: string;name: string;@@ -123,6 +129,7 @@ export interface TaskChannel {repositories?: string[];created_at: string;created_by?: UserBasic | null;+ system_role?: "personal" | "general" | null;}/** Lifecycle events a client may post into a channel's feed. */diff --git a/products/desktop/packages/ui/src/features/canvas/AGENTS.md b/products/desktop/packages/ui/src/features/canvas/AGENTS.mdindex 75b56138af0f..7c8ac057eecb 100644--- a/products/desktop/packages/ui/src/features/canvas/AGENTS.md+++ b/products/desktop/packages/ui/src/features/canvas/AGENTS.md@@ -62,11 +62,13 @@ changing breadcrumbs, canvas naming, or the canvas generation harness. The rootFour routes carry a channel's name — the channel list, an activity row, amention row, and remote search — and each calls it, because only the firstgoes through `useTaskChannels`.- Recognition uses `channel_type`, never the name.+ Recognition of a full channel object goes through `isPersonalChannel`/`isGeneralChannel`+ (`@posthog/core/canvas/channelName`), which check `system_role` first and fall back to+ `channel_type`/name for a server that predates the field — never the name alone.- **The lock follows what a space is, not what it is called.** `channelGlyph`- takes a `personal` flag, and every caller holding the channel passes- `channelType === "personal"`; the name match behind it is a fallback for- surfaces that hold a bare name.+ takes a `personal` flag; a caller holding the channel object should pass+ `isPersonalChannel(channel)` rather than `channelType === "personal"` directly, and the+ name match behind it is a fallback for surfaces that hold only a bare name.A public space named `personal` used to wear the lock while the real privatespace showed none, which is a space impersonating yours.`validateChannelName` reserves `personal` and `me` so the create and rename@@ -197,7 +199,8 @@ changing breadcrumbs, canvas naming, or the canvas generation harness. The rootThe one exception is a session opened from the list's tree: it loads in themain window and leaves the sidebar on the list, because picking a sessionwhile browsing across spaces is not a request to go into one. It says so with- `keepListForNextRoute()`, which the route effect consumes in place of sliding.+ `keepListForRoute(spaceId)`, which the route effect checks in place of sliding;+ the first-run landing on #general uses the same latch.## Breadcrumbsdiff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelsList.test.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelsList.test.tsxindex 87d8e020437c..93d0fd233e82 100644--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelsList.test.tsx+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelsList.test.tsx@@ -114,7 +114,7 @@ vi.mock("@tanstack/react-router", () => ({}));import {- consumeKeepListForNextRoute,+ shouldKeepListForRoute,showChannelList,showChannelPane,useChannelPaneStore,@@ -459,7 +459,7 @@ describe("ChannelsList", () => {expect(useChannelPaneStore.getState().pane).toBe("list");// The other half of it: the route effect in ChannelsSidebar slides into// the space unless the navigation says to stay put.- expect(consumeKeepListForNextRoute()).toBe(true);+ expect(shouldKeepListForRoute(ENG.id)).toBe(true);// Still scoped, so whatever asks for the channel pane next opens on the// space the session came from.expect(useCurrentChannelStore.getState().currentChannelId).toBe(ENG.id);diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelsList.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelsList.tsxindex 143ea229a7da..7a446d9ee370 100644--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelsList.tsx+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelsList.tsx@@ -87,7 +87,7 @@ import {import { useIsChannelUnread } from "@posthog/ui/features/canvas/hooks/useUnreadChannels";import { useUnreadSessionCount } from "@posthog/ui/features/canvas/hooks/useUnreadSessionCount";import {- keepListForNextRoute,+ keepListForRoute,showChannelPane,useChannelPaneStore,} from "@posthog/ui/features/canvas/stores/channelPaneStore";@@ -424,7 +424,7 @@ function useOpenSpaceTask(): (spaceId: string, taskId: string) => void {const setCurrentChannel = useCurrentChannelStore((s) => s.setCurrentChannel);return (spaceId, taskId) => {- keepListForNextRoute();+ keepListForRoute(spaceId);// Still scoped: the space is where the session lives, so anything that then// asks for the channel pane opens on the right one.setCurrentChannel(spaceId);diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelsSidebar.test.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelsSidebar.test.tsxindex e2f7787d66ef..5c6bf501c0ef 100644--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelsSidebar.test.tsx+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelsSidebar.test.tsx@@ -95,6 +95,7 @@ import {} from "@posthog/shared";import { ANALYTICS_EVENTS } from "@posthog/shared/analytics-events";import {+ keepListForRoute,showChannelList,useChannelPaneStore,} from "@posthog/ui/features/canvas/stores/channelPaneStore";@@ -228,6 +229,35 @@ describe("ChannelsSidebar", () => {expect(screen.queryByTestId("channel-sidebar")).toBeNull();});+ // A deep link back to the channel is a request to see it, so a latch armed+ // before an intervening channel-less route must not strand it on the list.+ it("does not hold the list for a deep link after a channel-less route", () => {+ mocks.routeChannelId = ENG.id;+ const { rerender } = renderSidebar();+ act(() => {+ showChannelList();+ keepListForRoute(ENG.id);+ });+ expect(listIsInteractive()).toBe(true);++ mocks.routeChannelId = undefined;+ rerender(+ <Theme>+ <ChannelsSidebar />+ </Theme>,+ );++ mocks.routeChannelId = ENG.id;+ rerender(+ <Theme>+ <ChannelsSidebar />+ </Theme>,+ );++ expect(listIsInteractive()).toBe(false);+ expect(screen.getByTestId("channel-sidebar").textContent).toBe(ENG.id);+ });+// A trackpad swipe reaches the panes as a horizontal wheel. Right (negative// deltaX, the platform "back" direction) leaves the channel; left returns to// the one still scoped.diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelsSidebar.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelsSidebar.tsxindex 662780a1a6f2..feaf74b78ece 100644--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelsSidebar.tsx+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelsSidebar.tsx@@ -18,7 +18,8 @@ import { useMarkChannelSeen } from "@posthog/ui/features/canvas/hooks/useMarkChaimport { useReportSpace } from "@posthog/ui/features/canvas/hooks/useReportSpace";import { useTrackChannelsSpaceViewed } from "@posthog/ui/features/canvas/hooks/useTrackChannelsSpaceViewed";import {- consumeKeepListForNextRoute,+ clearKeepListForRoute,+ shouldKeepListForRoute,showChannelList,showChannelPane,useChannelPaneStore,@@ -191,13 +192,19 @@ export function ChannelsSidebar() {enabled: channelsLayout,});useEffect(() => {- if (!channelsLayout || !routeChannelId) return;+ if (!channelsLayout) return;+ // A route with no channel ends the navigation the latch was armed for. Left+ // set, it would hold a later deep link to that channel on the list.+ if (!routeChannelId) {+ clearKeepListForRoute();+ return;+ }setCurrentChannel(routeChannelId);// Landing on a channel — a deep link, a mention, ⌘1-9 — is a request to see// it, so the slider follows the route even if the list was being browsed.// Unless the navigation said otherwise: opening a session from the list's// tree loads it without taking the tree off the screen.- if (!consumeKeepListForNextRoute()) showChannelPane();+ if (!shouldKeepListForRoute(routeChannelId)) showChannelPane();}, [channelsLayout, routeChannelId, setCurrentChannel]);// Browsing the list is view state, not navigation: you stay in the channeldiff --git a/products/desktop/packages/ui/src/features/canvas/components/WebsiteChannelHome.tsx b/products/desktop/packages/ui/src/features/canvas/components/WebsiteChannelHome.tsxindex d7eadc54d9b6..3796953bdc73 100644--- a/products/desktop/packages/ui/src/features/canvas/components/WebsiteChannelHome.tsx+++ b/products/desktop/packages/ui/src/features/canvas/components/WebsiteChannelHome.tsx@@ -1,3 +1,4 @@+import { isPersonalChannel } from "@posthog/core/canvas/channelName";import { insertTaskDedup } from "@posthog/core/tasks/taskDelete";import { ANALYTICS_EVENTS } from "@posthog/shared/analytics-events";import type { Task } from "@posthog/shared/domain-types";@@ -223,7 +224,7 @@ export function WebsiteChannelHome({ channelId }: { channelId: string }) {// The Slack-style intro pinned at the feed's start — public channels only;// the personal channel keeps the welcome empty state below.- const isPersonal = channel?.channel_type === "personal";+ const isPersonal = channel ? isPersonalChannel(channel) : false;const hasContextMd = (channelContext ?? "").trim().length > 0;// An in-flight build is spotted by its plan task in this channel's feed (by// title prefix — the only task↔context.md tie until the backend links them),diff --git a/products/desktop/packages/ui/src/features/canvas/hooks/useTaskChannels.test.tsx b/products/desktop/packages/ui/src/features/canvas/hooks/useTaskChannels.test.tsxindex 3579d580738b..f841ad650680 100644--- a/products/desktop/packages/ui/src/features/canvas/hooks/useTaskChannels.test.tsx+++ b/products/desktop/packages/ui/src/features/canvas/hooks/useTaskChannels.test.tsx@@ -22,6 +22,7 @@ function taskChannel(id: string,name: string,channelType: TaskChannel["channel_type"] = "public",+ systemRole?: TaskChannel["system_role"],): TaskChannel {return {id,@@ -29,6 +30,7 @@ function taskChannel(channel_type: channelType,starred: false,created_at: "2026-01-01T00:00:00Z",+ system_role: systemRole ?? null,};}@@ -47,24 +49,27 @@ describe("useTaskChannels", () => {});});- it("surfaces the personal channel from the list", async () => {- const personal = taskChannel("p1", "me", "personal");+ it("surfaces the personal and general channels from the list", async () => {+ const personal = taskChannel("p1", "me", "personal", "personal");+ const general = taskChannel("g1", "general", "public", "general");mockClient.getTaskChannels.mockResolvedValue([taskChannel("1", "growth"),+ general,personal,]);const { result } = renderHook(() => useTaskChannels(), { wrapper });await waitFor(() => expect(result.current.isLoading).toBe(false));- expect(result.current.channels.map((c) => c.id)).toEqual(["1", "p1"]);+ expect(result.current.channels.map((c) => c.id)).toEqual(["1", "g1", "p1"]);expect(result.current.personalChannel).toEqual({...personal,name: "personal",});+ expect(result.current.generalChannel).toEqual(general);});- it("reports loading (and no personal channel) until the list lands", () => {+ it("reports loading (and no personal or general channel) until the list lands", () => {mockClient.getTaskChannels.mockReturnValue(new Promise(() => {}));const { result } = renderHook(() => useTaskChannels(), { wrapper });@@ -72,6 +77,7 @@ describe("useTaskChannels", () => {expect(result.current.isLoading).toBe(true);expect(result.current.channels).toEqual([]);expect(result.current.personalChannel).toBeUndefined();+ expect(result.current.generalChannel).toBeUndefined();});it("updates repository links immediately while the request is pending", async () => {diff --git a/products/desktop/packages/ui/src/features/canvas/hooks/useTaskChannels.ts b/products/desktop/packages/ui/src/features/canvas/hooks/useTaskChannels.tsindex aa27b57f518d..1c8746e3d436 100644--- a/products/desktop/packages/ui/src/features/canvas/hooks/useTaskChannels.ts+++ b/products/desktop/packages/ui/src/features/canvas/hooks/useTaskChannels.ts@@ -1,4 +1,8 @@-import { channelDisplayName } from "@posthog/core/canvas/channelName";+import {+ channelDisplayName,+ isGeneralChannel,+ isPersonalChannel,+} from "@posthog/core/canvas/channelName";import type { TaskChannel } from "@posthog/shared/domain-types";import { useOptionalAuthenticatedClient } from "@posthog/ui/features/auth/authClient";import { useAuthenticatedQuery } from "@posthog/ui/hooks/useAuthenticatedQuery";@@ -16,13 +20,13 @@ export {} from "@posthog/core/canvas/channelName";/**- * Backend task channels — the single channel identity (feed, threads,- * instructions and canvases all hang off the same UUID). Listing also lazily- * provisions the requester's #me channel.+ * Backend task channels. Feed, threads, instructions and canvases all hang off+ * the same channel UUID.*/export function useTaskChannels(options?: { enabled?: boolean }): {channels: TaskChannel[];personalChannel: TaskChannel | undefined;+ generalChannel: TaskChannel | undefined;isLoading: boolean;} {const query = useAuthenticatedQuery<TaskChannel[]>(@@ -36,17 +40,26 @@ export function useTaskChannels(options?: { enabled?: boolean }): {const channels = useMemo(() =>(query.data ?? []).map((channel) =>- channel.channel_type === "personal"+ isPersonalChannel(channel)? { ...channel, name: channelDisplayName(channel.name) }: channel,),[query.data],);const personalChannel = useMemo(- () => channels.find((c) => c.channel_type === "personal"),+ () => channels.find((c) => isPersonalChannel(c)),+ [channels],+ );+ const generalChannel = useMemo(+ () => channels.find((c) => isGeneralChannel(c)),[channels],);- return { channels, personalChannel, isLoading: query.isLoading };+ return {+ channels,+ personalChannel,+ generalChannel,+ isLoading: query.isLoading,+ };}export function useUpdateTaskChannelRepositories() {diff --git a/products/desktop/packages/ui/src/features/canvas/stores/channelPaneStore.ts b/products/desktop/packages/ui/src/features/canvas/stores/channelPaneStore.tsindex 90482b225bc9..8c4d2c68671c 100644--- a/products/desktop/packages/ui/src/features/canvas/stores/channelPaneStore.ts+++ b/products/desktop/packages/ui/src/features/canvas/stores/channelPaneStore.ts@@ -23,36 +23,34 @@ export const useChannelPaneStore = create<ChannelPaneState>()((set) => ({}));/**- * Set by a navigation that is not a request to enter the space it belongs to —- * opening a session from the list's tree. The route effect that otherwise- * slides into the space consumes it.- *- * Deliberately not store state: it decides what a single navigation does, and a- * render pass is the wrong lifetime for that. Any explicit pane change below- * drops it, so it can't outlive the navigation it was set for.+ * Keyed on the channel rather than consumed on first read so it survives a+ * re-run of the same route effect (React StrictMode double-invokes mount+ * effects) and expires on its own once the route moves to another channel.*/-let keepListOnNextRoute = false;+let keepListForChannelId: string | null = null;++export function keepListForRoute(channelId: string): void {+ keepListForChannelId = channelId;+}-/** Keep the sidebar on the list through the navigation that follows. */-export function keepListForNextRoute(): void {- keepListOnNextRoute = true;+export function shouldKeepListForRoute(channelId: string): boolean {+ if (keepListForChannelId === channelId) return true;+ keepListForChannelId = null;+ return false;}-/** Reads the flag and clears it. */-export function consumeKeepListForNextRoute(): boolean {- const keep = keepListOnNextRoute;- keepListOnNextRoute = false;- return keep;+export function clearKeepListForRoute(): void {+ keepListForChannelId = null;}/** Slide back to the channel list, keeping the scoped channel as it is. */export function showChannelList(): void {- keepListOnNextRoute = false;+ keepListForChannelId = null;useChannelPaneStore.getState().setPane("list");}/** Slide to the channel pane — every channel entry point goes through here. */export function showChannelPane(): void {- keepListOnNextRoute = false;+ keepListForChannelId = null;useChannelPaneStore.getState().setPane("channel");}diff --git a/products/desktop/packages/ui/src/shell/App.tsx b/products/desktop/packages/ui/src/shell/App.tsxindex d74f0a03d961..261db483831d 100644--- a/products/desktop/packages/ui/src/shell/App.tsx+++ b/products/desktop/packages/ui/src/shell/App.tsx@@ -14,6 +14,11 @@ import { ScopeReauthPrompt } from "@posthog/ui/features/auth/components/ScopeReaimport { useAuthSession } from "@posthog/ui/features/auth/useAuthSession";import { useIsOrgAdmin } from "@posthog/ui/features/auth/useOrgRole";import { CanvasGenerationToaster } from "@posthog/ui/features/canvas/freeform/useCanvasGenerationToasts";+import {+ keepListForRoute,+ showChannelList,+} from "@posthog/ui/features/canvas/stores/channelPaneStore";+import { useSpaceTreeStore } from "@posthog/ui/features/canvas/stores/spaceTreeStore";import { AddDirectoryDialog } from "@posthog/ui/features/folder-picker/AddDirectoryDialog";import { ErrorDetailsDialog } from "@posthog/ui/features/notifications/ErrorDetailsDialog";import { OnboardingFlow } from "@posthog/ui/features/onboarding/components/OnboardingFlow";@@ -112,10 +117,15 @@ function App({ devToolbar }: AppProps) {let cancelled = false;const loadInitialRoute = async (): Promise<void> => {try {- const href = await resolveStartupLocation(+ const { href, firstRun } = await resolveStartupLocation(startupIdentity,authenticatedClient,);+ if (firstRun) {+ showChannelList();+ keepListForRoute(firstRun.generalChannelId);+ useSpaceTreeStore.getState().expandSpace(firstRun.generalChannelId);+ }router.history.replace(href);rememberStartupLocation(startupIdentity, href);await router.load();diff --git a/products/desktop/packages/ui/src/shell/startupLocation.test.ts b/products/desktop/packages/ui/src/shell/startupLocation.test.tsindex 3e9da0cc7185..6fbe95b7be60 100644--- a/products/desktop/packages/ui/src/shell/startupLocation.test.ts+++ b/products/desktop/packages/ui/src/shell/startupLocation.test.ts@@ -1,38 +1,141 @@import { stateStorage } from "@posthog/ui/shell/rendererStorage";import { afterEach, describe, expect, it, vi } from "vitest";-import { resolveStartupLocation } from "./startupLocation";+import {+ primeStartupProvision,+ resolveStartupLocation,+} from "./startupLocation";++const personal = {+ id: "me-id",+ name: "me",+ channel_type: "personal" as const,+ starred: false,+ created_at: "2026-01-01T00:00:00Z",+ system_role: "personal" as const,+};+const general = {+ id: "general-id",+ name: "general",+ channel_type: "public" as const,+ starred: false,+ created_at: "2026-01-01T00:00:00Z",+ system_role: "general" as const,+};describe("startup location", () => {afterEach(() => vi.restoreAllMocks());- it("restores the exact last location", async () => {+ it("restores the exact last location without provisioning", async () => {vi.spyOn(stateStorage, "getItem").mockResolvedValue("/code");+ const client = { provisionDefaultTaskChannels: vi.fn() };++ await expect(resolveStartupLocation("project", client)).resolves.toEqual({+ href: "/code",+ firstRun: null,+ });+ expect(client.provisionDefaultTaskChannels).not.toHaveBeenCalled();+ });++ it("lands a first-run user on the general space home", async () => {+ vi.spyOn(stateStorage, "getItem").mockResolvedValue(null);const client = {- getTaskChannels: vi.fn(),+ provisionDefaultTaskChannels: vi.fn().mockResolvedValue({+ channels: [personal, general],+ personal_created: true,+ general_created: true,+ }),};- await expect(resolveStartupLocation("project", client)).resolves.toBe(- "/code",- );- expect(client.getTaskChannels).not.toHaveBeenCalled();+ await expect(resolveStartupLocation("project", client)).resolves.toEqual({+ href: "/website/general-id",+ firstRun: { generalChannelId: "general-id" },+ });});- it("opens a new task in me when there is no saved location", async () => {+ it("skips the first-run treatment when the server created nothing", async () => {+ // A reinstall loses the saved location while the spaces survive.vi.spyOn(stateStorage, "getItem").mockResolvedValue(null);const client = {- getTaskChannels: vi.fn().mockResolvedValue([- {- id: "me-id",- name: "me",- channel_type: "personal",- starred: false,- },- ]),+ provisionDefaultTaskChannels: vi.fn().mockResolvedValue({+ channels: [personal, general],+ personal_created: false,+ general_created: false,+ }),};- await expect(resolveStartupLocation("project", client)).resolves.toBe(- "/website/me-id/new",+ await expect(resolveStartupLocation("project", client)).resolves.toEqual({+ href: "/website/general-id",+ firstRun: null,+ });+ });++ it("carries an install from before provisioning back to where it was", async () => {+ // The old key is the only trace of an install that predates the default+ // spaces, and it still has to land where the user left off.+ vi.spyOn(stateStorage, "getItem").mockImplementation(async (key) =>+ key.includes(":v2:") ? null : "/website/old-space",);- expect(client.getTaskChannels).toHaveBeenCalledOnce();+ const removeItem = vi+ .spyOn(stateStorage, "removeItem")+ .mockResolvedValue(undefined);+ const client = {+ provisionDefaultTaskChannels: vi.fn().mockResolvedValue({+ channels: [personal, general],+ personal_created: true,+ general_created: true,+ }),+ };++ await expect(resolveStartupLocation("project", client)).resolves.toEqual({+ href: "/website/old-space",+ firstRun: null,+ });+ expect(client.provisionDefaultTaskChannels).toHaveBeenCalledOnce();+ expect(removeItem).toHaveBeenCalledWith("startup-location:project");+ });++ it("opens anyway when provisioning is unavailable", async () => {+ // A server that cannot provision yet must not cost someone their location.+ vi.spyOn(stateStorage, "getItem").mockImplementation(async (key) =>+ key.includes(":v2:") ? null : "/website/old-space",+ );+ const removeItem = vi+ .spyOn(stateStorage, "removeItem")+ .mockResolvedValue(undefined);+ const client = {+ provisionDefaultTaskChannels: vi.fn().mockRejectedValue(new Error("404")),+ };++ await expect(resolveStartupLocation("project", client)).resolves.toEqual({+ href: "/website/old-space",+ firstRun: null,+ });+ expect(removeItem).not.toHaveBeenCalled();+ });++ it("consumes a primed provisioning result exactly once", async () => {+ vi.spyOn(stateStorage, "getItem").mockResolvedValue(null);+ const client = { provisionDefaultTaskChannels: vi.fn() };+ primeStartupProvision({+ channels: [personal, general],+ personal_created: true,+ general_created: false,+ });++ await expect(resolveStartupLocation("project", client)).resolves.toEqual({+ href: "/website/general-id",+ firstRun: { generalChannelId: "general-id" },+ });+ expect(client.provisionDefaultTaskChannels).not.toHaveBeenCalled();++ const again = {+ provisionDefaultTaskChannels: vi.fn().mockResolvedValue({+ channels: [personal, general],+ personal_created: false,+ general_created: false,+ }),+ };+ await resolveStartupLocation("project", again);+ expect(again.provisionDefaultTaskChannels).toHaveBeenCalledOnce();});});diff --git a/products/desktop/packages/ui/src/shell/startupLocation.ts b/products/desktop/packages/ui/src/shell/startupLocation.tsindex dbc5d6ff0f80..15f76dda3ba7 100644--- a/products/desktop/packages/ui/src/shell/startupLocation.ts+++ b/products/desktop/packages/ui/src/shell/startupLocation.ts@@ -1,21 +1,69 @@import type { PostHogAPIClient } from "@posthog/api-client/posthog-client";+import { isGeneralChannel } from "@posthog/core/canvas/channelName";+import type { ProvisionedTaskChannels } from "@posthog/shared/domain-types";import { stateStorage } from "@posthog/ui/shell/rendererStorage";-type StartupLocationClient = Pick<PostHogAPIClient, "getTaskChannels">;+type StartupLocationClient = Pick<+ PostHogAPIClient,+ "provisionDefaultTaskChannels"+>;-const storageKey = (identity: string): string => `startup-location:${identity}`;+const storageKey = (identity: string): string =>+ `startup-location:v2:${identity}`;+/** Where installs from before the default spaces existed kept their location. */+const legacyStorageKey = (identity: string): string =>+ `startup-location:${identity}`;++interface StartupLocation {+ href: string;+ firstRun: { generalChannelId: string } | null;+}++let primedProvision: ProvisionedTaskChannels | null = null;++/**+ * Whoever provisions first consumes the created flags, so a flow that provisions+ * before the app mounts has to hand its result over rather than let startup+ * provision again and read false flags.+ */+export function primeStartupProvision(result: ProvisionedTaskChannels): void {+ primedProvision = result;+}export async function resolveStartupLocation(identity: string,client: StartupLocationClient,-): Promise<string> {+): Promise<StartupLocation> {const saved = await stateStorage.getItem(storageKey(identity));- if (saved) return saved;- const personal = (await client.getTaskChannels()).find(- (channel) => channel.channel_type === "personal",+ if (saved) return { href: saved, firstRun: null };++ const legacy = await stateStorage.getItem(legacyStorageKey(identity));+ if (legacy) {+ // Provisioning does not get to decide whether someone who was already using+ // the app can open it. Keeping the old key retries on the next launch.+ try {+ await client.provisionDefaultTaskChannels();+ void stateStorage.removeItem(legacyStorageKey(identity));+ } catch {}+ return { href: legacy, firstRun: null };+ }++ const provisioned =+ primedProvision ?? (await client.provisionDefaultTaskChannels());+ primedProvision = null;+ const general = provisioned.channels.find((channel) =>+ isGeneralChannel(channel),);- if (!personal) throw new Error("Personal channel was not provisioned");- return `/website/${personal.id}/new`;+ if (!general) throw new Error("#general was not provisioned");++ // A reinstall or a new machine loses only the saved location, so the created+ // flags decide this rather than the absence of one.+ const isFirstRun =+ provisioned.personal_created || provisioned.general_created;+ return {+ href: `/website/${general.id}`,+ firstRun: isFirstRun ? { generalChannelId: general.id } : null,+ };}export function rememberStartupLocation(identity: string, href: string): void {diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex e231ec1d324c..3a5c1b8c2317 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -1290,7 +1290,7 @@ def create_and_run_task(enforce_self_driving_pr_quota(team, report_id=signal_report_id, stage="task_create")channel = _visible_channel(channel_id, team.id, user_id) if channel_id is not None else Noneif channel is None and not internal and origin_product not in TEAM_READABLE_ORIGIN_PRODUCTS:- channel = _ensure_personal_channel(team.id, user_id)+ channel = _ensure_personal_channel(team.id, user_id)[0]task = Task.create_and_run(team=team,title=title,@@ -1413,7 +1413,7 @@ def create_task_without_run("""if channel is None:channel = (- None if origin_product in TEAM_READABLE_ORIGIN_PRODUCTS else _ensure_personal_channel(team.id, user_id)+ None if origin_product in TEAM_READABLE_ORIGIN_PRODUCTS else _ensure_personal_channel(team.id, user_id)[0])task = Task.create_without_run(team=team,@@ -5052,7 +5052,7 @@ def create_task(and not validated_data.get("internal", False)and validated_data["origin_product"] not in TEAM_READABLE_ORIGIN_PRODUCTS):- validated_data["channel"] = _ensure_personal_channel(team_id, user_id)+ validated_data["channel"] = _ensure_personal_channel(team_id, user_id)[0]validated_data["client_provenance"] = client_provenancewarm_branch_provided = "branch" in validated_datawarm_branch = validated_data.pop("branch", None)@@ -6454,13 +6454,33 @@ def send_cancel(run_id: str | UUID, *, auth_token: str | None = None):# --- Channels & task threads ---+_CHANNEL_NAME_SEPARATORS = re.compile(r"[^a-z0-9]+")++def normalize_channel_name(name: str) -> str:- """Slack-style channel key: lowercase, whitespace collapsed to dashes.+ """Slack-style channel key: lowercase letters, digits and dashes, with every run of+ anything else becoming a single dash. Must stay in step with ``normalizeChannelName``+ in ``channelName.ts``, or a name is stored in a shape the field cannot produce.- Channels are resolved by name from client-side surfaces (folder names), so the- stored key must be canonical for the (team, name) uniqueness to mean anything.+ Returns "" for a name with nothing usable in it, which callers reject."""- return re.sub(r"\s+", "-", name.strip().lower())[:128]+ return _CHANNEL_NAME_SEPARATORS.sub("-", name.strip().lower()).strip("-")[:128].strip("-")+++PERSONAL_SPACE_NAMES = frozenset({Channel.PERSONAL_CHANNEL_NAME, Channel.PERSONAL_CHANNEL_LABEL})+RESERVED_CHANNEL_NAMES = PERSONAL_SPACE_NAMES | {Channel.GENERAL_CHANNEL_NAME}+++def is_personal_space_name(name: str) -> bool:+ """Reads as somebody's private space. Surfaces holding a bare name decide the lock and+ the label from it, so a shared space under one of these presents itself as private."""+ return normalize_channel_name(name) in PERSONAL_SPACE_NAMES+++def is_reserved_channel_name(name: str) -> bool:+ """Reads as one of the system spaces. Renaming a space to the general name would also+ make it permanently unrenameable, since the guards fall back to the name."""+ return normalize_channel_name(name) in RESERVED_CHANNEL_NAMESdef _set_channel_star(channel_id: UUID, team_id: int, user_id: int, *, starred: bool) -> None:@@ -6479,6 +6499,7 @@ def _channel_to_dto(channel: Channel, *, starred: bool = False) -> contracts.Chaid=channel.id,name=channel.name,channel_type=channel.channel_type,+ system_role=channel.system_role,github_integration=channel.github_integration_id,repositories=channel.repositories,created_at=channel.created_at,@@ -6493,20 +6514,46 @@ def _team_channels(team_id: int) -> QuerySet[Channel]:return Channel.objects.for_team(team_id)-def _ensure_personal_channel(team_id: int, user_id: int) -> Channel:- # select_related so _channel_to_dto doesn't lazy-load created_by per call.+def _ensure_system_channel(+ team_id: int,+ user_id: int | None,+ *,+ role: str,+ owner_lookup: dict[str, Any],+ legacy_lookup: dict[str, Any],+ create_defaults: dict[str, Any],+) -> tuple[Channel, bool]:+ """``legacy_lookup`` must be covered by a unique constraint; that is what makes the+ IntegrityError fallback safe under concurrent provisioning calls."""+ created = Falsechannels = _team_channels(team_id).select_related("created_by")- lookup = {- "team_id": team_id,- "created_by_id": user_id,- "channel_type": Channel.ChannelType.PERSONAL,- "deleted": False,- }- try:- channel, _ = channels.get_or_create(**lookup, defaults={"name": Channel.PERSONAL_CHANNEL_NAME})- except IntegrityError:- channel = channels.get(**lookup)- return channel+ channel = channels.filter(system_role=role, deleted=False, **owner_lookup).first()+ if channel is None:+ channel = channels.filter(**legacy_lookup).first()+ if channel is None:+ try:+ channel, created = channels.get_or_create(+ team_id=team_id, **legacy_lookup, defaults={**create_defaults, "system_role": role}+ )+ except IntegrityError:+ channel, created = channels.get(team_id=team_id, **legacy_lookup), False+ if created and channel.channel_type == Channel.ChannelType.PUBLIC:+ _emit_channel_created(channel, user_id)+ if channel.system_role != role:+ channel.system_role = role+ channel.save(update_fields=["system_role"])+ return channel, created+++def _ensure_personal_channel(team_id: int, user_id: int) -> tuple[Channel, bool]:+ return _ensure_system_channel(+ team_id,+ user_id,+ role=Channel.SystemRole.PERSONAL,+ owner_lookup={"created_by_id": user_id},+ legacy_lookup={"created_by_id": user_id, "channel_type": Channel.ChannelType.PERSONAL, "deleted": False},+ create_defaults={"name": Channel.PERSONAL_CHANNEL_NAME},+ )def ensure_personal_channel_id(team_id: int, user_id: int) -> UUID:@@ -6514,19 +6561,49 @@ def ensure_personal_channel_id(team_id: int, user_id: int) -> UUID:For callers outside a request (Temporal activities) that need somewhere to file a task."""- return _ensure_personal_channel(team_id, user_id).id+ return _ensure_personal_channel(team_id, user_id)[0].id+++def _ensure_general_channel(team_id: int, user_id: int | None) -> tuple[Channel, bool]:+ return _ensure_system_channel(+ team_id,+ user_id,+ role=Channel.SystemRole.GENERAL,+ owner_lookup={},+ legacy_lookup={+ "name": Channel.GENERAL_CHANNEL_NAME,+ "channel_type": Channel.ChannelType.PUBLIC,+ "deleted": False,+ },+ create_defaults={"created_by_id": user_id},+ )+++def _is_general_channel(channel: Channel) -> bool:+ """Must match ``isGeneralChannel`` in ``channelName.ts``: a row with no role but the+ general name is still the team's general space."""+ if channel.system_role is not None:+ return channel.system_role == Channel.SystemRole.GENERAL+ return channel.channel_type == Channel.ChannelType.PUBLIC and channel.name == Channel.GENERAL_CHANNEL_NAME+++def provision_default_channels(team_id: int, user_id: int) -> contracts.ProvisionedChannelsDTO:+ """The created flags let a client distinguish "this call provisioned the space"+ (first user in the team) from inheriting one that already existed."""+ _, personal_created = _ensure_personal_channel(team_id, user_id)+ _, general_created = _ensure_general_channel(team_id, user_id)+ return contracts.ProvisionedChannelsDTO(+ channels=list_channels(team_id, user_id),+ personal_created=personal_created,+ general_created=general_created,+ )def list_channels(team_id: int, user_id: int | None) -> list[contracts.ChannelDTO]:- """All live public channels plus the requester's personal channel (provisioned lazily),- personal first, then by name. ``starred`` reflects the requester's stars."""- channels: list[Channel] = []- if user_id is not None:- channels.append(_ensure_personal_channel(team_id, user_id))- channels.extend(- Channel.objects.filter(team_id=team_id, channel_type=Channel.ChannelType.PUBLIC, deleted=False)- .select_related("created_by")- .order_by("name")+ """Every space the requester can see, by name. ``starred`` reflects the requester's+ stars. Creates nothing, which is what lets a caller gate on a space existing."""+ channels = list(+ _team_channels(team_id).select_related("created_by").filter(Channel.visible_to_q(user_id)).order_by("name"))starred_ids: set = (set(ChannelStar.objects.filter(team_id=team_id, user_id=user_id).values_list("channel_id", flat=True))@@ -6559,27 +6636,33 @@ def _emit_channel_created(channel: Channel, user_id: int | None) -> None:def resolve_channel(team_id: int, user_id: int | None, *, name: str, star: bool) -> contracts.ChannelDTO | None:"""Resolve-or-create a public channel by (normalized) name. ``None`` for empty names.+ The general name resolves the team's general space, which cannot then be renamed away.Emits a ``channel_created`` feed message the first time a channel is created, and (unless``star`` is false) stars the channel for whoever created it. Resolving a channel thatalready exists leaves the requester's star alone — only creation stars."""normalized = normalize_channel_name(name)if not normalized:return None- created = False- try:- channel, created = Channel.objects.select_related("created_by").get_or_create(- team_id=team_id,- name=normalized,- channel_type=Channel.ChannelType.PUBLIC,- deleted=False,- defaults={"created_by_id": user_id},- )- except IntegrityError:- channel = Channel.objects.select_related("created_by").get(- team_id=team_id, name=normalized, channel_type=Channel.ChannelType.PUBLIC, deleted=False- )- if created:- _emit_channel_created(channel, user_id)+ if normalized == Channel.GENERAL_CHANNEL_NAME:+ # Resolving by name here would produce a second, unstamped general space, so+ # every path that can create one goes through the role-aware helper.+ channel, created = _ensure_general_channel(team_id, user_id)+ else:+ created = False+ try:+ channel, created = Channel.objects.select_related("created_by").get_or_create(+ team_id=team_id,+ name=normalized,+ channel_type=Channel.ChannelType.PUBLIC,+ deleted=False,+ defaults={"created_by_id": user_id},+ )+ except IntegrityError:+ channel = Channel.objects.select_related("created_by").get(+ team_id=team_id, name=normalized, channel_type=Channel.ChannelType.PUBLIC, deleted=False+ )+ if created:+ _emit_channel_created(channel, user_id)if user_id is None:starred = Falseelif not created:@@ -6609,6 +6692,8 @@ def update_channel(return "not_found"if name is not None:return "personal"+ if name is not None and _is_general_channel(channel):+ return "general"update_fields: list[str] = []if name is not None:normalized = normalize_channel_name(name)@@ -6636,6 +6721,8 @@ def delete_channel(channel_id: str | UUID, team_id: int, user_id: int | None) ->return "not_found"if channel.channel_type == Channel.ChannelType.PERSONAL:return "personal" if channel.created_by_id == user_id else "not_found"+ if _is_general_channel(channel):+ return "general"if channel.tasks.filter(deleted=False).exists() or channel.canvases.filter(deleted=False).exists():return "not_empty"channel.deleted = Truediff --git a/products/tasks/backend/facade/contracts.py b/products/tasks/backend/facade/contracts.pyindex e63990078c18..d00a6c8f41fc 100644--- a/products/tasks/backend/facade/contracts.py+++ b/products/tasks/backend/facade/contracts.py@@ -204,6 +204,14 @@ class ChannelDTO:created_at: datetimecreated_by: "TaskUserBasicInfo | None" = Nonestarred: bool = False+ system_role: str | None = None+++@dataclass(frozen=True)+class ProvisionedChannelsDTO:+ channels: list[ChannelDTO]+ personal_created: bool+ general_created: bool@dataclass(frozen=True)diff --git a/products/tasks/backend/migrations/0102_channel_system_role.py b/products/tasks/backend/migrations/0102_channel_system_role.pynew file mode 100644index 000000000000..654229fefaa0--- /dev/null+++ b/products/tasks/backend/migrations/0102_channel_system_role.py@@ -0,0 +1,20 @@+# Generated by Django 5.2.17 on 2026-08-17 23:32++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [("tasks", "0101_agentpeermessage")]++ operations = [+ migrations.AddField(+ model_name="channel",+ name="system_role",+ field=models.CharField(+ blank=True,+ choices=[("personal", "Personal"), ("general", "General")],+ max_length=16,+ null=True,+ ),+ ),+ ]diff --git a/products/tasks/backend/migrations/max_migration.txt b/products/tasks/backend/migrations/max_migration.txtindex 7b404c4d0330..e23fe6916a34 100644--- a/products/tasks/backend/migrations/max_migration.txt+++ b/products/tasks/backend/migrations/max_migration.txt@@ -1 +1 @@-0101_agentpeermessage+0102_channel_system_rolediff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.pyindex 987095e30a05..d39ebc458e6f 100644--- a/products/tasks/backend/models.py+++ b/products/tasks/backend/models.py@@ -79,13 +79,25 @@ def resolve_schema(schema: type[BaseModel] | dict) -> dict:class Channel(TeamScopedRootMixin):"""A shared feed of tasks (rendered as "#<name>" in PostHog Desktop). Every task isowned by the channel it was kicked off in. Each user gets one private "personal"- channel ("#me") per team, provisioned lazily on first channel list."""+ channel ("#me") per team, and each team gets a public "general" channel, Slack-style.+ Listing creates neither; provisioning does. The general channel can't be renamed or+ deleted."""class ChannelType(models.TextChoices):PUBLIC = "public", "Public"PERSONAL = "personal", "Personal"+ class SystemRole(models.TextChoices):+ """Identifies a channel as one of the two system-provisioned spaces, independent+ of its (renameable) name and its (visibility-only) channel_type."""++ PERSONAL = "personal", "Personal"+ GENERAL = "general", "General"+PERSONAL_CHANNEL_NAME = "me"+ # The label the personal channel is shown under, reserved so no other space can wear it.+ PERSONAL_CHANNEL_LABEL = "personal"+ GENERAL_CHANNEL_NAME = "general"@classmethoddef visible_to_q(cls, user_id: int | None, *, relation: Literal["", "channel", "task__channel"] = "") -> models.Q:@@ -113,6 +125,10 @@ class Channel(TeamScopedRootMixin):team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, related_name="+", db_constraint=False)name = models.CharField(max_length=128)channel_type = models.CharField(max_length=16, choices=ChannelType, default=ChannelType.PUBLIC)+ # Null for ordinary channels. No dedicated unique constraint: provisioning still creates/adopts+ # the general channel by its fixed name, so task_channel_team_name_public_unique (team, name)+ # remains the race guard; task_channel_team_user_personal_unique guards the personal role likewise.+ system_role = models.CharField(max_length=16, null=True, blank=True, choices=SystemRole.choices)created_by = models.ForeignKey("posthog.User", on_delete=models.SET_NULL, null=True, blank=True, related_name="+", db_constraint=False)diff --git a/products/tasks/backend/presentation/serializers.py b/products/tasks/backend/presentation/serializers.pyindex 7e9dfd5b7fd7..34a5d75c5b6f 100644--- a/products/tasks/backend/presentation/serializers.py+++ b/products/tasks/backend/presentation/serializers.py@@ -1690,6 +1690,16 @@ class ChannelSerializer(DataclassSerializer):"""Response shape for a task channel, read from a frozen ``ChannelDTO``."""created_by = TaskUserBasicInfoSerializer(allow_null=True, required=False)+ system_role = serializers.ChoiceField(+ choices=tasks_facade.Channel.SystemRole.choices,+ allow_null=True,+ read_only=True,+ help_text=(+ "Identifies this channel as one of the two system-provisioned spaces "+ "('personal' for the user's own #me space, 'general' for the team's "+ "shared #general space). Null for an ordinary channel."+ ),+ )class Meta:dataclass = ChannelDTO@@ -1702,9 +1712,28 @@ class ChannelSerializer(DataclassSerializer):"created_at","created_by","starred",+ "system_role",]+class ProvisionedChannelsSerializer(serializers.Serializer):+ """The requester's default channels, plus whether this call is what created them."""++ channels = ChannelSerializer(+ many=True,+ help_text="The full channel list after provisioning, same shape as the list endpoint.",+ )+ personal_created = serializers.BooleanField(+ help_text="Whether this call created the requester's personal #me channel."+ )+ general_created = serializers.BooleanField(+ help_text=(+ "Whether this call created the team's shared #general channel. True only for "+ "the first user to provision it, so clients can branch first-user setup on it."+ )+ )++class ChannelDeleteConflictSerializer(serializers.Serializer):detail = serializers.CharField(help_text="Why the space cannot be deleted.")@@ -1724,6 +1753,13 @@ class ChannelWriteSerializer(serializers.Serializer):),)+ def validate_name(self, value: str) -> str:+ # "general" resolves the team's general space here, so only the personal names are+ # refused.+ if tasks_facade.is_personal_space_name(value):+ raise serializers.ValidationError("That name is reserved for private spaces. Pick another name.")+ return value+class ChannelUpdateSerializer(serializers.Serializer):name = serializers.CharField(@@ -1744,6 +1780,11 @@ class ChannelUpdateSerializer(serializers.Serializer):help_text="GitHub repositories inherited by new tasks in this channel.",)+ def validate_name(self, value: str) -> str:+ if tasks_facade.is_reserved_channel_name(value):+ raise serializers.ValidationError("That name is reserved for a default space. Pick another name.")+ return value+def validate_github_integration(self, value):if value is not None and value.team_id != self.context["team_id"]:raise serializers.ValidationError("GitHub integration must belong to this project")diff --git a/products/tasks/backend/presentation/views/channels_api.py b/products/tasks/backend/presentation/views/channels_api.pyindex 40cf66a08b3f..6c195c7f8edc 100644--- a/products/tasks/backend/presentation/views/channels_api.py+++ b/products/tasks/backend/presentation/views/channels_api.py@@ -30,6 +30,7 @@ from products.tasks.backend.presentation.serializers import (ChannelStarWriteSerializer,ChannelUpdateSerializer,ChannelWriteSerializer,+ ProvisionedChannelsSerializer,TaskActivityMarkReadResponseSerializer,TaskActivityMarkReadSerializer,TaskActivityPageSerializer,@@ -57,9 +58,10 @@ PUBLISH_INSTRUCTIONS_SCHEMA_KWARGS: dict[str, Any] = {class ChannelViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):"""- API for task channels — the shared feeds tasks are kicked off in. Listing lazily- provisions the requester's personal "#me" channel; creation is resolve-or-create- by normalized name so clients can map channel-like surfaces onto backend channels.+ API for task channels — the shared feeds tasks are kicked off in. The+ provision_defaults action get-or-creates the requester's personal "#me" channel and+ the team's shared "#general" channel; creation is resolve-or-create by normalized+ name so clients can map channel-like surfaces onto backend channels."""authentication_classes = [@@ -76,6 +78,7 @@ class ChannelViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):scope_object_read_actions = ["list", "retrieve", "instructions", "instructions_versions", "context_generation"]scope_object_write_actions = ["create",+ "provision_defaults","partial_update","destroy","publish_instructions",@@ -98,19 +101,47 @@ class ChannelViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):@extend_schema(responses={200: OpenApiResponse(response=ChannelSerializer(many=True), description="List of channels")},summary="List channels",- description="All live public channels plus the requester's personal #me channel (created on first list).",+ description=(+ "All live public channels plus the requester's personal #me channel when it exists, "+ "sorted by name. Listing does not provision; call provision_defaults to create the "+ "default channels."+ ),)def list(self, request, *args, **kwargs):channels = tasks_facade.list_channels(self.team_id, self._user_id())return Response(ChannelSerializer(channels, many=True).data)+ @extend_schema(+ request=None,+ responses={+ 200: OpenApiResponse(+ response=ProvisionedChannelsSerializer,+ description="The channel list plus which default channels this call created",+ )+ },+ summary="Provision default channels",+ description=(+ "Get-or-create the requester's personal #me channel and the team's shared #general "+ "channel, and report which of the two this call created. Idempotent."+ ),+ )+ @action(methods=["POST"], detail=False, url_path="provision_defaults")+ def provision_defaults(self, request: Request, **kwargs) -> Response:+ user_id = self._user_id()+ if user_id is None:+ raise PermissionDenied("Provisioning default channels requires a user.")+ provisioned = tasks_facade.provision_default_channels(self.team_id, user_id)+ return Response(ProvisionedChannelsSerializer(provisioned).data)+@extend_schema(request=ChannelWriteSerializer,responses={200: ChannelSerializer},summary="Resolve or create a public channel",description=("Returns the existing public channel with the (normalized) name, creating it if needed. "- "A channel created here is starred for the requester unless star is false."+ "A channel created here is starred for the requester unless star is false. "+ "The general name returns the team's general space; names that read as a private "+ 'space ("me", "personal") are rejected.'),)def create(self, request, **kwargs):@@ -139,6 +170,8 @@ class ChannelViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):raise NotFound()if result == "personal":raise PermissionDenied("Personal channels cannot be renamed")+ if result == "general":+ raise PermissionDenied("The general space can't be renamed")if result == "invalid_name":return Response({"detail": "Invalid channel name"}, status=status.HTTP_400_BAD_REQUEST)if result == "name_taken":@@ -164,6 +197,8 @@ class ChannelViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):raise NotFound()if result == "personal":raise PermissionDenied("Your private space cannot be deleted")+ if result == "general":+ raise PermissionDenied("The general space can't be deleted")if result == "not_empty":return Response({"detail": "Remove this space's tasks and canvases before deleting it."},diff --git a/products/tasks/backend/tests/test_channels_api.py b/products/tasks/backend/tests/test_channels_api.pyindex fe9a48dd4513..829e9d433857 100644--- a/products/tasks/backend/tests/test_channels_api.py+++ b/products/tasks/backend/tests/test_channels_api.py@@ -9,7 +9,9 @@ from parameterized import parameterizedfrom rest_framework import statusfrom rest_framework.test import APIClient-from posthog.models import Integration, Organization, OrganizationMembership, Team, User+from posthog.models import Integration, Organization, OrganizationMembership, PersonalAPIKey, Team, User+from posthog.models.personal_api_key import hash_key_value+from posthog.models.utils import generate_random_token_personalfrom products.tasks.backend.exceptions import ComputeBillingLimitErrorfrom products.tasks.backend.facade import api as tasks_facade@@ -36,32 +38,62 @@ class ChannelsAPITestCase(TestCase):self.client = APIClient()self.client.force_authenticate(self.user)+ def _provision(self, client=None) -> dict:+ response = (client or self.client).post(f"{self._channels_url()}provision_defaults/")+ assert response.status_code == status.HTTP_200_OK, response.content+ return response.json()+def _channels_url(self) -> str:return f"/api/projects/{self.team.id}/task_channels/"def _tasks_url(self) -> str:return f"/api/projects/{self.team.id}/tasks/"- def test_list_provisions_personal_channel(self):- response = self.client.get(self._channels_url())- self.assertEqual(response.status_code, status.HTTP_200_OK)- personal = [c for c in response.json() if c["channel_type"] == "personal"]+ def test_provision_creates_personal_channel(self):+ provisioned = self._provision()+ self.assertTrue(provisioned["personal_created"])+ personal = [c for c in provisioned["channels"] if c["channel_type"] == "personal"]self.assertEqual(len(personal), 1)self.assertEqual(personal[0]["name"], "me")self.assertEqual(personal[0]["created_by"]["id"], self.user.id)- # Listing again reuses the same personal channel- again = self.client.get(self._channels_url()).json()+ again = self._provision()+ self.assertFalse(again["personal_created"])self.assertEqual(- [c["id"] for c in again if c["channel_type"] == "personal"],+ [c["id"] for c in again["channels"] if c["channel_type"] == "personal"],[personal[0]["id"]],)+ @parameterized.expand(+ [+ ("write_scope", "task:write", status.HTTP_200_OK),+ ("read_scope", "task:read", status.HTTP_403_FORBIDDEN),+ ]+ )+ def test_provisioning_over_a_scoped_token_needs_task_write(self, _name, scope, expected_status):+ # Desktop authenticates with an OAuth bearer token, so an action missing from the+ # write-scope list is refused before its scopes are even read.+ key = generate_random_token_personal()+ PersonalAPIKey.objects.create(+ user=self.user, label=f"provisioning {scope}", secure_value=hash_key_value(key), scopes=[scope]+ )++ response = APIClient().post(+ f"{self._channels_url()}provision_defaults/", headers={"authorization": f"Bearer {key}"}+ )+ self.assertEqual(response.status_code, expected_status, response.content)++ def test_list_does_not_provision(self):+ response = self.client.get(self._channels_url())+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json(), [])+ self.assertFalse(Channel.objects.for_team(self.team.id).exists())+def test_personal_channels_are_per_user(self):- mine = self.client.get(self._channels_url()).json()+ mine = self._provision()["channels"]other_client = APIClient()other_client.force_authenticate(self.other_user)- theirs = other_client.get(self._channels_url()).json()+ theirs = self._provision(other_client)["channels"]my_personal = [c["id"] for c in mine if c["channel_type"] == "personal"]their_personal = [c["id"] for c in theirs if c["channel_type"] == "personal"]@@ -76,7 +108,7 @@ class ChannelsAPITestCase(TestCase):self.assertEqual(second.json()["id"], first.json()["id"])def test_personal_channel_cannot_be_renamed_or_deleted(self):- self.client.get(self._channels_url())+ self._provision()# Direct ORM reads in tests bypass the DRF-set team context, so opt out# of the fail-closed scoping explicitly (see test_presence.py).personal = Channel.objects.unscoped().get(team=self.team, channel_type=Channel.ChannelType.PERSONAL)@@ -85,11 +117,136 @@ class ChannelsAPITestCase(TestCase):delete = self.client.delete(f"{self._channels_url()}{personal.id}/")self.assertEqual(delete.status_code, status.HTTP_403_FORBIDDEN)+ def test_provision_creates_general_channel_once(self):+ first = self._provision()+ self.assertTrue(first["general_created"])+ general = [c for c in first["channels"] if c["system_role"] == "general"]+ self.assertEqual(len(general), 1)+ self.assertEqual(general[0]["name"], "general")+ self.assertEqual(general[0]["channel_type"], "public")+ self.assertFalse(general[0]["starred"])++ other_client = APIClient()+ other_client.force_authenticate(self.other_user)+ again = self._provision(other_client)+ self.assertFalse(again["general_created"])+ self.assertEqual(+ [c["id"] for c in again["channels"] if c["system_role"] == "general"],+ [general[0]["id"]],+ )++ @parameterized.expand(+ [+ ("rename", lambda client, url: client.patch(url, {"name": "not-general"})),+ ("delete", lambda client, url: client.delete(url)),+ ]+ )+ def test_general_channel_cannot_be_renamed_or_deleted(self, _name, act):+ self._provision()+ general = Channel.objects.unscoped().get(team=self.team, system_role=Channel.SystemRole.GENERAL)+ response = act(self.client, f"{self._channels_url()}{general.id}/")+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)++ def test_legacy_personal_channel_is_stamped_with_system_role_on_provision(self):+ # A row from before the role existed is identified by channel_type alone.+ legacy = Channel.objects.for_team(self.team.id).create(+ team_id=self.team.id,+ created_by=self.user,+ name=Channel.PERSONAL_CHANNEL_NAME,+ channel_type=Channel.ChannelType.PERSONAL,+ )++ provisioned = self._provision()+ self.assertFalse(provisioned["personal_created"])+ personal = [c for c in provisioned["channels"] if c["channel_type"] == "personal"]+ self.assertEqual([c["id"] for c in personal], [str(legacy.id)])+ self.assertEqual(personal[0]["system_role"], "personal")++ legacy.refresh_from_db()+ self.assertEqual(legacy.system_role, Channel.SystemRole.PERSONAL)++ def test_legacy_general_channel_is_adopted_and_stamped_on_provision(self):+ legacy = Channel.objects.for_team(self.team.id).create(+ team_id=self.team.id,+ created_by=self.user,+ name=Channel.GENERAL_CHANNEL_NAME,+ channel_type=Channel.ChannelType.PUBLIC,+ )++ provisioned = self._provision()+ self.assertFalse(provisioned["general_created"])+ general = [c for c in provisioned["channels"] if c["system_role"] == "general"]+ self.assertEqual([c["id"] for c in general], [str(legacy.id)])++ legacy.refresh_from_db()+ self.assertEqual(legacy.system_role, Channel.SystemRole.GENERAL)++ @parameterized.expand(+ [+ ("hash_prefix", "#growth", "growth"),+ ("spaces", "Growth Ideas", "growth-ideas"),+ ("punctuation", "team.core!", "team-core"),+ ("surrounding_separators", " --growth-- ", "growth"),+ ]+ )+ def test_a_created_space_takes_the_name_desktop_showed(self, _name, sent, stored):+ # The field normalizes as the user types, so the server has to agree with it.+ response = self.client.post(self._channels_url(), {"name": sent})+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)+ self.assertEqual(response.json()["name"], stored)++ def test_a_name_with_nothing_usable_in_it_is_rejected(self):+ response = self.client.post(self._channels_url(), {"name": "###"})+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)++ def test_creating_a_space_named_general_resolves_the_system_space(self):+ created = self.client.post(self._channels_url(), {"name": "General"})+ self.assertEqual(created.status_code, status.HTTP_200_OK)+ self.assertEqual(created.json()["system_role"], "general")++ provisioned = self._provision()+ self.assertFalse(provisioned["general_created"])+ self.assertEqual(+ [c["id"] for c in provisioned["channels"] if c["system_role"] == "general"],+ [created.json()["id"]],+ )++ @parameterized.expand([("stored_name", "Me"), ("display_label", " personal ")])+ def test_a_shared_space_cannot_claim_a_personal_space_name(self, _name, name):+ response = self.client.post(self._channels_url(), {"name": name})+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)++ @parameterized.expand([("personal_name", "me"), ("personal_label", "personal"), ("general", "General")])+ def test_a_space_cannot_be_renamed_to_a_reserved_name(self, _name, name):+ channel_id = self.client.post(self._channels_url(), {"name": "growth"}).json()["id"]++ response = self.client.patch(f"{self._channels_url()}{channel_id}/", {"name": name})+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)++ @parameterized.expand(+ [+ ("rename", lambda client, url: client.patch(url, {"name": "not-general"})),+ ("delete", lambda client, url: client.delete(url)),+ ]+ )+ def test_unstamped_general_channel_cannot_be_renamed_or_deleted(self, _name, act):+ # Desktop reads an unstamped row named "general" as the team's general space, so+ # the server has to protect it on the same terms.+ legacy = Channel.objects.for_team(self.team.id).create(+ team_id=self.team.id,+ created_by=self.user,+ name=Channel.GENERAL_CHANNEL_NAME,+ channel_type=Channel.ChannelType.PUBLIC,+ )++ response = act(self.client, f"{self._channels_url()}{legacy.id}/")+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)+@patch("posthog.models.integration.github.GitHubIntegration.list_all_cached_repositories")def test_cannot_configure_someone_elses_personal_channel_repositories(self, list_repositories):list_repositories.return_value = [{"full_name": "posthog/posthog"}]integration = Integration.objects.create(team=self.team, kind="github", integration_id="1", config={})- self.client.get(self._channels_url())+ self._provision()personal = Channel.objects.unscoped().get(team=self.team, channel_type=Channel.ChannelType.PERSONAL)other_client = APIClient()@@ -224,7 +381,7 @@ class ChannelsAPITestCase(TestCase):])def test_task_in_private_space_stays_private(self, _name: str, select_channel: bool):- self.client.get(self._channels_url())+ self._provision()personal = Channel.objects.unscoped().get(team=self.team, channel_type=Channel.ChannelType.PERSONAL)payload = {"title": "Secret", "description": "mine"}if select_channel:@@ -243,7 +400,7 @@ class ChannelsAPITestCase(TestCase):)def test_team_readable_origin_does_not_widen_private_space(self):- self.client.get(self._channels_url())+ self._provision()personal = Channel.objects.unscoped().get(team=self.team, channel_type=Channel.ChannelType.PERSONAL)task = Task.objects.create(team=self.team,@@ -278,7 +435,7 @@ class ChannelsAPITestCase(TestCase):def test_task_controller_can_move_public_task_to_private_space(self):public_space_id = self.client.post(self._channels_url(), {"name": "shared"}).json()["id"]private_space_id = next(- space["id"] for space in self.client.get(self._channels_url()).json() if space["channel_type"] == "personal"+ space["id"] for space in self._provision()["channels"] if space["channel_type"] == "personal")task = self.client.post(self._tasks_url(),@@ -327,7 +484,7 @@ class ChannelsAPITestCase(TestCase):self.assertFalse(Channel.objects.unscoped().get(id=channel_id).deleted)def test_cannot_file_task_into_someone_elses_personal_channel(self):- self.client.get(self._channels_url())+ self._provision()personal = Channel.objects.unscoped().get(team=self.team, channel_type=Channel.ChannelType.PERSONAL)other_client = APIClient()other_client.force_authenticate(self.other_user)@@ -936,9 +1093,8 @@ class ChannelFeedMessageAPITestCase(TestCase):self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)def test_personal_channel_feed_is_owner_only(self):- # Listing provisions the requester's personal channel.- mine = self.client.get(self._channels_url()).json()- personal_id = next(c["id"] for c in mine if c["channel_type"] == "personal")+ mine = self.client.post(f"{self._channels_url()}provision_defaults/").json()+ personal_id = next(c["id"] for c in mine["channels"] if c["channel_type"] == "personal")self.client.post(self._feed_url(personal_id),{"event": "context_created", "payload": {"context_name": "me"}},diff --git a/products/tasks/backend/tests/test_facade.py b/products/tasks/backend/tests/test_facade.pyindex a5285a5e8e81..961416eb787e 100644--- a/products/tasks/backend/tests/test_facade.py+++ b/products/tasks/backend/tests/test_facade.py@@ -859,6 +859,12 @@ class TestFacadeReadsAndMappers(TestCase):),[first],)+ # Callers outside Desktop file tasks through here, so an unstamped system space+ # would escape from this path.+ self.assertEqual(+ Channel.objects.unscoped().get(id=first).system_role,+ Channel.SystemRole.PERSONAL,+ )@patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")def test_create_wizard_cloud_run_seeds_pending_user_message(self, _mock_workflow):diff --git a/products/tasks/frontend/generated/api.schemas.ts b/products/tasks/frontend/generated/api.schemas.tsindex be79ec5e4de4..b1a79f565493 100644--- a/products/tasks/frontend/generated/api.schemas.ts+++ b/products/tasks/frontend/generated/api.schemas.ts@@ -1061,6 +1061,17 @@ export interface TaskActivityMarkReadResponseApi {unread_count: number}+/**+ * * `personal` - Personal+ * * `general` - General+ */+export type SystemRoleEnumApi = (typeof SystemRoleEnumApi)[keyof typeof SystemRoleEnumApi]++export const SystemRoleEnumApi = {+ Personal: 'personal',+ General: 'general',+} as const+/*** Response shape for a task channel, read from a frozen ``ChannelDTO``.*/@@ -1074,6 +1085,11 @@ export interface ChannelDTOApi {created_at: stringcreated_by?: TaskUserBasicInfoApi | nullstarred?: boolean+ /** Identifies this channel as one of the two system-provisioned spaces ('personal' for the user's own #me space, 'general' for the team's shared #general space). Null for an ordinary channel.+ *+ * * `personal` - Personal+ * * `general` - General */+ readonly system_role: SystemRoleEnumApi | null}export interface PaginatedChannelDTOListApi {@@ -1243,6 +1259,18 @@ export interface ChannelStarWriteApi {starred: boolean}+/**+ * The requester's default channels, plus whether this call is what created them.+ */+export interface ProvisionedChannelsApi {+ /** The full channel list after provisioning, same shape as the list endpoint. */+ channels: ChannelDTOApi[]+ /** Whether this call created the requester's personal #me channel. */+ personal_created: boolean+ /** Whether this call created the team's shared #general channel. True only for the first user to provision it, so clients can branch first-user setup on it. */+ general_created: boolean+}+/*** Response shape for one @-mention of the requester in a task's thread.*/diff --git a/products/tasks/frontend/generated/api.ts b/products/tasks/frontend/generated/api.tsindex 28afee7ed8f4..2c4295175e18 100644--- a/products/tasks/frontend/generated/api.ts+++ b/products/tasks/frontend/generated/api.ts@@ -52,6 +52,7 @@ import type {PatchedTaskRunUpdateApi,PatchedTaskWriteApi,PinnedTaskIdsResponseApi,+ ProvisionedChannelsApi,RepositoryReadinessResponseApi,SandboxComputePricingApi,SandboxCustomImageBuildApi,@@ -736,7 +737,7 @@ export const getTaskChannelsListUrl = (projectId: string, params?: TaskChannelsL}/**- * All live public channels plus the requester's personal #me channel (created on first list).+ * All live public channels plus the requester's personal #me channel when it exists, sorted by name. Listing does not provision; call provision_defaults to create the default channels.* @summary List channels*/export const taskChannelsList = async (@@ -755,7 +756,7 @@ export const getTaskChannelsCreateUrl = (projectId: string) => {}/**- * Returns the existing public channel with the (normalized) name, creating it if needed. A channel created here is starred for the requester unless star is false.+ * Returns the existing public channel with the (normalized) name, creating it if needed. A channel created here is starred for the requester unless star is false. The general name returns the team's general space; names that read as a private space ("me", "personal") are rejected.* @summary Resolve or create a public channel*/export const taskChannelsCreate = async (@@ -836,9 +837,10 @@ export const getTaskChannelsRetrieveUrl = (projectId: string, id: string) => {}/**- * API for task channels — the shared feeds tasks are kicked off in. Listing lazily- * provisions the requester's personal "#me" channel; creation is resolve-or-create- * by normalized name so clients can map channel-like surfaces onto backend channels.+ * API for task channels — the shared feeds tasks are kicked off in. The+ * provision_defaults action get-or-creates the requester's personal "#me" channel and+ * the team's shared "#general" channel; creation is resolve-or-create by normalized+ * name so clients can map channel-like surfaces onto backend channels.* @summary Get a channel*/export const taskChannelsRetrieve = async (@@ -857,9 +859,10 @@ export const getTaskChannelsPartialUpdateUrl = (projectId: string, id: string) =}/**- * API for task channels — the shared feeds tasks are kicked off in. Listing lazily- * provisions the requester's personal "#me" channel; creation is resolve-or-create- * by normalized name so clients can map channel-like surfaces onto backend channels.+ * API for task channels — the shared feeds tasks are kicked off in. The+ * provision_defaults action get-or-creates the requester's personal "#me" channel and+ * the team's shared "#general" channel; creation is resolve-or-create by normalized+ * name so clients can map channel-like surfaces onto backend channels.* @summary Rename a public channel*/export const taskChannelsPartialUpdate = async (@@ -881,9 +884,10 @@ export const getTaskChannelsDestroyUrl = (projectId: string, id: string) => {}/**- * API for task channels — the shared feeds tasks are kicked off in. Listing lazily- * provisions the requester's personal "#me" channel; creation is resolve-or-create- * by normalized name so clients can map channel-like surfaces onto backend channels.+ * API for task channels — the shared feeds tasks are kicked off in. The+ * provision_defaults action get-or-creates the requester's personal "#me" channel and+ * the team's shared "#general" channel; creation is resolve-or-create by normalized+ * name so clients can map channel-like surfaces onto backend channels.* @summary Delete a public channel*/export const taskChannelsDestroy = async (projectId: string, id: string, options?: RequestInit): Promise<void> => {@@ -898,9 +902,10 @@ export const getTaskChannelsContextGenerationRetrieveUrl = (projectId: string, i}/**- * API for task channels — the shared feeds tasks are kicked off in. Listing lazily- * provisions the requester's personal "#me" channel; creation is resolve-or-create- * by normalized name so clients can map channel-like surfaces onto backend channels.+ * API for task channels — the shared feeds tasks are kicked off in. The+ * provision_defaults action get-or-creates the requester's personal "#me" channel and+ * the team's shared "#general" channel; creation is resolve-or-create by normalized+ * name so clients can map channel-like surfaces onto backend channels.* @summary Get the channel's CONTEXT.md generation task*/export const taskChannelsContextGenerationRetrieve = async (@@ -919,9 +924,10 @@ export const getTaskChannelsContextGenerationUpdateUrl = (projectId: string, id:}/**- * API for task channels — the shared feeds tasks are kicked off in. Listing lazily- * provisions the requester's personal "#me" channel; creation is resolve-or-create- * by normalized name so clients can map channel-like surfaces onto backend channels.+ * API for task channels — the shared feeds tasks are kicked off in. The+ * provision_defaults action get-or-creates the requester's personal "#me" channel and+ * the team's shared "#general" channel; creation is resolve-or-create by normalized+ * name so clients can map channel-like surfaces onto backend channels.* @summary Set or clear the channel's CONTEXT.md generation task*/export const taskChannelsContextGenerationUpdate = async (@@ -1006,9 +1012,10 @@ export const getTaskChannelsInstructionsDestroyUrl = (projectId: string, id: str}/**- * API for task channels — the shared feeds tasks are kicked off in. Listing lazily- * provisions the requester's personal "#me" channel; creation is resolve-or-create- * by normalized name so clients can map channel-like surfaces onto backend channels.+ * API for task channels — the shared feeds tasks are kicked off in. The+ * provision_defaults action get-or-creates the requester's personal "#me" channel and+ * the team's shared "#general" channel; creation is resolve-or-create by normalized+ * name so clients can map channel-like surfaces onto backend channels.* @summary Delete channel instructions*/export const taskChannelsInstructionsDestroy = async (@@ -1027,9 +1034,10 @@ export const getTaskChannelsInstructionsVersionsRetrieveUrl = (projectId: string}/**- * API for task channels — the shared feeds tasks are kicked off in. Listing lazily- * provisions the requester's personal "#me" channel; creation is resolve-or-create- * by normalized name so clients can map channel-like surfaces onto backend channels.+ * API for task channels — the shared feeds tasks are kicked off in. The+ * provision_defaults action get-or-creates the requester's personal "#me" channel and+ * the team's shared "#general" channel; creation is resolve-or-create by normalized+ * name so clients can map channel-like surfaces onto backend channels.* @summary List channel instruction versions*/export const taskChannelsInstructionsVersionsRetrieve = async (@@ -1051,9 +1059,10 @@ export const getTaskChannelsStarCreateUrl = (projectId: string, id: string) => {}/**- * API for task channels — the shared feeds tasks are kicked off in. Listing lazily- * provisions the requester's personal "#me" channel; creation is resolve-or-create- * by normalized name so clients can map channel-like surfaces onto backend channels.+ * API for task channels — the shared feeds tasks are kicked off in. The+ * provision_defaults action get-or-creates the requester's personal "#me" channel and+ * the team's shared "#general" channel; creation is resolve-or-create by normalized+ * name so clients can map channel-like surfaces onto backend channels.* @summary Star or unstar a channel for the requesting user*/export const taskChannelsStarCreate = async (@@ -1070,6 +1079,24 @@ export const taskChannelsStarCreate = async (})}+export const getTaskChannelsProvisionDefaultsCreateUrl = (projectId: string) => {+ return `/api/projects/${projectId}/task_channels/provision_defaults/`+}++/**+ * Get-or-create the requester's personal #me channel and the team's shared #general channel, and report which of the two this call created. Idempotent.+ * @summary Provision default channels+ */+export const taskChannelsProvisionDefaultsCreate = async (+ projectId: string,+ options?: RequestInit+): Promise<ProvisionedChannelsApi> => {+ return apiMutator<ProvisionedChannelsApi>(getTaskChannelsProvisionDefaultsCreateUrl(projectId), {+ ...options,+ method: 'POST',+ })+}+export const getTaskMentionsListUrl = (projectId: string, params?: TaskMentionsListParams) => {const normalizedParams = new URLSearchParams()diff --git a/products/tasks/frontend/generated/api.zod.ts b/products/tasks/frontend/generated/api.zod.tsindex 1ccaf685302b..e15bcce3bab5 100644--- a/products/tasks/frontend/generated/api.zod.ts+++ b/products/tasks/frontend/generated/api.zod.ts@@ -901,7 +901,7 @@ export const TaskActivityMarkReadCreateBody = /* @__PURE__ */ zod.describe('Request body for clearing the unread flag on specific tasks.')/**- * Returns the existing public channel with the (normalized) name, creating it if needed. A channel created here is starred for the requester unless star is false.+ * Returns the existing public channel with the (normalized) name, creating it if needed. A channel created here is starred for the requester unless star is false. The general name returns the team's general space; names that read as a private space ("me", "personal") are rejected.* @summary Resolve or create a public channel*/export const taskChannelsCreateBodyNameMax = 128@@ -951,9 +951,10 @@ export const TaskChannelsFeedCreateBody = /* @__PURE__ */ zod.describe("Request body for posting a system announcement into a channel's feed.")/**- * API for task channels — the shared feeds tasks are kicked off in. Listing lazily- * provisions the requester's personal "#me" channel; creation is resolve-or-create- * by normalized name so clients can map channel-like surfaces onto backend channels.+ * API for task channels — the shared feeds tasks are kicked off in. The+ * provision_defaults action get-or-creates the requester's personal "#me" channel and+ * the team's shared "#general" channel; creation is resolve-or-create by normalized+ * name so clients can map channel-like surfaces onto backend channels.* @summary Rename a public channel*/export const taskChannelsPartialUpdateBodyNameMax = 128@@ -980,9 +981,10 @@ export const TaskChannelsPartialUpdateBody = /* @__PURE__ */ zod.object({})/**- * API for task channels — the shared feeds tasks are kicked off in. Listing lazily- * provisions the requester's personal "#me" channel; creation is resolve-or-create- * by normalized name so clients can map channel-like surfaces onto backend channels.+ * API for task channels — the shared feeds tasks are kicked off in. The+ * provision_defaults action get-or-creates the requester's personal "#me" channel and+ * the team's shared "#general" channel; creation is resolve-or-create by normalized+ * name so clients can map channel-like surfaces onto backend channels.* @summary Set or clear the channel's CONTEXT.md generation task*/export const TaskChannelsContextGenerationUpdateBody = /* @__PURE__ */ zod@@ -1041,9 +1043,10 @@ export const TaskChannelsInstructionsPartialUpdateBody = /* @__PURE__ */ zod.describe('Request body for publishing a new instructions version.')/**- * API for task channels — the shared feeds tasks are kicked off in. Listing lazily- * provisions the requester's personal "#me" channel; creation is resolve-or-create- * by normalized name so clients can map channel-like surfaces onto backend channels.+ * API for task channels — the shared feeds tasks are kicked off in. The+ * provision_defaults action get-or-creates the requester's personal "#me" channel and+ * the team's shared "#general" channel; creation is resolve-or-create by normalized+ * name so clients can map channel-like surfaces onto backend channels.* @summary Star or unstar a channel for the requesting user*/export const TaskChannelsStarCreateBody = /* @__PURE__ */ zoddiff --git a/products/tasks/mcp/tools.yaml b/products/tasks/mcp/tools.yamlindex 6050fa6c2fe7..7f027ab0926c 100644--- a/products/tasks/mcp/tools.yaml+++ b/products/tasks/mcp/tools.yaml@@ -309,6 +309,9 @@ tools:task-channels-partial-update:operation: task_channels_partial_updateenabled: false+ task-channels-provision-defaults-create:+ operation: task_channels_provision_defaults_create+ enabled: falsetask-channels-star-create:operation: task_channels_star_createenabled: falsediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 26647a20d32d..2bba8a1c02e7 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -16493,6 +16493,18 @@ export namespace Schemas {role_at_organization?: string | null;}+ /**+ * * `personal` - Personal+ * * `general` - General+ */+ export type SystemRoleEnum = typeof SystemRoleEnum[keyof typeof SystemRoleEnum];+++ export const SystemRoleEnum = {+ Personal: 'personal',+ General: 'general',+ } as const;+/*** Response shape for a task channel, read from a frozen ``ChannelDTO``.*/@@ -16506,6 +16518,11 @@ export namespace Schemas {created_at: string;created_by?: TaskUserBasicInfo | null;starred?: boolean;+ /** Identifies this channel as one of the two system-provisioned spaces ('personal' for the user's own #me space, 'general' for the team's shared #general space). Null for an ordinary channel.+ *+ * * `personal` - Personal+ * * `general` - General */+ readonly system_role: SystemRoleEnum | null;}export interface ChannelDeleteConflict {@@ -66740,6 +66757,18 @@ export namespace Schemas {password: string;}+ /**+ * The requester's default channels, plus whether this call is what created them.+ */+ export interface ProvisionedChannels {+ /** The full channel list after provisioning, same shape as the list endpoint. */+ channels: ChannelDTO[];+ /** Whether this call created the requester's personal #me channel. */+ personal_created: boolean;+ /** Whether this call created the team's shared #general channel. True only for the first user to provision it, so clients can branch first-user setup on it. */+ general_created: boolean;+ }+/*** * `waiting` - Waiting* * `issuing` - Issuingdiff --git a/services/mcp/src/generated/tasks/api.ts b/services/mcp/src/generated/tasks/api.tsindex 0977537e1b19..0266f238d243 100644--- a/services/mcp/src/generated/tasks/api.ts+++ b/services/mcp/src/generated/tasks/api.ts@@ -735,7 +735,7 @@ export const LoopsRunsRetrieveQueryParams = /* @__PURE__ */ zod.object({})/**- * All live public channels plus the requester's personal #me channel (created on first list).+ * All live public channels plus the requester's personal #me channel when it exists, sorted by name. Listing does not provision; call provision_defaults to create the default channels.* @summary List channels*/export const TaskChannelsListParams = /* @__PURE__ */ zod.object({@@ -752,7 +752,7 @@ export const TaskChannelsListQueryParams = /* @__PURE__ */ zod.object({})/**- * Returns the existing public channel with the (normalized) name, creating it if needed. A channel created here is starred for the requester unless star is false.+ * Returns the existing public channel with the (normalized) name, creating it if needed. A channel created here is starred for the requester unless star is false. The general name returns the team's general space; names that read as a private space ("me", "personal") are rejected.* @summary Resolve or create a public channel*/export const TaskChannelsCreateParams = /* @__PURE__ */ zod.object({@@ -783,9 +783,10 @@ export const TaskChannelsCreateBody = /* @__PURE__ */ zod.describe('Request body for creating (resolve-or-create) or renaming a public channel.')/**- * API for task channels — the shared feeds tasks are kicked off in. Listing lazily- * provisions the requester's personal "#me" channel; creation is resolve-or-create- * by normalized name so clients can map channel-like surfaces onto backend channels.+ * API for task channels — the shared feeds tasks are kicked off in. The+ * provision_defaults action get-or-creates the requester's personal "#me" channel and+ * the team's shared "#general" channel; creation is resolve-or-create by normalized+ * name so clients can map channel-like surfaces onto backend channels.* @summary Get a channel*/export const TaskChannelsRetrieveParams = /* @__PURE__ */ zod.object({