Skip to content

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

feat(phai): add searchable github repository picker to task composer (#66326)

Georgiy Tarasovb44682f9126e
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index 0a241562e8e0..af3fcdbd33a8 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -237,7 +237,10 @@ import type {
} from 'products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rules/types'
import type { SymbolSetOrder } from 'products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/symbol_sets/symbolSetLogic'
import type { ErrorTrackingRecommendation } from 'products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/recommendations/types'
-import type { GitHubReposResponseApi } from 'products/integrations/frontend/generated/api.schemas'
+import type {
+ GitHubBranchesResponseApi,
+ GitHubReposResponseApi,
+} from 'products/integrations/frontend/generated/api.schemas'
import type { LogExplanation } from 'products/logs/frontend/components/LogsViewer/LogDetailsModal/Tabs/ExploreWithAI/types'
import type { NotebookCollabCursorApi } from 'products/notebooks/frontend/generated/api.schemas'
import type { Task, TaskListParams, TaskRun, TaskUpsertProps } from 'products/posthog_ai/frontend/types/taskTypes'
@@ -1573,6 +1576,10 @@ export class ApiRequest {
return this.integrations(teamId).addPathComponent(id).addPathComponent('github_repos')
}
+ public integrationGitHubBranches(id: IntegrationType['id'], teamId?: TeamType['id']): ApiRequest {
+ return this.integrations(teamId).addPathComponent(id).addPathComponent('github_branches')
+ }
+
public integrationJiraProjects(id: IntegrationType['id'], teamId?: TeamType['id']): ApiRequest {
return this.integrations(teamId).addPathComponent(id).addPathComponent('jira_projects')
}
@@ -5293,8 +5300,11 @@ const api = {
async bulkReorder(columns: Record<string, string[]>): Promise<{ updated: number; tasks: Task[] }> {
return await new ApiRequest().tasks().withAction('bulk_reorder').create({ data: { columns } })
},
- async run(id: Task['id']): Promise<Task> {
- return await new ApiRequest().task(id).withAction('run').create()
+ async run(id: Task['id'], data?: { branch?: string | null }): Promise<Task> {
+ return await new ApiRequest()
+ .task(id)
+ .withAction('run')
+ .create(data ? { data } : undefined)
},
runs: {
async list(taskId: Task['id'], params: Record<string, any> = {}): Promise<PaginatedResponse<TaskRun>> {
@@ -6181,10 +6191,16 @@ const api = {
},
async githubRepositories(
id: IntegrationType['id'],
- params?: { limit?: number; offset?: number }
+ params?: { limit?: number; offset?: number; search?: string }
): Promise<GitHubReposResponseApi> {
return await new ApiRequest().integrationGitHubRepositories(id).withQueryString(params).get()
},
+ async githubBranches(
+ id: IntegrationType['id'],
+ params: { repo: string; limit?: number; offset?: number; search?: string }
+ ): Promise<GitHubBranchesResponseApi> {
+ return await new ApiRequest().integrationGitHubBranches(id).withQueryString(params).get()
+ },
async githubLinkExisting(
data: {
source_team_id?: number
diff --git a/frontend/src/lib/integrations/GitHubBranchCombobox.tsx b/frontend/src/lib/integrations/GitHubBranchCombobox.tsx
new file mode 100644
index 000000000000..04d99d4b6fc8
--- /dev/null
+++ b/frontend/src/lib/integrations/GitHubBranchCombobox.tsx
@@ -0,0 +1,180 @@
+import { useActions, useValues } from 'kea'
+import { type MouseEvent, useEffect, useRef, useState } from 'react'
+
+import { IconGitBranch, IconRefresh } from '@posthog/icons'
+import {
+ Button,
+ Combobox,
+ ComboboxContent,
+ ComboboxEmpty,
+ ComboboxInput,
+ ComboboxItem,
+ ComboboxList,
+ ComboboxListFooter,
+ ComboboxTrigger,
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from '@posthog/quill'
+
+import { githubBranchSearchLogic } from './githubBranchSearchLogic'
+
+export interface GitHubBranchComboboxProps {
+ integrationId: number
+ /** Repository in `owner/repo` format whose branches to list. */
+ repo: string
+ /** Selected branch name, or empty when nothing is picked. */
+ value: string
+ onChange: (value: string | null) => void
+ disabled?: boolean
+ placeholder?: string
+}
+
+/** Sentinel item value for the "type a new branch name" action. */
+const CREATE_BRANCH_PREFIX = '__create__:'
+
+/**
+ * GitHub branch picker built on Quill's Combobox, mirroring the PostHog Code branch picker: a button
+ * trigger, in-popover server-side search, a paginated "Load more" footer, and a refresh control. It
+ * auto-selects the repository's default branch, and lets the user type a brand-new branch name (committed
+ * via a synthetic "Use \"x\" as branch name" item). Searching/pagination are delegated to
+ * {@link githubBranchSearchLogic}, keyed per repository.
+ */
+export function GitHubBranchCombobox({
+ integrationId,
+ repo,
+ value,
+ onChange,
+ disabled = false,
+ placeholder = 'Select branch...',
+}: GitHubBranchComboboxProps): JSX.Element {
+ const logic = githubBranchSearchLogic({ integrationId, repo })
+ const { branches, defaultBranch, loading, hasMore, searchQuery } = useValues(logic)
+ const { setSearchQuery, loadMore, refresh } = useActions(logic)
+
+ const triggerRef = useRef<HTMLButtonElement>(null)
+ const [open, setOpen] = useState(false)
+
+ const trimmedSearchQuery = searchQuery.trim()
+ const showInlineLoadingState = open && loading
+
+ // Pre-select the repo's default branch once it's known and nothing is chosen yet (matches PostHog Code).
+ useEffect(() => {
+ if (!value && defaultBranch) {
+ onChange(defaultBranch)
+ }
+ }, [value, defaultBranch, onChange])
+
+ // Offer "Use <typed> as branch name" when the search doesn't match an existing branch — lets the agent
+ // work on a brand-new branch.
+ const createSentinel = CREATE_BRANCH_PREFIX + trimmedSearchQuery
+ const showCreateItem = trimmedSearchQuery.length > 0 && !loading && !branches.includes(trimmedSearchQuery)
+ const items = showCreateItem ? [...branches, createSentinel] : branches
+
+ return (
+ <Combobox
+ items={items}
+ // Server-side search already filtered the list; don't let the combobox re-filter by input value.
+ filter={null}
+ value={value || null}
+ onValueChange={(next: string | null) => {
+ if (!next) {
+ onChange(null)
+ return
+ }
+ onChange(next.startsWith(CREATE_BRANCH_PREFIX) ? next.slice(CREATE_BRANCH_PREFIX.length) : next)
+ }}
+ open={open}
+ onOpenChange={(nextOpen: boolean) => {
+ setOpen(nextOpen)
+ if (!nextOpen && trimmedSearchQuery.length > 0) {
+ setSearchQuery('')
+ }
+ }}
+ inputValue={searchQuery}
+ onInputValueChange={(next: string) => setSearchQuery(next)}
+ disabled={disabled}
+ >
+ <ComboboxTrigger
+ render={
+ <Button ref={triggerRef} variant="outline" size="sm" disabled={disabled} aria-label="Branch">
+ <IconGitBranch className="shrink-0" />
+ <span className="min-w-0 truncate">{value || placeholder}</span>
+ </Button>
+ }
+ />
+ <ComboboxContent anchor={triggerRef} side="bottom" sideOffset={6} className="min-w-[280px]">
+ <div className="flex min-w-0 items-center gap-1 pe-2">
+ <div className="min-w-0 flex-1">
+ <ComboboxInput placeholder="Search branches..." />
+ </div>
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <Button
+ variant="outline"
+ size="sm"
+ disabled={disabled || loading}
+ aria-label="Refresh branches"
+ onMouseDown={(event: MouseEvent) => {
+ event.preventDefault()
+ event.stopPropagation()
+ }}
+ onClick={(event: MouseEvent) => {
+ event.preventDefault()
+ event.stopPropagation()
+ refresh()
+ }}
+ >
+ <IconRefresh className={loading ? 'animate-spin' : undefined} />
+ </Button>
+ }
+ />
+ <TooltipContent>Refresh branches</TooltipContent>
+ </Tooltip>
+ </div>
+ <ComboboxEmpty>{showInlineLoadingState ? 'Loading branches...' : 'No branches found.'}</ComboboxEmpty>
+ <ComboboxList>
+ {(item: string) =>
+ item.startsWith(CREATE_BRANCH_PREFIX) ? (
+ <ComboboxItem key={item} value={item}>
+ Use "{trimmedSearchQuery}" as branch name
+ </ComboboxItem>
+ ) : (
+ <ComboboxItem key={item} value={item}>
+ {item}
+ </ComboboxItem>
+ )
+ }
+ </ComboboxList>
+
+ {hasMore && (
+ <ComboboxListFooter>
+ <div className="px-2 pb-2">
+ <div className="px-1 pb-2 text-center text-muted text-xs">
+ {`Showing ${branches.length}+ ${trimmedSearchQuery ? 'matches' : 'branches'}`}
+ </div>
+ <Button
+ variant="outline"
+ size="sm"
+ className="w-full justify-center"
+ disabled={loading}
+ onMouseDown={(event: MouseEvent) => {
+ event.preventDefault()
+ event.stopPropagation()
+ }}
+ onClick={(event: MouseEvent) => {
+ event.preventDefault()
+ event.stopPropagation()
+ loadMore()
+ }}
+ >
+ Load more
+ </Button>
+ </div>
+ </ComboboxListFooter>
+ )}
+ </ComboboxContent>
+ </Combobox>
+ )
+}
diff --git a/frontend/src/lib/integrations/GitHubRepositoryCombobox.tsx b/frontend/src/lib/integrations/GitHubRepositoryCombobox.tsx
new file mode 100644
index 000000000000..8fd1d1d8f59e
--- /dev/null
+++ b/frontend/src/lib/integrations/GitHubRepositoryCombobox.tsx
@@ -0,0 +1,175 @@
+import { useActions, useValues } from 'kea'
+import { type MouseEvent, useRef, useState } from 'react'
+
+import { IconGithub, IconRefresh } from '@posthog/icons'
+import {
+ Button,
+ Combobox,
+ ComboboxContent,
+ ComboboxEmpty,
+ ComboboxInput,
+ ComboboxItem,
+ ComboboxList,
+ ComboboxListFooter,
+ ComboboxTrigger,
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from '@posthog/quill'
+
+import { githubRepositorySearchLogic } from './githubRepositorySearchLogic'
+
+export interface GitHubRepositoryComboboxProps {
+ integrationId: number
+ /** Selected repository in `owner/repo` format, or empty when nothing is picked. */
+ value: string
+ onChange: (value: string | null) => void
+ disabled?: boolean
+ placeholder?: string
+}
+
+/**
+ * GitHub repository picker built on Quill's Combobox, mirroring the PostHog Code repo picker: a button
+ * trigger, an in-popover search field driving server-side search, a paginated "Load more" footer, and a
+ * refresh control. Searching and pagination are delegated to {@link githubRepositorySearchLogic} so large
+ * accounts never load the full repository list up front.
+ */
+export function GitHubRepositoryCombobox({
+ integrationId,
+ value,
+ onChange,
+ disabled = false,
+ placeholder = 'Select repository...',
+}: GitHubRepositoryComboboxProps): JSX.Element {
+ const logic = githubRepositorySearchLogic({ id: integrationId })
+ const { repositoryNames, loading, hasMore, searchQuery, error } = useValues(logic)
+ const { setSearchQuery, loadMore, refresh } = useActions(logic)
+
+ const triggerRef = useRef<HTMLButtonElement>(null)
+ const [open, setOpen] = useState(false)
+
+ const trimmedSearchQuery = searchQuery.trim()
+ // While the popover is open we surface loading inline in the list; closed-and-loading shows a disabled
+ // button so the trigger never flickers an empty selection.
+ const showInlineLoadingState = open && loading
+ // Distinguish "this account genuinely has no repos" from "the search/refresh just hasn't returned yet".
+ const hasActiveSearchContext = open || trimmedSearchQuery.length > 0
+
+ if (loading && !showInlineLoadingState && repositoryNames.length === 0) {
+ return (
+ <Button variant="outline" size="sm" disabled>
+ <IconGithub className="shrink-0" />
+ Loading repos...
+ </Button>
+ )
+ }
+
+ if (repositoryNames.length === 0 && !showInlineLoadingState && !hasActiveSearchContext && !error) {
+ return (
+ <Button variant="outline" size="sm" disabled>
+ <IconGithub className="shrink-0" />
+ No GitHub repos
+ </Button>
+ )
+ }
+
+ return (
+ <Combobox
+ items={repositoryNames}
+ // Server-side search already filtered the list; don't let the combobox re-filter by input value.
+ filter={null}
+ value={value || null}
+ onValueChange={(next: string | null) => onChange(next ? next : null)}
+ open={open}
+ onOpenChange={(nextOpen: boolean) => {
+ setOpen(nextOpen)
+ // Reset back to the full list on the next open rather than on close: clearing the search
+ // while closing would empty the list and flip the trigger to a loading state for the
+ // debounce window, flickering the picker every time it's dismissed after a search.
+ if (nextOpen && trimmedSearchQuery.length > 0) {
+ setSearchQuery('')
+ }
+ }}
+ inputValue={searchQuery}
+ onInputValueChange={(next: string) => setSearchQuery(next)}
+ disabled={disabled}
+ >
+ <ComboboxTrigger
+ render={
+ <Button ref={triggerRef} variant="outline" size="sm" disabled={disabled} aria-label="Repository">
+ <IconGithub className="shrink-0" />
+ <span className="min-w-0 truncate">{value || placeholder}</span>
+ </Button>
+ }
+ />
+ <ComboboxContent anchor={triggerRef} side="bottom" sideOffset={6} className="min-w-[280px]">
+ <div className="flex min-w-0 items-center gap-1 pe-2">
+ <div className="min-w-0 flex-1">
+ <ComboboxInput placeholder="Search repositories..." />
+ </div>
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <Button
+ variant="outline"
+ size="sm"
+ disabled={disabled || loading}
+ aria-label="Refresh repositories"
+ onMouseDown={(event: MouseEvent) => {
+ event.preventDefault()
+ event.stopPropagation()
+ }}
+ onClick={(event: MouseEvent) => {
+ event.preventDefault()
+ event.stopPropagation()
+ refresh()
+ }}
+ >
+ <IconRefresh className={loading ? 'animate-spin' : undefined} />
+ </Button>
+ }
+ />
+ <TooltipContent>Refresh repositories</TooltipContent>
+ </Tooltip>
+ </div>
+ <ComboboxEmpty>
+ {showInlineLoadingState ? 'Loading repositories...' : error ? error : 'No repositories found.'}
+ </ComboboxEmpty>
+ <ComboboxList>
+ {(repo: string) => (
+ <ComboboxItem key={repo} value={repo}>
+ {repo}
+ </ComboboxItem>
+ )}
+ </ComboboxList>
+
+ {hasMore && (
+ <ComboboxListFooter>
+ <div className="px-2 pb-2">
+ <div className="px-1 pb-2 text-center text-muted text-xs">
+ {`Showing ${repositoryNames.length}+ ${trimmedSearchQuery ? 'matches' : 'repositories'}`}
+ </div>
+ <Button
+ variant="outline"
+ size="sm"
+ className="w-full justify-center"
+ disabled={loading}
+ onMouseDown={(event: MouseEvent) => {
+ event.preventDefault()
+ event.stopPropagation()
+ }}
+ onClick={(event: MouseEvent) => {
+ event.preventDefault()
+ event.stopPropagation()
+ loadMore()
+ }}
+ >
+ Load more
+ </Button>
+ </div>
+ </ComboboxListFooter>
+ )}
+ </ComboboxContent>
+ </Combobox>
+ )
+}
diff --git a/frontend/src/lib/integrations/githubBranchSearchLogic.ts b/frontend/src/lib/integrations/githubBranchSearchLogic.ts
new file mode 100644
index 000000000000..4b74fd9e731f
--- /dev/null
+++ b/frontend/src/lib/integrations/githubBranchSearchLogic.ts
@@ -0,0 +1,131 @@
+import { actions, afterMount, isBreakpoint, kea, key, listeners, path, props, reducers } from 'kea'
+
+import api from 'lib/api'
+
+import type { githubBranchSearchLogicType } from './githubBranchSearchLogicType'
+
+const PAGE_SIZE = 50
+const SEARCH_DEBOUNCE_MS = 300
+
+export interface GithubBranchSearchLogicProps {
+ integrationId: number
+ /** Repository in `owner/repo` format whose branches to list. */
+ repo: string
+}
+
+/**
+ * Server-side searchable, paginated GitHub branch source for a single repository. Mirrors
+ * {@link githubRepositorySearchLogic} but for the `github_branches` endpoint (which is repo-scoped), and
+ * additionally captures the repository's default branch so a picker can pre-select it. Keyed by integration
+ * id + repo so each repository's branch list stays independent.
+ */
+export const githubBranchSearchLogic = kea<githubBranchSearchLogicType>([
+ props({} as GithubBranchSearchLogicProps),
+ key((props) => `${props.integrationId}:${props.repo}`),
+ path((key) => ['lib', 'integrations', 'githubBranchSearchLogic', key]),
+
+ actions({
+ setSearchQuery: (searchQuery: string) => ({ searchQuery }),
+ loadPage: (offset: number) => ({ offset }),
+ loadPageSuccess: (branches: string[], defaultBranch: string | null, hasMore: boolean, offset: number) => ({
+ branches,
+ defaultBranch,
+ hasMore,
+ offset,
+ }),
+ loadPageFailure: true,
+ loadMore: true,
+ refresh: true,
+ }),
+
+ reducers({
+ searchQuery: [
+ '',
+ {
+ setSearchQuery: (_, { searchQuery }) => searchQuery,
+ },
+ ],
+ branches: [
+ [] as string[],
+ {
+ setSearchQuery: () => [],
+ refresh: () => [],
+ loadPageSuccess: (state, { branches, offset }) => {
+ if (offset === 0) {
+ return branches
+ }
+ const seen = new Set(state)
+ return [...state, ...branches.filter((b) => !seen.has(b))]
+ },
+ },
+ ],
+ // The repo's default branch, surfaced by the endpoint; used by the picker for pre-selection.
+ defaultBranch: [
+ null as string | null,
+ {
+ loadPageSuccess: (state, { defaultBranch }) => defaultBranch ?? state,
+ },
+ ],
+ loading: [
+ false,
+ {
+ setSearchQuery: () => true,
+ refresh: () => true,
+ loadPage: () => true,
+ loadPageSuccess: () => false,
+ loadPageFailure: () => false,
+ },
+ ],
+ hasMore: [
+ false,
+ {
+ loadPageSuccess: (_, { hasMore }) => hasMore,
+ loadPageFailure: () => false,
+ },
+ ],
+ currentOffset: [
+ 0,
+ {
+ setSearchQuery: () => 0,
+ refresh: () => 0,
+ loadPageSuccess: (_, { offset }) => offset + PAGE_SIZE,
+ },
+ ],
+ }),
+
+ listeners(({ actions, values, props }) => ({
+ setSearchQuery: async (_, breakpoint) => {
+ await breakpoint(SEARCH_DEBOUNCE_MS)
+ actions.loadPage(0)
+ },
+ refresh: () => {
+ actions.loadPage(0)
+ },
+ loadMore: () => {
+ if (values.hasMore && !values.loading) {
+ actions.loadPage(values.currentOffset)
+ }
+ },
+ loadPage: async ({ offset }, breakpoint) => {
+ try {
+ const response = await api.integrations.githubBranches(props.integrationId, {
+ repo: props.repo,
+ limit: PAGE_SIZE,
+ offset,
+ search: values.searchQuery.trim() || undefined,
+ })
+ await breakpoint()
+ actions.loadPageSuccess(response.branches, response.default_branch ?? null, response.has_more, offset)
+ } catch (e: any) {
+ if (isBreakpoint(e)) {
+ throw e
+ }
+ actions.loadPageFailure()
+ }
+ },
+ })),
+
+ afterMount(({ actions }) => {
+ actions.loadPage(0)
+ }),
+])
diff --git a/frontend/src/lib/integrations/githubRepositorySearchLogic.ts b/frontend/src/lib/integrations/githubRepositorySearchLogic.ts
new file mode 100644
index 000000000000..6c5e37072848
--- /dev/null
+++ b/frontend/src/lib/integrations/githubRepositorySearchLogic.ts
@@ -0,0 +1,151 @@
+import { actions, afterMount, isBreakpoint, kea, key, listeners, path, props, reducers, selectors } from 'kea'
+
+import api from 'lib/api'
+
+import type { GitHubRepoApi } from 'products/integrations/frontend/generated/api.schemas'
+
+import type { githubRepositorySearchLogicType } from './githubRepositorySearchLogicType'
+
+const PAGE_SIZE = 50
+const SEARCH_DEBOUNCE_MS = 300
+
+export interface GithubRepositorySearchLogicProps {
+ id: number
+}
+
+/**
+ * Server-side searchable, paginated GitHub repository source for a single integration. Unlike
+ * {@link githubIntegrationLogic} — which eagerly bulk-loads every repository in 500-row pages and ignores
+ * the search term — this drives the `github_repos` endpoint's `search`/`limit`/`offset` params directly so
+ * a repo picker can search across very large accounts without loading the whole list. Keyed by integration
+ * id so concurrent pickers stay independent.
+ */
+export const githubRepositorySearchLogic = kea<githubRepositorySearchLogicType>([
+ props({} as GithubRepositorySearchLogicProps),
+ key((props) => props.id),
+ path((key) => ['lib', 'integrations', 'githubRepositorySearchLogic', key]),
+
+ actions({
+ setSearchQuery: (searchQuery: string) => ({ searchQuery }),
+ loadPage: (offset: number) => ({ offset }),
+ loadPageSuccess: (repositories: GitHubRepoApi[], hasMore: boolean, offset: number) => ({
+ repositories,
+ hasMore,
+ offset,
+ }),
+ loadPageFailure: (error: string) => ({ error }),
+ loadMore: true,
+ refresh: true,
+ }),
+
+ reducers({
+ searchQuery: [
+ '',
+ {
+ setSearchQuery: (_, { searchQuery }) => searchQuery,
+ },
+ ],
+ repositories: [
+ [] as GitHubRepoApi[],
+ {
+ // A new query or refresh starts a fresh list; the first page (offset 0) replaces, later pages
+ // append (deduped by id) so "Load more" extends the current result set.
+ setSearchQuery: () => [],
+ refresh: () => [],
+ loadPageSuccess: (state, { repositories, offset }) => {
+ if (offset === 0) {
+ return repositories
+ }
+ const seenIds = new Set(state.map((r) => r.id))
+ return [...state, ...repositories.filter((r: GitHubRepoApi) => !seenIds.has(r.id))]
+ },
+ },
+ ],
+ loading: [
+ false,
+ {
+ setSearchQuery: () => true,
+ refresh: () => true,
+ loadPage: () => true,
+ loadPageSuccess: () => false,
+ loadPageFailure: () => false,
+ },
+ ],
+ hasMore: [
+ false,
+ {
+ loadPageSuccess: (_, { hasMore }) => hasMore,
+ loadPageFailure: () => false,
+ },
+ ],
+ error: [
+ null as string | null,
+ {
+ setSearchQuery: () => null,
+ refresh: () => null,
+ loadPage: () => null,
+ loadPageSuccess: () => null,
+ loadPageFailure: (_, { error }) => error,
+ },
+ ],
+ currentOffset: [
+ 0,
+ {
+ setSearchQuery: () => 0,
+ refresh: () => 0,
+ loadPageSuccess: (_, { offset }) => offset + PAGE_SIZE,
+ },
+ ],
+ }),
+
+ selectors({
+ // The picker selects on `owner/repo` (matches the Task API's repository format).
+ repositoryNames: [
+ (s) => [s.repositories],
+ (repositories: GitHubRepoApi[]): string[] => repositories.map((r) => r.full_name),
+ ],
+ }),
+
+ listeners(({ actions, values, props }) => ({
+ // Debounce keystrokes so a multi-character search fires one request, not one per character.
+ setSearchQuery: async (_, breakpoint) => {
+ await breakpoint(SEARCH_DEBOUNCE_MS)
+ actions.loadPage(0)
+ },
+ refresh: () => {
+ actions.loadPage(0)
+ },
+ loadMore: () => {
+ if (values.hasMore && !values.loading) {
+ actions.loadPage(values.currentOffset)
+ }
+ },
+ loadPage: async ({ offset }, breakpoint) => {
+ // Snapshot the query driving this request so a response that resolves after the search
+ // has moved on (e.g. a slow "Load more" landing mid-typing) can be discarded instead of
+ // committing stale repositories onto the new result set.
+ const query = values.searchQuery.trim()
+ try {
+ const response = await api.integrations.githubRepositories(props.id, {
+ limit: PAGE_SIZE,
+ offset,
+ search: query || undefined,
+ })
+ await breakpoint()
+ if (query !== values.searchQuery.trim()) {
+ return
+ }
+ actions.loadPageSuccess(response.repositories, response.has_more, offset)
+ } catch (e: any) {
+ if (isBreakpoint(e)) {
+ throw e
+ }
+ actions.loadPageFailure(e?.detail || e?.message || 'Failed to load repositories.')
+ }
+ },
+ })),
+
+ afterMount(({ actions }) => {
+ actions.loadPage(0)
+ }),
+])
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/RepositorySelector.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/RepositorySelector.tsx
index 888753b2a955..fe5d1078fe8a 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/RepositorySelector.tsx
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/RepositorySelector.tsx
@@ -3,7 +3,8 @@ import { useValues } from 'kea'
import { LemonSkeleton } from '@posthog/lemon-ui'
import { IntegrationChoice } from 'lib/components/CyclotronJob/integrations/IntegrationChoice'
-import { GitHubRepositoryPicker } from 'lib/integrations/GitHubIntegrationHelpers'
+import { GitHubBranchCombobox } from 'lib/integrations/GitHubBranchCombobox'
+import { GitHubRepositoryCombobox } from 'lib/integrations/GitHubRepositoryCombobox'
import { integrationsLogic } from 'lib/integrations/integrationsLogic'
import { urls } from 'scenes/urls'
@@ -15,20 +16,16 @@ export interface RepositorySelectorProps {
}
export function RepositorySelector({ value, onChange }: RepositorySelectorProps): JSX.Element {
- const { integrations, integrationsLoading } = useValues(integrationsLogic)
+ const { integrationsLoading } = useValues(integrationsLogic)
- // The picker uses plain repo names as keys, but the Task API expects owner/repo format
- const pickerValue = value.repository?.split('/')?.pop() ?? ''
+ // The picker selects on `owner/repo`, which is exactly the format the Task API expects. Switching repos
+ // clears the branch so the new repo's default branch is picked up.
+ const handleRepositoryChange = (repository: string | null): void => {
+ onChange({ ...value, repository: repository ?? undefined, branch: undefined })
+ }
- const handleRepositoryChange = (repoName: string): void => {
- if (!repoName) {
- onChange({ ...value, repository: undefined })
- return
- }
- const integration = integrations?.find((i) => i.id === value.integrationId)
- const owner = integration?.config?.account?.name || integration?.config?.account?.login
- const repository = owner ? `${owner}/${repoName}` : repoName
- onChange({ ...value, repository })
+ const handleBranchChange = (branch: string | null): void => {
+ onChange({ ...value, branch: branch ?? undefined })
}
if (integrationsLoading) {
@@ -47,6 +44,7 @@ export function RepositorySelector({ value, onChange }: RepositorySelectorProps)
...value,
integrationId: integrationId ?? undefined,
repository: undefined,
+ branch: undefined,
})
}
redirectUrl={urls.taskTracker()}
@@ -56,13 +54,25 @@ export function RepositorySelector({ value, onChange }: RepositorySelectorProps)
{value.integrationId ? (
<div>
<label className="block text-sm font-medium mb-2">Repository</label>
- <GitHubRepositoryPicker
+ <GitHubRepositoryCombobox
integrationId={value.integrationId}
- value={pickerValue}
+ value={value.repository ?? ''}
onChange={handleRepositoryChange}
/>
</div>
) : null}
+
+ {value.integrationId && value.repository ? (
+ <div>
+ <label className="block text-sm font-medium mb-2">Branch</label>
+ <GitHubBranchCombobox
+ integrationId={value.integrationId}
+ repo={value.repository}
+ value={value.branch ?? ''}
+ onChange={handleBranchChange}
+ />
+ </div>
+ ) : null}
</div>
)
}
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts
index d9a69f28c237..25cabdc32fed 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts
@@ -84,8 +84,9 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([
const newTask = await api.tasks.create(taskData)
lemonToast.success('Task created successfully')
- // Auto-run the task after creation; the detail scene shows the latest run by default.
- await api.tasks.run(newTask.id)
+ // Auto-run the task after creation; the detail scene shows the latest run by default. The
+ // run checks out the chosen branch (server falls back to the repo's default branch if unset).
+ await api.tasks.run(newTask.id, { branch: repositoryConfig.branch ?? null })
router.actions.push(`/tasks/${newTask.id}`)
actions.submitNewTaskSuccess()
diff --git a/products/posthog_ai/frontend/types/taskTypes.ts b/products/posthog_ai/frontend/types/taskTypes.ts
index 5c59df10dbc5..78ba91464730 100644
--- a/products/posthog_ai/frontend/types/taskTypes.ts
+++ b/products/posthog_ai/frontend/types/taskTypes.ts
@@ -4,6 +4,8 @@ export interface RepositoryConfig {
integrationId?: number
/** `owner/repo` (GitHub `full_name`), same as data warehouse / Cyclotron GitHub pickers */
repository?: string
+ /** Git branch the run checks out; defaults to the repo's default branch when unset. */
+ branch?: string
}
export enum OriginProduct {