Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
fix(agents): show sdk operations in inline activity (#8384)
Wolf Mermelsteince989bfbd3e7
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.mdindex db09d39316..4e91881fbb 100644--- a/apps/web/AGENTS.md+++ b/apps/web/AGENTS.md@@ -115,6 +115,8 @@ ownership. Cancel, logout, and the ten-minute timeout retire pending callbacks.- Passive PR mentions must not retry initial GitHub status failures on remount; preserve confirmed status through refetch errors and keep pending data reads out of their parent Suspense boundary.- Keep native booking exit navigation in the route shell, outside page loading boundaries, and use the router so the native hash route stays intact.- Diagnose native full reloads with `native_webview_started` and native launch/termination/update counters; termination coverage is iOS/macOS only, and a pageview alone also includes SPA navigation. See `tauri/src-tauri/README.md`.+- Inline agent steps reuse the session code-execution query for live SDK operation+ names; completed step snapshots come from the shared fold of the tool receipt.- All API/network calls live in service-clients.- Keep early DOCX opens loading while exports return processing (409); retry onlythat response, with a bounded wait. See the Word editor walkthrough indiff --git a/apps/web/src/features/agent-activity/agent-activity.test.tsx b/apps/web/src/features/agent-activity/agent-activity.test.tsxindex fbd03efcbf..972b22f7e0 100644--- a/apps/web/src/features/agent-activity/agent-activity.test.tsx+++ b/apps/web/src/features/agent-activity/agent-activity.test.tsx@@ -3,11 +3,18 @@ import type {ActivityRow,FoldedMessage,} from '@service-agent-fold/generated/types';-import { cleanup, render } from '@solidjs/testing-library';+import type { ExecutionRecord } from '@service-agent-harness/generated/schemas';+import { cleanup, render, waitFor } from '@solidjs/testing-library';+import { QueryClient, QueryClientProvider } from '@tanstack/solid-query';+import { ok } from 'neverthrow';import { createSignal } from 'solid-js';import { afterEach, expect, it, vi } from 'vitest';const live = vi.hoisted(() => ({ acquired: [] as (string | undefined)[] }));+const code = vi.hoisted(() => ({ read: vi.fn() }));+vi.mock('@service-agent-harness/client', () => ({+ agentHarnessServiceClient: { getCodeExecution: code.read },+}));const [messages, setMessages] = createSignal<FoldedMessage[]>([]);vi.mock('./queries/live-session', () => ({createLiveSession: (id: () => string | undefined) => {@@ -19,12 +26,22 @@ vi.mock('@app/features/block-agent/ui', () => ({TextShimmer: (props: { text: string }) => <>{props.text}</>,}));-import { AgentActivity } from './agent-activity';+import type { AgentActivityData } from '@macro-inc/lexical-core';+import { AgentActivity as Activity } from './agent-activity';++function AgentActivity(props: AgentActivityData) {+ return (+ <QueryClientProvider client={new QueryClient()}>+ <Activity {...props} />+ </QueryClientProvider>+ );+}afterEach(() => {cleanup();live.acquired.length = 0;setMessages([]);+ code.read.mockReset();});const snapshot: AgentActivityRow[] = [@@ -114,6 +131,96 @@ it('folds a long run behind a count of its earlier steps', () => {expect(view.getByText('Step 1')).toBeTruthy();});+it('replaces a live code step with observed SDK operations and preserves uncertain outcomes', async () => {+ const executionId = '019a0000-0000-7000-8000-000000000001';+ const record: ExecutionRecord = {+ executionId,+ source: 'export async function main() {}',+ status: 'running',+ calls: [],+ activity: [+ { id: 1, label: 'Search documents', status: 'completed' },+ { id: 2, label: 'Read email', status: 'running' },+ ],+ activityTruncated: false,+ };+ code.read.mockResolvedValue(ok(record));+ const client = new QueryClient();+ const view = render(() => (+ <QueryClientProvider client={client}>+ <Activity+ agentSessionId="session"+ turn={2}+ segment={1}+ rows={[{ id: 'code-1', label: 'Execute code', status: 'running' }]}+ sealed={false}+ />+ </QueryClientProvider>+ ));+ const message = reply([+ { id: 'code-1', label: 'Execute code', detail: null, status: 'running' },+ ]);+ message.parts = [+ { kind: 'text', text: 'Checking' },+ {+ kind: 'tool_use',+ id: 'code-1',+ name: { kind: 'mcp', server: 'macro_internal', tool: 'ExecuteCode' },+ status: 'running',+ detail: {+ kind: 'other',+ acpKind: 'other',+ input: { execution_id: executionId, source: record.source },+ result: null,+ output: null,+ error: null,+ },+ },+ ];+ setMessages([message]);+ await waitFor(() =>+ expect(steps(view)).toEqual([+ ['Search documents', 'completed'],+ ['Read email', 'running'],+ ])+ );+ expect(code.read).toHaveBeenCalledWith('session', executionId);++ client.setQueriesData(+ { queryKey: ['agentCodeExecution'] },+ {+ ...record,+ status: 'cancelled',+ activity: [+ { id: 1, label: 'Search documents', status: 'completed' },+ { id: 2, label: 'Read email', status: 'unknown' },+ ],+ }+ );+ await waitFor(() =>+ expect(steps(view)).toEqual([+ ['Search documents', 'completed'],+ ['Read email', 'interrupted'],+ ])+ );+ expect(view.queryByText(record.source)).toBeNull();++ code.read.mockRejectedValue(new Error('Temporary network failure'));+ await client.refetchQueries({ queryKey: ['agentCodeExecution'] });+ expect(steps(view)).toEqual([+ ['Search documents', 'completed'],+ ['Read email', 'interrupted'],+ ]);++ client.setQueriesData(+ { queryKey: ['agentCodeExecution'] },+ { ...record, source: 'another execution' }+ );+ await waitFor(() =>+ expect(steps(view)).toEqual([['Execute code', 'running']])+ );+});+it('updates a live row in place as the run paints, rather than redrawing it', () => {const view = render(() => (<AgentActivitydiff --git a/apps/web/src/features/agent-activity/agent-activity.tsx b/apps/web/src/features/agent-activity/agent-activity.tsxindex 6a4b3eb884..348aade082 100644--- a/apps/web/src/features/agent-activity/agent-activity.tsx+++ b/apps/web/src/features/agent-activity/agent-activity.tsx@@ -2,6 +2,7 @@ import type { AgentActivityData } from '@macro-inc/lexical-core';import { Show } from 'solid-js';import { ActivityRows } from './components/activity-rows';import { replyToTurn, segmentRows } from './core/live-reply';+import { createCodeActivityRows } from './queries/code-activity';import { createLiveSession } from './queries/live-session';/**@@ -25,9 +26,16 @@ export function AgentActivity(props: AgentActivityData) {function LiveActivity(props: AgentActivityData) {const live = createLiveSession(() => props.agentSessionId);+ const reply = () => replyToTurn(live.messages(), props.turn);const rows = () => {- const reply = replyToTurn(live.messages(), props.turn);- return (reply && segmentRows(reply, props.segment)) ?? props.rows;+ const message = reply();+ return (message && segmentRows(message, props.segment)) ?? props.rows;};- return <ActivityRows rows={rows()} />;+ const activity = createCodeActivityRows(+ () => props.agentSessionId,+ reply,+ () => props.segment,+ rows+ );+ return <ActivityRows rows={activity()} />;}diff --git a/apps/web/src/features/agent-activity/queries/code-activity.ts b/apps/web/src/features/agent-activity/queries/code-activity.tsnew file mode 100644index 0000000000..3cb38365a0--- /dev/null+++ b/apps/web/src/features/agent-activity/queries/code-activity.ts@@ -0,0 +1,63 @@+import { codeExecutionInput } from '@app/features/block-agent/state/code-execution';+import { isCodeExecution } from '@app/features/block-agent/state/tool-groups';+import type { AgentActivityRow } from '@macro-inc/lexical-core';+import { agentCodeExecutionQueryOptions } from '@queries/agent-session/code-execution';+import type {+ ActivityRow,+ FoldedMessage,+} from '@service-agent-fold/generated/types';+import { useQueries } from '@tanstack/solid-query';+import { type Accessor, createMemo } from 'solid-js';++/** Share the session view's observed SDK activity while an inline run is open. */+export function createCodeActivityRows(+ sessionId: Accessor<string>,+ reply: Accessor<FoldedMessage | undefined>,+ segment: Accessor<number>,+ rows: Accessor<readonly (ActivityRow | AgentActivityRow)[]>+) {+ const calls = createMemo(() => {+ const message = reply();+ const range = message?.segments.find((item) => item.index === segment());+ if (!message || !range) return [];+ return message.parts.slice(range.start, range.end).flatMap((part) => {+ if (+ !isCodeExecution(part) ||+ part.kind !== 'tool_use' ||+ part.status === 'pending'+ )+ return [];+ const input = codeExecutionInput(part);+ return input ? [{ ...input, id: part.id }] : [];+ });+ });+ const queries = useQueries(() => ({+ queries: calls().map((call) =>+ agentCodeExecutionQueryOptions(sessionId(), call.executionId)+ ),+ }));+ return () => {+ const replacements = new Map<string, ActivityRow[]>();+ calls().forEach((call, index) => {+ const query = queries[index];+ const record = query && !query.isPending ? query.data : undefined;+ const activity =+ record?.source === call.source ? record.activity : undefined;+ if (!activity?.length) return;+ replacements.set(+ call.id,+ activity.map((item) => ({+ id: `${call.id}:${item.id}`,+ label: item.label,+ detail: null,+ status:+ item.status === 'unknown' ||+ (item.status === 'running' && reply()?.stop !== null)+ ? 'interrupted'+ : item.status,+ }))+ );+ });+ return rows().flatMap((row) => replacements.get(row.id) ?? [row]);+ };+}diff --git a/apps/web/src/features/block-agent/state/code-execution.ts b/apps/web/src/features/block-agent/state/code-execution.tsnew file mode 100644index 0000000000..6719442627--- /dev/null+++ b/apps/web/src/features/block-agent/state/code-execution.ts@@ -0,0 +1,23 @@+import type { MessagePart } from '@service-agent-fold/generated/types';++// Match UUIDs accepted by Rust, including reserved versions and variants.+export const isExecutionId = (value: string) =>+ /^[\da-f]{8}(?:-[\da-f]{4}){3}-[\da-f]{12}$/i.test(value);++export function codeExecutionInput(part: MessagePart) {+ const input =+ part.kind === 'tool_use' && 'input' in part.detail+ ? part.detail.input+ : undefined;+ if (+ !input ||+ typeof input !== 'object' ||+ !('execution_id' in input) ||+ typeof input.execution_id !== 'string' ||+ !isExecutionId(input.execution_id) ||+ !('source' in input) ||+ typeof input.source !== 'string'+ )+ return;+ return { executionId: input.execution_id, source: input.source };+}diff --git a/apps/web/src/features/block-agent/views/CodeExecutionPart.tsx b/apps/web/src/features/block-agent/views/CodeExecutionPart.tsxindex 8b5502537b..c014636657 100644--- a/apps/web/src/features/block-agent/views/CodeExecutionPart.tsx+++ b/apps/web/src/features/block-agent/views/CodeExecutionPart.tsx@@ -7,11 +7,7 @@ import type {ToolCallContext,ToolUsePart,} from '../component/parts/shared';--// Rust accepts UUIDs with reserved versions/variants too. Model-selected IDs-// still identify real records; keep their document cards and failure status.-const isExecutionId = (value: string) =>- /^[\da-f]{8}(?:-[\da-f]{4}){3}-[\da-f]{12}$/i.test(value);+import { codeExecutionInput, isExecutionId } from '../state/code-execution';/** Production wiring; the result components receive only data and context. */export function CodeExecutionPart(props: {@@ -32,18 +28,8 @@ export function CodeExecutionPart(props: {? parsed.data: undefined;});- const input = () =>- 'input' in props.part.detail ? props.part.detail.input : undefined;- const requestedExecutionId = () => {- const value = input();- return typeof value === 'object' &&- value !== null &&- 'execution_id' in value &&- typeof value.execution_id === 'string' &&- isExecutionId(value.execution_id)- ? value.execution_id- : undefined;- };+ const requestedExecutionId = () =>+ codeExecutionInput(props.part)?.executionId;const executionId = () => {const saved = receipt()?.executionId;if (saved) return saved;@@ -53,16 +39,7 @@ export function CodeExecutionPart(props: {() => props.context.sessionId,executionId);- const source = () => {- const detail = props.part.detail;- const input = 'input' in detail ? detail.input : undefined;- return typeof input === 'object' &&- input !== null &&- 'source' in input &&- typeof input.source === 'string'- ? input.source- : undefined;- };+ const source = () => codeExecutionInput(props.part)?.source;if (import.meta.env.DEV) {let loggedCall: string | undefined;diff --git a/apps/web/src/lib/queries/agent-session/code-execution.ts b/apps/web/src/lib/queries/agent-session/code-execution.tsindex ac9c8a4792..162529d0fd 100644--- a/apps/web/src/lib/queries/agent-session/code-execution.ts+++ b/apps/web/src/lib/queries/agent-session/code-execution.ts@@ -14,7 +14,7 @@ export function useAgentCodeExecutionQuery();}-function agentCodeExecutionQueryOptions(+export function agentCodeExecutionQueryOptions(session: string,execution: string | undefined) {diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.tsindex a62aafcc27..ccc4c813ec 100644--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts@@ -16231,6 +16231,37 @@ export const ExecutionReceipt = z.object({});}}),+ activity: z+ .array(+ z.object({+ id: z.number().int().gte(0),+ label: z.string(),+ status: z.any().superRefine((x, ctx) => {+ const schemas = [+ z.literal('running'),+ z.literal('completed'),+ z.literal('failed'),+ z.literal('unknown'),+ ];+ const errors = schemas.reduce<z.ZodError[]>(+ (errors, schema) =>+ ((result) => (result.error ? [...errors, result.error] : errors))(+ schema.safeParse(x)+ ),+ []+ );+ if (schemas.length - errors.length !== 1) {+ ctx.addIssue({+ path: ctx.path,+ code: 'invalid_union',+ unionErrors: errors,+ message: 'Invalid input: Should pass single schema',+ });+ }+ }),+ })+ )+ .optional(),result: z.any().optional(),error: z.union([z.string(), z.null()]).optional(),});diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.tsindex 8981718657..9102a60369 100644--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts@@ -4783,6 +4783,10 @@ export type ExecutionStatus =| 'failed'| 'cancelled'| 'timed_out';+/**+ * A dispatch result; unfinished work is never reported as success.+ */+export type RecordedCallStatus = 'running' | 'completed' | 'failed' | 'unknown';export type ContentType =| 'channel'| 'channel-message'@@ -15221,6 +15225,10 @@ export interface ExecuteCode {export interface ExecutionReceipt {executionId: ExecutionId;status: ExecutionStatus;+ /**+ * Observed SDK operations for conversation activity snapshots.+ */+ activity?: ExecutionActivity[];/*** Only the value explicitly returned by the program.*/@@ -15232,6 +15240,20 @@ export interface ExecutionReceipt {*/error?: string | null;}+/**+ * A bounded SDK operation observed during execution; not an authorization or write receipt.+ */+export interface ExecutionActivity {+ /**+ * Request identity within the execution.+ */+ id: number;+ /**+ * Server-selected label from the generated operation catalog.+ */+ label: string;+ status: RecordedCallStatus;+}/*** Retrieve a chat thread's message history by its ID. Returns the conversation title and messages with their roles, content, and attachment references.*/diff --git a/crates/agent_code_mode/AGENTS.md b/crates/agent_code_mode/AGENTS.mdindex 28a0a372da..f1beab9efa 100644--- a/crates/agent_code_mode/AGENTS.md+++ b/crates/agent_code_mode/AGENTS.md@@ -12,7 +12,8 @@ execution records, and durable review stacks. Process isolation belongs to## Start here- `SKILL.md`: the agent-facing JavaScript contract and examples.-- `src/domain/service.rs`: execution admission, identity and persistence.+- `src/domain/service.rs`: execution admission, identity and persistence; tool+ receipts include observed SDK activity for inline conversation snapshots.- `src/domain/reviews.rs`: review validation, revisions, claims and outcomes.- `src/domain/documentation.rs`: bounded selection of generated SDK docs.diff --git a/crates/agent_code_mode/src/domain/models.rs b/crates/agent_code_mode/src/domain/models.rsindex 8efb75bd88..67bdb58b6e 100644--- a/crates/agent_code_mode/src/domain/models.rs+++ b/crates/agent_code_mode/src/domain/models.rs@@ -84,7 +84,7 @@ pub struct RecordedToolCall {}/// A dispatch result; unfinished work is never reported as success.-#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, ToSchema)]+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema, ToSchema)]#[serde(rename_all = "snake_case")]pub enum RecordedCallStatus {/// The dispatcher is still awaiting the tool.@@ -130,6 +130,9 @@ pub struct ExecutionReceipt {pub execution_id: ExecutionId,/// Last recorded outcome; running may be stale after a process interruption.pub status: ExecutionStatus,+ /// Observed SDK operations for conversation activity snapshots.+ #[serde(default)]+ pub activity: Vec<ExecutionActivity>,/// Only the value explicitly returned by the program.pub result: Option<Value>,/// Safe failure text, when execution did not succeed.@@ -169,7 +172,7 @@ pub enum CodeModeError {}/// A bounded SDK operation observed during execution; not an authorization or write receipt.-#[derive(Clone, Serialize, Deserialize, ToSchema)]+#[derive(Clone, Serialize, Deserialize, JsonSchema, ToSchema)]#[serde(rename_all = "camelCase")]pub struct ExecutionActivity {/// Request identity within the execution.diff --git a/crates/agent_code_mode/src/domain/service.rs b/crates/agent_code_mode/src/domain/service.rsindex 4e19812cdf..173f8d27e4 100644--- a/crates/agent_code_mode/src/domain/service.rs+++ b/crates/agent_code_mode/src/domain/service.rs@@ -364,6 +364,7 @@ fn receipt(record: &ExecutionRecord) -> ExecutionReceipt {ExecutionReceipt {execution_id: record.execution_id,status: record.status,+ activity: record.activity.clone(),result: record.result.clone(),error: execution_error(record),}diff --git a/crates/agent_code_mode/src/domain/service/test.rs b/crates/agent_code_mode/src/domain/service/test.rsindex 4004ba95f4..0784409f76 100644--- a/crates/agent_code_mode/src/domain/service/test.rs+++ b/crates/agent_code_mode/src/domain/service/test.rs@@ -388,7 +388,11 @@ async fn persists_live_activity_and_marks_unfinished_requests_unknown() {}).await.unwrap();- assert_eq!(running.await.unwrap().status, ExecutionStatus::Succeeded);+ let receipt = running.await.unwrap();+ assert_eq!(receipt.status, ExecutionStatus::Succeeded);+ assert_eq!(receipt.activity.len(), 2);+ assert_eq!(receipt.activity[0].status, RecordedCallStatus::Completed);+ assert_eq!(receipt.activity[1].status, RecordedCallStatus::Unknown);let record = store.get(session_id, id).await.unwrap();assert_eq!(record.activity.len(), 2);assert_eq!(record.activity[0].status, RecordedCallStatus::Completed);diff --git a/crates/folds/agent_fold/AGENTS.md b/crates/folds/agent_fold/AGENTS.mdindex 3fafe75030..eb4383e110 100644--- a/crates/folds/agent_fold/AGENTS.md+++ b/crates/folds/agent_fold/AGENTS.md@@ -18,6 +18,8 @@ to the browser via `inbound/wasm`.- `src/domain/fold.rs`: the fold itself — read its module doc first; it'stotal by design (see "Why this cannot fail") and never errors on read.+- `src/domain/model/segment/code_execution.rs`: expands internal code receipts+ into SDK activity rows for conversation snapshots, independent of harness.- `src/domain/model.rs`: the renderable vocabulary (`FoldedMessage`,`ToolStatus`, …) folds produce.- `src/domain/log.rs`: the raw log vocabulary folds consume.diff --git a/crates/folds/agent_fold/src/domain/harness/macro_tools.rs b/crates/folds/agent_fold/src/domain/harness/macro_tools.rsindex 6dddff6acd..939808cae2 100644--- a/crates/folds/agent_fold/src/domain/harness/macro_tools.rs+++ b/crates/folds/agent_fold/src/domain/harness/macro_tools.rs@@ -30,13 +30,18 @@ use crate::domain::model::{SubagentResult, ToolName, UserToolOutcome};/// imported so the wasm fold does not pull in the harness crate.pub const MCP_SERVER: &str = "macro";-/// The Macro tool `name` reaches over Macro's own MCP server, if it is one.+/// The Macro tool `name` reaches over Macro's MCP servers, if it is one.+/// Internal code execution must retain its JSON input and receipt even when+/// a harness calls it an `execute` tool rather than an `other` tool./// A native name is never a Macro tool by this rule - Macro's in-process/// agent is recognized by the harness it runs under, not by its tool names.#[must_use]pub fn mcp_tool(name: &ToolName) -> Option<&str> {match name {ToolName::Mcp { server, tool } if server == MCP_SERVER => Some(tool),+ ToolName::Mcp { server, tool } if server == "macro_internal" && tool == "ExecuteCode" => {+ Some(tool)+ }ToolName::Native { .. } | ToolName::Mcp { .. } => None,}}diff --git a/crates/folds/agent_fold/src/domain/model/segment.rs b/crates/folds/agent_fold/src/domain/model/segment.rsindex f2bfa7c3ed..1b369adb0e 100644--- a/crates/folds/agent_fold/src/domain/model/segment.rs+++ b/crates/folds/agent_fold/src/domain/model/segment.rs@@ -30,6 +30,8 @@ use super::{ElicitationOutcome, PermissionOutcome};#[cfg(test)]mod test;+mod code_execution;+/// Longest detail a row keeps, in characters.const DETAIL_MAX_CHARS: usize = 80;@@ -255,26 +257,27 @@ fn slice<'a>(parts: &'a [MessagePart], segment: &Segment) -> &'a [MessagePart] {fn activity_rows(parts: &[MessagePart], closed: bool) -> Vec<ActivityRow> {parts.iter()- .filter_map(|part| match part {+ .flat_map(|part| match part {MessagePart::ToolUse {id,name,status,detail,- } => Some(tool_row(id.0.clone(), name, *status, detail, closed)),+ } => code_execution::rows(&id.0, name, detail, closed)+ .unwrap_or_else(|| vec![tool_row(id.0.clone(), name, *status, detail, closed)]),MessagePart::Plan { entries } => {let done = entries.iter().filter(|entry| entry.status == PlanEntryStatus::Completed).count();- Some(ActivityRow {+ vec![ActivityRow {id: "plan".to_owned(),label: "Updated the plan".to_owned(),detail: Some(format!("{done}/{} done", entries.len())),status: ActivityStatus::Completed,- })+ }]}- _ => None,+ _ => Vec::new(),}).collect()}diff --git a/crates/folds/agent_fold/src/domain/model/segment/code_execution.rs b/crates/folds/agent_fold/src/domain/model/segment/code_execution.rsnew file mode 100644index 0000000000..fd625201b0--- /dev/null+++ b/crates/folds/agent_fold/src/domain/model/segment/code_execution.rs@@ -0,0 +1,61 @@+//! SDK activity carried by the internal code tool's receipt, independent of harness.++use serde::Deserialize;++use super::{ActivityRow, ActivityStatus, ToolDetail, ToolName};++// Read only the presentation fields of agent_code_mode's ExecutionReceipt.+// The wasm fold cannot depend on the execution service and its native runtime.+#[derive(Deserialize)]+struct Operation {+ id: u64,+ label: String,+ status: Status,+}++#[derive(Deserialize)]+#[serde(rename_all = "snake_case")]+enum Status {+ Running,+ Completed,+ Failed,+ Unknown,+}++pub(super) fn rows(+ id: &str,+ name: &ToolName,+ detail: &ToolDetail,+ closed: bool,+) -> Option<Vec<ActivityRow>> {+ if !matches!(name, ToolName::Mcp { server, tool } if server == "macro_internal" && tool == "ExecuteCode")+ {+ return None;+ }+ let output = match detail {+ ToolDetail::Macro { output, .. } => output.as_ref(),+ ToolDetail::Other { result, .. } => result.as_ref(),+ _ => None,+ }?;+ let activity: Vec<Operation> = serde_json::from_value(output.get("activity")?.clone()).ok()?;+ if activity.is_empty() {+ return None;+ }+ Some(+ activity+ .into_iter()+ .take(128)+ .map(|operation| ActivityRow {+ id: format!("{id}:{}", operation.id),+ label: operation.label,+ detail: None,+ status: match operation.status {+ Status::Running if !closed => ActivityStatus::Running,+ Status::Completed => ActivityStatus::Completed,+ Status::Failed => ActivityStatus::Failed,+ Status::Running | Status::Unknown => ActivityStatus::Interrupted,+ },+ })+ .collect(),+ )+}diff --git a/crates/folds/agent_fold/src/domain/model/segment/test.rs b/crates/folds/agent_fold/src/domain/model/segment/test.rsindex a7303ff440..563f1ada66 100644--- a/crates/folds/agent_fold/src/domain/model/segment/test.rs+++ b/crates/folds/agent_fold/src/domain/model/segment/test.rs@@ -68,6 +68,94 @@ fn kinds(segments: &[Segment]) -> Vec<(SegmentKind, bool)> {.collect()}+#[test]+fn code_execution_steps_show_observed_sdk_operations_without_source_or_results() {+ let part = MessagePart::ToolUse {+ id: ToolUseId("code-1".into()),+ name: ToolName::Mcp {+ server: "macro_internal".into(),+ tool: "ExecuteCode".into(),+ },+ status: ToolStatus::Completed,+ detail: ToolDetail::Other {+ kind: "other".into(),+ input: Some(serde_json::json!({"source": "secret program"})),+ result: Some(serde_json::json!({+ "result": {"data": "private result"},+ "activity": [+ {"id": 1, "label": "Search documents", "status": "completed"},+ {"id": 2, "label": "Read email", "status": "failed"},+ {"id": 3, "label": "Create document", "status": "unknown"},+ {"id": 4, "label": "Read email", "status": "running"}+ ]+ })),+ output: None,+ error: None,+ },+ };+ let live = segments(std::slice::from_ref(&part), false);+ assert_eq!(+ live[0].rows,+ vec![+ ActivityRow {+ id: "code-1:1".into(),+ label: "Search documents".into(),+ detail: None,+ status: ActivityStatus::Completed+ },+ ActivityRow {+ id: "code-1:2".into(),+ label: "Read email".into(),+ detail: None,+ status: ActivityStatus::Failed+ },+ ActivityRow {+ id: "code-1:3".into(),+ label: "Create document".into(),+ detail: None,+ status: ActivityStatus::Interrupted+ },+ ActivityRow {+ id: "code-1:4".into(),+ label: "Read email".into(),+ detail: None,+ status: ActivityStatus::Running+ },+ ]+ );+ assert_eq!(+ segments(std::slice::from_ref(&part), true)[0].rows[3].status,+ ActivityStatus::Interrupted+ );++ let mut external = part;+ if let MessagePart::ToolUse { name, .. } = &mut external {+ *name = ToolName::Mcp {+ server: "external".into(),+ tool: "ExecuteCode".into(),+ };+ }+ assert_eq!(segments(&[external], true)[0].rows.len(), 1);+}++#[test]+fn code_without_observed_requests_keeps_its_tool_step() {+ let part = MessagePart::ToolUse {+ id: ToolUseId("code-2".into()),+ name: ToolName::Mcp {+ server: "macro_internal".into(),+ tool: "ExecuteCode".into(),+ },+ status: ToolStatus::Completed,+ detail: ToolDetail::Macro {+ input: serde_json::json!({}),+ output: Some(serde_json::json!({"activity": []})),+ error: None,+ },+ };+ assert_eq!(segments(&[part], true)[0].rows[0].label, "Execute code");+}+#[test]fn an_unfinished_passage_is_the_one_open_segment() {let parts = [text("Looking into it")];diff --git a/crates/folds/agent_fold/src/domain/test/macro_tools.rs b/crates/folds/agent_fold/src/domain/test/macro_tools.rsindex bbb7d19bfc..068fa28e52 100644--- a/crates/folds/agent_fold/src/domain/test/macro_tools.rs+++ b/crates/folds/agent_fold/src/domain/test/macro_tools.rs@@ -13,6 +13,53 @@ use crate::testing::parse_log;use agent_client_protocol::schema::v1::ToolKind;use serde_json::{Value, json};+#[test]+fn code_activity_survives_native_and_mcp_json_output() {+ let receipt = json!({+ "executionId": "019a0000-0000-7000-8000-000000000001",+ "status": "succeeded",+ "activity": [{"id": 1, "label": "Search documents", "status": "completed"}]+ });+ for (namespace, output) in [+ ("macro", receipt.clone()),+ (+ "claudeCode",+ json!([{"type": "text", "text": receipt.to_string()}]),+ ),+ ] {+ let frames = [+ json!({"direction": "to_runtime", "content": {+ "type": "acp", "jsonrpc": "2.0", "id": "prompt-1", "method": "session/prompt",+ "params": {"sessionId": "s1", "prompt": [{"type": "text", "text": "Find documents"}]}+ }}),+ json!({"direction": "to_server", "content": {+ "type": "acp", "jsonrpc": "2.0", "method": "session/update",+ "params": {"sessionId": "s1", "update": {+ "sessionUpdate": "tool_call", "toolCallId": "code-1", "title": "Execute code",+ "kind": "execute", "status": "completed", "rawInput": {}, "rawOutput": output,+ "_meta": {(namespace): {"toolName": "mcp__macro_internal__ExecuteCode"}}+ }}+ }}),+ json!({"direction": "to_server", "content": {+ "type": "acp", "jsonrpc": "2.0", "id": "prompt-1", "result": {"stopReason": "end_turn"}+ }}),+ ];+ let recording = frames+ .iter()+ .map(Value::to_string)+ .collect::<Vec<_>>()+ .join("\n");+ let messages = fold(parse_log(&recording));+ let agent = messages+ .iter()+ .find(|message| message.author == crate::domain::model::Author::Agent)+ .unwrap();+ let segments = crate::domain::model::segments(&agent.parts, agent.stop.is_some());+ assert_eq!(segments[0].rows[0].label, "Search documents", "{namespace}");+ assert_eq!(segments[0].rows[0].id, "code-1:1");+ }+}+#[test]fn macro_mcp_calls_fold_to_macro_and_user_tool_details() {let messages = fold(parse_log(MACRO_MCP));diff --git a/docs/agent-guide/ai-chat.md b/docs/agent-guide/ai-chat.mdindex 34af6120b3..a0feba3427 100644--- a/docs/agent-guide/ai-chat.md+++ b/docs/agent-guide/ai-chat.md@@ -938,13 +938,18 @@ per harness process. Network hosts, process lifetime, output and memory arebounded; filesystem writes, arbitrary imports and subprocesses are denied.The token expires after issuance; process exit does not revoke it early.-The transcript shows **Run code** while execution is in flight. Expand it to-inspect the submitted source and final returned JSON or error. Code that creates-a saved review immediately emits a separate completed **PresentReview** ACP call.+Inline channel and discussion steps show the observed SDK operation names while+code runs, using the same execution journal as the full session view. The final+tool receipt carries those operations into the shared fold, so posted step+snapshots retain the names and outcomes without exposing source or returned JSON.+A code run without observed SDK requests keeps its generic execution step.+Unfinished requests are shown as interrupted, never as confirmed successes. Code+that creates a saved review immediately emits a separate completed **PresentReview**+ACP call.Its card can appear before the program finishes and stays editable afterwards.-Presentation means “Presented to the user,” not approved or sent. There is no-individual live progress stream or saved response journal for arbitrary SDK HTTP-calls. The execution journal retains source, status and final JSON/error;+Presentation means “Presented to the user,” not approved or sent. SDK operation+activity reports request outcomes, without storing request arguments or response+bodies. The execution journal retains source, status and final JSON/error;completed API writes are not rolled back after failure or cancellation.If a reused execution ID refers to different source, the card reports that toolresults are unavailable and does not display the other program's saved results.