feat(update): integrate managed installs and recoverable in-app updates (#6168)
Add owner-aware Stable and Preview updates with explicit consent, verified release plans, protected process handoff and bounded service recovery. Keep configuration and conversations separate from program rollback. Include the compact About controls, Windows long-path support, native package recovery checks and optional macOS Dock lifecycle integration. Preserve documented guidance for installations owned by other managers. This code integration does not publish packages, enable signing or advance the public update channel. Co-authored-by: chengyongru <61816729+chengyongru@users.noreply.github.com>
This commit is contained in:
1 parent
76da55994b
commit
fbb61a373f
216 files changed
+27948
-1084
No files matched your search
@@ -107,6 +107,16 @@ class BaseChannel(ABC):
|
||||
"""
|
||||
pass
|
||||
|
||||
@property
|
||||
def has_pending_delivery(self) -> bool:
|
||||
"""Whether delivery outlives an awaited ``send``/streaming call.
|
||||
|
||||
The manager already accounts for awaited sends and retries. Channels
|
||||
that enqueue their own writes must expose that work here, including
|
||||
transport cleanup, before a gateway can be considered idle.
|
||||
"""
|
||||
return False
|
||||
|
||||
def progress_transport_defaults(self) -> tuple[bool, bool] | None:
|
||||
"""Return channel-owned defaults for progress and tool-hint messages.
|
||||
|
||||
|
||||
@@ -3,10 +3,32 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Mapping
|
||||
from typing import Any, Protocol, runtime_checkable
|
||||
|
||||
QueryParams = Mapping[str, list[str]]
|
||||
|
||||
|
||||
class ChannelConnector(Protocol):
|
||||
"""Channel-owned setup actions called by the settings request owner."""
|
||||
|
||||
async def handle(self, action: str, query: QueryParams) -> dict[str, Any]: ...
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class ManagedChannelConnector(ChannelConnector, Protocol):
|
||||
"""Setup whose detached work can participate in gateway maintenance.
|
||||
|
||||
The synchronous property must stay true through awaited cleanup. ``close``
|
||||
returns only after owned writers have stopped; failure retains ownership.
|
||||
Settings requests account for their own awaited work separately.
|
||||
"""
|
||||
|
||||
@property
|
||||
def has_pending_work(self) -> bool: ...
|
||||
|
||||
async def close(self) -> None: ...
|
||||
|
||||
|
||||
class ChannelConnectError(Exception):
|
||||
"""User-facing channel connection failure."""
|
||||
|
||||
@@ -21,4 +43,6 @@ def query_first(query: QueryParams, key: str) -> str | None:
|
||||
return values[0] if values else None
|
||||
|
||||
|
||||
__all__ = ["ChannelConnectError", "QueryParams", "query_first"]
|
||||
__all__ = [
|
||||
"ChannelConnectError", "ChannelConnector", "ManagedChannelConnector", "QueryParams", "query_first",
|
||||
]
|
||||
@@ -46,6 +46,20 @@ class FeishuConnectStore:
|
||||
self._sessions: dict[str, FeishuConnectSession] = {}
|
||||
self._completion_lock = threading.Lock()
|
||||
|
||||
@property
|
||||
def has_pending_work(self) -> bool:
|
||||
# Registration only advances inside an owned settings request. Expired
|
||||
# QR records have no listener or detached writer to keep alive.
|
||||
now = time.monotonic()
|
||||
return any(session.deadline > now for session in tuple(self._sessions.values()))
|
||||
|
||||
async def close(self) -> None:
|
||||
def clear() -> None:
|
||||
with self._completion_lock:
|
||||
self._sessions.clear()
|
||||
|
||||
await asyncio.to_thread(clear)
|
||||
|
||||
async def handle(self, action: str, query: QueryParams) -> dict[str, Any]:
|
||||
"""Handle one generic settings connection action."""
|
||||
if action == "start":
|
||||
|
||||
@@ -11,8 +11,10 @@ from nanobot.channels.feishu.connect import FeishuConnectStore
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("shutdown", [False, True])
|
||||
async def test_feishu_cancel_wins_over_inflight_confirmation(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
shutdown: bool,
|
||||
) -> None:
|
||||
poll_started = threading.Event()
|
||||
release_poll = threading.Event()
|
||||
@@ -52,15 +54,20 @@ async def test_feishu_cancel_wins_over_inflight_confirmation(
|
||||
|
||||
store = FeishuConnectStore()
|
||||
started = await store.handle("start", {})
|
||||
assert store.has_pending_work is True
|
||||
query = {"session_id": [started["session_id"]]}
|
||||
poll_task = asyncio.create_task(store.handle("poll", query))
|
||||
assert await asyncio.to_thread(poll_started.wait, 5)
|
||||
|
||||
cancelled = await store.handle("cancel", query)
|
||||
if shutdown:
|
||||
await store.close()
|
||||
else:
|
||||
cancelled = await store.handle("cancel", query)
|
||||
assert cancelled["status"] == "cancelled"
|
||||
release_poll.set()
|
||||
completed = await poll_task
|
||||
|
||||
assert cancelled["status"] == "cancelled"
|
||||
assert store.has_pending_work is False
|
||||
assert completed["status"] == "cancelled"
|
||||
assert saved_results == []
|
||||
|
||||
|
||||
@@ -28,9 +28,10 @@ class LinearConnectSession:
|
||||
flow: LinearOAuthFlow
|
||||
config: LinearConfig
|
||||
state: LinearStateStore
|
||||
server: LinearServerLease
|
||||
server: LinearServerLease | None
|
||||
completion_lock: asyncio.Lock = field(default_factory=asyncio.Lock, repr=False)
|
||||
result: dict[str, Any] | None = None
|
||||
expiry_task: asyncio.Task[None] | None = None
|
||||
|
||||
|
||||
class LinearConnectStore:
|
||||
@@ -39,6 +40,16 @@ class LinearConnectStore:
|
||||
def __init__(self) -> None:
|
||||
self._sessions: dict[str, LinearConnectSession] = {}
|
||||
|
||||
@property
|
||||
def has_pending_work(self) -> bool:
|
||||
# A deadline alone does not close the callback/webhook listener. Cached
|
||||
# success, however, is retained only after releasing that listener.
|
||||
return any(session.server is not None for session in self._sessions.values())
|
||||
|
||||
async def close(self) -> None:
|
||||
for session_id in tuple(self._sessions):
|
||||
await self.cancel(session_id)
|
||||
|
||||
async def handle(self, action: str, query: QueryParams) -> dict[str, Any]:
|
||||
await self._cleanup()
|
||||
if action == "start":
|
||||
@@ -103,12 +114,19 @@ class LinearConnectStore:
|
||||
f"Unable to start the Linear callback listener on {config.host}:{config.port}: {exc}",
|
||||
status=502,
|
||||
) from exc
|
||||
self._sessions[flow.session_id] = LinearConnectSession(
|
||||
session = LinearConnectSession(
|
||||
flow=flow,
|
||||
config=config,
|
||||
state=state,
|
||||
server=lease,
|
||||
)
|
||||
self._sessions[flow.session_id] = session
|
||||
session.expiry_task = asyncio.create_task(
|
||||
self._expire_session(session), name=f"linear-connect-expire-{flow.session_id}",
|
||||
)
|
||||
session.expiry_task.add_done_callback(
|
||||
lambda task: task.exception() if not task.cancelled() else None,
|
||||
)
|
||||
return {
|
||||
"session_id": flow.session_id,
|
||||
"status": "pending",
|
||||
@@ -129,6 +147,7 @@ class LinearConnectStore:
|
||||
if self._sessions.get(session_id) is not session:
|
||||
return _terminal(session_id, "cancelled", "Linear authorization cancelled.")
|
||||
if session.result is not None:
|
||||
await self._release_listener(session)
|
||||
return dict(session.result)
|
||||
flow = session.flow
|
||||
if time.monotonic() >= flow.deadline:
|
||||
@@ -169,8 +188,7 @@ class LinearConnectStore:
|
||||
}
|
||||
# A browser may miss the first successful poll while switching tabs.
|
||||
# Retain its result until the session expires, but release the callback listener.
|
||||
OAUTH_FLOWS.remove(flow)
|
||||
await asyncio.to_thread(session.server.close)
|
||||
await self._release_listener(session)
|
||||
return dict(session.result)
|
||||
|
||||
async def cancel(self, session_id: str) -> dict[str, Any]:
|
||||
@@ -291,11 +309,26 @@ class LinearConnectStore:
|
||||
await self.cancel(session_id)
|
||||
|
||||
async def _close_session(self, session_id: str) -> None:
|
||||
session = self._sessions.pop(session_id, None)
|
||||
session = self._sessions.get(session_id)
|
||||
if session is None:
|
||||
return
|
||||
expiry_task = session.expiry_task
|
||||
if expiry_task is not None and expiry_task is not asyncio.current_task():
|
||||
expiry_task.cancel()
|
||||
await asyncio.gather(expiry_task, return_exceptions=True)
|
||||
await self._release_listener(session)
|
||||
self._sessions.pop(session_id, None)
|
||||
|
||||
async def _expire_session(self, session: LinearConnectSession) -> None:
|
||||
await asyncio.sleep(max(0, session.flow.deadline - time.monotonic()))
|
||||
await self.cancel(session.flow.session_id)
|
||||
|
||||
@staticmethod
|
||||
async def _release_listener(session: LinearConnectSession) -> None:
|
||||
OAUTH_FLOWS.remove(session.flow)
|
||||
await asyncio.to_thread(session.server.close)
|
||||
if session.server is not None:
|
||||
await asyncio.to_thread(session.server.close)
|
||||
session.server = None
|
||||
|
||||
|
||||
def _load_linear_config() -> LinearConfig:
|
||||
|
||||
@@ -37,7 +37,8 @@ class LinearWebhookError(ValueError):
|
||||
|
||||
class _ReusableThreadingHTTPServer(ThreadingHTTPServer):
|
||||
allow_reuse_address = True
|
||||
daemon_threads = True
|
||||
# server_close() must join request writers, not only stop accepting sockets.
|
||||
daemon_threads = False
|
||||
|
||||
|
||||
class SharedLinearHttpServer:
|
||||
@@ -65,6 +66,10 @@ class SharedLinearHttpServer:
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
protocol_version = "HTTP/1.1"
|
||||
|
||||
def setup(self) -> None:
|
||||
super().setup()
|
||||
self.connection.settimeout(5)
|
||||
|
||||
def do_GET(self) -> None: # noqa: N802
|
||||
parsed = urlparse(self.path)
|
||||
if parsed.path == owner.config.oauth_callback_path:
|
||||
@@ -99,6 +104,7 @@ class SharedLinearHttpServer:
|
||||
self.send_response(status.value)
|
||||
self.send_header("Content-Type", content_type)
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.send_header("Connection", "close")
|
||||
self.send_header("Cache-Control", "no-store")
|
||||
self.send_header("X-Content-Type-Options", "nosniff")
|
||||
self.end_headers()
|
||||
@@ -124,7 +130,7 @@ class SharedLinearHttpServer:
|
||||
self._server.server_close()
|
||||
self._server = None
|
||||
if self._thread is not None and self._thread.is_alive():
|
||||
self._thread.join(timeout=2)
|
||||
self._thread.join()
|
||||
self._thread = None
|
||||
|
||||
def _handle_oauth_callback(
|
||||
@@ -192,10 +198,11 @@ class LinearServerLease:
|
||||
self._closed = False
|
||||
|
||||
def close(self) -> None:
|
||||
if self._closed:
|
||||
return
|
||||
self._closed = True
|
||||
_release_server(self._server)
|
||||
with _SERVER_GUARD:
|
||||
if self._closed:
|
||||
return
|
||||
_release_server(self._server)
|
||||
self._closed = True
|
||||
|
||||
|
||||
_SERVER_GUARD = threading.RLock()
|
||||
@@ -222,10 +229,10 @@ def _release_server(server: SharedLinearHttpServer) -> None:
|
||||
with _SERVER_GUARD:
|
||||
if _shared_server is not server:
|
||||
return
|
||||
server._references -= 1 # pyright: ignore[reportPrivateUsage]
|
||||
if server._references <= 0: # pyright: ignore[reportPrivateUsage]
|
||||
if server._references == 1: # pyright: ignore[reportPrivateUsage]
|
||||
server.close()
|
||||
_shared_server = None
|
||||
server._references -= 1 # pyright: ignore[reportPrivateUsage]
|
||||
|
||||
|
||||
def _handler_response(
|
||||
@@ -237,6 +244,7 @@ def _handler_response(
|
||||
handler.send_response(status.value)
|
||||
handler.send_header("Content-Type", content_type)
|
||||
handler.send_header("Content-Length", str(len(body)))
|
||||
handler.send_header("Connection", "close")
|
||||
handler.send_header("Cache-Control", "no-store")
|
||||
handler.send_header("X-Content-Type-Options", "nosniff")
|
||||
handler.end_headers()
|
||||
|
||||
@@ -6,6 +6,7 @@ import hmac
|
||||
import http.client
|
||||
import json
|
||||
import socket
|
||||
import threading
|
||||
import time
|
||||
from dataclasses import replace
|
||||
from datetime import datetime, timezone
|
||||
@@ -287,12 +288,14 @@ def test_oauth_callback_does_not_report_cancelled_authorization_as_connected(
|
||||
lease.close()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("concurrent", [False, True])
|
||||
@pytest.mark.parametrize("concurrent, close_fails_once", [(False, False), (True, False), (False, True)])
|
||||
async def test_successful_authorization_survives_repeated_polls(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, concurrent: bool,
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, concurrent: bool, close_fails_once: bool,
|
||||
) -> None:
|
||||
state = LinearStateStore(tmp_path / "linear.sqlite3")
|
||||
lease = Mock(spec=LinearServerLease)
|
||||
if close_fails_once:
|
||||
lease.close.side_effect = [RuntimeError("listener close failed"), None]
|
||||
|
||||
async def exchange_code(_code: str, _verifier: str) -> LinearInstallation:
|
||||
await asyncio.sleep(0)
|
||||
@@ -310,11 +313,16 @@ async def test_successful_authorization_survives_repeated_polls(
|
||||
store = linear_connect.LinearConnectStore()
|
||||
started_at = time.monotonic()
|
||||
started = await store.handle("start", {})
|
||||
assert store.has_pending_work is True
|
||||
session_id = started["session_id"]
|
||||
query = {"session_id": [session_id]}
|
||||
oauth_state = parse_qs(urlparse(started["authorization_url"]).query)["state"][0]
|
||||
try:
|
||||
assert OAUTH_FLOWS.complete(oauth_state, code="authorization-code", error=None)
|
||||
if close_fails_once:
|
||||
with pytest.raises(RuntimeError, match="listener close failed"):
|
||||
await store.handle("poll", query)
|
||||
assert store.has_pending_work is True
|
||||
if concurrent:
|
||||
first, repeated = await asyncio.gather(
|
||||
store.handle("poll", query), store.handle("poll", query),
|
||||
@@ -323,11 +331,12 @@ async def test_successful_authorization_survives_repeated_polls(
|
||||
first = await store.handle("poll", query)
|
||||
repeated = await store.handle("poll", query)
|
||||
assert first["status"] == "succeeded"
|
||||
assert store.has_pending_work is False
|
||||
assert repeated == first
|
||||
assert (await store.handle("poll", query)) == first
|
||||
assert state.has_installations("client-id")
|
||||
client.exchange_code.assert_awaited_once()
|
||||
lease.close.assert_called_once()
|
||||
assert lease.close.call_count == (2 if close_fails_once else 1)
|
||||
assert (await store.handle("poll", {"session_id": ["unknown"]}))["status"] == "expired"
|
||||
|
||||
monkeypatch.setattr(
|
||||
@@ -340,6 +349,73 @@ async def test_successful_authorization_survives_repeated_polls(
|
||||
await store.cancel(session_id)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_connect_shutdown_joins_real_webhook_writer(tmp_path, monkeypatch) -> None:
|
||||
port = _free_port()
|
||||
state = LinearStateStore(tmp_path / "linear.sqlite3")
|
||||
write_entered, allow_write, listener_stopped = threading.Event(), threading.Event(), threading.Event()
|
||||
enqueue = state.enqueue_webhook
|
||||
monkeypatch.setattr(linear_connect, "_load_linear_config", lambda: _config(port))
|
||||
monkeypatch.setattr(linear_connect, "LinearStateStore", lambda: state)
|
||||
|
||||
def enqueue_after_release(delivery, payload):
|
||||
write_entered.set()
|
||||
assert allow_write.wait(3)
|
||||
return enqueue(delivery, payload)
|
||||
|
||||
monkeypatch.setattr(state, "enqueue_webhook", enqueue_after_release)
|
||||
store = linear_connect.LinearConnectStore()
|
||||
started = await store.start()
|
||||
lease = store._sessions[started["session_id"]].server
|
||||
server = lease._server._server
|
||||
shutdown_listener = server.shutdown
|
||||
|
||||
def shutdown_and_signal():
|
||||
shutdown_listener()
|
||||
listener_stopped.set()
|
||||
|
||||
monkeypatch.setattr(server, "shutdown", shutdown_and_signal)
|
||||
request = asyncio.create_task(asyncio.to_thread(_post_webhook, port, _agent_webhook()))
|
||||
closing = None
|
||||
try:
|
||||
assert await asyncio.to_thread(write_entered.wait, 1)
|
||||
closing = asyncio.create_task(store.close())
|
||||
assert await asyncio.to_thread(listener_stopped.wait, 1)
|
||||
assert not closing.done()
|
||||
assert store.has_pending_work is True
|
||||
finally:
|
||||
allow_write.set()
|
||||
response = await request
|
||||
if closing is not None:
|
||||
await closing
|
||||
else:
|
||||
await store.close()
|
||||
assert response[0] == 200
|
||||
assert store.has_pending_work is False
|
||||
assert not store._sessions
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_abandoned_authorization_releases_listener_without_poll(tmp_path, monkeypatch) -> None:
|
||||
state = LinearStateStore(tmp_path / "linear.sqlite3")
|
||||
lease = Mock(spec=LinearServerLease)
|
||||
monkeypatch.setattr(linear_connect, "_load_linear_config", _config)
|
||||
monkeypatch.setattr(linear_connect, "LinearStateStore", lambda: state)
|
||||
monkeypatch.setattr(linear_connect, "acquire_http_server", lambda *_args: lease)
|
||||
monkeypatch.setattr("nanobot.channels.linear.oauth.FLOW_TTL_SECONDS", 0.02)
|
||||
store = linear_connect.LinearConnectStore()
|
||||
started = await store.start()
|
||||
task = store._sessions[started["session_id"]].expiry_task
|
||||
assert task is not None
|
||||
try:
|
||||
await asyncio.wait_for(asyncio.shield(task), timeout=1)
|
||||
assert store.has_pending_work is False
|
||||
assert not store._sessions
|
||||
lease.close.assert_called_once()
|
||||
finally:
|
||||
await store.close()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_connect_store_lists_and_disconnects_workspaces(
|
||||
tmp_path: Path,
|
||||
|
||||
@@ -787,7 +787,7 @@ describe("Linear channel UI", () => {
|
||||
fireEvent.click(await screen.findByRole("menuitem", { name: "Remove workspace" }));
|
||||
const confirm = await screen.findByRole("alertdialog", { name: "Remove nanobot?" });
|
||||
fireEvent.click(within(confirm).getByRole("button", { name: "Remove workspace" }));
|
||||
expect(await screen.findByRole("button", { name: "Connect Linear" })).toBeEnabled();
|
||||
await waitFor(() => expect(screen.getByRole("button", { name: "Connect Linear" })).toBeEnabled());
|
||||
expect(screen.queryByText("Linear authorization cancelled.")).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole("link", { name: "Continue in Linear" })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
+65
-13
@@ -152,8 +152,11 @@ class ChannelManager:
|
||||
self._channel_errors: dict[str, str] = {}
|
||||
self._channel_tasks: dict[str, asyncio.Task[None]] = {}
|
||||
self._dispatch_task: asyncio.Task[None] | None = None
|
||||
self._restart_notice_task: asyncio.Task[None] | None = None
|
||||
self._outbound_tasks: dict[asyncio.Task[None], tuple[str, str]] = {}
|
||||
self._outbound_tails: dict[tuple[str, str], asyncio.Task[None]] = {}
|
||||
self._outbound_pending: list[OutboundMessage] = []
|
||||
self._outbound_dispatching = False
|
||||
self._outbound_slots = asyncio.Semaphore(_OUTBOUND_PENDING_LIMIT)
|
||||
self._outbound_sends = asyncio.Semaphore(_OUTBOUND_CONCURRENCY)
|
||||
self._stopping_channels: set[str] = set()
|
||||
@@ -161,9 +164,12 @@ class ChannelManager:
|
||||
self._origin_reply_fingerprints: OrderedDict[tuple[str, str, str], str] = OrderedDict()
|
||||
self._outbox = DeliveryOutbox(self._config_path.parent / "delivery" / "outbox.sqlite3")
|
||||
self._scheduled_deliveries: set[str] = set()
|
||||
self.bus.outbound_recorder = self._outbox.record
|
||||
self.bus.outbound_recorder = self._record_scheduled
|
||||
|
||||
self._init_channels()
|
||||
self._remove_delivery_check: Callable[[], None] | None = (
|
||||
self.bus.admission.register_pending_work(lambda: self.has_pending_delivery)
|
||||
)
|
||||
|
||||
def _channel_section(
|
||||
self,
|
||||
@@ -404,6 +410,8 @@ class ChannelManager:
|
||||
errors = self._channel_errors = {}
|
||||
errors.pop(name, None)
|
||||
try:
|
||||
if name != "websocket":
|
||||
await self.bus.admission.wait_until_open()
|
||||
await channel.start()
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
@@ -624,6 +632,10 @@ class ChannelManager:
|
||||
|
||||
async def start_all(self) -> None:
|
||||
"""Start all channels and the outbound dispatcher."""
|
||||
if self._remove_delivery_check is None:
|
||||
self._remove_delivery_check = self.bus.admission.register_pending_work(
|
||||
lambda: self.has_pending_delivery,
|
||||
)
|
||||
if not self.channels:
|
||||
logger.warning("No channels enabled")
|
||||
return
|
||||
@@ -647,7 +659,8 @@ class ChannelManager:
|
||||
notice = consume_restart_notice_from_env()
|
||||
if not notice:
|
||||
return None
|
||||
return asyncio.create_task(self._send_restart_notice_when_started(notice))
|
||||
self._restart_notice_task = asyncio.create_task(self._send_restart_notice_when_started(notice))
|
||||
return self._restart_notice_task
|
||||
|
||||
async def _send_restart_notice_when_started(
|
||||
self,
|
||||
@@ -657,6 +670,7 @@ class ChannelManager:
|
||||
poll_s: float = _RESTART_NOTICE_START_POLL_S,
|
||||
) -> None:
|
||||
"""Deliver a restart notice after the target channel starts."""
|
||||
await self.bus.admission.wait_until_open()
|
||||
loop = asyncio.get_running_loop()
|
||||
deadline = loop.time() + timeout_s
|
||||
target = self.channels.get(notice.channel)
|
||||
@@ -703,9 +717,18 @@ class ChannelManager:
|
||||
with suppress(asyncio.CancelledError):
|
||||
await self._dispatch_task
|
||||
|
||||
if self._restart_notice_task:
|
||||
self._restart_notice_task.cancel()
|
||||
with suppress(asyncio.CancelledError):
|
||||
await self._restart_notice_task
|
||||
self._restart_notice_task = None
|
||||
|
||||
# Stop all channels
|
||||
for name in list(self.channels):
|
||||
await self._stop_channel(name)
|
||||
if self._remove_delivery_check is not None:
|
||||
self._remove_delivery_check()
|
||||
self._remove_delivery_check = None
|
||||
|
||||
@staticmethod
|
||||
def _fingerprint_content(content: str) -> str:
|
||||
@@ -745,6 +768,25 @@ class ChannelManager:
|
||||
|
||||
return False
|
||||
|
||||
def _record_scheduled(self, msg: OutboundMessage) -> None:
|
||||
if msg.delivery is not None:
|
||||
with self.bus.admission.activity():
|
||||
self._outbox.record(msg)
|
||||
|
||||
@property
|
||||
def has_pending_delivery(self) -> bool:
|
||||
"""A synchronous idle check, including channel-owned transport queues.
|
||||
|
||||
Read on the gateway event loop immediately before closing admission.
|
||||
This is delivery liveness, not proof that every channel writer stopped.
|
||||
"""
|
||||
return bool(
|
||||
self.bus.outbound_size or self._outbound_pending or self._outbound_dispatching
|
||||
or self._outbound_tasks
|
||||
or (self._restart_notice_task is not None and not self._restart_notice_task.done())
|
||||
or any(channel.has_pending_delivery for channel in self.channels.values())
|
||||
)
|
||||
|
||||
async def _cancel_outbound(self, channel: str | None = None) -> None:
|
||||
tasks = [task for task, key in self._outbound_tasks.items()
|
||||
if channel is None or key[0] == channel]
|
||||
@@ -839,15 +881,17 @@ class ChannelManager:
|
||||
self._outbox.finish(msg, "sent")
|
||||
|
||||
async def _recover_scheduled(self) -> None:
|
||||
for msg in self._outbox.ready():
|
||||
channel = self.channels.get(msg.channel)
|
||||
if channel is None:
|
||||
self._outbox.finish(msg, "failed", "channel_disabled")
|
||||
else:
|
||||
await self._queue_outbound(channel, msg)
|
||||
with self.bus.admission.activity():
|
||||
for msg in self._outbox.ready():
|
||||
channel = self.channels.get(msg.channel)
|
||||
if channel is None:
|
||||
self._outbox.finish(msg, "failed", "channel_disabled")
|
||||
else:
|
||||
await self._queue_outbound(channel, msg)
|
||||
|
||||
async def _dispatch_outbound(self) -> None:
|
||||
try:
|
||||
await self.bus.admission.wait_until_open()
|
||||
await self._dispatch_outbound_loop()
|
||||
finally:
|
||||
await self._cancel_outbound()
|
||||
@@ -858,11 +902,12 @@ class ChannelManager:
|
||||
|
||||
# Buffer for messages that couldn't be processed during delta coalescing
|
||||
# (since asyncio.Queue doesn't support push_front)
|
||||
pending: list[OutboundMessage] = []
|
||||
pending = self._outbound_pending
|
||||
next_recovery = 0.0
|
||||
|
||||
while True:
|
||||
try:
|
||||
await self.bus.admission.wait_until_open()
|
||||
if time.monotonic() >= next_recovery:
|
||||
next_recovery = time.monotonic() + RETRY_SECONDS
|
||||
try:
|
||||
@@ -873,10 +918,15 @@ class ChannelManager:
|
||||
if pending:
|
||||
msg = pending.pop(0)
|
||||
else:
|
||||
msg = await asyncio.wait_for(
|
||||
self.bus.consume_outbound(),
|
||||
timeout=1.0
|
||||
)
|
||||
# wait_for creates a child task: it can remove the last
|
||||
# queued message before this dispatcher records ownership.
|
||||
# Keep dequeue and the busy claim in the same task.
|
||||
async with asyncio.timeout(1.0):
|
||||
msg = await self.bus.consume_outbound()
|
||||
self._outbound_dispatching = True
|
||||
# Intake can close while an empty queue is awaited. Retain the
|
||||
# message, but do not start another transport write while paused.
|
||||
await self.bus.admission.wait_until_open()
|
||||
|
||||
event = msg.event
|
||||
progress_event = event if isinstance(event, ProgressEvent) else None
|
||||
@@ -945,6 +995,8 @@ class ChannelManager:
|
||||
continue
|
||||
except asyncio.CancelledError:
|
||||
break
|
||||
finally:
|
||||
self._outbound_dispatching = False
|
||||
|
||||
@staticmethod
|
||||
async def _send_reasoning_delta(
|
||||
|
||||
@@ -11,6 +11,7 @@ from typing import TYPE_CHECKING, Any, cast
|
||||
|
||||
from packaging.requirements import InvalidRequirement, Requirement
|
||||
|
||||
from nanobot.channels.connect import ChannelConnector
|
||||
from nanobot.channels.contracts import ChannelManagementSpec, ChannelSetupSpec
|
||||
|
||||
if TYPE_CHECKING:
|
||||
@@ -93,7 +94,7 @@ class ChannelPlugin:
|
||||
)
|
||||
return channel_cls
|
||||
|
||||
def load_connector(self) -> Any:
|
||||
def load_connector(self) -> ChannelConnector:
|
||||
"""Construct the optional channel-owned interactive connector."""
|
||||
if self.connector is None:
|
||||
raise ImportError(f"Channel plugin '{self.name}' does not provide a connector")
|
||||
@@ -110,7 +111,9 @@ class ChannelPlugin:
|
||||
f"Channel plugin '{self.name}' connector '{self.connector}' "
|
||||
"does not provide handle()"
|
||||
)
|
||||
return connector
|
||||
# Dynamic plugin edge: handle() is the established connector contract.
|
||||
# Lifecycle support is optional and checked by its maintenance owner.
|
||||
return cast(ChannelConnector, connector)
|
||||
|
||||
|
||||
def _target_parts(target: str, *, label: str) -> tuple[str, str]:
|
||||
|
||||
@@ -93,6 +93,19 @@ class QQConnectStore:
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._sessions: dict[str, QQConnectSession] = {}
|
||||
self._commits: dict[str, asyncio.Task[None]] = {}
|
||||
self._closed = False
|
||||
|
||||
@property
|
||||
def has_pending_work(self) -> bool:
|
||||
now = time.monotonic()
|
||||
return bool(self._commits) or any(session.deadline > now for session in self._sessions.values())
|
||||
|
||||
async def close(self) -> None:
|
||||
self._closed = True
|
||||
self._sessions.clear()
|
||||
if self._commits:
|
||||
await asyncio.shield(asyncio.gather(*self._commits.values(), return_exceptions=True))
|
||||
|
||||
async def handle(self, action: str, query: QueryParams) -> dict[str, Any]:
|
||||
if action == "start":
|
||||
@@ -134,6 +147,10 @@ class QQConnectStore:
|
||||
# A transient portal error is not proof the scan failed; keep waiting.
|
||||
return _pending(session, "Waiting for QQ scan...")
|
||||
|
||||
self._cleanup()
|
||||
if self._sessions.get(session_id) is not session:
|
||||
return _payload(session_id, "expired", "This QQ login has expired. Start again.")
|
||||
|
||||
status = result.get("status")
|
||||
if status == 3:
|
||||
self._sessions.pop(session_id, None)
|
||||
@@ -151,7 +168,13 @@ class QQConnectStore:
|
||||
if not app_id or not secret:
|
||||
return _payload(session_id, "failed", "QQ confirmed the scan but returned no credentials.")
|
||||
|
||||
await asyncio.to_thread(save_credentials, app_id, secret)
|
||||
# Cancelling the awaiting request cannot stop a file-writing thread.
|
||||
# Retain ownership until the writer finishes, including during shutdown.
|
||||
commit = asyncio.create_task(asyncio.to_thread(save_credentials, app_id, secret))
|
||||
self._commits[session_id] = commit
|
||||
commit.add_done_callback(lambda task: self._commits.pop(session_id, None))
|
||||
commit.add_done_callback(lambda task: task.exception() if not task.cancelled() else None)
|
||||
await asyncio.shield(commit)
|
||||
session.credentials = (app_id, secret)
|
||||
return {
|
||||
"session_id": session_id,
|
||||
@@ -161,6 +184,8 @@ class QQConnectStore:
|
||||
|
||||
async def cancel(self, session_id: str) -> dict[str, Any]:
|
||||
self._sessions.pop(session_id, None)
|
||||
if commit := self._commits.get(session_id):
|
||||
await asyncio.shield(asyncio.gather(commit, return_exceptions=True))
|
||||
return _payload(session_id, "cancelled", "QQ login cancelled.")
|
||||
|
||||
async def login(self) -> tuple[str, str] | None:
|
||||
@@ -181,6 +206,8 @@ class QQConnectStore:
|
||||
self._sessions.pop(session.id, None)
|
||||
|
||||
def _new_session(self, task_id: str, key: str) -> QQConnectSession:
|
||||
if self._closed:
|
||||
raise ChannelConnectError("QQ connection store is closed", status=409)
|
||||
session = QQConnectSession(
|
||||
id=secrets.token_urlsafe(18),
|
||||
task_id=task_id,
|
||||
|
||||
@@ -48,9 +48,11 @@ async def test_qq_connect_writes_scanned_credentials_to_config(monkeypatch: pyte
|
||||
started = await store.start()
|
||||
assert started["status"] == "pending"
|
||||
assert started["qr_url"].endswith("task_id=task-1&_wv=2")
|
||||
assert store.has_pending_work
|
||||
|
||||
polled = await store.poll(started["session_id"])
|
||||
assert polled["status"] == "succeeded"
|
||||
assert not store.has_pending_work
|
||||
assert await store.poll(started["session_id"]) == {
|
||||
"session_id": started["session_id"],
|
||||
"status": "expired",
|
||||
@@ -64,6 +66,117 @@ async def test_qq_connect_writes_scanned_credentials_to_config(monkeypatch: pyte
|
||||
assert qq["allowFrom"] == ["42"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("stop", ["cancel", "close", "expire"])
|
||||
async def test_qq_late_portal_result_cannot_save_after_session_ends(
|
||||
monkeypatch: pytest.MonkeyPatch, _isolated_config: Path, stop: str,
|
||||
):
|
||||
key = base64.b64encode(b"k" * 32).decode()
|
||||
polling = asyncio.Event()
|
||||
release = asyncio.Event()
|
||||
|
||||
async def fake_poll(_task_id: str) -> dict[str, Any]:
|
||||
polling.set()
|
||||
await release.wait()
|
||||
return {"status": 2, "bot_appid": "1024", "bot_encrypt_secret": _encrypt("new", key)}
|
||||
|
||||
monkeypatch.setattr(connect, "poll_bind_task", fake_poll)
|
||||
store = QQConnectStore()
|
||||
session = store._new_session("task", key)
|
||||
before = _isolated_config.read_bytes()
|
||||
poll = asyncio.create_task(store.poll(session.id))
|
||||
try:
|
||||
await asyncio.wait_for(polling.wait(), timeout=5)
|
||||
if stop == "cancel":
|
||||
await store.cancel(session.id)
|
||||
elif stop == "close":
|
||||
await store.close()
|
||||
else:
|
||||
session.deadline = 0
|
||||
assert not store.has_pending_work
|
||||
finally:
|
||||
release.set()
|
||||
assert (await poll)["status"] == "expired"
|
||||
assert _isolated_config.read_bytes() == before
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("stop", ["cancel", "close"])
|
||||
async def test_qq_cleanup_waits_for_writer_after_poll_request_is_cancelled(
|
||||
monkeypatch: pytest.MonkeyPatch, _isolated_config: Path, stop: str,
|
||||
):
|
||||
from nanobot.runtime_admission import RuntimeAdmission, RuntimeBusyError
|
||||
|
||||
key = base64.b64encode(b"k" * 32).decode()
|
||||
saving = threading.Event()
|
||||
release = threading.Event()
|
||||
original_save = connect.save_credentials
|
||||
|
||||
async def fake_poll(_task_id: str) -> dict[str, Any]:
|
||||
return {"status": 2, "bot_appid": "1024", "bot_encrypt_secret": _encrypt("new", key)}
|
||||
|
||||
def slow_save(app_id: str, secret: str) -> None:
|
||||
saving.set()
|
||||
if not release.wait(timeout=5):
|
||||
raise TimeoutError("credential writer was not released")
|
||||
original_save(app_id, secret)
|
||||
|
||||
monkeypatch.setattr(connect, "poll_bind_task", fake_poll)
|
||||
monkeypatch.setattr(connect, "save_credentials", slow_save)
|
||||
store = QQConnectStore()
|
||||
admission = RuntimeAdmission()
|
||||
admission.register_pending_work(lambda: store.has_pending_work)
|
||||
session = store._new_session("task", key)
|
||||
poll = asyncio.create_task(store.poll(session.id))
|
||||
cleanup: asyncio.Task[None | dict[str, Any]] | None = None
|
||||
try:
|
||||
assert await asyncio.to_thread(saving.wait, 5)
|
||||
poll.cancel()
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await poll
|
||||
session.deadline = 0
|
||||
cleanup = asyncio.create_task(store.close() if stop == "close" else store.cancel(session.id))
|
||||
await asyncio.sleep(0)
|
||||
assert not cleanup.done()
|
||||
assert store.has_pending_work
|
||||
with pytest.raises(RuntimeBusyError), admission.pause_if_idle(lambda: False):
|
||||
pytest.fail("an active credential writer must block an update")
|
||||
finally:
|
||||
release.set()
|
||||
await asyncio.gather(poll, return_exceptions=True)
|
||||
if cleanup is not None:
|
||||
await cleanup
|
||||
await store.close()
|
||||
assert not store.has_pending_work
|
||||
with admission.pause_if_idle(lambda: False):
|
||||
assert admission.paused
|
||||
saved = json.loads(_isolated_config.read_text(encoding="utf-8"))["channels"]["qq"]
|
||||
assert (saved["appId"], saved["secret"], saved["allowFrom"]) == ("1024", "new", ["42"])
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_qq_close_during_start_does_not_leave_a_new_session(monkeypatch: pytest.MonkeyPatch):
|
||||
creating = asyncio.Event()
|
||||
release = asyncio.Event()
|
||||
|
||||
async def fake_create() -> tuple[str, str]:
|
||||
creating.set()
|
||||
await release.wait()
|
||||
return "late-task", base64.b64encode(b"k" * 32).decode()
|
||||
|
||||
monkeypatch.setattr(connect, "create_bind_task", fake_create)
|
||||
store = QQConnectStore()
|
||||
start = asyncio.create_task(store.start())
|
||||
try:
|
||||
await asyncio.wait_for(creating.wait(), timeout=5)
|
||||
await store.close()
|
||||
finally:
|
||||
release.set()
|
||||
with pytest.raises(connect.ChannelConnectError, match="closed"):
|
||||
await start
|
||||
assert not store.has_pending_work
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_qq_connect_keeps_waiting_on_transient_portal_errors(monkeypatch: pytest.MonkeyPatch):
|
||||
async def fake_create() -> tuple[str, str]:
|
||||
|
||||
@@ -29,6 +29,7 @@ from nanobot.bus.queue import MessageBus
|
||||
from nanobot.channels.base import BaseChannel
|
||||
from nanobot.channels.websocket.binary_http import BinaryHTTPBridge
|
||||
from nanobot.config_base import Base
|
||||
from nanobot.runtime_admission import RuntimeMaintenanceError
|
||||
from nanobot.session.webui_turns import (
|
||||
clear_websocket_turn_if_current,
|
||||
mark_websocket_turn_transcript_persistence_failed,
|
||||
@@ -705,6 +706,15 @@ class WebSocketChannel(BaseChannel):
|
||||
async def handler(connection: ServerConnection) -> None:
|
||||
await self._connection_loop(connection)
|
||||
|
||||
from aiohttp import web
|
||||
|
||||
async def handle_binary(request: web.BaseRequest) -> web.StreamResponse:
|
||||
try:
|
||||
with self.bus.admission.activity():
|
||||
return await self._uploads.handle(request)
|
||||
except RuntimeMaintenanceError:
|
||||
return web.json_response({"error": "Gateway update is being verified"}, status=503)
|
||||
|
||||
async def prune_uploads() -> None:
|
||||
while not stop_event.is_set():
|
||||
self._uploads.store.prune()
|
||||
@@ -720,7 +730,7 @@ class WebSocketChannel(BaseChannel):
|
||||
failures = 0
|
||||
while not stop_event.is_set():
|
||||
server: Server | None = None
|
||||
bridge = BinaryHTTPBridge(self._uploads.handle)
|
||||
bridge = BinaryHTTPBridge(handle_binary)
|
||||
was_serving = False
|
||||
started_at = 0.0
|
||||
try:
|
||||
@@ -969,6 +979,16 @@ class WebSocketChannel(BaseChannel):
|
||||
name=f"websocket-outbound-{id(connection):x}",
|
||||
)
|
||||
|
||||
@property
|
||||
def has_pending_delivery(self) -> bool:
|
||||
# send() only enqueues a frame. buffered_bytes includes the frame that
|
||||
# a writer has removed from its queue but has not finished transmitting.
|
||||
return bool(self._outbound_retire_tasks) or any(
|
||||
state.buffered_bytes or not state.queue.empty()
|
||||
or (state.writer is not None and not state.writer.done())
|
||||
for state in self._connection_outbound.values()
|
||||
)
|
||||
|
||||
async def _drain_connection_outbound(
|
||||
self,
|
||||
connection: ServerConnection,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"""Production listener regressions for HTTP upload + small WS references."""
|
||||
import asyncio
|
||||
import json
|
||||
import threading
|
||||
from pathlib import Path
|
||||
|
||||
import aiohttp
|
||||
@@ -9,6 +10,8 @@ from websockets.asyncio.client import connect
|
||||
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.channels.websocket.runtime import WebSocketChannel, WebSocketConfig
|
||||
from nanobot.config.loader import load_config
|
||||
from nanobot.runtime_admission import RuntimeBusyError
|
||||
from nanobot.session.manager import SessionManager
|
||||
from nanobot.webui.gateway_services import build_gateway_services
|
||||
|
||||
@@ -48,6 +51,134 @@ async def event(ws, name):
|
||||
return payload
|
||||
|
||||
|
||||
@pytest.mark.parametrize("finish", [True, False], ids=["complete", "disconnect"])
|
||||
async def test_streaming_upload_blocks_maintenance_until_written_or_cleaned(gateway, finish):
|
||||
channel, bus, http_url, ws_url = gateway
|
||||
port = int(http_url.rsplit(":", 1)[1])
|
||||
store = channel.gateway.uploads.store
|
||||
async with connect(ws_url) as ws:
|
||||
capability = (await event(ws, "ready"))["upload"]
|
||||
reader, writer = await asyncio.open_connection("127.0.0.1", port)
|
||||
try:
|
||||
writer.write((
|
||||
f"POST {capability['path']} HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\n"
|
||||
f"Authorization: Bearer {capability['token']}\r\n"
|
||||
"Content-Type: image/png\r\nContent-Length: 8\r\n\r\npart"
|
||||
).encode())
|
||||
await writer.drain()
|
||||
async with asyncio.timeout(3):
|
||||
while store._active == 0:
|
||||
await asyncio.sleep(.01)
|
||||
with pytest.raises(RuntimeBusyError):
|
||||
with bus.admission.pause_if_idle(lambda: False):
|
||||
pytest.fail("Maintenance ignored an in-progress binary write")
|
||||
assert not bus.admission.paused
|
||||
if finish:
|
||||
writer.write(b"done")
|
||||
await writer.drain()
|
||||
response = await asyncio.wait_for(reader.read(), timeout=3)
|
||||
assert response.startswith(b"HTTP/1.1 201"), response
|
||||
else:
|
||||
writer.close()
|
||||
await writer.wait_closed()
|
||||
async with asyncio.timeout(3):
|
||||
while store._active:
|
||||
await asyncio.sleep(.01)
|
||||
with bus.admission.pause_if_idle(lambda: False):
|
||||
assert bus.admission.paused
|
||||
if not finish:
|
||||
assert not tuple(store._journal.iterdir())
|
||||
finally:
|
||||
writer.close()
|
||||
await writer.wait_closed()
|
||||
|
||||
|
||||
async def test_threaded_settings_write_stays_busy_after_browser_disconnect(gateway, monkeypatch):
|
||||
channel, bus, _, ws_url = gateway
|
||||
entered, release = threading.Event(), threading.Event()
|
||||
settings = channel.gateway.settings
|
||||
original = settings.config.run_serialized
|
||||
|
||||
def delayed_save(*args, **kwargs):
|
||||
entered.set()
|
||||
assert release.wait(10), "Test did not release the settings writer"
|
||||
return original(*args, **kwargs)
|
||||
|
||||
monkeypatch.setattr(settings.config, "run_serialized", delayed_save)
|
||||
|
||||
def connection_url():
|
||||
token = channel.gateway.tokens.issue_token(300, audience="webui")
|
||||
return ws_url.replace("test-secret", token)
|
||||
|
||||
def request(identifier, value):
|
||||
return json.dumps({"type": "webui_request", "request_id": identifier,
|
||||
"action": "settings.runtime_config.update",
|
||||
"payload": {"values": {"agents.defaults.max_tool_iterations": value}}})
|
||||
|
||||
try:
|
||||
async with connect(connection_url()) as ws:
|
||||
await event(ws, "ready")
|
||||
await ws.send(request("slow-write", 31))
|
||||
assert await asyncio.to_thread(entered.wait, 3)
|
||||
with pytest.raises(RuntimeBusyError):
|
||||
with bus.admission.pause_if_idle(lambda: False):
|
||||
pytest.fail("Maintenance ignored a threaded settings write")
|
||||
# Existing mutation ownership deliberately survives a lost browser;
|
||||
# losing its delivery task must not make the gateway appear idle.
|
||||
with pytest.raises(RuntimeBusyError):
|
||||
with bus.admission.pause_if_idle(lambda: False):
|
||||
pytest.fail("Browser disconnect released an unfinished write")
|
||||
operation = channel._commands.request_operations["slow-write"].task
|
||||
release.set()
|
||||
result = await asyncio.wait_for(asyncio.shield(operation), timeout=5)
|
||||
assert result.status is None, result
|
||||
assert load_config(settings.config.path).agents.defaults.max_tool_iterations == 31
|
||||
async with connect(connection_url()) as ws:
|
||||
await event(ws, "ready")
|
||||
with bus.admission.pause_if_idle(lambda: False):
|
||||
await ws.send(request("blocked-write", 32))
|
||||
rejected = await event(ws, "webui_response")
|
||||
assert rejected["error"]["status"] == 503
|
||||
assert load_config(settings.config.path).agents.defaults.max_tool_iterations == 31
|
||||
await ws.send(request("after-abort", 33))
|
||||
assert (await event(ws, "webui_response"))["ok"] is True
|
||||
assert load_config(settings.config.path).agents.defaults.max_tool_iterations == 33
|
||||
finally:
|
||||
release.set()
|
||||
|
||||
|
||||
async def test_http_route_is_busy_until_its_async_work_finishes(gateway, monkeypatch):
|
||||
channel, bus, http_url, _ = gateway
|
||||
entered, release = asyncio.Event(), asyncio.Event()
|
||||
route = channel.gateway.http._dispatch_resolved
|
||||
|
||||
async def delayed_route(*args, **kwargs):
|
||||
entered.set()
|
||||
await release.wait()
|
||||
return await route(*args, **kwargs)
|
||||
|
||||
monkeypatch.setattr(channel.gateway.http, "_dispatch_resolved", delayed_route)
|
||||
async with aiohttp.ClientSession(headers={"Authorization": "Bearer test-secret"}) as http:
|
||||
request = asyncio.create_task(http.get(http_url + "/webui/bootstrap"))
|
||||
try:
|
||||
await asyncio.wait_for(entered.wait(), timeout=3)
|
||||
with pytest.raises(RuntimeBusyError):
|
||||
with bus.admission.pause_if_idle(lambda: False):
|
||||
pytest.fail("Maintenance ignored a running HTTP handler")
|
||||
release.set()
|
||||
async with await asyncio.wait_for(request, timeout=3) as response:
|
||||
assert response.status == 200
|
||||
await response.read()
|
||||
with bus.admission.pause_if_idle(lambda: False):
|
||||
async with http.get(http_url + "/webui/bootstrap") as response:
|
||||
assert response.status == 503
|
||||
async with http.get(http_url + "/webui/bootstrap") as response:
|
||||
assert response.status == 200
|
||||
finally:
|
||||
release.set()
|
||||
await asyncio.gather(request, return_exceptions=True)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("mime,name", [
|
||||
("image/png", "image.png"), ("text/csv", "report.csv"), ("video/webm", "clip.webm"),
|
||||
])
|
||||
|
||||
@@ -16,6 +16,7 @@ from nanobot.channels.manager import ChannelManager
|
||||
from nanobot.channels.websocket import runtime
|
||||
from nanobot.channels.websocket.runtime import WebSocketChannel, WebSocketConfig
|
||||
from nanobot.config.schema import Config
|
||||
from nanobot.runtime_admission import RuntimeBusyError
|
||||
from nanobot.webui.gateway_services import build_gateway_services
|
||||
|
||||
|
||||
@@ -64,7 +65,7 @@ class _RecordingConnection:
|
||||
|
||||
|
||||
def _channel() -> WebSocketChannel:
|
||||
bus = MagicMock(spec=MessageBus)
|
||||
bus = MessageBus()
|
||||
config = WebSocketConfig(
|
||||
enabled=True,
|
||||
allow_from=["*"],
|
||||
@@ -129,9 +130,24 @@ async def test_message_bus_delivers_to_ten_tuis_with_one_blocked_connection() ->
|
||||
assert await _next_text(connection) == "first"
|
||||
assert await _next_text(connection) == "last"
|
||||
assert connections[0].sent.empty()
|
||||
async with asyncio.timeout(2):
|
||||
while manager._outbound_tasks or bus.outbound_size:
|
||||
await asyncio.sleep(0)
|
||||
# The manager's send has finished; the physical transport still owns
|
||||
# its final frames. A shutdown idle check must include that second queue.
|
||||
assert channel.has_pending_delivery
|
||||
with pytest.raises(RuntimeBusyError):
|
||||
with bus.admission.pause_if_idle(lambda: False):
|
||||
pytest.fail("The blocked WebSocket transport was missed")
|
||||
assert not bus.admission.paused
|
||||
connections[0].release_send.set()
|
||||
assert await _next_text(connections[0]) == "first"
|
||||
assert await _next_text(connections[0]) == "last"
|
||||
async with asyncio.timeout(2):
|
||||
while manager.has_pending_delivery:
|
||||
await asyncio.sleep(0)
|
||||
with bus.admission.pause_if_idle(lambda: False):
|
||||
assert bus.admission.paused
|
||||
finally:
|
||||
dispatcher.cancel()
|
||||
await asyncio.gather(dispatcher, return_exceptions=True)
|
||||
@@ -142,6 +158,26 @@ async def test_message_bus_delivers_to_ten_tuis_with_one_blocked_connection() ->
|
||||
assert not channel._connection_outbound
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_delivery_remains_busy_until_timed_out_transport_is_retired(monkeypatch) -> None:
|
||||
monkeypatch.setattr(runtime, "_OUTBOUND_SEND_TIMEOUT_S", 0.02)
|
||||
channel = _channel()
|
||||
connection = _RecordingConnection(block_first_send=True, block_close=True)
|
||||
channel._attach(cast(Any, connection), "chat-retiring")
|
||||
try:
|
||||
await channel.send(_message("chat-retiring", "reply"))
|
||||
await asyncio.wait_for(connection.closed.wait(), 2)
|
||||
assert connection.send_cancelled.is_set()
|
||||
assert channel.has_pending_delivery
|
||||
connection.release_close.set()
|
||||
await asyncio.wait_for(_wait_for_retire_tasks(channel), 2)
|
||||
assert not channel.has_pending_delivery
|
||||
finally:
|
||||
connection.release_send.set()
|
||||
connection.release_close.set()
|
||||
await channel._cleanup_connection(cast(Any, connection))
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_slow_tui_does_not_block_a_different_topic() -> None:
|
||||
channel = _channel()
|
||||
|
||||
@@ -34,6 +34,15 @@ class WeixinConnectStore:
|
||||
def __init__(self) -> None:
|
||||
self._sessions: dict[str, WeixinConnectSession] = {}
|
||||
|
||||
@property
|
||||
def has_pending_work(self) -> bool:
|
||||
# Poll/commit are awaited by the settings request owner, not detached.
|
||||
return any(session.deadline > time.monotonic() for session in self._sessions.values())
|
||||
|
||||
async def close(self) -> None:
|
||||
for session_id in tuple(self._sessions):
|
||||
await self.cancel(session_id)
|
||||
|
||||
async def handle(self, action: str, query: QueryParams) -> dict[str, Any]:
|
||||
"""Handle one generic settings connection action."""
|
||||
if action == "start":
|
||||
|
||||
@@ -57,10 +57,12 @@ async def test_weixin_connect_store_saves_confirmed_qr_login(
|
||||
started = await store.start()
|
||||
assert started["status"] == "pending"
|
||||
assert started["qr_url"] == "https://qr.example/1"
|
||||
assert store.has_pending_work is True
|
||||
|
||||
completed = await store.poll(started["session_id"])
|
||||
assert completed["status"] == "succeeded"
|
||||
assert completed["account"] == "wx-user"
|
||||
assert store.has_pending_work is False
|
||||
|
||||
saved = json.loads((state_dir / "account.json").read_text())
|
||||
assert saved["token"] == "wx-token"
|
||||
@@ -177,9 +179,11 @@ async def test_weixin_reconnect_keeps_existing_account_until_scan_succeeds(
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("shutdown", [False, True])
|
||||
async def test_weixin_cancel_wins_over_inflight_confirmation(
|
||||
tmp_path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
shutdown: bool,
|
||||
) -> None:
|
||||
state_dir = tmp_path / "weixin-state"
|
||||
config_path = tmp_path / "config.json"
|
||||
@@ -214,15 +218,20 @@ async def test_weixin_cancel_wins_over_inflight_confirmation(
|
||||
|
||||
store = WeixinConnectStore()
|
||||
started = await store.handle("start", {})
|
||||
assert store.has_pending_work is True
|
||||
query = {"session_id": [started["session_id"]]}
|
||||
poll_task = asyncio.create_task(store.handle("poll", query))
|
||||
await asyncio.wait_for(poll_started.wait(), timeout=5)
|
||||
|
||||
cancelled = await store.handle("cancel", query)
|
||||
if shutdown:
|
||||
await store.close()
|
||||
else:
|
||||
cancelled = await store.handle("cancel", query)
|
||||
assert cancelled["status"] == "cancelled"
|
||||
release_poll.set()
|
||||
completed = await poll_task
|
||||
|
||||
assert cancelled["status"] == "cancelled"
|
||||
assert store.has_pending_work is False
|
||||
assert completed["status"] == "cancelled"
|
||||
assert not (state_dir / "account.json").exists()
|
||||
|
||||
|
||||
@@ -799,6 +799,7 @@ async def test_manager_surfaces_actionable_weixin_auth_error_without_traceback(
|
||||
)
|
||||
manager = manager_mod.ChannelManager.__new__(manager_mod.ChannelManager)
|
||||
manager._channel_errors = {}
|
||||
manager.bus = channel.bus
|
||||
|
||||
await manager._start_channel("weixin", channel)
|
||||
|
||||
|
||||
@@ -21,6 +21,7 @@ if TYPE_CHECKING:
|
||||
_NATIVE_STOP_TIMEOUT_SECONDS = 10.0
|
||||
_DATABASE_REPLACE_TIMEOUT_SECONDS = 10.0
|
||||
_FINALIZE_POLL_WAIT_SECONDS = 0.05
|
||||
_CONNECT_TTL_SECONDS = 600
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
@@ -36,6 +37,9 @@ class WhatsAppConnectSession:
|
||||
deadline: float
|
||||
qr_url: str = ""
|
||||
finalize_task: asyncio.Task[None] | None = None
|
||||
stop_task: asyncio.Task[None] | None = None
|
||||
discard_task: asyncio.Task[None] | None = None
|
||||
expiry_task: asyncio.Task[None] | None = None
|
||||
|
||||
|
||||
class WhatsAppConnectStore:
|
||||
@@ -44,6 +48,17 @@ class WhatsAppConnectStore:
|
||||
def __init__(self) -> None:
|
||||
self._sessions: dict[str, WhatsAppConnectSession] = {}
|
||||
|
||||
@property
|
||||
def has_pending_work(self) -> bool:
|
||||
"""Keep login/native workers owned until completion or confirmed cleanup."""
|
||||
return any(
|
||||
session.finalize_task is None
|
||||
or not session.finalize_task.done()
|
||||
or not self._session_stopped(session)
|
||||
or (session.discard_task is not None and not session.discard_task.done())
|
||||
for session in self._sessions.values()
|
||||
)
|
||||
|
||||
async def handle(self, action: str, query: QueryParams) -> dict[str, Any]:
|
||||
if action == "start":
|
||||
force = (query_first(query, "force") or "").strip().lower() in {
|
||||
@@ -99,9 +114,13 @@ class WhatsAppConnectStore:
|
||||
target_path=target_path,
|
||||
pending_path=pending_path,
|
||||
created_wall=now_wall,
|
||||
deadline=time.monotonic() + 600,
|
||||
deadline=time.monotonic() + _CONNECT_TTL_SECONDS,
|
||||
)
|
||||
self._sessions[session_id] = session
|
||||
session.expiry_task = asyncio.create_task(
|
||||
self._expire_session(session), name=f"whatsapp-connect-expire-{session.id}",
|
||||
)
|
||||
session.expiry_task.add_done_callback(self._observe_task)
|
||||
|
||||
qr_wait = asyncio.create_task(self._wait_for_qr(session))
|
||||
try:
|
||||
@@ -113,6 +132,7 @@ class WhatsAppConnectStore:
|
||||
finally:
|
||||
if not qr_wait.done():
|
||||
qr_wait.cancel()
|
||||
await asyncio.gather(qr_wait, return_exceptions=True)
|
||||
return self._pending_payload(session)
|
||||
|
||||
async def poll(self, session_id: str) -> dict[str, Any]:
|
||||
@@ -124,6 +144,9 @@ class WhatsAppConnectStore:
|
||||
"status": "expired",
|
||||
"message": "This WhatsApp login has expired. Start again.",
|
||||
}
|
||||
if session.discard_task is not None:
|
||||
# A concurrent poll must not promote a login being cancelled.
|
||||
return await self.cancel(session_id)
|
||||
if not session.result.done():
|
||||
return self._pending_payload(session)
|
||||
|
||||
@@ -138,21 +161,25 @@ class WhatsAppConnectStore:
|
||||
# Finish fast clients in this request without letting native shutdown
|
||||
# block the polling response path.
|
||||
await asyncio.wait({finalize_task}, timeout=_FINALIZE_POLL_WAIT_SECONDS)
|
||||
if session.discard_task is not None:
|
||||
return await self.cancel(session_id)
|
||||
if not finalize_task.done():
|
||||
payload = self._pending_payload(session)
|
||||
payload["qr_url"] = ""
|
||||
payload["message"] = "Finishing the WhatsApp connection."
|
||||
return payload
|
||||
|
||||
self._sessions.pop(session_id, None)
|
||||
try:
|
||||
finalize_task.result()
|
||||
except Exception as exc:
|
||||
if self._session_stopped(session):
|
||||
self._sessions.pop(session_id, None)
|
||||
return {
|
||||
"session_id": session_id,
|
||||
"status": "failed",
|
||||
"message": f"WhatsApp QR login failed: {exc}",
|
||||
}
|
||||
self._sessions.pop(session_id, None)
|
||||
return {
|
||||
"session_id": session_id,
|
||||
"status": "succeeded",
|
||||
@@ -162,15 +189,21 @@ class WhatsAppConnectStore:
|
||||
async def _finalize_session(self, session: WhatsAppConnectSession) -> None:
|
||||
try:
|
||||
session.result.result()
|
||||
await self._close_session(session)
|
||||
await self._commit_database(session.pending_path, session.target_path)
|
||||
except BaseException:
|
||||
await self._close_session(session)
|
||||
self._remove_database(session.pending_path)
|
||||
raise
|
||||
# A stop timeout is not proof that the native SQLite writer exited.
|
||||
# Preserve its database and ownership for an explicit cleanup retry.
|
||||
await self._close_session(session)
|
||||
try:
|
||||
await self._commit_database(session.pending_path, session.target_path)
|
||||
except BaseException:
|
||||
self._remove_database(session.pending_path)
|
||||
raise
|
||||
|
||||
async def cancel(self, session_id: str) -> dict[str, Any]:
|
||||
session = self._sessions.pop(session_id, None)
|
||||
session = self._sessions.get(session_id)
|
||||
if session is not None:
|
||||
await self._discard_session(session)
|
||||
return {
|
||||
@@ -186,17 +219,30 @@ class WhatsAppConnectStore:
|
||||
if time.monotonic() >= session.deadline
|
||||
]
|
||||
for session_id in expired:
|
||||
session = self._sessions.pop(session_id)
|
||||
await self._discard_session(session)
|
||||
await self.cancel(session_id)
|
||||
|
||||
async def _expire_session(self, session: WhatsAppConnectSession) -> None:
|
||||
await asyncio.sleep(max(0, session.deadline - time.monotonic()))
|
||||
await self.cancel(session.id)
|
||||
|
||||
async def close(self) -> None:
|
||||
"""Stop every login client before the gateway event loop closes."""
|
||||
sessions = tuple(self._sessions.values())
|
||||
self._sessions.clear()
|
||||
for session in sessions:
|
||||
await self._discard_session(session)
|
||||
|
||||
async def _discard_session(self, session: WhatsAppConnectSession) -> None:
|
||||
task = session.discard_task
|
||||
if task is None or task.done():
|
||||
task = asyncio.create_task(
|
||||
self._discard_and_remove(session), name=f"whatsapp-connect-discard-{session.id}",
|
||||
)
|
||||
task.add_done_callback(self._observe_task)
|
||||
session.discard_task = task
|
||||
# Closing a browser/request must not drop the native writer's owner.
|
||||
await asyncio.shield(task)
|
||||
|
||||
async def _discard_and_remove(self, session: WhatsAppConnectSession) -> None:
|
||||
finalize_task = session.finalize_task
|
||||
if (
|
||||
finalize_task is not None
|
||||
@@ -205,9 +251,10 @@ class WhatsAppConnectStore:
|
||||
if not finalize_task.done():
|
||||
finalize_task.cancel()
|
||||
await asyncio.gather(finalize_task, return_exceptions=True)
|
||||
else:
|
||||
await self._close_session(session)
|
||||
await self._close_session(session)
|
||||
self._remove_database(session.pending_path)
|
||||
if self._sessions.get(session.id) is session:
|
||||
del self._sessions[session.id]
|
||||
|
||||
@staticmethod
|
||||
async def _connect(
|
||||
@@ -229,36 +276,55 @@ class WhatsAppConnectStore:
|
||||
while not session.qr_url and not session.result.done():
|
||||
await asyncio.sleep(0.05)
|
||||
|
||||
async def _close_session(self, session: WhatsAppConnectSession) -> None:
|
||||
task = session.stop_task
|
||||
if task is None or (task.done() and not task.cancelled() and task.exception() is not None):
|
||||
task = asyncio.create_task(
|
||||
self._stop_session(session), name=f"whatsapp-connect-stop-{session.id}",
|
||||
)
|
||||
task.add_done_callback(self._observe_task)
|
||||
session.stop_task = task
|
||||
try:
|
||||
await asyncio.wait_for(asyncio.shield(task), timeout=_NATIVE_STOP_TIMEOUT_SECONDS)
|
||||
except TimeoutError as exc:
|
||||
raise RuntimeError(
|
||||
"WhatsApp is still stopping. Retry cancelling the connection before updating."
|
||||
) from exc
|
||||
|
||||
@staticmethod
|
||||
async def _close_session(session: WhatsAppConnectSession) -> None:
|
||||
def _observe_task(task: asyncio.Task[None]) -> None:
|
||||
if not task.cancelled():
|
||||
task.exception()
|
||||
|
||||
@staticmethod
|
||||
def _session_stopped(session: WhatsAppConnectSession) -> bool:
|
||||
task = session.stop_task
|
||||
return task is not None and task.done() and not task.cancelled() and task.exception() is None
|
||||
|
||||
@staticmethod
|
||||
async def _stop_session(session: WhatsAppConnectSession) -> None:
|
||||
if session.expiry_task is not None:
|
||||
session.expiry_task.cancel()
|
||||
await asyncio.gather(session.expiry_task, return_exceptions=True)
|
||||
if not session.result.done():
|
||||
session.result.cancel()
|
||||
if not session.connect_task.done():
|
||||
session.connect_task.cancel()
|
||||
with suppress(Exception, asyncio.CancelledError):
|
||||
await session.connect_task
|
||||
native_task: asyncio.Task[Any] | None = None
|
||||
if session.connect_task.done() and not session.connect_task.cancelled():
|
||||
with suppress(Exception, asyncio.CancelledError):
|
||||
native_task = session.connect_task.result()
|
||||
elif not session.result.cancelled():
|
||||
session.result.exception()
|
||||
# Both Stop and Neonize use asyncio.to_thread in the supported SDK.
|
||||
# Cancellation cannot join those threads. Signal, then await actual return;
|
||||
# the bounded caller may time out without cancelling this owned task.
|
||||
await session.client.stop()
|
||||
await asyncio.shield(asyncio.gather(session.connect_task, return_exceptions=True))
|
||||
if session.connect_task.cancelled():
|
||||
raise RuntimeError("WhatsApp connection shutdown could not be verified")
|
||||
native_task = session.connect_task.result()
|
||||
client_native_task = getattr(session.client, "connect_task", None)
|
||||
if native_task is None and isinstance(client_native_task, asyncio.Task):
|
||||
native_task = cast(asyncio.Task[Any], client_native_task)
|
||||
with suppress(Exception):
|
||||
await asyncio.wait_for(session.client.stop(), timeout=5)
|
||||
if native_task is not None:
|
||||
if not native_task.done():
|
||||
try:
|
||||
# Stop only signals neonize's Go worker. Wait for that worker
|
||||
# to return so Windows releases its SQLite file handle before
|
||||
# the temporary login database is promoted.
|
||||
await asyncio.wait_for(
|
||||
asyncio.shield(native_task),
|
||||
timeout=_NATIVE_STOP_TIMEOUT_SECONDS,
|
||||
)
|
||||
except TimeoutError:
|
||||
native_task.cancel()
|
||||
await asyncio.gather(native_task, return_exceptions=True)
|
||||
await asyncio.shield(asyncio.gather(native_task, return_exceptions=True))
|
||||
if native_task.cancelled():
|
||||
raise RuntimeError("WhatsApp native shutdown could not be verified")
|
||||
|
||||
@staticmethod
|
||||
def _build_channel() -> tuple[WhatsAppChannel, Path]:
|
||||
@@ -327,7 +393,7 @@ class WhatsAppConnectStore:
|
||||
"session_id": session.id,
|
||||
"status": "pending",
|
||||
"interval_ms": 2000,
|
||||
"expires_at_ms": int((session.created_wall + 600) * 1000),
|
||||
"expires_at_ms": int((session.created_wall + _CONNECT_TTL_SECONDS) * 1000),
|
||||
"message": "Waiting for the WhatsApp scan.",
|
||||
}
|
||||
if session.qr_url:
|
||||
|
||||
@@ -2,6 +2,7 @@ from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
import threading
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from typing import Any
|
||||
@@ -41,7 +42,8 @@ class _FakeClient:
|
||||
await self.native_stop.wait()
|
||||
self.native_released = True
|
||||
return
|
||||
await asyncio.Event().wait()
|
||||
await self.native_stop.wait()
|
||||
self.native_released = True
|
||||
|
||||
async def stop(self) -> None:
|
||||
if self.stop_gate is not None:
|
||||
@@ -107,6 +109,7 @@ async def test_whatsapp_connect_commits_new_session_after_scan(
|
||||
assert completed["status"] == "succeeded"
|
||||
assert target.read_bytes() == b"new-session"
|
||||
assert channel.client.stopped is True
|
||||
assert store.has_pending_work is False
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -121,6 +124,7 @@ async def test_whatsapp_connect_cancel_preserves_existing_session(
|
||||
monkeypatch.setattr(store, "_build_channel", lambda: (channel, target))
|
||||
|
||||
started = await store.start(force=True)
|
||||
assert store.has_pending_work is True
|
||||
pending_path = Path(channel.config.database_path)
|
||||
pending_path.write_bytes(b"partial-session")
|
||||
cancelled = await store.cancel(started["session_id"])
|
||||
@@ -129,6 +133,7 @@ async def test_whatsapp_connect_cancel_preserves_existing_session(
|
||||
assert target.read_bytes() == b"working-session"
|
||||
assert not pending_path.exists()
|
||||
assert channel.client.stopped is True
|
||||
assert store.has_pending_work is False
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -147,6 +152,7 @@ async def test_whatsapp_connect_clears_qr_while_finishing_login(
|
||||
|
||||
assert finishing["status"] == "pending"
|
||||
assert finishing["qr_url"] == ""
|
||||
assert store.has_pending_work is True
|
||||
|
||||
stop_gate.set()
|
||||
await asyncio.sleep(0)
|
||||
@@ -224,3 +230,132 @@ async def test_whatsapp_connect_store_closes_pending_login(
|
||||
assert started["status"] == "pending"
|
||||
assert not pending_path.exists()
|
||||
assert channel.client.stopped is True
|
||||
assert store.has_pending_work is False
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("action", ["cancel", "finalize"])
|
||||
async def test_native_thread_timeout_keeps_database_and_can_retry_cleanup(
|
||||
monkeypatch: pytest.MonkeyPatch, tmp_path: Path, action: str,
|
||||
) -> None:
|
||||
"""A cancelled asyncio wrapper cannot prove a native SQLite writer stopped."""
|
||||
target = tmp_path / "neonize.db"
|
||||
target.write_bytes(b"working-session")
|
||||
native_entered, native_release, native_exited = (
|
||||
threading.Event(), threading.Event(), threading.Event(),
|
||||
)
|
||||
channel = _FakeChannel(complete=action == "finalize", linger_until_stopped=True)
|
||||
store = WhatsAppConnectStore()
|
||||
monkeypatch.setattr(store, "_build_channel", lambda: (channel, target))
|
||||
monkeypatch.setattr("nanobot.channels.whatsapp.connect._NATIVE_STOP_TIMEOUT_SECONDS", 0.03)
|
||||
|
||||
def native_writer() -> None:
|
||||
native_entered.set()
|
||||
assert native_release.wait(3)
|
||||
native_exited.set()
|
||||
|
||||
async def connect() -> None:
|
||||
await channel.client.qr_handler(b"whatsapp-qr-payload")
|
||||
Path(channel.config.database_path).write_bytes(b"new-session")
|
||||
if channel.client.complete:
|
||||
channel.client.result.set_result(None)
|
||||
await asyncio.to_thread(native_writer)
|
||||
|
||||
monkeypatch.setattr(channel.client, "connect", connect)
|
||||
started = await store.start(force=True)
|
||||
pending = Path(channel.config.database_path)
|
||||
try:
|
||||
assert await asyncio.to_thread(native_entered.wait, 1)
|
||||
if action == "cancel":
|
||||
with pytest.raises(RuntimeError, match="still stopping"):
|
||||
await store.cancel(started["session_id"])
|
||||
else:
|
||||
result = await store.poll(started["session_id"])
|
||||
assert result["status"] == "failed"
|
||||
assert "still stopping" in result["message"]
|
||||
assert store.has_pending_work is True
|
||||
assert channel.client.connect_task is not None
|
||||
assert not channel.client.connect_task.done()
|
||||
assert not native_exited.is_set()
|
||||
assert pending.read_bytes() == b"new-session"
|
||||
assert target.read_bytes() == b"working-session"
|
||||
finally:
|
||||
native_release.set()
|
||||
await store.cancel(started["session_id"])
|
||||
assert native_exited.is_set()
|
||||
assert store.has_pending_work is False
|
||||
assert not pending.exists()
|
||||
assert target.read_bytes() == b"working-session"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_cancelling_cleanup_waiter_keeps_owned_shutdown(
|
||||
monkeypatch: pytest.MonkeyPatch, tmp_path: Path,
|
||||
) -> None:
|
||||
target = tmp_path / "neonize.db"
|
||||
stop_gate = asyncio.Event()
|
||||
channel = _FakeChannel(complete=False, stop_gate=stop_gate)
|
||||
store = WhatsAppConnectStore()
|
||||
monkeypatch.setattr(store, "_build_channel", lambda: (channel, target))
|
||||
started = await store.start(force=True)
|
||||
pending = Path(channel.config.database_path)
|
||||
pending.write_bytes(b"partial-session")
|
||||
waiter = asyncio.create_task(store.cancel(started["session_id"]))
|
||||
await asyncio.sleep(0)
|
||||
waiter.cancel()
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await waiter
|
||||
assert store.has_pending_work is True
|
||||
assert pending.exists()
|
||||
stop_gate.set()
|
||||
await store.close()
|
||||
assert store.has_pending_work is False
|
||||
assert channel.client.native_released is True
|
||||
assert not pending.exists()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_abandoned_login_expires_without_another_browser_poll(
|
||||
monkeypatch: pytest.MonkeyPatch, tmp_path: Path,
|
||||
) -> None:
|
||||
target = tmp_path / "neonize.db"
|
||||
channel = _FakeChannel(complete=False)
|
||||
store = WhatsAppConnectStore()
|
||||
monkeypatch.setattr(store, "_build_channel", lambda: (channel, target))
|
||||
monkeypatch.setattr("nanobot.channels.whatsapp.connect._CONNECT_TTL_SECONDS", 0.02)
|
||||
started = await store.start(force=True)
|
||||
session = store._sessions[started["session_id"]]
|
||||
try:
|
||||
await asyncio.wait_for(channel.client.native_stop.wait(), timeout=1)
|
||||
assert session.discard_task is not None
|
||||
await asyncio.wait_for(asyncio.shield(session.discard_task), timeout=1)
|
||||
assert store.has_pending_work is False
|
||||
assert channel.client.native_released is True
|
||||
finally:
|
||||
await store.close()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_cancel_during_finalize_does_not_promote_login_database(
|
||||
monkeypatch: pytest.MonkeyPatch, tmp_path: Path,
|
||||
) -> None:
|
||||
target = tmp_path / "neonize.db"
|
||||
target.write_bytes(b"working-session")
|
||||
stop_gate = asyncio.Event()
|
||||
channel = _FakeChannel(complete=True, stop_gate=stop_gate)
|
||||
store = WhatsAppConnectStore()
|
||||
monkeypatch.setattr(store, "_build_channel", lambda: (channel, target))
|
||||
started = await store.start(force=True)
|
||||
assert (await store.poll(started["session_id"]))["status"] == "pending"
|
||||
cancelling = asyncio.create_task(store.cancel(started["session_id"]))
|
||||
await asyncio.sleep(0)
|
||||
polling = asyncio.create_task(store.poll(started["session_id"]))
|
||||
try:
|
||||
assert store.has_pending_work is True
|
||||
finally:
|
||||
stop_gate.set()
|
||||
cancelled, polled = await asyncio.gather(cancelling, polling)
|
||||
assert cancelled["status"] == polled["status"] == "cancelled"
|
||||
assert target.read_bytes() == b"working-session"
|
||||
assert not Path(channel.config.database_path).exists()
|
||||
assert store.has_pending_work is False
|
||||
Reference in new issue
Block a user