Skip to content

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

fix: one session of an agent per room, and say so when one is displaced (CHOO-1419) (#109)

Louis Amaudruz91abcfe1cbaf
diff --git a/connectors/claude-code-plugin/.claude-plugin/plugin.json b/connectors/claude-code-plugin/.claude-plugin/plugin.json
index 3cf315ad5..d94e3b91c 100644
--- a/connectors/claude-code-plugin/.claude-plugin/plugin.json
+++ b/connectors/claude-code-plugin/.claude-plugin/plugin.json
@@ -1,5 +1,5 @@
{
"name": "switch-connector",
- "version": "0.7.7",
+ "version": "0.7.8",
"description": "Connect Claude Code to a Switch platform instance as a participating agent"
}
diff --git a/connectors/claude-code-plugin/skills/switch/SKILL.md b/connectors/claude-code-plugin/skills/switch/SKILL.md
index 8700774b0..00284580f 100644
--- a/connectors/claude-code-plugin/skills/switch/SKILL.md
+++ b/connectors/claude-code-plugin/skills/switch/SKILL.md
@@ -27,6 +27,13 @@ the same connection — you never talk to the Switch server directly.
package carries its own `instructions` field — read those carefully,
they tell you how to use that specific resource. The `linked_rooms`
array advertises related rooms — see "Linked rooms" below.
+
+ The response also carries a `warning` field, normally null. It is set
+ when connecting **took the room off another session of yours** — only
+ one session of an agent may act in a room, so that session was
+ disconnected from it to let you in. Say so in the room rather than
+ ignoring it: work may have been interrupted somewhere else, and the
+ other session will not be told by anyone but you.
3. **Delivery starts automatically.** `connect_to_room` claims the room on
the connection your tool calls travel over — the same one that delivers
your events — so events arrive as `<channel>` notifications as they
@@ -491,6 +498,11 @@ an alias only resolves in the room it was set in.
- **One room at a time.** Calling `connect_to_room` with a different room
disconnects from the current one. Delivery automatically re-targets to
the new room.
+- **One session of you per room.** Two sessions of the same agent cannot
+ both act in a room. Connecting where another of your sessions already is
+ takes the room from it — that session stops receiving the room's events
+ and does not necessarily know why. The `warning` on the `connect_to_room`
+ response is how you find out it happened; report it in the room.
- **Governance is enforced.** Your tool calls (Bash, Edit, Write, etc.)
are submitted to Switch for mediation before execution. If Switch denies
a tool call, you will see the reason. Do not try to circumvent denials.
diff --git a/connectors/codex-plugin/.codex-plugin/plugin.json b/connectors/codex-plugin/.codex-plugin/plugin.json
index e9e15348e..fe579c5d9 100644
--- a/connectors/codex-plugin/.codex-plugin/plugin.json
+++ b/connectors/codex-plugin/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "switch-connector-codex",
- "version": "0.1.4",
+ "version": "0.1.5",
"description": "Connect Codex to a Switch platform instance as a participating agent",
"skills": "./skills/"
}
diff --git a/connectors/codex-plugin/skills/switch/SKILL.md b/connectors/codex-plugin/skills/switch/SKILL.md
index 68f38961d..dc9089f42 100644
--- a/connectors/codex-plugin/skills/switch/SKILL.md
+++ b/connectors/codex-plugin/skills/switch/SKILL.md
@@ -31,6 +31,13 @@ say so rather than guessing.
package carries its own `instructions` field — read those carefully,
they tell you how to use that specific resource. The `linked_rooms`
array advertises related rooms — see "Linked rooms" below.
+
+ The response also carries a `warning` field, normally null. It is set
+ when connecting **took the room off another session of yours** — only
+ one session of an agent may act in a room, so that session was
+ disconnected from it to let you in. Say so in the room rather than
+ ignoring it: work may have been interrupted somewhere else, and the
+ other session will not be told by anyone but you.
3. **Delivery starts automatically.** `connect_to_room` claims the room on
the connection your session was launched with, and switchdash — which
holds that connection — delivers the room's events into your session as
diff --git a/core/switch_core/bridges/agent/api/handlers.py b/core/switch_core/bridges/agent/api/handlers.py
index 7ce244b57..1c3c7648e 100644
--- a/core/switch_core/bridges/agent/api/handlers.py
+++ b/core/switch_core/bridges/agent/api/handlers.py
@@ -85,6 +85,7 @@ from switch_core.bridges.agent.protocol.connections import (
RoomOccupiedError,
Scope,
UnknownConnectionError,
+ evicted_session_warning,
)
from switch_core.bridges.agent.protocol.service import AgentExistsError, ProtocolService
from switch_core.bridges.agent.protocol.stream import event_stream
@@ -830,10 +831,24 @@ async def connection_subscribe(
except RoomOccupiedError as exc:
raise HTTPException(status_code=409, detail=str(exc)) from exc
+ if evicted is not None:
+ logger.warning(
+ "[CONN] agent=%s connection=%s took room %s from connection %s",
+ agent.id,
+ conn.id,
+ req.room_id,
+ evicted.id,
+ )
+
return {
"ok": True,
"rooms": sorted(conn.rooms),
"evicted_connection_id": evicted.id if evicted else None,
+ "warning": (
+ evicted_session_warning(req.room_id, evicted.id)
+ if evicted is not None
+ else None
+ ),
}
diff --git a/core/switch_core/bridges/agent/operations/definitions.py b/core/switch_core/bridges/agent/operations/definitions.py
index d0f7b2b0f..5d95e3c4a 100644
--- a/core/switch_core/bridges/agent/operations/definitions.py
+++ b/core/switch_core/bridges/agent/operations/definitions.py
@@ -22,7 +22,10 @@ from switch_core.bridges.agent.operations.context import (
session_key,
)
from switch_core.bridges.agent.operations.registry import operation
-from switch_core.bridges.agent.protocol.connections import ConnectionError_
+from switch_core.bridges.agent.protocol.connections import (
+ ConnectionError_,
+ evicted_session_warning,
+)
from switch_core.bridges.agent.protocol.instructions import build_room_instructions
from switch_core.bridges.agent.protocol.service import ProtocolService
from switch_core.bridges.agent.protocol.types import IntegrationProfile
@@ -33,7 +36,7 @@ logger = logging.getLogger(__name__)
def claim_room_on_caller_connection(
protocol: ProtocolService, agent_id: str, connection_id: str, room_id: str
-) -> None:
+) -> str | None:
"""Bind the room to the connection that asked to connect.
Connecting IS claiming the room slot. The caller identified itself with a
@@ -47,28 +50,32 @@ def claim_room_on_caller_connection(
room *from Switch* rather than by reading the agent's tool result and
hoping its shape never changes.
- **Without takeover.** A dead connection is not a claimant at all —
- ``claimant_of`` filters on liveness — so the only thing takeover could ever
- win against is a connection that is genuinely alive and covering the room.
- Usually that is a supervisor delivering for this very session, and taking
- the slot from it stops delivery: the tool call succeeds, the agent believes
- it is in the room, and nothing reaches it again.
+ **The newcomer wins, and is told what it cost.** At most one session of an
+ agent may act in a room (CHOO-1419). A dead connection is not a claimant at
+ all — ``claimant_of`` filters on liveness — so the only thing a claim can
+ ever displace is a second session of this agent that is genuinely alive in
+ the room.
+
+ Refusing the newcomer instead would strand it: the session exists, was
+ started to work here, and has nowhere to go. Letting it in resolves the
+ duplicate rather than freezing it, and the loser learns it lost the room
+ from ``subscription_changed`` on its own stream.
- That is not hypothetical. A session started before its supervisor learned to
- share connections holds its own; when it reconnects, taking over would
- silence the supervisor that is actually feeding it.
+ What is not acceptable is doing it quietly. Returns the evicted connection
+ id so the caller can say so — a takeover nobody reports reads exactly like
+ the duplicate-session bug it is meant to resolve.
- Never fatal. The room binding is written before this runs, so a failure here
- costs delivery routing, not membership, and says so.
+ Faults other than occupancy stay non-fatal — they cost delivery routing
+ rather than the agent's place in the room, and say so in the log.
"""
connection = protocol.connections.get(connection_id)
if connection is None or connection.agent_id != agent_id:
# No connection behind this caller: an MCP transport session, or a
# runtime borrowing an id whose connection has since expired. The
# binding row still stands and room-scoped calls resolve through it.
- return
+ return None
try:
- protocol.connections.claim_room(connection, room_id)
+ evicted = protocol.connections.claim_room(connection, room_id, takeover=True)
except ConnectionError_ as exc:
logger.warning(
"[CONNECT] agent=%s connection=%s could not claim room %s: %s",
@@ -77,6 +84,17 @@ def claim_room_on_caller_connection(
room_id,
exc,
)
+ return None
+ if evicted is None:
+ return None
+ logger.warning(
+ "[CONNECT] agent=%s connection=%s took room %s from connection %s",
+ agent_id,
+ connection_id,
+ room_id,
+ evicted.id,
+ )
+ return evicted.id
@operation
@@ -140,7 +158,12 @@ async def connect_to_room(
Returns:
{agent_id, room_id, name, description, participants, instructions,
reference_types, references, documents, packages, linked_rooms,
- roles}.
+ roles, warning}.
+ `warning` is normally null. It is set when connecting took the room off
+ another live session of this same agent — only one session of an agent
+ may act in a room, so that session was disconnected from it to let this
+ one in. Surface it rather than ignoring it: it means work may have been
+ interrupted somewhere else.
Each reference, document, and package carries its own `instructions`
field — agent-facing guidance for that resource — alongside a short
`description`. `roles` lists the room's assumable roles, each
@@ -203,6 +226,10 @@ async def connect_to_room(
lifecycle = (
"explicit" if profile.connection_model == "session_passive" else "heartbeat"
)
+ evicted_connection_id = claim_room_on_caller_connection(
+ protocol, agent_id, key, room.id
+ )
+
async with protocol.session_factory() as db:
await protocol.agent_session_store.set_connected_room(
db,
@@ -213,8 +240,6 @@ async def connect_to_room(
)
await db.commit()
- claim_room_on_caller_connection(protocol, agent_id, key, room.id)
-
return {
"agent_id": agent_id,
"room_id": room.id,
@@ -241,6 +266,11 @@ async def connect_to_room(
"packages": resources["packages"],
"linked_rooms": linked_rooms,
"roles": roles,
+ "warning": (
+ evicted_session_warning(room.id, evicted_connection_id)
+ if evicted_connection_id
+ else None
+ ),
}
diff --git a/core/switch_core/bridges/agent/protocol/connections.py b/core/switch_core/bridges/agent/protocol/connections.py
index bad4eca79..03938ad0b 100644
--- a/core/switch_core/bridges/agent/protocol/connections.py
+++ b/core/switch_core/bridges/agent/protocol/connections.py
@@ -82,6 +82,23 @@ class RoomOccupiedError(ConnectionError_):
self.holder_id = holder_id
+def evicted_session_warning(room_id: str, evicted_connection_id: str) -> str:
+ """What to tell a caller that took a room off another live session.
+
+ One wording for every door that can evict, so a client does not have to
+ recognise the same event phrased two ways. Reported rather than logged
+ quietly: an unannounced takeover looks identical to the duplicate-session
+ bug it resolves — a session stops receiving a room and nothing says why.
+ """
+ return (
+ f"You evicted another session of this agent from room {room_id} "
+ f"(connection {evicted_connection_id}). Only one session of an agent "
+ "may act in a room, so that session has been disconnected from it and "
+ "will stop receiving its events. If that session was doing work here, "
+ "it no longer is."
+ )
+
+
class ProtocolVersionError(ConnectionError_):
def __init__(self, requested: int) -> None:
super().__init__(
diff --git a/core/tests/switch_core/bridges/agent/operations/test_connect_claims_room.py b/core/tests/switch_core/bridges/agent/operations/test_connect_claims_room.py
index d1e10071f..422806a66 100644
--- a/core/tests/switch_core/bridges/agent/operations/test_connect_claims_room.py
+++ b/core/tests/switch_core/bridges/agent/operations/test_connect_claims_room.py
@@ -10,6 +10,11 @@ remember. Two consequences, and the second is the point:
supervisor holding the connection learns the room **from Switch** instead of
reading the agent's tool result. Reading the tool result is what switchdash
did, and it broke silently the moment the result's shape changed.
+
+The claim is also what resolves a second session (CHOO-1419): a live claimant is
+another session of this agent already in the room, so the newcomer displaces it
+rather than the two coexisting — and the eviction is reported back, because a
+takeover nobody mentions looks exactly like the bug it resolves.
"""
from __future__ import annotations
@@ -24,6 +29,7 @@ from switch_core.bridges.agent.operations.definitions import (
from switch_core.bridges.agent.protocol.connections import (
PROTOCOL_VERSION,
ConnectionRegistry,
+ NoStreamAttachedError,
)
AGENT = "agent-1"
@@ -95,28 +101,109 @@ def test_a_dead_sibling_does_not_lock_the_agent_out() -> None:
assert claimant.id == CONN
-def test_a_live_sibling_keeps_the_room() -> None:
- """A tool call does not take a room off a connection that is delivering.
+def test_a_live_sibling_is_evicted_and_the_eviction_is_reported() -> None:
+ """A second session takes the room, and is told what it cost (CHOO-1419).
+
+ A live claimant is another session of this same agent already acting in the
+ room. Only one of them may, so the newcomer displaces it rather than the two
+ coexisting — refusing instead would strand a session that was started to
+ work here and has nowhere else to go.
+
+ The eviction is returned, not merely logged. An unannounced takeover is
+ indistinguishable from the duplicate-session bug it resolves: a session
+ stops receiving a room and nothing says why.
+ """
+ registry = ConnectionRegistry()
+ incumbent = _open(registry, "first-session")
+ registry.claim_room(incumbent, ROOM)
+ _open(registry, CONN)
+
+ evicted = claim_room_on_caller_connection(_protocol(registry), AGENT, CONN, ROOM)
+
+ assert evicted == "first-session"
+ claimant = registry.claimant_of(AGENT, ROOM)
+ assert claimant is not None
+ assert claimant.id == CONN
+ assert ROOM not in incumbent.rooms
+
- The only thing a takeover here could ever win against is a live connection
- covering the room — typically a supervisor feeding this very session. Taking
- the slot from it stops delivery *silently*: the call succeeds, the agent
- believes it is in the room, and nothing reaches it again.
+def test_the_evicted_session_is_woken_so_it_learns_it_lost_the_room() -> None:
+ """The loser has to find out, and its stream is the only way it can.
- Ownership goes the other way: a supervisor declaring a room when it opens
- its stream takes over; a `connect_to_room` yields.
+ Without the wake it stays blocked on its read, still believing it holds the
+ room, and switchdash keeps showing it under that room.
"""
registry = ConnectionRegistry()
- supervisor = _open(registry, "supervisor")
- registry.claim_room(supervisor, ROOM)
+ incumbent = _open(registry, "first-session")
+ registry.claim_room(incumbent, ROOM)
+ incumbent.wake.clear()
_open(registry, CONN)
claim_room_on_caller_connection(_protocol(registry), AGENT, CONN, ROOM)
+ assert incumbent.wake.is_set()
+
+
+def test_taking_an_unheld_room_reports_no_eviction() -> None:
+ """The warning must not fire on the ordinary case of an empty room."""
+ registry = ConnectionRegistry()
+ _open(registry, CONN)
+
+ evicted = claim_room_on_caller_connection(_protocol(registry), AGENT, CONN, ROOM)
+
+ assert evicted is None
+
+
+def test_a_dead_predecessor_is_not_reported_as_an_eviction() -> None:
+ """Nothing was displaced, so nothing should be announced.
+
+ A restart meets its own dead connection constantly. Reporting that as "you
+ evicted a session" would cry wolf on the most routine event there is.
+ """
+ import time as _time
+
+ registry = ConnectionRegistry()
+ dead = _open(registry, "previous-life")
+ registry.claim_room(dead, ROOM)
+ dead.last_beat = _time.monotonic() - 3600
+ _open(registry, CONN)
+
+ evicted = claim_room_on_caller_connection(_protocol(registry), AGENT, CONN, ROOM)
+
+ assert evicted is None
+
+
+def test_the_same_connection_reconnecting_is_not_a_duplicate() -> None:
+ """One session returning is not two sessions arriving.
+
+ A session keeps its connection id across reconnects, so it meets its own
+ claim. That must stay idempotent or every restart would lock itself out.
+ """
+ registry = ConnectionRegistry()
+ conn = _open(registry, CONN)
+ registry.claim_room(conn, ROOM)
+
+ evicted = claim_room_on_caller_connection(_protocol(registry), AGENT, CONN, ROOM)
+
+ assert evicted is None
claimant = registry.claimant_of(AGENT, ROOM)
assert claimant is not None
- assert claimant.id == "supervisor"
- assert ROOM in supervisor.rooms
+ assert claimant.id == CONN
+
+
+def test_another_agent_holding_the_room_is_not_a_conflict() -> None:
+ """The rule is one session per agent per room, not one agent per room."""
+ registry = ConnectionRegistry()
+ theirs = _open(registry, "their-session", agent_id="agent-2")
+ registry.claim_room(theirs, ROOM)
+ _open(registry, CONN)
+
+ claim_room_on_caller_connection(_protocol(registry), AGENT, CONN, ROOM)
+
+ ours = registry.claimant_of(AGENT, ROOM)
+ assert ours is not None
+ assert ours.id == CONN
+ assert ROOM in theirs.rooms
def test_an_unknown_connection_is_not_an_error() -> None:
@@ -139,20 +226,20 @@ def test_another_agents_connection_is_never_claimed_on() -> None:
assert registry.claimant_of(AGENT, ROOM) is None
-def test_a_failure_to_claim_is_logged_and_not_raised(
+def test_a_fault_that_is_not_occupancy_is_logged_and_not_raised(
caplog: Any,
) -> None:
- """Membership is already written; only routing is affected.
+ """Only occupancy is fatal; other faults cost routing, not membership.
- Raising here would fail a `connect_to_room` that genuinely succeeded.
+ Occupancy means someone else is in the agent's seat, which changes what the
+ caller may do. Any other connection fault leaves the room the caller's to
+ have, so failing the whole connect over it would be the harsher answer.
"""
registry = ConnectionRegistry()
conn = _open(registry, CONN)
def _explode(*_a: Any, **_kw: Any) -> None:
- from switch_core.bridges.agent.protocol.connections import RoomOccupiedError
-
- raise RoomOccupiedError(ROOM, "other")
+ raise NoStreamAttachedError(CONN)
registry.claim_room = _explode # type: ignore[method-assign]
diff --git a/core/tests/switch_core/bridges/agent/operations/test_connect_to_room_eviction.py b/core/tests/switch_core/bridges/agent/operations/test_connect_to_room_eviction.py
new file mode 100644
index 000000000..970f5865b
--- /dev/null
+++ b/core/tests/switch_core/bridges/agent/operations/test_connect_to_room_eviction.py
@@ -0,0 +1,244 @@
+"""What `connect_to_room` tells its caller about the room it just took.
+
+The operation-level counterpart to `test_connect_claims_room`, which covers the
+claim helper alone. What is pinned here is the **payload**, because that is
+where the original bug lived: the claim was refused, the refusal was swallowed,
+and the tool still answered with a full room and no hint that anything had gone
+wrong. A caller cannot act on a fact the response does not carry, so the
+response is the contract worth testing.
+
+Two sessions of one agent in one room produce exactly this call: the second
+session connects while the first still holds the slot.
+"""
+
+from __future__ import annotations
+
+from contextlib import asynccontextmanager
+from types import SimpleNamespace
+from typing import Any
+
+import pytest
+
+from switch_core.bridges.agent.operations import definitions
+from switch_core.bridges.agent.operations.callctx import (
+ CallContext,
+ reset_call_context,
+ set_call_context,
+)
+from switch_core.bridges.agent.operations.context import init_operations_protocol
+from switch_core.bridges.agent.protocol.connections import (
+ PROTOCOL_VERSION,
+ ConnectionRegistry,
+)
+
+AGENT = "agent-1"
+ROOM = "room-1"
+
+_PROFILE = {
+ "connection_model": "session_addressable",
+ "message_exchange": True,
+ "pre_invocation_mediation": [],
+ "post_invocation_mediation": [],
+ "event_reporting": [],
+ "task_protocol": {"can_delegate": False, "can_accept": False},
+}
+
+
+class _RecordingSessionStore:
+ """Stands in for AgentSessionStore, remembering the binding it was asked for."""
+
+ def __init__(self) -> None:
+ self.bindings: list[tuple[str, str, str]] = []
+
+ async def set_connected_room(
+ self,
+ session: Any,
+ agent_id: str,
+ room_id: str,
+ transport_session_id: str,
+ lifecycle: str,
+ ) -> None:
+ self.bindings.append((agent_id, room_id, transport_session_id))
+
+
+def _protocol(registry: ConnectionRegistry, store: _RecordingSessionStore) -> Any:
+ room = SimpleNamespace(id=ROOM, name="Room One", description="A room")
+ agent = SimpleNamespace(id=AGENT, name="agent-one", integration_profile=_PROFILE)
+ room_model = SimpleNamespace(id=ROOM, name="Room One", bridge_id=None)
+
+ @asynccontextmanager
+ async def session_factory():
+ yield SimpleNamespace(commit=_noop, get=_noop_get)
+
+ async def _noop(*_a: Any, **_kw: Any) -> None:
+ return None
+
+ async def _noop_get(*_a: Any, **_kw: Any) -> None:
+ return None
+
+ async def require_room_member(*_a: Any, **_kw: Any):
+ return room
+
+ async def list_participants(*_a: Any, **_kw: Any) -> list[Any]:
+ return []
+
+ async def list_room_resources(*_a: Any, **_kw: Any) -> dict[str, Any]:
+ return {
+ "reference_types": {},
+ "references": [],
+ "documents": [],
+ "packages": [],
+ "linked_rooms": [],
+ }
+
+ async def list_room_roles(*_a: Any, **_kw: Any) -> list[Any]:
+ return []
+
+ return SimpleNamespace(
+ connections=registry,
+ agent_session_store=store,
+ session_factory=session_factory,
+ agent_store=SimpleNamespace(get=_returning(agent)),
+ room_store=SimpleNamespace(get=_returning(room_model)),
+ require_room_member=require_room_member,
+ list_participants=list_participants,
+ list_room_resources=list_room_resources,
+ list_room_roles=list_room_roles,
+ )
+
+
+def _returning(value: Any):
+ async def _get(*_a: Any, **_kw: Any) -> Any:
+ return value
+
+ return _get
+
+
+def _open(registry: ConnectionRegistry, connection_id: str):
+ return registry.open(
+ agent_id=AGENT,
+ connection_id=connection_id,
+ scope="single",
+ delivery_filter="all",
+ spawn_capable=False,
+ cursor=0,
+ protocol_version=PROTOCOL_VERSION,
+ )
+
+
+def harness(monkeypatch: pytest.MonkeyPatch):
+ registry = ConnectionRegistry()
+ store = _RecordingSessionStore()
+ protocol = _protocol(registry, store)
+ init_operations_protocol(protocol)
+ # The instruction text is a large, separately-tested surface and none of it
+ # bears on the room slot.
+ monkeypatch.setattr(definitions, "build_room_instructions", lambda *a, **kw: "")
+ yield SimpleNamespace(registry=registry, store=store)
+ init_operations_protocol(None) # type: ignore[arg-type]
+
+
+async def _connect_as(connection_id: str) -> dict[str, Any]:
+ token = set_call_context(CallContext(agent_id=AGENT, session_key=connection_id))
+ try:
+ return await definitions.connect_to_room(
+ ROOM, include_general_instructions=False
+ )
+ finally:
+ reset_call_context(token)
+
+
+async def test_the_first_session_in_a_room_is_warned_about_nothing(
+ harness: Any,
+) -> None:
+ _open(harness.registry, "session-one")
+
+ result = await _connect_as("session-one")
+
+ assert result["warning"] is None
+ assert result["room_id"] == ROOM
+
+
+async def test_the_second_session_is_told_it_displaced_the_first(harness: Any) -> None:
+ """The response that used to hide this is the one that now carries it.
+
+ Without it the caller has no way to distinguish "I am in the room" from "I
+ took the room off something that was working in it".
+ """
+ _open(harness.registry, "session-one")
+ await _connect_as("session-one")
+ _open(harness.registry, "session-two")
+
+ result = await _connect_as("session-two")
+
+ assert result["warning"] is not None
+ assert "session-one" in result["warning"]
+ assert ROOM in result["warning"]
+
+
+async def test_the_second_session_actually_gets_the_room(harness: Any) -> None:
+ """Warning without delivery would be the old bug wearing a label.
+
+ The point of taking over is that the newcomer receives the room's events;
+ the previous holder must no longer be the claimant.
+ """
+ first = _open(harness.registry, "session-one")
+ await _connect_as("session-one")
+ _open(harness.registry, "session-two")
+
+ await _connect_as("session-two")
+
+ claimant = harness.registry.claimant_of(AGENT, ROOM)
+ assert claimant is not None
+ assert claimant.id == "session-two"
+ assert ROOM not in first.rooms
+
+
+async def test_the_evicted_session_is_woken_so_its_stream_reports_the_loss(
+ harness: Any,
+) -> None:
+ """How the loser — and through it, switchdash's sidebar — finds out.
+
+ The eviction reaches the previous holder as `subscription_changed` on its
+ own stream. Its client clears the room from the session, which is what stops
+ switchdash showing two sessions under one room.
+ """
+ first = _open(harness.registry, "session-one")
+ await _connect_as("session-one")
+ first.wake.clear()
+ _open(harness.registry, "session-two")
+
+ await _connect_as("session-two")
+
+ assert first.wake.is_set()
+
+
+async def test_reconnecting_as_the_same_session_warns_about_nothing(
+ harness: Any,
+) -> None:
+ """A session re-running its connect has displaced nobody but itself."""
+ _open(harness.registry, "session-one")
+ await _connect_as("session-one")
+
+ result = await _connect_as("session-one")
+
+ assert result["warning"] is None
+
+
+async def test_a_caller_with_no_live_connection_still_connects(harness: Any) -> None:
+ """An MCP transport session has no connection to claim on.
+
+ It is bound by the `agent_sessions` row instead, so the call must succeed
+ and report no eviction rather than failing for want of a slot.
+ """
+ result = await _connect_as("mcp-transport-session")
+
+ assert result["warning"] is None
+ assert harness.store.bindings == [(AGENT, ROOM, "mcp-transport-session")]
diff --git a/core/uv.lock b/core/uv.lock
index 33a3bede3..62611169c 100644
--- a/core/uv.lock
+++ b/core/uv.lock
@@ -2433,7 +2433,7 @@ wheels = [
[[package]]
name = "switch-core"
-version = "0.11.0"
+version = "0.12.0"
source = { editable = "." }
dependencies = [
{ name = "aiohttp" },
diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/remote-session-reconciler.test.ts b/dash/apps/switchdash-desktop/src/main/core/agents/remote-session-reconciler.test.ts
index 7ef13998d..6cc4192c7 100644
--- a/dash/apps/switchdash-desktop/src/main/core/agents/remote-session-reconciler.test.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/agents/remote-session-reconciler.test.ts
@@ -176,6 +176,36 @@ describe('RemoteSessionReconciler', () => {
expect(mirrorRemoteSessionRoom).not.toHaveBeenCalled();
});
+ it('drops the room mirror once the sidecar stops reporting a room (CHOO-1419)', async () => {
+ // A remote session evicted from its room used to keep its place in the
+ // sidebar, sitting under the room next to the session that took it — the
+ // two-sessions-in-one-room illusion. The sidecar reports the room is gone;
+ // that has to reach the mirror.
+ knownRows = [{ id: 'session-evicted' }];
+ httpGetJsonOverChannel.mockResolvedValue({
+ sessions: [{ sessionId: 'session-evicted', roomId: 'room-1' }],
+ });
+ await reconcile('agent-1');
+ expect(mirrorRemoteSessionRoom).toHaveBeenCalled();
+
+ httpGetJsonOverChannel.mockResolvedValue({
+ sessions: [{ sessionId: 'session-evicted', roomId: null }],
+ });
+ await reconcile('agent-1');
+
+ expect(clearSessionRoom).toHaveBeenCalledWith('session-evicted');
+ });
+
+ it('leaves a live session alone when the poll itself failed', async () => {
+ // The room must not be cleared because the VM was briefly unreachable —
+ // an unreadable snapshot says nothing about where a session is.
+ knownRows = [{ id: 'session-live' }];
+ httpGetJsonOverChannel.mockRejectedValue(new Error('unreachable'));
+ await reconcile('agent-1');
+
+ expect(clearSessionRoom).not.toHaveBeenCalled();
+ });
+
it('clears the room mirror when a session row is removed', async () => {
knownRows = [{ id: 'session-term', agentId: 'agent-1' }];
await handleRemoteTerminated('session-term');
diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/remote-session-reconciler.ts b/dash/apps/switchdash-desktop/src/main/core/agents/remote-session-reconciler.ts
index 6f2a9173d..1670c2922 100644
--- a/dash/apps/switchdash-desktop/src/main/core/agents/remote-session-reconciler.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/agents/remote-session-reconciler.ts
@@ -334,10 +334,17 @@ class RemoteSessionReconciler {
// this is what recovers a session's room after a restart/wake (the row is
// re-adopted but the room association is otherwise dropped) and reflects a
// later reconnect/room switch, for both freshly-adopted and already-known
- // sessions. Only sets a room the sidecar actually reports; clearing is left
- // to the prune/terminate path so a transient null poll cannot flicker the
- // badge off a still-live session.
+ // sessions.
+ //
+ // A null room is reported, not ignored. The snapshot is only trusted at
+ // all once `snapshot.ok` has passed, and for a session the sidecar owns
+ // "no room" is a fact it holds rather than a gap in the poll: the session
+ // has not connected yet, or it was evicted from the room it had. Dropping
+ // it left an evicted session sitting under a room it no longer attends,
+ // beside the session that took it — two sessions in one room, which is
+ // the illusion CHOO-1419 is about.
if (vm.roomId) this.mirrorSessionRoom(agent, vm.sessionId, vm.roomId);
+ else switchRoomService.clearSession(vm.sessionId);
}
await this.pruneVanished(agentId, vmIds);
diff --git a/dash/apps/switchdash-desktop/src/sidecar/sidecar-runtime.test.ts b/dash/apps/switchdash-desktop/src/sidecar/sidecar-runtime.test.ts
index 6d53ce349..12d51aa3e 100644
--- a/dash/apps/switchdash-desktop/src/sidecar/sidecar-runtime.test.ts
+++ b/dash/apps/switchdash-desktop/src/sidecar/sidecar-runtime.test.ts
@@ -51,6 +51,10 @@ function fakeRegistry(): SessionRegistry & { entries: () => SidecarSessionEntry[
const prev = sessions.get(entry.sessionId);
sessions.set(entry.sessionId, { ...entry, roomId: entry.roomId ?? prev?.roomId ?? null });
},
+ clearRoom: (id) => {
+ const prev = sessions.get(id);
+ if (prev) sessions.set(id, { ...prev, roomId: null });
+ },
forget: (id) => void sessions.delete(id),
entries: () => [...sessions.values()],
};
@@ -229,6 +233,44 @@ describe('SidecarRuntime (multi-session)', () => {
]);
});
+ it('reports a session evicted from its room as roomless (CHOO-1419)', async () => {
+ // The eviction reaches the sidecar as the server reporting an empty room
+ // list on the session's connection. Keeping the old room here is what left
+ // an evicted session displayed under a room it no longer attends.
+ const { runtime, created, registry } = makeRuntime();
+ await runtime.handleHook(switchRoomHook('room-1', PTY_A));
+
+ created[0].deps.onRoomChanged?.(null);
+
+ expect(runtime.connectedSessions()).toEqual([{ sessionId: 'session-a', roomId: null }]);
+ expect(runtime.roomIdForSession('session-a')).toBeNull();
+ expect(registry.entries()).toEqual([
+ expect.objectContaining({ sessionId: 'session-a', roomId: null }),
+ ]);
+ });
+
+ it('omits a session whose room the server has not named yet', async () => {
+ // Same `roomId: null` as an eviction, and it must NOT be reported: the
+ // supervisor opens the connection before the agent connects to anything, so
+ // publishing this one as roomless would overwrite the room the durable
+ // registry restored for a pane that outlived a supervisor restart.
+ const { runtime } = makeRuntime();
+
+ await runtime.ensureForSession('session-a', 'claude-code', null);
+
+ expect(runtime.connectedSessions()).toEqual([]);
+ });
+
+ it('stops reporting an evicted room as live, so the watcher may spawn again', async () => {
+ const { runtime, created } = makeRuntime();
+ await runtime.handleHook(switchRoomHook('room-1', PTY_A));
+ expect(runtime.hasLiveRoom('room-1')).toBe(true);
+
+ created[0].deps.onRoomChanged?.(null);
+
+ expect(runtime.hasLiveRoom('room-1')).toBe(false);
+ });
+
it('omits a connected session whose pane has died from connectedSessions()', async () => {
const created: Array<{ deps: RoomConnectionDeps; conn: ManagedConnection }> = [];
const factory: RoomConnectionFactory = (deps) => {
diff --git a/dash/apps/switchdash-desktop/src/sidecar/sidecar-runtime.ts b/dash/apps/switchdash-desktop/src/sidecar/sidecar-runtime.ts
index 21f46ec7f..3c441e604 100644
--- a/dash/apps/switchdash-desktop/src/sidecar/sidecar-runtime.ts
+++ b/dash/apps/switchdash-desktop/src/sidecar/sidecar-runtime.ts
@@ -58,14 +58,25 @@ export interface SessionRegistry {
providerId: string;
tmuxTarget: string;
}): void;
+ /** Drop the session's room while keeping the session. Distinct from `record`
+ * with a null room, which means "no room information" and preserves what is
+ * already known. */
+ clearRoom(sessionId: string): void;
forget(sessionId: string): void;
}
interface SessionConnection {
connection: ManagedConnection;
- /** Null for a session whose connection is open but whose room the server has
- * not named yet — `connectRoom` already branches on exactly that state. */
+ /** Null while the session holds no room — the server has not named one yet,
+ * or it named one and then took it away. `connectRoom` branches on this. */
roomId: string | null;
+ /** True once the server has taken this session's room away, as opposed to
+ * never having named one. The two are both `roomId: null` but must be
+ * reported differently: a session that lost its room has to be published as
+ * roomless so clients stop showing it under a room it no longer attends,
+ * whereas one that has yet to be told its room must not overwrite the room
+ * the durable registry restored for it. */
+ lostRoom: boolean;
tmuxTarget: string;
}
@@ -262,15 +273,25 @@ export class SidecarRuntime {
// session that moves rooms is followed without re-reading a hook.
onRoomChanged: (room) => {
const entry = this.sessions.get(sessionId);
- if (entry) entry.roomId = room;
+ if (entry) {
+ entry.roomId = room;
+ if (!room) entry.lostRoom = true;
+ }
if (room) {
this.deps.registry.record({ sessionId, roomId: room, providerId, tmuxTarget });
this.roomConnectedListener?.(room, sessionId);
+ return;
}
+ // Losing the room has to reach the durable registry too. It is what
+ // `/sessions` reports for a pane with no live connection and what a
+ // restart restores from, so leaving the old room there would put the
+ // session back under a room it no longer attends — and reconnect it,
+ // taking the room off whoever holds it now.
+ this.deps.registry.clearRoom(sessionId);
},
log: this.deps.log,
});
- this.sessions.set(sessionId, { connection, roomId, tmuxTarget });
+ this.sessions.set(sessionId, { connection, roomId, lostRoom: false, tmuxTarget });
if (roomId) this.deps.registry.record({ sessionId, roomId, providerId, tmuxTarget });
// The other end of the watcher's hand-off. If a spawned session comes up
// without the message that triggered it, this says whether a cursor was
@@ -331,13 +352,12 @@ export class SidecarRuntime {
* room the server has actually named, since a room-less one has nothing for
* switchdash to reconcile against.
*/
- connectedSessions(): Array<{ sessionId: string; roomId: string }> {
- const out: Array<{ sessionId: string; roomId: string }> = [];
+ connectedSessions(): Array<{ sessionId: string; roomId: string | null }> {
+ const out: Array<{ sessionId: string; roomId: string | null }> = [];
for (const [sessionId, session] of this.sessions) {
- const roomId = session.roomId;
- if (roomId && this.deps.isPaneLive(session.tmuxTarget)) {
- out.push({ sessionId, roomId });
- }
+ if (!this.deps.isPaneLive(session.tmuxTarget)) continue;
+ if (session.roomId === null && !session.lostRoom) continue;
+ out.push({ sessionId, roomId: session.roomId });
}
return out;
}
diff --git a/dash/apps/switchdash-desktop/src/sidecar/sidecar-state.test.ts b/dash/apps/switchdash-desktop/src/sidecar/sidecar-state.test.ts
index 1b8c2b18b..5a509a130 100644
--- a/dash/apps/switchdash-desktop/src/sidecar/sidecar-state.test.ts
+++ b/dash/apps/switchdash-desktop/src/sidecar/sidecar-state.test.ts
@@ -130,6 +130,32 @@ describe('SidecarStateStore', () => {
await store.close();
});
+ it('clears a room on request, which a bare hook must not do (CHOO-1419)', async () => {
+ const store = await open();
+ store.record(entry());
+
+ store.clearRoom('session-a');
+
+ expect(store.roomIdFor('session-a')).toBeNull();
+ expect(store.has('session-a')).toBe(true);
+ await store.close();
+ });
+
+ it('does not resurrect a cleared room across a restart', async () => {
+ // The restored entry is what /sessions reports for a pane with no live
+ // connection, and what a restarted session reconnects to. A room that
+ // outlived its connection would be re-claimed from whoever holds it now.
+ const first = await open();
+ first.record(entry());
+ first.clearRoom('session-a');
+ await first.close();
+
+ const second = await open();
+
+ expect(second.roomIdFor('session-a')).toBeNull();
+ await second.close();
+ });
+
it('forgets a deleted session so it is not restored', async () => {
const first = await open();
first.record(entry());
diff --git a/dash/apps/switchdash-desktop/src/sidecar/sidecar-state.ts b/dash/apps/switchdash-desktop/src/sidecar/sidecar-state.ts
index f29463beb..fcce43c0e 100644
--- a/dash/apps/switchdash-desktop/src/sidecar/sidecar-state.ts
+++ b/dash/apps/switchdash-desktop/src/sidecar/sidecar-state.ts
@@ -213,6 +213,22 @@ export class SidecarStateStore {
this.scheduleFlush();
}
+ /**
+ * Drop a session's room, keeping the session itself.
+ *
+ * The counterpart `record` cannot express: there a null room means "no room
+ * information" and the known room is kept, which is right for a bare hook but
+ * wrong for a session that genuinely left. Without this the last known room
+ * outlives the connection that held it, and `/sessions` keeps reporting a
+ * session under a room somebody else now holds.
+ */
+ clearRoom(sessionId: string): void {
+ const prev = this.sessions.get(sessionId);
+ if (!prev || prev.roomId === null) return;
+ this.sessions.set(sessionId, { ...prev, roomId: null });
+ this.scheduleFlush();
+ }
+
forget(sessionId: string): void {
if (this.sessions.delete(sessionId)) this.scheduleFlush();
}
diff --git a/docs/api/AGENT_PROTOCOL.md b/docs/api/AGENT_PROTOCOL.md
index bbfe9aa58..aea7ddd83 100644
--- a/docs/api/AGENT_PROTOCOL.md
+++ b/docs/api/AGENT_PROTOCOL.md
@@ -129,6 +129,18 @@ naming the incumbent. The common cause is an accident (a stale process, a
double launch) and rejecting surfaces it. An explicit takeover flag forces the
claim, evicting the incumbent, which is told why.
+**`connect_to_room` takes over rather than rejecting** (CHOO-1419). A tool call
+is not a client negotiating for a slot: it is a session that has already been
+started to work in this room and has nowhere else to go, so refusing it strands
+a live session instead of resolving the duplicate. It claims with takeover and
+returns a `warning` naming the room and the evicted connection; the incumbent
+learns it lost the room from `subscription_changed` on its own stream. Reporting
+is the load-bearing half — an unannounced takeover is indistinguishable from the
+duplicate-session bug it resolves, because in both a session stops receiving a
+room and nothing says why. A **dead** incumbent is not an eviction and is not
+reported: `claimant_of` filters on liveness, so a restart meeting its own stale
+connection displaces nobody.
+
### 2.5 Sessions are not a server concept
Switch models connections, not sessions. Whether a client runs one PTY or ten
@@ -724,8 +736,8 @@ Fail loud, never fake. Concretely:
| heartbeat with no stream attached | reject: reopen the stream |
| call with unknown/dead `connection_id` | reject: reconnect and resume |
| `connection_id` belonging to another agent | reject |
-| room slot already claimed | reject, naming the incumbent |
-| slot taken over | incumbent receives `evicted` and stops |
+| room slot already claimed | reject, naming the incumbent — except `connect_to_room`, which takes over and reports what it evicted |
+| slot taken over | incumbent's rooms change; it receives `subscription_changed` and goes dark on that room |
| server restart | cursors invalidated; clients told to re-read |
| incompatible protocol version | refuse at open with an upgrade message |
| per-agent connection cap exceeded | reject loudly |