-
Notifications
You must be signed in to change notification settings - Fork 39
fix(connection): preserve notification response ordering #129
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
hallerite
wants to merge
1
commit into
agentclientprotocol:main
Choose a base branch
from
hallerite:codex/fix-notification-response-ordering
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+212
−9
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,13 +1,13 @@ | ||
| from __future__ import annotations | ||
|
|
||
| import asyncio | ||
| from collections.abc import Callable | ||
| from collections.abc import Awaitable, Callable | ||
| from typing import Any, cast, final | ||
|
|
||
| from .._transport import Transport | ||
| from ..connection import Connection | ||
| from ..interfaces import Agent, Client | ||
| from ..meta import AGENT_METHODS | ||
| from ..meta import AGENT_METHODS, CLIENT_METHODS | ||
| from ..schema import ( | ||
| AcpMcpServer, | ||
| AudioContentBlock, | ||
|
|
@@ -37,6 +37,7 @@ | |
| ResourceContentBlock, | ||
| ResumeSessionRequest, | ||
| ResumeSessionResponse, | ||
| SessionNotification, | ||
| SetSessionConfigOptionBooleanRequest, | ||
| SetSessionConfigOptionResponse, | ||
| SetSessionConfigOptionSelectRequest, | ||
|
|
@@ -52,6 +53,40 @@ | |
| _CLIENT_CONNECTION_ERROR = "ClientSideConnection requires asyncio StreamWriter/StreamReader" | ||
|
|
||
|
|
||
| class _SessionUpdateTracker: | ||
| """Track in-flight session updates relative to each prompt.""" | ||
|
|
||
| def __init__(self) -> None: | ||
| self._latest: dict[str, int] = {} | ||
| self._pending: dict[str, dict[int, asyncio.Future[None]]] = {} | ||
|
|
||
| def checkpoint(self, session_id: str) -> int: | ||
| return self._latest.get(session_id, 0) | ||
|
|
||
| async def handle(self, session_id: str, notification: Awaitable[Any]) -> Any: | ||
| sequence = self._latest.get(session_id, 0) + 1 | ||
| self._latest[session_id] = sequence | ||
| completed: asyncio.Future[None] = asyncio.get_running_loop().create_future() | ||
| pending = self._pending.setdefault(session_id, {}) | ||
| pending[sequence] = completed | ||
| try: | ||
| return await notification | ||
| finally: | ||
| if not completed.done(): | ||
| completed.set_result(None) | ||
| pending.pop(sequence, None) | ||
| if not pending: | ||
| self._pending.pop(session_id, None) | ||
|
|
||
| async def wait(self, session_id: str, after: int) -> None: | ||
| # Snapshot before yielding so updates received after the response are | ||
| # not associated with this prompt. | ||
| pending = self._pending.get(session_id, {}) | ||
| notifications = tuple(completed for sequence, completed in pending.items() if sequence > after) | ||
| if notifications: | ||
| await asyncio.gather(*(asyncio.shield(completed) for completed in notifications)) | ||
|
|
||
|
|
||
| @final | ||
| @compatible_class | ||
| class ClientSideConnection: | ||
|
|
@@ -69,7 +104,17 @@ def __init__( | |
| **connection_kwargs: Any, | ||
| ) -> None: | ||
| client = to_client(self) if callable(to_client) else to_client | ||
| handler = build_client_router(cast(Client, client), use_unstable_protocol=use_unstable_protocol) | ||
| router = build_client_router(cast(Client, client), use_unstable_protocol=use_unstable_protocol) | ||
| self._session_updates = _SessionUpdateTracker() | ||
|
|
||
| async def handler(method: str, params: Any, is_notification: bool) -> Any: | ||
| if is_notification and method == CLIENT_METHODS["session_update"]: | ||
| notification = SessionNotification.model_validate(params) | ||
| return await self._session_updates.handle( | ||
| notification.session_id, router(method, params, is_notification) | ||
| ) | ||
| return await router(method, params, is_notification) | ||
|
|
||
| if isinstance(input_stream, Transport): | ||
| if output_stream is not None: | ||
| raise TypeError(_CLIENT_CONNECTION_ERROR) | ||
|
|
@@ -206,12 +251,21 @@ async def prompt( | |
| ], | ||
| **kwargs: Any, | ||
| ) -> PromptResponse: | ||
| return await request_model( | ||
| self._conn, | ||
| AGENT_METHODS["session_prompt"], | ||
| PromptRequest(prompt=prompt, session_id=session_id, field_meta=kwargs or None), | ||
| PromptResponse, | ||
| ) | ||
| checkpoint = self._session_updates.checkpoint(session_id) | ||
| try: | ||
| response = await request_model( | ||
| self._conn, | ||
| AGENT_METHODS["session_prompt"], | ||
| PromptRequest(prompt=prompt, session_id=session_id, field_meta=kwargs or None), | ||
| PromptResponse, | ||
| ) | ||
| except asyncio.CancelledError: | ||
| raise | ||
|
Comment on lines
+262
to
+263
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Maybe a bit nitpicky, but this except branch can be deleted, because |
||
| except Exception: | ||
| await self._session_updates.wait(session_id, checkpoint) | ||
| raise | ||
| await self._session_updates.wait(session_id, checkpoint) | ||
| return response | ||
|
|
||
| @param_model(ForkSessionRequest) | ||
| async def fork_session( | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Suggested change:
And pass the tracker to the router builder: