An open-source, faster Devin alternative
TypeScript
web: read-only Board and Item pages, and the working docs repository setting
Igor Zalutski via Computer873930465612
diff --git a/web/src/App.tsx b/web/src/App.tsxindex a6b220eb..b819ebf7 100644--- a/web/src/App.tsx+++ b/web/src/App.tsx@@ -25,6 +25,8 @@ const ComputerSessionsHome = lazy(const ComputerSession = lazy(() => import('./managed-agents/computer-sessions/Session'),)+const WorkBoard = lazy(() => import('./managed-agents/work/Board'))+const WorkItem = lazy(() => import('./managed-agents/work/Item'))const ManagedAgentDetail = lazy(() => import('./managed-agents/Detail'))const ManagedProjectDetail = lazy(() => import('./managed-agents/Project'))const ManagedSessionDetail = lazy(() => import('./managed-agents/Session'))@@ -133,6 +135,8 @@ export default function App() {path="computer/secrets"element={<ManagedComputerSecrets />}/>+ <Route path="computer/work" element={<WorkBoard />} />+ <Route path="computer/work/:number" element={<WorkItem />} /><Route path="automations" element={<ManagedAgentsHome list />} /><Routepath="model-access/callback"diff --git a/web/src/managed-agents/Computer.tsx b/web/src/managed-agents/Computer.tsxindex 551f7e07..f768d0a4 100644--- a/web/src/managed-agents/Computer.tsx+++ b/web/src/managed-agents/Computer.tsx@@ -59,6 +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 { ChatTextarea } from '@/components/chat-textarea'import {AgentCard,@@ -291,6 +292,7 @@ function ComputerPageContent() {failed={sessions.isError}/><AgentCard status={status.data} />+ <WorkRepositorySetting id="work-repository" /><IdeasToTry /></div></WithDeveloperFooter>diff --git a/web/src/managed-agents/work/Board.tsx b/web/src/managed-agents/work/Board.tsxnew file mode 100644index 00000000..df966820--- /dev/null+++ b/web/src/managed-agents/work/Board.tsx@@ -0,0 +1,521 @@+import { useContext, type ReactNode } from 'react'+import { Link, Navigate, useSearchParams } from 'react-router-dom'+import {+ useInfiniteQuery,+ useQuery,+ useQueryClient,+} from '@tanstack/react-query'+import { FileText, Loader2, Search, SquareKanban, X } from 'lucide-react'+import { ApiError } from '@/api/errors'+import { EmptyState } from '@/components/empty-state'+import { Panel } from '@/components/panel'+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,+ useOrg,+ workKeys,+ type Item,+ type OpenItemsPoll,+} from './api'+import {+ closedShown,+ indexIsOld,+ OPEN_POLL_MS,+ inProgress,+ matches,+ plural,+ readyToClose,+ repositoryName,+ staleDays,+ type Filters,+ type Tab,+} from './board'+import {+ AttentionMark,+ Avatar,+ PullChip,+ Tag,+ UnpublishedMark,+ WarningMark,+} from './parts'+import { WorkRepositorySetting } 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.++export default function BoardPage() {+ const auth = useContext(AuthContext)+ if (auth?.user && !auth.user.computerEnabled)+ return <Navigate to="/" replace />+ 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 (next) return next+ if (prev) return prev+ // A 304 with nothing cached cannot happen (no ETag was sent); ask again.+ return (await getOpenItems(null))!+ },+ 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()+ const tab: Tab = params.get('tab') === 'everyone' ? 'everyone' : 'mine'+ const filters: Filters = {+ tab,+ q: params.get('q') ?? '',+ tag: params.get('tag'),+ }+ const showOlder = params.get('older') === '1'+ const setParam = (k: string, v: string | null) =>+ setParams(+ (p) => {+ const next = new URLSearchParams(p)+ if (v) next.set(k, v)+ else next.delete(k)+ return next+ },+ { replace: true },+ )++ const open = useOpenItems()+ const repository = open.data?.page.repository ?? null+ const closed = useInfiniteQuery({+ queryKey: workKeys.closed(org),+ queryFn: ({ pageParam }) => getClosedItems(pageParam),+ initialPageParam: undefined as string | undefined,+ getNextPageParam: (last) => last.nextCursor ?? undefined,+ enabled: repository !== null,+ })++ if (open.isPending) {+ return (+ <div role="status" className="flex min-h-64 items-center justify-center">+ <Loader2 className="text-muted-foreground size-5 animate-spin" />+ </div>+ )+ }+ if (open.isError) {+ const missing = open.error instanceof ApiError && open.error.status === 404+ return (+ <BoardFrame>+ <Panel>+ <EmptyState+ icon={SquareKanban}+ title={+ missing+ ? 'The board is not available yet'+ : 'Could not load the board'+ }+ description={+ missing+ ? 'Tracked work is coming to this organization soon.'+ : 'Try loading this page again.'+ }+ />+ </Panel>+ </BoardFrame>+ )+ }++ const page = open.data.page+ if (!page.repository) {+ return (+ <BoardFrame>+ <Panel>+ <EmptyState+ icon={FileText}+ title="Nothing is tracked yet"+ description={<WhatIsAnItem />}+ />+ </Panel>+ <div className="mt-8">+ <WorkRepositorySetting />+ </div>+ </BoardFrame>+ )+ }++ const closedItems = closed.data?.pages.flatMap((p) => p.items) ?? []+ const all = [...page.items, ...closedItems]+ const shown = all.filter((i) => matches(i, filters))+ const progress = inProgress(shown)+ const ready = readyToClose(shown)+ const done = closedShown(shown, showOlder)+ const needYou = progress.filter(+ (i) => i.attention?.state === 'needs_you',+ ).length+ const filtering = !!filters.q.trim() || !!filters.tag+ const mineEmpty =+ tab === 'mine' &&+ !filtering &&+ !all.some((i) => i.mine) &&+ all.length > 0 &&+ !closed.isPending+ const nothing = all.length === 0 && !page.building && !closed.isPending++ return (+ <BoardFrame+ tab={tab}+ onTab={(t) => setParam('tab', t === 'mine' ? null : t)}+ q={filters.q}+ onQ={(q) => setParam('q', q || null)}+ tag={filters.tag}+ onClearTag={() => setParam('tag', null)}+ status={+ <IndexStatus+ repository={repositoryName(page.repository)}+ problem={page.repository.problem ?? null}+ building={page.building}+ asOf={page.asOf}+ />+ }+ >+ {nothing ? (+ <Panel>+ <EmptyState+ icon={FileText}+ title="Nothing is tracked yet"+ description={<WhatIsAnItem />}+ />+ </Panel>+ ) : mineEmpty ? (+ <Panel>+ <EmptyState+ icon={SquareKanban}+ title="You own no items"+ description={+ <>+ Items without an owner, and other people's, are on{' '}+ <button+ type="button"+ className="text-foreground underline underline-offset-4"+ onClick={() => setParam('tab', 'everyone')}+ >+ Everyone+ </button>+ .+ </>+ }+ />+ </Panel>+ ) : (+ <div className="grid gap-x-6 gap-y-8 lg:grid-cols-[minmax(0,2fr)_minmax(0,1fr)_minmax(0,1fr)]">+ <Column+ title="In progress"+ count={progress.length}+ note={needYou ? `${needYou} need you` : null}+ wide+ >+ {progress.map((i) => (+ <Card key={i.number} item={i} onTag={(t) => setParam('tag', t)} />+ ))}+ {page.building && !progress.length ? (+ <p className="text-muted-foreground text-xs">+ Reading the working docs…+ </p>+ ) : null}+ </Column>+ <Column+ title="Ready to close"+ count={ready.length}+ note="nothing left in the doc"+ >+ {ready.map((i) => (+ <Card key={i.number} item={i} onTag={(t) => setParam('tag', t)}>+ {/* Close arrives in build step 5. */}+ </Card>+ ))}+ </Column>+ <Column+ title="Closed"+ count={done.length}+ note={showOlder ? 'all' : 'last 7 days'}+ footer={+ <div className="space-y-3">+ <div className="text-muted-foreground flex items-center gap-2 text-xs">+ <Switch+ id="work-show-older"+ checked={showOlder}+ onCheckedChange={(on) => setParam('older', on ? '1' : null)}+ />+ <label htmlFor="work-show-older">Show older</label>+ </div>+ {showOlder && closed.hasNextPage ? (+ <button+ type="button"+ className="text-muted-foreground hover:text-foreground text-xs underline underline-offset-4"+ disabled={closed.isFetchingNextPage}+ onClick={() => void closed.fetchNextPage()}+ >+ {closed.isFetchingNextPage ? 'Loading…' : 'Load more'}+ </button>+ ) : null}+ </div>+ }+ >+ {done.map((i) => (+ <Card key={i.number} item={i} onTag={(t) => setParam('tag', t)} />+ ))}+ </Column>+ </div>+ )}+ </BoardFrame>+ )+}++function WhatIsAnItem() {+ return (+ <>+ An item is a working doc an agent keeps about work that outlives one+ sitting: what it is, where it stands, and what is left. Any session can be+ tracked: say “track this” in it, and the item shows up here.+ </>+ )+}++function BoardFrame({+ tab,+ onTab,+ q,+ onQ,+ tag,+ onClearTag,+ status,+ children,+}: {+ tab?: Tab+ onTab?: (t: Tab) => void+ q?: string+ onQ?: (q: string) => void+ tag?: string | null+ onClearTag?: () => void+ status?: ReactNode+ children: ReactNode+}) {+ return (+ <div>+ <header className="mb-6 flex flex-wrap items-center gap-x-4 gap-y-3">+ <h1 className="text-xl font-semibold tracking-tight">Board</h1>+ {tab && onTab ? (+ <div+ role="tablist"+ aria-label="Whose items"+ className="bg-muted flex rounded-md p-0.5"+ >+ {(['mine', 'everyone'] as const).map((t) => (+ <button+ key={t}+ type="button"+ role="tab"+ aria-selected={tab === t}+ onClick={() => onTab(t)}+ className={cn(+ 'text-muted-foreground rounded px-3 py-1 text-sm transition-colors',+ tab === t && 'bg-background text-foreground shadow-xs',+ )}+ >+ {t === 'mine' ? 'Mine' : 'Everyone'}+ </button>+ ))}+ </div>+ ) : null}+ {onQ ? (+ <div className="relative w-full sm:w-64">+ <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) => onQ(e.target.value)}+ onKeyDown={(e) => e.key === 'Escape' && onQ('')}+ placeholder="Filter by title or state"+ aria-label="Filter by title or state"+ className="border-input placeholder:text-muted-foreground focus-visible:border-ring/60 h-8 w-full rounded-md border bg-transparent pr-2 pl-8 text-sm outline-none"+ />+ </div>+ ) : null}+ {tag && onClearTag ? (+ <button+ type="button"+ onClick={onClearTag}+ className="bg-foreground text-background inline-flex items-center gap-1 rounded px-1.5 py-0.5 font-mono text-[11px]"+ aria-label={`Clear the tag filter ${tag}`}+ >+ {tag}+ <X className="size-3" aria-hidden />+ </button>+ ) : null}+ <div className="flex-1" />+ {status}+ </header>+ {children}+ </div>+ )+}++/** Which repository the board reads, and how fresh what it shows is. */+function IndexStatus({+ repository,+ problem,+ building,+ asOf,+}: {+ repository: string+ problem: string | null+ building: boolean+ asOf: string | null+}) {+ return (+ <p className="text-muted-foreground flex flex-wrap items-center gap-x-1.5 text-xs">+ {problem ? (+ <>+ <span className="text-status-error">+ Cannot read {repository}: {problem}.+ </span>+ <Link+ to="/computer#work-repository"+ className="hover:text-foreground underline underline-offset-4"+ >+ Settings+ </Link>+ </>+ ) : building ? (+ <span role="status" className="inline-flex items-center gap-1.5">+ <Loader2 className="size-3 animate-spin" aria-hidden />+ Reading {repository}…+ </span>+ ) : indexIsOld(asOf) ? (+ <span title={asOf ?? undefined}>As of {timeAgo(asOf)} ago</span>+ ) : null}+ </p>+ )+}++function Column({+ title,+ count,+ note,+ wide,+ footer,+ children,+}: {+ title: string+ count: number+ note: string | null+ wide?: boolean+ footer?: ReactNode+ children: ReactNode+}) {+ return (+ <section aria-label={title} className="min-w-0">+ <h2 className="mb-3 flex items-baseline gap-1.5 text-sm">+ <span className="font-medium">{title}</span>+ <span className="text-muted-foreground tabular-nums">{count}</span>+ {note ? (+ <span className="text-muted-foreground text-xs">· {note}</span>+ ) : null}+ </h2>+ <div className={cn('grid items-start gap-3', wide && 'xl:grid-cols-2')}>+ {children}+ </div>+ {footer ? <div className="mt-3">{footer}</div> : null}+ </section>+ )+}++export function Card({+ item,+ onTag,+ children,+}: {+ item: Item+ onTag: (tag: string) => void+ // The card's action (Close, Reopen), from build step 5.+ children?: ReactNode+}) {+ const stale = staleDays(item)+ const closed = item.stage === 'closed'+ return (+ <article+ className={cn(+ 'bg-panel hover:border-foreground/20 relative rounded-lg border p-3.5 transition-colors',+ stale !== null && 'bg-muted/40 border-dashed opacity-75',+ )}+ >+ <h3 className="flex items-start gap-1.5 text-sm leading-5 font-medium">+ <span className="text-muted-foreground font-normal tabular-nums">+ {item.number}+ </span>+ <Link+ to={`/computer/work/${item.number}`}+ className={cn(+ 'min-w-0 flex-1 after:absolute after:inset-0 after:rounded-lg',+ closed && 'text-muted-foreground',+ )}+ >+ {item.title}+ </Link>+ <WarningMark warnings={item.warnings} />+ </h3>+ {item.stateLine ? (+ <p className="text-muted-foreground mt-1 line-clamp-2 text-xs leading-5">+ {item.stateLine}+ </p>+ ) : null}+ {item.tags.length ? (+ <div className="mt-2 flex flex-wrap gap-1">+ {item.tags.map((t) => (+ <Tag key={t} tag={t} onClick={() => onTag(t)} />+ ))}+ </div>+ ) : null}+ <div className="text-muted-foreground mt-2.5 flex flex-wrap items-center gap-1.5 text-xs">+ {item.owner ? <Avatar person={item.owner} /> : null}+ {item.pullRequests.map((pr) => (+ <PullChip key={pr.url} pr={pr} />+ ))}+ {item.sessions.length ? (+ <span>{plural(item.sessions.length, 'session')}</span>+ ) : null}+ <span className="ml-auto tabular-nums" title={item.updatedAt}>+ {stale !== null+ ? `no change in ${stale} days`+ : timeAgo(+ closed ? (item.closedAt ?? item.updatedAt) : item.updatedAt,+ )}+ </span>+ </div>+ {item.unpublished ? <UnpublishedMark className="mt-2" /> : null}+ {closed || item.attention || children ? (+ <div className="mt-2.5 flex min-h-5 items-center gap-2 border-t border-dashed pt-2.5">+ {closed ? (+ <span className="text-muted-foreground text-xs">+ {item.closedBy ? `Closed by ${item.closedBy}` : 'Closed'}+ </span>+ ) : (+ <AttentionMark item={item} />+ )}+ <div className="relative z-10 ml-auto">{children}</div>+ </div>+ ) : null}+ </article>+ )+}diff --git a/web/src/managed-agents/work/Item.tsx b/web/src/managed-agents/work/Item.tsxnew file mode 100644index 00000000..4e265087--- /dev/null+++ b/web/src/managed-agents/work/Item.tsx@@ -0,0 +1,450 @@+import { useContext, type ReactNode } from 'react'+import { Link, Navigate, useParams, useSearchParams } from 'react-router-dom'+import { useInfiniteQuery, useQuery } from '@tanstack/react-query'+import {+ ExternalLink,+ FileText,+ GitCommitHorizontal,+ Loader2,+} from 'lucide-react'+import { ApiError } from '@/api/errors'+import { EmptyState } from '@/components/empty-state'+import { Panel } from '@/components/panel'+import { AuthContext } from '@/hooks/useAuth'+import { cn } from '@/lib/utils'+import { AgentMarkdown } from '../AgentMarkdown'+import { StatusDot } from '../computer-sessions/parts'+import { timeAgo } from '../computer-sessions/transcript'+import {+ getHistory,+ getItem,+ useOrg,+ workKeys,+ type Item,+ type Revision,+} from './api'+import {+ OPEN_POLL_MS,+ personName,+ presentBody,+ pullLabel,+ pullStateWord,+ resolveAgainst,+} from './board'+import {+ AttentionMark,+ Avatar,+ PullDot,+ SectionTitle,+ Tag,+ UnpublishedMark,+ WarningMark,+} from './parts'++// One item (ux-spec 5): its working doc at reading width, and beside it the+// details the API composes and the doc's history. No chat, no diff.++export default function ItemPage() {+ const auth = useContext(AuthContext)+ if (auth?.user && !auth.user.computerEnabled)+ return <Navigate to="/" replace />+ return <ItemView />+}++export function ItemView() {+ const org = useOrg()+ const number = Number(useParams().number)+ const valid = Number.isInteger(number) && number > 0+ const [params, setParams] = useSearchParams()+ const tab = params.get('tab') === 'history' ? 'history' : 'details'+ const item = useQuery({+ queryKey: workKeys.item(org, number),+ queryFn: () => getItem(number),+ enabled: valid,+ refetchInterval: OPEN_POLL_MS,+ retry: (count, error) =>+ !(error instanceof ApiError && error.status === 404) && count < 2,+ })++ if (!valid || item.isError) {+ const missing =+ !valid || (item.error instanceof ApiError && item.error.status === 404)+ return (+ <div>+ <Breadcrumb number={valid ? number : null} />+ <Panel>+ <EmptyState+ icon={FileText}+ title={missing ? 'No such item' : 'Could not load this item'}+ description={+ missing+ ? 'It may have been renamed, or tracked work is not available here yet.'+ : 'Try loading this page again.'+ }+ action={+ <Link+ to="/computer/work"+ className="text-sm underline underline-offset-4"+ >+ Back to the board+ </Link>+ }+ />+ </Panel>+ </div>+ )+ }+ if (item.isPending) {+ return (+ <div role="status" className="flex min-h-64 items-center justify-center">+ <Loader2 className="text-muted-foreground size-5 animate-spin" />+ </div>+ )+ }++ const it = item.data.item+ return (+ <div>+ <Breadcrumb number={it.number} />+ <ItemHeader item={it} />+ <div className="mt-6 flex flex-col gap-8 lg:flex-row lg:items-start">+ <article className="min-w-0 flex-1">+ <div className="max-w-[72ch]">+ <AgentMarkdown resolveUrl={(u) => resolveAgainst(u, it.url)}>+ {presentBody(item.data.body)}+ </AgentMarkdown>+ </div>+ </article>+ <aside className="lg:sticky lg:top-8 lg:w-80 lg:shrink-0">+ <div+ role="tablist"+ aria-label="About this item"+ className="mb-4 flex gap-4 border-b text-sm"+ >+ {(['details', 'history'] as const).map((t) => (+ <button+ key={t}+ type="button"+ role="tab"+ aria-selected={tab === t}+ onClick={() =>+ setParams(+ (p) => {+ const next = new URLSearchParams(p)+ if (t === 'history') next.set('tab', t)+ else next.delete('tab')+ return next+ },+ { replace: true },+ )+ }+ className={cn(+ 'text-muted-foreground -mb-px border-b-2 border-transparent pb-2 transition-colors',+ tab === t && 'border-foreground text-foreground',+ )}+ >+ {t === 'details' ? 'Details' : 'History'}+ </button>+ ))}+ </div>+ {tab === 'details' ? (+ <Details item={it} />+ ) : (+ <HistoryList number={it.number} />+ )}+ </aside>+ </div>+ </div>+ )+}++function Breadcrumb({ number }: { number: number | null }) {+ return (+ <nav aria-label="Breadcrumb" className="text-muted-foreground mb-3 text-xs">+ <Link to="/computer/work" className="hover:text-foreground">+ Board+ </Link>+ {number !== null ? (+ <>+ <span className="mx-1.5">/</span>+ <span className="tabular-nums">{number}</span>+ </>+ ) : null}+ </nav>+ )+}++function ItemHeader({ item }: { item: Item }) {+ const closed = item.stage === 'closed'+ return (+ <header className="border-b pb-5">+ <div className="flex flex-wrap items-start gap-x-4 gap-y-2">+ <h1 className="min-w-0 flex-1 text-xl font-semibold tracking-tight">+ <span className="text-muted-foreground mr-2 font-normal tabular-nums">+ {item.number}+ </span>+ {item.title}+ </h1>+ <div className="flex items-center gap-2">+ <a+ href={item.url}+ target="_blank"+ rel="noreferrer"+ className="text-muted-foreground hover:text-foreground inline-flex items-center gap-1 text-xs"+ >+ View on GitHub+ <ExternalLink className="size-3" aria-hidden />+ </a>+ {/* Close and Reopen arrive here with build step 5. */}+ </div>+ </div>+ <div className="text-muted-foreground mt-2 flex flex-wrap items-center gap-x-3 gap-y-1.5 text-xs">+ <span+ className={cn(+ 'rounded-full border px-2 py-0.5 font-medium',+ closed+ ? 'text-muted-foreground'+ : item.readyToClose+ ? 'text-foreground'+ : 'text-status-running border-status-running/40',+ )}+ >+ {closed ? 'Closed' : item.readyToClose ? 'Ready to close' : 'Open'}+ </span>+ <span className="inline-flex items-center gap-1.5">+ {item.owner ? (+ <>+ <Avatar person={item.owner} />+ {personName(item.owner)}+ </>+ ) : (+ 'no owner'+ )}+ </span>+ {item.author ? <span>started by {personName(item.author)}</span> : null}+ {closed ? (+ <span title={item.closedAt ?? undefined}>+ {item.closedBy ? `closed by ${item.closedBy}` : 'closed'}+ {item.closedAt ? ` · ${timeAgo(item.closedAt)}` : null}+ </span>+ ) : (+ <span title={item.updatedAt}>changed {timeAgo(item.updatedAt)}</span>+ )}+ {!closed ? <AttentionMark item={item} /> : null}+ <WarningMark warnings={item.warnings} />+ {item.unpublished ? <UnpublishedMark /> : null}+ </div>+ </header>+ )+}++function Details({ item }: { item: Item }) {+ const people = peopleOf(item)+ return (+ <div className="space-y-6 text-sm">+ {item.warnings.length ? (+ <Section title="Problems in the doc">+ <ul className="text-status-pending space-y-1 text-xs">+ {item.warnings.map((w) => (+ <li key={w}>{w}</li>+ ))}+ </ul>+ </Section>+ ) : null}+ <Section title="Tags">+ {item.tags.length ? (+ <div className="flex flex-wrap gap-1">+ {item.tags.map((t) => (+ <Link+ key={t}+ to={`/computer/work?tab=everyone&tag=${encodeURIComponent(t)}`}+ title={`Show items tagged ${t}`}+ >+ <Tag tag={t} />+ </Link>+ ))}+ </div>+ ) : (+ <None>No tags</None>+ )}+ </Section>+ <Section title={`Sessions${count(item.sessions.length)}`}>+ {item.sessions.length ? (+ <ul className="space-y-2">+ {item.sessions.map((s) => (+ <li key={s.id} className="flex items-start gap-2">+ {s.status ? (+ <span className="mt-1.5">+ <StatusDot status={s.status} />+ </span>+ ) : null}+ <div className="min-w-0">+ <Link+ to={`/computer/sessions/${s.id}`}+ className="hover:text-foreground block truncate underline-offset-4 hover:underline"+ >+ {s.title || 'Untitled session'}+ </Link>+ <p className="text-muted-foreground text-xs">+ {[s.ownerName, s.status].filter(Boolean).join(' · ')}+ </p>+ </div>+ </li>+ ))}+ </ul>+ ) : (+ <None>No session has worked on it yet</None>+ )}+ </Section>+ <Section title={`Pull requests${count(item.pullRequests.length)}`}>+ {item.pullRequests.length ? (+ <ul className="space-y-2">+ {item.pullRequests.map((pr) => (+ <li key={pr.url} className="flex items-start gap-2">+ <span className="mt-2">+ <PullDot state={pr.state} />+ </span>+ <div className="min-w-0">+ <a+ href={pr.url}+ target="_blank"+ rel="noreferrer"+ className="block truncate underline-offset-4 hover:underline"+ >+ <span className="text-muted-foreground tabular-nums">+ {pullLabel(pr)}+ </span>{' '}+ {pr.title}+ </a>+ <p className="text-muted-foreground text-xs">+ {pullStateWord(pr.state)}+ </p>+ </div>+ </li>+ ))}+ </ul>+ ) : (+ <None>None linked</None>+ )}+ </Section>+ <Section title="People">+ <ul className="space-y-1.5">+ {people.map(({ name, role }) => (+ <li key={`${role}-${name}`} className="flex items-center gap-2">+ <Avatar person={{ name, email: name, id: null }} />+ <span className="min-w-0 truncate">{name}</span>+ <span className="text-muted-foreground ml-auto text-xs">+ {role}+ </span>+ </li>+ ))}+ </ul>+ {!people.length ? <None>Nobody yet</None> : null}+ </Section>+ </div>+ )+}++/** The people the item names, each once with the role it names them in. */+function peopleOf(item: Item): { name: string; role: string }[] {+ const out: { name: string; role: string }[] = []+ const add = (name: string | null | undefined, role: string) => {+ if (!name || out.some((p) => p.name === name)) return+ out.push({ name, role })+ }+ add(item.owner && personName(item.owner), 'owner')+ add(item.author && personName(item.author), 'author')+ for (const s of item.sessions) add(s.ownerName, 'session')+ return out+}++function HistoryList({ number }: { number: number }) {+ const org = useOrg()+ const history = useInfiniteQuery({+ queryKey: workKeys.history(org, number),+ queryFn: ({ pageParam }) => getHistory(number, pageParam),+ initialPageParam: undefined as string | undefined,+ getNextPageParam: (last) => last.nextCursor ?? undefined,+ })+ if (history.isPending) {+ return (+ <Loader2+ className="text-muted-foreground size-4 animate-spin"+ aria-label="Loading"+ />+ )+ }+ if (history.isError) {+ return <None>Could not load the history.</None>+ }+ const revisions = history.data.pages.flatMap((p) => p.revisions)+ if (!revisions.length) return <None>No changes yet</None>+ return (+ <div>+ <ol className="relative space-y-4 border-l pl-4">+ {revisions.map((r) => (+ <RevisionRow key={r.sha} revision={r} />+ ))}+ </ol>+ {history.hasNextPage ? (+ <button+ type="button"+ className="text-muted-foreground hover:text-foreground mt-4 text-xs underline underline-offset-4"+ disabled={history.isFetchingNextPage}+ onClick={() => void history.fetchNextPage()}+ >+ {history.isFetchingNextPage ? 'Loading…' : 'Older changes'}+ </button>+ ) : null}+ </div>+ )+}++function RevisionRow({ revision: r }: { revision: Revision }) {+ return (+ <li className="relative text-sm">+ <span+ aria-hidden+ className="bg-background absolute top-1.5 -left-[21px] size-2.5 rounded-full border"+ />+ <p className="leading-5">{r.summary}</p>+ <p className="text-muted-foreground mt-0.5 flex flex-wrap items-center gap-x-2 text-xs">+ <span>{r.authorName}</span>+ <span title={r.at}>{timeAgo(r.at)}</span>+ {r.sessionId ? (+ <Link+ to={`/computer/sessions/${r.sessionId}`}+ className="hover:text-foreground underline underline-offset-4"+ >+ session+ </Link>+ ) : null}+ <a+ href={r.url}+ target="_blank"+ rel="noreferrer"+ title="This change on GitHub"+ className="hover:text-foreground inline-flex items-center gap-0.5 font-mono"+ >+ <GitCommitHorizontal className="size-3" aria-hidden />+ {r.sha.slice(0, 7)}+ </a>+ </p>+ </li>+ )+}++function Section({ title, children }: { title: string; children: ReactNode }) {+ return (+ <section>+ <SectionTitle>{title}</SectionTitle>+ {children}+ </section>+ )+}++function None({ children }: { children: ReactNode }) {+ return <p className="text-muted-foreground text-xs">{children}</p>+}++const count = (n: number) => (n ? ` · ${n}` : '')diff --git a/web/src/managed-agents/work/RepositorySetting.tsx b/web/src/managed-agents/work/RepositorySetting.tsxnew file mode 100644index 00000000..c258e130--- /dev/null+++ b/web/src/managed-agents/work/RepositorySetting.tsx@@ -0,0 +1,203 @@+import { useState, type FormEvent } 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 { Button } from '@/components/ui/button'+import { notifyError, notifySuccess } from '@/lib/errors'+import { computerQueryKey, getComputer } from '../computer-api'+import {+ getRepository,+ putRepository,+ useOrg,+ workKeys,+ type Repository,+} from './api'+import { repositoryName } from './board'++// Which repository holds the organization's working docs (tech design 3.1):+// one per organization, chosen from what its GitHub connection can reach.++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++ return (+ <section id={id} aria-labelledby="work-repository">+ <h2 id="work-repository" className="mb-3 text-sm font-semibold">+ Working docs+ </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 ? (+ <RepositoryForm+ 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">{current.problem}</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>+ )}+ </div>+ </section>+ )+}++function RepositoryForm({+ current,+ onDone,+ onCancel,+}: {+ current: Repository | null+ onDone: () => void+ onCancel?: () => void+}) {+ const qc = useQueryClient()+ const org = useOrg()+ const computer = useQuery({+ queryKey: computerQueryKey,+ queryFn: getComputer,+ })+ 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 installation =+ installations.find((i) => i.id === installationId) ??+ (installations.length === 1 ? installations[0] : undefined)++ const save = useMutation({+ mutationFn: () =>+ putRepository({+ installationId: installation!.id,+ owner: installation!.accountLogin,+ name: name.trim(),+ branch: branch.trim() || 'main',+ }),+ onSuccess: (repository) => {+ qc.setQueryData(workKeys.repository(org), repository)+ void qc.invalidateQueries({ queryKey: ['work', org] })+ notifySuccess('Working docs repository saved.')+ onDone()+ },+ 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) {+ return (+ <div className="flex flex-wrap items-center justify-between gap-3">+ <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>+ </div>+ )+ }++ return (+ <form onSubmit={submit} 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"+ />+ </Field>+ <Field label="Branch" htmlFor="work-repo-branch">+ <Input+ id="work-repo-branch"+ value={branch}+ onChange={(e) => setBranch(e.target.value)}+ autoComplete="off"+ />+ </Field>+ </div>+ <div className="flex gap-2">+ <Button+ type="submit"+ size="sm"+ disabled={!installation || !name.trim() || save.isPending}+ >+ {save.isPending ? <Loader2 className="animate-spin" /> : null}+ Save+ </Button>+ {onCancel ? (+ <Button type="button" size="sm" variant="ghost" onClick={onCancel}>+ Cancel+ </Button>+ ) : null}+ </div>+ </form>+ )+}diff --git a/web/src/managed-agents/work/screens.test.tsx b/web/src/managed-agents/work/screens.test.tsxnew file mode 100644index 00000000..72621ca7--- /dev/null+++ b/web/src/managed-agents/work/screens.test.tsx@@ -0,0 +1,356 @@+// @vitest-environment happy-dom++import { act } from 'react'+import { createRoot, type Root } from 'react-dom/client'+import { MemoryRouter, Route, Routes } from 'react-router-dom'+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { ApiError } from '@/api/errors'+import { AuthContext, type AuthContextValue } from '@/hooks/useAuth'+import { makeItem, minutesAgo } from './fixtures'++const workApi = vi.hoisted(() => ({+ getOpenItems: vi.fn(),+ getClosedItems: vi.fn(),+ getItem: vi.fn(),+ getHistory: vi.fn(),+ getRepository: vi.fn(),+ putRepository: 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 repository = {+ installationId: '1',+ owner: 'acme',+ name: 'knowledge',+ branch: 'main',+ problem: null,+}+const openPage = (items: ReturnType<typeof makeItem>[], over = {}) => ({+ etag: '"h1"',+ page: {+ repository,+ head: 'abc',+ asOf: new Date().toISOString(),+ building: false,+ items,+ ...over,+ },+})++const auth: AuthContextValue = {+ user: {+ id: 'usr_1',+ email: '[email protected]',+ orgId: 'org_1',+ computerEnabled: true,+ },+ loading: false,+ error: null,+ switchOrg: async () => {},+ refreshUser: async () => {},+}++let container: HTMLDivElement+let root: Root++beforeEach(() => {+ ;(+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }+ ).IS_REACT_ACT_ENVIRONMENT = true+ container = document.createElement('div')+ document.body.appendChild(container)+ root = createRoot(container)+ workApi.getClosedItems.mockResolvedValue({ items: [], nextCursor: null })+})++afterEach(() => {+ act(() => root.unmount())+ container.remove()+ document.body.innerHTML = ''+ vi.clearAllMocks()+})++async function render(url: string) {+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ })+ act(() => {+ root.render(+ <AuthContext.Provider value={auth}>+ <QueryClientProvider client={client}>+ <MemoryRouter initialEntries={[url]}>+ <Routes>+ <Route path="/computer/work" element={<Board />} />+ <Route path="/computer/work/:number" element={<ItemView />} />+ </Routes>+ </MemoryRouter>+ </QueryClientProvider>+ </AuthContext.Provider>,+ )+ })+ for (let i = 0; i < 50 && container.querySelector('[role="status"]'); i++) {+ await flush()+ }+ await flush()+}++async function flush() {+ await act(async () => {+ await new Promise((resolve) => setTimeout(resolve, 0))+ })+}++function column(title: string) {+ const el = container.querySelector(`section[aria-label="${title}"]`)+ if (!el) throw new Error(`no column ${title}`)+ return el+}+const titles = (el: Element) =>+ [...el.querySelectorAll('article h3 a')].map((a) => a.textContent)++function click(el: Element | null | undefined) {+ if (!el) throw new Error('nothing to click')+ act(() => {+ el.dispatchEvent(new MouseEvent('click', { bubbles: true }))+ })+}++describe('board', () => {+ const items = [+ makeItem({ number: 1, title: 'Mine, quiet', mine: true }),+ makeItem({+ number: 2,+ title: 'Mine, needs me',+ mine: true,+ updatedAt: minutesAgo(600),+ attention: { state: 'needs_you', name: null, since: minutesAgo(30) },+ }),+ makeItem({+ number: 3,+ title: 'Theirs, waiting',+ updatedAt: minutesAgo(10),+ attention: { state: 'waiting_on', name: 'Maya', since: minutesAgo(180) },+ }),+ makeItem({+ number: 4,+ title: 'Mine, done',+ mine: true,+ readyToClose: true,+ warnings: ['A Left item has no checkbox.'],+ }),+ ]++ it('shows my items in their columns, needing me first', async () => {+ workApi.getOpenItems.mockResolvedValue(openPage(items))+ workApi.getClosedItems.mockResolvedValue({+ items: [+ makeItem({+ number: 5,+ title: 'Closed lately',+ stage: 'closed',+ mine: true,+ closedAt: minutesAgo(60),+ closedBy: 'Igor',+ }),+ makeItem({+ number: 6,+ title: 'Closed long ago',+ stage: 'closed',+ mine: true,+ closedAt: minutesAgo(30 * 24 * 60),+ }),+ ],+ nextCursor: null,+ })+ await render('/computer/work')+ expect(titles(column('In progress'))).toEqual([+ 'Mine, needs me',+ 'Mine, quiet',+ ])+ expect(titles(column('Ready to close'))).toEqual(['Mine, done'])+ expect(titles(column('Closed'))).toEqual(['Closed lately'])+ expect(column('Closed').textContent).toContain('Closed by Igor')+ expect(column('In progress').textContent).toContain('needs you')+ expect(+ container.querySelector('[aria-label^="The doc has a problem"]'),+ ).not.toBeNull()+ })++ it('shows everyone, with others waiting in grey words', async () => {+ workApi.getOpenItems.mockResolvedValue(openPage(items))+ await render('/computer/work?tab=everyone')+ expect(titles(column('In progress'))).toEqual([+ 'Mine, needs me',+ 'Theirs, waiting',+ 'Mine, quiet',+ ])+ expect(column('In progress').textContent).toContain('waiting on Maya · 3h')+ })++ it('filters by text and by tag from the address', async () => {+ workApi.getOpenItems.mockResolvedValue(+ openPage([+ makeItem({ number: 1, title: 'Billing', tags: ['billing'] }),+ makeItem({ number: 2, title: 'Docs', tags: ['docs'] }),+ ]),+ )+ await render('/computer/work?tab=everyone&tag=docs')+ expect(titles(column('In progress'))).toEqual(['Docs'])+ act(() => root.unmount())+ root = createRoot(container)+ await render('/computer/work?tab=everyone&q=bill')+ expect(titles(column('In progress'))).toEqual(['Billing'])+ })++ it('points to Everyone when I own nothing', async () => {+ workApi.getOpenItems.mockResolvedValue(+ openPage([makeItem({ number: 3, title: 'Theirs' })]),+ )+ await render('/computer/work')+ expect(container.textContent).toContain('You own no items')+ click(+ [...container.querySelectorAll('button')].find(+ (b) => b.textContent === 'Everyone' && b.getAttribute('role') !== 'tab',+ ),+ )+ await flush()+ expect(titles(column('In progress'))).toEqual(['Theirs'])+ })++ it('explains what an item is before a repository is set', async () => {+ workApi.getOpenItems.mockResolvedValue(+ openPage([], { repository: null, head: null, asOf: null }),+ )+ 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(workApi.getClosedItems).not.toHaveBeenCalled()+ })++ it('reads a 404 as not available yet', async () => {+ workApi.getOpenItems.mockRejectedValue(new ApiError('Not found', 404))+ await render('/computer/work')+ expect(container.textContent).toContain('The board is not available yet')+ })++ it('sends a repository problem to settings', async () => {+ workApi.getOpenItems.mockResolvedValue(+ openPage(items, {+ repository: { ...repository, problem: 'access was removed' },+ }),+ )+ await render('/computer/work')+ expect(container.textContent).toContain(+ 'Cannot read acme/knowledge: access was removed.',+ )+ expect(+ container.querySelector('a[href="/computer#work-repository"]'),+ ).not.toBeNull()+ })++ it('offers no Close or Reopen yet', async () => {+ workApi.getOpenItems.mockResolvedValue(openPage(items))+ await render('/computer/work')+ const words = [...container.querySelectorAll('button')].map(+ (b) => b.textContent,+ )+ expect(words).not.toContain('Close')+ expect(words).not.toContain('Reopen')+ })+})++describe('item page', () => {+ const item = makeItem({+ number: 12,+ title: 'Usage billing',+ owner: { email: '[email protected]', name: 'Igor', id: 'usr_1' },+ author: { email: '[email protected]', name: 'Maya', id: null },+ tags: ['billing'],+ sessions: [+ { id: 'cs_1', title: 'Meter minutes', ownerName: 'Igor', status: 'idle' },+ ],+ pullRequests: [+ {+ url: 'https://github.com/acme/app/pull/41',+ state: 'merged',+ title: 'Meter',+ },+ ],+ })++ it('renders the doc under a header, with details beside it', async () => {+ workApi.getItem.mockResolvedValue({+ item,+ body: '---\nnumber: 12\n---\n# Usage billing\n\n## Why\n\nBecause.',+ })+ await render('/computer/work/12')+ expect(container.querySelector('h1')?.textContent).toBe('12Usage billing')+ expect(container.querySelector('article h2')?.textContent).toBe('Why')+ expect(container.textContent).toContain('started by Maya')+ expect(container.textContent).not.toContain('number: 12')+ expect(+ container.querySelector('a[href="/computer/sessions/cs_1"]')?.textContent,+ ).toBe('Meter minutes')+ expect(container.textContent).toContain('#41 Meter')+ expect(container.textContent).toContain('merged')+ expect(workApi.getHistory).not.toHaveBeenCalled()+ })++ it('says when an item has no owner', async () => {+ workApi.getItem.mockResolvedValue({+ item: { ...item, owner: null },+ body: 'x',+ })+ await render('/computer/work/12')+ expect(container.querySelector('header')?.textContent).toContain('no owner')+ })++ it('lists the changes on the History tab', async () => {+ workApi.getItem.mockResolvedValue({ item, body: 'x' })+ workApi.getHistory.mockResolvedValue({+ revisions: [+ {+ sha: 'abcdef1234567',+ url: 'https://github.com/acme/knowledge/commit/abcdef1',+ at: minutesAgo(5),+ authorName: 'Computer for Igor',+ summary: 'Record the price question',+ sessionId: 'cs_9',+ },+ ],+ nextCursor: null,+ })+ await render('/computer/work/12?tab=history')+ expect(workApi.getHistory).toHaveBeenCalledWith(12, undefined)+ expect(container.textContent).toContain('Record the price question')+ expect(container.textContent).toContain('Computer for Igor')+ expect(+ container.querySelector('a[href="/computer/sessions/cs_9"]'),+ ).not.toBeNull()+ expect(+ container.querySelector(+ 'a[href="https://github.com/acme/knowledge/commit/abcdef1"]',+ )?.textContent,+ ).toContain('abcdef1')+ })++ it('says when there is no such item', async () => {+ workApi.getItem.mockRejectedValue(new ApiError('Not found', 404))+ await render('/computer/work/99')+ expect(container.textContent).toContain('No such item')+ })+})