An open-source, faster Devin alternative
TypeScript
web: set aside and the events excerpt in the sessions client; the transcript items shared
Igor Zalutski via Computer2e250dc9cae9
diff --git a/web/src/managed-agents/computer-sessions-api.ts b/web/src/managed-agents/computer-sessions-api.tsindex 05e47471..1082755a 100644--- a/web/src/managed-agents/computer-sessions-api.ts+++ b/web/src/managed-agents/computer-sessions-api.ts@@ -56,6 +56,8 @@ export const SessionSchema = z.looseObject({title: z.string().nullable(),status: z.string(),archived: z.boolean(),+ // Set aside by its owner in triage, until something newer needs them.+ aside: z.boolean().default(false),owner: PersonSchema.nullable(),origin: z.looseObject({type: z.string(),@@ -107,6 +109,8 @@ const EventPageSchema = z.looseObject({events: z.array(EventSchema),lastSeq: z.number(),hasMore: z.boolean(),+ // With `tailTurns`: the turns before the tail, as one line each.+ earlierTurns: z.array(z.unknown()).nullable().optional(),})export type EventPage = z.infer<typeof EventPageSchema>@@ -132,6 +136,7 @@ const SendResultSchema = z.looseObject({const AskResultSchema = z.looseObject({ ask: AskSchema })export type ListSessionsQuery = {+ owner?: 'me' | 'anyone'status?: stringq?: stringarchived?: 'false' | 'true' | 'all'@@ -220,6 +225,26 @@ export function updateSession().then((r) => r.session)}+// Sets the session aside in triage until something newer needs its owner:+// `ref` is the ask being set aside. Owner only.+export function setAside(id: string, ref: string) {+ return apiFetch(+ `${PREFIX}/sessions/${encodeURIComponent(id)}/aside`,+ { method: 'PUT', body: JSON.stringify({ ref }) },+ SessionResultSchema,+ '/api',+ ).then((r) => r.session)+}++export function bringBack(id: string) {+ return apiFetch(+ `${PREFIX}/sessions/${encodeURIComponent(id)}/aside`,+ { method: 'DELETE' },+ SessionResultSchema,+ '/api',+ ).then((r) => r.session)+}+export type IfBusy = 'queue' | 'steer' | 'interrupt'export function sendTurn(id: string, input: string, ifBusy: IfBusy) {@@ -303,5 +328,7 @@ export const sessionKeys = {all: ['computer-sessions'] as const,list: (q: ListSessionsQuery) => ['computer-sessions', 'list', q] as const,one: (id: string) => ['computer-sessions', 'one', id] as const,+ events: (id: string, q: object) =>+ ['computer-sessions', 'events', id, q] as const,capabilities: ['computer-sessions', 'capabilities'] as const,}diff --git a/web/src/managed-agents/computer-sessions/Session.tsx b/web/src/managed-agents/computer-sessions/Session.tsxindex 795e59de..2d948979 100644--- a/web/src/managed-agents/computer-sessions/Session.tsx+++ b/web/src/managed-agents/computer-sessions/Session.tsx@@ -1,32 +1,13 @@import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'import { Link, useParams } from 'react-router-dom'import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'-import {- Archive,- ArchiveRestore,- ArrowUp,- Check,- ChevronRight,- CircleAlert,- Loader2,- Square,- X,- User,-} from 'lucide-react'-import { ApiError, getOrgMembers } from '@/api/client'-import type { OrgMember } from '@/api/schemas'+import { Archive, ArchiveRestore, ArrowUp, Loader2, Square } from 'lucide-react'+import { ApiError } from '@/api/client'import { ChatTextarea } from '@/components/chat-textarea'import { SlackMark } from '@/components/slack-mark'import { Button } from '@/components/ui/button'-import {- Tooltip,- TooltipContent,- TooltipProvider,- TooltipTrigger,-} from '@/components/ui/tooltip'import { notifyError } from '@/lib/errors'import { cn } from '@/lib/utils'-import { AgentMarkdown } from '../AgentMarkdown'import {getEvents,getSession,@@ -38,21 +19,17 @@ import {type SessionEvent,type SessionSettings,} from '../computer-sessions-api'-import { AskCard, OpenComputerMark, SettingsPickers, StatusDot } from './parts'+import { Item } from './conversation'+import { useMemberEmails } from './members'+import { AskCard, SettingsPickers, StatusDot } from './parts'import {- askTitle,isBusy,markSeen,sessionTitle,statusLabel,useCapabilities,} from './state'-import {- buildTranscript,- formatDuration,- mergeEvents,- type TranscriptItem,-} from './transcript'+import { buildTranscript, mergeEvents } from './transcript'// Events that change what the session row says (status, asks, title).const SESSION_EVENTS = /^(session\.|turn\.|ask\.|runtime\.)/@@ -263,199 +240,6 @@ function Header({ id }: { id: string }) {)}-/** Where a message came from, beside its author's name; the web's own messages say nothing. */-const VIA: Record<string, string> = { slack: 'Slack', opc: 'CLI', api: 'API' }--// Members' emails by member id (`usr_…`). The computer derives that id from the-// user id: the WorkOS id when there is one, else a hash (`memberId` in managed-agents).-async function memberEmails(- members: OrgMember[],-): Promise<Map<string, string>> {- const emails = new Map<string, string>()- for (const m of members) {- const workos = /^user_(\w+)$/.exec(m.workosUserId ?? '')- if (workos) emails.set(`usr_${workos[1].toLowerCase()}`, m.email)- if (!m.id) continue- const digest = new Uint8Array(- await crypto.subtle.digest('SHA-256', new TextEncoder().encode(m.id)),- )- const hex = [...digest.slice(0, 13)]- .map((b) => b.toString(16).padStart(2, '0'))- .join('')- emails.set(`usr_x${hex}`, m.email)- }- return emails-}--function useMemberEmails(): Map<string, string> | undefined {- const { data: members } = useQuery({- queryKey: ['org-members'],- queryFn: getOrgMembers,- staleTime: 5 * 60_000,- })- const { data } = useQuery({- queryKey: ['org-members', 'emails', members],- queryFn: () => memberEmails(members ?? []),- enabled: !!members,- staleTime: Infinity,- })- return data-}--// A person's avatar: initials of their name, or the first letter of their email.-function initials(author: string): string {- if (author.includes('@')) return author[0].toUpperCase()- const words = author.trim().split(/\s+/)- return words- .slice(0, 2)- .map((w) => w[0].toUpperCase())- .join('')-}--function Item({- item,- leads,- emails,-}: {- item: TranscriptItem- leads: boolean- emails: Map<string, string> | undefined-}) {- switch (item.kind) {- case 'user': {- const email = item.authorId ? emails?.get(item.authorId) : undefined- return (- <div className="flex items-end justify-end gap-2">- <div className="flex max-w-[85%] flex-col items-end gap-1">- {item.author || email ? (- <span className="text-muted-foreground text-xs">- {item.author ?? email}- {item.via && VIA[item.via] ? ` · ${VIA[item.via]}` : ''}- </span>- ) : null}- <div className="bg-secondary rounded-2xl rounded-br-md px-3.5 py-2 text-sm whitespace-pre-wrap">- {item.text}- </div>- </div>- <TooltipProvider delayDuration={200}>- <Tooltip>- <TooltipTrigger asChild>- <span className="bg-secondary text-muted-foreground flex size-7 shrink-0 items-center justify-center rounded-full text-[11px] font-medium">- {item.author || email ? (- initials(item.author ?? email ?? '')- ) : (- <User className="size-3.5" />- )}- </span>- </TooltipTrigger>- <TooltipContent side="left">- {item.author ?? email ?? 'Someone'}- {email && item.author && email !== item.author ? (- <span className="block opacity-70">{email}</span>- ) : null}- </TooltipContent>- </Tooltip>- </TooltipProvider>- </div>- )- }- case 'agent':- return (- <div className="space-y-2">- {leads ? <AgentByline /> : null}- <AgentMarkdown>{item.text}</AgentMarkdown>- </div>- )- case 'work':- return (- <div className="space-y-2">- {leads ? <AgentByline /> : null}- <WorkStep item={item} />- </div>- )- case 'ask':- // Open asks are answered at the end of the transcript.- if (item.ask.status === 'open') return null- return (- <p className="text-muted-foreground flex items-center gap-1.5 text-xs">- {item.ask.status === 'answered' ? (- <Check className="size-3.5" aria-hidden />- ) : (- <X className="size-3.5" aria-hidden />- )}- {askTitle(item.ask)} · {item.ask.status}- </p>- )- case 'note':- return (- <p- className={cn(- 'flex items-center gap-1.5 text-xs',- item.tone === 'error'- ? 'text-destructive'- : 'text-muted-foreground',- )}- >- {item.tone === 'error' ? (- <CircleAlert className="size-3.5" aria-hidden />- ) : null}- {item.text}- </p>- )- }-}--function WorkStep({- item,-}: {- item: Extract<TranscriptItem, { kind: 'work' }>-}) {- const [open, setOpen] = useState(false)- const ms =- new Date(item.endedAt).getTime() - new Date(item.startedAt).getTime()- const failed = item.tools.filter((t) => t.status === 'failed').length- const label = item.open- ? `Working · ${item.tools.length} ${item.tools.length === 1 ? 'step' : 'steps'}`- : `Worked for ${formatDuration(ms)}`- return (- <div>- <button- type="button"- onClick={() => setOpen((o) => !o)}- className="text-muted-foreground hover:text-foreground flex items-center gap-1 text-xs"- >- <ChevronRight- className={cn('size-3.5 transition-transform', open && 'rotate-90')}- aria-hidden- />- {label}- {failed ? (- <span className="text-destructive">· {failed} failed</span>- ) : null}- </button>- {open && item.tools.length ? (- <ul className="border-border mt-1.5 ml-1.5 space-y-0.5 border-l pl-3">- {item.tools.map((t) => (- <li- key={t.callId}- className="text-muted-foreground flex items-center gap-1.5 font-mono text-xs"- >- {t.status === 'running' ? (- <Loader2 className="size-3 shrink-0 animate-spin" aria-hidden />- ) : t.status === 'failed' ? (- <X className="text-destructive size-3 shrink-0" aria-hidden />- ) : (- <Check className="size-3 shrink-0 opacity-60" aria-hidden />- )}- <span className="truncate">{t.title}</span>- </li>- ))}- </ul>- ) : null}- </div>- )-}-function Composer({ id }: { id: string }) {const qc = useQueryClient()const { data: s } = useQuery({@@ -573,12 +357,3 @@ function Composer({ id }: { id: string }) {</div>)}--function AgentByline() {- return (- <div className="flex items-center gap-2 text-xs font-medium">- <OpenComputerMark className="size-6" />- Computer- </div>- )-}diff --git a/web/src/managed-agents/computer-sessions/conversation.tsx b/web/src/managed-agents/computer-sessions/conversation.tsxnew file mode 100644index 00000000..4357cb44--- /dev/null+++ b/web/src/managed-agents/computer-sessions/conversation.tsx@@ -0,0 +1,189 @@+import { useState } from 'react'+import {+ Check,+ ChevronRight,+ CircleAlert,+ Loader2,+ User,+ X,+} from 'lucide-react'+import {+ Tooltip,+ TooltipContent,+ TooltipProvider,+ TooltipTrigger,+} from '@/components/ui/tooltip'+import { cn } from '@/lib/utils'+import { AgentMarkdown } from '../AgentMarkdown'+import { OpenComputerMark } from './parts'+import { askTitle } from './state'+import { formatDuration, type TranscriptItem } from './transcript'++// A transcript's items as the session view draws them; triage shows an+// excerpt of the same.++/** Where a message came from, beside its author's name; the web's own messages say nothing. */+const VIA: Record<string, string> = { slack: 'Slack', opc: 'CLI', api: 'API' }++// A person's avatar: initials of their name, or the first letter of their email.+function initials(author: string): string {+ if (author.includes('@')) return author[0].toUpperCase()+ const words = author.trim().split(/\s+/)+ return words+ .slice(0, 2)+ .map((w) => w[0].toUpperCase())+ .join('')+}++export function Item({+ item,+ leads,+ emails,+}: {+ item: TranscriptItem+ leads: boolean+ emails: Map<string, string> | undefined+}) {+ switch (item.kind) {+ case 'user': {+ const email = item.authorId ? emails?.get(item.authorId) : undefined+ return (+ <div className="flex items-end justify-end gap-2">+ <div className="flex max-w-[85%] flex-col items-end gap-1">+ {item.author || email ? (+ <span className="text-muted-foreground text-xs">+ {item.author ?? email}+ {item.via && VIA[item.via] ? ` · ${VIA[item.via]}` : ''}+ </span>+ ) : null}+ <div className="bg-secondary rounded-2xl rounded-br-md px-3.5 py-2 text-sm whitespace-pre-wrap">+ {item.text}+ </div>+ </div>+ <TooltipProvider delayDuration={200}>+ <Tooltip>+ <TooltipTrigger asChild>+ <span className="bg-secondary text-muted-foreground flex size-7 shrink-0 items-center justify-center rounded-full text-[11px] font-medium">+ {item.author || email ? (+ initials(item.author ?? email ?? '')+ ) : (+ <User className="size-3.5" />+ )}+ </span>+ </TooltipTrigger>+ <TooltipContent side="left">+ {item.author ?? email ?? 'Someone'}+ {email && item.author && email !== item.author ? (+ <span className="block opacity-70">{email}</span>+ ) : null}+ </TooltipContent>+ </Tooltip>+ </TooltipProvider>+ </div>+ )+ }+ case 'agent':+ return (+ <div className="space-y-2">+ {leads ? <AgentByline /> : null}+ <AgentMarkdown>{item.text}</AgentMarkdown>+ </div>+ )+ case 'work':+ return (+ <div className="space-y-2">+ {leads ? <AgentByline /> : null}+ <WorkStep item={item} />+ </div>+ )+ case 'ask':+ // Open asks are answered at the end of the transcript.+ if (item.ask.status === 'open') return null+ return (+ <p className="text-muted-foreground flex items-center gap-1.5 text-xs">+ {item.ask.status === 'answered' ? (+ <Check className="size-3.5" aria-hidden />+ ) : (+ <X className="size-3.5" aria-hidden />+ )}+ {askTitle(item.ask)} · {item.ask.status}+ </p>+ )+ case 'note':+ return (+ <p+ className={cn(+ 'flex items-center gap-1.5 text-xs',+ item.tone === 'error'+ ? 'text-destructive'+ : 'text-muted-foreground',+ )}+ >+ {item.tone === 'error' ? (+ <CircleAlert className="size-3.5" aria-hidden />+ ) : null}+ {item.text}+ </p>+ )+ }+}++function WorkStep({+ item,+}: {+ item: Extract<TranscriptItem, { kind: 'work' }>+}) {+ const [open, setOpen] = useState(false)+ const ms =+ new Date(item.endedAt).getTime() - new Date(item.startedAt).getTime()+ const failed = item.tools.filter((t) => t.status === 'failed').length+ const label = item.open+ ? `Working · ${item.tools.length} ${item.tools.length === 1 ? 'step' : 'steps'}`+ : `Worked for ${formatDuration(ms)}`+ return (+ <div>+ <button+ type="button"+ onClick={() => setOpen((o) => !o)}+ className="text-muted-foreground hover:text-foreground flex items-center gap-1 text-xs"+ >+ <ChevronRight+ className={cn('size-3.5 transition-transform', open && 'rotate-90')}+ aria-hidden+ />+ {label}+ {failed ? (+ <span className="text-destructive">· {failed} failed</span>+ ) : null}+ </button>+ {open && item.tools.length ? (+ <ul className="border-border mt-1.5 ml-1.5 space-y-0.5 border-l pl-3">+ {item.tools.map((t) => (+ <li+ key={t.callId}+ className="text-muted-foreground flex items-center gap-1.5 font-mono text-xs"+ >+ {t.status === 'running' ? (+ <Loader2 className="size-3 shrink-0 animate-spin" aria-hidden />+ ) : t.status === 'failed' ? (+ <X className="text-destructive size-3 shrink-0" aria-hidden />+ ) : (+ <Check className="size-3 shrink-0 opacity-60" aria-hidden />+ )}+ <span className="truncate">{t.title}</span>+ </li>+ ))}+ </ul>+ ) : null}+ </div>+ )+}++export function AgentByline() {+ return (+ <div className="flex items-center gap-2 text-xs font-medium">+ <OpenComputerMark className="size-6" />+ Computer+ </div>+ )+}diff --git a/web/src/managed-agents/computer-sessions/members.ts b/web/src/managed-agents/computer-sessions/members.tsnew file mode 100644index 00000000..bcedeb23--- /dev/null+++ b/web/src/managed-agents/computer-sessions/members.ts@@ -0,0 +1,39 @@+import { useQuery } from '@tanstack/react-query'+import { getOrgMembers } from '@/api/client'+import type { OrgMember } from '@/api/schemas'++// Members' emails by member id (`usr_…`). The computer derives that id from the+// user id: the WorkOS id when there is one, else a hash (`memberId` in managed-agents).+async function memberEmails(+ members: OrgMember[],+): Promise<Map<string, string>> {+ const emails = new Map<string, string>()+ for (const m of members) {+ const workos = /^user_(\w+)$/.exec(m.workosUserId ?? '')+ if (workos) emails.set(`usr_${workos[1].toLowerCase()}`, m.email)+ if (!m.id) continue+ const digest = new Uint8Array(+ await crypto.subtle.digest('SHA-256', new TextEncoder().encode(m.id)),+ )+ const hex = [...digest.slice(0, 13)]+ .map((b) => b.toString(16).padStart(2, '0'))+ .join('')+ emails.set(`usr_x${hex}`, m.email)+ }+ return emails+}++export function useMemberEmails(): Map<string, string> | undefined {+ const { data: members } = useQuery({+ queryKey: ['org-members'],+ queryFn: getOrgMembers,+ staleTime: 5 * 60_000,+ })+ const { data } = useQuery({+ queryKey: ['org-members', 'emails', members],+ queryFn: () => memberEmails(members ?? []),+ enabled: !!members,+ staleTime: Infinity,+ })+ return data+}diff --git a/web/src/managed-agents/computer-sessions/parts.tsx b/web/src/managed-agents/computer-sessions/parts.tsxindex c859f507..65a15a24 100644--- a/web/src/managed-agents/computer-sessions/parts.tsx+++ b/web/src/managed-agents/computer-sessions/parts.tsx@@ -167,24 +167,36 @@ function preview(input: unknown): string | null {// An open ask, answerable here: approve or deny a tool call, or answer the// agent's questions. A secret is set privately, so it points to Secrets.+// `hideTitle` leaves out the ask's title where the page already heads with it;+// `onAnswered` runs once an answer or a skip is accepted.export function AskCard({ask,session,showSession,+ hideTitle,+ onAnswered,}: {ask: Asksession?: SessionshowSession?: boolean+ hideTitle?: boolean+ onAnswered?: () => void}) {const qc = useQueryClient()const answer = useMutation({mutationFn: (a: AskAnswer) => answerAsk(ask.sessionId, ask.id, a),- onSuccess: () => void qc.invalidateQueries({ queryKey: sessionKeys.all }),+ onSuccess: () => {+ onAnswered?.()+ void qc.invalidateQueries({ queryKey: sessionKeys.all })+ },onError: (e) => notifyError('Could not answer', e),})const dismiss = useMutation({mutationFn: () => dismissAsk(ask.sessionId, ask.id),- onSuccess: () => void qc.invalidateQueries({ queryKey: sessionKeys.all }),+ onSuccess: () => {+ onAnswered?.()+ void qc.invalidateQueries({ queryKey: sessionKeys.all })+ },onError: (e) => notifyError('Could not dismiss', e),})const busy = answer.isPending || dismiss.isPending@@ -203,12 +215,14 @@ export function AskCard({{ask.kind === 'approval' ? (<ApprovalBodyask={ask}+ hideTitle={hideTitle}busy={busy}onAnswer={(a) => answer.mutate(a)}/>) : ask.kind === 'question' ? (<QuestionBodyask={ask}+ hideTitle={hideTitle}busy={busy}onAnswer={(a) => answer.mutate(a)}onDismiss={() => dismiss.mutate()}@@ -230,17 +244,21 @@ export function AskCard({function ApprovalBody({ask,+ hideTitle,busy,onAnswer,}: {ask: Ask+ hideTitle?: booleanbusy: booleanonAnswer: (a: AskAnswer) => void}) {const detail = preview(ask.approval?.input)return (<div className="space-y-2">- <p className="text-sm font-medium">{askTitle(ask)}</p>+ {hideTitle ? null : (+ <p className="text-sm font-medium">{askTitle(ask)}</p>+ )}{detail ? (<pre className="bg-muted text-muted-foreground max-h-40 overflow-auto rounded-md px-2.5 py-1.5 font-mono text-xs whitespace-pre-wrap">{detail}@@ -282,11 +300,13 @@ function ApprovalBody({function QuestionBody({ask,+ hideTitle,busy,onAnswer,onDismiss,}: {ask: Ask+ hideTitle?: booleanbusy: booleanonAnswer: (a: AskAnswer) => voidonDismiss: () => void@@ -312,7 +332,10 @@ function QuestionBody({<div className="space-y-3">{questions.map((q) => (<div key={q.id} className="space-y-1.5">- <p className="text-sm font-medium">{q.text || q.header}</p>+ {/* The headline is the first question's text: one question needs no repeat. */}+ {hideTitle && questions.length === 1 ? null : (+ <p className="text-sm font-medium">{q.text || q.header}</p>+ )}<div className="flex flex-wrap gap-1.5">{q.options.map((o) => {const on = choices[q.id]?.includes(o.label)