An open-source, faster Devin alternative
TypeScript
web: triage, one ask at a time (work-tracking step 1)
Igor Zalutski via Computerc205dffab322
diff --git a/web/src/App.tsx b/web/src/App.tsxindex a6b220eb..6cfb702d 100644--- a/web/src/App.tsx+++ b/web/src/App.tsx@@ -25,6 +25,9 @@ const ComputerSessionsHome = lazy(const ComputerSession = lazy(() => import('./managed-agents/computer-sessions/Session'),)+const ComputerTriage = lazy(+ () => import('./managed-agents/computer-sessions/Triage'),+)const ManagedAgentDetail = lazy(() => import('./managed-agents/Detail'))const ManagedProjectDetail = lazy(() => import('./managed-agents/Project'))const ManagedSessionDetail = lazy(() => import('./managed-agents/Session'))@@ -123,6 +126,7 @@ export default function App() {</Suspense>}>+ <Route path="computer/triage" element={<ComputerTriage />} /><Route path="computer/sessions"><Route index element={<ComputerSessionsHome />} />{/* The same home, for a phone, where the index is the list. */}diff --git a/web/src/api/mock-computer-sessions.ts b/web/src/api/mock-computer-sessions.tsindex a18564a5..89a62545 100644--- a/web/src/api/mock-computer-sessions.ts+++ b/web/src/api/mock-computer-sessions.ts@@ -28,6 +28,8 @@ type MockSession = Json & {lastText: string | nulllastSeq: numberlastActiveAt: string+ // The ask set aside in triage; the server keeps it on the session row.+ asideRef?: string | null}type MockEvent = Json & { seq: number; type: string }@@ -104,6 +106,7 @@ function history(s: MockSession,minAgo: number,steps: Array<[string, Json, Json?]>,+ turnId = 'tn_preview',) {const events = journal.get(s.id)!steps.forEach(([type, data, actor], i) => {@@ -112,7 +115,7 @@ function history(seq: events.length + 1,createdAt: ago(minAgo + (steps.length - i) * 0.4),sessionId: s.id,- turnId: 'tn_preview',+ turnId,actor: actor ?? null,type,data,@@ -180,16 +183,32 @@ function seed() {'Run psql on staging','psql $STAGING_URL -c "ALTER ROLE app PASSWORD \'…\'"',)+ ask.turnId = 'tn_rotate_2'rotate.asks = [ask]- history(rotate, 3, [- said('Rotate the staging database password and update the app secret.'),- ...tool('Read deploy/staging.env', 'Read'),- ...tool('grep -rn STAGING_DB_PASSWORD .'),- reply(- 'The app reads `STAGING_DB_PASSWORD` from the organization secrets. I will set a new password on the `app` role, then update the secret.',- ),- ['ask.opened', { ask }],- ])+ history(+ rotate,+ 9,+ [+ said('Which services read the staging database password?'),+ ...tool('grep -rn STAGING_DB_PASSWORD .'),+ reply('Only the app does, through `STAGING_DB_PASSWORD`.'),+ done,+ ],+ 'tn_rotate_1',+ )+ history(+ rotate,+ 3,+ [+ said('Rotate the staging database password and update the app secret.'),+ ...tool('Read deploy/staging.env', 'Read'),+ reply(+ 'The app reads `STAGING_DB_PASSWORD` from the organization secrets. I will set a new password on the `app` role, then update the secret.',+ ),+ ['ask.opened', { ask }],+ ],+ 'tn_rotate_2',+ )const charts = session('Pick a chart library for the usage page',@@ -233,6 +252,35 @@ function seed() {['ask.opened', { ask: question }],])+ const docs = session(+ 'Deploy the docs preview',+ 'waiting',+ 40,+ 'dashboard',+ null,+ )+ const secret = {+ id: nextId('ak'),+ sessionId: docs.id,+ turnId: 'tn_preview',+ kind: 'secret',+ status: 'open',+ createdAt: ago(40),+ closedAt: null,+ closedBy: null,+ answer: null,+ approval: null,+ question: null,+ secret: { name: 'VERCEL_TOKEN' },+ }+ docs.asks = [secret]+ history(docs, 40, [+ said('Deploy a preview of the docs site for the Sessions launch.'),+ ...tool('Read docs/vercel.json', 'Read'),+ reply('The deploy needs a Vercel token, and none is set.'),+ ['ask.opened', { ask: secret }],+ ])+const flaky = session('Fix the flaky checkout e2e test','running',@@ -414,6 +462,16 @@ function playTurn(s: MockSession, input: string) {steps.forEach((step, i) => setTimeout(step, 600 + i * 1300))}+// A session as the API returns it: `aside` while the ask set aside is still+// the oldest open one.+function view(s: MockSession): Json {+ const { asideRef, ...rest } = s+ const open = s.asks+ .filter((a) => a.status === 'open')+ .sort((a, b) => String(a.createdAt).localeCompare(String(b.createdAt)))+ return { ...rest, aside: !!asideRef && open[0]?.id === asideRef }+}+const wait = <T>(ms: number, value: () => T) =>new Promise<T>((resolve) => setTimeout(() => resolve(value()), ms))@@ -445,7 +503,7 @@ export function computerSessionsMock(.filter((s) => !q || s.title.toLowerCase().includes(q)).filter((s) => archived === 'all' || s.archived === (archived === 'true')).sort((a, b) => b.lastActiveAt.localeCompare(a.lastActiveAt))- return { sessions: rows, nextCursor: null }+ return { sessions: rows.map(view), nextCursor: null }}if (rest === '/sessions' && method === 'POST') {const text = typeof input.input === 'string' ? input.input : ''@@ -459,7 +517,7 @@ export function computerSessionsMock(s.settings = { ...settings, ...pick(input, ['model', 'effort', 'mode']) }emit(s, 'message.received', { input: text, delivery: 'started' }, me)playTurn(s, text)- return { session: s }+ return { session: view(s) }}const m = rest.match(/^\/sessions\/([^/]+)(\/.*)?$/)@@ -468,14 +526,22 @@ export function computerSessionsMock(if (!s) return undefinedconst sub = m[2] ?? ''- if (sub === '' && method === 'GET') return { session: s }+ if (sub === '' && method === 'GET') return { session: view(s) }if (sub === '' && method === 'PATCH') {Object.assign(s, pick(input, ['title', 'archived']))s.settings = {...(s.settings as Json),...pick(input, ['model', 'effort', 'mode']),}- return { session: s, seq: s.lastSeq }+ return { session: view(s), seq: s.lastSeq }+ }+ if (sub === '/aside' && method === 'PUT') {+ s.asideRef = typeof input.ref === 'string' ? input.ref : null+ return { session: view(s) }+ }+ if (sub === '/aside' && method === 'DELETE') {+ s.asideRef = null+ return { session: view(s) }}if (sub === '/events') {const events = journal.get(s.id)!@@ -506,6 +572,17 @@ export function computerSessionsMock(}if (sub === '/turns' && method === 'POST') {const text = typeof input.input === 'string' ? input.input : ''+ // Steering a waiting session answers its open asks with the message.+ if (input.ifBusy === 'steer') {+ for (const ask of s.asks.filter((a) => a.status === 'open')) {+ Object.assign(ask, {+ status: 'declined',+ closedAt: new Date().toISOString(),+ })+ emit(s, 'ask.closed', { ask })+ }+ s.asks = []+ }emit(s,'message.received',@@ -524,7 +601,7 @@ export function computerSessionsMock(emit(s, 'turn.cancelled', {})s.status = 'idle's.activeTurnId = null- return { session: s }+ return { session: view(s) }}const askMatch = sub.match(/^\/asks\/([^/]+)\/(answer|dismiss)$/)if (askMatch && method === 'POST') {diff --git a/web/src/managed-agents/computer-sessions/Layout.tsx b/web/src/managed-agents/computer-sessions/Layout.tsxindex 98a94f99..93bd64cc 100644--- a/web/src/managed-agents/computer-sessions/Layout.tsx+++ b/web/src/managed-agents/computer-sessions/Layout.tsx@@ -16,6 +16,7 @@ import {ChevronsUpDown,CreditCard,KeyRound,+ Inbox,Loader2,LogOut,MessagesSquare,@@ -57,6 +58,7 @@ import {WORKING,} from './state'import { timeAgo } from './transcript'+import { useTriageCount } from './triage'// The computer's own full-screen view (work 107): a flat icon rail, the// sessions sidebar, and the open session or the new-session home.@@ -69,6 +71,8 @@ export default function ComputerSessionsLayout() {const { user } = useAuth()const { pathname } = useLocation()const sessions = !!useMatch('/computer/sessions/*')+ // Triage is full height too, with its own panel instead of the sidebar.+ const full = !!useMatch('/computer/triage') || sessions// On a phone the list and a session take turns: the list at// /computer/sessions, the session (or the new-session home) on its own.const listing = !!useMatch({ path: '/computer/sessions', end: true })@@ -82,10 +86,10 @@ export default function ComputerSessionsLayout() {className={cn('min-w-0 flex-1',listing && 'hidden md:block',- !sessions && 'flex flex-col overflow-y-auto',+ !full && 'flex flex-col overflow-y-auto',)}>- {sessions ? null : (+ {full ? null : (<div className="sticky top-0 z-20"><BillingWarningBanner /></div>@@ -99,7 +103,7 @@ export default function ComputerSessionsLayout() {</div>}>- {sessions ? (+ {full ? (<Outlet />) : (<div@@ -125,27 +129,38 @@ function RailLink({to,label,end,+ badge,children,}: {to: stringlabel: stringend?: boolean+ badge?: numberchildren: ReactNode}) {+ const name = badge ? `${label}, ${badge}` : labelreturn (<NavLinkto={to}end={end}- title={label}- aria-label={label}+ title={name}+ aria-label={name}className={({ isActive }) =>cn(- 'text-muted-foreground hover:bg-sidebar-accent hover:text-foreground flex size-9 items-center justify-center rounded-md transition-colors',+ 'text-muted-foreground hover:bg-sidebar-accent hover:text-foreground relative flex size-9 items-center justify-center rounded-md transition-colors',isActive && 'bg-sidebar-accent text-foreground',)}>{children}+ {badge ? (+ <span+ aria-hidden+ className="bg-primary text-primary-foreground absolute -top-0.5 -right-0.5 flex h-4 min-w-4 items-center justify-center rounded-full px-1 text-[10px] leading-none font-medium"+ >+ {badge > 99 ? '99+' : badge}+ </span>+ ) : null}</NavLink>)}@@ -156,6 +171,7 @@ function Rail() {const navigate = useNavigate()const orgs = user?.orgs ?? []const activeOrg = orgs.find((o) => o.isActive)+ const asks = useTriageCount(!!user?.computerEnabled)return (<nav className="bg-sidebar border-sidebar-border flex w-14 shrink-0 flex-col items-center gap-1 border-r py-3"><Link@@ -166,9 +182,14 @@ function Rail() {<OpenComputerMark className="size-8" /></Link>{user?.computerEnabled ? (- <RailLink to="/computer/sessions" label="Sessions">- <MessagesSquare className="size-4" aria-hidden />- </RailLink>+ <>+ <RailLink to="/computer/triage" label="Triage" badge={asks}>+ <Inbox className="size-4" aria-hidden />+ </RailLink>+ <RailLink to="/computer/sessions" label="Sessions">+ <MessagesSquare className="size-4" aria-hidden />+ </RailLink>+ </>) : null}<RailLink to="/automations" label="Automations"><CalendarClock className="size-4" aria-hidden />diff --git a/web/src/managed-agents/computer-sessions/Triage.test.tsx b/web/src/managed-agents/computer-sessions/Triage.test.tsxnew file mode 100644index 00000000..8a3b62f5--- /dev/null+++ b/web/src/managed-agents/computer-sessions/Triage.test.tsx@@ -0,0 +1,290 @@+// @vitest-environment happy-dom++import { act } from 'react'+import { createRoot, type Root } from 'react-dom/client'+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'+import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import type {+ Ask,+ ListSessionsQuery,+ Session,+ SessionEvent,+} from '../computer-sessions-api'++const api = vi.hoisted(() => ({+ listSessions: vi.fn(),+ getEvents: vi.fn(),+ getCapabilities: vi.fn(),+ sendTurn: vi.fn(),+ setAside: vi.fn(),+ bringBack: vi.fn(),+ answerAsk: vi.fn(),+ dismissAsk: vi.fn(),+}))+vi.mock('../computer-sessions-api', async (importOriginal) => ({+ ...(await importOriginal<typeof import('../computer-sessions-api')>()),+ ...api,+}))+vi.mock('@/api/client', async (importOriginal) => ({+ ...(await importOriginal<typeof import('@/api/client')>()),+ getOrgMembers: vi.fn(() => Promise.resolve([])),+}))++const { default: Triage } = await import('./Triage')++const ask = (id: string, sessionId: string, min: number): Ask => ({+ id,+ sessionId,+ turnId: `tn_${sessionId}`,+ kind: 'other',+ status: 'open',+ createdAt: new Date(Date.now() - min * 60_000).toISOString(),+})+const session = (id: string, asks: Ask[], status = 'waiting'): Session => ({+ id,+ title: `Thread ${id}`,+ status,+ archived: false,+ aside: false,+ owner: null,+ origin: { type: 'dashboard' },+ settings: { model: null, effort: null, mode: null },+ activeTurnId: null,+ asks,+ lastText: 'checking the logs',+ lastSeq: 1,+ createdAt: new Date().toISOString(),+ lastActiveAt: new Date().toISOString(),+})++// The server's view: waiting sessions with their asks and what is set aside.+let waiting: Session[] = []+let working: Session[] = []+const asideRefs = new Map<string, string>()+const shown = () =>+ waiting.map((s) => ({ ...s, aside: asideRefs.get(s.id) === s.asks[0]?.id }))++let seq = 0+const ev = (+ turnId: string,+ type: string,+ data: Record<string, unknown>,+): SessionEvent => ({+ id: `ev_${++seq}`,+ seq,+ createdAt: new Date().toISOString(),+ turnId,+ actor: type === 'message.received' ? { name: 'Igor' } : null,+ type,+ data,+})++async function settle(until: () => boolean, label: string) {+ for (let attempt = 0; attempt < 50; attempt += 1) {+ if (until()) return+ await act(async () => {+ await new Promise((resolve) => setTimeout(resolve, 0))+ })+ }+ throw new Error(`Timed out waiting for ${label}`)+}++function Location() {+ const location = useLocation()+ return <output data-testid="location">{location.search}</output>+}++describe('Triage', () => {+ let container: HTMLDivElement+ let root: Root+ let client: QueryClient++ beforeEach(() => {+ ;(+ globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }+ ).IS_REACT_ACT_ENVIRONMENT = true+ container = document.createElement('div')+ document.body.append(container)+ root = createRoot(container)+ client = new QueryClient({+ defaultOptions: {+ queries: { retry: false },+ mutations: { retry: false },+ },+ })+ waiting = [+ session('b', [ask('ak_b', 'b', 5)]),+ session('a', [ask('ak_a', 'a', 30)]),+ ]+ working = [1, 2, 3, 4, 5, 6, 7].map((i) => session(`w${i}`, [], 'running'))+ asideRefs.clear()+ api.listSessions.mockImplementation((q: ListSessionsQuery) =>+ Promise.resolve({+ sessions: q.status === 'waiting' ? shown() : working,+ nextCursor: null,+ }),+ )+ api.getEvents.mockImplementation((id: string) =>+ Promise.resolve({+ events: [+ ev('tn_old', 'message.received', { input: `Earlier in ${id}` }),+ ev('tn_old', 'turn.completed', {}),+ ev(`tn_${id}`, 'message.received', { input: `Start ${id}` }),+ ev(`tn_${id}`, 'message.completed', { text: `Asking in ${id}` }),+ ],+ earlierTurns: [{}, {}],+ lastSeq: seq,+ hasMore: false,+ }),+ )+ api.getCapabilities.mockResolvedValue({+ models: [],+ modes: [],+ features: { steer: true },+ })+ api.setAside.mockImplementation((id: string, ref: string) => {+ asideRefs.set(id, ref)+ return Promise.resolve(shown().find((s) => s.id === id))+ })+ })++ afterEach(() => {+ act(() => root.unmount())+ container.remove()+ vi.clearAllMocks()+ })++ const render = (path = '/computer/triage') =>+ act(() => {+ root.render(+ <QueryClientProvider client={client}>+ <MemoryRouter initialEntries={[path]}>+ <Routes>+ <Route+ path="/computer/triage"+ element={+ <>+ <Triage />+ <Location />+ </>+ }+ />+ </Routes>+ </MemoryRouter>+ </QueryClientProvider>,+ )+ })+ const text = () => container.textContent ?? ''+ const location = () =>+ container.querySelector('[data-testid="location"]')!.textContent+ const button = (name: string) =>+ [...container.querySelectorAll('button')].find(+ (b) => b.textContent === name || b.getAttribute('aria-label') === name,+ )!+ const box = () => container.querySelector('textarea')!+ const type = (value: string) =>+ act(() => {+ Object.getOwnPropertyDescriptor(+ HTMLTextAreaElement.prototype,+ 'value',+ )?.set?.call(box(), value)+ box().dispatchEvent(new Event('input', { bubbles: true }))+ })+ const click = (el: Element) =>+ act(() => {+ ;(el as HTMLElement).click()+ })++ it('opens the oldest ask with its excerpt, and lists the rest', async () => {+ render()+ await settle(() => location() === '?ask=ak_a', 'the oldest ask selected')+ await settle(() => text().includes('Asking in a'), 'the excerpt')+ expect(container.querySelector('h1')?.textContent).toBe('Needs you')+ expect(text()).toContain('2 earlier messages')+ expect(text()).toContain('where it stopped')+ // The rule sits before the asking turn, after the earlier one.+ const rule = text().indexOf('where it stopped')+ expect(text().indexOf('Earlier in a')).toBeLessThan(rule)+ expect(text().indexOf('Start a')).toBeGreaterThan(rule)+ expect(+ container.querySelector('[aria-current="true"]')?.textContent,+ ).toContain('Thread a')+ // Agents working: five rows, then the rest as a link to Sessions.+ expect(text()).toContain('2 more')+ expect(text()).not.toContain('Set aside2')+ })++ it('keeps typed text per ask, and a reply answers it and moves on', async () => {+ api.sendTurn.mockImplementation((id: string) => {+ waiting = waiting.filter((s) => s.id !== id)+ return Promise.resolve({+ turn: { id: 'tn_x', status: 'running' },+ delivery: 'started',+ })+ })+ render()+ await settle(() => location() === '?ask=ak_a', 'the oldest ask selected')+ type('use the token bucket')+ const rowB = [...container.querySelectorAll('aside button')].find((b) =>+ b.textContent?.includes('Thread b'),+ )!+ click(rowB)+ await settle(() => location() === '?ask=ak_b', 'the second ask')+ expect(box().value).toBe('')+ const rowA = [...container.querySelectorAll('aside button')].find((b) =>+ b.textContent?.includes('Thread a'),+ )!+ click(rowA)+ await settle(() => box().value === 'use the token bucket', 'the draft')++ click(button('Send'))+ await settle(() => location() === '?ask=ak_b', 'the next ask')+ expect(api.sendTurn).toHaveBeenCalledWith(+ 'a',+ 'use the token bucket',+ 'steer',+ )+ })++ it('says "Not sent" and keeps the text when sending fails', async () => {+ api.sendTurn.mockRejectedValueOnce(new Error('offline'))+ render('/computer/triage?ask=ak_a')+ await settle(() => !!container.querySelector('textarea'), 'the box')+ type('ship it')+ click(button('Send'))+ await settle(() => text().includes('Not sent'), 'the failure')+ expect(box().value).toBe('ship it')+ expect(location()).toBe('?ask=ak_a')+ api.sendTurn.mockResolvedValueOnce({+ turn: { id: 'tn_x', status: 'running' },+ delivery: 'started',+ })+ click(button('Retry'))+ await settle(() => location() === '?ask=ak_b', 'the next ask')+ })++ it('sets an ask aside, and ends on "All clear" with what is set aside', async () => {+ waiting = [waiting[1]]+ render()+ await settle(() => location() === '?ask=ak_a', 'the ask')+ click(button('Set aside'))+ await settle(() => text().includes('All clear'), 'all clear')+ expect(api.setAside).toHaveBeenCalledWith('a', 'ak_a')+ expect(text()).toContain('1 set aside')+ expect(text()).toContain('Set aside1')+ })++ it('keeps an ask answered elsewhere on screen, with Next', async () => {+ render('/computer/triage?ask=ak_a')+ await settle(() => text().includes('Asking in a'), 'the ask')+ waiting = waiting.filter((s) => s.id !== 'a')+ await act(() => client.refetchQueries())+ await settle(+ () => text().includes('This was answered elsewhere.'),+ 'the line',+ )+ click(button('Next'))+ await settle(() => location() === '?ask=ak_b', 'the next ask')+ })+})diff --git a/web/src/managed-agents/computer-sessions/Triage.tsx b/web/src/managed-agents/computer-sessions/Triage.tsxnew file mode 100644index 00000000..1e86b805--- /dev/null+++ b/web/src/managed-agents/computer-sessions/Triage.tsx@@ -0,0 +1,471 @@+import {+ useEffect,+ useLayoutEffect,+ useMemo,+ useRef,+ useState,+ type ReactNode,+} from 'react'+import { Link, useSearchParams } from 'react-router-dom'+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'+import { ArrowUp, Loader2 } from 'lucide-react'+import { ChatTextarea } from '@/components/chat-textarea'+import { Button } from '@/components/ui/button'+import { notifyError } from '@/lib/errors'+import { cn } from '@/lib/utils'+import {+ bringBack,+ getEvents,+ sendTurn,+ sessionKeys,+ setAside,+ type Session,+} from '../computer-sessions-api'+import { Item } from './conversation'+import { useMemberEmails } from './members'+import { AskCard, StatusDot } from './parts'+import { sessionLine, sessionTitle, useCapabilities } from './state'+import { TRIAGE_NEEDS, useTriage, type TriageEntry } from './triage'+import { buildTranscript, timeAgo } from './transcript'++// Triage (work-tracking ux-spec 3): one ask at a time, answer, next. The ask+// on screen is `?ask=<id>`; nothing replaces it while it is shown.++const WORKING_ROWS = 5+// Asks the agent put as a dialog, answered with AskCard's buttons.+const DIALOGS = new Set(['approval', 'question', 'secret'])++export default function Triage() {+ const qc = useQueryClient()+ const { needs, aside, working, loaded } = useTriage()+ const [params, setParams] = useSearchParams()+ const want = params.get('ask')+ // Text typed for each ask, kept when moving between rows.+ const [drafts, setDrafts] = useState<Record<string, string>>({})+ // Asks answered from here: they leave the list before the next poll says so.+ const [done, setDone] = useState<ReadonlySet<string>>(new Set())+ const open = needs.filter((e) => !done.has(e.ref))++ // The ask on screen, kept once its row is gone so the card does not vanish.+ const live = [...needs, ...aside].find((e) => e.ref === want) ?? null+ const [shown, setShown] = useState<TriageEntry | null>(null)+ if (live && live !== shown) setShown(live)+ const entry = live ?? (shown?.ref === want ? shown : null)+ const gone = !live && !!entry && !done.has(entry.ref)++ const go = (ref: string | null, replace = false) =>+ setParams(ref ? { ask: ref } : {}, { replace })+ const next = (after: string) =>+ open.find((e) => e.ref !== after && !done.has(e.ref))?.ref ?? null++ // Nothing (or an unknown ask) selected: open the oldest that needs you.+ const first = open[0]?.ref ?? null+ useEffect(() => {+ if (!loaded || entry) return+ if (first || want) go(first, true)+ // `go` changes every render; this follows the data only.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [loaded, entry, first, want])++ const answered = (ref: string) => {+ setDone((d) => new Set(d).add(ref))+ setDrafts((d) => {+ const rest = { ...d }+ delete rest[ref]+ return rest+ })+ go(next(ref))+ }+ const refetch = () =>+ qc.refetchQueries({ queryKey: sessionKeys.list(TRIAGE_NEEDS) })++ return (+ <div className="flex h-full">+ <aside className="border-border hidden w-80 shrink-0 flex-col overflow-y-auto border-r md:flex">+ <Section label="Needs you" count={loaded ? open.length : undefined}>+ {loaded && !open.length ? (+ <p className="text-muted-foreground px-3 py-1 text-sm">+ Nothing right now.+ </p>+ ) : null}+ {open.map((e) => (+ <AskRow+ key={e.ref}+ entry={e}+ current={e.ref === entry?.ref}+ onClick={() => go(e.ref)}+ />+ ))}+ </Section>+ {aside.length ? (+ <Section label="Set aside" count={aside.length}>+ {aside.map((e) => (+ <AskRow+ key={e.ref}+ entry={e}+ current={e.ref === entry?.ref}+ onClick={() => go(e.ref)}+ />+ ))}+ </Section>+ ) : null}+ <Section+ label="Agents working"+ count={loaded ? working.length : undefined}+ >+ {working.slice(0, WORKING_ROWS).map((s) => (+ <WorkingRow key={s.id} session={s} />+ ))}+ {working.length > WORKING_ROWS ? (+ <Link+ to="/computer/sessions"+ className="text-muted-foreground hover:text-foreground block px-3 py-1 text-xs"+ >+ {working.length - WORKING_ROWS} more+ </Link>+ ) : null}+ </Section>+ </aside>+ <div className="min-w-0 flex-1">+ {entry ? (+ <AskView+ key={entry.ref}+ entry={entry}+ gone={gone}+ draft={drafts[entry.ref] ?? ''}+ setDraft={(text) => setDrafts((d) => ({ ...d, [entry.ref]: text }))}+ onAnswered={() => answered(entry.ref)}+ onAside={async () => {+ await refetch()+ go(next(entry.ref))+ }}+ onBack={() => void refetch()}+ onNext={() => go(next(entry.ref))}+ />+ ) : loaded ? (+ <AllClear+ working={working.length}+ aside={aside.length}+ onAside={() => go(aside[0]?.ref ?? null)}+ />+ ) : null}+ </div>+ </div>+ )+}++function Section({+ label,+ count,+ children,+}: {+ label: string+ count?: number+ children: ReactNode+}) {+ return (+ <section className="border-border space-y-0.5 border-b px-2 py-4 last:border-b-0">+ <h2 className="flex items-baseline gap-2 px-3 pb-1.5 text-sm font-medium">+ {label}+ {count !== undefined ? (+ <span className="text-muted-foreground text-xs font-normal">+ {count}+ </span>+ ) : null}+ </h2>+ {children}+ </section>+ )+}++function AskRow({+ entry,+ current,+ onClick,+}: {+ entry: TriageEntry+ current: boolean+ onClick: () => void+}) {+ return (+ <button+ type="button"+ onClick={onClick}+ aria-current={current ? 'true' : undefined}+ className={cn(+ 'hover:bg-muted/60 flex w-full items-start gap-2 rounded-md px-3 py-1.5 text-left',+ current && 'bg-muted',+ )}+ >+ <span className="min-w-0 flex-1">+ <span className="block truncate text-sm">{entry.line}</span>+ <span className="text-muted-foreground block truncate text-xs">+ {sessionTitle(entry.session)}+ </span>+ </span>+ <span className="text-muted-foreground shrink-0 pt-0.5 text-xs">+ {timeAgo(entry.at)}+ </span>+ </button>+ )+}++function WorkingRow({ session }: { session: Session }) {+ const line = sessionLine(session)+ return (+ <Link+ to={`/computer/sessions/${session.id}`}+ className="hover:bg-muted/60 flex items-start gap-2 rounded-md px-3 py-1.5"+ >+ <StatusDot status={session.status} className="mt-1.5" />+ <span className="min-w-0 flex-1">+ <span className="block truncate text-sm">{sessionTitle(session)}</span>+ {line ? (+ <span className="text-muted-foreground block truncate text-xs">+ {line}+ </span>+ ) : null}+ </span>+ </Link>+ )+}++function AllClear({+ working,+ aside,+ onAside,+}: {+ working: number+ aside: number+ onAside: () => void+}) {+ return (+ <div className="flex h-full flex-col items-center justify-center gap-3 px-6 text-center">+ <h1 className="text-2xl font-semibold tracking-tight">All clear</h1>+ {aside ? (+ <Button variant="outline" size="sm" onClick={onAside}>+ {aside} set aside+ </Button>+ ) : working ? (+ <p className="text-muted-foreground max-w-sm text-sm">+ {working} {working === 1 ? 'agent is' : 'agents are'} working. The+ next one that needs you appears here.+ </p>+ ) : null}+ </div>+ )+}++function AskView({+ entry,+ gone,+ draft,+ setDraft,+ onAnswered,+ onAside,+ onBack,+ onNext,+}: {+ entry: TriageEntry+ gone: boolean+ draft: string+ setDraft: (text: string) => void+ onAnswered: () => void+ onAside: () => Promise<void>+ onBack: () => void+ onNext: () => void+}) {+ const { session: s, ask } = entry+ const { data: caps } = useCapabilities()+ // Focus in the box when the ask appears.+ const answer = useRef<HTMLDivElement>(null)+ useEffect(() => answer.current?.querySelector('textarea')?.focus(), [])++ // A reply is the answer: steering closes the open asks with the message+ // (turns, "Open asks close as declined; the message is the answer"). Once+ // the ask is gone, the text goes as an ordinary message.+ const send = useMutation({+ mutationFn: (text: string) =>+ sendTurn(+ s.id,+ text,+ !gone && caps?.features.steer !== false ? 'steer' : 'queue',+ ),+ onSuccess: () => (gone ? setDraft('') : onAnswered()),+ })+ const aside = useMutation({+ mutationFn: () =>+ entry.aside ? bringBack(s.id) : setAside(s.id, entry.ref),+ onSuccess: () => (entry.aside ? onBack() : onAside()),+ onError: (e) =>+ notifyError(+ entry.aside ? 'Could not bring it back' : 'Could not set it aside',+ e,+ ),+ })+ const submit = () => {+ if (draft.trim() && !send.isPending) send.mutate(draft.trim())+ }+ const dialog = !gone && DIALOGS.has(ask.kind)++ return (+ <div className="mx-auto flex h-full w-full max-w-3xl flex-col px-6 pt-8 pb-5">+ <header className="shrink-0 space-y-1 pb-4">+ <p className="text-muted-foreground flex min-w-0 items-center gap-1.5 text-sm">+ <span className="truncate">{sessionTitle(s)}</span>+ <span aria-hidden>·</span>+ <span className="shrink-0">{timeAgo(entry.at)} ago</span>+ </p>+ <h1 className="text-xl font-semibold tracking-tight">{entry.line}</h1>+ </header>++ <Conversation session={s} turnId={ask.turnId} />++ <div ref={answer} className="shrink-0 space-y-2 pt-4">+ {gone ? (+ <div className="flex items-center justify-between gap-3 rounded-lg border px-3 py-2 text-sm">+ <span className="text-muted-foreground">+ This was answered elsewhere.+ </span>+ <Button size="sm" onClick={onNext}>+ Next+ </Button>+ </div>+ ) : dialog ? (+ <AskCard ask={ask} session={s} hideTitle onAnswered={onAnswered} />+ ) : null}+ <div className="bg-card focus-within:border-ring/60 rounded-xl border shadow-sm transition-colors">+ <ChatTextarea+ value={draft}+ onChange={(e) => setDraft(e.target.value)}+ onSend={submit}+ placeholder={gone ? 'Message the agent' : 'Reply'}+ aria-label="Reply"+ className="min-h-11 resize-none border-0 bg-transparent px-4 pt-3 shadow-none focus-visible:ring-0 dark:bg-transparent"+ />+ <div className="flex items-center justify-end gap-1.5 px-2 pb-2">+ {send.isError ? (+ <p+ role="alert"+ className="text-destructive mr-auto flex items-center gap-2 px-2 text-xs"+ >+ Not sent+ <button+ type="button"+ className="underline underline-offset-2"+ onClick={submit}+ >+ Retry+ </button>+ </p>+ ) : null}+ {gone ? null : (+ <Button+ size="sm"+ variant="ghost"+ disabled={aside.isPending}+ onClick={() => aside.mutate()}+ >+ {entry.aside ? 'Bring back' : 'Set aside'}+ </Button>+ )}+ <Button+ size="icon"+ className="rounded-full"+ aria-label="Send"+ disabled={!draft.trim() || send.isPending}+ onClick={submit}+ >+ {send.isPending ? (+ <Loader2 className="animate-spin" aria-hidden />+ ) : (+ <ArrowUp aria-hidden />+ )}+ </Button>+ </div>+ </div>+ </div>+ </div>+ )+}++const TAIL_TURNS = 3++// The excerpt: a link to the earlier messages, then the last turns, with a+// rule where the asking turn starts.+function Conversation({+ session,+ turnId,+}: {+ session: Session+ turnId: string | null+}) {+ const page = useQuery({+ queryKey: sessionKeys.events(session.id, { tailTurns: TAIL_TURNS }),+ queryFn: () => getEvents(session.id, { tailTurns: TAIL_TURNS }),+ refetchInterval: 10_000,+ })+ const emails = useMemberEmails()+ const events = page.data?.events+ const [before, after] = useMemo(() => {+ const all = events ?? []+ const at = turnId ? all.findIndex((e) => e.turnId === turnId) : -1+ if (at <= 0) return [buildTranscript(all), []]+ return [buildTranscript(all.slice(0, at)), buildTranscript(all.slice(at))]+ }, [events, turnId])+ const earlier = page.data?.earlierTurns?.length ?? 0++ const scroller = useRef<HTMLDivElement>(null)+ useLayoutEffect(() => {+ const el = scroller.current+ if (el) el.scrollTop = el.scrollHeight+ }, [before.length, after.length])++ const items = (list: typeof before) =>+ list.map((item, i) => (+ <Item+ key={item.key}+ item={item}+ emails={emails}+ leads={i === 0 || list[i - 1].kind === 'user'}+ />+ ))++ return (+ <section+ aria-label="Conversation"+ className="flex min-h-0 flex-1 flex-col rounded-xl border"+ >+ <div className="border-border flex h-10 shrink-0 items-center justify-between gap-3 border-b px-4 text-xs">+ <span className="font-medium">Conversation</span>+ <Link+ to={`/computer/sessions/${session.id}`}+ className="text-muted-foreground hover:text-foreground underline-offset-2 hover:underline"+ >+ Open the session+ </Link>+ </div>+ <div ref={scroller} className="min-h-0 flex-1 overflow-y-auto">+ <div className="space-y-5 px-5 py-4">+ {earlier ? (+ <Link+ to={`/computer/sessions/${session.id}`}+ className="text-muted-foreground hover:text-foreground block text-center text-xs"+ >+ {earlier} earlier {earlier === 1 ? 'message' : 'messages'}+ </Link>+ ) : null}+ {items(before)}+ {after.length ? (+ <div className="text-muted-foreground flex items-center gap-3 text-xs">+ <span className="bg-border h-px flex-1" />+ where it stopped+ <span className="bg-border h-px flex-1" />+ </div>+ ) : null}+ {items(after)}+ </div>+ </div>+ </section>+ )+}diff --git a/web/src/managed-agents/computer-sessions/triage.test.ts b/web/src/managed-agents/computer-sessions/triage.test.tsnew file mode 100644index 00000000..39be9bb9--- /dev/null+++ b/web/src/managed-agents/computer-sessions/triage.test.ts@@ -0,0 +1,79 @@+import { describe, expect, it } from 'vitest'+import type { Ask, Session } from '../computer-sessions-api'+import { triageEntries, triageEntry } from './triage'++const ask = (id: string, createdAt: string, status = 'open'): Ask => ({+ id,+ sessionId: 'cs_1',+ turnId: 'tn_1',+ kind: 'question',+ status,+ createdAt,+ question: {+ questions: [+ {+ id: 'q1',+ header: 'Library',+ text: `Question ${id}?`,+ multiSelect: false,+ options: [],+ },+ ],+ },+})++const session = (id: string, asks: Ask[], aside = false): Session => ({+ id,+ title: `Session ${id}`,+ status: 'waiting',+ archived: false,+ aside,+ owner: null,+ origin: { type: 'dashboard' },+ settings: { model: null, effort: null, mode: null },+ activeTurnId: null,+ asks,+ lastText: null,+ lastSeq: 1,+ createdAt: '2026-11-19T10:00:00.000Z',+ lastActiveAt: null,+})++describe('triageEntry', () => {+ it("is the session's oldest open ask, headed with its words", () => {+ const e = triageEntry(+ session('a', [+ ask('ak_new', '2026-11-19T12:00:00.000Z'),+ ask('ak_closed', '2026-11-19T09:00:00.000Z', 'answered'),+ ask('ak_old', '2026-11-19T11:00:00.000Z'),+ ]),+ )+ expect(e).toMatchObject({+ ref: 'ak_old',+ line: 'Question ak_old?',+ at: '2026-11-19T11:00:00.000Z',+ aside: false,+ })+ })++ it('is null when nothing is open', () => {+ expect(+ triageEntry(+ session('a', [ask('ak_1', '2026-11-19T09:00:00.000Z', 'declined')]),+ ),+ ).toBeNull()+ })+})++describe('triageEntries', () => {+ it('orders asks oldest first and keeps set-aside ones apart', () => {+ const { needs, aside } = triageEntries([+ session('late', [ask('ak_late', '2026-11-19T12:00:00.000Z')]),+ session('none', []),+ session('early', [ask('ak_early', '2026-11-19T08:00:00.000Z')]),+ session('away', [ask('ak_away', '2026-11-19T07:00:00.000Z')], true),+ ])+ expect(needs.map((e) => e.ref)).toEqual(['ak_early', 'ak_late'])+ expect(aside.map((e) => e.ref)).toEqual(['ak_away'])+ })+})diff --git a/web/src/managed-agents/computer-sessions/triage.ts b/web/src/managed-agents/computer-sessions/triage.tsnew file mode 100644index 00000000..332ab502--- /dev/null+++ b/web/src/managed-agents/computer-sessions/triage.ts@@ -0,0 +1,102 @@+import { useMemo } from 'react'+import { useQuery } from '@tanstack/react-query'+import {+ listSessions,+ sessionKeys,+ type Ask,+ type ListSessionsQuery,+ type Session,+} from '../computer-sessions-api'+import { askTitle } from './state'++// What triage shows (work-tracking, ux-spec 3): the caller's own sessions+// that wait on them, one ask each. For now an ask is a session's oldest open+// ask, found from the session list. When sessions carry `attention` (tech+// design 3.7), this file is the one place that changes: the query asks for+// attention instead of `waiting`, and `triageEntry` reads `attention.ref` and+// its headline instead of the oldest open ask.++export const TRIAGE_NEEDS: ListSessionsQuery = {+ owner: 'me',+ status: 'waiting',+ limit: 50,+}+export const TRIAGE_WORKING: ListSessionsQuery = {+ owner: 'me',+ status: 'starting,running',+ limit: 50,+}++export type TriageEntry = {+ /** The ask's id: what Set aside stores, and what the screen selects by. */+ ref: string+ session: Session+ ask: Ask+ /** The ask in one line, the screen's headline. */+ line: string+ /** When the ask opened. */+ at: string+ aside: boolean+}++/** The session's ask for triage: its oldest open ask, or null when none is open. */+export function triageEntry(s: Session): TriageEntry | null {+ const ask = s.asks+ .filter((a) => a.status === 'open')+ .sort((a, b) => a.createdAt.localeCompare(b.createdAt))[0]+ if (!ask) return null+ return {+ ref: ask.id,+ session: s,+ ask,+ line: askTitle(ask),+ at: ask.createdAt,+ aside: s.aside,+ }+}++/** Asks oldest first, split into those that need you and those set aside. */+export function triageEntries(sessions: Session[]) {+ const all = sessions+ .map(triageEntry)+ .filter((e): e is TriageEntry => e !== null)+ .sort((a, b) => a.at.localeCompare(b.at))+ return {+ needs: all.filter((e) => !e.aside),+ aside: all.filter((e) => e.aside),+ }+}++export function useTriage() {+ const needs = useQuery({+ queryKey: sessionKeys.list(TRIAGE_NEEDS),+ queryFn: () => listSessions(TRIAGE_NEEDS),+ refetchInterval: 5_000,+ })+ const working = useQuery({+ queryKey: sessionKeys.list(TRIAGE_WORKING),+ queryFn: () => listSessions(TRIAGE_WORKING),+ refetchInterval: 5_000,+ })+ // Kept while the list is unchanged, so an entry's identity says whether it moved.+ const entries = useMemo(+ () => triageEntries(needs.data?.sessions ?? []),+ [needs.data],+ )+ return {+ ...entries,+ working: working.data?.sessions ?? [],+ loaded: needs.isSuccess,+ }+}++/** The rail's badge: asks that need you, set-aside ones not counted. */+export function useTriageCount(enabled = true) {+ const { data } = useQuery({+ queryKey: sessionKeys.list(TRIAGE_NEEDS),+ queryFn: () => listSessions(TRIAGE_NEEDS),+ refetchInterval: 15_000,+ enabled,+ })+ return triageEntries(data?.sessions ?? []).needs.length+}