Skip to content

Use Claude Code, Codex, VSCode, Pi, and OpenCode (and 6 other harnesses) for free (1.3B+ free tokens) from your terminal, app, IDE, or phone, and now from the browser with native browser sessions (multi-harness + multi-model) like OpenClaw (voice supported + ToS friendly)

Python

Make Telegram startup notices clearable (#1066)

Ali Khokharef76bddd58d1
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md
index 0152bbc3..7139f519 100644
--- a/ARCHITECTURE.md
+++ b/ARCHITECTURE.md
@@ -863,10 +863,11 @@ The API sees only the application-owned `TaskController` used to preserve
The platform factory returns a `MessagingPlatformComponents` bundle from
[messaging/platforms/ports.py](src/free_claude_code/messaging/platforms/ports.py): a
-`MessagingRuntime` with separate `quiesce()` and `close()` phases, an `OutboundMessenger`
-for queued sends/edits/deletes, and an optional `VoiceCancellation` port for
-scoped and bulk voice cancellation during `/stop` and `/clear`. Workflow code
-depends on these ports, not on Telegram or Discord SDK objects.
+`MessagingRuntime` with separate `quiesce()` and `close()` phases, an
+`OutboundMessenger` for queued sends/edits/deletes, an optional
+`VoiceCancellation` port for scoped and bulk voice cancellation during `/stop`
+and `/clear`, and an optional immutable startup-notice intent. Workflow code
+depends on these ports and values, not on Telegram or Discord SDK objects.
Runtime adapters in
[messaging/platforms/telegram.py](src/free_claude_code/messaging/platforms/telegram.py) and
@@ -955,6 +956,19 @@ statuses after outbound delivery starts. Diagnostic detail policy is captured
at construction and passed into the processor; messaging does not read global
settings while executing callbacks or failures.
+Clearable lifecycle notices are workflow-owned rather than SDK-runtime side
+effects. After transport readiness and restored-status repair,
+`ApplicationRuntime` hands the platform's semantic startup-notice intent to the
+workflow. The workflow owns platform rendering and snapshots a dedicated clear
+generation before sending outside its state lock. Once delivery returns a
+message ID, a cancellation-safe finalizer briefly reacquires the lock: it records
+the ID only if no global clear or startup cancellation crossed the reservation;
+otherwise it releases the lock and deletes the notice. Failed compensation
+attempts to restore the ID to the current message log so a later `/clear` can
+retry. No platform I/O runs under the workflow lock. Ordinary notice-send
+failure is privacy-safe and nonfatal, while cancellation before a delivery
+receipt remains immediate and cannot create a phantom message ID.
+
[messaging/turn_intake.py](src/free_claude_code/messaging/turn_intake.py) owns inbound message
recording, slash command dispatch, status-echo filtering, initial status
messages, and rendering detached frozen admission/queue effects. It asks the workflow
@@ -1071,9 +1085,15 @@ message IDs recorded after the early wipe. Once clear commits, ordinary failures
from final persistence, cancellation effects, and CLI cleanup are all attempted
and preserved rather than producing a false successful clear.
Per-chat message ID tracking for `/clear` lives in
-[messaging/session/message_log.py](src/free_claude_code/messaging/session/message_log.py). `/clear`
-guarantees FCC state cleanup and tries tracked platform deletes through the
-list-based outbound delete port, but Discord/Telegram can still reject
+[messaging/session/message_log.py](src/free_claude_code/messaging/session/message_log.py). Startup
+notices use the same bounded log as other clearable output. An incoming
+standalone `/clear` defers log insertion because the command handler owns its ID
+on success; this prevents the command from evicting an older deletion target at
+the cap. Failed or cancelled clear attempts record the command before propagating
+so it remains discoverable by a later clear.
+
+`/clear` guarantees FCC state cleanup and tries tracked platform deletes through
+the list-based outbound delete port, but Discord/Telegram can still reject
individual message deletions for platform reasons such as permissions, age, or
missing messages.
diff --git a/README.md b/README.md
index 23535f96..01d98b59 100644
--- a/README.md
+++ b/README.md
@@ -310,8 +310,9 @@ Configure integrations from **Admin UI → Messaging**, then click **Validate**
</details>
Bot commands: standalone `/stop` cancels all work, standalone `/clear` resets all
-sessions, and `/stats` shows session state. Reply with `/stop` to cancel only
-that request while other queued requests continue. Reply with `/clear` to
+sessions and removes tracked bot messages in that chat—including Telegram's
+online notice—and `/stats` shows session state. Reply with `/stop` to cancel
+only that request while other queued requests continue. Reply with `/clear` to
remove that conversation branch. A successful stop updates the affected task
status instead of posting a second confirmation message. A no-op, or a global
stop whose affected statuses are in another chat, still replies explicitly.
diff --git a/pyproject.toml b/pyproject.toml
index 0638c5c9..f31819ae 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
[project]
name = "free-claude-code"
-version = "3.5.9"
+version = "3.5.10"
description = "Middleware between Claude Code CLI (Anthropic API) and NVIDIA NIM"
readme = "README.md"
requires-python = ">=3.14.0"
diff --git a/smoke/capabilities.py b/smoke/capabilities.py
index 34e0e76c..c74c54a1 100644
--- a/smoke/capabilities.py
+++ b/smoke/capabilities.py
@@ -385,6 +385,7 @@ CAPABILITY_CONTRACTS: tuple[CapabilityContract, ...] = (
),
(
"test_messaging_commands_stop_clear_stats_e2e",
+ "test_messaging_startup_notice_is_clearable_e2e",
"test_messaging_active_stop_uses_status_only_e2e",
"test_messaging_queued_scoped_cancel_e2e",
),
diff --git a/smoke/features.py b/smoke/features.py
index 10f32fbf..4517988e 100644
--- a/smoke/features.py
+++ b/smoke/features.py
@@ -451,6 +451,7 @@ FEATURE_INVENTORY: tuple[FeatureCoverage, ...] = (
(),
(
"test_messaging_commands_stop_clear_stats_e2e",
+ "test_messaging_startup_notice_is_clearable_e2e",
"test_messaging_active_stop_uses_status_only_e2e",
"test_messaging_queued_scoped_cancel_e2e",
),
diff --git a/smoke/product/test_messaging_product_live.py b/smoke/product/test_messaging_product_live.py
index 3553a30b..50e375b2 100644
--- a/smoke/product/test_messaging_product_live.py
+++ b/smoke/product/test_messaging_product_live.py
@@ -3,6 +3,8 @@ import json
import pytest
+from free_claude_code.messaging.models import MessageScope
+from free_claude_code.messaging.platforms.ports import MessagingStartupNotice
from free_claude_code.messaging.trees import MessageState, TreeIdentity
from smoke.lib.e2e import FakeCLISession, FakePlatformDriver, default_cli_events
@@ -80,6 +82,48 @@ async def test_messaging_commands_stop_clear_stats_e2e(
assert driver.session_store.load_conversation_snapshot().trees == {}
+async def test_messaging_startup_notice_is_clearable_e2e(tmp_path) -> None:
+ first_driver = FakePlatformDriver("telegram", tmp_path)
+ scope = MessageScope(platform="telegram", chat_id="chat_1")
+
+ await first_driver.workflow.publish_startup_notice(
+ MessagingStartupNotice(
+ chat_id=scope.chat_id,
+ transport_label="Bot API",
+ )
+ )
+ first_startup_id = first_driver.platform.sent[-1]["message_id"]
+ first_driver.session_store.flush_pending_save()
+
+ driver = FakePlatformDriver("telegram", tmp_path)
+ await driver.platform.send_message("untracked", "advance fake message ID")
+ await driver.workflow.publish_startup_notice(
+ MessagingStartupNotice(
+ chat_id=scope.chat_id,
+ transport_label="Bot API",
+ )
+ )
+ second_startup = driver.platform.sent[-1]
+ second_startup_id = second_startup["message_id"]
+ assert second_startup["text"] == (
+ "🚀 *Claude Code Proxy is online\\!* \\(Bot API\\)"
+ )
+ assert second_startup["parse_mode"] == "MarkdownV2"
+ assert driver.session_store.get_message_ids_for_chat(
+ scope.platform, scope.chat_id
+ ) == [first_startup_id, second_startup_id]
+
+ await driver.send("/clear", message_id="clear_startup")
+
+ deleted = {entry["message_id"] for entry in driver.platform.deletes}
+ assert {first_startup_id, second_startup_id, "clear_startup"} <= deleted
+ assert (
+ driver.session_store.get_message_ids_for_chat(scope.platform, scope.chat_id)
+ == []
+ )
+
+
@pytest.mark.asyncio
@pytest.mark.parametrize("platform_name", ["discord", "telegram"])
async def test_messaging_active_stop_uses_status_only_e2e(
diff --git a/src/free_claude_code/messaging/command_context.py b/src/free_claude_code/messaging/command_context.py
index 1a179617..1d14b890 100644
--- a/src/free_claude_code/messaging/command_context.py
+++ b/src/free_claude_code/messaging/command_context.py
@@ -91,8 +91,8 @@ class MessagingCommandContext(Protocol):
chat_id: str,
msg_id: str | None,
kind: str,
- ) -> None:
- """Persist an outgoing platform message ID."""
+ ) -> bool:
+ """Record an outgoing platform message ID and report clear-log ownership."""
...
diff --git a/src/free_claude_code/messaging/platforms/__init__.py b/src/free_claude_code/messaging/platforms/__init__.py
index 5ada4995..f7f302fb 100644
--- a/src/free_claude_code/messaging/platforms/__init__.py
+++ b/src/free_claude_code/messaging/platforms/__init__.py
@@ -4,6 +4,7 @@ from .factory import MessagingPlatformOptions, create_messaging_components
from .ports import (
MessagingPlatformComponents,
MessagingRuntime,
+ MessagingStartupNotice,
OutboundMessenger,
VoiceCancellation,
)
@@ -12,6 +13,7 @@ __all__ = [
"MessagingPlatformComponents",
"MessagingPlatformOptions",
"MessagingRuntime",
+ "MessagingStartupNotice",
"OutboundMessenger",
"VoiceCancellation",
"create_messaging_components",
diff --git a/src/free_claude_code/messaging/platforms/factory.py b/src/free_claude_code/messaging/platforms/factory.py
index 1e3d5ba4..0b678bb6 100644
--- a/src/free_claude_code/messaging/platforms/factory.py
+++ b/src/free_claude_code/messaging/platforms/factory.py
@@ -6,7 +6,7 @@ from loguru import logger
from ..limiter import MessagingRateLimiter
from ..voice import Transcriber
-from .ports import MessagingPlatformComponents
+from .ports import MessagingPlatformComponents, MessagingStartupNotice
@dataclass(frozen=True, slots=True)
@@ -58,11 +58,20 @@ def create_messaging_components(
log_raw_messaging_content=opts.log_raw_messaging_content,
log_api_error_tracebacks=opts.log_api_error_tracebacks,
)
+ startup_notice = (
+ MessagingStartupNotice(
+ chat_id=opts.allowed_telegram_user_id,
+ transport_label="Bot API",
+ )
+ if opts.allowed_telegram_user_id
+ else None
+ )
return MessagingPlatformComponents(
name=runtime.name,
runtime=runtime,
outbound=runtime.outbound,
voice_cancellation=runtime,
+ startup_notice=startup_notice,
)
if platform_type == "discord":
diff --git a/src/free_claude_code/messaging/platforms/ports.py b/src/free_claude_code/messaging/platforms/ports.py
index fe398d69..318b01a3 100644
--- a/src/free_claude_code/messaging/platforms/ports.py
+++ b/src/free_claude_code/messaging/platforms/ports.py
@@ -62,6 +62,14 @@ class OutboundMessenger(Protocol):
def fire_and_forget(self, task: Awaitable[Any]) -> None: ...
+@dataclass(frozen=True, slots=True)
+class MessagingStartupNotice:
+ """One clearable customer notice declared by a platform composition."""
+
+ chat_id: str
+ transport_label: str
+
+
@runtime_checkable
class VoiceCancellation(Protocol):
"""Optional voice-note cancellation boundary used by stop/clear flows."""
@@ -83,3 +91,4 @@ class MessagingPlatformComponents:
runtime: MessagingRuntime
outbound: OutboundMessenger
voice_cancellation: VoiceCancellation | None = None
+ startup_notice: MessagingStartupNotice | None = None
diff --git a/src/free_claude_code/messaging/platforms/telegram.py b/src/free_claude_code/messaging/platforms/telegram.py
index 083a6078..900f2e0f 100644
--- a/src/free_claude_code/messaging/platforms/telegram.py
+++ b/src/free_claude_code/messaging/platforms/telegram.py
@@ -150,23 +150,6 @@ class TelegramRuntime:
)
self._connected = True
- try:
- target = self.allowed_user_id
- if target:
- startup_text = (
- f"🚀 *{escape_md_v2('Claude Code Proxy is online!')}* "
- f"{escape_md_v2('(Bot API)')}"
- )
- await self.outbound.send_message(target, startup_text)
- except Exception as e:
- if self._log_api_error_tracebacks:
- logger.warning("Could not send startup message: {}", e)
- else:
- logger.warning(
- "Could not send startup message: exc_type={}",
- type(e).__name__,
- )
-
logger.info("Telegram platform started (Bot API)")
async def _retry_connection_step(
diff --git a/src/free_claude_code/messaging/turn_intake.py b/src/free_claude_code/messaging/turn_intake.py
index fd5c35a0..571f2ad3 100644
--- a/src/free_claude_code/messaging/turn_intake.py
+++ b/src/free_claude_code/messaging/turn_intake.py
@@ -37,7 +37,7 @@ class MessagingTurnIntake:
],
format_status: Callable[[str, str, str | None], str],
get_parse_mode: Callable[[], str | None],
- record_outgoing_message: Callable[[str, str, str | None, str], None],
+ record_outgoing_message: Callable[[str, str, str | None, str], bool],
log_messaging_error_details: bool = False,
) -> None:
self.platform_name = platform_name
@@ -51,6 +51,30 @@ class MessagingTurnIntake:
self._record_outgoing_message = record_outgoing_message
self._log_messaging_error_details = log_messaging_error_details
+ def _record_incoming_message(
+ self,
+ incoming: IncomingMessage,
+ command_base: str,
+ ) -> None:
+ if incoming.message_id is None:
+ return
+ try:
+ self.session_store.record_message_id(
+ incoming.platform,
+ incoming.chat_id,
+ str(incoming.message_id),
+ direction="in",
+ kind=message_kind_for_command(command_base),
+ )
+ except Exception as exc:
+ logger.debug(
+ "Failed to record incoming message_id: {}",
+ format_exception_for_log(
+ exc,
+ log_full_message=self._log_messaging_error_details,
+ ),
+ )
+
async def handle_message(
self,
incoming: IncomingMessage,
@@ -62,25 +86,20 @@ class MessagingTurnIntake:
"""
cmd_base = parse_command_base(incoming.text)
- try:
- if incoming.message_id is not None:
- self.session_store.record_message_id(
- incoming.platform,
- incoming.chat_id,
- str(incoming.message_id),
- direction="in",
- kind=message_kind_for_command(cmd_base),
- )
- except Exception as e:
- logger.debug(
- "Failed to record incoming message_id: {}",
- format_exception_for_log(
- e, log_full_message=self._log_messaging_error_details
- ),
- )
+ # Standalone clear owns and deletes its command ID. Defer recording so the
+ # command cannot evict an older deletion target from a bounded log; if the
+ # clear fails or is cancelled, retain the command for a later clear.
+ is_global_clear = cmd_base == "/clear" and not incoming.is_reply()
+ if not is_global_clear:
+ self._record_incoming_message(incoming, cmd_base)
- if await dispatch_command(self._command_context, incoming, cmd_base):
- return
+ try:
+ if await dispatch_command(self._command_context, incoming, cmd_base):
+ return
+ except BaseException:
+ if is_global_clear:
+ self._record_incoming_message(incoming, cmd_base)
+ raise
text = incoming.text or ""
if any(text.startswith(p) for p in STATUS_MESSAGE_PREFIXES):
diff --git a/src/free_claude_code/messaging/workflow.py b/src/free_claude_code/messaging/workflow.py
index 9d329762..aa461a67 100644
--- a/src/free_claude_code/messaging/workflow.py
+++ b/src/free_claude_code/messaging/workflow.py
@@ -12,7 +12,11 @@ from .command_context import ReplyClearResult, StopOutcome
from .managed_protocols import ManagedClaudeSessionManagerProtocol
from .models import IncomingMessage, MessageScope
from .node_runner import MessagingNodeRunner
-from .platforms.ports import OutboundMessenger, VoiceCancellation
+from .platforms.ports import (
+ MessagingStartupNotice,
+ OutboundMessenger,
+ VoiceCancellation,
+)
from .rendering.profiles import build_rendering_profile
from .safe_diagnostics import format_exception_for_log
from .session import SessionStore
@@ -105,6 +109,7 @@ class MessagingWorkflow:
self._rendering_profile = build_rendering_profile(self.platform_name)
self._state_lock = asyncio.Lock()
self._admission_epoch = 0
+ self._clear_generation = 0
self._pending_restored_status_targets: tuple[NodeUiTarget, ...] = ()
self._tree_queue: TreeQueueManager
@@ -210,6 +215,109 @@ class MessagingWorkflow:
type(exc).__name__,
)
+ async def publish_startup_notice(self, notice: MessagingStartupNotice) -> None:
+ """Publish one notice, then transfer its receipt to clear ownership."""
+ async with self._state_lock:
+ clear_generation = self._clear_generation
+
+ try:
+ message_id = await self.outbound.queue_send_message(
+ notice.chat_id,
+ self.format_status(
+ "🚀",
+ "Claude Code Proxy is online!",
+ f"({notice.transport_label})",
+ ),
+ parse_mode=self._parse_mode(),
+ fire_and_forget=False,
+ )
+ except Exception as exc:
+ logger.warning(
+ "Could not publish messaging startup notice: {}",
+ format_exception_for_log(
+ exc,
+ log_full_message=self._log_messaging_error_details,
+ ),
+ )
+ return
+
+ if not message_id:
+ return
+
+ publisher_task = asyncio.current_task()
+ await _finish_owned_operation(
+ self._finalize_startup_notice(
+ notice,
+ message_id,
+ clear_generation,
+ publisher_task,
+ ),
+ name="messaging-finalize-startup-notice",
+ )
+
+ async def _finalize_startup_notice(
+ self,
+ notice: MessagingStartupNotice,
+ message_id: str,
+ clear_generation: int,
+ publisher_task: asyncio.Task[Any] | None,
+ ) -> None:
+ """Commit one delivery receipt or compensate it outside the state lock."""
+ async with self._state_lock:
+ must_discard = (
+ publisher_task is not None and publisher_task.cancelling() > 0
+ ) or clear_generation != self._clear_generation
+ if not must_discard:
+ must_discard = not self.record_outgoing_message(
+ self.platform_name,
+ notice.chat_id,
+ message_id,
+ "startup",
+ )
+
+ if must_discard:
+ await self._discard_startup_notice(notice.chat_id, message_id)
+
+ async def _discard_startup_notice(
+ self,
+ chat_id: str,
+ message_id: str,
+ ) -> None:
+ """Delete an uncommitted notice or retain its ID for a later clear."""
+ try:
+ await self.outbound.queue_delete_messages(
+ chat_id,
+ [message_id],
+ fire_and_forget=False,
+ )
+ except Exception as exc:
+ logger.warning(
+ "Could not discard messaging startup notice: {}",
+ format_exception_for_log(
+ exc,
+ log_full_message=self._log_messaging_error_details,
+ ),
+ )
+ async with self._state_lock:
+ tracked = self.record_outgoing_message(
+ self.platform_name,
+ chat_id,
+ message_id,
+ "startup",
+ )
+ if not tracked:
+ logger.warning(
+ "Messaging startup notice could neither be deleted nor tracked"
+ )
+ return
+
+ async with self._state_lock:
+ self.forget_message_ids(
+ self.platform_name,
+ chat_id,
+ {message_id},
+ )
+
async def close(self) -> None:
"""Finish every owned task and durable write before releasing delivery."""
await self.stop_all_tasks()
@@ -428,6 +536,7 @@ class MessagingWorkflow:
# the epoch advances, the following synchronous wipe and the
# manager's cancellation-safe detach complete as one-way work.
self._admission_epoch += 1
+ self._clear_generation += 1
try:
self.session_store.clear_all()
except Exception as exc:
@@ -517,10 +626,10 @@ class MessagingWorkflow:
chat_id: str,
msg_id: str | None,
kind: str,
- ) -> None:
- """Record an outgoing message ID for /clear, best effort."""
+ ) -> bool:
+ """Record an outgoing message ID for /clear and report ownership."""
if not msg_id:
- return
+ return False
try:
self.session_store.record_message_id(
platform,
@@ -537,6 +646,8 @@ class MessagingWorkflow:
log_full_message=self._log_messaging_error_details,
),
)
+ return False
+ return True
def _apply_cancellation_result(self, result: CancellationResult) -> None:
"""Apply detached UI and persistence effects from one transition."""
diff --git a/src/free_claude_code/runtime/application.py b/src/free_claude_code/runtime/application.py
index 20254a05..c2f220fc 100644
--- a/src/free_claude_code/runtime/application.py
+++ b/src/free_claude_code/runtime/application.py
@@ -380,7 +380,7 @@ class ApplicationRuntime:
storage_path=os.path.join(data_path, "sessions.json"),
message_log_cap=settings.max_message_log_entries_per_chat,
)
- self._messaging_workflow = messaging_workflow_module.MessagingWorkflow(
+ workflow = messaging_workflow_module.MessagingWorkflow(
platform_name=components.name,
outbound=components.outbound,
voice_cancellation=components.voice_cancellation,
@@ -391,10 +391,13 @@ class ApplicationRuntime:
log_raw_cli_diagnostics=settings.log_raw_cli_diagnostics,
log_messaging_error_details=settings.log_messaging_error_details,
)
- self._messaging_workflow.restore()
- components.runtime.on_message(self._messaging_workflow.handle_message)
+ self._messaging_workflow = workflow
+ workflow.restore()
+ components.runtime.on_message(workflow.handle_message)
await components.runtime.start()
- await self._messaging_workflow.repair_restored_statuses()
+ await workflow.repair_restored_statuses()
+ if components.startup_notice is not None:
+ await workflow.publish_startup_notice(components.startup_notice)
logger.info("{} platform started with messaging workflow", components.name)
async def _close_owned_resources(self) -> bool:
diff --git a/tests/messaging/test_handler.py b/tests/messaging/test_handler.py
index 87ea7cd8..c5384753 100644
--- a/tests/messaging/test_handler.py
+++ b/tests/messaging/test_handler.py
@@ -5,6 +5,7 @@ import pytest
from free_claude_code.messaging.command_context import ReplyClearResult, StopOutcome
from free_claude_code.messaging.models import MessageScope
+from free_claude_code.messaging.platforms.ports import MessagingStartupNotice
from free_claude_code.messaging.session import SessionStore
from free_claude_code.messaging.trees import (
BranchRemovalResult,
@@ -38,6 +39,10 @@ def _stop_outcome(
return StopOutcome(cancelled_count, scopes, fallback_required)
+def _startup_notice(chat_id: str = _SCOPE.chat_id) -> MessagingStartupNotice:
+ return MessagingStartupNotice(chat_id=chat_id, transport_label="Bot API")
+
+
async def _event_stream(events):
for event in events:
await asyncio.sleep(0)
@@ -1301,6 +1306,414 @@ async def test_global_clear_command_deletes_returned_ids(
mock_platform.queue_send_message.assert_not_awaited()
+ "failure",
+ (RuntimeError("clear failed"), asyncio.CancelledError()),
+ ids=("failure", "cancellation"),
+)
+async def test_interrupted_global_clear_records_its_deferred_command_id(
+ handler,
+ mock_platform,
+ mock_session_store,
+ incoming_message_factory,
+ failure: BaseException,
+) -> None:
+ handler.clear_all_state = AsyncMock(side_effect=failure)
+ incoming = incoming_message_factory(
+ text="/clear",
+ chat_id="chat_1",
+ message_id="150",
+ )
+
+ with pytest.raises(type(failure)):
+ await handler.handle_message(incoming)
+
+ mock_session_store.record_message_id.assert_called_once_with(
+ incoming.platform,
+ incoming.chat_id,
+ incoming.message_id,
+ direction="in",
+ kind="command",
+ )
+ mock_platform.queue_delete_messages.assert_not_awaited()
+
+
+async def test_startup_notice_is_published_and_recorded_for_clear(
+ handler,
+ mock_platform,
+ mock_session_store,
+) -> None:
+ mock_platform.queue_send_message.return_value = "startup_1"
+
+ await handler.publish_startup_notice(_startup_notice())
+
+ mock_platform.queue_send_message.assert_awaited_once_with(
+ _SCOPE.chat_id,
+ "🚀 *Claude Code Proxy is online\\!* \\(Bot API\\)",
+ parse_mode="MarkdownV2",
+ fire_and_forget=False,
+ )
+ mock_session_store.record_message_id.assert_called_once_with(
+ _SCOPE.platform,
+ _SCOPE.chat_id,
+ "startup_1",
+ direction="out",
+ kind="startup",
+ )
+ mock_platform.queue_delete_messages.assert_not_awaited()
+
+
+async def test_startup_notice_failure_is_nonfatal_and_records_nothing(
+ handler,
+ mock_platform,
+ mock_session_store,
+) -> None:
+ mock_platform.queue_send_message.side_effect = RuntimeError("unavailable")
+
+ await handler.publish_startup_notice(_startup_notice())
+
+ mock_session_store.record_message_id.assert_not_called()
+ mock_platform.queue_delete_messages.assert_not_awaited()
+
+
+async def test_startup_notice_without_delivery_receipt_records_nothing(
+ handler,
+ mock_platform,
+ mock_session_store,
+) -> None:
+ mock_platform.queue_send_message.return_value = None
+
+ await handler.publish_startup_notice(_startup_notice())
+
+ mock_session_store.record_message_id.assert_not_called()
+ mock_platform.queue_delete_messages.assert_not_awaited()
+
+
+async def test_startup_notice_record_failure_is_compensated_outside_state_lock(
+ handler,
+ mock_platform,
+ mock_session_store,
+) -> None:
+ mock_platform.queue_send_message.return_value = "startup_1"
+ mock_session_store.record_message_id.side_effect = OSError("store unavailable")
+
+ async def delete_notice(*args, **kwargs) -> None:
+ assert not handler._state_lock.locked()
+
+ mock_platform.queue_delete_messages.side_effect = delete_notice
+
+ await handler.publish_startup_notice(_startup_notice())
+
+ mock_session_store.record_message_id.assert_called_once_with(
+ _SCOPE.platform,
+ _SCOPE.chat_id,
+ "startup_1",
+ direction="out",
+ kind="startup",
+ )
+ mock_platform.queue_delete_messages.assert_awaited_once_with(
+ _SCOPE.chat_id,
+ ["startup_1"],
+ fire_and_forget=False,
+ )
+ mock_session_store.forget_message_ids.assert_called_once_with(
+ _SCOPE.platform,
+ _SCOPE.chat_id,
+ {"startup_1"},
+ )
+
+
+async def test_failed_startup_notice_compensation_restores_clear_ownership(
+ handler,
+ mock_platform,
+ mock_session_store,
+) -> None:
+ mock_platform.queue_send_message.return_value = "startup_1"
+ mock_session_store.record_message_id.side_effect = (
+ OSError("store unavailable"),
+ None,
+ )
+ mock_platform.queue_delete_messages.side_effect = RuntimeError("delete unavailable")
+
+ await handler.publish_startup_notice(_startup_notice())
+
+ assert mock_session_store.record_message_id.call_count == 2
+ assert mock_session_store.record_message_id.call_args_list == [
+ call(
+ _SCOPE.platform,
+ _SCOPE.chat_id,
+ "startup_1",
+ direction="out",
+ kind="startup",
+ ),
+ call(
+ _SCOPE.platform,
+ _SCOPE.chat_id,
+ "startup_1",
+ direction="out",
+ kind="startup",
+ ),
+ ]
+ mock_session_store.forget_message_ids.assert_not_called()
+
+
+async def test_startup_notice_publication_propagates_cancellation(
+ handler,
+ mock_platform,
+ mock_session_store,
+) -> None:
+ send_started = asyncio.Event()
+ send_cancelled = asyncio.Event()
+
+ async def send_notice(*args, **kwargs) -> None:
+ send_started.set()
+ try:
+ await asyncio.Event().wait()
+ finally:
+ send_cancelled.set()
+
+ mock_platform.queue_send_message.side_effect = send_notice
+ task = asyncio.create_task(handler.publish_startup_notice(_startup_notice()))
+ await send_started.wait()
+
+ task.cancel()
+
+ with pytest.raises(asyncio.CancelledError):
+ await task
+ await send_cancelled.wait()
+ mock_session_store.record_message_id.assert_not_called()
+ mock_platform.queue_delete_messages.assert_not_awaited()
+
+
+async def test_startup_notice_cancellation_after_receipt_finishes_compensation(
+ handler,
+ mock_platform,
+ mock_session_store,
+) -> None:
+ send_started = asyncio.Event()
+ release_send = asyncio.Event()
+ finalizer_started = asyncio.Event()
+
+ async def send_notice(*args, **kwargs) -> str:
+ send_started.set()
+ await release_send.wait()
+ return "startup_1"
+
+ original_finalize = handler._finalize_startup_notice
+
+ async def finalize_notice(*args, **kwargs) -> None:
+ finalizer_started.set()
+ await original_finalize(*args, **kwargs)
+
+ mock_platform.queue_send_message.side_effect = send_notice
+ with patch.object(
+ handler,
+ "_finalize_startup_notice",
+ side_effect=finalize_notice,
+ ):
+ task = asyncio.create_task(handler.publish_startup_notice(_startup_notice()))
+ await send_started.wait()
+ await handler._state_lock.acquire()
+ try:
+ release_send.set()
+ await finalizer_started.wait()
+ finally:
+ handler._state_lock.release()
+ task.cancel()
+
+ with pytest.raises(asyncio.CancelledError):
+ await task
+
+ mock_session_store.record_message_id.assert_not_called()
+ mock_platform.queue_delete_messages.assert_awaited_once_with(
+ _SCOPE.chat_id,
+ ["startup_1"],
+ fire_and_forget=False,
+ )
+ mock_session_store.forget_message_ids.assert_called_once_with(
+ _SCOPE.platform,
+ _SCOPE.chat_id,
+ {"startup_1"},
+ )
+
+
+async def test_concurrent_global_clear_does_not_wait_for_startup_delivery(
+ mock_platform,
+ mock_cli_manager,
+ tmp_path,
+) -> None:
+ store = SessionStore(storage_path=str(tmp_path / "sessions.json"))
+ workflow = MessagingWorkflow(
+ mock_platform,
+ mock_cli_manager,
+ store,
+ platform_name="telegram",
+ voice_cancellation=mock_platform,
+ )
+ send_started = asyncio.Event()
+ release_send = asyncio.Event()
+
+ async def send_notice(*args, **kwargs) -> str:
+ send_started.set()
+ await release_send.wait()
+ return "startup_1"
+
+ mock_platform.queue_send_message.side_effect = send_notice
+ publish_task = asyncio.create_task(
+ workflow.publish_startup_notice(_startup_notice())
+ )
+ await send_started.wait()
+ clear_task = asyncio.create_task(
+ workflow.clear_all_state(_SCOPE.platform, _SCOPE.chat_id)
+ )
+ try:
+ done, _pending = await asyncio.wait({clear_task}, timeout=1)
+ assert clear_task in done
+ assert clear_task.result() == frozenset()
+ finally:
+ release_send.set()
+ await asyncio.gather(publish_task, clear_task, return_exceptions=True)
+
+ assert store.get_message_ids_for_chat(_SCOPE.platform, _SCOPE.chat_id) == []
+ mock_platform.queue_delete_messages.assert_awaited_once_with(
+ _SCOPE.chat_id,
+ ["startup_1"],
+ fire_and_forget=False,
+ )
+
+
+async def test_global_stop_does_not_wait_for_or_invalidate_startup_delivery(
+ handler,
+ mock_platform,
+ mock_session_store,
+) -> None:
+ send_started = asyncio.Event()
+ release_send = asyncio.Event()
+
+ async def send_notice(*args, **kwargs) -> str:
+ send_started.set()
+ await release_send.wait()
+ return "startup_1"
+
+ mock_platform.queue_send_message.side_effect = send_notice
+ publish_task = asyncio.create_task(
+ handler.publish_startup_notice(_startup_notice())
+ )
+ await send_started.wait()
+ stop_task = asyncio.create_task(handler.stop_all_tasks())
+ try:
+ done, _pending = await asyncio.wait({stop_task}, timeout=1)
+ assert stop_task in done
+ stop_task.result()
+ finally:
+ release_send.set()
+ await asyncio.gather(publish_task, stop_task, return_exceptions=True)
+
+ mock_session_store.record_message_id.assert_called_once_with(
+ _SCOPE.platform,
+ _SCOPE.chat_id,
+ "startup_1",
+ direction="out",
+ kind="startup",
+ )
+ mock_platform.queue_delete_messages.assert_not_awaited()
+
+
+async def test_global_clear_precedes_concurrent_startup_notice_publication(
+ mock_platform,
+ mock_cli_manager,
+ tmp_path,
+) -> None:
+ store = SessionStore(storage_path=str(tmp_path / "sessions.json"))
+ workflow = MessagingWorkflow(
+ mock_platform,
+ mock_cli_manager,
+ store,
+ platform_name="telegram",
+ voice_cancellation=mock_platform,
+ )
+ clear_started = asyncio.Event()
+ release_clear = asyncio.Event()
+
+ async def clear_trees(*, reason: CancellationReason) -> CancellationResult:
+ assert reason is CancellationReason.STOP
+ clear_started.set()
+ await release_clear.wait()
+ return CancellationResult()
+
+ with patch.object(workflow.tree_queue, "clear_all", side_effect=clear_trees):
+ clear_task = asyncio.create_task(
+ workflow.clear_all_state(_SCOPE.platform, _SCOPE.chat_id)
+ )
+ await clear_started.wait()
+ publish_task = asyncio.create_task(
+ workflow.publish_startup_notice(_startup_notice())
+ )
+ await asyncio.sleep(0)
+ mock_platform.queue_send_message.assert_not_awaited()
+
+ release_clear.set()
+
+ assert await clear_task == frozenset()
+ await publish_task
+
+ assert store.get_message_ids_for_chat(_SCOPE.platform, _SCOPE.chat_id) == [
+ "msg_123"
+ ]
+ mock_platform.queue_delete_messages.assert_not_awaited()
+
+
+async def test_clear_command_cannot_evict_startup_notice_at_message_log_cap(
+ mock_platform,
+ mock_cli_manager,
+ incoming_message_factory,
+ tmp_path,
+) -> None:
+ store = SessionStore(
+ storage_path=str(tmp_path / "sessions.json"),
+ message_log_cap=1,
+ )
+ workflow = MessagingWorkflow(
+ mock_platform,
+ mock_cli_manager,
+ store,
+ platform_name="telegram",
+ voice_cancellation=mock_platform,
+ )
+ store.record_message_id(
+ _SCOPE.platform,
+ _SCOPE.chat_id,
+ "100",
+ direction="out",
+ kind="startup",
+ )
+ incoming = incoming_message_factory(
+ text="/clear",
+ chat_id=_SCOPE.chat_id,
+ message_id="101",
+ )
+
+ await workflow.handle_message(incoming)
+
+ mock_platform.queue_delete_messages.assert_awaited_once_with(
+ _SCOPE.chat_id,
+ ["101", "100"],
+ fire_and_forget=False,
+ )
+
+
@pytest.mark.asyncio
async def test_clear_all_state_is_chat_scoped_for_deletes_and_global_for_fcc_state(
handler, mock_cli_manager, mock_session_store, incoming_message_factory
@@ -1687,6 +2100,13 @@ async def test_reply_clear_unknown_reports_nothing_to_clear(
await handler.handle_message(incoming)
assert "Nothing to clear" in mock_platform.queue_send_message.call_args.args[1]
+ mock_session_store.record_message_id.assert_any_call(
+ incoming.platform,
+ incoming.chat_id,
+ incoming.message_id,
+ direction="in",
+ kind="command",
+ )
mock_session_store.clear_all.assert_not_called()
diff --git a/tests/messaging/test_messaging_factory.py b/tests/messaging/test_messaging_factory.py
index e23600bd..bc813e36 100644
--- a/tests/messaging/test_messaging_factory.py
+++ b/tests/messaging/test_messaging_factory.py
@@ -6,6 +6,7 @@ from free_claude_code.messaging.platforms.factory import (
MessagingPlatformOptions,
create_messaging_components,
)
+from free_claude_code.messaging.platforms.ports import MessagingStartupNotice
class TestCreateMessagingComponents:
@@ -47,6 +48,10 @@ class TestCreateMessagingComponents:
assert result.runtime is mock_runtime
assert result.outbound is mock_runtime.outbound
assert result.voice_cancellation is mock_runtime
+ assert result.startup_notice == MessagingStartupNotice(
+ chat_id="12345",
+ transport_label="Bot API",
+ )
limiter_cls.assert_called_once_with(
rate_limit=7,
rate_window=2.5,
@@ -109,6 +114,7 @@ class TestCreateMessagingComponents:
assert result.runtime is mock_runtime
assert result.outbound is mock_runtime.outbound
assert result.voice_cancellation is mock_runtime
+ assert result.startup_notice is None
limiter_cls.assert_called_once_with(
rate_limit=3,
rate_window=4.5,
@@ -176,6 +182,8 @@ class TestCreateMessagingComponents:
assert first is not None
assert second is not None
+ assert first.startup_notice is None
+ assert second.startup_notice is None
first_limiter = runtime_cls.call_args_list[0].kwargs["limiter"]
second_limiter = runtime_cls.call_args_list[1].kwargs["limiter"]
assert first_limiter is not second_limiter
diff --git a/tests/messaging/test_telegram.py b/tests/messaging/test_telegram.py
index d00c6719..c4baac6e 100644
--- a/tests/messaging/test_telegram.py
+++ b/tests/messaging/test_telegram.py
@@ -41,6 +41,7 @@ def test_telegram_platform_init_no_token():
@pytest.mark.asyncio
async def test_telegram_platform_start_success(telegram_platform):
+ telegram_platform.outbound.send_message = AsyncMock()
with patch("telegram.ext.Application.builder") as mock_builder:
mock_app = MagicMock()
mock_app.initialize = AsyncMock()
@@ -55,6 +56,7 @@ async def test_telegram_platform_start_success(telegram_platform):
mock_app.initialize.assert_called_once()
mock_app.start.assert_called_once()
telegram_platform._limiter.start.assert_called_once_with()
+ telegram_platform.outbound.send_message.assert_not_awaited()
@pytest.mark.asyncio
diff --git a/tests/runtime/test_application_runtime.py b/tests/runtime/test_application_runtime.py
index 246462f1..1a1df315 100644
--- a/tests/runtime/test_application_runtime.py
+++ b/tests/runtime/test_application_runtime.py
@@ -11,6 +11,7 @@ from free_claude_code.messaging.command_context import StopOutcome
from free_claude_code.messaging.platforms.ports import (
InboundMessageHandler,
MessagingPlatformComponents,
+ MessagingStartupNotice,
)
from free_claude_code.messaging.session import SessionStore
from free_claude_code.messaging.workflow import MessagingWorkflow
@@ -875,3 +876,55 @@ async def test_composition_records_runtime_before_workspace_setup() -> None:
assert events == ["messaging.quiesce", "messaging.close"]
assert runtime._closed is True
+
+
+async def test_composition_publishes_startup_notice_after_runtime_and_repair() -> None:
+ events: list[str] = []
+ manager = ProviderRuntimeManager(_settings("nvidia_nim/model"))
+ runtime = ApplicationRuntime(manager, transcriber=None)
+ messaging = TrackingMessagingRuntime(events)
+ notice = MessagingStartupNotice(
+ chat_id="chat",
+ transport_label="test transport",
+ )
+ components = MessagingPlatformComponents(
+ name="tracking",
+ runtime=messaging,
+ outbound=MagicMock(),
+ startup_notice=notice,
+ )
+ workflow = MagicMock()
+ workflow.handle_message = AsyncMock()
+ workflow.restore.side_effect = lambda: events.append("workflow.restore")
+ workflow.repair_restored_statuses = AsyncMock(
+ side_effect=lambda: events.append("workflow.repair")
+ )
+ workflow.publish_startup_notice = AsyncMock(
+ side_effect=lambda published: events.append("workflow.notice")
+ )
+ workflow.close = AsyncMock()
+ cli_manager = MagicMock()
+
+ with (
+ patch(
+ "free_claude_code.runtime.application.cli_managed.ManagedClaudeSessionManager",
+ return_value=cli_manager,
+ ),
+ patch("free_claude_code.runtime.application.messaging_session.SessionStore"),
+ patch(
+ "free_claude_code.runtime.application.messaging_workflow_module.MessagingWorkflow",
+ return_value=workflow,
+ ),
+ ):
+ await runtime._start_messaging_workflow(components)
+
+ assert events == [
+ "workflow.restore",
+ "messaging.start",
+ "workflow.repair",
+ "workflow.notice",
+ ]
+ workflow.publish_startup_notice.assert_awaited_once_with(notice)
+
+ assert await runtime.close() is True
diff --git a/uv.lock b/uv.lock
index 6e36e0d1..4404f296 100644
--- a/uv.lock
+++ b/uv.lock
@@ -561,7 +561,7 @@ wheels = [
[[package]]
name = "free-claude-code"
-version = "3.5.9"
+version = "3.5.10"
source = { editable = "." }
dependencies = [
{ name = "aiohttp" },