:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(desktop): mirror web GitHub and Slack integration settings (#85116)
Charles Vien8fc6fce90665
diff --git a/products/desktop/apps/mobile/src/features/tasks/hooks/useIntegrations.ts b/products/desktop/apps/mobile/src/features/tasks/hooks/useIntegrations.tsindex 25f909f6f93e..97499a2a0d75 100644--- a/products/desktop/apps/mobile/src/features/tasks/hooks/useIntegrations.ts+++ b/products/desktop/apps/mobile/src/features/tasks/hooks/useIntegrations.ts@@ -102,6 +102,7 @@ export function useIntegrations(options: UseIntegrationsOptions = {}) {isError: false,isRefetching: repositoriesQuery.isRefetching,})),+ githubIntegrations.map((integration) => integration.id),).repositoryMap,).sort();diff --git a/products/desktop/packages/api-client/src/posthog-client.ts b/products/desktop/packages/api-client/src/posthog-client.tsindex 8ecbd016e628..a0ddaec0ae76 100644--- a/products/desktop/packages/api-client/src/posthog-client.ts+++ b/products/desktop/packages/api-client/src/posthog-client.ts@@ -327,6 +327,8 @@ export type {export type Evaluation = Schemas.Evaluation;+export type GithubInstallationStatus = "connected" | "unavailable";+export interface UserGitHubIntegration {id: string;kind: "github";@@ -336,22 +338,39 @@ export interface UserGitHubIntegration {type?: string | null;name?: string | null;} | null;+ github_login?: string | null;uses_shared_installation?: boolean;+ /** False when disconnecting would also uninstall the App from GitHub. */+ installation_shared?: boolean;+ installation_status?: GithubInstallationStatus;created_at?: string;}+/** `unidentified` means the requester could not be resolved, so approval can never+ * be detected and the user has to restart the connect flow. */+export type GithubInstallRequestStatus =+ | "pending"+ | "approved"+ | "unidentified";+/** A personal GitHub App install awaiting (or granted) org-owner approval; the* durable server-side counterpart to the in-flight connect spinner. Mirrors* `GitHubInstallRequest` on the backend. */-export interface GitHubInstallRequest {+export interface GithubInstallRequestItem {id: string;github_login: string;- /** `unidentified` means the requester could not be resolved, so approval can- * never be detected and the user has to restart the connect flow. */- status: "pending" | "approved" | "unidentified";- installation_id?: string | null;+ status: GithubInstallRequestStatus;+ installation_id: string | null;+ account_login?: string | null;+ account_type?: string | null;requested_at: string;- resolved_at?: string | null;+ resolved_at: string | null;+}++export interface GithubInstallRequestsResponse {+ results: GithubInstallRequestItem[];+ /** App install page with no PostHog state, for an org owner to open. */+ install_url?: string | null;}export interface LlmSkillCreatedBy {@@ -1730,7 +1749,23 @@ export class PostHogAPIClient {return data.results ?? [];}- async getGithubInstallRequests(): Promise<GitHubInstallRequest[]> {+ async disconnectGithubUserIntegration(installationId: string): Promise<void> {+ const urlPath = `/api/users/@me/integrations/github/${encodeURIComponent(installationId)}/`;+ const url = new URL(`${this.api.baseUrl}${urlPath}`);+ const response = await this.api.fetcher.fetch({+ method: "delete",+ url,+ path: urlPath,+ });+ if (!response.ok && response.status !== 404) {+ throw new Error(+ `Failed to disconnect GitHub integration: ${response.statusText}`,+ );+ }+ }++ /** `GET /api/users/@me/integrations/github/install_requests/`: installs waiting on a GitHub org owner. */+ async getGithubInstallRequests(): Promise<GithubInstallRequestsResponse> {const urlPath = `/api/users/@me/integrations/github/install_requests/`;const url = new URL(`${this.api.baseUrl}${urlPath}`);const response = await this.api.fetcher.fetch({@@ -1738,32 +1773,52 @@ export class PostHogAPIClient {url,path: urlPath,});-if (!response.ok) {throw new Error(`Failed to fetch GitHub install requests: ${response.statusText}`,);}-- const data = (await response.json()) as {- results?: GitHubInstallRequest[];+ const data =+ (await response.json()) as Partial<GithubInstallRequestsResponse>;+ return {+ results: data.results ?? [],+ install_url: data.install_url ?? null,};- return data.results ?? [];}- async disconnectGithubUserIntegration(installationId: string): Promise<void> {- const urlPath = `/api/users/@me/integrations/github/${encodeURIComponent(installationId)}/`;+ async dismissGithubInstallRequest(requestId: string): Promise<void> {+ const urlPath = `/api/users/@me/integrations/github/install_requests/${encodeURIComponent(requestId)}/`;const url = new URL(`${this.api.baseUrl}${urlPath}`);- const response = await this.api.fetcher.fetch({+ await this.api.fetcher.fetch({method: "delete",url,path: urlPath,});- if (!response.ok && response.status !== 404) {- throw new Error(- `Failed to disconnect GitHub integration: ${response.statusText}`,- );- }+ }++ /** `DELETE /api/environments/{project}/integrations/{id}/`: any team-level integration (GitHub, Slack, ...). */+ async deleteIntegration(+ projectId: number,+ integrationId: number | string,+ ): Promise<void> {+ await this.api.delete("/api/projects/{project_id}/integrations/{id}/", {+ path: { project_id: projectId.toString(), id: Number(integrationId) },+ });+ }++ /** Emails the project's admins asking them to connect an integration; members only. */+ async requestIntegrationAccess(+ projectId: number,+ body: { kind: string; reason: string },+ ): Promise<void> {+ const urlPath = `/api/environments/${projectId}/integrations/request_access/`;+ const url = new URL(`${this.api.baseUrl}${urlPath}`);+ await this.api.fetcher.fetch({+ method: "post",+ url,+ path: urlPath,+ overrides: { body: JSON.stringify(body) },+ });}/** The user's linked Slack identities. Empty until they run the Sign-in-with-Slack flow. */@@ -4055,6 +4110,7 @@ export class PostHogAPIClient {): Promise<{repositories: string[];hasMore: boolean;+ total: number | null;}> {const teamId = await this.getTeamId();const url = new URL(@@ -4077,10 +4133,14 @@ export class PostHogAPIClient {);}- const data = (await response.json()) as { has_more?: boolean };+ const data = (await response.json()) as {+ has_more?: boolean;+ total?: number;+ };return {repositories: this.normalizeGithubRepositories(data),hasMore: data.has_more ?? false,+ total: typeof data.total === "number" ? data.total : null,};}@@ -4114,6 +4174,7 @@ export class PostHogAPIClient {): Promise<{repositories: string[];hasMore: boolean;+ total: number | null;}> {const urlPath = `/api/users/@me/integrations/github/${installationId}/repos/`;const url = new URL(`${this.api.baseUrl}${urlPath}`);@@ -4134,10 +4195,14 @@ export class PostHogAPIClient {);}- const data = (await response.json()) as { has_more?: boolean };+ const data = (await response.json()) as {+ has_more?: boolean;+ total?: number;+ };return {repositories: this.normalizeGithubRepositories(data),hasMore: data.has_more ?? false,+ total: typeof data.total === "number" ? data.total : null,};}diff --git a/products/desktop/packages/core/src/integrations/connectEligibility.test.ts b/products/desktop/packages/core/src/integrations/connectEligibility.test.tsindex 652a12db1d9a..b23fd87eded8 100644--- a/products/desktop/packages/core/src/integrations/connectEligibility.test.ts+++ b/products/desktop/packages/core/src/integrations/connectEligibility.test.ts@@ -1,9 +1,22 @@import { describe, expect, it } from "vitest";import {+ classifyGithubCallback,computeShouldUseTeamFlow,validateInstallUrl,} from "./connectEligibility";+describe("classifyGithubCallback", () => {+ it.each([+ [null, "success"],+ ["", "success"],+ ["github_install_pending", "pending_org_approval"],+ ["installation_not_authorized", "not_authorized"],+ ["access_denied", "error"],+ ])("maps %s to %s", (code, expected) => {+ expect(classifyGithubCallback(code)).toBe(expected);+ });+});+describe("computeShouldUseTeamFlow", () => {it("is true only for admins on a project without a team integration in a known region", () => {expect(diff --git a/products/desktop/packages/core/src/integrations/connectEligibility.ts b/products/desktop/packages/core/src/integrations/connectEligibility.tsindex 5df64a405b8d..5173bc507f54 100644--- a/products/desktop/packages/core/src/integrations/connectEligibility.ts+++ b/products/desktop/packages/core/src/integrations/connectEligibility.ts@@ -23,3 +23,23 @@ export function validateInstallUrl(}return trimmed;}++export type GithubConnectOutcomeKind =+ | "success"+ | "pending_org_approval"+ | "not_authorized"+ | "error";++/**+ * GitHub answers a member's install attempt with `setup_action=request` when an org owner has to+ * approve it. PostHog relays that as the `github_install_pending` code, which is a waiting state+ * rather than a failure, so it must not land in the generic error branch.+ */+export function classifyGithubCallback(+ errorCode: string | null | undefined,+): GithubConnectOutcomeKind {+ if (!errorCode) return "success";+ if (errorCode === "github_install_pending") return "pending_org_approval";+ if (errorCode === "installation_not_authorized") return "not_authorized";+ return "error";+}diff --git a/products/desktop/packages/core/src/integrations/connectErrors.test.ts b/products/desktop/packages/core/src/integrations/connectErrors.test.tsindex b7b99a8c4412..6d280733de55 100644--- a/products/desktop/packages/core/src/integrations/connectErrors.test.ts+++ b/products/desktop/packages/core/src/integrations/connectErrors.test.ts@@ -1,9 +1,78 @@+import { ApiRequestError } from "@posthog/api-client/fetcher";import { describe, expect, it } from "vitest";import {describeGithubConnectError,+ describeIntegrationDisconnectError,+ isAlreadyDisconnectedError,isGithubConnectPendingApproval,} from "./connectErrors";+describe("describeIntegrationDisconnectError", () => {+ it.each([+ [+ "403 explains the admin gate",+ new ApiRequestError(403, "{}", { detail: "nope" }),+ "Only project admins can disconnect this integration.",+ ],+ [+ "validation detail is shown verbatim",+ new ApiRequestError(400, "{}", {+ detail:+ "This integration is used by enabled data pipelines: Slack alerts.",+ }),+ "This integration is used by enabled data pipelines: Slack alerts.",+ ],+ [+ "plain error keeps its message",+ new Error("network down"),+ "network down",+ ],+ ["unknown falls back", "nope", "Failed to disconnect."],+ ])("%s", (_name, error, expected) => {+ expect(+ describeIntegrationDisconnectError(error, "Failed to disconnect."),+ ).toBe(expected);+ });+});++describe("isAlreadyDisconnectedError", () => {+ it.each([+ [+ "typed 404",+ new ApiRequestError(+ 404,+ '{"detail":"No GitHub integration found for this installation."}',+ ),+ true,+ ],+ [+ "legacy message with status",+ new Error(+ 'Failed request: [404] {"detail":"No GitHub integration found for this installation."}',+ ),+ true,+ ],+ [+ "legacy status text",+ new Error("Failed to disconnect GitHub integration: Not Found"),+ true,+ ],+ ["typed 500", new ApiRequestError(500, "boom"), false],+ [+ "typed 400 whose blocker detail reads like a 404",+ new ApiRequestError(+ 400,+ '{"detail":"Workflow not found alerts uses it"}',+ ),+ false,+ ],+ ["unrelated error", new Error("network down"), false],+ ["not an error", "nope", false],+ ])("%s", (_name, error, expected) => {+ expect(isAlreadyDisconnectedError(error)).toBe(expected);+ });+});+describe("describeGithubConnectError", () => {it("returns an empty string for no error", () => {expect(describeGithubConnectError(null)).toBe("");diff --git a/products/desktop/packages/core/src/integrations/connectErrors.ts b/products/desktop/packages/core/src/integrations/connectErrors.tsindex 4bdd42c9c7a8..744bd02d5c9b 100644--- a/products/desktop/packages/core/src/integrations/connectErrors.ts+++ b/products/desktop/packages/core/src/integrations/connectErrors.ts@@ -1,3 +1,5 @@+import { requestErrorStatus } from "@posthog/api-client/fetcher";+export interface GithubConnectError {message: string;code: string | null;@@ -6,6 +8,27 @@ export interface GithubConnectError {export const GITHUB_CONNECT_TIMEOUT_MESSAGE ="We didn't hear back from GitHub. If your organization requires approval to install the PostHog app, ask a GitHub org owner to approve it, then connect again.";+export const GITHUB_INSTALL_PENDING_MESSAGE =+ "GitHub sent your request to your organization owners. Once an owner approves the PostHog app, we'll finish connecting here.";++/**+ * A disconnect that 404s means the row is already gone, usually because the App was+ * uninstalled on GitHub and the webhook cleaned up first. That is the outcome the user+ * wanted, so callers treat it as success and refresh rather than surface a failure.+ *+ * A typed error carries its status, so that decides on its own. The message match is only+ * for untyped callers — a 400 body that happens to read "not found" (the blocker names the+ * pipelines and workflows still using the integration) is a real failure.+ */+export function isAlreadyDisconnectedError(error: unknown): boolean {+ const status = requestErrorStatus(error);+ if (status !== undefined) return status === 404;+ return (+ error instanceof Error &&+ /\[404\]|not found|No GitHub integration found/i.test(error.message)+ );+}+export const GITHUB_CONNECT_ERROR_MESSAGES: Record<string, string> = {access_denied:"You declined access on GitHub. Try again to grant the permissions PostHog needs.",@@ -54,3 +77,27 @@ export function describeGithubConnectError(}return error.message;}++/**+ * A message for a failed team-integration disconnect. The backend refuses with a 403 for+ * non-admins and with a validation detail when pipelines or workflows still use the+ * integration; that detail is the actionable part, so it is shown verbatim.+ */+export function describeIntegrationDisconnectError(+ error: unknown,+ fallback: string,+): string {+ 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;+ 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.tsindex 1574c6423eeb..b82900aaf841 100644--- a/products/desktop/packages/core/src/integrations/connectMachine.test.ts+++ b/products/desktop/packages/core/src/integrations/connectMachine.test.ts@@ -25,6 +25,18 @@ describe("connectReducer", () => {).toEqual({ state: "error", error });});+ it("pending ends the flow without an error", () => {+ expect(+ connectReducer({ state: "connecting", error: null }, { type: "pending" }),+ ).toEqual({ state: "pending", error: null });+ expect(deriveConnectFlags("pending")).toEqual({+ isConnecting: false,+ isTimedOut: false,+ hasError: false,+ isPending: true,+ });+ });+it("succeed and reset return to idle", () => {expect(connectReducer(CONNECT_INITIAL_STATUS, { type: "succeed" }).state,@@ -52,6 +64,7 @@ describe("deriveConnectFlags", () => {isConnecting: true,isTimedOut: false,hasError: false,+ isPending: false,});expect(deriveConnectFlags("error").hasError).toBe(true);expect(deriveConnectFlags("timed-out").isTimedOut).toBe(true);@@ -85,10 +98,11 @@ describe("invalidation keys", () => {expect(githubInvalidationKeys(7)[0]).toEqual(["integrations", 7]);});- it("slack keys cover list and root", () => {+ it("slack keys cover list, root, and the autonomy config", () => {expect(slackInvalidationKeys()).toEqual([["integrations", "list"],["integrations"],+ ["signals", "user-autonomy-config"],]);});});diff --git a/products/desktop/packages/core/src/integrations/connectMachine.ts b/products/desktop/packages/core/src/integrations/connectMachine.tsindex b96e37fb0657..5756444a7356 100644--- a/products/desktop/packages/core/src/integrations/connectMachine.ts+++ b/products/desktop/packages/core/src/integrations/connectMachine.ts@@ -1,6 +1,12 @@+import { signalsConfigKeys } from "../inbox/inboxQuery";import { githubInstallRequestKeys } from "./repositoryKeys";-export type ConnectState = "idle" | "connecting" | "timed-out" | "error";+export type ConnectState =+ | "idle"+ | "connecting"+ | "timed-out"+ | "error"+ | "pending";export interface ConnectError {message: string;@@ -16,6 +22,7 @@ export type ConnectAction =| { type: "begin" }| { type: "succeed" }| { type: "fail"; error: ConnectError }+ | { type: "pending" }| { type: "timeout" }| { type: "reset" };@@ -35,6 +42,9 @@ export function connectReducer(return { state: "idle", error: null };case "fail":return { state: "error", error: action.error };+ // GitHub handed the install to an org owner: the flow ended, but not in failure.+ case "pending":+ return { state: "pending", error: null };case "timeout":return { state: "timed-out", error: status.error };case "reset":@@ -48,6 +58,7 @@ export interface ConnectFlags {isConnecting: boolean;isTimedOut: boolean;hasError: boolean;+ isPending: boolean;}export function deriveConnectFlags(state: ConnectState): ConnectFlags {@@ -55,6 +66,7 @@ export function deriveConnectFlags(state: ConnectState): ConnectFlags {isConnecting: state === "connecting",isTimedOut: state === "timed-out",hasError: state === "error",+ isPending: state === "pending",};}@@ -83,5 +95,11 @@ export function githubInvalidationKeys(}export function slackInvalidationKeys(): ReadonlyArray<ReadonlyArray<unknown>> {- return [["integrations", "list"], ["integrations"]];+ // The autonomy config caches slack_notification_integration_id; connecting or+ // disconnecting a workspace changes it server-side, so refresh it too.+ return [+ ["integrations", "list"],+ ["integrations"],+ [...signalsConfigKeys.userAutonomyConfig],+ ];}diff --git a/products/desktop/packages/core/src/integrations/disconnectCopy.test.ts b/products/desktop/packages/core/src/integrations/disconnectCopy.test.tsnew file mode 100644index 000000000000..97cd0bdbd369--- /dev/null+++ b/products/desktop/packages/core/src/integrations/disconnectCopy.test.ts@@ -0,0 +1,35 @@+import { describe, expect, it } from "vitest";+import { buildGithubDisconnectDescription } from "./disconnectCopy";++describe("buildGithubDisconnectDescription", () => {+ it.each([+ [+ "project, last reference",+ false,+ "project" as const,+ "This uninstalls the PostHog app from PostHog on GitHub and disconnects it from every PostHog project and personal account that uses it.",+ ],+ [+ "project, shared",+ true,+ "project" as const,+ "This project stops using GitHub. The PostHog app stays installed on GitHub because other projects or accounts still use it.",+ ],+ [+ "account, shared",+ true,+ "account" as const,+ "Your account stops using GitHub. The PostHog app stays installed on GitHub because other projects or accounts still use it.",+ ],+ [+ "account, last reference",+ false,+ "account" as const,+ "This uninstalls the PostHog app from PostHog on GitHub and disconnects it from every PostHog project and personal account that uses it.",+ ],+ ])("%s", (_name, installationShared, scope, expected) => {+ expect(+ buildGithubDisconnectDescription("PostHog", installationShared, scope),+ ).toBe(expected);+ });+});diff --git a/products/desktop/packages/core/src/integrations/disconnectCopy.ts b/products/desktop/packages/core/src/integrations/disconnectCopy.tsnew file mode 100644index 000000000000..fea32a41bafa--- /dev/null+++ b/products/desktop/packages/core/src/integrations/disconnectCopy.ts@@ -0,0 +1,24 @@+export type GithubDisconnectScope = "project" | "account";++/**+ * Disconnecting the last PostHog reference to a GitHub App installation also uninstalls the App+ * on GitHub and drops every other PostHog link to it, so the dialog states which case applies+ * instead of a generic warning.+ */+export function buildGithubDisconnectDescription(+ accountLabel: string,+ installationShared: boolean,+ scope: GithubDisconnectScope,+): string {+ if (installationShared) {+ const subject =+ scope === "account"+ ? "Your account stops using GitHub."+ : "This project stops using GitHub.";+ return `${subject} The PostHog app stays installed on GitHub because other projects or accounts still use it.`;+ }+ return `This uninstalls the PostHog app from ${accountLabel} on GitHub and disconnects it from every PostHog project and personal account that uses it.`;+}++export const SLACK_DISCONNECT_DESCRIPTION =+ "Reports and notifications from this project stop posting to Slack until someone reconnects it.";diff --git a/products/desktop/packages/core/src/integrations/installRequests.test.ts b/products/desktop/packages/core/src/integrations/installRequests.test.tsnew file mode 100644index 000000000000..bad90f334305--- /dev/null+++ b/products/desktop/packages/core/src/integrations/installRequests.test.ts@@ -0,0 +1,75 @@+import type { GithubInstallRequestItem } from "@posthog/api-client/posthog-client";+import { describe, expect, it } from "vitest";+import {+ buildOrgOwnerMessage,+ hasPendingInstallRequest,+ unlinkedApprovedRequests,+} from "./installRequests";++const request = (+ status: GithubInstallRequestItem["status"],+ installation_id: string | null = null,+): GithubInstallRequestItem => ({+ id: installation_id ?? status,+ github_login: "octocat",+ status,+ installation_id,+ requested_at: "2026-08-18T00:00:00Z",+ resolved_at: null,+});++describe("hasPendingInstallRequest", () => {+ it.each([+ ["undefined", undefined, false],+ ["empty", [], false],+ ["only approved", [request("approved")], false],+ ["mixed", [request("approved"), request("pending")], true],+ ])("%s", (_name, requests, expected) => {+ expect(hasPendingInstallRequest(requests)).toBe(expected);+ });+});++describe("buildOrgOwnerMessage", () => {+ it("names the install page the owner should open", () => {+ expect(+ buildOrgOwnerMessage("https://github.com/apps/posthog/installations/new"),+ ).toContain("https://github.com/apps/posthog/installations/new");+ });+});++describe("unlinkedApprovedRequests", () => {+ it.each([+ ["undefined", undefined, [], []],+ ["only pending is never returned", [request("pending", "123")], [], []],+ [+ "approved and not yet linked stays",+ [request("approved", "123")],+ [],+ ["123"],+ ],+ [+ "approved but already linked drops out",+ [request("approved", "123")],+ ["123"],+ [],+ ],+ [+ "approved without an installation id stays",+ [request("approved", null)],+ ["123"],+ [null],+ ],+ [+ "one linked, one still unlinked",+ [request("approved", "123"), request("approved", "456")],+ ["123"],+ ["456"],+ ],+ ] as const)("%s", (_name, requests, linkedIds, expectedIds) => {+ expect(+ unlinkedApprovedRequests(requests, linkedIds).map(+ (r) => r.installation_id,+ ),+ ).toEqual(expectedIds);+ });+});diff --git a/products/desktop/packages/core/src/integrations/installRequests.ts b/products/desktop/packages/core/src/integrations/installRequests.tsnew file mode 100644index 000000000000..93137ad0ce98--- /dev/null+++ b/products/desktop/packages/core/src/integrations/installRequests.ts@@ -0,0 +1,31 @@+import type { GithubInstallRequestItem } from "@posthog/api-client/posthog-client";++export function hasPendingInstallRequest(+ requests: ReadonlyArray<GithubInstallRequestItem> | undefined,+): boolean {+ return requests?.some((request) => request.status === "pending") ?? false;+}++/**+ * Approved requests still worth a "Finish connecting" prompt. An approved request is durable+ * server state that outlives the connection it unblocked, so once its installation is linked in+ * PostHog it drops out here — otherwise the banner keeps offering "Finish connecting" next to an+ * already-connected surface. Requests without an installation id (never expected once approved)+ * stay visible rather than being hidden on a missing match.+ */+export function unlinkedApprovedRequests(+ requests: ReadonlyArray<GithubInstallRequestItem> | undefined,+ linkedInstallationIds: ReadonlyArray<string>,+): GithubInstallRequestItem[] {+ const linked = new Set(linkedInstallationIds);+ return (requests ?? []).filter(+ (request) =>+ request.status === "approved" &&+ (request.installation_id === null ||+ !linked.has(request.installation_id)),+ );+}++export function buildOrgOwnerMessage(installUrl: string): string {+ return `Can you approve the PostHog GitHub app for our organization? Open ${installUrl}, pick the organization, and approve the pending request.`;+}diff --git a/products/desktop/packages/core/src/integrations/repositories.test.ts b/products/desktop/packages/core/src/integrations/repositories.test.tsindex 9e6062748d14..b83ec645f26a 100644--- a/products/desktop/packages/core/src/integrations/repositories.test.ts+++ b/products/desktop/packages/core/src/integrations/repositories.test.ts@@ -105,7 +105,7 @@ describe("combineGithubRepositories", () => {result({ integrationId: 2, repos: ["a/x", "a/z"] }),];- const combined = combineGithubRepositories(results);+ const combined = combineGithubRepositories(results, [1, 2]);expect(combined.repositoryMap).toEqual({"a/x": 1,@@ -113,14 +113,28 @@ describe("combineGithubRepositories", () => {"a/z": 2,});expect(combined.isPending).toBe(false);+ expect(combined.failedIntegrationIds).toEqual([]);});it("reports pending when any result is pending", () => {- const combined = combineGithubRepositories([- result<TeamRepositoriesResult>(undefined, { isPending: true }),- ]);+ const combined = combineGithubRepositories(+ [result<TeamRepositoriesResult>(undefined, { isPending: true })],+ [1],+ );expect(combined.isPending).toBe(true);});++ it("tallies failed integration ids so the row can flag the failure", () => {+ const results: RepositoryQueryResult<TeamRepositoriesResult>[] = [+ result({ integrationId: 1, repos: ["a/x"] }),+ result<TeamRepositoriesResult>(undefined, { isError: true }),+ ];++ const combined = combineGithubRepositories(results, [1, 2]);++ expect(combined.repositoryMap).toEqual({ "a/x": 1 });+ expect(combined.failedIntegrationIds).toEqual([2]);+ });});describe("combineUserGithubRepositories", () => {diff --git a/products/desktop/packages/core/src/integrations/repositories.ts b/products/desktop/packages/core/src/integrations/repositories.tsindex 92079b8d577c..c7815e337830 100644--- a/products/desktop/packages/core/src/integrations/repositories.ts+++ b/products/desktop/packages/core/src/integrations/repositories.ts@@ -137,23 +137,30 @@ export interface TeamRepositoriesResult {export interface CombinedTeamRepositories {repositoryMap: Record<string, number>;isPending: boolean;+ failedIntegrationIds: number[];}export function combineGithubRepositories(results: ReadonlyArray<RepositoryQueryResult<TeamRepositoriesResult>>,+ integrationIds: ReadonlyArray<number>,): CombinedTeamRepositories {const map: Record<string, number> = {};+ const failedIntegrationIds: number[] = [];let pending = false;- for (const result of results) {+ results.forEach((result, index) => {if (result.isPending) pending = true;- if (!result.data) continue;+ if (result.isError) {+ const integrationId = integrationIds[index];+ if (integrationId != null) failedIntegrationIds.push(integrationId);+ }+ if (!result.data) return;for (const repo of result.data.repos ?? []) {if (!(repo in map)) {map[repo] = result.data.integrationId;}}- }- return { repositoryMap: map, isPending: pending };+ });+ return { repositoryMap: map, isPending: pending, failedIntegrationIds };}export interface UserRepositoryIntegrationRef {diff --git a/products/desktop/packages/core/src/integrations/selectors.ts b/products/desktop/packages/core/src/integrations/selectors.tsindex 7e89beb3d9ee..dc9b729eb3b8 100644--- a/products/desktop/packages/core/src/integrations/selectors.ts+++ b/products/desktop/packages/core/src/integrations/selectors.ts@@ -5,6 +5,9 @@ export interface IntegrationAccount {export interface IntegrationConfig {account?: IntegrationAccount;+ installation_id?: string | number;+ /** GitHub's scope for the installation: "all" repositories or "selected" ones. */+ repository_selection?: string | null;[key: string]: unknown;}@@ -13,6 +16,11 @@ export interface Integration {kind: string;config?: IntegrationConfig;display_name?: string;+ created_at?: string;+ /** GitHub only. False when disconnecting would also uninstall the App from GitHub. */+ installation_shared?: boolean | null;+ /** GitHub only. `unavailable` once the App was removed or suspended on GitHub. */+ installation_status?: "connected" | "unavailable" | null;[key: string]: unknown;}diff --git a/products/desktop/packages/core/src/onboarding/githubConnectPanel.ts b/products/desktop/packages/core/src/onboarding/githubConnectPanel.tsindex 800635f78792..147af9b28d03 100644--- a/products/desktop/packages/core/src/onboarding/githubConnectPanel.ts+++ b/products/desktop/packages/core/src/onboarding/githubConnectPanel.ts@@ -1,6 +1,7 @@import type { OnboardingGithubConnectFlow } from "@posthog/shared/analytics-events";import {GITHUB_CONNECT_TIMEOUT_MESSAGE,+ GITHUB_INSTALL_PENDING_MESSAGE,isGithubConnectPendingApproval,} from "../integrations/connectErrors";import { POSTHOG_GITHUB_APP_URL } from "../integrations/githubApp";@@ -10,12 +11,15 @@ export interface GithubPanelMessageOptions {connectErrorMessage: string;timedOut: boolean;isConnecting: boolean;+ /** GitHub is waiting on an org owner to approve the install. */+ isPending?: boolean;}export function getGithubPanelMessage(options: GithubPanelMessageOptions,): string {if (options.hasConnectError) return options.connectErrorMessage;+ if (options.isPending) return GITHUB_INSTALL_PENDING_MESSAGE;if (options.timedOut) {return GITHUB_CONNECT_TIMEOUT_MESSAGE;}diff --git a/products/desktop/packages/core/src/onboarding/githubConnectService.test.ts b/products/desktop/packages/core/src/onboarding/githubConnectService.test.tsindex 0a3f7e99d90d..33938a2d0c35 100644--- a/products/desktop/packages/core/src/onboarding/githubConnectService.test.ts+++ b/products/desktop/packages/core/src/onboarding/githubConnectService.test.ts@@ -1,3 +1,4 @@+import { ApiRequestError } from "@posthog/api-client/fetcher";import { describe, expect, it, vi } from "vitest";import { GithubConnectService } from "./githubConnectService";import type { GithubConnectClient } from "./identifiers";@@ -20,6 +21,26 @@ describe("GithubConnectService", () => {expect(disconnect).toHaveBeenCalledWith("install-1");});+ it("treats a row that is already gone as disconnected", async () => {+ const disconnect = vi+ .fn()+ .mockRejectedValue(new ApiRequestError(404, '{"detail":"gone"}'));+ const service = new GithubConnectService(makeClient(disconnect));++ await expect(+ service.disconnectInstallation("install-1"),+ ).resolves.toBeUndefined();+ });++ it("still surfaces other disconnect failures", async () => {+ const disconnect = vi+ .fn()+ .mockRejectedValue(new ApiRequestError(500, "boom"));+ const service = new GithubConnectService(makeClient(disconnect));++ await expect(service.disconnectInstallation("install-1")).rejects.toThrow();+ });+it("reconnect disconnects then runs the connect flow in order", async () => {const calls: string[] = [];const disconnect = vi.fn().mockImplementation(async () => {diff --git a/products/desktop/packages/core/src/onboarding/githubConnectService.ts b/products/desktop/packages/core/src/onboarding/githubConnectService.tsindex 829e598c7358..5aa71f64b268 100644--- a/products/desktop/packages/core/src/onboarding/githubConnectService.ts+++ b/products/desktop/packages/core/src/onboarding/githubConnectService.ts@@ -1,4 +1,5 @@import { inject, injectable } from "inversify";+import { isAlreadyDisconnectedError } from "../integrations/connectErrors";import { GITHUB_CONNECT_CLIENT, type GithubConnectClient } from "./identifiers";@injectable()@@ -21,8 +22,13 @@ export class GithubConnectService {return true;}+ /** A row already removed server-side (uninstalled on GitHub) counts as disconnected. */async disconnectInstallation(installationId: string): Promise<void> {- await this.client.disconnectGithubUserIntegration(installationId);+ try {+ await this.client.disconnectGithubUserIntegration(installationId);+ } catch (error) {+ if (!isAlreadyDisconnectedError(error)) throw error;+ }}isReconnecting(installationId: string): boolean {@@ -40,7 +46,7 @@ export class GithubConnectService {if (this.reconnectingInstallationId !== null) return;this.reconnectingInstallationId = installationId;try {- await this.client.disconnectGithubUserIntegration(installationId);+ await this.disconnectInstallation(installationId);await connect();} finally {this.reconnectingInstallationId = null;diff --git a/products/desktop/packages/core/src/settings/githubRepoSummary.test.ts b/products/desktop/packages/core/src/settings/githubRepoSummary.test.tsindex 2a23a66ff65f..6d7cb53b05be 100644--- a/products/desktop/packages/core/src/settings/githubRepoSummary.test.ts+++ b/products/desktop/packages/core/src/settings/githubRepoSummary.test.ts@@ -1,9 +1,74 @@import { describe, expect, it } from "vitest";import {+ describeGithubRepoAccess,+ formatGithubAccountLabel,+ formatRepoPreview,githubInstallationSettingsUrl,summarizeReposByOwner,} from "./githubRepoSummary";+describe("describeGithubRepoAccess", () => {+ it.each([+ [+ "all with total",+ { selection: "all", total: 712, repos: ["a"], accountLabel: "PostHog" },+ { kind: "all", label: "All repositories in PostHog (712)" },+ ],+ [+ "all without total",+ { selection: "all", total: null, repos: [], accountLabel: "PostHog" },+ { kind: "all", label: "All repositories in PostHog" },+ ],+ [+ "selected repos",+ { selection: "selected", total: 2, repos: ["a/b", "a/c"] },+ { kind: "selected", label: "2 selected repositories" },+ ],+ [+ "single selected repo",+ { selection: "selected", total: 1, repos: ["a/b"] },+ { kind: "selected", label: "1 selected repository" },+ ],+ [+ "no repos",+ { selection: "selected", total: 0, repos: [] },+ { kind: "empty", label: "No repositories accessible" },+ ],+ [+ "unknown selection",+ { selection: null, total: null, repos: ["a/b", "a/c", "a/d"] },+ { kind: "unknown", label: "3 repositories accessible" },+ ],+ ])("%s", (_name, input, expected) => {+ expect(describeGithubRepoAccess(input)).toEqual(expected);+ });+});++describe("formatGithubAccountLabel", () => {+ it.each([+ ["real name", { name: "PostHog", type: "Organization" }, "PostHog"],+ ["blank name", { name: " ", type: null }, "GitHub installation 152736578"],+ [+ "numeric placeholder",+ { name: "152736578", type: null },+ "GitHub installation 152736578",+ ],+ ["missing account", null, "GitHub installation 152736578"],+ ])("%s", (_name, account, expected) => {+ expect(formatGithubAccountLabel(account, "152736578")).toBe(expected);+ });+});++describe("formatRepoPreview", () => {+ it.each([+ [["a/b"], "a/b"],+ [["a/b", "a/c", "a/d"], "a/b, a/c, a/d"],+ [["a/b", "a/c", "a/d", "a/e", "a/f"], "a/b, a/c, a/d and 2 more"],+ ])("%j", (repos, expected) => {+ expect(formatRepoPreview(repos)).toBe(expected);+ });+});+describe("summarizeReposByOwner", () => {it("counts repos per owner and sorts by count desc then owner asc", () => {const result = summarizeReposByOwner([diff --git a/products/desktop/packages/core/src/settings/githubRepoSummary.ts b/products/desktop/packages/core/src/settings/githubRepoSummary.tsindex c72fa4021760..d4d45cb7a39f 100644--- a/products/desktop/packages/core/src/settings/githubRepoSummary.ts+++ b/products/desktop/packages/core/src/settings/githubRepoSummary.ts@@ -35,3 +35,76 @@ export function githubInstallationSettingsUrl(}return `https://github.com/settings/installations/${integration.installation_id}`;}++export type GithubRepoAccessKind = "all" | "selected" | "empty" | "unknown";++export interface GithubRepoAccessInput {+ /** GitHub's `repository_selection` for the installation, when the row carries it. */+ selection: string | null | undefined;+ /** Total repositories the installation can see, when the API reported one. */+ total: number | null | undefined;+ repos: readonly string[];+ accountLabel?: string | null;+}++export interface GithubRepoAccessSummary {+ kind: GithubRepoAccessKind;+ label: string;+}++function repositoryNoun(count: number): string {+ return count === 1 ? "repository" : "repositories";+}++/**+ * One line describing what an installation can see. "all" is summarized rather than listed:+ * an org with hundreds of repositories reads better as a count than as a truncated list.+ */+export function describeGithubRepoAccess(+ input: GithubRepoAccessInput,+): GithubRepoAccessSummary {+ const account = input.accountLabel?.trim() || "this installation";+ if (input.selection === "all") {+ const suffix = input.total != null ? ` (${input.total})` : "";+ return { kind: "all", label: `All repositories in ${account}${suffix}` };+ }+ const count = input.repos.length;+ if (count === 0) {+ return { kind: "empty", label: "No repositories accessible" };+ }+ if (input.selection === "selected") {+ return {+ kind: "selected",+ label: `${count} selected ${repositoryNoun(count)}`,+ };+ }+ return {+ kind: "unknown",+ label: `${count} ${repositoryNoun(count)} accessible`,+ };+}++/**+ * The account name shown for an installation. A blank or purely numeric name is the+ * placeholder written when GitHub failed to return the account at connect time, so it is+ * replaced with a label that says what the number is.+ */+export function formatGithubAccountLabel(+ account: GithubInstallationAccount | null | undefined,+ installationId: string | number,+): string {+ const name = account?.name?.trim() ?? "";+ if (!name || /^\d+$/.test(name)) {+ return `GitHub installation ${installationId}`;+ }+ return name;+}++export function formatRepoPreview(+ repos: readonly string[],+ previewCount = 3,+): string {+ const preview = repos.slice(0, previewCount).join(", ");+ const remainder = repos.length - previewCount;+ return remainder > 0 ? `${preview} and ${remainder} more` : preview;+}diff --git a/products/desktop/packages/ui/src/features/inbox/components/ConfigureAgentsSection.tsx b/products/desktop/packages/ui/src/features/inbox/components/ConfigureAgentsSection.tsxindex 460f006c22cf..b7dfe92e08d7 100644--- a/products/desktop/packages/ui/src/features/inbox/components/ConfigureAgentsSection.tsx+++ b/products/desktop/packages/ui/src/features/inbox/components/ConfigureAgentsSection.tsx@@ -211,7 +211,6 @@ export function ConfigureAgentsSection() {<SlackInboxNotificationsSettingsisLoading={isLoadingSlack}showHeader={false}- showTopBorder={false}/></SettingsSubsection>diff --git a/products/desktop/packages/ui/src/features/inbox/components/DataSourceSetup.tsx b/products/desktop/packages/ui/src/features/inbox/components/DataSourceSetup.tsxindex 39ca0204f949..ac29b4fa2ea0 100644--- a/products/desktop/packages/ui/src/features/inbox/components/DataSourceSetup.tsx+++ b/products/desktop/packages/ui/src/features/inbox/components/DataSourceSetup.tsx@@ -1,3 +1,4 @@+import { GITHUB_INSTALL_PENDING_MESSAGE } from "@posthog/core/integrations/connectErrors";import { Button } from "@posthog/quill";import {EXTERNAL_INBOX_SOURCE_BY_PRODUCT,@@ -7,6 +8,7 @@ import { useAuthenticatedClient } from "@posthog/ui/features/auth/authClient";import { useAuthStateValue } from "@posthog/ui/features/auth/store";import { GitHubRepoPicker } from "@posthog/ui/features/folder-picker/GitHubRepoPicker";import { DynamicSourceSetup } from "@posthog/ui/features/inbox/components/DynamicSourceSetup";+import { GithubInstallRequestsBanner } from "@posthog/ui/features/integrations/components/GithubInstallRequestsBanner";import {describeGithubConnectError,useGithubConnect,@@ -102,6 +104,7 @@ function GitHubSetup({ onComplete, onCancel }: SetupFormProps) {isConnecting: connecting,isTimedOut: timedOut,hasError: hasConnectError,+ isPending: awaitingApproval,connect: handleConnectGitHub,} = useGithubConnect({projectId,@@ -180,11 +183,13 @@ function GitHubSetup({ onComplete, onCancel }: SetupFormProps) {if (!hasGithubIntegration) {const statusMessage = hasConnectError? describeGithubConnectError(connectError)- : timedOut- ? "We didn't hear back from GitHub. If the browser tab was closed, click Try again."- : connecting- ? "Waiting for GitHub… finish authorizing in your browser, then return here."- : "Connect your GitHub account to import issues as Self-driving signals.";+ : awaitingApproval+ ? GITHUB_INSTALL_PENDING_MESSAGE+ : timedOut+ ? "We didn't hear back from GitHub. If the browser tab was closed, click Try again."+ : connecting+ ? "Waiting for GitHub… finish authorizing in your browser, then return here."+ : "Connect your GitHub account to import issues as Self-driving signals.";return (<SetupFormContainer title="Connect GitHub"><Flex direction="column" gap="3">@@ -197,6 +202,12 @@ function GitHubSetup({ onComplete, onCancel }: SetupFormProps) {>{statusMessage}</Text>+ {projectId != null ? (+ <GithubInstallRequestsBanner+ onFinishConnecting={() => void handleConnectGitHub()}+ isConnecting={connecting}+ />+ ) : null}<Flex gap="2" justify="end"><Buttontype="button"diff --git a/products/desktop/packages/ui/src/features/integrations/components/DisconnectIntegrationDialog.tsx b/products/desktop/packages/ui/src/features/integrations/components/DisconnectIntegrationDialog.tsxnew file mode 100644index 000000000000..2458d6cb4ee4--- /dev/null+++ b/products/desktop/packages/ui/src/features/integrations/components/DisconnectIntegrationDialog.tsx@@ -0,0 +1,59 @@+import {+ AlertDialog,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle,+ Button,+} from "@posthog/quill";+import type { ReactElement } from "react";++interface DisconnectIntegrationDialogProps {+ open: boolean;+ title: string;+ description: string;+ confirmLabel?: string;+ isPending: boolean;+ onConfirm: () => void;+ onCancel: () => void;+}++export function DisconnectIntegrationDialog({+ open,+ title,+ description,+ confirmLabel = "Disconnect",+ isPending,+ onConfirm,+ onCancel,+}: DisconnectIntegrationDialogProps): ReactElement {+ return (+ <AlertDialog+ open={open}+ onOpenChange={(next) => {+ if (!next && !isPending) onCancel();+ }}+ >+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>{title}</AlertDialogTitle>+ <AlertDialogDescription>{description}</AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <Button variant="outline" onClick={onCancel} disabled={isPending}>+ Cancel+ </Button>+ <Button+ variant="destructive"+ onClick={onConfirm}+ loading={isPending}+ disabled={isPending}+ >+ {confirmLabel}+ </Button>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ );+}diff --git a/products/desktop/packages/ui/src/features/integrations/components/GithubInstallRequestsBanner.tsx b/products/desktop/packages/ui/src/features/integrations/components/GithubInstallRequestsBanner.tsxnew file mode 100644index 000000000000..f367bd0fd513--- /dev/null+++ b/products/desktop/packages/ui/src/features/integrations/components/GithubInstallRequestsBanner.tsx@@ -0,0 +1,136 @@+import type { GithubInstallRequestItem } from "@posthog/api-client/posthog-client";+import {+ buildOrgOwnerMessage,+ unlinkedApprovedRequests,+} from "@posthog/core/integrations/installRequests";+import { Button, Text } from "@posthog/quill";+import { useDismissGithubInstallRequest } from "@posthog/ui/features/integrations/useDismissGithubInstallRequest";+import { useGithubInstallRequests } from "@posthog/ui/features/integrations/useGithubInstallRequests";+import { useUserGithubIntegrations } from "@posthog/ui/features/integrations/useIntegrations";+import { useCopy } from "@posthog/ui/primitives/useCopy";++interface GithubInstallRequestsBannerProps {+ /** Re-runs the surface's own connect flow once an owner has approved the install. */+ onFinishConnecting: () => void;+ isConnecting?: boolean;+}++/**+ * The "waiting for a GitHub org owner" state and its resolution. Rendering this keeps the+ * install-request list polling while anything is pending.+ */+export function GithubInstallRequestsBanner({+ onFinishConnecting,+ isConnecting = false,+}: GithubInstallRequestsBannerProps) {+ const { data } = useGithubInstallRequests();+ const { data: linkedInstallations, isSuccess: linkedInstallationsLoaded } =+ useUserGithubIntegrations();+ const dismiss = useDismissGithubInstallRequest();+ const { copied, copy } = useCopy();++ const requests = data?.results ?? [];+ const pending = requests.filter((r) => r.status === "pending");+ // Only surface approved requests once we know which installations are already linked.+ // An empty list while the query loads or after it fails would read as "nothing linked"+ // and offer "Finish connecting" for an install that is in fact already connected.+ const approved = linkedInstallationsLoaded+ ? unlinkedApprovedRequests(+ requests,+ (linkedInstallations ?? []).map(+ (integration) => integration.installation_id,+ ),+ )+ : [];+ const installUrl = data?.install_url ?? null;++ if (pending.length === 0 && approved.length === 0) {+ return null;+ }++ return (+ <div className="flex flex-col gap-2">+ {approved.map((request: GithubInstallRequestItem) => (+ <div+ key={request.id}+ className="flex flex-wrap items-center justify-between gap-2 rounded-(--radius-2) border border-(--green-6) bg-(--green-2) px-3 py-2"+ >+ <Text size="sm">+ An organization owner approved the PostHog app for{" "}+ <span className="font-medium">+ {request.account_login ||+ request.github_login ||+ "your organization"}+ </span>+ . Finish connecting to start using it.+ </Text>+ <div className="flex shrink-0 gap-2">+ <Button+ type="button"+ variant="primary"+ size="sm"+ onClick={onFinishConnecting}+ loading={isConnecting}+ disabled={isConnecting}+ >+ Finish connecting+ </Button>+ <Button+ type="button"+ variant="outline"+ size="sm"+ onClick={() => dismiss.mutate(request.id)}+ disabled={dismiss.isPending}+ >+ Dismiss+ </Button>+ </div>+ </div>+ ))}+ {pending.map((request: GithubInstallRequestItem) => (+ <div+ key={request.id}+ className="flex flex-col gap-2 rounded-(--radius-2) border border-(--blue-6) bg-(--blue-2) px-3 py-2"+ >+ <Text size="sm">+ GitHub sent your request+ {request.github_login ? (+ <>+ {" "}+ (as <span className="font-medium">{request.github_login}</span>)+ </>+ ) : null}{" "}+ to your organization owners. Once an owner approves the PostHog app,+ we'll finish connecting here.+ </Text>+ {installUrl ? (+ <code className="whitespace-normal break-words rounded-(--radius-1) bg-(--gray-3) px-2 py-1 text-(--gray-11) text-xs">+ {buildOrgOwnerMessage(installUrl)}+ </code>+ ) : null}+ <div className="flex flex-wrap gap-2">+ {installUrl ? (+ <Button+ type="button"+ variant="outline"+ size="sm"+ onClick={() => copy(buildOrgOwnerMessage(installUrl))}+ >+ {copied ? "Copied" : "Copy message for your org owner"}+ </Button>+ ) : null}+ <Button+ type="button"+ variant="outline"+ size="sm"+ onClick={() => dismiss.mutate(request.id)}+ disabled={dismiss.isPending}+ >+ Dismiss+ </Button>+ </div>+ </div>+ ))}+ </div>+ );+}diff --git a/products/desktop/packages/ui/src/features/integrations/components/GithubRepoSummary.stories.tsx b/products/desktop/packages/ui/src/features/integrations/components/GithubRepoSummary.stories.tsxnew file mode 100644index 000000000000..573c78cd453d--- /dev/null+++ b/products/desktop/packages/ui/src/features/integrations/components/GithubRepoSummary.stories.tsx@@ -0,0 +1,86 @@+import { Button } from "@posthog/quill";+import { GithubRepoSummary } from "@posthog/ui/features/integrations/components/GithubRepoSummary";+import { SettingsCard } from "@posthog/ui/features/settings/components/SettingsCard";+import type { Meta, StoryObj } from "@storybook/react-vite";++const repos = [+ "posthog/posthog",+ "posthog/posthog-js",+ "posthog/posthog.com",+ "posthog/posthog-python",+ "posthog/code",+];++const meta: Meta<typeof GithubRepoSummary> = {+ title: "Integrations/GithubRepoSummary",+ component: GithubRepoSummary,+ parameters: { layout: "padded" },+ decorators: [+ (Story) => (+ <SettingsCard>+ <Story />+ </SettingsCard>+ ),+ ],+ args: {+ accountLabel: "PostHog",+ repos,+ status: "connected",+ meta: "Connected 3 days ago",+ onManage: () => {},+ actions: (+ <Button variant="outline" size="sm" className="text-(--red-11)">+ Disconnect+ </Button>+ ),+ },+};++export default meta;+type Story = StoryObj<typeof GithubRepoSummary>;++export const SelectedRepositories: Story = {+ args: {+ summary: { kind: "selected", label: "5 selected repositories" },+ },+};++export const AllRepositories: Story = {+ args: {+ summary: { kind: "all", label: "All repositories in PostHog (712)" },+ },+};++export const NoRepositories: Story = {+ args: {+ repos: [],+ summary: { kind: "empty", label: "No repositories accessible" },+ },+};++export const LoadingRepositories: Story = {+ args: {+ repos: [],+ isLoadingRepos: true,+ summary: { kind: "unknown", label: "" },+ },+};++export const RemovedFromGithub: Story = {+ args: {+ status: "unavailable",+ summary: { kind: "selected", label: "5 selected repositories" },+ actions: (+ <Button variant="outline" size="sm" className="text-(--red-11)">+ Remove+ </Button>+ ),+ },+};++export const PlaceholderAccountName: Story = {+ args: {+ accountLabel: "GitHub installation 152736578",+ summary: { kind: "unknown", label: "5 repositories accessible" },+ },+};diff --git a/products/desktop/packages/ui/src/features/integrations/components/GithubRepoSummary.tsx b/products/desktop/packages/ui/src/features/integrations/components/GithubRepoSummary.tsxnew file mode 100644index 000000000000..4a3abf2434c6--- /dev/null+++ b/products/desktop/packages/ui/src/features/integrations/components/GithubRepoSummary.tsx@@ -0,0 +1,166 @@+import {+ ArrowSquareOutIcon,+ CaretDownIcon,+ CaretRightIcon,+ GithubLogoIcon,+ WarningIcon,+} from "@phosphor-icons/react";+import type { GithubRepoAccessSummary } from "@posthog/core/settings/githubRepoSummary";+import { formatRepoPreview } from "@posthog/core/settings/githubRepoSummary";+import { Button, Spinner, Text } from "@posthog/quill";+import type { ReactNode } from "react";+import { useState } from "react";++export type GithubConnectionStatus = "connected" | "unavailable" | "loading";++interface GithubRepoSummaryProps {+ /** The GitHub org or user the installation belongs to. */+ accountLabel: string;+ summary: GithubRepoAccessSummary;+ repos: readonly string[];+ status: GithubConnectionStatus;+ isLoadingRepos?: boolean;+ hasRepoFetchFailed?: boolean;+ /** Appended to the description line, e.g. "Connected 3 days ago". */+ meta?: ReactNode;+ onManage?: () => void;+ /** Slot on the right for the row's actions (Disconnect, Remove...). */+ actions?: ReactNode;+ /** Slot under the row for extra notes or banners. */+ children?: ReactNode;+}++/**+ * One installation row shared by the project connection, the personal installations list and+ * the Self-driving settings, so all three describe repository access the same way.+ */+export function GithubRepoSummary({+ accountLabel,+ summary,+ repos,+ status,+ isLoadingRepos = false,+ hasRepoFetchFailed = false,+ meta,+ onManage,+ actions,+ children,+}: GithubRepoSummaryProps) {+ const [expanded, setExpanded] = useState(false);+ const canExpand = summary.kind !== "all" && repos.length > 0;+ const isUnavailable = status === "unavailable";++ const metaSuffix = meta ? (+ <>+ <span className="mx-0.5">·</span>+ {meta}+ </>+ ) : null;++ const descriptionLine = isLoadingRepos ? (+ <span className="min-w-0">Loading repositories…{metaSuffix}</span>+ ) : hasRepoFetchFailed ? (+ <>+ <WarningIcon+ size={13}+ weight="fill"+ className="shrink-0 text-(--amber-9)"+ />+ <span className="min-w-0 text-(--amber-11)">+ Couldn't load repositories+ </span>+ </>+ ) : canExpand ? (+ <>+ <button+ type="button"+ aria-expanded={expanded}+ onClick={() => setExpanded((value) => !value)}+ className="-mx-1 flex min-w-0 cursor-pointer items-center gap-1 rounded px-1 text-left transition-colors hover:bg-(--gray-3)"+ >+ {expanded ? (+ <CaretDownIcon size={11} className="shrink-0 text-(--gray-10)" />+ ) : (+ <CaretRightIcon size={11} className="shrink-0 text-(--gray-10)" />+ )}+ <span className="min-w-0">+ {summary.label}+ {": "}+ <span className="text-gray-12">{formatRepoPreview(repos)}</span>+ </span>+ </button>+ {meta ? <span className="min-w-0">{metaSuffix}</span> : null}+ </>+ ) : (+ <span className="min-w-0">+ {summary.label}+ {metaSuffix}+ </span>+ );++ return (+ <div className="flex flex-col gap-2 px-3.5 py-2.5">+ <div className="flex min-h-11 items-center justify-between gap-6">+ <div className="flex min-w-0 flex-1 items-center gap-3">+ <div className="shrink-0 text-(--gray-11)">+ <GithubLogoIcon size={24} />+ </div>+ <div className="flex min-w-0 flex-col gap-0.5">+ <div className="flex min-w-0 items-center gap-1.5">+ <span className="truncate font-medium text-[13px] text-gray-12 leading-5">+ {accountLabel}+ </span>+ {isUnavailable ? (+ <span className="shrink-0 rounded-full bg-(--red-3) px-1.5 py-px font-medium text-(--red-11) text-[11px]">+ Removed from GitHub+ </span>+ ) : null}+ </div>+ <div className="flex min-w-0 items-center gap-1 text-[12px] text-gray-10 leading-snug">+ {status === "loading" ? <Spinner /> : descriptionLine}+ </div>+ </div>+ </div>+ <div className="flex shrink-0 items-center gap-2">+ {onManage ? (+ <Button+ type="button"+ variant="outline"+ size="sm"+ onClick={onManage}+ >+ Manage+ <ArrowSquareOutIcon size={12} />+ </Button>+ ) : null}+ {actions}+ </div>+ </div>+ {expanded && canExpand ? (+ <div className="ml-9 max-h-48 overflow-y-auto rounded-(--radius-2) border border-(--gray-5) bg-(--gray-2)">+ <div className="flex flex-col py-1">+ {repos.map((repo) => (+ <Text+ key={repo}+ size="xs"+ variant="muted"+ className="truncate px-2 py-0.5"+ >+ {repo}+ </Text>+ ))}+ </div>+ </div>+ ) : null}+ {isUnavailable ? (+ <div className="ml-9 rounded-(--radius-2) border border-(--red-6) bg-(--red-2) px-3 py-2">+ <Text size="xs" className="text-(--red-11)">+ The PostHog app was removed from GitHub. Remove this connection,+ then connect again if you still need it.+ </Text>+ </div>+ ) : null}+ {children}+ </div>+ );+}diff --git a/products/desktop/packages/ui/src/features/integrations/components/RequestIntegrationAccessForm.tsx b/products/desktop/packages/ui/src/features/integrations/components/RequestIntegrationAccessForm.tsxnew file mode 100644index 000000000000..d9318d06c463--- /dev/null+++ b/products/desktop/packages/ui/src/features/integrations/components/RequestIntegrationAccessForm.tsx@@ -0,0 +1,83 @@+import { Button, Text, Textarea } from "@posthog/quill";+import { useAuthenticatedClient } from "@posthog/ui/features/auth/authClient";+import { toast } from "@posthog/ui/primitives/toast";+import { useMutation } from "@tanstack/react-query";+import { useState } from "react";++const MAX_REASON_LENGTH = 2000;++interface RequestIntegrationAccessFormProps {+ projectId: number;+ kind: "github" | "slack";+ integrationName: string;+}++/**+ * The PostHog-side handoff for members who can't connect an integration themselves: the+ * request emails the project's admins, who can connect it in either the web app or Desktop.+ */+export function RequestIntegrationAccessForm({+ projectId,+ kind,+ integrationName,+}: RequestIntegrationAccessFormProps) {+ const client = useAuthenticatedClient();+ const [reason, setReason] = useState("");+ const [sent, setSent] = useState(false);++ const request = useMutation({+ mutationFn: async () => {+ await client.requestIntegrationAccess(projectId, {+ kind,+ reason: reason.trim(),+ });+ },+ onSuccess: () => {+ setSent(true);+ toast.success("Request sent. A project admin will get an email.");+ },+ onError: (error) => {+ toast.error(+ error instanceof Error ? error.message : "Couldn't send the request.",+ );+ },+ });++ if (sent) {+ return (+ <Text size="xs" variant="muted">+ Request sent. A project admin will get an email and can connect{" "}+ {integrationName} for this project.+ </Text>+ );+ }++ return (+ <div className="flex flex-col gap-2">+ <Text size="xs" variant="muted">+ Connecting {integrationName} needs a project admin. Tell them why you+ need it and we'll email them.+ </Text>+ <Textarea+ value={reason}+ onChange={(event) => setReason(event.target.value)}+ maxLength={MAX_REASON_LENGTH}+ rows={2}+ placeholder="e.g. I'm setting up Self-driving for the mobile repositories."+ disabled={request.isPending}+ />+ <div className="flex">+ <Button+ type="button"+ variant="primary"+ size="sm"+ onClick={() => request.mutate()}+ loading={request.isPending}+ disabled={request.isPending || reason.trim().length === 0}+ >+ Ask a project admin+ </Button>+ </div>+ </div>+ );+}diff --git a/products/desktop/packages/ui/src/features/integrations/useDismissGithubInstallRequest.ts b/products/desktop/packages/ui/src/features/integrations/useDismissGithubInstallRequest.tsnew file mode 100644index 000000000000..7d54d417c23a--- /dev/null+++ b/products/desktop/packages/ui/src/features/integrations/useDismissGithubInstallRequest.ts@@ -0,0 +1,31 @@+import { requestErrorStatus } from "@posthog/api-client/fetcher";+import { useAuthenticatedClient } from "@posthog/ui/features/auth/authClient";+import { GITHUB_INSTALL_REQUESTS_QUERY_KEY } from "@posthog/ui/features/integrations/useGithubInstallRequests";+import { toast } from "@posthog/ui/primitives/toast";+import { useMutation, useQueryClient } from "@tanstack/react-query";++export function useDismissGithubInstallRequest() {+ const client = useAuthenticatedClient();+ const queryClient = useQueryClient();++ return useMutation({+ mutationFn: async (requestId: string) => {+ if (!client) throw new Error("Not authenticated");+ try {+ await client.dismissGithubInstallRequest(requestId);+ } catch (error) {+ // Already gone server-side counts as dismissed.+ if (requestErrorStatus(error) !== 404) throw error;+ }+ },+ // A swallowed 404 resolves, so onError only fires for a real failure.+ onError: () => {+ toast.error("Couldn't dismiss the request. Try again.");+ },+ onSettled: () => {+ void queryClient.invalidateQueries({+ queryKey: [...GITHUB_INSTALL_REQUESTS_QUERY_KEY],+ });+ },+ });+}diff --git a/products/desktop/packages/ui/src/features/integrations/useGitHubIntegrationCallback.ts b/products/desktop/packages/ui/src/features/integrations/useGitHubIntegrationCallback.tsindex c2093ce0d671..5ca4458aac4e 100644--- a/products/desktop/packages/ui/src/features/integrations/useGitHubIntegrationCallback.ts+++ b/products/desktop/packages/ui/src/features/integrations/useGitHubIntegrationCallback.ts@@ -1,3 +1,5 @@+import { classifyGithubCallback } from "@posthog/core/integrations/connectEligibility";+import type { IntegrationCallback } from "@posthog/core/integrations/github";import { useHostTRPCClient } from "@posthog/host-router/react";import { logger } from "@posthog/ui/shell/logger";import { useEffect, useRef } from "react";@@ -15,9 +17,35 @@ export interface IntegrationCallbackError {interface Options {onSuccess: (projectId: number | null) => void;onError: (error: IntegrationCallbackError) => void;+ /** GitHub handed the install to an org owner; not an error, so it gets its own branch. */+ onPending?: (error: IntegrationCallbackError) => void;onTimedOut?: () => void;}+type CallbackData = Pick<+ IntegrationCallback,+ "status" | "projectId" | "errorCode" | "errorMessage"+>;++function dispatchCallback(data: CallbackData, opts: Options): void {+ if (data.status !== "error") {+ opts.onSuccess(data.projectId);+ return;+ }+ const error: IntegrationCallbackError = {+ message: data.errorMessage ?? DEFAULT_ERROR_MESSAGE,+ code: data.errorCode,+ };+ if (+ classifyGithubCallback(data.errorCode) === "pending_org_approval" &&+ opts.onPending+ ) {+ opts.onPending(error);+ return;+ }+ opts.onError(error);+}+/*** Subscribes to GitHub integration deep link callbacks and drains any pending* callback that arrived before the subscription was established (cold-start).@@ -25,13 +53,17 @@ interface Options {export function useGitHubIntegrationCallback({onSuccess,onError,+ onPending,onTimedOut,}: Options): void {const client = useHostTRPCClient();const hasConsumedPendingRef = useRef(false);- const optsRef = useRef({ onSuccess, onError, onTimedOut });- optsRef.current = { onSuccess, onError, onTimedOut };+ const optsRef = useRef({ onSuccess, onError, onPending, onTimedOut });+ // Declared before the subscription effects so the commit order keeps the ref ahead of them.+ useEffect(() => {+ optsRef.current = { onSuccess, onError, onPending, onTimedOut };+ });useEffect(() => {const callbackSubscription = client.githubIntegration.onCallback.subscribe(@@ -39,14 +71,7 @@ export function useGitHubIntegrationCallback({{onData: (data) => {log.info("Received integration deep link callback", data);- if (data.status === "error") {- optsRef.current.onError({- message: data.errorMessage ?? DEFAULT_ERROR_MESSAGE,- code: data.errorCode,- });- return;- }- optsRef.current.onSuccess(data.projectId);+ dispatchCallback(data, optsRef.current);},},);@@ -74,14 +99,7 @@ export function useGitHubIntegrationCallback({await client.githubIntegration.consumePendingCallback.query();if (!pending) return;log.info("Consumed pending integration callback on mount", pending);- if (pending.status === "error") {- optsRef.current.onError({- message: pending.errorMessage ?? DEFAULT_ERROR_MESSAGE,- code: pending.errorCode,- });- return;- }- optsRef.current.onSuccess(pending.projectId);+ dispatchCallback(pending, optsRef.current);} catch (error) {log.error("Failed to consume pending integration callback", error);}diff --git a/products/desktop/packages/ui/src/features/integrations/useGithubInstallRequests.ts b/products/desktop/packages/ui/src/features/integrations/useGithubInstallRequests.tsnew file mode 100644index 000000000000..584725e4584a--- /dev/null+++ b/products/desktop/packages/ui/src/features/integrations/useGithubInstallRequests.ts@@ -0,0 +1,26 @@+import { hasPendingInstallRequest } from "@posthog/core/integrations/installRequests";+import { githubInstallRequestKeys } from "@posthog/core/integrations/repositoryKeys";+import { useAuthenticatedQuery } from "@posthog/ui/hooks/useAuthenticatedQuery";++export const GITHUB_INSTALL_REQUESTS_QUERY_KEY =+ githubInstallRequestKeys.list();++const PENDING_POLL_INTERVAL_MS = 15_000;++/**+ * Installs waiting on a GitHub org owner. GitHub only reports the outcome through a webhook,+ * so while any request is pending the list is polled; once nothing is pending it goes quiet.+ */+export function useGithubInstallRequests() {+ return useAuthenticatedQuery(+ GITHUB_INSTALL_REQUESTS_QUERY_KEY,+ (client) => client.getGithubInstallRequests(),+ {+ refetchInterval: (query) =>+ hasPendingInstallRequest(query.state.data?.results)+ ? PENDING_POLL_INTERVAL_MS+ : false,+ refetchOnWindowFocus: true,+ },+ );+}diff --git a/products/desktop/packages/ui/src/features/integrations/useGithubUserConnect.ts b/products/desktop/packages/ui/src/features/integrations/useGithubUserConnect.tsindex 8bc177c25c92..bd57421255b8 100644--- a/products/desktop/packages/ui/src/features/integrations/useGithubUserConnect.ts+++ b/products/desktop/packages/ui/src/features/integrations/useGithubUserConnect.ts@@ -36,6 +36,8 @@ interface Result {isConnecting: boolean;isTimedOut: boolean;hasError: boolean;+ /** GitHub is waiting on an org owner to approve the install. */+ isPending: boolean;connect: () => Promise<void>;reset: () => void;}@@ -111,6 +113,12 @@ function useConnectStateMachine(stopPolling();dispatch({ type: "fail", error: cbError });},+ onPending: () => {+ stopPolling();+ dispatch({ type: "pending" });+ // The install request row exists server-side now; refresh so banners pick it up.+ invalidate(projectId);+ },onTimedOut: () => {stopPolling();dispatch({ type: "timeout" });diff --git a/products/desktop/packages/ui/src/features/integrations/useIntegrations.ts b/products/desktop/packages/ui/src/features/integrations/useIntegrations.tsindex d2f3eccdd4f8..e17ffff02b2e 100644--- a/products/desktop/packages/ui/src/features/integrations/useIntegrations.ts+++ b/products/desktop/packages/ui/src/features/integrations/useIntegrations.ts@@ -25,7 +25,6 @@ import {} from "@posthog/core/integrations/repositories";import type { RepositoriesService } from "@posthog/core/integrations/repositoriesService";import {- githubInstallRequestKeys,integrationKeys,type RepositoryRefetchKey,userGithubIntegrationKeys,@@ -72,12 +71,24 @@ async function refetchRepositoryKeys();}-export function useIntegrations() {+export interface IntegrationsQueryOptions {+ /**+ * Settings surfaces pass an interval so an uninstall on GitHub or Slack shows up while someone+ * is looking at the page; every other caller keeps the default one-shot fetch.+ */+ refetchInterval?: number;+}++export function useIntegrations(options: IntegrationsQueryOptions = {}) {const setIntegrations = useIntegrationStore((state) => state.setIntegrations);const query = useAuthenticatedQuery(integrationKeys.list(),(client) => client.getIntegrations() as Promise<Integration[]>,+ {+ refetchInterval: options.refetchInterval ?? false,+ refetchOnWindowFocus: true,+ },);useEffect(() => {@@ -104,26 +115,22 @@ function useAllGithubRepositories(githubIntegrations: Integration[]) {staleTime: 5 * 60 * 1000,meta: AUTH_SCOPED_QUERY_META,})),- combine: combineGithubRepositories,+ combine: (results) =>+ combineGithubRepositories(+ results,+ githubIntegrations.map((integration) => integration.id),+ ),});}-export function useUserGithubIntegrations() {- return useAuthenticatedQuery(userGithubIntegrationKeys.list(), (client) =>- client.getGithubUserIntegrations(),- );-}--// Polls only while pending; an approved or empty list never changes on its own.-export function useGithubInstallRequests() {+export function useUserGithubIntegrations(+ options: IntegrationsQueryOptions = {},+) {return useAuthenticatedQuery(- githubInstallRequestKeys.list(),- (client) => client.getGithubInstallRequests(),+ userGithubIntegrationKeys.list(),+ (client) => client.getGithubUserIntegrations(),{- refetchInterval: (query) =>- (query.state.data ?? []).some((request) => request.status === "pending")- ? 30_000- : false,+ refetchInterval: options.refetchInterval ?? false,refetchOnWindowFocus: true,},);@@ -580,8 +587,11 @@ export function useRepositoryIntegration() {useIntegrationSelectors();const [isRefreshingRepos, setIsRefreshingRepos] = useState(false);- const { repositoryMap, isPending: reposPending } =- useAllGithubRepositories(githubIntegrations);+ const {+ repositoryMap,+ isPending: reposPending,+ failedIntegrationIds,+ } = useAllGithubRepositories(githubIntegrations);const repositories = useMemo(() => Object.keys(repositoryMap),@@ -625,5 +635,6 @@ export function useRepositoryIntegration() {isRefreshingRepos,refreshRepositories,hasGithubIntegration,+ failedIntegrationIds,};}diff --git a/products/desktop/packages/ui/src/features/integrations/useSlackConnect.ts b/products/desktop/packages/ui/src/features/integrations/useSlackConnect.tsindex efdb738efe90..05fdcd8ef479 100644--- a/products/desktop/packages/ui/src/features/integrations/useSlackConnect.ts+++ b/products/desktop/packages/ui/src/features/integrations/useSlackConnect.ts@@ -18,7 +18,7 @@ const POLL_TIMEOUT_MS = 300_000;export type SlackConnectState = ConnectState;export type SlackConnectError = ConnectError;-interface Result {+export interface SlackConnectResult {state: SlackConnectState;error: SlackConnectError | null;isConnecting: boolean;@@ -41,8 +41,12 @@ function invalidateIntegrationQueries(queryClient: QueryClient): void {* - refetches integration queries on success so the rest of the UI updates,* - times out after 5 minutes and refetches as a fallback (a Slack admin who* finishes the install in another browser still surfaces eventually).+ *+ * State is per-instance and the pending-callback read is destructive, so a surface with a+ * connect button and an error callout must call this once and share the result, not call it+ * from each component.*/-export function useSlackConnect(): Result {+export function useSlackConnect(): SlackConnectResult {const client = useHostTRPCClient();const queryClient = useQueryClient();const cloudRegion = useAuthStateValue((s) => s.cloudRegion);diff --git a/products/desktop/packages/ui/src/features/onboarding/components/GitHubConnectPanel.tsx b/products/desktop/packages/ui/src/features/onboarding/components/GitHubConnectPanel.tsxindex 77478fcb8019..cb581e9758f6 100644--- a/products/desktop/packages/ui/src/features/onboarding/components/GitHubConnectPanel.tsx+++ b/products/desktop/packages/ui/src/features/onboarding/components/GitHubConnectPanel.tsx@@ -6,7 +6,10 @@ import {GithubLogo,Plus,} from "@phosphor-icons/react";-import { isGithubConnectPendingApproval } from "@posthog/core/integrations/connectErrors";+import {+ GITHUB_CONNECT_PENDING_APPROVAL_CODE,+ isGithubConnectPendingApproval,+} from "@posthog/core/integrations/connectErrors";import {buildConnectAbandonedProps,buildConnectFailedProps,@@ -21,6 +24,7 @@ import {} from "@posthog/core/onboarding/githubConnectPanel";import type { GithubConnectService } from "@posthog/core/onboarding/githubConnectService";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 type { OnboardingGithubConnectFlow } from "@posthog/shared/analytics-events";@@ -28,12 +32,12 @@ import { ANALYTICS_EVENTS } from "@posthog/shared/analytics-events";import { useAuthStateValue } from "@posthog/ui/features/auth/store";import { GithubApprovalNotice } from "@posthog/ui/features/integrations/GithubApprovalNotice";import { useGithubDisconnect } from "@posthog/ui/features/integrations/useGithubDisconnect";+import { useGithubInstallRequests } from "@posthog/ui/features/integrations/useGithubInstallRequests";import {describeGithubConnectError,useGithubConnect,} from "@posthog/ui/features/integrations/useGithubUserConnect";import {- useGithubInstallRequests,useUserGithubIntegrations,useUserRepositoryIntegration,} from "@posthog/ui/features/integrations/useIntegrations";@@ -93,6 +97,7 @@ export function GitHubConnectPanel() {isConnecting,isTimedOut: timedOut,hasError: hasConnectError,+ isPending: awaitingApproval,connect: handleConnectGitHub,reset: resetConnect,} = useGithubConnect({@@ -104,7 +109,10 @@ export function GitHubConnectPanel() {},});const canTakeAction = !isConnecting && !timedOut && !hasConnectError;- const isPendingApproval = isGithubConnectPendingApproval(connectError?.code);+ // The callback reports an org-owner wait through onPending when the caller+ // handles it, and on the error channel otherwise, so both are read here.+ const isPendingApproval =+ awaitingApproval || isGithubConnectPendingApproval(connectError?.code);// Every path that begins a connect, including reconnect, must go through// this, or its "started" event has no abandoned counterpart.@@ -151,7 +159,12 @@ export function GitHubConnectPanel() {timedOut,errorCode: connectError?.code,};- const fingerprint = buildConnectFailureFingerprint(failureInputs);+ // A pending approval ends the flow without an error, so it carries no+ // failure fingerprint of its own; reuse the code so it stays deduped and+ // still counts as terminal for the abandonment marker below.+ const fingerprint = isPendingApproval+ ? GITHUB_CONNECT_PENDING_APPROVAL_CODE+ : buildConnectFailureFingerprint(failureInputs);const flowType = inFlightConnectRef.current?.flowType ?? "user_new";// Clear the marker only on a terminal outcome — even a deduped one. A// non-terminal re-run (a retry moving error/timeout back to connecting)@@ -183,6 +196,7 @@ export function GitHubConnectPanel() {connectErrorMessage: describeGithubConnectError(connectError),timedOut,isConnecting,+ isPending: awaitingApproval,});const {@@ -190,10 +204,10 @@ export function GitHubConnectPanel() {isLoading: githubUserIntegrationsLoading,} = useUserGithubIntegrations();const hasGitIntegration = githubUserIntegrations.length > 0;- const { data: githubInstallRequests = [] } = useGithubInstallRequests();+ const { data: githubInstallRequests } = useGithubInstallRequests();const approvalState = deriveGithubApprovalState({errorCode: connectError?.code,- requests: githubInstallRequests,+ requests: githubInstallRequests?.results ?? [],hasIntegration: hasGitIntegration,});const isAwaitingApproval = approvalState === "awaiting";@@ -345,7 +359,10 @@ export function GitHubConnectPanel() {<Flex direction="column" gap="3">{githubUserIntegrations.map((integration) => {const installationId = integration.installation_id;- const accountName = integration.account?.name ?? "GitHub";+ const accountName = formatGithubAccountLabel(+ integration.account,+ installationId,+ );const installRepos = reposByInstallationId[installationId];const isLoadingInstallRepos = installRepos === undefined;const isStale = failedInstallationIds.includes(installationId);diff --git a/products/desktop/packages/ui/src/features/settings/components/SettingsPageContent.tsx b/products/desktop/packages/ui/src/features/settings/components/SettingsPageContent.tsxindex 58443b754c95..059d260e0473 100644--- a/products/desktop/packages/ui/src/features/settings/components/SettingsPageContent.tsx+++ b/products/desktop/packages/ui/src/features/settings/components/SettingsPageContent.tsx@@ -75,7 +75,7 @@ const SETTINGS_PAGES: Record<SettingsCategory, SettingsPageDefinition> = {shortcuts: defineSettingsPage("Shortcuts", ShortcutsSettings),"quick-ask": defineSettingsPage("Quick ask", QuickAskSettings),github: defineSettingsPage("GitHub", GitHubSettings),- slack: defineSettingsPage("Slack integration", SlackSettings),+ slack: defineSettingsPage("Slack", SlackSettings),discord: defineSettingsPage("Discord", DiscordSettings),// Slack notification config lives in the dedicated Slack section; the Signals// section links out to it rather than duplicating the controls.@@ -119,7 +119,7 @@ function ContainedSettingsPageLayout({title,}: SettingsPageLayoutProps) {return (- <div className="h-full w-full overflow-y-auto">+ <div className="h-full w-full overflow-y-auto [scrollbar-gutter:stable_both-edges]"><div className="relative z-[1] mx-auto max-w-[800px] p-6"><div className="flex flex-col gap-5"><SettingsPageHeader formMode={formMode} icon={icon} title={title} />diff --git a/products/desktop/packages/ui/src/features/settings/components/SettingsPanel.tsx b/products/desktop/packages/ui/src/features/settings/components/SettingsPanel.tsxindex 648dc3078571..4a98d31cf735 100644--- a/products/desktop/packages/ui/src/features/settings/components/SettingsPanel.tsx+++ b/products/desktop/packages/ui/src/features/settings/components/SettingsPanel.tsx@@ -226,7 +226,7 @@ export function SettingsPanel({}}/>- <div className="flex-1 overflow-y-auto">+ <div className="flex-1 overflow-y-auto [scrollbar-gutter:stable]">{searchQuery.trim() ? (<SettingsSearchResultsresults={searchResults}diff --git a/products/desktop/packages/ui/src/features/settings/sections/DiscordPresencePreview.tsx b/products/desktop/packages/ui/src/features/settings/sections/DiscordPresencePreview.tsxindex c5b96f8243f6..7b4188561b3e 100644--- a/products/desktop/packages/ui/src/features/settings/sections/DiscordPresencePreview.tsx+++ b/products/desktop/packages/ui/src/features/settings/sections/DiscordPresencePreview.tsx@@ -1,5 +1,7 @@import { DotsThree, GameController, Pause, Play } from "@phosphor-icons/react";-import { Flex, SegmentedControl, Text } from "@radix-ui/themes";+import { SettingsSection } from "@posthog/ui/features/settings/components/SettingsCard";+import { SettingsSegmented } from "@posthog/ui/features/settings/components/SettingsSegmented";+import { Flex, Text } from "@radix-ui/themes";import { useEffect, useState } from "react";import posthogIcon from "../../auth/assets/posthog-icon.svg";@@ -63,27 +65,22 @@ export function DiscordPresencePreview({const state = showRepoName ? `${SAMPLE_REPO} · ${statusPart}` : statusPart;return (- <Flex direction="column" gap="3">- <Flex- align="center"- justify="between"- className="border-gray-6 border-t pt-4"- >- <Text className="font-medium text-sm">Preview</Text>- <div className={enabled ? "" : "pointer-events-none opacity-50"}>- <SegmentedControl.Root- size="1"- value={running ? "running" : "idle"}- onValueChange={(value) => setRunning(value === "running")}- >- <SegmentedControl.Item value="running">- Running- </SegmentedControl.Item>- <SegmentedControl.Item value="idle">Idle</SegmentedControl.Item>- </SegmentedControl.Root>- </div>- </Flex>-+ <SettingsSection+ label="Preview"+ description="What your Discord profile shows while you work."+ action={+ <SettingsSegmented+ value={running ? "running" : "idle"}+ options={[+ { value: "running", label: "Running" },+ { value: "idle", label: "Idle" },+ ]}+ onValueChange={(value) => setRunning(value === "running")}+ ariaLabel="Preview state"+ disabled={!enabled}+ />+ }+ ><divclassName={`max-w-[380px] rounded-xl border border-gray-5 bg-gray-2 px-4 py-3 ${enabled ? "" : "pointer-events-none opacity-50"@@ -130,6 +127,6 @@ export function DiscordPresencePreview({</Flex></Flex></div>- </Flex>+ </SettingsSection>);}diff --git a/products/desktop/packages/ui/src/features/settings/sections/DiscordSettings.tsx b/products/desktop/packages/ui/src/features/settings/sections/DiscordSettings.tsxindex 93745fc1a3aa..12c9d3c0d4d3 100644--- a/products/desktop/packages/ui/src/features/settings/sections/DiscordSettings.tsx+++ b/products/desktop/packages/ui/src/features/settings/sections/DiscordSettings.tsx@@ -1,13 +1,17 @@import { useService } from "@posthog/di/react";+import { Switch } from "@posthog/quill";import { ANALYTICS_EVENTS } from "@posthog/shared";import {DISCORD_PRESENCE_CLIENT,type DiscordPresenceClient,type DiscordPresenceState,} from "@posthog/ui/features/discord-presence/identifiers";-import { SettingRow } from "@posthog/ui/features/settings/SettingRow";+import {+ SettingsCard,+ SettingsCardRow,+ SettingsSection,+} from "@posthog/ui/features/settings/components/SettingsCard";import { track } from "@posthog/ui/shell/analytics";-import { Flex, Switch, Text } from "@radix-ui/themes";import { useEffect, useState } from "react";import { DiscordPresencePreview } from "./DiscordPresencePreview";@@ -78,72 +82,68 @@ export function DiscordSettings() {client.setShowRepoName(checked);};+ const statusDescription = !enabled ? (+ "Show what you're working on in PostHog on your profile"+ ) : !configured ? (+ <span className="text-(--amber-11)">+ No Discord application is configured for this build, so nothing will+ appear yet.+ </span>+ ) : connected ? (+ <span className="text-(--green-11)">Connected to Discord</span>+ ) : (+ <span className="text-(--amber-11)">+ Waiting for Discord (desktop app needs to be running)...+ </span>+ );+return (- <Flex direction="column">- <SettingRow- label="Rich Presence"- description="Show what you're working on in PostHog on your profile"- noBorder- >- <Switch- checked={enabled}- onCheckedChange={handleEnabledChange}- size="1"- />- </SettingRow>+ <div className="flex flex-col gap-7">+ <SettingsCard>+ <SettingsCardRow label="Rich Presence" description={statusDescription}>+ <Switch+ size="sm"+ checked={enabled}+ onCheckedChange={handleEnabledChange}+ />+ </SettingsCardRow>+ </SettingsCard>- {enabled && (- <>- {!configured ? (- <Text color="yellow" className="-mt-3 pb-3 text-[13px]">- No Discord application is configured for this build, so nothing- will appear yet.- </Text>- ) : (- <Text- color={connected ? "green" : "amber"}- className="-mt-3 pb-3 text-[13px]"+ {enabled ? (+ <SettingsSection+ label="Privacy"+ description="What the Rich Presence card reveals about your session."+ >+ <SettingsCard>+ <SettingsCardRow+ label="Show task title"+ description="Include the focused task's title">- {connected- ? "Connected to Discord"- : "Waiting for Discord (desktop app needs to be running)..."}- </Text>- )}-- <Text className="block border-gray-6 border-t pt-4 font-medium text-sm">- Privacy- </Text>-- <SettingRow- label="Show task title"- description="Include the focused task's title"- >- <Switch- checked={state?.showTaskTitle ?? false}- onCheckedChange={handleShowTaskTitleChange}- size="1"- />- </SettingRow>-- <SettingRow- label="Show repository name"- description="Include the repository (org/repo) you're working in"- noBorder- >- <Switch- checked={state?.showRepoName ?? false}- onCheckedChange={handleShowRepoNameChange}- size="1"- />- </SettingRow>- </>- )}+ <Switch+ size="sm"+ checked={state?.showTaskTitle ?? false}+ onCheckedChange={handleShowTaskTitleChange}+ />+ </SettingsCardRow>+ <SettingsCardRow+ label="Show repository name"+ description="Include the repository (org/repo) you're working in"+ >+ <Switch+ size="sm"+ checked={state?.showRepoName ?? false}+ onCheckedChange={handleShowRepoNameChange}+ />+ </SettingsCardRow>+ </SettingsCard>+ </SettingsSection>+ ) : null}<DiscordPresencePreviewenabled={enabled}showTaskTitle={state?.showTaskTitle ?? false}showRepoName={state?.showRepoName ?? false}/>- </Flex>+ </div>);}diff --git a/products/desktop/packages/ui/src/features/settings/sections/GitHubIntegrationSection.tsx b/products/desktop/packages/ui/src/features/settings/sections/GitHubIntegrationSection.tsxindex b1ed62404acb..50d8d7c04a73 100644--- a/products/desktop/packages/ui/src/features/settings/sections/GitHubIntegrationSection.tsx+++ b/products/desktop/packages/ui/src/features/settings/sections/GitHubIntegrationSection.tsx@@ -2,53 +2,56 @@ import {ArrowSquareOutIcon,CheckCircleIcon,GitBranchIcon,- InfoIcon,} from "@phosphor-icons/react";import {describeGithubConnectError,GITHUB_CONNECT_TIMEOUT_MESSAGE,} from "@posthog/core/integrations/connectErrors";-import { summarizeReposByOwner } from "@posthog/core/settings/githubRepoSummary";-import { Button } from "@posthog/quill";+import {+ describeGithubRepoAccess,+ formatGithubAccountLabel,+} from "@posthog/core/settings/githubRepoSummary";+import { Button, Spinner, Text } from "@posthog/quill";import { useAuthStateValue } from "@posthog/ui/features/auth/store";+import { useIsOrgAdmin } from "@posthog/ui/features/auth/useOrgRole";+import { GithubInstallRequestsBanner } from "@posthog/ui/features/integrations/components/GithubInstallRequestsBanner";+import { RequestIntegrationAccessForm } from "@posthog/ui/features/integrations/components/RequestIntegrationAccessForm";+import { useIntegrationSelectors } from "@posthog/ui/features/integrations/store";import { useGithubConnect } from "@posthog/ui/features/integrations/useGithubUserConnect";import { useRepositoryIntegration } from "@posthog/ui/features/integrations/useIntegrations";-import { Box, Flex, Spinner, Text, Tooltip } from "@radix-ui/themes";-import { useMemo } from "react";+import { openSettings } from "@posthog/ui/features/settings/hooks/useOpenSettings";+import { Tooltip } from "@posthog/ui/primitives/Tooltip";++interface GitHubIntegrationSectionProps {+ hasGithubIntegration: boolean;+ isLoading?: boolean;+ /** When false, omit the dashed bottom rule (e.g. inside a parent `divide-y` list). */+ showBottomBorder?: boolean;+}/**- * Past this count, the tooltip would become an unreadable wall of `owner/name`- * rows, so we collapse to owner-level summaries instead.+ * The compact "is this project connected to GitHub" row used by Self-driving setup. Full+ * management (disconnect, personal installations) lives on the GitHub settings page.*/-const REPO_LIST_TOOLTIP_THRESHOLD = 10;-export function GitHubIntegrationSection({hasGithubIntegration,isLoading = false,showBottomBorder = true,-}: {- hasGithubIntegration: boolean;- isLoading?: boolean;- /** When false, omit the dashed bottom rule (e.g. inside a parent `divide-y` list). */- showBottomBorder?: boolean;-}) {+}: GitHubIntegrationSectionProps) {const borderClass = showBottomBorder? "border-(--gray-5) border-b border-dashed pb-4": "";- const { repositories, isLoadingRepos } = useRepositoryIntegration();- const ownerSummary = useMemo(- () =>- repositories.length > REPO_LIST_TOOLTIP_THRESHOLD- ? summarizeReposByOwner(repositories)- : null,- [repositories],- );const projectId = useAuthStateValue((state) => state.currentProjectId);+ const { isAdmin } = useIsOrgAdmin();+ const { githubIntegrations } = useIntegrationSelectors();+ const { repositories, getIntegrationIdForRepo, isLoadingRepos } =+ useRepositoryIntegration();const {error: connectError,isConnecting: connecting,isTimedOut: timedOut,hasError: hasConnectError,+ isPending: awaitingApproval,connect: handleConnect,} = useGithubConnect({projectId,@@ -57,111 +60,160 @@ export function GitHubIntegrationSection({if (isLoading) {return (- <Flex align="center" justify="between" gap="4" className={borderClass}>- <Flex align="center" gap="3" className="min-w-0 flex-1">- <Box className="size-[20px] shrink-0 animate-pulse rounded bg-gray-4" />- <Flex direction="column" gap="2" className="min-w-0 flex-1">- <Box className="h-[12px] w-[40%] animate-pulse rounded bg-gray-4" />- <Box className="h-[11px] w-[60%] animate-pulse rounded bg-gray-3" />- </Flex>- </Flex>- <Box className="h-[24px] w-[120px] shrink-0 animate-pulse rounded bg-gray-3" />- </Flex>+ <div className={`flex items-center justify-between gap-4 ${borderClass}`}>+ <div className="flex min-w-0 flex-1 items-center gap-3">+ <div className="size-[20px] shrink-0 animate-pulse rounded bg-gray-4" />+ <div className="flex min-w-0 flex-1 flex-col gap-2">+ <div className="h-[12px] w-[40%] animate-pulse rounded bg-gray-4" />+ <div className="h-[11px] w-[60%] animate-pulse rounded bg-gray-3" />+ </div>+ </div>+ <div className="h-[24px] w-[120px] shrink-0 animate-pulse rounded bg-gray-3" />+ </div>);}- return (- <Flex align="center" justify="between" gap="4" className={borderClass}>- <Flex align="center" gap="3">- <Box className="shrink-0 text-(--gray-11)">- <GitBranchIcon size={20} />- </Box>- <Flex direction="column">- <Text className="font-medium text-(--gray-12) text-sm">- Project-level code access- </Text>- {hasGithubIntegration &&- !isLoadingRepos &&- repositories.length > 0 ? (- <Tooltip- content={- ownerSummary ? (- <Flex direction="column" gap="1">- <Text className="text-(--gray-10) text-[13px]">- {repositories.length} repos across {ownerSummary.length}{" "}- {ownerSummary.length === 1 ? "owner" : "owners"}- </Text>- {ownerSummary.map(({ owner, count }) => (- <Text key={owner} className="text-[13px]">- {owner} ({count})- </Text>- ))}- </Flex>- ) : (- <Flex direction="column" gap="1">- {repositories.map((repo) => (- <Text key={repo} className="text-[13px]">- {repo}- </Text>- ))}- </Flex>- )- }- side="bottom"- >- <Flex align="center" gap="1" className="cursor-help">- <Text className="text-(--gray-11) text-[13px]">- Connected and active ({repositories.length}{" "}- {repositories.length === 1 ? "repo" : "repos"})- </Text>- <InfoIcon size={13} className="shrink-0 text-(--gray-9)" />- </Flex>- </Tooltip>- ) : (+ const summaries = githubIntegrations.map((integration) => {+ const installationId = String(integration.config?.installation_id ?? "");+ const accountLabel = formatGithubAccountLabel(+ integration.config?.account,+ installationId,+ );+ const repos = repositories.filter(+ (repo) => getIntegrationIdForRepo(repo) === integration.id,+ );+ const selection = integration.config?.repository_selection ?? null;+ return {+ id: integration.id,+ accountLabel,+ repos,+ summary: describeGithubRepoAccess({+ selection,+ total: selection === "all" && !isLoadingRepos ? repos.length : null,+ repos,+ accountLabel,+ }),+ unavailable: integration.installation_status === "unavailable",+ };+ });++ // A row GitHub has removed still counts toward hasGithubIntegration, but it can't grant code+ // access — so the connected tick needs a genuinely available installation, not just any row.+ const hasConnectedIntegration = summaries.some((entry) => !entry.unavailable);++ const statusLine = hasGithubIntegration ? (+ <div className="flex flex-col gap-0.5">+ {summaries.map((entry) => (+ <Tooltip+ key={entry.id}+ content={+ entry.repos.length > 0 ? (+ <div className="flex max-h-64 flex-col gap-0.5 overflow-y-auto">+ {entry.repos.map((repo) => (+ <Text key={repo} size="xs">+ {repo}+ </Text>+ ))}+ </div>+ ) : (+ entry.summary.label+ )+ }+ side="bottom"+ >+ <span className="flex cursor-help items-center gap-1"><Text+ size="xs"className={- hasConnectError- ? "text-(--red-11) text-[13px]"- : "text-(--gray-11) text-[13px]"+ entry.unavailable ? "text-(--red-11)" : "text-(--gray-11)"}>- {hasGithubIntegration- ? "Connected and active"- : hasConnectError- ? describeGithubConnectError(connectError)- : timedOut- ? GITHUB_CONNECT_TIMEOUT_MESSAGE- : "Required for the Inbox pipeline to work"}+ {entry.unavailable+ ? `Removed from ${entry.accountLabel} on GitHub`+ : `${entry.accountLabel}: ${isLoadingRepos ? "loading repositories…" : entry.summary.label}`}+ </Text>+ </span>+ </Tooltip>+ ))}+ </div>+ ) : (+ <Text+ size="xs"+ className={hasConnectError ? "text-(--red-11)" : "text-(--gray-11)"}+ >+ {hasConnectError+ ? describeGithubConnectError(connectError)+ : timedOut+ ? GITHUB_CONNECT_TIMEOUT_MESSAGE+ : "Required for the Inbox pipeline to work"}+ </Text>+ );++ const showAdminHandoff =+ !hasGithubIntegration && !awaitingApproval && isAdmin === false;++ return (+ <div className={`flex flex-col gap-3 ${borderClass}`}>+ <div className="flex items-center justify-between gap-4">+ <div className="flex min-w-0 items-center gap-3">+ <div className="shrink-0 text-(--gray-11)">+ <GitBranchIcon size={20} />+ </div>+ <div className="flex min-w-0 flex-col">+ <Text size="sm" weight="medium">+ Project-level code access</Text>- )}- </Flex>- </Flex>- {connecting ? (- <Spinner size="2" />- ) : (- <Flex align="center" gap="2">- {hasGithubIntegration ? (- <CheckCircleIcon- size={16}- weight="fill"- className="text-(--green-9)"- />- ) : null}- <Button- type="button"- variant="outline"- size="sm"- onClick={() => void handleConnect()}- >- {hasGithubIntegration- ? "Update in GitHub"- : hasConnectError || timedOut- ? "Try again"- : "Connect GitHub"}- <ArrowSquareOutIcon size={12} />- </Button>- </Flex>- )}- </Flex>+ {statusLine}+ </div>+ </div>+ {connecting ? (+ <Spinner />+ ) : (+ <div className="flex shrink-0 items-center gap-2">+ {hasConnectedIntegration ? (+ <CheckCircleIcon+ size={16}+ weight="fill"+ className="text-(--green-9)"+ />+ ) : null}+ {hasGithubIntegration ? (+ <Button+ type="button"+ variant="outline"+ size="sm"+ onClick={() => openSettings("github")}+ >+ Manage+ </Button>+ ) : showAdminHandoff || awaitingApproval ? null : (+ <Button+ type="button"+ variant="outline"+ size="sm"+ disabled={isAdmin === null}+ onClick={() => void handleConnect()}+ >+ {hasConnectError || timedOut ? "Try again" : "Connect GitHub"}+ <ArrowSquareOutIcon size={12} />+ </Button>+ )}+ </div>+ )}+ </div>+ {projectId != null ? (+ <GithubInstallRequestsBanner+ onFinishConnecting={() => void handleConnect()}+ isConnecting={connecting}+ />+ ) : null}+ {showAdminHandoff && projectId != null ? (+ <RequestIntegrationAccessForm+ projectId={projectId}+ kind="github"+ integrationName="GitHub"+ />+ ) : null}+ </div>);}diff --git a/products/desktop/packages/ui/src/features/settings/sections/GitHubSettings.tsx b/products/desktop/packages/ui/src/features/settings/sections/GitHubSettings.tsxindex d4e4e55ba664..6008fd61a0f6 100644--- a/products/desktop/packages/ui/src/features/settings/sections/GitHubSettings.tsx+++ b/products/desktop/packages/ui/src/features/settings/sections/GitHubSettings.tsx@@ -1,349 +1,49 @@-import {- ArrowSquareOutIcon,- CaretDownIcon,- CaretRightIcon,- GearSixIcon,- GitBranchIcon,- GithubLogoIcon,- WarningIcon,-} from "@phosphor-icons/react";-import type { UserGitHubIntegration } from "@posthog/api-client/posthog-client";-import { deriveGithubApprovalState } from "@posthog/core/onboarding/githubConnectPanel";-import { githubInstallationSettingsUrl } from "@posthog/core/settings/githubRepoSummary";-import { formatRelativeTimeLong } from "@posthog/shared";-import { useOptionalAuthenticatedClient } from "@posthog/ui/features/auth/authClient";+import { ArrowSquareOutIcon } from "@phosphor-icons/react";+import { Button } from "@posthog/quill";import { useAuthStateValue } from "@posthog/ui/features/auth/store";-import { GithubApprovalNotice } from "@posthog/ui/features/integrations/GithubApprovalNotice";-import {- describeGithubConnectError,- invalidateGithubQueries,- useGithubUserConnect,-} from "@posthog/ui/features/integrations/useGithubUserConnect";-import {- useGithubInstallRequests,- useUserGithubIntegrations,- useUserRepositoryIntegration,-} from "@posthog/ui/features/integrations/useIntegrations";-import { toast } from "@posthog/ui/primitives/toast";+import { PersonalGithubInstallationsSection } from "@posthog/ui/features/settings/sections/PersonalGithubInstallationsSection";+import { ProjectGithubConnectionSection } from "@posthog/ui/features/settings/sections/ProjectGithubConnectionSection";import { openUrlInBrowser } from "@posthog/ui/utils/browser";-import {- AlertDialog,- Box,- Button,- Flex,- IconButton,- Spinner,- Text,- Tooltip,-} from "@radix-ui/themes";-import { useMutation, useQueryClient } from "@tanstack/react-query";-import { useState } from "react";+import { getPostHogUrl } from "@posthog/ui/utils/urls";-const REPO_PREVIEW_COUNT = 3;+const GITHUB_DOCS_URL = "https://posthog.com/docs/libraries/github";export function GitHubSettings() {const projectId = useAuthStateValue((s) => s.currentProjectId);const cloudRegion = useAuthStateValue((s) => s.cloudRegion);- const { data: integrations = [], isLoading } = useUserGithubIntegrations();- const { reposByInstallationId, failedInstallationIds, isLoadingRepos } =- useUserRepositoryIntegration();- const {- error,- isConnecting,- hasError: hasConnectError,- connect,- reset,- } = useGithubUserConnect({ projectId });- const canConnect = projectId != null && cloudRegion != null && !isConnecting;-- const { data: installRequests = [] } = useGithubInstallRequests();- const approvalState = deriveGithubApprovalState({- errorCode: error?.code,- requests: installRequests,- hasIntegration: integrations.length > 0,- });-- const handleConnect = () => {- if (hasConnectError) reset();- void connect();- };-- const connectButtonLabel =- integrations.length === 0 ? "Connect GitHub" : "Connect another account";+ const githubSettingsUrl = projectId+ ? getPostHogUrl(+ `/project/${projectId}/settings/project-integrations#integration-github`,+ cloudRegion,+ )+ : null;return (- <Flex direction="column" gap="3">- <Flex align="center" justify="between" gap="3" wrap="wrap">- <Text className="text-(--gray-11) text-[13px]">- Personal GitHub installations linked to your PostHog account.- </Text>- <Button- size="1"- disabled={!canConnect}- onClick={handleConnect}- className="shrink-0"- >- {isConnecting ? (- <Spinner size="1" />- ) : (- <ArrowSquareOutIcon size={12} />- )}- {isConnecting ? "Waiting…" : connectButtonLabel}- </Button>- </Flex>-- {approvalState !== "none" ? (- <GithubApprovalNotice state={approvalState} />- ) : hasConnectError ? (- <Text className="text-(--red-11) text-[13px]">- {describeGithubConnectError(error)}- </Text>- ) : null}-- <Flex direction="column" className="border-(--gray-5) border-t">- {isLoading ? (- <Flex align="center" gap="2" py="4">- <Spinner size="1" />- <Text className="text-(--gray-11) text-[13px]">Loading…</Text>- </Flex>- ) : integrations.length === 0 ? (- <Flex align="center" gap="3" py="4">- <Box className="shrink-0 text-(--gray-11)">- <GithubLogoIcon size={20} />- </Box>- <Text className="text-(--gray-11) text-[13px]">- No GitHub integrations yet. Connect one to enable cloud tasks.- </Text>- </Flex>- ) : (- integrations.map((integration) => (- <GitHubIntegrationRow- key={integration.installation_id}- integration={integration}- repos={reposByInstallationId[integration.installation_id] ?? []}- hasRepoFetchFailed={failedInstallationIds.includes(- integration.installation_id,- )}- isLoadingRepos={isLoadingRepos}- />- ))- )}- </Flex>- </Flex>- );-}--interface GitHubIntegrationRowProps {- integration: UserGitHubIntegration;- repos: string[];- hasRepoFetchFailed: boolean;- isLoadingRepos: boolean;-}--function GitHubIntegrationRow({- integration,- repos,- hasRepoFetchFailed,- isLoadingRepos,-}: GitHubIntegrationRowProps) {- const apiClient = useOptionalAuthenticatedClient();- const projectId = useAuthStateValue((s) => s.currentProjectId);- const queryClient = useQueryClient();- const [confirmOpen, setConfirmOpen] = useState(false);- const [expanded, setExpanded] = useState(false);-- const disconnect = useMutation({- mutationFn: async () => {- if (!apiClient) throw new Error("Not authenticated");- await apiClient.disconnectGithubUserIntegration(- integration.installation_id,- );- },- onSuccess: () => {- setConfirmOpen(false);- toast.success("Disconnected GitHub account");- invalidateGithubQueries(queryClient, projectId);- },- onError: (err) => {- toast.error(- err instanceof Error ? err.message : "Failed to disconnect GitHub",- );- },- });-- const rawAccountName = integration.account?.name;- const accountName =- (typeof rawAccountName === "string" && rawAccountName.trim()) ||- "GitHub account";- const repoCount = repos.length;- const canExpand = repoCount > 0;- const settingsUrl = githubInstallationSettingsUrl(integration);-- const repoPreview = repos.slice(0, REPO_PREVIEW_COUNT).join(", ");- const repoRemainder = repoCount - REPO_PREVIEW_COUNT;-- const repoSummaryNode = isLoadingRepos ? (- <Text className="text-(--gray-11) text-[13px]">Loading repositories…</Text>- ) : hasRepoFetchFailed ? (- <Flex align="center" gap="1">- <WarningIcon- size={13}- weight="fill"- className="shrink-0 text-(--amber-9)"- />- <Text className="text-(--amber-11) text-[13px]">- Couldn't load repositories- </Text>- </Flex>- ) : repoCount === 0 ? (- <Text className="text-(--gray-11) text-[13px]">- No repositories accessible- </Text>- ) : (- <Text className="text-(--gray-11) text-[13px]" truncate>- {repoCount} {repoCount === 1 ? "repository" : "repositories"} accessible:{" "}- <Text className="text-(--gray-12)">{repoPreview}</Text>- {repoRemainder > 0 ? ` and ${repoRemainder} more` : ""}- </Text>- );-- return (- <>- <Flex- direction="column"- gap="2"- py="3"- className="border-(--gray-5) border-b"- >- <Flex align="start" justify="between" gap="4">- <Flex align="start" gap="3" className="min-w-0 flex-1">- <Box className="shrink-0 text-(--gray-11)">- <GithubLogoIcon size={28} />- </Box>- <Flex direction="column" gap="1" className="min-w-0">- <Text className="text-(--gray-12) text-sm">- <Text className="font-medium">Connected</Text> to{" "}- <button- type="button"- onClick={() => void openUrlInBrowser(settingsUrl)}- className="cursor-pointer font-medium underline hover:text-(--accent-11)"- >- {accountName}- </button>- </Text>- {integration.created_at && (- <Text className="text-(--gray-11) text-[13px]">- Created {formatRelativeTimeLong(integration.created_at)}- </Text>- )}- <Flex align="center" gap="2" className="min-w-0">- <Flex align="center" gap="1" className="min-w-0 flex-1">- <GitBranchIcon- size={13}- className="shrink-0 text-(--gray-10)"- />- {canExpand ? (- <button- type="button"- onClick={() => setExpanded((v) => !v)}- className="-mx-1 flex min-w-0 cursor-pointer items-center gap-1 rounded px-1 text-left transition-colors hover:bg-(--gray-3)"- >- {expanded ? (- <CaretDownIcon- size={11}- className="shrink-0 text-(--gray-10)"- />- ) : (- <CaretRightIcon- size={11}- className="shrink-0 text-(--gray-10)"- />- )}- {repoSummaryNode}- </button>- ) : (- repoSummaryNode- )}- </Flex>- <Tooltip content="Manage on GitHub">- <IconButton- size="1"- variant="soft"- color="gray"- onClick={() => void openUrlInBrowser(settingsUrl)}- className="shrink-0"- >- <GearSixIcon size={12} />- </IconButton>- </Tooltip>- </Flex>- </Flex>- </Flex>+ <div className="flex flex-col gap-7">+ <ProjectGithubConnectionSection />+ <PersonalGithubInstallationsSection />+ <div className="flex flex-wrap items-center gap-3">+ {githubSettingsUrl ? (<Button- size="1"- variant="soft"- color="red"- disabled={disconnect.isPending}- onClick={() => setConfirmOpen(true)}- className="shrink-0"+ type="button"+ variant="outline"+ size="sm"+ onClick={() => void openUrlInBrowser(githubSettingsUrl)}>- {disconnect.isPending ? <Spinner size="1" /> : null}- Disconnect+ <ArrowSquareOutIcon size={12} />+ Advanced settings in PostHog</Button>- </Flex>- {expanded && canExpand && (- <div className="ml-9 max-h-48 overflow-y-auto rounded-(--radius-2) border border-(--gray-5) bg-(--gray-2)">- <Flex direction="column" py="1">- {repos.map((repo) => (- <Text- key={repo}- className="px-2 py-0.5 text-(--gray-11) text-[13px]"- truncate- >- {repo}- </Text>- ))}- </Flex>- </div>- )}- </Flex>-- <AlertDialog.Root- open={confirmOpen}- onOpenChange={(open) => {- if (!disconnect.isPending) setConfirmOpen(open);- }}- >- <AlertDialog.Content maxWidth="420px" size="1">- <AlertDialog.Title className="text-sm">- Disconnect {accountName}?- </AlertDialog.Title>- <AlertDialog.Description>- <Text color="gray" className="text-[13px]">- You won't be able to create cloud tasks against repos in this- installation until you reconnect.- </Text>- </AlertDialog.Description>- <Flex justify="end" gap="3" mt="3">- <AlertDialog.Cancel>- <Button variant="soft" color="gray" size="1">- Cancel- </Button>- </AlertDialog.Cancel>- <Button- variant="solid"- color="red"- size="1"- disabled={disconnect.isPending}- onClick={() => disconnect.mutate()}- >- {disconnect.isPending ? <Spinner size="1" /> : null}- Disconnect- </Button>- </Flex>- </AlertDialog.Content>- </AlertDialog.Root>- </>+ ) : null}+ <button+ type="button"+ onClick={() => void openUrlInBrowser(GITHUB_DOCS_URL)}+ className="ml-auto inline-flex cursor-pointer items-center gap-1 border-0 bg-transparent p-0 text-gray-10 text-xs no-underline hover:text-gray-12"+ >+ Learn about the GitHub integration+ <ArrowSquareOutIcon size={11} />+ </button>+ </div>+ </div>);}diff --git a/products/desktop/packages/ui/src/features/settings/sections/PersonalGithubInstallationsSection.tsx b/products/desktop/packages/ui/src/features/settings/sections/PersonalGithubInstallationsSection.tsxnew file mode 100644index 000000000000..05c87d287ecb--- /dev/null+++ b/products/desktop/packages/ui/src/features/settings/sections/PersonalGithubInstallationsSection.tsx@@ -0,0 +1,240 @@+import { ArrowSquareOutIcon, GithubLogoIcon } from "@phosphor-icons/react";+import type { UserGitHubIntegration } from "@posthog/api-client/posthog-client";+import { isAlreadyDisconnectedError } from "@posthog/core/integrations/connectErrors";+import { buildGithubDisconnectDescription } from "@posthog/core/integrations/disconnectCopy";+import {+ describeGithubRepoAccess,+ formatGithubAccountLabel,+ githubInstallationSettingsUrl,+} from "@posthog/core/settings/githubRepoSummary";+import { Button, Spinner, Text } from "@posthog/quill";+import { formatRelativeTimeLong } from "@posthog/shared";+import { useOptionalAuthenticatedClient } from "@posthog/ui/features/auth/authClient";+import { useAuthStateValue } from "@posthog/ui/features/auth/store";+import { DisconnectIntegrationDialog } from "@posthog/ui/features/integrations/components/DisconnectIntegrationDialog";+import { GithubRepoSummary } from "@posthog/ui/features/integrations/components/GithubRepoSummary";+import {+ describeGithubConnectError,+ invalidateGithubQueries,+ useGithubUserConnect,+} from "@posthog/ui/features/integrations/useGithubUserConnect";+import {+ useUserGithubIntegrations,+ useUserRepositoryIntegration,+} from "@posthog/ui/features/integrations/useIntegrations";+import {+ SettingsCard,+ SettingsSection,+} from "@posthog/ui/features/settings/components/SettingsCard";+import { toast } from "@posthog/ui/primitives/toast";+import { openUrlInBrowser } from "@posthog/ui/utils/browser";+import { useMutation, useQueryClient } from "@tanstack/react-query";+import { useState } from "react";++const SETTINGS_REFETCH_INTERVAL_MS = 30_000;++/**+ * The user's own GitHub App installations. Agents use these to act as the user (commits,+ * pull requests, review comments), independent of which project is open.+ */+export function PersonalGithubInstallationsSection() {+ const projectId = useAuthStateValue((s) => s.currentProjectId);+ const cloudRegion = useAuthStateValue((s) => s.cloudRegion);+ const { data: integrations = [], isLoading } = useUserGithubIntegrations({+ refetchInterval: SETTINGS_REFETCH_INTERVAL_MS,+ });+ const { reposByInstallationId, failedInstallationIds, isLoadingRepos } =+ useUserRepositoryIntegration();+ const {+ error,+ isConnecting,+ hasError: hasConnectError,+ connect,+ reset,+ } = useGithubUserConnect({ projectId });+ const canConnect = projectId != null && cloudRegion != null && !isConnecting;++ const handleConnect = () => {+ if (hasConnectError) reset();+ void connect();+ };++ return (+ <SettingsSection+ label="Your GitHub account"+ description="Personal GitHub installations linked to your PostHog account. Agents use these to act as you."+ action={+ <Button+ type="button"+ variant="outline"+ size="sm"+ disabled={!canConnect}+ onClick={handleConnect}+ >+ {isConnecting ? <Spinner /> : <ArrowSquareOutIcon size={12} />}+ {isConnecting+ ? "Waiting…"+ : integrations.length === 0+ ? "Connect GitHub"+ : "Connect another account"}+ </Button>+ }+ >+ {hasConnectError ? (+ <Text size="xs" className="text-(--red-11)">+ {describeGithubConnectError(error)}+ </Text>+ ) : null}++ <SettingsCard>+ {isLoading ? (+ <div className="flex items-center gap-2 px-3.5 py-3">+ <Spinner />+ <Text size="xs" variant="muted">+ Loading…+ </Text>+ </div>+ ) : integrations.length === 0 ? (+ <div className="flex items-center gap-3 px-3.5 py-3">+ <div className="shrink-0 text-(--gray-11)">+ <GithubLogoIcon size={20} />+ </div>+ <div className="flex flex-col gap-0.5">+ <span className="font-medium text-[13px] text-gray-12 leading-5">+ No GitHub account linked yet+ </span>+ <span className="text-[12px] text-gray-10 leading-snug">+ Connect one so agents can open pull requests as you.+ </span>+ </div>+ </div>+ ) : (+ integrations.map((integration) => (+ <PersonalGithubInstallationRow+ key={integration.installation_id}+ integration={integration}+ repos={reposByInstallationId[integration.installation_id] ?? []}+ hasRepoFetchFailed={failedInstallationIds.includes(+ integration.installation_id,+ )}+ isLoadingRepos={isLoadingRepos}+ projectId={projectId}+ />+ ))+ )}+ </SettingsCard>+ </SettingsSection>+ );+}++interface PersonalGithubInstallationRowProps {+ integration: UserGitHubIntegration;+ repos: string[];+ hasRepoFetchFailed: boolean;+ isLoadingRepos: boolean;+ projectId: number | null;+}++function PersonalGithubInstallationRow({+ integration,+ repos,+ hasRepoFetchFailed,+ isLoadingRepos,+ projectId,+}: PersonalGithubInstallationRowProps) {+ const client = useOptionalAuthenticatedClient();+ const queryClient = useQueryClient();+ const [confirmOpen, setConfirmOpen] = useState(false);++ const accountLabel = formatGithubAccountLabel(+ integration.account,+ integration.installation_id,+ );+ const selection = integration.repository_selection ?? null;+ const summary = describeGithubRepoAccess({+ selection,+ total: selection === "all" && !isLoadingRepos ? repos.length : null,+ repos,+ accountLabel,+ });+ const status =+ integration.installation_status === "unavailable"+ ? "unavailable"+ : "connected";+ const settingsUrl = githubInstallationSettingsUrl(integration);++ const disconnect = useMutation({+ mutationFn: async () => {+ if (!client) throw new Error("Not authenticated");+ await client.disconnectGithubUserIntegration(integration.installation_id);+ },+ onSuccess: () => {+ setConfirmOpen(false);+ toast.success("Disconnected GitHub account");+ invalidateGithubQueries(queryClient, projectId);+ },+ onError: (err) => {+ if (isAlreadyDisconnectedError(err)) {+ setConfirmOpen(false);+ toast.info("Already disconnected.");+ invalidateGithubQueries(queryClient, projectId);+ return;+ }+ toast.error(+ err instanceof Error ? err.message : "Failed to disconnect GitHub",+ );+ },+ });++ return (+ <>+ <GithubRepoSummary+ accountLabel={accountLabel}+ summary={summary}+ repos={repos}+ status={status}+ isLoadingRepos={isLoadingRepos}+ hasRepoFetchFailed={hasRepoFetchFailed}+ meta={+ integration.created_at+ ? `Connected ${formatRelativeTimeLong(integration.created_at)}`+ : "Connected"+ }+ onManage={() => void openUrlInBrowser(settingsUrl)}+ actions={+ <Button+ type="button"+ variant="outline"+ size="sm"+ className="text-(--red-11)"+ disabled={disconnect.isPending}+ onClick={() => setConfirmOpen(true)}+ >+ {status === "unavailable" ? "Remove" : "Disconnect"}+ </Button>+ }+ />+ <DisconnectIntegrationDialog+ open={confirmOpen}+ title={+ status === "unavailable"+ ? `Remove ${accountLabel}?`+ : `Disconnect ${accountLabel}?`+ }+ description={+ status === "unavailable"+ ? "The PostHog app is no longer installed on GitHub, so this only removes the stale link from your account."+ : buildGithubDisconnectDescription(+ accountLabel,+ integration.installation_shared === true,+ "account",+ )+ }+ confirmLabel={status === "unavailable" ? "Remove" : "Disconnect"}+ isPending={disconnect.isPending}+ onConfirm={() => disconnect.mutate()}+ onCancel={() => setConfirmOpen(false)}+ />+ </>+ );+}diff --git a/products/desktop/packages/ui/src/features/settings/sections/ProjectGithubConnectionSection.tsx b/products/desktop/packages/ui/src/features/settings/sections/ProjectGithubConnectionSection.tsxnew file mode 100644index 000000000000..084513254027--- /dev/null+++ b/products/desktop/packages/ui/src/features/settings/sections/ProjectGithubConnectionSection.tsx@@ -0,0 +1,279 @@+import { ArrowSquareOutIcon } from "@phosphor-icons/react";+import {+ describeIntegrationDisconnectError,+ GITHUB_CONNECT_TIMEOUT_MESSAGE,+ isAlreadyDisconnectedError,+} from "@posthog/core/integrations/connectErrors";+import { buildGithubDisconnectDescription } from "@posthog/core/integrations/disconnectCopy";+import type { Integration } from "@posthog/core/integrations/selectors";+import {+ describeGithubRepoAccess,+ formatGithubAccountLabel,+ githubInstallationSettingsUrl,+} from "@posthog/core/settings/githubRepoSummary";+import { Button, Spinner, Text } from "@posthog/quill";+import { formatRelativeTimeLong } from "@posthog/shared";+import { useOptionalAuthenticatedClient } from "@posthog/ui/features/auth/authClient";+import { useAuthStateValue } from "@posthog/ui/features/auth/store";+import { useIsOrgAdmin } from "@posthog/ui/features/auth/useOrgRole";+import { DisconnectIntegrationDialog } from "@posthog/ui/features/integrations/components/DisconnectIntegrationDialog";+import { GithubInstallRequestsBanner } from "@posthog/ui/features/integrations/components/GithubInstallRequestsBanner";+import { GithubRepoSummary } from "@posthog/ui/features/integrations/components/GithubRepoSummary";+import { RequestIntegrationAccessForm } from "@posthog/ui/features/integrations/components/RequestIntegrationAccessForm";+import { useIntegrationSelectors } from "@posthog/ui/features/integrations/store";+import {+ describeGithubConnectError,+ invalidateGithubQueries,+ useGithubConnect,+} from "@posthog/ui/features/integrations/useGithubUserConnect";+import {+ useIntegrations,+ useRepositoryIntegration,+} from "@posthog/ui/features/integrations/useIntegrations";+import {+ SettingsCard,+ SettingsCardRow,+ SettingsSection,+} from "@posthog/ui/features/settings/components/SettingsCard";+import { toast } from "@posthog/ui/primitives/toast";+import { openUrlInBrowser } from "@posthog/ui/utils/browser";+import { useMutation, useQueryClient } from "@tanstack/react-query";+import { useState } from "react";++const SETTINGS_REFETCH_INTERVAL_MS = 30_000;++/**+ * The project's GitHub App connection: what Self-driving and cloud tasks run against. Mirrors+ * the web project settings so both surfaces describe the same installation the same way.+ */+export function ProjectGithubConnectionSection() {+ const projectId = useAuthStateValue((s) => s.currentProjectId);+ const { isLoading } = useIntegrations({+ refetchInterval: SETTINGS_REFETCH_INTERVAL_MS,+ });+ const { githubIntegrations, hasGithubIntegration } =+ useIntegrationSelectors();+ const { isAdmin } = useIsOrgAdmin();+ const {+ error: connectError,+ isConnecting,+ isTimedOut,+ hasError: hasConnectError,+ isPending: isAwaitingApproval,+ connect,+ } = useGithubConnect({+ projectId,+ projectHasTeamIntegration: hasGithubIntegration,+ });++ return (+ <SettingsSection+ label="Project connection"+ description="GitHub access for this project's Self-driving pipeline and cloud tasks."+ >+ {projectId != null ? (+ <GithubInstallRequestsBanner+ onFinishConnecting={() => void connect()}+ isConnecting={isConnecting}+ />+ ) : null}++ {hasConnectError ? (+ <Text size="xs" className="text-(--red-11)">+ {describeGithubConnectError(connectError)}+ </Text>+ ) : isTimedOut ? (+ <Text size="xs" variant="muted">+ {GITHUB_CONNECT_TIMEOUT_MESSAGE}+ </Text>+ ) : null}++ <SettingsCard>+ {isLoading ? (+ <div className="flex items-center gap-2 px-3.5 py-3">+ <Spinner />+ <Text size="xs" variant="muted">+ Loading…+ </Text>+ </div>+ ) : hasGithubIntegration ? (+ githubIntegrations.map((integration) => (+ <ProjectGithubIntegrationRow+ key={integration.id}+ integration={integration}+ projectId={projectId}+ canDisconnect={isAdmin === true}+ />+ ))+ ) : isAwaitingApproval ? (+ <SettingsCardRow+ label="No GitHub connection yet"+ description="A GitHub organization owner still needs to approve the PostHog app."+ />+ ) : isAdmin === false && projectId != null ? (+ <div className="px-3.5 py-3">+ <RequestIntegrationAccessForm+ projectId={projectId}+ kind="github"+ integrationName="GitHub"+ />+ </div>+ ) : (+ <SettingsCardRow+ label="No GitHub connection yet"+ description="Connect GitHub so Self-driving and cloud tasks can work with your repositories."+ >+ <Button+ type="button"+ variant="primary"+ size="sm"+ disabled={projectId == null || isAdmin === null || isConnecting}+ onClick={() => void connect()}+ >+ {isConnecting ? <Spinner /> : <ArrowSquareOutIcon size={12} />}+ {isConnecting+ ? "Waiting for GitHub…"+ : hasConnectError || isTimedOut+ ? "Try again"+ : "Connect GitHub"}+ </Button>+ </SettingsCardRow>+ )}+ </SettingsCard>+ </SettingsSection>+ );+}++interface ProjectGithubIntegrationRowProps {+ integration: Integration;+ projectId: number | null;+ canDisconnect: boolean;+}++function ProjectGithubIntegrationRow({+ integration,+ projectId,+ canDisconnect,+}: ProjectGithubIntegrationRowProps) {+ const client = useOptionalAuthenticatedClient();+ const queryClient = useQueryClient();+ const [confirmOpen, setConfirmOpen] = useState(false);+ const {+ repositories,+ getIntegrationIdForRepo,+ isLoadingRepos,+ failedIntegrationIds,+ } = useRepositoryIntegration();++ const hasRepoFetchFailed = failedIntegrationIds.includes(integration.id);++ const installationId =+ integration.config?.installation_id ?? integration.integration_id ?? "";+ const accountLabel = formatGithubAccountLabel(+ integration.config?.account,+ String(installationId),+ );+ const repos = repositories.filter(+ (repo) => getIntegrationIdForRepo(repo) === integration.id,+ );+ const selection = integration.config?.repository_selection ?? null;+ const summary = describeGithubRepoAccess({+ selection,+ total: selection === "all" && !isLoadingRepos ? repos.length : null,+ repos,+ accountLabel,+ });+ const status =+ integration.installation_status === "unavailable"+ ? "unavailable"+ : "connected";+ const settingsUrl = installationId+ ? githubInstallationSettingsUrl({+ installation_id: String(installationId),+ account: integration.config?.account,+ })+ : null;++ const disconnect = useMutation({+ mutationFn: async () => {+ if (!client) throw new Error("Not authenticated");+ if (projectId == null) throw new Error("No project selected");+ await client.deleteIntegration(projectId, integration.id);+ },+ onSuccess: () => {+ setConfirmOpen(false);+ toast.success("GitHub disconnected from this project.");+ invalidateGithubQueries(queryClient, projectId);+ },+ onError: (error) => {+ if (isAlreadyDisconnectedError(error)) {+ setConfirmOpen(false);+ toast.info("Already disconnected.");+ invalidateGithubQueries(queryClient, projectId);+ return;+ }+ toast.error(+ describeIntegrationDisconnectError(+ error,+ "Failed to disconnect GitHub.",+ ),+ );+ },+ });++ return (+ <>+ <GithubRepoSummary+ accountLabel={accountLabel}+ summary={summary}+ repos={repos}+ status={status}+ isLoadingRepos={isLoadingRepos}+ hasRepoFetchFailed={hasRepoFetchFailed}+ meta={+ typeof integration.created_at === "string"+ ? `Connected ${formatRelativeTimeLong(integration.created_at)}`+ : undefined+ }+ onManage={+ settingsUrl ? () => void openUrlInBrowser(settingsUrl) : undefined+ }+ actions={+ canDisconnect ? (+ <Button+ type="button"+ variant="outline"+ size="sm"+ className="text-(--red-11)"+ disabled={disconnect.isPending}+ onClick={() => setConfirmOpen(true)}+ >+ {status === "unavailable" ? "Remove" : "Disconnect"}+ </Button>+ ) : null+ }+ />+ <DisconnectIntegrationDialog+ open={confirmOpen}+ title={+ status === "unavailable"+ ? `Remove ${accountLabel} from this project?`+ : `Disconnect GitHub from ${accountLabel}?`+ }+ description={+ status === "unavailable"+ ? "The PostHog app is no longer installed on GitHub, so this only removes the stale connection from PostHog."+ : buildGithubDisconnectDescription(+ accountLabel,+ integration.installation_shared === true,+ "project",+ )+ }+ confirmLabel={status === "unavailable" ? "Remove" : "Disconnect"}+ isPending={disconnect.isPending}+ onConfirm={() => disconnect.mutate()}+ onCancel={() => setConfirmOpen(false)}+ />+ </>+ );+}diff --git a/products/desktop/packages/ui/src/features/settings/sections/SignalDefaultChannelSettings.tsx b/products/desktop/packages/ui/src/features/settings/sections/SignalDefaultChannelSettings.tsxindex cf3efd418836..27961158a465 100644--- a/products/desktop/packages/ui/src/features/settings/sections/SignalDefaultChannelSettings.tsx+++ b/products/desktop/packages/ui/src/features/settings/sections/SignalDefaultChannelSettings.tsx@@ -1,8 +1,8 @@import { useIsOrgAdmin } from "@posthog/ui/features/auth/useOrgRole";import { useSignalSourceManager } from "@posthog/ui/features/inbox/hooks/useSignalSourceManager";import { useIntegrationSelectors } from "@posthog/ui/features/integrations/store";+import { SettingsCardRow } from "@posthog/ui/features/settings/components/SettingsCard";import { SlackChannelCombobox } from "@posthog/ui/features/settings/components/SlackChannelCombobox";-import { Box, Flex, Text } from "@radix-ui/themes";interface SignalDefaultChannelSettingsProps {/** Workspace whose channels are listed — shared with the per-user section. */@@ -25,50 +25,38 @@ export function SignalDefaultChannelSettings({if (isLoading) {return (- <Flex direction="column" gap="2" pt="2">- <Flex direction="column" gap="1">- <Box className="h-[14px] w-[200px] animate-pulse rounded bg-gray-4" />- <Box className="h-[11px] w-[80%] animate-pulse rounded bg-gray-3" />- </Flex>- <Box className="mt-1 h-[28px] w-[200px] animate-pulse rounded bg-gray-3" />- </Flex>+ <div className="flex min-h-11 items-center justify-between gap-6 px-3.5 py-2">+ <div className="flex min-w-0 flex-col gap-1">+ <div className="h-[13px] w-[200px] animate-pulse rounded bg-gray-4" />+ <div className="h-[11px] w-[280px] animate-pulse rounded bg-gray-3" />+ </div>+ <div className="h-[28px] w-[200px] shrink-0 animate-pulse rounded bg-gray-3" />+ </div>);}- // Connecting Slack is offered in the per-user section below; nothing to- // configure here until a workspace exists.+ // Connecting Slack is offered by the workspace section; nothing to configure+ // here until a workspace exists.if (!hasSlackIntegration) return null;return (- <Flex direction="column" gap="2" pt="2">- <Flex direction="column" gap="1">- <Text className="font-medium text-(--gray-12) text-sm">- Default notification channel- </Text>- <Text className="text-(--gray-11) text-[13px]">- Where every report is posted for the whole team. Reviewers who set- their own channel below are notified there instead.- </Text>- </Flex>-- <Flex direction="column" gap="1" className="min-w-0">- <Text className="text-(--gray-11) text-[12px]">Default Channel</Text>- <SlackChannelCombobox- integrationId={integrationId}- value={channelTarget}- onChange={(channel) => void handleUpdateTeamSlackChannel(channel)}- offLabel="No default channel"- ariaLabel="Default notification channel"- modal={channelComboboxModal}- disabled={!canEdit || !integrationId}- />- </Flex>-- {isAdmin === false ? (- <Text className="text-(--gray-10) text-[11px]">- Only organization admins can change the team's default channel.- </Text>- ) : null}- </Flex>+ <SettingsCardRow+ label="Default notification channel"+ description={+ isAdmin === false+ ? "Where every report is posted for the whole team. Only organization admins can change it."+ : "Where every report is posted for the whole team. Reviewers who set their own channel are notified there instead."+ }+ >+ <SlackChannelCombobox+ integrationId={integrationId}+ value={channelTarget}+ onChange={(channel) => void handleUpdateTeamSlackChannel(channel)}+ offLabel="No default channel"+ ariaLabel="Default notification channel"+ modal={channelComboboxModal}+ disabled={!canEdit || !integrationId}+ />+ </SettingsCardRow>);}diff --git a/products/desktop/packages/ui/src/features/settings/sections/SignalSlackNotificationsSettings.tsx b/products/desktop/packages/ui/src/features/settings/sections/SignalSlackNotificationsSettings.tsxindex 5d158703e52b..56ab3acbf462 100644--- a/products/desktop/packages/ui/src/features/settings/sections/SignalSlackNotificationsSettings.tsx+++ b/products/desktop/packages/ui/src/features/settings/sections/SignalSlackNotificationsSettings.tsx@@ -1,11 +1,9 @@-import { Button } from "@posthog/quill";import type { SignalReportPriority } from "@posthog/shared/domain-types";import { useSignalSourceManager } from "@posthog/ui/features/inbox/hooks/useSignalSourceManager";import { useIntegrationSelectors } from "@posthog/ui/features/integrations/store";-import { useSlackConnect } from "@posthog/ui/features/integrations/useSlackConnect";+import { SettingsCardRow } from "@posthog/ui/features/settings/components/SettingsCard";import { SlackChannelCombobox } from "@posthog/ui/features/settings/components/SlackChannelCombobox";import { SettingsOptionSelect } from "@posthog/ui/features/settings/SettingsOptionSelect";-import { Box, Callout, Flex, Text } from "@radix-ui/themes";const NOTIFY_ALL_VALUE = "__all__";@@ -21,33 +19,21 @@ const MIN_PRIORITY_OPTIONS: {{ value: "P4", label: "P4 and above" },];-const SETTINGS_CONTROL_CLASS = "min-w-[200px] max-w-[240px]";-interface SignalSlackNotificationsSettingsProps {/** Workspace whose channels are listed — shared with the team default. */integrationId: number | null;channelComboboxModal?: boolean;isLoading?: boolean;- /** When false, omit the dashed top rule (e.g. inside a parent `divide-y` list). */- showTopBorder?: boolean;- /** When true, omit the connect-workspace prompt (shown by a parent section). */- hideWorkspaceConnect?: boolean;}export function SignalSlackNotificationsSettings({integrationId,channelComboboxModal = false,isLoading = false,- showTopBorder = true,- hideWorkspaceConnect = false,}: SignalSlackNotificationsSettingsProps) {- const topBorderClass = showTopBorder- ? "border-(--gray-5) border-t border-dashed pt-4"- : "";const { hasSlackIntegration } = useIntegrationSelectors();const { userAutonomyConfig, handleUpdateSlackNotifications } =useSignalSourceManager();- const slackConnect = useSlackConnect();const selectedChannelTarget =userAutonomyConfig?.slack_notification_channel ?? null;@@ -58,62 +44,19 @@ export function SignalSlackNotificationsSettings({if (isLoading) {return (- <Flex direction="column" gap="2" className={topBorderClass}>- <Flex direction="column" gap="1">- <Box className="h-[14px] w-[160px] animate-pulse rounded bg-gray-4" />- <Box className="h-[11px] w-[80%] animate-pulse rounded bg-gray-3" />- </Flex>- <Box className="mt-1 h-[28px] w-[200px] animate-pulse rounded bg-gray-3" />- </Flex>+ <div className="flex min-h-11 items-center justify-between gap-6 px-3.5 py-2">+ <div className="flex min-w-0 flex-col gap-1">+ <div className="h-[13px] w-[160px] animate-pulse rounded bg-gray-4" />+ <div className="h-[11px] w-[280px] animate-pulse rounded bg-gray-3" />+ </div>+ <div className="h-[28px] w-[200px] shrink-0 animate-pulse rounded bg-gray-3" />+ </div>);}- if (!hasSlackIntegration) {- if (hideWorkspaceConnect) {- return null;- }-- return (- <Flex direction="column" gap="2" className={topBorderClass}>- <Flex direction="column" gap="1">- <Text className="font-medium text-(--gray-12) text-sm">- Notify me directly- </Text>- <Text className="text-(--gray-11) text-[13px]">- Get pinged in your own channel when you're a suggested reviewer on a- new report.- </Text>- </Flex>- <Button- type="button"- variant="outline"- size="sm"- disabled={slackConnect.isConnecting}- onClick={() => {- void slackConnect.connect();- }}- className="w-fit"- >- {slackConnect.isConnecting- ? "Waiting for Slack…"- : "Connect Slack workspace"}- </Button>- {slackConnect.hasError && slackConnect.error ? (- <Callout.Root size="1" color="red" variant="soft">- <Callout.Text>{slackConnect.error.message}</Callout.Text>- </Callout.Root>- ) : null}- {slackConnect.isTimedOut ? (- <Callout.Root size="1" color="gray" variant="soft">- <Callout.Text>- We didn't hear back from PostHog. If you completed the connection- in your browser it should appear shortly, otherwise try again.- </Callout.Text>- </Callout.Root>- ) : null}- </Flex>- );- }+ // Connecting Slack is offered by the workspace section; nothing to configure+ // here until a workspace exists.+ if (!hasSlackIntegration) return null;const onChannelChange = (channel: string | null) => {if (channel === null) {@@ -131,42 +74,34 @@ export function SignalSlackNotificationsSettings({};return (- <Flex direction="column" gap="2" className={topBorderClass}>- <Flex direction="column" gap="1">- <Text className="font-medium text-(--gray-12) text-sm">- Notify me directly- </Text>- <Text className="text-(--gray-11) text-[13px]">- When you're a suggested reviewer, get pinged in your own channel- instead of the team's default channel above.- </Text>- </Flex>-- <Flex gap="2" wrap="wrap" align="end">- <Flex direction="column" gap="1" className="min-w-0">- <Text className="text-(--gray-11) text-[12px]">Channel</Text>- <SlackChannelCombobox- integrationId={integrationId}- value={selectedChannelTarget}- onChange={onChannelChange}- offLabel="Off, don't notify me"- ariaLabel="Notification channel"- modal={channelComboboxModal}- disabled={!integrationId}- />- </Flex>- <Flex direction="column" gap="1" className="min-w-0">- <Text className="text-(--gray-11) text-[12px]">Min. priority</Text>- <SettingsOptionSelect- value={minPriority ?? NOTIFY_ALL_VALUE}- options={MIN_PRIORITY_OPTIONS}- ariaLabel="Minimum priority to notify"- disabled={!notificationsEnabled}- className={SETTINGS_CONTROL_CLASS}- onValueChange={onMinPriorityChange}- />- </Flex>- </Flex>- </Flex>+ <>+ <SettingsCardRow+ label="Notify me directly"+ description="When you're a suggested reviewer, get pinged in your own channel instead of the team's default channel."+ >+ <SlackChannelCombobox+ integrationId={integrationId}+ value={selectedChannelTarget}+ onChange={onChannelChange}+ offLabel="Off, don't notify me"+ ariaLabel="Notification channel"+ modal={channelComboboxModal}+ disabled={!integrationId}+ />+ </SettingsCardRow>+ <SettingsCardRow+ label="Minimum priority"+ description="Only ping me for reports at or above this priority."+ >+ <SettingsOptionSelect+ value={minPriority ?? NOTIFY_ALL_VALUE}+ options={MIN_PRIORITY_OPTIONS}+ ariaLabel="Minimum priority to notify"+ disabled={!notificationsEnabled}+ className="min-w-[200px] max-w-[240px]"+ onValueChange={onMinPriorityChange}+ />+ </SettingsCardRow>+ </>);}diff --git a/products/desktop/packages/ui/src/features/settings/sections/SlackCommentNotificationsSettings.tsx b/products/desktop/packages/ui/src/features/settings/sections/SlackCommentNotificationsSettings.tsxindex 87ef07672c58..2bddefd32214 100644--- a/products/desktop/packages/ui/src/features/settings/sections/SlackCommentNotificationsSettings.tsx+++ b/products/desktop/packages/ui/src/features/settings/sections/SlackCommentNotificationsSettings.tsx@@ -1,6 +1,10 @@-import { Button, Switch, Text } from "@posthog/quill";+import { Button, Switch } from "@posthog/quill";import { useMeQuery } from "@posthog/ui/features/auth/useMeQuery";-import { SettingRow } from "@posthog/ui/features/settings/SettingRow";+import {+ SettingsCard,+ SettingsCardRow,+ SettingsSection,+} from "@posthog/ui/features/settings/components/SettingsCard";import { useAuthenticatedMutation } from "@posthog/ui/hooks/useAuthenticatedMutation";import { useAuthenticatedQuery } from "@posthog/ui/hooks/useAuthenticatedQuery";import { toast } from "@posthog/ui/primitives/toast";@@ -67,54 +71,48 @@ export function SlackCommentNotificationsSettings() {);return (- <div className="flex flex-col border-(--gray-5) border-t border-dashed pt-3">- <Text size="sm" weight="medium" className="mb-1 block">- Comment notifications- </Text>- <Text size="xs" variant="muted" className="mb-1 block">- Comment notifications can also reach you in Slack, so you hear about- them when PostHog Code isn't open.- </Text>+ <SettingsSection+ label="Comment notifications"+ description="Comment notifications can also reach you in Slack, so you hear about them when PostHog Code isn't open."+ >+ <SettingsCard>+ <SettingsCardRow+ label="Slack account"+ description={+ linked+ ? `Linked to ${links?.[0]?.slack_team_name ?? "Slack"}`+ : "Only needed when your Slack email differs from your PostHog email. Otherwise we find you by email."+ }+ >+ {linked ? (+ <span className="text-[12px] text-gray-10">Linked</span>+ ) : (+ <Button+ size="sm"+ variant="outline"+ loading={connecting}+ disabled={linksLoading}+ onClick={() => connect()}+ >+ Link Slack account+ </Button>+ )}+ </SettingsCardRow>- <SettingRow- label="Slack account"- description={- linked- ? `Linked to ${links?.[0]?.slack_team_name ?? "Slack"}`- : "Only needed when your Slack email differs from your PostHog email. Otherwise we find you by email."- }- >- {linked ? (- <Text size="xs" variant="muted">- Linked- </Text>- ) : (- <Button- size="xs"- loading={connecting}- disabled={linksLoading}- onClick={() => connect()}- >- Link Slack account- </Button>- )}- </SettingRow>-- <SettingRow- label="Slack DMs for comments"- description="Get a direct message when someone mentions you, replies to your comment, or comments on something you own"- noBorder- >- <div className="flex items-center gap-2">+ <SettingsCardRow+ label="Slack DMs for comments"+ description="Get a direct message when someone mentions you, replies to your comment, or comments on something you own"+ >{/* Deliberately not gated on a link: an unlinked recipient is matched to Slack byemail, so gating here would hide a path that works. */}<Switch+ size="sm"checked={enabled}onCheckedChange={(next) => mutate(next)}disabled={isLoading || isPending}/>- </div>- </SettingRow>- </div>+ </SettingsCardRow>+ </SettingsCard>+ </SettingsSection>);}diff --git a/products/desktop/packages/ui/src/features/settings/sections/SlackInboxNotificationsSettings.tsx b/products/desktop/packages/ui/src/features/settings/sections/SlackInboxNotificationsSettings.tsxindex d7e51fab51e8..9995beec6b1d 100644--- a/products/desktop/packages/ui/src/features/settings/sections/SlackInboxNotificationsSettings.tsx+++ b/products/desktop/packages/ui/src/features/settings/sections/SlackInboxNotificationsSettings.tsx@@ -5,32 +5,30 @@ import {} from "@posthog/core/settings/slackNotificationTarget";import { useSignalSourceManager } from "@posthog/ui/features/inbox/hooks/useSignalSourceManager";import { useIntegrationSelectors } from "@posthog/ui/features/integrations/store";+import {+ SettingsCard,+ SettingsCardRow,+} from "@posthog/ui/features/settings/components/SettingsCard";import { SettingsOptionSelect } from "@posthog/ui/features/settings/SettingsOptionSelect";import { SignalDefaultChannelSettings } from "@posthog/ui/features/settings/sections/SignalDefaultChannelSettings";import { SignalSlackNotificationsSettings } from "@posthog/ui/features/settings/sections/SignalSlackNotificationsSettings";-import {- SlackWorkspaceConnection,- SlackWorkspaceConnectionCallouts,-} from "@posthog/ui/features/settings/sections/SlackWorkspaceConnection";-import { Box, Flex, Text } from "@radix-ui/themes";+import { SlackWorkspaceConnectionBlock } from "@posthog/ui/features/settings/sections/SlackWorkspaceConnection";import { useMemo } from "react";-const WORKSPACE_CONTROL_CLASS = "min-w-[160px] max-w-[240px]";-interface SlackInboxNotificationsSettingsProps {channelComboboxModal?: boolean;isLoading?: boolean;/** When false, omit the section header (parent already titles this block). */showHeader?: boolean;- /** When false, omit the dashed top rule (nested under a parent section). */- showTopBorder?: boolean;+ /** When false, omit the workspace rows (a parent section renders them). */+ showWorkspaceConnection?: boolean;}export function SlackInboxNotificationsSettings({channelComboboxModal = false,isLoading = false,showHeader = true,- showTopBorder = true,+ showWorkspaceConnection = true,}: SlackInboxNotificationsSettingsProps) {const { slackIntegrations, hasSlackIntegration } = useIntegrationSelectors();const { userAutonomyConfig, handleUpdateSlackNotifications } =@@ -63,68 +61,63 @@ export function SlackInboxNotificationsSettings({void handleUpdateSlackNotifications({ integrationId, channel: null });};- const topBorderClass = showTopBorder- ? "border-(--gray-5) border-t border-dashed pt-3"- : "";+ const showConfiguration = isLoading || hasSlackIntegration;return (- <Flex direction="column" gap="3" className={topBorderClass}>+ <div className="flex flex-col gap-3">{showHeader ? (- <>- <Flex align="center" gap="2">- <Box className="shrink-0 text-(--gray-11)">+ <div className="flex flex-col gap-1">+ <div className="flex items-center gap-2">+ <span className="shrink-0 text-(--gray-11)"><SlackLogoIcon size={16} />- </Box>- <Text className="font-medium text-(--gray-12) text-sm">+ </span>+ <span className="font-medium text-(--gray-12) text-sm">Inbox notifications- </Text>- </Flex>- <Text className="text-(--gray-11) text-[13px]">+ </span>+ </div>+ <p className="m-0 text-(--gray-11) text-[13px]">New inbox reports are posted to Slack with the suggested reviewers@mentioned. PostHog must be in the channel, so invite it with{" "}<code className="text-[13px]">/invite @PostHog</code>.- </Text>- </>+ </p>+ </div>) : null}- <SlackWorkspaceConnection isLoading={isLoading} />- <SlackWorkspaceConnectionCallouts />+ {showWorkspaceConnection ? (+ <SlackWorkspaceConnectionBlock isLoading={isLoading} />+ ) : null}- {!isLoading && hasSlackIntegration ? (- <Flex align="center" gap="2" pt="2" className="min-w-0">- <Text className="shrink-0 text-(--gray-11) text-[12px]">- Workspace- </Text>- {slackIntegrations.length > 1 ? (- <SettingsOptionSelect- value={- effectiveIntegrationId ? String(effectiveIntegrationId) : ""- }- options={integrationOptions}- ariaLabel="Slack workspace"- placeholder="Select workspace"- className={WORKSPACE_CONTROL_CLASS}- onValueChange={onIntegrationChange}- />- ) : slackIntegrations[0] ? (- <Text className="truncate font-medium text-(--gray-12) text-[13px]">- {getSlackIntegrationLabel(slackIntegrations[0])}- </Text>+ {showConfiguration ? (+ <SettingsCard>+ {!isLoading && slackIntegrations.length > 1 ? (+ <SettingsCardRow+ label="Workspace"+ description="Channels below are listed from this workspace."+ >+ <SettingsOptionSelect+ value={+ effectiveIntegrationId ? String(effectiveIntegrationId) : ""+ }+ options={integrationOptions}+ ariaLabel="Slack workspace"+ placeholder="Select workspace"+ className="min-w-[160px] max-w-[240px]"+ onValueChange={onIntegrationChange}+ />+ </SettingsCardRow>) : null}- </Flex>+ <SignalDefaultChannelSettings+ integrationId={effectiveIntegrationId}+ channelComboboxModal={channelComboboxModal}+ isLoading={isLoading}+ />+ <SignalSlackNotificationsSettings+ integrationId={effectiveIntegrationId}+ channelComboboxModal={channelComboboxModal}+ isLoading={isLoading}+ />+ </SettingsCard>) : null}-- <SignalDefaultChannelSettings- integrationId={effectiveIntegrationId}- channelComboboxModal={channelComboboxModal}- isLoading={isLoading}- />- <SignalSlackNotificationsSettings- integrationId={effectiveIntegrationId}- channelComboboxModal={channelComboboxModal}- isLoading={isLoading}- hideWorkspaceConnect- />- </Flex>+ </div>);}diff --git a/products/desktop/packages/ui/src/features/settings/sections/SlackSettings.tsx b/products/desktop/packages/ui/src/features/settings/sections/SlackSettings.tsxindex 70ce2a0a4324..54052f0b51f4 100644--- a/products/desktop/packages/ui/src/features/settings/sections/SlackSettings.tsx+++ b/products/desktop/packages/ui/src/features/settings/sections/SlackSettings.tsx@@ -1,17 +1,30 @@import { ArrowSquareOutIcon } from "@phosphor-icons/react";-import { Button, Text } from "@posthog/quill";+import { Button, Spinner } from "@posthog/quill";import { useAuthStateValue } from "@posthog/ui/features/auth/store";+import { useIntegrationSelectors } from "@posthog/ui/features/integrations/store";import { useIntegrations } from "@posthog/ui/features/integrations/useIntegrations";+import { useSlackConnect } from "@posthog/ui/features/integrations/useSlackConnect";+import { SettingsSection } from "@posthog/ui/features/settings/components/SettingsCard";import { SlackCommentNotificationsSettings } from "@posthog/ui/features/settings/sections/SlackCommentNotificationsSettings";-import { Tooltip } from "@posthog/ui/primitives/Tooltip";import { openUrlInBrowser } from "@posthog/ui/utils/browser";import { getPostHogUrl } from "@posthog/ui/utils/urls";import { SlackInboxNotificationsSettings } from "./SlackInboxNotificationsSettings";+import {+ SlackWorkspaceConnection,+ SlackWorkspaceConnectionCallouts,+} from "./SlackWorkspaceConnection";++const SLACK_DOCS_URL = "https://posthog.com/docs/libraries/slack";+const SETTINGS_REFETCH_INTERVAL_MS = 30_000;export function SlackSettings() {const projectId = useAuthStateValue((s) => s.currentProjectId);const cloudRegion = useAuthStateValue((s) => s.cloudRegion);- const { isLoading } = useIntegrations();+ const { isLoading } = useIntegrations({+ refetchInterval: SETTINGS_REFETCH_INTERVAL_MS,+ });+ const { hasSlackIntegration } = useIntegrationSelectors();+ const slackConnect = useSlackConnect();const slackSettingsUrl = projectId? getPostHogUrl(@@ -20,42 +33,84 @@ export function SlackSettings() {): null;- const manageButton = (- <Button- size="xs"- disabled={!slackSettingsUrl}- onClick={() => {- if (slackSettingsUrl) void openUrlInBrowser(slackSettingsUrl);- }}- >- <ArrowSquareOutIcon size={12} />- Manage in PostHog Web- </Button>- );-- const manageButtonWithTooltip = slackSettingsUrl ? (- manageButton- ) : (- <Tooltip content="Sign in to a PostHog project to manage the Slack integration">- {manageButton}- </Tooltip>- );-return (- <div className="flex flex-col gap-3">- <Text className="text-(--gray-11) text-[13px]">- Connect Slack to PostHog to kick off tasks like pull requests directly- from Slack.- </Text>-- <div className="flex">{manageButtonWithTooltip}</div>+ <div className="flex flex-col gap-7">+ <SettingsSection+ label="Workspace connection"+ description="Connect a Slack workspace so reports can post to channels, reviewers get pinged, and you can kick off tasks from Slack."+ action={+ !isLoading && hasSlackIntegration ? (+ <Button+ type="button"+ variant="outline"+ size="sm"+ disabled={slackConnect.isConnecting}+ onClick={() => {+ void slackConnect.connect();+ }}+ >+ {slackConnect.isConnecting ? (+ <Spinner />+ ) : (+ <ArrowSquareOutIcon size={12} />+ )}+ {slackConnect.isConnecting+ ? "Waiting…"+ : "Connect another workspace"}+ </Button>+ ) : undefined+ }+ >+ <SlackWorkspaceConnection+ slackConnect={slackConnect}+ isLoading={isLoading}+ showConnectAnother={false}+ />+ <SlackWorkspaceConnectionCallouts slackConnect={slackConnect} />+ </SettingsSection>- <SlackInboxNotificationsSettings- isLoading={isLoading}- showHeader={false}- />+ {hasSlackIntegration ? (+ <SettingsSection+ label="Inbox notifications"+ description={+ <>+ New inbox reports are posted to Slack with the suggested reviewers+ @mentioned. PostHog must be in the channel, so invite it with{" "}+ <code className="text-[12px]">/invite @PostHog</code>.+ </>+ }+ >+ <SlackInboxNotificationsSettings+ isLoading={isLoading}+ showHeader={false}+ showWorkspaceConnection={false}+ />+ </SettingsSection>+ ) : null}<SlackCommentNotificationsSettings />++ <div className="flex flex-wrap items-center gap-3">+ {slackSettingsUrl ? (+ <Button+ type="button"+ variant="outline"+ size="sm"+ onClick={() => void openUrlInBrowser(slackSettingsUrl)}+ >+ <ArrowSquareOutIcon size={12} />+ Advanced settings in PostHog+ </Button>+ ) : null}+ <button+ type="button"+ onClick={() => void openUrlInBrowser(SLACK_DOCS_URL)}+ className="ml-auto inline-flex cursor-pointer items-center gap-1 border-0 bg-transparent p-0 text-gray-10 text-xs no-underline hover:text-gray-12"+ >+ Learn about the Slack integration+ <ArrowSquareOutIcon size={11} />+ </button>+ </div></div>);}diff --git a/products/desktop/packages/ui/src/features/settings/sections/SlackWorkspaceConnection.tsx b/products/desktop/packages/ui/src/features/settings/sections/SlackWorkspaceConnection.tsxindex 72bc918ffbfb..dabdf97e4c33 100644--- a/products/desktop/packages/ui/src/features/settings/sections/SlackWorkspaceConnection.tsx+++ b/products/desktop/packages/ui/src/features/settings/sections/SlackWorkspaceConnection.tsx@@ -1,66 +1,97 @@import { SlackLogoIcon } from "@phosphor-icons/react";-import { Button } from "@posthog/quill";+import {+ describeIntegrationDisconnectError,+ isAlreadyDisconnectedError,+} from "@posthog/core/integrations/connectErrors";+import { slackInvalidationKeys } from "@posthog/core/integrations/connectMachine";+import { SLACK_DISCONNECT_DESCRIPTION } from "@posthog/core/integrations/disconnectCopy";+import { Button, Spinner, Text } from "@posthog/quill";import { formatRelativeTimeLong } from "@posthog/shared";+import { useOptionalAuthenticatedClient } from "@posthog/ui/features/auth/authClient";+import { useAuthStateValue } from "@posthog/ui/features/auth/store";+import { useIsOrgAdmin } from "@posthog/ui/features/auth/useOrgRole";+import { DisconnectIntegrationDialog } from "@posthog/ui/features/integrations/components/DisconnectIntegrationDialog";import {type Integration,useIntegrationSelectors,} from "@posthog/ui/features/integrations/store";-import { useSlackConnect } from "@posthog/ui/features/integrations/useSlackConnect";-import { Box, Callout, Flex, Spinner, Text } from "@radix-ui/themes";+import {+ type SlackConnectResult,+ useSlackConnect,+} from "@posthog/ui/features/integrations/useSlackConnect";+import { toast } from "@posthog/ui/primitives/toast";+import { useMutation, useQueryClient } from "@tanstack/react-query";+import { useState } from "react";interface SlackWorkspaceConnectionProps {+ /** The page's single connect instance — see `useSlackConnect`. */+ slackConnect: SlackConnectResult;isLoading?: boolean;+ /** When false, omit the connect-another button (a parent header renders it). */+ showConnectAnother?: boolean;}export function SlackWorkspaceConnection({+ slackConnect,isLoading = false,+ showConnectAnother = true,}: SlackWorkspaceConnectionProps) {const { slackIntegrations, hasSlackIntegration } = useIntegrationSelectors();- const slackConnect = useSlackConnect();if (isLoading) {return (- <Flex align="center" gap="2" py="1">- <Spinner size="1" />- <Text className="text-(--gray-11) text-[13px]">Loading Slack…</Text>- </Flex>+ <div className="flex items-center gap-2 rounded-(--radius-3) border border-(--gray-5) bg-(--color-panel-solid) px-3.5 py-3">+ <Spinner />+ <Text size="xs" variant="muted">+ Loading Slack…+ </Text>+ </div>);}if (hasSlackIntegration) {return (- <Flex direction="column" gap="2">- {slackIntegrations.map((integration) => (- <SlackWorkspaceRow key={integration.id} integration={integration} />- ))}- </Flex>+ <div className="flex flex-col gap-2">+ <div className="divide-y divide-(--gray-4) rounded-(--radius-3) border border-(--gray-5) bg-(--color-panel-solid)">+ {slackIntegrations.map((integration) => (+ <SlackWorkspaceRow key={integration.id} integration={integration} />+ ))}+ </div>+ {showConnectAnother ? (+ <div className="flex">+ <Button+ type="button"+ variant="outline"+ size="sm"+ disabled={slackConnect.isConnecting}+ onClick={() => {+ void slackConnect.connect();+ }}+ >+ {slackConnect.isConnecting+ ? "Waiting for Slack…"+ : "Connect another workspace"}+ </Button>+ </div>+ ) : null}+ </div>);}return (- <Flex- align="center"- justify="between"- gap="4"- className="rounded-(--radius-2) border border-border bg-(--color-panel-solid) px-4 py-3.5"- >- <Flex align="center" gap="3" className="min-w-0">- <Box className="shrink-0 text-(--gray-11)">- <SlackLogoIcon size={20} />- </Box>- <Flex direction="column" gap="1" className="min-w-0">- <Text className="font-medium text-(--gray-12) text-sm">- Slack workspace- </Text>- <Text className="text-(--gray-11) text-[13px] leading-snug">- Connect a workspace so reports can post to channels and reviewers- get pinged.- </Text>- </Flex>- </Flex>+ <div className="flex min-h-11 items-center justify-between gap-6 rounded-(--radius-3) border border-(--gray-5) bg-(--color-panel-solid) px-3.5 py-2">+ <div className="flex min-w-0 flex-col gap-0.5 py-0.5">+ <span className="font-medium text-[13px] text-gray-12 leading-5">+ No Slack workspace connected yet+ </span>+ <span className="text-[12px] text-gray-10 leading-snug">+ Connect a workspace so reports can post to channels and reviewers get+ pinged.+ </span>+ </div><Buttontype="button"- variant="outline"+ variant="primary"size="sm"className="shrink-0"disabled={slackConnect.isConnecting}@@ -72,11 +103,17 @@ export function SlackWorkspaceConnection({? "Waiting for Slack…": "Connect Slack workspace"}</Button>- </Flex>+ </div>);}function SlackWorkspaceRow({ integration }: { integration: Integration }) {+ const projectId = useAuthStateValue((s) => s.currentProjectId);+ const client = useOptionalAuthenticatedClient();+ const queryClient = useQueryClient();+ const { isAdmin } = useIsOrgAdmin();+ const [confirmOpen, setConfirmOpen] = useState(false);+const rawDisplayName = integration.display_name;const workspaceName =(typeof rawDisplayName === "string" && rawDisplayName.trim()) ||@@ -84,52 +121,130 @@ function SlackWorkspaceRow({ integration }: { integration: Integration }) {const createdAt =typeof integration.created_at === "string" ? integration.created_at : null;+ const invalidate = () => {+ for (const queryKey of slackInvalidationKeys()) {+ void queryClient.invalidateQueries({ queryKey: [...queryKey] });+ }+ };++ const disconnect = useMutation({+ mutationFn: async () => {+ if (!client) throw new Error("Not authenticated");+ if (projectId == null) throw new Error("No project selected");+ await client.deleteIntegration(projectId, integration.id);+ },+ onSuccess: () => {+ setConfirmOpen(false);+ toast.success("Slack workspace disconnected.");+ invalidate();+ },+ onError: (error) => {+ if (isAlreadyDisconnectedError(error)) {+ setConfirmOpen(false);+ toast.info("Already disconnected.");+ invalidate();+ return;+ }+ toast.error(+ describeIntegrationDisconnectError(+ error,+ "Failed to disconnect Slack.",+ ),+ );+ },+ });+return (- <Flex- align="center"- gap="3"- className="rounded-(--radius-2) border border-border bg-(--color-panel-solid) px-4 py-3.5"- >- <Box className="shrink-0 text-(--gray-11)">- <SlackLogoIcon size={24} />- </Box>- <Flex direction="column" gap="0.5" className="min-w-0">- <Text className="text-(--gray-12) text-sm">- <Text className="font-medium">Connected</Text> to{" "}- <Text className="font-medium">{workspaceName}</Text>- </Text>- {createdAt ? (- <Text className="text-(--gray-11) text-[13px]">- Connected {formatRelativeTimeLong(createdAt)}- </Text>+ <>+ <div className="flex min-h-11 items-center justify-between gap-6 px-3.5 py-2.5">+ <div className="flex min-w-0 flex-1 items-center gap-3">+ <div className="shrink-0 text-(--gray-11)">+ <SlackLogoIcon size={24} />+ </div>+ <div className="flex min-w-0 flex-col gap-0.5">+ <span className="truncate font-medium text-[13px] text-gray-12 leading-5">+ {workspaceName}+ </span>+ {createdAt ? (+ <span className="truncate text-[12px] text-gray-10 leading-snug">+ Connected {formatRelativeTimeLong(createdAt)}+ </span>+ ) : null}+ </div>+ </div>+ {isAdmin === true ? (+ <Button+ type="button"+ variant="outline"+ size="sm"+ className="shrink-0 text-(--red-11)"+ disabled={disconnect.isPending}+ onClick={() => setConfirmOpen(true)}+ >+ Disconnect+ </Button>) : null}- </Flex>- </Flex>+ </div>+ <DisconnectIntegrationDialog+ open={confirmOpen}+ title={`Disconnect ${workspaceName}?`}+ description={SLACK_DISCONNECT_DESCRIPTION}+ isPending={disconnect.isPending}+ onConfirm={() => disconnect.mutate()}+ onCancel={() => setConfirmOpen(false)}+ />+ </>);}-export function SlackWorkspaceConnectionCallouts() {- const slackConnect = useSlackConnect();-+export function SlackWorkspaceConnectionCallouts({+ slackConnect,+}: {+ slackConnect: SlackConnectResult;+}) {if (!slackConnect.hasError && !slackConnect.isTimedOut) {return null;}return (- <Flex direction="column" gap="2">+ <div className="flex flex-col gap-2">{slackConnect.hasError && slackConnect.error ? (- <Callout.Root size="1" color="red" variant="soft">- <Callout.Text>{slackConnect.error.message}</Callout.Text>- </Callout.Root>+ <div className="rounded-(--radius-2) border border-(--red-6) bg-(--red-2) px-3 py-2">+ <Text size="xs" className="text-(--red-11)">+ {slackConnect.error.message}+ </Text>+ </div>) : null}{slackConnect.isTimedOut ? (- <Callout.Root size="1" color="gray" variant="soft">- <Callout.Text>+ <div className="rounded-(--radius-2) border border-(--gray-5) bg-(--gray-2) px-3 py-2">+ <Text size="xs" variant="muted">We didn't hear back from PostHog. If you completed the connection inyour browser it should appear shortly, otherwise try again.- </Callout.Text>- </Callout.Root>+ </Text>+ </div>) : null}- </Flex>+ </div>+ );+}++/**+ * The workspace rows plus their connect callouts, sharing one connect instance. For surfaces+ * that render both together and have no connect action of their own in the header.+ */+export function SlackWorkspaceConnectionBlock({+ isLoading = false,+}: {+ isLoading?: boolean;+}) {+ const slackConnect = useSlackConnect();++ return (+ <>+ <SlackWorkspaceConnection+ slackConnect={slackConnect}+ isLoading={isLoading}+ />+ <SlackWorkspaceConnectionCallouts slackConnect={slackConnect} />+ </>);}