: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): open the first session when a space is first provisioned (#86811)
Adam Bowker511e47ab3e68
diff --git a/products/desktop/packages/api-client/src/posthog-client.ts b/products/desktop/packages/api-client/src/posthog-client.tsindex d51548cd459a..82a0199c6b41 100644--- a/products/desktop/packages/api-client/src/posthog-client.ts+++ b/products/desktop/packages/api-client/src/posthog-client.ts@@ -2790,8 +2790,8 @@ export class PostHogAPIClient {// Task channels + threads. Not in the generated OpenAPI client yet, so these// go through the raw fetcher like the desktop file-system endpoints above.- // List backend task channels: all public channels plus the requester's- // personal "#me" channel (provisioned lazily server-side on first list).+ // All public channels plus the requester's #me. Creates nothing: startup provisions the+ // default spaces, which is what lets a caller gate on one already existing.async getTaskChannels(): Promise<TaskChannel[]> {const teamId = await this.getTeamId();const urlPath = `/api/projects/${teamId}/task_channels/`;@@ -2860,6 +2860,24 @@ export class PostHogAPIClient {return (await response.json()) as ProvisionedTaskChannels;}+ /**+ * Opens the first-run agent session in #general. Reads the company's homepage, so it takes a+ * few seconds; callers fire it without awaiting. Resolves false when no session was started,+ * which is the normal path while the spaces rollout has not reached this user.+ */+ async startOnboardingSession(): Promise<string | null> {+ const teamId = await this.getTeamId();+ const urlPath = `/api/projects/${teamId}/task_channels/onboarding_session/`;+ const response = await this.api.fetcher.fetch({+ method: "post",+ url: new URL(`${this.api.baseUrl}${urlPath}`),+ path: urlPath,+ });+ if (!response.ok) return null;+ const data = (await response.json()) as { task_id?: string | null };+ return data.task_id ?? null;+ }+async updateTaskChannelRepositories(id: string,githubIntegration: number | null,diff --git a/products/desktop/packages/ui/src/features/auth/SignInCard.tsx b/products/desktop/packages/ui/src/features/auth/SignInCard.tsxindex b6820d07ae95..39648fff1bf5 100644--- a/products/desktop/packages/ui/src/features/auth/SignInCard.tsx+++ b/products/desktop/packages/ui/src/features/auth/SignInCard.tsx@@ -8,6 +8,7 @@ interface SignInCardProps {hogMessage: string;subtitle: string;onAuthInitiated?: (region: CloudRegion) => void;+ /** Defaults to the dev build, which is the only place a local instance is worth offering. */includeDevRegion?: boolean;}@@ -16,7 +17,7 @@ export function SignInCard({hogMessage,subtitle,onAuthInitiated,- includeDevRegion = false,+ includeDevRegion = import.meta.env.DEV,}: SignInCardProps) {return (<Flex direction="column" gap="4">diff --git a/products/desktop/packages/ui/src/features/auth/components/AuthScreen.tsx b/products/desktop/packages/ui/src/features/auth/components/AuthScreen.tsxindex 1d3d8c75cc8d..8f3411660446 100644--- a/products/desktop/packages/ui/src/features/auth/components/AuthScreen.tsx+++ b/products/desktop/packages/ui/src/features/auth/components/AuthScreen.tsx@@ -1,8 +1,8 @@import { happyHog } from "@posthog/ui/assets/hedgehogs";+import { SignInCard } from "@posthog/ui/features/auth/SignInCard";import { FullScreenLayout } from "@posthog/ui/primitives/FullScreenLayout";import { Callout, Flex } from "@radix-ui/themes";import { useAuthStateValue } from "../store";-import { SignInCard } from "./SignInCard";export function AuthScreen() {const sessionEndReason = useAuthStateValue((state) => state.sessionEndReason);diff --git a/products/desktop/packages/ui/src/features/auth/components/SignInCard.tsx b/products/desktop/packages/ui/src/features/auth/components/SignInCard.tsxdeleted file mode 100644index 57fb8637adbf..000000000000--- a/products/desktop/packages/ui/src/features/auth/components/SignInCard.tsx+++ /dev/null@@ -1,13 +0,0 @@-import type { CloudRegion } from "@posthog/shared";-import { SignInCard as BaseSignInCard } from "../SignInCard";--interface SignInCardProps {- hogSrc: string;- hogMessage: string;- subtitle: string;- onAuthInitiated?: (region: CloudRegion) => void;-}--export function SignInCard(props: SignInCardProps) {- return <BaseSignInCard {...props} includeDevRegion={import.meta.env.DEV} />;-}diff --git a/products/desktop/packages/ui/src/features/browser-tabs/BrowserTabStrip.tsx b/products/desktop/packages/ui/src/features/browser-tabs/BrowserTabStrip.tsxindex b3260b257cb1..56d5e7e860a8 100644--- a/products/desktop/packages/ui/src/features/browser-tabs/BrowserTabStrip.tsx+++ b/products/desktop/packages/ui/src/features/browser-tabs/BrowserTabStrip.tsx@@ -732,9 +732,8 @@ export function BrowserTabStrip() {navigate({ to: "/new", state });return;}- // #me is provisioned lazily server-side with the channel list (same source- // the sidebar's #me row reads); fall back to the new-task screen while it- // hasn't loaded yet.+ // Startup provisions #me, so its absence here means the list has not loaded rather+ // than that there is nothing to open.const personal = channels.find((c) => c.channelType === "personal");if (personal) {navigate({diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelsList.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelsList.tsxindex e066a80d7064..070bdb1ca7b2 100644--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelsList.tsx+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelsList.tsx@@ -1371,8 +1371,7 @@ const PersonalChannelRow = memo(function PersonalChannelRow({const { channels } = useChannels();const { ensureChannelId, openPersonalChannel } = useOpenPersonalChannel();- // Personal channels are provisioned lazily server-side when the channel list- // is fetched; `undefined` just means the list hasn't loaded it yet.+ // Startup provisions #me, so `undefined` means the list has not loaded yet.const meChannel = channels.find((c) => c.channelType === "personal");const isUnread = useIsChannelUnread()(meChannel?.id);const unreadSessions = useUnreadSessionCount()(meChannel?.id);diff --git a/products/desktop/packages/ui/src/features/canvas/components/channelFeedDisplay.ts b/products/desktop/packages/ui/src/features/canvas/components/channelFeedDisplay.tsindex 310432565ef8..24ddabda7ccf 100644--- a/products/desktop/packages/ui/src/features/canvas/components/channelFeedDisplay.ts+++ b/products/desktop/packages/ui/src/features/canvas/components/channelFeedDisplay.ts@@ -2,11 +2,13 @@ import type { Task } from "@posthog/shared/domain-types";import type { ChannelFeedSystemMessage } from "@posthog/ui/features/canvas/hooks/useChannelFeedMessages";// Injected context wrappers a prompt may carry (Slack thread history, a-// channel's CONTEXT.md, canvas instructions, saved personalization). The feed-// shows what the user actually asked, so these are stripped and the timeline-// renders them as their own collapsible surfaces.+// channel's CONTEXT.md, canvas instructions, saved personalization, the+// onboarding session's whole brief). The feed shows what the user actually+// asked, so these are stripped and the timeline renders them as their own+// collapsible surfaces. Nobody asked for the onboarding brief, so it has no+// surface of its own and the card falls back to its title.const CONTEXT_BLOCK_REGEX =- /<(slack_thread_context|channel_context|canvas_generation_instructions|user_custom_instructions)\b[^>]*>[\s\S]*?<\/\1>/g;+ /<(slack_thread_context|channel_context|canvas_generation_instructions|user_custom_instructions|onboarding_brief)\b[^>]*>[\s\S]*?<\/\1>/g;export function stripContextBlocks(text: string): string {return textdiff --git a/products/desktop/packages/ui/src/features/canvas/hooks/useDashboards.ts b/products/desktop/packages/ui/src/features/canvas/hooks/useDashboards.tsindex a60ea0ab4900..620349c2aecb 100644--- a/products/desktop/packages/ui/src/features/canvas/hooks/useDashboards.ts+++ b/products/desktop/packages/ui/src/features/canvas/hooks/useDashboards.ts@@ -242,8 +242,8 @@ export function useDashboardMutations() {/*** Create an empty canvas in a channel, enter edit mode, and navigate to it.- * `opts.channelId` overrides the bound channel, for callers whose channel is- * provisioned lazily and so has no id at render time (the "me" row).+ * `opts.channelId` overrides the bound channel, for callers whose channel has no id at+ * render time because the list has not loaded (the "me" row).*/export function useCreateAndOpenDashboard(channelId: string | undefined,diff --git a/products/desktop/packages/ui/src/features/onboarding/components/OnboardingFlow.tsx b/products/desktop/packages/ui/src/features/onboarding/components/OnboardingFlow.tsxindex cce35c2c5143..ec2baf785759 100644--- a/products/desktop/packages/ui/src/features/onboarding/components/OnboardingFlow.tsx+++ b/products/desktop/packages/ui/src/features/onboarding/components/OnboardingFlow.tsx@@ -35,8 +35,8 @@ import { shipIt } from "@posthog/ui/primitives/confetti";import { FullScreenLayout } from "@posthog/ui/primitives/FullScreenLayout";import { openTaskInput } from "@posthog/ui/router/useOpenTask";import { track } from "@posthog/ui/shell/analytics";+import { firstRun } from "@posthog/ui/shell/firstRun";import { logger } from "@posthog/ui/shell/logger";-import { primeStartupProvision } from "@posthog/ui/shell/startupLocation";import { useHostCapabilities } from "@posthog/ui/shell/useHostCapabilities";import { Button, Flex } from "@radix-ui/themes";import { useQueryClient } from "@tanstack/react-query";@@ -93,15 +93,9 @@ export function OnboardingFlow() {// Best-effort. The response also seeds the channel cache that the first-run// landing reads moments later.const assignRepoToSpaces = async (): Promise<void> => {- if (!apiClient) return;- // Prime the in-flight promise before the first await so startup consumes- // this result instead of provisioning again and reading false created- // flags. This runs synchronously before completeOnboarding mounts the main- // app, which is what wins the race against startup's own provisioning.- const provisionPromise = apiClient.provisionDefaultTaskChannels();- if (startupIdentity)- primeStartupProvision(startupIdentity, provisionPromise);- const provisioned = await provisionPromise;+ if (!apiClient || !startupIdentity) return;+ const provisioned = await firstRun(startupIdentity, apiClient).provisioned;+ if (!provisioned) return;// Set before the entry exists: setQueryData builds the query from the defaults in// place at that moment, and an unmarked entry survives clearAuthScopedQueries and// hands the next account these channels. Every mounted read of this key is alreadydiff --git a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatThread.tsx b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatThread.tsxindex 57cfb0a1d7d6..339c20e45d79 100644--- a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatThread.tsx+++ b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatThread.tsx@@ -99,6 +99,10 @@ import { isPlanItem } from "@posthog/ui/features/sessions/components/new-thread/import { extractCanvasInstructions } from "@posthog/ui/features/sessions/components/session-update/canvasInstructions";import { extractChannelContext } from "@posthog/ui/features/sessions/components/session-update/channelContext";import { extractCustomInstructions } from "@posthog/ui/features/sessions/components/session-update/customInstructions";+import {+ extractOnboardingBrief,+ ONBOARDING_BRIEF_LABEL,+} from "@posthog/ui/features/sessions/components/session-update/onboardingBrief";import {hasFileMentions,MentionChip,@@ -534,14 +538,24 @@ function UserBubble({() => extractCustomInstructions(afterCanvasInstructions),[afterCanvasInstructions],);+ const afterCustomInstructions = customInstructions+ ? customInstructions.stripped+ : afterCanvasInstructions;+ const onboardingBrief = useMemo(+ () => extractOnboardingBrief(afterCustomInstructions),+ [afterCustomInstructions],+ );const displayContent = collapsePiSkillInvocation(- customInstructions ? customInstructions.stripped : afterCanvasInstructions,+ onboardingBrief ? onboardingBrief.stripped : afterCustomInstructions,);const showChannelContextTag = !!channelContext && bluebirdEnabled;const showCanvasInstructionsTag = !!canvasInstructions && bluebirdEnabled;// Provenance is never flag-gated: a peer message must not read as the user's.const showHeaderChips =- !!peerAgentMessage || showChannelContextTag || showCanvasInstructionsTag;+ !!peerAgentMessage ||+ showChannelContextTag ||+ showCanvasInstructionsTag ||+ !!onboardingBrief;const taskId = useSessionTaskId();const openChannelContextInSplit = usePanelLayoutStore((s) => s.openChannelContextInSplit,@@ -583,6 +597,12 @@ function UserBubble({label={`From agent: ${peerAgentMessage.senderTaskTitle}`}/>)}+ {onboardingBrief && (+ <MentionChip+ icon={<FileText size={12} />}+ label={ONBOARDING_BRIEF_LABEL}+ />+ )}{showChannelContextTag && channelContext && (<MentionChipicon={<FileText size={12} />}@@ -618,53 +638,56 @@ function UserBubble({)}</ChatMessageHeader>)}- <ChatBubble- align={peerAgentMessage ? "start" : "end"}- variant={peerAgentMessage ? "outline" : "default"}- className={cn(- "rounded-lg ring-(--gray-11) ring-0 ring-inset transition-shadow",- keyboardFocused && "ring-[3px]",- )}- >- <ChatBubbleContent>- <div- ref={textRef}- className={cn(- "[&_p]:my-0",- !isExpanded && "max-h-[5lh] overflow-hidden",- // Fade the clamped text out at the bottom so it reads as "continues below". Only- // when actually overflowing — a short collapsed message shouldn't fade. The mask is- // paint-only, so it doesn't affect the overflow measurement above.- !isExpanded &&- isOverflowing &&- "[mask-image:linear-gradient(to_bottom,black_45%,transparent)]",- )}- >- {containsFileMentions ? (- parseFileMentions(displayContent)- ) : (- <ChatMarkdown content={displayContent} />- )}- </div>- {attachments.length > 0 && !containsFileMentions && (- <div className="mt-1.5">- <UserMessageAttachments attachments={attachments} />- </div>+ {/* The brief is the whole message, so stripping it leaves nothing to put in a bubble. */}+ {(!!displayContent || attachments.length > 0) && (+ <ChatBubble+ align={peerAgentMessage ? "start" : "end"}+ variant={peerAgentMessage ? "outline" : "default"}+ className={cn(+ "rounded-lg ring-(--gray-11) ring-0 ring-inset transition-shadow",+ keyboardFocused && "ring-[3px]",)}- {isOverflowing && (- <button- type="button"- onClick={() => setIsExpanded((v) => !v)}- className="mt-1 flex items-center gap-0.5 text-muted-foreground text-sm hover:text-foreground"+ >+ <ChatBubbleContent>+ <div+ ref={textRef}+ className={cn(+ "[&_p]:my-0",+ !isExpanded && "max-h-[5lh] overflow-hidden",+ // Fade the clamped text out at the bottom so it reads as "continues below". Only+ // when actually overflowing — a short collapsed message shouldn't fade. The mask is+ // paint-only, so it doesn't affect the overflow measurement above.+ !isExpanded &&+ isOverflowing &&+ "[mask-image:linear-gradient(to_bottom,black_45%,transparent)]",+ )}>- Show {isExpanded ? "less" : "more"}- <CaretDown- className={cn("size-3", isExpanded && "rotate-180")}- />- </button>- )}- </ChatBubbleContent>- </ChatBubble>+ {containsFileMentions ? (+ parseFileMentions(displayContent)+ ) : (+ <ChatMarkdown content={displayContent} />+ )}+ </div>+ {attachments.length > 0 && !containsFileMentions && (+ <div className="mt-1.5">+ <UserMessageAttachments attachments={attachments} />+ </div>+ )}+ {isOverflowing && (+ <button+ type="button"+ onClick={() => setIsExpanded((v) => !v)}+ className="mt-1 flex items-center gap-0.5 text-muted-foreground text-sm hover:text-foreground"+ >+ Show {isExpanded ? "less" : "more"}+ <CaretDown+ className={cn("size-3", isExpanded && "rotate-180")}+ />+ </button>+ )}+ </ChatBubbleContent>+ </ChatBubble>+ )}{timestamp != null && (<ChatMessageFooter className="items-center gap-1 opacity-0 transition-opacity group-hover:opacity-100">{formatTimestamp(timestamp)}diff --git a/products/desktop/packages/ui/src/features/sessions/components/session-update/UserMessage.test.tsx b/products/desktop/packages/ui/src/features/sessions/components/session-update/UserMessage.test.tsxindex 25fc245ffd53..d7499c740caf 100644--- a/products/desktop/packages/ui/src/features/sessions/components/session-update/UserMessage.test.tsx+++ b/products/desktop/packages/ui/src/features/sessions/components/session-update/UserMessage.test.tsx@@ -109,6 +109,28 @@ describe("UserMessage", () => {expect(screen.queryByText(/channel_context/)).not.toBeInTheDocument();});+ it("replaces a whole-message onboarding brief with a chip", () => {+ vi.stubEnv("DEV", false);+ renderWithFlags(+ <UserMessage+ content={+ "<onboarding_brief>\nWrite the first message.\n</onboarding_brief>"+ }+ taskId="task-1"+ />,+ false,+ );++ expect(+ screen.getByText("Getting started with PostHog Desktop"),+ ).toBeInTheDocument();+ // The brief is the entire message, so a bare strip would leave an empty bubble.+ expect(screen.queryByText(/onboarding_brief/)).not.toBeInTheDocument();+ expect(+ screen.queryByText(/Write the first message/),+ ).not.toBeInTheDocument();+ });+it("renders Pi skill invocations as a command chip", () => {renderWithFlags(<UserMessage content={PROMPT_WITH_PI_SKILL} />, true);diff --git a/products/desktop/packages/ui/src/features/sessions/components/session-update/UserMessage.tsx b/products/desktop/packages/ui/src/features/sessions/components/session-update/UserMessage.tsxindex 90399b2b9f76..1f3267937395 100644--- a/products/desktop/packages/ui/src/features/sessions/components/session-update/UserMessage.tsx+++ b/products/desktop/packages/ui/src/features/sessions/components/session-update/UserMessage.tsx@@ -21,6 +21,10 @@ import { CollapsibleMessageContent } from "./CollapsibleMessageContent";import { extractCanvasInstructions } from "./canvasInstructions";import { extractChannelContext } from "./channelContext";import { extractCustomInstructions } from "./customInstructions";+import {+ extractOnboardingBrief,+ ONBOARDING_BRIEF_LABEL,+} from "./onboardingBrief";import {hasFileMentions,MentionChip,@@ -104,8 +108,15 @@ export const UserMessage = memo(function UserMessage({() => extractCustomInstructions(afterCanvasInstructions),[afterCanvasInstructions],);+ const afterCustomInstructions = customInstructions+ ? customInstructions.stripped+ : afterCanvasInstructions;+ const onboardingBrief = useMemo(+ () => extractOnboardingBrief(afterCustomInstructions),+ [afterCustomInstructions],+ );const displayContent = collapsePiSkillInvocation(- customInstructions ? customInstructions.stripped : afterCanvasInstructions,+ onboardingBrief ? onboardingBrief.stripped : afterCustomInstructions,);const showChannelContextTag = !!channelContext && bluebirdEnabled;const showCanvasInstructionsTag = !!canvasInstructions && bluebirdEnabled;@@ -153,7 +164,8 @@ export const UserMessage = memo(function UserMessage({)}{(!!peerAgentMessage ||showChannelContextTag ||- showCanvasInstructionsTag) && (+ showCanvasInstructionsTag ||+ !!onboardingBrief) && (<Flexwrap="wrap"gap="1"@@ -165,6 +177,12 @@ export const UserMessage = memo(function UserMessage({label={`From agent: ${peerAgentMessage.senderTaskTitle}`}/>)}+ {onboardingBrief && (+ <MentionChip+ icon={<FileText size={12} />}+ label={ONBOARDING_BRIEF_LABEL}+ />+ )}{showChannelContextTag && channelContext && (<MentionChipicon={<FileText size={12} />}diff --git a/products/desktop/packages/ui/src/features/sessions/components/session-update/onboardingBrief.ts b/products/desktop/packages/ui/src/features/sessions/components/session-update/onboardingBrief.tsnew file mode 100644index 000000000000..c90594aa9be0--- /dev/null+++ b/products/desktop/packages/ui/src/features/sessions/components/session-update/onboardingBrief.ts@@ -0,0 +1,21 @@+// The first-run session's whole prompt arrives wrapped in `<onboarding_brief>` (see+// ONBOARDING_PROMPT_TAG in the tasks facade). Nobody typed it, so the conversation shows a chip+// in its place rather than the brief itself — and a chip rather than nothing, because the block+// is the entire message and stripping it would leave an empty bubble.+const ONBOARDING_BRIEF_REGEX =+ /<onboarding_brief\b[^>]*>[\s\S]*?<\/onboarding_brief>/;++export const ONBOARDING_BRIEF_LABEL = "Getting started with PostHog Desktop";++export function extractOnboardingBrief(+ content: string,+): { stripped: string } | null {+ const match = ONBOARDING_BRIEF_REGEX.exec(content);+ if (match?.index === undefined) return null;+ return {+ stripped: (+ content.slice(0, match.index) ++ content.slice(match.index + match[0].length)+ ).trim(),+ };+}diff --git a/products/desktop/packages/ui/src/features/task-detail/hooks/useTaskCreation.ts b/products/desktop/packages/ui/src/features/task-detail/hooks/useTaskCreation.tsindex 6cc4d9dfe5b9..bf3b431b5505 100644--- a/products/desktop/packages/ui/src/features/task-detail/hooks/useTaskCreation.ts+++ b/products/desktop/packages/ui/src/features/task-detail/hooks/useTaskCreation.ts@@ -238,11 +238,9 @@ export function useTaskCreation({// Used to name the task occupying a branch's worktree when reuse is blocked.const { data: tasks } = useTasks();- // Tasks created without a channel default into the user's private #me- // backend channel so they still surface in the Channels space instead of- // staying unfiled. The personal channel is per-user and provisioned lazily- // server-side on first list, so this can't collide across teammates. If it- // hasn't loaded yet the task is created unfiled, as before.+ // Tasks created without a channel default into the user's private #me channel so they+ // surface in the Channels space instead of staying unfiled. #me is per-user, so this+ // cannot collide across teammates; before the list loads the task is created unfiled.const bluebirdEnabled = useFeatureFlag(PROJECT_BLUEBIRD_FLAG,import.meta.env.DEV,diff --git a/products/desktop/packages/ui/src/shell/App.tsx b/products/desktop/packages/ui/src/shell/App.tsxindex a55ae27e11d9..9dbc956ee85c 100644--- a/products/desktop/packages/ui/src/shell/App.tsx+++ b/products/desktop/packages/ui/src/shell/App.tsx@@ -14,6 +14,7 @@ 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 { useChannelsLayout } from "@posthog/ui/features/canvas/hooks/useChannelsLayout";import { 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";@@ -27,6 +28,7 @@ import { router } from "@posthog/ui/router/router";import { AppLoadingScreen } from "@posthog/ui/shell/AppLoadingScreen";import { track } from "@posthog/ui/shell/analytics";import { ErrorBoundary } from "@posthog/ui/shell/ErrorBoundary";+import { beginFirstRun } from "@posthog/ui/shell/firstRun";import { logger } from "@posthog/ui/shell/logger";import { openExternalUrl } from "@posthog/ui/shell/openExternal";import {@@ -91,6 +93,12 @@ function App({ devToolbar }: AppProps) {wasShowingAiGateRef.current = needsAiApproval;}, [needsAiApproval, currentOrg]);+ const spacesLayoutEnabled = useChannelsLayout();+ // Read through a ref so a flag arriving mid-startup cannot re-run the resolve and replace+ // a route the user has already moved off.+ const spacesLayoutEnabledRef = useRef(spacesLayoutEnabled);+ spacesLayoutEnabledRef.current = spacesLayoutEnabled;+const readyForMainApp =isBootstrapped &&isAuthenticated &&@@ -100,6 +108,15 @@ function App({ devToolbar }: AppProps) {!needsAiApproval;const startupIdentity = getAuthIdentity(authState);+ // Provision, and open the first session, as soon as the user is through the access check.+ // Onboarding runs next and takes far longer than either call, so starting here is what keeps+ // the session ready by the time the route resolves instead of the route waiting on it.+ useEffect(() => {+ if (!isAuthenticated || hasCodeAccess !== true) return;+ if (!startupIdentity || !authenticatedClient) return;+ beginFirstRun(startupIdentity, authenticatedClient);+ }, [isAuthenticated, hasCodeAccess, startupIdentity, authenticatedClient]);+// Resolve and load the initial route before mounting the router. Reset when// the user leaves the main app so a later re-entry starts fresh.const [initialRouteLoaded, setInitialRouteLoaded] = useState(false);@@ -117,6 +134,7 @@ function App({ devToolbar }: AppProps) {const { href, firstRun } = await resolveStartupLocation(startupIdentity,authenticatedClient,+ spacesLayoutEnabledRef.current,);if (firstRun) {showChannelList(firstRun.generalChannelId);diff --git a/products/desktop/packages/ui/src/shell/firstRun.ts b/products/desktop/packages/ui/src/shell/firstRun.tsnew file mode 100644index 000000000000..faeb5deb26f6--- /dev/null+++ b/products/desktop/packages/ui/src/shell/firstRun.ts@@ -0,0 +1,65 @@+import type { PostHogAPIClient } from "@posthog/api-client/posthog-client";+import type { ProvisionedTaskChannels } from "@posthog/shared/domain-types";++export type FirstRunClient = Pick<+ PostHogAPIClient,+ "provisionDefaultTaskChannels" | "startOnboardingSession"+>;++export interface FirstRun {+ /** ``null`` when provisioning failed, which must not stop the app opening. */+ provisioned: Promise<ProvisionedTaskChannels | null>;+ /** ``null`` unless this is the first run and the backend opened a session. */+ sessionTaskId: Promise<string | null>;+}++/**+ * Only #general is proof: creating a task without one ensures the personal space, so a user who+ * reached the composer before provisioning ran has a personal space that provisioning did not+ * create and reports `personal_created: false`.+ */+export function isFirstRun(+ provisioned: ProvisionedTaskChannels | null,+): boolean {+ return Boolean(provisioned?.general_created || provisioned?.personal_created);+}++let started: (FirstRun & { identity: string }) | null = null;++function begin(identity: string, client: FirstRunClient): FirstRun {+ const provisioned = client.provisionDefaultTaskChannels().catch(() => {+ // Dropped so a later caller provisions again rather than inheriting the failure.+ if (started?.identity === identity) started = null;+ return null;+ });+ const entry = {+ identity,+ provisioned,+ // Its own promise, not awaited into `provisioned`, so a hung scrape cannot hold up+ // the callers that only need the channels.+ sessionTaskId: provisioned.then((channels) =>+ isFirstRun(channels)+ ? client.startOnboardingSession().catch(() => null)+ : null,+ ),+ };+ started = entry;+ return entry;+}++/**+ * Start provisioning and, on a first run, the session the user will land in. Called as soon as+ * the user is through the access check, so the work overlaps onboarding instead of following it.+ */+export function beginFirstRun(identity: string, client: FirstRunClient): void {+ if (started?.identity !== identity) begin(identity, client);+}++/**+ * The result of {@link beginFirstRun}, shared rather than consumed: `personal_created` and+ * `general_created` are true only for whoever provisions first, so every reader has to see the+ * same response or the later ones decide this is not a first run.+ */+export function firstRun(identity: string, client: FirstRunClient): FirstRun {+ return started?.identity === identity ? started : begin(identity, client);+}diff --git a/products/desktop/packages/ui/src/shell/startupLocation.test.ts b/products/desktop/packages/ui/src/shell/startupLocation.test.tsindex d45428f4e4c4..d416043b68a6 100644--- a/products/desktop/packages/ui/src/shell/startupLocation.test.ts+++ b/products/desktop/packages/ui/src/shell/startupLocation.test.ts@@ -1,9 +1,7 @@import { stateStorage } from "@posthog/ui/shell/rendererStorage";-import { afterEach, describe, expect, it, vi } from "vitest";-import {- primeStartupProvision,- resolveStartupLocation,-} from "./startupLocation";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { beginFirstRun, firstRun } from "./firstRun";+import { resolveStartupLocation } from "./startupLocation";const personal = {id: "me-id",@@ -22,28 +20,56 @@ const general = {system_role: "general" as const,};+// Each case gets its own identity so the module-level first run from a previous one is never+// the thing under test.+let identityCounter = 0;+let identity = "project";+describe("startup location", () => {+ beforeEach(() => {+ identityCounter += 1;+ identity = `project-${identityCounter}`;+ });afterEach(() => vi.restoreAllMocks());it("reopens a location saved before the routes were flattened", async () => {- vi.spyOn(stateStorage, "getItem").mockResolvedValue("/website/eng/loops");- const client = { provisionDefaultTaskChannels: vi.fn() };+ vi.spyOn(stateStorage, "getItem").mockImplementation(async (key) =>+ key.includes(":v2:") ? "/website/eng/loops" : null,+ );+ const client = {+ provisionDefaultTaskChannels: vi.fn().mockResolvedValue({+ channels: [personal, general],+ personal_created: false,+ general_created: false,+ }),+ startOnboardingSession: vi.fn(),+ };- await expect(resolveStartupLocation("project", client)).resolves.toEqual({- href: "/spaces/eng/loops",- firstRun: null,- });+ await expect(+ resolveStartupLocation(identity, client, true),+ ).resolves.toEqual({ href: "/spaces/eng/loops", firstRun: null });});- it("restores the exact last location without provisioning", async () => {- vi.spyOn(stateStorage, "getItem").mockResolvedValue("/new");- const client = { provisionDefaultTaskChannels: vi.fn() };+ it("restores the exact last location", async () => {+ vi.spyOn(stateStorage, "getItem").mockImplementation(async (key) =>+ key.includes(":v2:") ? "/code" : null,+ );+ const client = {+ provisionDefaultTaskChannels: vi.fn().mockResolvedValue({+ channels: [personal, general],+ personal_created: false,+ general_created: false,+ }),+ startOnboardingSession: vi.fn(),+ };- await expect(resolveStartupLocation("project", client)).resolves.toEqual({+ await expect(+ resolveStartupLocation(identity, client, true),+ ).resolves.toEqual({href: "/new",firstRun: null,});- expect(client.provisionDefaultTaskChannels).not.toHaveBeenCalled();+ expect(client.startOnboardingSession).not.toHaveBeenCalled();});it("lands a first-run user on the general space home", async () => {@@ -54,12 +80,75 @@ describe("startup location", () => {personal_created: true,general_created: true,}),+ startOnboardingSession: vi.fn().mockResolvedValue("session-id"),+ };++ await expect(+ resolveStartupLocation(identity, client, true),+ ).resolves.toEqual({+ href: "/spaces/general-id/tasks/session-id",+ firstRun: { generalChannelId: "general-id" },+ });+ });++ it("opens the session when only #general is new", async () => {+ // Creating a task ensures the personal space, so someone who reached the composer before+ // provisioning ran owns a personal space it did not create. Only #general proves a first run.+ vi.spyOn(stateStorage, "getItem").mockResolvedValue(null);+ const client = {+ provisionDefaultTaskChannels: vi.fn().mockResolvedValue({+ channels: [personal, general],+ personal_created: false,+ general_created: true,+ }),+ startOnboardingSession: vi.fn().mockResolvedValue("session-id"),+ };++ await expect(+ resolveStartupLocation(identity, client, true),+ ).resolves.toEqual({+ href: "/spaces/general-id/tasks/session-id",+ firstRun: { generalChannelId: "general-id" },+ });+ });++ it("does not open a second session when both spaces already existed", async () => {+ vi.spyOn(stateStorage, "getItem").mockResolvedValue(null);+ const client = {+ provisionDefaultTaskChannels: vi.fn().mockResolvedValue({+ channels: [personal, general],+ personal_created: false,+ general_created: false,+ }),+ startOnboardingSession: vi.fn().mockResolvedValue("session-id"),+ };++ await resolveStartupLocation(identity, client, true);++ expect(client.startOnboardingSession).not.toHaveBeenCalled();+ });++ it("opens the app even when starting the session never resolves", async () => {+ vi.spyOn(stateStorage, "getItem").mockResolvedValue(null);+ const client = {+ provisionDefaultTaskChannels: vi.fn().mockResolvedValue({+ channels: [personal, general],+ personal_created: true,+ general_created: true,+ }),+ startOnboardingSession: vi.fn().mockReturnValue(new Promise(() => {})),};- await expect(resolveStartupLocation("project", client)).resolves.toEqual({+ vi.useFakeTimers();+ const resolving = resolveStartupLocation(identity, client, true);+ await vi.runAllTimersAsync();+ vi.useRealTimers();++ await expect(resolving).resolves.toEqual({href: "/spaces/general-id",firstRun: { generalChannelId: "general-id" },});+ expect(client.startOnboardingSession).toHaveBeenCalled();});it("skips the first-run treatment when the server created nothing", async () => {@@ -71,9 +160,12 @@ describe("startup location", () => {personal_created: false,general_created: false,}),+ startOnboardingSession: vi.fn().mockResolvedValue("session-id"),};- await expect(resolveStartupLocation("project", client)).resolves.toEqual({+ await expect(+ resolveStartupLocation(identity, client, true),+ ).resolves.toEqual({href: "/spaces/general-id",firstRun: null,});@@ -94,14 +186,17 @@ describe("startup location", () => {personal_created: true,general_created: true,}),+ startOnboardingSession: vi.fn().mockResolvedValue("session-id"),};- await expect(resolveStartupLocation("project", client)).resolves.toEqual({+ await expect(+ resolveStartupLocation(identity, client, true),+ ).resolves.toEqual({href: "/spaces/old-space",firstRun: null,});expect(client.provisionDefaultTaskChannels).toHaveBeenCalledOnce();- expect(removeItem).toHaveBeenCalledWith("startup-location:project");+ expect(removeItem).toHaveBeenCalledWith(`startup-location:${identity}`);});it("opens anyway when provisioning is unavailable", async () => {@@ -114,17 +209,33 @@ describe("startup location", () => {.mockResolvedValue(undefined);const client = {provisionDefaultTaskChannels: vi.fn().mockRejectedValue(new Error("404")),+ startOnboardingSession: vi.fn().mockResolvedValue("session-id"),};- await expect(resolveStartupLocation("project", client)).resolves.toEqual({+ await expect(+ resolveStartupLocation(identity, client, true),+ ).resolves.toEqual({href: "/spaces/old-space",firstRun: null,});expect(removeItem).not.toHaveBeenCalled();});- it("ignores a hand-off primed by a different account", async () => {- // A logout or account switch between priming and consuming would otherwise hand the+ it("falls back to code when provisioning and saved locations are unavailable", async () => {+ vi.spyOn(stateStorage, "getItem").mockResolvedValue(null);+ const client = {+ provisionDefaultTaskChannels: vi.fn().mockRejectedValue(new Error("503")),+ startOnboardingSession: vi.fn(),+ };++ await expect(+ resolveStartupLocation(identity, client, true),+ ).resolves.toEqual({ href: "/code", firstRun: null });+ expect(client.startOnboardingSession).not.toHaveBeenCalled();+ });++ it("ignores a first run started by a different account", async () => {+ // A logout or account switch between starting and reading would otherwise hand the// next account the previous project's channels.vi.spyOn(stateStorage, "getItem").mockResolvedValue(null);const client = {@@ -133,50 +244,108 @@ describe("startup location", () => {personal_created: false,general_created: false,}),- startOnboardingSession: vi.fn().mockResolvedValue(true),+ startOnboardingSession: vi.fn().mockResolvedValue("session-id"),};- primeStartupProvision(- "someone-else",- Promise.resolve({+ beginFirstRun("someone-else", {+ provisionDefaultTaskChannels: vi.fn().mockResolvedValue({+ channels: [personal, general],+ personal_created: true,+ general_created: true,+ }),+ startOnboardingSession: vi.fn().mockResolvedValue("other-session"),+ });++ await expect(+ resolveStartupLocation(identity, client, true),+ ).resolves.toEqual({ href: "/spaces/general-id", firstRun: null });+ expect(client.provisionDefaultTaskChannels).toHaveBeenCalledOnce();+ });++ it("keeps a spaces-off user on a route they can navigate away from", async () => {+ vi.spyOn(stateStorage, "getItem").mockResolvedValue(null);+ const client = {+ provisionDefaultTaskChannels: vi.fn().mockResolvedValue({channels: [personal, general],personal_created: true,general_created: true,}),+ startOnboardingSession: vi.fn().mockResolvedValue("session-id"),+ };++ await expect(+ resolveStartupLocation(identity, client, false),+ ).resolves.toEqual({ href: "/code", firstRun: null });+ });++ it("takes the first run over a saved location when onboarding just provisioned", async () => {+ vi.spyOn(stateStorage, "getItem").mockImplementation(async (key) =>+ key.includes(":v2:") ? "/settings" : null,);+ const client = {+ provisionDefaultTaskChannels: vi.fn().mockResolvedValue({+ channels: [personal, general],+ personal_created: true,+ general_created: false,+ }),+ startOnboardingSession: vi.fn().mockResolvedValue("session-id"),+ };+ beginFirstRun(identity, client);- await expect(resolveStartupLocation("project", client)).resolves.toEqual({- href: "/spaces/general-id",- firstRun: null,+ await expect(+ resolveStartupLocation(identity, client, true),+ ).resolves.toEqual({+ href: "/spaces/general-id/tasks/session-id",+ firstRun: { generalChannelId: "general-id" },});- expect(client.provisionDefaultTaskChannels).toHaveBeenCalledOnce();});- it("consumes a primed provisioning result exactly once", async () => {+ it("shares one provisioning result between onboarding and startup", async () => {+ // personal_created and general_created are true only for whoever provisions first, so a+ // second call here would report that this is not a first run.vi.spyOn(stateStorage, "getItem").mockResolvedValue(null);- const client = { provisionDefaultTaskChannels: vi.fn() };- primeStartupProvision(- "project",- Promise.resolve({+ const client = {+ provisionDefaultTaskChannels: vi.fn().mockResolvedValue({channels: [personal, general],personal_created: true,general_created: false,}),- );+ startOnboardingSession: vi.fn().mockResolvedValue("session-id"),+ };- await expect(resolveStartupLocation("project", client)).resolves.toEqual({- href: "/spaces/general-id",+ beginFirstRun(identity, client);+ beginFirstRun(identity, client);++ await expect(+ resolveStartupLocation(identity, client, true),+ ).resolves.toEqual({+ href: "/spaces/general-id/tasks/session-id",firstRun: { generalChannelId: "general-id" },});- expect(client.provisionDefaultTaskChannels).not.toHaveBeenCalled();+ expect(client.provisionDefaultTaskChannels).toHaveBeenCalledOnce();+ expect(client.startOnboardingSession).toHaveBeenCalledOnce();+ });- const again = {+ it("provisions again when an earlier attempt failed", async () => {+ vi.spyOn(stateStorage, "getItem").mockResolvedValue(null);+ const failed = firstRun(identity, {+ provisionDefaultTaskChannels: vi.fn().mockRejectedValue(new Error("503")),+ startOnboardingSession: vi.fn(),+ });+ await expect(failed.provisioned).resolves.toBeNull();+ const client = {provisionDefaultTaskChannels: vi.fn().mockResolvedValue({channels: [personal, general],- personal_created: false,+ personal_created: true,general_created: false,}),+ startOnboardingSession: vi.fn().mockResolvedValue("session-id"),};- await resolveStartupLocation("project", again);- expect(again.provisionDefaultTaskChannels).toHaveBeenCalledOnce();++ await expect(+ resolveStartupLocation(identity, client, true),+ ).resolves.toEqual({+ href: "/spaces/general-id/tasks/session-id",+ firstRun: { generalChannelId: "general-id" },+ });});});diff --git a/products/desktop/packages/ui/src/shell/startupLocation.ts b/products/desktop/packages/ui/src/shell/startupLocation.tsindex d69063f4fdde..37ea2fe82e20 100644--- a/products/desktop/packages/ui/src/shell/startupLocation.ts+++ b/products/desktop/packages/ui/src/shell/startupLocation.ts@@ -1,14 +1,12 @@-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 { rewriteLegacyHref } from "@posthog/ui/router/legacyPaths";+import {+ type FirstRunClient,+ firstRun,+ isFirstRun,+} from "@posthog/ui/shell/firstRun";import { stateStorage } from "@posthog/ui/shell/rendererStorage";-type StartupLocationClient = Pick<- PostHogAPIClient,- "provisionDefaultTaskChannels"->;-const storageKey = (identity: string): string =>`startup-location:v2:${identity}`;/** Where installs from before the default spaces existed kept their location. */@@ -20,76 +18,71 @@ interface StartupLocation {firstRun: { generalChannelId: string } | null;}-let primedProvision: {- identity: string;- result: Promise<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. The in-flight promise is handed over- * (not the resolved value) so the hand-off wins the race synchronously, before- * the caller mounts the app, even while the network call is still pending.+ * The session is started at sign-in and normally settles while onboarding is still on screen, so+ * this wait is only ever paid by someone who got through onboarding faster than the scrape. The+ * cap is what stops a hung one holding the app shut: past it the feed opens, and the session+ * shows up there instead.*/-export function primeStartupProvision(- identity: string,- result: Promise<ProvisionedTaskChannels>,-): void {- primedProvision = { identity, result };-}+const SESSION_WAIT_MS = 15_000;-async function consumePrimedProvision(- identity: string,- client: StartupLocationClient,-): Promise<ProvisionedTaskChannels> {- const primed = primedProvision;- primedProvision = null;- // Keyed by identity because a logout or account switch between priming and- // consuming would otherwise hand the next account the previous project's- // channels. Everything else in this module is already keyed the same way.- if (primed && primed.identity === identity) {- try {- return await primed.result;- } catch {- // A failed hand-off must not cost the user their provisioning, so fall- // back to provisioning here as if nothing had been primed.- }- }- return client.provisionDefaultTaskChannels();+async function cappedSessionTaskId(+ sessionTaskId: Promise<string | null>,+): Promise<string | null> {+ return Promise.race([+ sessionTaskId,+ new Promise<null>((resolve) =>+ setTimeout(() => resolve(null), SESSION_WAIT_MS),+ ),+ ]);}export async function resolveStartupLocation(identity: string,- client: StartupLocationClient,+ client: FirstRunClient,+ spacesEnabled: boolean,): Promise<StartupLocation> {- const saved = await stateStorage.getItem(storageKey(identity));- if (saved) return { href: rewriteLegacyHref(saved), firstRun: null };+ // Provisioning is what says whether this is a first run, so it is read before anything looks at+ // where the user was last. A saved location is written on every navigation and is shared by every+ // account on the project, so it answers neither question reliably.+ const run = firstRun(identity, client);+ const provisioned = await run.provisioned;+ // The old key predates the created flags, so its presence is the only proof this install was+ // in use before the default spaces existed. That outranks the flags: provisioning a long-time+ // user's spaces for the first time reports a first run, and they are not new.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 {}+ if (provisioned) void stateStorage.removeItem(legacyStorageKey(identity));return { href: rewriteLegacyHref(legacy), firstRun: null };}- const provisioned = await consumePrimedProvision(identity, client);+ const firstRunHere = isFirstRun(provisioned);++ if (!firstRunHere) {+ const saved = await stateStorage.getItem(storageKey(identity));+ if (saved) return { href: rewriteLegacyHref(saved), firstRun: null };+ }+ if (!provisioned) return { href: "/code", firstRun: null };+const general = provisioned.channels.find((channel) =>isGeneralChannel(channel),);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;+ // /website renders WebsiteLayout, which suppresses ContentHeader and hides the Channels+ // toggle, and the route stays registered whether or not the layout is on. Sending someone+ // there before we know they can leave again is how a first run strands with no way back;+ // /code is navigable either way. An uncached flag reads false here, so a flag-on user can+ // land on /code once, which costs them a click rather than the session.+ if (!spacesEnabled) return { href: "/code", firstRun: null };++ const sessionTaskId = await cappedSessionTaskId(run.sessionTaskId);return {- href: `/spaces/${general.id}`,- firstRun: isFirstRun ? { generalChannelId: general.id } : null,+ href: sessionTaskId+ ? `/spaces/${general.id}/tasks/${sessionTaskId}`+ : `/spaces/${general.id}`,+ firstRun: firstRunHere ? { generalChannelId: general.id } : null,};}