An open-source, faster Devin alternative
TypeScript
Work web: a self-contained knowledge repository section with its state, a switch confirmation and a fix per problem
Igor Zalutski via Computerdebdc8852db2
diff --git a/web/src/api/mock-work.ts b/web/src/api/mock-work.tsindex 63481232..03fdde01 100644--- a/web/src/api/mock-work.ts+++ b/web/src/api/mock-work.ts@@ -413,6 +413,24 @@ function scenario() {: new URLSearchParams(window.location.search).get('work')}+// `?work=problem` reads `&problem=<code>` from the page's address (default+// access_denied); access_denied comes with the server's own sentence, the+// others with none, so the web's own words show.+function problemOf() {+ const code =+ (typeof window === 'undefined'+ ? null+ : new URLSearchParams(window.location.search).get('problem')) ??+ 'access_denied'+ return {+ problem: code,+ problemMessage:+ code === 'access_denied'+ ? "The installation cannot read the repository's contents."+ : null,+ }+}+// Returns undefined for paths it does not serve.export function workMock(path: string,@@ -429,12 +447,7 @@ export function workMock(s === 'none'? null: s === 'problem' && repository- ? {- ...repository,- problem: 'access_denied',- problemMessage:- "The installation cannot read the repository's contents.",- }+ ? { ...repository, ...problemOf() }: repositoryif (rest === '/repository') {diff --git a/web/src/managed-agents/Computer.tsx b/web/src/managed-agents/Computer.tsxindex f768d0a4..f7d72fb0 100644--- a/web/src/managed-agents/Computer.tsx+++ b/web/src/managed-agents/Computer.tsx@@ -59,7 +59,7 @@ import { GitHubStarBonus } from './GitHubStarBonus'import { launchAuthorizationWindow } from './authorization-window'import { SlackInstallButton, UnlinkSlackDialog } from './computer-slack'import { createSession } from './computer-sessions-api'-import { WorkRepositorySetting } from './work/RepositorySetting'+import { KnowledgeRepositorySection } from './work/KnowledgeRepository'import { ChatTextarea } from '@/components/chat-textarea'import {AgentCard,@@ -292,7 +292,7 @@ function ComputerPageContent() {failed={sessions.isError}/><AgentCard status={status.data} />- <WorkRepositorySetting id="work-repository" />+ <KnowledgeRepositorySection id="work-repository" /><IdeasToTry /></div></WithDeveloperFooter>diff --git a/web/src/managed-agents/work/Board.tsx b/web/src/managed-agents/work/Board.tsxindex 5034d8bd..dd433cef 100644--- a/web/src/managed-agents/work/Board.tsx+++ b/web/src/managed-agents/work/Board.tsx@@ -1,10 +1,6 @@import { useContext, type ReactNode } from 'react'import { Link, Navigate, useSearchParams } from 'react-router-dom'-import {- useInfiniteQuery,- useQuery,- useQueryClient,-} from '@tanstack/react-query'+import { useInfiniteQuery } from '@tanstack/react-query'import {FileText,Loader2,@@ -20,19 +16,10 @@ import { Switch } from '@/components/ui/switch'import { AuthContext } from '@/hooks/useAuth'import { cn } from '@/lib/utils'import { timeAgo } from '../computer-sessions/transcript'-import {- getClosedItems,- getOpenItems,- keepOpenItems,- useOrg,- workKeys,- type Item,- type OpenItemsPoll,-} from './api'+import { getClosedItems, useOrg, workKeys, type Item } from './api'import {closedShown,indexIsOld,- OPEN_POLL_MS,inProgress,matches,plural,@@ -51,7 +38,8 @@ import {UnpublishedMark,WarningMark,} from './parts'-import { WorkRepositorySetting } from './RepositorySetting'+import { useOpenItems } from './queries'+import { FirstRepository } from './RepositorySetting'// The board (ux-spec 4): tracked items in three columns, Mine or Everyone.// Read-only for now; Close and Reopen arrive with build step 5.@@ -63,25 +51,6 @@ export default function BoardPage() {return <Board />}-function useOpenItems() {- const qc = useQueryClient()- const key = workKeys.open(useOrg())- return useQuery({- queryKey: key,- queryFn: async () => {- const prev = qc.getQueryData<OpenItemsPoll>(key)- const next = await getOpenItems(prev?.etag ?? null)- if (prev) return keepOpenItems(prev, next)- if (!('notModified' in next)) return next- // A 304 with nothing cached cannot happen (no ETag was sent); ask again.- return (await getOpenItems(null)) as OpenItemsPoll- },- refetchInterval: OPEN_POLL_MS,- retry: (count, error) =>- !(error instanceof ApiError && error.status === 404) && count < 2,- })-}-export function Board() {const org = useOrg()const [params, setParams] = useSearchParams()@@ -155,7 +124,7 @@ export function Board() {/></Panel><div className="mt-8">- <WorkRepositorySetting />+ <FirstRepository /></div></BoardFrame>)diff --git a/web/src/managed-agents/work/KnowledgeRepository.tsx b/web/src/managed-agents/work/KnowledgeRepository.tsxnew file mode 100644index 00000000..c01074b9--- /dev/null+++ b/web/src/managed-agents/work/KnowledgeRepository.tsx@@ -0,0 +1,262 @@+import { useState, type ReactNode } from 'react'+import { ExternalLink, Loader2 } from 'lucide-react'+import { ApiError } from '@/api/errors'+import { Button } from '@/components/ui/button'+import { relativeTime } from '../computer-state'+import type { Repository } from './api'+import { repositoryName, repositoryProblem } from './board'+import {+ useGrantingInstallations,+ useOpenItems,+ useRepository,+} from './queries'+import { ConnectGitHubButton, RepositoryPicker } 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.++/** `id` goes on the section, as a link target. */+export function KnowledgeRepositorySection({ id }: { id?: string }) {+ const repository = useRepository()+ const [editing, setEditing] = useState(false)++ let body: ReactNode+ if (repository.isPending) {+ body = (+ <p role="status" className="text-muted-foreground flex items-center">+ <Loader2 className="size-4 animate-spin" aria-label="Loading" />+ </p>+ )+ } 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>+ )+ } else if (!repository.data) {+ body = <RepositoryPicker current={null} />+ } else if (editing) {+ body = (+ <RepositoryPicker+ current={repository.data}+ onDone={() => setEditing(false)}+ onCancel={() => setEditing(false)}+ />+ )+ } else {+ body = (+ <Current repository={repository.data} onChange={() => setEditing(true)} />+ )+ }++ 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>+ )+}++/** How fresh the board's reading is, from the open-items poll. */+function ReadState({ repository: r }: { repository: Repository }) {+ const open = useOpenItems()+ const page = open.data?.page+ if (!page) return <span className="text-muted-foreground">…</span>+ if (page.building) {+ return (+ <span className="inline-flex items-center gap-1.5">+ <Loader2+ className="text-muted-foreground size-3.5 animate-spin"+ aria-hidden+ />+ Reading the working docs for the first time…+ </span>+ )+ }+ if (!page.asOf) {+ return <span className="text-muted-foreground">Not read yet</span>+ }+ return (+ <span>+ Up to date+ <span className="text-muted-foreground">+ {' '}+ · read{' '}+ <span className="tabular-nums" title={page.asOf}>+ {relativeTime(page.asOf)}+ </span>+ {page.head ? (+ <>+ {' '}+ at{' '}+ <a+ href={`https://github.com/${r.owner}/${r.name}/commit/${page.head}`}+ target="_blank"+ rel="noreferrer"+ className="hover:text-foreground font-mono text-xs"+ >+ {page.head.slice(0, 7)}+ </a>+ </>+ ) : null}+ </span>+ </span>+ )+}++/**+ * The one action that fixes the problem, by the server's code (its+ * RepositoryProblem): reconnect a lost installation, grant access to a+ * repository it no longer reaches, or choose again.+ */+function Fix({+ repository: r,+ onChange,+}: {+ repository: Repository+ onChange: () => void+}) {+ const code = r.problem ?? ''+ const needsAccess =+ code === 'repository_not_found' || code === 'access_denied'+ // Only the access fix needs the installation's settings page.+ const installations = useGrantingInstallations(needsAccess)+ const settingsUrl = installations.data?.find(+ (i) => i.id === String(r.installationId),+ )?.settingsUrl++ if (code === 'installation_removed' || code === 'installation_suspended') {+ return (+ <Actions+ hint={+ code === 'installation_suspended'+ ? 'Unsuspend the GitHub App, or connect it again, then come back.'+ : 'Connect the GitHub App again, then come back.'+ }+ >+ <ConnectGitHubButton label="Reconnect GitHub" variant="default" />+ <Button size="sm" variant="ghost" onClick={onChange}>+ Choose another repository+ </Button>+ </Actions>+ )+ }+ if (needsAccess) {+ return (+ <Actions hint="Grant the GitHub App this repository again, or pick another one.">+ {settingsUrl ? (+ <Button size="sm" asChild>+ <a href={settingsUrl} target="_blank" rel="noreferrer">+ Adjust GitHub App access+ <ExternalLink aria-hidden />+ </a>+ </Button>+ ) : null}+ <Button+ size="sm"+ variant={settingsUrl ? 'outline' : 'default'}+ onClick={onChange}+ >+ Choose another repository+ </Button>+ </Actions>+ )+ }+ if (code === 'branch_not_found') {+ return (+ <Actions+ hint={`The ${r.branch} branch is gone. Choose the repository again to use its default branch.`}+ >+ <Button size="sm" onClick={onChange}>+ Change+ </Button>+ </Actions>+ )+ }+ if (code === 'github_app_not_configured') {+ return (+ <Actions 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>+ )+}++function Actions({ hint, children }: { hint?: string; children?: ReactNode }) {+ 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>+ )+}diff --git a/web/src/managed-agents/work/RepositorySetting.tsx b/web/src/managed-agents/work/RepositorySetting.tsxindex 10930968..e8a8db6d 100644--- a/web/src/managed-agents/work/RepositorySetting.tsx+++ b/web/src/managed-agents/work/RepositorySetting.tsx@@ -1,6 +1,5 @@import { useState } from 'react'-import { Link } from 'react-router-dom'-import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'+import { useMutation, useQueryClient } from '@tanstack/react-query'import {Check,ExternalLink,@@ -9,14 +8,16 @@ import {RefreshCw,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 { notifyError, notifySuccess } from '@/lib/errors'import { cn } from '@/lib/utils'+import { addManagedGitHubConnection } from '../api'+import { launchAuthorizationWindow } from '../authorization-window'import { relativeTime } from '../computer-state'import {- getRepositories,- getRepository,putRepository,useOrg,workKeys,@@ -24,82 +25,68 @@ import {type GrantingInstallation,type Repository,} from './api'-import { repositoryName, repositoryProblem } from './board'+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.-export function WorkRepositorySetting({ id }: { id?: string }) {- const org = useOrg()- const repository = useQuery({- queryKey: workKeys.repository(org),- queryFn: getRepository,- })- const [editing, setEditing] = useState(false)- const current = repository.data ?? null-+/** The board's empty state: choose the repository, and the board loads. */+export function FirstRepository() {return (- <section id={id} aria-labelledby="work-repository-title">+ <section aria-labelledby="work-repository-title"><h2 id="work-repository-title" className="mb-3 text-sm font-semibold">- Working docs+ Knowledge repository</h2><div className="bg-panel rounded-lg border px-5 py-3 text-sm">- {repository.isPending ? (- <Loader2- className="text-muted-foreground size-4 animate-spin"- aria-label="Loading"- />- ) : repository.isError ? (- <p className="text-muted-foreground">- Working docs are not available here yet.- </p>- ) : editing || !current ? (- <RepositoryPicker- current={current}- onDone={() => setEditing(false)}- onCancel={current ? () => setEditing(false) : undefined}- />- ) : (- <div className="flex flex-wrap items-center justify-between gap-3">- <div className="min-w-0">- <p className="font-medium">- {repositoryName(current)}- <span className="text-muted-foreground font-normal">- {' '}- · {current.branch}- </span>- </p>- {current.problem ? (- <p className="text-status-error">- {repositoryProblem(current)}- </p>- ) : (- <p className="text-muted-foreground">- Tracked items live here and show on the{' '}- <Link- to="/computer/work"- className="hover:text-foreground underline underline-offset-4"- >- board- </Link>- .- </p>- )}- </div>- <Button- size="sm"- variant="outline"- onClick={() => setEditing(true)}- >- Change- </Button>- </div>- )}+ <RepositoryPicker current={null} /></div></section>)}+/**+ * 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+ * again on focus.+ */+export function ConnectGitHubButton({+ label = 'Connect GitHub',+ variant = 'outline',+}: {+ label?: string+ variant?: 'default' | 'outline'+}) {+ const [starting, setStarting] = useState(false)+ return (+ <Button+ type="button"+ size="sm"+ variant={variant}+ disabled={starting}+ onClick={() => {+ setStarting(true)+ void launchAuthorizationWindow(() =>+ addManagedGitHubConnection('install'),+ )+ .catch((error: unknown) =>+ notifyError("Couldn't start the GitHub installation.", error),+ )+ .finally(() => setStarting(false))+ }}+ >+ {starting ? (+ <Loader2 className="animate-spin" aria-hidden />+ ) : (+ <GithubMark className="size-3.5" />+ )}+ {label}+ </Button>+ )+}+// About six rows show; the rest scroll.const LIST_HEIGHT = 'max-h-[16.5rem]'@@ -109,22 +96,20 @@ const LIST_HEIGHT = 'max-h-[16.5rem]'* 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({+export function RepositoryPicker({current,onDone,onCancel,}: {current: Repository | null- onDone: () => void+ onDone?: () => voidonCancel?: () => void}) {const qc = useQueryClient()const org = useOrg()- const list = useQuery({- queryKey: workKeys.repositories(org),- queryFn: getRepositories,- refetchOnWindowFocus: 'always',- })+ const list = useGrantingInstallations()+ // A switch away from a set repository waits for a confirmation.+ const [pending, setPending] = useState<Choice | null>(null)const installations = list.data ?? []const [chosen, setChosen] = useState<string | null>(null)const [q, setQ] = useState('')@@ -133,13 +118,7 @@ function RepositoryPicker({installations.find((i) => i.id === want) ?? installations[0]const save = useMutation({- mutationFn: ({- installationId,- repository: r,- }: {- installationId: string- repository: GrantedRepository- }) =>+ mutationFn: ({ installationId, repository: r }: Choice) =>putRepository({installationId,owner: r.owner,@@ -149,8 +128,9 @@ function RepositoryPicker({onSuccess: (repository) => {qc.setQueryData(workKeys.repository(org), repository)void qc.invalidateQueries({ queryKey: ['work', org] })- notifySuccess('Working docs repository saved.')- onDone()+ notifySuccess('Knowledge repository saved.')+ setPending(null)+ onDone?.()},onError: (e) => notifyError('Could not save the repository', e),})@@ -161,9 +141,7 @@ function RepositoryPicker({<p className="text-muted-foreground">Connect GitHub first: working docs live in one of its repositories.</p>- <Button size="sm" variant="outline" asChild>- <Link to="/managed-agents/connections">Connect GitHub</Link>- </Button>+ <ConnectGitHubButton /></div>)}@@ -278,12 +256,14 @@ function RepositoryPicker({selected={isCurrent(r)}saving={save.isPending && save.variables.repository.id === r.id}disabled={save.isPending}- onSelect={() =>- save.mutate({+ onSelect={() => {+ const choice = {installationId: installation.id,repository: r,- })- }+ }+ if (current) setPending(choice)+ else save.mutate(choice)+ }}/>))}{installation.truncated ? (@@ -307,10 +287,33 @@ function RepositoryPicker({</Button>) : null}</div>+ {current ? (+ <ConfirmDialog+ open={pending !== null}+ onOpenChange={(open) => !open && setPending(null)}+ title={`Switch the board to ${pending ? `${pending.repository.owner}/${pending.repository.name}` : ''}?`}+ 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.+ </>+ }+ confirmLabel="Switch"+ pending={save.isPending}+ onConfirm={() => pending && save.mutate(pending)}+ />+ ) : null}</div>)}+type Choice = { installationId: string; repository: GrantedRepository }+function RepositoryRow({repository: r,selected,diff --git a/web/src/managed-agents/work/queries.ts b/web/src/managed-agents/work/queries.tsnew file mode 100644index 00000000..40068404--- /dev/null+++ b/web/src/managed-agents/work/queries.ts@@ -0,0 +1,62 @@+import { useQuery, useQueryClient } from '@tanstack/react-query'+import { ApiError } from '@/api/errors'+import {+ getOpenItems,+ getRepositories,+ getRepository,+ keepOpenItems,+ useOrg,+ workKeys,+ type OpenItemsPoll,+} from './api'+import { OPEN_POLL_MS } from './board'++// The queries more than one screen reads, so they share one cache entry.++const notThereYet = (count: number, error: Error) =>+ !(error instanceof ApiError && error.status === 404) && count < 2++/**+ * The open items, polled with the last ETag: the board's data, and on the+ * settings page how fresh the index is (`asOf`, `head`, `building`).+ */+export function useOpenItems() {+ const qc = useQueryClient()+ const key = workKeys.open(useOrg())+ return useQuery({+ queryKey: key,+ queryFn: async () => {+ const prev = qc.getQueryData<OpenItemsPoll>(key)+ const next = await getOpenItems(prev?.etag ?? null)+ if (prev) return keepOpenItems(prev, next)+ if (!('notModified' in next)) return next+ // A 304 with nothing cached cannot happen (no ETag was sent); ask again.+ return (await getOpenItems(null)) as OpenItemsPoll+ },+ refetchInterval: OPEN_POLL_MS,+ retry: notThereYet,+ })+}++/** The chosen repository, with its problem when it cannot be read. */+export function useRepository() {+ return useQuery({+ queryKey: workKeys.repository(useOrg()),+ queryFn: getRepository,+ retry: notThereYet,+ })+}++/**+ * The installations and what they grant. Read again whenever the window+ * regains focus (past the default 30 s staleTime), so coming back from GitHub+ * shows a repository just granted.+ */+export function useGrantingInstallations(enabled = true) {+ return useQuery({+ queryKey: workKeys.repositories(useOrg()),+ queryFn: getRepositories,+ refetchOnWindowFocus: 'always',+ enabled,+ })+}diff --git a/web/src/managed-agents/work/screens.test.tsx b/web/src/managed-agents/work/screens.test.tsxindex 79d87d01..26a0d7b3 100644--- a/web/src/managed-agents/work/screens.test.tsx+++ b/web/src/managed-agents/work/screens.test.tsx@@ -25,7 +25,7 @@ vi.mock('./api', async (importOriginal) => ({const { Board } = await import('./Board')const { ItemView } = await import('./Item')-const { WorkRepositorySetting } = await import('./RepositorySetting')+const { KnowledgeRepositorySection } = await import('./KnowledgeRepository')const repository = {installationId: '1',@@ -91,7 +91,10 @@ async function render(url: string) {<Routes><Route path="/computer/work" element={<Board />} /><Route path="/computer/work/:number" element={<ItemView />} />- <Route path="/computer" element={<WorkRepositorySetting />} />+ <Route+ path="/computer"+ element={<KnowledgeRepositorySection id="work-repository" />}+ /></Routes></MemoryRouter></QueryClientProvider>@@ -241,7 +244,7 @@ describe('board', () => {workApi.getRepository.mockResolvedValue(null)await render('/computer/work')expect(container.textContent).toContain('An item is a working doc')- expect(container.textContent).toContain('Working docs')+ expect(container.textContent).toContain('Knowledge repository')expect(workApi.getClosedItems).not.toHaveBeenCalled()})@@ -251,7 +254,7 @@ describe('board', () => {expect(container.textContent).toContain('The board is not available yet')})- it('names the repository it reads, quietly linked to settings', async () => {+ it('names the repository it reads, quietly linked to its setting', async () => {workApi.getOpenItems.mockResolvedValue(openPage(items))await render('/computer/work')expect(@@ -260,6 +263,21 @@ describe('board', () => {).toBe('acme/knowledge')})+ it('chooses the first repository in place, then loads', async () => {+ workApi.getOpenItems.mockResolvedValue(+ openPage([], { repository: null, head: null, asOf: null }),+ )+ workApi.getRepositories.mockResolvedValue([acme])+ workApi.putRepository.mockResolvedValue(repository)+ await render('/computer/work')+ workApi.getOpenItems.mockResolvedValue(openPage(items))+ click(container.querySelector('button[aria-label="Select knowledge"]'))+ await settle()+ // No confirmation for a first choice.+ expect(workApi.putRepository).toHaveBeenCalledTimes(1)+ expect(column('In progress')).toBeTruthy()+ })+it('sends a repository problem to settings', async () => {workApi.getOpenItems.mockResolvedValue(openPage(items, {@@ -276,8 +294,9 @@ describe('board', () => {)expect(container.textContent).not.toContain('access_denied')expect(- container.querySelector('a[href="/computer#work-repository"]'),- ).not.toBeNull()+ container.querySelector('a[href="/computer#work-repository"]')+ ?.textContent,+ ).toBe('Settings')})it('shows no time where the last change or the closing is not known', async () => {@@ -590,9 +609,126 @@ describe('repository picker', () => {workApi.getRepository.mockResolvedValue(null)workApi.getRepositories.mockResolvedValue([])await render('/computer')+ expect(button('Connect GitHub')).toBeTruthy()+ })++ it('confirms before switching from a set repository', async () => {+ workApi.getRepository.mockResolvedValue(repository)+ 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 flush()+ expect(workApi.putRepository).not.toHaveBeenCalled()+ const dialog = document.body.querySelector('[role="alertdialog"]')!+ expect(dialog.textContent).toContain('Switch the board to acme/app?')+ expect(dialog.textContent).toContain(+ 'Nothing is deleted or changed in either repository',+ )+ click(+ [...dialog.querySelectorAll('button')].find(+ (b) => b.textContent === 'Switch',+ ),+ )+ await settle()+ expect(workApi.putRepository).toHaveBeenCalledWith({+ installationId: '1',+ owner: 'acme',+ name: 'app',+ branch: 'main',+ })+ })+})++function button(text: string) {+ return [...container.querySelectorAll('button')].find(+ (b) => b.textContent === text,+ )+}++describe('knowledge repository section', () => {+ beforeEach(() => {+ workApi.getRepositories.mockResolvedValue([acme])+ workApi.getOpenItems.mockResolvedValue(+ openPage(items(), { head: '9f2c1a7e4b3d', asOf: minutesAgo(2) }),+ )+ })+ const items = () => [makeItem({ number: 1, title: 'One' })]+ const withProblem = (problem: string, problemMessage: string | null = null) =>+ workApi.getRepository.mockResolvedValue({+ ...repository,+ problem,+ problemMessage,+ })++ it('shows the repository, its branch and how fresh the reading is', async () => {+ workApi.getRepository.mockResolvedValue(repository)+ await render('/computer')+ expect(container.querySelector('section#work-repository')).not.toBeNull()expect(- container.querySelector('a[href="/managed-agents/connections"]')+ container.querySelector('a[href="https://github.com/acme/knowledge"]')?.textContent,- ).toBe('Connect GitHub')+ ).toBe('acme/knowledge')+ expect(container.textContent).toContain('main')+ expect(container.textContent).toContain(+ 'Up to date · read 2 min ago at 9f2c1a7',+ )+ // The installations are read only when choosing.+ expect(workApi.getRepositories).not.toHaveBeenCalled()+ })++ it('says when the first read is still going', async () => {+ workApi.getRepository.mockResolvedValue(repository)+ workApi.getOpenItems.mockResolvedValue(+ openPage([], { building: true, asOf: null }),+ )+ await render('/computer')+ expect(container.textContent).toContain(+ 'Reading the working docs for the first time',+ )+ })++ it('offers Reconnect GitHub when the installation is gone', async () => {+ withProblem('installation_removed')+ await render('/computer')+ expect(container.textContent).toContain(+ 'The GitHub installation is not connected to this organization.',+ )+ expect(button('Reconnect GitHub')).toBeTruthy()+ expect(button('Change')).toBeUndefined()+ expect(container.textContent).not.toContain('installation_removed')+ })++ it('offers GitHub App access and another repository when it is not granted', async () => {+ withProblem('repository_not_found')+ await render('/computer')+ expect(+ [...container.querySelectorAll('a')]+ .find((a) => a.textContent === 'Adjust GitHub App access')+ ?.getAttribute('href'),+ ).toBe(acme.settingsUrl)+ click(button('Choose another repository'))+ await settle()+ expect(rows()).toEqual(['app', 'knowledge', 'website'])+ })++ it('says the branch is gone and offers Change', async () => {+ withProblem('branch_not_found')+ await render('/computer')+ expect(container.textContent).toContain('The main branch is gone.')+ expect(button('Change')).toBeTruthy()+ expect(workApi.getRepositories).not.toHaveBeenCalled()+ })+})++describe('knowledge repository section, not available', () => {+ it('says so quietly while the Work API is not there', async () => {+ workApi.getRepository.mockRejectedValue(new ApiError('Not found', 404))+ await render('/computer')+ expect(container.textContent).toContain(+ 'Tracked work is not available here yet.',+ )})})