Skip to content

armgit / macro

Public Imported from GitHub
0

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

feat(agents): measure first readable answer in the transcript (#7583)

Wolf Mermelsteinc631b0e2b8ed
diff --git a/apps/web/src/features/agents-view/mobile-agent-composer.tsx b/apps/web/src/features/agents-view/mobile-agent-composer.tsx
index 88b8764bcb..a287f5f376 100644
--- a/apps/web/src/features/agents-view/mobile-agent-composer.tsx
+++ b/apps/web/src/features/agents-view/mobile-agent-composer.tsx
@@ -13,7 +13,11 @@ function Composer() {
const layout = useSplitLayout();
const userId = useUserId();
const start = (conversation: StartConversation) => {
- const id = startPendingSession({ ...conversation, userId: userId() });
+ const id = startPendingSession({
+ ...conversation,
+ userId: userId(),
+ submitSurface: 'mobile_composer',
+ });
layout.openWithSplit({ type: 'agent', id }, { referredFrom: 'agents' });
};
return (
diff --git a/apps/web/src/features/agents-view/views/AgentsView.tsx b/apps/web/src/features/agents-view/views/AgentsView.tsx
index 2182f3a110..dd702b46b6 100644
--- a/apps/web/src/features/agents-view/views/AgentsView.tsx
+++ b/apps/web/src/features/agents-view/views/AgentsView.tsx
@@ -253,6 +253,7 @@ function AgentsWorkspace(props: { initialRoute?: AgentsRoute }) {
const id = startPendingSession({
...start,
userId: userId(),
+ submitSurface: 'agents',
});
openConversation(
{ id, type: 'agent_session' },
diff --git a/apps/web/src/features/block-agent/agent-session-provider.tsx b/apps/web/src/features/block-agent/agent-session-provider.tsx
index 557203bbb7..700f2828f4 100644
--- a/apps/web/src/features/block-agent/agent-session-provider.tsx
+++ b/apps/web/src/features/block-agent/agent-session-provider.tsx
@@ -1,5 +1,6 @@
/** App-facing composition for the agent session and its controllers. */
+import { AgentSession } from '@core/agent-session/AgentSession';
import { toast } from '@core/component/Toast/Toast';
import { isCodexBotId } from '@core/constant/codexAgent';
import { isCursorBotId } from '@core/constant/cursorAgent';
@@ -168,6 +169,10 @@ export function AgentSessionProvider(
bot: live.bot,
metadata: live.metadata,
messages,
+ observeRenderedText: (id, turn, element) =>
+ id === sessionId()
+ ? AgentSession.get(id)?.observeRenderedText(turn, element)
+ : undefined,
// A create that failed leaves the block with nothing to load, which
// is the same dead end for the reader as a load that failed.
loadFailed: () => live.loadFailed() || failed(),
diff --git a/apps/web/src/features/block-agent/component/AgentMessage.test.tsx b/apps/web/src/features/block-agent/component/AgentMessage.test.tsx
index bb94d0a888..bf5c294bef 100644
--- a/apps/web/src/features/block-agent/component/AgentMessage.test.tsx
+++ b/apps/web/src/features/block-agent/component/AgentMessage.test.tsx
@@ -7,11 +7,19 @@ import type {
MessagePart,
} from '@service-agent-fold/generated/types';
import { cleanup, render } from '@solidjs/testing-library';
-import { createSignal, type JSX } from 'solid-js';
+import { createSignal, type JSX, onMount } from 'solid-js';
import { createStore, reconcile } from 'solid-js/store';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { Message } from './AgentMessage';
+const renderTelemetry = vi.hoisted(() => ({
+ context: vi.fn(),
+ observe: vi.fn(),
+}));
+vi.mock('../context/AgentSessionContext', () => ({
+ useOptionalAgentSession: renderTelemetry.context,
+}));
+
// 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.
@@ -33,7 +41,18 @@ vi.mock('@ui', () => ({
),
}));
vi.mock('./parts/TextPart', () => ({
- TextPart: (props: { text: string }) => <p data-testid="text">{props.text}</p>,
+ TextPart: (props: {
+ text: string;
+ observeRender?: (element: HTMLElement) => void;
+ }) => {
+ let element!: HTMLParagraphElement;
+ onMount(() => props.observeRender?.(element));
+ return (
+ <p ref={element} data-testid="text">
+ {props.text}
+ </p>
+ );
+ },
}));
vi.mock('./parts/ToolCallPart', () => ({
ToolCallPart: (props: {
@@ -110,6 +129,8 @@ vi.mock('../views/LiveToolGroup', () => ({
afterEach(() => {
viewerId.current = 'macro|[email protected]';
+ renderTelemetry.context.mockReset();
+ renderTelemetry.observe.mockReset();
cleanup();
});
@@ -146,6 +167,29 @@ const message = (
});
describe('Message tool grouping', () => {
+ it('observes only agent answer DOM on the existing session and matching turn', () => {
+ renderTelemetry.context.mockReturnValue({
+ observeRenderedText: renderTelemetry.observe,
+ });
+ const answer = message([text('Hello')]);
+ answer.turn = 3;
+ render(() => <Message message={answer} inFlight />);
+ expect(renderTelemetry.observe).toHaveBeenCalledExactlyOnceWith(
+ 'session',
+ 3,
+ expect.any(HTMLElement)
+ );
+ cleanup();
+ renderTelemetry.observe.mockClear();
+ render(() => (
+ <Message
+ message={{ ...answer, author: { kind: 'user', userId: null } }}
+ inFlight={false}
+ />
+ ));
+ expect(renderTelemetry.observe).not.toHaveBeenCalled();
+ });
+
it('folds consecutive tool calls into one group, keeping their indices', () => {
const view = render(() => (
<Message
diff --git a/apps/web/src/features/block-agent/component/AgentMessage.tsx b/apps/web/src/features/block-agent/component/AgentMessage.tsx
index d9638cbf53..dd165e8935 100644
--- a/apps/web/src/features/block-agent/component/AgentMessage.tsx
+++ b/apps/web/src/features/block-agent/component/AgentMessage.tsx
@@ -20,6 +20,7 @@ import type {
import { UserMessageBubble } from '@ui';
import { For, Index, type JSX, Match, Show, Switch } from 'solid-js';
import { match } from 'ts-pattern';
+import { useOptionalAgentSession } from '../context/AgentSessionContext';
import { isControlMessage } from '../state/control-message';
import { isNotificationMessage } from '../state/notification-message';
import { thoughtIsStreaming } from '../state/thought-streaming';
@@ -58,12 +59,28 @@ function AgentMessagePart(props: {
/** The turn is still in flight — the tail thought reads "Thinking". */
inFlight: boolean;
}): JSX.Element {
+ const session = useOptionalAgentSession();
// Match accessors keep a part's renderer mounted when a streamed snapshot
// replaces the object, preserving disclosures while updating their contents.
return (
<Switch>
<Match when={props.part.kind === 'text' && props.part}>
- {(part) => <TextPart text={part().text} inFlight={props.inFlight} />}
+ {(part) => (
+ <TextPart
+ text={part().text}
+ inFlight={props.inFlight}
+ observeRender={
+ props.message.author.kind === 'agent'
+ ? (element) =>
+ session?.observeRenderedText?.(
+ props.message.agentSessionId,
+ props.message.turn,
+ element
+ )
+ : undefined
+ }
+ />
+ )}
</Match>
<Match when={props.part.kind === 'attachment' && props.part}>
{(part) => <AttachmentPart part={part()} />}
diff --git a/apps/web/src/features/block-agent/component/parts/TextPart.test.tsx b/apps/web/src/features/block-agent/component/parts/TextPart.test.tsx
index 3632d8cff0..41416ceae0 100644
--- a/apps/web/src/features/block-agent/component/parts/TextPart.test.tsx
+++ b/apps/web/src/features/block-agent/component/parts/TextPart.test.tsx
@@ -29,6 +29,21 @@ vi.mock('@core/component/LexicalMarkdown/theme', () => ({
}));
describe('TextPart', () => {
+ it('hands mounted markdown DOM to its observer and cleans up when unmounted', () => {
+ const stop = vi.fn();
+ const observe = vi.fn((element: HTMLElement) => {
+ expect(element.isConnected).toBe(true);
+ expect(element.classList.contains('chat-markdown-container')).toBe(true);
+ return stop;
+ });
+ const view = render(() => (
+ <TextPart text="Hello" observeRender={observe} />
+ ));
+ expect(observe).toHaveBeenCalledOnce();
+ view.unmount();
+ expect(stop).toHaveBeenCalledOnce();
+ });
+
it('does not re-render unchanged markdown when inFlight flips', () => {
parses.length = 0;
const [inFlight, setInFlight] = createSignal(false);
diff --git a/apps/web/src/features/block-agent/component/parts/TextPart.tsx b/apps/web/src/features/block-agent/component/parts/TextPart.tsx
index b1c5509673..fe147f2c4e 100644
--- a/apps/web/src/features/block-agent/component/parts/TextPart.tsx
+++ b/apps/web/src/features/block-agent/component/parts/TextPart.tsx
@@ -2,20 +2,32 @@
import { StaticMarkdown } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';
import { channelTheme } from '@core/component/LexicalMarkdown/theme';
-import { createMemo } from 'solid-js';
+import { createMemo, onCleanup, onMount } from 'solid-js';
import { hideIncompleteMacroXml } from './hideIncompleteMacroXml';
-export function TextPart(props: { text: string; inFlight?: boolean }) {
+export function TextPart(props: {
+ text: string;
+ inFlight?: boolean;
+ observeRender?: (element: HTMLElement) => (() => void) | undefined;
+}) {
// Memoized so an `inFlight` flip that leaves the text unchanged does not
// rebuild the markdown DOM and reload its images.
const markdown = createMemo(() =>
props.inFlight ? hideIncompleteMacroXml(props.text) : props.text
);
+ let content!: HTMLDivElement;
+ onMount(() => {
+ const stop = props.observeRender?.(content);
+ if (stop) onCleanup(stop);
+ });
return (
// `chat-markdown-container` is the overflow host for KaTeX display math
// (see index.css).
- <div class="chat-markdown-container whitespace-pre-wrap wrap-break-word max-w-full text-base">
+ <div
+ ref={content}
+ class="chat-markdown-container whitespace-pre-wrap wrap-break-word max-w-full text-base"
+ >
<StaticMarkdown
markdown={markdown()}
theme={channelTheme}
diff --git a/apps/web/src/features/block-agent/context/AgentSessionContext.tsx b/apps/web/src/features/block-agent/context/AgentSessionContext.tsx
index d59e5a3433..33251c8524 100644
--- a/apps/web/src/features/block-agent/context/AgentSessionContext.tsx
+++ b/apps/web/src/features/block-agent/context/AgentSessionContext.tsx
@@ -41,6 +41,12 @@ export type AgentSessionState = {
metadata: Accessor<SessionMetadata | undefined>;
/** The folded transcript, ordered by turn, live-following the session. */
messages: Accessor<FoldedMessage[]>;
+ /** Optional in galleries/replays; production reports actual answer rendering. */
+ observeRenderedText?: (
+ sessionId: string,
+ turn: number,
+ element: HTMLElement
+ ) => (() => void) | undefined;
loadFailed: Accessor<boolean>;
/** The load failed because the viewer is not a participant (401/403). */
accessDenied: Accessor<boolean>;
diff --git a/apps/web/src/features/block-agent/context/pending-session.ts b/apps/web/src/features/block-agent/context/pending-session.ts
index e82e4ab698..2fe5d364cf 100644
--- a/apps/web/src/features/block-agent/context/pending-session.ts
+++ b/apps/web/src/features/block-agent/context/pending-session.ts
@@ -24,7 +24,10 @@
import { handleAiUsageLimitError } from '@app/features/paywall/ai-usage-limit-handling';
import { AgentSession } from '@core/agent-session/AgentSession';
-import { PromptTrace } from '@core/agent-session/prompt-telemetry';
+import {
+ type PromptSubmitSurface,
+ PromptTrace,
+} from '@core/agent-session/prompt-telemetry';
import {
replenishWarmAgentSession,
takeWarmAgentSession,
@@ -79,6 +82,8 @@ export type StartPendingSessionOptions = {
attachments?: PromptAttachment[];
/** The sender, so the first prompt is attributed as the log will. */
userId?: string;
+ /** The submitting composer, independent of its position in a split layout. */
+ submitSurface?: PromptSubmitSurface;
/** Model to run on instead of the persona's, set as the session is created. */
modelOverride?: string;
/**
@@ -113,7 +118,10 @@ export function startPendingSession(
// and every request on the way, lands in one trace.
const trace =
prompt || options.attachments?.length
- ? new PromptTrace(id, { newSession: true })
+ ? new PromptTrace(id, {
+ newSession: true,
+ submitSurface: options.submitSurface,
+ })
: undefined;
const [sessionId, setSessionId] = createSignal<string>();
const [error, setError] = createSignal<string>();
diff --git a/apps/web/src/features/home/home-agent-composer.test.tsx b/apps/web/src/features/home/home-agent-composer.test.tsx
index 7f2838db75..12edd8e173 100644
--- a/apps/web/src/features/home/home-agent-composer.test.tsx
+++ b/apps/web/src/features/home/home-agent-composer.test.tsx
@@ -89,7 +89,11 @@ it('forwards the shared composer selection into the common session flow', () =>
};
mocks.onStart?.(start);
// The viewer rides along so the first prompt is attributed as the log will.
- expect(mocks.start).toHaveBeenCalledWith({ ...start, userId: 'viewer-1' });
+ expect(mocks.start).toHaveBeenCalledWith({
+ ...start,
+ userId: 'viewer-1',
+ submitSurface: 'home',
+ });
expect(mocks.replace).toHaveBeenCalledWith({
next: { type: 'component', id: 'agents-session~agents~pending-session' },
});
diff --git a/apps/web/src/features/home/home-agent-composer.tsx b/apps/web/src/features/home/home-agent-composer.tsx
index 95fa999fcc..5b17719b96 100644
--- a/apps/web/src/features/home/home-agent-composer.tsx
+++ b/apps/web/src/features/home/home-agent-composer.tsx
@@ -79,7 +79,11 @@ export function HomeAgentComposer(props: { autoFocus?: boolean }) {
},
});
const start = (conversation: StartConversation) => {
- const id = startPendingSession({ ...conversation, userId: userId() });
+ const id = startPendingSession({
+ ...conversation,
+ userId: userId(),
+ submitSurface: 'home',
+ });
panel.handle.replace({
next: {
type: 'component',
diff --git a/apps/web/src/lib/core/agent-session/AgentSession.test.ts b/apps/web/src/lib/core/agent-session/AgentSession.test.ts
index 53a035ce3d..6eca1f18d2 100644
--- a/apps/web/src/lib/core/agent-session/AgentSession.test.ts
+++ b/apps/web/src/lib/core/agent-session/AgentSession.test.ts
@@ -9,7 +9,7 @@ import type { FoldInput } from '@core/agent-fold/client';
import type { FoldedStreamEvent } from '@service-agent-fold/generated/types';
import type { AgentSessionLogEntryDto } from '@service-agent-harness/generated/schemas';
import { err, ok } from 'neverthrow';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { beforeEach, describe, expect, it, onTestFinished, vi } from 'vitest';
const fold = vi.hoisted(() => ({
pushSession: vi.fn(),
@@ -1050,6 +1050,35 @@ describe('AgentSession', () => {
expect(span.ends).toBe(0);
expect(span.attributes['agent.prompt.first_output_part']).toBe('thought');
+ const answer = document.createElement('div');
+ answer.textContent = 'Hello';
+ document.body.append(answer);
+ vi.spyOn(answer, 'getBoundingClientRect').mockReturnValue(
+ new DOMRect(10, 10, 300, 30)
+ );
+ const createRange = document.createRange.bind(document);
+ const ranges = vi
+ .spyOn(document, 'createRange')
+ .mockImplementation(() => {
+ const range = createRange();
+ range.getClientRects = () => {
+ const rects = [
+ range.startContainer.parentElement!.getBoundingClientRect(),
+ ];
+ return Object.assign(rects, {
+ item: (index: number) => rects[index],
+ });
+ };
+ return range;
+ });
+ onTestFinished(() => ranges.mockRestore());
+ const unsubscribe = live.subscribe(() => {
+ // Folding establishes telemetry before that batch mounts the answer UI.
+ expect(span.attributes['agent.prompt.first_text_at_ms']).toEqual(
+ expect.any(Number)
+ );
+ live.observeRenderedText(1, answer);
+ });
fold.pushSession.mockResolvedValueOnce([
{
kind: 'update',
@@ -1069,6 +1098,10 @@ describe('AgentSession', () => {
] satisfies FoldedStreamEvent[]);
AgentSession.ingest({ agentSessionId: SESSION, entries: [row(3)] });
await settle();
+ expect(span.ends).toBe(0);
+ expect(span.attributes['agent.prompt.first_text_rendered_at_ms']).toEqual(
+ expect.any(Number)
+ );
await new Promise((resolve) =>
requestAnimationFrame(() => requestAnimationFrame(resolve))
);
@@ -1087,6 +1120,8 @@ describe('AgentSession', () => {
expect.any(Number)
);
live.release();
+ unsubscribe();
+ answer.remove();
expect(span.ends).toBe(1);
expect(span.attributes['agent.prompt.outcome']).toBe('text');
});
diff --git a/apps/web/src/lib/core/agent-session/AgentSession.ts b/apps/web/src/lib/core/agent-session/AgentSession.ts
index 87de9e6156..0b33e661ca 100644
--- a/apps/web/src/lib/core/agent-session/AgentSession.ts
+++ b/apps/web/src/lib/core/agent-session/AgentSession.ts
@@ -481,6 +481,21 @@ export class AgentSession {
return this.chain.then(() => readSession(this.id));
}
+ /** Observe mounted answer DOM only while this tab awaits that prompt's paint. */
+ observeRenderedText(
+ turn: number,
+ element: HTMLElement
+ ): (() => void) | undefined {
+ const stops = [...this.prompts].flatMap((prompt) => {
+ const stop = prompt.observeRenderedText(turn, element);
+ return stop ? [stop] : [];
+ });
+ if (stops.length === 0) return;
+ return () => {
+ for (const stop of stops) stop();
+ };
+ }
+
release(): void {
this.references -= 1;
if (this.references > 0) return;
@@ -694,11 +709,11 @@ export class AgentSession {
if (this.closed || events.length === 0) return;
const metadata = events.findLast((event) => event.kind === 'metadata');
if (metadata) this.setTurn(metadata.metadata.turn);
- for (const listener of this.listeners) listener(events);
for (const prompt of this.prompts) {
prompt.observe(events, delivery);
if (prompt.ended) this.prompts.delete(prompt);
}
+ for (const listener of this.listeners) listener(events);
});
// A failed push must not poison the chain for every input after it.
this.chain = run.catch((error: unknown) => {
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.ts
index f4ff840555..e73669d01c 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
@@ -54,15 +54,172 @@ const ACTION = '01a0abed-3000-7000-8000-000000000001';
beforeEach(() => {
telemetry.spans.length = 0;
+ vi.stubGlobal('IntersectionObserver', undefined);
+ vi.stubGlobal('requestAnimationFrame', (callback: () => void) =>
+ setTimeout(callback, 16)
+ );
+ vi.stubGlobal('cancelAnimationFrame', clearTimeout);
+ vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockReturnValue(
+ new DOMRect(10, 10, 300, 30)
+ );
+ const createRange = document.createRange.bind(document);
+ vi.spyOn(document, 'createRange').mockImplementation(() => {
+ const range = createRange();
+ range.getClientRects = () => {
+ const rects = [
+ range.startContainer.parentElement!.getBoundingClientRect(),
+ ];
+ return Object.assign(rects, { item: (index: number) => rects[index] });
+ };
+ return range;
+ });
});
afterEach(() => {
vi.useRealTimers();
vi.unstubAllGlobals();
vi.restoreAllMocks();
+ document.body.replaceChildren();
+ history.replaceState(null, '', '/');
});
+function withText(text = 'Hello'): PromptTrace {
+ const trace = new PromptTrace(SESSION, { newSession: true });
+ trace.expect(ACTION);
+ trace.observe([
+ {
+ kind: 'new',
+ message: {
+ agentSessionId: SESSION,
+ turn: 1,
+ author: { kind: 'user', userId: null },
+ requestId: ACTION,
+ parts: [{ kind: 'text', text: 'Question' }],
+ stop: null,
+ pending: false,
+ },
+ },
+ {
+ kind: 'new',
+ message: {
+ agentSessionId: SESSION,
+ turn: 1,
+ author: { kind: 'agent' },
+ requestId: null,
+ parts: [{ kind: 'text', text }],
+ stop: null,
+ pending: false,
+ },
+ },
+ ]);
+ return trace;
+}
+
describe('PromptTrace', () => {
+ it('keeps raw text and actual readable paint separate', async () => {
+ vi.useFakeTimers();
+ const trace = withText('**');
+ const element = document.createElement('div');
+ element.textContent = '**';
+ document.body.append(element);
+ trace.observeRenderedText(1, element);
+ vi.advanceTimersByTime(32);
+ const [span] = telemetry.spans;
+ expect(span.attributes).toHaveProperty('agent.prompt.first_text_at_ms');
+ expect(span.attributes).not.toHaveProperty(
+ 'agent.prompt.first_text_paint_at_ms'
+ );
+ expect(trace.ended).toBe(false);
+
+ element.textContent = 'Readable answer';
+ await Promise.resolve();
+ vi.advanceTimersByTime(32);
+ expect(span.attributes['agent.prompt.outcome']).toBe('text');
+ expect(span.attributes['agent.prompt.first_text_paint_at_ms']).toBe(64);
+ expect(JSON.stringify(span)).not.toContain('Readable answer');
+ });
+
+ it('reports raw text without a transcript as not rendered', () => {
+ vi.useFakeTimers();
+ const trace = withText();
+ vi.advanceTimersByTime(32);
+ expect(trace.ended).toBe(false);
+ vi.advanceTimersByTime(10_000);
+ expect(telemetry.spans[0].attributes).toMatchObject({
+ 'agent.prompt.outcome': 'not_rendered',
+ 'agent.prompt.renderer_mounted': false,
+ 'agent.prompt.renderer_attached': false,
+ });
+ });
+
+ it('cannot finish from a different turn, and records an unmounted renderer explicitly', () => {
+ vi.useFakeTimers();
+ const trace = withText();
+ const element = document.createElement('div');
+ element.textContent = 'Hello';
+ document.body.append(element);
+ expect(trace.observeRenderedText(2, element)).toBeUndefined();
+ vi.advanceTimersByTime(32);
+ expect(trace.ended).toBe(false);
+
+ const stop = trace.observeRenderedText(1, element);
+ stop?.();
+ element.remove();
+ vi.advanceTimersByTime(10_000);
+ expect(telemetry.spans[0].attributes).toMatchObject({
+ 'agent.prompt.outcome': 'not_rendered',
+ 'agent.prompt.renderer_mounted': true,
+ 'agent.prompt.renderer_attached': false,
+ });
+ expect(telemetry.spans[0].attributes).not.toHaveProperty(
+ 'agent.prompt.first_text_paint_at_ms'
+ );
+ });
+
+ it.each([
+ ['/app/md/private-document-id', 'document'],
+ ['/app/drive/md/private-document-id', 'document'],
+ ['/app/drive/shared/pdf/private-document-id', 'document'],
+ [
+ '/app/drive/folder/private-folder-id/code/private-document-id',
+ 'document',
+ ],
+ ['/app/drive/folder/private-folder-id', 'drive'],
+ ['/app/drive', 'drive'],
+ ['/app/home', 'home'],
+ ['/app/agents', 'agents'],
+ ['/app/search', 'search'],
+ ['/app/drive/md/private-document-id/~/home', 'other'],
+ ])('records only a bounded submit surface for %s', (path, surface) => {
+ history.replaceState(null, '', path);
+ const trace = new PromptTrace(SESSION, { newSession: true });
+ trace.end('released');
+ expect(telemetry.spans[0].attributes['agent.prompt.submit_surface']).toBe(
+ surface
+ );
+ expect(JSON.stringify(telemetry.spans[0])).not.toContain('private-');
+ });
+
+ it.each(['home', 'agents', 'mobile_composer'] as const)(
+ 'uses the submitting %s composer instead of another split pane',
+ (submitSurface) => {
+ history.replaceState(
+ null,
+ '',
+ '/app/drive/md/private-document-id/~/home/~/agents'
+ );
+ const trace = new PromptTrace(SESSION, {
+ newSession: true,
+ submitSurface,
+ });
+ trace.end('released');
+ expect(telemetry.spans[0].attributes['agent.prompt.submit_surface']).toBe(
+ submitSurface
+ );
+ expect(JSON.stringify(telemetry.spans[0])).not.toContain('private-');
+ }
+ );
+
it('records the prompt from acceptance through confirmation to the first painted text', () => {
vi.useFakeTimers();
vi.stubGlobal('requestAnimationFrame', (callback: () => void) =>
@@ -119,6 +276,10 @@ describe('PromptTrace', () => {
trace.observe(output);
trace.observe(output);
expect(trace.ended).toBe(false);
+ const answer = document.createElement('div');
+ answer.textContent = 'hello';
+ document.body.append(answer);
+ trace.observeRenderedText(1, answer);
vi.advanceTimersByTime(32);
expect(telemetry.spans).toHaveLength(1);
@@ -139,6 +300,8 @@ describe('PromptTrace', () => {
'confirmed',
'first_output',
'first_text',
+ 'text_mounted',
+ 'first_text_rendered',
'first_text_paint',
]) {
expect(span.attributes[`agent.prompt.${stage}_at_ms`]).toEqual(
@@ -153,6 +316,8 @@ describe('PromptTrace', () => {
'agent.prompt.confirmed',
'agent.prompt.first_output',
'agent.prompt.first_text',
+ 'agent.prompt.text_mounted',
+ 'agent.prompt.first_text_rendered',
'agent.prompt.first_text_paint',
]);
expect(trace.ended).toBe(true);
@@ -249,7 +414,7 @@ describe('PromptTrace', () => {
'agent.prompt.first_text_delivery_ms': 50,
'agent.prompt.first_text_fold_ms': 0,
'agent.prompt.hidden': true,
- 'agent.prompt.outcome': 'text',
+ 'agent.prompt.outcome': 'hidden',
});
expect(span.attributes).not.toHaveProperty(
'agent.prompt.first_text_paint_at_ms'
diff --git a/apps/web/src/lib/core/agent-session/prompt-telemetry.ts b/apps/web/src/lib/core/agent-session/prompt-telemetry.ts
index 6f9ff13206..a0a41541d4 100644
--- a/apps/web/src/lib/core/agent-session/prompt-telemetry.ts
+++ b/apps/web/src/lib/core/agent-session/prompt-telemetry.ts
@@ -19,6 +19,7 @@ import type {
FoldedStreamEvent,
} from '@service-agent-fold/generated/types';
import { match } from 'ts-pattern';
+import { observeRenderedAnswer } from './render-telemetry';
/** How a sent prompt ended, as far as this span is concerned. */
export type PromptOutcome =
@@ -32,6 +33,10 @@ export type PromptOutcome =
| 'failed'
/** Every holder released the session before any output arrived. */
| 'released'
+ /** The document was hidden before a readable answer could paint. */
+ | 'hidden'
+ /** Raw text arrived but no visible renderer confirmed it before the deadline. */
+ | 'not_rendered'
/** Still waiting at {@link STALL_THRESHOLD_MS} — reported, not concluded. */
| 'stalled';
@@ -51,7 +56,11 @@ export type PromptStage =
| 'first_output'
/** The turn's first agent text was folded. */
| 'first_text'
- /** The frame after the first text was folded: what a person saw. */
+ /** A renderer for the matching answer mounted. */
+ | 'text_mounted'
+ /** Readable answer text was present in visible transcript DOM. */
+ | 'first_text_rendered'
+ /** That visible DOM remained readable across a paint boundary. */
| 'first_text_paint';
/**
@@ -87,11 +96,29 @@ export function frameDelivery(
* exports once it ends.
*/
const STALL_THRESHOLD_MS = 5 * 60_000;
+const RENDER_TIMEOUT_MS = 10_000;
type Attributes = Record<string, string | number | boolean>;
+/** Bounded UI origins supplied by the composer that submits the prompt. */
+export type PromptSubmitSurface =
+ | 'home'
+ | 'agents'
+ | 'mobile_composer'
+ | 'search'
+ | 'document'
+ | 'drive'
+ | 'agent_session'
+ | 'other';
+
+type PromptTraceOptions = {
+ newSession: boolean;
+ submitSurface?: PromptSubmitSurface;
+};
+
export class PromptTrace {
readonly #span: Span | undefined;
+ readonly #sessionId: string;
readonly #startedAt = performance.now();
/** Ids the prompt may be confirmed under: the speculated one and the accepted one. */
readonly #actionIds = new Set<string>();
@@ -101,9 +128,14 @@ export class PromptTrace {
#text = false;
#ended = false;
#stallTimer: ReturnType<typeof setTimeout> | undefined;
+ #renderTimer: ReturnType<typeof setTimeout> | undefined;
+ #mounted = false;
+ #rendered = false;
+ readonly #renderers = new Set<() => void>();
- constructor(sessionId: string, options: { newSession: boolean }) {
- this.#span = start(sessionId, options.newSession);
+ constructor(sessionId: string, options: PromptTraceOptions) {
+ this.#sessionId = sessionId;
+ this.#span = start(sessionId, options);
this.#stallTimer = setTimeout(
() => this.end('stalled'),
STALL_THRESHOLD_MS
@@ -131,7 +163,8 @@ export class PromptTrace {
stage(stage: PromptStage, attributes: Attributes = {}): void {
if (this.#ended) return;
- const atMs = Math.round(performance.now() - this.#startedAt);
+ const now = performance.now();
+ const atMs = Math.round(now - this.#startedAt);
this.#set(`agent.prompt.${stage}_at_ms`, atMs);
for (const [name, value] of Object.entries(attributes)) {
this.#set(`agent.prompt.${name}`, value);
@@ -141,11 +174,56 @@ export class PromptTrace {
at_ms: atMs,
...attributes,
});
+ performance.measure(`agent.prompt.${stage}`, {
+ start: this.#startedAt,
+ end: now,
+ detail: { sessionId: this.#sessionId },
+ });
} catch {
// See the module comment.
}
}
+ /** Called by the matching TextPart, never by raw fold delivery. */
+ observeRenderedText(
+ turn: number,
+ element: HTMLElement
+ ): (() => void) | undefined {
+ if (this.#ended || this.#turn !== turn) return;
+ try {
+ if (!this.#mounted) {
+ this.#mounted = true;
+ this.stage('text_mounted');
+ }
+ const stop = observeRenderedAnswer(element, {
+ readable: () => {
+ if (this.#rendered) return;
+ this.#rendered = true;
+ this.stage('first_text_rendered');
+ },
+ painted: () => {
+ this.stage('first_text_paint');
+ this.end('text');
+ },
+ hidden: () => {
+ if (this.#text) this.end('hidden');
+ },
+ });
+ if (this.#ended) {
+ stop();
+ return;
+ }
+ this.#renderers.add(stop);
+ return () => {
+ stop();
+ this.#renderers.delete(stop);
+ };
+ } catch {
+ // Rendering the answer must never depend on telemetry support.
+ return;
+ }
+ }
+
/** The control will be sent under `actionId`; its confirmation may name it. */
expect(actionId: string): void {
this.#actionIds.add(actionId);
@@ -182,6 +260,13 @@ export class PromptTrace {
if (this.#ended) return;
clearTimeout(this.#stallTimer);
this.#stallTimer = undefined;
+ clearTimeout(this.#renderTimer);
+ this.#renderTimer = undefined;
+ this.#set('agent.prompt.renderer_mounted', this.#mounted);
+ this.#set('agent.prompt.renderer_attached', this.#renderers.size > 0);
+ for (const stop of this.#renderers) stop();
+ this.#renderers.clear();
+ if (outcome === 'hidden') this.#set('agent.prompt.hidden', true);
this.#set('agent.prompt.outcome', outcome);
this.#set(
'agent.prompt.total_ms',
@@ -191,6 +276,11 @@ export class PromptTrace {
try {
if (outcome === 'failed' && error !== undefined) this.#span?.error(error);
this.#span?.end();
+ performance.measure('agent.prompt', {
+ start: this.#startedAt,
+ end: performance.now(),
+ detail: { sessionId: this.#sessionId, outcome },
+ });
} catch {
// See the module comment.
}
@@ -238,15 +328,12 @@ export class PromptTrace {
// A hidden tab never paints, and never runs animation frames either.
if (documentHidden()) {
this.#set('agent.prompt.hidden', true);
- this.end('text');
+ this.end('hidden');
return;
}
- // Two frames: the first runs before the paint the text lands in.
- requestAnimationFrame(() =>
- requestAnimationFrame(() => {
- this.stage('first_text_paint');
- this.end('text');
- })
+ this.#renderTimer = setTimeout(
+ () => this.end('not_rendered'),
+ RENDER_TIMEOUT_MS
);
}
@@ -276,13 +363,42 @@ function messagesOf(event: FoldedStreamEvent): FoldedMessage[] {
.exhaustive();
}
-function start(sessionId: string, newSession: boolean): Span | undefined {
+function start(
+ sessionId: string,
+ options: PromptTraceOptions
+): Span | undefined {
try {
const span = Telemetry.span('agent.prompt');
span.setAttr('agent.session.id', sessionId);
- span.setAttr('agent.prompt.new_session', newSession);
+ span.setAttr('agent.prompt.new_session', options.newSession);
+ span.setAttr(
+ 'agent.prompt.submit_surface',
+ options.submitSurface ?? submitSurface(options.newSession)
+ );
return span;
} catch {
return undefined;
}
}
+
+/** Bounded route categories only; paths and entity IDs are never telemetry labels. */
+function submitSurface(newSession: boolean): PromptSubmitSurface {
+ if (!newSession) return 'agent_session';
+ const route = typeof location === 'undefined' ? '' : location.pathname;
+ // Layout URLs enumerate panes without identifying the active one. Known
+ // composers supply their origin explicitly; never guess the leftmost pane.
+ if (route.includes('/~/')) return 'other';
+ if (/^\/app\/drive(?:\/|$)/.test(route)) {
+ return /\/(?:md|task|skill|snippet|canvas|pdf|code|csv|image|video|spreadsheet|unknown)\/[^/]+\/?$/.test(
+ route
+ )
+ ? 'document'
+ : 'drive';
+ }
+ if (/^\/app\/?$/.test(route) || /^\/app\/home(?:\/|$)/.test(route))
+ return 'home';
+ if (/^\/app\/agents(?:\/|$)/.test(route)) return 'agents';
+ if (/^\/app\/search(?:\/|$)/.test(route)) return 'search';
+ if (/^\/app\/(?:md|pdf|code|document)\//.test(route)) return 'document';
+ return 'other';
+}
diff --git a/apps/web/src/lib/core/agent-session/render-telemetry.test.ts b/apps/web/src/lib/core/agent-session/render-telemetry.test.ts
new file mode 100644
index 0000000000..21bb7a9bd8
--- /dev/null
+++ b/apps/web/src/lib/core/agent-session/render-telemetry.test.ts
@@ -0,0 +1,200 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { observeRenderedAnswer } from './render-telemetry';
+
+const cleanups: (() => void)[] = [];
+const rangeRects = vi.fn<(range: Range) => DOMRect[]>();
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ vi.stubGlobal('IntersectionObserver', undefined);
+ vi.stubGlobal('requestAnimationFrame', (callback: () => void) =>
+ setTimeout(callback, 16)
+ );
+ vi.stubGlobal('cancelAnimationFrame', clearTimeout);
+ vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockReturnValue(
+ new DOMRect(10, 10, 300, 30)
+ );
+ rangeRects.mockImplementation((range) => [
+ range.startContainer.parentElement!.getBoundingClientRect(),
+ ]);
+ const createRange = document.createRange.bind(document);
+ vi.spyOn(document, 'createRange').mockImplementation(() => {
+ const range = createRange();
+ range.getClientRects = () => {
+ const rects = rangeRects(range);
+ return Object.assign(rects, { item: (index: number) => rects[index] });
+ };
+ return range;
+ });
+});
+
+afterEach(() => {
+ for (const cleanup of cleanups.splice(0)) cleanup();
+ document.body.replaceChildren();
+ vi.useRealTimers();
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+});
+
+function observe(html: string, parent = document.body) {
+ const element = document.createElement('div');
+ element.innerHTML = html;
+ parent.append(element);
+ const callbacks = {
+ readable: vi.fn(),
+ painted: vi.fn(),
+ hidden: vi.fn(),
+ };
+ const stop = observeRenderedAnswer(element, callbacks);
+ cleanups.push(stop);
+ return { element, callbacks, stop };
+}
+
+describe('rendered answer telemetry', () => {
+ it.each(['**', '1. **', '```'])(
+ 'waits past the bare prefix %s until words render',
+ async (prefix) => {
+ const { element, callbacks } = observe(prefix);
+ vi.advanceTimersByTime(32);
+ expect(callbacks.readable).not.toHaveBeenCalled();
+ expect(callbacks.painted).not.toHaveBeenCalled();
+ element.textContent = 'The sky is blue';
+ await Promise.resolve();
+ expect(callbacks.readable).toHaveBeenCalledOnce();
+ expect(callbacks.painted).not.toHaveBeenCalled();
+ vi.advanceTimersByTime(32);
+ expect(callbacks.painted).toHaveBeenCalledOnce();
+ }
+ );
+
+ it('does not count code language and copy controls before the code arrives', async () => {
+ const { element, callbacks } = observe(
+ '<div class="md-static-code-container"><div>JavaScript<button>Copy</button></div><pre></pre></div>'
+ );
+ vi.advanceTimersByTime(32);
+ expect(callbacks.painted).not.toHaveBeenCalled();
+ element.querySelector('pre')!.textContent = 'const answer = 42;';
+ await Promise.resolve();
+ vi.advanceTimersByTime(32);
+ expect(callbacks.painted).toHaveBeenCalledOnce();
+ });
+
+ it.each(['42', '你好', 'مرحبا'])(
+ 'counts readable answers including %s',
+ (text) => {
+ const { callbacks } = observe(text);
+ vi.advanceTimersByTime(32);
+ expect(callbacks.painted).toHaveBeenCalledOnce();
+ }
+ );
+
+ it('waits until actual code scrolls into view when only its toolbar intersects', () => {
+ let partTop = 90;
+ vi.mocked(HTMLElement.prototype.getBoundingClientRect).mockImplementation(
+ () => new DOMRect(10, partTop, 300, 80)
+ );
+ const scroller = document.createElement('div');
+ scroller.style.overflowY = 'auto';
+ document.body.append(scroller);
+ vi.spyOn(scroller, 'getBoundingClientRect').mockReturnValue(
+ new DOMRect(10, 10, 300, 100)
+ );
+ vi.spyOn(scroller, 'clientHeight', 'get').mockReturnValue(100);
+ // The pre's box overlaps the viewport, but its text is below the clip.
+ rangeRects.mockImplementation(() => [
+ new DOMRect(10, partTop + 50, 100, 20),
+ ]);
+ const { callbacks } = observe(
+ '<div class="md-static-code-container"><div>JavaScript<button>Copy</button></div><pre>const answer = 42;</pre></div>',
+ scroller
+ );
+ vi.advanceTimersByTime(32);
+ expect(callbacks.readable).not.toHaveBeenCalled();
+ expect(callbacks.painted).not.toHaveBeenCalled();
+
+ partTop = 30;
+ scroller.dispatchEvent(new Event('scroll'));
+ expect(callbacks.readable).toHaveBeenCalledOnce();
+ vi.advanceTimersByTime(32);
+ expect(callbacks.painted).toHaveBeenCalledOnce();
+ });
+
+ it.each(['<strong>Hello</strong>', '<em>42</em>'])(
+ 'counts visible inline text %s inside an overflow clip',
+ (html) => {
+ const scroller = document.createElement('div');
+ scroller.style.overflowX = 'hidden';
+ scroller.style.overflowY = 'auto';
+ document.body.append(scroller);
+ vi.spyOn(scroller, 'clientWidth', 'get').mockReturnValue(300);
+ vi.spyOn(scroller, 'clientHeight', 'get').mockReturnValue(30);
+ const { callbacks } = observe(html, scroller);
+ vi.advanceTimersByTime(32);
+ expect(callbacks.painted).toHaveBeenCalledOnce();
+ }
+ );
+
+ it('rejects CSS-hidden answer text even when its container is visible', () => {
+ const { callbacks } = observe('<span style="display:none">Hello</span>');
+ vi.advanceTimersByTime(32);
+ expect(callbacks.painted).not.toHaveBeenCalled();
+ });
+
+ it('does not report a paint when navigation disconnects the text between frames', () => {
+ const { element, callbacks } = observe('Hello');
+ vi.advanceTimersByTime(16);
+ element.remove();
+ vi.advanceTimersByTime(16);
+ expect(callbacks.painted).not.toHaveBeenCalled();
+ });
+
+ it('waits for an intersection so clipped transcript text is not counted', () => {
+ let intersect!: (target: Element, visible: boolean) => void;
+ vi.stubGlobal(
+ 'IntersectionObserver',
+ class {
+ constructor(callback: IntersectionObserverCallback) {
+ intersect = (target, isIntersecting) =>
+ callback(
+ [{ target, isIntersecting } as IntersectionObserverEntry],
+ this as unknown as IntersectionObserver
+ );
+ }
+ observe() {}
+ disconnect() {}
+ }
+ );
+ const { element, callbacks } = observe('Hello');
+ intersect(element, false);
+ vi.advanceTimersByTime(32);
+ expect(callbacks.painted).not.toHaveBeenCalled();
+ intersect(element, true);
+ vi.advanceTimersByTime(32);
+ expect(callbacks.painted).toHaveBeenCalledOnce();
+ });
+
+ it('reports a hidden tab without a visible success', () => {
+ const { callbacks } = observe('Hello');
+ vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('hidden');
+ document.dispatchEvent(new Event('visibilitychange'));
+ vi.advanceTimersByTime(32);
+ expect(callbacks.hidden).toHaveBeenCalled();
+ expect(callbacks.painted).not.toHaveBeenCalled();
+ });
+
+ it('cancels pending frames and DOM observation on cleanup', async () => {
+ const removeListener = vi.spyOn(document, 'removeEventListener');
+ const { element, callbacks, stop } = observe('Hello');
+ stop();
+ element.textContent = 'More words';
+ await Promise.resolve();
+ vi.advanceTimersByTime(32);
+ expect(callbacks.painted).not.toHaveBeenCalled();
+ expect(callbacks.readable).toHaveBeenCalledOnce();
+ expect(removeListener).toHaveBeenCalledWith(
+ 'scroll',
+ expect.any(Function),
+ true
+ );
+ });
+});
diff --git a/apps/web/src/lib/core/agent-session/render-telemetry.ts b/apps/web/src/lib/core/agent-session/render-telemetry.ts
new file mode 100644
index 0000000000..2e9ce65e9e
--- /dev/null
+++ b/apps/web/src/lib/core/agent-session/render-telemetry.ts
@@ -0,0 +1,135 @@
+/** Observe actual answer DOM; raw fold text may still be Markdown scaffolding. */
+
+function readableText(element: HTMLElement): boolean {
+ const walker = document.createTreeWalker(element, NodeFilter.SHOW_TEXT);
+ let text = '';
+ for (let node = walker.nextNode(); node; node = walker.nextNode()) {
+ const parent = node.parentElement;
+ if (
+ !parent ||
+ parent.closest('button, input, select, [aria-hidden="true"]') ||
+ (parent.closest('.md-static-code-container') && !parent.closest('pre'))
+ )
+ continue;
+ const range = document.createRange();
+ range.selectNodeContents(node);
+ if (![...range.getClientRects()].some((rect) => visible(parent, rect)))
+ continue;
+ text += node.textContent ?? '';
+ }
+ // Keep real numeric answers, but not a streaming list marker such as `1. **`.
+ return /[\p{L}\p{N}]/u.test(text) && !/^\s*\d+[.)][\s*_`~]*$/u.test(text);
+}
+
+function visible(
+ element: HTMLElement,
+ rect = element.getBoundingClientRect()
+): boolean {
+ if (!element.isConnected || document.visibilityState === 'hidden')
+ return false;
+ let left = Math.max(0, rect.left);
+ let top = Math.max(0, rect.top);
+ let right = Math.min(window.innerWidth, rect.right);
+ let bottom = Math.min(window.innerHeight, rect.bottom);
+ for (
+ let node: HTMLElement | null = element;
+ node;
+ node = node.parentElement
+ ) {
+ const style = getComputedStyle(node);
+ if (
+ style.display === 'none' ||
+ style.visibility === 'hidden' ||
+ style.visibility === 'collapse' ||
+ style.opacity === '0'
+ )
+ return false;
+ // A container can intersect while all its text is clipped below a scroll
+ // viewport. Intersect the actual glyph rectangles with every overflow clip.
+ const clipsX = /^(auto|scroll|hidden|clip)$/.test(style.overflowX);
+ const clipsY = /^(auto|scroll|hidden|clip)$/.test(style.overflowY);
+ if (clipsX || clipsY) {
+ const bounds = node.getBoundingClientRect();
+ if (clipsX) {
+ const start = bounds.left + node.clientLeft;
+ left = Math.max(left, start);
+ right = Math.min(right, start + node.clientWidth);
+ }
+ if (clipsY) {
+ const start = bounds.top + node.clientTop;
+ top = Math.max(top, start);
+ bottom = Math.min(bottom, start + node.clientHeight);
+ }
+ }
+ if (left >= right || top >= bottom) return false;
+ }
+ return true;
+}
+
+/** No content leaves the renderer; callbacks report only lifecycle milestones. */
+export function observeRenderedAnswer(
+ element: HTMLElement,
+ callbacks: { readable: () => void; painted: () => void; hidden: () => void }
+): () => void {
+ let stopped = false;
+ let readable = false;
+ let intersecting = typeof IntersectionObserver === 'undefined';
+ let frame: number | undefined;
+ const cancelFrame = () => {
+ if (frame !== undefined) cancelAnimationFrame(frame);
+ frame = undefined;
+ };
+ const ready = () => intersecting && visible(element) && readableText(element);
+ const check = () => {
+ if (stopped) return;
+ if (document.visibilityState === 'hidden') {
+ callbacks.hidden();
+ return;
+ }
+ if (frame !== undefined || !ready()) return;
+ if (!readable) {
+ readable = true;
+ callbacks.readable();
+ }
+ // Validate the same DOM across a paint boundary. Navigation, unmounting,
+ // hidden tabs, and CSS-hidden transcripts must not become visible successes.
+ frame = requestAnimationFrame(() => {
+ frame = requestAnimationFrame(() => {
+ frame = undefined;
+ if (stopped) return;
+ if (document.visibilityState === 'hidden') callbacks.hidden();
+ else if (ready()) callbacks.painted();
+ });
+ });
+ };
+ const mutations = new MutationObserver(check);
+ mutations.observe(element, {
+ childList: true,
+ subtree: true,
+ characterData: true,
+ attributes: true,
+ });
+ const intersection =
+ typeof IntersectionObserver === 'undefined'
+ ? undefined
+ : new IntersectionObserver((entries) => {
+ intersecting = entries.some(
+ (entry) => entry.target === element && entry.isIntersecting
+ );
+ check();
+ });
+ intersection?.observe(element);
+ document.addEventListener('visibilitychange', check);
+ // Scrolling can reveal text without changing whether its outer part intersects.
+ document.addEventListener('scroll', check, true);
+ check();
+
+ return () => {
+ stopped = true;
+ cancelFrame();
+ mutations.disconnect();
+ intersection?.disconnect();
+ document.removeEventListener('visibilitychange', check);
+ document.removeEventListener('scroll', check, true);
+ };
+}
diff --git a/docs/AGENT_GUIDE/ai-chat.md b/docs/AGENT_GUIDE/ai-chat.md
index 490a77a4bc..6cd8626d31 100644
--- a/docs/AGENT_GUIDE/ai-chat.md
+++ b/docs/AGENT_GUIDE/ai-chat.md
@@ -27,6 +27,24 @@ the session must keep the same streamed turn without restarting its load. Also
leave a pending destination, then reopen the session and confirm the sent prompt
and complete answer remain available.
+The `agent.prompt` trace separates raw fold text (`first_text`) from mounted
+answer DOM (`text_mounted`), readable visible text (`first_text_rendered`), and
+its paint (`first_text_paint`). Only the final milestone is a visible-response
+success. Bare Markdown prefixes and code-toolbar labels do not count. With only
+a code toolbar visible at a scroll boundary, verify the milestone waits until
+the code itself scrolls into view. A hidden tab reports `hidden`; raw text without
+a visible renderer within ten seconds reports `not_rendered`, including whether
+a renderer mounted and stayed attached.
+`submit_surface` uses bounded composer categories, including explicit Home,
+Agents, and mobile origins so a neighboring split cannot mislabel the submit.
+The fallback recognizes Drive documents; an ambiguous split reports `other`.
+All milestones omit message contents. Compare these timings with created,
+loaded, configured, delivery, and fold timing to distinguish startup, transport,
+and rendering delays.
+The same stages are available immediately in DevTools as
+`performance.getEntriesByType('measure')` entries named `agent.prompt.*`, with
+session ID in `detail`; the `agent.prompt` entry includes the final outcome.
+
## Working with projects
Project tools can list, read, create, update, delete, and share projects, and