: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): edit repositories on the inbox GitHub source (#85117)
Charles Vienfc58f2914fc7
diff --git a/products/desktop/packages/api-client/src/posthog-client.ts b/products/desktop/packages/api-client/src/posthog-client.tsindex a0ddaec0ae76..56422ed21f4d 100644--- a/products/desktop/packages/api-client/src/posthog-client.ts+++ b/products/desktop/packages/api-client/src/posthog-client.ts@@ -576,6 +576,8 @@ export interface ExternalDataSource {// The generated `ExternalDataSourceSerializers` types this as `string`,// but the actual API returns an array of schema objectsschemas?: ExternalDataSourceSchema[] | string;+ /** Non-secret connection settings, e.g. a GitHub source's `repositories`. */+ job_inputs?: Record<string, unknown> | null;}/**@@ -2255,6 +2257,36 @@ export class PostHogAPIClient {return response.data as unknown as ExternalDataSource;}+ /**+ * `PATCH .../external_data_sources/{id}/`. `job_inputs` merges into the stored inputs, so+ * changing a GitHub source's repositories only needs `{ repositories: [...] }`.+ */+ async updateExternalDataSource(+ projectId: number,+ sourceId: string,+ payload: { job_inputs: Record<string, unknown> },+ ): Promise<ExternalDataSource> {+ const response = await this.api.patch(+ "/api/projects/{project_id}/external_data_sources/{id}/",+ {+ path: { project_id: projectId.toString(), id: sourceId },+ body: payload as unknown as Schemas.PatchedExternalDataSourceSerializers,+ withResponse: true,+ throwOnStatusError: false,+ },+ );+ if (!response.ok) {+ const errorData = isObjectRecord(response.data)+ ? (response.data as { detail?: string })+ : {};+ throw new Error(+ errorData.detail ??+ `Failed to update external data source: ${response.statusText}`,+ );+ }+ return response.data as unknown as ExternalDataSource;+ }+/*** Fetch the connect-form field schema for external data source types from the* warehouse wizard endpoint. Pass `sourceType` (e.g. `"Jira"`) to scope to one@@ -2334,6 +2366,39 @@ export class PostHogAPIClient {}}+ /**+ * Update several of a source's schemas in one request. The backend commits each schema on its+ * own, so one schema failing still applies the rest and the error names the ones it could not+ * save — unlike a client-side loop, where the first failure skips everything after it.+ */+ async bulkUpdateExternalDataSchemas(+ projectId: number,+ sourceId: string,+ schemas: { id: string; should_sync?: boolean; sync_type?: string }[],+ ): Promise<void> {+ const response = await this.api.patch(+ "/api/projects/{project_id}/external_data_sources/{id}/bulk_update_schemas/",+ {+ path: { project_id: projectId.toString(), id: sourceId },+ query: {},+ body: {+ schemas,+ } as unknown as Schemas.PatchedExternalDataSourceBulkUpdateSchemas,+ withResponse: true,+ throwOnStatusError: false,+ },+ );+ if (!response.ok) {+ const errorData = isObjectRecord(response.data)+ ? (response.data as { detail?: string })+ : {};+ throw new Error(+ errorData.detail ??+ `Failed to update external data schemas: ${response.statusText}`,+ );+ }+ }+async getTasks(options?: TaskListOptions): Promise<Task[]> {return (await this.getTasksPage(options)).tasks;}diff --git a/products/desktop/packages/core/src/integrations/githubSourceRepos.test.ts b/products/desktop/packages/core/src/integrations/githubSourceRepos.test.tsnew file mode 100644index 000000000000..5ab90adfc1b6--- /dev/null+++ b/products/desktop/packages/core/src/integrations/githubSourceRepos.test.ts@@ -0,0 +1,101 @@+import { describe, expect, it } from "vitest";+import {+ buildGithubRepositoriesPatch,+ effectiveGithubSourceRepos,+ githubIssuesSchemaNames,+ githubIssuesSchemasToEnable,+ githubSourceIntegrationId,+} from "./githubSourceRepos";++describe("effectiveGithubSourceRepos", () => {+ it.each([+ [+ "multi-repo source",+ { repositories: ["acme/a", "acme/b"], repository: "acme/a" },+ ["acme/a", "acme/b"],+ ],+ ["legacy single repo", { repository: "acme/a" }, ["acme/a"]],+ [+ "empty repositories falls back to legacy",+ { repositories: [], repository: "acme/a" },+ ["acme/a"],+ ],+ ["nothing configured", { auth_method: {} }, []],+ ["missing job inputs", undefined, []],+ ])("%s", (_name, jobInputs, expected) => {+ expect(effectiveGithubSourceRepos(jobInputs)).toEqual(expected);+ });+});++describe("buildGithubRepositoriesPatch", () => {+ it("sends only the repositories list, deduplicated", () => {+ expect(+ buildGithubRepositoriesPatch(["acme/a", "acme/b", "acme/a"]),+ ).toEqual({ job_inputs: { repositories: ["acme/a", "acme/b"] } });+ });+});++describe("githubIssuesSchemaNames", () => {+ it.each([+ [+ "qualifies and lowercases every repository",+ ["Acme/A", "acme/b"],+ undefined,+ ["acme/a.issues", "acme/b.issues"],+ ],+ [+ "keeps the pre-multi-repo repository bare",+ ["acme/a", "acme/b"],+ { repository: "Acme/A" },+ ["issues", "acme/b.issues"],+ ],+ ["no repositories", [], undefined, []],+ ])("%s", (_name, repos, jobInputs, expected) => {+ expect(githubIssuesSchemaNames(repos, jobInputs)).toEqual(expected);+ });+});++describe("githubIssuesSchemasToEnable", () => {+ const schemas = [+ { id: "1", name: "issues", should_sync: true, sync_type: "full_refresh" },+ { id: "2", name: "acme/b.issues", should_sync: false, sync_type: null },+ { id: "3", name: "acme/b.commits", should_sync: false, sync_type: null },+ {+ id: "4",+ name: "acme/c.issues",+ should_sync: true,+ sync_type: "incremental",+ },+ ];++ it.each([+ ["a repository whose issues are off", ["acme/b"], ["2"]],+ ["a repository already replicating in full", ["acme/a"], []],+ ["a repository on the wrong sync type", ["acme/c"], ["4"]],+ ["a repository with no rows yet", ["acme/d"], []],+ ])("%s", (_name, repos, expectedIds) => {+ const source = { job_inputs: { repository: "acme/a" }, schemas };+ expect(githubIssuesSchemasToEnable(repos, source).map((s) => s.id)).toEqual(+ expectedIds,+ );+ });+});++describe("githubSourceIntegrationId", () => {+ it.each([+ ["oauth source", { auth_method: { github_integration_id: 7 } }, 7],+ [+ "id stored as a string",+ { auth_method: { github_integration_id: "7" } },+ 7,+ ],+ [+ "personal access token source",+ { auth_method: { selection: "pat" } },+ null,+ ],+ ["missing job inputs", undefined, null],+ ])("%s", (_name, jobInputs, expected) => {+ expect(githubSourceIntegrationId(jobInputs)).toBe(expected);+ });+});diff --git a/products/desktop/packages/core/src/integrations/githubSourceRepos.ts b/products/desktop/packages/core/src/integrations/githubSourceRepos.tsnew file mode 100644index 000000000000..fc243d5ee0ea--- /dev/null+++ b/products/desktop/packages/core/src/integrations/githubSourceRepos.ts@@ -0,0 +1,101 @@+import type { ExternalDataSource } from "@posthog/api-client/posthog-client";++/** The only GitHub table Self-driving reads. */+const ISSUES_ENDPOINT = "issues";++/**+ * Full table replication. Issues get edited and closed after they are created, so an append-only+ * sync would miss everything that happens to an issue after PostHog first saw it.+ */+export const GITHUB_ISSUES_SYNC_TYPE = "full_refresh";++/** GitHub full names are case-insensitive, and the backend lowercases them before naming rows. */+function normalizeRepo(repo: string): string {+ return repo.trim().toLowerCase();+}++/**+ * The repositories a warehouse GitHub source syncs. Newer sources carry `repositories`; sources+ * created before multi-repo support only have the single `repository`, which the backend keeps+ * as a server-managed marker once `repositories` exists.+ */+export function effectiveGithubSourceRepos(+ jobInputs: Record<string, unknown> | null | undefined,+): string[] {+ const repositories = jobInputs?.repositories;+ if (Array.isArray(repositories)) {+ const named = repositories.filter(+ (repo): repo is string => typeof repo === "string" && repo.trim() !== "",+ );+ if (named.length > 0) return named;+ }+ const repository = jobInputs?.repository;+ return typeof repository === "string" && repository.trim() !== ""+ ? [repository]+ : [];+}++export function buildGithubRepositoriesPatch(repos: readonly string[]): {+ job_inputs: { repositories: string[] };+} {+ return { job_inputs: { repositories: [...new Set(repos)] } };+}++/**+ * The team GitHub installation a source authenticates through. Null for a source connected with a+ * personal access token, which carries no installation to scope a repository list by.+ */+export function githubSourceIntegrationId(+ jobInputs: Record<string, unknown> | null | undefined,+): number | null {+ const authMethod = jobInputs?.auth_method;+ if (typeof authMethod !== "object" || authMethod === null) return null;+ const id = (authMethod as Record<string, unknown>).github_integration_id;+ if (typeof id === "number") return Number.isFinite(id) ? id : null;+ if (typeof id !== "string" || id.trim() === "") return null;+ const parsed = Number(id);+ return Number.isFinite(parsed) ? parsed : null;+}++/**+ * The names the backend gives each repository's `issues` schema row. Rows are named+ * `owner/repo.issues`, except on a source created before multi-repo support, where that one+ * repository's rows keep the bare endpoint name forever.+ */+export function githubIssuesSchemaNames(+ repos: readonly string[],+ jobInputs?: Record<string, unknown> | null,+): string[] {+ const legacyRepo =+ typeof jobInputs?.repository === "string"+ ? normalizeRepo(jobInputs.repository)+ : "";+ return [+ ...new Set(+ repos.map((repo) => {+ const normalized = normalizeRepo(repo);+ return normalized && normalized === legacyRepo+ ? ISSUES_ENDPOINT+ : `${normalized}.${ISSUES_ENDPOINT}`;+ }),+ ),+ ];+}++/**+ * The schema rows that still have to be switched on for `repos` to reach the inbox. Adding a+ * repository to a source creates its rows disabled, so its issues never sync until something+ * enables them — pass the source as re-read after the repositories were saved.+ */+export function githubIssuesSchemasToEnable(+ repos: readonly string[],+ source: Pick<ExternalDataSource, "job_inputs" | "schemas"> | undefined,+): { id: string }[] {+ const schemas = Array.isArray(source?.schemas) ? source.schemas : [];+ const wanted = new Set(githubIssuesSchemaNames(repos, source?.job_inputs));+ return schemas.filter(+ (schema) =>+ wanted.has(schema.name) &&+ (!schema.should_sync || schema.sync_type !== GITHUB_ISSUES_SYNC_TYPE),+ );+}diff --git a/products/desktop/packages/ui/src/features/folder-picker/GitHubRepoMultiPicker.tsx b/products/desktop/packages/ui/src/features/folder-picker/GitHubRepoMultiPicker.tsxnew file mode 100644index 000000000000..0f91782f702c--- /dev/null+++ b/products/desktop/packages/ui/src/features/folder-picker/GitHubRepoMultiPicker.tsx@@ -0,0 +1,140 @@+import { GithubLogo } from "@phosphor-icons/react";+import {+ Button,+ Combobox,+ ComboboxChip,+ ComboboxChips,+ ComboboxChipsInput,+ ComboboxContent,+ ComboboxEmpty,+ ComboboxItem,+ ComboboxList,+ ComboboxValue,+ Spinner,+ Text,+} from "@posthog/quill";+import { useRef } from "react";++interface GitHubRepoMultiPickerProps {+ value: string[];+ onChange: (repos: string[]) => void;+ /** Repositories to offer; selected repos not in this list stay selectable as chips. */+ repositories: string[];+ isLoading: boolean;+ isLoadingMore?: boolean;+ hasMore?: boolean;+ onLoadMore?: () => void;+ open?: boolean;+ onOpenChange?: (open: boolean) => void;+ searchQuery?: string;+ onSearchQueryChange?: (value: string) => void;+ placeholder?: string;+ disabled?: boolean;+}++/**+ * Multi-select sibling of `GitHubRepoPicker`. Kept separate because the single-select picker's+ * `value: string | null` contract has several callers that would all need touching otherwise.+ */+export function GitHubRepoMultiPicker({+ value,+ onChange,+ repositories,+ isLoading,+ isLoadingMore = false,+ hasMore = false,+ onLoadMore,+ open,+ onOpenChange,+ searchQuery,+ onSearchQueryChange,+ placeholder = "Search repositories…",+ disabled = false,+}: GitHubRepoMultiPickerProps) {+ const anchorRef = useRef<HTMLDivElement>(null);+ const items = Array.from(new Set([...value, ...repositories]));++ return (+ <Combobox<string, true>+ multiple+ items={items}+ filter={null}+ value={value}+ onValueChange={(next) => onChange(next ?? [])}+ open={open}+ onOpenChange={onOpenChange}+ inputValue={searchQuery}+ onInputValueChange={(next) => onSearchQueryChange?.(next)}+ disabled={disabled}+ >+ <ComboboxChips+ ref={anchorRef}+ className="flex min-h-9 w-full flex-wrap items-center gap-1 rounded-(--radius-2) border border-border bg-(--color-panel-solid) px-1.5 py-1"+ >+ <span className="shrink-0 pl-1 text-(--gray-11)">+ <GithubLogo size={14} weight="regular" />+ </span>+ <ComboboxValue>+ {(selected: string[]) =>+ selected.map((repo) => (+ <ComboboxChip key={repo} title={repo} showRemove>+ {repo}+ </ComboboxChip>+ ))+ }+ </ComboboxValue>+ <ComboboxChipsInput+ placeholder={value.length === 0 ? placeholder : ""}+ aria-label="Repositories"+ className="min-w-24 flex-1 bg-transparent text-[13px] text-gray-12 outline-none placeholder:text-gray-10"+ />+ </ComboboxChips>+ <ComboboxContent+ anchor={anchorRef}+ align="start"+ sideOffset={4}+ className="flex max-h-80 w-(--anchor-width) min-w-80 flex-col"+ >+ <ComboboxEmpty+ className={+ isLoading+ ? "flex flex-1 flex-col items-center justify-center gap-2 py-4"+ : undefined+ }+ >+ {isLoading ? (+ <>+ <Spinner className="size-4" />+ <Text size="sm" variant="muted">+ Loading repositories+ </Text>+ </>+ ) : (+ "No repositories found."+ )}+ </ComboboxEmpty>+ <ComboboxList className="flex-1">+ {(repo: string) => (+ <ComboboxItem key={repo} value={repo}>+ {repo}+ </ComboboxItem>+ )}+ </ComboboxList>+ {hasMore ? (+ <div className="shrink-0 border-t p-1">+ <Button+ variant="outline"+ size="sm"+ className="w-full"+ disabled={isLoadingMore}+ loading={isLoadingMore}+ onClick={onLoadMore}+ >+ Load more repositories+ </Button>+ </div>+ ) : null}+ </ComboboxContent>+ </Combobox>+ );+}diff --git a/products/desktop/packages/ui/src/features/inbox/components/DataSourceSetup.tsx b/products/desktop/packages/ui/src/features/inbox/components/DataSourceSetup.tsxindex ac29b4fa2ea0..6901c4700bf7 100644--- a/products/desktop/packages/ui/src/features/inbox/components/DataSourceSetup.tsx+++ b/products/desktop/packages/ui/src/features/inbox/components/DataSourceSetup.tsx@@ -1,4 +1,5 @@import { GITHUB_INSTALL_PENDING_MESSAGE } from "@posthog/core/integrations/connectErrors";+import { githubIssuesSchemaNames } from "@posthog/core/integrations/githubSourceRepos";import { Button } from "@posthog/quill";import {EXTERNAL_INBOX_SOURCE_BY_PRODUCT,@@ -6,7 +7,7 @@ import {} from "@posthog/shared";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 { GitHubRepoMultiPicker } from "@posthog/ui/features/folder-picker/GitHubRepoMultiPicker";import { DynamicSourceSetup } from "@posthog/ui/features/inbox/components/DynamicSourceSetup";import { GithubInstallRequestsBanner } from "@posthog/ui/features/integrations/components/GithubInstallRequestsBanner";import {@@ -97,7 +98,7 @@ function GitHubSetup({ onComplete, onCancel }: SetupFormProps) {hasMore: visibleRepositoriesHasMore,loadMore: loadMoreVisibleRepositories,} = useGithubRepositories(repoPickerSearchQuery, isRepoPickerOpen);- const [repo, setRepo] = useState<string | null>(null);+ const [repos, setRepos] = useState<string[]>([]);const [loading, setLoading] = useState(false);const {error: connectError,@@ -110,38 +111,42 @@ function GitHubSetup({ onComplete, onCancel }: SetupFormProps) {projectId,projectHasTeamIntegration: hasGithubIntegration,});- const selectedIntegrationId = repo- ? getIntegrationIdForRepo(repo)+ // One warehouse source syncs through one installation, so every picked repo has to resolve to+ // the same team integration; the first repo decides which.+ const selectedIntegrationId = repos[0]+ ? getIntegrationIdForRepo(repos[0]): undefined;+ const mixedInstallations = repos.some(+ (repo) => getIntegrationIdForRepo(repo) !== selectedIntegrationId,+ );useEffect(() => {- if (isLoadingRepos || !repo || repositories.includes(repo)) {- return;- }-- setRepo(null);- }, [isLoadingRepos, repo, repositories]);-- useEffect(() => {- if (repo === null && repositories.length > 0) {- setRepo(repositories[0]);+ if (isLoadingRepos) return;+ const available = new Set(repositories);+ const known = repos.filter((repo) => available.has(repo));+ if (known.length !== repos.length) {+ setRepos(known);}- }, [repo, repositories]);+ }, [isLoadingRepos, repos, repositories]);const handleSubmit = useCallback(async () => {- if (!projectId || !client || !repo || !selectedIntegrationId) return;+ if (!projectId || !client || repos.length === 0 || !selectedIntegrationId) {+ return;+ }setLoading(true);try {await client.createExternalDataSource(projectId, {source_type: "Github",payload: {- repository: repo,+ repositories: repos,auth_method: {selection: "oauth",github_integration_id: selectedIntegrationId,},- schemas: schemasPayload(["issues"]),+ // A multi-repo source names its schema rows per repository, so naming the bare+ // `issues` table here would leave every repository unsynced.+ schemas: schemasPayload(githubIssuesSchemaNames(repos)),},});toast.success("GitHub data source created");@@ -153,7 +158,7 @@ function GitHubSetup({ onComplete, onCancel }: SetupFormProps) {} finally {setLoading(false);}- }, [projectId, client, onComplete, repo, selectedIntegrationId]);+ }, [projectId, client, onComplete, repos, selectedIntegrationId]);const handleRefreshRepositories = useCallback(() => {void refreshRepositories()@@ -239,27 +244,41 @@ function GitHubSetup({ onComplete, onCancel }: SetupFormProps) {return (<SetupFormContainer title="Connect GitHub"><Flex direction="column" gap="3">- <GitHubRepoPicker- value={repo}- onChange={setRepo}+ <span className="text-gray-11 text-sm">+ Pick the repositories whose issues should feed Self-driving. You can+ add or remove repositories later.+ </span>+ <GitHubRepoMultiPicker+ value={repos}+ onChange={setRepos}repositories={isRepoPickerOpen ? visibleRepositories : repositories}isLoading={isLoadingRepos || (isRepoPickerOpen && visibleRepositoriesLoading)}isLoadingMore={visibleRepositoriesFetchingMore}- isRefreshing={isRefreshingRepos}- onRefresh={handleRefreshRepositories}+ hasMore={visibleRepositoriesHasMore}+ onLoadMore={loadMoreVisibleRepositories}open={isRepoPickerOpen}onOpenChange={handleRepoPickerOpenChange}searchQuery={repoPickerSearchQuery}onSearchQueryChange={handleRepoPickerSearchChange}- hasMore={visibleRepositoriesHasMore}- onLoadMore={loadMoreVisibleRepositories}- placeholder="Select repository..."- size="2"/>+ {mixedInstallations ? (+ <span className="text-(--amber-11) text-sm">+ Pick repositories from one GitHub installation per source.+ </span>+ ) : null}<Flex gap="2" justify="end">+ <Button+ type="button"+ variant="outline"+ size="sm"+ onClick={handleRefreshRepositories}+ disabled={isRefreshingRepos}+ >+ {isRefreshingRepos ? "Refreshing…" : "Refresh repositories"}+ </Button><Buttontype="button"variant="outline"@@ -274,7 +293,12 @@ function GitHubSetup({ onComplete, onCancel }: SetupFormProps) {variant="primary"size="sm"onClick={handleSubmit}- disabled={!repo || !selectedIntegrationId || loading}+ disabled={+ repos.length === 0 ||+ !selectedIntegrationId ||+ mixedInstallations ||+ loading+ }>{loading ? "Creating..." : "Create source"}</Button>diff --git a/products/desktop/packages/ui/src/features/inbox/components/GitHubSourceRepositoriesDialog.tsx b/products/desktop/packages/ui/src/features/inbox/components/GitHubSourceRepositoriesDialog.tsxnew file mode 100644index 000000000000..13792e3fd9d9--- /dev/null+++ b/products/desktop/packages/ui/src/features/inbox/components/GitHubSourceRepositoriesDialog.tsx@@ -0,0 +1,218 @@+import type { ExternalDataSource } from "@posthog/api-client/posthog-client";+import {+ buildGithubRepositoriesPatch,+ effectiveGithubSourceRepos,+ GITHUB_ISSUES_SYNC_TYPE,+ githubIssuesSchemasToEnable,+ githubSourceIntegrationId,+} from "@posthog/core/integrations/githubSourceRepos";+import {+ Button,+ Dialog,+ DialogBody,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+ Text,+} from "@posthog/quill";+import { useOptionalAuthenticatedClient } from "@posthog/ui/features/auth/authClient";+import { useAuthStateValue } from "@posthog/ui/features/auth/store";+import { GitHubRepoMultiPicker } from "@posthog/ui/features/folder-picker/GitHubRepoMultiPicker";+import {+ useGithubRepositories,+ useRepositoryIntegration,+} from "@posthog/ui/features/integrations/useIntegrations";+import { toast } from "@posthog/ui/primitives/toast";+import { useMutation, useQueryClient } from "@tanstack/react-query";+import { useState } from "react";++interface GitHubSourceRepositoriesDialogProps {+ source: ExternalDataSource;+ open: boolean;+ onClose: () => void;+ onSaved?: () => void;+}++/**+ * Add or remove repositories on an existing GitHub inbox source. The backend reconciles the+ * per-repo schemas and webhooks from the new list, so the PATCH only carries `repositories`; it+ * creates an added repository's rows disabled, which the save then switches on.+ */+export function GitHubSourceRepositoriesDialog({+ source,+ open,+ onClose,+ onSaved,+}: GitHubSourceRepositoriesDialogProps) {+ const projectId = useAuthStateValue((state) => state.currentProjectId);+ const client = useOptionalAuthenticatedClient();+ const queryClient = useQueryClient();+ const initialRepos = effectiveGithubSourceRepos(source.job_inputs);+ const [repos, setRepos] = useState<string[]>(initialRepos);+ const [searchQuery, setSearchQuery] = useState("");+ const [pickerOpen, setPickerOpen] = useState(false);+ const { repositories, isLoadingRepos } = useRepositoryIntegration();+ // A source syncs through one GitHub installation, and editing repos can't change it. Scope the+ // picker to the installation the source stored, so it never offers repos the source's credential+ // can't reach. Null on a personal-access-token source, which has no installation to scope by.+ const sourceIntegrationId = githubSourceIntegrationId(source.job_inputs);+ // Unscoped, `useGithubRepositories` lists every team installation, so a token-authenticated+ // source would be offered repositories its token cannot read and save a sync that never runs.+ // Nothing here can list what a token reaches, so show the current list read-only instead.+ const canPickRepos = sourceIntegrationId !== null;+ const {+ repositories: visibleRepositories,+ isPending: visibleRepositoriesLoading,+ isFetchingMore,+ hasMore,+ loadMore,+ } = useGithubRepositories(+ searchQuery,+ pickerOpen && canPickRepos,+ sourceIntegrationId,+ );++ const save = useMutation({+ mutationFn: async () => {+ if (!client) throw new Error("Not authenticated");+ if (projectId == null) throw new Error("No project selected");+ await client.updateExternalDataSource(+ projectId,+ source.id,+ buildGithubRepositoriesPatch(repos),+ );+ // Saving the list creates each added repository's rows disabled, so read the source back+ // and switch its issues on — otherwise the repository shows on the card and syncs nothing.+ const saved = (await client.listExternalDataSources(projectId)).find(+ (candidate) => candidate.id === source.id,+ );+ if (!saved) {+ throw new Error(+ "Saved the repositories, but could not read the source back to start syncing their issues. Try saving again.",+ );+ }+ const schemasToEnable = githubIssuesSchemasToEnable(repos, saved);+ if (schemasToEnable.length > 0) {+ // One request, not one per repository: enabling a schema makes the server probe GitHub,+ // and the bulk endpoint attempts every schema instead of stopping at the first failure.+ await client.bulkUpdateExternalDataSchemas(+ projectId,+ source.id,+ schemasToEnable.map((schema) => ({+ id: schema.id,+ should_sync: true,+ sync_type: GITHUB_ISSUES_SYNC_TYPE,+ })),+ );+ }+ },+ onSuccess: () => {+ toast.success("Repositories updated");+ void queryClient.invalidateQueries({+ queryKey: ["external-data-sources", projectId],+ });+ onSaved?.();+ onClose();+ },+ onError: (error) => {+ toast.error(+ error instanceof Error+ ? error.message+ : "Failed to update repositories",+ );+ },+ });++ const initialRepoSet = new Set(initialRepos);+ const unchanged =+ repos.length === initialRepoSet.size &&+ repos.every((repo) => initialRepoSet.has(repo));+ // A save reconciles the repositories first, then switches their issues schemas on in a second+ // step. If that step fails, the repositories PATCH has already landed, so once the source+ // refetches the list is unchanged yet some schemas are still off. Keep Save usable in that+ // case so a retry can finish enabling them.+ const hasSchemasToEnable =+ githubIssuesSchemasToEnable(repos, source).length > 0;++ return (+ <Dialog+ open={open}+ onOpenChange={(next) => {+ if (!next && !save.isPending) onClose();+ }}+ >+ <DialogContent className="sm:max-w-lg">+ <DialogHeader>+ <DialogTitle>Edit repositories</DialogTitle>+ <DialogDescription>+ Issues from these repositories feed Self-driving. Removing one stops+ syncing it; its past signals stay.+ </DialogDescription>+ </DialogHeader>+ <DialogBody>+ {!canPickRepos ? (+ <div className="flex flex-col gap-2">+ <Text size="sm">+ {initialRepos.length > 0+ ? initialRepos.join(", ")+ : "No repositories selected"}+ </Text>+ <Text size="xs" variant="muted">+ This source connects with a personal access token, so PostHog+ can't tell which repositories the token reaches. Change them+ from Data pipelines in PostHog.+ </Text>+ </div>+ ) : (+ <div className="flex flex-col gap-2">+ <GitHubRepoMultiPicker+ value={repos}+ onChange={setRepos}+ repositories={pickerOpen ? visibleRepositories : repositories}+ isLoading={+ isLoadingRepos || (pickerOpen && visibleRepositoriesLoading)+ }+ isLoadingMore={isFetchingMore}+ hasMore={hasMore}+ onLoadMore={loadMore}+ open={pickerOpen}+ onOpenChange={(next) => {+ setPickerOpen(next);+ if (!next) setSearchQuery("");+ }}+ searchQuery={searchQuery}+ onSearchQueryChange={setSearchQuery}+ disabled={save.isPending}+ />+ {repos.length === 0 ? (+ <Text size="xs" className="text-(--amber-11)">+ Keep at least one repository, or turn the source off instead.+ </Text>+ ) : null}+ </div>+ )}+ </DialogBody>+ <DialogFooter>+ <Button variant="outline" onClick={onClose} disabled={save.isPending}>+ {canPickRepos ? "Cancel" : "Close"}+ </Button>+ <Button+ variant="primary"+ onClick={() => save.mutate()}+ loading={save.isPending}+ disabled={+ !canPickRepos ||+ save.isPending ||+ repos.length === 0 ||+ (unchanged && !hasSchemasToEnable)+ }+ >+ Save+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+}diff --git a/products/desktop/packages/ui/src/features/inbox/components/SignalSourceToggles.tsx b/products/desktop/packages/ui/src/features/inbox/components/SignalSourceToggles.tsxindex 2c7ea21b9860..224c0b59b6f9 100644--- a/products/desktop/packages/ui/src/features/inbox/components/SignalSourceToggles.tsx+++ b/products/desktop/packages/ui/src/features/inbox/components/SignalSourceToggles.tsx@@ -8,15 +8,20 @@ import {PlugIcon,VideoIcon,} from "@phosphor-icons/react";-import type { SignalSourceConfig } from "@posthog/api-client/posthog-client";+import type {+ ExternalDataSource,+ SignalSourceConfig,+} from "@posthog/api-client/posthog-client";+import { formatRepoPreview } from "@posthog/core/settings/githubRepoSummary";import { Button, Spinner, Switch } from "@posthog/quill";import {EXTERNAL_INBOX_SOURCES,type ToggleableSourceProduct,} from "@posthog/shared";+import { GitHubSourceRepositoriesDialog } from "@posthog/ui/features/inbox/components/GitHubSourceRepositoriesDialog";import { getSourceProductMeta } from "@posthog/ui/features/inbox/components/utils/source-product-icons";import { Badge } from "@posthog/ui/primitives/Badge";-import { memo, useCallback } from "react";+import { memo, useCallback, useState } from "react";export type SignalSourceValues = Record<ToggleableSourceProduct, boolean>;@@ -191,6 +196,52 @@ interface SourceState {requiresSetup: boolean;loading: boolean;syncStatus?: SignalSourceConfig["status"];+ externalSource?: ExternalDataSource;+ /** GitHub only: the repositories the warehouse source syncs. */+ configuredRepos?: string[];+}++/**+ * The GitHub source syncs a fixed repository list, unlike credential-based sources that pull+ * everything, so the card says which repositories and offers to change them.+ */+function GithubSourceRepositories({+ source,+ repos,+}: {+ source: ExternalDataSource;+ repos: string[];+}) {+ const [editing, setEditing] = useState(false);+ const label =+ repos.length === 0+ ? "No repositories selected"+ : `${repos.length} ${repos.length === 1 ? "repository" : "repositories"}: ${formatRepoPreview(repos)}`;+ return (+ <div className="mt-1 flex flex-wrap items-center gap-2">+ <span+ title={repos.join(", ")}+ className="min-w-0 truncate text-[12px] text-gray-11"+ >+ {label}+ </span>+ <Button+ type="button"+ variant="outline"+ size="xs"+ onClick={() => setEditing(true)}+ >+ Edit repositories+ </Button>+ {editing ? (+ <GitHubSourceRepositoriesDialog+ source={source}+ open={editing}+ onClose={() => setEditing(false)}+ />+ ) : null}+ </div>+ );}/**@@ -224,6 +275,10 @@ const ExternalSourceCard = memo(function ExternalSourceCard({const handleSetup = useCallback(() => onSetup?.(product), [onSetup, product]);const meta = getSourceProductMeta(product);const Icon = meta?.Icon ?? PlugIcon;+ const githubSource =+ product === "github" && state?.externalSource && state.configuredRepos+ ? { source: state.externalSource, repos: state.configuredRepos }+ : null;return (<SignalSourceToggleCard@@ -237,6 +292,14 @@ const ExternalSourceCard = memo(function ExternalSourceCard({onSetup={handleSetup}loading={state?.loading}syncStatus={state?.syncStatus}+ statusSection={+ githubSource ? (+ <GithubSourceRepositories+ source={githubSource.source}+ repos={githubSource.repos}+ />+ ) : undefined+ }compact/>);diff --git a/products/desktop/packages/ui/src/features/inbox/hooks/useSignalSourceToggles.ts b/products/desktop/packages/ui/src/features/inbox/hooks/useSignalSourceToggles.tsindex 69ae012443c5..4ccd7636233c 100644--- a/products/desktop/packages/ui/src/features/inbox/hooks/useSignalSourceToggles.ts+++ b/products/desktop/packages/ui/src/features/inbox/hooks/useSignalSourceToggles.ts@@ -1,4 +1,8 @@-import type { SignalSourceConfig } from "@posthog/api-client/posthog-client";+import type {+ ExternalDataSource,+ SignalSourceConfig,+} from "@posthog/api-client/posthog-client";+import { effectiveGithubSourceRepos } from "@posthog/core/integrations/githubSourceRepos";import {ANALYTICS_EVENTS,EXTERNAL_INBOX_SOURCES,@@ -163,18 +167,26 @@ export function useSignalSourceToggles() {requiresSetup: boolean;loading: boolean;syncStatus?: SignalSourceConfig["status"];+ externalSource?: ExternalDataSource;+ /** GitHub only: the repositories the warehouse source syncs. */+ configuredRepos?: string[];}>> = {};for (const product of ALL_SOURCE_PRODUCTS) {const config = configs?.find((c) => c.source_product === product);if (isSetupSourceProduct(product)) {- const hasExternalSource = !!findExternalSource(product);+ const externalSource = findExternalSource(product) ?? undefined;const isEnabled = serverValues[product];states[product] = {- requiresSetup: !hasExternalSource && !isEnabled,+ requiresSetup: !externalSource && !isEnabled,loading: !!loadingSources[product],syncStatus: config?.status ?? null,+ externalSource,+ configuredRepos:+ product === "github" && externalSource+ ? effectiveGithubSourceRepos(externalSource.job_inputs)+ : undefined,};} else {states[product] = {