Skip to content

An open-source, faster Devin alternative

TypeScript

web: group session transcript by turn + surface queued input

Igor Zalutskifeb243267ce0
diff --git a/web/src/components/session-conversation.tsx b/web/src/components/session-conversation.tsx
new file mode 100644
index 00000000..a1c372f9
--- /dev/null
+++ b/web/src/components/session-conversation.tsx
@@ -0,0 +1,151 @@
+import type { ReactNode } from 'react'
+import { Link } from 'react-router-dom'
+import { Hourglass } from 'lucide-react'
+import { Button } from '@/components/ui/button'
+import {
+ bodyText,
+ isOutOfCredits,
+ type GroupedTimeline,
+} from '@/lib/session-turns'
+
+// A single chat bubble (You / Agent). Shared between the grouped Conversation
+// view and the flat All log so both render identical message markup.
+export function MessageBubble({
+ label,
+ text,
+ seq,
+ meta,
+ outOfCredits,
+}: {
+ label: string
+ text: string | null
+ seq?: number // shown as #seq in the All log; omitted in the chat view
+ meta?: ReactNode // trailing tag next to the header (e.g. queued chip)
+ outOfCredits?: boolean
+}) {
+ return (
+ <div>
+ <div className="mb-1 flex items-center gap-2">
+ <span className="text-foreground text-xs font-semibold">{label}</span>
+ {seq != null ? (
+ <span className="text-muted-foreground/70 font-mono text-[10px]">
+ #{seq}
+ </span>
+ ) : null}
+ {meta}
+ </div>
+ <p className="text-foreground/90 text-sm whitespace-pre-wrap">{text}</p>
+ {outOfCredits ? (
+ <Button asChild size="sm" className="mt-2">
+ <Link to="/billing">Top up</Link>
+ </Button>
+ ) : null}
+ </div>
+ )
+}
+
+// "A reply is coming" — a gentle agent-side typing indicator. Three dots pulse
+// in sequence; no failure is implied. Shown while a turn is running with no
+// answer yet, OR while input sits queued waiting for its follow-up turn to
+// dispatch (the ~gap the user otherwise reads as "stuck").
+function ReplyIndicator() {
+ return (
+ <li className="px-4 py-3">
+ <div className="mb-1 flex items-center gap-2">
+ <span className="text-foreground/70 text-xs font-semibold">Agent</span>
+ </div>
+ <span
+ className="flex items-center gap-1"
+ role="status"
+ aria-label="Agent is responding"
+ >
+ {[0, 1, 2].map((i) => (
+ <span
+ key={i}
+ className="bg-muted-foreground/50 size-1.5 animate-pulse rounded-full"
+ style={{ animationDelay: `${i * 200}ms`, animationDuration: '1s' }}
+ />
+ ))}
+ </span>
+ </li>
+ )
+}
+
+// Grouped chat view: one block per turn (its inputs as "You", its agent.message
+// outputs as "Agent"), an error affordance on failure, and a single trailing
+// "reply coming" indicator while the agent still owes a response. Lifecycle
+// chrome (turn.started/turn.completed/agent.result/tool.call) is hidden here.
+// Queued input — typed while a turn was running and not yet claimed by a
+// follow-up turn — trails the groups.
+export function TurnConversation({
+ grouped,
+ halted = false,
+}: {
+ grouped: GroupedTimeline
+ halted?: boolean
+}) {
+ const last = grouped.groups[grouped.groups.length - 1]
+ const runningNoAnswer =
+ !!last &&
+ last.state === 'running' &&
+ !last.events.some((e) => e.type === 'agent.message')
+ // A response is expected (no failure) when a turn is mid-flight without an
+ // answer yet, or input is queued for a not-yet-dispatched turn. Suppressed
+ // when halted (out of credits → nothing runs until top-up).
+ const replyPending = !halted && (runningNoAnswer || grouped.pending.length > 0)
+
+ return (
+ <ul className="divide-y">
+ {grouped.groups.map((group) => {
+ const errorEv = group.events.find((e) => e.type.startsWith('error'))
+ return (
+ <li key={group.turnId} className="space-y-3 px-4 py-3">
+ {group.events.map((ev) => {
+ if (ev.turn_id == null) {
+ return (
+ <MessageBubble
+ key={ev.id}
+ label={ev.actor?.display ?? 'You'}
+ text={bodyText(ev)}
+ />
+ )
+ }
+ if (ev.type === 'agent.message') {
+ return (
+ <MessageBubble
+ key={ev.id}
+ label={ev.actor?.display ?? 'Agent'}
+ text={bodyText(ev)}
+ outOfCredits={isOutOfCredits(ev)}
+ />
+ )
+ }
+ return null // hide agent.result / tool.call / error chrome
+ })}
+ {group.state === 'error' ? (
+ <div className="bg-status-error-bg/40 text-status-error rounded-sm px-3 py-2 text-xs">
+ {(errorEv && bodyText(errorEv)) ??
+ 'The agent hit an error on this turn.'}
+ </div>
+ ) : null}
+ </li>
+ )
+ })}
+ {grouped.pending.map((ev) => (
+ <li key={ev.id} className="px-4 py-3">
+ <MessageBubble
+ label={ev.actor?.display ?? 'You'}
+ text={bodyText(ev)}
+ meta={
+ <span className="text-muted-foreground bg-muted inline-flex items-center gap-1 rounded-sm px-1.5 py-0.5 text-[10px] font-medium">
+ <Hourglass className="size-2.5" />
+ Queued · runs next
+ </span>
+ }
+ />
+ </li>
+ ))}
+ {replyPending ? <ReplyIndicator /> : null}
+ </ul>
+ )
+}
diff --git a/web/src/lib/session-turns.ts b/web/src/lib/session-turns.ts
new file mode 100644
index 00000000..0f7758f5
--- /dev/null
+++ b/web/src/lib/session-turns.ts
@@ -0,0 +1,139 @@
+import type { SessionEvent } from '@/api/client'
+
+// Pure, React-free grouping of a session's raw event stream into turns.
+//
+// The backend never interrupts a running turn: input typed mid-turn is queued
+// and gets its own follow-up turn on completion. The only wire linkage between
+// an input event and the turn that consumes it is the inclusive seq range on
+// the turn's `turn.started` body (`input_from_seq`/`input_to_seq`). Input events
+// carry `turn_id == null`, so they cannot be grouped by turn_id — only by range.
+//
+// Rule: an input event with seq S belongs to the turn whose started bounds
+// satisfy `from <= S <= to`. If no started turn covers S, the input is pending
+// (typed but not yet claimed by a turn).
+
+export type TurnState = 'running' | 'completed' | 'error' | 'canceled'
+
+export interface TurnGroup {
+ turnId: string
+ fromSeq: number | null
+ toSeq: number | null
+ state: TurnState
+ yieldReason?: string
+ // seq-ordered; the turn's inputs + its outputs; excludes turn.started/turn.completed.
+ events: SessionEvent[]
+}
+
+export interface GroupedTimeline {
+ groups: TurnGroup[] // ordered by turn.started seq
+ pending: SessionEvent[] // input events (turn_id==null) not yet claimed by any turn, seq-ordered
+}
+
+// body is unknown (inline JSON <=32KB); pull the common { text } shape defensively.
+export function bodyText(ev: SessionEvent): string | null {
+ const b = ev.body
+ if (
+ b &&
+ typeof b === 'object' &&
+ typeof (b as Record<string, unknown>).text === 'string'
+ ) {
+ return (b as Record<string, string>).text
+ }
+ return null
+}
+
+// The runtime's failPreExec emits an agent.message tagged with an
+// insufficient_credits code so the UI can offer a "top up" affordance.
+export function isOutOfCredits(ev: SessionEvent): boolean {
+ return (
+ ev.type === 'agent.message' &&
+ (ev.body as Record<string, unknown> | null | undefined)?.code ===
+ 'insufficient_credits'
+ )
+}
+
+// Reads input_from_seq/input_to_seq off a turn.started body, coercing legacy
+// string seqs; null when a bound is absent (a turn with null bounds can't claim
+// inputs by range).
+export function turnBounds(ev: SessionEvent): {
+ from: number | null
+ to: number | null
+} {
+ const b = (ev.body ?? {}) as Record<string, unknown>
+ const num = (v: unknown) =>
+ v == null || Number.isNaN(Number(v)) ? null : Number(v)
+ return { from: num(b.input_from_seq), to: num(b.input_to_seq) }
+}
+
+export function groupIntoTurns(input: SessionEvent[]): GroupedTimeline {
+ const sorted = [...input].sort((a, b) => a.seq - b.seq)
+ const byTurn = new Map<string, TurnGroup>()
+ const order: string[] = []
+
+ // Pass 1: skeletons from turn.started (defines the seq ranges + order).
+ for (const ev of sorted) {
+ if (ev.type !== 'turn.started' || !ev.turn_id) continue
+ const { from, to } = turnBounds(ev)
+ byTurn.set(ev.turn_id, {
+ turnId: ev.turn_id,
+ fromSeq: from,
+ toSeq: to,
+ state: 'running',
+ events: [],
+ })
+ order.push(ev.turn_id)
+ }
+
+ // Pass 2: completion -> state.
+ for (const ev of sorted) {
+ if (ev.type !== 'turn.completed' || !ev.turn_id) continue
+ const g = byTurn.get(ev.turn_id)
+ if (!g) continue
+ const rawYr = ((ev.body ?? {}) as Record<string, unknown>).yield_reason
+ const yr = typeof rawYr === 'string' ? rawYr : ''
+ g.yieldReason = yr || undefined
+ g.state =
+ yr === 'error' ? 'error' : yr === 'canceled' ? 'canceled' : 'completed'
+ }
+
+ // Pass 3: assign every event.
+ const pending: SessionEvent[] = []
+ for (const ev of sorted) {
+ // chrome; state already captured above.
+ if (ev.type === 'turn.started' || ev.type === 'turn.completed') continue
+ if (ev.turn_id && byTurn.has(ev.turn_id)) {
+ // agent.message / agent.result / tool.call / error.
+ byTurn.get(ev.turn_id)!.events.push(ev)
+ continue
+ }
+ if (ev.turn_id == null) {
+ // input event: claim by seq range.
+ const g = [...byTurn.values()].find(
+ (t) =>
+ t.fromSeq != null &&
+ t.toSeq != null &&
+ ev.seq >= t.fromSeq &&
+ ev.seq <= t.toSeq,
+ )
+ if (g) g.events.push(ev)
+ else pending.push(ev) // seq beyond every started turn -> not yet claimed
+ continue
+ }
+ // turn_id set but no matching started skeleton (out-of-order/late): lazily create.
+ const g: TurnGroup = {
+ turnId: ev.turn_id,
+ fromSeq: null,
+ toSeq: null,
+ state: 'running',
+ events: [ev],
+ }
+ byTurn.set(ev.turn_id, g)
+ order.push(ev.turn_id)
+ }
+
+ for (const g of byTurn.values()) g.events.sort((a, b) => a.seq - b.seq)
+ return {
+ groups: order.map((id) => byTurn.get(id)!),
+ pending: pending.sort((a, b) => a.seq - b.seq),
+ }
+}
diff --git a/web/src/pages/SessionDetail.tsx b/web/src/pages/SessionDetail.tsx
index b6c0d3d7..f06a5fdc 100644
--- a/web/src/pages/SessionDetail.tsx
+++ b/web/src/pages/SessionDetail.tsx
@@ -25,19 +25,12 @@ import { SessionWebhooks } from '@/components/session-webhooks'
import { ApiHint } from '@/components/api-hint'
import { MessagesSquare } from 'lucide-react'
import { cn } from '@/lib/utils'
+import {
+ MessageBubble,
+ TurnConversation,
+} from '@/components/session-conversation'
+import { bodyText, groupIntoTurns, isOutOfCredits } from '@/lib/session-turns'
-// body is unknown (inline JSON ≤32KB); pull the common shapes defensively.
-function bodyText(ev: SessionEvent): string | null {
- const b = ev.body
- if (
- b &&
- typeof b === 'object' &&
- typeof (b as Record<string, unknown>).text === 'string'
- ) {
- return (b as Record<string, string>).text
- }
- return null
-}
function toolSummary(ev: SessionEvent): string {
const b = (ev.body ?? {}) as Record<string, unknown>
const tool = typeof b.tool === 'string' ? b.tool : 'tool'
@@ -48,6 +41,12 @@ function humanizeType(t: string): string {
return t.replace(/[._]/g, ' ').replace(/^\w/, (c) => c.toUpperCase())
}
+interface TurnStartInfo {
+ from: number | null
+ to: number | null
+ preview: string | null
+}
+
const LEVELS = [
{ value: 'all', label: 'All' },
{ value: 'user', label: 'Conversation' },
@@ -59,7 +58,7 @@ export default function SessionDetail() {
const queryClient = useQueryClient()
const halted = useHalted() // top-level: must run before any early return (Rules of Hooks)
const [draft, setDraft] = useState('')
- const [level, setLevel] = useState<LevelFilter>('all')
+ const [level, setLevel] = useState<LevelFilter>('user')
const [confirmCancel, setConfirmCancel] = useState(false)
const [liveEvents, setLiveEvents] = useState<SessionEvent[]>([])
const [streamOk, setStreamOk] = useState(false)
@@ -171,6 +170,28 @@ export default function SessionDetail() {
)
}, [eventData, liveEvents, sessionId])
+ // Group the (unfiltered) stream by turn: turn.started is level:progress, so it
+ // must be read from allEvents, never the level==='user' filter.
+ const grouped = useMemo(() => groupIntoTurns(allEvents), [allEvents])
+ // Seqs of input events typed but not yet claimed by a turn → tagged "queued".
+ const pendingSeqs = useMemo(
+ () => new Set(grouped.pending.map((e) => e.seq)),
+ [grouped],
+ )
+ // Per-turn seq range + input preview, so the All log's turn.started row is
+ // self-describing instead of a bare orphan marker.
+ const turnStartInfo = useMemo(() => {
+ const m = new Map<string, TurnStartInfo>()
+ for (const g of grouped.groups) {
+ const firstInput = g.events.find((e) => e.turn_id == null)
+ const raw = firstInput ? bodyText(firstInput) : null
+ const preview =
+ raw && raw.length > 40 ? `${raw.slice(0, 40)}…` : (raw ?? null)
+ m.set(g.turnId, { from: g.fromSeq, to: g.toSeq, preview })
+ }
+ return m
+ }, [grouped])
+
if (isLoading) {
return (
<div className="space-y-4">
@@ -185,8 +206,10 @@ export default function SessionDetail() {
const canSteer = !archived
const canCancel = status === 'running' || status === 'awaiting_input'
- const events =
- level === 'user' ? allEvents.filter((e) => e.level === 'user') : allEvents
+ const isEmpty =
+ level === 'user'
+ ? grouped.groups.length === 0 && grouped.pending.length === 0
+ : allEvents.length === 0
return (
<div className="max-w-4xl">
@@ -302,16 +325,23 @@ export default function SessionDetail() {
</div>
</div>
- {events.length === 0 ? (
+ {isEmpty ? (
<EmptyState
icon={MessagesSquare}
title="No events yet"
description="Events from the agent's turns will stream in here."
/>
+ ) : level === 'user' ? (
+ <TurnConversation grouped={grouped} halted={halted} />
) : (
<ul className="divide-y">
- {events.map((ev) => (
- <EventRow key={ev.id} ev={ev} />
+ {allEvents.map((ev) => (
+ <EventRow
+ key={ev.id}
+ ev={ev}
+ pending={pendingSeqs}
+ bounds={turnStartInfo}
+ />
))}
</ul>
)}
@@ -323,7 +353,10 @@ export default function SessionDetail() {
<CircleAlert className="size-3.5 shrink-0" />
<span>
Out of credits —{' '}
- <Link to="/billing" className="font-medium underline underline-offset-2">
+ <Link
+ to="/billing"
+ className="font-medium underline underline-offset-2"
+ >
top up to resume
</Link>
.
@@ -341,7 +374,12 @@ export default function SessionDetail() {
value={draft}
onChange={(e) => setDraft(e.target.value)}
onSend={() => {
- if (draft.trim() && canSteer && !halted && !steerMutation.isPending) {
+ if (
+ draft.trim() &&
+ canSteer &&
+ !halted &&
+ !steerMutation.isPending
+ ) {
steerMutation.mutate()
}
}}
@@ -358,12 +396,19 @@ export default function SessionDetail() {
<Button
type="submit"
title="Enter to send · Shift+Enter for newline"
- disabled={!draft.trim() || !canSteer || halted || steerMutation.isPending}
+ disabled={
+ !draft.trim() || !canSteer || halted || steerMutation.isPending
+ }
>
<Send className="size-4" />
Send
</Button>
</form>
+ {status === 'running' && !halted && !archived ? (
+ <p className="text-muted-foreground mt-2 text-xs">
+ Agent is working — your message will run in the next turn.
+ </p>
+ ) : null}
</div>
</Panel>
@@ -387,33 +432,52 @@ export default function SessionDetail() {
)
}
-function EventRow({ ev }: { ev: SessionEvent }) {
+function EventRow({
+ ev,
+ pending,
+ bounds,
+}: {
+ ev: SessionEvent
+ pending: Set<number>
+ bounds: Map<string, TurnStartInfo>
+}) {
const text = bodyText(ev)
// Conversation messages — the signal.
if (ev.type === 'user.message' || ev.type === 'agent.message') {
const isUser = ev.type === 'user.message'
- // Out-of-credits notice (from the runtime's failPreExec) → make the "top up" actionable.
- const outOfCredits =
- ev.type === 'agent.message' &&
- (ev.body as Record<string, unknown> | null | undefined)?.code ===
- 'insufficient_credits'
return (
<li className="px-4 py-3">
- <div className="mb-1 flex items-center gap-2">
- <span className="text-foreground text-xs font-semibold">
- {ev.actor?.display ?? (isUser ? 'You' : 'Agent')}
- </span>
- <span className="text-muted-foreground/70 font-mono text-[10px]">
- #{ev.seq}
- </span>
- </div>
- <p className="text-foreground/90 text-sm whitespace-pre-wrap">{text}</p>
- {outOfCredits && (
- <Button asChild size="sm" className="mt-2">
- <Link to="/billing">Top up</Link>
- </Button>
- )}
+ <MessageBubble
+ label={ev.actor?.display ?? (isUser ? 'You' : 'Agent')}
+ text={text}
+ seq={ev.seq}
+ // Input typed while a turn was running but not yet claimed by a turn.
+ meta={
+ isUser && pending.has(ev.seq) ? (
+ <span className="text-muted-foreground text-[10px]">
+ · queued
+ </span>
+ ) : undefined
+ }
+ outOfCredits={isOutOfCredits(ev)}
+ />
+ </li>
+ )
+ }
+
+ // Turn started — de-orphaned: self-describing with its seq range + input preview.
+ if (ev.type === 'turn.started') {
+ const info = bounds.get(ev.turn_id ?? '')
+ const range =
+ info && info.from != null
+ ? ` · running #${info.from}${info.to != null && info.to > info.from ? `–#${info.to}` : ''}`
+ : ''
+ const preview = info?.preview ? ` : "${info.preview}"` : ''
+ return (
+ <li className="text-muted-foreground flex items-center gap-2 px-4 py-1.5 text-xs">
+ <span className="bg-border h-px w-4 shrink-0" />
+ {`Turn started${range}${preview}`}
</li>
)
}