Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

fix(agents): show Claude Code task reports as system rows, not prompts (#9065)

Wolf Mermelsteincce900051606
diff --git a/Cargo.lock b/Cargo.lock
index 26da356b26..c936336d59 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -393,10 +393,12 @@ dependencies = [
"agent_runtime_protocol",
"chrono",
"clap",
+ "html-escape",
"insta",
"lazy-regex",
"macro_user_id",
"macro_uuid",
+ "nom 8.0.0",
"non_empty",
"rootcause",
"serde",
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.md
index 9006103e1c..b6e784eb20 100644
--- a/apps/web/AGENTS.md
+++ b/apps/web/AGENTS.md
@@ -625,6 +625,8 @@ payloads exhaustively, summarize outcomes without draft content, and keep the
icon, truncated summary, timestamp, and optional subject action on one line on
desktop and mobile.
Keep Responding bound to the notification turn, including rejection and noop.
+Harness background-task reports are `task_notification` message parts, rendered
+as `ActionLine` rows in the agent reply (`TaskNotificationPart`).
The backend-free desktop/mobile check is
`bunx playwright test --config src/features/block-agent/browser-test/playwright.config.ts`.
The same suite covers stopping and reloading an agent reply inside a mention:
diff --git a/apps/web/src/features/block-agent/browser-test/main.tsx b/apps/web/src/features/block-agent/browser-test/main.tsx
index 6f53115046..44d34f9974 100644
--- a/apps/web/src/features/block-agent/browser-test/main.tsx
+++ b/apps/web/src/features/block-agent/browser-test/main.tsx
@@ -1,8 +1,12 @@
import { isTouchDevice } from '@core/mobile/isTouchDevice';
import { createSignal, For } from 'solid-js';
import '../../../index.css';
-import type { SessionNotification } from '@service-agent-fold/generated/types';
+import type {
+ FoldedMessage,
+ SessionNotification,
+} from '@service-agent-fold/generated/types';
import { render } from 'solid-js/web';
+import { Message } from '../component/AgentMessage';
import { SessionEventRow } from '../components/session-event-row';
import { PresentedReviewPart } from '../views/PresentedReviewPart';
import {
@@ -60,6 +64,47 @@ const events: SessionNotification[] = [
},
},
];
+// The turn a background task's report wakes the agent for, as the fold
+// gives it: reports first, then the reply.
+const taskReply: FoldedMessage = {
+ agentSessionId: session.sessionId(),
+ requestId: null,
+ pending: false,
+ postedAt: null,
+ segments: [],
+ phase: null,
+ turn: 2,
+ author: { kind: 'agent' },
+ stop: { kind: 'end_turn' },
+ parts: [
+ {
+ kind: 'task_notification',
+ status: 'completed',
+ summary:
+ 'Background command "Run affected tests in nix shell" completed (exit code 0)',
+ event: null,
+ },
+ {
+ kind: 'task_notification',
+ status: 'failed',
+ summary: 'Background command "cargo test" failed with exit code 101',
+ event: null,
+ },
+ {
+ kind: 'task_notification',
+ status: 'completed',
+ summary: 'Agent "Research document removal" finished',
+ event: null,
+ },
+ {
+ kind: 'task_notification',
+ status: null,
+ summary: 'Monitor event: "PR checks"',
+ event: 'check: fail',
+ },
+ { kind: 'text', text: 'The tests passed; one check is still failing.' },
+ ],
+};
const [openedReview, setOpenedReview] = createSignal('');
const root = document.getElementById('root');
if (!root) throw new Error('Fixture root missing');
@@ -81,6 +126,9 @@ render(
)}
</For>
</section>
+ <section aria-label="Task reports" class="min-w-0">
+ <Message message={taskReply} inFlight={false} />
+ </section>
<output aria-label="Opened review">{openedReview()}</output>
<div id={`review-${reviewId}`}>
<PresentedReviewPart
diff --git a/apps/web/src/features/block-agent/browser-test/notifications.browser.e2e.ts b/apps/web/src/features/block-agent/browser-test/notifications.browser.e2e.ts
index 5ad8b95b7d..cf5d57a906 100644
--- a/apps/web/src/features/block-agent/browser-test/notifications.browser.e2e.ts
+++ b/apps/web/src/features/block-agent/browser-test/notifications.browser.e2e.ts
@@ -77,3 +77,31 @@ test('typed event rows stay on one line and open their review subject', async ({
.getByRole('region', { name: 'Session events' })
.screenshot({ path: test.info().outputPath('session-event-rows.png') });
});
+
+test('background task reports read as one-line system rows, not prompts', async ({
+ page,
+}) => {
+ await page.goto('/');
+ const reports = page.getByRole('region', { name: 'Task reports' });
+ await expect(reports).toContainText('Run affected tests in nix shell');
+ await expect(reports).toContainText(
+ 'Monitor event: "PR checks" · check: fail'
+ );
+ await expect(reports).not.toContainText('<task-notification>');
+ await expect(reports.locator('.text-failure')).toHaveCount(1);
+ for (const label of await reports.locator('.truncate').all()) {
+ expect(
+ await label.evaluate(
+ (element) => element.getBoundingClientRect().height <= 20
+ )
+ ).toBe(true);
+ }
+ expect(
+ await page.evaluate(
+ () => document.documentElement.scrollWidth <= window.innerWidth
+ )
+ ).toBe(true);
+ await reports.screenshot({
+ path: test.info().outputPath('task-reports.png'),
+ });
+});
diff --git a/apps/web/src/features/block-agent/component/AgentMessage.tsx b/apps/web/src/features/block-agent/component/AgentMessage.tsx
index 2a1de23ffa..adef565c8b 100644
--- a/apps/web/src/features/block-agent/component/AgentMessage.tsx
+++ b/apps/web/src/features/block-agent/component/AgentMessage.tsx
@@ -50,6 +50,7 @@ import { ElicitationPart } from './parts/ElicitationPart';
import { PermissionPart } from './parts/PermissionPart';
import { PlanPart } from './parts/PlanPart';
import { type ToolUsePart, toolUsedAfter } from './parts/shared';
+import { TaskNotificationPart } from './parts/TaskNotificationPart';
import { TextPart } from './parts/TextPart';
import { ToolApprovalPart } from './parts/ToolApprovalPart';
import { ToolCallPart } from './parts/ToolCallPart';
@@ -136,6 +137,9 @@ function AgentMessagePart(props: {
<Match when={props.part.kind === 'control' && props.part}>
{(part) => <ControlPart part={part()} />}
</Match>
+ <Match when={props.part.kind === 'task_notification' && props.part}>
+ {(part) => <TaskNotificationPart part={part()} />}
+ </Match>
<Match when={props.part.kind === 'elicitation' && props.part}>
{(part) => <ElicitationPart part={part()} turn={props.message.turn} />}
</Match>
diff --git a/apps/web/src/features/block-agent/component/parts/TaskNotificationPart.test.tsx b/apps/web/src/features/block-agent/component/parts/TaskNotificationPart.test.tsx
new file mode 100644
index 0000000000..907dda8ee2
--- /dev/null
+++ b/apps/web/src/features/block-agent/component/parts/TaskNotificationPart.test.tsx
@@ -0,0 +1,72 @@
+/**
+ * @vitest-environment jsdom
+ */
+
+import type { MessagePart } from '@service-agent-fold/generated/types';
+import { render } from '@solidjs/testing-library';
+import { expect, it, vi } from 'vitest';
+import { TaskNotificationPart } from './TaskNotificationPart';
+
+// The `ui` barrel reaches the chat input's storage module on import (the
+// `ControlPart.test.tsx` idiom).
+vi.mock('../../ui', () => ({
+ ActionLine: (props: { label: string; failed?: boolean }) => (
+ <div data-testid="action-line" data-failed={String(props.failed ?? false)}>
+ {props.label}
+ </div>
+ ),
+}));
+
+type TaskNotification = Extract<MessagePart, { kind: 'task_notification' }>;
+
+it.each<[TaskNotification, string, string]>([
+ [
+ {
+ kind: 'task_notification',
+ status: 'completed',
+ summary: 'Background command "Run tests" completed (exit code 0)',
+ event: null,
+ },
+ 'Background command "Run tests" completed (exit code 0)',
+ 'false',
+ ],
+ [
+ {
+ kind: 'task_notification',
+ status: 'failed',
+ summary: 'Background command "Run tests" failed with exit code 1',
+ event: null,
+ },
+ 'Background command "Run tests" failed with exit code 1',
+ 'true',
+ ],
+ [
+ {
+ kind: 'task_notification',
+ status: 'completed',
+ summary: 'Agent "Research" finished',
+ event: null,
+ },
+ 'Agent "Research" finished',
+ 'false',
+ ],
+ [
+ {
+ kind: 'task_notification',
+ status: null,
+ summary: 'Monitor event: "PR checks"',
+ event: 'check: fail',
+ },
+ 'Monitor event: "PR checks" · check: fail',
+ 'false',
+ ],
+ [
+ { kind: 'task_notification', status: null, summary: '', event: null },
+ 'Background task update',
+ 'false',
+ ],
+])('reads %o as one system line', (part, label, failed) => {
+ const { getByTestId } = render(() => <TaskNotificationPart part={part} />);
+ expect(getByTestId('action-line').textContent).toBe(label);
+ expect(getByTestId('action-line').getAttribute('data-failed')).toBe(failed);
+});
diff --git a/apps/web/src/features/block-agent/component/parts/TaskNotificationPart.tsx b/apps/web/src/features/block-agent/component/parts/TaskNotificationPart.tsx
new file mode 100644
index 0000000000..2edaddc7a3
--- /dev/null
+++ b/apps/web/src/features/block-agent/component/parts/TaskNotificationPart.tsx
@@ -0,0 +1,31 @@
+/**
+ * The harness reporting on background work it started earlier: a command
+ * finishing, a subagent returning, a monitor streaming an event. The harness
+ * hands the agent this report as a user turn; here it reads as punctuation in
+ * the agent's reply, never as something a person said.
+ */
+
+import type { MessagePart } from '@service-agent-fold/generated/types';
+import { ActionLine } from '../../ui';
+
+type TaskNotificationPartData = Extract<
+ MessagePart,
+ { kind: 'task_notification' }
+>;
+
+/** The summary already names the task and its outcome; a monitor adds what it saw. */
+export function taskNotificationLabel(part: TaskNotificationPartData): string {
+ const summary = part.summary || 'Background task update';
+ return part.event ? `${summary} · ${part.event}` : summary;
+}
+
+export function TaskNotificationPart(props: {
+ part: TaskNotificationPartData;
+}) {
+ return (
+ <ActionLine
+ label={taskNotificationLabel(props.part)}
+ failed={props.part.status === 'failed'}
+ />
+ );
+}
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/presentation.ts b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/presentation.ts
index 4239dac17c..68742e8b58 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/presentation.ts
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/presentation.ts
@@ -274,6 +274,15 @@ function partActivity(part: MessagePart): MagicChipActivity {
label: 'Question answered',
busy: true,
}))
+ // The agent wakes to answer a background task's report.
+ .with({ kind: 'task_notification' }, (part) => ({
+ label:
+ part.status === 'failed'
+ ? 'Background task failed'
+ : 'Background task update',
+ detail: part.summary || undefined,
+ busy: true,
+ }))
.with({ kind: 'plan' }, ({ entries }) => {
const completed = entries.filter(
(entry) => entry.status === 'completed'
diff --git a/apps/web/src/lib/service-clients/service-agent-fold/generated/types.ts b/apps/web/src/lib/service-clients/service-agent-fold/generated/types.ts
index 93746c493d..a7ac38bdc7 100644
--- a/apps/web/src/lib/service-clients/service-agent-fold/generated/types.ts
+++ b/apps/web/src/lib/service-clients/service-agent-fold/generated/types.ts
@@ -935,6 +935,24 @@ export type MessagePart =
/** The tasks, in the order the agent listed them. */
entries: PlanEntry[];
}
+ /**
+ * A background task the harness reported on: a command, subagent or
+ * monitor it started earlier finished or emitted an event. The harness
+ * hands the agent this report as a user turn; it is shown as a system
+ * fact, never as something a person said.
+ */
+ | {
+ kind: 'task_notification';
+ /** Where the task ended up; absent for a monitor's mid-stream event. */
+ status: TaskStatus | null;
+ /**
+ * The harness's one-line account, such as `Background command
+ * "Run tests" completed (exit code 0)`.
+ */
+ summary: string;
+ /** The line a monitor streamed, for a monitor event. */
+ event: string | null;
+ }
/**
* The agent asking the user a question.
*
@@ -1589,6 +1607,15 @@ export type SubagentResult = {
stats: ToolStats | null;
};
+/** How a background task ended, per [`MessagePart::TaskNotification`]. */
+export type TaskStatus =
+ /** It ran to the end. */
+ | 'completed'
+ /** It ended with an error or a nonzero exit. */
+ | 'failed'
+ /** It was stopped, or did not survive the previous session. */
+ | 'stopped';
+
/** Where a held call stands. */
export type ToolApprovalStatus =
/** Held until the owner answers. */
diff --git a/crates/folds/agent_fold/AGENTS.md b/crates/folds/agent_fold/AGENTS.md
index cc373e2a98..480a139f23 100644
--- a/crates/folds/agent_fold/AGENTS.md
+++ b/crates/folds/agent_fold/AGENTS.md
@@ -66,6 +66,12 @@ keep deserialization compatible with existing flat rows. Exact `<noop/>` is buff
turns without tool activity; lifecycle still reports the turn ending. User turns
and tool-bearing turns preserve the literal text.
+Claude Code injects background-task reports (`<task-notification>`) as user
+turns. `claude_fold` copies the transcript's `origin` to
+`_meta.claudeCode.origin`; only that tag makes a user chunk a
+`TaskNotification` agent part in the open turn. Untagged text, even identical
+XML, stays a prompt.
+
Server-added invocation context is marked by the protocol’s block metadata.
Omit those blocks from user messages, including replay; preserve unmarked text
even when it contains agent-context tags.
diff --git a/crates/folds/agent_fold/Cargo.toml b/crates/folds/agent_fold/Cargo.toml
index f454d773ce..7658453ec7 100644
--- a/crates/folds/agent_fold/Cargo.toml
+++ b/crates/folds/agent_fold/Cargo.toml
@@ -44,9 +44,11 @@ agent-client-protocol = { workspace = true }
agent_runtime_protocol = { path = "../../agent_runtime_protocol", default-features = false }
chrono = { workspace = true }
clap = { workspace = true, optional = true }
+html-escape = { workspace = true }
lazy-regex = { workspace = true }
macro_user_id = { path = "../../macro_user_id" }
macro_uuid = { path = "../../macro_uuid" }
+nom = { workspace = true }
non_empty = { path = "../../non_empty" }
rootcause = { workspace = true }
serde = { workspace = true }
diff --git a/crates/folds/agent_fold/src/bin/fold_jsonl.rs b/crates/folds/agent_fold/src/bin/fold_jsonl.rs
index 3f65aa4dcb..c793fee024 100644
--- a/crates/folds/agent_fold/src/bin/fold_jsonl.rs
+++ b/crates/folds/agent_fold/src/bin/fold_jsonl.rs
@@ -287,6 +287,21 @@ fn render_part(part: &MessagePart) -> String {
.unwrap_or_default()
);
}
+ MessagePart::TaskNotification {
+ status,
+ summary,
+ event,
+ } => {
+ let _ = writeln!(
+ out,
+ "[task {}] {summary}{}",
+ status.map_or("event", |status| status.into()),
+ event
+ .as_deref()
+ .map(|event| format!(": {event}"))
+ .unwrap_or_default()
+ );
+ }
MessagePart::Control { control, outcome } => {
let label = match control {
Control::SetModel { model } => format!("model changed to {model}"),
diff --git a/crates/folds/agent_fold/src/domain/fold/state.rs b/crates/folds/agent_fold/src/domain/fold/state.rs
index cb10b74923..afd362b5e4 100644
--- a/crates/folds/agent_fold/src/domain/fold/state.rs
+++ b/crates/folds/agent_fold/src/domain/fold/state.rs
@@ -3,7 +3,7 @@
use std::collections::{HashMap, HashSet};
use crate::domain::error::FoldError;
-use crate::domain::harness::{HarnessReader, ToolFrame};
+use crate::domain::harness::{HarnessReader, ToolFrame, claude_code};
use agent_client_protocol::schema::v1::SessionId;
use crate::domain::log::{AgentSessionId, AgentSessionLog, Message};
@@ -476,6 +476,18 @@ impl FoldState {
SessionUpdate::AgentThoughtChunk(chunk) => StepChange::message(
content_block_text(chunk.content).and_then(|text| self.append_thought(text)),
),
+ // The harness reporting on its own background work. Shown in the
+ // agent's reply, in whatever turn is open, never as a prompt.
+ SessionUpdate::UserMessageChunk(chunk)
+ if claude_code::is_task_notification(chunk.meta.as_ref()) =>
+ {
+ let text = content_block_text(chunk.content).unwrap_or_default();
+ claude_code::task_notifications(&text)
+ .into_iter()
+ .filter_map(|part| self.push_agent_part(part))
+ .flat_map(|(changed, _)| StepChange::message(Some(changed)))
+ .collect()
+ }
// Replay has no original prompt requests: user chunks are its
// authoritative prompts. Outside load, ignore prompt echoes.
SessionUpdate::UserMessageChunk(chunk)
diff --git a/crates/folds/agent_fold/src/domain/harness/claude_code.rs b/crates/folds/agent_fold/src/domain/harness/claude_code.rs
index eca605068a..d5b43166be 100644
--- a/crates/folds/agent_fold/src/domain/harness/claude_code.rs
+++ b/crates/folds/agent_fold/src/domain/harness/claude_code.rs
@@ -21,11 +21,16 @@
use agent_client_protocol::schema::v1::{ContentBlock, Meta};
use lazy_regex::regex_is_match;
+use nom::bytes::complete::{tag, take_until, take_while1};
+use nom::character::complete::{char, multispace0};
+use nom::multi::many0;
+use nom::sequence::{delimited, preceded};
+use nom::{IResult, Parser};
use serde::Deserialize;
use serde_json::Value;
use super::{HarnessReader, ToolFrame, generic, has_namespace, namespaced, raw};
-use crate::domain::model::{SubagentResult, ToolName, ToolStats, ToolUseId};
+use crate::domain::model::{MessagePart, SubagentResult, ToolName, ToolStats, ToolUseId};
/// The `_meta` namespace Claude Code writes under.
pub const NAMESPACE: &str = "claudeCode";
@@ -45,6 +50,7 @@ struct ClaudeCodeMeta {
subagent: bool,
parent_tool_use_id: Option<String>,
tool_response: Option<Value>,
+ origin: Option<String>,
}
fn meta_of(meta: Option<&Meta>) -> ClaudeCodeMeta {
@@ -197,3 +203,75 @@ impl HarnessReader for ClaudeCode {
pub fn tool_name(meta: Option<&Meta>) -> Option<String> {
meta_of(meta).tool_name
}
+
+/// Whether a user chunk is a task report the CLI itself injected. Only the
+/// `_meta.claudeCode.origin` tag `claude_fold` copies from the transcript
+/// marks one, never its text: a person can type the same XML.
+#[must_use]
+pub fn is_task_notification(meta: Option<&Meta>) -> bool {
+ meta_of(meta).origin.as_deref() == Some("task-notification")
+}
+
+/// The reports in a [`is_task_notification`] chunk, one part per
+/// `<task-notification>` block, and never none.
+#[must_use]
+pub fn task_notifications(text: &str) -> Vec<MessagePart> {
+ let blocks = many0(preceded(
+ take_until(TASK_NOTIFICATION_OPEN),
+ task_notification,
+ ))
+ .parse(text)
+ .map(|(_, blocks)| blocks)
+ .unwrap_or_default();
+ // Tagged but unparseable is still the CLI's: show that it reported.
+ if blocks.is_empty() {
+ return vec![MessagePart::TaskNotification {
+ status: None,
+ summary: String::new(),
+ event: None,
+ }];
+ }
+ blocks
+ .into_iter()
+ .map(|fields| {
+ let field = |name: &str| {
+ fields
+ .iter()
+ .find(|(field, _)| *field == name)
+ .map(|(_, value)| html_escape::decode_html_entities(value.trim()).into_owned())
+ };
+ MessagePart::TaskNotification {
+ status: field("status").and_then(|status| status.parse().ok()),
+ summary: field("summary").unwrap_or_default(),
+ event: field("event"),
+ }
+ })
+ .collect()
+}
+
+const TASK_NOTIFICATION_OPEN: &str = "<task-notification>";
+
+/// One `<task-notification>` block, as its `<name>value</name>` fields.
+fn task_notification(input: &str) -> IResult<&str, Vec<(&str, &str)>> {
+ delimited(
+ tag(TASK_NOTIFICATION_OPEN),
+ many0(preceded(multispace0, field)),
+ (multispace0, tag("</task-notification>")),
+ )
+ .parse(input)
+}
+
+/// `<name>value</name>`, the value raw: a subagent's `<result>` is prose
+/// that may hold markup of its own.
+fn field(input: &str) -> IResult<&str, (&str, &str)> {
+ let (input, name) = delimited(
+ char('<'),
+ take_while1(|c: char| c.is_ascii_alphanumeric() || c == '-'),
+ char('>'),
+ )
+ .parse(input)?;
+ let close = format!("</{name}>");
+ let (input, value) = take_until(close.as_str()).parse(input)?;
+ let (input, _) = tag(close.as_str()).parse(input)?;
+ Ok((input, (name, value)))
+}
diff --git a/crates/folds/agent_fold/src/domain/model.rs b/crates/folds/agent_fold/src/domain/model.rs
index 1a70607ed6..70feb84fb0 100644
--- a/crates/folds/agent_fold/src/domain/model.rs
+++ b/crates/folds/agent_fold/src/domain/model.rs
@@ -57,7 +57,7 @@ pub use interaction::{PendingInteraction, PendingPermission, PendingToolApproval
pub use metadata::{
AvailableCommand, Harness, ModelOption, SessionMetadata, SessionNotification, TurnState,
};
-pub use part::{Control, ControlOutcome, MessagePart, StopReason};
+pub use part::{Control, ControlOutcome, MessagePart, StopReason, TaskStatus};
pub use permission::{PermissionOption, PermissionOptionKind, PermissionOutcome};
pub use plan::{PlanEntry, PlanEntryPriority, PlanEntryStatus};
pub use segment::{
diff --git a/crates/folds/agent_fold/src/domain/model/part.rs b/crates/folds/agent_fold/src/domain/model/part.rs
index 0732b70afd..e4d9a5b397 100644
--- a/crates/folds/agent_fold/src/domain/model/part.rs
+++ b/crates/folds/agent_fold/src/domain/model/part.rs
@@ -115,6 +115,19 @@ pub enum MessagePart {
/// The tasks, in the order the agent listed them.
entries: Vec<PlanEntry>,
},
+ /// A background task the harness reported on: a command, subagent or
+ /// monitor it started earlier finished or emitted an event. The harness
+ /// hands the agent this report as a user turn; it is shown as a system
+ /// fact, never as something a person said.
+ TaskNotification {
+ /// Where the task ended up; absent for a monitor's mid-stream event.
+ status: Option<TaskStatus>,
+ /// The harness's one-line account, such as `Background command
+ /// "Run tests" completed (exit code 0)`.
+ summary: String,
+ /// The line a monitor streamed, for a monitor event.
+ event: Option<String>,
+ },
/// The agent asking the user a question.
///
/// When the question was asked on behalf of a tool call this fold had
@@ -181,6 +194,21 @@ impl MessagePart {
}
}
+/// How a background task ended, per [`MessagePart::TaskNotification`].
+#[derive(
+ Debug, Clone, Copy, PartialEq, Eq, Serialize, Type, strum::EnumString, strum::IntoStaticStr,
+)]
+#[serde(rename_all = "snake_case")]
+#[strum(serialize_all = "snake_case")]
+pub enum TaskStatus {
+ /// It ran to the end.
+ Completed,
+ /// It ended with an error or a nonzero exit.
+ Failed,
+ /// It was stopped, or did not survive the previous session.
+ Stopped,
+}
+
/// A session control operation shown in the conversation timeline.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Type)]
#[serde(tag = "kind", rename_all = "snake_case")]
diff --git a/crates/folds/agent_fold/src/domain/model/search.rs b/crates/folds/agent_fold/src/domain/model/search.rs
index 037398a046..fe575b74d0 100644
--- a/crates/folds/agent_fold/src/domain/model/search.rs
+++ b/crates/folds/agent_fold/src/domain/model/search.rs
@@ -107,6 +107,12 @@ impl SearchText {
self.push(&entry.content);
}
}
+ MessagePart::TaskNotification { summary, event, .. } => {
+ self.push(summary);
+ if let Some(event) = event {
+ self.push(event);
+ }
+ }
MessagePart::Elicitation {
message,
request,
diff --git a/crates/folds/agent_fold/src/domain/model/segment.rs b/crates/folds/agent_fold/src/domain/model/segment.rs
index 1b369adb0e..76a2557644 100644
--- a/crates/folds/agent_fold/src/domain/model/segment.rs
+++ b/crates/folds/agent_fold/src/domain/model/segment.rs
@@ -244,7 +244,8 @@ fn part_kind(part: &MessagePart) -> Option<SegmentKind> {
| MessagePart::ToolApproval { .. } => Some(SegmentKind::Interaction),
MessagePart::Thought { .. }
| MessagePart::Attachment { .. }
- | MessagePart::Control { .. } => None,
+ | MessagePart::Control { .. }
+ | MessagePart::TaskNotification { .. } => None,
}
}
diff --git a/crates/folds/agent_fold/src/domain/test.rs b/crates/folds/agent_fold/src/domain/test.rs
index fab5c0801f..73f0d0df2b 100644
--- a/crates/folds/agent_fold/src/domain/test.rs
+++ b/crates/folds/agent_fold/src/domain/test.rs
@@ -19,3 +19,5 @@ mod util;
mod replay;
mod notifications;
+
+mod task_notifications;
diff --git a/crates/folds/agent_fold/src/domain/test/task_notifications.rs b/crates/folds/agent_fold/src/domain/test/task_notifications.rs
new file mode 100644
index 0000000000..989cd541a6
--- /dev/null
+++ b/crates/folds/agent_fold/src/domain/test/task_notifications.rs
@@ -0,0 +1,102 @@
+use super::util::parse_log;
+use crate::domain::fold::fold;
+use crate::domain::model::{Author, AuthorKind, MessagePart, StopReason, TaskStatus};
+
+#[test]
+fn cli_task_reports_join_the_agent_reply_and_typed_xml_stays_a_prompt() {
+ let messages = fold(parse_log(
+ r#"
+{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"s","update":{"sessionUpdate":"user_message_chunk","content":{"type":"text","text":"Run the tests in the background."}}}}}
+{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"s","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"Waiting for the test run to finish."}}}}}
+{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"_session/turn_complete","params":{"sessionId":"s","outcome":{"kind":"finished"}}}}
+{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"s","update":{"sessionUpdate":"user_message_chunk","content":{"type":"text","text":"<task-notification>\n<task-id>bf1lef9e9</task-id>\n<tool-use-id>toolu_01</tool-use-id>\n<output-file>/tmp/tasks/bf1lef9e9.output</output-file>\n<status>completed</status>\n<summary>Background command \"cargo test &gt; out.log\" completed (exit code 0)</summary>\n</task-notification>\n<task-notification>\n<task-id>b88i97ihr</task-id>\n<summary>Monitor event: \"PR checks\"</summary>\n<event>check: fail</event>\n</task-notification>\n<task-notification>\n<task-id>a05</task-id>\n<status>completed</status>\n<summary>Agent \"Research\" finished</summary>\n<result>Found <b>two</b> callers.</result>\n</task-notification>"},"_meta":{"claudeCode":{"origin":"task-notification"}}}}}}
+{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"s","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"The tests passed."}}}}}
+{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"_session/turn_complete","params":{"sessionId":"s","outcome":{"kind":"finished"}}}}
+{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"s","update":{"sessionUpdate":"user_message_chunk","content":{"type":"text","text":"<task-notification><status>failed</status></task-notification>"}}}}}
+"#,
+ ));
+
+ let parts: Vec<_> = messages
+ .iter()
+ .map(|message| {
+ (
+ message.author.kind(),
+ message.parts.to_vec(),
+ message.stop.clone(),
+ )
+ })
+ .collect();
+ assert_eq!(
+ parts,
+ [
+ (
+ AuthorKind::User,
+ vec![MessagePart::Text {
+ text: "Run the tests in the background.".to_owned(),
+ }],
+ None,
+ ),
+ (
+ AuthorKind::Agent,
+ vec![MessagePart::Text {
+ text: "Waiting for the test run to finish.".to_owned(),
+ }],
+ Some(StopReason::EndTurn),
+ ),
+ (
+ AuthorKind::Agent,
+ vec![
+ MessagePart::TaskNotification {
+ status: Some(TaskStatus::Completed),
+ summary:
+ "Background command \"cargo test > out.log\" completed (exit code 0)"
+ .to_owned(),
+ event: None,
+ },
+ MessagePart::TaskNotification {
+ status: None,
+ summary: "Monitor event: \"PR checks\"".to_owned(),
+ event: Some("check: fail".to_owned()),
+ },
+ MessagePart::TaskNotification {
+ status: Some(TaskStatus::Completed),
+ summary: "Agent \"Research\" finished".to_owned(),
+ event: None,
+ },
+ MessagePart::Text {
+ text: "The tests passed.".to_owned(),
+ },
+ ],
+ Some(StopReason::EndTurn),
+ ),
+ // Untagged, the same XML is something a person typed.
+ (
+ AuthorKind::User,
+ vec![MessagePart::Text {
+ text: "<task-notification><status>failed</status></task-notification>"
+ .to_owned(),
+ }],
+ None,
+ ),
+ ]
+ );
+}
+
+#[test]
+fn a_tagged_report_that_does_not_parse_still_never_reads_as_a_prompt() {
+ let messages = fold(parse_log(
+ r#"
+{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"s","update":{"sessionUpdate":"user_message_chunk","content":{"type":"text","text":"<task-notification><status>completed"},"_meta":{"claudeCode":{"origin":"task-notification"}}}}}}
+"#,
+ ));
+ assert_eq!(messages.len(), 1);
+ assert_eq!(messages[0].author, Author::Agent);
+ assert_eq!(
+ messages[0].parts.to_vec(),
+ [MessagePart::TaskNotification {
+ status: None,
+ summary: String::new(),
+ event: None,
+ }]
+ );
+}
diff --git a/crates/folds/claude_fold/fixtures/conversation.jsonl b/crates/folds/claude_fold/fixtures/conversation.jsonl
index c83a700492..f47cac19d9 100644
--- a/crates/folds/claude_fold/fixtures/conversation.jsonl
+++ b/crates/folds/claude_fold/fixtures/conversation.jsonl
@@ -7,3 +7,5 @@
{"type":"assistant","uuid":"a3","isSidechain":true,"message":{"content":[{"type":"text","text":"Hidden child."}],"stop_reason":"end_turn"}}
{"type":"assistant","uuid":"a4","message":{"content":[{"type":"text","text":"You are welcome."}],"stop_reason":"max_tokens"}}
{"type":"future_record","uuid":"f1"}
+{"type":"user","uuid":"n1","origin":{"kind":"task-notification"},"message":{"role":"user","content":"<task-notification>\n<task-id>b1</task-id>\n<tool-use-id>t9</tool-use-id>\n<output-file>/tmp/tasks/b1.output</output-file>\n<status>failed</status>\n<summary>Background command \"Run tests\" failed with exit code 1</summary>\n</task-notification>"}}
+{"type":"assistant","uuid":"a5","message":{"content":[{"type":"text","text":"The tests failed."}],"stop_reason":"end_turn"}}
diff --git a/crates/folds/claude_fold/src/lib.rs b/crates/folds/claude_fold/src/lib.rs
index a978398963..a9d747610f 100644
--- a/crates/folds/claude_fold/src/lib.rs
+++ b/crates/folds/claude_fold/src/lib.rs
@@ -43,7 +43,7 @@ impl Fold for ClaudeLog {
};
match entry.get("type").and_then(Value::as_str) {
Some("assistant") => assistant(message),
- Some("user") => user_message(message),
+ Some("user") => user_message(message, origin(&entry)),
_ => Vec::new(),
}
}
@@ -105,7 +105,14 @@ fn assistant(message: &Value) -> Vec<LogEvent> {
events
}
-fn user_message(message: &Value) -> Vec<LogEvent> {
+/// Who the CLI says wrote a user line. Claude Code injects its own events
+/// (`task-notification` when a background task settles) as user turns; the
+/// fold reads this tag, never the text, to tell them from a person's prompt.
+fn origin(entry: &Value) -> Option<&str> {
+ entry.pointer("/origin/kind").and_then(Value::as_str)
+}
+
+fn user_message(message: &Value, origin: Option<&str>) -> Vec<LogEvent> {
let mut events = tool_results(message);
let text = match message.get("content") {
Some(Value::String(text)) => text.clone(),
@@ -116,10 +123,14 @@ fn user_message(message: &Value) -> Vec<LogEvent> {
.join("\n"),
};
if !text.is_empty() {
- events.push(LogEvent::Update(json!({
+ let mut update = json!({
"sessionUpdate": "user_message_chunk",
"content": {"type": "text", "text": text},
- })));
+ });
+ if let Some(origin) = origin {
+ update["_meta"] = json!({"claudeCode": {"origin": origin}});
+ }
+ events.push(LogEvent::Update(update));
}
events
}
diff --git a/crates/folds/claude_fold/src/snapshots/claude_fold__test__api_messages_snapshot.snap b/crates/folds/claude_fold/src/snapshots/claude_fold__test__api_messages_snapshot.snap
index 79be544e50..3d5182aff9 100644
--- a/crates/folds/claude_fold/src/snapshots/claude_fold__test__api_messages_snapshot.snap
+++ b/crates/folds/claude_fold/src/snapshots/claude_fold__test__api_messages_snapshot.snap
@@ -89,5 +89,29 @@ expression: messages
},
"pending": false,
"postedAt": null
+ },
+ {
+ "turn": 2,
+ "author": {
+ "kind": "agent"
+ },
+ "requestId": null,
+ "parts": [
+ {
+ "kind": "task_notification",
+ "status": "failed",
+ "summary": "Background command \"Run tests\" failed with exit code 1",
+ "event": null
+ },
+ {
+ "kind": "text",
+ "text": "The tests failed."
+ }
+ ],
+ "stop": {
+ "kind": "end_turn"
+ },
+ "pending": false,
+ "postedAt": null
}
]
diff --git a/crates/folds/claude_fold/src/snapshots/claude_fold__test__conversation_snapshot.snap b/crates/folds/claude_fold/src/snapshots/claude_fold__test__conversation_snapshot.snap
index e88e0f0843..4f23445e68 100644
--- a/crates/folds/claude_fold/src/snapshots/claude_fold__test__conversation_snapshot.snap
+++ b/crates/folds/claude_fold/src/snapshots/claude_fold__test__conversation_snapshot.snap
@@ -86,5 +86,31 @@ expression: events
},
{
"TurnEnded": "max_tokens"
+ },
+ {
+ "Update": {
+ "sessionUpdate": "user_message_chunk",
+ "content": {
+ "type": "text",
+ "text": "<task-notification>\n<task-id>b1</task-id>\n<tool-use-id>t9</tool-use-id>\n<output-file>/tmp/tasks/b1.output</output-file>\n<status>failed</status>\n<summary>Background command \"Run tests\" failed with exit code 1</summary>\n</task-notification>"
+ },
+ "_meta": {
+ "claudeCode": {
+ "origin": "task-notification"
+ }
+ }
+ }
+ },
+ {
+ "Update": {
+ "sessionUpdate": "agent_message_chunk",
+ "content": {
+ "type": "text",
+ "text": "The tests failed."
+ }
+ }
+ },
+ {
+ "TurnEnded": "end_turn"
}
]
diff --git a/crates/folds/claude_fold/src/test.rs b/crates/folds/claude_fold/src/test.rs
index 780890a553..405fe25ddf 100644
--- a/crates/folds/claude_fold/src/test.rs
+++ b/crates/folds/claude_fold/src/test.rs
@@ -172,3 +172,21 @@ fn model_changes_snapshot() {
.collect();
insta::assert_json_snapshot!(events);
}
+
+#[test]
+fn cli_injected_user_lines_carry_their_origin() {
+ let mut log = ClaudeLog::default();
+ let text = "<task-notification>\n<task-id>bf1lef9e9</task-id>\n<status>completed</status>\n<summary>Background command \"Run tests\" completed (exit code 0)</summary>\n</task-notification>";
+ let notification = line(json!({
+ "type": "user", "uuid": "n1", "origin": {"kind": "task-notification"},
+ "message": {"role": "user", "content": text}
+ }));
+ assert_eq!(
+ log.entry(&notification),
+ [LogEvent::Update(json!({
+ "sessionUpdate": "user_message_chunk",
+ "content": {"type": "text", "text": text},
+ "_meta": {"claudeCode": {"origin": "task-notification"}},
+ }))]
+ );
+}
diff --git a/docs/agent-guide/ai-chat.md b/docs/agent-guide/ai-chat.md
index 225f63cfcd..55c55579f4 100644
--- a/docs/agent-guide/ai-chat.md
+++ b/docs/agent-guide/ai-chat.md
@@ -633,6 +633,11 @@ the shimmer.
changes the model of an idle native session after native confirmation and
displays the model identified by the session (Codex's live footer, or native
transcript metadata). Unexpected native dialogs must be completed in Herdr.
+ When a background command, subagent, or monitor that Claude Code started
+ reports back, the reply opens with a quiet one-line row per report, such as
+ `Background command "Run tests" completed (exit code 0)`, red when it failed,
+ never a prompt bubble of `<task-notification>` XML. Claude still receives the
+ full report.
For Codex, open the current model's submenu to select **Reasoning effort**.
Choices come from the installed Codex catalog; the selected effort is confirmed
from the native session and shown beside the model. Local Herdr changes and
diff --git a/packages/sdk/generated/agent-fold/index.ts b/packages/sdk/generated/agent-fold/index.ts
index 4fcbe4bdf2..7769210ea9 100644
--- a/packages/sdk/generated/agent-fold/index.ts
+++ b/packages/sdk/generated/agent-fold/index.ts
@@ -853,6 +853,22 @@ outcome: ControlOutcome } |
{ kind: "plan";
/** The tasks, in the order the agent listed them. */
entries: PlanEntry[] } |
+/**
+ * A background task the harness reported on: a command, subagent or
+ * monitor it started earlier finished or emitted an event. The harness
+ * hands the agent this report as a user turn; it is shown as a system
+ * fact, never as something a person said.
+ */
+{ kind: "task_notification";
+/** Where the task ended up; absent for a monitor's mid-stream event. */
+status: TaskStatus | null;
+/**
+ * The harness's one-line account, such as `Background command
+ * "Run tests" completed (exit code 0)`.
+ */
+summary: string;
+/** The line a monitor streamed, for a monitor event. */
+event: string | null } |
/**
* The agent asking the user a question.
*
@@ -1477,6 +1493,15 @@ export type SubagentResult = {
stats: ToolStats | null,
};
+/** How a background task ended, per [`MessagePart::TaskNotification`]. */
+export type TaskStatus =
+/** It ran to the end. */
+"completed" |
+/** It ended with an error or a nonzero exit. */
+"failed" |
+/** It was stopped, or did not survive the previous session. */
+"stopped";
+
/** Where a held call stands. */
export type ToolApprovalStatus =
/** Held until the owner answers. */