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
feat(agents): show where and when each prompt came from (#8112)
Wolf Mermelstein209106b429c6
diff --git a/apps/web/src/features/agent-activity/agent-activity.test.tsx b/apps/web/src/features/agent-activity/agent-activity.test.tsxindex 63393ced9d..fbd03efcbf 100644--- a/apps/web/src/features/agent-activity/agent-activity.test.tsx+++ b/apps/web/src/features/agent-activity/agent-activity.test.tsx@@ -45,6 +45,7 @@ function reply(rows: ActivityRow[]): FoldedMessage {{ index: 1, kind: 'activity', start: 1, end: 3, sealed: false, rows },],phase: 'working',+ postedAt: null,};}diff --git a/apps/web/src/features/agent-activity/agent-typing.test.tsx b/apps/web/src/features/agent-activity/agent-typing.test.tsxindex aaa1b5664c..df013b4c06 100644--- a/apps/web/src/features/agent-activity/agent-typing.test.tsx+++ b/apps/web/src/features/agent-activity/agent-typing.test.tsx@@ -123,6 +123,7 @@ function writing(text: string): FoldedMessage {{ index: 0, kind: 'prose', start: 0, end: 1, sealed: false, rows: [] },],phase: 'writing',+ postedAt: null,};}diff --git a/apps/web/src/features/agent-activity/core/live-reply.test.ts b/apps/web/src/features/agent-activity/core/live-reply.test.tsindex 7fc970df0a..01f85f31d4 100644--- a/apps/web/src/features/agent-activity/core/live-reply.test.ts+++ b/apps/web/src/features/agent-activity/core/live-reply.test.ts@@ -28,6 +28,7 @@ function reply(pending: false,segments,phase: closed ? null : 'writing',+ postedAt: null,};}diff --git a/apps/web/src/features/agent-activity/queries/live-session.test.tsx b/apps/web/src/features/agent-activity/queries/live-session.test.tsxindex f43cffcf81..d19bbe6c3c 100644--- a/apps/web/src/features/agent-activity/queries/live-session.test.tsx+++ b/apps/web/src/features/agent-activity/queries/live-session.test.tsx@@ -43,6 +43,7 @@ function message(text: string): FoldedMessage {pending: false,segments: [],phase: 'writing',+ postedAt: null,};}diff --git a/apps/web/src/features/block-agent/agent-session-provider.tsx b/apps/web/src/features/block-agent/agent-session-provider.tsxindex 1bd5e1742b..79ce850e7e 100644--- a/apps/web/src/features/block-agent/agent-session-provider.tsx+++ b/apps/web/src/features/block-agent/agent-session-provider.tsx@@ -83,6 +83,7 @@ export function AgentSessionProvider(pending: true,segments: [],phase: null,+ postedAt: null,},];};diff --git a/apps/web/src/features/block-agent/component/AgentMessage.test.tsx b/apps/web/src/features/block-agent/component/AgentMessage.test.tsxindex fda6459e5c..757ca43159 100644--- a/apps/web/src/features/block-agent/component/AgentMessage.test.tsx+++ b/apps/web/src/features/block-agent/component/AgentMessage.test.tsx@@ -23,6 +23,13 @@ vi.mock('../context/AgentSessionContext', () => ({// The layer under test is how a message lays its parts out — which calls fold// into a group and at what index — so every part renderer and ui primitive// is a marker. The per-part components have their own tests.+const openedOrigins = vi.hoisted(() => [] as unknown[]);+vi.mock('../open-prompt-origin', () => ({+ useOpenPromptOrigin: () => (destination: unknown) => {+ openedOrigins.push(destination);+ },+}));+vi.mock('@core/util/message-send-motion', () => ({messageSendMotion: () => {},}));@@ -162,6 +169,7 @@ const message = (agentSessionId: 'session',requestId: null,pending: false,+ postedAt: null,segments: [],phase: null,turn: 0,@@ -787,3 +795,69 @@ describe('Message failed turns', () => {expect(view.queryByTestId('action-line')).toBeNull();});});++describe('Message prompt footer', () => {+ const context = (xml: string) =>+ `<m-agent-context>${JSON.stringify({ version: 1, text: xml }).replace(/</g, '\\u003c')}</m-agent-context>\nWork on the assigned task.`;++ it('says under the prompt what started it, and goes there on click', () => {+ openedOrigins.length = 0;+ const view = render(() => (+ <Message+ message={{+ ...message([+ text(+ context(+ '<trigger kind="task_assigned" discussion="d1"><assigned by="Julia" by_id="macro|[email protected]"/><task id="task-1" title="Fix calendar popover scroll" status="Todo"/></trigger>'+ )+ ),+ ]),+ author: { kind: 'user', userId: 'macro|[email protected]' },+ }}+ inFlight={false}+ />+ ));++ const line = view.getByRole('button', {+ name: 'via task Fix calendar popover scroll from Julia',+ });+ line.click();+ expect(openedOrigins).toEqual([{ kind: 'task', taskId: 'task-1' }]);+ });++ it('shows only when a prompt typed in the session was posted', () => {+ const view = render(() => (+ <Message+ message={{+ ...message([+ text(+ context('<session owner="Me" owner_id="macro|[email protected]"/>')+ ),+ ]),+ author: { kind: 'user', userId: 'macro|[email protected]' },+ postedAt: '2026-10-15T14:02:00+00:00',+ }}+ inFlight={false}+ />+ ));+ const footer = view.getByTestId('prompt-footer');+ expect(footer.querySelector('button')).toBeNull();+ expect(footer.querySelector('time')?.dateTime).toBe(+ '2026-10-15T14:02:00+00:00'+ );+ });++ it('adds nothing under a prompt the log has not confirmed', () => {+ const view = render(() => (+ <Message+ message={{+ ...message([text('Do the thing.')]),+ author: { kind: 'user', userId: 'macro|[email protected]' },+ pending: true,+ }}+ inFlight={false}+ />+ ));+ expect(view.queryByTestId('prompt-footer')).toBeNull();+ });+});diff --git a/apps/web/src/features/block-agent/component/AgentMessage.tsx b/apps/web/src/features/block-agent/component/AgentMessage.tsxindex 10dc6b5a07..91a07faa5b 100644--- a/apps/web/src/features/block-agent/component/AgentMessage.tsx+++ b/apps/web/src/features/block-agent/component/AgentMessage.tsx@@ -18,11 +18,21 @@ import type {MessagePart,} from '@service-agent-fold/generated/types';import { UserMessageBubble } from '@ui';-import { For, Index, type JSX, Match, Show, Switch } from 'solid-js';+import {+ createMemo,+ For,+ Index,+ type JSX,+ Match,+ Show,+ Switch,+} from 'solid-js';import { match } from 'ts-pattern';import { useOptionalAgentSession } from '../context/AgentSessionContext';+import { useOpenPromptOrigin } from '../open-prompt-origin';import { isControlMessage } from '../state/control-message';import { isNotificationMessage } from '../state/notification-message';+import { agentContextText, promptOrigin } from '../state/prompt-origin';import { thoughtIsStreaming } from '../state/thought-streaming';import { segmentParts } from '../state/tool-groups';import {@@ -33,6 +43,7 @@ import {WorkingLine,} from '../ui';import { LiveToolGroup } from '../views/LiveToolGroup';+import { PromptFooter } from './PromptFooter';import { AttachmentPart } from './parts/AttachmentPart';import { ControlPart } from './parts/ControlPart';import { ElicitationPart } from './parts/ElicitationPart';@@ -247,34 +258,24 @@ function promptAuthorName(: idToDisplayName(author.userId);}-const AGENT_CONTEXT_OPEN = '<m-agent-context>';-const PENDING_AGENT_CONTEXT = `${AGENT_CONTEXT_OPEN}{"version":1,"text":""}</m-agent-context>\n\n`;-/*** A prompt, in the chat block's user-bubble treatment* (`@core/component/AI/component/message/UserMessage.tsx`): right-aligned,* rounded, filled surface shared with production chat. A prompt another- * participant sent carries their name above the bubble.+ * participant sent carries their name above the bubble; under it, when it was+ * posted and, when the harness delivered it from elsewhere, where from.*/function UserMessage(props: { message: FoldedMessage }) {const userId = useUserId();const authorName = () => promptAuthorName(props.message.author, userId());- // The harness puts context before every prompt it delivers. Until the log- // confirms this one, an empty stand-in renders where it will, through the- // same markdown, so nothing moves when the real one arrives.- const parts = () => {- const parts = props.message.parts;- if (!props.message.pending) return parts;- const first = parts.findIndex((part) => part.kind === 'text');- const part = parts[first];- if (part?.kind !== 'text' || part.text.startsWith(AGENT_CONTEXT_OPEN))- return parts;- return parts.map((each, index) =>- index === first- ? { ...part, text: PENDING_AGENT_CONTEXT + part.text }- : each- );- };+ const openOrigin = useOpenPromptOrigin();+ // Memoized: reading the origin parses the context's XML.+ const origin = createMemo(() => {+ const first = props.message.parts.find((part) => part.kind === 'text');+ const context =+ first?.kind === 'text' ? agentContextText(first.text) : undefined;+ return context === undefined ? undefined : promptOrigin(context);+ });return (<div@@ -298,7 +299,7 @@ function UserMessage(props: { message: FoldedMessage }) {)}</Show><UserMessageBubble>- <For each={parts()}>+ <For each={props.message.parts}>{(part, index) => (<AgentMessagePartpart={part}@@ -309,6 +310,20 @@ function UserMessage(props: { message: FoldedMessage }) {)}</For></UserMessageBubble>+ <Show when={origin() || props.message.postedAt}>+ <PromptFooter+ origin={origin()}+ postedAt={props.message.postedAt ?? undefined}+ onOpen={+ origin()?.destination+ ? () => {+ const destination = origin()?.destination;+ if (destination) openOrigin(destination);+ }+ : undefined+ }+ />+ </Show></div>);}diff --git a/apps/web/src/features/block-agent/component/PromptFooter.tsx b/apps/web/src/features/block-agent/component/PromptFooter.tsxnew file mode 100644index 0000000000..144073abc2--- /dev/null+++ b/apps/web/src/features/block-agent/component/PromptFooter.tsx@@ -0,0 +1,77 @@+import { formatDate } from '@core/util/date';+import { Show } from 'solid-js';+import type { PromptOrigin } from '../state/prompt-origin';++/**+ * A quiet line under a prompt: where it came from, when the harness delivered+ * it from elsewhere, and when it was posted - `via @mention in #eng · 2:02 PM`,+ * or just `2:02 PM`. Clicking the origin goes to that place.+ */+export function PromptFooter(props: {+ origin: PromptOrigin | undefined;+ /** RFC 3339; absent until the log confirms the prompt. */+ postedAt: string | undefined;+ onOpen?: () => void;+}) {+ const originText = (origin: PromptOrigin) => (+ <>+ {origin.lead}+ <Show when={origin.place}>+ {(place) => (+ <>+ {' '}+ <span class="text-ink-muted">{place()}</span>+ </>+ )}+ </Show>+ <Show when={origin.tail}>{(tail) => <> {tail()}</>}</Show>+ </>+ );+ const label = (origin: PromptOrigin) =>+ [origin.lead, origin.place, origin.tail].filter(Boolean).join(' ');++ return (+ <div+ class="mr-2 flex max-w-[85%] min-w-0 items-center gap-1.5 text-xs text-ink-extra-muted"+ data-testid="prompt-footer"+ >+ <Show when={props.origin}>+ {(origin) => (+ <Show+ when={props.onOpen}+ fallback={+ <span class="min-w-0 truncate px-1" title={label(origin())}>+ {originText(origin())}+ </span>+ }+ >+ {(open) => (+ <button+ type="button"+ title={label(origin())}+ onClick={() => open()()}+ class="min-w-0 truncate rounded px-1 text-left underline decoration-dotted underline-offset-2 not-touch:hover:bg-hover not-touch:hover:text-ink"+ >+ {originText(origin())}+ </button>+ )}+ </Show>+ )}+ </Show>+ <Show when={props.postedAt}>+ {(postedAt) => (+ <>+ <Show when={props.origin}>+ <span class="shrink-0" aria-hidden="true">+ ·+ </span>+ </Show>+ <time class="shrink-0 px-1" datetime={postedAt()}>+ {formatDate(postedAt(), { showTime: true })}+ </time>+ </>+ )}+ </Show>+ </div>+ );+}diff --git a/apps/web/src/features/block-agent/context/pending-session.test.tsx b/apps/web/src/features/block-agent/context/pending-session.test.tsxindex 5593144b10..1ce99366fc 100644--- a/apps/web/src/features/block-agent/context/pending-session.test.tsx+++ b/apps/web/src/features/block-agent/context/pending-session.test.tsx@@ -157,6 +157,7 @@ describe('pending navigation ownership', () => {pending: false,segments: [],phase: null,+ postedAt: null,},},{@@ -171,6 +172,7 @@ describe('pending navigation ownership', () => {pending: false,segments: [],phase: null,+ postedAt: null,},},] satisfies FoldedStreamEvent[]);diff --git a/apps/web/src/features/block-agent/debug/Gallery.tsx b/apps/web/src/features/block-agent/debug/Gallery.tsxindex d947b81334..1f936b7dc5 100644--- a/apps/web/src/features/block-agent/debug/Gallery.tsx+++ b/apps/web/src/features/block-agent/debug/Gallery.tsx@@ -408,6 +408,7 @@ function ToolReplayDemo() {pending: false,segments: [],phase: null,+ postedAt: null,turn: 0,author: { kind: 'agent' },stop: inFlight() ? null : { kind: 'end_turn' },@@ -457,6 +458,7 @@ function DisplayResultsDemo() {pending: false,segments: [],phase: null,+ postedAt: null,turn: 0,author: { kind: 'agent' },stop: pending() ? null : { kind: 'end_turn' },@@ -526,6 +528,7 @@ const FIXTURE_MESSAGE: FoldedMessage = {pending: false,segments: [],phase: null,+ postedAt: null,turn: 0,author: { kind: 'agent' },stop: { kind: 'end_turn' },@@ -774,6 +777,7 @@ const FIXTURE_IN_FLIGHT: FoldedMessage = {pending: false,segments: [],phase: null,+ postedAt: null,turn: 1,author: { kind: 'agent' },stop: null,@@ -819,6 +823,7 @@ const FIXTURE_UNCLOSED: FoldedMessage = {pending: false,segments: [],phase: null,+ postedAt: null,turn: 2,author: { kind: 'agent' },stop: null,@@ -887,6 +892,7 @@ function PromptAuthorDemo() {pending: false,segments: [],phase: null,+ postedAt: null,turn: 0,author: { kind: 'user', userId },stop: null,diff --git a/apps/web/src/features/block-agent/open-prompt-origin.ts b/apps/web/src/features/block-agent/open-prompt-origin.tsnew file mode 100644index 0000000000..f5ea3532bf--- /dev/null+++ b/apps/web/src/features/block-agent/open-prompt-origin.ts@@ -0,0 +1,110 @@+import { callsHostedContent } from '@app/features/calls-view/calls-hosted-content';+import { documentCommentLocation } from '@app/features/notifications/document-comment-location';+import { openProject } from '@app/features/projects/open-project';+import { routineContent } from '@app/features/routines/routine-navigation';+import { globalSplitManager } from '@app/signal/splitLayout';+import { navigateToChannelMessage } from '@block-channel/utils/link';+import { useSplitLayout } from '@components/app/split-layout/layout';+import { openDocument } from '@core/component/LexicalMarkdown/component/core/BlockLink';+import { toast } from '@core/component/Toast/Toast';+import { COMMENT_LINK_PARAM } from '@core/messages/comment-link';+import { openExternalUrl } from '@core/util/url';+import { getItemPreview, isAccessiblePreviewItem } from '@queries/preview';+import { ResultAsync } from 'neverthrow';+import { match } from 'ts-pattern';+import type { OriginDestination } from './state/prompt-origin';++/**+ * Opens the place a prompt came from: a host action, deliberately outside the+ * feature layers. Called during setup: it reads the split layout from context.+ */+export function useOpenPromptOrigin(): (+ destination: OriginDestination+) => void {+ const layout = useSplitLayout();++ /** A document's block depends on its file type, which the context omits. */+ const openDocumentComment = async (+ documentId: string,+ commentId: string | undefined+ ) => {+ const preview = await ResultAsync.fromPromise(+ getItemPreview({ id: documentId, type: 'document' }),+ () => 'unreadable' as const+ );+ if (+ preview.isErr() ||+ !isAccessiblePreviewItem(preview.value) ||+ preview.value.type !== 'document'+ ) {+ toast.failure("Couldn't open that document");+ return;+ }+ const location = documentCommentLocation(commentId ?? '', {+ fileType: preview.value.fileType,+ subType: preview.value.subType,+ });+ openDocument(+ location.blockName,+ documentId,+ commentId ? location.params : undefined+ );+ };++ return (destination) =>+ match(destination)+ .with({ kind: 'channel_message' }, (target) => {+ const orchestrator = globalSplitManager()?.getOrchestrator();+ if (target.messageId && orchestrator) {+ void navigateToChannelMessage(+ orchestrator,+ target.channelId,+ target.messageId,+ target.threadId+ );+ return;+ }+ layout.openWithSplit({ type: 'channel', id: target.channelId });+ })+ .with({ kind: 'document' }, ({ documentId, commentId }) => {+ void openDocumentComment(documentId, commentId);+ })+ .with({ kind: 'project' }, ({ projectId, commentId }) =>+ openProject(layout, projectId, { discussionId: commentId })+ )+ .with({ kind: 'crm_company' }, ({ companyId, commentId }) => {+ openDocument(+ 'company',+ companyId,+ commentId ? { [COMMENT_LINK_PARAM]: commentId } : undefined+ );+ })+ .with({ kind: 'crm_contact' }, ({ contactId, commentId }) => {+ openDocument(+ 'contact',+ contactId,+ commentId ? { [COMMENT_LINK_PARAM]: commentId } : undefined+ );+ })+ .with({ kind: 'call' }, ({ callId }) => {+ const content = callsHostedContent({ type: 'call', id: callId });+ if (content) layout.openWithSplit(content);+ })+ .with({ kind: 'task' }, ({ taskId }) => {+ layout.openWithSplit({ type: 'task', id: taskId });+ })+ .with({ kind: 'routine' }, ({ routineId }) => {+ layout.openWithSplit(routineContent(routineId), { activate: true });+ })+ .with({ kind: 'email_thread' }, ({ threadId }) => {+ layout.openWithSplit({ type: 'email', id: threadId });+ })+ .with({ kind: 'agent_session' }, ({ sessionId }) => {+ layout.openWithSplit(+ { type: 'agent', id: sessionId },+ { activate: true }+ );+ })+ .with({ kind: 'external' }, ({ url }) => openExternalUrl(url))+ .exhaustive();+}diff --git a/apps/web/src/features/block-agent/state/live-turn.test.ts b/apps/web/src/features/block-agent/state/live-turn.test.tsindex 632aa057a5..83fea8adb1 100644--- a/apps/web/src/features/block-agent/state/live-turn.test.ts+++ b/apps/web/src/features/block-agent/state/live-turn.test.ts@@ -7,6 +7,7 @@ const agent = (turn: number, stop: FoldedMessage['stop']): FoldedMessage => ({pending: false,segments: [],phase: null,+ postedAt: null,requestId: null,turn,author: { kind: 'agent' },@@ -18,6 +19,7 @@ const user = (turn: number): FoldedMessage => ({pending: false,segments: [],phase: null,+ postedAt: null,requestId: null,turn,author: { kind: 'user', userId: 'u' },@@ -29,6 +31,7 @@ const control = (turn: number): FoldedMessage => ({pending: false,segments: [],phase: null,+ postedAt: null,requestId: 'r',turn,author: { kind: 'user', userId: 'u' },diff --git a/apps/web/src/features/block-agent/state/prompt-origin.test.ts b/apps/web/src/features/block-agent/state/prompt-origin.test.tsnew file mode 100644index 0000000000..074434da5b--- /dev/null+++ b/apps/web/src/features/block-agent/state/prompt-origin.test.ts@@ -0,0 +1,514 @@+import {+ type AgentContextPrompt,+ composeAgentContextPrompt,+} from '@macro-inc/lexical-core/utils/agent-context';+import { describe, expect, it } from 'vitest';+import { agentContextText, promptOrigin } from './prompt-origin';++const julia = {+ id: 'macro|[email protected]',+ name: 'Julia',+ email: '[email protected]',+};+const teo = {+ id: 'macro|[email protected]',+ name: 'Teo',+ email: '[email protected]',+};+const agent = { id: 'bot|00000000-0000-0000-0000-00000000c5c5', name: 'Macro' };++/** The origin of a prompt the real composer wrote. */+function originOf(input: AgentContextPrompt) {+ const text = agentContextText(composeAgentContextPrompt(input));+ if (text === undefined) throw new Error('the composer wrote no context');+ return promptOrigin(text);+}++describe('agentContextText', () => {+ it('reads the context text out of the envelope', () => {+ expect(+ agentContextText(+ '<m-agent-context>{"version":1,"text":"<trigger kind=\\"requested\\"/>"}</m-agent-context>\nhello'+ )+ ).toBe('<trigger kind="requested"/>');+ });++ it('is undefined for a prompt without context', () => {+ expect(agentContextText('hello')).toBeUndefined();+ });+});++describe('promptOrigin', () => {+ it('names the channel and points at the mention in its thread', () => {+ expect(+ originOf({+ promptMarkdown: 'why do the snapshot tests flake?',+ trigger: {+ kind: 'mentioned',+ surface: {+ type: 'channel',+ id: 'c1',+ name: 'eng',+ channel_type: 'public',+ },+ prompt_message_id: 'm2',+ sender: julia,+ reply_target: { kind: 'thread', root_id: 'm1' },+ thread: {+ root_id: 'm1',+ messages: [+ {+ id: 'm1',+ author: teo,+ content: 'third red build today',+ posted_at: '2026-10-15T14:00:00Z',+ },+ {+ id: 'm2',+ author: julia,+ content: 'why do the snapshot tests flake?',+ posted_at: '2026-10-15T14:02:00Z',+ },+ ],+ messages_omitted: false,+ },+ },+ })+ ).toEqual({+ lead: 'via @mention in',+ place: '#eng',+ tail: undefined,+ destination: {+ kind: 'channel_message',+ channelId: 'c1',+ messageId: 'm2',+ threadId: 'm1',+ },+ });+ });++ it('names a direct message by its sender and points at the top-level message', () => {+ expect(+ originOf({+ promptMarkdown: 'draft a reply to Acme',+ trigger: {+ kind: 'mentioned',+ surface: {+ type: 'channel',+ id: 'c2',+ channel_type: 'direct_message',+ },+ prompt_message_id: 'd1',+ sender: teo,+ reply_target: { kind: 'none' },+ channel: [+ {+ root_id: 'd1',+ messages: [+ {+ id: 'd1',+ author: teo,+ content: 'draft a reply to Acme',+ posted_at: '2026-10-15T11:40:00Z',+ },+ ],+ messages_omitted: false,+ },+ ],+ },+ })+ ).toEqual({+ lead: 'via @mention in',+ place: 'a DM with Teo',+ tail: undefined,+ destination: {+ kind: 'channel_message',+ channelId: 'c2',+ messageId: 'd1',+ threadId: undefined,+ },+ });+ });++ it('points a document comment mention at its comment', () => {+ expect(+ originOf({+ promptMarkdown: 'can you check the QA calendar?',+ trigger: {+ kind: 'mentioned',+ surface: {+ type: 'document_comment',+ id: 'doc-1',+ name: 'Launch plan',+ },+ prompt_message_id: 'm2',+ sender: julia,+ reply_target: { kind: 'thread', root_id: 'm1' },+ thread: {+ root_id: 'm1',+ messages: [+ {+ id: 'm2',+ author: julia,+ content: 'can you check the QA calendar?',+ posted_at: '2026-10-15T14:02:00Z',+ },+ ],+ messages_omitted: false,+ },+ },+ })+ ).toEqual({+ lead: 'via @mention in',+ place: 'a comment on Launch plan',+ tail: undefined,+ destination: { kind: 'document', documentId: 'doc-1', commentId: 'm2' },+ });+ });++ it('names project, CRM and call chat surfaces', () => {+ const on = (+ surface: Extract<+ AgentContextPrompt['trigger'],+ { kind: 'mentioned' }+ >['surface']+ ) =>+ originOf({+ promptMarkdown: 'summarize this',+ trigger: {+ kind: 'mentioned',+ surface,+ prompt_message_id: 'm1',+ sender: julia,+ reply_target: { kind: 'none' },+ channel: [+ {+ root_id: 'm1',+ messages: [+ {+ id: 'm1',+ author: julia,+ content: 'summarize this',+ posted_at: '2026-10-15T14:02:00Z',+ },+ ],+ messages_omitted: false,+ },+ ],+ },+ });++ expect(+ on({ type: 'project_comment', id: 'p1', name: 'Calendar polish' })+ ).toMatchObject({+ place: 'a comment on Calendar polish',+ destination: { kind: 'project', projectId: 'p1' },+ });+ expect(+ on({ type: 'crm_company_comment', id: 'co1', name: 'Acme Corp' })+ ).toMatchObject({+ place: 'a comment on Acme Corp',+ destination: { kind: 'crm_company', companyId: 'co1', commentId: 'm1' },+ });+ expect(+ on({ type: 'crm_contact_comment', id: 'ct1', name: 'Sam Lee' })+ ).toMatchObject({+ place: 'a comment on Sam Lee',+ destination: { kind: 'crm_contact', contactId: 'ct1', commentId: 'm1' },+ });+ expect(+ on({ type: 'call_chat', id: 'call-0', title: 'Standup' })+ ).toMatchObject({+ place: 'Standup call chat',+ destination: { kind: 'call', callId: 'call-0' },+ });+ });++ it('says how a follow-up reached the agent', () => {+ const followUp = (+ addressed_by: 'mention' | 'explicit_reply' | 'inferred'+ ) =>+ originOf({+ promptMarkdown: 'and the popover one too',+ trigger: {+ kind: 'follow_up',+ addressed_by,+ discussion: {+ surface: {+ type: 'channel',+ id: 'c1',+ name: 'eng',+ channel_type: 'public',+ },+ prompt_message_id: 'p',+ sender: julia,+ reply_target: { kind: 'none' },+ channel: [+ {+ root_id: 'p',+ messages: [+ {+ id: 'p',+ author: julia,+ content: 'and the popover one too',+ posted_at: '2026-10-15T14:02:00Z',+ },+ ],+ messages_omitted: false,+ },+ ],+ },+ },+ });++ expect(followUp('mention')).toMatchObject({+ lead: 'via @mention in',+ place: '#eng',+ tail: undefined,+ });+ expect(followUp('explicit_reply')).toMatchObject({+ lead: 'via reply in',+ place: '#eng',+ tail: undefined,+ });+ expect(followUp('inferred')).toMatchObject({+ lead: 'via message in',+ place: '#eng',+ tail: '(inferred)',+ destination: { kind: 'channel_message', channelId: 'c1', messageId: 'p' },+ });+ });++ it('names the assigned task and who assigned it', () => {+ expect(+ originOf({+ promptMarkdown: 'Work on the assigned task.',+ trigger: {+ kind: 'task_assigned',+ task: {+ id: 'task-1',+ title: 'Fix calendar popover scroll',+ markdown: 'The popover scrolls the page behind it.',+ status: 'Todo',+ assignees: [agent],+ },+ assigned_by: julia,+ assigned_at: '2026-10-15T14:02:00Z',+ discussion_id: 'd1',+ },+ })+ ).toEqual({+ lead: 'via task',+ place: 'Fix calendar popover scroll',+ tail: 'from Julia',+ destination: { kind: 'task', taskId: 'task-1' },+ });+ });++ it('names the repository of a composer request and links to it', () => {+ expect(+ originOf({+ promptMarkdown: 'Upgrade the lexical packages.',+ trigger: {+ kind: 'requested',+ requested_by: julia,+ requested_at: '2026-10-15T14:02:00Z',+ repo_url: 'https://github.com/macro-inc/macro',+ },+ })+ ).toEqual({+ lead: 'via composer in',+ place: 'macro-inc/macro',+ tail: undefined,+ destination: {+ kind: 'external',+ url: 'https://github.com/macro-inc/macro',+ },+ });+ });++ it('points a handoff at the session that dispatched it', () => {+ expect(+ originOf({+ promptMarkdown: 'Fix the flaky sync test.',+ trigger: {+ kind: 'dispatched',+ dispatched_by: julia,+ dispatched_at: '2026-10-15T14:02:00Z',+ from_bot: '00000000-0000-0000-0000-00000000a2a2',+ from_session: 's-1',+ },+ })+ ).toEqual({+ lead: 'via handoff from',+ place: 'another agent',+ tail: 'for Julia',+ destination: { kind: 'agent_session', sessionId: 's-1' },+ });+ });++ it('points a scheduled routine run at the routine', () => {+ expect(+ originOf({+ promptMarkdown: 'Triage the inbox.',+ trigger: {+ kind: 'routine',+ routine_id: 'r-1',+ name: 'Morning triage',+ owner: julia,+ instructions: 'Sort new email.',+ triggers: [+ { type: 'schedule', cron: '0 0 9 * * MON-FRI', timezone: 'UTC' },+ ],+ firing: {+ type: 'scheduled',+ scheduled_for: '2026-10-15T09:00:00Z',+ schedule: 'Every weekday at 9:00',+ },+ },+ })+ ).toEqual({+ lead: 'via routine',+ place: 'Morning triage',+ tail: '· every weekday at 9:00',+ destination: { kind: 'routine', routineId: 'r-1' },+ });+ });++ it('points an event routine run at what fired it', () => {+ const routine = (+ firing: Extract<+ AgentContextPrompt['trigger'],+ { kind: 'routine' }+ >['firing']+ ) =>+ originOf({+ promptMarkdown: 'Do the thing.',+ trigger: {+ kind: 'routine',+ routine_id: 'r-2',+ name: 'Watcher',+ owner: julia,+ instructions: 'Do the thing.',+ triggers: [{ type: 'events', events: ['any'] }],+ firing,+ },+ });++ expect(+ routine({+ type: 'event',+ event: {+ event: 'task_status_changed',+ task: {+ id: 'task-2',+ title: 'Renew SSL cert',+ markdown: '',+ status: 'Blocked',+ },+ },+ })+ ).toEqual({+ lead: 'via routine',+ place: 'Watcher',+ tail: '· Renew SSL cert moved to Blocked',+ destination: { kind: 'task', taskId: 'task-2' },+ });++ expect(+ routine({+ type: 'event',+ event: {+ event: 'email_received',+ email: {+ thread_id: 'e-1',+ subject: 'Invoice #42',+ from: 'Acme Billing <[email protected]>',+ to: ['[email protected]'],+ received_at: '2026-10-15T08:15:00Z',+ body: 'Attached.',+ },+ },+ })+ ).toEqual({+ lead: 'via routine',+ place: 'Watcher',+ tail: '· email from Acme Billing',+ destination: { kind: 'email_thread', threadId: 'e-1' },+ });++ expect(+ routine({+ type: 'event',+ event: {+ event: 'channel_message_attachment_created',+ entity_type: 'document',+ entity_id: 'doc-q3',+ discussion: {+ surface: {+ type: 'channel',+ id: 'c2',+ channel_type: 'direct_message',+ },+ prompt_message_id: 'f1',+ sender: teo,+ reply_target: { kind: 'none' },+ thread: {+ root_id: 'q',+ messages: [+ {+ id: 'f1',+ author: teo,+ content: 'here you go',+ posted_at: '2026-10-15T10:05:00Z',+ },+ ],+ messages_omitted: true,+ },+ },+ },+ })+ ).toEqual({+ lead: 'via routine',+ place: 'Watcher',+ tail: '· file from Teo',+ destination: {+ kind: 'channel_message',+ channelId: 'c2',+ messageId: 'f1',+ threadId: 'q',+ },+ });++ expect(+ routine({+ type: 'event',+ event: {+ event: 'call_ended',+ call: {+ id: 'call-1',+ title: 'Acme renewal',+ started_at: '2026-10-15T14:00:00Z',+ ended_at: '2026-10-15T14:30:00Z',+ participants: [],+ transcript_omitted: false,+ },+ },+ })+ ).toEqual({+ lead: 'via routine',+ place: 'Watcher',+ tail: '· Acme renewal ended',+ destination: { kind: 'call', callId: 'call-1' },+ });+ });++ it('is undefined when the context names no trigger', () => {+ expect(+ promptOrigin(+ '<session owner="Julia" owner_id="macro|[email protected]"/>'+ )+ ).toBeUndefined();+ expect(promptOrigin('Prior message 1: <unclosed')).toBeUndefined();+ });+});diff --git a/apps/web/src/features/block-agent/state/prompt-origin.ts b/apps/web/src/features/block-agent/state/prompt-origin.tsnew file mode 100644index 0000000000..07a1945376--- /dev/null+++ b/apps/web/src/features/block-agent/state/prompt-origin.ts@@ -0,0 +1,422 @@+/**+ * What started a prompt, read from the `<m-agent-context>` block the harness+ * puts before it. The block is XML written for the model by+ * `composeAgentContextPrompt` in `@macro-inc/lexical-core`; this reads back+ * the few facts a person needs: what called the agent, where, when, and where+ * to go to see it.+ */++import { Result } from 'neverthrow';+import { match, P } from 'ts-pattern';++const parseJson = Result.fromThrowable(+ (text: string): unknown => JSON.parse(text),+ () => 'invalid json' as const+);++const OPEN = '<m-agent-context>';+const CLOSE = '</m-agent-context>';++/** Somewhere in the app a prompt came from. */+export type OriginDestination =+ | {+ kind: 'channel_message';+ channelId: string;+ messageId: string | undefined;+ threadId: string | undefined;+ }+ | { kind: 'document'; documentId: string; commentId: string | undefined }+ | { kind: 'project'; projectId: string; commentId: string | undefined }+ | { kind: 'crm_company'; companyId: string; commentId: string | undefined }+ | { kind: 'crm_contact'; contactId: string; commentId: string | undefined }+ | { kind: 'call'; callId: string }+ | { kind: 'task'; taskId: string }+ | { kind: 'routine'; routineId: string }+ | { kind: 'email_thread'; threadId: string }+ | { kind: 'agent_session'; sessionId: string }+ | { kind: 'external'; url: string };++/**+ * One line under the prompt: `{lead} {place} {tail}`, with `place` set+ * brighter.+ */+export type PromptOrigin = {+ lead: string;+ place: string | undefined;+ tail: string | undefined;+ destination: OriginDestination | undefined;+};++/** The context text of a prompt part, when the part opens with one. */+export function agentContextText(markdown: string): string | undefined {+ if (!markdown.startsWith(OPEN)) return undefined;+ const end = markdown.indexOf(CLOSE);+ if (end < 0) return undefined;+ const data = parseJson(markdown.slice(OPEN.length, end)).unwrapOr(undefined);+ if (+ typeof data === 'object' &&+ data !== null &&+ 'text' in data &&+ typeof data.text === 'string'+ )+ return data.text;+ return undefined;+}++function children(element: Element, tag: string): Element[] {+ return [...element.children].filter((child) => child.tagName === tag);+}++function child(element: Element, tag: string): Element | undefined {+ return children(element, tag)[0];+}++function attribute(+ element: Element | undefined,+ name: string+): string | undefined {+ return element?.getAttribute(name) ?? undefined;+}++/** The message whose `marker` attribute is set, anywhere in `element`. */+function markedMessage(element: Element): Element | undefined {+ return [...element.getElementsByTagName('message')].find((message) =>+ [...message.attributes].some(+ (item) =>+ item.value === 'true' &&+ [+ 'mentioned_you',+ 'replied_to_you',+ 'addressed_to_you',+ 'wrote_to_you',+ 'fired_routine',+ ].includes(item.name)+ )+ );+}++type Discussion = {+ /** Where, as a reader names it: `#eng`, `a comment on Launch plan`. */+ place: string;+ destination: OriginDestination | undefined;+};++/** The surface and message of a `<discussion>`. */+function readDiscussion(discussion: Element): Discussion | undefined {+ const message = markedMessage(discussion);+ const messageId = attribute(message, 'id');+ const sender = attribute(child(discussion, 'sender'), 'name');+ const surface = [...discussion.children].find((element) =>+ [+ 'channel',+ 'document',+ 'project',+ 'crm_company',+ 'crm_contact',+ 'call',+ ].includes(element.tagName)+ );+ if (!surface) return undefined;+ const id = attribute(surface, 'id') ?? '';+ const name = attribute(surface, 'name');+ const commentOn = (place: string | undefined) =>+ place ? `a comment on ${place}` : 'a comment';++ return match(surface.tagName)+ .with('channel', () => {+ const thread =+ message?.parentElement?.tagName === 'thread'+ ? attribute(message.parentElement, 'root')+ : undefined;+ return {+ place: name+ ? `#${name}`+ : sender+ ? `a DM with ${sender}`+ : 'a direct message',+ destination: {+ kind: 'channel_message' as const,+ channelId: id,+ messageId,+ threadId: thread === messageId ? undefined : thread,+ },+ };+ })+ .with('document', () => ({+ place: commentOn(name),+ destination: {+ kind: 'document' as const,+ documentId: id,+ commentId: messageId,+ },+ }))+ .with('project', () => ({+ place: commentOn(name),+ destination: {+ kind: 'project' as const,+ projectId: id,+ commentId: messageId,+ },+ }))+ .with('crm_company', () => ({+ place: commentOn(name),+ destination: {+ kind: 'crm_company' as const,+ companyId: id,+ commentId: messageId,+ },+ }))+ .with('crm_contact', () => ({+ place: commentOn(name),+ destination: {+ kind: 'crm_contact' as const,+ contactId: id,+ commentId: messageId,+ },+ }))+ .with('call', () => ({+ place: `${attribute(surface, 'title') ?? 'a call'} call chat`,+ destination: { kind: 'call' as const, callId: id },+ }))+ .otherwise(() => undefined);+}++/** `a/b` from a GitHub URL, or the URL itself. */+function repoName(url: string): string {+ const found = /github\.com\/([^/]+\/[^/?#]+)/.exec(url);+ return found ? found[1].replace(/\.git$/, '') : url;+}++/** Why a routine ran, after its name: `every weekday at 9:00`. */+type Firing = {+ tail: string | undefined;+ destination: OriginDestination | undefined;+};++function readFiring(trigger: Element): Firing {+ const scheduled = child(trigger, 'scheduled');+ if (scheduled) {+ const schedule = attribute(scheduled, 'schedule');+ return {+ tail: schedule ? `· ${lowerFirst(schedule)}` : undefined,+ destination: undefined,+ };+ }+ const manual = child(trigger, 'manual');+ if (manual)+ return {+ tail: '· run by hand',+ destination: undefined,+ };+ const event = child(trigger, 'event');+ if (!event) return { tail: undefined, destination: undefined };++ const task = child(event, 'task');+ const taskTitle = attribute(task, 'title') ?? 'a task';+ const taskDestination = task+ ? { kind: 'task' as const, taskId: attribute(task, 'id') ?? '' }+ : undefined;+ const document = child(event, 'document');+ const documentName = attribute(document, 'name') ?? 'a document';+ const documentDestination = document+ ? {+ kind: 'document' as const,+ documentId: attribute(document, 'id') ?? '',+ commentId: undefined,+ }+ : undefined;+ const discussion = child(event, 'discussion');+ const read = discussion ? readDiscussion(discussion) : undefined;+ const sender = discussion+ ? attribute(child(discussion, 'sender'), 'name')+ : undefined;+ const call = child(event, 'call');+ const callTitle = attribute(call, 'title') ?? 'A call';+ const callDestination = call+ ? { kind: 'call' as const, callId: attribute(call, 'id') ?? '' }+ : undefined;+ const email = child(event, 'email');+ const channel = child(event, 'channel');++ return match(attribute(event, 'type'))+ .with('document_created', () => ({+ tail: `· ${documentName} created`,+ destination: documentDestination,+ }))+ .with('document_updated', () => ({+ tail: `· ${documentName} edited`,+ destination: documentDestination,+ }))+ .with('document_deleted', () => ({+ tail: `· ${documentName} deleted`,+ destination: undefined,+ }))+ .with('task_created', () => ({+ tail: `· ${taskTitle} created`,+ destination: taskDestination,+ }))+ .with(P.union('task_status_changed', 'task_priority_changed'), () => {+ const to = attribute(child(event, 'change'), 'to');+ return {+ tail: to ? `· ${taskTitle} moved to ${to}` : `· ${taskTitle} changed`,+ destination: taskDestination,+ };+ })+ .with('task_property_changed', () => ({+ tail: `· ${taskTitle} changed`,+ destination: taskDestination,+ }))+ .with('email_received', () => {+ const from = attribute(email, 'from');+ return {+ tail: from ? `· email from ${senderName(from)}` : '· email received',+ destination: email+ ? {+ kind: 'email_thread' as const,+ threadId: attribute(email, 'thread') ?? '',+ }+ : undefined,+ };+ })+ .with('channel_created', () => {+ const name = attribute(channel, 'name');+ return {+ tail: name ? `· #${name} created` : '· channel created',+ destination: channel+ ? {+ kind: 'channel_message' as const,+ channelId: attribute(channel, 'id') ?? '',+ messageId: undefined,+ threadId: undefined,+ }+ : undefined,+ };+ })+ .with(+ P.union(+ 'channel_message_posted',+ 'channel_mentioned',+ 'channel_message_patched'+ ),+ (type) => {+ const what = match(type)+ .with('channel_message_posted', () => 'message')+ .with('channel_mentioned', () => 'mention')+ .with('channel_message_patched', () => 'edit')+ .exhaustive();+ return {+ tail: read ? `· ${what} in ${read.place}` : `· ${what}`,+ destination: read?.destination,+ };+ }+ )+ .with('channel_message_attachment_created', () => ({+ tail: sender ? `· file from ${sender}` : '· file shared',+ destination: read?.destination,+ }))+ .with('call_started', () => ({+ tail: `· ${callTitle} started`,+ destination: callDestination,+ }))+ .with('call_ended', () => ({+ tail: `· ${callTitle} ended`,+ destination: callDestination,+ }))+ .otherwise(() => ({ tail: undefined, destination: undefined }));+}++/** `Acme Billing` from `Acme Billing <[email protected]>`. */+function senderName(from: string): string {+ return from.replace(/\s*<[^>]*>\s*$/, '').trim() || from;+}++function lowerFirst(text: string): string {+ return text.charAt(0).toLowerCase() + text.slice(1);+}++/**+ * Where a prompt came from, or `undefined` when its context names no trigger+ * (a prompt typed in the session itself, or older unstructured context).+ */+export function promptOrigin(contextText: string): PromptOrigin | undefined {+ const parsed = new DOMParser().parseFromString(+ `<context>${contextText}</context>`,+ 'application/xml'+ );+ if (parsed.getElementsByTagName('parsererror').length > 0) return undefined;+ const trigger = child(parsed.documentElement, 'trigger');+ if (!trigger) return undefined;+ const discussion = child(trigger, 'discussion');++ const fromDiscussion = (lead: string, tail?: string) => {+ const read = discussion ? readDiscussion(discussion) : undefined;+ return {+ lead,+ place: read?.place,+ tail,+ destination: read?.destination,+ };+ };++ return match(attribute(trigger, 'kind'))+ .with('mentioned', () => fromDiscussion('via @mention in'))+ .with('follow_up', () =>+ match(attribute(trigger, 'addressed_by'))+ .with('explicit_reply', () => fromDiscussion('via reply in'))+ .with('inferred', () => fromDiscussion('via message in', '(inferred)'))+ .otherwise(() => fromDiscussion('via @mention in'))+ )+ .with('conversation', () => fromDiscussion('via message in'))+ .with('task_assigned', () => {+ const task = child(trigger, 'task');+ const assigned = child(trigger, 'assigned');+ const by = attribute(assigned, 'by');+ return {+ lead: 'via task',+ place: attribute(task, 'title'),+ tail: by ? `from ${by}` : undefined,+ destination: task+ ? { kind: 'task' as const, taskId: attribute(task, 'id') ?? '' }+ : undefined,+ };+ })+ .with('requested', () => {+ const requested = child(trigger, 'requested');+ const repo = attribute(requested, 'repo');+ return {+ lead: repo ? 'via composer in' : 'via composer',+ place: repo ? repoName(repo) : undefined,+ tail: undefined,+ destination: repo+ ? { kind: 'external' as const, url: repo }+ : undefined,+ };+ })+ .with('dispatched', () => {+ const dispatched = child(trigger, 'dispatched');+ const by = attribute(dispatched, 'by');+ const session = attribute(dispatched, 'from_session');+ return {+ lead: 'via handoff from',+ place: 'another agent',+ tail: by ? `for ${by}` : undefined,+ destination: session+ ? { kind: 'agent_session' as const, sessionId: session }+ : undefined,+ };+ })+ .with('routine', () => {+ const routine = child(trigger, 'routine');+ const firing = readFiring(trigger);+ const routineId = attribute(routine, 'id');+ return {+ lead: 'via routine',+ place: attribute(routine, 'name'),+ tail: firing.tail,+ destination:+ firing.destination ??+ (routineId ? { kind: 'routine' as const, routineId } : undefined),+ };+ })+ .otherwise(() => undefined);+}diff --git a/apps/web/src/features/block-agent/state/session-summary.test.ts b/apps/web/src/features/block-agent/state/session-summary.test.tsindex 48b74265c1..eca724bdb5 100644--- a/apps/web/src/features/block-agent/state/session-summary.test.ts+++ b/apps/web/src/features/block-agent/state/session-summary.test.ts@@ -16,6 +16,7 @@ function message(turn: number, parts: MessagePart[]): FoldedMessage {pending: false,segments: [],phase: null,+ postedAt: null,turn,author: { kind: 'agent' },parts,diff --git a/apps/web/src/lib/core/agent-session/AgentSession.test.ts b/apps/web/src/lib/core/agent-session/AgentSession.test.tsindex 2c9da61c6a..9eea09e2a6 100644--- a/apps/web/src/lib/core/agent-session/AgentSession.test.ts+++ b/apps/web/src/lib/core/agent-session/AgentSession.test.ts@@ -1153,6 +1153,7 @@ describe('AgentSession', () => {pending: false,segments: [],phase: null,+ postedAt: null,},{agentSessionId: SESSION,@@ -1167,6 +1168,7 @@ describe('AgentSession', () => {pending: false,segments: [],phase: null,+ postedAt: null,},]);const [span] = renderSpans();@@ -1294,6 +1296,7 @@ describe('AgentSession', () => {pending: false,segments: [],phase: null,+ postedAt: null,},},{@@ -1308,6 +1311,7 @@ describe('AgentSession', () => {pending: false,segments: [],phase: null,+ postedAt: null,},},] satisfies FoldedStreamEvent[]);@@ -1361,6 +1365,7 @@ describe('AgentSession', () => {pending: false,segments: [],phase: null,+ postedAt: null,},},] satisfies FoldedStreamEvent[]);diff --git a/apps/web/src/lib/core/agent-session/prompt-telemetry.test.ts b/apps/web/src/lib/core/agent-session/prompt-telemetry.test.tsindex ca3d6bdf8f..f88b24904d 100644--- a/apps/web/src/lib/core/agent-session/prompt-telemetry.test.ts+++ b/apps/web/src/lib/core/agent-session/prompt-telemetry.test.ts@@ -99,6 +99,7 @@ function withText(text = 'Hello'): PromptTrace {pending: false,segments: [],phase: null,+ postedAt: null,},},{@@ -113,6 +114,7 @@ function withText(text = 'Hello'): PromptTrace {pending: false,segments: [],phase: null,+ postedAt: null,},},]);@@ -368,6 +370,7 @@ describe('PromptTrace', () => {pending: true,segments: [],phase: null,+ postedAt: null,},},];@@ -385,6 +388,7 @@ describe('PromptTrace', () => {pending: false,segments: [],phase: null,+ postedAt: null,},},];@@ -402,6 +406,7 @@ describe('PromptTrace', () => {pending: false,segments: [],phase: null,+ postedAt: null,},},];@@ -472,6 +477,7 @@ describe('PromptTrace', () => {pending: false,segments: [],phase: null,+ postedAt: null,},},{@@ -486,6 +492,7 @@ describe('PromptTrace', () => {pending: false,segments: [],phase: null,+ postedAt: null,},},]);@@ -526,6 +533,7 @@ describe('PromptTrace', () => {pending: false,segments: [],phase: null,+ postedAt: null,},},{@@ -540,6 +548,7 @@ describe('PromptTrace', () => {pending: false,segments: [],phase: null,+ postedAt: null,},},],@@ -579,6 +588,7 @@ describe('PromptTrace', () => {pending: false,segments: [],phase: null,+ postedAt: null,},{agentSessionId: SESSION,@@ -590,6 +600,7 @@ describe('PromptTrace', () => {pending: false,segments: [],phase: null,+ postedAt: null,},],},diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/AgentContext.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/AgentContext.tsxindex b553aef9ed..2636bc6b57 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/AgentContext.tsx+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/AgentContext.tsx@@ -1,64 +1,8 @@-import { Popover } from '@kobalte/core/popover';import type { AgentContextDecoratorProps } from '@macro-inc/lexical-core';-import Eye from '@phosphor/eye.svg';-import { type Component, createMemo, createSignal, For, Show } from 'solid-js';-import { AgentContextElement } from './AgentContextElement';-import { parseContext, summaryOf } from './agent-context-tree';+import type { Component } from 'solid-js';-/** A small eye in the message's corner, opening what the agent was given. */-export const AgentContext: Component<AgentContextDecoratorProps> = (props) => {- const [raw, setRaw] = createSignal(false);- const elements = createMemo(() => parseContext(props.text));- const label = () => {- const parsed = elements();- return parsed ? summaryOf(parsed) : 'Context';- };-- return (- // Zero height so the message keeps its own spacing: the next block is- // styled as the first one, and the eye sits in the corner over it.- <div class="relative h-0 [&+*]:!mt-1.5">- <Popover placement="bottom-end" gutter={4}>- <Popover.Trigger- aria-label={`What the agent saw: ${label()}`}- title={label()}- class="absolute -top-3 -right-3 rounded p-0.5 text-ink-extra-muted hover:bg-hover hover:text-ink"- >- <Eye class="size-3.5" />- </Popover.Trigger>- <Popover.Portal>- <Popover.Content class="z-action-menu flex max-h-[60vh] w-[28rem] max-w-[90vw] flex-col gap-2 overflow-auto rounded-xl border border-edge-muted bg-menu p-3 text-xs text-ink-muted shadow-lg">- <div class="flex items-center justify-between gap-2">- <span class="font-medium text-ink">- Context shared with the agent- </span>- <button- type="button"- onClick={() => setRaw(!raw())}- class="text-[11px] text-ink-extra-muted hover:text-ink"- >- {raw() ? 'Structured' : 'Raw'}- </button>- </div>- <Show- when={!raw() && elements()}- fallback={- <pre class="whitespace-pre-wrap font-mono text-[11px]">- {props.text}- </pre>- }- >- {(parsed) => (- <div class="flex flex-col gap-3">- <For each={parsed()}>- {(element) => <AgentContextElement element={element} />}- </For>- </div>- )}- </Show>- </Popover.Content>- </Popover.Portal>- </Popover>- </div>- );-};+/**+ * The context the harness gives an agent stays hidden: the prompt says where+ * it came from on its own line, `PromptOrigin` in block-agent.+ */+export const AgentContext: Component<AgentContextDecoratorProps> = () => null;diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/AgentContextElement.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/AgentContextElement.tsxdeleted file mode 100644index 24b5d6967b..0000000000--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/AgentContextElement.tsx+++ /dev/null@@ -1,47 +0,0 @@-import { type Component, For, Show } from 'solid-js';-import { type ContextElement, displayValue } from './agent-context-tree';--/** An attribute that names the agent itself, such as `mentioned_you`. */-function isAboutTheAgent(name: string, value: string): boolean {- return value === 'true' && name.endsWith('_you');-}--/** One element of the context: its tag, its attributes, its text, and what it holds. */-export const AgentContextElement: Component<{ element: ContextElement }> = (- props-) => (- <div class="flex min-w-0 flex-col gap-1">- <div class="flex flex-wrap items-baseline gap-1">- <span class="font-mono text-[11px] text-ink-extra-muted">- {props.element.tag}- </span>- <For each={props.element.attributes}>- {([name, value]) => (- <span- class="rounded px-1.5 py-px text-[11px]"- classList={{- 'bg-accent/10 text-accent': isAboutTheAgent(name, value),- 'bg-hover text-ink-muted': !isAboutTheAgent(name, value),- }}- >- <span class="opacity-70">{name.replaceAll('_', ' ')}</span>{' '}- {displayValue(name, value)}- </span>- )}- </For>- </div>- <For each={props.element.notes}>- {(note) => <p class="text-xs italic text-ink-extra-muted">{note}</p>}- </For>- <Show when={props.element.text}>- {(text) => <p class="whitespace-pre-wrap text-sm text-ink">{text()}</p>}- </Show>- <Show when={props.element.children.length > 0}>- <div class="flex flex-col gap-2 border-l border-edge-muted pl-3">- <For each={props.element.children}>- {(child) => <AgentContextElement element={child} />}- </For>- </div>- </Show>- </div>-);diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/create-magic-chip-model.test.ts b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/create-magic-chip-model.test.tsindex 74eb7c0d2d..9db7da3511 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/create-magic-chip-model.test.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/create-magic-chip-model.test.ts@@ -111,6 +111,7 @@ const prompt: FoldedMessage = {pending: false,segments: [],phase: null,+ postedAt: null,};const response: FoldedMessage = {@@ -123,6 +124,7 @@ const response: FoldedMessage = {pending: false,segments: [],phase: null,+ postedAt: null,};const openResponse: FoldedMessage = {diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/presentation.test.ts b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/presentation.test.tsindex c3e51d9711..76a499dc72 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/presentation.test.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/presentation.test.ts@@ -16,6 +16,7 @@ const response = (overrides: Partial<FoldedMessage> = {}): FoldedMessage => ({pending: false,segments: [],phase: null,+ postedAt: null,...overrides,});diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/agent-context-tree.test.ts b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/agent-context-tree.test.tsdeleted file mode 100644index 397f17d7e5..0000000000--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/agent-context-tree.test.ts+++ /dev/null@@ -1,82 +0,0 @@-import { describe, expect, it } from 'vitest';-import { parseContext, summaryOf } from './agent-context-tree';--describe('parseContext', () => {- it('reads elements, attributes, notes and text', () => {- expect(- parseContext(- '<trigger kind="mentioned"><note>Opened the session.</note><channel id="c1" name="eng" type="public"/><thread root="m1"><message id="m1" author="Julia">hello</message></thread></trigger>'- )- ).toEqual([- {- tag: 'trigger',- attributes: [['kind', 'mentioned']],- notes: ['Opened the session.'],- text: undefined,- children: [- {- tag: 'channel',- attributes: [- ['id', 'c1'],- ['name', 'eng'],- ['type', 'public'],- ],- notes: [],- text: undefined,- children: [],- },- {- tag: 'thread',- attributes: [['root', 'm1']],- notes: [],- text: undefined,- children: [- {- tag: 'message',- attributes: [- ['id', 'm1'],- ['author', 'Julia'],- ],- notes: [],- text: 'hello',- children: [],- },- ],- },- ],- },- ]);- });-- it('gives up on text that is not XML', () => {- expect(parseContext('Prior message 1: <unclosed')).toBeUndefined();- });-});--describe('summaryOf', () => {- it('names the kind and the channel', () => {- expect(- summaryOf(- parseContext(- '<session owner="Wolf"/><trigger kind="follow_up"><discussion><channel name="eng"/></discussion></trigger>'- ) ?? []- )- ).toBe('Follow-up · #eng');- });-- it('names a task by its title', () => {- expect(- summaryOf(- parseContext(- '<trigger kind="task_assigned"><task id="t1" title="Fix scroll"/></trigger>'- ) ?? []- )- ).toBe('Task assigned · Fix scroll');- });-- it('falls back to Context without a trigger', () => {- expect(- summaryOf(parseContext('<instructions>Be brief.</instructions>') ?? [])- ).toBe('Context');- });-});diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/agent-context-tree.ts b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/agent-context-tree.tsdeleted file mode 100644index 9a5bdfd450..0000000000--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/agent-context-tree.ts+++ /dev/null@@ -1,100 +0,0 @@-import { match } from 'ts-pattern';--/** One element of an agent's context, as the XML has it. */-export type ContextElement = {- tag: string;- attributes: [name: string, value: string][];- /** Guidance the agent was given about this element. */- notes: string[];- /** Text of an element without element children. */- text: string | undefined;- children: ContextElement[];-};--function toElement(element: Element): ContextElement {- const children = [...element.children];- return {- tag: element.tagName,- attributes: [...element.attributes].map((item) => [item.name, item.value]),- notes: children- .filter((child) => child.tagName === 'note')- .map((child) => child.textContent ?? ''),- text:- children.length === 0- ? element.textContent?.trim() || undefined- : undefined,- children: children- .filter((child) => child.tagName !== 'note')- .map(toElement),- };-}--/** Top-level elements, or `undefined` when the text is not XML. */-export function parseContext(text: string): ContextElement[] | undefined {- const parsed = new DOMParser().parseFromString(- `<context>${text}</context>`,- 'application/xml'- );- if (parsed.getElementsByTagName('parsererror').length > 0) return undefined;- return [...parsed.documentElement.children].map(toElement);-}--export function attributeOf(- element: ContextElement,- name: string-): string | undefined {- return element.attributes.find(([key]) => key === name)?.[1];-}--function findFirst(- elements: ContextElement[],- tags: string[]-): ContextElement | undefined {- for (const element of elements) {- if (tags.includes(element.tag)) return element;- const found = findFirst(element.children, tags);- if (found) return found;- }- return undefined;-}--const PLACE_TAGS = [- 'channel',- 'document',- 'task',- 'routine',- 'project',- 'call',-];--/** Where the trigger happened, as a reader names it: `#eng`, a document's name. */-export function placeOf(trigger: ContextElement): string | undefined {- const place = findFirst([trigger], PLACE_TAGS);- if (!place) return undefined;- const name = attributeOf(place, 'name') ?? attributeOf(place, 'title');- if (!name) return undefined;- return place.tag === 'channel' ? `#${name}` : name;-}--/** The chip's label: what called the agent, and where. */-export function summaryOf(elements: ContextElement[]): string {- const trigger = elements.find((element) => element.tag === 'trigger');- if (!trigger) return 'Context';- const kind = match(attributeOf(trigger, 'kind'))- .with('mentioned', () => 'Mentioned')- .with('follow_up', () => 'Follow-up')- .with('task_assigned', () => 'Task assigned')- .with('requested', () => 'Requested')- .with('dispatched', () => 'Dispatched')- .with('routine', () => 'Routine')- .otherwise(() => 'Context');- const place = placeOf(trigger);- return place ? `${kind} · ${place}` : kind;-}--/** Times in the context are RFC 3339; show them the way the app does. */-export function displayValue(name: string, value: string): string {- if (name !== 'at' && name !== 'due' && !name.endsWith('_at')) return value;- const time = new Date(value);- return Number.isNaN(time.getTime()) ? value : time.toLocaleString();-}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.tsindex 308c5f4b6c..654e270556 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@@ -530,6 +530,12 @@ export type FoldedMessage = {* has ended and on a user's message.*/phase: TurnPhase | null;+ /**+ * When a user's prompt was posted, RFC 3339. Absent on agent and control+ * messages, until the log confirms a prompt, and on history a runtime+ * replayed on load.+ */+ postedAt: string | null;};/**diff --git a/crates/agent_session/src/bin/seed_jsonl.rs b/crates/agent_session/src/bin/seed_jsonl.rsindex 2a6594badd..93ec74b32e 100644--- a/crates/agent_session/src/bin/seed_jsonl.rs+++ b/crates/agent_session/src/bin/seed_jsonl.rs@@ -201,6 +201,7 @@ fn parse_line(agent_session_id: session,user_id,content,+ logged_at: None,})}diff --git a/crates/agent_session/src/domain/events.rs b/crates/agent_session/src/domain/events.rsindex 0b775a89bb..14d29e54ad 100644--- a/crates/agent_session/src/domain/events.rs+++ b/crates/agent_session/src/domain/events.rs@@ -524,6 +524,7 @@ impl LogAppendedMetadata {agent_session_id,user_id: entry.user_id,content: entry.content,+ logged_at: Some(entry.created_at),},}).collect()diff --git a/crates/agent_session/src/domain/routines/service/test.rs b/crates/agent_session/src/domain/routines/service/test.rsindex 31d1140722..7f2d2743bf 100644--- a/crates/agent_session/src/domain/routines/service/test.rs+++ b/crates/agent_session/src/domain/routines/service/test.rs@@ -513,6 +513,7 @@ async fn refuses_known_prompt_replays_even_after_completion() {agent_session_id: fx.session.id,user_id: Some(action.owner.clone()),content: crate::domain::model::Message::ToRuntime(content),+ logged_at: None,}]);let response = serde_json::json!({"direction": "to_server",diff --git a/crates/agent_session/src/domain/service.rs b/crates/agent_session/src/domain/service.rsindex 220bbd0f20..24536ca4e0 100644--- a/crates/agent_session/src/domain/service.rs+++ b/crates/agent_session/src/domain/service.rs@@ -956,6 +956,7 @@ wherecontent: Message::ToServer(ToServerMessage::Event {event: SystemEvent::Disconnected,}),+ logged_at: None,}),).await@@ -978,6 +979,7 @@ whereagent_session_id: id,user_id: None,content: Message::ToServer(message),+ logged_at: None,}).await?;logs.flush().awaitdiff --git a/crates/agent_session/src/domain/service/test.rs b/crates/agent_session/src/domain/service/test.rsindex c609755988..3fe88afbe9 100644--- a/crates/agent_session/src/domain/service/test.rs+++ b/crates/agent_session/src/domain/service/test.rs@@ -187,6 +187,7 @@ async fn only_the_first_prompt_is_selected_for_automatic_naming() {).expect("a set-model frame builds"),),+ logged_at: None,}]);assert_eq!(initial_prompt_for_rename(&folds, session, &prompt).await,@@ -1357,6 +1358,7 @@ fn any_event(session: AgentSessionId) -> AgentSessionLog {content: Message::ToServer(ToServerMessage::Event {event: agent_runtime_protocol::domain::schema::v0::SystemEvent::AcpReady,}),+ logged_at: None,}}@@ -2427,6 +2429,7 @@ mod fold_signals {content: Message::ToServer(ToServerMessage::Event {event: SystemEvent::AcpReady,}),+ logged_at: None,}).await.expect("append succeeds");@@ -2458,6 +2461,7 @@ fn streamed_frame(text: &str) -> AgentSessionLog {).unwrap(),))),+ logged_at: None,}}@@ -2566,6 +2570,7 @@ async fn system_events_flush_pending_frames_through() {content: Message::ToServer(ToServerMessage::Event {event: SystemEvent::AcpReady,}),+ logged_at: None,},).await@@ -2725,6 +2730,7 @@ async fn a_load_boundary_lands_after_the_frames_buffered_before_it() {).unwrap(),))),+ logged_at: None,};let initialization_log_id = AgentSessionLogWriter::append(&mut logs, initialize).await@@ -2743,6 +2749,7 @@ async fn a_load_boundary_lands_after_the_frames_buffered_before_it() {Ok(serde_json::json!({})),),))),+ logged_at: None,};let response_id = AgentSessionLogWriter::append_with_boundary(&mut logs,diff --git a/crates/agent_session/src/domain/service/test/initial_model.rs b/crates/agent_session/src/domain/service/test/initial_model.rsindex 88ffcd89c5..f2a1236815 100644--- a/crates/agent_session/src/domain/service/test/initial_model.rs+++ b/crates/agent_session/src/domain/service/test/initial_model.rs@@ -52,6 +52,7 @@ async fn only_the_startup_selection_reply_releases_model_projection() {agent_session_id: fx.session,user_id: None,content,+ logged_at: None,}).await.unwrap();@@ -70,6 +71,7 @@ async fn only_the_startup_selection_reply_releases_model_projection() {agent_session_id: fx.session,user_id: None,content,+ logged_at: None,}).await.unwrap();diff --git a/crates/agent_session/src/domain/session/actors.rs b/crates/agent_session/src/domain/session/actors.rsindex 8dc4638fe2..91fcd9fc9e 100644--- a/crates/agent_session/src/domain/session/actors.rs+++ b/crates/agent_session/src/domain/session/actors.rs@@ -398,6 +398,7 @@ whereagent_session_id: self.machine.id(),user_id: None,content: Message::ToServer(message),+ logged_at: None,},boundary,);@@ -447,6 +448,7 @@ whereagent_session_id: self.machine.id(),user_id: None,content: Message::ToRuntime(context.request.clone()),+ logged_at: None,}).await?.log_id;@@ -586,6 +588,7 @@ whereagent_session_id: self.machine.id(),user_id: from,content: Message::ToRuntime(message.clone()),+ logged_at: None,}).await?;if acp_method(&message) == Some("initialize") {@@ -610,6 +613,7 @@ whereagent_session_id: self.machine.id(),user_id,content,+ logged_at: None,}).await?;self.forward_signals(appended.signals);diff --git a/crates/agent_session/src/outbound/postgres.rs b/crates/agent_session/src/outbound/postgres.rsindex e90a2194d2..93a6866847 100644--- a/crates/agent_session/src/outbound/postgres.rs+++ b/crates/agent_session/src/outbound/postgres.rs@@ -1244,6 +1244,7 @@ impl TryFrom<AgentSessionLogRow> for StoredAgentSessionLog {agent_session_id: AgentSessionId::new_from_uuid(row.agent_session_id),user_id: row.user_id,content: parse_message(&row.direction, row.content)?,+ logged_at: Some(row.created_at),},})}diff --git a/crates/agent_session/src/outbound/postgres/recovery.rs b/crates/agent_session/src/outbound/postgres/recovery.rsindex c08dbd7217..6f2ebe3089 100644--- a/crates/agent_session/src/outbound/postgres/recovery.rs+++ b/crates/agent_session/src/outbound/postgres/recovery.rs@@ -40,6 +40,7 @@ impl<B: BotFacts + 'static> StaleSessionRepo for PgAgentSessionRepo<B> {content: Message::ToServer(ToServerMessage::Event {event: SystemEvent::Disconnected,}),+ logged_at: None,};let (direction, content) = message_columns(&log.content)?;let status = SessionStatus::Event(SystemEvent::Disconnected);diff --git a/crates/agent_session/src/outbound/postgres/test.rs b/crates/agent_session/src/outbound/postgres/test.rsindex bbf2df7a52..618d6186a6 100644--- a/crates/agent_session/src/outbound/postgres/test.rs+++ b/crates/agent_session/src/outbound/postgres/test.rs@@ -138,6 +138,7 @@ async fn append_system_event<B: entity_registry::BotFacts + 'static>(agent_session_id,user_id: None,content: Message::ToServer(ToServerMessage::Event { event }),+ logged_at: None,},).await@@ -900,6 +901,7 @@ async fn log_create_and_list_by_session_orders_chronologically(pool: PgPool) {content: Message::ToServer(ToServerMessage::Event {event: SystemEvent::AcpReady,}),+ logged_at: None,},).await@@ -919,6 +921,7 @@ async fn log_create_and_list_by_session_orders_chronologically(pool: PgPool) {agent_session_id: session_id,user_id: None,content: Message::ToRuntime(ToRuntimeMessage::Acp(acp_notification())),+ logged_at: None,},).await@@ -1621,6 +1624,7 @@ fn fenced_log(id: AgentSessionId) -> AgentSessionLog {agent_session_id: id,user_id: None,content: Message::ToRuntime(ToRuntimeMessage::Acp(acp_notification())),+ logged_at: None,}}@@ -1642,6 +1646,7 @@ fn cursor_checkpoint_log(id: AgentSessionId, run: &str) -> AgentSessionLog {).expect("valid checkpoint notification"),))),+ logged_at: None,}}@@ -2293,6 +2298,7 @@ async fn participants_are_the_distinct_users_the_log_attributes(pool: PgPool) {agent_session_id: session_id,user_id: user,content: Message::ToRuntime(ToRuntimeMessage::Acp(acp_notification())),+ logged_at: None,},).await@@ -2787,6 +2793,7 @@ async fn create_batch_fenced_writes_in_order_under_the_given_ids(pool: PgPool) {).unwrap(),))),+ logged_at: None,};let frames: Vec<AgentSessionLog> = ["one", "two", "three"].into_iter().map(streamed).collect();let ids: Vec<Uuid> = (0..frames.len())diff --git a/crates/agent_session/src/outbound/postgres/test/recovery.rs b/crates/agent_session/src/outbound/postgres/test/recovery.rsindex 4dfa63eed9..512e57efed 100644--- a/crates/agent_session/src/outbound/postgres/test/recovery.rs+++ b/crates/agent_session/src/outbound/postgres/test/recovery.rs@@ -110,6 +110,7 @@ async fn recovery_preserves_history_closes_stale_turn_and_fences_old_writer(poolcontent: Message::ToServer(ToServerMessage::Event {event: SystemEvent::AcpReady,}),+ logged_at: None,},&resumed,)diff --git a/crates/agent_session/src/outbound/postgres/test/search.rs b/crates/agent_session/src/outbound/postgres/test/search.rsindex f934a1acf2..b9f7bf169d 100644--- a/crates/agent_session/src/outbound/postgres/test/search.rs+++ b/crates/agent_session/src/outbound/postgres/test/search.rs@@ -31,6 +31,7 @@ async fn search_snapshot_folds_persisted_acp_instead_of_indexing_protocol_framesagent_session_id: session.id,user_id: Some(user_id(OWNER)),content: serde_json::from_value(content).unwrap(),+ logged_at: None,},).awaitdiff --git a/crates/agent_session/src/testing/test.rs b/crates/agent_session/src/testing/test.rsindex 58b3dee322..86a7dcb641 100644--- a/crates/agent_session/src/testing/test.rs+++ b/crates/agent_session/src/testing/test.rs@@ -12,6 +12,7 @@ fn seeded_frames_remain_ordered_when_the_clock_has_not_advanced() {content: Message::ToServer(ToServerMessage::Event {event: SystemEvent::AcpReady,}),+ logged_at: None,};// Put the existing seed ahead of the wall clock to exercise the tie/backward// clock path deterministically, rather than hoping two calls share a tick.@@ -47,6 +48,7 @@ async fn effective_history_orders_timestamps_and_uuid_ties_before_selecting_bouncontent: Message::ToServer(ToServerMessage::Event {event: SystemEvent::AcpReady,}),+ logged_at: None,},};// Intentionally scrambled insertion order and UUIDs contrary to timestamp order.diff --git a/crates/agent_session_realtime/src/outbound/redis_stream/consumer/test.rs b/crates/agent_session_realtime/src/outbound/redis_stream/consumer/test.rsindex 1578377fe4..330eb61b2e 100644--- a/crates/agent_session_realtime/src/outbound/redis_stream/consumer/test.rs+++ b/crates/agent_session_realtime/src/outbound/redis_stream/consumer/test.rs@@ -103,6 +103,7 @@ fn appended(session: AgentSessionId, ids: impl IntoIterator<Item = u128>) -> Logcontent: Message::ToServer(ToServerMessage::Event {event: SystemEvent::AcpReady,}),+ logged_at: None,},}).collect(),diff --git a/crates/codex_cloud_agents/tests/fold.rs b/crates/codex_cloud_agents/tests/fold.rsindex 5003ea5289..46c1b15f8a 100644--- a/crates/codex_cloud_agents/tests/fold.rs+++ b/crates/codex_cloud_agents/tests/fold.rs@@ -377,6 +377,7 @@ fn entry(to_runtime: bool, value: Value) -> AgentSessionLog {} else {Message::ToServer(ToServerMessage::Acp(AcpMessage(frame)))},+ logged_at: None,}}fn assert_fold(log: &[AgentSessionLog]) -> Vec<FoldedMessage> {diff --git a/crates/codex_cloud_agents/tests/snapshots/fold__recorded_missing_deltas_replay.snap b/crates/codex_cloud_agents/tests/snapshots/fold__recorded_missing_deltas_replay.snapindex 014103c379..b2243c3d19 100644--- a/crates/codex_cloud_agents/tests/snapshots/fold__recorded_missing_deltas_replay.snap+++ b/crates/codex_cloud_agents/tests/snapshots/fold__recorded_missing_deltas_replay.snap@@ -17,7 +17,8 @@ expression: messages}],"stop": null,- "pending": false+ "pending": false,+ "postedAt": null},{"turn": 0,@@ -68,7 +69,8 @@ expression: messages"stop": {"kind": "end_turn"},- "pending": false+ "pending": false,+ "postedAt": null},{"turn": 1,@@ -84,7 +86,8 @@ expression: messages}],"stop": null,- "pending": false+ "pending": false,+ "postedAt": null},{"turn": 1,@@ -101,6 +104,7 @@ expression: messages"stop": {"kind": "end_turn"},- "pending": false+ "pending": false,+ "postedAt": null}]diff --git a/crates/codex_cloud_agents/tests/snapshots/fold__verified_pr_tool.snap b/crates/codex_cloud_agents/tests/snapshots/fold__verified_pr_tool.snapindex 9c814b308e..2415094763 100644--- a/crates/codex_cloud_agents/tests/snapshots/fold__verified_pr_tool.snap+++ b/crates/codex_cloud_agents/tests/snapshots/fold__verified_pr_tool.snap@@ -17,7 +17,8 @@ expression: messages}],"stop": null,- "pending": false+ "pending": false,+ "postedAt": null},{"turn": 0,@@ -57,6 +58,7 @@ expression: messages"stop": {"kind": "end_turn"},- "pending": false+ "pending": false,+ "postedAt": null}]diff --git a/crates/coding_agent_worker/src/herdr/acp_agent/commands/test.rs b/crates/coding_agent_worker/src/herdr/acp_agent/commands/test.rsindex 13cec857b3..5281d6dfa1 100644--- a/crates/coding_agent_worker/src/herdr/acp_agent/commands/test.rs+++ b/crates/coding_agent_worker/src/herdr/acp_agent/commands/test.rs@@ -24,6 +24,7 @@ fn advertised_commands_reach_macro_metadata_for_each_provider() {},})).unwrap(),+ logged_at: None,});let names: Vec<_> = fold.metadata()diff --git a/crates/complete_graph/src/schema/test.rs b/crates/complete_graph/src/schema/test.rsindex 39b6001087..662bf18be3 100644--- a/crates/complete_graph/src/schema/test.rs+++ b/crates/complete_graph/src/schema/test.rs@@ -1515,6 +1515,7 @@ async fn agent_session_log_appended_streams_runs_for_an_accessible_session() {content: Message::ToServer(ToServerMessage::Event {event: SystemEvent::AcpReady,}),+ logged_at: None,},}]).awaitdiff --git a/crates/cursor_cloud_agents/src/domain/service/test/fold.rs b/crates/cursor_cloud_agents/src/domain/service/test/fold.rsindex 55cf35a72c..fef4476451 100644--- a/crates/cursor_cloud_agents/src/domain/service/test/fold.rs+++ b/crates/cursor_cloud_agents/src/domain/service/test/fold.rs@@ -193,6 +193,7 @@ fn entry(content: Message) -> AgentSessionLog {agent_session_id: AgentSessionId::TEST_A,user_id: None,content,+ logged_at: None,}}diff --git a/crates/folds/agent_fold/src/bin/fold_jsonl.rs b/crates/folds/agent_fold/src/bin/fold_jsonl.rsindex 2a8ff8d154..07677aec3d 100644--- a/crates/folds/agent_fold/src/bin/fold_jsonl.rs+++ b/crates/folds/agent_fold/src/bin/fold_jsonl.rs@@ -138,6 +138,7 @@ fn parse_line(agent_session_id: session,user_id: None,content,+ logged_at: None,})}diff --git a/crates/folds/agent_fold/src/domain/fold/content.rs b/crates/folds/agent_fold/src/domain/fold/content.rsindex 8204503626..2d98e5c1e7 100644--- a/crates/folds/agent_fold/src/domain/fold/content.rs+++ b/crates/folds/agent_fold/src/domain/fold/content.rs@@ -78,6 +78,7 @@ impl FoldState {parts: NonEmpty::one(part),stop: None,pending: self.speculative,+ posted_at: None,});self.open_turn().agent = Some(message);return Some((Changed::new(message), 0));diff --git a/crates/folds/agent_fold/src/domain/fold/control.rs b/crates/folds/agent_fold/src/domain/fold/control.rsindex c64160495c..34cd2eaacc 100644--- a/crates/folds/agent_fold/src/domain/fold/control.rs+++ b/crates/folds/agent_fold/src/domain/fold/control.rs@@ -25,6 +25,7 @@ impl FoldState {}),stop: None,pending: self.speculative,+ posted_at: None,});Some(Changed::new(message))}@@ -56,6 +57,7 @@ impl FoldState {parts: NonEmpty::one(MessagePart::Control { control, outcome }),stop: None,pending: self.speculative,+ posted_at: None,});Some(Changed::new(message))}diff --git a/crates/folds/agent_fold/src/domain/fold/state.rs b/crates/folds/agent_fold/src/domain/fold/state.rsindex 15ad710d48..c04eab512f 100644--- a/crates/folds/agent_fold/src/domain/fold/state.rs+++ b/crates/folds/agent_fold/src/domain/fold/state.rs@@ -269,7 +269,12 @@ impl FoldState {&& PromptRequest::matches_method(&request.method){return self- .begin_turn(&request.id, request.params.as_ref(), entry.user_id.clone())+ .begin_turn(+ &request.id,+ request.params.as_ref(),+ entry.user_id.clone(),+ entry.logged_at,+ ).into_iter().map(StepChange::Message).collect();diff --git a/crates/folds/agent_fold/src/domain/fold/turn.rs b/crates/folds/agent_fold/src/domain/fold/turn.rsindex d4b5fcd55e..1388dc9439 100644--- a/crates/folds/agent_fold/src/domain/fold/turn.rs+++ b/crates/folds/agent_fold/src/domain/fold/turn.rs@@ -5,6 +5,7 @@ use crate::domain::model::{Author, FailureNotice, FoldedMessage, MessagePart, Stuse agent_client_protocol::RawJsonRpcParams;use agent_client_protocol::schema::v1::{Error, PromptRequest, RequestId};use agent_runtime_protocol::domain::action::AgentActionId;+use chrono::{DateTime, Utc};use macro_user_id::user_id::MacroUserIdStr;use non_empty::NonEmpty;@@ -46,6 +47,7 @@ impl FoldState {parts: NonEmpty::one(part),stop: None,pending: self.speculative,+ posted_at: None,});Some(Changed::new(message))}@@ -56,6 +58,7 @@ impl FoldState {prompt_id: &RequestId,params: Option<&RawJsonRpcParams>,user_id: Option<MacroUserIdStr<'static>>,+ logged_at: Option<DateTime<Utc>>,) -> Vec<Changed> {// A speculative prompt behind a stop is the queue head, dispatching// once the cancel lands. The turn it follows can only end one way,@@ -124,6 +127,7 @@ impl FoldState {parts,stop: None,pending: self.speculative,+ posted_at: logged_at,});Changed::new(message)});@@ -247,6 +251,7 @@ impl FoldState {}),stop: None,pending: self.speculative,+ posted_at: None,});(message, Changed::new(message))}diff --git a/crates/folds/agent_fold/src/domain/log.rs b/crates/folds/agent_fold/src/domain/log.rsindex a910a5972a..c262e9dee2 100644--- a/crates/folds/agent_fold/src/domain/log.rs+++ b/crates/folds/agent_fold/src/domain/log.rs@@ -9,6 +9,7 @@//! meet them.use agent_runtime_protocol::domain::schema::v0::{ToRuntimeMessage, ToServerMessage};+use chrono::{DateTime, Utc};use macro_user_id::user_id::MacroUserIdStr;use macro_uuid::Uuid;use serde::{Deserialize, Serialize};@@ -93,4 +94,7 @@ pub struct AgentSessionLog {pub user_id: Option<MacroUserIdStr<'static>>,/// The logged frame.pub content: Message,+ /// When the log stored the entry. `None` for a frame not stored yet: one+ /// being appended, or one this client speculated.+ pub logged_at: Option<DateTime<Utc>>,}diff --git a/crates/folds/agent_fold/src/domain/model.rs b/crates/folds/agent_fold/src/domain/model.rsindex f224161cf2..a15ddf4edc 100644--- a/crates/folds/agent_fold/src/domain/model.rs+++ b/crates/folds/agent_fold/src/domain/model.rs@@ -13,6 +13,7 @@//! said, what it ran, and what it wanted permission to do.use agent_runtime_protocol::domain::action::AgentActionId;+use chrono::{DateTime, Utc};use macro_user_id::user_id::MacroUserIdStr;use non_empty::NonEmpty;use serde::Serialize;@@ -229,6 +230,10 @@ pub struct FoldedMessage {/// confirmed: a prompt on the wire, a stop just pressed. Cleared when the/// confirmed frame folds in its place. Always false on the server's fold.pub pending: bool,+ /// When the log stored the prompt this user message came from. `None` on+ /// agent and control messages, on a prompt not stored yet, and on history+ /// a runtime replays on load, whose frames are as old as the load.+ pub posted_at: Option<DateTime<Utc>>,}impl FoldedMessage {diff --git a/crates/folds/agent_fold/src/domain/model/search/test.rs b/crates/folds/agent_fold/src/domain/model/search/test.rsindex a71008694b..031b0cfa36 100644--- a/crates/folds/agent_fold/src/domain/model/search/test.rs+++ b/crates/folds/agent_fold/src/domain/model/search/test.rs@@ -17,6 +17,7 @@ fn message(parts: Vec<MessagePart>) -> FoldedMessage {parts: NonEmpty::new(parts).expect("test message has parts"),stop: None,pending: false,+ posted_at: None,}}diff --git a/crates/folds/agent_fold/src/domain/speculation.rs b/crates/folds/agent_fold/src/domain/speculation.rsindex 1679efe91e..29199d8233 100644--- a/crates/folds/agent_fold/src/domain/speculation.rs+++ b/crates/folds/agent_fold/src/domain/speculation.rs@@ -334,6 +334,7 @@ impl SpeculativeFold {agent_session_id: self.session,user_id: speculation.user_id.clone(),content: Message::ToRuntime(message),+ logged_at: None,})}diff --git a/crates/folds/agent_fold/src/domain/speculation/test.rs b/crates/folds/agent_fold/src/domain/speculation/test.rsindex e17ccd27c1..a372ae69f6 100644--- a/crates/folds/agent_fold/src/domain/speculation/test.rs+++ b/crates/folds/agent_fold/src/domain/speculation/test.rs@@ -50,6 +50,7 @@ fn logged(action: &AgentAction, action_id: AgentActionId) -> AgentSessionLog {.to_runtime(&SessionId::from(ACP_SESSION), action_id.to_request_id()).expect("action encodes"),),+ logged_at: None,}}diff --git a/crates/folds/agent_fold/src/domain/test/machine.rs b/crates/folds/agent_fold/src/domain/test/machine.rsindex ba0472b369..99128cf8c5 100644--- a/crates/folds/agent_fold/src/domain/test/machine.rs+++ b/crates/folds/agent_fold/src/domain/test/machine.rs@@ -319,3 +319,33 @@ fn a_tool_call_without_a_prompt_opens_a_turn() {agent.parts[0]);}++const TEXT_PROMPT: &str = r#"{"direction":"to_runtime","content":{"type":"acp","jsonrpc":"2.0","id":"p0","method":"session/prompt","params":{"sessionId":"s","prompt":[{"type":"text","text":"tighten the fold"}]}}}"#;++/// A prompt shows when it was sent, which is when the log stored it.+#[test]+fn a_stored_prompt_carries_the_time_it_was_logged() {+ let logged_at = "2026-10-15T14:02:00Z".parse().unwrap();+ let mut machine = FoldMachineImpl::new();+ for entry in parse_log(TEXT_PROMPT) {+ let _ = machine.push(AgentSessionLog {+ logged_at: Some(logged_at),+ ..entry+ });+ }++ assert_eq!(machine.messages()[0].posted_at, Some(logged_at));+}++/// A prompt still on the wire has no time yet: guessing one would show a+/// time the log may never agree with.+#[test]+fn a_speculated_prompt_has_no_time() {+ let mut machine = FoldMachineImpl::new();+ for entry in parse_log(TEXT_PROMPT) {+ let _ = machine.push_speculative(entry);+ }++ assert!(machine.messages()[0].pending);+ assert_eq!(machine.messages()[0].posted_at, None);+}diff --git a/crates/folds/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@command_invocation.jsonl.snap b/crates/folds/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@command_invocation.jsonl.snapindex b14283b39b..161f599a6a 100644--- a/crates/folds/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@command_invocation.jsonl.snap+++ b/crates/folds/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@command_invocation.jsonl.snap@@ -1,7 +1,7 @@----source: crates/agent_fold/src/domain/test/real_recordings.rs+source: crates/folds/agent_fold/src/domain/test/real_recordings.rsexpression: messages-input_file: crates/agent_fold/fixtures/real/command_invocation.jsonl+input_file: crates/folds/agent_fold/fixtures/real/command_invocation.jsonl---[FoldedMessage {@@ -28,6 +28,7 @@ input_file: crates/agent_fold/fixtures/real/command_invocation.jsonl},stop: None,pending: false,+ posted_at: None,},FoldedMessage {id: TurnId(@@ -52,6 +53,7 @@ input_file: crates/agent_fold/fixtures/real/command_invocation.jsonl},stop: None,pending: false,+ posted_at: None,},FoldedMessage {id: TurnId(@@ -70,5 +72,6 @@ input_file: crates/agent_fold/fixtures/real/command_invocation.jsonlEndTurn,),pending: false,+ posted_at: None,},]diff --git a/crates/folds/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@elicitation_claude_single_select.jsonl.snap b/crates/folds/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@elicitation_claude_single_select.jsonl.snapindex 3a708c28bc..6d10a0eb80 100644--- a/crates/folds/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@elicitation_claude_single_select.jsonl.snap+++ b/crates/folds/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@elicitation_claude_single_select.jsonl.snap@@ -1,7 +1,7 @@----source: crates/agent_fold/src/domain/test/real_recordings.rs+source: crates/folds/agent_fold/src/domain/test/real_recordings.rsexpression: messages-input_file: crates/agent_fold/fixtures/real/elicitation_claude_single_select.jsonl+input_file: crates/folds/agent_fold/fixtures/real/elicitation_claude_single_select.jsonl---[FoldedMessage {@@ -27,6 +27,7 @@ input_file: crates/agent_fold/fixtures/real/elicitation_claude_single_select.jso},stop: None,pending: false,+ posted_at: None,},FoldedMessage {id: TurnId(@@ -139,5 +140,6 @@ input_file: crates/agent_fold/fixtures/real/elicitation_claude_single_select.jsoEndTurn,),pending: false,+ posted_at: None,},]diff --git a/crates/folds/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@plan_todo.jsonl.snap b/crates/folds/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@plan_todo.jsonl.snapindex 9cef450448..a2069f72c3 100644--- a/crates/folds/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@plan_todo.jsonl.snap+++ b/crates/folds/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@plan_todo.jsonl.snap@@ -1,7 +1,7 @@----source: crates/agent_fold/src/domain/test/real_recordings.rs+source: crates/folds/agent_fold/src/domain/test/real_recordings.rsexpression: messages-input_file: crates/agent_fold/fixtures/real/plan_todo.jsonl+input_file: crates/folds/agent_fold/fixtures/real/plan_todo.jsonl---[FoldedMessage {@@ -28,6 +28,7 @@ input_file: crates/agent_fold/fixtures/real/plan_todo.jsonl},stop: None,pending: false,+ posted_at: None,},FoldedMessage {id: TurnId(@@ -52,6 +53,7 @@ input_file: crates/agent_fold/fixtures/real/plan_todo.jsonl},stop: None,pending: false,+ posted_at: None,},FoldedMessage {id: TurnId(@@ -169,5 +171,6 @@ input_file: crates/agent_fold/fixtures/real/plan_todo.jsonlEndTurn,),pending: false,+ posted_at: None,},]diff --git a/crates/folds/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@real_multi_turn.jsonl.snap b/crates/folds/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@real_multi_turn.jsonl.snapindex bfbccc631f..1102c93bbe 100644--- a/crates/folds/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@real_multi_turn.jsonl.snap+++ b/crates/folds/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@real_multi_turn.jsonl.snap@@ -1,8 +1,7 @@----source: crates/agent_fold/src/domain/test/real_recordings.rs-assertion_line: 244+source: crates/folds/agent_fold/src/domain/test/real_recordings.rsexpression: messages-input_file: crates/agent_fold/fixtures/real/real_multi_turn.jsonl+input_file: crates/folds/agent_fold/fixtures/real/real_multi_turn.jsonl---[FoldedMessage {@@ -28,6 +27,7 @@ input_file: crates/agent_fold/fixtures/real/real_multi_turn.jsonl},stop: None,pending: false,+ posted_at: None,},FoldedMessage {id: TurnId(@@ -124,6 +124,7 @@ input_file: crates/agent_fold/fixtures/real/real_multi_turn.jsonlEndTurn,),pending: false,+ posted_at: None,},FoldedMessage {id: TurnId(@@ -150,6 +151,7 @@ input_file: crates/agent_fold/fixtures/real/real_multi_turn.jsonl},stop: None,pending: false,+ posted_at: None,},FoldedMessage {id: TurnId(@@ -174,6 +176,7 @@ input_file: crates/agent_fold/fixtures/real/real_multi_turn.jsonl},stop: None,pending: false,+ posted_at: None,},FoldedMessage {id: TurnId(@@ -768,6 +771,7 @@ input_file: crates/agent_fold/fixtures/real/real_multi_turn.jsonlEndTurn,),pending: false,+ posted_at: None,},FoldedMessage {id: TurnId(@@ -793,6 +797,7 @@ input_file: crates/agent_fold/fixtures/real/real_multi_turn.jsonl},stop: None,pending: false,+ posted_at: None,},FoldedMessage {id: TurnId(@@ -819,6 +824,7 @@ input_file: crates/agent_fold/fixtures/real/real_multi_turn.jsonl},stop: None,pending: false,+ posted_at: None,},FoldedMessage {id: TurnId(@@ -843,6 +849,7 @@ input_file: crates/agent_fold/fixtures/real/real_multi_turn.jsonl},stop: None,pending: false,+ posted_at: None,},FoldedMessage {id: TurnId(@@ -889,5 +896,6 @@ input_file: crates/agent_fold/fixtures/real/real_multi_turn.jsonl},stop: None,pending: false,+ posted_at: None,},]diff --git a/crates/folds/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@real_single_turn.jsonl.snap b/crates/folds/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@real_single_turn.jsonl.snapindex 3df4571748..111b389922 100644--- a/crates/folds/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@real_single_turn.jsonl.snap+++ b/crates/folds/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@real_single_turn.jsonl.snap@@ -1,7 +1,7 @@----source: crates/agent_fold/src/domain/test/real_recordings.rs+source: crates/folds/agent_fold/src/domain/test/real_recordings.rsexpression: messages-input_file: crates/agent_fold/fixtures/real/real_single_turn.jsonl+input_file: crates/folds/agent_fold/fixtures/real/real_single_turn.jsonl---[FoldedMessage {@@ -27,6 +27,7 @@ input_file: crates/agent_fold/fixtures/real/real_single_turn.jsonl},stop: None,pending: false,+ posted_at: None,},FoldedMessage {id: TurnId(@@ -45,5 +46,6 @@ input_file: crates/agent_fold/fixtures/real/real_single_turn.jsonlEndTurn,),pending: false,+ posted_at: None,},]diff --git a/crates/folds/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@resumed_and_continued.jsonl.snap b/crates/folds/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@resumed_and_continued.jsonl.snapindex edf992a350..71f420a826 100644--- a/crates/folds/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@resumed_and_continued.jsonl.snap+++ b/crates/folds/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@resumed_and_continued.jsonl.snap@@ -1,7 +1,7 @@----source: crates/agent_fold/src/domain/test/real_recordings.rs+source: crates/folds/agent_fold/src/domain/test/real_recordings.rsexpression: messages-input_file: crates/agent_fold/fixtures/real/resumed_and_continued.jsonl+input_file: crates/folds/agent_fold/fixtures/real/resumed_and_continued.jsonl---[FoldedMessage {@@ -21,6 +21,7 @@ input_file: crates/agent_fold/fixtures/real/resumed_and_continued.jsonl},stop: None,pending: false,+ posted_at: None,},FoldedMessage {id: TurnId(@@ -268,6 +269,7 @@ input_file: crates/agent_fold/fixtures/real/resumed_and_continued.jsonlEndTurn,),pending: false,+ posted_at: None,},FoldedMessage {id: TurnId(@@ -286,6 +288,7 @@ input_file: crates/agent_fold/fixtures/real/resumed_and_continued.jsonl},stop: None,pending: false,+ posted_at: None,},FoldedMessage {id: TurnId(@@ -302,6 +305,7 @@ input_file: crates/agent_fold/fixtures/real/resumed_and_continued.jsonl},stop: None,pending: false,+ posted_at: None,},FoldedMessage {id: TurnId(@@ -326,6 +330,7 @@ input_file: crates/agent_fold/fixtures/real/resumed_and_continued.jsonl},stop: None,pending: false,+ posted_at: None,},FoldedMessage {id: TurnId(@@ -344,6 +349,7 @@ input_file: crates/agent_fold/fixtures/real/resumed_and_continued.jsonlEndTurn,),pending: false,+ posted_at: None,},FoldedMessage {id: TurnId(@@ -368,6 +374,7 @@ input_file: crates/agent_fold/fixtures/real/resumed_and_continued.jsonl},stop: None,pending: false,+ posted_at: None,},FoldedMessage {id: TurnId(@@ -439,6 +446,7 @@ input_file: crates/agent_fold/fixtures/real/resumed_and_continued.jsonlEndTurn,),pending: false,+ posted_at: None,},FoldedMessage {id: TurnId(@@ -463,6 +471,7 @@ input_file: crates/agent_fold/fixtures/real/resumed_and_continued.jsonl},stop: None,pending: false,+ posted_at: None,},FoldedMessage {id: TurnId(@@ -687,5 +696,6 @@ input_file: crates/agent_fold/fixtures/real/resumed_and_continued.jsonlEndTurn,),pending: false,+ posted_at: None,},]diff --git a/crates/folds/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@resumed_no_prompt.jsonl.snap b/crates/folds/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@resumed_no_prompt.jsonl.snapindex bbdcb049d9..c925b3bebc 100644--- a/crates/folds/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@resumed_no_prompt.jsonl.snap+++ b/crates/folds/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@resumed_no_prompt.jsonl.snap@@ -1,8 +1,7 @@----source: crates/agent_fold/src/domain/test/real_recordings.rs-assertion_line: 244+source: crates/folds/agent_fold/src/domain/test/real_recordings.rsexpression: messages-input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl+input_file: crates/folds/agent_fold/fixtures/real/resumed_no_prompt.jsonl---[FoldedMessage {@@ -22,6 +21,7 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl},stop: None,pending: false,+ posted_at: None,},FoldedMessage {id: TurnId(@@ -483,6 +483,7 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonlEndTurn,),pending: false,+ posted_at: None,},FoldedMessage {id: TurnId(@@ -501,6 +502,7 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl},stop: None,pending: false,+ posted_at: None,},FoldedMessage {id: TurnId(@@ -632,6 +634,7 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonlEndTurn,),pending: false,+ posted_at: None,},FoldedMessage {id: TurnId(@@ -650,6 +653,7 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl},stop: None,pending: false,+ posted_at: None,},FoldedMessage {id: TurnId(@@ -834,6 +838,7 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonlEndTurn,),pending: false,+ posted_at: None,},FoldedMessage {id: TurnId(@@ -852,6 +857,7 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl},stop: None,pending: false,+ posted_at: None,},FoldedMessage {id: TurnId(@@ -1919,6 +1925,7 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonlEndTurn,),pending: false,+ posted_at: None,},FoldedMessage {id: TurnId(@@ -1937,6 +1944,7 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl},stop: None,pending: false,+ posted_at: None,},FoldedMessage {id: TurnId(@@ -2744,6 +2752,7 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonlEndTurn,),pending: false,+ posted_at: None,},FoldedMessage {id: TurnId(@@ -2762,6 +2771,7 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl},stop: None,pending: false,+ posted_at: None,},FoldedMessage {id: TurnId(@@ -3654,6 +3664,7 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl},stop: None,pending: false,+ posted_at: None,},FoldedMessage {id: TurnId(@@ -3680,6 +3691,7 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl},stop: None,pending: false,+ posted_at: None,},FoldedMessage {id: TurnId(@@ -3705,6 +3717,7 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl},stop: None,pending: false,+ posted_at: None,},FoldedMessage {id: TurnId(@@ -3731,5 +3744,6 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl},stop: None,pending: false,+ posted_at: None,},]diff --git a/crates/folds/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@subagent_claude_code.jsonl.snap b/crates/folds/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@subagent_claude_code.jsonl.snapindex b072f40511..d2e1b02aa5 100644--- a/crates/folds/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@subagent_claude_code.jsonl.snap+++ b/crates/folds/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@subagent_claude_code.jsonl.snap@@ -1,7 +1,7 @@----source: crates/agent_fold/src/domain/test/real_recordings.rs+source: crates/folds/agent_fold/src/domain/test/real_recordings.rsexpression: messages-input_file: crates/agent_fold/fixtures/real/subagent_claude_code.jsonl+input_file: crates/folds/agent_fold/fixtures/real/subagent_claude_code.jsonl---[FoldedMessage {@@ -28,6 +28,7 @@ input_file: crates/agent_fold/fixtures/real/subagent_claude_code.jsonl},stop: None,pending: false,+ posted_at: None,},FoldedMessage {id: TurnId(@@ -52,6 +53,7 @@ input_file: crates/agent_fold/fixtures/real/subagent_claude_code.jsonl},stop: None,pending: false,+ posted_at: None,},FoldedMessage {id: TurnId(@@ -150,5 +152,6 @@ input_file: crates/agent_fold/fixtures/real/subagent_claude_code.jsonlEndTurn,),pending: false,+ posted_at: None,},]diff --git a/crates/folds/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@subagent_cursor.jsonl.snap b/crates/folds/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@subagent_cursor.jsonl.snapindex 274aa8c7b2..33ec2c20ad 100644--- a/crates/folds/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@subagent_cursor.jsonl.snap+++ b/crates/folds/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@subagent_cursor.jsonl.snap@@ -1,7 +1,7 @@----source: crates/agent_fold/src/domain/test/real_recordings.rs+source: crates/folds/agent_fold/src/domain/test/real_recordings.rsexpression: messages-input_file: crates/agent_fold/fixtures/real/subagent_cursor.jsonl+input_file: crates/folds/agent_fold/fixtures/real/subagent_cursor.jsonl---[FoldedMessage {@@ -23,6 +23,7 @@ input_file: crates/agent_fold/fixtures/real/subagent_cursor.jsonl},stop: None,pending: false,+ posted_at: None,},FoldedMessage {id: TurnId(@@ -145,5 +146,6 @@ input_file: crates/agent_fold/fixtures/real/subagent_cursor.jsonlEndTurn,),pending: false,+ posted_at: None,},]diff --git a/crates/folds/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@subagent_macro_inmem.jsonl.snap b/crates/folds/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@subagent_macro_inmem.jsonl.snapindex 36ec808f65..fd331f8f36 100644--- a/crates/folds/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@subagent_macro_inmem.jsonl.snap+++ b/crates/folds/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@subagent_macro_inmem.jsonl.snap@@ -1,7 +1,7 @@----source: crates/agent_fold/src/domain/test/real_recordings.rs+source: crates/folds/agent_fold/src/domain/test/real_recordings.rsexpression: messages-input_file: crates/agent_fold/fixtures/real/subagent_macro_inmem.jsonl+input_file: crates/folds/agent_fold/fixtures/real/subagent_macro_inmem.jsonl---[FoldedMessage {@@ -23,6 +23,7 @@ input_file: crates/agent_fold/fixtures/real/subagent_macro_inmem.jsonl},stop: None,pending: false,+ posted_at: None,},FoldedMessage {id: TurnId(@@ -80,5 +81,6 @@ input_file: crates/agent_fold/fixtures/real/subagent_macro_inmem.jsonlEndTurn,),pending: false,+ posted_at: None,},]diff --git a/crates/folds/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@subagent_opencode.jsonl.snap b/crates/folds/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@subagent_opencode.jsonl.snapindex d15387777f..eb2199d0c4 100644--- a/crates/folds/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@subagent_opencode.jsonl.snap+++ b/crates/folds/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@subagent_opencode.jsonl.snap@@ -1,7 +1,7 @@----source: crates/agent_fold/src/domain/test/real_recordings.rs+source: crates/folds/agent_fold/src/domain/test/real_recordings.rsexpression: messages-input_file: crates/agent_fold/fixtures/real/subagent_opencode.jsonl+input_file: crates/folds/agent_fold/fixtures/real/subagent_opencode.jsonl---[FoldedMessage {@@ -27,6 +27,7 @@ input_file: crates/agent_fold/fixtures/real/subagent_opencode.jsonl},stop: None,pending: false,+ posted_at: None,},FoldedMessage {id: TurnId(@@ -86,5 +87,6 @@ input_file: crates/agent_fold/fixtures/real/subagent_opencode.jsonlEndTurn,),pending: false,+ posted_at: None,},]diff --git a/crates/folds/agent_fold/src/inbound/wasm.rs b/crates/folds/agent_fold/src/inbound/wasm.rsindex 4b9955b3d7..4a4aab5bd4 100644--- a/crates/folds/agent_fold/src/inbound/wasm.rs+++ b/crates/folds/agent_fold/src/inbound/wasm.rs@@ -173,11 +173,11 @@ impl WireInput {Ok(match self {Self::Snapshot { rows } => FoldInput::Snapshot(rows.into_iter()- .map(|row| (row.cursor, row.frame.into_log(session)))+ .map(|row| (row.cursor, row.frame.into_log(session, row.cursor))).collect(),),Self::Confirmed { row } => {- FoldInput::Confirmed(row.cursor, row.frame.into_log(session))+ FoldInput::Confirmed(row.cursor, row.frame.into_log(session, row.cursor))}Self::Speculated {action_id,@@ -212,7 +212,7 @@ struct DurableEntry {}impl LogEntry {- fn into_log(self, session: AgentSessionId) -> AgentSessionLog {+ fn into_log(self, session: AgentSessionId, cursor: LogCursor) -> AgentSessionLog {AgentSessionLog {agent_session_id: session,// A user id that will not parse is dropped rather than rejected:@@ -222,6 +222,7 @@ impl LogEntry {.user_id.and_then(|id| MacroUserIdStr::try_from(id).ok()),content: self.message,+ logged_at: Some(cursor.created_at),}}}diff --git a/crates/folds/agent_fold/src/inbound/wire.rs b/crates/folds/agent_fold/src/inbound/wire.rsindex a2886c48f1..32eeb22c37 100644--- a/crates/folds/agent_fold/src/inbound/wire.rs+++ b/crates/folds/agent_fold/src/inbound/wire.rs@@ -48,6 +48,10 @@ pub struct FoldedMessage {/// What an agent's unfinished reply is doing now; absent once its turn/// has ended and on a user's message.phase: Option<TurnPhase>,+ /// When a user's prompt was posted, RFC 3339. Absent on agent and control+ /// messages, until the log confirms a prompt, and on history a runtime+ /// replayed on load.+ posted_at: Option<String>,}impl FoldedMessage {@@ -74,6 +78,7 @@ impl FoldedMessage {pending: message.pending,segments,phase,+ posted_at: message.posted_at.map(|at| at.to_rfc3339()),}}}diff --git a/crates/folds/agent_fold/src/inbound/wire/test.rs b/crates/folds/agent_fold/src/inbound/wire/test.rsindex eb67c17340..8d0857451f 100644--- a/crates/folds/agent_fold/src/inbound/wire/test.rs+++ b/crates/folds/agent_fold/src/inbound/wire/test.rs@@ -24,6 +24,7 @@ fn domain_parts_serialize_directly_into_the_browser_contract() {}),stop: None,pending: false,+ posted_at: None,};let session = AgentSessionId::new_from_uuid(macro_uuid::Uuid::from_u128(7));@@ -61,7 +62,8 @@ fn domain_parts_serialize_directly_into_the_browser_contract() {"status": "running"}]}],- "phase": "working"+ "phase": "working",+ "postedAt": null}));@@ -127,3 +129,24 @@ fn empty_replacement_is_an_explicit_browser_event() {json!({"kind":"replace", "messages":[]}));}++#[test]+fn a_prompt_carries_when_it_was_posted() {+ let message = ModelFoldedMessage {+ id: TurnId(0),+ author: Author::User { user_id: None },+ request_id: None,+ parts: NonEmpty::one(MessagePart::Text {+ text: "tighten the fold".to_owned(),+ }),+ stop: None,+ pending: false,+ posted_at: Some("2026-10-15T14:02:00Z".parse().unwrap()),+ };+ let session = AgentSessionId::new_from_uuid(macro_uuid::Uuid::from_u128(7));++ assert_eq!(+ serde_json::to_value(FoldedMessage::new(session, message)).unwrap()["postedAt"],+ json!("2026-10-15T14:02:00+00:00")+ );+}diff --git a/crates/folds/agent_fold/src/testing.rs b/crates/folds/agent_fold/src/testing.rsindex bf70ee8bc8..ca1bd005fc 100644--- a/crates/folds/agent_fold/src/testing.rs+++ b/crates/folds/agent_fold/src/testing.rs@@ -120,6 +120,7 @@ fn parse_line(session: AgentSessionId, line: &str) -> AgentSessionLog {MacroUserIdStr::try_from_email("[email protected]").expect("test email parses")}),content,+ logged_at: None,}}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.snapindex 7df151ed9c..79be544e50 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@@ -17,7 +17,8 @@ expression: messages}],"stop": null,- "pending": false+ "pending": false,+ "postedAt": null},{"turn": 0,@@ -51,7 +52,8 @@ expression: messages"stop": {"kind": "end_turn"},- "pending": false+ "pending": false,+ "postedAt": null},{"turn": 1,@@ -67,7 +69,8 @@ expression: messages}],"stop": null,- "pending": false+ "pending": false,+ "postedAt": null},{"turn": 1,@@ -84,6 +87,7 @@ expression: messages"stop": {"kind": "end_turn"},- "pending": false+ "pending": false,+ "postedAt": null}]diff --git a/crates/folds/codex_fold/src/snapshots/codex_fold__test__api_messages_snapshot.snap b/crates/folds/codex_fold/src/snapshots/codex_fold__test__api_messages_snapshot.snapindex 83ed840a4c..5bf7bac198 100644--- a/crates/folds/codex_fold/src/snapshots/codex_fold__test__api_messages_snapshot.snap+++ b/crates/folds/codex_fold/src/snapshots/codex_fold__test__api_messages_snapshot.snap@@ -17,7 +17,8 @@ expression: messages}],"stop": null,- "pending": false+ "pending": false,+ "postedAt": null},{"turn": 0,@@ -97,7 +98,8 @@ expression: messages"stop": {"kind": "end_turn"},- "pending": false+ "pending": false,+ "postedAt": null},{"turn": 1,@@ -113,7 +115,8 @@ expression: messages}],"stop": null,- "pending": false+ "pending": false,+ "postedAt": null},{"turn": 1,@@ -130,6 +133,7 @@ expression: messages"stop": {"kind": "cancelled"},- "pending": false+ "pending": false,+ "postedAt": null}]diff --git a/docs/agent-guide/ai-chat.md b/docs/agent-guide/ai-chat.mdindex e8d0999f8b..486dde574a 100644--- a/docs/agent-guide/ai-chat.md+++ b/docs/agent-guide/ai-chat.md@@ -5,6 +5,15 @@ User-sent messages in chat and agent transcripts use an ink-colored bubble withlighter bubble with the normal text palette. Preview Markdown and controls at`/app/debug/ui?ui=invert-util` under **User-sent AI message**.+A prompt shows a quiet line under its bubble (`data-testid="prompt-footer"`):+when it was posted, and, for a prompt delivered from elsewhere (a mention, a+follow-up in a discussion, an assigned task, a handoff, a routine run), where+it came from, such as `via @mention in #eng · 2:02 PM`. A prompt typed in the+session shows only its time. Click the origin to open that place: the message+in its channel or comment thread, the task, the email, the call, the routine,+or the session that handed the work off. The context the agent was given stays+hidden. A prompt still sending shows no line until the log confirms it.+## Connecting an app from an agent sessionWhen existing tools cannot handle a request, agent sessions can use