An open-source, faster Devin alternative
TypeScript
Work web: choose the knowledge repository with a combobox
Igor Zalutski via Computerf9715a5f297a
diff --git a/web/src/managed-agents/work/Board.tsx b/web/src/managed-agents/work/Board.tsxindex 87d9a93d..7b220249 100644--- a/web/src/managed-agents/work/Board.tsx+++ b/web/src/managed-agents/work/Board.tsx@@ -121,11 +121,10 @@ export function Board() {icon={FileText}title="Nothing is tracked yet"description={<WhatIsAnItem />}+ action={<FirstRepository />}+ className="[&>div:last-child]:w-full"/></Panel>- <div className="mt-8">- <FirstRepository />- </div></BoardFrame>)}diff --git a/web/src/managed-agents/work/KnowledgeRepository.tsx b/web/src/managed-agents/work/KnowledgeRepository.tsxindex c01074b9..bc7ef78a 100644--- a/web/src/managed-agents/work/KnowledgeRepository.tsx+++ b/web/src/managed-agents/work/KnowledgeRepository.tsx@@ -1,6 +1,12 @@import { useState, type ReactNode } from 'react'import { ExternalLink, Loader2 } from 'lucide-react'import { ApiError } from '@/api/errors'+import {+ SettingsAction,+ SettingsRow,+ SettingsRowSkeleton,+ SettingsSection,+} from '@/components/settings'import { Button } from '@/components/ui/button'import { relativeTime } from '../computer-state'import type { Repository } from './api'@@ -10,115 +16,99 @@ import {useOpenItems,useRepository,} from './queries'-import { ConnectGitHubButton, RepositoryPicker } from './RepositorySetting'+import { ConnectGitHubButton, RepositoryCombobox } from './RepositorySetting'-// The knowledge repository setting, as one self-contained section that can be-// mounted on any settings surface: which repository holds the working docs,-// how the board's reading of it stands, Change (with a confirmation when it-// switches), and the one action that fixes each problem the server reports.+// The knowledge repository setting, as one self-contained section in the+// settings anatomy (components/settings.tsx), so it can be mounted on any+// settings surface: which repository holds the working docs (the Repository+// row is the picker itself), its branch, how the board's reading of it+// stands, and the one action that fixes each problem the server reports./** `id` goes on the section, as a link target. */export function KnowledgeRepositorySection({ id }: { id?: string }) {const repository = useRepository()- const [editing, setEditing] = useState(false)+ // Open from a fix ("Choose another repository") as well as the trigger.+ const [choosing, setChoosing] = useState(false)- let body: ReactNode+ let rows: ReactNodeif (repository.isPending) {- body = (- <p role="status" className="text-muted-foreground flex items-center">- <Loader2 className="size-4 animate-spin" aria-label="Loading" />- </p>+ rows = (+ <div role="status" aria-label="Loading" className="divide-y">+ <SettingsRowSkeleton />+ <SettingsRowSkeleton />+ <SettingsRowSkeleton />+ </div>)} else if (repository.isError) {const missing =repository.error instanceof ApiError && repository.error.status === 404- body = (- <p className="text-muted-foreground">- {missing- ? 'Tracked work is not available here yet.'- : 'Could not load the knowledge repository. Try loading this page again.'}- </p>+ rows = (+ <SettingsRow>+ <span className="text-muted-foreground">+ {missing+ ? 'Tracked work is not available here yet.'+ : 'Could not load the knowledge repository. Try loading this page again.'}+ </span>+ </SettingsRow>)} else if (!repository.data) {- body = <RepositoryPicker current={null} />- } else if (editing) {- body = (- <RepositoryPicker- current={repository.data}- onDone={() => setEditing(false)}- onCancel={() => setEditing(false)}- />+ rows = (+ <SettingsRow label="Repository">+ <RepositoryCombobox current={null} />+ </SettingsRow>)} else {- body = (- <Current repository={repository.data} onChange={() => setEditing(true)} />+ const r = repository.data+ const problem = repositoryProblem(r)+ rows = (+ <>+ <SettingsRow+ label="Repository"+ action={+ <SettingsAction size="icon-sm" asChild>+ <a+ href={`https://github.com/${r.owner}/${r.name}`}+ target="_blank"+ rel="noreferrer"+ aria-label={`Open ${repositoryName(r)} on GitHub`}+ title="Open on GitHub"+ >+ <ExternalLink />+ </a>+ </SettingsAction>+ }+ >+ <RepositoryCombobox+ current={r}+ open={choosing}+ onOpenChange={setChoosing}+ />+ </SettingsRow>+ <SettingsRow label="Branch">+ <span className="font-mono text-[13px]">{r.branch}</span>+ </SettingsRow>+ <SettingsRow label="State">+ {problem ? (+ <span className="text-status-error">{problem}</span>+ ) : (+ <ReadState repository={r} />+ )}+ </SettingsRow>+ {problem ? (+ <Fix repository={r} onChoose={() => setChoosing(true)} />+ ) : null}+ </>)}return (- <section id={id} aria-labelledby="knowledge-repository-title">- <h2- id="knowledge-repository-title"- className="mb-1 text-sm font-semibold"- >- Knowledge repository- </h2>- <p className="text-muted-foreground mb-3 text-sm">- The GitHub repository where agents keep working docs. The board shows- the items in it.- </p>- <div className="bg-panel rounded-lg border px-5 py-4 text-sm">{body}</div>- </section>- )-}--/** The chosen repository, how the board's reading of it stands, and its fix. */-function Current({- repository: r,- onChange,-}: {- repository: Repository- onChange: () => void-}) {- const problem = repositoryProblem(r)- return (- <div className="space-y-4">- <div className="flex flex-wrap items-start justify-between gap-3">- <dl className="grid min-w-0 grid-cols-[6rem_minmax(0,1fr)] gap-x-4 gap-y-1.5">- <dt className="text-muted-foreground">Repository</dt>- <dd className="min-w-0">- <a- href={`https://github.com/${r.owner}/${r.name}`}- target="_blank"- rel="noreferrer"- className="hover:text-foreground inline-flex items-center gap-1 font-medium"- >- {repositoryName(r)}- <ExternalLink- className="text-muted-foreground size-3"- aria-hidden- />- </a>- </dd>- <dt className="text-muted-foreground">Branch</dt>- <dd>{r.branch}</dd>- <dt className="text-muted-foreground">State</dt>- <dd>- {problem ? (- <span className="text-status-error">{problem}</span>- ) : (- <ReadState repository={r} />- )}- </dd>- </dl>- {problem ? null : (- <Button size="sm" variant="outline" onClick={onChange}>- Change- </Button>- )}- </div>- {problem ? <Fix repository={r} onChange={onChange} /> : null}- </div>+ <SettingsSection+ id={id}+ title="Knowledge repository"+ description="The GitHub repository where agents keep working docs. The board shows the items in it."+ >+ {rows}+ </SettingsSection>)}@@ -176,10 +166,10 @@ function ReadState({ repository: r }: { repository: Repository }) {*/function Fix({repository: r,- onChange,+ onChoose,}: {repository: Repository- onChange: () => void+ onChoose: () => void}) {const code = r.problem ?? ''const needsAccess =@@ -189,10 +179,21 @@ function Fix({const settingsUrl = installations.data?.find((i) => i.id === String(r.installationId),)?.settingsUrl+ // Quiet beside the fix itself; the button when it is the only way out.+ const another = (alone = false) =>+ alone ? (+ <Button size="sm" onClick={onChoose}>+ Choose another repository+ </Button>+ ) : (+ <SettingsAction onClick={onChoose}>+ Choose another repository+ </SettingsAction>+ )if (code === 'installation_removed' || code === 'installation_suspended') {return (- <Actions+ <FixRowhint={code === 'installation_suspended'? 'Unsuspend the GitHub App, or connect it again, then come back.'@@ -200,15 +201,13 @@ function Fix({}><ConnectGitHubButton label="Reconnect GitHub" variant="default" />- <Button size="sm" variant="ghost" onClick={onChange}>- Choose another repository- </Button>- </Actions>+ {another()}+ </FixRow>)}if (needsAccess) {return (- <Actions hint="Grant the GitHub App this repository again, or pick another one.">+ <FixRow hint="Grant the GitHub App this repository again, or pick another one.">{settingsUrl ? (<Button size="sm" asChild><a href={settingsUrl} target="_blank" rel="noreferrer">@@ -217,46 +216,40 @@ function Fix({</a></Button>) : null}- <Button- size="sm"- variant={settingsUrl ? 'outline' : 'default'}- onClick={onChange}- >- Choose another repository- </Button>- </Actions>+ {another(!settingsUrl)}+ </FixRow>)}if (code === 'branch_not_found') {return (- <Actions+ <FixRowhint={`The ${r.branch} branch is gone. Choose the repository again to use its default branch.`}>- <Button size="sm" onClick={onChange}>- Change+ <Button size="sm" onClick={onChoose}>+ Choose again</Button>- </Actions>+ </FixRow>)}if (code === 'github_app_not_configured') {return (- <Actions hint="This is on our side, not yours; the board reads again once it is fixed." />+ <FixRow hint="This is on our side, not yours; the board reads again once it is fixed." />)}- return (- <Actions>- <Button size="sm" variant="outline" onClick={onChange}>- Change- </Button>- </Actions>- )+ return <FixRow>{another(true)}</FixRow>}-function Actions({ hint, children }: { hint?: string; children?: ReactNode }) {+function FixRow({ hint, children }: { hint?: string; children?: ReactNode }) {+ // In the value column, the hint over its buttons: a full sentence and two+ // buttons do not fit one line beside each other.return (- <div className="flex flex-wrap items-center gap-x-4 gap-y-2 border-t pt-4">- {hint ? <p className="text-muted-foreground flex-1">{hint}</p> : null}- {children ? <div className="flex gap-2">{children}</div> : null}- </div>+ <SettingsRow indent className="py-3">+ <div className="space-y-2.5">+ {hint ? <p className="text-muted-foreground">{hint}</p> : null}+ {children ? (+ <div className="flex flex-wrap items-center gap-2">{children}</div>+ ) : null}+ </div>+ </SettingsRow>)}diff --git a/web/src/managed-agents/work/RepositorySetting.tsx b/web/src/managed-agents/work/RepositorySetting.tsxindex e8a8db6d..1dda1b8f 100644--- a/web/src/managed-agents/work/RepositorySetting.tsx+++ b/web/src/managed-agents/work/RepositorySetting.tsx@@ -1,7 +1,15 @@-import { useState } from 'react'+import {+ useEffect,+ useId,+ useRef,+ useState,+ type KeyboardEvent,+ type ReactNode,+} from 'react'import { useMutation, useQueryClient } from '@tanstack/react-query'import {Check,+ ChevronsUpDown,ExternalLink,Loader2,Lock,@@ -9,9 +17,13 @@ import {Search,} from 'lucide-react'import { ConfirmDialog } from '@/components/confirm-dialog'-import { Input, Select } from '@/components/form'import { GithubMark } from '@/components/github-mark'import { Button } from '@/components/ui/button'+import {+ Popover,+ PopoverContent,+ PopoverTrigger,+} from '@/components/ui/popover'import { notifyError, notifySuccess } from '@/lib/errors'import { cn } from '@/lib/utils'import { addManagedGitHubConnection } from '../api'@@ -25,31 +37,34 @@ import {type GrantingInstallation,type Repository,} from './api'-import { repositoryName } from './board'import { useGrantingInstallations } from './queries'// Which repository holds the organization's working docs (tech design 3.1):// one per organization, chosen from what its GitHub connection can reach.-// The first choice can be made on the board itself (`FirstRepository`); the-// setting with its state and fixes is KnowledgeRepositorySection.+// One control shows the choice and opens a searchable list of what the+// installations grant, as GitHub's and Vercel's repository pickers do. The+// board's first-time state uses it (`FirstRepository`); the setting with its+// state and fixes is KnowledgeRepositorySection./** The board's empty state: choose the repository, and the board loads. */export function FirstRepository() {return (- <section aria-labelledby="work-repository-title">- <h2 id="work-repository-title" className="mb-3 text-sm font-semibold">- Knowledge repository- </h2>- <div className="bg-panel rounded-lg border px-5 py-3 text-sm">- <RepositoryPicker current={null} />- </div>- </section>+ <div className="mx-auto w-full max-w-sm space-y-3 text-left">+ <p className="text-muted-foreground text-center text-sm">+ Choose the{' '}+ <span className="text-foreground font-medium">+ knowledge repository+ </span>+ : the GitHub repository where agents keep these docs.+ </p>+ <RepositoryCombobox current={null} prominent />+ </div>)}/*** Starts the managed GitHub App install in a new window, as Connections and- * the Computer page do. Coming back, the picker and the repository are read+ * the Computer page do. Coming back, the list and the repository are read* again on focus.*/export function ConnectGitHubButton({@@ -87,35 +102,58 @@ export function ConnectGitHubButton({)}-// About six rows show; the rest scroll.-const LIST_HEIGHT = 'max-h-[16.5rem]'+type Choice = { installationId: string; repository: GrantedRepository }++const fullName = (r: { owner: string; name: string }) => `${r.owner}/${r.name}`++const sameRepository = (current: Repository | null, c: Choice) =>+ !!current &&+ String(current.installationId) === c.installationId &&+ current.owner.toLowerCase() === c.repository.owner.toLowerCase() &&+ current.name.toLowerCase() === c.repository.name.toLowerCase()/**- * The repositories the organization's GitHub installations grant, most- * recently pushed first, filtered as you type. Selecting one saves it on its- * default branch. The list is read again when the window regains focus, so- * coming back from granting access on GitHub shows the new repository.+ * The repository, as one control: the trigger shows the choice, and opens the+ * repositories the organization's GitHub installations grant, most recently+ * pushed first, grouped by account when there are several, filtered as you+ * type. Choosing one saves it on its default branch, after a confirmation+ * when it replaces another. The list is read when first wanted, again on+ * every open and whenever the window regains focus, so coming back from+ * granting access on GitHub shows the new repository.+ *+ * `open`/`onOpenChange` let a fix elsewhere ("Choose another repository")+ * open it.*/-export function RepositoryPicker({+export function RepositoryCombobox({current,- onDone,- onCancel,+ prominent = false,+ open: openProp,+ onOpenChange,}: {current: Repository | null- onDone?: () => void- onCancel?: () => void+ /** Full width and a little taller, for a first choice. */+ prominent?: boolean+ open?: boolean+ onOpenChange?: (open: boolean) => void}) {const qc = useQueryClient()const org = useOrg()- const list = useGrantingInstallations()- // A switch away from a set repository waits for a confirmation.+ const [innerOpen, setInnerOpen] = useState(false)+ const open = openProp ?? innerOpen+ // Read the list once it is wanted: a first choice needs it to know whether+ // GitHub is connected at all; otherwise hovering the trigger is enough.+ const [wanted, setWanted] = useState(!current)+ const list = useGrantingInstallations(wanted || open)const [pending, setPending] = useState<Choice | null>(null)- const installations = list.data ?? []- const [chosen, setChosen] = useState<string | null>(null)- const [q, setQ] = useState('')- const want = chosen ?? (current ? String(current.installationId) : '')- const installation =- installations.find((i) => i.id === want) ?? installations[0]++ const setOpen = (next: boolean) => {+ if (next) {+ setWanted(true)+ if (list.isFetched && !list.isFetching) void list.refetch()+ }+ setInnerOpen(next)+ onOpenChange?.(next)+ }const save = useMutation({mutationFn: ({ installationId, repository: r }: Choice) =>@@ -130,15 +168,26 @@ export function RepositoryPicker({void qc.invalidateQueries({ queryKey: ['work', org] })notifySuccess('Knowledge repository saved.')setPending(null)- onDone?.()},onError: (e) => notifyError('Could not save the repository', e),})- if (list.isSuccess && installations.length === 0) {+ const choose = (c: Choice) => {+ setOpen(false)+ // The same repository again: nothing to do, unless it has a problem+ // (choosing it again saves its default branch, the fix for a lost one).+ if (sameRepository(current, c)) {+ if (current?.problem) save.mutate(c)+ return+ }+ if (current) setPending(c)+ else save.mutate(c)+ }++ if (!current && list.isSuccess && list.data.length === 0) {return (<div className="flex flex-wrap items-center justify-between gap-3">- <p className="text-muted-foreground">+ <p className="text-muted-foreground text-sm">Connect GitHub first: working docs live in one of its repositories.</p><ConnectGitHubButton />@@ -146,161 +195,94 @@ export function RepositoryPicker({)}- const isCurrent = (r: GrantedRepository) =>- !!current &&- !!installation &&- String(current.installationId) === installation.id &&- current.owner.toLowerCase() === r.owner.toLowerCase() &&- current.name.toLowerCase() === r.name.toLowerCase()- const needle = q.trim().toLowerCase()- const shown = (installation?.repositories ?? []).filter((r) =>- r.name.toLowerCase().includes(needle),- )+ // What the trigger shows: the saving choice, else the current one.+ const shown = save.isPending+ ? save.variables.repository+ : (current &&+ list.data+ ?.find((i) => i.id === String(current.installationId))+ ?.repositories.find(+ (r) =>+ r.owner.toLowerCase() === current.owner.toLowerCase() &&+ r.name.toLowerCase() === current.name.toLowerCase(),+ )) ||+ currentreturn (- <div className="space-y-3 py-1">- <p className="text-muted-foreground">- Pick the repository where agents keep working docs for tracked items.- Everyone in the organization can read them.- </p>- <div className="flex gap-2">- {installations.length > 1 ? (- <div className="w-44 shrink-0">- <Select- id="work-repo-account"- value={installation?.id ?? ''}- onValueChange={(v) => {- setChosen(v)- setQ('')- }}- options={installations.map((i) => ({- value: i.id,- label: i.accountLogin,- }))}- />- </div>- ) : null}- <div className="relative min-w-0 flex-1">- <Search- className="text-muted-foreground pointer-events-none absolute top-1/2 left-2.5 size-3.5 -translate-y-1/2"- aria-hidden- />- <Input- value={q}- onChange={(e) => setQ(e.target.value)}- onKeyDown={(e) => e.key === 'Escape' && setQ('')}- placeholder="Search repositories"- aria-label="Search repositories"- autoComplete="off"- className="pl-8"- />- </div>- <Button- type="button"- size="icon"- variant="outline"- onClick={() => void list.refetch()}- disabled={list.isFetching}- aria-label="Refresh the list"- title="Refresh the list"- >- <RefreshCw- className={cn('size-3.5', list.isFetching && 'animate-spin')}- />- </Button>- </div>- <div className={cn('overflow-y-auto rounded-md border', LIST_HEIGHT)}>- {list.isPending ? (- <p- role="status"- className="text-muted-foreground flex items-center justify-center gap-2 px-3 py-10"+ <>+ <Popover open={open} onOpenChange={setOpen}>+ <PopoverTrigger asChild>+ <Button+ type="button"+ variant="outline"+ aria-haspopup="listbox"+ disabled={save.isPending}+ onPointerEnter={() => setWanted(true)}+ onFocus={() => setWanted(true)}+ // Dressed as the Input beside it: same height, border and+ // (transparent) background.+ className={cn(+ 'border-input h-8 w-full justify-between gap-2 bg-transparent px-2.5 font-normal hover:bg-transparent aria-expanded:bg-transparent',+ !prominent && 'max-w-80',+ )}>- <Loader2 className="size-4 animate-spin" aria-hidden />- Loading repositories from GitHub…- </p>- ) : !installation ? (- <div className="flex flex-col items-center gap-2 px-3 py-8 text-center">- <p className="text-muted-foreground">- Could not load the repositories from GitHub.- </p>- <Button- type="button"- size="sm"- variant="outline"- onClick={() => void list.refetch()}- disabled={list.isFetching}- >- Try again- </Button>- </div>- ) : installation.problem ? (- <p className="text-status-error px-3 py-8 text-center">- {installation.problemMessage ??- `GitHub would not list the repositories of ${installation.accountLogin}.`}- </p>- ) : installation.repositories.length === 0 ? (- <p className="text-muted-foreground px-3 py-8 text-center">- The GitHub App cannot reach any repository of{' '}- {installation.accountLogin} yet. Grant it one, then come back.- </p>- ) : shown.length === 0 ? (- <p className="text-muted-foreground px-3 py-8 text-center">- No repository matches “{q.trim()}”.- </p>- ) : (- <ul className="divide-y" aria-label="Repositories">- {shown.map((r) => (- <RepositoryRow- key={r.id}- repository={r}- selected={isCurrent(r)}- saving={save.isPending && save.variables.repository.id === r.id}- disabled={save.isPending}- onSelect={() => {- const choice = {- installationId: installation.id,- repository: r,- }- if (current) setPending(choice)- else save.mutate(choice)- }}+ <span className="flex min-w-0 items-center gap-2">+ <GithubMark className="text-muted-foreground size-3.5 shrink-0" />+ {shown ? (+ <span className="truncate font-medium">{fullName(shown)}</span>+ ) : (+ <span className="text-muted-foreground">+ Select a repository+ </span>+ )}+ {shown && 'private' in shown && shown.private ? (+ <Lock+ className="text-muted-foreground size-3 shrink-0"+ aria-label="Private"+ />+ ) : null}+ </span>+ {save.isPending ? (+ <Loader2+ className="text-muted-foreground size-3.5 animate-spin"+ aria-label="Saving"/>- ))}- {installation.truncated ? (- <li className="text-muted-foreground px-3 py-2 text-xs">- Only the first {installation.repositories.length} repositories- are listed.- </li>- ) : null}- </ul>- )}- </div>- <div className="flex flex-wrap items-center justify-between gap-2">- {installation ? (- <MissingRepository installation={installation} />- ) : (- <span />- )}- {onCancel ? (- <Button type="button" size="sm" variant="ghost" onClick={onCancel}>- Cancel+ ) : (+ <ChevronsUpDown+ className="text-muted-foreground size-3.5"+ aria-hidden+ />+ )}</Button>- ) : null}- </div>+ </PopoverTrigger>+ <PopoverContent+ className="w-(--radix-popover-trigger-width) rounded-lg border p-0 shadow-md ring-0"+ // The search takes focus, not the first link.+ onOpenAutoFocus={(e) => e.preventDefault()}+ >+ <RepositoryList+ current={current}+ installations={list.data}+ loading={list.isPending}+ failed={list.isError && !list.data}+ fetching={list.isFetching}+ onRefresh={() => void list.refetch()}+ onChoose={choose}+ />+ </PopoverContent>+ </Popover>{current ? (<ConfirmDialogopen={pending !== null}- onOpenChange={(open) => !open && setPending(null)}- title={`Switch the board to ${pending ? `${pending.repository.owner}/${pending.repository.name}` : ''}?`}+ onOpenChange={(o) => !o && !save.isPending && setPending(null)}+ title={`Switch the board to ${pending ? fullName(pending.repository) : ''}?`}description={<>The board is rebuilt from{' '}- {pending- ? `${pending.repository.owner}/${pending.repository.name}`- : ''}{' '}- on its {pending?.repository.defaultBranch} branch, and the items- in {repositoryName(current)} stop showing here. Nothing is deleted- or changed in either repository, and you can switch back.+ {pending ? fullName(pending.repository) : ''} on its{' '}+ {pending?.repository.defaultBranch} branch, and the items in{' '}+ {fullName(current)} stop showing here. Nothing is deleted or+ changed in either repository, and you can switch back.</>}confirmLabel="Switch"@@ -308,84 +290,284 @@ export function RepositoryPicker({onConfirm={() => pending && save.mutate(pending)}/>) : null}- </div>+ </>)}-type Choice = { installationId: string; repository: GrantedRepository }--function RepositoryRow({- repository: r,- selected,- saving,- disabled,- onSelect,+/** The popover's body: search, the grouped list, and the access footer. */+function RepositoryList({+ current,+ installations,+ loading,+ failed,+ fetching,+ onRefresh,+ onChoose,}: {- repository: GrantedRepository- selected: boolean- saving: boolean- disabled: boolean- onSelect: () => void+ current: Repository | null+ installations: GrantingInstallation[] | undefined+ loading: boolean+ failed: boolean+ fetching: boolean+ onRefresh: () => void+ onChoose: (c: Choice) => void}) {- return (- <li className="flex items-center gap-3 px-3 py-2">- <span className="flex min-w-0 flex-1 items-center gap-1.5">- <span className="truncate font-medium">{r.name}</span>- {r.private ? (- <Lock- className="text-muted-foreground size-3 shrink-0"- aria-label="Private"- />- ) : null}- </span>- {r.pushedAt ? (- <span- className="text-muted-foreground shrink-0 text-xs tabular-nums"- title={new Date(r.pushedAt).toLocaleString()}- >- {relativeTime(r.pushedAt)}- </span>- ) : null}- {selected ? (- <span className="text-muted-foreground inline-flex h-7 w-20 shrink-0 items-center justify-center gap-1 text-[0.8rem]">- <Check className="size-3.5" aria-hidden />- Selected- </span>- ) : (- <Button+ const listId = useId()+ const searchRef = useRef<HTMLInputElement>(null)+ const [q, setQ] = useState('')+ const needle = q.trim().toLowerCase()+ const all = installations ?? []+ const grouped = all.length > 1+ const groups = all.map((installation) => ({+ installation,+ rows: installation.repositories.filter((r) =>+ r.name.toLowerCase().includes(needle),+ ),+ }))+ const options: Choice[] = groups.flatMap((g) =>+ g.rows.map((repository) => ({+ installationId: g.installation.id,+ repository,+ })),+ )+ const optionId = (c: Choice) =>+ `${listId}-${c.installationId}-${c.repository.id}`++ // The active row starts on the current choice, then follows the keys and+ // the pointer; a new search starts again at the top.+ const [active, setActive] = useState<number | null>(null)+ const start = Math.max(+ 0,+ options.findIndex((c) => sameRepository(current, c)),+ )+ const at =+ options.length === 0+ ? -1+ : Math.min(active ?? (needle ? 0 : start), options.length - 1)+ const activeId = at >= 0 ? optionId(options[at]) : undefined++ useEffect(() => {+ searchRef.current?.focus()+ }, [])+ useEffect(() => {+ if (activeId) {+ document.getElementById(activeId)?.scrollIntoView?.({ block: 'nearest' })+ }+ }, [activeId])++ const onKeyDown = (e: KeyboardEvent<HTMLInputElement>) => {+ if (options.length === 0) return+ const move = (to: number) => {+ e.preventDefault()+ setActive((to + options.length) % options.length)+ }+ if (e.key === 'ArrowDown') move(at + 1)+ else if (e.key === 'ArrowUp') move(at - 1)+ else if (e.key === 'Home') move(0)+ else if (e.key === 'End') move(options.length - 1)+ else if (e.key === 'Enter' && at >= 0) {+ e.preventDefault()+ onChoose(options[at])+ }+ }++ const indexOf = new Map(options.map((c, n) => [optionId(c), n]))+ let body+ if (loading) {+ body = (+ <p+ role="status"+ className="text-muted-foreground flex items-center justify-center gap-2 px-3 py-8 text-sm"+ >+ <Loader2 className="size-4 animate-spin" aria-hidden />+ Loading repositories…+ </p>+ )+ } else if (failed) {+ body = (+ <p className="text-muted-foreground px-3 py-8 text-center text-sm">+ Could not load repositories ·{' '}+ <buttontype="button"- size="sm"- variant="outline"- className="w-20 shrink-0"- onClick={onSelect}- disabled={disabled}- aria-label={`Select ${r.name}`}+ onClick={onRefresh}+ className="text-foreground underline underline-offset-4">- {saving ? <Loader2 className="animate-spin" /> : null}- Select- </Button>- )}- </li>+ Try again+ </button>+ </p>+ )+ } else {+ body = (+ <div id={listId} role="listbox" aria-label="Repositories">+ {groups.map(({ installation: i, rows }) => {+ // While searching, an account with nothing matching steps aside.+ if (needle && rows.length === 0) return null+ return (+ <div+ key={i.id}+ role="group"+ aria-label={i.accountLogin}+ className="not-first:mt-1"+ >+ {grouped ? (+ // Indented to the names, past the check's slot.+ <div className="text-muted-foreground flex h-7 items-center justify-between gap-2 pr-2 pl-8 text-xs">+ <span className="truncate font-medium">{i.accountLogin}</span>+ <AccessLink installation={i}>Adjust access</AccessLink>+ </div>+ ) : null}+ {i.problem ? (+ <p className="text-muted-foreground py-1.5 pr-2 pl-8 text-xs">+ {i.problemMessage ??+ `GitHub would not list the repositories of ${i.accountLogin}.`}+ </p>+ ) : i.repositories.length === 0 ? (+ <p className="text-muted-foreground py-1.5 pr-2 pl-8 text-xs">+ The GitHub App cannot reach any repository of {i.accountLogin}{' '}+ yet.+ </p>+ ) : null}+ {rows.map((r) => {+ const c = { installationId: i.id, repository: r }+ const n = indexOf.get(optionId(c)) ?? -1+ const selected = sameRepository(current, c)+ return (+ <div+ key={r.id}+ id={optionId(c)}+ role="option"+ aria-selected={selected}+ data-active={n === at}+ // Keep the focus in the search while clicking.+ onMouseDown={(e) => e.preventDefault()}+ onMouseMove={() => n !== at && setActive(n)}+ onClick={() => onChoose(c)}+ // The keys work from the search (aria-activedescendant);+ // this is for a row that got focus some other way.+ tabIndex={-1}+ onKeyDown={(e) => e.key === 'Enter' && onChoose(c)}+ className="data-[active=true]:bg-muted flex h-8 cursor-pointer items-center gap-2 rounded-md px-2 text-sm"+ >+ <span className="flex size-4 shrink-0 items-center justify-center">+ {selected ? (+ <Check className="size-3.5" aria-hidden />+ ) : null}+ </span>+ <span className="truncate">{r.name}</span>+ {r.private ? (+ <Lock+ className="text-muted-foreground size-3 shrink-0"+ aria-label="Private"+ />+ ) : null}+ {r.pushedAt ? (+ <span+ className="text-muted-foreground ml-auto shrink-0 pl-3 text-xs tabular-nums"+ title={new Date(r.pushedAt).toLocaleString()}+ >+ {relativeTime(r.pushedAt)}+ </span>+ ) : null}+ </div>+ )+ })}+ {i.truncated && !needle ? (+ <p className="text-muted-foreground py-1.5 pr-2 pl-8 text-xs">+ Only the first {i.repositories.length} repositories are+ listed.+ </p>+ ) : null}+ </div>+ )+ })}+ {needle && options.length === 0 ? (+ <p className="text-muted-foreground px-3 py-6 text-center text-sm">+ No repository matches “{q.trim()}”.+ </p>+ ) : null}+ </div>+ )+ }++ return (+ <div className="flex flex-col">+ {/* The search's icon sits in the check's column of the rows. */}+ <div className="flex items-center gap-2 border-b px-3">+ <Search+ className="text-muted-foreground size-3.5 shrink-0"+ aria-hidden+ />+ <input+ ref={searchRef}+ value={q}+ onChange={(e) => {+ setQ(e.target.value)+ setActive(null)+ }}+ onKeyDown={onKeyDown}+ placeholder="Search repositories"+ aria-label="Search repositories"+ role="combobox"+ aria-expanded+ aria-controls={listId}+ aria-autocomplete="list"+ aria-activedescendant={activeId}+ autoComplete="off"+ spellCheck={false}+ className="placeholder:text-muted-foreground h-9 min-w-0 flex-1 bg-transparent text-sm outline-none"+ />+ </div>+ <div className="max-h-[260px] overflow-y-auto p-1">{body}</div>+ {all.length > 0 ? (+ // One line always: with several accounts their links are in the+ // group headers, and only Refresh is left here.+ <div className="text-muted-foreground flex h-9 items-center justify-between gap-2 border-t pr-1 pl-3 text-xs whitespace-nowrap">+ {grouped ? (+ <span />+ ) : (+ <p className="min-w-0 truncate">+ Missing a repository?{' '}+ <AccessLink installation={all[0]}>+ Adjust GitHub App access+ </AccessLink>+ </p>+ )}+ <Button+ type="button"+ size="xs"+ variant="ghost"+ className="text-muted-foreground hover:text-foreground"+ onClick={onRefresh}+ disabled={fetching}+ aria-label={grouped ? undefined : 'Refresh the list'}+ title="Refresh the list"+ >+ <RefreshCw className={cn(fetching && 'animate-spin')} aria-hidden />+ {grouped ? 'Refresh' : null}+ </Button>+ </div>+ ) : null}+ </div>)}-function MissingRepository({+/** The installation's settings on GitHub, where access is granted. */+function AccessLink({installation,+ children,}: {installation: GrantingInstallation+ children: ReactNode}) {return (- <p className="text-muted-foreground text-xs">- Missing a repository?{' '}- <a- href={installation.settingsUrl}- target="_blank"- rel="noreferrer"- className="hover:text-foreground inline-flex items-center gap-0.5 underline underline-offset-4"- >- Adjust GitHub App access- <ExternalLink className="size-3" aria-hidden />- </a>- </p>+ <a+ href={installation.settingsUrl}+ target="_blank"+ rel="noreferrer"+ className="text-foreground/80 hover:text-foreground inline-flex items-center gap-0.5 underline-offset-4 hover:underline"+ >+ {children}+ <ExternalLink className="size-3" aria-hidden />+ </a>)}diff --git a/web/src/managed-agents/work/screens.test.tsx b/web/src/managed-agents/work/screens.test.tsxindex ecce9187..56b121f1 100644--- a/web/src/managed-agents/work/screens.test.tsx+++ b/web/src/managed-agents/work/screens.test.tsx@@ -105,10 +105,15 @@ async function render(url: string) {}// Flushes until nothing is loading (the repository setting loads in two-// steps: the choice, then the picker's list).+// steps: the choice, then the picker's list, which is in a popover outside+// the container).async function settle() {await flush()- for (let i = 0; i < 50 && container.querySelector('[role="status"]'); i++) {+ for (+ let i = 0;+ i < 50 && document.body.querySelector('[role="status"]');+ i+++ ) {await flush()}await flush()@@ -242,9 +247,11 @@ describe('board', () => {openPage([], { repository: null, head: null, asOf: null }),)workApi.getRepository.mockResolvedValue(null)+ workApi.getRepositories.mockResolvedValue([acme])await render('/computer/work')expect(container.textContent).toContain('An item is a working doc')- expect(container.textContent).toContain('Knowledge repository')+ expect(container.textContent).toContain('Choose the knowledge repository')+ expect(trigger()?.textContent).toContain('Select a repository')expect(workApi.getClosedItems).not.toHaveBeenCalled()})@@ -271,7 +278,8 @@ describe('board', () => {workApi.putRepository.mockResolvedValue(repository)await render('/computer/work')workApi.getOpenItems.mockResolvedValue(openPage(items))- click(container.querySelector('button[aria-label="Select knowledge"]'))+ await openPicker()+ click(option('knowledge'))await settle()// No confirmation for a first choice.expect(workApi.putRepository).toHaveBeenCalledTimes(1)@@ -499,10 +507,29 @@ const acme = {problemMessage: null,}-function rows() {- return [...container.querySelectorAll('ul[aria-label="Repositories"] li')]- .map((li) => li.querySelector('.font-medium')?.textContent)- .filter(Boolean)+const trigger = () =>+ container.querySelector<HTMLButtonElement>('button[aria-haspopup="listbox"]')++async function openPicker() {+ click(trigger())+ await settle()+}++// The options of the open picker, by name (it portals to the body).+const options = () => [...document.body.querySelectorAll('[role="option"]')]+const rows = () =>+ options().map((o) => o.querySelector('.truncate')?.textContent)+const option = (name: string) =>+ options().find((o) => o.querySelector('.truncate')?.textContent === name)+const search = () =>+ document.body.querySelector<HTMLInputElement>(+ 'input[aria-label="Search repositories"]',+ )!++function key(el: Element, k: string) {+ act(() => {+ el.dispatchEvent(new KeyboardEvent('keydown', { key: k, bubbles: true }))+ })}function type(el: HTMLInputElement, value: string) {@@ -518,34 +545,62 @@ describe('repository picker', () => {workApi.getRepositories.mockResolvedValue([acme])})- it('lists what GitHub grants, in the order the server sends', async () => {+ it('shows Select a repository, and lists what GitHub grants on open', async () => {workApi.getRepository.mockResolvedValue(null)await render('/computer')+ expect(trigger()?.textContent).toContain('Select a repository')+ await openPicker()expect(rows()).toEqual(['app', 'knowledge', 'website'])- expect(container.querySelector('[aria-label="Private"]')).not.toBeNull()- expect(container.textContent).toContain('5 min ago')- // One installation: no account select.- expect(container.querySelector('#work-repo-account')).toBeNull()- const access = [...container.querySelectorAll('a')].find((a) =>+ expect(document.activeElement).toBe(search())+ expect(+ option('app')?.querySelector('[aria-label="Private"]'),+ ).not.toBeNull()+ expect(option('app')?.textContent).toContain('5 min ago')+ // One installation: no account headings, one access link.+ expect(+ document.body.querySelector('[role="group"]')?.textContent,+ ).not.toContain('acme/')+ const access = [...document.body.querySelectorAll('a')].find((a) =>a.textContent?.includes('Adjust GitHub App access'),)expect(access?.getAttribute('href')).toBe(acme.settingsUrl)expect(access?.getAttribute('target')).toBe('_blank')})+ it('groups by account when several installations grant', async () => {+ workApi.getRepository.mockResolvedValue(null)+ workApi.getRepositories.mockResolvedValue([+ acme,+ {+ ...acme,+ id: '2',+ accountLogin: 'acme-labs',+ repositories: [],+ problem: 'installation_suspended',+ problemMessage: 'The installation is suspended.',+ },+ ])+ await render('/computer')+ await openPicker()+ const groups = [...document.body.querySelectorAll('[role="group"]')]+ expect(groups.map((g) => g.getAttribute('aria-label'))).toEqual([+ 'acme',+ 'acme-labs',+ ])+ expect(groups[1].textContent).toContain('The installation is suspended.')+ })+it('filters by name as you type', async () => {workApi.getRepository.mockResolvedValue(null)await render('/computer')- const search = container.querySelector<HTMLInputElement>(- 'input[aria-label="Search repositories"]',- )!- type(search, 'WEB')+ await openPicker()+ type(search(), 'WEB')expect(rows()).toEqual(['website'])- type(search, 'nothing')- expect(container.textContent).toContain('No repository matches')+ type(search(), 'nothing')+ expect(document.body.textContent).toContain('No repository matches')})- it('saves a selected repository on its default branch', async () => {+ it('saves a clicked repository on its default branch, without asking', async () => {workApi.getRepository.mockResolvedValue(null)workApi.putRepository.mockResolvedValue({...repository,@@ -553,8 +608,10 @@ describe('repository picker', () => {branch: 'trunk',})await render('/computer')- click(container.querySelector('button[aria-label="Select website"]'))+ await openPicker()+ click(option('website'))await flush()+ expect(document.body.querySelector('[role="alertdialog"]')).toBeNull()expect(workApi.putRepository).toHaveBeenCalledWith({installationId: '1',owner: 'acme',@@ -563,27 +620,39 @@ describe('repository picker', () => {})})- it('marks the current choice on Change, and Cancel goes back', async () => {+ it('chooses with the arrow keys and Enter', async () => {+ workApi.getRepository.mockResolvedValue(null)+ workApi.putRepository.mockResolvedValue(repository)+ await render('/computer')+ await openPicker()+ key(search(), 'ArrowDown')+ expect(search().getAttribute('aria-activedescendant')).toBe(+ option('knowledge')?.id,+ )+ key(search(), 'Enter')+ await flush()+ expect(options()).toEqual([])+ expect(workApi.putRepository).toHaveBeenCalledWith({+ installationId: '1',+ owner: 'acme',+ name: 'knowledge',+ branch: 'main',+ })+ })++ it('reads the list only when wanted, and checks the current one', async () => {workApi.getRepository.mockResolvedValue(repository)await render('/computer')expect(workApi.getRepositories).not.toHaveBeenCalled()- click(- [...container.querySelectorAll('button')].find(- (b) => b.textContent === 'Change',- ),- )- await settle()- const knowledge = [- ...container.querySelectorAll('ul[aria-label="Repositories"] li'),- ].find((li) => li.textContent?.includes('knowledge'))!- expect(knowledge.textContent).toContain('Selected')- expect(knowledge.querySelector('button')).toBeNull()- click(- [...container.querySelectorAll('button')].find(- (b) => b.textContent === 'Cancel',- ),- )- expect(container.querySelector('ul[aria-label="Repositories"]')).toBeNull()+ expect(trigger()?.textContent).toContain('acme/knowledge')+ await openPicker()+ expect(option('knowledge')?.getAttribute('aria-selected')).toBe('true')+ expect(option('app')?.getAttribute('aria-selected')).toBe('false')+ // The same one again changes nothing.+ click(option('knowledge'))+ await flush()+ expect(workApi.putRepository).not.toHaveBeenCalled()+ expect(document.body.querySelector('[role="alertdialog"]')).toBeNull()})it('says when GitHub could not list, with a way to try again', async () => {@@ -592,12 +661,11 @@ describe('repository picker', () => {new ApiError('GitHub is unavailable', 503),)await render('/computer')- expect(container.textContent).toContain(- 'Could not load the repositories from GitHub.',- )+ await openPicker()+ expect(document.body.textContent).toContain('Could not load repositories')workApi.getRepositories.mockResolvedValue([acme])click(- [...container.querySelectorAll('button')].find(+ [...document.body.querySelectorAll('button')].find((b) => b.textContent === 'Try again',),)@@ -610,6 +678,7 @@ describe('repository picker', () => {workApi.getRepositories.mockResolvedValue([])await render('/computer')expect(button('Connect GitHub')).toBeTruthy()+ expect(trigger()).toBeNull()})it('confirms before switching from a set repository', async () => {@@ -617,9 +686,8 @@ describe('repository picker', () => {workApi.getOpenItems.mockResolvedValue(openPage([]))workApi.putRepository.mockResolvedValue({ ...repository, name: 'app' })await render('/computer')- click(button('Change'))- await settle()- click(container.querySelector('button[aria-label="Select app"]'))+ await openPicker()+ click(option('app'))await flush()expect(workApi.putRepository).not.toHaveBeenCalled()const dialog = document.body.querySelector('[role="alertdialog"]')!@@ -667,10 +735,12 @@ describe('knowledge repository section', () => {workApi.getRepository.mockResolvedValue(repository)await render('/computer')expect(container.querySelector('section#work-repository')).not.toBeNull()+ expect(trigger()?.textContent).toContain('acme/knowledge')expect(- container.querySelector('a[href="https://github.com/acme/knowledge"]')- ?.textContent,- ).toBe('acme/knowledge')+ container+ .querySelector('a[href="https://github.com/acme/knowledge"]')+ ?.getAttribute('aria-label'),+ ).toBe('Open acme/knowledge on GitHub')expect(container.textContent).toContain('main')expect(container.textContent).toContain('Up to date · read 2 min ago at 9f2c1a7',@@ -697,7 +767,7 @@ describe('knowledge repository section', () => {'The GitHub installation is not connected to this organization.',)expect(button('Reconnect GitHub')).toBeTruthy()- expect(button('Change')).toBeUndefined()+ expect(button('Choose another repository')).toBeTruthy()expect(container.textContent).not.toContain('installation_removed')})@@ -714,12 +784,23 @@ describe('knowledge repository section', () => {expect(rows()).toEqual(['app', 'knowledge', 'website'])})- it('says the branch is gone and offers Change', async () => {+ it('says the branch is gone, and choosing it again saves it', async () => {withProblem('branch_not_found')+ workApi.putRepository.mockResolvedValue(repository)await render('/computer')expect(container.textContent).toContain('The main branch is gone.')- expect(button('Change')).toBeTruthy()expect(workApi.getRepositories).not.toHaveBeenCalled()+ click(button('Choose again'))+ await settle()+ click(option('knowledge'))+ await flush()+ expect(document.body.querySelector('[role="alertdialog"]')).toBeNull()+ expect(workApi.putRepository).toHaveBeenCalledWith({+ installationId: '1',+ owner: 'acme',+ name: 'knowledge',+ branch: 'main',+ })})})