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.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(workbench): anchor interrupted activity chips backward, never the tail (#935)
Call Whitec42fce5fa390
diff --git a/docs/plans/chat-agent-activity-panel.md b/docs/plans/chat-agent-activity-panel.mdindex 04274088e..e24470ed0 100644--- a/docs/plans/chat-agent-activity-panel.md+++ b/docs/plans/chat-agent-activity-panel.md@@ -188,17 +188,40 @@ read by ChatPage from `bootstrap.config.ui.show_agent_activity`.reads `messages` + `agent_events` via storage services; 404 on unknown session):- **summary** (no params) — one entry per turn with ≥1 activity row, no row text:- `{"groups": [{"id", "anchor_message_id", "status", "steps", "started_at",- "ended_at", "duration_ms"}]}`. Loaded once on chat open so past turns show a chip.+ `{"groups": [{"id", "anchor_message_id", "anchor_position", "open", "status",+ "steps", "started_at", "ended_at", "duration_ms"}]}`. Loaded once on chat open so+ past turns show a chip.- **detail** (`?group_id=<id>`) — that one group plus `"rows": [{"id", "kind"(`assistant`|`tool_call`), "text", "created_at"}]`. The lazy expand; 404 on anunknown group id.`status ∈ done | failed | interrupted`. `id` is the group's first-activity-row id-(stable key across summary/detail). `anchor_message_id` is the transcript message-the chip renders above — the terminal reply for done/failed, the next turn's opening-message for a history-interrupted turn, or `null` when the interrupted turn trails-the transcript. Grouping logic lives in `storage/agent_activity_service.py`; the+(stable key across summary/detail).++**Anchoring invariant (corrected — was a P1 rendering bug, fixed post-#934).** A+group is positioned relative to a transcript message that is **at or before the+group's own end — never a future message**:++- **done / failed** → `anchor_message_id` = the turn's terminal reply (`result` /+ `error` / backend-failure `notify`), `anchor_position = "before"` (the chip hugs+ the reply from above).+- **interrupted** → `anchor_message_id` = the boundary immediately *before* the+ turn's activity (its triggering user/harness message, tracked as+ `last_boundary_id`), `anchor_position = "after"` (the chip sits just below the+ trigger). It is NEVER anchored to the next turn's opener (a future message) and+ NEVER to the transcript tail.+- `open` = true only for the last un-terminated turn. The frontend promotes the+ `open` group into the tail **live running card** while the turn is running;+ otherwise it renders as an interrupted chip after its trigger. **The transcript+ tail is reserved exclusively for the live card** — a settled/interrupted chip is+ never placed there. `anchor_message_id` is `null` only in the degenerate+ no-prior-message case (rendered at the top, never the tail).++Original bug: interrupted turns anchored *forward* to the next turn's opening+message; while that message did not yet exist (or was minted much later) the+frontend fell back to the tail slot, so the "Interrupted" chip rendered below newer+messages and even below the next turn's live card. The backward-anchor invariant+fixes it at source. Grouping logic lives in `storage/agent_activity_service.py`; thelow-level read is `agent_events_service.list_session_events`.### (c) Timestamp-parsed turn-boundary groupingdiff --git a/storage/agent_activity_service.py b/storage/agent_activity_service.pyindex 9270d14b1..c4a1bf3fd 100644--- a/storage/agent_activity_service.py+++ b/storage/agent_activity_service.py@@ -208,6 +208,8 @@ def _make_group(*,status: str,anchor_id: Optional[str],+ anchor_position: str,+ open_turn: bool,started_iso: Optional[str],ended_iso: Optional[str],include_rows: bool,@@ -215,7 +217,15 @@ def _make_group(started = started_iso or pending[0]["created_at"]group: dict[str, Any] = {"id": pending[0]["id"],+ # A group is positioned relative to a transcript message that is AT OR BEFORE+ # the group's own end (never a future message): done/failed anchor to their+ # terminal reply (rendered BEFORE it — hug the reply from above); interrupted+ # anchor to the turn's trigger / the boundary before its activity (rendered+ # AFTER it). ``open_turn`` marks the last un-terminated turn — the only group+ # the frontend may promote into the tail live card while it is still running."anchor_message_id": anchor_id,+ "anchor_position": anchor_position,+ "open": open_turn,"status": status,"steps": len(pending),"started_at": started,@@ -239,6 +249,11 @@ def _build_groups(items: list[dict[str, Any]], *, include_rows: bool) -> list[digroups: list[dict[str, Any]] = []pending: list[dict[str, Any]] = []turn_start_iso: Optional[str] = None+ # Id of the most recent transcript-visible boundary (turn_start OR terminal). An+ # interrupted turn anchors BACKWARD to this — the boundary immediately before its+ # activity (its trigger) — so its chip is positioned by its OWN chronology and+ # never attaches to a future message (the ordering bug).+ last_boundary_id: Optional[str] = Nonefor item in items:kind = item["kind"]if kind == "activity":@@ -246,12 +261,15 @@ def _build_groups(items: list[dict[str, Any]], *, include_rows: bool) -> list[dielif kind == "turn_start":if pending:# Activity with no terminal before a new turn opened → interrupted;- # anchor the chip against the opening message of the next turn.+ # anchor AFTER the boundary that preceded this activity (its trigger),+ # NOT the next turn's opener. Not ``open`` — a later turn exists.groups.append(_make_group(pending,status="interrupted",- anchor_id=item["id"],+ anchor_id=last_boundary_id,+ anchor_position="after",+ open_turn=False,started_iso=turn_start_iso,ended_iso=pending[-1]["created_at"],include_rows=include_rows,@@ -259,6 +277,7 @@ def _build_groups(items: list[dict[str, Any]], *, include_rows: bool) -> list[di)pending = []turn_start_iso = item["created_at"]+ last_boundary_id = item["id"]elif kind == "terminal":if pending:groups.append(@@ -266,6 +285,8 @@ def _build_groups(items: list[dict[str, Any]], *, include_rows: bool) -> list[dipending,status=_terminal_status(item["mtype"]),anchor_id=item["id"],+ anchor_position="before",+ open_turn=False,started_iso=turn_start_iso,ended_iso=item["created_at"],include_rows=include_rows,@@ -273,14 +294,19 @@ def _build_groups(items: list[dict[str, Any]], *, include_rows: bool) -> list[di)pending = []turn_start_iso = None- # kind == "ignore": leave pending + turn_start untouched+ last_boundary_id = item["id"]+ # kind == "ignore": leave pending + boundary + turn_start untouchedif pending:- # Trailing interrupted turn (no following message): chip trails the transcript.+ # The last un-terminated turn. Anchor AFTER its trigger (never the tail); the+ # frontend renders it as an interrupted chip there, OR — while the turn is+ # still running — promotes it into the tail live card (``open``).groups.append(_make_group(pending,status="interrupted",- anchor_id=None,+ anchor_id=last_boundary_id,+ anchor_position="after",+ open_turn=True,started_iso=turn_start_iso,ended_iso=pending[-1]["created_at"],include_rows=include_rows,diff --git a/tests/test_agent_activity_service.py b/tests/test_agent_activity_service.pyindex 0683e0d30..9ab591186 100644--- a/tests/test_agent_activity_service.py+++ b/tests/test_agent_activity_service.py@@ -129,21 +129,32 @@ def test_done_failed_interrupted_and_trailing_groups(isolated_state):assert [g["status"] for g in groups] == ["done", "failed", "interrupted", "interrupted"]done = groups[0]- assert done["anchor_message_id"] == "m_r1"+ assert done["anchor_message_id"] == "m_r1" # own terminal+ assert done["anchor_position"] == "before" # chip hugs the reply from above+ assert done["open"] is Falseassert done["steps"] == 2 # assistant + tool_callassert done["duration_ms"] == 3000 # 10:00:00 → 10:00:03 (turn start → terminal)failed = groups[1]- assert failed["anchor_message_id"] == "m_er3"+ assert failed["anchor_message_id"] == "m_er3" # own terminal+ assert failed["anchor_position"] == "before"+ assert failed["open"] is Falseassert failed["steps"] == 1interrupted = groups[2]- # Anchored at the NEXT turn's opening message (chip sits above it).- assert interrupted["anchor_message_id"] == "m_u5"+ # Anchored AFTER its OWN trigger (m_u4), NOT the next turn's opener — never a+ # future message. It is not the last turn, so not ``open``.+ assert interrupted["anchor_message_id"] == "m_u4"+ assert interrupted["anchor_position"] == "after"+ assert interrupted["open"] is Falseassert interrupted["steps"] == 1trailing = groups[3]- assert trailing["anchor_message_id"] is None # trails the transcript+ # The last un-terminated turn: anchored AFTER its OWN trigger (m_u5), never null+ # / the tail; ``open`` so the frontend may promote it into the live card.+ assert trailing["anchor_message_id"] == "m_u5"+ assert trailing["anchor_position"] == "after"+ assert trailing["open"] is Trueassert trailing["steps"] == 1# ``id`` is the first activity row's id (stable key for lazy detail).@@ -333,6 +344,110 @@ def test_show_page_user_marks_do_not_split_a_turn(isolated_state):assert groups[0]["steps"] == 2+def test_interrupted_followed_by_running_turn_anchors_to_own_trigger(isolated_state):+ """(a) Interrupted turn followed by a still-RUNNING next turn — the P1 repro.+ The interrupted chip must anchor AFTER its OWN trigger (above the newer turn),+ NEVER forward to the next turn's opener nor to the tail."""+ engine = create_sqlite_engine()+ sid = "ses_ia"+ with engine.begin() as conn:+ scope = _seed_session(conn, session_id=sid)+ _msg(conn, scope, sid, mid="m_u1", mtype="user", author="user", created_at="2026-06-01T10:00:00Z", text="q1", source="user")+ _evt(conn, scope, sid, eid="e_1", created_at="2026-06-01T10:00:01Z", text="🔧 `Bash`")+ _msg(conn, scope, sid, mid="m_r1", mtype="result", author="agent", created_at="2026-06-01T10:00:02Z", text="a1")+ _msg(conn, scope, sid, mid="m_u2", mtype="user", author="user", created_at="2026-06-01T10:01:00Z", text="q2", source="user")+ _evt(conn, scope, sid, eid="e_2", created_at="2026-06-01T10:01:01Z", text="🔧 `Read`") # turn2 (interrupted)+ _msg(conn, scope, sid, mid="m_u3", mtype="user", author="user", created_at="2026-06-01T10:02:00Z", text="q3", source="user")+ _evt(conn, scope, sid, eid="e_3", created_at="2026-06-01T10:02:01Z", text="🔧 `Bash`") # turn3 running (no terminal)++ with engine.connect() as conn:+ groups = agent_activity_service.list_turn_groups(conn, session_id=sid)["groups"]+ assert [g["status"] for g in groups] == ["done", "interrupted", "interrupted"]+ turn1, turn2, turn3 = groups+ assert turn1["anchor_message_id"] == "m_r1" and turn1["anchor_position"] == "before"+ # turn2 anchors to its OWN trigger (m_u2) — above m_u3, never the future opener.+ assert turn2["anchor_message_id"] == "m_u2"+ assert turn2["anchor_position"] == "after"+ assert turn2["open"] is False+ # turn3 is the open (running-candidate) turn: own trigger, open (→ live card).+ assert turn3["anchor_message_id"] == "m_u3" and turn3["open"] is True+++def test_interrupted_followed_by_completed_turn_ordering(isolated_state):+ """(b) Interrupted turn followed by a COMPLETED next turn — same ordering:+ interrupted after its trigger, the next turn done at its own reply."""+ engine = create_sqlite_engine()+ sid = "ses_ib"+ with engine.begin() as conn:+ scope = _seed_session(conn, session_id=sid)+ _msg(conn, scope, sid, mid="m_u2", mtype="user", author="user", created_at="2026-06-01T10:01:00Z", text="q2", source="user")+ _evt(conn, scope, sid, eid="e_2", created_at="2026-06-01T10:01:01Z", text="🔧 `Read`") # interrupted turn+ _msg(conn, scope, sid, mid="m_u3", mtype="user", author="user", created_at="2026-06-01T10:02:00Z", text="q3", source="user")+ _evt(conn, scope, sid, eid="e_3", created_at="2026-06-01T10:02:01Z", text="🔧 `Bash`")+ _msg(conn, scope, sid, mid="m_r3", mtype="result", author="agent", created_at="2026-06-01T10:02:02Z", text="a3")++ with engine.connect() as conn:+ groups = agent_activity_service.list_turn_groups(conn, session_id=sid)["groups"]+ assert [g["status"] for g in groups] == ["interrupted", "done"]+ interrupted, done = groups+ assert interrupted["anchor_message_id"] == "m_u2"+ assert interrupted["anchor_position"] == "after"+ assert interrupted["open"] is False+ assert done["anchor_message_id"] == "m_r3"+ assert done["anchor_position"] == "before"+ assert done["open"] is False+++def test_failed_turn_anchors_to_its_own_terminal(isolated_state):+ """(c) A failed turn anchors to its OWN error terminal (rendered before it),+ never forward — even when a later turn follows."""+ engine = create_sqlite_engine()+ sid = "ses_ic"+ with engine.begin() as conn:+ scope = _seed_session(conn, session_id=sid)+ _msg(conn, scope, sid, mid="m_u1", mtype="user", author="user", created_at="2026-06-01T10:00:00Z", text="q1", source="user")+ _evt(conn, scope, sid, eid="e_1", created_at="2026-06-01T10:00:01Z", text="🔧 `Bash`")+ _msg(conn, scope, sid, mid="m_err", mtype="error", author="agent", created_at="2026-06-01T10:00:02Z", text="boom")+ _msg(conn, scope, sid, mid="m_u2", mtype="user", author="user", created_at="2026-06-01T10:01:00Z", text="q2", source="user")++ with engine.connect() as conn:+ groups = agent_activity_service.list_turn_groups(conn, session_id=sid)["groups"]+ assert [g["status"] for g in groups] == ["failed"]+ assert groups[0]["anchor_message_id"] == "m_err" # own terminal, not the later m_u2+ assert groups[0]["anchor_position"] == "before"+ assert groups[0]["open"] is False+++def test_send_while_busy_override_interrupt_anchors_backward(isolated_state):+ """(d) Owner's exact repro: quick-reply send then a second send OVERRIDES the+ running turn. The overridden turn is interrupted; its chip must anchor after its+ OWN trigger (above the override message + the new running turn), never forward to+ the override message nor to the tail. Microsecond-encoded ids under tight+ (same-second) override timing."""+ engine = create_sqlite_engine()+ sid = "ses_id"+ base = 1_800_000_000_000_000+ trig2 = _clock_id("msg", base + 0) # turn2 trigger (quick-reply send)+ over3 = _clock_id("msg", base + 2_000_000) # override send → turn3 trigger+ with engine.begin() as conn:+ scope = _seed_session(conn, session_id=sid)+ _msg(conn, scope, sid, mid=trig2, mtype="user", author="user", created_at="2026-06-01T10:00:00Z", text="q2", source="user")+ _evt(conn, scope, sid, eid=_clock_id("evt", base + 1_000_000), created_at="2026-06-01T10:00:00Z", text="🔧 `Bash`") # turn2 activity+ _msg(conn, scope, sid, mid=over3, mtype="user", author="user", created_at="2026-06-01T10:00:00Z", text="q3 override", source="user")+ _evt(conn, scope, sid, eid=_clock_id("evt", base + 3_000_000), created_at="2026-06-01T10:00:01Z", text="🔧 `Read`") # turn3 running++ with engine.connect() as conn:+ groups = agent_activity_service.list_turn_groups(conn, session_id=sid)["groups"]+ assert [g["status"] for g in groups] == ["interrupted", "interrupted"]+ turn2, turn3 = groups+ # The overridden turn anchors to its OWN trigger, NOT the override message, NOT null.+ assert turn2["anchor_message_id"] == trig2+ assert turn2["anchor_message_id"] != over3+ assert turn2["anchor_position"] == "after"+ assert turn2["open"] is False+ assert turn3["anchor_message_id"] == over3 and turn3["open"] is True++def test_get_turn_group_unknown_id_returns_none(isolated_state):engine = create_sqlite_engine()sid = "ses_none"diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsxindex c663307b9..2341050a1 100644--- a/ui/src/components/workbench/ChatPage.tsx+++ b/ui/src/components/workbench/ChatPage.tsx@@ -422,7 +422,10 @@ export const ChatPage: React.FC = () => {}if (sid !== sessionIdRef.current) return true;const fetched = (res.groups ?? []).map(groupFromWire);- const inflightIdx = running ? fetched.findIndex((g) => g.anchorMessageId === null) : -1;+ // The last un-terminated turn is the ``open`` group. While a turn is running it+ // IS that turn — promote it into the live card (re-hydrate) rather than render+ // it as a chip; otherwise it renders as an interrupted chip after its trigger.+ const inflightIdx = running ? fetched.findIndex((g) => g.open) : -1;const inflight = inflightIdx >= 0 ? fetched[inflightIdx] : null;const groups = inflight ? fetched.filter((_, i) => i !== inflightIdx) : fetched;// Settled groups are always safe to replace (storage is authoritative);@@ -1637,19 +1640,28 @@ export const ChatPage: React.FC = () => {return urls;}, [messages]);- // Agent Activity chips are positioned by anchor message id; a null-anchor group- // is the one interrupted turn that trails the transcript.+ // Agent Activity chips are positioned relative to a transcript message: 'before'+ // it (done/failed, hugging the reply) or 'after' it (interrupted, below the+ // trigger). Both keyed by anchor id → array (a message can have both, e.g. a done+ // chip before it and an agent-initiated interrupted chip after it). A null anchor+ // (degenerate no-prior-message case) renders at the TOP — never the tail, which+ // belongs exclusively to the live running card.const activityByAnchor = useMemo(() => {- const map = new Map<string, ActivityGroup>();+ const before = new Map<string, ActivityGroup[]>();+ const after = new Map<string, ActivityGroup[]>();+ const top: ActivityGroup[] = [];for (const group of activityGroups) {- if (group.anchorMessageId) map.set(group.anchorMessageId, group);+ if (!group.anchorMessageId) {+ top.push(group);+ continue;+ }+ const map = group.anchorPosition === 'before' ? before : after;+ const list = map.get(group.anchorMessageId);+ if (list) list.push(group);+ else map.set(group.anchorMessageId, [group]);}- return map;+ return { before, after, top };}, [activityGroups]);- const trailingActivity = useMemo(- () => activityGroups.find((group) => group.anchorMessageId === null) ?? null,- [activityGroups],- );// Lazy-load a group's rows from the endpoint (history chips arrive as summary// only). On failure, record an error so the chip offers retry instead of showing// a misleading "no activity" empty state.@@ -1832,8 +1844,9 @@ export const ChatPage: React.FC = () => {followingTailRef={followingTailRef}activity={{enabled: showAgentActivity,- byAnchor: activityByAnchor,- trailing: trailingActivity,+ beforeAnchor: activityByAnchor.before,+ afterAnchor: activityByAnchor.after,+ topGroups: activityByAnchor.top,liveRows,liveStartedAt,cardExpanded: activityCardExpanded,@@ -2453,8 +2466,9 @@ interface TranscriptProps {// transcript renders exactly as before — the ThinkingBubble and nothing else).activity?: {enabled: boolean;- byAnchor: Map<string, ActivityGroup>;- trailing: ActivityGroup | null;+ beforeAnchor: Map<string, ActivityGroup[]>;+ afterAnchor: Map<string, ActivityGroup[]>;+ topGroups: ActivityGroup[];liveRows: ActivityRow[];liveStartedAt: number | null;cardExpanded: boolean;@@ -2584,6 +2598,20 @@ const Transcript: React.FC<TranscriptProps> = ({const liveActive = !!activity?.enabled && activity.liveRows.length > 0;const showActivityCard = shouldShowRunningCard(!!activity?.enabled, working, activity?.liveRows.length ?? 0);const showThinking = working && !lastIsAgentTerminal && !liveActive;+ // Render one settled-turn chip (before/after its anchor message, or at the top).+ // Plain render helper (not a component) so it stays referentially simple.+ const renderActivityChip = (group: ActivityGroup) =>+ activity ? (+ <ActivityChip+ key={group.id}+ group={group}+ expanded={!!activity.expanded[group.id]}+ loading={!!activity.loading[group.id]}+ error={!!activity.error[group.id]}+ onToggle={() => activity.onToggleGroup(group)}+ onRetry={() => activity.onRetryGroup(group)}+ />+ ) : null;const empty = messages.length === 0 && !working;// Capture the topmost (partly) visible row as the restore anchor. Viewport-@@ -2832,22 +2860,17 @@ const Transcript: React.FC<TranscriptProps> = ({<Loader2 className="size-4 animate-spin" /></div>)}+ {/* Degenerate null-anchor groups render at the TOP (never the tail). */}+ {activity?.enabled && activity.topGroups.map((group) => renderActivityChip(group))}{messages.map((message) => {- // Agent Activity chip for the turn whose reply (or next opening- // message) is THIS row — rendered directly above it.- const chip = activity?.enabled ? activity.byAnchor.get(message.id) : undefined;+ // Agent Activity chips positioned relative to THIS row: 'before' it+ // (done/failed, hugging the reply from above) and 'after' it (interrupted,+ // just below the turn's trigger).+ const before = activity?.enabled ? activity.beforeAnchor.get(message.id) : undefined;+ const after = activity?.enabled ? activity.afterAnchor.get(message.id) : undefined;return (<Fragment key={message.id}>- {chip && (- <ActivityChip- group={chip}- expanded={!!activity!.expanded[chip.id]}- loading={!!activity!.loading[chip.id]}- error={!!activity!.error[chip.id]}- onToggle={() => activity!.onToggleGroup(chip)}- onRetry={() => activity!.onRetryGroup(chip)}- />- )}+ {before?.map((group) => renderActivityChip(group))}<MessageRowmessage={message}session={session}@@ -2855,9 +2878,12 @@ const Transcript: React.FC<TranscriptProps> = ({onQuickReply={onQuickReply}highlighted={message.id === highlightedId}/>+ {after?.map((group) => renderActivityChip(group))}</Fragment>);})}+ {/* The transcript TAIL is reserved exclusively for the live running card+ (or the ThinkingBubble fallback) — never a settled/interrupted chip. */}{showActivityCard && activity ? (<ActivityCardrows={activity.liveRows}@@ -2868,16 +2894,6 @@ const Transcript: React.FC<TranscriptProps> = ({) : showThinking ? (<ThinkingBubble session={session} />) : null}- {activity?.enabled && activity.trailing && (- <ActivityChip- group={activity.trailing}- expanded={!!activity.expanded[activity.trailing.id]}- loading={!!activity.loading[activity.trailing.id]}- error={!!activity.error[activity.trailing.id]}- onToggle={() => activity.onToggleGroup(activity.trailing!)}- onRetry={() => activity.onRetryGroup(activity.trailing!)}- />- )}{footer}</div></div>diff --git a/ui/src/lib/agentActivity.test.ts b/ui/src/lib/agentActivity.test.tsindex 754babc71..5d886a472 100644--- a/ui/src/lib/agentActivity.test.ts+++ b/ui/src/lib/agentActivity.test.ts@@ -93,10 +93,12 @@ describe('isActivityMessageType', () => {});describe('groupFromWire', () => {- it('maps snake_case wire fields to the camelCase group', () => {+ it('maps snake_case wire fields (incl. anchor_position + open) to the group', () => {const group = groupFromWire({id: 'm_a1',anchor_message_id: 'm_r1',+ anchor_position: 'before',+ open: false,status: 'done',steps: 3,duration_ms: 83000,@@ -104,20 +106,26 @@ describe('groupFromWire', () => {rows: [{ id: 'm_a1', kind: 'assistant', text: 'hi', created_at: '2026-06-01T10:00:01Z' }],});expect(group.anchorMessageId).toBe('m_r1');+ expect(group.anchorPosition).toBe('before');+ expect(group.open).toBe(false);expect(group.durationMs).toBe(83000);expect(group.rows).toHaveLength(1);expect(group.rows?.[0].kind).toBe('assistant');});- it('normalizes null anchor + missing duration/rows', () => {+ it('maps an open interrupted group anchored after its trigger', () => {const group = groupFromWire({id: 'e_t1',- anchor_message_id: null,+ anchor_message_id: 'm_u2',+ anchor_position: 'after',+ open: true,status: 'interrupted',steps: 1,duration_ms: null,});- expect(group.anchorMessageId).toBeNull();+ expect(group.anchorMessageId).toBe('m_u2');+ expect(group.anchorPosition).toBe('after');+ expect(group.open).toBe(true);expect(group.durationMs).toBeNull();expect(group.rows).toBeUndefined();});diff --git a/ui/src/lib/agentActivity.ts b/ui/src/lib/agentActivity.tsindex 4e69f73a2..cb4a1cd33 100644--- a/ui/src/lib/agentActivity.ts+++ b/ui/src/lib/agentActivity.ts@@ -11,15 +11,21 @@ export type ActivityRow = {created_at: string;};-// A group is positioned in the transcript by ``anchorMessageId`` (the chip renders-// directly above that message: the terminal reply for done/failed, the next turn's-// opening message for a history-interrupted turn). ``null`` = trails the transcript-// (the live running card, or an interrupted turn with no following message).-// ``rows`` is present once loaded (live snapshot or lazy fetch); absent = summary-// only (fetch on expand).+// A group is positioned relative to a transcript message that is AT OR BEFORE the+// group's own end (never a future message): done/failed anchor to their terminal+// reply with ``anchorPosition: 'before'`` (the chip hugs the reply from above);+// interrupted anchor to the boundary before their activity (the turn's trigger)+// with ``anchorPosition: 'after'`` (the chip sits just below the trigger). ``open``+// marks the last un-terminated turn — the ONLY group the frontend may promote into+// the tail live card while it is still running; the transcript tail is otherwise+// reserved exclusively for that live card. ``anchorMessageId`` is null only in the+// degenerate no-prior-message case (rendered at the top, never the tail). ``rows``+// is present once loaded (live snapshot or lazy fetch); absent = summary only.export type ActivityGroup = {id: string;anchorMessageId: string | null;+ anchorPosition: 'before' | 'after';+ open: boolean;status: ActivityStatus;steps: number;durationMs: number | null;@@ -31,6 +37,8 @@ export type ActivityGroup = {export type TurnActivityGroupWire = {id: string;anchor_message_id: string | null;+ anchor_position: 'before' | 'after';+ open: boolean;status: ActivityStatus;steps: number;duration_ms: number | null;@@ -42,6 +50,8 @@ export type TurnActivityGroupWire = {export const groupFromWire = (wire: TurnActivityGroupWire): ActivityGroup => ({id: wire.id,anchorMessageId: wire.anchor_message_id ?? null,+ anchorPosition: wire.anchor_position === 'before' ? 'before' : 'after',+ open: Boolean(wire.open),status: wire.status,steps: wire.steps,durationMs: wire.duration_ms ?? null,