Skip to content

AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents

feat(agents): open a run to see what the agent did, without leaving the agent (#15583)

Hazem Adel1193f3b219b9
diff --git a/packages/server/api/src/app/ee/agent/agent-conversation-controller.ts b/packages/server/api/src/app/ee/agent/agent-conversation-controller.ts
index 8e667e5024b..c123d2255d8 100644
--- a/packages/server/api/src/app/ee/agent/agent-conversation-controller.ts
+++ b/packages/server/api/src/app/ee/agent/agent-conversation-controller.ts
@@ -61,6 +61,21 @@ export const agentConversationController: FastifyPluginAsyncZod = async (app) =>
})
})
+ app.get('/conversations/runs/:id', GetAgentRunRoute, async (request) => {
+ const readerId = await securityHelper.getUserIdFromRequest(request)
+ assertNotNullOrUndefined(readerId, 'userId')
+ const run = await agentConversationService(request.log).getAgentRunOrThrow({
+ id: request.params.id,
+ projectId: request.projectId,
+ })
+ await agentService(request.log).getOneOrThrow({
+ id: run.agentId,
+ projectId: request.projectId,
+ userId: readerId,
+ })
+ return run
+ })
+
app.get('/conversations/:id', GetConversationRoute, async (request) => {
return agentConversationService(request.log).getConversationOrThrow({
id: request.params.id,
@@ -448,6 +463,23 @@ const ListAgentRunsRoute = {
const CONVERSATION_PARAMS = z.object({ id: z.string() })
+const GetAgentRunRoute = {
+ config: {
+ security: securityAccess.project(
+ CHAT_PRINCIPALS,
+ Permission.READ_AGENT,
+ { type: ProjectResourceType.QUERY },
+ ),
+ },
+ schema: {
+ tags: ['agents'],
+ security: [SERVICE_KEY_SECURITY_OPENAPI],
+ description: 'Read one unattended run a flow step made, without being able to continue it',
+ params: CONVERSATION_PARAMS,
+ querystring: z.object({ projectId: z.string() }),
+ },
+}
+
const GetConversationRoute = {
config: {
security: securityAccess.publicPlatform(CHAT_PRINCIPALS),
diff --git a/packages/server/api/src/app/ee/agent/agent-conversation-service.ts b/packages/server/api/src/app/ee/agent/agent-conversation-service.ts
index 1acca12ca1b..c27520bb6f1 100644
--- a/packages/server/api/src/app/ee/agent/agent-conversation-service.ts
+++ b/packages/server/api/src/app/ee/agent/agent-conversation-service.ts
@@ -168,6 +168,27 @@ export const agentConversationService = (log: FastifyBaseLogger) => ({
return paginationHelper.createPage(withFlow, paginationCursor)
},
+ async getAgentRunOrThrow({ id, projectId }: { id: string, projectId: string }): Promise<AgentRunListItem & { agentId: string }> {
+ const run = await agentHelpers.conversationRepo().findOne({
+ where: { id, projectId, source: AgentRunSource.FLOW_STEP },
+ select: [
+ 'id', 'created', 'updated', 'platformId', 'projectId', 'userId',
+ 'agentId', 'flowRunId', 'aiCredits', 'source', 'title',
+ 'modelName', 'status', 'activeRunId', 'uiMessages', 'summary',
+ 'summarizedUpToIndex',
+ ],
+ })
+ if (isNil(run) || isNil(run.agentId)) {
+ throw new ActivepiecesError({ code: ErrorCode.ENTITY_NOT_FOUND, params: { entityId: id, entityType: 'AgentConversation' } })
+ }
+ const flowByRunId = await flowReferencesFor([run])
+ return {
+ ...run,
+ agentId: run.agentId,
+ flow: isNil(run.flowRunId) ? null : flowByRunId.get(run.flowRunId) ?? null,
+ }
+ },
+
async getConversationOrThrow({ id, platformId, userId }: ConversationIdentifier): Promise<AgentConversation> {
// Eval conversations must never be opened or messaged through the regular (non-dry-run) chat
// path — that would run real tools against a conversation meant to be side-effect-free.
diff --git a/packages/server/api/test/integration/ee/agent/agent-runs-list.test.ts b/packages/server/api/test/integration/ee/agent/agent-runs-list.test.ts
index 4fdb476b352..9463b9e6426 100644
--- a/packages/server/api/test/integration/ee/agent/agent-runs-list.test.ts
+++ b/packages/server/api/test/integration/ee/agent/agent-runs-list.test.ts
@@ -61,10 +61,61 @@ async function seedRun({ ctx, agentId, source, projectId, title }: {
return id
}
+function getRun(ctx: TestContext, runId: string, projectId?: string) {
+ return ctx.get(`/v1/agents/conversations/runs/${runId}?projectId=${projectId ?? ctx.project.id}`)
+}
+
function listRuns(ctx: TestContext, agentId: string, projectId?: string) {
return ctx.get(`/v1/agents/conversations/runs?projectId=${projectId ?? ctx.project.id}&agentId=${agentId}`)
}
+describe('reading one unattended run', () => {
+ it('returns the run so it can be read without being able to continue it', async () => {
+ const ctx = await context()
+ const agent = await createAgent(ctx)
+ const runId = await seedRun({ ctx, agentId: agent.id, source: AgentRunSource.FLOW_STEP, title: 'Swept the inbox' })
+
+ const response = await getRun(ctx, runId)
+
+ expect(response.statusCode).toBe(StatusCodes.OK)
+ expect(response.json().id).toBe(runId)
+ expect(response.json().title).toBe('Swept the inbox')
+ })
+
+ it('never hands back the raw model transcript, only the curated one the UI shows', async () => {
+ const ctx = await context()
+ const agent = await createAgent(ctx)
+ const runId = await seedRun({ ctx, agentId: agent.id, source: AgentRunSource.FLOW_STEP })
+
+ const response = await getRun(ctx, runId)
+
+ expect(response.statusCode).toBe(StatusCodes.OK)
+ expect(response.json().messages).toBeUndefined()
+ expect(response.json()).toHaveProperty('uiMessages')
+ })
+
+ it('refuses a chat conversation, so this is not a way around the rule that chat history stays private', async () => {
+ const ctx = await context()
+ const agent = await createAgent(ctx)
+ const chatId = await seedRun({ ctx, agentId: agent.id, source: AgentRunSource.CHAT, title: 'A private chat' })
+
+ const response = await getRun(ctx, chatId)
+
+ expect(response.statusCode).toBe(StatusCodes.NOT_FOUND)
+ })
+
+ it('refuses a run that belongs to another project', async () => {
+ const ctx = await context()
+ const other = await context()
+ const agent = await createAgent(other)
+ const runId = await seedRun({ ctx: other, agentId: agent.id, source: AgentRunSource.FLOW_STEP })
+
+ const response = await getRun(ctx, runId)
+
+ expect(response.statusCode).not.toBe(StatusCodes.OK)
+ })
+})
+
describe('the runs a flow step made with an agent', () => {
it('lists the unattended runs, which is the half of the history nobody could see', async () => {
const ctx = await context()
diff --git a/packages/web/src/app/routes/agents/id/index.tsx b/packages/web/src/app/routes/agents/id/index.tsx
index f4ba2490584..137ca7aeb49 100644
--- a/packages/web/src/app/routes/agents/id/index.tsx
+++ b/packages/web/src/app/routes/agents/id/index.tsx
@@ -181,7 +181,12 @@ const AgentEditorContent = () => {
return (
<div className="flex h-full w-full">
<div className="flex min-w-0 grow flex-col">
- <div className="flex h-[60px] shrink-0 items-center gap-3 border-b border-border px-5">
+ <div
+ className={cn(
+ 'flex h-[60px] shrink-0 items-center gap-3 px-5',
+ !runsOpen && 'border-b border-border',
+ )}
+ >
<button
type="button"
aria-label={t('Back to agents')}
diff --git a/packages/web/src/app/routes/agents/id/runs/index.tsx b/packages/web/src/app/routes/agents/id/runs/index.tsx
index 5cfadd2d078..ed7eb7dee5b 100644
--- a/packages/web/src/app/routes/agents/id/runs/index.tsx
+++ b/packages/web/src/app/routes/agents/id/runs/index.tsx
@@ -11,8 +11,7 @@ import {
Hourglass,
Workflow,
} from 'lucide-react';
-import { useCallback, useMemo } from 'react';
-import { Link, useNavigate } from 'react-router-dom';
+import { useMemo, useState } from 'react';
import { DataTable, RowDataWithActions } from '@/components/custom/data-table';
import { DataTableColumnHeader } from '@/components/custom/data-table/data-table-column-header';
@@ -22,9 +21,9 @@ import { StatusIconWithText } from '@/components/custom/status-icon-with-text';
import { agentsQueries } from '@/features/agents/hooks/agents-hooks';
import { agentRunUtils } from '@/features/agents/lib/agent-run-utils';
import { projectCollectionUtils } from '@/features/projects';
-import { authenticationSession } from '@/lib/authentication-session';
import { formatUtils } from '@/lib/format-utils';
-import { useNewWindow } from '@/lib/navigation-utils';
+
+import { RunDetailPanel } from './run-detail-panel';
type AgentRunsProps = {
agentId: string;
@@ -32,24 +31,7 @@ type AgentRunsProps = {
export const AgentRuns = ({ agentId }: AgentRunsProps) => {
const { project } = projectCollectionUtils.useCurrentProject();
- const navigate = useNavigate();
- const openNewWindow = useNewWindow();
- const openFlowRun = useCallback(
- (run: AgentRunListItem, newWindow: boolean) => {
- if (isNil(run.flow)) {
- return;
- }
- const to = authenticationSession.appendProjectRoutePrefix(
- `/runs/${run.flow.flowRunId}`,
- );
- if (newWindow) {
- openNewWindow(to);
- return;
- }
- navigate(to);
- },
- [navigate, openNewWindow],
- );
+ const [openRunId, setOpenRunId] = useState<string | null>(null);
const {
data: runs,
isLoading,
@@ -66,12 +48,19 @@ export const AgentRuns = ({ agentId }: AgentRunsProps) => {
<DataTableColumnHeader column={column} title={t('Run')} icon={Bot} />
),
cell: ({ row }) => (
- <div className="flex items-center gap-2 text-left">
+ <button
+ type="button"
+ className="flex items-center gap-2 text-left hover:underline"
+ onClick={(e) => {
+ e.stopPropagation();
+ setOpenRunId(row.original.id);
+ }}
+ >
<TruncatedColumnTextValue
value={row.original.title ?? t('Untitled run')}
className="max-w-[260px] 2xl:max-w-[420px]"
/>
- </div>
+ </button>
),
},
{
@@ -90,16 +79,9 @@ export const AgentRuns = ({ agentId }: AgentRunsProps) => {
return <span className="text-muted-foreground">{'\u2014'}</span>;
}
return (
- <Link
- to={authenticationSession.appendProjectRoutePrefix(
- `/runs/${flow.flowRunId}`,
- )}
- className="flex items-center gap-2 text-left hover:underline"
- onClick={(e) => e.stopPropagation()}
- onAuxClick={(e) => e.stopPropagation()}
- >
+ <div className="flex items-center gap-2 text-left">
<TruncatedColumnTextValue value={flow.displayName} />
- </Link>
+ </div>
);
},
},
@@ -186,7 +168,7 @@ export const AgentRuns = ({ agentId }: AgentRunsProps) => {
);
return (
- <div className="flex h-full w-full flex-col pt-2">
+ <div className="flex h-full w-full min-w-0 flex-col">
<DataTable
columns={columns}
page={runs}
@@ -194,14 +176,14 @@ export const AgentRuns = ({ agentId }: AgentRunsProps) => {
isError={isError}
errorStateEntity={t('runs')}
onRetry={refetch}
- onRowClick={(row, newWindow) => openFlowRun(row, newWindow)}
- getRowClassName={(row) => (isNil(row.flow) ? 'cursor-default' : '')}
+ onRowClick={(row) => setOpenRunId(row.id)}
emptyStateIcon={<History className="size-14" />}
emptyStateTextTitle={t('No flow has run this agent yet')}
emptyStateTextDescription={t(
'Add a Run Agent step to a flow and pick this agent. Every run it makes on its own shows up here.',
)}
/>
+ <RunDetailPanel runId={openRunId} onClose={() => setOpenRunId(null)} />
</div>
);
};
diff --git a/packages/web/src/app/routes/agents/id/runs/run-detail-panel.tsx b/packages/web/src/app/routes/agents/id/runs/run-detail-panel.tsx
new file mode 100644
index 00000000000..5744a3c3081
--- /dev/null
+++ b/packages/web/src/app/routes/agents/id/runs/run-detail-panel.tsx
@@ -0,0 +1,274 @@
+import { isNil } from '@activepieces/core-utils';
+import {
+ AgentRunListItem,
+ ContentBlockType,
+ PersistedAgentPart,
+ PersistedAgentPartType,
+ PersistedAgentRole,
+ PersistedToolCallStatus,
+} from '@activepieces/shared';
+import { t } from 'i18next';
+import {
+ ArrowUpRight,
+ Brain,
+ ChevronRight,
+ CircleAlert,
+ CircleCheck,
+ Paperclip,
+} from 'lucide-react';
+import { useState } from 'react';
+
+import { DataFetchErrorState } from '@/components/custom/data-fetch-error-state';
+import { JsonViewer } from '@/components/custom/json-viewer';
+import { StatusIconWithText } from '@/components/custom/status-icon-with-text';
+import {
+ Collapsible,
+ CollapsibleContent,
+ CollapsibleTrigger,
+} from '@/components/ui/collapsible';
+import { ScrollArea } from '@/components/ui/scroll-area';
+import {
+ Sheet,
+ SheetContent,
+ SheetHeader,
+ SheetTitle,
+} from '@/components/ui/sheet';
+import { Skeleton } from '@/components/ui/skeleton';
+import {
+ MarkdownBlock,
+ PromptBlock,
+ TimelineItem,
+} from '@/features/agents/agent-timeline/timeline-blocks';
+import { agentsQueries } from '@/features/agents/hooks/agents-hooks';
+import { agentRunUtils } from '@/features/agents/lib/agent-run-utils';
+import { projectCollectionUtils } from '@/features/projects';
+import { authenticationSession } from '@/lib/authentication-session';
+import { formatUtils } from '@/lib/format-utils';
+import { cn } from '@/lib/utils';
+
+type RunDetailPanelProps = {
+ runId: string | null;
+ onClose: () => void;
+};
+
+export const RunDetailPanel = ({ runId, onClose }: RunDetailPanelProps) => {
+ const { project } = projectCollectionUtils.useCurrentProject();
+ const {
+ data: run,
+ isLoading,
+ isError,
+ refetch,
+ } = agentsQueries.useAgentRun({
+ runId,
+ projectId: project.id,
+ });
+
+ return (
+ <Sheet open={!isNil(runId)} onOpenChange={(next) => !next && onClose()}>
+ <SheetContent side="right" className="w-full gap-0 p-0 sm:max-w-[640px]">
+ <SheetHeader className="shrink-0 gap-2 border-b border-border px-6 py-4">
+ <SheetTitle className="line-clamp-2 pr-8 text-base font-semibold">
+ {run?.title ?? t('Untitled run')}
+ </SheetTitle>
+ {!isNil(run) && <MetaStrip run={run} />}
+ </SheetHeader>
+ {isError ? (
+ <DataFetchErrorState
+ entity={t('run')}
+ onRetry={() => void refetch()}
+ />
+ ) : isLoading || isNil(run) ? (
+ <div className="flex flex-col gap-3 px-6 py-5">
+ <Skeleton className="h-16 w-full" />
+ <Skeleton className="h-4 w-2/3" />
+ <Skeleton className="h-16 w-full" />
+ </div>
+ ) : (
+ <ScrollArea className="min-h-0 grow">
+ <div className="flex flex-col gap-6 px-6 py-5">
+ {run.uiMessages?.map((message, messageIndex) =>
+ message.role === PersistedAgentRole.USER ? (
+ <Prompt key={messageIndex} parts={message.parts} />
+ ) : (
+ <div key={messageIndex} className="flex flex-col gap-6">
+ {message.parts.map((part, partIndex) => (
+ <Part key={partIndex} part={part} index={partIndex} />
+ ))}
+ </div>
+ ),
+ )}
+ </div>
+ </ScrollArea>
+ )}
+ </SheetContent>
+ </Sheet>
+ );
+};
+
+const MetaStrip = ({ run }: { run: AgentRunListItem }) => {
+ const look = agentRunUtils.getStatusIcon(run.status);
+ const durationMs = agentRunUtils.getDurationMs(run);
+ return (
+ <div className="flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-muted-foreground">
+ <StatusIconWithText
+ icon={look.Icon}
+ text={agentRunUtils.getStatusLabel(run.status)}
+ variant={look.variant}
+ />
+ {!isNil(durationMs) && (
+ <>
+ <Dot />
+ <span>{formatUtils.formatDuration(durationMs, true)}</span>
+ </>
+ )}
+ {!isNil(run.aiCredits) && (
+ <>
+ <Dot />
+ <span>{t('{credits} credits', { credits: run.aiCredits })}</span>
+ </>
+ )}
+ {!isNil(run.flow) && (
+ <>
+ <Dot />
+ <a
+ href={authenticationSession.appendProjectRoutePrefix(
+ `/runs/${run.flow.flowRunId}`,
+ )}
+ className="flex min-w-0 items-center gap-1 hover:underline"
+ >
+ <span className="min-w-0 truncate">{run.flow.displayName}</span>
+ <ArrowUpRight size={12} className="shrink-0" />
+ </a>
+ </>
+ )}
+ </div>
+ );
+};
+
+const Dot = () => <span aria-hidden="true">&middot;</span>;
+
+const Prompt = ({ parts }: { parts: PersistedAgentPart[] }) => {
+ const text = parts
+ .filter((part) => part.type === PersistedAgentPartType.TEXT)
+ .map((part) => part.text)
+ .join('\n');
+ if (text.length === 0) {
+ return null;
+ }
+ return <PromptBlock prompt={text} />;
+};
+
+const Part = ({ part, index }: { part: PersistedAgentPart; index: number }) => {
+ if (part.type === PersistedAgentPartType.TEXT) {
+ return (
+ <MarkdownBlock
+ index={index}
+ step={{ type: ContentBlockType.MARKDOWN, markdown: part.text }}
+ />
+ );
+ }
+ if (part.type === PersistedAgentPartType.TOOL_CALL) {
+ return <ToolCall part={part} />;
+ }
+ if (part.type === PersistedAgentPartType.REASONING) {
+ return (
+ <TimelineItem icon={<Brain className="h-4 w-4 text-muted-foreground" />}>
+ <p className="py-3 text-sm text-muted-foreground">{part.text}</p>
+ </TimelineItem>
+ );
+ }
+ if (
+ part.type === PersistedAgentPartType.IMAGE ||
+ part.type === PersistedAgentPartType.FILE ||
+ part.type === PersistedAgentPartType.SOURCE_URL
+ ) {
+ return (
+ <TimelineItem
+ icon={<Paperclip className="h-4 w-4 text-muted-foreground" />}
+ >
+ <a
+ href={part.url}
+ target="_blank"
+ rel="noreferrer"
+ className="flex items-center gap-1 py-3 text-sm hover:underline"
+ >
+ <span className="min-w-0 truncate">{partLabel(part)}</span>
+ <ArrowUpRight size={12} className="shrink-0" />
+ </a>
+ </TimelineItem>
+ );
+ }
+ return null;
+};
+
+function partLabel(part: PersistedAgentPart): string {
+ if (part.type === PersistedAgentPartType.IMAGE) {
+ return part.title ?? t('Image');
+ }
+ if (part.type === PersistedAgentPartType.FILE) {
+ return part.fileName;
+ }
+ if (part.type === PersistedAgentPartType.SOURCE_URL) {
+ return part.title ?? part.url;
+ }
+ return '';
+}
+
+const ToolCall = ({
+ part,
+}: {
+ part: Extract<PersistedAgentPart, { type: PersistedAgentPartType.TOOL_CALL }>;
+}) => {
+ const failed = part.status === PersistedToolCallStatus.ERROR;
+ const [open, setOpen] = useState(failed);
+ const hasInput = Object.keys(part.input ?? {}).length > 0;
+ const hasOutput = !isNil(part.output);
+
+ return (
+ <TimelineItem
+ icon={
+ failed ? (
+ <CircleAlert className="h-4 w-4 text-destructive" />
+ ) : (
+ <CircleCheck className="h-4 w-4 text-muted-foreground" />
+ )
+ }
+ >
+ <Collapsible open={open} onOpenChange={setOpen}>
+ <CollapsibleTrigger className="flex w-full items-center gap-2 py-3 text-left text-sm">
+ <span className="min-w-0 truncate">
+ {part.title ?? (
+ <span className="font-mono text-xs">{part.toolName}</span>
+ )}
+ </span>
+ <ChevronRight
+ size={14}
+ className={cn(
+ 'shrink-0 text-muted-foreground transition-transform',
+ open && 'rotate-90',
+ )}
+ />
+ </CollapsibleTrigger>
+ <CollapsibleContent className="flex flex-col gap-3 pt-3">
+ {failed && !isNil(part.errorText) && (
+ <p className="text-xs text-destructive">{part.errorText}</p>
+ )}
+ {hasInput && <Payload label={t('Input')} value={part.input} />}
+ {hasOutput && <Payload label={t('Output')} value={part.output} />}
+ </CollapsibleContent>
+ </Collapsible>
+ </TimelineItem>
+ );
+};
+
+const Payload = ({ label, value }: { label: string; value: unknown }) => (
+ <JsonViewer
+ json={value}
+ title={
+ <span className="text-xss font-medium uppercase tracking-wider text-muted-foreground">
+ {label}
+ </span>
+ }
+ hideDownload
+ />
+);
diff --git a/packages/web/src/features/agents/agent-timeline/timeline-blocks.tsx b/packages/web/src/features/agents/agent-timeline/timeline-blocks.tsx
index b81e10287f0..440b6115130 100644
--- a/packages/web/src/features/agents/agent-timeline/timeline-blocks.tsx
+++ b/packages/web/src/features/agents/agent-timeline/timeline-blocks.tsx
@@ -49,7 +49,7 @@ const parseJsonOrReturnOriginal = (json: unknown) => {
}
};
-const TimelineItem = ({
+export const TimelineItem = ({
icon,
children,
iconLeft = 'left-0',
diff --git a/packages/web/src/features/agents/api/agents.ts b/packages/web/src/features/agents/api/agents.ts
index d1bf696dcde..50e406fc102 100644
--- a/packages/web/src/features/agents/api/agents.ts
+++ b/packages/web/src/features/agents/api/agents.ts
@@ -46,6 +46,11 @@ export const agentsApi = {
delete(id: string): Promise<void> {
return api.delete<void>(`/v1/agents/${id}`);
},
+ getRun(id: string, projectId: string): Promise<AgentRunListItem> {
+ return api.get<AgentRunListItem>(`/v1/agents/conversations/runs/${id}`, {
+ projectId,
+ });
+ },
listRuns(request: ListAgentRunsRequest): Promise<SeekPage<AgentRunListItem>> {
return api.get<SeekPage<AgentRunListItem>>(
'/v1/agents/conversations/runs',
diff --git a/packages/web/src/features/agents/hooks/agents-hooks.ts b/packages/web/src/features/agents/hooks/agents-hooks.ts
index fa9a9fc8b5c..87da1597cfc 100644
--- a/packages/web/src/features/agents/hooks/agents-hooks.ts
+++ b/packages/web/src/features/agents/hooks/agents-hooks.ts
@@ -1,3 +1,4 @@
+import { isNil } from '@activepieces/core-utils';
import {
Agent,
AgentConversationStatus,
@@ -102,6 +103,18 @@ export const agentsQueries = {
queryFn: () => agentsApi.get(id, { includeUsage }),
enabled,
}),
+ useAgentRun: ({
+ runId,
+ projectId,
+ }: {
+ runId: string | null;
+ projectId: string;
+ }) =>
+ useQuery({
+ queryKey: [AGENTS_KEY, 'run', runId],
+ enabled: !isNil(runId),
+ queryFn: () => agentsApi.getRun(runId ?? '', projectId),
+ }),
useAgentRuns: ({
agentId,
projectId,