Skip to content

An open-source, faster Devin alternative

TypeScript

Preserve debug history and direct running sessions (#639)

Mohamed Habib785d5e72ab3f
diff --git a/cloudflare-workers/api-edge/src/managed_agents.test.ts b/cloudflare-workers/api-edge/src/managed_agents.test.ts
index fe3df6fa..e39a4788 100644
--- a/cloudflare-workers/api-edge/src/managed_agents.test.ts
+++ b/cloudflare-workers/api-edge/src/managed_agents.test.ts
@@ -766,6 +766,50 @@ describe("managed agents proxy", () => {
expect(JSON.stringify(body)).not.toMatch(/blue|lambda|microvm/i);
});
+ it("forwards explicit running-session input modes", async () => {
+ const fetchSpy = vi.fn(async () =>
+ Response.json(
+ { turnId: "turn-2", status: "running", duplicate: false },
+ { status: 202 },
+ ),
+ );
+ vi.stubGlobal("fetch", fetchSpy);
+
+ const response = await proxyManagedAgents(
+ new Request(
+ "https://app.opencomputer.dev/api/managed-agents/sessions/session-1/turns",
+ {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({
+ input: "focus on the failing test",
+ mode: "steer",
+ idempotencyKey: "admission-1",
+ }),
+ },
+ ),
+ {
+ OC_MANAGED_AGENTS_SECRET: "test-secret",
+ MANAGED_AGENTS_API_URL: "https://managedagents.test",
+ },
+ { orgID: "org_test", userID: "user_test" },
+ "/api/managed-agents",
+ );
+
+ expect(response.status).toBe(202);
+ const [, init] = fetchSpy.mock.calls[0] as unknown as [URL, RequestInit];
+ expect(await new Response(init.body).json()).toMatchObject({
+ input: "focus on the failing test",
+ mode: "steer",
+ idempotencyKey: "admission-1",
+ });
+ expect(await response.json()).toEqual({
+ turnId: "turn-2",
+ status: "running",
+ duplicate: false,
+ });
+ });
+
it("removes backend artifact and runtime fields from successful responses", async () => {
vi.stubGlobal(
"fetch",
diff --git a/web/src/managed-agents/Detail.tsx b/web/src/managed-agents/Detail.tsx
index f2febe49..9bd52e7e 100644
--- a/web/src/managed-agents/Detail.tsx
+++ b/web/src/managed-agents/Detail.tsx
@@ -21,7 +21,6 @@ import {
Loader2,
Plus,
Send,
- Square,
TerminalSquare,
Wrench,
} from 'lucide-react'
@@ -41,6 +40,7 @@ import { Button } from '@/components/ui/button'
import { notifyError } from '@/lib/errors'
import { cn } from '@/lib/utils'
import {
+ admitManagedAgentInput,
displayManagedAgentName,
getManagedAgentDeployment,
getManagedAgentDeployments,
@@ -49,6 +49,7 @@ import {
getManagedAgents,
getManagedAgentSessions,
type ManagedAgentEvent,
+ type ManagedAgentInputMode,
type ManagedAgentSession,
type ManagedAgentSummary,
type ManagedProjectOverview,
@@ -58,6 +59,11 @@ import { DebugInspector } from './DebugInspector'
import { isNearScrollEnd } from './scroll-follow'
import { createStartCommand, starterCommands } from './onboarding'
import { projectContextSearch } from './project-context'
+import {
+ playgroundSessionIdFromSearch,
+ playgroundSessionSearch,
+ sessionsForEnvironment,
+} from './session-history'
import { ManagedProjectSecrets } from './Secrets'
import { ManagedSlackWizard } from './SlackWizard'
@@ -273,14 +279,20 @@ function PlaygroundChat({
agentId,
session,
events,
+ onSessionFinished,
}: {
agentId: string
session?: ManagedAgentSession
events: ManagedAgentEvent[]
+ onSessionFinished?: (sessionId: string) => void
}) {
const queryClient = useQueryClient()
const [prompt, setPrompt] = useState('')
+ const [inputMode, setInputMode] = useState<ManagedAgentInputMode>('queue')
+ const [admitting, setAdmitting] = useState(false)
+ const [admissionNotice, setAdmissionNotice] = useState<string>()
const [liveSessionId, setLiveSessionId] = useState(session?.id)
+ const liveSessionIdRef = useRef(session?.id)
const timelineRef = useRef<HTMLDivElement>(null)
const composerRef = useRef<HTMLDivElement>(null)
const followOutputRef = useRef(true)
@@ -293,6 +305,7 @@ function PlaygroundChat({
() =>
new ManagedAgentChatTransport(agentId, session?.id, (sessionId) => {
setLiveSessionId(sessionId)
+ liveSessionIdRef.current = sessionId
}),
[agentId, session?.id],
)
@@ -302,7 +315,7 @@ function PlaygroundChat({
enabled: Boolean(liveSessionId),
refetchInterval: 1_000,
})
- const { messages, sendMessage, status, stop, error } = useChat({
+ const { messages, sendMessage, status, error } = useChat({
id: session?.id ?? `new-${agentId}`,
messages: initialMessages,
transport,
@@ -310,16 +323,22 @@ function PlaygroundChat({
onError: (chatError) => notifyError("Couldn't run this agent.", chatError),
onFinish: () => {
void queryClient.invalidateQueries({
- queryKey: ['managed-agent-sessions', agentId],
+ queryKey: ['managed-agent-sessions'],
})
- if (liveSessionId) {
+ const completedSessionId = liveSessionIdRef.current
+ if (completedSessionId) {
void queryClient.invalidateQueries({
- queryKey: ['managed-agent-session-events', liveSessionId],
+ queryKey: ['managed-agent-session-events', completedSessionId],
})
+ onSessionFinished?.(completedSessionId)
}
},
})
const running = status === 'submitted' || status === 'streaming'
+ const agentWorking =
+ running ||
+ session?.status === 'running' ||
+ session?.status === 'waiting_runtime'
useLayoutEffect(() => {
const timeline = timelineRef.current
@@ -333,9 +352,44 @@ function PlaygroundChat({
const send = () => {
const input = prompt.trim()
- if (!input || running) return
+ if (!input || admitting) return
+ if (agentWorking) {
+ const sessionId = liveSessionIdRef.current
+ if (!sessionId) {
+ notifyError(
+ "Couldn't direct this run.",
+ new Error('The durable session has not been created yet.'),
+ )
+ return
+ }
+ setAdmitting(true)
+ setAdmissionNotice(undefined)
+ void admitManagedAgentInput(sessionId, input, inputMode)
+ .then(() => {
+ setPrompt('')
+ setAdmissionNotice(
+ inputMode === 'queue'
+ ? 'Queued after the active work.'
+ : inputMode === 'steer'
+ ? 'Steering will apply at the next safe boundary.'
+ : 'Active work was interrupted and the replacement was admitted.',
+ )
+ void queryClient.invalidateQueries({
+ queryKey: ['managed-agent-sessions'],
+ })
+ void queryClient.invalidateQueries({
+ queryKey: ['managed-agent-session-events', sessionId],
+ })
+ })
+ .catch((admissionError: unknown) =>
+ notifyError("Couldn't direct this run.", admissionError),
+ )
+ .finally(() => setAdmitting(false))
+ return
+ }
followOutputRef.current = true
setPrompt('')
+ setAdmissionNotice(undefined)
void sendMessage({ text: input })
requestAnimationFrame(() =>
composerRef.current?.querySelector('textarea')?.focus(),
@@ -354,7 +408,7 @@ function PlaygroundChat({
{liveSessionId ?? 'A session is created when you send a message'}
</p>
</div>
- {running ? (
+ {agentWorking ? (
<div className="text-muted-foreground flex items-center gap-2 text-xs">
<span className="bg-foreground size-1.5 animate-pulse rounded-full" />
Agent is working
@@ -430,6 +484,11 @@ function PlaygroundChat({
{error ? (
<p className="text-destructive mb-2 text-xs">{error.message}</p>
) : null}
+ {admissionNotice ? (
+ <p className="text-muted-foreground mb-2 text-xs">
+ {admissionNotice}
+ </p>
+ ) : null}
<div
ref={composerRef}
className="bg-background focus-within:border-ring/60 rounded-lg border p-2 transition-colors"
@@ -445,10 +504,36 @@ function PlaygroundChat({
<p className="text-muted-foreground text-[10px]">
Enter to send · Shift + Enter for a new line
</p>
- {running ? (
- <Button variant="outline" size="sm" onClick={() => void stop()}>
- <Square className="fill-current" /> Stop
- </Button>
+ {agentWorking ? (
+ <div className="flex items-center gap-2">
+ <select
+ aria-label="Running session input mode"
+ value={inputMode}
+ onChange={(event) =>
+ setInputMode(event.target.value as ManagedAgentInputMode)
+ }
+ className="border-input bg-background h-8 rounded-md border px-2 text-xs outline-none"
+ >
+ <option value="queue">Queue after current</option>
+ <option value="steer">Steer active work</option>
+ <option value="interrupt">Interrupt and replace</option>
+ </select>
+ <Button
+ size="sm"
+ variant={
+ inputMode === 'interrupt' ? 'destructive' : 'default'
+ }
+ disabled={!prompt.trim() || admitting}
+ onClick={send}
+ >
+ {admitting ? (
+ <Loader2 className="animate-spin" />
+ ) : (
+ <Send />
+ )}
+ {inputMode === 'interrupt' ? 'Interrupt' : 'Send'}
+ </Button>
+ </div>
) : (
<Button size="sm" disabled={!prompt.trim()} onClick={send}>
<Send /> Send
@@ -498,7 +583,7 @@ export default function ManagedAgentDetail({
searchParams.get('environment') === 'production'
? 'production'
: 'development'
- const [selectedPlaygroundId, setSelectedPlaygroundId] = useState<string>()
+ const requestedPlaygroundId = playgroundSessionIdFromSearch(location.search)
const [newSessionKey, setNewSessionKey] = useState(() => crypto.randomUUID())
const agents = useQuery({
@@ -545,26 +630,36 @@ export default function ManagedAgentDetail({
queryKey: ['managed-agent-channels'],
queryFn: getManagedAgentChannels,
})
- const selectedPlayground = sessions.data?.find(
- (session) => session.id === selectedPlaygroundId,
+ const environmentSessions = project
+ ? sessionsForEnvironment(
+ sessions.data ?? [],
+ project.deployments,
+ agentId,
+ environment,
+ )
+ : (sessions.data ?? [])
+ const playgroundSessions = environmentSessions.filter(
+ (session) => session.source === 'playground',
)
+ const externalSessions = environmentSessions.filter(
+ (session) => session.source !== 'playground',
+ )
+ const selectedPlayground = playgroundSessions.find(
+ (session) => session.id === requestedPlaygroundId,
+ )
+ const selectedPlaygroundId = selectedPlayground?.id
const selectedPlaygroundEvents = useQuery({
queryKey: ['managed-agent-session-events', selectedPlaygroundId],
queryFn: () => getManagedAgentSessionEvents(selectedPlaygroundId!),
enabled: Boolean(selectedPlaygroundId),
})
- const environmentSessions = (sessions.data ?? []).filter(
- (session) =>
- !projectEnvironment?.activeDeploymentId ||
- session.deploymentId === projectEnvironment.activeDeploymentId,
- )
- const playgroundSessions = environmentSessions.filter(
- (session) => session.source === 'playground',
- )
- const externalSessions = environmentSessions.filter(
- (session) => session.source !== 'playground',
- )
+ const selectPlaygroundSession = (sessionId?: string) => {
+ void navigate({
+ pathname: location.pathname,
+ search: playgroundSessionSearch(location.search, sessionId),
+ })
+ }
const activeAliasChannel = (channels.data ?? []).find(
(channel) =>
channel.agentId === agentId &&
@@ -687,15 +782,18 @@ export default function ManagedAgentDetail({
aria-label="Playground agent"
value={agentId}
onChange={(event) => {
- setSelectedPlaygroundId(undefined)
setNewSessionKey(crypto.randomUUID())
- void navigate({
- pathname: location.pathname,
- search: projectContextSearch(
+ const search = new URLSearchParams(
+ projectContextSearch(
location.search,
event.target.value,
environment,
),
+ )
+ search.delete('session')
+ void navigate({
+ pathname: location.pathname,
+ search: search.toString(),
})
}}
className="border-input bg-background h-9 min-w-52 rounded-md border px-3 text-sm outline-none"
@@ -784,7 +882,7 @@ export default function ManagedAgentDetail({
variant="ghost"
aria-label="New playground session"
onClick={() => {
- setSelectedPlaygroundId(undefined)
+ selectPlaygroundSession()
setNewSessionKey(crypto.randomUUID())
}}
>
@@ -809,7 +907,7 @@ export default function ManagedAgentDetail({
<button
key={session.id}
type="button"
- onClick={() => setSelectedPlaygroundId(session.id)}
+ onClick={() => selectPlaygroundSession(session.id)}
className={cn(
'hover:bg-muted/70 mb-1 w-full rounded-md px-3 py-2 text-left transition-colors',
selectedPlaygroundId === session.id && 'bg-muted',
@@ -823,6 +921,9 @@ export default function ManagedAgentDetail({
{session.turns.length === 1 ? 'turn' : 'turns'} ·{' '}
{formatDate(session.updatedAt)}
</span>
+ <span className="text-muted-foreground mt-0.5 block truncate font-mono text-[10px]">
+ deployment {session.deploymentId.slice(0, 12)}
+ </span>
</button>
))}
</div>
@@ -837,6 +938,7 @@ export default function ManagedAgentDetail({
agentId={project ? `${agentId}@${environment}` : agentId}
session={selectedPlayground}
events={selectedPlaygroundEvents.data ?? []}
+ onSessionFinished={selectPlaygroundSession}
/>
)}
</div>
diff --git a/web/src/managed-agents/api.ts b/web/src/managed-agents/api.ts
index 33a59ddf..ea2ab99f 100644
--- a/web/src/managed-agents/api.ts
+++ b/web/src/managed-agents/api.ts
@@ -153,9 +153,12 @@ const eventsResponseSchema = z.object({
const turnSchema = z.object({
turnId: z.string(),
+ status: z.string(),
duplicate: z.boolean(),
})
+export type ManagedAgentInputMode = 'queue' | 'steer' | 'interrupt'
+
const sessionSchema = z.object({
id: z.string(),
agentId: z.string(),
@@ -170,6 +173,10 @@ const sessionSchema = z.object({
z.object({
id: z.string(),
input: z.string(),
+ mode: z
+ .enum(['queue', 'steer', 'interrupt'])
+ .optional()
+ .default('queue'),
status: z.string(),
createdAt: z.string(),
updatedAt: z.string(),
@@ -413,6 +420,36 @@ export async function getManagedAgentSessionEvents(sessionId: string) {
).events
}
+export async function admitManagedAgentInput(
+ sessionId: string,
+ input: string,
+ mode: ManagedAgentInputMode,
+ signal?: AbortSignal,
+) {
+ return apiFetch(
+ `/managed-agents/sessions/${encodeURIComponent(sessionId)}/turns`,
+ {
+ method: 'POST',
+ body: JSON.stringify({
+ input,
+ mode,
+ idempotencyKey: crypto.randomUUID(),
+ }),
+ signal,
+ },
+ turnSchema,
+ )
+}
+
+async function suspendManagedAgentIfIdle(sessionId: string) {
+ const session = await getManagedAgentSession(sessionId).catch(() => undefined)
+ if (session?.status !== 'idle') return
+ await apiFetch(
+ `/managed-agents/sessions/${encodeURIComponent(sessionId)}/suspend`,
+ { method: 'POST' },
+ ).catch(() => undefined)
+}
+
export function managedAgentRenderDebug(event: ManagedAgentEvent) {
if (event.type !== 'agent.rendered') return undefined
const parsed = renderDebugSchema.safeParse(event.data)
@@ -511,23 +548,20 @@ export async function runManagedAgent(
90_000,
options.signal,
)
- const turn = await apiFetch(
- `/managed-agents/sessions/${encodeURIComponent(sessionId)}/turns`,
- {
- method: 'POST',
- body: JSON.stringify({
- input,
- idempotencyKey: crypto.randomUUID(),
- }),
- signal: options.signal,
- },
- turnSchema,
+ const turn = await admitManagedAgentInput(
+ sessionId,
+ input,
+ 'queue',
+ options.signal,
)
const completed = await waitForAgentEvent(
sessionId,
connected.cursor,
(event) =>
- event.type === 'turn.completed' || event.type === 'turn.failed',
+ event.turnId === turn.turnId &&
+ (event.type === 'turn.completed' ||
+ event.type === 'turn.failed' ||
+ event.type === 'turn.cancelled'),
onEvent,
180_000,
options.signal,
@@ -541,10 +575,7 @@ export async function runManagedAgent(
}
return { sessionId, turnId: turn.turnId }
} finally {
- await apiFetch(
- `/managed-agents/sessions/${encodeURIComponent(sessionId)}/suspend`,
- { method: 'POST' },
- ).catch(() => undefined)
+ await suspendManagedAgentIfIdle(sessionId)
}
}
@@ -577,23 +608,15 @@ export async function continueManagedAgentSession(
cursor = connected.cursor
}
try {
- const turn = await apiFetch(
- `/managed-agents/sessions/${encodeURIComponent(sessionId)}/turns`,
- {
- method: 'POST',
- body: JSON.stringify({
- input,
- idempotencyKey: crypto.randomUUID(),
- }),
- signal,
- },
- turnSchema,
- )
+ const turn = await admitManagedAgentInput(sessionId, input, 'queue', signal)
const completed = await waitForAgentEvent(
sessionId,
cursor,
(event) =>
- event.type === 'turn.completed' || event.type === 'turn.failed',
+ event.turnId === turn.turnId &&
+ (event.type === 'turn.completed' ||
+ event.type === 'turn.failed' ||
+ event.type === 'turn.cancelled'),
onEvent,
180_000,
signal,
@@ -607,10 +630,7 @@ export async function continueManagedAgentSession(
}
return { sessionId, turnId: turn.turnId }
} finally {
- await apiFetch(
- `/managed-agents/sessions/${encodeURIComponent(sessionId)}/suspend`,
- { method: 'POST' },
- ).catch(() => undefined)
+ await suspendManagedAgentIfIdle(sessionId)
}
}
@@ -632,24 +652,17 @@ export async function invokeManagedAgent(agentId: string, input: string) {
() => undefined,
90_000,
)
- const turn = await apiFetch(
- `/managed-agents/sessions/${encodeURIComponent(sessionId)}/turns`,
- {
- method: 'POST',
- body: JSON.stringify({
- input,
- idempotencyKey: crypto.randomUUID(),
- }),
- },
- turnSchema,
- )
+ const turn = await admitManagedAgentInput(sessionId, input, 'queue')
let streamedText = ''
let completedText = ''
const completed = await waitForAgentEvent(
sessionId,
connected.cursor,
(event) =>
- event.type === 'turn.completed' || event.type === 'turn.failed',
+ event.turnId === turn.turnId &&
+ (event.type === 'turn.completed' ||
+ event.type === 'turn.failed' ||
+ event.type === 'turn.cancelled'),
(event) => {
if (event.type === 'message.delta') {
streamedText +=
@@ -676,9 +689,6 @@ export async function invokeManagedAgent(agentId: string, input: string) {
output: streamedText || completedText || 'Done.',
}
} finally {
- await apiFetch(
- `/managed-agents/sessions/${encodeURIComponent(sessionId)}/suspend`,
- { method: 'POST' },
- ).catch(() => undefined)
+ await suspendManagedAgentIfIdle(sessionId)
}
}
diff --git a/web/src/managed-agents/session-history.test.ts b/web/src/managed-agents/session-history.test.ts
new file mode 100644
index 00000000..139f92af
--- /dev/null
+++ b/web/src/managed-agents/session-history.test.ts
@@ -0,0 +1,89 @@
+import { describe, expect, it } from 'vitest'
+import type { ManagedAgentDeployment, ManagedAgentSession } from './api'
+import {
+ playgroundSessionIdFromSearch,
+ playgroundSessionSearch,
+ sessionsForEnvironment,
+} from './session-history'
+
+function deployment(
+ id: string,
+ alias: string,
+ agentId = 'reviewer',
+): ManagedAgentDeployment {
+ return {
+ id,
+ agentId,
+ alias,
+ channels: [],
+ connections: [],
+ createdAt: '2026-08-15T00:00:00.000Z',
+ }
+}
+
+function session(id: string, deploymentId: string): ManagedAgentSession {
+ return {
+ id,
+ agentId: 'reviewer',
+ deploymentId,
+ status: 'idle',
+ source: 'playground',
+ createdAt: '2026-08-15T00:00:00.000Z',
+ updatedAt: '2026-08-15T00:00:00.000Z',
+ turns: [],
+ }
+}
+
+describe('sessionsForEnvironment', () => {
+ it('keeps sessions from historical deployments in the selected environment', () => {
+ const sessions = [
+ session('old-development', 'dev-1'),
+ session('active-development', 'dev-2'),
+ session('production', 'prod-1'),
+ ]
+
+ expect(
+ sessionsForEnvironment(
+ sessions,
+ [
+ deployment('dev-1', 'development'),
+ deployment('dev-2', 'development'),
+ deployment('prod-1', 'production'),
+ ],
+ 'reviewer',
+ 'development',
+ ).map(({ id }) => id),
+ ).toEqual(['old-development', 'active-development'])
+ })
+
+ it('does not include another agent deployment', () => {
+ expect(
+ sessionsForEnvironment(
+ [session('other', 'other-dev')],
+ [deployment('other-dev', 'development', 'other-agent')],
+ 'reviewer',
+ 'development',
+ ),
+ ).toEqual([])
+ })
+})
+
+describe('playground session URL state', () => {
+ it('round trips a selected session without losing project context', () => {
+ const search = playgroundSessionSearch(
+ '?agent=reviewer&environment=production',
+ 'session-1',
+ )
+
+ expect(search).toBe(
+ '?agent=reviewer&environment=production&session=session-1',
+ )
+ expect(playgroundSessionIdFromSearch(search)).toBe('session-1')
+ })
+
+ it('clears only the session when starting a new draft', () => {
+ expect(playgroundSessionSearch('?agent=reviewer&session=session-1')).toBe(
+ '?agent=reviewer',
+ )
+ })
+})
diff --git a/web/src/managed-agents/session-history.ts b/web/src/managed-agents/session-history.ts
new file mode 100644
index 00000000..19355f27
--- /dev/null
+++ b/web/src/managed-agents/session-history.ts
@@ -0,0 +1,30 @@
+import type { ManagedAgentDeployment, ManagedAgentSession } from './api'
+import type { ProjectEnvironment } from './project-context'
+
+export function sessionsForEnvironment(
+ sessions: ManagedAgentSession[],
+ deployments: ManagedAgentDeployment[],
+ agentId: string,
+ environment: ProjectEnvironment,
+) {
+ const deploymentIds = new Set(
+ deployments
+ .filter(
+ (deployment) =>
+ deployment.agentId === agentId && deployment.alias === environment,
+ )
+ .map((deployment) => deployment.id),
+ )
+ return sessions.filter((session) => deploymentIds.has(session.deploymentId))
+}
+
+export function playgroundSessionIdFromSearch(search: string) {
+ return new URLSearchParams(search).get('session') || undefined
+}
+
+export function playgroundSessionSearch(search: string, sessionId?: string) {
+ const next = new URLSearchParams(search)
+ if (sessionId) next.set('session', sessionId)
+ else next.delete('session')
+ return next.size ? `?${next.toString()}` : ''
+}