Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(desktop): modernize onboarding with Quill (#96460)

Adam Leith301c158c643c
diff --git a/products/desktop/packages/core/src/integrations/apiErrorBody.ts b/products/desktop/packages/core/src/integrations/apiErrorBody.ts
new file mode 100644
index 000000000000..8f0ed5ced822
--- /dev/null
+++ b/products/desktop/packages/core/src/integrations/apiErrorBody.ts
@@ -0,0 +1,17 @@
+export interface ApiErrorBody {
+ code: string | null;
+ detail: string | null;
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === "object" && value !== null;
+}
+
+/** Read the stable string fields from an API error without leaking casts. */
+export function readApiErrorBody(error: unknown): ApiErrorBody {
+ const body = isRecord(error) && isRecord(error.body) ? error.body : null;
+ return {
+ code: typeof body?.code === "string" ? body.code : null,
+ detail: typeof body?.detail === "string" ? body.detail : null,
+ };
+}
diff --git a/products/desktop/packages/core/src/integrations/connectErrors.test.ts b/products/desktop/packages/core/src/integrations/connectErrors.test.ts
index 6d280733de55..c2b965c4e24f 100644
--- a/products/desktop/packages/core/src/integrations/connectErrors.test.ts
+++ b/products/desktop/packages/core/src/integrations/connectErrors.test.ts
@@ -4,6 +4,7 @@ import {
describeGithubConnectError,
describeIntegrationDisconnectError,
isAlreadyDisconnectedError,
+ isGithubConnectAlreadyLinked,
isGithubConnectPendingApproval,
} from "./connectErrors";
@@ -89,6 +90,18 @@ describe("describeGithubConnectError", () => {
describeGithubConnectError({ message: "raw message", code: "unknown" }),
).toBe("raw message");
});
+
+ it("replaces the already-linked API detail with concise copy", () => {
+ const error = {
+ message:
+ "All GitHub App installations accessible to your account are already linked.",
+ code: "invalid_input",
+ };
+ expect(isGithubConnectAlreadyLinked(error)).toBe(true);
+ expect(describeGithubConnectError(error)).toBe(
+ "All GitHub organizations available to your account are already connected.",
+ );
+ });
});
describe("isGithubConnectPendingApproval", () => {
diff --git a/products/desktop/packages/core/src/integrations/connectErrors.ts b/products/desktop/packages/core/src/integrations/connectErrors.ts
index 9f6c5c57d800..cf305ca2c0ba 100644
--- a/products/desktop/packages/core/src/integrations/connectErrors.ts
+++ b/products/desktop/packages/core/src/integrations/connectErrors.ts
@@ -1,4 +1,5 @@
import { requestErrorStatus } from "@posthog/api-client/fetcher";
+import { readApiErrorBody } from "./apiErrorBody";
export interface GithubConnectError {
message: string;
@@ -60,6 +61,15 @@ const GITHUB_CONNECT_ERROR_MESSAGES: Record<string, string> = {
export const GITHUB_CONNECT_PENDING_APPROVAL_CODE = "github_install_pending";
+export function isGithubConnectAlreadyLinked(
+ error: GithubConnectError | null,
+): boolean {
+ return (
+ error?.code === "invalid_input" &&
+ /all GitHub App installations.*already linked/i.test(error.message)
+ );
+}
+
/** Travels on the error channel but is not a failure: the connect can still
* succeed once an org owner approves, so callers render it as informational. */
export function isGithubConnectPendingApproval(
@@ -72,6 +82,9 @@ export function describeGithubConnectError(
error: GithubConnectError | null,
): string {
if (!error) return "";
+ if (isGithubConnectAlreadyLinked(error)) {
+ return "All GitHub organizations available to your account are already connected.";
+ }
if (error.code && GITHUB_CONNECT_ERROR_MESSAGES[error.code]) {
return GITHUB_CONNECT_ERROR_MESSAGES[error.code];
}
@@ -90,14 +103,7 @@ export function describeIntegrationDisconnectError(
if (requestErrorStatus(error) === 403) {
return "Only project admins can disconnect this integration.";
}
- const body =
- error && typeof error === "object" && "body" in error
- ? (error as { body?: unknown }).body
- : null;
- const detail =
- body && typeof body === "object" && "detail" in body
- ? (body as { detail?: unknown }).detail
- : null;
- if (typeof detail === "string" && detail) return detail;
+ const { detail } = readApiErrorBody(error);
+ if (detail) return detail;
return error instanceof Error ? error.message : fallback;
}
diff --git a/products/desktop/packages/core/src/integrations/connectMachine.test.ts b/products/desktop/packages/core/src/integrations/connectMachine.test.ts
index b82900aaf841..e2c55fb78ebf 100644
--- a/products/desktop/packages/core/src/integrations/connectMachine.test.ts
+++ b/products/desktop/packages/core/src/integrations/connectMachine.test.ts
@@ -82,6 +82,19 @@ describe("toConnectError", () => {
it("falls back for non-Error values", () => {
expect(toConnectError("x", "fallback").message).toBe("fallback");
});
+
+ it("extracts the code and detail from an API request error", () => {
+ const error = Object.assign(new Error("raw response"), {
+ body: {
+ code: "invalid_input",
+ detail: "All installations are linked.",
+ },
+ });
+ expect(toConnectError(error, "fallback")).toEqual({
+ message: "All installations are linked.",
+ code: "invalid_input",
+ });
+ });
});
describe("invalidation keys", () => {
diff --git a/products/desktop/packages/core/src/integrations/connectMachine.ts b/products/desktop/packages/core/src/integrations/connectMachine.ts
index 5756444a7356..5a02188c4e5f 100644
--- a/products/desktop/packages/core/src/integrations/connectMachine.ts
+++ b/products/desktop/packages/core/src/integrations/connectMachine.ts
@@ -1,4 +1,5 @@
import { signalsConfigKeys } from "../inbox/inboxQuery";
+import { readApiErrorBody } from "./apiErrorBody";
import { githubInstallRequestKeys } from "./repositoryKeys";
export type ConnectState =
@@ -74,9 +75,11 @@ export function toConnectError(
error: unknown,
fallbackMessage: string,
): ConnectError {
+ const { code, detail } = readApiErrorBody(error);
return {
- message: error instanceof Error ? error.message : fallbackMessage,
- code: null,
+ message:
+ detail || (error instanceof Error ? error.message : fallbackMessage),
+ code,
};
}
diff --git a/products/desktop/packages/core/src/onboarding/githubConnectPanel.test.ts b/products/desktop/packages/core/src/onboarding/githubConnectPanel.test.ts
index 09313a6ee056..4169f623d9a6 100644
--- a/products/desktop/packages/core/src/onboarding/githubConnectPanel.test.ts
+++ b/products/desktop/packages/core/src/onboarding/githubConnectPanel.test.ts
@@ -8,6 +8,7 @@ import {
deriveAlternativeConnectedProjects,
deriveConnectButtonState,
deriveGithubApprovalState,
+ didGithubConnectCompleteFromIntegrations,
getGithubPanelMessage,
isAnyIntegrationStale,
resolveSelectedProjectId,
@@ -78,6 +79,48 @@ describe("isAnyIntegrationStale", () => {
});
});
+describe("didGithubConnectCompleteFromIntegrations", () => {
+ it("completes an initial connection when the first integration appears", () => {
+ expect(
+ didGithubConnectCompleteFromIntegrations({
+ isConnecting: true,
+ integrationCountAtStart: 0,
+ currentIntegrationCount: 1,
+ }),
+ ).toBe(true);
+ });
+
+ it("completes an additional organization connection when its integration appears", () => {
+ expect(
+ didGithubConnectCompleteFromIntegrations({
+ isConnecting: true,
+ integrationCountAtStart: 1,
+ currentIntegrationCount: 2,
+ }),
+ ).toBe(true);
+ });
+
+ it("does not complete before the integration count increases", () => {
+ expect(
+ didGithubConnectCompleteFromIntegrations({
+ isConnecting: true,
+ integrationCountAtStart: 1,
+ currentIntegrationCount: 1,
+ }),
+ ).toBe(false);
+ });
+
+ it("ignores integration changes outside an active connection", () => {
+ expect(
+ didGithubConnectCompleteFromIntegrations({
+ isConnecting: false,
+ integrationCountAtStart: 0,
+ currentIntegrationCount: 1,
+ }),
+ ).toBe(false);
+ });
+});
+
describe("buildInstallationSettingsUrl", () => {
it("links an org install to the app page (org settings are owner-only)", () => {
expect(
diff --git a/products/desktop/packages/core/src/onboarding/githubConnectPanel.ts b/products/desktop/packages/core/src/onboarding/githubConnectPanel.ts
index e1ca5a25c4af..2a40d9667480 100644
--- a/products/desktop/packages/core/src/onboarding/githubConnectPanel.ts
+++ b/products/desktop/packages/core/src/onboarding/githubConnectPanel.ts
@@ -64,6 +64,17 @@ export function isAnyIntegrationStale(
);
}
+export function didGithubConnectCompleteFromIntegrations(inputs: {
+ isConnecting: boolean;
+ integrationCountAtStart: number;
+ currentIntegrationCount: number;
+}): boolean {
+ return (
+ inputs.isConnecting &&
+ inputs.currentIntegrationCount > inputs.integrationCountAtStart
+ );
+}
+
export function buildInstallationSettingsUrl(
account: GithubInstallationAccount | null | undefined,
installationId: string,
diff --git a/products/desktop/packages/ui/src/features/consent/ConsentStep.tsx b/products/desktop/packages/ui/src/features/consent/ConsentStep.tsx
index 177c38a68a89..e4aa19380eac 100644
--- a/products/desktop/packages/ui/src/features/consent/ConsentStep.tsx
+++ b/products/desktop/packages/ui/src/features/consent/ConsentStep.tsx
@@ -63,7 +63,24 @@ export function ConsentStep({
</AnimatePresence>
</div>
</div>
- <StepActions>
+ <StepActions
+ primaryAction={
+ <Button
+ variant="primary"
+ size="lg"
+ className="h-10 px-4 text-sm"
+ disabled={
+ isSubmitting ||
+ consent.status !== "resolved" ||
+ !consent.satisfied
+ }
+ onClick={onNext}
+ >
+ Next
+ <ArrowRight size={16} />
+ </Button>
+ }
+ >
{onBack && (
<Button
variant="outline"
@@ -76,20 +93,6 @@ export function ConsentStep({
Back
</Button>
)}
- <Button
- variant="primary"
- size="lg"
- className="h-10 px-4 text-sm"
- disabled={
- isSubmitting ||
- consent.status !== "resolved" ||
- !consent.satisfied
- }
- onClick={onNext}
- >
- Next
- <ArrowRight size={16} />
- </Button>
</StepActions>
</div>
</div>
diff --git a/products/desktop/packages/ui/src/features/folder-picker/GitHubRepoPicker.tsx b/products/desktop/packages/ui/src/features/folder-picker/GitHubRepoPicker.tsx
index 119730fc7429..60286acbe4c7 100644
--- a/products/desktop/packages/ui/src/features/folder-picker/GitHubRepoPicker.tsx
+++ b/products/desktop/packages/ui/src/features/folder-picker/GitHubRepoPicker.tsx
@@ -3,6 +3,7 @@ import {
CaretDown,
GithubLogo,
MagnifyingGlass,
+ X,
} from "@phosphor-icons/react";
import {
Button,
@@ -13,13 +14,13 @@ import {
ComboboxItem,
ComboboxList,
ComboboxTrigger,
+ cn,
InputGroupAddon,
InputGroupButton,
Text,
} from "@posthog/quill";
import { Spin, Spinner } from "@posthog/ui/primitives/Spinner";
import { Tooltip } from "@posthog/ui/primitives/Tooltip";
-import { FIELD_TRIGGER_CLASS } from "@posthog/ui/styles/fieldTrigger";
import { defaultFilter } from "cmdk";
import { type RefObject, useEffect, useMemo, useRef, useState } from "react";
@@ -91,6 +92,12 @@ export function GitHubRepoPicker({
}: GitHubRepoPickerProps) {
const buttonSize = size === "2" ? "lg" : "sm";
const buttonTextClass = size === "2" ? "text-[13px]" : "";
+ const triggerSize = variant === "field" ? "lg" : buttonSize;
+ const triggerClass = cn(
+ variant === "field" && "w-full justify-start",
+ buttonTextClass,
+ triggerClassName,
+ );
const triggerRef = useRef<HTMLButtonElement>(null);
const [uncontrolledOpen, setUncontrolledOpen] = useState(false);
const [uncontrolledSearchQuery, setUncontrolledSearchQuery] = useState("");
@@ -120,6 +127,7 @@ export function GitHubRepoPicker({
);
}, [repositories, trimmedSearchQuery]);
const hasMore = controlledHasMore ?? filteredRepositoryCount > visibleLimit;
+ const showClear = variant === "field" && value !== null && !disabled;
const showLoadingMore = useDelayedVisibility(
effectiveIsLoadingMore,
LOAD_MORE_INDICATOR_DELAY_MS,
@@ -147,8 +155,8 @@ export function GitHubRepoPicker({
<Button
variant="outline"
disabled
- size={buttonSize}
- className={`${buttonTextClass} ${triggerClassName ?? ""}`}
+ size={triggerSize}
+ className={triggerClass}
>
<GithubLogo size={16} weight="regular" className="shrink-0" />
Loading repos...
@@ -168,8 +176,8 @@ export function GitHubRepoPicker({
<Button
variant="outline"
disabled
- size={buttonSize}
- className={`${buttonTextClass} ${triggerClassName ?? ""}`}
+ size={triggerSize}
+ className={triggerClass}
>
<GithubLogo size={16} weight="regular" className="shrink-0" />
No GitHub repos
@@ -184,10 +192,15 @@ export function GitHubRepoPicker({
<Button
type="button"
variant="outline"
- size={buttonSize}
+ size={triggerSize}
disabled
aria-label="Repository"
- className={`pointer-events-none min-w-0 max-w-full cursor-default justify-start disabled:opacity-100 ${buttonTextClass} ${triggerClassName ?? ""}`}
+ className={cn(
+ "pointer-events-none min-w-0 max-w-full cursor-default justify-start disabled:opacity-100",
+ variant === "field" && "w-full",
+ buttonTextClass,
+ triggerClassName,
+ )}
>
<GithubLogo size={14} weight="regular" className="shrink-0" />
<span className="min-w-0 truncate">{onlyRepo}</span>
@@ -224,28 +237,55 @@ export function GitHubRepoPicker({
}}
disabled={disabled}
>
- <ComboboxTrigger
- render={
- variant === "field" ? (
- <button
- ref={triggerRef}
+ {variant === "field" ? (
+ <div className="relative w-full">
+ <ComboboxTrigger
+ render={
+ <Button
+ ref={triggerRef}
+ type="button"
+ variant="outline"
+ size="lg"
+ left
+ disabled={disabled}
+ aria-label="Repository"
+ className={triggerClass}
+ >
+ <div className="flex min-w-0 flex-1 items-center gap-2">
+ <GithubLogo size={16} className="shrink-0 text-foreground" />
+ <span
+ className="min-w-0 max-w-full truncate text-left font-medium text-foreground"
+ title={value ?? undefined}
+ >
+ {value ?? placeholder}
+ </span>
+ </div>
+ <CaretDown
+ size={14}
+ className="shrink-0 text-muted-foreground"
+ />
+ </Button>
+ }
+ />
+ {showClear ? (
+ <Button
type="button"
- disabled={disabled}
- aria-label="Repository"
- className={`${FIELD_TRIGGER_CLASS} ${triggerClassName ?? ""}`}
+ size="icon-xs"
+ variant="default"
+ aria-label="Clear repository"
+ className="-translate-y-1/2 absolute top-1/2 right-8"
+ onClick={(event) => {
+ event.stopPropagation();
+ onChange(null);
+ }}
>
- <div className="flex min-w-0 flex-1 items-center gap-2">
- <GithubLogo size={16} className="shrink-0 text-(--gray-12)" />
- <span
- className="min-w-0 max-w-full truncate text-left font-medium text-(--gray-12)"
- title={value ?? undefined}
- >
- {value ?? placeholder}
- </span>
- </div>
- <CaretDown size={14} className="shrink-0 text-(--gray-9)" />
- </button>
- ) : (
+ <X size={12} />
+ </Button>
+ ) : null}
+ </div>
+ ) : (
+ <ComboboxTrigger
+ render={
<Button
ref={triggerRef}
variant="outline"
@@ -257,14 +297,14 @@ export function GitHubRepoPicker({
<GithubLogo size={14} weight="regular" className="shrink-0" />
<span className="min-w-0 truncate">{value ?? placeholder}</span>
</Button>
- )
- }
- />
+ }
+ />
+ )}
<ComboboxContent
anchor={anchor ?? triggerRef}
side="bottom"
sideOffset={6}
- className="flex h-80 w-80 flex-col"
+ className="flex h-80 min-w-(--anchor-width) flex-col"
>
{showSearchInput ? (
<ComboboxInput
diff --git a/products/desktop/packages/ui/src/features/integrations/GithubApprovalNotice.tsx b/products/desktop/packages/ui/src/features/integrations/GithubApprovalNotice.tsx
index 66a0cf0cc9b7..a7a33db53540 100644
--- a/products/desktop/packages/ui/src/features/integrations/GithubApprovalNotice.tsx
+++ b/products/desktop/packages/ui/src/features/integrations/GithubApprovalNotice.tsx
@@ -1,5 +1,12 @@
import { CheckCircle, Clock } from "@phosphor-icons/react";
-import { cn } from "@posthog/quill";
+import {
+ cn,
+ Item,
+ ItemContent,
+ ItemDescription,
+ ItemMedia,
+ ItemTitle,
+} from "@posthog/quill";
export function GithubApprovalNotice({
state,
@@ -10,28 +17,29 @@ export function GithubApprovalNotice({
}) {
if (state === "awaiting") {
return (
- <div className={cn("flex flex-col gap-1", className)}>
- <div className="flex items-center gap-2 font-medium text-(--gray-12) text-sm">
- <Clock size={16} className="text-(--amber-11)" />
- Waiting for a GitHub org owner to approve
- </div>
- <span className="text-(--gray-11) text-sm">
- Cloud runs will not be available until your integration is approved.
- In the meantime, you can run tasks on your local machine.
- </span>
- </div>
+ <Item variant="muted" size="sm" tone="warning" className={className}>
+ <ItemMedia variant="icon">
+ <Clock size={16} />
+ </ItemMedia>
+ <ItemContent>
+ <ItemTitle>Waiting for a GitHub org owner to approve</ItemTitle>
+ <ItemDescription>
+ Cloud runs will not be available until your integration is approved.
+ In the meantime, you can run tasks on your local machine.
+ </ItemDescription>
+ </ItemContent>
+ </Item>
);
}
return (
- <div
- className={cn(
- "flex items-center gap-2 font-medium text-(--gray-12) text-sm",
- className,
- )}
- >
- <CheckCircle size={16} weight="fill" className="text-(--green-9)" />
- Your GitHub org owner approved the request
- </div>
+ <Item variant="muted" size="sm" tone="success" className={cn(className)}>
+ <ItemMedia variant="icon">
+ <CheckCircle size={16} weight="fill" />
+ </ItemMedia>
+ <ItemContent>
+ <ItemTitle>Your GitHub org owner approved the request</ItemTitle>
+ </ItemContent>
+ </Item>
);
}
diff --git a/products/desktop/packages/ui/src/features/integrations/components/GithubConnectionEmpty.test.tsx b/products/desktop/packages/ui/src/features/integrations/components/GithubConnectionEmpty.test.tsx
new file mode 100644
index 000000000000..442e919954b4
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/integrations/components/GithubConnectionEmpty.test.tsx
@@ -0,0 +1,33 @@
+import { render, screen } from "@testing-library/react";
+import { describe, expect, it, vi } from "vitest";
+import { GithubConnectionEmpty } from "./GithubConnectionEmpty";
+
+vi.mock("@posthog/ui/utils/browser", () => ({
+ openUrlInBrowser: vi.fn(),
+}));
+
+describe("GithubConnectionEmpty", () => {
+ it.each([
+ { showLearnMore: true, expected: true },
+ { showLearnMore: false, expected: false },
+ ])(
+ "sets Learn more visibility to $expected",
+ ({ showLearnMore, expected }) => {
+ render(
+ <GithubConnectionEmpty
+ connected={false}
+ description="Connect GitHub to continue."
+ showLearnMore={showLearnMore}
+ title="Connect GitHub"
+ >
+ <span>Connection action</span>
+ </GithubConnectionEmpty>,
+ );
+
+ expect(screen.getByText("Connection action")).toBeInTheDocument();
+ expect(
+ screen.queryByRole("button", { name: "Learn more" }) !== null,
+ ).toBe(expected);
+ },
+ );
+});
diff --git a/products/desktop/packages/ui/src/features/integrations/components/GithubConnectionEmpty.tsx b/products/desktop/packages/ui/src/features/integrations/components/GithubConnectionEmpty.tsx
new file mode 100644
index 000000000000..8e61ae8a1c8b
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/integrations/components/GithubConnectionEmpty.tsx
@@ -0,0 +1,73 @@
+import { ArrowSquareOutIcon } from "@phosphor-icons/react";
+import {
+ Button,
+ cn,
+ Empty,
+ EmptyContent,
+ EmptyDescription,
+ EmptyHeader,
+ EmptyMedia,
+ EmptyTitle,
+} from "@posthog/quill";
+import { GithubConnectionIcon } from "@posthog/ui/features/integrations/components/GithubConnectionIcon";
+import { openUrlInBrowser } from "@posthog/ui/utils/browser";
+import type { ReactNode } from "react";
+
+const GITHUB_DOCS_URL = "https://posthog.com/docs/libraries/github?tab=Desktop";
+
+interface GithubConnectionEmptyProps {
+ connected: boolean;
+ description: ReactNode;
+ children?: ReactNode;
+ descriptionClassName?: string;
+ loading?: boolean;
+ showLearnMore?: boolean;
+ title?: ReactNode;
+ className?: string;
+}
+
+export function GithubConnectionEmpty({
+ connected,
+ description,
+ children,
+ descriptionClassName,
+ loading = false,
+ showLearnMore = true,
+ title,
+ className,
+}: GithubConnectionEmptyProps) {
+ return (
+ <Empty className={cn("py-6", className)} aria-live="polite">
+ <EmptyHeader>
+ <EmptyMedia>
+ <GithubConnectionIcon connected={connected} loading={loading} />
+ </EmptyMedia>
+ {title ? <EmptyTitle>{title}</EmptyTitle> : null}
+ <EmptyDescription className={descriptionClassName}>
+ {description}
+ </EmptyDescription>
+ </EmptyHeader>
+ {(children || showLearnMore) && (
+ <EmptyContent
+ className={
+ showLearnMore
+ ? "flex-row justify-center gap-2"
+ : "w-full max-w-none items-stretch"
+ }
+ >
+ {children}
+ {showLearnMore && (
+ <Button
+ type="button"
+ variant="link-muted"
+ onClick={() => void openUrlInBrowser(GITHUB_DOCS_URL)}
+ >
+ Learn more
+ <ArrowSquareOutIcon size={12} />
+ </Button>
+ )}
+ </EmptyContent>
+ )}
+ </Empty>
+ );
+}
diff --git a/products/desktop/packages/ui/src/features/integrations/components/GithubConnectionIcon.tsx b/products/desktop/packages/ui/src/features/integrations/components/GithubConnectionIcon.tsx
new file mode 100644
index 000000000000..86c5a53d6c6f
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/integrations/components/GithubConnectionIcon.tsx
@@ -0,0 +1,139 @@
+import { GithubLogoIcon, HeartIcon } from "@phosphor-icons/react";
+import Logo from "@posthog/ui/primitives/Logo";
+import { Spinner } from "@posthog/ui/primitives/Spinner";
+import { domAnimation, LazyMotion, m, useReducedMotion } from "framer-motion";
+
+interface GithubConnectionIconProps {
+ connected: boolean;
+ loading?: boolean;
+}
+
+export function GithubConnectionIcon({
+ connected,
+ loading = false,
+}: GithubConnectionIconProps) {
+ const shouldReduceMotion = useReducedMotion() === true;
+ 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";
+
+ return (
+ <LazyMotion features={domAnimation}>
+ {connected ? (
+ <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-destructive-foreground"
+ 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>
+ ) : (
+ <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>
+ )}
+ </LazyMotion>
+ );
+}
diff --git a/products/desktop/packages/ui/src/features/integrations/integrationsClientImpl.ts b/products/desktop/packages/ui/src/features/integrations/integrationsClientImpl.ts
index 66c52817f990..97571d7426b0 100644
--- a/products/desktop/packages/ui/src/features/integrations/integrationsClientImpl.ts
+++ b/products/desktop/packages/ui/src/features/integrations/integrationsClientImpl.ts
@@ -10,7 +10,6 @@ import {
type HostTrpcClient,
} from "@posthog/host-router/client";
import { getAuthenticatedClient } from "@posthog/ui/features/auth/authClientImperative";
-import { openExternalUrl } from "@posthog/ui/shell/openExternal";
async function authedClient() {
const client = await getAuthenticatedClient();
@@ -36,7 +35,9 @@ export class UiGithubConnectClient implements GithubConnectClient {
}
async launchUrl(url: string): Promise<void> {
- openExternalUrl(url);
+ await resolveService<HostTrpcClient>(
+ HOST_TRPC_CLIENT,
+ ).os.openExternal.mutate({ url });
}
async startTeamFlow(input: {
diff --git a/products/desktop/packages/ui/src/features/integrations/useGithubUserConnect.ts b/products/desktop/packages/ui/src/features/integrations/useGithubUserConnect.ts
index 48adcd148bd9..5e777ba29d54 100644
--- a/products/desktop/packages/ui/src/features/integrations/useGithubUserConnect.ts
+++ b/products/desktop/packages/ui/src/features/integrations/useGithubUserConnect.ts
@@ -42,6 +42,10 @@ interface Result {
reset: () => void;
}
+interface GithubConnectResult extends Result {
+ connectUser: () => Promise<void>;
+}
+
export function invalidateGithubQueries(
queryClient: QueryClient,
projectId: number | null = null,
@@ -195,26 +199,32 @@ function machineToResult(
};
}
-export function useGithubUserConnect({ projectId }: Options): Result {
- const connectService = useService<GithubConnectService>(
- GITHUB_CONNECT_SERVICE,
- );
- const machine = useConnectStateMachine(projectId);
-
- const connect = useCallback(async () => {
- if (machine.stateRef.current === "connecting") return;
- if (projectId === null) return;
+function useConnectGithubUser(
+ connectService: GithubConnectService,
+ projectId: number | null,
+ machine: StateMachine,
+): () => Promise<void> {
+ return useCallback(async () => {
+ if (machine.stateRef.current === "connecting" || projectId === null) return;
machine.beginConnecting();
try {
await connectService.connectUser(projectId);
machine.scheduleDevPolling();
machine.scheduleUserFlowTimeout();
- } catch (e) {
+ } catch (error) {
machine.finishWithError(
- toConnectError(e, "Failed to start GitHub connection"),
+ toConnectError(error, "Failed to start GitHub connection"),
);
}
- }, [connectService, projectId, machine]);
+ }, [connectService, machine, projectId]);
+}
+
+export function useGithubUserConnect({ projectId }: Options): Result {
+ const connectService = useService<GithubConnectService>(
+ GITHUB_CONNECT_SERVICE,
+ );
+ const machine = useConnectStateMachine(projectId);
+ const connect = useConnectGithubUser(connectService, projectId, machine);
return machineToResult(machine, connect);
}
@@ -240,13 +250,14 @@ export function useGithubConnect({
projectId,
projectHasTeamIntegration,
onConnected,
-}: ConnectOptions): Result {
+}: ConnectOptions): GithubConnectResult {
const connectService = useService<GithubConnectService>(
GITHUB_CONNECT_SERVICE,
);
const cloudRegion = useAuthStateValue((s) => s.cloudRegion);
const { isAdmin } = useIsOrgAdmin();
const machine = useConnectStateMachine(projectId, onConnected);
+ const connectUser = useConnectGithubUser(connectService, projectId, machine);
const connect = useCallback(async () => {
if (machine.stateRef.current === "connecting") return;
@@ -277,5 +288,5 @@ export function useGithubConnect({
machine,
]);
- return machineToResult(machine, connect);
+ return { ...machineToResult(machine, connect), connectUser };
}
diff --git a/products/desktop/packages/ui/src/features/onboarding/components/ConnectGitHubStep.tsx b/products/desktop/packages/ui/src/features/onboarding/components/ConnectGitHubStep.tsx
index ae49b824b538..3c1817837c45 100644
--- a/products/desktop/packages/ui/src/features/onboarding/components/ConnectGitHubStep.tsx
+++ b/products/desktop/packages/ui/src/features/onboarding/components/ConnectGitHubStep.tsx
@@ -1,15 +1,15 @@
import { ArrowLeft, ArrowRight } from "@phosphor-icons/react";
import { isAnyIntegrationStale } from "@posthog/core/onboarding/githubConnectPanel";
+import { Button, Heading, Text } from "@posthog/quill";
import type { OnboardingStepCompletedProperties } from "@posthog/shared/analytics-events";
+import { GithubConnectionEmpty } from "@posthog/ui/features/integrations/components/GithubConnectionEmpty";
import {
useUserGithubIntegrations,
useUserRepositoryIntegration,
} from "@posthog/ui/features/integrations/useIntegrations";
-import { GithubConnectionLink } from "@posthog/ui/features/onboarding/components/GithubConnectionLink";
import { OptionalBadge } from "@posthog/ui/features/onboarding/components/OptionalBadge";
import { StepActions } from "@posthog/ui/features/onboarding/components/StepActions";
-import { Button, Flex, Text } from "@radix-ui/themes";
-import { motion } from "framer-motion";
+import { motion, useReducedMotion } from "framer-motion";
import { GitHubConnectPanel } from "./GitHubConnectPanel";
type StepContext = Pick<OnboardingStepCompletedProperties, "github_connected">;
@@ -20,6 +20,7 @@ interface ConnectGitHubStepProps {
}
export function ConnectGitHubStep({ onNext, onBack }: ConnectGitHubStepProps) {
+ const shouldReduceMotion = useReducedMotion() === true;
const { data: githubUserIntegrations = [] } = useUserGithubIntegrations();
const { failedInstallationIds } = useUserRepositoryIntegration();
// A revoked installation still leaves its row behind, so the link must not
@@ -32,81 +33,67 @@ export function ConnectGitHubStep({ onNext, onBack }: ConnectGitHubStepProps) {
};
return (
- <Flex align="center" justify="center" height="100%" px="8">
- <Flex
- direction="column"
- align="center"
- className="h-full w-full max-w-[480px] pt-[24px] pb-[40px]"
- >
- <Flex
- direction="column"
- align="center"
- className="min-h-0 w-full flex-1 overflow-y-auto"
+ <main className="w-full">
+ <div className="mx-auto flex w-full max-w-[480px] flex-col gap-4">
+ <motion.div
+ initial={shouldReduceMotion ? false : { opacity: 0, y: 8 }}
+ animate={{ opacity: 1, y: 0 }}
+ transition={{ duration: 0.25, ease: "easeOut" }}
+ className="flex flex-col gap-1.5"
>
- <Flex
- direction="column"
- gap="5"
- style={{ margin: "auto 0" }}
- className="w-full"
- >
- <Flex direction="column" gap="4" className="w-full">
- <motion.div
- initial={{ opacity: 0, y: 8 }}
- animate={{ opacity: 1, y: 0 }}
- transition={{ duration: 0.3 }}
- >
- <GithubConnectionLink connected={isConnected} />
- </motion.div>
+ <div className="flex items-center gap-2">
+ {/* biome-ignore lint/a11y/useHeadingContent: Quill supplies the heading text through this render target. */}
+ <Heading size="xl" render={<h1 className="font-bold" />}>
+ Connect your codebase
+ </Heading>
+ <OptionalBadge />
+ </div>
+ <Text size="sm" variant="muted">
+ Unlocks cloud environments and self-driving tasks.
+ </Text>
+ </motion.div>
- <motion.div
- initial={{ opacity: 0, y: 8 }}
- animate={{ opacity: 1, y: 0 }}
- transition={{ duration: 0.3, delay: 0.02 }}
- >
- <Flex direction="column" gap="2">
- <Flex align="center" gap="2">
- <Text className="font-bold text-(--gray-12) text-2xl">
- Connect your codebase
- </Text>
- <OptionalBadge />
- </Flex>
- <Text className="text-(--gray-11) text-sm">
- Code access helps us understand your product, and helps you
- build.
- </Text>
- </Flex>
- </motion.div>
-
- <motion.div
- key="github-panel"
- initial={{ opacity: 0, y: 8 }}
- animate={{ opacity: 1, y: 0 }}
- transition={{ duration: 0.3, delay: 0.05 }}
- >
- <GitHubConnectPanel />
- </motion.div>
- </Flex>
- </Flex>
- </Flex>
-
- <StepActions>
- {onBack && (
- <Button size="3" variant="outline" color="gray" onClick={onBack}>
- <ArrowLeft size={16} weight="bold" />
- Back
- </Button>
- )}
- <Button
- size="3"
- variant={isConnected ? "solid" : "outline"}
- color={isConnected ? undefined : "gray"}
- onClick={handleContinue}
- >
- {isConnected ? "Continue" : "Skip for now"}
- <ArrowRight size={16} weight="bold" />
- </Button>
- </StepActions>
- </Flex>
- </Flex>
+ <motion.div
+ key="github-panel"
+ initial={shouldReduceMotion ? false : { opacity: 0, y: 8 }}
+ animate={{ opacity: 1, y: 0 }}
+ transition={{ duration: 0.25, delay: 0.03, ease: "easeOut" }}
+ >
+ <div className="flex flex-col gap-4">
+ <GithubConnectionEmpty
+ connected={isConnected}
+ showLearnMore={false}
+ className="border-solid"
+ description={
+ isConnected
+ ? "GitHub connected"
+ : "Gives PostHog Desktop read access to your repos"
+ }
+ >
+ <GitHubConnectPanel />
+ </GithubConnectionEmpty>
+ <StepActions
+ primaryAction={
+ <Button
+ size="lg"
+ variant={isConnected ? "primary" : "outline"}
+ onClick={handleContinue}
+ >
+ {isConnected ? "Continue" : "Skip for now"}
+ <ArrowRight size={16} weight="bold" />
+ </Button>
+ }
+ >
+ {onBack && (
+ <Button size="lg" onClick={onBack}>
+ <ArrowLeft size={16} weight="bold" />
+ Back
+ </Button>
+ )}
+ </StepActions>
+ </div>
+ </motion.div>
+ </div>
+ </main>
);
}
diff --git a/products/desktop/packages/ui/src/features/onboarding/components/GitHubConnectPanel.tsx b/products/desktop/packages/ui/src/features/onboarding/components/GitHubConnectPanel.tsx
index 81a0827a6a5e..b7c127750a4f 100644
--- a/products/desktop/packages/ui/src/features/onboarding/components/GitHubConnectPanel.tsx
+++ b/products/desktop/packages/ui/src/features/onboarding/components/GitHubConnectPanel.tsx
@@ -3,11 +3,13 @@ import {
ArrowsClockwise,
CheckCircle,
GearSix,
+ Info,
Plus,
- Trash,
+ WarningCircle,
} from "@phosphor-icons/react";
import {
GITHUB_CONNECT_PENDING_APPROVAL_CODE,
+ isGithubConnectAlreadyLinked,
isGithubConnectPendingApproval,
} from "@posthog/core/integrations/connectErrors";
import { githubInvalidationKeys } from "@posthog/core/integrations/connectMachine";
@@ -19,6 +21,7 @@ import {
deriveAlternativeConnectedProjects,
deriveConnectButtonState,
deriveGithubApprovalState,
+ didGithubConnectCompleteFromIntegrations,
getGithubPanelMessage,
isAnyIntegrationStale,
resolveSelectedProjectId,
@@ -27,10 +30,29 @@ import type { GithubConnectService } from "@posthog/core/onboarding/githubConnec
import { GITHUB_CONNECT_SERVICE } from "@posthog/core/onboarding/identifiers";
import { formatGithubAccountLabel } from "@posthog/core/settings/githubRepoSummary";
import { useService } from "@posthog/di/react";
-import { Button as QuillButton } from "@posthog/quill";
+import {
+ Badge,
+ Button,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+ Item,
+ ItemActions,
+ ItemContent,
+ ItemDescription,
+ ItemMedia,
+ ItemTitle,
+ Skeleton,
+ Text,
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from "@posthog/quill";
import type { OnboardingGithubConnectFlow } from "@posthog/shared/analytics-events";
import { ANALYTICS_EVENTS } from "@posthog/shared/analytics-events";
import { useAuthStateValue } from "@posthog/ui/features/auth/store";
+import { DisconnectIntegrationDialog } from "@posthog/ui/features/integrations/components/DisconnectIntegrationDialog";
import { GithubApprovalNotice } from "@posthog/ui/features/integrations/GithubApprovalNotice";
import { useGithubDisconnect } from "@posthog/ui/features/integrations/useGithubDisconnect";
import { useGithubInstallRequests } from "@posthog/ui/features/integrations/useGithubInstallRequests";
@@ -44,20 +66,10 @@ import {
} from "@posthog/ui/features/integrations/useIntegrations";
import { useProjectsWithIntegrations } from "@posthog/ui/features/onboarding/hooks/useProjectsWithIntegrations";
import { useOnboardingStore } from "@posthog/ui/features/onboarding/onboardingStore";
-import { Spinner } from "@posthog/ui/primitives/Spinner";
-import { Tooltip } from "@posthog/ui/primitives/Tooltip";
import { track } from "@posthog/ui/shell/analytics";
import { openExternalUrl } from "@posthog/ui/shell/openExternal";
-import {
- AlertDialog,
- Button,
- Flex,
- IconButton,
- Skeleton,
- Text,
-} from "@radix-ui/themes";
import { useQueryClient } from "@tanstack/react-query";
-import { useEffect, useMemo, useRef, useState } from "react";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
export function GitHubConnectPanel() {
const queryClient = useQueryClient();
@@ -80,14 +92,25 @@ export function GitHubConnectPanel() {
() => projects.find((p) => p.id === selectedProjectId),
[projects, selectedProjectId],
);
+ const {
+ data: githubUserIntegrations = [],
+ isLoading: githubUserIntegrationsLoading,
+ } = useUserGithubIntegrations();
// Armed on connect start, cleared on any terminal outcome, so an unmount in
// between is reported as an abandoned connect.
const inFlightConnectRef = useRef<{
flowType: OnboardingGithubConnectFlow;
startedAtMs: number;
+ integrationCountAtStart: number;
} | null>(null);
+ const reportConnected = useCallback(() => {
+ if (!inFlightConnectRef.current) return;
+ inFlightConnectRef.current = null;
+ track(ANALYTICS_EVENTS.ONBOARDING_GITHUB_CONNECTED);
+ }, []);
+
const {
error: connectError,
isConnecting,
@@ -95,14 +118,12 @@ export function GitHubConnectPanel() {
hasError: hasConnectError,
isPending: awaitingApproval,
connect: handleConnectGitHub,
+ connectUser: handleConnectAdditionalGitHub,
reset: resetConnect,
} = useGithubConnect({
projectId: selectedProjectId,
projectHasTeamIntegration: selectedProject?.hasGithubIntegration ?? null,
- onConnected: () => {
- inFlightConnectRef.current = null;
- track(ANALYTICS_EVENTS.ONBOARDING_GITHUB_CONNECTED);
- },
+ onConnected: reportConnected,
});
const canTakeAction = !isConnecting && !timedOut && !hasConnectError;
// The callback reports an org-owner wait through onPending when the caller
@@ -120,7 +141,11 @@ export function GitHubConnectPanel() {
flow_type: flowType,
is_retry: isRetry,
});
- inFlightConnectRef.current = { flowType, startedAtMs: Date.now() };
+ inFlightConnectRef.current = {
+ flowType,
+ startedAtMs: Date.now(),
+ integrationCountAtStart: githubUserIntegrations.length,
+ };
};
const initiateConnect = (
@@ -131,6 +156,11 @@ export function GitHubConnectPanel() {
void handleConnectGitHub();
};
+ const initiateAdditionalConnect = () => {
+ markConnectStarted("user_new");
+ void handleConnectAdditionalGitHub();
+ };
+
useEffect(() => {
return () => {
const inFlight = inFlightConnectRef.current;
@@ -146,6 +176,29 @@ export function GitHubConnectPanel() {
};
}, []);
+ useEffect(() => {
+ const inFlight = inFlightConnectRef.current;
+ if (!inFlight) return;
+ // The integration query can confirm success before Electron receives the
+ // deep-link callback. A new integration is a second success signal.
+ if (
+ !didGithubConnectCompleteFromIntegrations({
+ isConnecting,
+ integrationCountAtStart: inFlight.integrationCountAtStart,
+ currentIntegrationCount: githubUserIntegrations.length,
+ })
+ ) {
+ return;
+ }
+ resetConnect();
+ reportConnected();
+ }, [
+ githubUserIntegrations.length,
+ isConnecting,
+ reportConnected,
+ resetConnect,
+ ]);
+
const connectService = useService<GithubConnectService>(
GITHUB_CONNECT_SERVICE,
);
@@ -194,11 +247,8 @@ export function GitHubConnectPanel() {
isConnecting,
isPending: awaitingApproval,
});
+ const isAlreadyLinked = isGithubConnectAlreadyLinked(connectError);
- const {
- data: githubUserIntegrations = [],
- isLoading: githubUserIntegrationsLoading,
- } = useUserGithubIntegrations();
const hasGitIntegration = githubUserIntegrations.length > 0;
const { data: githubInstallRequests } = useGithubInstallRequests();
const approvalState = deriveGithubApprovalState({
@@ -208,8 +258,12 @@ export function GitHubConnectPanel() {
});
const isAwaitingApproval = approvalState === "awaiting";
const isApprovedNotLinked = approvalState === "approved";
- const { failedInstallationIds, reposByInstallationId } =
- useUserRepositoryIntegration();
+ const {
+ failedInstallationIds,
+ reposByInstallationId,
+ isRefreshingRepos,
+ refreshRepositories,
+ } = useUserRepositoryIntegration();
const anyIntegrationStale = isAnyIntegrationStale(
githubUserIntegrations,
failedInstallationIds,
@@ -224,10 +278,9 @@ export function GitHubConnectPanel() {
),
[hasGitIntegration, projectsWithGithub, selectedProjectId],
);
- const [selectedAlternativeId] = useState<number | null>(null);
- const [isRefreshing, setIsRefreshing] = useState(false);
- const refreshGithubState = async () => {
- setIsRefreshing(true);
+ const [isCheckingStatus, setIsCheckingStatus] = useState(false);
+ const checkGithubState = async () => {
+ setIsCheckingStatus(true);
try {
await Promise.all(
githubInvalidationKeys(selectedProjectId).map((queryKey) =>
@@ -235,17 +288,10 @@ export function GitHubConnectPanel() {
),
);
} finally {
- setIsRefreshing(false);
+ setIsCheckingStatus(false);
}
};
- const selectedAlternative = useMemo(() => {
- if (!alternativeConnectedProjects.length) return null;
- return (
- alternativeConnectedProjects.find(
- (p) => p.id === selectedAlternativeId,
- ) ?? alternativeConnectedProjects[0]
- );
- }, [alternativeConnectedProjects, selectedAlternativeId]);
+ const selectedAlternative = alternativeConnectedProjects[0] ?? null;
// Which connect path applies. The user presses the same button either way.
const teamConnectFlow: OnboardingGithubConnectFlow | null =
@@ -267,16 +313,13 @@ export function GitHubConnectPanel() {
return (
<div>
- <Flex direction="column" gap="3">
- <Flex direction="column" gap="1" className="empty:hidden">
- {(isLoading || githubUserIntegrationsLoading) && (
- <Skeleton className="h-[16px] w-[80px]" />
- )}
+ <div className="flex flex-col gap-3">
+ <div className="flex flex-col gap-1 empty:hidden">
{!isLoading &&
!githubUserIntegrationsLoading &&
hasGitIntegration &&
anyIntegrationStale && (
- <Text className="text-(--amber-11) text-[13px]">
+ <Text size="xs" className="text-warning-foreground">
Reconnect needed
</Text>
)}
@@ -284,23 +327,20 @@ export function GitHubConnectPanel() {
!isLoading &&
!githubUserIntegrationsLoading &&
(isAwaitingApproval ? (
- <GithubApprovalNotice state="awaiting" className="pt-3" />
+ <GithubApprovalNotice state="awaiting" />
) : isApprovedNotLinked ? (
- <GithubApprovalNotice state="approved" className="pt-3" />
+ <GithubApprovalNotice state="approved" />
) : defaultPanelMessage ? (
<Text
- className={
- hasConnectError
- ? "text-(--red-11) text-sm"
- : "text-(--gray-11) text-sm"
- }
+ size="sm"
+ variant={hasConnectError ? "destructive" : "muted"}
>
{defaultPanelMessage}
</Text>
) : null)}
- </Flex>
+ </div>
{hasGitIntegration ? (
- <Flex direction="column" gap="3">
+ <div className="flex flex-col gap-3">
{githubUserIntegrations.map((integration) => {
const installationId = integration.installation_id;
const accountName = formatGithubAccountLabel(
@@ -313,101 +353,74 @@ export function GitHubConnectPanel() {
const isReconnecting =
reconnectingInstallationId === installationId;
return (
- <Flex
+ <Item
key={integration.id}
- direction="column"
- gap="2"
- p="3"
- className="rounded-[10px] border border-(--gray-a4) bg-(--color-panel-solid)"
+ variant="outline"
+ size="sm"
+ tone={isStale ? "warning" : "success"}
+ className="w-full pr-2"
>
- <Flex align="center" justify="between" gap="2" wrap="wrap">
- <Flex align="center" gap="2">
- {!isStale && (
- <CheckCircle
- size={15}
- weight="fill"
- className="shrink-0 text-(--green-9)"
- />
- )}
- <Text className="font-bold text-(--gray-12) text-sm">
+ <ItemMedia variant="icon">
+ {isStale ? (
+ <WarningCircle
+ size={15}
+ weight="fill"
+ className="text-warning-foreground"
+ />
+ ) : (
+ <CheckCircle
+ size={15}
+ weight="fill"
+ className="text-success-foreground"
+ />
+ )}
+ </ItemMedia>
+ <ItemContent>
+ <ItemTitle className="flex min-w-0 items-center gap-2">
+ <span className="truncate font-semibold">
{accountName}
- </Text>
- <Text className="text-(--gray-10) text-[12px]">
+ </span>
+ <Badge variant="default">
{integration.account?.type === "Organization"
? "org"
: "personal"}
- </Text>
- </Flex>
+ </Badge>
+ </ItemTitle>
{isStale && (
- <Text className="text-(--amber-11) text-[12px]">
+ <ItemDescription className="text-warning-foreground">
Reconnect needed
+ </ItemDescription>
+ )}
+ </ItemContent>
+ <ItemActions className="flex shrink-0 items-center gap-2">
+ {!isStale && (
+ <Text size="xs" variant="muted">
+ {isLoadingInstallRepos
+ ? "Loading..."
+ : installRepos.length === 1
+ ? "1 repo"
+ : `${installRepos.length} repos`}
</Text>
)}
- <Flex align="center" gap="3">
- {!isStale && (
- <Text className="text-(--gray-10) text-[12px]">
- {isLoadingInstallRepos
- ? "Loading…"
- : installRepos.length === 1
- ? "1 repo"
- : `${installRepos.length} repos`}
- </Text>
- )}
- <Tooltip content="Manage on GitHub">
- <IconButton
- size="1"
- variant="ghost"
- color="gray"
- aria-label={`Manage ${accountName} on GitHub`}
- onClick={() =>
- openExternalUrl(
- buildInstallationSettingsUrl(
- integration.account,
- installationId,
- ),
- )
- }
- >
- <GearSix size={14} />
- </IconButton>
- </Tooltip>
- <Tooltip content="Disconnect">
- <IconButton
- size="1"
- variant="ghost"
- color="gray"
- aria-label={`Disconnect ${accountName}`}
- onClick={() =>
- setDisconnectTarget({ installationId, accountName })
- }
- >
- <Trash size={14} />
- </IconButton>
- </Tooltip>
- </Flex>
- </Flex>
- <Flex
- align="center"
- gap="3"
- wrap="wrap"
- className="empty:hidden"
- >
{isStale && (
<Button
- size="1"
- variant="solid"
- disabled={reconnectingInstallationId !== null}
+ size="sm"
+ variant="outline"
+ loading={isReconnecting}
+ disabled={
+ reconnectingInstallationId !== null && !isReconnecting
+ }
onClick={async () => {
markConnectStarted("user_new", true);
setReconnectingInstallationId(installationId);
try {
await reconnect(
installationId,
- handleConnectGitHub,
+ handleConnectAdditionalGitHub,
);
} catch {
// The pre-connect disconnect failed, so no
- // connect flow ever started; a later unmount
+ // connect flow ever started. A later unmount
// must not report this as user abandonment.
inFlightConnectRef.current = null;
} finally {
@@ -415,85 +428,163 @@ export function GitHubConnectPanel() {
}
}}
>
- {isReconnecting && <Spinner size="sm" />}
Reconnect
<ArrowSquareOut size={12} />
</Button>
)}
- </Flex>
- </Flex>
+ <DropdownMenu>
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <DropdownMenuTrigger
+ render={
+ <Button
+ size="icon-sm"
+ variant="default"
+ aria-label={`Manage ${accountName}`}
+ >
+ <GearSix size={14} />
+ </Button>
+ }
+ />
+ }
+ />
+ <TooltipContent>Manage</TooltipContent>
+ </Tooltip>
+ <DropdownMenuContent
+ align="end"
+ side="bottom"
+ sideOffset={6}
+ className="min-w-fit"
+ >
+ <DropdownMenuItem
+ onClick={() =>
+ openExternalUrl(
+ buildInstallationSettingsUrl(
+ integration.account,
+ installationId,
+ ),
+ )
+ }
+ >
+ Open settings on GitHub
+ <ArrowSquareOut size={12} className="ml-auto" />
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ variant="destructive"
+ onClick={() =>
+ setDisconnectTarget({
+ installationId,
+ accountName,
+ })
+ }
+ >
+ Disconnect...
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </ItemActions>
+ </Item>
);
})}
- <Flex align="center" gap="3" wrap="wrap">
- <Button
- size="1"
- variant="soft"
- color="gray"
- disabled={isRefreshing}
- onClick={() => void refreshGithubState()}
- >
- {isRefreshing ? (
- <Spinner size="sm" />
- ) : (
+ <div className="flex flex-wrap items-center gap-2">
+ {isRefreshingRepos ? (
+ <Skeleton className="h-6 w-[76px] rounded-md" />
+ ) : (
+ <Button
+ size="sm"
+ variant="default"
+ onClick={() => void refreshRepositories()}
+ >
<ArrowsClockwise size={12} />
- )}
- Refresh
- </Button>
- <Button
- size="1"
- variant="ghost"
- color="gray"
- onClick={() => initiateConnect("user_new")}
- disabled={isConnecting}
+ Refresh
+ </Button>
+ )}
+ {isConnecting ? (
+ <Skeleton className="h-6 w-[171px] rounded-md" />
+ ) : (
+ <Button
+ size="sm"
+ variant="link-muted"
+ onClick={initiateAdditionalConnect}
+ >
+ <Plus size={12} />
+ Add org
+ </Button>
+ )}
+ </div>
+ {defaultPanelMessage && (
+ <Item
+ variant="muted"
+ size="sm"
+ tone={
+ isAlreadyLinked
+ ? "info"
+ : hasConnectError
+ ? "destructive"
+ : "warning"
+ }
>
- {isConnecting ? <Spinner size="sm" /> : <Plus size={12} />}
- Add another GitHub org
- </Button>
- </Flex>
- </Flex>
+ <ItemMedia variant="icon">
+ {isAlreadyLinked ? (
+ <Info size={15} weight="fill" />
+ ) : (
+ <WarningCircle size={15} weight="fill" />
+ )}
+ </ItemMedia>
+ <ItemContent>
+ <ItemTitle>
+ {isAlreadyLinked
+ ? "No other GitHub organizations to add"
+ : hasConnectError
+ ? "Couldn't connect GitHub"
+ : timedOut
+ ? "GitHub did not respond"
+ : "Waiting for approval"}
+ </ItemTitle>
+ <ItemDescription>{defaultPanelMessage}</ItemDescription>
+ </ItemContent>
+ </Item>
+ )}
+ </div>
) : isAwaitingApproval ? (
<Button
- size="2"
- variant="soft"
- color="gray"
+ size="sm"
+ variant="outline"
className="self-start"
- disabled={isRefreshing}
- onClick={() => void refreshGithubState()}
+ loading={isCheckingStatus}
+ onClick={() => void checkGithubState()}
>
- {isRefreshing ? (
- <Spinner size="sm" />
- ) : (
- <ArrowsClockwise size={12} />
- )}
+ <ArrowsClockwise size={12} />
Check again
</Button>
) : isApprovedNotLinked ? (
- <QuillButton
+ <Button
variant="primary"
size="lg"
- className="h-[44px] w-full"
+ className="w-full"
loading={isConnecting}
onClick={() => initiateConnect("user_new")}
>
Sign in with GitHub
<ArrowSquareOut size={12} />
- </QuillButton>
+ </Button>
) : !isLoading && !githubUserIntegrationsLoading ? (
teamConnectFlow && canTakeAction ? (
<Button
- size="3"
- variant="solid"
+ size="lg"
+ variant="primary"
onClick={() => initiateConnect(teamConnectFlow)}
- className="w-full"
+ className="w-fit self-center"
>
Sign in with GitHub
<ArrowSquareOut size={12} />
</Button>
) : (
- <Flex direction="column" gap="2" className="w-full">
+ <div className="flex w-full flex-col gap-2">
<Button
- size="3"
- variant="solid"
+ size="lg"
+ variant="primary"
onClick={() => {
const { isRetry, shouldReset } = deriveConnectButtonState({
isConnecting,
@@ -503,10 +594,9 @@ export function GitHubConnectPanel() {
if (shouldReset) resetConnect();
initiateConnect("user_new", isRetry);
}}
- disabled={isConnecting}
- className="w-full"
+ loading={isConnecting}
+ className="w-fit self-center"
>
- {isConnecting && <Spinner size="md" />}
{
deriveConnectButtonState({
isConnecting,
@@ -518,59 +608,30 @@ export function GitHubConnectPanel() {
</Button>
{hasConnectError && (
<Button
- size="1"
- variant="ghost"
- color="gray"
+ size="sm"
+ variant="link-muted"
onClick={resetConnect}
className="self-start"
>
Dismiss
</Button>
)}
- </Flex>
+ </div>
)
) : null}
- </Flex>
- <AlertDialog.Root
+ </div>
+ <DisconnectIntegrationDialog
open={disconnectTarget !== null}
- onOpenChange={(next: boolean) => {
- if (!next && !isDisconnecting) {
- setDisconnectTarget(null);
- }
+ title={`Disconnect ${disconnectTarget?.accountName ?? "GitHub"}`}
+ description="This removes your personal GitHub authorization from PostHog. The GitHub app stays installed. Remove it in GitHub if you also want to uninstall the app."
+ isPending={isDisconnecting}
+ onCancel={() => setDisconnectTarget(null)}
+ onConfirm={() => {
+ if (!disconnectTarget) return;
+ disconnect({ installationId: disconnectTarget.installationId });
+ setDisconnectTarget(null);
}}
- >
- <AlertDialog.Content maxWidth="450px">
- <AlertDialog.Title>
- Disconnect{" "}
- {disconnectTarget ? disconnectTarget.accountName : "GitHub"}
- </AlertDialog.Title>
- <AlertDialog.Description className="text-sm">
- This removes your personal GitHub authorization from PostHog. You
- can reconnect at any time. The GitHub App itself stays installed in
- your org, so uninstall it on GitHub if you want to remove that too.
- </AlertDialog.Description>
- <Flex gap="3" mt="4" justify="end">
- <AlertDialog.Cancel>
- <Button variant="soft" color="gray" disabled={isDisconnecting}>
- Cancel
- </Button>
- </AlertDialog.Cancel>
- <Button
- variant="solid"
- color="red"
- onClick={() => {
- if (!disconnectTarget) return;
- disconnect({ installationId: disconnectTarget.installationId });
- setDisconnectTarget(null);
- }}
- disabled={isDisconnecting}
- >
- {isDisconnecting ? <Spinner size="sm" /> : null}
- Disconnect
- </Button>
- </Flex>
- </AlertDialog.Content>
- </AlertDialog.Root>
+ />
</div>
);
}
diff --git a/products/desktop/packages/ui/src/features/onboarding/components/GithubConnectionLink.stories.tsx b/products/desktop/packages/ui/src/features/onboarding/components/GithubConnectionLink.stories.tsx
deleted file mode 100644
index ae3799ade443..000000000000
--- a/products/desktop/packages/ui/src/features/onboarding/components/GithubConnectionLink.stories.tsx
+++ /dev/null
@@ -1,15 +0,0 @@
-import { GithubConnectionLink } from "@posthog/ui/features/onboarding/components/GithubConnectionLink";
-import type { Meta, StoryObj } from "@storybook/react-vite";
-
-const meta: Meta<typeof GithubConnectionLink> = {
- title: "Onboarding/GithubConnectionLink",
- component: GithubConnectionLink,
-};
-export default meta;
-
-type Story = StoryObj<typeof GithubConnectionLink>;
-
-export const Disconnected: Story = { args: { connected: false } };
-export const Connected: Story = {
- args: { connected: true, accountLabel: "Connected as adboio" },
-};
diff --git a/products/desktop/packages/ui/src/features/onboarding/components/GithubConnectionLink.tsx b/products/desktop/packages/ui/src/features/onboarding/components/GithubConnectionLink.tsx
deleted file mode 100644
index b5bf0d5ec35d..000000000000
--- a/products/desktop/packages/ui/src/features/onboarding/components/GithubConnectionLink.tsx
+++ /dev/null
@@ -1,62 +0,0 @@
-import { GithubLogo } from "@phosphor-icons/react";
-import { cn } from "@posthog/quill";
-import Logo from "@posthog/ui/primitives/Logo";
-import { Flex, Text } from "@radix-ui/themes";
-import type { ReactNode } from "react";
-
-function Tile({ children }: { children: ReactNode }) {
- return (
- <Flex
- align="center"
- justify="center"
- className="size-[48px] shrink-0 rounded-[12px] border border-(--gray-a4) bg-(--color-panel-solid)"
- >
- {children}
- </Flex>
- );
-}
-
-interface GithubConnectionLinkProps {
- connected: boolean;
- /** Shown under the link once a connection exists. */
- accountLabel?: string | null;
-}
-
-/** The link between the two marks carries the connection state. */
-export function GithubConnectionLink({
- connected,
- accountLabel,
-}: GithubConnectionLinkProps) {
- return (
- <Flex direction="column" align="center" gap="2">
- <Flex align="center">
- <Tile>
- <span className="[&>svg]:h-[17px] [&>svg]:w-auto">
- <Logo wordmark={false} />
- </span>
- </Tile>
- <div
- className={cn(
- "w-[56px] border-t-2 transition-colors duration-300",
- connected
- ? "border-(--green-9) border-solid"
- : "border-(--gray-a6) border-dashed",
- )}
- />
- <Tile>
- <GithubLogo
- size={26}
- weight="fill"
- className={cn(
- "transition-colors duration-300",
- connected ? "text-(--gray-12)" : "text-(--gray-9)",
- )}
- />
- </Tile>
- </Flex>
- {connected && accountLabel && (
- <Text className="text-(--green-11) text-[13px]">{accountLabel}</Text>
- )}
- </Flex>
- );
-}
diff --git a/products/desktop/packages/ui/src/features/onboarding/components/InstallCliStep.tsx b/products/desktop/packages/ui/src/features/onboarding/components/InstallCliStep.tsx
index a16fb52959fe..2fdf6b9298bd 100644
--- a/products/desktop/packages/ui/src/features/onboarding/components/InstallCliStep.tsx
+++ b/products/desktop/packages/ui/src/features/onboarding/components/InstallCliStep.tsx
@@ -471,15 +471,18 @@ export function InstallCliStep({ onNext, onBack }: InstallCliStepProps) {
</Flex>
</Flex>
- <StepActions>
+ <StepActions
+ primaryAction={
+ <Button size="3" onClick={handleContinue}>
+ Continue
+ <ArrowRight size={16} weight="bold" />
+ </Button>
+ }
+ >
<Button size="3" variant="outline" color="gray" onClick={onBack}>
<ArrowLeft size={16} weight="bold" />
Back
</Button>
- <Button size="3" onClick={handleContinue}>
- Continue
- <ArrowRight size={16} weight="bold" />
- </Button>
</StepActions>
</Flex>
</Flex>
diff --git a/products/desktop/packages/ui/src/features/onboarding/components/OnboardingFlow.tsx b/products/desktop/packages/ui/src/features/onboarding/components/OnboardingFlow.tsx
index dc93b99e4239..aabb79916357 100644
--- a/products/desktop/packages/ui/src/features/onboarding/components/OnboardingFlow.tsx
+++ b/products/desktop/packages/ui/src/features/onboarding/components/OnboardingFlow.tsx
@@ -1,10 +1,11 @@
-import { ArrowRight, SignOut } from "@phosphor-icons/react";
-import { getAuthIdentity } from "@posthog/core/auth/authIdentity";
-import { integrationKeys } from "@posthog/core/integrations/repositoryKeys";
import {
- classifyIntegrations,
- type Integration,
-} from "@posthog/core/integrations/selectors";
+ ArrowLeft,
+ ArrowRight,
+ CheckCircle,
+ Lifebuoy,
+ SignOut,
+} from "@phosphor-icons/react";
+import { getAuthIdentity } from "@posthog/core/auth/authIdentity";
import {
buildAbandonedProps,
buildCompletedProps,
@@ -12,31 +13,37 @@ import {
type StepCompletedContext,
} from "@posthog/core/onboarding/analytics";
import {
- planSpaceRepoAssignments,
- resolveRepoIntegrationId,
-} from "@posthog/core/onboarding/spaceRepoAssignment";
+ Button,
+ ButtonGroup,
+ Item,
+ ItemActions,
+ ItemContent,
+ ItemMedia,
+ ItemTitle,
+ Text,
+} from "@posthog/quill";
import { ANALYTICS_EVENTS } from "@posthog/shared/analytics-events";
-import type { TaskChannel } from "@posthog/shared/domain-types";
import { useOptionalAuthenticatedClient } from "@posthog/ui/features/auth/authClient";
import { useAuthStateValue } from "@posthog/ui/features/auth/store";
import { useLogoutMutation } from "@posthog/ui/features/auth/useAuthMutations";
-import { AUTH_SCOPED_QUERY_META } from "@posthog/ui/features/auth/useCurrentUser";
-import { TASK_CHANNELS_QUERY_KEY } from "@posthog/ui/features/canvas/hooks/useTaskChannels";
+import { useCurrentUser } from "@posthog/ui/features/auth/useCurrentUser";
import { ConsentStep } from "@posthog/ui/features/consent/ConsentStep";
import { useUserGithubIntegrations } from "@posthog/ui/features/integrations/useIntegrations";
import { ConnectGitHubStep } from "@posthog/ui/features/onboarding/components/ConnectGitHubStep";
import { InstallCliStep } from "@posthog/ui/features/onboarding/components/InstallCliStep";
import { useOnboardingFlow } from "@posthog/ui/features/onboarding/hooks/useOnboardingFlow";
import { useOnboardingStore } from "@posthog/ui/features/onboarding/onboardingStore";
+import { saveOnboardingRepository } from "@posthog/ui/features/onboarding/saveOnboardingRepository";
import { useSettingsStore } from "@posthog/ui/features/settings/settingsStore";
import { shipIt } from "@posthog/ui/primitives/confetti";
import { FullScreenLayout } from "@posthog/ui/primitives/FullScreenLayout";
+import { ProductWordmark } from "@posthog/ui/primitives/ProductWordmark";
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 { useHostCapabilities } from "@posthog/ui/shell/useHostCapabilities";
-import { Button, Flex } from "@radix-ui/themes";
+import { isMac, isWindows } from "@posthog/ui/utils/platform";
import { useQueryClient } from "@tanstack/react-query";
import { AnimatePresence, motion } from "framer-motion";
import { useEffect, useRef, useState } from "react";
@@ -58,8 +65,163 @@ interface OnboardingFlowProps {
onOpenSupport?: () => void;
}
+function OnboardingAccount({
+ email,
+ isAuthenticated,
+ isLoggingOut,
+ onLogout,
+}: {
+ email?: string;
+ isAuthenticated: boolean;
+ isLoggingOut: boolean;
+ onLogout: () => void;
+}) {
+ if (!isAuthenticated) return null;
+
+ return (
+ <aside className="absolute right-8 bottom-6 z-[2] w-[380px] max-w-[calc(100%-4rem)]">
+ <Item
+ variant="muted"
+ size="sm"
+ className="w-full border border-border py-1"
+ >
+ <ItemMedia variant="icon">
+ <CheckCircle
+ size={14}
+ weight="fill"
+ className="text-success-foreground"
+ />
+ </ItemMedia>
+ <ItemContent>
+ <ItemTitle className="max-w-full truncate font-normal text-xs">
+ Signed in as {email ?? "your PostHog account"}
+ </ItemTitle>
+ </ItemContent>
+ <ItemActions>
+ <Button
+ size="xs"
+ variant="link-muted"
+ className="min-h-11"
+ onClick={onLogout}
+ loading={isLoggingOut}
+ >
+ <SignOut size={14} />
+ Log out
+ </Button>
+ </ItemActions>
+ </Item>
+ </aside>
+ );
+}
+
+function OnboardingDebugNavigation({
+ currentIndex,
+ totalSteps,
+ onBack,
+ onNext,
+}: {
+ currentIndex: number;
+ totalSteps: number;
+ onBack: () => void;
+ onNext: () => void;
+}) {
+ if (!IS_DEV) return null;
+
+ return (
+ <nav
+ aria-label="Onboarding debug navigation"
+ className="no-drag flex items-center gap-2"
+ >
+ <ButtonGroup aria-label="Onboarding step navigation">
+ <Button
+ size="icon-sm"
+ variant="outline"
+ aria-label="Previous onboarding step"
+ disabled={currentIndex <= 0}
+ onClick={onBack}
+ >
+ <ArrowLeft size={12} />
+ </Button>
+ <Button
+ size="icon-sm"
+ variant="outline"
+ aria-label="Next onboarding step"
+ disabled={currentIndex < 0 || currentIndex >= totalSteps - 1}
+ onClick={onNext}
+ >
+ <ArrowRight size={12} />
+ </Button>
+ </ButtonGroup>
+ <Text size="xs" variant="muted">
+ {currentIndex + 1} / {totalSteps}
+ </Text>
+ </nav>
+ );
+}
+
+function OnboardingHeader({
+ currentIndex,
+ totalSteps,
+ onBack,
+ onNext,
+ onOpenSupport,
+ onSkip,
+ showSkipSetup,
+}: {
+ currentIndex: number;
+ totalSteps: number;
+ onBack: () => void;
+ onNext: () => void;
+ onOpenSupport?: () => void;
+ onSkip: () => void;
+ showSkipSetup: boolean;
+}) {
+ return (
+ <header
+ className="flex h-10 w-full items-center gap-3"
+ style={{
+ paddingLeft: isMac ? "env(titlebar-area-x, 78px)" : "78px",
+ paddingRight: isWindows ? "140px" : "12px",
+ }}
+ >
+ <div className="no-drag [&_p]:!text-md [&_svg]:!h-[18px] [&_svg]:!w-auto flex items-center">
+ <ProductWordmark />
+ </div>
+ <OnboardingDebugNavigation
+ currentIndex={currentIndex}
+ totalSteps={totalSteps}
+ onBack={onBack}
+ onNext={onNext}
+ />
+ <div className="no-drag ml-auto flex items-center gap-1">
+ <Button
+ size="xs"
+ variant="link-muted"
+ className="min-h-8 px-2 text-xs opacity-80 hover:opacity-100"
+ onClick={onOpenSupport}
+ >
+ <Lifebuoy size={12} />
+ Get support
+ </Button>
+ {showSkipSetup && (
+ <Button
+ size="xs"
+ variant="link-muted"
+ className="min-h-8 px-2 text-xs opacity-80 hover:opacity-100"
+ onClick={onSkip}
+ >
+ Skip setup
+ <ArrowRight size={12} weight="bold" />
+ </Button>
+ )}
+ </div>
+ </header>
+ );
+}
+
export function OnboardingFlow({ onOpenSupport }: OnboardingFlowProps) {
const [consentSubmitting, setConsentSubmitting] = useState(false);
+ const [isCompleting, setIsCompleting] = useState(false);
const queryClient = useQueryClient();
const {
currentStep,
@@ -91,66 +253,27 @@ export function OnboardingFlow({ onOpenSupport }: OnboardingFlowProps) {
(state) => state.setLastUsedWorkspaceMode,
);
const apiClient = useOptionalAuthenticatedClient();
+ const { data: currentUser } = useCurrentUser({ client: apiClient });
const { localWorkspaces } = useHostCapabilities();
const startupIdentity = useAuthStateValue(getAuthIdentity);
- // Best-effort. The response also seeds the channel cache that the first-run
- // landing reads moments later.
+ // Best-effort. This also seeds the cache that the first screen reads.
const assignRepoToSpaces = async (): Promise<void> => {
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 already
- // auth-scoped via useAuthenticatedQuery; this covers the one write that precedes them.
- queryClient.setQueryDefaults(TASK_CHANNELS_QUERY_KEY, {
- meta: AUTH_SCOPED_QUERY_META,
- });
- queryClient.setQueryData(TASK_CHANNELS_QUERY_KEY, provisioned.channels);
- // Cloud-only hosts keep the picked GitHub repo in selectedDirectory (they
- // never set selectedCloudRepo). On local-workspace hosts selectedDirectory
- // can be a filesystem path, so only the explicit cloud pick is a valid
- // "owner/repo" space default there.
+ // Cloud-only hosts store the GitHub repository in selectedDirectory.
+ // Local-workspace hosts keep cloud and local selections separate.
const cloudRepo = localWorkspaces
? selectedCloudRepo
: selectedDirectory || null;
if (!cloudRepo) return;
- // Fetched directly: the integrations store only fills once the main app's
- // hooks mount, which has not happened during onboarding.
- const integrations = await queryClient.fetchQuery({
- queryKey: integrationKeys.list(),
- queryFn: () => apiClient.getIntegrations() as Promise<Integration[]>,
- staleTime: 60_000,
- meta: AUTH_SCOPED_QUERY_META,
+ const provisioned = await firstRun(startupIdentity, apiClient).provisioned;
+ if (!provisioned) return;
+ await saveOnboardingRepository({
+ client: apiClient,
+ provisioned,
+ queryClient,
+ repository: cloudRepo,
});
- const integrationId = resolveRepoIntegrationId(
- cloudRepo,
- classifyIntegrations(integrations).githubIntegrations,
- );
- // Channels only accept a team integration alongside repositories, so a
- // user-level-only GitHub connection cannot set a space default.
- if (integrationId == null) return;
- for (const channelId of planSpaceRepoAssignments(provisioned.channels, {
- personalCreated: provisioned.personal_created,
- generalCreated: provisioned.general_created,
- })) {
- const updated = await apiClient.updateTaskChannelRepositories(
- channelId,
- integrationId,
- [cloudRepo],
- );
- // The direct API call bypasses the standard mutation's cache sync, so
- // patch the seeded channel cache with the assigned repository. Otherwise
- // consumers stay on the repository-less provision response until the poll.
- queryClient.setQueryData<TaskChannel[]>(
- TASK_CHANNELS_QUERY_KEY,
- (channels) =>
- channels?.map((channel) =>
- channel.id === updated.id ? updated : channel,
- ),
- );
- }
};
const flowStartedAtRef = useRef(Date.now());
@@ -237,7 +360,9 @@ export function OnboardingFlow({ onOpenSupport }: OnboardingFlowProps) {
]);
useHotkeys("left", handleBack, { enableOnFormTags: false }, [handleBack]);
- const handleComplete = (repoSkipped: boolean) => {
+ const handleComplete = async (repoSkipped: boolean) => {
+ if (isCompleting) return;
+ setIsCompleting(true);
if (repoSkipped) {
track(ANALYTICS_EVENTS.ONBOARDING_STEP_SKIPPED, {
step_id: currentStep,
@@ -266,15 +391,18 @@ export function OnboardingFlow({ onOpenSupport }: OnboardingFlowProps) {
localWorkspaces && !selectedCloudRepo && !!selectedDirectory;
setLastUsedWorkspaceMode(pickedLocalRepo ? "local" : "cloud");
}
- assignRepoToSpaces().catch((error) =>
- log.warn("Failed to save onboarding repo to spaces", { error }),
- );
+ try {
+ await assignRepoToSpaces();
+ } catch (error) {
+ log.warn("Failed to save onboarding repo to spaces", { error });
+ }
shipIt();
completeOnboarding();
openTaskInput();
};
const handleSkip = () => {
+ if (isCompleting) return;
track(ANALYTICS_EVENTS.ONBOARDING_STEP_SKIPPED, {
step_id: currentStep,
step_index: currentIndex,
@@ -297,128 +425,127 @@ export function OnboardingFlow({ onOpenSupport }: OnboardingFlowProps) {
resetOnboarding();
};
- const footerRight = (
- <Flex gap="5">
- {isAuthenticated && (
- <Button
- size="1"
- variant="ghost"
- color="gray"
- onClick={handleLogout}
- className="opacity-50"
- >
- <SignOut size={14} />
- Log out
- </Button>
- )}
- {IS_DEV && isAuthenticated && (
- <Button
- size="1"
- variant="ghost"
- color="gray"
- onClick={handleSkip}
- className="opacity-50"
- >
- <ArrowRight size={14} weight="bold" />
- Skip setup
- </Button>
- )}
- </Flex>
- );
-
return (
- <FullScreenLayout footerRight={footerRight} onOpenSupport={onOpenSupport}>
- <AnimatePresence mode="wait" custom={direction}>
- {currentStep === "project-select" && (
- <motion.div
- key="project-select"
- custom={direction}
- initial="enter"
- animate="center"
- exit="exit"
- variants={stepVariants}
- transition={{ duration: 0.3 }}
- className="min-h-0 w-full flex-1"
- >
- <ProjectSelectStep onNext={handleNext} onBack={onBack} />
- </motion.div>
- )}
+ <FullScreenLayout
+ backgroundPattern="grid"
+ showFooter={false}
+ titleBarContent={
+ <OnboardingHeader
+ currentIndex={currentIndex}
+ totalSteps={activeSteps.length}
+ onBack={back}
+ onNext={next}
+ onOpenSupport={onOpenSupport}
+ onSkip={handleSkip}
+ showSkipSetup={IS_DEV && isAuthenticated}
+ />
+ }
+ >
+ <OnboardingAccount
+ email={currentUser?.email}
+ isAuthenticated={isAuthenticated}
+ isLoggingOut={logoutMutation.isPending}
+ onLogout={handleLogout}
+ />
+ <div className="h-full overflow-y-auto px-8 pt-16">
+ <div className="mx-auto flex min-h-full w-full max-w-[720px] flex-col items-center">
+ <div className="w-full">
+ <div aria-hidden="true" className="h-20 shrink-0" />
+ <AnimatePresence mode="wait" custom={direction}>
+ {currentStep === "project-select" && (
+ <motion.div
+ key="project-select"
+ custom={direction}
+ initial="enter"
+ animate="center"
+ exit="exit"
+ variants={stepVariants}
+ transition={{ duration: 0.3 }}
+ className="w-full"
+ >
+ <ProjectSelectStep onNext={handleNext} onBack={onBack} />
+ </motion.div>
+ )}
- {currentStep === "consent" && (
- <motion.div
- key="consent"
- custom={direction}
- initial="enter"
- animate="center"
- exit="exit"
- variants={stepVariants}
- transition={{ duration: 0.3 }}
- className="min-h-0 w-full flex-1"
- >
- <ConsentStep
- onNext={handleNext}
- onBack={onBack}
- requirements={consentRequirement}
- onSubmittingChange={setConsentSubmitting}
- />
- </motion.div>
- )}
+ {currentStep === "consent" && (
+ <motion.div
+ key="consent"
+ custom={direction}
+ initial="enter"
+ animate="center"
+ exit="exit"
+ variants={stepVariants}
+ transition={{ duration: 0.3 }}
+ className="w-full"
+ >
+ <ConsentStep
+ onNext={handleNext}
+ onBack={onBack}
+ requirements={consentRequirement}
+ onSubmittingChange={setConsentSubmitting}
+ />
+ </motion.div>
+ )}
- {currentStep === "connect-github" && (
- <motion.div
- key="connect-github"
- custom={direction}
- initial="enter"
- animate="center"
- exit="exit"
- variants={stepVariants}
- transition={{ duration: 0.3 }}
- className="min-h-0 w-full flex-1"
- >
- <ConnectGitHubStep onNext={handleNext} onBack={onBack} />
- </motion.div>
- )}
+ {currentStep === "connect-github" && (
+ <motion.div
+ key="connect-github"
+ custom={direction}
+ initial="enter"
+ animate="center"
+ exit="exit"
+ variants={stepVariants}
+ transition={{ duration: 0.3 }}
+ className="w-full"
+ >
+ <ConnectGitHubStep onNext={handleNext} onBack={onBack} />
+ </motion.div>
+ )}
- {currentStep === "install-cli" && (
- <motion.div
- key="install-cli"
- custom={direction}
- initial="enter"
- animate="center"
- exit="exit"
- variants={stepVariants}
- transition={{ duration: 0.3 }}
- className="min-h-0 w-full flex-1"
- >
- <InstallCliStep onNext={handleNext} onBack={handleBack} />
- </motion.div>
- )}
+ {currentStep === "install-cli" && (
+ <motion.div
+ key="install-cli"
+ custom={direction}
+ initial="enter"
+ animate="center"
+ exit="exit"
+ variants={stepVariants}
+ transition={{ duration: 0.3 }}
+ className="w-full"
+ >
+ <InstallCliStep onNext={handleNext} onBack={handleBack} />
+ </motion.div>
+ )}
- {currentStep === "select-repo" && (
- <motion.div
- key="select-repo"
- custom={direction}
- initial="enter"
- animate="center"
- exit="exit"
- variants={stepVariants}
- transition={{ duration: 0.3 }}
- className="min-h-0 w-full flex-1"
- >
- <SelectRepoStep
- onComplete={handleComplete}
- onBack={handleBack}
- selectedDirectory={selectedDirectory}
- detectedRepo={detectedRepo}
- isDetectingRepo={isDetectingRepo}
- onDirectoryChange={handleDirectoryChange}
- selectedCloudRepo={selectedCloudRepo}
- onCloudRepoChange={handleCloudRepoChange}
- hasGithubIntegration={hasGithubIntegration}
- />
- </motion.div>
- )}
- </AnimatePresence>
+ {currentStep === "select-repo" && (
+ <motion.div
+ key="select-repo"
+ custom={direction}
+ initial="enter"
+ animate="center"
+ exit="exit"
+ variants={stepVariants}
+ transition={{ duration: 0.3 }}
+ className="w-full"
+ >
+ <SelectRepoStep
+ onComplete={handleComplete}
+ onBack={handleBack}
+ selectedDirectory={selectedDirectory}
+ detectedRepo={detectedRepo}
+ isDetectingRepo={isDetectingRepo}
+ onDirectoryChange={handleDirectoryChange}
+ selectedCloudRepo={selectedCloudRepo}
+ onCloudRepoChange={handleCloudRepoChange}
+ hasGithubIntegration={hasGithubIntegration}
+ isCompleting={isCompleting}
+ />
+ </motion.div>
+ )}
+ </AnimatePresence>
+ </div>
+ </div>
+ </div>
</FullScreenLayout>
);
}
diff --git a/products/desktop/packages/ui/src/features/onboarding/components/OptionalBadge.tsx b/products/desktop/packages/ui/src/features/onboarding/components/OptionalBadge.tsx
index 1d41c42f11f0..813421d16cba 100644
--- a/products/desktop/packages/ui/src/features/onboarding/components/OptionalBadge.tsx
+++ b/products/desktop/packages/ui/src/features/onboarding/components/OptionalBadge.tsx
@@ -1,7 +1,5 @@
+import { Badge } from "@posthog/quill";
+
export function OptionalBadge() {
- return (
- <span className="inline-flex items-center rounded-[6px] bg-(--gray-a3) px-[6px] py-px font-medium text-(--gray-11) text-[11px]">
- Optional
- </span>
- );
+ return <Badge variant="default">Optional</Badge>;
}
diff --git a/products/desktop/packages/ui/src/features/onboarding/components/ProjectSelectStep.tsx b/products/desktop/packages/ui/src/features/onboarding/components/ProjectSelectStep.tsx
index 9d538be1c441..1b812f24eaee 100644
--- a/products/desktop/packages/ui/src/features/onboarding/components/ProjectSelectStep.tsx
+++ b/products/desktop/packages/ui/src/features/onboarding/components/ProjectSelectStep.tsx
@@ -1,10 +1,6 @@
+import { ArrowLeft, ArrowRight, CaretDown } from "@phosphor-icons/react";
import {
- ArrowLeft,
- ArrowRight,
- CaretDown,
- CheckCircle,
-} from "@phosphor-icons/react";
-import {
+ Button,
Combobox,
ComboboxCollection,
ComboboxContent,
@@ -15,8 +11,10 @@ import {
ComboboxLabel,
ComboboxList,
ComboboxTrigger,
+ Heading,
+ Skeleton,
+ Text,
} from "@posthog/quill";
-import { REGION_LABELS } from "@posthog/shared";
import { ANALYTICS_EVENTS } from "@posthog/shared/analytics-events";
import { useOptionalAuthenticatedClient } from "@posthog/ui/features/auth/authClient";
import { OAuthControls } from "@posthog/ui/features/auth/OAuthControls";
@@ -26,23 +24,16 @@ import {
} from "@posthog/ui/features/auth/store";
import { useSelectProjectMutation } from "@posthog/ui/features/auth/useAuthMutations";
import { useCurrentUser } from "@posthog/ui/features/auth/useCurrentUser";
-import { StepActions } from "@posthog/ui/features/onboarding/components/StepActions";
import {
type ProjectInfo,
useProjects,
} from "@posthog/ui/features/projects/useProjects";
-import { LoadingState } from "@posthog/ui/primitives/LoadingState";
-import { ProductWordmark } from "@posthog/ui/primitives/ProductWordmark";
-import { Spinner } from "@posthog/ui/primitives/Spinner";
import { track } from "@posthog/ui/shell/analytics";
import { logger } from "@posthog/ui/shell/logger";
-import {
- FIELD_CONTENT_CLASS,
- FIELD_TRIGGER_CLASS,
-} from "@posthog/ui/styles/fieldTrigger";
-import { Button, Flex, Text } from "@radix-ui/themes";
-import { AnimatePresence, motion } from "framer-motion";
+import { FIELD_CONTENT_CLASS } from "@posthog/ui/styles/fieldTrigger";
+import { AnimatePresence, motion, useReducedMotion } from "framer-motion";
import { useMemo, useRef, useState } from "react";
+import { StepActions } from "./StepActions";
const log = logger.scope("project-select-step");
@@ -58,34 +49,8 @@ interface ProjectSelectStepProps {
onBack?: () => void;
}
-/** The sign-in button resolves into this, so signing in reads as a completed line. */
-function SignedInRow({ email }: { email: string | undefined }) {
- const cloudRegion = useAuthStateValue((state) => state.cloudRegion);
- const region = cloudRegion ? REGION_LABELS[cloudRegion].label : null;
- return (
- <Flex
- align="center"
- gap="2"
- className="h-[44px] w-full rounded-[6px] border border-(--gray-a4) px-[14px]"
- >
- <CheckCircle
- size={16}
- weight="fill"
- className="shrink-0 text-(--green-9)"
- />
- <Text className="min-w-0 truncate text-(--gray-12) text-sm">
- Signed in as {email ?? "your PostHog account"}
- </Text>
- {region && (
- <Text className="ml-auto shrink-0 text-(--gray-11) text-xs">
- {region}
- </Text>
- )}
- </Flex>
- );
-}
-
export function ProjectSelectStep({ onNext, onBack }: ProjectSelectStepProps) {
+ const shouldReduceMotion = useReducedMotion() === true;
const authFetched = useAuthStateFetched();
const isAuthenticated =
useAuthStateValue((state) => state.status) === "authenticated";
@@ -123,193 +88,198 @@ export function ProjectSelectStep({ onNext, onBack }: ProjectSelectStepProps) {
() => sortedProjects.find((p) => p.id === currentProjectId) ?? null,
[sortedProjects, currentProjectId],
);
+ const projectLoading = isLoading || selectProjectMutation.isPending;
return (
- <Flex align="center" justify="center" height="100%" px="8">
- <Flex
- direction="column"
- align="center"
- className="h-full w-full max-w-[480px] pt-[24px] pb-[40px]"
- >
- <Flex
- direction="column"
- align="center"
- className="min-h-0 w-full flex-1 overflow-y-auto"
- >
- <Flex
- direction="column"
- gap="6"
- style={{ margin: "auto 0" }}
- className="w-full"
- >
- <div className="flex justify-center">
- <ProductWordmark />
- </div>
-
- <AnimatePresence mode="wait">
- {isAuthenticated ? (
- <motion.div
- key="signed-in"
- initial={{ opacity: 0, y: 4 }}
- animate={{ opacity: 1, y: 0 }}
- transition={{ duration: 0.2 }}
- className="w-full"
- >
- <SignedInRow email={fullUser?.email} />
- </motion.div>
- ) : authFetched ? (
- <motion.div
- key="oauth"
- initial={{ opacity: 1 }}
- exit={{ opacity: 0, y: -4 }}
- transition={{ duration: 0.2 }}
- className="w-full"
- >
- <OAuthControls
- onAuthInitiated={(region) =>
- track(ANALYTICS_EVENTS.ONBOARDING_SIGN_IN_INITIATED, {
- region,
- })
- }
- />
- </motion.div>
- ) : null}
- </AnimatePresence>
-
- {isAuthenticated && isLoading && (
- <LoadingState className="h-[80px]" />
- )}
+ <main className="w-full">
+ <div className="mx-auto flex w-full max-w-[480px] flex-col gap-4">
+ <div className="flex flex-col gap-1.5">
+ {/* biome-ignore lint/a11y/useHeadingContent: Quill supplies the heading text through this render target. */}
+ <Heading size="xl" render={<h1 className="font-bold" />}>
+ Choose a project
+ </Heading>
+ <Text size="sm" variant="muted">
+ Choose the PostHog project you want to use with Desktop.
+ </Text>
+ </div>
- {isAuthenticated && !isLoading && (
+ <div className="flex w-full flex-col gap-4">
+ <AnimatePresence mode="wait">
+ {!isAuthenticated && authFetched ? (
<motion.div
- initial={{ opacity: 0, y: 8 }}
- animate={{ opacity: 1, y: 0 }}
- transition={{ duration: 0.3 }}
+ key="oauth"
+ initial={{ opacity: 1 }}
+ exit={shouldReduceMotion ? undefined : { opacity: 0, y: -4 }}
+ transition={{ duration: 0.2 }}
className="w-full"
>
- <Flex direction="column" gap="2" className="w-full">
- <Text className="font-medium text-(--gray-11) text-sm">
- Project
- </Text>
- <Combobox
- items={sortedGroups}
- value={selectedProject}
- onValueChange={(value) => {
- const project = value as ProjectInfo | null;
- if (project) {
- selectProjectMutation.mutate(project.id, {
- onError: (error) =>
- log.error("Failed to select project", error),
- });
- }
- setProjectOpen(false);
- }}
- open={projectOpen}
- onOpenChange={setProjectOpen}
- disabled={selectProjectMutation.isPending}
- itemToStringLabel={(project) => project.name}
- itemToStringValue={(project) => String(project.id)}
- >
- <ComboboxTrigger
- render={
- <button
- ref={projectAnchorRef}
- type="button"
- className={FIELD_TRIGGER_CLASS}
- >
- <Flex
- direction="column"
- gap="1"
- align="start"
- className="min-w-0 flex-1 text-left"
+ <OAuthControls
+ onAuthInitiated={(region) =>
+ track(ANALYTICS_EVENTS.ONBOARDING_SIGN_IN_INITIATED, {
+ region,
+ })
+ }
+ />
+ </motion.div>
+ ) : null}
+ </AnimatePresence>
+
+ {isAuthenticated && (
+ <motion.div
+ initial={shouldReduceMotion ? false : { opacity: 0, y: 8 }}
+ animate={{ opacity: 1, y: 0 }}
+ transition={{ duration: 0.3 }}
+ className="w-full"
+ >
+ <div className="flex w-full flex-col gap-2">
+ <Text size="xs" variant="muted" weight="medium">
+ Project
+ </Text>
+ <Combobox
+ items={sortedGroups}
+ value={selectedProject}
+ onValueChange={(value) => {
+ const project = value as ProjectInfo | null;
+ if (project) {
+ selectProjectMutation.mutate(project.id, {
+ onError: (error) =>
+ log.error("Failed to select project", error),
+ });
+ }
+ setProjectOpen(false);
+ }}
+ open={projectOpen}
+ onOpenChange={setProjectOpen}
+ disabled={projectLoading}
+ itemToStringLabel={(project) => project.name}
+ itemToStringValue={(project) => String(project.id)}
+ >
+ <ComboboxTrigger
+ render={
+ <Button
+ ref={projectAnchorRef}
+ type="button"
+ variant="outline"
+ size="lg"
+ left
+ aria-label={
+ projectLoading
+ ? "Loading project"
+ : `Project: ${currentProject?.name ?? "Select a project"}`
+ }
+ aria-busy={projectLoading || undefined}
+ className="h-auto min-h-14 w-full justify-between px-3 py-2"
+ >
+ {projectLoading ? (
+ <span
+ aria-hidden="true"
+ className="flex min-w-0 flex-1 flex-col gap-1.5"
>
- <Text className="min-w-0 max-w-full truncate font-medium text-(--gray-12)">
+ <Skeleton className="h-3.5 w-28" />
+ <Skeleton className="h-2.5 w-20" />
+ </span>
+ ) : (
+ <span className="flex min-w-0 flex-1 flex-col items-start gap-0.5 text-left">
+ <Text
+ render={<span />}
+ size="sm"
+ weight="medium"
+ className="min-w-0 max-w-full truncate"
+ >
{currentProject?.name ?? "Select a project..."}
</Text>
{currentProject && (
- <Text className="min-w-0 max-w-full truncate text-(--gray-11) text-[13px]">
+ <Text
+ render={<span />}
+ size="xs"
+ variant="muted"
+ className="min-w-0 max-w-full truncate"
+ >
{currentProject.organization.name}
</Text>
)}
- </Flex>
- <CaretDown
- size={14}
- className="shrink-0 text-(--gray-9)"
- />
- </button>
- }
- />
- <ComboboxContent
- anchor={projectAnchorRef}
- side="bottom"
- align="start"
- sideOffset={4}
- className={FIELD_CONTENT_CLASS}
- >
- <ComboboxInput
- placeholder="Search projects..."
- showTrigger={false}
- />
- <ComboboxEmpty>No projects found.</ComboboxEmpty>
- <ComboboxList className="max-h-[240px]">
- {(group: ProjectGroup) => (
- <ComboboxGroup key={group.orgId} items={group.items}>
- <ComboboxLabel>{group.orgName}</ComboboxLabel>
- <ComboboxCollection>
- {(project: ProjectInfo) => (
- <ComboboxItem
- key={project.id}
- value={project}
- title={project.name}
- >
- <Text>{project.name}</Text>
- </ComboboxItem>
- )}
- </ComboboxCollection>
- </ComboboxGroup>
+ </span>
)}
- </ComboboxList>
- </ComboboxContent>
- </Combobox>
- {selectProjectMutation.isError && (
- <Text className="text-(--red-11) text-[13px]">
- Couldn't switch to that project. Try again.
- </Text>
- )}
- </Flex>
- </motion.div>
- )}
- </Flex>
- </Flex>
-
- <StepActions>
- {onBack && (
- <Button size="3" variant="outline" color="gray" onClick={onBack}>
- <ArrowLeft size={16} weight="bold" />
- Back
- </Button>
+ <CaretDown
+ size={14}
+ className="shrink-0 text-muted-foreground"
+ />
+ </Button>
+ }
+ />
+ <ComboboxContent
+ anchor={projectAnchorRef}
+ side="bottom"
+ align="start"
+ sideOffset={4}
+ className={FIELD_CONTENT_CLASS}
+ >
+ <ComboboxInput
+ placeholder="Search projects..."
+ showTrigger={false}
+ />
+ <ComboboxEmpty>No projects found.</ComboboxEmpty>
+ <ComboboxList className="max-h-[240px]">
+ {(group: ProjectGroup) => (
+ <ComboboxGroup key={group.orgId} items={group.items}>
+ <ComboboxLabel>{group.orgName}</ComboboxLabel>
+ <ComboboxCollection>
+ {(project: ProjectInfo) => (
+ <ComboboxItem
+ key={project.id}
+ value={project}
+ title={project.name}
+ >
+ <Text size="sm">{project.name}</Text>
+ </ComboboxItem>
+ )}
+ </ComboboxCollection>
+ </ComboboxGroup>
+ )}
+ </ComboboxList>
+ </ComboboxContent>
+ </Combobox>
+ {selectProjectMutation.isError && (
+ <Text size="xs" variant="destructive">
+ Couldn't switch to that project. Try again.
+ </Text>
+ )}
+ </div>
+ </motion.div>
)}
- {isAuthenticated && !isLoading && (
- <Button
- size="3"
- onClick={() => {
- track(ANALYTICS_EVENTS.ONBOARDING_PROJECT_SELECTED, {
- had_multiple_orgs: hasMultipleOrgs,
- had_multiple_projects: sortedProjects.length > 1,
- });
- onNext();
- }}
- disabled={
- currentProjectId == null || selectProjectMutation.isPending
+ {(onBack || isAuthenticated) && (
+ <StepActions
+ primaryAction={
+ isAuthenticated ? (
+ <Button
+ size="lg"
+ variant="primary"
+ onClick={() => {
+ track(ANALYTICS_EVENTS.ONBOARDING_PROJECT_SELECTED, {
+ had_multiple_orgs: hasMultipleOrgs,
+ had_multiple_projects: sortedProjects.length > 1,
+ });
+ onNext();
+ }}
+ loading={selectProjectMutation.isPending}
+ disabled={currentProjectId == null || projectLoading}
+ >
+ Continue
+ <ArrowRight size={16} weight="bold" />
+ </Button>
+ ) : null
}
>
- {selectProjectMutation.isPending && <Spinner size="md" />}
- Continue
- <ArrowRight size={16} weight="bold" />
- </Button>
+ {onBack && (
+ <Button size="lg" variant="outline" onClick={onBack}>
+ <ArrowLeft size={16} weight="bold" />
+ Back
+ </Button>
+ )}
+ </StepActions>
)}
- </StepActions>
- </Flex>
- </Flex>
+ </div>
+ </div>
+ </main>
);
}
diff --git a/products/desktop/packages/ui/src/features/onboarding/components/SelectRepoStep.tsx b/products/desktop/packages/ui/src/features/onboarding/components/SelectRepoStep.tsx
index 5257de7d6311..77de8bfc93c6 100644
--- a/products/desktop/packages/ui/src/features/onboarding/components/SelectRepoStep.tsx
+++ b/products/desktop/packages/ui/src/features/onboarding/components/SelectRepoStep.tsx
@@ -1,20 +1,48 @@
-import { ArrowLeft, ArrowRight, CheckCircle } from "@phosphor-icons/react";
+import {
+ ArrowLeft,
+ ArrowRight,
+ CheckCircle,
+ FolderOpen,
+} from "@phosphor-icons/react";
import { repoMatchesGitHubRepos } from "@posthog/core/onboarding/repoProvider";
-import { cn } from "@posthog/quill";
+import {
+ Button,
+ cn,
+ Empty,
+ EmptyContent,
+ EmptyDescription,
+ EmptyHeader,
+ EmptyMedia,
+ EmptyTitle,
+ Heading,
+ Item,
+ ItemContent,
+ ItemDescription,
+ ItemMedia,
+ ItemTitle,
+ Text,
+} from "@posthog/quill";
+import { FolderPicker } from "@posthog/ui/features/folder-picker/FolderPicker";
+import { GitHubRepoPicker } from "@posthog/ui/features/folder-picker/GitHubRepoPicker";
+import { useFolders } from "@posthog/ui/features/folders/useFolders";
+import { useUserRepositoryIntegration } from "@posthog/ui/features/integrations/useIntegrations";
import { Spinner } from "@posthog/ui/primitives/Spinner";
import { useHostCapabilities } from "@posthog/ui/shell/useHostCapabilities";
-import { Button, Flex, Text } from "@radix-ui/themes";
-import { AnimatePresence, motion } from "framer-motion";
-import { useMemo, useState } from "react";
-import { FolderPicker } from "../../folder-picker/FolderPicker";
-import { GitHubRepoPicker } from "../../folder-picker/GitHubRepoPicker";
-import { useUserRepositoryIntegration } from "../../integrations/useIntegrations";
+import { getFilePath } from "@posthog/ui/utils/getFilePath";
+import { motion, useReducedMotion } from "framer-motion";
+import { type DragEvent, useMemo, useRef, useState } from "react";
import type { DetectedRepo } from "../types";
import { OptionalBadge } from "./OptionalBadge";
import { StepActions } from "./StepActions";
+function handleDragOver(event: DragEvent<HTMLDivElement>): void {
+ if (!event.dataTransfer.types.includes("Files")) return;
+ event.preventDefault();
+ event.dataTransfer.dropEffect = "copy";
+}
+
interface SelectRepoStepProps {
- onComplete: (skipped: boolean) => void;
+ onComplete: (skipped: boolean) => void | Promise<void>;
onBack: () => void;
selectedDirectory: string;
detectedRepo: DetectedRepo | null;
@@ -23,10 +51,9 @@ interface SelectRepoStepProps {
selectedCloudRepo: string | null;
onCloudRepoChange: (repo: string | null) => void;
hasGithubIntegration: boolean | undefined;
+ isCompleting: boolean;
}
-type RepoSource = "github" | "local";
-
export function SelectRepoStep({
onComplete,
onBack,
@@ -37,226 +64,224 @@ export function SelectRepoStep({
selectedCloudRepo,
onCloudRepoChange,
hasGithubIntegration,
+ isCompleting,
}: SelectRepoStepProps) {
+ const shouldReduceMotion = useReducedMotion() === true;
const { localWorkspaces } = useHostCapabilities();
+ const { addFolder } = useFolders();
const {
repositories,
isLoadingRepos,
isRefreshingRepos,
refreshRepositories,
} = useUserRepositoryIntegration();
+ const [isDraggingFolder, setIsDraggingFolder] = useState(false);
+ const [dropError, setDropError] = useState<string | null>(null);
+ const dragDepthRef = useRef(0);
- // `null` follows the default source until the user switches explicitly.
- const [chosenSource, setChosenSource] = useState<RepoSource | null>(null);
- const showSourceSwitch = localWorkspaces && hasGithubIntegration === true;
- const repoSource: RepoSource = !localWorkspaces
- ? "github"
- : (chosenSource ?? (hasGithubIntegration ? "github" : "local"));
-
+ const useGithubRepository = !localWorkspaces || hasGithubIntegration === true;
+ const hasSelection = useGithubRepository
+ ? localWorkspaces
+ ? selectedCloudRepo !== null
+ : selectedDirectory !== ""
+ : selectedDirectory !== "";
const repoMatchesGitHub = useMemo(
() => repoMatchesGitHubRepos(detectedRepo, repositories),
[detectedRepo, repositories],
);
- // Cloud-only hosts keep the picked repo in selectedDirectory.
- const hasSelection =
- localWorkspaces && repoSource === "github"
- ? !!selectedCloudRepo
- : !!selectedDirectory;
+ const handleDragEnter = (event: DragEvent<HTMLDivElement>) => {
+ if (!event.dataTransfer.types.includes("Files")) return;
+ event.preventDefault();
+ dragDepthRef.current += 1;
+ setIsDraggingFolder(true);
+ };
- return (
- <Flex align="center" justify="center" height="100%" px="8">
- <Flex
- direction="column"
- align="center"
- className="h-full w-full max-w-[480px] pt-[24px] pb-[40px]"
- >
- <Flex
- direction="column"
- align="center"
- className="min-h-0 w-full flex-1 overflow-y-auto"
- >
- <Flex
- direction="column"
- gap="5"
- style={{ margin: "auto 0" }}
- className="w-full"
- >
- <motion.div
- initial={{ opacity: 0, y: 8 }}
- animate={{ opacity: 1, y: 0 }}
- transition={{ duration: 0.3 }}
- >
- <Flex direction="column" gap="2">
- <Flex align="center" gap="2">
- <Text className="font-bold text-(--gray-12) text-2xl">
- Pick a repo
- </Text>
- <OptionalBadge />
- </Flex>
- <Text className="text-(--gray-11) text-sm">
- New tasks use this repo by default. You can change it any time
- from the home screen.
- </Text>
- </Flex>
- </motion.div>
+ const handleDragLeave = (event: DragEvent<HTMLDivElement>) => {
+ event.preventDefault();
+ dragDepthRef.current = Math.max(0, dragDepthRef.current - 1);
+ if (dragDepthRef.current === 0) setIsDraggingFolder(false);
+ };
- <motion.div
- initial={{ opacity: 0, y: 8 }}
- animate={{ opacity: 1, y: 0 }}
- transition={{ duration: 0.3, delay: 0.05 }}
- >
- <Flex direction="column" gap="2" className="w-full">
- {repoSource === "github" ? (
- <GitHubRepoPicker
- value={
- localWorkspaces
- ? selectedCloudRepo
- : selectedDirectory || null
- }
- onChange={(repo) =>
- localWorkspaces
- ? onCloudRepoChange(repo)
- : onDirectoryChange(repo ?? "")
- }
- repositories={repositories}
- isLoading={isLoadingRepos}
- onRefresh={refreshRepositories}
- isRefreshing={isRefreshingRepos}
- placeholder="Select repository..."
- variant="field"
- />
- ) : (
- <FolderPicker
- variant="field"
- value={selectedDirectory}
- onChange={onDirectoryChange}
- placeholder="Select repository..."
- />
- )}
+ const handleFolderDrop = async (event: DragEvent<HTMLDivElement>) => {
+ event.preventDefault();
+ dragDepthRef.current = 0;
+ setIsDraggingFolder(false);
+ setDropError(null);
- <AnimatePresence mode="wait">
- {repoSource === "local" && isDetectingRepo && (
- <motion.div
- key="detecting"
- initial={{ opacity: 0 }}
- animate={{ opacity: 1 }}
- exit={{ opacity: 0 }}
- transition={{ duration: 0.15 }}
- >
- <Flex align="center" gap="2">
- <Spinner size="md" className="text-(--gray-9)" />
- <Text className="text-(--gray-9) text-[13px]">
- Detecting repository...
- </Text>
- </Flex>
- </motion.div>
- )}
- {repoSource === "local" &&
- !isDetectingRepo &&
- selectedDirectory &&
- detectedRepo && (
- <motion.div
- key="detected"
- initial={{ opacity: 0, y: 4 }}
- animate={{ opacity: 1, y: 0 }}
- exit={{ opacity: 0 }}
- transition={{ duration: 0.2 }}
- >
- <Flex align="center" gap="2">
- <CheckCircle
- size={14}
- weight="fill"
- className={
- repoMatchesGitHub
- ? "text-(--green-9)"
- : "text-(--gray-9)"
- }
- />
- <Text
- className={cn(
- "text-[13px]",
- repoMatchesGitHub
- ? "text-(--green-11)"
- : "text-(--gray-11)",
- )}
- >
- {repoMatchesGitHub
- ? `Linked to ${detectedRepo.fullName} on GitHub`
- : `Detected ${detectedRepo.fullName}`}
- </Text>
- </Flex>
- </motion.div>
- )}
- {repoSource === "local" &&
- !isDetectingRepo &&
- selectedDirectory &&
- !detectedRepo && (
- <motion.div
- key="no-repo"
- initial={{ opacity: 0, y: 4 }}
- animate={{ opacity: 1, y: 0 }}
- exit={{ opacity: 0 }}
- transition={{ duration: 0.2 }}
- >
- <Text className="text-(--gray-9) text-[13px]">
- No git remote detected. You can still continue.
- </Text>
- </motion.div>
- )}
- </AnimatePresence>
+ const item = event.dataTransfer.items[0];
+ const entry = item?.webkitGetAsEntry?.();
+ if (entry && !entry.isDirectory) {
+ setDropError("Drop a folder, not a file.");
+ return;
+ }
- {showSourceSwitch && (
- <button
- type="button"
- onClick={() => {
- const nextSource =
- repoSource === "github" ? "local" : "github";
- // Clear the source being left so a later Skip cannot
- // silently assign or persist a repo the user
- // navigated away from.
- if (nextSource === "local") {
- onCloudRepoChange(null);
- } else {
- onDirectoryChange("");
- }
- setChosenSource(nextSource);
- }}
- className="cursor-pointer self-start border-0 bg-transparent p-0 text-(--gray-10) text-[13px] underline hover:text-(--gray-11)"
- >
- {repoSource === "github"
- ? "Use a local folder instead"
- : "Back to GitHub repos"}
- </button>
- )}
- </Flex>
- </motion.div>
- </Flex>
- </Flex>
+ const file = event.dataTransfer.files[0];
+ const path = file ? getFilePath(file) : "";
+ if (!path) {
+ setDropError(
+ "This folder path is not available. Choose the folder instead.",
+ );
+ return;
+ }
- <StepActions>
- <Button size="3" variant="outline" color="gray" onClick={onBack}>
- <ArrowLeft size={16} weight="bold" />
- Back
- </Button>
- {hasSelection ? (
- <Button size="3" onClick={() => onComplete(false)}>
- Get started
- <ArrowRight size={16} weight="bold" />
- </Button>
+ try {
+ await addFolder(path);
+ onDirectoryChange(path);
+ } catch {
+ setDropError(
+ "PostHog could not add this folder. Choose the folder instead.",
+ );
+ }
+ };
+
+ const localFolderStatus = selectedDirectory ? (
+ <Item
+ variant="muted"
+ size="sm"
+ tone={
+ isDetectingRepo
+ ? "default"
+ : detectedRepo && repoMatchesGitHub
+ ? "success"
+ : "info"
+ }
+ aria-live="polite"
+ >
+ <ItemMedia variant="icon">
+ {isDetectingRepo ? (
+ <Spinner />
+ ) : detectedRepo ? (
+ <CheckCircle size={15} weight="fill" />
+ ) : (
+ <FolderOpen size={15} weight="fill" />
+ )}
+ </ItemMedia>
+ <ItemContent>
+ <ItemTitle>
+ {isDetectingRepo
+ ? "Checking folder"
+ : detectedRepo
+ ? repoMatchesGitHub
+ ? `Linked to ${detectedRepo.fullName} on GitHub`
+ : `Detected ${detectedRepo.fullName}`
+ : "Folder ready"}
+ </ItemTitle>
+ {!isDetectingRepo && !detectedRepo && (
+ <ItemDescription>
+ No Git remote was detected. You can still use this folder.
+ </ItemDescription>
+ )}
+ </ItemContent>
+ </Item>
+ ) : null;
+
+ return (
+ <main className="w-full">
+ <div className="mx-auto flex w-full max-w-[480px] flex-col gap-4">
+ <motion.div
+ initial={shouldReduceMotion ? false : { opacity: 0, y: 8 }}
+ animate={{ opacity: 1, y: 0 }}
+ transition={{ duration: 0.25, ease: "easeOut" }}
+ className="flex flex-col gap-1.5"
+ >
+ <div className="flex items-center gap-2">
+ {/* biome-ignore lint/a11y/useHeadingContent: Quill supplies the heading text through this render target. */}
+ <Heading size="xl" render={<h1 className="font-bold" />}>
+ Pick a repo
+ </Heading>
+ <OptionalBadge />
+ </div>
+ <Text size="sm" variant="muted">
+ New tasks use this repo by default. Change it anytime from home.
+ </Text>
+ </motion.div>
+
+ <motion.div
+ initial={shouldReduceMotion ? false : { opacity: 0, y: 8 }}
+ animate={{ opacity: 1, y: 0 }}
+ transition={{ duration: 0.25, delay: 0.03, ease: "easeOut" }}
+ className="flex flex-col gap-4"
+ >
+ {useGithubRepository ? (
+ <GitHubRepoPicker
+ value={
+ localWorkspaces ? selectedCloudRepo : selectedDirectory || null
+ }
+ onChange={(repo) =>
+ localWorkspaces
+ ? onCloudRepoChange(repo)
+ : onDirectoryChange(repo ?? "")
+ }
+ repositories={repositories}
+ isLoading={isLoadingRepos}
+ onRefresh={refreshRepositories}
+ isRefreshing={isRefreshingRepos}
+ placeholder="Select repository…"
+ variant="field"
+ disabled={isCompleting}
+ />
) : (
- <Button
- size="3"
- variant="outline"
- color="gray"
- onClick={() => onComplete(true)}
+ <Empty
+ className={cn("py-6", isDraggingFolder && "bg-muted")}
+ aria-live="polite"
+ onDragEnter={handleDragEnter}
+ onDragLeave={handleDragLeave}
+ onDragOver={handleDragOver}
+ onDrop={(event) => void handleFolderDrop(event)}
>
- Skip & get started
- <ArrowRight size={16} weight="bold" />
- </Button>
+ <EmptyHeader>
+ <EmptyMedia variant="icon">
+ <FolderOpen size={18} weight="fill" />
+ </EmptyMedia>
+ <EmptyTitle>
+ {isDraggingFolder
+ ? "Drop your folder"
+ : "Choose a local folder"}
+ </EmptyTitle>
+ <EmptyDescription>
+ Drop a folder here, or choose one from your computer.
+ </EmptyDescription>
+ </EmptyHeader>
+ <EmptyContent className="w-full max-w-none">
+ <FolderPicker
+ value={selectedDirectory}
+ onChange={(path) => {
+ setDropError(null);
+ onDirectoryChange(path);
+ }}
+ placeholder="Choose folder…"
+ />
+ {dropError && (
+ <Text size="xs" variant="destructive">
+ {dropError}
+ </Text>
+ )}
+ {localFolderStatus}
+ </EmptyContent>
+ </Empty>
)}
- </StepActions>
- </Flex>
- </Flex>
+
+ <StepActions
+ primaryAction={
+ <Button
+ size="lg"
+ variant={hasSelection ? "primary" : "outline"}
+ loading={isCompleting}
+ onClick={() => void onComplete(!hasSelection)}
+ >
+ {hasSelection ? "Get started" : "Skip & get started"}
+ <ArrowRight size={16} weight="bold" />
+ </Button>
+ }
+ >
+ <Button size="lg" disabled={isCompleting} onClick={onBack}>
+ <ArrowLeft size={16} weight="bold" />
+ Back
+ </Button>
+ </StepActions>
+ </motion.div>
+ </div>
+ </main>
);
}
diff --git a/products/desktop/packages/ui/src/features/onboarding/components/StepActions.tsx b/products/desktop/packages/ui/src/features/onboarding/components/StepActions.tsx
index a8bf66843f1c..1bb5ce0b62aa 100644
--- a/products/desktop/packages/ui/src/features/onboarding/components/StepActions.tsx
+++ b/products/desktop/packages/ui/src/features/onboarding/components/StepActions.tsx
@@ -1,24 +1,31 @@
-import { Flex } from "@radix-ui/themes";
-import { motion } from "framer-motion";
+import { motion, useReducedMotion } from "framer-motion";
import type { ReactNode } from "react";
interface StepActionsProps {
- children: ReactNode;
+ children?: ReactNode;
+ primaryAction: ReactNode;
delay?: number;
}
-export function StepActions({ children, delay = 0.15 }: StepActionsProps) {
+export function StepActions({
+ children,
+ primaryAction,
+ delay = 0.15,
+}: StepActionsProps) {
+ const shouldReduceMotion = useReducedMotion() === true;
+
return (
<motion.div
- initial={{ opacity: 0, y: 8 }}
+ initial={shouldReduceMotion ? false : { opacity: 0, y: 8 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.25, delay }}
style={{ zIndex: 1 }}
- className="relative shrink-0 pt-[16px]"
+ className="relative shrink-0"
>
- <Flex gap="4" align="center">
+ <div className="flex items-center justify-end gap-2">
{children}
- </Flex>
+ {primaryAction}
+ </div>
</motion.div>
);
}
diff --git a/products/desktop/packages/ui/src/features/onboarding/saveOnboardingRepository.test.ts b/products/desktop/packages/ui/src/features/onboarding/saveOnboardingRepository.test.ts
new file mode 100644
index 000000000000..07d350f43470
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/onboarding/saveOnboardingRepository.test.ts
@@ -0,0 +1,113 @@
+import type { TaskChannel } from "@posthog/shared/domain-types";
+import { TASK_CHANNELS_QUERY_KEY } from "@posthog/ui/features/canvas/hooks/useTaskChannels";
+import { QueryClient } from "@tanstack/react-query";
+import { describe, expect, it, vi } from "vitest";
+import { saveOnboardingRepository } from "./saveOnboardingRepository";
+
+function channel(overrides: Partial<TaskChannel>): TaskChannel {
+ return {
+ id: "channel-id",
+ name: "channel",
+ channel_type: "public",
+ starred: false,
+ created_at: "2026-01-01T00:00:00Z",
+ system_role: null,
+ ...overrides,
+ };
+}
+
+describe("saveOnboardingRepository", () => {
+ it("updates empty system spaces and their shared cache", async () => {
+ const personal = channel({
+ id: "personal-id",
+ name: "me",
+ channel_type: "personal",
+ system_role: "personal",
+ });
+ const general = channel({
+ id: "general-id",
+ name: "general",
+ system_role: "general",
+ });
+ const updatedChannels = [personal, general].map((item) => ({
+ ...item,
+ github_integration: 12,
+ repositories: ["posthog/posthog"],
+ }));
+ const updateTaskChannelRepositories = vi
+ .fn()
+ .mockImplementation((channelId: string) =>
+ Promise.resolve(updatedChannels.find((item) => item.id === channelId)),
+ );
+ const client = {
+ getIntegrations: vi.fn().mockResolvedValue([
+ {
+ id: 12,
+ kind: "github",
+ config: { account: { name: "PostHog" } },
+ },
+ ]),
+ updateTaskChannelRepositories,
+ };
+ const queryClient = new QueryClient();
+
+ await expect(
+ saveOnboardingRepository({
+ client,
+ provisioned: {
+ channels: [personal, general],
+ personal_created: true,
+ general_created: true,
+ },
+ queryClient,
+ repository: "posthog/posthog",
+ }),
+ ).resolves.toBe(2);
+
+ expect(updateTaskChannelRepositories).toHaveBeenCalledTimes(2);
+ expect(updateTaskChannelRepositories).toHaveBeenCalledWith(
+ "personal-id",
+ 12,
+ ["posthog/posthog"],
+ );
+ expect(updateTaskChannelRepositories).toHaveBeenCalledWith(
+ "general-id",
+ 12,
+ ["posthog/posthog"],
+ );
+ expect(
+ queryClient.getQueryData<TaskChannel[]>(TASK_CHANNELS_QUERY_KEY),
+ ).toEqual(updatedChannels);
+ });
+
+ it("keeps the provisioned cache when no team integration matches", async () => {
+ const general = channel({
+ id: "general-id",
+ name: "general",
+ system_role: "general",
+ });
+ const client = {
+ getIntegrations: vi.fn().mockResolvedValue([]),
+ updateTaskChannelRepositories: vi.fn(),
+ };
+ const queryClient = new QueryClient();
+
+ await expect(
+ saveOnboardingRepository({
+ client,
+ provisioned: {
+ channels: [general],
+ personal_created: false,
+ general_created: true,
+ },
+ queryClient,
+ repository: "posthog/posthog",
+ }),
+ ).resolves.toBe(0);
+
+ expect(client.updateTaskChannelRepositories).not.toHaveBeenCalled();
+ expect(queryClient.getQueryData(TASK_CHANNELS_QUERY_KEY)).toEqual([
+ general,
+ ]);
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/onboarding/saveOnboardingRepository.ts b/products/desktop/packages/ui/src/features/onboarding/saveOnboardingRepository.ts
new file mode 100644
index 000000000000..3a065882d9d7
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/onboarding/saveOnboardingRepository.ts
@@ -0,0 +1,74 @@
+import type { PostHogAPIClient } from "@posthog/api-client/posthog-client";
+import { integrationKeys } from "@posthog/core/integrations/repositoryKeys";
+import {
+ classifyIntegrations,
+ type Integration,
+} from "@posthog/core/integrations/selectors";
+import {
+ planSpaceRepoAssignments,
+ resolveRepoIntegrationId,
+} from "@posthog/core/onboarding/spaceRepoAssignment";
+import type {
+ ProvisionedTaskChannels,
+ TaskChannel,
+} from "@posthog/shared/domain-types";
+import { AUTH_SCOPED_QUERY_META } from "@posthog/ui/features/auth/useCurrentUser";
+import { TASK_CHANNELS_QUERY_KEY } from "@posthog/ui/features/canvas/hooks/useTaskChannels";
+import type { QueryClient } from "@tanstack/react-query";
+
+type OnboardingRepositoryClient = Pick<
+ PostHogAPIClient,
+ "getIntegrations" | "updateTaskChannelRepositories"
+>;
+
+interface SaveOnboardingRepositoryInput {
+ client: OnboardingRepositoryClient;
+ provisioned: ProvisionedTaskChannels;
+ queryClient: QueryClient;
+ repository: string;
+}
+
+/** Save the onboarding repository in each empty system space and its cache. */
+export async function saveOnboardingRepository({
+ client,
+ provisioned,
+ queryClient,
+ repository,
+}: SaveOnboardingRepositoryInput): Promise<number> {
+ queryClient.setQueryDefaults(TASK_CHANNELS_QUERY_KEY, {
+ meta: AUTH_SCOPED_QUERY_META,
+ });
+ queryClient.setQueryData(TASK_CHANNELS_QUERY_KEY, provisioned.channels);
+
+ const integrations = await queryClient.fetchQuery({
+ queryKey: integrationKeys.list(),
+ queryFn: () => client.getIntegrations() as Promise<Integration[]>,
+ staleTime: 60_000,
+ meta: AUTH_SCOPED_QUERY_META,
+ });
+ const integrationId = resolveRepoIntegrationId(
+ repository,
+ classifyIntegrations(integrations).githubIntegrations,
+ );
+ if (integrationId === null) return 0;
+
+ const targetIds = planSpaceRepoAssignments(provisioned.channels, {
+ personalCreated: provisioned.personal_created,
+ generalCreated: provisioned.general_created,
+ });
+ const updatedChannels = await Promise.all(
+ targetIds.map((channelId) =>
+ client.updateTaskChannelRepositories(channelId, integrationId, [
+ repository,
+ ]),
+ ),
+ );
+ const updatedById = new Map(
+ updatedChannels.map((channel) => [channel.id, channel]),
+ );
+ queryClient.setQueryData<TaskChannel[]>(TASK_CHANNELS_QUERY_KEY, (channels) =>
+ channels?.map((channel) => updatedById.get(channel.id) ?? channel),
+ );
+
+ return updatedChannels.length;
+}
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.tsx
index d11569043aa9..33ab353d9c19 100644
--- a/products/desktop/packages/ui/src/features/task-detail/components/CloudGithubSetupDialog.tsx
+++ b/products/desktop/packages/ui/src/features/task-detail/components/CloudGithubSetupDialog.tsx
@@ -1,8 +1,3 @@
-import {
- ArrowSquareOutIcon,
- GithubLogoIcon,
- HeartIcon,
-} from "@phosphor-icons/react";
import {
describeGithubConnectError,
GITHUB_CONNECT_TIMEOUT_MESSAGE,
@@ -13,24 +8,15 @@ import {
AlertDialogContent,
AlertDialogFooter,
Button,
- Empty,
- EmptyContent,
- EmptyDescription,
- EmptyHeader,
- EmptyMedia,
- EmptyTitle,
} from "@posthog/quill";
import { useAuthStateValue } from "@posthog/ui/features/auth/store";
+import { GithubConnectionEmpty } from "@posthog/ui/features/integrations/components/GithubConnectionEmpty";
import { useGithubConnect } from "@posthog/ui/features/integrations/useGithubUserConnect";
import { useRepositoryIntegration } from "@posthog/ui/features/integrations/useIntegrations";
-import Logo from "@posthog/ui/primitives/Logo";
-import { Spinner } from "@posthog/ui/primitives/Spinner";
import { useRendererWindowFocusStore } from "@posthog/ui/shell/rendererWindowFocusStore";
-import { openUrlInBrowser } from "@posthog/ui/utils/browser";
-import { domAnimation, LazyMotion, m, useReducedMotion } from "framer-motion";
+import { 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;
@@ -140,59 +126,41 @@ export function CloudGithubSetupDialog({
<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>
+ <GithubConnectionEmpty
+ connected={showConnectedAnimation}
+ loading={waitingForGithub}
+ title={
+ showConnectedAnimation
+ ? "GitHub connected"
+ : waitingForGithub
+ ? "Waiting for GitHub"
+ : "GitHub authentication required"
+ }
+ description={
+ showConnectedAnimation
+ ? "You're ready to use Cloud tasks."
+ : waitingForGithub
+ ? "Finish authorizing in your browser, then return here."
+ : (connectionMessage ??
+ "Cloud tasks require GitHub authentication.")
+ }
+ descriptionClassName={
+ hasError || isTimedOut ? "text-destructive" : undefined
+ }
+ showLearnMore={!showConnectedAnimation}
+ >
{!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>
+ <Button
+ type="button"
+ variant="primary"
+ loading={waitingForGithub}
+ disabled={!canConnect || waitingForGithub}
+ onClick={() => void handleConnect()}
+ >
+ {hasError || isTimedOut ? "Try again" : "Connect GitHub"}
+ </Button>
)}
- </Empty>
+ </GithubConnectionEmpty>
</div>
<AlertDialogFooter>
@@ -208,137 +176,3 @@ export function CloudGithubSetupDialog({
</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/WorkspaceModeSelect.tsx b/products/desktop/packages/ui/src/features/task-detail/components/WorkspaceModeSelect.tsx
index e63b2c236102..3f37b7fe4009 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
@@ -82,9 +82,6 @@ const CLOUD_ICON = <Cloud size={14} weight="regular" />;
const IMAGE_ICON = <Cube size={14} weight="regular" />;
-const ICON_BUTTON_CLASS =
- "flex cursor-pointer items-center justify-center rounded-sm border-0 bg-transparent p-0.5 text-muted-foreground transition-colors hover:bg-fill-hover hover:text-foreground";
-
export function WorkspaceModeSelect({
value,
onChange,
@@ -290,19 +287,15 @@ export function WorkspaceModeSelect({
<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
+ <Button
type="button"
+ size="icon-xs"
+ variant="default"
onClick={handleAddEnvironment}
aria-label="Add cloud environment"
- className={ICON_BUTTON_CLASS}
>
<Plus size={12} />
- </button>
+ </Button>
</div>
</div>
@@ -312,6 +305,7 @@ export function WorkspaceModeSelect({
key={option.key}
option={option}
isFavorite={favoriteKey === option.key}
+ githubSetupRequired={githubSetupRequired}
onSelect={selectTarget}
onToggleFavorite={toggleFavorite}
/>
@@ -329,6 +323,7 @@ export function WorkspaceModeSelect({
key={option.key}
option={option}
isFavorite={favoriteKey === option.key}
+ githubSetupRequired={githubSetupRequired}
onSelect={selectTarget}
onToggleFavorite={toggleFavorite}
/>
@@ -355,11 +350,13 @@ export function WorkspaceModeSelect({
function CloudTargetItem({
option,
isFavorite,
+ githubSetupRequired,
onSelect,
onToggleFavorite,
}: {
option: CloudTargetOption;
isFavorite: boolean;
+ githubSetupRequired: boolean;
onSelect: (target: CloudTarget) => void;
onToggleFavorite: (target: CloudTarget) => void;
}) {
@@ -379,8 +376,15 @@ function CloudTargetItem({
</ItemDescription>
</ItemContent>
<ItemActions className="mr-1.5 ml-auto self-center">
- <button
+ {githubSetupRequired && (
+ <span className="whitespace-nowrap text-[11px] text-warning-foreground">
+ Connect GitHub
+ </span>
+ )}
+ <Button
type="button"
+ size="icon-xs"
+ variant="default"
tabIndex={-1}
aria-label={
isFavorite
@@ -398,14 +402,13 @@ function CloudTargetItem({
onToggleFavorite(option.target);
}}
className={cn(
- "flex cursor-pointer items-center justify-center rounded-sm border-0 bg-transparent p-0.5 transition-colors hover:text-foreground",
isFavorite
? "text-foreground"
: "text-muted-foreground opacity-0 group-hover/dropdown-menu-item:opacity-100",
)}
>
<Star size={12} weight={isFavorite ? "fill" : "regular"} />
- </button>
+ </Button>
</ItemActions>
</ItemMenuItem>
}
diff --git a/products/desktop/packages/ui/src/primitives/DraggableTitleBar.tsx b/products/desktop/packages/ui/src/primitives/DraggableTitleBar.tsx
index 335232d998a0..b196ed947f8d 100644
--- a/products/desktop/packages/ui/src/primitives/DraggableTitleBar.tsx
+++ b/products/desktop/packages/ui/src/primitives/DraggableTitleBar.tsx
@@ -1,4 +1,4 @@
-import { Box } from "@radix-ui/themes";
+import type { ReactNode } from "react";
const TITLE_BAR_HEIGHT = 36;
@@ -6,11 +6,13 @@ const TITLE_BAR_HEIGHT = 36;
* A draggable title bar for Electron windows: a draggable area at the top of
* the window when using hidden title bars (e.g. the login screen).
*/
-export function DraggableTitleBar() {
+export function DraggableTitleBar({ children }: { children?: ReactNode }) {
return (
- <Box
+ <div
className="drag absolute top-0 right-0 left-0 z-10 w-full"
style={{ height: TITLE_BAR_HEIGHT }}
- />
+ >
+ {children}
+ </div>
);
}
diff --git a/products/desktop/packages/ui/src/primitives/FullScreenLayout.tsx b/products/desktop/packages/ui/src/primitives/FullScreenLayout.tsx
index 4396572beb25..c38f2aa4f53c 100644
--- a/products/desktop/packages/ui/src/primitives/FullScreenLayout.tsx
+++ b/products/desktop/packages/ui/src/primitives/FullScreenLayout.tsx
@@ -1,5 +1,6 @@
import { Lifebuoy } from "@phosphor-icons/react";
import { DotPatternBackground } from "@posthog/ui/primitives/DotPatternBackground";
+import { MathGridBackground } from "@posthog/ui/primitives/MathGridBackground";
import { useThemeStore } from "@posthog/ui/shell/themeStore";
import { Button, Flex, Theme } from "@radix-ui/themes";
import type { ReactNode } from "react";
@@ -7,20 +8,26 @@ import { DraggableTitleBar } from "./DraggableTitleBar";
interface FullScreenLayoutProps {
children: ReactNode;
+ backgroundPattern?: "dots" | "grid";
footerLeft?: ReactNode;
footerRight?: ReactNode;
/** Host-provided update banner shown in the default footer. */
banner?: ReactNode;
/** Host opens the support link. */
onOpenSupport?: () => void;
+ showFooter?: boolean;
+ titleBarContent?: ReactNode;
}
export function FullScreenLayout({
children,
+ backgroundPattern = "dots",
footerLeft,
footerRight,
banner,
onOpenSupport,
+ showFooter = true,
+ titleBarContent,
}: FullScreenLayoutProps) {
const isDarkMode = useThemeStore((state) => state.isDarkMode);
@@ -35,10 +42,14 @@ export function FullScreenLayout({
height="100vh"
className="relative overflow-hidden"
>
- <DraggableTitleBar />
+ <DraggableTitleBar>{titleBarContent}</DraggableTitleBar>
<div className="absolute inset-0 bg-(--color-background)" />
- <DotPatternBackground />
+ {backgroundPattern === "grid" ? (
+ <MathGridBackground />
+ ) : (
+ <DotPatternBackground />
+ )}
<Flex
direction="column"
@@ -54,27 +65,29 @@ export function FullScreenLayout({
{children}
</Flex>
- <Flex
- justify="between"
- className="absolute right-[32px] bottom-[20px] left-[32px] z-[2]"
- >
- {footerLeft ?? (
- <Flex align="center" gap="3">
- <Button
- size="1"
- variant="ghost"
- color="gray"
- onClick={onOpenSupport}
- className="opacity-50"
- >
- <Lifebuoy size={14} />
- Get support
- </Button>
- {banner}
- </Flex>
- )}
- {footerRight ?? <div />}
- </Flex>
+ {showFooter && (
+ <Flex
+ justify="between"
+ className="absolute right-[32px] bottom-[20px] left-[32px] z-[2]"
+ >
+ {footerLeft ?? (
+ <Flex align="center" gap="3">
+ <Button
+ size="1"
+ variant="ghost"
+ color="gray"
+ onClick={onOpenSupport}
+ className="opacity-50"
+ >
+ <Lifebuoy size={14} />
+ Get support
+ </Button>
+ {banner}
+ </Flex>
+ )}
+ {footerRight ?? <div />}
+ </Flex>
+ )}
</Flex>
</Flex>
</Theme>
diff --git a/products/desktop/packages/ui/src/primitives/MathGridBackground.tsx b/products/desktop/packages/ui/src/primitives/MathGridBackground.tsx
new file mode 100644
index 000000000000..bddea67b4894
--- /dev/null
+++ b/products/desktop/packages/ui/src/primitives/MathGridBackground.tsx
@@ -0,0 +1,37 @@
+import { useId } from "react";
+
+const GRID_STROKE = "var(--border)";
+
+export function MathGridBackground() {
+ const patternId = useId();
+
+ return (
+ <svg
+ aria-hidden="true"
+ className="pointer-events-none absolute inset-0 size-full opacity-[0.35] dark:opacity-[0.16]"
+ style={{
+ maskImage:
+ "radial-gradient(circle at center, black 0%, rgba(0, 0, 0, 0.72) 48%, transparent 88%)",
+ WebkitMaskImage:
+ "radial-gradient(circle at center, black 0%, rgba(0, 0, 0, 0.72) 48%, transparent 88%)",
+ }}
+ >
+ <defs>
+ <pattern
+ id={patternId}
+ width="32"
+ height="32"
+ patternUnits="userSpaceOnUse"
+ >
+ <path
+ d="M 32 0 L 0 0 0 32"
+ fill="none"
+ stroke={GRID_STROKE}
+ strokeWidth="0.5"
+ />
+ </pattern>
+ </defs>
+ <rect width="100%" height="100%" fill={`url(#${patternId})`} />
+ </svg>
+ );
+}
diff --git a/products/desktop/packages/ui/src/primitives/ProductWordmark.tsx b/products/desktop/packages/ui/src/primitives/ProductWordmark.tsx
index 060e83d53cb7..01caf7f58958 100644
--- a/products/desktop/packages/ui/src/primitives/ProductWordmark.tsx
+++ b/products/desktop/packages/ui/src/primitives/ProductWordmark.tsx
@@ -9,10 +9,10 @@ import Logo from "@posthog/ui/primitives/Logo";
export function ProductWordmark() {
return (
<div className="flex items-center gap-2">
- <span className="flex [&>svg]:h-[26px] [&>svg]:w-auto">
+ <span className="flex [&>svg]:h-[18px] [&>svg]:w-auto">
<Logo wordmark={false} />
</span>
- <Text className="font-bold text-(--gray-12) text-[25px] leading-none tracking-[-0.05em]">
+ <Text className="font-bold text-foreground text-md leading-none tracking-[-0.05em]">
PostHog Desktop
</Text>
</div>