diff --git a/CHANGELOG.md b/CHANGELOG.md index 5a63bdd..9f9046b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,13 @@ Sync wave from `chat@4.31.0` to `chat@4.41.1` (tracking #184). `UPSTREAM_PARITY` stays `4.31.0` until #203. +- **Slack Agent Sessions lifecycle and native stop** (#215; Slack half of vercel/chat `2ce2be00` #862, chat@4.39.0, plus `8b6d7f3a` #882 and `2cc8cc3f` #897, chat@4.40.0). Only with `agent_view=True`; without it nothing changes (no `agents.sessions.*` call, byte-identical stream stop payloads). A live check in an `agent_view` workspace is still pending. + - **Consumer-visible (agent_view typing):** `start_typing()` without a status (and `thread.start_typing()`) now moves the agent session to `processing` through `agents.sessions.setStatus` (with `initiator_user_id`) instead of calling `assistant.threads.setStatus` with "Typing..."; `start_typing(thread_id, "")` moves it to `active`. A custom status still goes through `assistant.threads.setStatus`. A failed `agents.sessions.setStatus` is logged, with no legacy fallback. The adapter now has `end_typing`, so a reply posted after `thread.start_typing()` (a post, or a post+edit stream) moves the session back to `active` (or the `StreamingPlanOptions.session_status`). + - **Consumer-visible (agent_view status and titles):** `set_assistant_status(channel, ts, "")` (or whitespace) sets the session `active` instead of sending an empty status; a custom status without `loading_messages` (explicit or configured) now sends `loading_messages=[status]`. `set_assistant_title` calls `agents.sessions.rename` instead of `assistant.threads.setTitle`. + - **Consumer-visible (agent_view streams):** native `stream()` sends `session_status` on `chat.stopStream` (`"active"`, or `StreamOptions.session_status`) and `"processing"` when a long reply rotates to a new message. The adapter's post+edit fallback and the final-stop expiry path call `end_typing` with the same status. When the turn's `signal` is aborted, `stream()` stops reading and finalizes the message with what was streamed. + - **Consumer-visible (Stop button):** an `agent_session_stopped` event aborts the running turn (`chat.abort_turn`: `thread.signal` fires, also across processes, since `supports_turn_cancellation` is now `agent_view`), sets the session `active`, then runs `chat.on_agent_session_stopped` handlers. It never waits for the thread lock. `agent_session_title_changed` runs `chat.on_agent_session_title_changed` handlers. + - **Consumer-visible (automatic titles):** a top-level human DM under `agent_view` now renames its session to the message's first line (trimmed, at most 80 characters) after it is processed. New `SlackAdapterConfig.session_title`: `None` (default, on under `agent_view`), `False` to opt out, or a sync/async resolver taking `SlackSessionTitleContext` (return `None` to skip). Failures are logged. + - New public `SlackAdapter.set_session_status(channel_id, thread_ts, status, *, initiator_user_id=None, title=None)`; new types `SlackSessionTitle`, `SlackSessionTitleContext` in `chat_sdk.adapters.slack.types`. Under an org-wide Enterprise Grid install, `agents.sessions.setStatus` / `agents.sessions.rename` carry the event's `team_id` like the other Web API calls (#268). - **Teams outbound: reactions, targeted ephemeral messages, placeholder-aware native streaming** (#219). Ports vercel/chat `5eb8b846` (#734), `160140e3` (#737) and `93a58af5` (#709) from chat@4.35.0, and `85089037` (#951, chat@4.41.0). A live Teams check is pending. - **Consumer-visible (Teams):** `add_reaction` / `remove_reaction` now call the Teams conversations reactions API instead of logging a warning, and can raise (`AuthenticationError`, `AdapterPermissionError`, `NetworkError`, `AdapterRateLimitError`). `check`, `eyes`, `pin`, `rocket`, `thinking`, `thumbs_up` and `x` map to their Teams IDs; any other name is sent as a native Teams reaction ID (`like`, `heart`, `1f440_eyes`, ...). - **Consumer-visible (Teams):** `TeamsAdapter.post_ephemeral` is new. In channels and group chats, `thread.post_ephemeral(user, ...)` now sends a native targeted message that only `user` sees (`used_fallback=False`), instead of opening a DM. The app must be installed in that conversation. In a 1:1 chat it posts normally with `used_fallback=True`. Edits and deletes of a targeted message go through the targeted endpoint: the sent id is recorded in the state adapter under `teams:targetedActivity:{conversationId}:{messageId}` for 24 hours (the key upstream uses), and state errors fall back to the plain endpoint. diff --git a/docs/UPSTREAM_SYNC.md b/docs/UPSTREAM_SYNC.md index 28a9de9..a541957 100644 --- a/docs/UPSTREAM_SYNC.md +++ b/docs/UPSTREAM_SYNC.md @@ -2120,8 +2120,8 @@ of `c21ccbc0` (#943). Everything is opt-in on `SlackAdapterConfig`. `propagate_handler_errors` and `wait_until` are both set. The task is created synchronously inside the webhook's copied context, so it sees the multi-workspace token. It is pinned and has a done-callback that retrieves - its exception. `CancelledError` propagates. The Agent Sessions title hook - (#215) goes at the end of the task. Python-specific: `wait_until` gets + its exception. `CancelledError` propagates. The task ends by applying the + configured Agent Sessions title (#215). Python-specific: `wait_until` gets `asyncio.shield(bridge)`, not the task itself. Upstream's promise cannot be cancelled, but an asyncio task can, so a host that cancels its `wait_until` awaitable after the 200 would otherwise drop the DM before `process_message` @@ -2143,8 +2143,8 @@ of `c21ccbc0` (#943). Everything is opt-in on `SlackAdapterConfig`. `loading_messages=[status] if status else (configured if configured is not None else ["Typing..."])` (upstream `??`). `set_assistant_status` uses the explicit `loading_messages` when it is not `None`, otherwise the config. - As before, the field is omitted when it is empty. Upstream's agent-view - status branches belong to #215. + As before, the field is omitted when it is empty. The agent-view status + branches came with #215. - **`feedback_buttons: bool | SlackFeedbackButtonsOptions | None`.** `True` normalizes to `SlackFeedbackButtonsOptions()`. `build_feedback_buttons_block(options=None)` builds the `context_actions` block (`message_feedback`, `"Good response"` / @@ -2176,9 +2176,9 @@ of `c21ccbc0` (#943). Everything is opt-in on `SlackAdapterConfig`. next to #211's flat-DM case. Under agent_view, edits and deletes of a top-level DM use the per-message thread and are not bridged to a subscribed `slack:{D}:` thread, as upstream (`handleMessageChanged` / - `handleMessageDeleted` call `threadIdForMessageEvent` directly). Not - ported: the session-title / session-status cases in the same describe - blocks (#215). + `handleMessageDeleted` call `threadIdForMessageEvent` directly). The + session-title / session-status cases in the same describe blocks are in + `tests/test_slack_agent_sessions.py` (#215). ### Streaming and thread API (chat@4.32–4.41.1, #199) @@ -2397,19 +2397,99 @@ current stream (a "segment") and continues the reply in a new message. - **slack_sdk floor.** The `slack` extras now need `slack-sdk>=3.40.0`, the first release whose `AsyncChatStream.append` takes `chunks` (the replay and the `chunks=[]` flush need it). -- **Deferred (#215).** The rotation `stop()` does not send - `session_status="processing"` under `agent_view`, and the return of the - finalized message after a final-stop expiry does not call `end_typing` - (upstream `index.ts:6508`). Both places carry a `# SL10:` marker. +- **Agent Sessions (#215).** Under `agent_view` the rotation `stop()` sends + `session_status="processing"`, and the return of the finalized message + after a final-stop expiry calls `end_typing` (upstream `index.ts:6508`). - **Tests.** `tests/test_slack_stream_rotation.py` ports 17 of the 18 "native stream rotation" tests (the `it.each` max-age case is one - parametrized test; the `agent_view` one is #215), plus Python tests for + parametrized test; the `agent_view` one landed with #215), plus Python tests for the Grid `team_id` on every segment, rotation cutting the mention-resolved buffer, cancellation during the rotation `stop()` and the successor's replay, the final-stop expiry without a recorded ts, a structured chunk confirming buffered text, the table separator's whitespace set and the fence tracker's closing rules. +### Slack Agent Sessions lifecycle and native stop (chat@4.39–4.40, #215) + +Slack half of `2ce2be00` (vercel/chat#862, chat@4.39.0) plus `8b6d7f3a` +(#882) and `2cc8cc3f` (#897, both chat@4.40.0), on top of #201's turn +cancellation and #214's `agent_view`. Everything is gated on `agent_view`; +the legacy `assistant_view` payloads are unchanged. No divergence-table rows. + +- **Lifecycle calls.** `set_session_status(channel_id, thread_ts, status, *, + initiator_user_id=None, title=None)` and `_rename_agent_session` call + `client.api_call(api_method="agents.sessions.setStatus" | "agents.sessions.rename", + json=...)` (slack_sdk has no generated `agents_sessions_*` methods). The + optional fields are sent only when truthy, as upstream's spreads. As + upstream's `withToken`, the `json` body goes through `_with_token_kwargs` + (#268), so an org-wide install adds the event's `team_id` (the body has + `channel_id`, not `channel`, so no `client_context_team_id`). +- **`supports_turn_cancellation`** returns `agent_view`. +- **`start_typing(thread_id, status=None, *, options=None)`.** Under + `agent_view`, `None` sets the session to `processing` and `""` to `active` + (8b6d7f3a; compared with `== ""`, never `or`), with `initiator_user_id` + from `TypingOptions`, logging failures without a legacy fallback. A custom + status still uses `assistant.threads.setStatus` (2cc8cc3f: Slack's + compatibility bridge renders it in the agent-session loading UX). +- **`end_typing(thread_id, status="active")`** sets the session status; it + does nothing without `agent_view` or a thread ts and logs failures. +- **`set_assistant_status`.** Under `agent_view` an empty or whitespace-only + status (`not status.strip()`) sets the session to `active`. Otherwise the + legacy call's `loading_messages` is the explicit list, then the config, + then `[status]` under `agent_view` (omitted when empty, as before). + **`set_assistant_title`** renames the agent session under `agent_view`. +- **`stream()`.** Each chunk-loop iteration first checks + `options.signal.aborted` and breaks, so the stream is still finalized + through `stop()` (the signal is checked, the task is not cancelled). + Before breaking it closes the input iterator (best-effort `aclose()`, so a + failing close cannot skip `stop()`): JS `for await` + does that on `break`, Python's `async for` does not. + Under `agent_view` the final `stop()` carries `session_status` + (`options.session_status`, default `"active"`), the rotation `stop()` + carries `"processing"`, and every fallback return (post+edit fallback, + first-stop failure, final-stop expiry) calls `end_typing` with the same + status. +- **Events.** `agent_session_stopped` builds the thread id from `channel` + + `thread_ts` and runs a task that awaits `chat.abort_turn` (warns on error), + sets the session `active` (warns on error) and calls + `chat.process_agent_session_stopped` with `streaming_message_ts`. As + upstream, that dispatch is fire-and-forget: the handlers run in their own + task, which core hands to the same `wait_until`. It never + takes the thread lock (the stopped turn holds it). The task is pinned, has + a logging done-callback, and is handed to `wait_until` shielded, as #214's + bridge. `agent_session_title_changed` calls + `process_agent_session_title_changed` (`title`, `previous_title`). +- **`session_title`** (`SlackSessionTitle = bool | resolver`, default + `None` meaning `agent_view`; `SlackSessionTitleContext(channel_id, text, + thread_ts, user_id)`). The open_dm bridge task applies it after + `process_message` for a top-level human DM with text (no `bot_id`, + `subtype` or `thread_ts`): the resolver's result (sync or async; `None` + skips) or the first line, trimmed and cut to 80 characters (code points; + upstream's `slice` counts UTF-16 units). Errors are logged. Upstream also + schedules the title after `processMessage` on the non-bridge path for the + same messages; that branch is unreachable (the bridge takes every + agent_view top-level DM first), so it is not ported. +- **Tests.** `tests/test_slack_agent_sessions.py` ports the named + `index.test.ts` cases ("routes custom labels and clearing separately on an + agent_view DM thread", "uses native $expected without custom text in agent + view", "does not fall back to a legacy label when native status fails", + "surfaces custom status text via the legacy API and clears via the + sessions lifecycle", "passes agent loading messages $expected", "renames + an agent session under agentView", "aborts and activates an agent session + when the user stops it", "dispatches agent session title changes" and the + three automatic-title cases); "finishes agent streams with an active + session status" is in `tests/test_slack_api.py` and "keeps the agent + session processing while the reply continues" in + `tests/test_slack_stream_rotation.py`. Python tests cover legacy mode + making no `agents.sessions.*` call, `""` versus `None`, an aborted signal + still awaiting `stop()` once, append-failure, first-stop-failure and + final-expiry `end_typing`, the + stop handler aborting a real turn that holds the thread lock, and title + trimming, resolvers and failures. `index.test.ts` is not fidelity-mapped. +- **Live check pending.** The Stop button cancelling a streaming reply and + the session returning to `active` still need a check in an `agent_view` + workspace. + ### AI messages without text and tool names (chat@4.35–4.41, #198) Parity with upstream `25f30998` (vercel/chat#713, chat@4.35.0), adapted diff --git a/src/chat_sdk/adapters/slack/adapter.py b/src/chat_sdk/adapters/slack/adapter.py index d0bbdde..84f2290 100644 --- a/src/chat_sdk/adapters/slack/adapter.py +++ b/src/chat_sdk/adapters/slack/adapter.py @@ -28,6 +28,7 @@ from typing import Any, Literal, NoReturn, TypedDict, cast from urllib.parse import parse_qs +from chat_sdk._compat import aclose_quietly from chat_sdk.adapters.slack.agent_context import ( _js_truthy, get_app_context, @@ -68,6 +69,8 @@ SlackFeedbackButtonsOptions, SlackInstallation, SlackInstallationProvider, + SlackSessionTitle, + SlackSessionTitleContext, SlackSuggestedPrompts, SlackSuggestedPromptsContext, SlackThreadId, @@ -107,6 +110,9 @@ from chat_sdk.types import ( ActionEvent, AdapterPostableMessage, + AgentSessionStatus, + AgentSessionStoppedEvent, + AgentSessionTitleChangedEvent, AppContextChangedEvent, AppHomeOpenedEvent, AssistantContextChangedEvent, @@ -1440,6 +1446,11 @@ def __init__(self, config: SlackAdapterConfig | None = None) -> None: self._agent_view: bool = config.agent_view self._suggested_prompts: SlackSuggestedPrompts | None = config.suggested_prompts self._loading_messages: list[str] | None = config.loading_messages + # Automatic agent-session titles (vercel/chat 2ce2be00 #862): on by + # default under agent_view (upstream ``sessionTitle ?? agentView``). + self._session_title: SlackSessionTitle = ( + config.session_title if config.session_title is not None else self._agent_view + ) # Normalized feedback_buttons config (``True`` becomes the defaults). self._feedback_buttons: SlackFeedbackButtonsOptions | None = None if config.feedback_buttons: @@ -1575,6 +1586,16 @@ def bot_user_id(self) -> str | None: def lock_scope(self) -> LockScope: return self._lock_scope + @property + def supports_turn_cancellation(self) -> bool: + """``True`` under ``agent_view``: Slack's native Stop button aborts turns. + + Chat then publishes each turn in the state backend, so an + ``agent_session_stopped`` delivered to another process still aborts + the turn (upstream ``supportsTurnCancellation = agentView``). + """ + return self._agent_view + @property def persist_message_history(self) -> bool: return self._persist_message_history @@ -2943,6 +2964,10 @@ def _process_event_payload(self, payload: dict[str, Any], options: WebhookOption self._handle_assistant_thread_started(event, options) elif event_type == "assistant_thread_context_changed": self._handle_assistant_context_changed(event, options) + elif event_type == "agent_session_stopped": + self._handle_agent_session_stopped(event, options) + elif event_type == "agent_session_title_changed": + self._handle_agent_session_title_changed(event, options) elif event_type == "app_context_changed": self._handle_app_context_changed(event, options) elif event_type == "app_home_opened": @@ -3931,6 +3956,11 @@ async def factory() -> Message: self._bridge_agent_view_dm(event, thread_id, make_factory, options) return + # Upstream (chat@4.41.1 index.ts:3537-3557) also schedules the session + # title after this call for an agent_view top-level human DM. That + # branch is unreachable there: every such message took the bridge + # above (same ``agentView && isDM && !thread_ts`` guard), which applies + # the title itself. Not ported. self._chat.process_message(self, thread_id, make_factory(thread_id), options) def _bridge_agent_view_dm( @@ -3976,8 +4006,7 @@ async def _bridge() -> None: # and has a wait_until to observe the failure. if options is not None and options.propagate_handler_errors and options.wait_until is not None: raise - # Hook for #215 (Agent Sessions): upstream applies the configured - # session title here (``applyConfiguredSessionTitle``). + await self._apply_configured_session_title(event) try: bridge = asyncio.get_running_loop().create_task(_bridge()) @@ -4217,6 +4246,141 @@ def _handle_assistant_context_changed(self, event: dict[str, Any], options: Webh options, ) + # ================================================================== + # Agent Sessions (agent_view) + # ================================================================== + + def _handle_agent_session_stopped(self, event: dict[str, Any], options: WebhookOptions | None = None) -> None: + """The user pressed Slack's native Stop button (vercel/chat 2ce2be00 #862). + + Aborts the session's running turn, moves the session back to + ``active`` and dispatches ``on_agent_session_stopped``. Runs as its + own task without the thread lock: the turn being stopped holds it. + """ + chat = self._chat + if chat is None: + self._logger.warn("Chat instance not initialized, ignoring agent_session_stopped") + return + + channel_id: str = event.get("channel") or "" + thread_ts: str = event.get("thread_ts") or "" + thread_id = self.encode_thread_id(SlackThreadId(channel=channel_id, thread_ts=thread_ts)) + streaming_message_ts = event.get("streaming_message_ts") + + async def _stop() -> None: + try: + await chat.abort_turn(thread_id) + except Exception as error: + self._logger.warn( + "Failed to abort stopped Slack agent session", {"error": error, "threadId": thread_id} + ) + try: + await self.set_session_status(channel_id, thread_ts, "active") + except Exception as error: + self._logger.warn( + "Failed to activate stopped Slack agent session", {"error": error, "threadId": thread_id} + ) + # Upstream parity (chat@4.41.1 index.ts:3980-3990): dispatch is + # fire-and-forget here; ``process_agent_session_stopped`` hands + # its own handler task to the same ``wait_until``. + chat.process_agent_session_stopped( + AgentSessionStoppedEvent( + adapter=self, + channel_id=channel_id, + streaming_message_ts=list(streaming_message_ts) if isinstance(streaming_message_ts, list) else [], + thread_id=thread_id, + thread_ts=thread_ts, + user_id=event.get("user") or "", + ), + options, + ) + + try: + task = asyncio.get_running_loop().create_task(_stop()) + except RuntimeError: + return # No running event loop + # Upstream parity: not tracked by ``disconnect()`` (see the DM bridge). + _pin_task(task) + task.add_done_callback(self._log_agent_session_stop_result) + if options is not None and options.wait_until is not None: + # Shielded, as for the DM bridge: a host cancelling its wait_until + # task must not cancel the (uncancellable upstream) stop work. + options.wait_until(asyncio.shield(task)) + + def _log_agent_session_stop_result(self, task: asyncio.Task[Any]) -> None: + """Done-callback for the stop task: log (and so retrieve) an unexpected failure.""" + if task.cancelled(): + return + error = task.exception() + if error is not None: + self._logger.error("Slack agent_session_stopped handling failed", {"error": error}) + + def _handle_agent_session_title_changed(self, event: dict[str, Any], options: WebhookOptions | None = None) -> None: + """An agent session's title changed (vercel/chat 2ce2be00 #862).""" + if not self._chat: + self._logger.warn("Chat instance not initialized, ignoring agent_session_title_changed") + return + channel_id: str = event.get("channel") or "" + thread_ts: str = event.get("thread_ts") or "" + self._chat.process_agent_session_title_changed( + AgentSessionTitleChangedEvent( + adapter=self, + channel_id=channel_id, + previous_title=event.get("previous_title"), + thread_id=self.encode_thread_id(SlackThreadId(channel=channel_id, thread_ts=thread_ts)), + thread_ts=thread_ts, + title=event.get("title") or "", + user_id=event.get("user") or "", + ), + options, + ) + + async def _apply_configured_session_title(self, event: dict[str, Any]) -> None: + """Title a new agent session from its root message (upstream ``applyConfiguredSessionTitle``). + + Only for a top-level human DM with text under ``agent_view``. The + title is the resolver's result, or the message's first line, trimmed + and cut to 80 characters (code points, where upstream's ``slice`` + counts UTF-16 units); an empty title is skipped. Errors are logged, + never raised. + """ + channel_id = event.get("channel") + ts = event.get("ts") + user_id = event.get("user") + text = event.get("text") + if not ( + self._agent_view + and self._session_title + and channel_id + and ts + and user_id + and isinstance(text, str) + and text + and not event.get("bot_id") + and not event.get("subtype") + and not event.get("thread_ts") + ): + return + try: + configured = self._session_title + if callable(configured): + resolved = configured( + SlackSessionTitleContext(channel_id=channel_id, text=text, thread_ts=ts, user_id=user_id) + ) + if inspect.isawaitable(resolved): + resolved = await resolved + else: + resolved = text.split("\n", 1)[0].strip() + title = resolved.strip()[:80] if isinstance(resolved, str) else "" + if not title: + return + await self._rename_agent_session(channel_id, ts, title) + except Exception as error: + self._logger.warn( + "Failed to set Slack agent session title", + {"channelId": channel_id, "error": error, "threadTs": ts}, + ) + # ================================================================== # App home / member joined # ================================================================== @@ -4429,9 +4593,20 @@ async def set_assistant_status( ) -> None: """Set status/thinking indicator for an assistant thread. + A custom status goes through the legacy ``assistant.threads.setStatus`` + API, also under ``agent_view``, where Slack's compatibility bridge + renders the text in the agent-session loading UX + (``agents.sessions.setStatus`` only takes lifecycle states). Under + ``agent_view`` an empty or whitespace-only status clears the loading + state by moving the session to ``active`` (vercel/chat 2cc8cc3f #897). + When ``loading_messages`` is omitted (``None``), falls back to the - adapter-level ``loading_messages`` config (vercel/chat 0f743c9b). + adapter-level ``loading_messages`` config (vercel/chat 0f743c9b), and + under ``agent_view`` then to ``[status]``. """ + if self._agent_view and not status.strip(): + await self.set_session_status(channel_id, thread_ts, "active") + return client = self._get_client() kwargs: dict[str, Any] = { "channel_id": channel_id, @@ -4439,12 +4614,51 @@ async def set_assistant_status( "status": status, } effective_loading_messages = loading_messages if loading_messages is not None else self._loading_messages + if effective_loading_messages is None and self._agent_view: + effective_loading_messages = [status] if effective_loading_messages: kwargs["loading_messages"] = effective_loading_messages await client.assistant_threads_setStatus(**self._with_token_kwargs(**kwargs)) + async def set_session_status( + self, + channel_id: str, + thread_ts: str, + status: AgentSessionStatus, + *, + initiator_user_id: str | None = None, + title: str | None = None, + ) -> None: + """Set a Slack Agent Session lifecycle state, creating the session if needed. + + Calls ``agents.sessions.setStatus`` (vercel/chat 2ce2be00 #862). Raises + ``SlackApiError`` when Slack rejects the call. + """ + payload: dict[str, Any] = {"channel_id": channel_id, "thread_ts": thread_ts, "status": status} + if initiator_user_id: + payload["initiator_user_id"] = initiator_user_id + if title: + payload["title"] = title + # slack_sdk has no generated ``agents_sessions_*`` methods. + await self._get_client().api_call( + api_method="agents.sessions.setStatus", json=self._with_token_kwargs(**payload) + ) + + async def _rename_agent_session(self, channel_id: str, thread_ts: str, title: str) -> None: + """Rename a Slack Agent Session (``agents.sessions.rename``).""" + await self._get_client().api_call( + api_method="agents.sessions.rename", + json=self._with_token_kwargs(channel_id=channel_id, thread_ts=thread_ts, title=title), + ) + async def set_assistant_title(self, channel_id: str, thread_ts: str, title: str) -> None: - """Set title for an assistant thread (shown in History tab).""" + """Set title for an assistant thread (shown in History tab). + + Under ``agent_view`` this renames the agent session instead. + """ + if self._agent_view: + await self._rename_agent_session(channel_id, thread_ts, title) + return client = self._get_client() await client.assistant_threads_setTitle( **self._with_token_kwargs(channel_id=channel_id, thread_ts=thread_ts, title=title) @@ -5907,7 +6121,11 @@ async def start_typing( ) -> None: """Show typing / status indicator in the thread. - Uses Slack's ``assistant.threads.setStatus`` API when available. + A custom status uses Slack's ``assistant.threads.setStatus`` API. Under + ``agent_view`` without one, the agent session moves to + ``processing`` (no status) or ``active`` (an explicit ``""``, which + clears it) through ``agents.sessions.setStatus`` instead + (vercel/chat 2ce2be00, 8b6d7f3a, 2cc8cc3f). Failures are logged. """ decoded = self.decode_thread_id(thread_id) channel = decoded.channel @@ -5915,6 +6133,26 @@ async def start_typing( if not thread_ts: self._logger.debug("Slack: startTyping skipped - no thread context") return + if self._agent_view and not status: + # ``""`` and ``None`` differ here: ``""`` clears (8b6d7f3a). + session_status: AgentSessionStatus = "active" if status == "" else "processing" + self._logger.debug( + "Slack API: agents.sessions.setStatus", + {"channel": channel, "threadTs": thread_ts, "status": session_status}, + ) + try: + await self.set_session_status( + channel, + thread_ts, + session_status, + initiator_user_id=options.initiator_user_id if options is not None else None, + ) + except Exception as exc: + self._logger.warn( + "Slack API: agents.sessions.setStatus failed", + {"channel": channel, "threadTs": thread_ts, "error": exc}, + ) + return # Upstream (vercel/chat 0f743c9b): ``status ?? loadingMessages?.[0] ?? # "Typing..."`` and ``status ? [status] : (loadingMessages ?? @@ -5942,6 +6180,27 @@ async def start_typing( {"channel": channel, "threadTs": thread_ts, "error": exc}, ) + async def end_typing(self, thread_id: str, status: AgentSessionStatus | None = "active") -> None: + """Move the agent session to ``status`` after a reply (``agent_view`` only). + + Does nothing without ``agent_view`` or a thread ts. ``None`` means + ``"active"``. Failures are logged (upstream ``endTyping``). + """ + if not self._agent_view: + return + decoded = self.decode_thread_id(thread_id) + if not decoded.thread_ts: + return + try: + await self.set_session_status( + decoded.channel, decoded.thread_ts, status if status is not None else "active" + ) + except Exception as exc: + self._logger.warn( + "Slack API: agents.sessions.setStatus failed", + {"channel": decoded.channel, "threadTs": decoded.thread_ts, "error": exc}, + ) + # ================================================================== # Streaming # ================================================================== @@ -6031,6 +6290,12 @@ async def stream( stream_kwargs["team_id"] = recipient_team_id if options and options.task_display_mode: stream_kwargs["task_display_mode"] = options.task_display_mode + # Agent session state once the reply ends (agent_view only; vercel/chat + # 2ce2be00): sent with the final ``stop`` and on every early return. + session_status: AgentSessionStatus = ( + options.session_status if options is not None and options.session_status is not None else "active" + ) + signal = options.signal if options is not None else None async def create_streamer() -> Any: # Every segment gets the same kwargs, including the Grid @@ -6323,9 +6588,10 @@ async def rotate_segment(delta: str) -> str: stop_kwargs: dict[str, Any] = {"token": token} if final_text: stop_kwargs["markdown_text"] = final_text - # SL10: agent_view keeps the session busy here with - # ``session_status="processing"`` (upstream d4a1f03a), since the - # reply continues in the next segment. Wired with #215. + if self._agent_view: + # Keep the agent session busy: the reply continues in the next + # segment, and chat.stopStream defaults to "active". + stop_kwargs["session_status"] = "processing" try: result = await segment.streamer.stop(**stop_kwargs) last_flushed = sent @@ -6453,7 +6719,17 @@ async def push_text_and_flush(text: str) -> None: renderer.push(text) await flush_committed() - async for chunk in text_stream: + source = aiter(text_stream) + async for chunk in source: + # The turn was stopped (e.g. Slack's Stop button): stop reading + # and finalize below, so the stream is still closed cleanly. + if signal is not None and signal.aborted: + # Python-specific: JS ``for await`` closes the iterator on + # ``break``; Python's ``async for`` does not, which would leave + # a generator input (and its producer cleanup) suspended. + # Best-effort, so a failing close cannot skip ``stop()``. + await aclose_quietly(source) + break if isinstance(chunk, str): await push_text_and_flush(chunk) elif isinstance(chunk, dict) and chunk.get("type") == "markdown_text": @@ -6487,6 +6763,7 @@ async def push_text_and_flush(text: str) -> None: await flush_committed(force=True) if mode == "fallback": + await self.end_typing(thread_id, session_status) return finish_fallback() # Caller blocks (StreamingPlan end_with) first, then the configured @@ -6496,6 +6773,9 @@ async def push_text_and_flush(text: str) -> None: if self._feedback_buttons is not None: stop_blocks.append(build_feedback_buttons_block(self._feedback_buttons)) stop_kwargs: dict[str, Any] = {"token": token} + if self._agent_view: + # Only under agent_view, so legacy stop payloads are unchanged. + stop_kwargs["session_status"] = session_status if stop_blocks: stop_kwargs["blocks"] = stop_blocks try: @@ -6513,6 +6793,7 @@ async def push_text_and_flush(text: str) -> None: # ``ts`` accessor). switch_to_fallback(exc) await flush_fallback(True) + await self.end_typing(thread_id, session_status) return finish_fallback() if not is_stream_expired(exc): raise @@ -6530,8 +6811,7 @@ async def push_text_and_flush(text: str) -> None: "Slack: stream expired before stop, stream-end blocks skipped", {"channel": channel, "messageId": expired_ts, "skippedBlocks": len(stop_blocks)}, ) - # SL10: end_typing(thread_id, session_status) before this - # return (upstream index.ts:6508). Wired with #215. + await self.end_typing(thread_id, session_status) return RawMessage(id=expired_ts, thread_id=thread_id, raw={"ts": expired_ts}) self._logger.warn( "Slack: stream expired before stop, delivering the rest in a new message", diff --git a/src/chat_sdk/adapters/slack/types.py b/src/chat_sdk/adapters/slack/types.py index b733512..48362cc 100644 --- a/src/chat_sdk/adapters/slack/types.py +++ b/src/chat_sdk/adapters/slack/types.py @@ -112,6 +112,28 @@ class SlackSuggestedPromptsContext: ] SlackSuggestedPrompts: TypeAlias = SlackSuggestedPromptsOptions | SlackSuggestedPromptsResolver + +@dataclass +class SlackSessionTitleContext: + """Context passed to a dynamic agent-session title resolver.""" + + # The DM channel the agent session lives in. + channel_id: str + # Text of the session's root user message. + text: str + # The session's root message ts. + thread_ts: str + # The user who sent the root message. + user_id: str + + +# Automatic agent-session title configuration (upstream ``SlackSessionTitle``): +# ``True`` uses the first line of the root message, ``False`` disables +# automatic titles, and a resolver (sync or async) returns a custom title or +# ``None`` to skip it. +SlackSessionTitleResolver = Callable[[SlackSessionTitleContext], "str | None | Awaitable[str | None]"] +SlackSessionTitle: TypeAlias = bool | SlackSessionTitleResolver + # ============================================================================= # Configuration # ============================================================================= @@ -273,6 +295,15 @@ class SlackAdapterConfig: # :class:`SlackSuggestedPromptsOptions` or a sync/async resolver taking a # :class:`SlackSuggestedPromptsContext`. Failures are logged, never raised. suggested_prompts: SlackSuggestedPrompts | None = None + # Automatically title new agent sessions from their root user message + # (``agents.sessions.rename``), applied after a top-level human DM is + # processed under ``agent_view``. ``None`` (the default) means on when + # ``agent_view`` is enabled. ``True`` uses the first line of the message + # (trimmed, at most 80 characters), ``False`` disables it, and a sync or + # async resolver taking a :class:`SlackSessionTitleContext` returns the + # title or ``None`` to skip it. Failures are logged, never raised. + # Upstream ``sessionTitle``. + session_title: SlackSessionTitle | None = None # Default rotating loading messages for the assistant thinking indicator # (``assistant.threads.setStatus`` ``loading_messages``). Used by # ``start_typing`` and ``set_assistant_status`` when no explicit diff --git a/tests/test_slack_agent_sessions.py b/tests/test_slack_agent_sessions.py new file mode 100644 index 0000000..41c0477 --- /dev/null +++ b/tests/test_slack_agent_sessions.py @@ -0,0 +1,663 @@ +"""Slack Agent Sessions lifecycle and native stop (issue #215). + +Ports the Agent Sessions cases of upstream +``packages/adapter-slack/src/index.test.ts`` (chat@4.41.1; vercel/chat +2ce2be00 #862, 2cc8cc3f #897, 8b6d7f3a #882), plus Python-specific guards. +The stream rotation and native-stream-fallback cases live with their +describes in ``test_slack_stream_rotation.py`` / ``test_slack_api.py``. +""" + +from __future__ import annotations + +import asyncio +import hashlib +import hmac +import json +import time +from collections.abc import AsyncIterator +from typing import Any +from unittest.mock import AsyncMock, MagicMock, call + +import pytest + +from chat_sdk.adapters.slack.adapter import SlackAdapter, create_slack_adapter +from chat_sdk.adapters.slack.types import SlackAdapterConfig, SlackSessionTitleContext +from chat_sdk.chat import Chat +from chat_sdk.state.memory import MemoryStateAdapter +from chat_sdk.testing import MockLogger, create_mock_chat_instance, create_mock_state +from chat_sdk.types import ( + AgentSessionStoppedEvent, + ChatConfig, + RawMessage, + StreamOptions, + TurnSignal, + TypingOptions, + WebhookOptions, +) + +SECRET = "test-signing-secret" +TOKEN = "xoxb-test-token" +SET_STATUS = "agents.sessions.setStatus" +RENAME = "agents.sessions.rename" + + +@pytest.fixture(autouse=True) +def _clean_slack_env(monkeypatch: pytest.MonkeyPatch) -> None: + for key in ("SLACK_BOT_TOKEN", "SLACK_SIGNING_SECRET", "SLACK_CLIENT_ID", "SLACK_CLIENT_SECRET", "SLACK_APP_TOKEN"): + monkeypatch.delenv(key, raising=False) + + +class _FakeRequest: + def __init__(self, body: str, headers: dict[str, str]): + self.body = body.encode("utf-8") + self.headers = headers + self.url = "" + + async def text(self) -> str: + return self.body.decode("utf-8") + + +def _signed(payload: dict[str, Any]) -> _FakeRequest: + body = json.dumps(payload) + ts = str(int(time.time())) + sig = "v0=" + hmac.new(SECRET.encode(), f"v0:{ts}:{body}".encode(), hashlib.sha256).hexdigest() + return _FakeRequest( + body, {"x-slack-request-timestamp": ts, "x-slack-signature": sig, "content-type": "application/json"} + ) + + +def _adapter(**config: Any) -> tuple[SlackAdapter, MagicMock, MockLogger]: + logger = MockLogger() + defaults: dict[str, Any] = {"bot_token": TOKEN, "signing_secret": SECRET, "bot_user_id": "U_BOT", "logger": logger} + defaults.update(config) + adapter = create_slack_adapter(SlackAdapterConfig(**defaults)) + client = MagicMock() + client.api_call = AsyncMock(return_value={"ok": True}) + client.assistant_threads_setStatus = AsyncMock(return_value={"ok": True}) + client.assistant_threads_setTitle = AsyncMock(return_value={"ok": True}) + client.users_info = AsyncMock(return_value={"ok": True, "user": {"name": "user", "real_name": "User"}}) + adapter._get_client = lambda token=None: client # type: ignore[method-assign] + return adapter, client, logger + + +def _api_calls(client: MagicMock, method: str) -> list[dict[str, Any]]: + return [c.kwargs["json"] for c in client.api_call.await_args_list if c.kwargs.get("api_method") == method] + + +async def _dispatch(adapter: SlackAdapter, payload: dict[str, Any]) -> dict[str, Any]: + tasks: list[Any] = [] + response = await adapter.handle_webhook(_signed(payload), WebhookOptions(wait_until=tasks.append)) + await asyncio.gather(*tasks) + return response + + +def _dm_message(**extra: Any) -> dict[str, Any]: + return { + "type": "event_callback", + "event": { + "type": "message", + "channel": "D1", + "channel_type": "im", + "user": "U1", + "text": "hi", + "ts": "1771.99", + "event_ts": "1771.99", + **extra, + }, + } + + +def _stopped_event() -> dict[str, Any]: + return { + "type": "event_callback", + "team_id": "T123", + "event": { + "type": "agent_session_stopped", + "user": "U_USER", + "channel": "D_AGENT", + "thread_ts": "1234567890.111111", + "streaming_message_ts": ["1234567891.222222", "1234567891.333333"], + "event_ts": "1234567892.333333", + }, + } + + +async def _init(adapter: SlackAdapter, state: Any = None) -> Any: + chat = create_mock_chat_instance( + state=state if state is not None else create_mock_state(), + overrides={"process_message": MagicMock(return_value=None)}, + ) + await adapter.initialize(chat) + return chat + + +# --------------------------------------------------------------------------- +# Typing / status / title (PR A) +# --------------------------------------------------------------------------- + + +class TestAgentSessionStatus: + # TS: "routes custom labels and clearing separately on an agent_view DM thread" + async def test_routes_custom_labels_and_clearing_separately_on_an_agent_view_dm_thread(self): + adapter, client, _ = _adapter(agent_view=True) + options = TypingOptions(initiator_user_id="U1") + + await adapter.start_typing("slack:D1:1771.99", "Thinking...", options=options) + await adapter.start_typing("slack:D1:1771.99", "", options=options) + await adapter.start_typing("slack:D1:1771.99", "Reading xyz.md", options=options) + + # Custom statuses go through the legacy Assistants API, whose + # compatibility bridge renders the text in the agent-session loading UX. + assert [c.kwargs for c in client.assistant_threads_setStatus.await_args_list] == [ + {"channel_id": "D1", "thread_ts": "1771.99", "status": "Thinking...", "loading_messages": ["Thinking..."]}, + { + "channel_id": "D1", + "thread_ts": "1771.99", + "status": "Reading xyz.md", + "loading_messages": ["Reading xyz.md"], + }, + ] + # An explicit empty status ends typing via the Agent Sessions lifecycle. + assert _api_calls(client, SET_STATUS) == [ + {"channel_id": "D1", "thread_ts": "1771.99", "status": "active", "initiator_user_id": "U1"} + ] + + # TS: "uses native $expected without custom text in agent view" (it.each). + # Also the Python-specific ``""`` vs ``None`` guard (8b6d7f3a): never + # collapse the two with ``or``. + @pytest.mark.parametrize(("status", "expected"), [(None, "processing"), ("", "active")]) + async def test_uses_native_status_without_custom_text_in_agent_view(self, status, expected): + adapter, client, _ = _adapter(agent_view=True, loading_messages=["Configured..."]) + + await adapter.start_typing("slack:D123:1.2", status, options=TypingOptions(initiator_user_id="U123")) + + client.api_call.assert_awaited_once_with( + api_method=SET_STATUS, + json={"channel_id": "D123", "thread_ts": "1.2", "status": expected, "initiator_user_id": "U123"}, + ) + client.assistant_threads_setStatus.assert_not_awaited() + + # TS: "does not fall back to a legacy label when native status fails" + async def test_does_not_fall_back_to_a_legacy_label_when_native_status_fails(self): + adapter, client, logger = _adapter(agent_view=True) + failure = RuntimeError("API error") + client.api_call = AsyncMock(side_effect=failure) + + assert await adapter.start_typing("slack:D123:1.2") is None + + client.assistant_threads_setStatus.assert_not_awaited() + warned = [c for c in logger.warn.calls if c[0] == "Slack API: agents.sessions.setStatus failed"] + assert len(warned) == 1 + assert warned[0][1]["error"] is failure + + # TS: "surfaces custom status text via the legacy API and clears via the sessions lifecycle" + async def test_surfaces_custom_status_text_via_the_legacy_api_and_clears_via_the_sessions_lifecycle(self): + adapter, client, _ = _adapter(agent_view=True) + + await adapter.set_assistant_status("D123", "1.2", "Working...") + await adapter.set_assistant_status("D123", "1.2", "") + + client.assistant_threads_setStatus.assert_awaited_once_with( + channel_id="D123", thread_ts="1.2", status="Working...", loading_messages=["Working..."] + ) + client.api_call.assert_awaited_once_with( + api_method=SET_STATUS, json={"channel_id": "D123", "thread_ts": "1.2", "status": "active"} + ) + + # TS: "passes agent loading messages $expected" (it.each) + @pytest.mark.parametrize( + ("configured", "supplied", "expected"), + [ + (None, None, ["Working..."]), + (["Configured..."], None, ["Configured..."]), + (["Configured..."], ["Searching...", "Reading..."], ["Searching...", "Reading..."]), + ], + ) + async def test_passes_agent_loading_messages(self, configured, supplied, expected): + adapter, client, _ = _adapter(agent_view=True, loading_messages=configured) + + await adapter.set_assistant_status("D123", "1.2", "Working...", supplied) + + client.assistant_threads_setStatus.assert_awaited_once_with( + channel_id="D123", thread_ts="1.2", status="Working...", loading_messages=expected + ) + client.api_call.assert_not_awaited() + + # Python-specific: upstream ``!status.trim()`` -- whitespace-only clears too. + async def test_whitespace_only_status_clears_the_session(self): + adapter, client, _ = _adapter(agent_view=True) + + await adapter.set_assistant_status("D123", "1.2", " \n") + + client.assistant_threads_setStatus.assert_not_awaited() + assert _api_calls(client, SET_STATUS) == [{"channel_id": "D123", "thread_ts": "1.2", "status": "active"}] + + # TS: "renames an agent session under agentView" + async def test_renames_an_agent_session_under_agentview(self): + adapter, client, _ = _adapter(agent_view=True) + + await adapter.set_assistant_title("D123", "1.2", "Agent title") + + client.api_call.assert_awaited_once_with( + api_method=RENAME, json={"channel_id": "D123", "thread_ts": "1.2", "title": "Agent title"} + ) + client.assistant_threads_setTitle.assert_not_awaited() + + # Python-specific: the legacy assistant_view path makes no Agent Sessions call. + async def test_legacy_mode_makes_no_agent_sessions_calls(self): + adapter, client, _ = _adapter() + + await adapter.start_typing("slack:D1:1.2") + await adapter.start_typing("slack:D1:1.2", "") + await adapter.end_typing("slack:D1:1.2", "active") + await adapter.set_assistant_status("D1", "1.2", "") + await adapter.set_assistant_title("D1", "1.2", "Title") + await adapter.set_assistant_status("D1", "1.2", "Working...") + + client.api_call.assert_not_awaited() + assert [c.kwargs["status"] for c in client.assistant_threads_setStatus.await_args_list] == [ + "Typing...", + "", + "", + "Working...", + ] + # The ``[status]`` loading_messages fallback is agent_view-only. + assert client.assistant_threads_setStatus.await_args_list[-1] == call( + channel_id="D1", thread_ts="1.2", status="Working..." + ) + client.assistant_threads_setTitle.assert_awaited_once_with(channel_id="D1", thread_ts="1.2", title="Title") + assert adapter.supports_turn_cancellation is False + + async def test_supports_turn_cancellation_under_agent_view(self): + adapter, _, _ = _adapter(agent_view=True) + + assert adapter.supports_turn_cancellation is True + + +class TestEndTyping: + @pytest.mark.parametrize(("status", "expected"), [("suspended", "suspended"), (None, "active")]) + async def test_moves_the_session_to_the_requested_status(self, status, expected): + adapter, client, _ = _adapter(agent_view=True) + + await adapter.end_typing("slack:D1:1.2", status) + + assert _api_calls(client, SET_STATUS) == [{"channel_id": "D1", "thread_ts": "1.2", "status": expected}] + + async def test_skips_a_thread_without_a_ts(self): + adapter, client, _ = _adapter(agent_view=True) + + await adapter.end_typing("slack:D1:") + + client.api_call.assert_not_awaited() + + async def test_logs_a_failure_instead_of_raising(self): + adapter, client, logger = _adapter(agent_view=True) + client.api_call = AsyncMock(side_effect=RuntimeError("boom")) + + await adapter.end_typing("slack:D1:1.2") + + assert [c[0] for c in logger.warn.calls] == ["Slack API: agents.sessions.setStatus failed"] + + +# --------------------------------------------------------------------------- +# stream(): cancellation and session status (PR A) +# --------------------------------------------------------------------------- + + +def _streaming(adapter: SlackAdapter, client: MagicMock) -> MagicMock: + streamer = MagicMock() + streamer.append = AsyncMock(return_value={"ok": True, "ts": "1234567890.5"}) + streamer.stop = AsyncMock(return_value={"ok": True, "ts": "1234567890.5"}) + client.chat_stream = AsyncMock(return_value=streamer) + return streamer + + +class TestStreamCancellation: + # Python-specific: an aborted turn stops reading the stream but still + # finalizes the native stream exactly once (never left open in Slack). + async def test_aborted_signal_stops_reading_and_still_stops_the_stream_once(self): + adapter, client, _ = _adapter(agent_view=True) + streamer = _streaming(adapter, client) + signal = TurnSignal() + thread_id = "slack:D1:1.2" + consumed: list[str] = [] + + async def chunks() -> AsyncIterator[str]: + try: + consumed.append("first") + yield "first\n" + signal._abort() # what Chat.abort_turn does for a running turn + consumed.append("second") + yield "second\n" + consumed.append("third") + yield "third\n" + finally: + # JS ``for await`` closes the source on ``break``; so must we. + consumed.append("closed") + + result = await adapter.stream(thread_id, chunks(), StreamOptions(signal=signal)) + + assert signal.aborted is True + # The chunk yielded after the abort is never sent. + assert consumed == ["first", "second", "closed"] + assert [c.kwargs["markdown_text"] for c in streamer.append.await_args_list] == ["first\n"] + streamer.stop.assert_awaited_once_with(token=TOKEN, session_status="active") + assert isinstance(result, RawMessage) + assert result.id == "1234567890.5" + + # Python-specific: closing a generator that holds a TaskGroup across + # ``yield`` raises ``BaseExceptionGroup([GeneratorExit()])``; the close is + # best-effort, so the native stream is still finalized. + async def test_a_failing_input_close_still_finalizes_the_stream(self): + adapter, client, _ = _adapter(agent_view=True) + streamer = _streaming(adapter, client) + signal = TurnSignal() + + async def chunks() -> AsyncIterator[str]: + async with asyncio.TaskGroup(): + yield "first\n" + signal._abort() + yield "second\n" + + result = await adapter.stream("slack:D1:1.2", chunks(), StreamOptions(signal=signal)) + + streamer.stop.assert_awaited_once_with(token=TOKEN, session_status="active") + assert result is not None + assert result.id == "1234567890.5" + + async def test_requested_session_status_is_sent_on_the_final_stop(self): + adapter, client, _ = _adapter(agent_view=True) + streamer = _streaming(adapter, client) + + async def chunks() -> AsyncIterator[str]: + yield "done\n" + + await adapter.stream("slack:D1:1.2", chunks(), StreamOptions(session_status="suspended")) + + assert streamer.stop.await_args.kwargs["session_status"] == "suspended" + + # Python-specific: without agent_view the stop payload is unchanged. + async def test_legacy_stream_stop_carries_no_session_status(self): + adapter, client, _ = _adapter() + streamer = _streaming(adapter, client) + + async def chunks() -> AsyncIterator[str]: + yield "done\n" + + await adapter.stream("slack:D1:1.2", chunks(), StreamOptions(session_status="suspended")) + + streamer.stop.assert_awaited_once_with(token=TOKEN) + client.api_call.assert_not_awaited() + + async def test_post_and_edit_fallback_ends_the_agent_session(self): + adapter, client, _ = _adapter(agent_view=True) + streamer = _streaming(adapter, client) + streamer.append = AsyncMock(side_effect=RuntimeError("no streaming here")) + adapter.post_message = AsyncMock( # type: ignore[method-assign] + return_value=RawMessage(id="fallback-ts", thread_id="slack:D1:1.2", raw={}) + ) + adapter.edit_message = AsyncMock( # type: ignore[method-assign] + return_value=RawMessage(id="fallback-ts", thread_id="slack:D1:1.2", raw={}) + ) + + async def chunks() -> AsyncIterator[str]: + yield "hello\n" + + result = await adapter.stream("slack:D1:1.2", chunks(), StreamOptions(session_status="suspended")) + + assert result is not None + assert result.id == "fallback-ts" + streamer.stop.assert_not_awaited() + assert _api_calls(client, SET_STATUS) == [{"channel_id": "D1", "thread_ts": "1.2", "status": "suspended"}] + + # Short replies can buffer every delta, so stop() is the first real API + # call; when it fails the reply falls back to post+edit and still ends + # the agent session (upstream index.ts:6471-6484). + async def test_first_stop_failure_fallback_ends_the_agent_session(self): + adapter, client, _ = _adapter(agent_view=True) + streamer = _streaming(adapter, client) + streamer.append = AsyncMock(return_value=None) # buffered, no API call + streamer.stop = AsyncMock(side_effect=RuntimeError("no streaming here")) + adapter.post_message = AsyncMock( # type: ignore[method-assign] + return_value=RawMessage(id="fallback-ts", thread_id="slack:D1:1.2", raw={}) + ) + + async def chunks() -> AsyncIterator[str]: + yield "short reply" + + result = await adapter.stream("slack:D1:1.2", chunks(), StreamOptions(session_status="suspended")) + + assert result is not None + assert result.id == "fallback-ts" + streamer.stop.assert_awaited_once_with(token=TOKEN, session_status="suspended") + assert _api_calls(client, SET_STATUS) == [{"channel_id": "D1", "thread_ts": "1.2", "status": "suspended"}] + + +# --------------------------------------------------------------------------- +# Events (PR B) +# --------------------------------------------------------------------------- + + +class TestAgentSessionEvents: + # TS: "aborts and activates an agent session when the user stops it" + async def test_aborts_and_activates_an_agent_session_when_the_user_stops_it(self): + state = create_mock_state() + adapter, client, _ = _adapter(agent_view=True) + chat = await _init(adapter, state) + + response = await _dispatch(adapter, _stopped_event()) + + thread_id = "slack:D_AGENT:1234567890.111111" + assert response["status"] == 200 + chat.abort_turn.assert_awaited_once_with(thread_id) + assert _api_calls(client, SET_STATUS) == [ + {"channel_id": "D_AGENT", "thread_ts": "1234567890.111111", "status": "active"} + ] + chat.process_agent_session_stopped.assert_called_once() + event, options = chat.process_agent_session_stopped.call_args.args + assert isinstance(event, AgentSessionStoppedEvent) + assert event.adapter is adapter + assert event.channel_id == "D_AGENT" + assert event.streaming_message_ts == ["1234567891.222222", "1234567891.333333"] + assert event.thread_id == thread_id + assert event.thread_ts == "1234567890.111111" + assert event.user_id == "U_USER" + assert isinstance(options, WebhookOptions) + assert state._acquire_lock_calls == [] + + # Python-specific: abort and activation failures are logged and the stop + # is still dispatched. + async def test_stop_dispatches_even_when_abort_and_activation_fail(self): + adapter, client, logger = _adapter(agent_view=True) + chat = await _init(adapter) + chat.abort_turn.side_effect = RuntimeError("state down") + client.api_call = AsyncMock(side_effect=RuntimeError("slack down")) + + await _dispatch(adapter, _stopped_event()) + + assert [c[0] for c in logger.warn.calls] == [ + "Failed to abort stopped Slack agent session", + "Failed to activate stopped Slack agent session", + ] + chat.process_agent_session_stopped.assert_called_once() + + # TS: "dispatches agent session title changes" + async def test_dispatches_agent_session_title_changes(self): + adapter, _, _ = _adapter(agent_view=True) + chat = await _init(adapter) + + response = await adapter.handle_webhook( + _signed( + { + "type": "event_callback", + "team_id": "T123", + "event": { + "type": "agent_session_title_changed", + "user": "U_USER", + "channel": "D_AGENT", + "thread_ts": "1234567890.111111", + "title": "New title", + "event_ts": "1234567892.333333", + "team_id": "T123", + }, + } + ) + ) + + assert response["status"] == 200 + event, options = chat.process_agent_session_title_changed.call_args.args + assert event.previous_title is None + assert event.thread_id == "slack:D_AGENT:1234567890.111111" + assert event.thread_ts == "1234567890.111111" + assert event.title == "New title" + assert event.user_id == "U_USER" + assert event.channel_id == "D_AGENT" + assert options is None + + # Python-specific: the stop handler runs while the stopped turn still + # holds the thread lock (a real Chat; gates, no sleeps). + async def test_stop_aborts_a_running_turn_that_holds_the_thread_lock(self): + adapter, client, _ = _adapter(agent_view=True) + state = MemoryStateAdapter() + chat = Chat(ChatConfig(user_name="bot", adapters={"slack": adapter}, state=state, logger=MockLogger())) + started = asyncio.Event() + stopped_events: list[AgentSessionStoppedEvent] = [] + handler_saw_abort: list[bool] = [] + + async def on_dm(thread: Any, message: Any, *rest: Any) -> None: + started.set() + await thread.signal.wait() + handler_saw_abort.append(thread.signal.aborted) + + async def on_stopped(event: AgentSessionStoppedEvent) -> None: + stopped_events.append(event) + + chat.on_direct_message(on_dm) + chat.on_agent_session_stopped(on_stopped) + tasks: list[Any] = [] + try: + # A threaded follow-up takes the normal (non-bridge) path. + await chat.webhooks["slack"]( + _signed(_dm_message(thread_ts="1771.00")), WebhookOptions(wait_until=tasks.append) + ) + await asyncio.wait_for(started.wait(), timeout=5) + stop = _stopped_event() + stop["event"].update(channel="D1", thread_ts="1771.00") + + await chat.webhooks["slack"](_signed(stop), WebhookOptions(wait_until=tasks.append)) + await asyncio.wait_for(asyncio.gather(*tasks), timeout=5) + + assert handler_saw_abort == [True] + assert [e.thread_id for e in stopped_events] == ["slack:D1:1771.00"] + assert _api_calls(client, SET_STATUS) == [{"channel_id": "D1", "thread_ts": "1771.00", "status": "active"}] + finally: + await asyncio.gather(*tasks, return_exceptions=True) + await chat.shutdown() + + +# --------------------------------------------------------------------------- +# Automatic session titles (PR B) +# --------------------------------------------------------------------------- + + +class TestAutomaticSessionTitles: + # TS: "automatically titles a top-level agent_view DM session" + async def test_automatically_titles_a_top_level_agent_view_dm_session(self): + adapter, client, _ = _adapter(agent_view=True) + await _init(adapter) + + await _dispatch(adapter, _dm_message()) + + assert _api_calls(client, RENAME) == [{"channel_id": "D1", "thread_ts": "1771.99", "title": "hi"}] + + # TS: "skips automatic titles when sessionTitle is disabled" + async def test_skips_automatic_titles_when_sessiontitle_is_disabled(self): + adapter, client, _ = _adapter(agent_view=True, session_title=False) + await _init(adapter) + + await _dispatch(adapter, _dm_message()) + + assert _api_calls(client, RENAME) == [] + + # TS: "does not retitle an agent_view DM follow-up" + async def test_does_not_retitle_an_agent_view_dm_follow_up(self): + adapter, client, _ = _adapter(agent_view=True) + await _init(adapter) + + await _dispatch(adapter, _dm_message(thread_ts="1771.00")) + + assert _api_calls(client, RENAME) == [] + + # Python-specific: first line only, trimmed, cut to 80 characters. + @pytest.mark.parametrize( + ("text", "expected"), + [ + (" Summarize this \nmore detail", "Summarize this"), + (" " + "x" * 100 + " \nsecond line", "x" * 80), + ], + ) + async def test_uses_the_trimmed_first_line_cut_to_80_characters(self, text, expected): + adapter, client, _ = _adapter(agent_view=True) + await _init(adapter) + + await _dispatch(adapter, _dm_message(text=text)) + + assert _api_calls(client, RENAME) == [{"channel_id": "D1", "thread_ts": "1771.99", "title": expected}] + + @pytest.mark.parametrize("is_async", [False, True]) + async def test_uses_a_sync_or_async_resolver(self, is_async): + contexts: list[SlackSessionTitleContext] = [] + + def resolve(context: SlackSessionTitleContext) -> str: + contexts.append(context) + return f" Re: {context.text} " + + async def resolve_async(context: SlackSessionTitleContext) -> str: + return resolve(context) + + adapter, client, _ = _adapter(agent_view=True, session_title=resolve_async if is_async else resolve) + await _init(adapter) + + await _dispatch(adapter, _dm_message()) + + assert contexts == [SlackSessionTitleContext(channel_id="D1", text="hi", thread_ts="1771.99", user_id="U1")] + assert _api_calls(client, RENAME) == [{"channel_id": "D1", "thread_ts": "1771.99", "title": "Re: hi"}] + + @pytest.mark.parametrize("resolved", [None, " "]) + async def test_skips_when_the_resolver_returns_nothing(self, resolved): + adapter, client, _ = _adapter(agent_view=True, session_title=lambda _context: resolved) + await _init(adapter) + + await _dispatch(adapter, _dm_message()) + + assert _api_calls(client, RENAME) == [] + + async def test_logs_a_resolver_failure_without_failing_the_webhook(self): + def boom(_context: SlackSessionTitleContext) -> str: + raise RuntimeError("resolver failed") + + adapter, client, logger = _adapter(agent_view=True, session_title=boom) + await _init(adapter) + + response = await _dispatch(adapter, _dm_message()) + + assert response["status"] == 200 + assert [c[0] for c in logger.warn.calls] == ["Failed to set Slack agent session title"] + assert _api_calls(client, RENAME) == [] + + @pytest.mark.parametrize("extra", [{"bot_id": "B1"}, {"text": ""}, {"subtype": "file_share"}]) + async def test_skips_bot_and_empty_messages(self, extra): + adapter, client, _ = _adapter(agent_view=True) + await _init(adapter) + + await _dispatch(adapter, _dm_message(**extra)) + + assert _api_calls(client, RENAME) == [] + + async def test_defaults_off_without_agent_view(self): + adapter, client, _ = _adapter(session_title=True) + await _init(adapter) + + await _dispatch(adapter, _dm_message()) + + assert _api_calls(client, RENAME) == [] diff --git a/tests/test_slack_api.py b/tests/test_slack_api.py index 519b988..440c391 100644 --- a/tests/test_slack_api.py +++ b/tests/test_slack_api.py @@ -2329,6 +2329,18 @@ def _task_update() -> Any: class TestNativeStreamingFallback: + # TS: "finishes agent streams with an active session status" (vercel/chat 2ce2be00) + @pytest.mark.asyncio + async def test_finishes_agent_streams_with_an_active_session_status(self): + adapter, client, _, _ = _fallback_adapter(agent_view=True) + stop = AsyncMock(return_value={"ok": True, "ts": "stream-ts"}) + client.chat_stream = AsyncMock(return_value=_streamer(AsyncMock(return_value={"ok": True}), stop)) + + await adapter.stream(_DM_STREAM_THREAD, _text_stream("hello")) + + stop.assert_awaited_once() + assert stop.await_args.kwargs["session_status"] == "active" + @pytest.mark.asyncio async def test_returns_none_before_consuming_the_stream_when_native_streaming_is_false(self): adapter, client, _, _ = _fallback_adapter(native_streaming=False) diff --git a/tests/test_slack_enterprise_grid.py b/tests/test_slack_enterprise_grid.py index bdd6642..9a439e9 100644 --- a/tests/test_slack_enterprise_grid.py +++ b/tests/test_slack_enterprise_grid.py @@ -546,6 +546,8 @@ async def _fetch_linked_message(adapter: SlackAdapter) -> None: ("assistant_threads_setStatus", lambda a: a.set_assistant_status("C1", "1.1", "thinking"), False), ("assistant_threads_setTitle", lambda a: a.set_assistant_title("C1", "1.1", "title"), False), ("api_call", lambda a: a.set_suggested_prompts("C1", None, [{"title": "t", "message": "m"}]), False), + ("api_call", lambda a: a.set_session_status("C1", "1.1", "active"), False), + ("api_call", lambda a: a._rename_agent_session("C1", "1.1", "title"), False), ] diff --git a/tests/test_slack_stream_rotation.py b/tests/test_slack_stream_rotation.py index e53b458..f25c9db 100644 --- a/tests/test_slack_stream_rotation.py +++ b/tests/test_slack_stream_rotation.py @@ -167,6 +167,22 @@ async def stream() -> AsyncIterator[str]: assert counts_mid_stream == [1] assert s.chat_stream.await_count == 2 + # TS: "keeps the agent session processing while the reply continues" + # (vercel/chat d4a1f03a, wired with #215) + @pytest.mark.asyncio + async def test_keeps_the_agent_session_processing_while_the_reply_continues(self, tick): + s = _setup(agent_view=True) + + async def stream() -> AsyncIterator[str]: + yield "a\n" + tick(MAX_AGE + 1) + yield "b\n\nc\n" + + await s.adapter.stream(THREAD, stream()) + + assert s.segments[0].stop.await_args.kwargs["session_status"] == "processing" + assert s.segments[1].stop.await_args.kwargs["session_status"] == "active" + @pytest.mark.asyncio async def test_continues_in_a_new_message_when_slack_expired_the_segment_before_rotation(self, tick): s = _setup() @@ -514,6 +530,28 @@ async def stream() -> AsyncIterator[Any]: warnings = [call.args[0] for call in s.logger.warn.call_args_list] assert not any("structured-chunk append failed" in message for message in warnings) + # Upstream index.ts:6508: the expired-final early return still hands the + # agent session back (#215). + @pytest.mark.asyncio + async def test_an_expired_final_segment_still_ends_the_agent_session_with_the_requested_status(self): + s = _setup(agent_view=True) + s.segments[0].stop.side_effect = _ExpiredStreamError() + client = s.adapter._get_client() + client.api_call = AsyncMock(return_value={"ok": True}) + + async def stream() -> AsyncIterator[str]: + yield "first\n" + + result = await s.adapter.stream(THREAD, stream(), StreamOptions(session_status="suspended")) + + assert result is not None + assert result.id == "1234567890.0" + assert s.segments[0].stop.await_args.kwargs["session_status"] == "suspended" + client.api_call.assert_awaited_once_with( + api_method="agents.sessions.setStatus", + json={"channel_id": "D123", "thread_ts": "1234567890.000000", "status": "suspended"}, + ) + @pytest.mark.asyncio async def test_an_expired_final_segment_with_no_recorded_ts_re_raises(self): # Every delta was confirmed but no Slack response carried a ts, so