Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

fix(chat): restore full activity history in running sessions (#1876)

Call White9993ce41ce36
diff --git a/docs/plans/live-activity-history.md b/docs/plans/live-activity-history.md
new file mode 100644
index 000000000..9dc07667f
--- /dev/null
+++ b/docs/plans/live-activity-history.md
@@ -0,0 +1,83 @@
+# Running Activity History Hydration
+
+## Problem
+
+Switching to a running Session can display only the latest streamed steps even
+when the durable Activity group contains hundreds of rows. Both the detail-fetch
+gate in ChatPage and the live reducer treat a nonempty stream buffer as complete
+history. A single live event arriving before either HTTP response wins that race.
+Settled groups use their durable details directly and are unaffected.
+
+## Scope
+
+Keep the existing Activity endpoint and live reducer as the owners. Read the
+running group's history even when live rows exist, then merge by persisted row
+identity in emission order with the newer live tail. Preserve already-loaded rows
+as the durable endpoint's bounded window advances. Replay must not add duplicate
+steps, and hydration must retain the earliest start time.
+The detail response exposes `order_micros`, the exact emission key already used
+by storage. Migrated event IDs are opaque hashes; only storage can recover their
+original Message clock. Durable hydration owns that key even when it overlaps a
+live row. Equal emission keys use the endpoint's deterministic ID tie-break.
+
+Generation checks must reject detail responses after settlement, a new turn, an
+output phase boundary, a visibility reset, or a Session switch, including returning
+to the same Session. The live generation belongs to one Activity phase, not the
+entire logical Turn; detached completions do not advance that generation.
+Detail failures use the existing bounded refresh retry.
+
+## Validation
+
+- Reproduce both response orderings in ChatPage with 300 persisted steps.
+- Assert the full history and live tail remain visible exactly once after replay
+ and reconnect.
+- Cover lifecycle invalidation and lazy loading of settled groups.
+- Verify the shared ordering fixture against real SQLite detail output and the
+ frontend wire mapper/reducer, including migration-only clocks and live overlap.
+- Run focused UI tests, lint, and the production UI build before PR review.
+
+## Review Audit
+
+- Head `190c6ef87f`: one P2 finding, one root-cause class (missing deterministic
+ tie ordering when hydration windows advance). No repeated findings-bearing head.
+- Scope decision: reuse storage's existing time/ID order in the live reducer;
+ no API or data-model change. Regression tests cover every window split with
+ overlap and without it, both arrival orders, and both legacy and clock-bearing
+ IDs whose emission times tie.
+- Head `0f54955369`: one P2 finding, a distinct root-cause class (phase boundaries
+ changed durable group ownership without invalidating the live generation).
+ Two findings-bearing heads total; no repeated root-cause class.
+- Scope decision: reuse the existing generation reset at the shared effective
+ boundary-role policy. Keep controller Turn state unchanged and keep detached
+ completion handling refresh-only. Exercise old summary/detail responses and
+ already-hydrated rows across the boundary; preserve settled-chip ownership.
+- Head `f0a1427071`: one P2 finding (migrated event order is unavailable in the
+ detail wire). This repeats the ordering-contract class from `190c6ef87f`.
+ Three findings-bearing heads total; the repeated-class circuit breaker fired.
+- Orchestrator diagnosis: frontend time/ID reconstruction cannot match storage
+ for migration-generated hashes whose original clock exists only in metadata.
+ The previous tie-break fix addressed the visible tie, not the missing contract.
+ The phase-boundary fix is independent and remains in place.
+- Scope decision before further implementation: add the existing storage
+ emission key to Activity detail rows as `order_micros`; let durable rows own
+ that key during hydration. Keep ID-clock fallback only for rows without a
+ durable key (including current SSE envelopes). Verify a shared fixture against
+ real SQLite grouping and the consuming frontend reducer across window shifts,
+ both snapshot orders, mixed sources, migration hashes, and overlapping live rows.
+ No migration, configuration change, new dependency, or alternate grouping owner.
+- Head `85b62d2bd7`: one P2 finding (historical transcript filtering bypassed
+ Activity phase invalidation). Four findings-bearing heads total: ordering on
+ `190c6ef87f` and `f0a1427071`, phase ownership on `0f54955369` and `85b62d2bd7`.
+ The phase-ownership class has now repeated, triggering a second diagnosis pause.
+- Orchestrator diagnosis: the existing generation model expresses the required
+ ownership, but its message-driven transition sits behind transcript-only
+ filtering. Both an already-historical window and a capped, unpinned window can
+ skip it. Turn start/end already bypass these filters; visibility and Session
+ changes already invalidate their generation. The durable ordering fix remains
+ independent and unchanged.
+- Scope decision before further implementation: process Activity lifecycle
+ messages immediately after Session routing, before every transcript-view gate.
+ Preserve historical transcript freezing and Activity-row ingestion policy.
+ Exercise the same phase invariant across live, search-history, and capped-tail
+ views, with boundaries before summary, during detail, and after hydration.
+ Reuse the current reducer and coalesced refresh; no new state or API contract.
diff --git a/storage/agent_activity_service.py b/storage/agent_activity_service.py
index d9b4e5701..e0346e0d2 100644
--- a/storage/agent_activity_service.py
+++ b/storage/agent_activity_service.py
@@ -470,6 +470,8 @@ def _make_group(
"kind": item["row_kind"],
"text": item.get("text") or "",
"created_at": item["created_at"],
+ # Migrated event ids are hashes; only storage has the original clock.
+ "order_micros": item["sort"],
}
for item in pending
]
diff --git a/tests/test_agent_activity_service.py b/tests/test_agent_activity_service.py
index 9f1b4ca16..d531322c9 100644
--- a/tests/test_agent_activity_service.py
+++ b/tests/test_agent_activity_service.py
@@ -393,6 +393,45 @@ def test_migrated_terminal_uses_original_message_clock_for_same_second_order(
assert groups[0]["anchor_message_id"] == _clock_id("msg", base + 1_000)
+def test_detail_exposes_the_same_order_contract_consumed_by_ui(isolated_state):
+ fixture_path = (
+ Path(__file__).resolve().parents[1]
+ / "ui/src/lib/agentActivity.order.fixture.json"
+ )
+ fixture = json.loads(fixture_path.read_text(encoding="utf-8"))
+ wire_keys = ("id", "kind", "text", "created_at", "order_micros")
+ expected_rows = [{key: row[key] for key in wire_keys} for row in fixture["rows"]]
+ engine = create_sqlite_engine()
+ sid = "ses_activity_order_contract"
+ with engine.begin() as conn:
+ scope = _seed_session(conn, session_id=sid)
+ _msg(
+ conn, scope, sid, mid="fixture-prompt", mtype="user", author="user",
+ created_at="2026-09-04T23:59:59Z", source="user", text="start",
+ )
+ for row in fixture["rows"]:
+ if row["kind"] == "assistant":
+ _msg(
+ conn, scope, sid, mid=row["id"], mtype="assistant", author="agent",
+ created_at=row["created_at"], text=row["text"],
+ )
+ else:
+ assert row["kind"] == "tool_call"
+ metadata = {"legacy_message_id": row["legacy_message_id"]} if "legacy_message_id" in row else {}
+ _evt(
+ conn, scope, sid, eid=row["id"], created_at=row["created_at"],
+ text=row["text"], metadata=metadata,
+ )
+
+ with engine.connect() as conn:
+ groups = agent_activity_service.list_turn_groups(conn, session_id=sid)["groups"]
+ assert len(groups) == 1
+ detail = agent_activity_service.get_turn_group(conn, session_id=sid, group_id=groups[0]["id"])
+ assert detail is not None
+ assert detail["open"] is True
+ assert detail["rows"] == expected_rows
+
+
def test_duration_measured_from_turn_opener(isolated_state):
"""The chip duration spans the turn opener → terminal (what the history endpoint
reports), not first-activity → terminal — so live and reloaded chips agree."""
diff --git a/ui/src/components/workbench/ChatPage.hydration.test.tsx b/ui/src/components/workbench/ChatPage.hydration.test.tsx
index 2e6492f95..e4372e8e5 100644
--- a/ui/src/components/workbench/ChatPage.hydration.test.tsx
+++ b/ui/src/components/workbench/ChatPage.hydration.test.tsx
@@ -1,8 +1,9 @@
/** @vitest-environment jsdom */
-import { act, cleanup, render, screen, waitFor } from '@testing-library/react';
+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { MemoryRouter, Route, Routes, useNavigate } from 'react-router-dom';
+import type { TurnActivityGroupWire } from '../../lib/agentActivity';
const mocks = vi.hoisted(() => ({
api: {
@@ -173,9 +174,13 @@ const projectedMessage = (id: string, text: string) => ({
read_at: null,
});
-const SessionSwitcher = () => {
+const SessionSwitcher = ({ sessionId = 'session-running', label = 'switch chat', search = '' }: {
+ sessionId?: string;
+ label?: string;
+ search?: string;
+}) => {
const navigate = useNavigate();
- return <button type="button" onClick={() => navigate('/chat/session-running')}>switch chat</button>;
+ return <button type="button" onClick={() => navigate({ pathname: `/chat/${sessionId}`, search })}>{label}</button>;
};
describe('ChatPage transcript hydration', () => {
@@ -507,6 +512,344 @@ describe('ChatPage transcript hydration', () => {
await waitFor(() => expect(screen.getByText('chat.agentActivity.running')).toBeTruthy());
expect(screen.queryByText('chat.agentActivity.interrupted')).toBeNull();
+ act(() => mocks.events?.onMessageNew({
+ ...projectedMessage('next-active-step', 'next live step'),
+ session_id: 'session-running',
+ author: 'agent',
+ type: 'assistant',
+ source: 'agent',
+ }));
+ expect(screen.getByText('still working')).toBeTruthy();
+ expect(screen.getByText('next live step')).toBeTruthy();
+ });
+
+ it.each(['before summary', 'during detail'] as const)(
+ 'retains the full running history when live rows arrive %s on a session switch',
+ async (arrival) => {
+ const rows = Array.from({ length: 300 }, (_, index) => ({
+ id: `step-${index}`,
+ kind: 'assistant' as const,
+ text: `activity step ${index}`,
+ created_at: new Date(Date.UTC(2026, 8, 5, 0, 0, index)).toISOString(),
+ }));
+ const openGroup: TurnActivityGroupWire = {
+ id: rows[0].id,
+ anchor_message_id: null,
+ anchor_position: 'after',
+ open: true,
+ status: 'interrupted',
+ steps: rows.length,
+ duration_ms: null,
+ };
+ const summary = deferred<{ groups: TurnActivityGroupWire[] }>();
+ const detail = deferred<TurnActivityGroupWire>();
+ const running = { ...idleTurnState, foreground: 'running', in_flight: true };
+ mocks.api.getSession.mockImplementation((id: string) => Promise.resolve({ id }));
+ mocks.api.getSessionBootstrap.mockImplementation((id: string) => Promise.resolve({
+ ...bootstrapPayload(id),
+ config: { ui: { show_agent_activity: true } },
+ turn_state: id === 'session-running' ? running : idleTurnState,
+ }));
+ mocks.api.getTurnState.mockResolvedValue(running);
+ mocks.api.getSessionActivity.mockImplementation((id: string) => (
+ id === 'session-running' ? summary.promise : Promise.resolve({ groups: [] })
+ ));
+ mocks.api.getSessionActivityGroup.mockReturnValue(detail.promise);
+
+ render(
+ <MemoryRouter initialEntries={['/chat/session-old']}>
+ <SessionSwitcher />
+ <Routes>
+ <Route path="/chat/:sessionId" element={<ChatPage />} />
+ </Routes>
+ </MemoryRouter>,
+ );
+
+ await waitFor(() => expect(mocks.api.getSessionActivity).toHaveBeenCalledWith('session-old'));
+ act(() => screen.getByRole('button', { name: 'switch chat' }).click());
+ await waitFor(() => expect(mocks.api.getSessionActivity).toHaveBeenCalledWith('session-running'));
+
+ if (arrival === 'during detail') {
+ await act(async () => summary.resolve({ groups: [openGroup] }));
+ await waitFor(() => expect(mocks.api.getSessionActivityGroup).toHaveBeenCalled());
+ }
+ const emit = (id: string, text: string) => mocks.events?.onMessageNew({
+ ...projectedMessage(id, text),
+ session_id: 'session-running',
+ created_at: rows.find((row) => row.id === id)?.created_at
+ ?? new Date(Date.UTC(2026, 8, 5, 0, 0, 300)).toISOString(),
+ author: 'agent',
+ type: 'assistant',
+ source: 'agent',
+ });
+ act(() => {
+ emit(rows[299].id, rows[299].text);
+ emit('step-300', 'activity step 300');
+ });
+ if (arrival === 'before summary') {
+ await act(async () => summary.resolve({ groups: [openGroup] }));
+ await waitFor(() => expect(mocks.api.getSessionActivityGroup).toHaveBeenCalled());
+ }
+ await act(async () => detail.resolve({ ...openGroup, rows }));
+
+ const expected = [...rows.map((row) => row.text), 'activity step 300'];
+ const renderedRows = () => screen.getAllByText(/^activity step \d+$/).map((el) => el.textContent);
+ await waitFor(() => expect(renderedRows()).toEqual(expected));
+ act(() => emit(rows[298].id, rows[298].text));
+ expect(renderedRows()).toEqual(expected);
+
+ // Reconnect can re-read an older snapshot while the live tail is newer.
+ const reads = mocks.api.getSessionActivityGroup.mock.calls.length;
+ act(() => mocks.events?.onConnected());
+ await waitFor(() => expect(mocks.api.getSessionActivityGroup.mock.calls.length).toBeGreaterThan(reads));
+ expect(renderedRows()).toEqual(expected);
+ },
+ );
+
+ it.each(['next turn', 'other session', 'same session again'] as const)(
+ 'rejects old running history after entering the %s',
+ async (transition) => {
+ const openGroup: TurnActivityGroupWire = {
+ id: 'old-group', anchor_message_id: null, anchor_position: 'after',
+ open: true, status: 'interrupted', steps: 1, duration_ms: null,
+ };
+ const oldDetail = deferred<TurnActivityGroupWire>();
+ const currentDetail = deferred<TurnActivityGroupWire>();
+ const running = { ...idleTurnState, foreground: 'running', in_flight: true };
+ mocks.api.getSession.mockImplementation((id: string) => Promise.resolve({ id }));
+ mocks.api.getSessionBootstrap.mockImplementation((id: string) => Promise.resolve({
+ ...bootstrapPayload(id),
+ config: { ui: { show_agent_activity: true } },
+ turn_state: running,
+ }));
+ mocks.api.getTurnState.mockResolvedValue(running);
+ mocks.api.getSessionActivity
+ .mockResolvedValueOnce({ groups: [openGroup] })
+ .mockResolvedValue({ groups: [{ ...openGroup, id: 'current-group' }] });
+ mocks.api.getSessionActivityGroup.mockImplementation((_sid: string, groupId: string) => (
+ groupId === 'old-group' ? oldDetail.promise : currentDetail.promise
+ ));
+ render(
+ <MemoryRouter initialEntries={['/chat/session-new']}>
+ <SessionSwitcher />
+ <SessionSwitcher sessionId="session-new" label="return chat" />
+ <Routes>
+ <Route path="/chat/:sessionId" element={<ChatPage />} />
+ </Routes>
+ </MemoryRouter>,
+ );
+ await waitFor(() => expect(mocks.api.getSessionActivityGroup).toHaveBeenCalledWith('session-new', 'old-group'));
+ if (transition === 'next turn') {
+ act(() => mocks.events?.onTurnStart({ session_id: 'session-new' }));
+ } else {
+ act(() => screen.getByRole('button', { name: 'switch chat' }).click());
+ await waitFor(() => expect(mocks.api.getSessionBootstrap).toHaveBeenCalledTimes(2));
+ if (transition === 'same session again') {
+ act(() => screen.getByRole('button', { name: 'return chat' }).click());
+ await waitFor(() => expect(mocks.api.getSessionBootstrap).toHaveBeenCalledTimes(3));
+ }
+ }
+ act(() => mocks.events?.onMessageNew({
+ ...projectedMessage('current-row', 'current live row'),
+ session_id: transition === 'other session' ? 'session-running' : 'session-new',
+ author: 'agent', type: 'assistant', source: 'agent',
+ }));
+ await act(async () => oldDetail.resolve({
+ ...openGroup,
+ rows: [{ id: 'old-row', kind: 'assistant', text: 'obsolete history row', created_at: '2026-09-05T00:00:00Z' }],
+ }));
+ expect(screen.queryByText('obsolete history row')).toBeNull();
+ expect(screen.getByText('current live row')).toBeTruthy();
+ },
+ );
+
+ it('recovers running history after a detail failure while live rows continue', async () => {
+ const group: TurnActivityGroupWire = {
+ id: 'history', anchor_message_id: null, anchor_position: 'after',
+ open: true, status: 'interrupted', steps: 1, duration_ms: null,
+ };
+ mocks.api.getSessionBootstrap.mockResolvedValue({
+ ...bootstrapPayload('session-new'),
+ config: { ui: { show_agent_activity: true } },
+ turn_state: { ...idleTurnState, foreground: 'running', in_flight: true },
+ });
+ mocks.api.getSessionActivity.mockResolvedValue({ groups: [group] });
+ mocks.api.getSessionActivityGroup
+ .mockRejectedValueOnce(new Error('temporary detail failure'))
+ .mockResolvedValue({
+ ...group,
+ rows: [{ id: 'history', kind: 'assistant', text: 'recovered history row', created_at: '2026-09-05T00:00:00Z' }],
+ });
+ render(
+ <MemoryRouter initialEntries={['/chat/session-new']}>
+ <Routes>
+ <Route path="/chat/:sessionId" element={<ChatPage />} />
+ </Routes>
+ </MemoryRouter>,
+ );
+ await waitFor(() => expect(mocks.api.getSessionActivityGroup).toHaveBeenCalledTimes(1));
+ act(() => mocks.events?.onMessageNew({
+ ...projectedMessage('live', 'live during recovery'),
+ author: 'agent', type: 'assistant', source: 'agent',
+ }));
+ await waitFor(() => expect(screen.getByText('recovered history row')).toBeTruthy(), { timeout: 2500 });
+ expect(screen.getByText('live during recovery')).toBeTruthy();
+ expect(mocks.api.getSessionActivityGroup).toHaveBeenCalledTimes(2);
+ });
+
+ it.each((['before summary', 'during detail', 'after hydration'] as const).flatMap((arrival) => (
+ (['live tail', 'search history', 'capped tail'] as const).map((view) => ({ arrival, view }))
+ )))(
+ 'isolates Activity phases when output arrives $arrival in $view without ending the Turn',
+ async ({ arrival, view }) => {
+ // No browser layout in jsdom; reader placement is driven explicitly below.
+ vi.stubGlobal('requestAnimationFrame', () => 0);
+ let scrollRoot: HTMLElement | null = null;
+ vi.stubGlobal('IntersectionObserver', class {
+ constructor(_callback: IntersectionObserverCallback, options?: IntersectionObserverInit) {
+ if (options?.root instanceof HTMLElement) scrollRoot = options.root;
+ }
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ });
+ const previous: TurnActivityGroupWire = {
+ id: 'previous-phase', anchor_message_id: null, anchor_position: 'after',
+ open: true, status: 'interrupted', steps: 1, duration_ms: null,
+ };
+ const settled: TurnActivityGroupWire = {
+ ...previous, open: false, status: 'done',
+ anchor_message_id: 'phase-output', anchor_position: 'before',
+ };
+ const current: TurnActivityGroupWire = {
+ ...previous, id: 'current-phase', anchor_message_id: 'phase-output',
+ };
+ const oldSummary = deferred<{ groups: TurnActivityGroupWire[] }>();
+ const oldDetail = deferred<TurnActivityGroupWire>();
+ let phaseAdvanced = false;
+ const previousRow = {
+ id: previous.id, kind: 'assistant' as const, text: 'previous phase step',
+ created_at: '2026-09-05T00:00:00Z',
+ };
+ const running = { ...idleTurnState, foreground: 'running', in_flight: true };
+ const transcript = Array.from({ length: view === 'capped tail' ? 300 : 1 }, (_, index) => ({
+ ...projectedMessage(`prompt-${index}`, `prompt ${index}`),
+ projection: undefined,
+ }));
+ const output = {
+ ...projectedMessage('phase-output', 'phase result'),
+ author: 'agent', type: 'output', source: 'agent', created_at: '2026-09-05T00:00:01Z',
+ };
+ mocks.api.getSessionBootstrap.mockResolvedValue({
+ ...bootstrapPayload('session-new'),
+ messages: transcript,
+ config: { ui: { show_agent_activity: true } }, turn_state: running,
+ });
+ mocks.api.getTurnState.mockResolvedValue(running);
+ mocks.api.listSessionMessages.mockImplementation((_sid: string, options?: { aroundId?: string }) => (
+ Promise.resolve(options?.aroundId ? {
+ messages: [{ ...projectedMessage('historical-prompt', 'historical prompt'), projection: undefined }],
+ next_after_id: 'historical-prompt',
+ } : { messages: [transcript[0], output] })
+ ));
+ mocks.api.getSessionActivity.mockImplementation(() => (
+ phaseAdvanced ? Promise.resolve({ groups: [settled, current] }) : oldSummary.promise
+ ));
+ mocks.api.getSessionActivityGroup.mockImplementation((_sid: string, groupId: string) => (
+ groupId === previous.id ? oldDetail.promise : Promise.resolve({
+ ...current,
+ rows: [{ id: current.id, kind: 'assistant', text: 'current phase history', created_at: '2026-09-05T00:00:02Z' }],
+ })
+ ));
+ render(
+ <MemoryRouter initialEntries={['/chat/session-new']}>
+ <SessionSwitcher sessionId="session-new" search="?msg=historical-prompt" label="read history" />
+ <Routes>
+ <Route path="/chat/:sessionId" element={<ChatPage />} />
+ </Routes>
+ </MemoryRouter>,
+ );
+ await waitFor(() => expect(mocks.api.getSessionActivity).toHaveBeenCalled());
+ if (arrival !== 'before summary') {
+ await act(async () => oldSummary.resolve({ groups: [previous] }));
+ await waitFor(() => expect(mocks.api.getSessionActivityGroup).toHaveBeenCalledWith('session-new', previous.id));
+ }
+ if (arrival === 'after hydration') {
+ await act(async () => oldDetail.resolve({ ...previous, rows: [previousRow] }));
+ await screen.findByText(previousRow.text);
+ }
+ if (view === 'search history') {
+ act(() => screen.getByRole('button', { name: 'read history' }).click());
+ await screen.findByText('historical prompt');
+ } else if (view === 'capped tail') {
+ // Enter through the real scroll handler; the boundary itself will detach
+ // the capped transcript rather than append an unseen tail message.
+ if (!scrollRoot) throw new Error('transcript scroll root not observed');
+ Object.defineProperties(scrollRoot, {
+ scrollHeight: { value: 10_000, configurable: true },
+ clientHeight: { value: 800, configurable: true },
+ scrollTop: { value: 0, writable: true, configurable: true },
+ });
+ fireEvent.scroll(scrollRoot);
+ }
+ phaseAdvanced = true;
+ act(() => {
+ mocks.events?.onMessageNew(output);
+ });
+ if (view !== 'live tail') {
+ expect(screen.queryByText(output.text)).toBeNull();
+ act(() => screen.getByRole('button', { name: 'chat.scrollToBottom' }).click());
+ await screen.findByText(output.text);
+ }
+ act(() => {
+ mocks.events?.onMessageNew({
+ ...projectedMessage('current-live', 'current phase live step'),
+ author: 'agent', type: 'assistant', source: 'agent', created_at: '2026-09-05T00:00:03Z',
+ });
+ });
+ await act(async () => {
+ oldSummary.resolve({ groups: [previous] });
+ oldDetail.resolve({ ...previous, rows: [previousRow] });
+ });
+ await screen.findByText('current phase history');
+ expect(screen.getByText('current phase live step')).toBeTruthy();
+ expect(screen.getByText('chat.agentActivity.running')).toBeTruthy();
+ expect(screen.queryByText(previousRow.text)).toBeNull();
+ // The old phase remains available only in its durable, settled chip.
+ act(() => screen.getByTitle('chat.agentActivity.expand').click());
+ await screen.findByText(previousRow.text);
+ expect(screen.getAllByText(previousRow.text)).toHaveLength(1);
+ expect(screen.getByText('current phase live step')).toBeTruthy();
+ },
+ );
+
+ it('keeps completed Activity history lazy and separate from the running card', async () => {
+ const group: TurnActivityGroupWire = {
+ id: 'completed', anchor_message_id: null, anchor_position: 'before',
+ open: false, status: 'done', steps: 1, duration_ms: 1000,
+ };
+ mocks.api.getSessionBootstrap.mockResolvedValue({
+ ...bootstrapPayload('session-new'),
+ config: { ui: { show_agent_activity: true } },
+ messages: [projectedMessage('user-message', 'start completed task')],
+ });
+ mocks.api.getSessionActivity.mockResolvedValue({ groups: [group] });
+ mocks.api.getSessionActivityGroup.mockResolvedValue({
+ ...group,
+ rows: [{ id: 'completed', kind: 'assistant', text: 'completed history row', created_at: '2026-09-05T00:00:00Z' }],
+ });
+ render(
+ <MemoryRouter initialEntries={['/chat/session-new']}>
+ <Routes>
+ <Route path="/chat/:sessionId" element={<ChatPage />} />
+ </Routes>
+ </MemoryRouter>,
+ );
+ const expand = await screen.findByTitle('chat.agentActivity.expand');
+ expect(mocks.api.getSessionActivityGroup).not.toHaveBeenCalled();
+ act(() => expand.click());
+ await screen.findByText('completed history row');
+ expect(screen.queryByText('chat.agentActivity.running')).toBeNull();
});
it('uses the thinking dots and the Activity header as shortcuts for the global display setting', async () => {
diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsx
index 27e469d76..d21f1c7de 100644
--- a/ui/src/components/workbench/ChatPage.tsx
+++ b/ui/src/components/workbench/ChatPage.tsx
@@ -18,7 +18,7 @@ import { readChatViewMode, writeChatViewMode } from '../../lib/chatViewMemory';
import { normalizeChatMessageFontSize } from '../../lib/chatDisplay';
import { setConfigField } from '../../lib/configMutations';
import { annotationStandIn, annotationTitleKey, readAnnotationView } from '../../lib/annotationView';
-import { isTerminalAgentMessage, isTranscriptMessage, shouldRefreshAgentActivityForMessage } from '../../lib/chatMessageTypes';
+import { isAgentActivityBoundaryMessage, isTerminalAgentMessage, isTranscriptMessage, shouldRefreshAgentActivityForMessage } from '../../lib/chatMessageTypes';
import { chatRowKind, drawsEmptyBodyPlaceholder, isAgentAuthored } from '../../lib/chatRowKind';
import { useIosKeyboardInset } from '../../lib/useIosKeyboardInset';
import { isProxyMediaUrl } from '../../lib/mediaProxy';
@@ -707,12 +707,15 @@ export const ChatPage: React.FC = () => {
// every "a turn is starting now" path so clear-on-idle stays race-safe. Also sets
// ``workingRef`` synchronously so a settle refresh in the same tick reads it.
const markWorking = useCallback(() => {
+ // Authoritative running can arrive after an early idle read on navigation.
+ // Resume before hydrating, so the next live row cannot discard that history.
+ if (liveStateRef.current.settled) dispatchLive({ type: 'turn_start' });
turnEpochRef.current += 1;
workingSetAtRef.current = Date.now();
activityForegroundRef.current = 'running';
workingRef.current = true;
setWorking(true);
- }, []);
+ }, [dispatchLive]);
// ----- Agent Activity: the live buffer feeds ONLY the in-flight running card, as
// a pure generation state machine (see liveActivityReducer). Settled groups come
@@ -753,9 +756,10 @@ export const ChatPage: React.FC = () => {
return groups.map((g) => (g.rows || !prevRows.has(g.id) ? g : { ...g, rows: prevRows.get(g.id) }));
});
if (inflight) {
- // Still running: re-hydrate the card's rows only if the live stream hasn't
- // already filled them (the reducer also drops a stale-generation rehydrate).
- if (liveStateRef.current.rows.length === 0) {
+ // A live tail does not prove history is loaded. Always reconcile the
+ // current running generation with its durable rows; the reducer merges
+ // overlap and keeps live events that arrived during this read.
+ if (liveStateRef.current.gen === issuedGen && !liveStateRef.current.settled) {
try {
const wire = await api.getSessionActivityGroup(sid, inflight.id);
if (sid !== sessionIdRef.current || !showAgentActivityRef.current) return true;
@@ -771,7 +775,7 @@ export const ChatPage: React.FC = () => {
});
}
} catch {
- /* re-hydrate is best-effort; live streaming still fills the card */
+ return false; // use the same bounded retry as a failed summary read
}
}
} else if (foreground === 'idle') {
@@ -1496,14 +1500,6 @@ export const ChatPage: React.FC = () => {
setHydratedTranscriptSessionId(sessionId);
setFailedBootstrapSessionId(null);
activityForegroundRef.current = bootstrap.turn_state.foreground;
- // Chat Activity chips for past turns: resync the per-turn summary (row text
- // lazy-loads on expand). If a turn is in flight, the refresh re-hydrates the
- // running card instead of showing it as interrupted.
- if (activityEnabled) {
- scheduleActivityRefresh();
- } else {
- setActivityGroups([]);
- }
setQueue(bootstrap.queued ?? []);
setInitialDraft(bootstrap.draft?.text ?? '');
setRuntimeState(bootstrap.turn_state);
@@ -1516,6 +1512,13 @@ export const ChatPage: React.FC = () => {
workingRef.current = false;
setWorking(false);
}
+ // Reconcile only after restoring the live generation above, so a recovered
+ // running turn's history request is tagged with the generation it belongs to.
+ if (activityEnabled) {
+ scheduleActivityRefresh();
+ } else {
+ setActivityGroups([]);
+ }
} catch (err) {
// A superseded failure must not stamp an error onto the newer request's
// loading state, even when both requests belong to the same route.
@@ -1578,9 +1581,9 @@ export const ChatPage: React.FC = () => {
// never leak into the new chat (refresh re-reads the toggle + summary).
setActivityGroups([]);
activityForegroundRef.current = 'unknown';
- liveStateRef.current = initialLiveActivity();
- setLiveRows([]);
- setLiveStartedAt(null);
+ // Keep generations monotonic across navigation, including A -> B -> A:
+ // matching the Session id again must not admit A's earlier detail response.
+ dispatchLive({ type: 'reset' });
setActivityCardExpanded(false);
setExpandedActivity({});
setLoadingActivity({});
@@ -1595,7 +1598,7 @@ export const ChatPage: React.FC = () => {
window.clearTimeout(graceResyncRef.current);
graceResyncRef.current = null;
}
- }, [api, sessionId, applyLocalSession]);
+ }, [api, sessionId, applyLocalSession, dispatchLive]);
// Persistent per-session subscription: append every transcript-visible
// ``message.new`` for THIS session for as long as the page is open. An agent
@@ -1622,6 +1625,14 @@ export const ChatPage: React.FC = () => {
// new chat (Codex P2).
onMessageNew: (msg) => {
if (msg.session_id !== sessionIdRef.current) return;
+ // Activity lifecycle belongs to the Session, not its transcript viewport.
+ // Apply it before history/cap filters can drop the message from this view;
+ // detached completions only refresh storage, never reset the live group.
+ if (showAgentActivityRef.current && shouldRefreshAgentActivityForMessage(msg)) {
+ if (isTerminalAgentMessage(msg)) dispatchLive({ type: 'settle' });
+ else if (isAgentActivityBoundaryMessage(msg)) dispatchLive({ type: 'reset' });
+ scheduleActivityRefresh();
+ }
// Agent Activity rows (assistant / tool_call) only reach the browser when
// the toggle streams them (message_mirror). Route them to the running
// buffer — never the transcript. ``isTranscriptMessage`` already excludes
@@ -1648,12 +1659,6 @@ export const ChatPage: React.FC = () => {
// Harness live rows can precede read-side provenance enrichment. Pull
// the enriched REST row so trigger/source chips update without reload.
if (needsHarnessProvenanceReconcile(msg)) void reconcile();
- // Rebuild durable Activity groups for a phase boundary, terminal reply, or
- // detached completion. Only a terminal reply owns this live generation.
- if (showAgentActivityRef.current && shouldRefreshAgentActivityForMessage(msg)) {
- if (isTerminalAgentMessage(msg)) dispatchLive({ type: 'settle' });
- scheduleActivityRefresh();
- }
// Don't clear ``working`` from a result row here: with the queue, a
// result can belong to an EARLIER turn while a newer queued turn is
// already running, so clearing on it would hide Stop on the live turn
diff --git a/ui/src/lib/agentActivity.order.fixture.json b/ui/src/lib/agentActivity.order.fixture.json
new file mode 100644
index 000000000..d3cd705d1
--- /dev/null
+++ b/ui/src/lib/agentActivity.order.fixture.json
@@ -0,0 +1,48 @@
+{
+ "rows": [
+ {
+ "id": "evt_opaque_A",
+ "kind": "tool_call",
+ "text": "opaque tool A",
+ "created_at": "2026-09-05T00:00:00Z",
+ "order_micros": 1788566400000000
+ },
+ {
+ "id": "evt_opaque_a",
+ "kind": "tool_call",
+ "text": "opaque tool a",
+ "created_at": "2026-09-05T00:00:00Z",
+ "order_micros": 1788566400000000
+ },
+ {
+ "id": "msg_0065ab110ede3e812345678",
+ "kind": "assistant",
+ "text": "assistant step",
+ "created_at": "2026-09-05T00:00:00Z",
+ "order_micros": 1788566400001000
+ },
+ {
+ "id": "evt_legacy_ffffffffffffffffffffffff",
+ "kind": "tool_call",
+ "text": "earlier migrated tool",
+ "created_at": "2026-09-05T00:00:00Z",
+ "order_micros": 1788566400002000,
+ "legacy_message_id": "msg_0065ab110ede7d012345678"
+ },
+ {
+ "id": "evt_0065ab110edebb812345678",
+ "kind": "tool_call",
+ "text": "current tool",
+ "created_at": "2026-09-05T00:00:00Z",
+ "order_micros": 1788566400003000
+ },
+ {
+ "id": "evt_legacy_000000000000000000000000",
+ "kind": "tool_call",
+ "text": "later migrated tool",
+ "created_at": "2026-09-05T00:00:00Z",
+ "order_micros": 1788566400004000,
+ "legacy_message_id": "msg_0065ab110edefa012345678"
+ }
+ ]
+}
diff --git a/ui/src/lib/agentActivity.test.ts b/ui/src/lib/agentActivity.test.ts
index 5bb861ecd..c1507a567 100644
--- a/ui/src/lib/agentActivity.test.ts
+++ b/ui/src/lib/agentActivity.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, it } from 'vitest';
import type { WorkbenchMessage } from '../context/ApiContext';
+import orderFixture from './agentActivity.order.fixture.json';
import {
activityGroupsForForeground,
activityRowFromMessage,
@@ -349,7 +350,10 @@ describe('activityRowFromMessage', () => {
});
describe('liveActivityReducer (generation invariant)', () => {
- const row = (id: string): ActivityRow => ({ id, kind: 'tool_call', text: id, created_at: `t-${id}` });
+ const row = (id: string): ActivityRow => ({
+ id, kind: 'tool_call', text: id,
+ created_at: new Date(Date.UTC(2026, 8, 5, 0, 0, Number(id) || 0)).toISOString(),
+ });
it('turn_start bumps the generation and clears the buffer', () => {
let s = initialLiveActivity();
@@ -410,7 +414,7 @@ describe('liveActivityReducer (generation invariant)', () => {
expect(cleared.rows).toEqual([]);
});
- it('rehydrate_for_gen fills only an empty buffer of the current generation', () => {
+ it('rehydrate_for_gen preserves the live tail and only applies to its generation', () => {
const s = liveActivityReducer(initialLiveActivity(), { type: 'turn_start' });
const gen = s.gen;
const hydrated = liveActivityReducer(s, {
@@ -420,11 +424,110 @@ describe('liveActivityReducer (generation invariant)', () => {
startedAt: 50,
});
expect(hydrated.rows.map((r) => r.id)).toEqual(['x', 'y']);
- // Does not clobber an already-filled buffer, nor a stale generation:
+ // Re-reading a snapshot preserves newer live rows without duplicating overlap.
const withLive = liveActivityReducer(hydrated, { type: 'row', row: row('z'), now: 60 });
- const noClobber = liveActivityReducer(withLive, { type: 'rehydrate_for_gen', gen, rows: [row('w')], startedAt: 70 });
+ const noClobber = liveActivityReducer(withLive, { type: 'rehydrate_for_gen', gen, rows: [row('x'), row('y')], startedAt: 50 });
expect(noClobber.rows.map((r) => r.id)).toEqual(['x', 'y', 'z']);
const staleGen = liveActivityReducer(hydrated, { type: 'rehydrate_for_gen', gen: gen - 1, rows: [row('w')], startedAt: 70 });
expect(staleGen.rows.map((r) => r.id)).toEqual(['x', 'y']);
});
+
+ it('merges durable history with overlapping live rows in emission order', () => {
+ const history = Array.from({ length: 300 }, (_, index) => row(String(index)));
+ let state = liveActivityReducer(initialLiveActivity(), { type: 'turn_start' });
+ state = liveActivityReducer(state, { type: 'row', row: history[299], now: 500 });
+ state = liveActivityReducer(state, { type: 'row', row: row('300'), now: 600 });
+ state = liveActivityReducer(state, {
+ type: 'rehydrate_for_gen', gen: state.gen, rows: history, startedAt: 100,
+ });
+ expect(state.rows).toEqual([...history, row('300')]);
+ expect(state.startedAt).toBe(100);
+ expect(liveActivityReducer(state, { type: 'row', row: history[299], now: 700 })).toBe(state);
+ });
+
+ it.each(['overlapping', 'disjoint'] as const)('retains emission order when the durable window moves (%s)', (window) => {
+ const rows = Array.from({ length: 6 }, (_, i): ActivityRow => ({
+ id: `${i % 2 ? 'evt' : 'msg'}_${(1_700_000_000_000_000 + i).toString(16).padStart(15, '0')}12345678`,
+ kind: i % 2 ? 'tool_call' : 'assistant',
+ text: `step ${i}`,
+ created_at: '2023-11-14T22:13:20Z',
+ }));
+ let state = liveActivityReducer(initialLiveActivity(), {
+ type: 'rehydrate_for_gen', gen: 0, rows: rows.slice(0, 3), startedAt: 100,
+ });
+ state = liveActivityReducer(state, {
+ type: 'rehydrate_for_gen', gen: state.gen,
+ rows: rows.slice(window === 'overlapping' ? 2 : 3), startedAt: 200,
+ });
+ expect(state.rows).toEqual(rows);
+ expect(state.startedAt).toBe(100);
+ });
+
+ it.each(['legacy ids', 'clock ids'] as const)('preserves durable tie order across hydration windows with %s', (idShape) => {
+ // The endpoint orders equal emission clocks by id, not locale or source.
+ const ids = idShape === 'legacy ids'
+ ? ['evt_A', 'evt_a', 'msg_A', 'msg_a', 'opaque_A', 'opaque_a']
+ : Array.from({ length: 6 }, (_, i) => `${i < 3 ? 'evt' : 'msg'}_${(1_700_000_000_000_000).toString(16).padStart(15, '0')}${String(i).padStart(8, '0')}`);
+ const rows = ids.map((id, i): ActivityRow => ({
+ id, kind: id.startsWith('msg_') ? 'assistant' : 'tool_call', text: `step ${i}`,
+ created_at: '2023-11-14T22:13:20Z',
+ }));
+ // Cover every boundary, including a later disjoint snapshot and a stale
+ // earlier snapshot after reconnect. The union must always match durable order.
+ for (let split = 1; split < rows.length; split += 1) {
+ for (const overlap of [0, 1]) {
+ const windows = [rows.slice(0, split), rows.slice(split - overlap)];
+ for (const snapshots of [windows, [...windows].reverse()]) {
+ let state = initialLiveActivity();
+ for (const snapshot of snapshots) {
+ state = liveActivityReducer(state, {
+ type: 'rehydrate_for_gen', gen: state.gen, rows: snapshot, startedAt: 100,
+ });
+ }
+ expect(state.rows).toEqual(rows);
+ }
+ }
+ }
+ });
+
+ it('does not rehydrate a settled generation or the next turn', () => {
+ let state = liveActivityReducer(initialLiveActivity(), { type: 'turn_start' });
+ const late = { type: 'rehydrate_for_gen' as const, gen: state.gen, rows: [row('old')], startedAt: 1 };
+ state = liveActivityReducer(state, { type: 'settle' });
+ expect(liveActivityReducer(state, late)).toBe(state);
+ state = liveActivityReducer(state, { type: 'turn_start' });
+ expect(liveActivityReducer(state, late)).toBe(state);
+ });
+});
+
+describe('durable Activity order contract', () => {
+ // This same fixture is asserted against real SQLite grouping by the Python
+ // service test, including migrated tool hashes whose clocks are metadata-only.
+ const wireRows = orderFixture.rows.map(({ id, kind, text, created_at, order_micros }) => ({
+ id, kind: kind as ActivityRow['kind'], text, created_at, order_micros,
+ }));
+ const rows = groupFromWire({
+ id: wireRows[0].id, anchor_message_id: null, anchor_position: 'after',
+ open: true, status: 'interrupted', steps: wireRows.length, duration_ms: null,
+ rows: wireRows,
+ }).rows!;
+
+ it.each(['forward', 'reverse'] as const)('preserves server ordering across %s hydration windows and live overlap', (arrival) => {
+ for (let split = 0; split <= rows.length; split += 1) {
+ const snapshots = [rows.slice(0, split), rows.slice(Math.max(0, split - 1))];
+ if (arrival === 'reverse') snapshots.reverse();
+ const migrated = wireRows[3];
+ let state = liveActivityReducer(initialLiveActivity(), {
+ type: 'row', now: 100,
+ row: { id: migrated.id, kind: migrated.kind, text: migrated.text, created_at: migrated.created_at },
+ });
+ for (const snapshot of snapshots) {
+ state = liveActivityReducer(state, {
+ type: 'rehydrate_for_gen', gen: state.gen, rows: snapshot, startedAt: 100,
+ });
+ }
+ expect(state.rows).toEqual(wireRows);
+ expect(liveActivityReducer(state, { type: 'row', row: rows[3], now: 200 })).toBe(state);
+ }
+ });
});
diff --git a/ui/src/lib/agentActivity.ts b/ui/src/lib/agentActivity.ts
index 973729b3a..e7d1ff522 100644
--- a/ui/src/lib/agentActivity.ts
+++ b/ui/src/lib/agentActivity.ts
@@ -1,5 +1,6 @@
import type { WorkbenchMessage } from '../context/ApiContext';
import { specFor } from './messageTypes';
+import { timestampOrderTimeMs } from './transcriptOrder';
// One turn's activity, as rendered by the Chat Activity panel. Mirrors the
// backend ``storage/agent_activity_service.py`` shape (see the /activity endpoint).
@@ -10,6 +11,19 @@ export type ActivityRow = {
kind: 'assistant' | 'tool_call';
text: string;
created_at: string;
+ order_micros?: number; // authoritative durable key; absent on live SSE rows
+};
+
+// Storage owns persisted order, including clocks recovered from migration metadata.
+// Live rows without a durable key still carry their emission clock in the id.
+const activityRowTimeMs = (row: ActivityRow): number => {
+ if (row.order_micros !== undefined) return row.order_micros / 1000;
+ const clock = /^[^_]{3}_([0-9a-f]{15})/i.exec(row.id)?.[1];
+ if (clock) {
+ const micros = Number.parseInt(clock, 16);
+ if (Number.isSafeInteger(micros)) return micros / 1000;
+ }
+ return timestampOrderTimeMs(row.created_at);
};
// A group is positioned relative to a transcript message that is AT OR BEFORE the
@@ -69,7 +83,7 @@ export type TurnActivityGroupWire = {
duration_ms: number | null;
started_at?: string | null;
ended_at?: string | null;
- rows?: Array<{ id: string; kind: 'assistant' | 'tool_call'; text: string; created_at: string }>;
+ rows?: Array<{ id: string; kind: 'assistant' | 'tool_call'; text: string; created_at: string; order_micros?: number }>;
};
export const groupFromWire = (wire: TurnActivityGroupWire): ActivityGroup => ({
@@ -81,7 +95,9 @@ export const groupFromWire = (wire: TurnActivityGroupWire): ActivityGroup => ({
steps: wire.steps,
durationMs: wire.duration_ms ?? null,
startedAt: wire.started_at ?? null,
- rows: wire.rows?.map((r) => ({ id: r.id, kind: r.kind, text: r.text, created_at: r.created_at })),
+ rows: wire.rows?.map((r) => ({
+ id: r.id, kind: r.kind, text: r.text, created_at: r.created_at, order_micros: r.order_micros,
+ })),
});
// A live ``message.new`` of type assistant/tool_call → an activity row (the live
@@ -95,7 +111,7 @@ export const activityRowFromMessage = (msg: WorkbenchMessage): ActivityRow => ({
// ===== Live running-card buffer: a pure state machine (state, not timing) =====
// The live buffer drives ONLY the in-flight running card; all SETTLED groups come
-// from the durable endpoint. Each turn is tagged with a monotonic GENERATION so
+// from the durable endpoint. Each Activity phase is tagged with a monotonic GENERATION so
// that a stale buffer is invisible by construction and a late settle-refresh is a
// structural no-op for a newer turn:
// - the running card renders only while ``working`` AND ``rows`` are non-empty,
@@ -105,7 +121,7 @@ export const activityRowFromMessage = (msg: WorkbenchMessage): ActivityRow => ({
// resolution is dropped). This subsumes the "stale/late buffer" class without
// promise-cancellation or grace-timer bookkeeping.
export type LiveActivityState = {
- gen: number; // current turn generation (monotonic)
+ gen: number; // current Activity phase generation (monotonic)
settled: boolean; // the current generation has settled (terminal / turn.end seen)
rows: ActivityRow[]; // current-generation buffer (empty ⇒ nothing to show)
startedAt: number | null; // elapsed-clock start for the running card
@@ -148,10 +164,12 @@ export const liveActivityReducer = (
// previous generation are dropped by construction).
return { gen: state.gen + 1, settled: false, rows: [], startedAt: null };
case 'reset':
- // Turning Activity off invalidates every in-flight refresh from the visible
- // generation. Re-enabling may then hydrate only the current durable turn.
+ // Visibility changes, navigation and output phase boundaries invalidate
+ // every in-flight read from the previous visible group without settling work.
return { gen: state.gen + 1, settled: false, rows: [], startedAt: null };
case 'row':
+ // Storage hydration can include a row before its SSE envelope arrives.
+ if (state.rows.some((row) => row.id === event.row.id)) return state;
if (state.settled) {
// First row after a settle with no turn.start = an agent-initiated new turn.
return { gen: state.gen + 1, settled: false, rows: [event.row], startedAt: event.now };
@@ -169,11 +187,19 @@ export const liveActivityReducer = (
// this resolution is a stale no-op and must not wipe the new turn's rows).
return event.gen === state.gen ? { ...state, rows: [], startedAt: null } : state;
case 'rehydrate_for_gen':
- // In-flight re-hydrate from storage, only if still the current generation and
- // the live stream hasn't already filled the buffer.
- return event.gen === state.gen && state.rows.length === 0
- ? { ...state, rows: event.rows, startedAt: event.startedAt }
- : state;
+ if (event.gen !== state.gen || state.settled) return state;
+ // Match storage's (emission time, id) order even when its bounded window
+ // advances. Stable timestamp-only sorting would move retained tied rows last.
+ // Durable rows win overlap so SSE cannot erase storage-only ordering keys.
+ return {
+ ...state,
+ rows: [...new Map([...state.rows, ...event.rows].map((row) => [row.id, row])).values()]
+ .sort((a, b) => {
+ const timeOrder = activityRowTimeMs(a) - activityRowTimeMs(b);
+ return timeOrder || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
+ }),
+ startedAt: Math.min(state.startedAt ?? event.startedAt, event.startedAt),
+ };
default:
return state;
}
diff --git a/ui/src/lib/chatMessageTypes.test.ts b/ui/src/lib/chatMessageTypes.test.ts
index 3f345cedf..4948c41a1 100644
--- a/ui/src/lib/chatMessageTypes.test.ts
+++ b/ui/src/lib/chatMessageTypes.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, it } from 'vitest';
import {
+ isAgentActivityBoundaryMessage,
isBoundaryMessage,
isDetachedCompletionMessage,
isNotifyMessageType,
@@ -103,6 +104,24 @@ describe('isBoundaryMessage', () => {
});
});
+describe('isAgentActivityBoundaryMessage', () => {
+ it('advances Activity only for the catalog effective boundary role', () => {
+ for (const type of messageTypeNames()) {
+ const spec = specFor(type);
+ for (const detached of [false, true]) {
+ for (const event of [undefined, ...spec.terminalWhenEvents]) {
+ const message = { type, metadata: { detached, event } };
+ const isBoundary = spec.activityRole === 'boundary'
+ && !(detached && spec.detachedCompletion)
+ && event === undefined;
+ expect(isAgentActivityBoundaryMessage({ ...message, author: 'agent' }), type).toBe(isBoundary);
+ expect(isAgentActivityBoundaryMessage({ ...message, author: 'user' }), type).toBe(false);
+ }
+ }
+ }
+ });
+});
+
describe('isDetachedCompletionMessage', () => {
it('classifies lifecycle provenance independently from presentation', () => {
for (const type of ['result', 'error', 'notify']) {
diff --git a/ui/src/lib/chatMessageTypes.ts b/ui/src/lib/chatMessageTypes.ts
index 9e89c10a2..a2dc0e9c8 100644
--- a/ui/src/lib/chatMessageTypes.ts
+++ b/ui/src/lib/chatMessageTypes.ts
@@ -62,6 +62,12 @@ export const isTerminalAgentMessage = (message: TerminalAgentMessageCandidate):
return spec.transcript && activityRoleForMessage(message) === 'terminal';
};
+// A phase boundary advances the Activity group without settling the Turn.
+// Presentation's isBoundaryMessage also includes detached legacy completions,
+// which must not invalidate the foreground group's live rows or hydration.
+export const isAgentActivityBoundaryMessage = (message: TerminalAgentMessageCandidate): boolean =>
+ message.author === 'agent' && activityRoleForMessage(message) === 'boundary';
+
// Terminal replies, nonterminal phase boundaries, and detached completions all
// require a durable Activity refresh. Only terminal replies settle the live Turn.
export const shouldRefreshAgentActivityForMessage = (