Skip to content

Commit 830af22

Browse files
authored
fix: keep a separate agent session for each person in a thread (#285)
* fix: reply once to a thread reply that mentions the agent A thread reply that @-mentions the agent fires both app_mention and message, so the agent ran twice and posted two replies. The message listener now leaves those replies to app_mention. * test: assert the agent runs for a thread reply * fix: keep a separate agent session for each person in a thread Sessions were keyed by channel and thread, so anyone replying in a channel thread resumed the session of the person who started it, including results the agent fetched with that person's user token. Sessions are now keyed by channel, thread, and user. The agent auto-replies in a thread only to people with their own session, and others start one with an @mention. * test: check that a DM mentioning the agent still runs it * refactor: name the own session check and test session keys for each person
1 parent 66284fa commit 830af22

22 files changed

Lines changed: 378 additions & 49 deletions

File tree

‎README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@ Once the agent is running, there are several ways to interact:
7474

7575
* **App Home** — Open the agent in Slack and click the _Home_ tab to see a welcome message.
7676
* **Direct Messages** — Open a DM with the agent. Pick a suggested prompt or type your own message, and the agent will reply in a thread.
77-
* **Channel @mentions** — Invite the agent to a channel by typing `/invite @agent-name`, then @mention it with your message. It responds in a thread so the channel stays clean.
77+
* **Channel @mentions** — Invite the agent to a channel by typing `/invite @agent-name`, then @mention it with your message. It responds in a thread so the channel stays clean. It replies to follow-ups from the person who mentioned it and anyone else can @mention it to start their own conversation.
7878
* **Assistant Panel** — Click _Add Agent_ in the top-right corner of Slack, select the agent, and choose a suggested prompt like _Write a Message_, _Summarize_, or _Brainstorm_.
7979

8080
For full setup instructions, pick a framework above and follow the README in that directory.

‎claude-agent-sdk/README.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -276,7 +276,7 @@ Once the agent is running, there are several ways to interact:
276276

277277
**Direct Messages** — Open a DM with the agent. You'll see suggested prompts like _Write a Message_, _Summarize_, and _Brainstorm_ — pick one or type your own message. The agent replies in a thread. Send follow-up messages in the same thread and the agent will maintain the full conversation context.
278278

279-
**Channel @mentions** — Invite the agent to a channel by typing `/invite @agent-name` in the message box, then @mention it followed by your message. The agent responds in a thread so the channel stays clean.
279+
**Channel @mentions** — Invite the agent to a channel by typing `/invite @agent-name` in the message box, then @mention it followed by your message. The agent responds in a thread so the channel stays clean. In that thread, the agent replies to follow-up messages from the person who mentioned it. Anyone else in the thread can @mention the agent to start their own conversation and the agent keeps each person's conversation separate.
280280

281281
**Assistant Panel** — Click _Add Agent_ in the top-right corner of Slack, select the agent from the list, then pick a suggested prompt or type a message.
282282

@@ -333,7 +333,7 @@ The `tools` directory contains one example tool (emoji reaction) defined using t
333333

334334
### `/thread_context`
335335

336-
The `store.py` file implements a thread-safe in-memory session ID store, keyed by channel and thread. The Claude Agent SDK manages conversation history server-side via sessions, so only session IDs need to be tracked locally for resuming conversations.
336+
The `store.py` file implements a thread-safe in-memory session ID store, keyed by channel, thread, and user, so each person in a thread has their own conversation. The Claude Agent SDK manages conversation history server-side via sessions, so only session IDs need to be tracked locally for resuming conversations.
337337

338338
## Troubleshooting
339339

‎claude-agent-sdk/listeners/events/app_mentioned.py‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,9 @@ async def handle_app_mentioned(
5050
)
5151

5252
# Get session ID for conversation context
53-
existing_session_id = session_store.get_session(channel_id, thread_ts)
53+
existing_session_id = session_store.get_session(
54+
channel_id, thread_ts, context.user_id
55+
)
5456

5557
# Run the agent with deps for tool access
5658
deps = AgentDeps(
@@ -73,7 +75,9 @@ async def handle_app_mentioned(
7375

7476
# Store session ID for future context
7577
if new_session_id:
76-
session_store.set_session(channel_id, thread_ts, new_session_id)
78+
session_store.set_session(
79+
channel_id, thread_ts, context.user_id, new_session_id
80+
)
7781

7882
except Exception as e:
7983
logger.exception("Failed to handle app mention")

‎claude-agent-sdk/listeners/events/message.py‎

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -35,9 +35,10 @@ async def handle_message(
3535
elif is_thread_reply:
3636
if f"<@{context.bot_user_id}>" in event.get("text", ""):
3737
return
38-
# Channel thread replies are handled only if the bot is already engaged
39-
session = session_store.get_session(context.channel_id, event["thread_ts"])
40-
if session is None:
38+
own_session = session_store.get_session(
39+
context.channel_id, event["thread_ts"], context.user_id
40+
)
41+
if own_session is None:
4142
return
4243
else:
4344
# Top-level channel messages are handled by app_mentioned
@@ -49,7 +50,9 @@ async def handle_message(
4950
thread_ts = event.get("thread_ts") or event["ts"]
5051

5152
# Get session ID for conversation context
52-
existing_session_id = session_store.get_session(channel_id, thread_ts)
53+
existing_session_id = session_store.get_session(
54+
channel_id, thread_ts, context.user_id
55+
)
5356

5457
# Set assistant thread status with loading messages
5558
await set_status(
@@ -85,7 +88,9 @@ async def handle_message(
8588

8689
# Store session ID for future context
8790
if new_session_id:
88-
session_store.set_session(channel_id, thread_ts, new_session_id)
91+
session_store.set_session(
92+
channel_id, thread_ts, context.user_id, new_session_id
93+
)
8994

9095
except Exception as e:
9196
logger.exception("Failed to handle message")
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
import logging
2+
from unittest.mock import AsyncMock, Mock, patch
3+
4+
import pytest
5+
from slack_bolt.context.async_context import AsyncBoltContext
6+
from slack_sdk.web.async_client import AsyncWebClient
7+
8+
from listeners.events.app_mentioned import handle_app_mentioned
9+
from thread_context import session_store
10+
11+
test_logger = logging.getLogger(__name__)
12+
13+
14+
class TestAppMentioned:
15+
def setup_method(self):
16+
session_store.set_session("C234", "1.0", "U123", "session-1")
17+
self.fake_client = Mock(AsyncWebClient)
18+
self.fake_client.reactions_add = AsyncMock()
19+
self.fake_context = Mock(AsyncBoltContext)
20+
self.fake_context.bot_user_id = "UBOT"
21+
self.fake_context.channel_id = "C234"
22+
self.fake_context.user_id = "U456"
23+
24+
@pytest.mark.asyncio
25+
async def test_starts_a_separate_session_for_a_second_person_in_the_thread(self):
26+
with patch(
27+
"listeners.events.app_mentioned.run_agent",
28+
AsyncMock(return_value=("Hi", "session-2")),
29+
) as fake_run_agent:
30+
await handle_app_mentioned(
31+
client=self.fake_client,
32+
context=self.fake_context,
33+
event={
34+
"channel": "C234",
35+
"text": "<@UBOT> what did you find?",
36+
"thread_ts": "1.0",
37+
"ts": "3.0",
38+
"user": "U456",
39+
},
40+
logger=test_logger,
41+
say=AsyncMock(),
42+
say_stream=AsyncMock(
43+
return_value=Mock(append=AsyncMock(), stop=AsyncMock())
44+
),
45+
set_status=AsyncMock(),
46+
)
47+
48+
assert fake_run_agent.call_args.kwargs["session_id"] is None
49+
assert session_store.get_session("C234", "1.0", "U456") == "session-2"
50+
assert session_store.get_session("C234", "1.0", "U123") == "session-1"

‎claude-agent-sdk/tests/test_message.py‎

Lines changed: 38 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313

1414
class TestMessage:
1515
def setup_method(self):
16-
session_store.set_session("C123", "1.0", "session-1")
16+
session_store.set_session("C123", "1.0", "U123", "session-1")
1717
self.fake_client = Mock(AsyncWebClient)
1818
self.fake_client.reactions_add = AsyncMock()
1919
self.fake_context = Mock(AsyncBoltContext)
@@ -64,3 +64,40 @@ async def test_runs_agent_for_dm_that_mentions_the_agent(self):
6464
)
6565

6666
fake_run_agent.assert_called_once()
67+
68+
@pytest.mark.asyncio
69+
async def test_skips_thread_reply_from_someone_without_their_own_session(self):
70+
self.fake_context.user_id = "U456"
71+
72+
fake_run_agent = await self.handle("what did you find?", user="U456")
73+
74+
fake_run_agent.assert_not_called()
75+
76+
@pytest.mark.asyncio
77+
async def test_stores_the_new_session_under_the_person_who_replied(self):
78+
session_store.set_session("C123", "1.0", "U123", "session-1")
79+
80+
with patch(
81+
"listeners.events.message.run_agent",
82+
AsyncMock(return_value=("Hi", "session-2")),
83+
):
84+
await handle_message(
85+
client=self.fake_client,
86+
context=self.fake_context,
87+
event={
88+
"channel_type": "channel",
89+
"text": "and then?",
90+
"thread_ts": "1.0",
91+
"ts": "2.0",
92+
"user": "U123",
93+
},
94+
logger=test_logger,
95+
say=AsyncMock(),
96+
say_stream=AsyncMock(
97+
return_value=Mock(append=AsyncMock(), stop=AsyncMock())
98+
),
99+
set_status=AsyncMock(),
100+
)
101+
102+
assert session_store.get_session("C123", "1.0", "U123") == "session-2"
103+
assert session_store.get_session("C123", "1.0", "U456") is None
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
from thread_context.store import SessionStore
2+
3+
4+
class TestSessionStore:
5+
def test_keeps_different_users_in_the_same_thread_independent(self):
6+
store = SessionStore()
7+
store.set_session("C1", "T1", "U1", "sid-1")
8+
9+
assert store.get_session("C1", "T1", "U2") is None
10+
11+
store.set_session("C1", "T1", "U2", "sid-2")
12+
13+
assert store.get_session("C1", "T1", "U1") == "sid-1"
14+
assert store.get_session("C1", "T1", "U2") == "sid-2"

‎claude-agent-sdk/thread_context/store.py‎

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,24 +5,23 @@
55
class SessionStore:
66
"""Thread-safe in-memory session ID store.
77
8-
Stores Claude Agent SDK session IDs keyed by (channel_id, thread_ts).
98
The SDK manages conversation history server-side via sessions, so we
109
only need to track session IDs for resuming conversations.
1110
Includes TTL-based cleanup and a maximum entry limit.
1211
"""
1312

1413
def __init__(self, ttl_seconds: int = 86400, max_entries: int = 1000):
15-
self._store: dict[tuple[str, str], dict] = {}
14+
self._store: dict[tuple[str, str, str], dict] = {}
1615
self._lock = threading.Lock()
1716
self._ttl_seconds = ttl_seconds
1817
self._max_entries = max_entries
1918

20-
def get_session(self, channel_id: str, thread_ts: str) -> str | None:
19+
def get_session(self, channel_id: str, thread_ts: str, user_id: str) -> str | None:
2120
"""Retrieve session ID for a thread.
2221
2322
Returns None if no session exists or if the session has expired.
2423
"""
25-
key = (channel_id, thread_ts)
24+
key = (channel_id, thread_ts, user_id)
2625
with self._lock:
2726
entry = self._store.get(key)
2827
if entry is None:
@@ -32,9 +31,11 @@ def get_session(self, channel_id: str, thread_ts: str) -> str | None:
3231
return None
3332
return entry["session_id"]
3433

35-
def set_session(self, channel_id: str, thread_ts: str, session_id: str) -> None:
34+
def set_session(
35+
self, channel_id: str, thread_ts: str, user_id: str, session_id: str
36+
) -> None:
3637
"""Store session ID for a thread."""
37-
key = (channel_id, thread_ts)
38+
key = (channel_id, thread_ts, user_id)
3839
with self._lock:
3940
self._store[key] = {
4041
"session_id": session_id,

‎openai-agents-sdk/README.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -276,7 +276,7 @@ Once the agent is running, there are several ways to interact:
276276

277277
**Direct Messages** — Open a DM with the agent. You'll see suggested prompts like _Write a Message_, _Summarize_, and _Brainstorm_ — pick one or type your own message. The agent replies in a thread. Send follow-up messages in the same thread and the agent will maintain the full conversation context.
278278

279-
**Channel @mentions** — Invite the agent to a channel by typing `/invite @agent-name` in the message box, then @mention it followed by your message. The agent responds in a thread so the channel stays clean.
279+
**Channel @mentions** — Invite the agent to a channel by typing `/invite @agent-name` in the message box, then @mention it followed by your message. The agent responds in a thread so the channel stays clean. In that thread, the agent replies to follow-up messages from the person who mentioned it. Anyone else in the thread can @mention the agent to start their own conversation and the agent keeps each person's conversation separate.
280280

281281
**Assistant Panel** — Click _Add Agent_ in the top-right corner of Slack, select the agent from the list, then pick a suggested prompt or type a message.
282282

@@ -333,7 +333,7 @@ The `tools` directory contains one example tool (emoji reaction) that the agent
333333

334334
### `/thread_context`
335335

336-
The `store.py` file implements a thread-safe in-memory conversation history store, keyed by channel and thread. This enables multi-turn conversations where the agent remembers previous context within a thread.
336+
The `store.py` file implements a thread-safe in-memory conversation history store, keyed by channel, thread, and user, so each person in a thread has their own conversation. This enables multi-turn conversations where the agent remembers previous context within a thread.
337337

338338
## Troubleshooting
339339

‎openai-agents-sdk/listeners/events/app_mentioned.py‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ def handle_app_mentioned(
4848
)
4949

5050
# Get conversation history
51-
history = conversation_store.get_history(channel_id, thread_ts)
51+
history = conversation_store.get_history(channel_id, thread_ts, context.user_id)
5252

5353
# Build input for the agent
5454
if history:
@@ -74,7 +74,9 @@ def handle_app_mentioned(
7474
streamer.stop(blocks=feedback_blocks)
7575

7676
# Store conversation history
77-
conversation_store.set_history(channel_id, thread_ts, result.to_input_list())
77+
conversation_store.set_history(
78+
channel_id, thread_ts, context.user_id, result.to_input_list()
79+
)
7880

7981
except Exception as e:
8082
logger.exception("Failed to handle app mention")

0 commit comments

Comments
 (0)