: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): guide cloud GitHub setup (#96423)
Adam Leith5f53b48fc450
diff --git a/products/desktop/apps/code/src/renderer/features/dev-toolbar/components/DevToolbar.tsx b/products/desktop/apps/code/src/renderer/features/dev-toolbar/components/DevToolbar.tsxindex 7d531bf56978..c6f00d49b568 100644--- a/products/desktop/apps/code/src/renderer/features/dev-toolbar/components/DevToolbar.tsx+++ b/products/desktop/apps/code/src/renderer/features/dev-toolbar/components/DevToolbar.tsx@@ -18,6 +18,7 @@ import {useCurrentUser,} from "@posthog/ui/features/auth/authQueries";import { useLogoutMutation } from "@posthog/ui/features/auth/useAuthMutations";+import { useClearGithubUserIntegrations } from "@posthog/ui/features/integrations/useClearGithubUserIntegrations";import { useOnboardingStore } from "@posthog/ui/features/onboarding/onboardingStore";import { openSettings } from "@posthog/ui/features/settings/hooks/useOpenSettings";import { useSettingsStore } from "@posthog/ui/features/settings/settingsStore";@@ -43,6 +44,7 @@ import {Cpu,FileText,FolderOpen,+ GitBranch,Globe,LayoutGrid,MemoryStick,@@ -361,6 +363,7 @@ function UserMenu() {const client = useOptionalAuthenticatedClient();const { data: user } = useCurrentUser({ client, enabled: isAuthenticated });const logoutMutation = useLogoutMutation();+ const clearGithubIntegration = useClearGithubUserIntegrations();const handleResetOnboarding = () => {useOnboardingStore.getState().resetOnboarding();@@ -427,6 +430,13 @@ function UserMenu() {<RotateCcw size={12} className="mr-2 text-muted-foreground" />Reset product tours</DropdownMenuItem>+ <DropdownMenuItem+ disabled={clearGithubIntegration.isPending}+ onClick={() => clearGithubIntegration.mutate()}+ >+ <GitBranch size={12} className="mr-2 text-muted-foreground" />+ Clear GitHub integration+ </DropdownMenuItem></DropdownMenuGroup><DropdownMenuSeparator /><DropdownMenuGroup>diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelHomeComposer.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelHomeComposer.tsxindex 0292256cd864..8a094490c0b2 100644--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelHomeComposer.tsx+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelHomeComposer.tsx@@ -171,6 +171,10 @@ export const ChannelHomeComposer = forwardRef<isLoadingIntegrations,allowWorktree: false,});+ const cloudGithubUnavailable =+ workspaceMode === "cloud" &&+ !isLoadingIntegrations &&+ !hasGithubIntegration;const { cloudTarget, setCloudTarget } = useCloudTargetSelection();const cloudIds = workspaceMode === "cloud" ? cloudTargetIds(cloudTarget) : {};const [repositoryDialogOpen, setRepositoryDialogOpen] = useState(false);@@ -463,6 +467,8 @@ export const ChannelHomeComposer = forwardRef<overrideModes={["local", "cloud"]}cloudTarget={cloudTarget}onCloudTargetChange={setCloudTarget}+ hasGithubIntegration={hasGithubIntegration}+ isLoadingGithubIntegration={isLoadingIntegrations}size="1"disabled={isBusy}/>@@ -470,7 +476,7 @@ export const ChannelHomeComposer = forwardRef<cloud={workspaceMode === "cloud"}repositoryCount={taskRepositories.length}hasFolder={!!taskFolder}- disabled={isBusy}+ disabled={isBusy || cloudGithubUnavailable}onOpen={() => setRepositoryDialogOpen(true)}/></div>diff --git a/products/desktop/packages/ui/src/features/canvas/components/TaskRepositoryDialog.tsx b/products/desktop/packages/ui/src/features/canvas/components/TaskRepositoryDialog.tsxindex a882ad366902..d1c09c17bf8a 100644--- a/products/desktop/packages/ui/src/features/canvas/components/TaskRepositoryDialog.tsx+++ b/products/desktop/packages/ui/src/features/canvas/components/TaskRepositoryDialog.tsx@@ -123,7 +123,7 @@ export function TaskRepositoryDialog({/><labelhtmlFor="save-task-repositories-to-space"- className="flex cursor-pointer items-center gap-2 text-sm"+ className="flex cursor-pointer items-center gap-2 text-xs"><Checkboxid="save-task-repositories-to-space"diff --git a/products/desktop/packages/ui/src/features/integrations/useClearGithubUserIntegrations.test.ts b/products/desktop/packages/ui/src/features/integrations/useClearGithubUserIntegrations.test.tsnew file mode 100644index 000000000000..807d0e2b8dde--- /dev/null+++ b/products/desktop/packages/ui/src/features/integrations/useClearGithubUserIntegrations.test.ts@@ -0,0 +1,39 @@+import { describe, expect, it, vi } from "vitest";+import { clearGithubUserIntegrations } from "./useClearGithubUserIntegrations";++describe("clearGithubUserIntegrations", () => {+ it("disconnects every personal GitHub installation", async () => {+ const disconnectGithubUserIntegration = vi+ .fn()+ .mockResolvedValue(undefined);+ const client = {+ getGithubUserIntegrations: vi+ .fn()+ .mockResolvedValue([+ { installation_id: "installation-1" },+ { installation_id: "installation-2" },+ ]),+ disconnectGithubUserIntegration,+ };++ await expect(clearGithubUserIntegrations(client)).resolves.toBe(2);+ expect(disconnectGithubUserIntegration).toHaveBeenCalledTimes(2);+ expect(disconnectGithubUserIntegration).toHaveBeenCalledWith(+ "installation-1",+ );+ expect(disconnectGithubUserIntegration).toHaveBeenCalledWith(+ "installation-2",+ );+ });++ it("does nothing when no personal GitHub installation exists", async () => {+ const disconnectGithubUserIntegration = vi.fn();+ const client = {+ getGithubUserIntegrations: vi.fn().mockResolvedValue([]),+ disconnectGithubUserIntegration,+ };++ await expect(clearGithubUserIntegrations(client)).resolves.toBe(0);+ expect(disconnectGithubUserIntegration).not.toHaveBeenCalled();+ });+});diff --git a/products/desktop/packages/ui/src/features/integrations/useClearGithubUserIntegrations.ts b/products/desktop/packages/ui/src/features/integrations/useClearGithubUserIntegrations.tsnew file mode 100644index 000000000000..7e17c8da8c62--- /dev/null+++ b/products/desktop/packages/ui/src/features/integrations/useClearGithubUserIntegrations.ts@@ -0,0 +1,55 @@+import type { PostHogAPIClient } from "@posthog/api-client/posthog-client";+import { userGithubIntegrationKeys } from "@posthog/core/integrations/repositoryKeys";+import { useOptionalAuthenticatedClient } from "@posthog/ui/features/auth/authClient";+import { useAuthStateValue } from "@posthog/ui/features/auth/store";+import { invalidateGithubQueries } from "@posthog/ui/features/integrations/useGithubUserConnect";+import { toast } from "@posthog/ui/primitives/toast";+import { useMutation, useQueryClient } from "@tanstack/react-query";++type GithubIntegrationClient = Pick<+ PostHogAPIClient,+ "getGithubUserIntegrations" | "disconnectGithubUserIntegration"+>;++export async function clearGithubUserIntegrations(+ client: GithubIntegrationClient,+): Promise<number> {+ const integrations = await client.getGithubUserIntegrations();+ await Promise.all(+ integrations.map((integration) =>+ client.disconnectGithubUserIntegration(integration.installation_id),+ ),+ );+ return integrations.length;+}++export function useClearGithubUserIntegrations() {+ const client = useOptionalAuthenticatedClient();+ const projectId = useAuthStateValue((state) => state.currentProjectId);+ const queryClient = useQueryClient();++ return useMutation({+ mutationFn: async () => {+ if (!client) throw new Error("Not authenticated");+ return clearGithubUserIntegrations(client);+ },+ onSuccess: (removedCount) => {+ queryClient.setQueryData(userGithubIntegrationKeys.list(), []);+ if (removedCount === 0) {+ toast.info("No GitHub integration found.");+ } else {+ toast.success("Removed GitHub integration");+ }+ },+ onError: (error) => {+ toast.error(+ error instanceof Error+ ? error.message+ : "Failed to remove GitHub integration.",+ );+ },+ onSettled: () => {+ invalidateGithubQueries(queryClient, projectId);+ },+ });+}diff --git a/products/desktop/packages/ui/src/features/task-detail/components/CloudGithubMissingNotice.tsx b/products/desktop/packages/ui/src/features/task-detail/components/CloudGithubMissingNotice.tsxdeleted file mode 100644index d4df320729d4..000000000000--- a/products/desktop/packages/ui/src/features/task-detail/components/CloudGithubMissingNotice.tsx+++ /dev/null@@ -1,65 +0,0 @@-import { ArrowSquareOutIcon, InfoIcon } from "@phosphor-icons/react";-import {- describeGithubConnectError,- GITHUB_CONNECT_TIMEOUT_MESSAGE,-} from "@posthog/core/integrations/connectErrors";-import { useAuthStateValue } from "@posthog/ui/features/auth/store";-import { useGithubConnect } from "@posthog/ui/features/integrations/useGithubUserConnect";-import { useRepositoryIntegration } from "@posthog/ui/features/integrations/useIntegrations";-import { Button, Callout, Flex, Spinner, Text } from "@radix-ui/themes";--export function CloudGithubMissingNotice() {- const projectId = useAuthStateValue((s) => s.currentProjectId);- const cloudRegion = useAuthStateValue((s) => s.cloudRegion);- const { hasGithubIntegration: hasTeamGithubIntegration } =- useRepositoryIntegration();- const { error, isConnecting, isTimedOut, hasError, connect, reset } =- useGithubConnect({- projectId,- projectHasTeamIntegration: hasTeamGithubIntegration,- });- const canConnect = projectId != null && cloudRegion != null;-- return (- <Callout.Root color="amber" variant="soft" size="1">- <Flex align="center" gap="2" justify="between" wrap="wrap">- <Flex align="start" gap="2" className="min-w-0 flex-1">- <Callout.Icon>- <InfoIcon size={14} />- </Callout.Icon>- <Callout.Text>- <Text size="1">- {hasError- ? describeGithubConnectError(error)- : isTimedOut- ? GITHUB_CONNECT_TIMEOUT_MESSAGE- : "Connect GitHub to your PostHog account for cloud tasks."}- </Text>- </Callout.Text>- </Flex>- <Button- size="1"- variant="soft"- color="amber"- disabled={!canConnect || isConnecting}- onClick={() => {- if (!canConnect) return;- if (hasError) reset();- void connect();- }}- >- {isConnecting ? (- <Spinner size="1" />- ) : (- <ArrowSquareOutIcon size={12} />- )}- {isConnecting- ? "Waiting…"- : hasError || isTimedOut- ? "Try again"- : "Connect GitHub"}- </Button>- </Flex>- </Callout.Root>- );-}diff --git a/products/desktop/packages/ui/src/features/task-detail/components/CloudGithubSetupDialog.test.tsx b/products/desktop/packages/ui/src/features/task-detail/components/CloudGithubSetupDialog.test.tsxnew file mode 100644index 000000000000..9b83942409c9--- /dev/null+++ b/products/desktop/packages/ui/src/features/task-detail/components/CloudGithubSetupDialog.test.tsx@@ -0,0 +1,196 @@+import { useRendererWindowFocusStore } from "@posthog/ui/shell/rendererWindowFocusStore";+import { act, fireEvent, render, screen } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { CloudGithubSetupDialog } from "./CloudGithubSetupDialog";++const connectState = vi.hoisted(() => ({+ error: null,+ isConnecting: false,+ isTimedOut: false,+ hasError: false,+ isPending: false,+ connect: vi.fn(async () => undefined),+ reset: vi.fn(),+ onConnected: null as (() => void) | null,+}));++vi.mock("@posthog/ui/features/auth/store", () => ({+ useAuthStateValue: (selector: (state: unknown) => unknown) =>+ selector({ currentProjectId: 1, cloudRegion: "us" }),+}));+vi.mock("@posthog/ui/features/integrations/useIntegrations", () => ({+ useRepositoryIntegration: () => ({ hasGithubIntegration: false }),+}));+vi.mock("@posthog/ui/features/integrations/useGithubUserConnect", () => ({+ useGithubConnect: ({ onConnected }: { onConnected?: () => void }) => {+ connectState.onConnected = onConnected ?? null;+ return connectState;+ },+}));+vi.mock("@posthog/ui/utils/browser", () => ({+ openUrlInBrowser: vi.fn(),+}));++describe("CloudGithubSetupDialog", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ connectState.error = null;+ connectState.isConnecting = false;+ connectState.isTimedOut = false;+ connectState.hasError = false;+ connectState.isPending = false;+ connectState.onConnected = null;+ useRendererWindowFocusStore.setState({ focused: false });+ });++ afterEach(() => {+ vi.useRealTimers();+ });++ it("starts the GitHub connection", async () => {+ const user = userEvent.setup();+ render(<CloudGithubSetupDialog onConnected={vi.fn()} onClose={vi.fn()} />);++ expect(+ screen.getByText("GitHub authentication required"),+ ).toBeInTheDocument();+ expect(+ screen.getByText("Cloud tasks require GitHub authentication."),+ ).toBeInTheDocument();+ await user.click(screen.getByRole("button", { name: "Connect GitHub" }));++ expect(connectState.connect).toHaveBeenCalledOnce();+ });++ it("shows the onboarding visual while it waits for GitHub", () => {+ connectState.isConnecting = true;++ render(<CloudGithubSetupDialog onConnected={vi.fn()} onClose={vi.fn()} />);++ const waitingState = screen+ .getByText("Waiting for GitHub")+ .closest('[data-slot="empty"]');+ expect(waitingState).toBeInTheDocument();+ expect(waitingState).toHaveTextContent(+ "Finish authorizing in your browser, then return here.",+ );+ expect(+ waitingState?.querySelector('[aria-label="Loading"]'),+ ).not.toBeNull();+ });++ it("cancels only after the user selects Cancel", async () => {+ const user = userEvent.setup();+ const onClose = vi.fn();+ render(<CloudGithubSetupDialog onConnected={vi.fn()} onClose={onClose} />);++ expect(onClose).not.toHaveBeenCalled();+ await user.click(screen.getByRole("button", { name: "Cancel" }));+ expect(onClose).toHaveBeenCalledOnce();+ expect(connectState.reset).toHaveBeenCalledOnce();+ });++ it("waits for window focus after the integration appears", () => {+ vi.useFakeTimers();+ const onConnected = vi.fn();+ const { rerender } = render(+ <CloudGithubSetupDialog+ hasGithubIntegration={false}+ onConnected={onConnected}+ onClose={vi.fn()}+ />,+ );++ rerender(+ <CloudGithubSetupDialog+ hasGithubIntegration+ onConnected={onConnected}+ onClose={vi.fn()}+ />,+ );+ expect(onConnected).not.toHaveBeenCalled();++ act(() => useRendererWindowFocusStore.setState({ focused: true }));++ act(() => vi.advanceTimersByTime(499));+ expect(screen.queryByText("GitHub connected")).not.toBeInTheDocument();+ expect(onConnected).not.toHaveBeenCalled();++ act(() => vi.advanceTimersByTime(1));++ expect(screen.getByText("GitHub connected")).toBeInTheDocument();+ expect(+ screen.getByRole("img", { name: "PostHog connected to GitHub" }),+ ).toBeInTheDocument();+ expect(screen.getByRole("button", { name: "Close" })).toBeInTheDocument();+ expect(+ screen.queryByRole("button", { name: "Cancel" }),+ ).not.toBeInTheDocument();+ expect(connectState.reset).toHaveBeenCalledOnce();+ expect(onConnected).not.toHaveBeenCalled();++ act(() => vi.advanceTimersByTime(1_199));+ expect(onConnected).not.toHaveBeenCalled();++ act(() => vi.advanceTimersByTime(1));+ expect(screen.getByText("GitHub connected")).toBeInTheDocument();+ expect(onConnected).toHaveBeenCalledOnce();+ });++ it("completes setup when Close is selected during the success animation", () => {+ vi.useFakeTimers();+ const onConnected = vi.fn();+ const onClose = vi.fn();+ const { rerender } = render(+ <CloudGithubSetupDialog+ hasGithubIntegration={false}+ onConnected={onConnected}+ onClose={onClose}+ />,+ );++ rerender(+ <CloudGithubSetupDialog+ hasGithubIntegration+ onConnected={onConnected}+ onClose={onClose}+ />,+ );+ act(() => useRendererWindowFocusStore.setState({ focused: true }));+ act(() => vi.advanceTimersByTime(500));++ fireEvent.click(screen.getByRole("button", { name: "Close" }));++ expect(onConnected).toHaveBeenCalledOnce();+ expect(onClose).toHaveBeenCalledOnce();++ act(() => vi.advanceTimersByTime(1_200));+ expect(onConnected).toHaveBeenCalledOnce();+ });++ it("waits for window focus after the deep-link callback", () => {+ vi.useFakeTimers();+ const onConnected = vi.fn();+ render(+ <CloudGithubSetupDialog+ hasGithubIntegration={false}+ onConnected={onConnected}+ onClose={vi.fn()}+ />,+ );++ act(() => connectState.onConnected?.());+ expect(onConnected).not.toHaveBeenCalled();++ act(() => useRendererWindowFocusStore.setState({ focused: true }));++ expect(screen.queryByText("GitHub connected")).not.toBeInTheDocument();+ act(() => vi.advanceTimersByTime(500));+ expect(screen.getByText("GitHub connected")).toBeInTheDocument();+ expect(onConnected).not.toHaveBeenCalled();++ act(() => vi.advanceTimersByTime(1_200));+ expect(onConnected).toHaveBeenCalledOnce();+ });+});diff --git a/products/desktop/packages/ui/src/features/task-detail/components/CloudGithubSetupDialog.tsx b/products/desktop/packages/ui/src/features/task-detail/components/CloudGithubSetupDialog.tsxnew file mode 100644index 000000000000..d27aea0090f4--- /dev/null+++ b/products/desktop/packages/ui/src/features/task-detail/components/CloudGithubSetupDialog.tsx@@ -0,0 +1,344 @@+import {+ ArrowSquareOutIcon,+ GithubLogoIcon,+ HeartIcon,+} from "@phosphor-icons/react";+import {+ describeGithubConnectError,+ GITHUB_CONNECT_TIMEOUT_MESSAGE,+ GITHUB_INSTALL_PENDING_MESSAGE,+} from "@posthog/core/integrations/connectErrors";+import {+ AlertDialog,+ AlertDialogContent,+ AlertDialogFooter,+ Button,+ Empty,+ EmptyContent,+ EmptyDescription,+ EmptyHeader,+ EmptyMedia,+ EmptyTitle,+ Spinner,+} from "@posthog/quill";+import { useAuthStateValue } from "@posthog/ui/features/auth/store";+import { useGithubConnect } from "@posthog/ui/features/integrations/useGithubUserConnect";+import { useRepositoryIntegration } from "@posthog/ui/features/integrations/useIntegrations";+import Logo from "@posthog/ui/primitives/Logo";+import { useRendererWindowFocusStore } from "@posthog/ui/shell/rendererWindowFocusStore";+import { openUrlInBrowser } from "@posthog/ui/utils/browser";+import { domAnimation, LazyMotion, m, useReducedMotion } from "framer-motion";+import { useCallback, useEffect, useRef, useState } from "react";++const GITHUB_DOCS_URL = "https://posthog.com/docs/libraries/github?tab=Desktop";+const FOCUS_SUCCESS_DELAY_MS = 500;+const CONNECTED_SEQUENCE_MS = 1_200;++interface CloudGithubSetupDialogProps {+ hasGithubIntegration?: boolean;+ onConnected: () => void;+ onClose: () => void;+}++export function CloudGithubSetupDialog({+ hasGithubIntegration,+ onConnected,+ onClose,+}: CloudGithubSetupDialogProps) {+ const projectId = useAuthStateValue((state) => state.currentProjectId);+ const cloudRegion = useAuthStateValue((state) => state.cloudRegion);+ const { hasGithubIntegration: hasTeamGithubIntegration } =+ useRepositoryIntegration();+ const windowFocused = useRendererWindowFocusStore((state) => state.focused);+ const shouldReduceMotion = useReducedMotion() === true;+ const [connectCallbackReceived, setConnectCallbackReceived] = useState(false);+ const [connectionStarted, setConnectionStarted] = useState(false);+ const [showConnectedAnimation, setShowConnectedAnimation] = useState(false);+ const didCompleteRef = useRef(false);+ const didNotifyConnectedRef = useRef(false);+ const handleConnectCallback = useCallback(() => {+ setConnectCallbackReceived(true);+ }, []);+ const {+ error,+ isConnecting,+ isTimedOut,+ hasError,+ isPending,+ connect,+ reset,+ } = useGithubConnect({+ projectId,+ projectHasTeamIntegration: hasTeamGithubIntegration,+ onConnected: handleConnectCallback,+ });+ const canConnect = projectId != null && cloudRegion != null;++ const connectionConfirmed =+ connectCallbackReceived || hasGithubIntegration === true;++ useEffect(() => {+ if (!connectionConfirmed || !windowFocused || didCompleteRef.current) {+ return;+ }++ const timer = window.setTimeout(() => {+ didCompleteRef.current = true;+ reset();+ setConnectionStarted(false);+ setShowConnectedAnimation(true);+ }, FOCUS_SUCCESS_DELAY_MS);+ return () => window.clearTimeout(timer);+ }, [connectionConfirmed, reset, windowFocused]);++ useEffect(() => {+ if (!showConnectedAnimation || didNotifyConnectedRef.current) return;++ const timer = window.setTimeout(+ () => {+ didNotifyConnectedRef.current = true;+ onConnected();+ },+ shouldReduceMotion ? 0 : CONNECTED_SEQUENCE_MS,+ );+ return () => window.clearTimeout(timer);+ }, [onConnected, shouldReduceMotion, showConnectedAnimation]);++ const handleConnect = useCallback(async () => {+ if (!canConnect) return;+ setConnectionStarted(true);+ await connect();+ }, [canConnect, connect]);++ const handleClose = useCallback(() => {+ if (showConnectedAnimation && !didNotifyConnectedRef.current) {+ didNotifyConnectedRef.current = true;+ onConnected();+ }+ reset();+ setConnectCallbackReceived(false);+ setConnectionStarted(false);+ setShowConnectedAnimation(false);+ onClose();+ }, [onClose, onConnected, reset, showConnectedAnimation]);++ const connectionMessage = hasError+ ? describeGithubConnectError(error)+ : isTimedOut+ ? GITHUB_CONNECT_TIMEOUT_MESSAGE+ : isPending+ ? GITHUB_INSTALL_PENDING_MESSAGE+ : null;+ const waitingForGithub =+ (connectionStarted || isConnecting) &&+ !hasError &&+ !isTimedOut &&+ !isPending &&+ !showConnectedAnimation;++ return (+ <AlertDialog open onOpenChange={() => undefined}>+ <AlertDialogContent>+ <div className="p-2">+ <Empty className="py-6" aria-live="polite">+ <EmptyHeader>+ <EmptyMedia>+ <LazyMotion features={domAnimation}>+ <GithubConnectionIcon+ connected={showConnectedAnimation}+ loading={waitingForGithub}+ shouldReduceMotion={shouldReduceMotion}+ />+ </LazyMotion>+ </EmptyMedia>+ <EmptyTitle>+ {showConnectedAnimation+ ? "GitHub connected"+ : waitingForGithub+ ? "Waiting for GitHub"+ : "GitHub authentication required"}+ </EmptyTitle>+ <EmptyDescription+ className={+ hasError || isTimedOut ? "text-destructive" : undefined+ }+ >+ {showConnectedAnimation+ ? "You're ready to use Cloud tasks."+ : waitingForGithub+ ? "Finish authorizing in your browser, then return here."+ : (connectionMessage ??+ "Cloud tasks require GitHub authentication.")}+ </EmptyDescription>+ </EmptyHeader>+ {!showConnectedAnimation && (+ <EmptyContent className="flex-row justify-center gap-2">+ <Button+ type="button"+ variant="primary"+ loading={waitingForGithub}+ disabled={!canConnect || waitingForGithub}+ onClick={() => void handleConnect()}+ >+ {hasError || isTimedOut ? "Try again" : "Connect GitHub"}+ </Button>+ <Button+ type="button"+ variant="link-muted"+ onClick={() => void openUrlInBrowser(GITHUB_DOCS_URL)}+ >+ Learn more+ <ArrowSquareOutIcon size={12} />+ </Button>+ </EmptyContent>+ )}+ </Empty>+ </div>++ <AlertDialogFooter>+ <Button+ type="button"+ variant={showConnectedAnimation ? "primary" : "outline"}+ onClick={handleClose}+ >+ {showConnectedAnimation ? "Close" : "Cancel"}+ </Button>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ );+}++function GithubConnectionIcon({+ connected,+ loading,+ shouldReduceMotion,+}: {+ connected: boolean;+ loading: boolean;+ shouldReduceMotion: boolean;+}) {+ const movementTransition = {+ duration: shouldReduceMotion ? 0 : 0.55,+ delay: shouldReduceMotion ? 0 : 0.12,+ ease: [0.645, 0.045, 0.355, 1] as const,+ };+ const enterTransition = {+ duration: shouldReduceMotion ? 0 : 0.28,+ delay: shouldReduceMotion ? 0 : 0.8,+ ease: [0.215, 0.61, 0.355, 1] as const,+ };+ const tileClassName =+ "absolute top-1/2 left-1/2 flex size-8 items-center justify-center rounded-md border border-border bg-muted";++ if (connected) {+ return (+ <div+ key="connected"+ className="relative h-8 w-28"+ aria-label="PostHog connected to GitHub"+ role="img"+ >+ <m.span+ aria-hidden="true"+ className={tileClassName}+ initial={+ shouldReduceMotion+ ? false+ : {+ opacity: 0,+ transform: "translate(-50%, -50%) scale(0.92)",+ }+ }+ animate={{+ opacity: 1,+ transform: "translate(-52px, -50%) scale(1)",+ }}+ transition={movementTransition}+ >+ <span className="[&>svg]:h-3.5 [&>svg]:w-auto">+ <Logo wordmark={false} />+ </span>+ </m.span>++ <m.span+ aria-hidden="true"+ className="absolute top-1/2 left-1/2 flex items-center justify-center text-(--red-9)"+ initial={+ shouldReduceMotion+ ? false+ : {+ opacity: 0,+ transform: "translate(-50%, -50%) scale(0.6)",+ }+ }+ animate={{+ opacity: 1,+ transform: "translate(-50%, -50%) scale(1)",+ }}+ transition={enterTransition}+ >+ <HeartIcon size={14} weight="fill" />+ </m.span>++ <m.span+ aria-hidden="true"+ className={tileClassName}+ initial={+ shouldReduceMotion+ ? false+ : {+ opacity: 0,+ transform: "translate(-50%, -50%) scale(0.92)",+ }+ }+ animate={{+ opacity: 1,+ transform: "translate(20px, -50%) scale(1)",+ }}+ transition={movementTransition}+ >+ <GithubLogoIcon size={17} weight="fill" />+ </m.span>+ </div>+ );+ }++ return (+ <div className="relative h-8 w-28" aria-label="GitHub" role="img">+ <m.span+ aria-hidden="true"+ className={tileClassName}+ initial={false}+ animate={{+ opacity: loading ? 0 : 1,+ transform: "translate(-50%, -50%) scale(1)",+ }}+ transition={{+ duration: shouldReduceMotion ? 0 : 0.15,+ ease: [0.215, 0.61, 0.355, 1],+ }}+ >+ <GithubLogoIcon size={17} weight="fill" />+ </m.span>++ <m.span+ aria-hidden="true"+ className="absolute inset-0 flex items-center justify-center"+ initial={false}+ animate={{+ opacity: loading ? 1 : 0,+ transform: loading ? "scale(1)" : "scale(0.92)",+ }}+ transition={{+ duration: shouldReduceMotion ? 0 : 0.15,+ ease: [0.215, 0.61, 0.355, 1],+ }}+ >+ <span className="flex size-8 items-center justify-center rounded-md bg-muted">+ <Spinner />+ </span>+ </m.span>+ </div>+ );+}diff --git a/products/desktop/packages/ui/src/features/task-detail/components/TaskInput.tsx b/products/desktop/packages/ui/src/features/task-detail/components/TaskInput.tsxindex 600d559e4692..fa700c7e073e 100644--- a/products/desktop/packages/ui/src/features/task-detail/components/TaskInput.tsx+++ b/products/desktop/packages/ui/src/features/task-detail/components/TaskInput.tsx@@ -131,7 +131,6 @@ import { useResolvedWorkspaceMode } from "../hooks/useResolvedWorkspaceMode";import { useTaskCreation } from "../hooks/useTaskCreation";import { useWarmTask } from "../hooks/useWarmTask";import { ChannelContextChip } from "./ChannelContextChip";-import { CloudGithubMissingNotice } from "./CloudGithubMissingNotice";import { NewTaskSuggestions } from "./ContinueCliSessions";import { shouldShowChannelContextChip } from "./channelContext";import {@@ -852,6 +851,10 @@ export function TaskInput({const effectiveWorkspaceMode = workspaceMode;const cloudIds = workspaceMode === "cloud" ? cloudTargetIds(cloudTarget) : {};+ const cloudGithubUnavailable =+ effectiveWorkspaceMode === "cloud" &&+ !isLoadingIntegrations &&+ !hasGithubIntegration;const repoOptional = !!allowNoRepo && workspaceMode === "cloud";@@ -1403,6 +1406,8 @@ export function TaskInput({adapter={runtime === "pi" ? undefined : adapter}cloudTarget={cloudTarget}onCloudTargetChange={setCloudTarget}+ hasGithubIntegration={hasGithubIntegration}+ isLoadingGithubIntegration={isLoadingIntegrations}size="1"/>{repoOptional && (@@ -1410,7 +1415,7 @@ export function TaskInput({cloud={workspaceMode === "cloud"}repositoryCount={taskRepositories.length}hasFolder={!!taskFolder}- disabled={isCreatingTask}+ disabled={isCreatingTask || cloudGithubUnavailable}onOpen={() => setRepositoryDialogOpen(true)}/>)}@@ -1752,13 +1757,6 @@ export function TaskInput({</Tooltip></div>)}- {effectiveWorkspaceMode === "cloud" &&- !isLoadingRepos &&- !hasGithubIntegration && (- <div className="mx-2 mt-2">- <CloudGithubMissingNotice />- </div>- )}</Flex><div className="absolute top-full right-0 left-0 z-10">{suggestions ? (diff --git a/products/desktop/packages/ui/src/features/task-detail/components/WorkspaceModeSelect.test.tsx b/products/desktop/packages/ui/src/features/task-detail/components/WorkspaceModeSelect.test.tsxnew file mode 100644index 000000000000..e46b49ae841a--- /dev/null+++ b/products/desktop/packages/ui/src/features/task-detail/components/WorkspaceModeSelect.test.tsx@@ -0,0 +1,195 @@+import { render, screen, waitFor } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { beforeEach, describe, expect, it, vi } from "vitest";+import { WorkspaceModeSelect } from "./WorkspaceModeSelect";++const cloudTargetOptionsState = vi.hoisted(() => ({+ options: [+ {+ key: "default",+ target: { kind: "default" as const },+ name: "Default",+ description: "Full network access",+ },+ ],+ favoriteKey: null,+ toggleFavorite: vi.fn(),+}));++vi.mock("@posthog/ui/features/settings/adapterSubscription", () => ({+ useAdapterSubscription: () => ({+ flagEnabled: false,+ subscriptionOn: false,+ loggedIn: false,+ }),+}));+vi.mock("@posthog/ui/features/settings/hooks/useOpenSettings", () => ({+ openSettings: vi.fn(),+}));+vi.mock("@posthog/ui/shell/useHostCapabilities", () => ({+ useHostCapabilities: () => ({ localWorkspaces: true }),+}));+vi.mock("../hooks/useCloudModeEnabled", () => ({+ useCloudModeEnabled: () => true,+}));+vi.mock("../hooks/useCloudTarget", () => ({+ useCloudTargetOptions: () => cloudTargetOptionsState,+}));+vi.mock("./CloudGithubSetupDialog", () => ({+ CloudGithubSetupDialog: ({+ onConnected,+ onClose,+ }: {+ onConnected: () => void;+ onClose: () => void;+ }) => (+ <div role="alertdialog">+ <button type="button" onClick={onConnected}>+ Complete GitHub connection+ </button>+ <button type="button" onClick={onClose}>+ Cancel+ </button>+ </div>+ ),+}));++describe("WorkspaceModeSelect", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it("opens GitHub setup before selecting Cloud", async () => {+ const user = userEvent.setup();+ const onChange = vi.fn();+ render(+ <WorkspaceModeSelect+ value="local"+ onChange={onChange}+ overrideModes={["local", "cloud"]}+ hasGithubIntegration={false}+ isLoadingGithubIntegration={false}+ />,+ );++ const trigger = screen.getByRole("button", { name: "Workspace mode" });+ await user.click(trigger);++ expect(await screen.findByText("Run location")).toBeInTheDocument();+ expect(screen.getByText("Run in a cloud sandbox")).toBeInTheDocument();+ expect(screen.getByText("Connect GitHub")).toBeInTheDocument();++ await user.click(screen.getByText("Cloud"));++ expect(screen.getByRole("alertdialog")).toBeInTheDocument();+ expect(onChange).not.toHaveBeenCalled();+ });++ it("preserves the previous mode when the user cancels GitHub setup", async () => {+ const user = userEvent.setup();+ const onChange = vi.fn();+ render(+ <WorkspaceModeSelect+ value="local"+ onChange={onChange}+ overrideModes={["local", "cloud"]}+ hasGithubIntegration={false}+ />,+ );++ const trigger = screen.getByRole("button", { name: "Workspace mode" });+ await user.click(trigger);+ await user.click(await screen.findByText("Cloud"));+ await user.click(screen.getByRole("button", { name: "Cancel" }));++ expect(onChange).not.toHaveBeenCalled();+ expect(screen.queryByRole("alertdialog")).not.toBeInTheDocument();+ expect(trigger).toHaveTextContent("Local");+ await waitFor(() => expect(trigger).toHaveFocus());+ });++ it("selects Cloud after GitHub connects", async () => {+ const user = userEvent.setup();+ const onChange = vi.fn();+ render(+ <WorkspaceModeSelect+ value="local"+ onChange={onChange}+ overrideModes={["local", "cloud"]}+ hasGithubIntegration={false}+ />,+ );++ await user.click(screen.getByRole("button", { name: "Workspace mode" }));+ await user.click(await screen.findByText("Cloud"));+ await user.click(+ screen.getByRole("button", { name: "Complete GitHub connection" }),+ );++ expect(onChange).toHaveBeenCalledWith("cloud");+ expect(screen.getByRole("alertdialog")).toBeInTheDocument();+ });++ it("selects Cloud directly when GitHub is connected", async () => {+ const user = userEvent.setup();+ const onChange = vi.fn();+ render(+ <WorkspaceModeSelect+ value="local"+ onChange={onChange}+ overrideModes={["local", "cloud"]}+ hasGithubIntegration+ />,+ );++ await user.click(screen.getByRole("button", { name: "Workspace mode" }));++ expect(+ await screen.findByText("Run in a cloud sandbox"),+ ).toBeInTheDocument();+ expect(screen.queryByText("Connect GitHub")).not.toBeInTheDocument();++ await user.click(screen.getByText("Cloud"));+ expect(onChange).toHaveBeenCalledWith("cloud");+ expect(screen.queryByRole("alertdialog")).not.toBeInTheDocument();+ });++ it("does not show the setup requirement while GitHub is loading", async () => {+ const user = userEvent.setup();+ render(+ <WorkspaceModeSelect+ value="local"+ onChange={vi.fn()}+ overrideModes={["local", "cloud"]}+ hasGithubIntegration={false}+ isLoadingGithubIntegration+ />,+ );++ await user.click(screen.getByRole("button", { name: "Workspace mode" }));++ expect(+ await screen.findByText("Run in a cloud sandbox"),+ ).toBeInTheDocument();+ expect(screen.queryByText("Connect GitHub")).not.toBeInTheDocument();+ });++ it("keeps the standard Cloud trigger label", () => {+ render(+ <WorkspaceModeSelect+ value="cloud"+ onChange={vi.fn()}+ overrideModes={["local", "cloud"]}+ hasGithubIntegration={false}+ isLoadingGithubIntegration={false}+ />,+ );++ expect(+ screen.getByRole("button", { name: "Workspace mode" }),+ ).toHaveTextContent("Cloud");+ expect(+ screen.getByRole("button", { name: "Workspace mode" }),+ ).not.toHaveTextContent("Requires GitHub");+ });+});diff --git a/products/desktop/packages/ui/src/features/task-detail/components/WorkspaceModeSelect.tsx b/products/desktop/packages/ui/src/features/task-detail/components/WorkspaceModeSelect.tsxindex f45a97dc6e33..e63b2c236102 100644--- a/products/desktop/packages/ui/src/features/task-detail/components/WorkspaceModeSelect.tsx+++ b/products/desktop/packages/ui/src/features/task-detail/components/WorkspaceModeSelect.tsx@@ -27,7 +27,7 @@ import type { Adapter, WorkspaceMode } from "@posthog/shared";import { useAdapterSubscription } from "@posthog/ui/features/settings/adapterSubscription";import { openSettings } from "@posthog/ui/features/settings/hooks/useOpenSettings";import { useHostCapabilities } from "@posthog/ui/shell/useHostCapabilities";-import { useCallback, useMemo, useState } from "react";+import { useCallback, useMemo, useRef, useState } from "react";import {type CloudTarget,type CloudTargetOption,@@ -36,6 +36,7 @@ import {} from "../cloudTargets";import { useCloudModeEnabled } from "../hooks/useCloudModeEnabled";import { useCloudTargetOptions } from "../hooks/useCloudTarget";+import { CloudGithubSetupDialog } from "./CloudGithubSetupDialog";export type { WorkspaceMode };@@ -53,6 +54,8 @@ interface WorkspaceModeSelectProps {adapter?: Adapter;cloudTarget?: CloudTarget;onCloudTargetChange?: (target: CloudTarget) => void;+ hasGithubIntegration?: boolean;+ isLoadingGithubIntegration?: boolean;}const LOCAL_MODES: {@@ -90,6 +93,8 @@ export function WorkspaceModeSelect({adapter,cloudTarget = DEFAULT_CLOUD_TARGET,onCloudTargetChange,+ hasGithubIntegration,+ isLoadingGithubIntegration = false,}: WorkspaceModeSelectProps) {const { localWorkspaces } = useHostCapabilities();const cloudModeEnabled = useCloudModeEnabled();@@ -108,6 +113,11 @@ export function WorkspaceModeSelect({const { options, favoriteKey, toggleFavorite } = useCloudTargetOptions();const [menuOpen, setMenuOpen] = useState(false);+ const pendingCloudTargetRef = useRef<CloudTarget | null>(null);+ const triggerRef = useRef<HTMLButtonElement>(null);+ const [setupDialogOpen, setSetupDialogOpen] = useState(false);+ const githubSetupRequired =+ hasGithubIntegration === false && !isLoadingGithubIntegration;const environmentOptions = options.filter((option) => option.target.kind !== "image",@@ -121,7 +131,7 @@ export function WorkspaceModeSelect({openSettings("cloud-environments", "create");}, []);- const selectTarget = useCallback(+ const commitCloudTarget = useCallback((target: CloudTarget) => {onChange("cloud");onCloudTargetChange?.(target);@@ -129,6 +139,31 @@ export function WorkspaceModeSelect({[onChange, onCloudTargetChange],);+ const selectTarget = useCallback(+ (target: CloudTarget) => {+ setMenuOpen(false);+ if (githubSetupRequired) {+ pendingCloudTargetRef.current = target;+ setSetupDialogOpen(true);+ return;+ }+ commitCloudTarget(target);+ },+ [commitCloudTarget, githubSetupRequired],+ );++ const closeGithubSetupDialog = useCallback(() => {+ pendingCloudTargetRef.current = null;+ setSetupDialogOpen(false);+ window.requestAnimationFrame(() => triggerRef.current?.focus());+ }, []);++ const handleGithubConnected = useCallback(() => {+ if (!pendingCloudTargetRef.current) return;+ commitCloudTarget(pendingCloudTargetRef.current);+ pendingCloudTargetRef.current = null;+ }, [commitCloudTarget]);+const showCloud = overrideModes? overrideModes.includes("cloud"): cloudModeEnabled;@@ -165,128 +200,155 @@ export function WorkspaceModeSelect({}, [value]);return (- <DropdownMenu open={menuOpen} onOpenChange={setMenuOpen}>- <DropdownMenuTrigger- render={- <Button- type="button"- variant="default"- size="sm"- disabled={disabled}- aria-label="Workspace mode"- >- <span className="text-muted-foreground">{triggerIcon}</span>- {triggerLabel}- </Button>- }- />- <DropdownMenuContent- align="start"- side="bottom"- sideOffset={6}- className="w-auto min-w-[280px]"- >- {localModes.length > 0 && (- <div className="flex items-center justify-between px-2 py-1">- <MenuLabel className="p-0">Local</MenuLabel>- {subscriptionInUseLabel && (- <span className="text-[11px] text-muted-foreground">- {subscriptionInUseLabel}- </span>- )}- </div>- )}+ <>+ <DropdownMenu open={menuOpen} onOpenChange={setMenuOpen}>+ <DropdownMenuTrigger+ render={+ <Button+ type="button"+ ref={triggerRef}+ variant="default"+ size="sm"+ disabled={disabled}+ aria-label="Workspace mode"+ >+ <span className="text-muted-foreground">{triggerIcon}</span>+ {triggerLabel}+ </Button>+ }+ />+ <DropdownMenuContent+ align="start"+ side="bottom"+ sideOffset={6}+ className="w-auto min-w-[280px]"+ >+ {localModes.length > 0 && (+ <div className="flex items-center justify-between px-2 py-1">+ <MenuLabel className="p-0">+ {showCloud && options.length === 1 ? "Run location" : "Local"}+ </MenuLabel>+ {subscriptionInUseLabel && (+ <span className="text-[11px] text-muted-foreground">+ {subscriptionInUseLabel}+ </span>+ )}+ </div>+ )}++ <DropdownMenuGroup>+ {localModes.map((item) => (+ <DropdownMenuItem+ key={item.mode}+ onClick={() => onChange(item.mode)}+ render={+ <ItemMenuItem size="xs" className="w-full" render={<div />}>+ <ItemMedia variant="icon" className="mt-2 ml-2">+ <span>{item.icon}</span>+ </ItemMedia>+ <ItemContent variant="menuItem">+ <ItemTitle>{item.label}</ItemTitle>+ <ItemDescription className="whitespace-nowrap leading-none">+ {item.description}+ </ItemDescription>+ </ItemContent>+ </ItemMenuItem>+ }+ />+ ))}+ </DropdownMenuGroup>- <DropdownMenuGroup>- {localModes.map((item) => (+ {showCloud && options.length === 1 && (<DropdownMenuItem- key={item.mode}- onClick={() => onChange(item.mode)}+ onClick={() => selectTarget(DEFAULT_CLOUD_TARGET)}render={- <ItemMenuItem size="xs" className="w-full">+ <ItemMenuItem size="xs" className="w-full" render={<div />}><ItemMedia variant="icon" className="mt-2 ml-2">- <span>{item.icon}</span>+ <span>{CLOUD_ICON}</span></ItemMedia><ItemContent variant="menuItem">- <ItemTitle>{item.label}</ItemTitle>+ <ItemTitle>Cloud</ItemTitle><ItemDescription className="whitespace-nowrap leading-none">- {item.description}+ Run in a cloud sandbox</ItemDescription></ItemContent>+ {githubSetupRequired && (+ <ItemActions className="mr-1.5 ml-auto self-center">+ <span className="whitespace-nowrap text-[11px] text-warning-foreground">+ Connect GitHub+ </span>+ </ItemActions>+ )}</ItemMenuItem>}/>- ))}- </DropdownMenuGroup>+ )}- {showCloud && options.length === 1 && (- <DropdownMenuItem- onClick={() => selectTarget(DEFAULT_CLOUD_TARGET)}- render={- <ItemMenuItem size="xs" className="w-full">- <ItemMedia variant="icon" className="mt-2 ml-2">- <span>{CLOUD_ICON}</span>- </ItemMedia>- <ItemContent variant="menuItem">- <ItemTitle>Cloud</ItemTitle>- <ItemDescription className="whitespace-nowrap leading-none">- Run in a cloud sandbox- </ItemDescription>- </ItemContent>- </ItemMenuItem>- }- />- )}+ {showCloud && options.length > 1 && (+ <>+ <DropdownMenuSeparator />+ <div className="flex items-center justify-between px-2 py-1">+ <MenuLabel className="p-0">Cloud environments</MenuLabel>+ <div className="flex items-center gap-1.5">+ {githubSetupRequired && (+ <span className="whitespace-nowrap text-[11px] text-warning-foreground">+ GitHub setup required+ </span>+ )}+ <button+ type="button"+ onClick={handleAddEnvironment}+ aria-label="Add cloud environment"+ className={ICON_BUTTON_CLASS}+ >+ <Plus size={12} />+ </button>+ </div>+ </div>- {showCloud && options.length > 1 && (- <>- <DropdownMenuSeparator />- <div className="flex items-center justify-between px-2 py-1">- <MenuLabel className="p-0">Cloud environments</MenuLabel>- <button- type="button"- onClick={handleAddEnvironment}- aria-label="Add cloud environment"- className={ICON_BUTTON_CLASS}- >- <Plus size={12} />- </button>- </div>+ <DropdownMenuGroup>+ {environmentOptions.map((option) => (+ <CloudTargetItem+ key={option.key}+ option={option}+ isFavorite={favoriteKey === option.key}+ onSelect={selectTarget}+ onToggleFavorite={toggleFavorite}+ />+ ))}+ </DropdownMenuGroup>- <DropdownMenuGroup>- {environmentOptions.map((option) => (- <CloudTargetItem- key={option.key}- option={option}- isFavorite={favoriteKey === option.key}- onSelect={selectTarget}- onToggleFavorite={toggleFavorite}- />- ))}- </DropdownMenuGroup>+ {imageOptions.length > 0 && (+ <>+ <div className="px-2 py-1">+ <MenuLabel className="p-0">Images</MenuLabel>+ </div>+ <DropdownMenuGroup>+ {imageOptions.map((option) => (+ <CloudTargetItem+ key={option.key}+ option={option}+ isFavorite={favoriteKey === option.key}+ onSelect={selectTarget}+ onToggleFavorite={toggleFavorite}+ />+ ))}+ </DropdownMenuGroup>+ </>+ )}+ </>+ )}+ </DropdownMenuContent>+ </DropdownMenu>- {imageOptions.length > 0 && (- <>- <div className="px-2 py-1">- <MenuLabel className="p-0">Images</MenuLabel>- </div>- <DropdownMenuGroup>- {imageOptions.map((option) => (- <CloudTargetItem- key={option.key}- option={option}- isFavorite={favoriteKey === option.key}- onSelect={selectTarget}- onToggleFavorite={toggleFavorite}- />- ))}- </DropdownMenuGroup>- </>- )}- </>- )}- </DropdownMenuContent>- </DropdownMenu>+ {setupDialogOpen ? (+ <CloudGithubSetupDialog+ hasGithubIntegration={hasGithubIntegration}+ onConnected={handleGithubConnected}+ onClose={closeGithubSetupDialog}+ />+ ) : null}+ </>);}diff --git a/products/desktop/packages/ui/src/features/task-detail/hooks/useResolvedWorkspaceMode.test.tsx b/products/desktop/packages/ui/src/features/task-detail/hooks/useResolvedWorkspaceMode.test.tsxindex 58765a5e9995..23ee96436e04 100644--- a/products/desktop/packages/ui/src/features/task-detail/hooks/useResolvedWorkspaceMode.test.tsx+++ b/products/desktop/packages/ui/src/features/task-detail/hooks/useResolvedWorkspaceMode.test.tsx@@ -94,6 +94,30 @@ describe("useResolvedWorkspaceMode", () => {expect(result.current.workspaceMode).toBe("local");});+ it("returns to the previous local mode when GitHub is removed", () => {+ cloudState.enabled = true;+ cloudState.flagsLoaded = true;+ settingsState.lastUsedLocalWorkspaceMode = "worktree";++ const { result, rerender } = renderHook(+ (props: Parameters<typeof useResolvedWorkspaceMode>[0]) =>+ useResolvedWorkspaceMode(props),+ { initialProps: SETTLED },+ );++ expect(result.current.workspaceMode).toBe("cloud");++ rerender({+ hasGithubIntegration: false,+ isLoadingIntegrations: false,+ });++ expect(result.current.workspaceMode).toBe("worktree");+ expect(settingsState.setLastUsedWorkspaceMode).toHaveBeenCalledWith(+ "worktree",+ );+ });+it("ignores a cached integration until the live query settles", () => {cloudState.enabled = true;cloudState.flagsLoaded = true;diff --git a/products/desktop/packages/ui/src/features/task-detail/hooks/useResolvedWorkspaceMode.ts b/products/desktop/packages/ui/src/features/task-detail/hooks/useResolvedWorkspaceMode.tsindex f46d85b2510b..61d33ec7f0f2 100644--- a/products/desktop/packages/ui/src/features/task-detail/hooks/useResolvedWorkspaceMode.ts+++ b/products/desktop/packages/ui/src/features/task-detail/hooks/useResolvedWorkspaceMode.ts@@ -62,6 +62,7 @@ export function useResolvedWorkspaceMode({});const initiallyResolved = pinCloud || !localWorkspaces;const [isResolved, setIsResolved] = useState(initiallyResolved);+ const previousHasGithubIntegrationRef = useRef(hasGithubIntegration);const cloudSignalsSettled = areCloudSignalsSettled({cloudModeEnabled,@@ -101,6 +102,35 @@ export function useResolvedWorkspaceMode({localFallback,]);+ useEffect(() => {+ const previouslyHadGithub = previousHasGithubIntegrationRef.current;+ previousHasGithubIntegrationRef.current = hasGithubIntegration;++ if (+ !isResolved ||+ isLoadingIntegrations ||+ !previouslyHadGithub ||+ hasGithubIntegration ||+ workspaceMode !== "cloud" ||+ pinCloud ||+ !localWorkspaces+ ) {+ return;+ }++ setWorkspaceModeState(localFallback);+ setLastUsedWorkspaceMode(localFallback);+ }, [+ hasGithubIntegration,+ isLoadingIntegrations,+ isResolved,+ localFallback,+ localWorkspaces,+ pinCloud,+ setLastUsedWorkspaceMode,+ workspaceMode,+ ]);+const setWorkspaceMode = useCallback((mode: WorkspaceMode) => {didResolveRef.current = true;