Skip to content

Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.

refactor(bridges): let the agent decide when the indicator moves (CHOO-1104)

Louis Amaudruz9b53303133b5
diff --git a/core/switch_core/bridges/agent/api/handlers.py b/core/switch_core/bridges/agent/api/handlers.py
index 1c3c7648e..c6c9b67a9 100644
--- a/core/switch_core/bridges/agent/api/handlers.py
+++ b/core/switch_core/bridges/agent/api/handlers.py
@@ -607,6 +607,7 @@ async def set_runtime_state(
deeplink_url=req.deeplink_url,
detail=req.detail,
control_capabilities=req.control_capabilities,
+ anchor_event_id=req.anchor_event_id,
)
except ValueError as e:
raise HTTPException(status_code=404, detail=str(e)) from e
diff --git a/core/switch_core/bridges/agent/api/schemas.py b/core/switch_core/bridges/agent/api/schemas.py
index 06b486fa0..367902813 100644
--- a/core/switch_core/bridges/agent/api/schemas.py
+++ b/core/switch_core/bridges/agent/api/schemas.py
@@ -145,6 +145,12 @@ class RuntimeStateRequest(BaseModel):
# turn, when it was in a thread, so the bridge surfaces the state in that
# thread. Omit / null when the agent was addressed at the conversation root.
thread_id: str | None = None
+ # Message id of the latest message the connector has actually delivered to
+ # the agent's session. The bridge repositions the runtime indicator when
+ # this changes, so it only ever moves on evidence the agent has the
+ # message — not merely because one arrived. Report the same value on a
+ # periodic refresh; only a genuine change moves the indicator.
+ anchor_event_id: str | None = None
# A `switchdash://session?…` deeplink switchdash builds so the bridged
# working / awaiting-input message can link back to its session. Relayed
# verbatim to the channel; null for connectors that don't manage a UI.
diff --git a/core/switch_core/bridges/agent/protocol/service.py b/core/switch_core/bridges/agent/protocol/service.py
index ac5a6c3d5..ddf89a063 100644
--- a/core/switch_core/bridges/agent/protocol/service.py
+++ b/core/switch_core/bridges/agent/protocol/service.py
@@ -1001,6 +1001,7 @@ class ProtocolService:
deeplink_url: str | None = None,
detail: str | None = None,
control_capabilities: dict[str, bool] | None = None,
+ anchor_event_id: str | None = None,
) -> None:
"""Record and broadcast an agent's runtime state in a room.
@@ -1017,6 +1018,13 @@ class ProtocolService:
foo.py"); like `thread_id` it is transient and rides the event only —
the bridge surfaces it in place on the live working message.
+ `anchor_event_id` is the latest message the reporting connector has
+ actually handed to the agent's session. The bridge repositions the
+ indicator when it changes, so position follows what the agent has
+ genuinely been given rather than what merely arrived in the room. Also
+ transient routing — reported on every refresh, and only a change moves
+ anything.
+
The `switchdash://` deeplink is rewritten to a gateway HTTP redirect when
`GATEWAY_PUBLIC_URL` is configured, so the "Open in SwitchDash" link is
clickable on platforms that only linkify http(s) (Discord). The rewritten
@@ -1055,6 +1063,7 @@ class ProtocolService:
thread_id=thread_id,
deeplink_url=deeplink_url,
detail=detail,
+ anchor_event_id=anchor_event_id,
)
async def _emit_runtime_state(
@@ -1069,6 +1078,7 @@ class ProtocolService:
thread_id: str | None,
deeplink_url: str | None = None,
detail: str | None = None,
+ anchor_event_id: str | None = None,
) -> None:
client = self.client_lifecycle.get_by_agent_id(agent_id)
if client is None or client.nio_client is None:
@@ -1088,6 +1098,7 @@ class ProtocolService:
"thread_id": thread_id,
"deeplink_url": deeplink_url,
"detail": detail,
+ "anchor_event_id": anchor_event_id,
},
)
diff --git a/core/switch_core/bridges/collaboration/bridge_core.py b/core/switch_core/bridges/collaboration/bridge_core.py
index f684b56a2..ac38417cf 100644
--- a/core/switch_core/bridges/collaboration/bridge_core.py
+++ b/core/switch_core/bridges/collaboration/bridge_core.py
@@ -31,11 +31,7 @@ from switch_core.bridges.collaboration.models import (
)
from switch_core.clients.admin_messages import ADMIN_MARKER, AdminMessageType
from switch_core.clients.client_base import ClientBase, ClientConfig
-from switch_core.clients.mentions import (
- mention_regex,
- strip_emphasis,
- unique_mention_tokens,
-)
+from switch_core.clients.mentions import mention_regex, strip_emphasis
from switch_core.db.models import BridgeMessageMap, ExternalUser
from switch_core.db.stores.agent_store import AgentStore
from switch_core.db.stores.bridge_message_map_store import BridgeMessageMapStore
@@ -150,6 +146,9 @@ class BridgeCore:
# See _schedule_indicator_move.
self._indicator_move_timers: dict[tuple[str, str], asyncio.TimerHandle] = {}
self._indicator_move_targets: dict[tuple[str, str], str | None] = {}
+ # (channel_id, agent_name) -> the last message the agent reported having
+ # been handed. Cleared when its turn ends. See _follow_reported_anchor.
+ self._reported_anchors: dict[tuple[str, str], str] = {}
@property
def adapter(self) -> CollaborationAdapter:
@@ -444,14 +443,6 @@ class BridgeCore:
matrix_event_id=event_id,
external_post_id=msg.message_ref,
)
- await self._move_indicators_for_addressees(
- channel_id=msg.channel_id,
- room_id=room_id,
- channel_type=msg.channel_type,
- content=content,
- mention_target=mention_target,
- thread_root_id=msg.root_id,
- )
return
# Caption convention: the text rides as the caption on the first
@@ -497,15 +488,6 @@ class BridgeCore:
external_post_id=msg.message_ref,
)
- await self._move_indicators_for_addressees(
- channel_id=msg.channel_id,
- room_id=room_id,
- channel_type=msg.channel_type,
- content=content,
- mention_target=mention_target,
- thread_root_id=msg.root_id,
- )
-
async def _handle_inbound_command(self, cmd: InboundCommand) -> None:
room_ids = self._channel_to_room.get(cmd.channel_id)
if room_ids is None:
@@ -1330,6 +1312,48 @@ class BridgeCore:
deeplink_url=event.deeplink_url,
detail=event.detail,
)
+ await self._follow_reported_anchor(
+ channel_id,
+ event.agent_name,
+ event.state,
+ event.anchor_event_id,
+ thread_root_ref,
+ )
+
+ async def _follow_reported_anchor(
+ self,
+ channel_id: str,
+ agent_name: str,
+ state: str,
+ anchor_event_id: str | None,
+ thread_root_ref: str | None,
+ ) -> None:
+ """Move the indicator when the agent reports it has been handed a
+ newer message than the one it was last positioned against.
+
+ Position follows what the agent has actually received, not what merely
+ arrived in the room — a message the agent has not been given yet must
+ not make the indicator look like the agent has seen it. The periodic
+ activity refresh repeats the current anchor, so it never moves anything.
+ """
+ key = (channel_id, agent_name)
+ if state != "working":
+ self._reported_anchors.pop(key, None)
+ return
+ if anchor_event_id is None:
+ return
+
+ if self._reported_anchors.get(key) == anchor_event_id:
+ return
+ previous = self._reported_anchors.get(key)
+ self._reported_anchors[key] = anchor_event_id
+ if previous is None:
+ # First anchor of the turn — the indicator was only just posted
+ # against it, so there is nothing to move.
+ return
+
+ self._indicator_move_targets[key] = thread_root_ref
+ await self._run_indicator_move(key)
# ── Protection sync ──────────────────────────────────────────────────────
@@ -1367,77 +1391,6 @@ class BridgeCore:
if agent_name in self._adapter.agents_with_live_runtime_state(channel_id):
self._schedule_indicator_move(channel_id, agent_name, thread_root_id)
- async def _move_indicators_for_addressees(
- self,
- *,
- channel_id: str,
- room_id: str,
- channel_type: ChannelType,
- content: str,
- mention_target: str | None,
- thread_root_id: str | None,
- ) -> None:
- """Follow an inbound message, for each addressed agent working here.
-
- Only agents the message actually addresses move: unrelated chatter in a
- busy channel leaves a working agent's indicator where it is."""
- live = self._adapter.agents_with_live_runtime_state(channel_id)
- if not live:
- return
-
- # Every message in a 1:1 room addresses the agent, with no mention.
- if channel_type == "direct":
- for agent_name in live:
- self._schedule_indicator_move(channel_id, agent_name, thread_root_id)
- return
-
- stripped = strip_emphasis(content)
- addressed = {
- agent_name
- for agent_name in live
- if mention_regex(agent_name).search(stripped) is not None
- }
- if mention_target is not None and mention_target in live:
- addressed.add(mention_target)
-
- unmatched = [name for name in live if name not in addressed]
- if unmatched:
- addressed.update(
- await self._live_agents_addressed_by_alias(room_id, content, unmatched)
- )
-
- for agent_name in addressed:
- self._schedule_indicator_move(channel_id, agent_name, thread_root_id)
-
- async def _live_agents_addressed_by_alias(
- self, room_id: str, content: str, candidates: list[str]
- ) -> set[str]:
- """Of `candidates`, those addressed by their room alias rather than name.
-
- An alias is room-scoped, so it cannot be matched from the message text
- alone. Only consulted when a plain-name match has already failed for the
- agent, keeping this off the path of the common case."""
- tokens = unique_mention_tokens(content)
- if not tokens:
- return set()
-
- by_name = {name.lower(): name for name in candidates}
- matched: set[str] = set()
- async with self._session_factory() as session:
- for token in tokens:
- agent_id = await self._room_store.get_agent_id_by_alias(
- session, room_id, token
- )
- if agent_id is None:
- continue
- agent = await self._agent_store.get(session, agent_id)
- if agent is None:
- continue
- name = by_name.get(agent.name.lower())
- if name is not None:
- matched.add(name)
- return matched
-
def _schedule_indicator_move(
self, channel_id: str, agent_name: str, thread_root_id: str | None
) -> None:
diff --git a/core/switch_core/events.py b/core/switch_core/events.py
index e68ef37fc..a1d54f29d 100644
--- a/core/switch_core/events.py
+++ b/core/switch_core/events.py
@@ -154,6 +154,12 @@ class AgentRuntimeStateEvent(SwitchEvent):
# place on the live working message. Transient — never persisted. Only
# meaningful while `state == "working"`; None → generic "working on it…".
detail: str | None = None
+ # Event id of the most recent message the agent has actually been handed.
+ # The bridge moves the runtime indicator below the conversation when this
+ # changes, so the indicator only claims the agent has seen a message once
+ # the agent really has. Unchanged between reports (e.g. the periodic
+ # activity refresh) means the indicator stays where it is.
+ anchor_event_id: str | None = None
# ── Permission ────────────────────────────────────────────────────────────────
diff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_inbound_media.py b/core/tests/switch_core/bridges/collaboration/test_bridge_inbound_media.py
index 4fcae8061..9e74b4384 100644
--- a/core/tests/switch_core/bridges/collaboration/test_bridge_inbound_media.py
+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_inbound_media.py
@@ -61,9 +61,6 @@ class _FakeAdapter:
def translate_inbound(self, content: str) -> str:
return content
- def agents_with_live_runtime_state(self, channel_id: str) -> list[str]:
- return []
-
def _fake_bridge() -> SimpleNamespace:
puppet = _FakePuppet()
@@ -86,12 +83,7 @@ def _fake_bridge() -> SimpleNamespace:
_record_message_map=_record_message_map,
puppet=puppet,
recorded=recorded,
- _indicator_move_timers={},
- )
- ns._move_indicators_for_addressees = (
- BridgeCore._move_indicators_for_addressees.__get__(ns)
)
- ns._schedule_indicator_move = BridgeCore._schedule_indicator_move.__get__(ns)
return ns
diff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_indicator_position.py b/core/tests/switch_core/bridges/collaboration/test_bridge_indicator_position.py
index 69a69eca2..2f269aa25 100644
--- a/core/tests/switch_core/bridges/collaboration/test_bridge_indicator_position.py
+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_indicator_position.py
@@ -23,43 +23,21 @@ class _FakeAdapter:
self.targets.append(thread_root_id)
-def _bridge(live: list[str], *, aliases: dict[str, str] | None = None) -> Any:
+def _bridge(live: list[str]) -> Any:
"""A BridgeCore stand-in wired to the real positioning methods."""
adapter = _FakeAdapter(live)
- alias_map = aliases or {}
-
- class _RoomStore:
- async def get_agent_id_by_alias(
- self, _session: Any, _room_id: str, alias: str
- ) -> str | None:
- return alias_map.get(alias.lower())
-
- class _AgentStore:
- async def get(self, _session: Any, agent_id: str) -> Any:
- return SimpleNamespace(name=agent_id)
-
- class _Session:
- async def __aenter__(self) -> Any:
- return self
-
- async def __aexit__(self, *_exc: Any) -> None:
- return None
-
ns = SimpleNamespace(
_adapter=adapter,
- _room_store=_RoomStore(),
- _agent_store=_AgentStore(),
- _session_factory=lambda: _Session(),
_indicator_move_timers={},
_indicator_move_targets={},
+ _reported_anchors={},
adapter_spy=adapter,
)
for name in (
"_move_indicator_for_sender",
- "_move_indicators_for_addressees",
- "_live_agents_addressed_by_alias",
"_schedule_indicator_move",
"_run_indicator_move",
+ "_follow_reported_anchor",
):
setattr(ns, name, getattr(BridgeCore, name).__get__(ns))
return ns
@@ -70,9 +48,7 @@ def _drain(bridge: Any, coro: Any) -> list[tuple[str, str]]:
async def _go() -> None:
await coro
- timers = list(bridge._indicator_move_timers.values())
- # Fire the coalescing timers immediately rather than waiting them out.
- for timer in timers:
+ for timer in list(bridge._indicator_move_timers.values()):
timer.cancel()
for key in list(bridge._indicator_move_timers):
await bridge._run_indicator_move(key)
@@ -81,89 +57,101 @@ def _drain(bridge: Any, coro: Any) -> list[tuple[str, str]]:
return bridge.adapter_spy.moved
-def _addressees(
- bridge: Any,
- content: str,
- channel_type: str = "channel_public",
- thread_root_id: str | None = None,
+def _anchor(
+ bridge: Any, anchor_event_id: str | None, *, thread: str | None = None
) -> Any:
- return bridge._move_indicators_for_addressees(
- channel_id="chan-1",
- room_id="room-1",
- channel_type=channel_type,
- content=content,
- mention_target=None,
- thread_root_id=thread_root_id,
+ return bridge._follow_reported_anchor(
+ "chan-1", "agent-a", "working", anchor_event_id, thread
)
-# ── Inbound: only agents the message addresses ──────────────────────────────
+# ── Inbound: driven by what the agent reports it has received ───────────────
-def test_addressed_agent_indicator_follows_the_message() -> None:
+def test_a_new_reported_anchor_moves_the_indicator() -> None:
bridge = _bridge(["agent-a"])
- moved = _drain(bridge, _addressees(bridge, "@agent-a can you look at this?"))
+ async def go() -> None:
+ await _anchor(bridge, "$m1")
+ await _anchor(bridge, "$m2")
- assert moved == [("chan-1", "agent-a")]
+ assert _drain(bridge, go()) == [("chan-1", "agent-a")]
-def test_unaddressed_chatter_leaves_the_indicator_alone() -> None:
- # The whole point of scoping this per agent: a busy channel must not drag a
- # working agent's indicator around on traffic that has nothing to do with it.
+def test_the_first_anchor_of_a_turn_moves_nothing() -> None:
+ # The indicator was only just posted against that message.
bridge = _bridge(["agent-a"])
- moved = _drain(bridge, _addressees(bridge, "unrelated chatter between humans"))
-
- assert moved == []
+ assert _drain(bridge, _anchor(bridge, "$m1")) == []
-def test_only_the_addressed_agent_of_several_moves() -> None:
- bridge = _bridge(["agent-a", "agent-b"])
+def test_repeating_the_same_anchor_moves_nothing() -> None:
+ # The 5s activity refresh replays the current anchor; it must not churn.
+ bridge = _bridge(["agent-a"])
- moved = _drain(bridge, _addressees(bridge, "@agent-b over to you"))
+ async def go() -> None:
+ await _anchor(bridge, "$m1")
+ for _ in range(5):
+ await _anchor(bridge, "$m1")
- assert moved == [("chan-1", "agent-b")]
+ assert _drain(bridge, go()) == []
-def test_a_prefix_of_a_longer_name_is_not_treated_as_addressed() -> None:
+def test_a_message_the_agent_has_not_been_given_moves_nothing() -> None:
+ # The whole point of the redesign: arriving in the room is not evidence the
+ # agent saw it, so only what the agent reports may move the indicator.
bridge = _bridge(["agent-a"])
- moved = _drain(bridge, _addressees(bridge, "@agent-a-2 please take this"))
+ async def go() -> None:
+ await _anchor(bridge, "$m1")
+ # A message lands in the room, but the agent is busy and is never
+ # handed it — so no new anchor is ever reported.
+ await _anchor(bridge, "$m1")
- assert moved == []
+ assert _drain(bridge, go()) == []
-def test_agent_addressed_by_its_room_alias_moves() -> None:
- bridge = _bridge(["agent-a"], aliases={"worker": "agent-a"})
+def test_a_report_without_an_anchor_moves_nothing() -> None:
+ # Connectors that don't report anchors simply never reposition.
+ bridge = _bridge(["agent-a"])
- moved = _drain(bridge, _addressees(bridge, "@worker ping"))
+ async def go() -> None:
+ await _anchor(bridge, "$m1")
+ await _anchor(bridge, None)
- assert moved == [("chan-1", "agent-a")]
+ assert _drain(bridge, go()) == []
-def test_every_message_addresses_the_agent_in_a_dm_room() -> None:
+def test_the_move_lands_in_the_thread_of_the_reported_message() -> None:
bridge = _bridge(["agent-a"])
- moved = _drain(
- bridge, _addressees(bridge, "no mention here", channel_type="direct")
- )
+ async def go() -> None:
+ await _anchor(bridge, "$m1", thread=None)
+ await _anchor(bridge, "$m2", thread="root-7")
- assert moved == [("chan-1", "agent-a")]
+ _drain(bridge, go())
+ assert bridge.adapter_spy.targets == ["root-7"]
-def test_nothing_is_scheduled_when_no_indicator_is_live() -> None:
- bridge = _bridge([])
- moved = _drain(bridge, _addressees(bridge, "@agent-a hello"))
+def test_the_anchor_resets_when_the_turn_ends() -> None:
+ # A later turn's first anchor must not be mistaken for a move within the
+ # previous one.
+ bridge = _bridge(["agent-a"])
- assert moved == []
+ async def go() -> None:
+ await _anchor(bridge, "$m1")
+ await bridge._follow_reported_anchor("chan-1", "agent-a", "idle", None, None)
+ await _anchor(bridge, "$m2")
+
+ assert _drain(bridge, go()) == []
# ── Outbound: the agent's own messages ──────────────────────────────────────
def test_indicator_follows_a_message_the_agent_posts() -> None:
+ # No ambiguity here — the agent demonstrably acted, so core may move it.
bridge = _bridge(["agent-a"])
moved = _drain(bridge, bridge._move_indicator_for_sender("chan-1", "agent-a", None))
@@ -179,79 +167,29 @@ def test_another_agents_message_does_not_move_this_indicator() -> None:
assert moved == []
-# ── Threads ─────────────────────────────────────────────────────────────────
-
-
-def test_the_move_targets_the_thread_the_message_arrived_in() -> None:
- bridge = _bridge(["agent-a"])
-
- _drain(bridge, _addressees(bridge, "@agent-a in here", thread_root_id="root-7"))
-
- assert bridge.adapter_spy.targets == ["root-7"]
-
-
-def test_a_coalesced_burst_lands_in_the_most_recent_thread() -> None:
- # The indicator should follow where the conversation ended up, not where it
- # was when the coalescing window opened.
- bridge = _bridge(["agent-a"])
-
- async def burst() -> None:
- await _addressees(bridge, "@agent-a first", thread_root_id="root-1")
- await _addressees(bridge, "@agent-a second", thread_root_id="root-2")
- await _addressees(bridge, "@agent-a third", thread_root_id="root-3")
-
- _drain(bridge, burst())
-
- assert bridge.adapter_spy.targets == ["root-3"]
-
-
-def test_a_message_at_the_channel_root_brings_the_indicator_back_out() -> None:
- bridge = _bridge(["agent-a"])
-
- _drain(bridge, _addressees(bridge, "@agent-a out here", thread_root_id=None))
-
- assert bridge.adapter_spy.targets == [None]
+def test_nothing_moves_when_no_indicator_is_live() -> None:
+ bridge = _bridge([])
+ moved = _drain(bridge, bridge._move_indicator_for_sender("chan-1", "agent-a", None))
-# ── Coalescing ──────────────────────────────────────────────────────────────
+ assert moved == []
-def test_a_burst_of_messages_costs_a_single_move() -> None:
+def test_a_burst_of_agent_posts_costs_a_single_move() -> None:
bridge = _bridge(["agent-a"])
scheduled: list[Any] = []
async def burst() -> None:
for _ in range(20):
- await _addressees(bridge, "@agent-a another one")
+ await bridge._move_indicator_for_sender("chan-1", "agent-a", None)
scheduled.append(bridge._indicator_move_timers[("chan-1", "agent-a")])
moved = _drain(bridge, burst())
- # One timer object throughout: later messages were absorbed into the queued
- # move rather than each scheduling their own.
- assert len(scheduled) == 20
assert all(timer is scheduled[0] for timer in scheduled)
assert moved == [("chan-1", "agent-a")]
-def test_a_later_message_does_not_push_the_queued_move_back() -> None:
- # A sustained conversation must not starve the move by resetting its timer
- # on every message, so the deadline is set once and left alone.
- bridge = _bridge(["agent-a"])
- deadlines: list[float] = []
-
- async def burst() -> None:
- for _ in range(3):
- await _addressees(bridge, "@agent-a keep talking")
- deadlines.append(
- bridge._indicator_move_timers[("chan-1", "agent-a")].when()
- )
-
- _drain(bridge, burst())
-
- assert len(set(deadlines)) == 1
-
-
def test_a_platform_failure_during_a_move_does_not_escape() -> None:
# The indicator is cosmetic; a failed move must not propagate into the
# bridge callback that happened to trigger it.
diff --git a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/room-connection.ts b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/room-connection.ts
index d0aa83f58..dd3617a49 100644
--- a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/room-connection.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/room-connection.ts
@@ -107,6 +107,12 @@ interface QueuedInjection {
* room root.
*/
threadId: string | null;
+ /**
+ * The message's own id. Reported to the bridge once this injection actually
+ * reaches the session, so the runtime indicator only moves below a message
+ * the agent has really been handed.
+ */
+ messageId: string | null;
}
/** Provider-specific keystroke payload builder, injected to keep the core free
@@ -233,6 +239,13 @@ export class RoomConnection {
private roomTurnActive = false;
/** Thread of the current room turn (see QueuedInjection.threadId). */
private currentThreadId: string | null = null;
+ /**
+ * The last message actually delivered into the session. Reported with runtime
+ * state so the bridge can position the indicator below what the agent has
+ * genuinely received — a message that merely arrived in the room must not
+ * make the indicator claim the agent has seen it.
+ */
+ private currentAnchorId: string | null = null;
/** Last activity line (without the elapsed suffix), to skip redundant refreshes. */
private lastActivityDetail: string | null = null;
/** Monotonic timestamp the current working turn began, for the elapsed suffix. */
@@ -398,6 +411,7 @@ export class RoomConnection {
this.runtimeState = 'idle';
this.roomTurnActive = false;
this.currentThreadId = null;
+ this.currentAnchorId = null;
void this.postRuntimeState('idle', null, { detached: true }).catch(() => {});
}
this.abort.abort();
@@ -483,6 +497,10 @@ export class RoomConnection {
room_id: this.roomId,
state,
thread_id: threadId,
+ // Reported on every push, including the periodic activity refresh.
+ // The bridge repositions only when the value CHANGES, so a refresh
+ // that repeats the current anchor deliberately moves nothing.
+ anchor_event_id: this.currentAnchorId,
deeplink_url: this.sessionDeeplink(),
detail: detail ?? null,
control_capabilities: this.control.capabilities,
@@ -513,6 +531,8 @@ export class RoomConnection {
const addressed = event.type === 'message' && (event.payload as MessagePayload).addressed;
const threadId =
event.type === 'message' ? ((event.payload as MessagePayload).thread_id ?? null) : null;
+ const messageId =
+ event.type === 'message' ? (event.payload as MessagePayload).message_id : null;
if (event.type === 'message' && !addressed) {
this.missed += 1;
}
@@ -550,7 +570,7 @@ export class RoomConnection {
body = `${body}\n(Some earlier room events were dropped and cannot be replayed: ${this.pendingGapReason} — call read_context before responding.)`;
this.pendingGapReason = null;
}
- this.enqueue({ text: body, addressed, threadId });
+ this.enqueue({ text: body, addressed, threadId, messageId });
}
/**
@@ -668,6 +688,7 @@ export class RoomConnection {
if (next === 'idle') {
this.roomTurnActive = false;
this.currentThreadId = null;
+ this.currentAnchorId = null;
}
}
this.busy = isBlockingStatus(status, notificationType);
@@ -860,6 +881,7 @@ export class RoomConnection {
if (item.addressed) {
this.roomTurnActive = true;
this.currentThreadId = item.threadId;
+ this.currentAnchorId = item.messageId;
this.setRuntimeState('working');
}