Skip to content

An open-source, faster Devin alternative

TypeScript

Work web: pick the repository from a searchable list instead of typing it

Igor Zalutski via Computer48b99d64e5a0
diff --git a/web/src/managed-agents/work/Board.tsx b/web/src/managed-agents/work/Board.tsx
index b6dc774b..5034d8bd 100644
--- a/web/src/managed-agents/work/Board.tsx
+++ b/web/src/managed-agents/work/Board.tsx
@@ -410,9 +410,21 @@ function IndexStatus({
<Loader2 className="size-3 animate-spin" aria-hidden />
Reading {repository}…
</span>
- ) : indexIsOld(asOf) ? (
- <span title={asOf ?? undefined}>As of {timeAgo(asOf)} ago</span>
- ) : null}
+ ) : (
+ <>
+ {/* Quiet: where the board reads from, and the way to change it. */}
+ <Link
+ to="/computer#work-repository"
+ title="Change the working docs repository"
+ className="hover:text-foreground"
+ >
+ {repository}
+ </Link>
+ {indexIsOld(asOf) ? (
+ <span title={asOf ?? undefined}>· As of {timeAgo(asOf)} ago</span>
+ ) : null}
+ </>
+ )}
</p>
)
}
diff --git a/web/src/managed-agents/work/RepositorySetting.tsx b/web/src/managed-agents/work/RepositorySetting.tsx
index 1562020f..10930968 100644
--- a/web/src/managed-agents/work/RepositorySetting.tsx
+++ b/web/src/managed-agents/work/RepositorySetting.tsx
@@ -1,16 +1,27 @@
-import { useState, type FormEvent } from 'react'
+import { useState } from 'react'
import { Link } from 'react-router-dom'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
-import { Loader2 } from 'lucide-react'
-import { Field, Input, Select } from '@/components/form'
+import {
+ Check,
+ ExternalLink,
+ Loader2,
+ Lock,
+ RefreshCw,
+ Search,
+} from 'lucide-react'
+import { Input, Select } from '@/components/form'
import { Button } from '@/components/ui/button'
import { notifyError, notifySuccess } from '@/lib/errors'
-import { computerQueryKey, getComputer } from '../computer-api'
+import { cn } from '@/lib/utils'
+import { relativeTime } from '../computer-state'
import {
+ getRepositories,
getRepository,
putRepository,
useOrg,
workKeys,
+ type GrantedRepository,
+ type GrantingInstallation,
type Repository,
} from './api'
import { repositoryName, repositoryProblem } from './board'
@@ -28,8 +39,8 @@ export function WorkRepositorySetting({ id }: { id?: string }) {
const current = repository.data ?? null
return (
- <section id={id} aria-labelledby="work-repository">
- <h2 id="work-repository" className="mb-3 text-sm font-semibold">
+ <section id={id} aria-labelledby="work-repository-title">
+ <h2 id="work-repository-title" className="mb-3 text-sm font-semibold">
Working docs
</h2>
<div className="bg-panel rounded-lg border px-5 py-3 text-sm">
@@ -43,7 +54,7 @@ export function WorkRepositorySetting({ id }: { id?: string }) {
Working docs are not available here yet.
</p>
) : editing || !current ? (
- <RepositoryForm
+ <RepositoryPicker
current={current}
onDone={() => setEditing(false)}
onCancel={current ? () => setEditing(false) : undefined}
@@ -89,7 +100,16 @@ export function WorkRepositorySetting({ id }: { id?: string }) {
)
}
-function RepositoryForm({
+// About six rows show; the rest scroll.
+const LIST_HEIGHT = 'max-h-[16.5rem]'
+
+/**
+ * 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.
+ */
+function RepositoryPicker({
current,
onDone,
onCancel,
@@ -100,27 +120,31 @@ function RepositoryForm({
}) {
const qc = useQueryClient()
const org = useOrg()
- const computer = useQuery({
- queryKey: computerQueryKey,
- queryFn: getComputer,
+ const list = useQuery({
+ queryKey: workKeys.repositories(org),
+ queryFn: getRepositories,
+ refetchOnWindowFocus: 'always',
})
- const installations = computer.data?.github.installations ?? []
- const [installationId, setInstallationId] = useState(
- current ? String(current.installationId) : '',
- )
- const [name, setName] = useState(current?.name ?? '')
- const [branch, setBranch] = useState(current?.branch ?? 'main')
+ 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 === installationId) ??
- (installations.length === 1 ? installations[0] : undefined)
+ installations.find((i) => i.id === want) ?? installations[0]
const save = useMutation({
- mutationFn: () =>
+ mutationFn: ({
+ installationId,
+ repository: r,
+ }: {
+ installationId: string
+ repository: GrantedRepository
+ }) =>
putRepository({
- installationId: installation!.id,
- owner: installation!.accountLogin,
- name: name.trim(),
- branch: branch.trim() || 'main',
+ installationId,
+ owner: r.owner,
+ name: r.name,
+ branch: r.defaultBranch,
}),
onSuccess: (repository) => {
qc.setQueryData(workKeys.repository(org), repository)
@@ -130,12 +154,8 @@ function RepositoryForm({
},
onError: (e) => notifyError('Could not save the repository', e),
})
- const submit = (e: FormEvent) => {
- e.preventDefault()
- if (installation && name.trim()) save.mutate()
- }
- if (computer.isSuccess && installations.length === 0) {
+ if (list.isSuccess && installations.length === 0) {
return (
<div className="flex flex-wrap items-center justify-between gap-3">
<p className="text-muted-foreground">
@@ -148,58 +168,221 @@ function RepositoryForm({
)
}
+ 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),
+ )
+
return (
- <form onSubmit={submit} className="space-y-3 py-1">
+ <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="grid gap-3 sm:grid-cols-[minmax(0,12rem)_minmax(0,20rem)_minmax(0,8rem)]">
- <Field label="GitHub account" htmlFor="work-repo-account">
- <Select
- id="work-repo-account"
- value={installation?.id ?? ''}
- onValueChange={setInstallationId}
- placeholder="Choose"
- options={installations.map((i) => ({
- value: i.id,
- label: i.accountLogin,
- }))}
- />
- </Field>
- <Field label="Repository" htmlFor="work-repo-name">
- <Input
- id="work-repo-name"
- value={name}
- onChange={(e) => setName(e.target.value)}
- placeholder="knowledge"
- autoComplete="off"
+ <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
/>
- </Field>
- <Field label="Branch" htmlFor="work-repo-branch">
<Input
- id="work-repo-branch"
- value={branch}
- onChange={(e) => setBranch(e.target.value)}
+ 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"
/>
- </Field>
- </div>
- <div className="flex gap-2">
+ </div>
<Button
- type="submit"
- size="sm"
- disabled={!installation || !name.trim() || save.isPending}
+ type="button"
+ size="icon"
+ variant="outline"
+ onClick={() => void list.refetch()}
+ disabled={list.isFetching}
+ aria-label="Refresh the list"
+ title="Refresh the list"
>
- {save.isPending ? <Loader2 className="animate-spin" /> : null}
- Save
+ <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"
+ >
+ <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 &ldquo;{q.trim()}&rdquo;.
+ </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={() =>
+ save.mutate({
+ installationId: installation.id,
+ repository: r,
+ })
+ }
+ />
+ ))}
+ {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
</Button>
) : null}
</div>
- </form>
+ </div>
+ )
+}
+
+function RepositoryRow({
+ repository: r,
+ selected,
+ saving,
+ disabled,
+ onSelect,
+}: {
+ repository: GrantedRepository
+ selected: boolean
+ saving: boolean
+ disabled: boolean
+ onSelect: () => 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
+ type="button"
+ size="sm"
+ variant="outline"
+ className="w-20 shrink-0"
+ onClick={onSelect}
+ disabled={disabled}
+ aria-label={`Select ${r.name}`}
+ >
+ {saving ? <Loader2 className="animate-spin" /> : null}
+ Select
+ </Button>
+ )}
+ </li>
+ )
+}
+
+function MissingRepository({
+ installation,
+}: {
+ installation: GrantingInstallation
+}) {
+ 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>
)
}
diff --git a/web/src/managed-agents/work/screens.test.tsx b/web/src/managed-agents/work/screens.test.tsx
index dce30c20..79d87d01 100644
--- a/web/src/managed-agents/work/screens.test.tsx
+++ b/web/src/managed-agents/work/screens.test.tsx
@@ -16,20 +16,16 @@ const workApi = vi.hoisted(() => ({
getHistory: vi.fn(),
getRepository: vi.fn(),
putRepository: vi.fn(),
+ getRepositories: vi.fn(),
}))
vi.mock('./api', async (importOriginal) => ({
...(await importOriginal<typeof import('./api')>()),
...workApi,
}))
-vi.mock('../computer-api', async (importOriginal) => ({
- ...(await importOriginal<typeof import('../computer-api')>()),
- getComputer: vi.fn().mockResolvedValue({
- github: { installations: [{ id: '1', accountLogin: 'acme' }] },
- }),
-}))
const { Board } = await import('./Board')
const { ItemView } = await import('./Item')
+const { WorkRepositorySetting } = await import('./RepositorySetting')
const repository = {
installationId: '1',
@@ -95,12 +91,20 @@ async function render(url: string) {
<Routes>
<Route path="/computer/work" element={<Board />} />
<Route path="/computer/work/:number" element={<ItemView />} />
+ <Route path="/computer" element={<WorkRepositorySetting />} />
</Routes>
</MemoryRouter>
</QueryClientProvider>
</AuthContext.Provider>,
)
})
+ await settle()
+}
+
+// Flushes until nothing is loading (the repository setting loads in two
+// steps: the choice, then the picker's list).
+async function settle() {
+ await flush()
for (let i = 0; i < 50 && container.querySelector('[role="status"]'); i++) {
await flush()
}
@@ -247,6 +251,15 @@ describe('board', () => {
expect(container.textContent).toContain('The board is not available yet')
})
+ it('names the repository it reads, quietly linked to settings', async () => {
+ workApi.getOpenItems.mockResolvedValue(openPage(items))
+ await render('/computer/work')
+ expect(
+ container.querySelector('a[href="/computer#work-repository"]')
+ ?.textContent,
+ ).toBe('acme/knowledge')
+ })
+
it('sends a repository problem to settings', async () => {
workApi.getOpenItems.mockResolvedValue(
openPage(items, {
@@ -437,3 +450,149 @@ describe('item page', () => {
expect(container.textContent).not.toContain('No item')
})
})
+
+const granted = (
+ name: string,
+ pushedAt: string | null,
+ over: Record<string, unknown> = {},
+) => ({
+ id: name.length,
+ owner: 'acme',
+ name,
+ private: false,
+ defaultBranch: 'main',
+ pushedAt,
+ ...over,
+})
+const acme = {
+ id: '1',
+ accountLogin: 'acme',
+ accountType: 'Organization',
+ settingsUrl:
+ 'https://github.com/organizations/acme/settings/installations/41',
+ repositories: [
+ granted('app', minutesAgo(5), { private: true }),
+ granted('knowledge', minutesAgo(180)),
+ granted('website', minutesAgo(4000), { defaultBranch: 'trunk' }),
+ ],
+ truncated: false,
+ problem: null,
+ problemMessage: null,
+}
+
+function rows() {
+ return [...container.querySelectorAll('ul[aria-label="Repositories"] li')]
+ .map((li) => li.querySelector('.font-medium')?.textContent)
+ .filter(Boolean)
+}
+
+function type(el: HTMLInputElement, value: string) {
+ act(() => {
+ // Through the prototype's setter, so React sees a change.
+ Reflect.set(HTMLInputElement.prototype, 'value', value, el)
+ el.dispatchEvent(new Event('input', { bubbles: true }))
+ })
+}
+
+describe('repository picker', () => {
+ beforeEach(() => {
+ workApi.getRepositories.mockResolvedValue([acme])
+ })
+
+ it('lists what GitHub grants, in the order the server sends', async () => {
+ workApi.getRepository.mockResolvedValue(null)
+ await render('/computer')
+ 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) =>
+ a.textContent?.includes('Adjust GitHub App access'),
+ )
+ expect(access?.getAttribute('href')).toBe(acme.settingsUrl)
+ expect(access?.getAttribute('target')).toBe('_blank')
+ })
+
+ 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')
+ expect(rows()).toEqual(['website'])
+ type(search, 'nothing')
+ expect(container.textContent).toContain('No repository matches')
+ })
+
+ it('saves a selected repository on its default branch', async () => {
+ workApi.getRepository.mockResolvedValue(null)
+ workApi.putRepository.mockResolvedValue({
+ ...repository,
+ name: 'website',
+ branch: 'trunk',
+ })
+ await render('/computer')
+ click(container.querySelector('button[aria-label="Select website"]'))
+ await flush()
+ expect(workApi.putRepository).toHaveBeenCalledWith({
+ installationId: '1',
+ owner: 'acme',
+ name: 'website',
+ branch: 'trunk',
+ })
+ })
+
+ it('marks the current choice on Change, and Cancel goes back', 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()
+ })
+
+ it('says when GitHub could not list, with a way to try again', async () => {
+ workApi.getRepository.mockResolvedValue(null)
+ workApi.getRepositories.mockRejectedValue(
+ new ApiError('GitHub is unavailable', 503),
+ )
+ await render('/computer')
+ expect(container.textContent).toContain(
+ 'Could not load the repositories from GitHub.',
+ )
+ workApi.getRepositories.mockResolvedValue([acme])
+ click(
+ [...container.querySelectorAll('button')].find(
+ (b) => b.textContent === 'Try again',
+ ),
+ )
+ await settle()
+ expect(rows()).toEqual(['app', 'knowledge', 'website'])
+ })
+
+ it('asks to connect GitHub when no installation grants anything', async () => {
+ workApi.getRepository.mockResolvedValue(null)
+ workApi.getRepositories.mockResolvedValue([])
+ await render('/computer')
+ expect(
+ container.querySelector('a[href="/managed-agents/connections"]')
+ ?.textContent,
+ ).toBe('Connect GitHub')
+ })
+})