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

Preserve user messages during messaging clear (#1068)

Ali Khokhare37b50463698
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md
index 306f573c..429a554c 100644
--- a/ARCHITECTURE.md
+++ b/ARCHITECTURE.md
@@ -946,19 +946,20 @@ 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
+attempts to restore the ID to the current clearable-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
-to resolve and admit turns rather than receiving a mutable tree. Reply lookup is
-always scoped by platform and chat; an unknown or cross-chat reference cannot
-attach to another tree and therefore starts an independent root. If duplicate
-delivery or an epoch change rejects admission after a provisional status was
-sent, intake deletes that status and removes it from the message log.
+[messaging/turn_intake.py](src/free_claude_code/messaging/turn_intake.py) owns explicit clear-command
+retention, slash command dispatch, status-echo filtering, initial status messages,
+and rendering detached frozen admission/queue effects. Ordinary user messages are
+never inserted into the clearable-message log. Intake asks the workflow to resolve
+and admit turns rather than receiving a mutable tree. Reply lookup is always scoped
+by platform and chat; an unknown or cross-chat reference cannot attach to another
+tree and therefore starts an independent root. If duplicate delivery or an epoch
+change rejects admission after a provisional status was sent, intake deletes that
+status and removes it from the clearable-message log.
[messaging/node_runner.py](src/free_claude_code/messaging/node_runner.py) owns managed CLI session
lifecycle for queued nodes: parent-session fork/resume, session registration,
@@ -1015,7 +1016,9 @@ task draining. Reply `/stop` cancels exactly one request; its matching finisher
releases execution ownership and advances the next eligible queued request.
Global `/stop` drains every queue instead, and reply `/clear` removes the whole
selected branch before any survivor can advance. Separate trees still progress
-independently.
+independently. Branch transitions return internal `reference_ids` for repository
+unindexing separately from `clearable_message_ids` for platform deletion. User
+prompt IDs remain references only; FCC status IDs are the branch's deletion targets.
[messaging/trees/repository.py](src/free_claude_code/messaging/trees/repository.py)
is manager-private and owns only aggregate/reference indexes.
[messaging/trees/processor.py](src/free_claude_code/messaging/trees/processor.py) owns every
@@ -1063,21 +1066,22 @@ that dirty state for retry. Successful retry writes the current in-memory
snapshot and is the only operation that marks it clean.
Global `/clear` performs an early authoritative wipe, detaches and drains every
tree, then writes an authoritative empty conversation snapshot while preserving
-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). 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.
+clearable 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 deletion ownership for `/clear` lives in
+[messaging/session/clearable_message_log.py](src/free_claude_code/messaging/session/clearable_message_log.py).
+The bounded log accepts only FCC-authored output and explicit clear commands;
+loading drops legacy user-content entries. Startup notices use the same log as other
+clearable output. An incoming standalone `/clear` defers 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 only authorized platform deletes
+through the list-based outbound delete port. User-authored prompts and voice notes
+remain on the platform. Discord/Telegram can still reject individual deletions for
+platform reasons such as permissions, age, or missing messages.
```mermaid
sequenceDiagram
diff --git a/README.md b/README.md
index 1ea3e792..ea83544a 100644
--- a/README.md
+++ b/README.md
@@ -310,12 +310,14 @@ Configure integrations from **Admin UI → Messaging**, then click **Validate**
</details>
Bot commands: standalone `/stop` cancels all work, standalone `/clear` resets all
-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.
+sessions and removes tracked FCC messages in that chat—including Telegram's
+online notice and the clear command itself—while preserving user messages and
+voice notes. `/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 and its FCC replies without deleting user-authored messages.
+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.
<details>
<summary><strong>Voice notes</strong></summary>
diff --git a/pyproject.toml b/pyproject.toml
index 9cef116c..7db5b361 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
[project]
name = "free-claude-code"
-version = "3.5.12"
+version = "3.5.13"
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 51e37dd0..7b03115a 100644
--- a/smoke/capabilities.py
+++ b/smoke/capabilities.py
@@ -373,7 +373,7 @@ CAPABILITY_CONTRACTS: tuple[CapabilityContract, ...] = (
"messaging_commands",
"free_claude_code.messaging.commands",
"/stop, /clear, /stats command messages",
- "task cancellation with status-owned success UI, cleanup, or stats response",
+ "state cleanup with status-owned UI and user-authored messages preserved",
"terminal status edit, no-op feedback, or best-effort platform cleanup",
(
"tests/messaging/test_handler.py",
diff --git a/smoke/features.py b/smoke/features.py
index 0c665b60..27c929fa 100644
--- a/smoke/features.py
+++ b/smoke/features.py
@@ -438,7 +438,7 @@ FEATURE_INVENTORY: tuple[FeatureCoverage, ...] = (
),
FeatureCoverage(
"messaging_commands",
- "Messaging commands mutate state with task-status-owned stop feedback",
+ "Messaging commands mutate FCC state while preserving user-authored messages",
"public_surface",
(
"tests/messaging/test_handler.py",
diff --git a/smoke/lib/e2e.py b/smoke/lib/e2e.py
index 95d4af24..4efc78a0 100644
--- a/smoke/lib/e2e.py
+++ b/smoke/lib/e2e.py
@@ -450,8 +450,9 @@ class FakePlatform:
result = self._pending_voice.get((scope, reply_id))
if result is None:
return None
- for message_id in result.message_ids:
- self._pending_voice.pop((scope, message_id), None)
+ self._pending_voice.pop((scope, result.voice_message_id), None)
+ if result.status_message_id is not None:
+ self._pending_voice.pop((scope, result.status_message_id), None)
return result
async def cancel_all_pending_voices(
diff --git a/smoke/product/test_messaging_product_live.py b/smoke/product/test_messaging_product_live.py
index 50e375b2..3e5ff94b 100644
--- a/smoke/product/test_messaging_product_live.py
+++ b/smoke/product/test_messaging_product_live.py
@@ -69,6 +69,7 @@ async def test_messaging_commands_stop_clear_stats_e2e(
) -> None:
driver = FakePlatformDriver(platform_name, tmp_path)
root = await driver.send("start work", message_id="root_1")
+ root_status_id = driver.platform.sent[-1]["message_id"]
await driver.send("/stats", message_id="stats_1")
await driver.send("/stop", message_id="stop_1", reply_to=root.message_id)
@@ -76,9 +77,11 @@ async def test_messaging_commands_stop_clear_stats_e2e(
await driver.send("/clear", message_id="clear_all")
sent_text = "\n".join(sent["text"] for sent in driver.platform.sent)
+ deleted = {entry["message_id"] for entry in driver.platform.deletes}
assert "Stats" in sent_text
assert "Nothing to stop for that message" in sent_text
- assert driver.platform.deletes
+ assert {root_status_id, "clear_1", "clear_all"} <= deleted
+ assert root.message_id not in deleted
assert driver.session_store.load_conversation_snapshot().trees == {}
@@ -110,7 +113,7 @@ async def test_messaging_startup_notice_is_clearable_e2e(tmp_path) -> None:
"🚀 *Claude Code Proxy is online\\!* \\(Bot API\\)"
)
assert second_startup["parse_mode"] == "MarkdownV2"
- assert driver.session_store.get_message_ids_for_chat(
+ assert driver.session_store.get_clearable_message_ids_for_chat(
scope.platform, scope.chat_id
) == [first_startup_id, second_startup_id]
@@ -119,7 +122,9 @@ async def test_messaging_startup_notice_is_clearable_e2e(tmp_path) -> None:
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)
+ driver.session_store.get_clearable_message_ids_for_chat(
+ scope.platform, scope.chat_id
+ )
== []
)
@@ -396,7 +401,8 @@ async def test_voice_platform_fake_e2e(platform_name: str, tmp_path) -> None:
await driver.send("/stop", message_id="stop_voice")
deleted = {entry["message_id"] for entry in driver.platform.deletes}
- assert {"voice_msg_1", "voice_status_1", "clear_voice"} <= deleted
+ assert {"voice_status_1", "clear_voice"} <= deleted
+ assert "voice_msg_1" not in deleted
assert driver.platform.pending_voice_count == 0
sent_text = "\n".join(sent["text"] for sent in driver.platform.sent)
assert "Voice note cancelled" in sent_text
diff --git a/src/free_claude_code/config/admin/manifest.py b/src/free_claude_code/config/admin/manifest.py
index 3db30b91..10e8ea03 100644
--- a/src/free_claude_code/config/admin/manifest.py
+++ b/src/free_claude_code/config/admin/manifest.py
@@ -315,7 +315,7 @@ _NON_PROVIDER_FIELDS: tuple[ConfigFieldSpec, ...] = (
),
ConfigFieldSpec(
"MAX_MESSAGE_LOG_ENTRIES_PER_CHAT",
- "Max Message Log Entries",
+ "Max Clearable Messages Per Chat",
"messaging",
"number",
settings_attr="max_message_log_entries_per_chat",
diff --git a/src/free_claude_code/messaging/command_context.py b/src/free_claude_code/messaging/command_context.py
index 1d14b890..d11379f2 100644
--- a/src/free_claude_code/messaging/command_context.py
+++ b/src/free_claude_code/messaging/command_context.py
@@ -13,7 +13,7 @@ from .transcript import RenderCtx
class ReplyClearResult:
"""Customer-facing result of clearing one replied-to owner."""
- message_ids: frozenset[str]
+ clearable_message_ids: frozenset[str]
tree_cleared: bool
@@ -73,16 +73,16 @@ class MessagingCommandContext(Protocol):
...
async def clear_all_state(self, platform: str, chat_id: str) -> frozenset[str]:
- """Globally clear FCC state and return invoking-chat platform IDs."""
+ """Clear FCC state and return authorized invoking-chat deletion IDs."""
...
- def forget_message_ids(
+ def forget_clearable_message_ids(
self,
platform: str,
chat_id: str,
message_ids: set[str],
) -> None:
- """Forget deleted platform message IDs."""
+ """Forget deleted platform message IDs authorized for clear."""
...
def record_outgoing_message(
diff --git a/src/free_claude_code/messaging/command_dispatcher.py b/src/free_claude_code/messaging/command_dispatcher.py
index 171743ed..31d30b67 100644
--- a/src/free_claude_code/messaging/command_dispatcher.py
+++ b/src/free_claude_code/messaging/command_dispatcher.py
@@ -18,11 +18,6 @@ def parse_command_base(text: str | None) -> str:
return cmd.split("@", 1)[0] if cmd else ""
-def message_kind_for_command(command_base: str) -> str:
- """Return the persistence kind for an incoming message."""
- return "command" if command_base.startswith("/") else "content"
-
-
async def dispatch_command(
context: MessagingCommandContext,
incoming: IncomingMessage,
diff --git a/src/free_claude_code/messaging/commands.py b/src/free_claude_code/messaging/commands.py
index 22fcd4eb..1e7bdf09 100644
--- a/src/free_claude_code/messaging/commands.py
+++ b/src/free_claude_code/messaging/commands.py
@@ -161,14 +161,14 @@ async def handle_clear_command(
)
return
- message_ids = set(result.message_ids)
+ clearable_message_ids = set(result.clearable_message_ids)
if incoming.message_id is not None:
- message_ids.add(str(incoming.message_id))
- await _delete_message_ids(handler, incoming.chat_id, message_ids)
- handler.forget_message_ids(
+ clearable_message_ids.add(str(incoming.message_id))
+ await _delete_message_ids(handler, incoming.chat_id, clearable_message_ids)
+ handler.forget_clearable_message_ids(
incoming.platform,
incoming.chat_id,
- message_ids,
+ clearable_message_ids,
)
if not result.tree_cleared:
msg_id = await handler.outbound.queue_send_message(
diff --git a/src/free_claude_code/messaging/session/message_log.py b/src/free_claude_code/messaging/session/clearable_message_log.py
similarity index 73%
rename from src/free_claude_code/messaging/session/message_log.py
rename to src/free_claude_code/messaging/session/clearable_message_log.py
index 60d18a9b..1ecb4306 100644
--- a/src/free_claude_code/messaging/session/message_log.py
+++ b/src/free_claude_code/messaging/session/clearable_message_log.py
@@ -1,11 +1,11 @@
-"""Per-chat message ID log used by messaging clear commands."""
+"""Persist platform messages that `/clear` is authorized to delete."""
from datetime import UTC, datetime
from typing import Any
-class MessageLog:
- """Track inbound/outbound platform message IDs in insertion order."""
+class ClearableMessageLog:
+ """Track FCC output and explicit clear-command IDs in insertion order."""
def __init__(self, *, cap: int | None = None) -> None:
self._items: dict[str, list[dict[str, Any]]] = {}
@@ -17,7 +17,8 @@ class MessageLog:
return self._cap
@classmethod
- def from_json(cls, raw_log: Any, *, cap: int | None = None) -> MessageLog:
+ def from_json(cls, raw_log: Any, *, cap: int | None = None) -> ClearableMessageLog:
+ """Load clearable IDs while dropping legacy user-content entries."""
log = cls(cap=cap)
if not isinstance(raw_log, dict):
return log
@@ -30,37 +31,56 @@ class MessageLog:
message_id = item.get("message_id")
if message_id is None:
continue
+ direction = str(item.get("direction") or "")
+ kind = str(item.get("kind") or "")
+ if direction != "out" and kind != "clear_command":
+ continue
log._append(
chat_key,
str(message_id),
ts=str(item.get("ts") or ""),
- direction=str(item.get("direction") or ""),
- kind=str(item.get("kind") or ""),
+ direction=direction,
+ kind=kind,
)
return log
def to_json(self) -> dict[str, list[dict[str, Any]]]:
return {chat_key: list(items) for chat_key, items in self._items.items()}
- def record(
+ def record_outbound(
self,
*,
platform: str,
chat_id: str,
message_id: str,
- direction: str,
kind: str,
) -> bool:
- chat_key = make_chat_key(platform, chat_id)
+ """Record one FCC-authored platform message."""
return self._append(
- chat_key,
+ make_chat_key(platform, chat_id),
str(message_id),
ts=datetime.now(UTC).isoformat(),
- direction=str(direction),
+ direction="out",
kind=str(kind),
)
- def get_message_ids_for_chat(self, platform: str, chat_id: str) -> list[str]:
+ def record_clear_command(
+ self,
+ *,
+ platform: str,
+ chat_id: str,
+ message_id: str,
+ ) -> bool:
+ """Record an explicit user command that authorized its own deletion."""
+ return self._append(
+ make_chat_key(platform, chat_id),
+ str(message_id),
+ ts=datetime.now(UTC).isoformat(),
+ direction="in",
+ kind="clear_command",
+ )
+
+ def ids_for_chat(self, platform: str, chat_id: str) -> list[str]:
chat_key = make_chat_key(platform, chat_id)
return [
str(item.get("message_id"))
@@ -68,9 +88,7 @@ class MessageLog:
if item.get("message_id") is not None
]
- def remove_message_ids(
- self, platform: str, chat_id: str, message_ids: set[str]
- ) -> bool:
+ def remove_ids(self, platform: str, chat_id: str, message_ids: set[str]) -> bool:
chat_key = make_chat_key(platform, chat_id)
if not message_ids or chat_key not in self._items:
return False
diff --git a/src/free_claude_code/messaging/session/store.py b/src/free_claude_code/messaging/session/store.py
index 78479048..5260827d 100644
--- a/src/free_claude_code/messaging/session/store.py
+++ b/src/free_claude_code/messaging/session/store.py
@@ -11,13 +11,13 @@ from free_claude_code.messaging.trees import (
TreeSnapshot,
)
-from .message_log import MessageLog
+from .clearable_message_log import ClearableMessageLog
from .persistence import DebouncedJsonPersistence
class SessionStore:
"""
- Persistent storage for conversation snapshots and message IDs.
+ Persistent storage for conversation snapshots and clearable platform messages.
The store reads both the old raw ``trees``/``node_to_tree`` shape and the
current typed ``conversation`` snapshot shape. Runtime callers deal in typed
@@ -33,7 +33,7 @@ class SessionStore:
self.storage_path = storage_path
self._lock = threading.RLock()
self._conversation = ConversationSnapshot()
- self._message_log = MessageLog(cap=message_log_cap)
+ self._clearable_messages = ClearableMessageLog(cap=message_log_cap)
self._dirty = False
self._persistence = DebouncedJsonPersistence(
storage_path,
@@ -63,15 +63,15 @@ class SessionStore:
with self._lock:
self._conversation = ConversationSnapshot.from_json(conversation_data)
- self._message_log = MessageLog.from_json(
+ self._clearable_messages = ClearableMessageLog.from_json(
data.get("message_log", {}) if isinstance(data, dict) else {},
- cap=self._message_log.cap,
+ cap=self._clearable_messages.cap,
)
message_count = sum(
- len(items) for items in self._message_log.to_json().values()
+ len(items) for items in self._clearable_messages.to_json().values()
)
logger.info(
- "Loaded {} trees and {} msg_ids from {}",
+ "Loaded {} trees and {} clearable message IDs from {}",
len(self._conversation.trees),
message_count,
self.storage_path,
@@ -81,7 +81,7 @@ class SessionStore:
with self._lock:
return {
"conversation": self._conversation.to_json(),
- "message_log": self._message_log.to_json(),
+ "message_log": self._clearable_messages.to_json(),
}
def load_conversation_snapshot(self) -> ConversationSnapshot:
@@ -107,38 +107,53 @@ class SessionStore:
def flush_pending_save(self) -> None:
self._persistence.flush()
- def record_message_id(
+ def record_outbound_message_id(
self,
platform: str,
chat_id: str,
message_id: str,
- direction: str,
kind: str,
) -> None:
if message_id is None:
return
with self._lock:
- recorded = self._message_log.record(
+ recorded = self._clearable_messages.record_outbound(
platform=str(platform),
chat_id=str(chat_id),
message_id=str(message_id),
- direction=str(direction),
kind=str(kind),
)
if recorded:
self._persistence.schedule_save()
- def get_message_ids_for_chat(self, platform: str, chat_id: str) -> list[str]:
+ def record_clear_command_id(
+ self,
+ platform: str,
+ chat_id: str,
+ message_id: str,
+ ) -> None:
+ if message_id is None:
+ return
with self._lock:
- return self._message_log.get_message_ids_for_chat(
- str(platform), str(chat_id)
+ recorded = self._clearable_messages.record_clear_command(
+ platform=str(platform),
+ chat_id=str(chat_id),
+ message_id=str(message_id),
)
+ if recorded:
+ self._persistence.schedule_save()
+
+ def get_clearable_message_ids_for_chat(
+ self, platform: str, chat_id: str
+ ) -> list[str]:
+ with self._lock:
+ return self._clearable_messages.ids_for_chat(str(platform), str(chat_id))
- def forget_message_ids(
+ def forget_clearable_message_ids(
self, platform: str, chat_id: str, message_ids: set[str]
) -> None:
with self._lock:
- removed = self._message_log.remove_message_ids(
+ removed = self._clearable_messages.remove_ids(
str(platform),
str(chat_id),
{str(message_id) for message_id in message_ids},
@@ -149,7 +164,7 @@ class SessionStore:
def clear_all(self) -> None:
with self._lock:
self._conversation = ConversationSnapshot()
- self._message_log.clear()
+ self._clearable_messages.clear()
self._write_current_state()
def clear_conversation_snapshot(self) -> None:
diff --git a/src/free_claude_code/messaging/trees/manager.py b/src/free_claude_code/messaging/trees/manager.py
index 1f89f22d..ff86fd39 100644
--- a/src/free_claude_code/messaging/trees/manager.py
+++ b/src/free_claude_code/messaging/trees/manager.py
@@ -469,18 +469,18 @@ class TreeQueueManager:
return BranchRemovalResult(
cancellation=CancellationResult(),
removed_tree_identity=None,
- message_ids=frozenset(),
+ clearable_message_ids=frozenset(),
)
target = await tree.resolve_reply(branch_root_id)
if target is None:
return BranchRemovalResult(
cancellation=CancellationResult(),
removed_tree_identity=None,
- message_ids=frozenset(),
+ clearable_message_ids=frozenset(),
)
identity = tree.identity
transition = await tree.remove_branch(target.node_id)
- lookup_ids = set(transition.message_ids)
+ lookup_ids = set(transition.reference_ids)
if transition.removed_entire_tree:
self._repository.remove_tree(identity)
else:
@@ -514,7 +514,7 @@ class TreeQueueManager:
removed_tree_identity=(
identity if transition.removed_entire_tree else None
),
- message_ids=transition.message_ids,
+ clearable_message_ids=transition.clearable_message_ids,
)
def get_tree_count(self) -> int:
@@ -527,12 +527,16 @@ class TreeQueueManager:
"""Wait until every processor-owned claim has finished cleanup."""
await self._processor.wait_idle()
- async def get_message_ids_for_chat(self, platform: str, chat_id: str) -> set[str]:
+ async def get_clearable_message_ids_for_chat(
+ self, platform: str, chat_id: str
+ ) -> set[str]:
async with self._lock:
- message_ids: set[str] = set()
+ clearable_message_ids: set[str] = set()
for tree in self._repository.trees():
- message_ids.update(await tree.message_ids_for_chat(platform, chat_id))
- return message_ids
+ clearable_message_ids.update(
+ await tree.clearable_message_ids_for_chat(platform, chat_id)
+ )
+ return clearable_message_ids
async def snapshot(self) -> ConversationSnapshot:
async with self._lock:
diff --git a/src/free_claude_code/messaging/trees/runtime.py b/src/free_claude_code/messaging/trees/runtime.py
index f10aa8e1..bb1e8a87 100644
--- a/src/free_claude_code/messaging/trees/runtime.py
+++ b/src/free_claude_code/messaging/trees/runtime.py
@@ -281,7 +281,8 @@ class MessageTree:
)
return TreeBranchRemoval(
cancellation=empty,
- message_ids=frozenset(),
+ reference_ids=frozenset(),
+ clearable_message_ids=frozenset(),
removed_entire_tree=False,
)
@@ -297,16 +298,19 @@ class MessageTree:
if active is not None:
active.cancellation_requested = True
cancelled_nodes: list[NodeUiTarget] = []
- message_ids: set[str] = set()
+ reference_ids: set[str] = set()
+ clearable_message_ids: set[str] = set()
queue_changed = False
for node_id in branch_ids:
node = self._graph.get_node(node_id)
if node is None:
continue
- message_ids.add(node.node_id)
+ reference_ids.add(node.node_id)
if node.status_message_id:
- message_ids.add(str(node.status_message_id))
+ status_message_id = str(node.status_message_id)
+ reference_ids.add(status_message_id)
+ clearable_message_ids.add(status_message_id)
queue_changed = self._queue.remove(node_id) or queue_changed
if node.state in (MessageState.PENDING, MessageState.IN_PROGRESS):
node.mark_error()
@@ -327,7 +331,8 @@ class MessageTree:
)
return TreeBranchRemoval(
cancellation=cancellation,
- message_ids=frozenset(message_ids),
+ reference_ids=frozenset(reference_ids),
+ clearable_message_ids=frozenset(clearable_message_ids),
removed_entire_tree=removed_entire_tree,
)
@@ -444,19 +449,20 @@ class MessageTree:
async with self._lock:
return self._graph.snapshot()
- async def message_ids_for_chat(self, platform: str, chat_id: str) -> set[str]:
- """Copy message IDs belonging to one platform chat."""
+ async def clearable_message_ids_for_chat(
+ self, platform: str, chat_id: str
+ ) -> set[str]:
+ """Copy FCC-authored message IDs belonging to one platform chat."""
async with self._lock:
if self.identity.scope.platform != str(platform) or (
self.identity.scope.chat_id != str(chat_id)
):
return set()
- message_ids: set[str] = set()
+ clearable_message_ids: set[str] = set()
for node in self._graph.all_nodes():
- message_ids.add(node.node_id)
if node.status_message_id:
- message_ids.add(str(node.status_message_id))
- return message_ids
+ clearable_message_ids.add(str(node.status_message_id))
+ return clearable_message_ids
@classmethod
def from_snapshot(cls, snapshot: TreeSnapshot) -> MessageTree:
diff --git a/src/free_claude_code/messaging/trees/transitions.py b/src/free_claude_code/messaging/trees/transitions.py
index 747c4495..6951bb26 100644
--- a/src/free_claude_code/messaging/trees/transitions.py
+++ b/src/free_claude_code/messaging/trees/transitions.py
@@ -101,7 +101,8 @@ class TreeBranchRemoval:
"""Single-tree atomic cancellation and graph-removal transition."""
cancellation: TreeCancellation
- message_ids: frozenset[str]
+ reference_ids: frozenset[str]
+ clearable_message_ids: frozenset[str]
removed_entire_tree: bool
@@ -111,7 +112,7 @@ class BranchRemovalResult:
cancellation: CancellationResult
removed_tree_identity: TreeIdentity | None
- message_ids: frozenset[str]
+ clearable_message_ids: frozenset[str]
@dataclass(frozen=True, slots=True)
diff --git a/src/free_claude_code/messaging/turn_intake.py b/src/free_claude_code/messaging/turn_intake.py
index 571f2ad3..2e1bae34 100644
--- a/src/free_claude_code/messaging/turn_intake.py
+++ b/src/free_claude_code/messaging/turn_intake.py
@@ -10,7 +10,6 @@ from .cli_event_constants import STATUS_MESSAGE_PREFIXES
from .command_context import MessagingCommandContext
from .command_dispatcher import (
dispatch_command,
- message_kind_for_command,
parse_command_base,
)
from .models import IncomingMessage, MessageScope
@@ -51,24 +50,19 @@ 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:
+ def _record_clear_command(self, incoming: IncomingMessage) -> None:
+ """Retain a clear command only when later clear cleanup may need it."""
if incoming.message_id is None:
return
try:
- self.session_store.record_message_id(
+ self.session_store.record_clear_command_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: {}",
+ "Failed to record clear command message_id: {}",
format_exception_for_log(
exc,
log_full_message=self._log_messaging_error_details,
@@ -89,16 +83,17 @@ class MessagingTurnIntake:
# 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)
+ is_clear = cmd_base == "/clear"
+ is_global_clear = is_clear and not incoming.is_reply()
+ if is_clear and not is_global_clear:
+ self._record_clear_command(incoming)
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)
+ self._record_clear_command(incoming)
raise
text = incoming.text or ""
@@ -197,7 +192,7 @@ class MessagingTurnIntake:
type(exc).__name__,
)
try:
- self.session_store.forget_message_ids(
+ self.session_store.forget_clearable_message_ids(
incoming.platform,
incoming.chat_id,
{status_message_id},
diff --git a/src/free_claude_code/messaging/voice.py b/src/free_claude_code/messaging/voice.py
index b2e993da..98d95953 100644
--- a/src/free_claude_code/messaging/voice.py
+++ b/src/free_claude_code/messaging/voice.py
@@ -63,19 +63,18 @@ class VoiceHandoffOutcome(Enum):
@dataclass(frozen=True, slots=True)
class VoiceCancellationResult:
- """Message IDs released by one successful voice cancellation."""
+ """Released ownership for one successfully cancelled user voice note."""
scope: MessageScope
voice_message_id: str
status_message_id: str | None
@property
- def message_ids(self) -> frozenset[str]:
- """Return each platform message ID owned by the cancelled voice note."""
- ids = {self.voice_message_id}
- if self.status_message_id is not None:
- ids.add(self.status_message_id)
- return frozenset(ids)
+ def clearable_message_ids(self) -> frozenset[str]:
+ """Return only FCC-authored platform messages authorized for deletion."""
+ if self.status_message_id is None:
+ return frozenset()
+ return frozenset({self.status_message_id})
@dataclass(slots=True)
diff --git a/src/free_claude_code/messaging/workflow.py b/src/free_claude_code/messaging/workflow.py
index aa461a67..d8215641 100644
--- a/src/free_claude_code/messaging/workflow.py
+++ b/src/free_claude_code/messaging/workflow.py
@@ -312,7 +312,7 @@ class MessagingWorkflow:
return
async with self._state_lock:
- self.forget_message_ids(
+ self.forget_clearable_message_ids(
self.platform_name,
chat_id,
{message_id},
@@ -455,7 +455,7 @@ class MessagingWorkflow:
if voice_result is None:
return None
return ReplyClearResult(
- message_ids=voice_result.message_ids,
+ clearable_message_ids=voice_result.clearable_message_ids,
tree_cleared=False,
)
@@ -464,11 +464,11 @@ class MessagingWorkflow:
if branch.removed_tree_identity is not None:
self.session_store.remove_tree_snapshot(branch.removed_tree_identity)
- message_ids = set(branch.message_ids)
+ clearable_message_ids = set(branch.clearable_message_ids)
if voice_result is not None:
- message_ids.update(voice_result.message_ids)
+ clearable_message_ids.update(voice_result.clearable_message_ids)
return ReplyClearResult(
- message_ids=frozenset(message_ids),
+ clearable_message_ids=frozenset(clearable_message_ids),
tree_cleared=True,
)
@@ -510,27 +510,29 @@ class MessagingWorkflow:
for voice in voice_results:
self.render_voice_stopped(voice)
async with self._state_lock:
- message_ids: set[str] = set()
+ clearable_message_ids: set[str] = set()
clear_scope = MessageScope(platform=platform, chat_id=chat_id)
for voice in voice_results:
if voice.scope == clear_scope:
- message_ids.update(voice.message_ids)
+ clearable_message_ids.update(voice.clearable_message_ids)
try:
- message_ids.update(
+ clearable_message_ids.update(
str(message_id)
- for message_id in self.session_store.get_message_ids_for_chat(
- platform,
- chat_id,
+ for message_id in self.session_store.get_clearable_message_ids_for_chat(
+ platform, chat_id
)
if message_id is not None
)
except Exception as exc:
logger.debug(
- "Failed to read message log for /clear: {}", type(exc).__name__
+ "Failed to read clearable-message log for /clear: {}",
+ type(exc).__name__,
)
- message_ids.update(
- await self._tree_queue.get_message_ids_for_chat(platform, chat_id)
+ clearable_message_ids.update(
+ await self._tree_queue.get_clearable_message_ids_for_chat(
+ platform, chat_id
+ )
)
# All fallible/cancellable reads precede the commit boundary. Once
# the epoch advances, the following synchronous wipe and the
@@ -552,7 +554,7 @@ class MessagingWorkflow:
failures.append(exc)
# A runner may terminalize during task draining after the early
# store clear. The detached manager now rejects later writes; clear
- # this final pre-detach snapshot without erasing newer message logs.
+ # this final pre-detach snapshot without erasing newer clearable IDs.
try:
self.session_store.clear_conversation_snapshot()
except Exception as exc:
@@ -573,7 +575,7 @@ class MessagingWorkflow:
raise failures[0]
if failures:
raise ExceptionGroup("Global clear failed", failures)
- return frozenset(message_ids)
+ return frozenset(clearable_message_ids)
async def _cancel_all_pending_voices(
self,
@@ -606,14 +608,16 @@ class MessagingWorkflow:
)
)
- def forget_message_ids(
+ def forget_clearable_message_ids(
self,
platform: str,
chat_id: str,
message_ids: set[str],
) -> None:
try:
- self.session_store.forget_message_ids(platform, chat_id, message_ids)
+ self.session_store.forget_clearable_message_ids(
+ platform, chat_id, message_ids
+ )
except Exception as exc:
logger.warning(
"Failed to update session store after branch clear: {}",
@@ -631,12 +635,11 @@ class MessagingWorkflow:
if not msg_id:
return False
try:
- self.session_store.record_message_id(
+ self.session_store.record_outbound_message_id(
platform,
chat_id,
str(msg_id),
- direction="out",
- kind=kind,
+ kind,
)
except Exception as exc:
logger.debug(
diff --git a/tests/conftest.py b/tests/conftest.py
index 9f799cbe..2fe37717 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -148,8 +148,9 @@ def mock_session_store():
store.get_tree = MagicMock(return_value=None)
store.register_node = MagicMock()
store.clear_all = MagicMock()
- store.record_message_id = MagicMock()
- store.get_message_ids_for_chat = MagicMock(return_value=[])
+ store.record_outbound_message_id = MagicMock()
+ store.record_clear_command_id = MagicMock()
+ store.get_clearable_message_ids_for_chat = MagicMock(return_value=[])
return store
diff --git a/tests/messaging/test_handler.py b/tests/messaging/test_handler.py
index c5384753..24924f52 100644
--- a/tests/messaging/test_handler.py
+++ b/tests/messaging/test_handler.py
@@ -128,6 +128,26 @@ async def test_handle_message_turn_trace_always_includes_full_message_text(
assert trace_mock.call_args.kwargs["message_text"] == text
+async def test_user_prompt_is_never_recorded_as_clearable(
+ handler,
+ mock_session_store,
+ incoming_message_factory,
+) -> None:
+ incoming = incoming_message_factory(text="keep me", message_id="user-prompt")
+
+ await handler.handle_message(incoming)
+ await _wait_for_idle(handler)
+
+ mock_session_store.record_clear_command_id.assert_not_called()
+ mock_session_store.record_outbound_message_id.assert_called_once_with(
+ incoming.platform,
+ incoming.chat_id,
+ "msg_123",
+ "status",
+ )
+
+
@pytest.mark.parametrize(
("target", "expected"),
[
@@ -574,7 +594,7 @@ async def test_duplicate_delivery_removes_its_provisional_status(
["status-rejected"],
fire_and_forget=False,
)
- mock_session_store.forget_message_ids.assert_called_once_with(
+ mock_session_store.forget_clearable_message_ids.assert_called_once_with(
incoming.platform,
incoming.chat_id,
{"status-rejected"},
@@ -1304,6 +1324,7 @@ async def test_global_clear_command_deletes_returned_ids(
fire_and_forget=False,
)
mock_platform.queue_send_message.assert_not_awaited()
+ handler.session_store.record_clear_command_id.assert_not_called()
@pytest.mark.asyncio
@@ -1329,12 +1350,10 @@ async def test_interrupted_global_clear_records_its_deferred_command_id(
with pytest.raises(type(failure)):
await handler.handle_message(incoming)
- mock_session_store.record_message_id.assert_called_once_with(
+ mock_session_store.record_clear_command_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()
@@ -1355,12 +1374,11 @@ async def test_startup_notice_is_published_and_recorded_for_clear(
parse_mode="MarkdownV2",
fire_and_forget=False,
)
- mock_session_store.record_message_id.assert_called_once_with(
+ mock_session_store.record_outbound_message_id.assert_called_once_with(
_SCOPE.platform,
_SCOPE.chat_id,
"startup_1",
- direction="out",
- kind="startup",
+ "startup",
)
mock_platform.queue_delete_messages.assert_not_awaited()
@@ -1375,7 +1393,7 @@ async def test_startup_notice_failure_is_nonfatal_and_records_nothing(
await handler.publish_startup_notice(_startup_notice())
- mock_session_store.record_message_id.assert_not_called()
+ mock_session_store.record_outbound_message_id.assert_not_called()
mock_platform.queue_delete_messages.assert_not_awaited()
@@ -1389,7 +1407,7 @@ async def test_startup_notice_without_delivery_receipt_records_nothing(
await handler.publish_startup_notice(_startup_notice())
- mock_session_store.record_message_id.assert_not_called()
+ mock_session_store.record_outbound_message_id.assert_not_called()
mock_platform.queue_delete_messages.assert_not_awaited()
@@ -1400,7 +1418,9 @@ async def test_startup_notice_record_failure_is_compensated_outside_state_lock(
mock_session_store,
) -> None:
mock_platform.queue_send_message.return_value = "startup_1"
- mock_session_store.record_message_id.side_effect = OSError("store unavailable")
+ mock_session_store.record_outbound_message_id.side_effect = OSError(
+ "store unavailable"
+ )
async def delete_notice(*args, **kwargs) -> None:
assert not handler._state_lock.locked()
@@ -1409,19 +1429,18 @@ async def test_startup_notice_record_failure_is_compensated_outside_state_lock(
await handler.publish_startup_notice(_startup_notice())
- mock_session_store.record_message_id.assert_called_once_with(
+ mock_session_store.record_outbound_message_id.assert_called_once_with(
_SCOPE.platform,
_SCOPE.chat_id,
"startup_1",
- direction="out",
- kind="startup",
+ "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(
+ mock_session_store.forget_clearable_message_ids.assert_called_once_with(
_SCOPE.platform,
_SCOPE.chat_id,
{"startup_1"},
@@ -1435,7 +1454,7 @@ async def test_failed_startup_notice_compensation_restores_clear_ownership(
mock_session_store,
) -> None:
mock_platform.queue_send_message.return_value = "startup_1"
- mock_session_store.record_message_id.side_effect = (
+ mock_session_store.record_outbound_message_id.side_effect = (
OSError("store unavailable"),
None,
)
@@ -1443,24 +1462,22 @@ async def test_failed_startup_notice_compensation_restores_clear_ownership(
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 == [
+ assert mock_session_store.record_outbound_message_id.call_count == 2
+ assert mock_session_store.record_outbound_message_id.call_args_list == [
call(
_SCOPE.platform,
_SCOPE.chat_id,
"startup_1",
- direction="out",
- kind="startup",
+ "startup",
),
call(
_SCOPE.platform,
_SCOPE.chat_id,
"startup_1",
- direction="out",
- kind="startup",
+ "startup",
),
]
- mock_session_store.forget_message_ids.assert_not_called()
+ mock_session_store.forget_clearable_message_ids.assert_not_called()
@pytest.mark.asyncio
@@ -1488,7 +1505,7 @@ async def test_startup_notice_publication_propagates_cancellation(
with pytest.raises(asyncio.CancelledError):
await task
await send_cancelled.wait()
- mock_session_store.record_message_id.assert_not_called()
+ mock_session_store.record_outbound_message_id.assert_not_called()
mock_platform.queue_delete_messages.assert_not_awaited()
@@ -1532,13 +1549,13 @@ async def test_startup_notice_cancellation_after_receipt_finishes_compensation(
with pytest.raises(asyncio.CancelledError):
await task
- mock_session_store.record_message_id.assert_not_called()
+ mock_session_store.record_outbound_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(
+ mock_session_store.forget_clearable_message_ids.assert_called_once_with(
_SCOPE.platform,
_SCOPE.chat_id,
{"startup_1"},
@@ -1583,7 +1600,9 @@ async def test_concurrent_global_clear_does_not_wait_for_startup_delivery(
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) == []
+ assert (
+ store.get_clearable_message_ids_for_chat(_SCOPE.platform, _SCOPE.chat_id) == []
+ )
mock_platform.queue_delete_messages.assert_awaited_once_with(
_SCOPE.chat_id,
["startup_1"],
@@ -1619,12 +1638,11 @@ async def test_global_stop_does_not_wait_for_or_invalidate_startup_delivery(
release_send.set()
await asyncio.gather(publish_task, stop_task, return_exceptions=True)
- mock_session_store.record_message_id.assert_called_once_with(
+ mock_session_store.record_outbound_message_id.assert_called_once_with(
_SCOPE.platform,
_SCOPE.chat_id,
"startup_1",
- direction="out",
- kind="startup",
+ "startup",
)
mock_platform.queue_delete_messages.assert_not_awaited()
@@ -1668,9 +1686,9 @@ async def test_global_clear_precedes_concurrent_startup_notice_publication(
assert await clear_task == frozenset()
await publish_task
- assert store.get_message_ids_for_chat(_SCOPE.platform, _SCOPE.chat_id) == [
- "msg_123"
- ]
+ assert store.get_clearable_message_ids_for_chat(
+ _SCOPE.platform, _SCOPE.chat_id
+ ) == ["msg_123"]
mock_platform.queue_delete_messages.assert_not_awaited()
@@ -1692,12 +1710,11 @@ async def test_clear_command_cannot_evict_startup_notice_at_message_log_cap(
platform_name="telegram",
voice_cancellation=mock_platform,
)
- store.record_message_id(
+ store.record_outbound_message_id(
_SCOPE.platform,
_SCOPE.chat_id,
"100",
- direction="out",
- kind="startup",
+ "startup",
)
incoming = incoming_message_factory(
text="/clear",
@@ -1731,13 +1748,13 @@ async def test_clear_all_state_is_chat_scoped_for_deletes_and_global_for_fcc_sta
await handler.tree_queue.admit(root_1, "101")
await handler.tree_queue.admit(root_2, "201")
await _wait_for_idle(handler)
- mock_session_store.get_message_ids_for_chat.return_value = ["42"]
+ mock_session_store.get_clearable_message_ids_for_chat.return_value = ["42"]
mock_session_store.reset_mock()
- mock_session_store.get_message_ids_for_chat.return_value = ["42"]
+ mock_session_store.get_clearable_message_ids_for_chat.return_value = ["42"]
message_ids = await handler.clear_all_state("telegram", "chat_1")
- assert message_ids == frozenset({"42", "100", "101"})
+ assert message_ids == frozenset({"42", "101"})
assert "200" not in message_ids
assert handler.get_tree_count() == 0
mock_cli_manager.stop_all.assert_awaited_once()
@@ -1774,13 +1791,13 @@ async def test_clear_all_joins_voices_before_lock_and_returns_only_current_chat_
return CancellationResult()
mock_platform.cancel_all_pending_voices.side_effect = cancel_voices
- mock_session_store.get_message_ids_for_chat.return_value = ["stored"]
+ mock_session_store.get_clearable_message_ids_for_chat.return_value = ["stored"]
with patch.object(handler.tree_queue, "clear_all", side_effect=clear_trees):
message_ids = await handler.clear_all_state("telegram", "chat_1")
await asyncio.sleep(0)
assert events == ["voices", "trees"]
- assert message_ids == frozenset({"stored", "voice", "voice_status"})
+ assert message_ids == frozenset({"stored", "voice_status"})
assert "other_voice" not in message_ids
assert "other_status" not in message_ids
assert {
@@ -1983,7 +2000,7 @@ async def test_cancelled_global_clear_finishes_owned_transaction_before_propagat
mock_session_store.reset_mock()
with patch.object(
handler.tree_queue,
- "get_message_ids_for_chat",
+ "get_clearable_message_ids_for_chat",
new=block_id_read,
):
clear_task = asyncio.create_task(
@@ -2074,16 +2091,22 @@ async def test_reply_clear_removes_only_branch_and_persists_remaining_tree(
)
)
- assert set(deleted_ids) == {"102", "103", "150"}
+ assert set(deleted_ids) == {"103", "150"}
+ assert "102" not in deleted_ids
assert "100" not in deleted_ids
assert "101" not in deleted_ids
assert await handler.tree_queue.get_node(root.scope, "102") is None
assert await handler.tree_queue.get_node(root.scope, "100") is not None
mock_session_store.save_tree_snapshot.assert_called_once()
- mock_session_store.forget_message_ids.assert_called_once_with(
+ mock_session_store.record_clear_command_id.assert_called_once_with(
"telegram",
"chat_1",
- {"102", "103", "150"},
+ "150",
+ )
+ mock_session_store.forget_clearable_message_ids.assert_called_once_with(
+ "telegram",
+ "chat_1",
+ {"103", "150"},
)
@@ -2100,12 +2123,10 @@ 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(
+ mock_session_store.record_clear_command_id.assert_any_call(
incoming.platform,
incoming.chat_id,
incoming.message_id,
- direction="in",
- kind="command",
)
mock_session_store.clear_all.assert_not_called()
@@ -2135,7 +2156,8 @@ async def test_reply_clear_root_removes_tree_snapshot(
)
)
- assert set(deleted_ids) == {"100", "101", "150"}
+ assert set(deleted_ids) == {"101", "150"}
+ assert "100" not in deleted_ids
mock_session_store.remove_tree_snapshot.assert_called_once_with(
TreeIdentity(scope=root.scope, root_id="100")
)
@@ -2211,7 +2233,7 @@ async def test_global_clear_removes_snapshot_saved_during_detach_window(
await workflow.handle_message(incoming)
await runner_started.wait()
- get_ids = workflow.tree_queue.get_message_ids_for_chat
+ get_ids = workflow.tree_queue.get_clearable_message_ids_for_chat
async def block_id_read(platform: str, chat_id: str) -> set[str]:
id_read_started.set()
@@ -2221,7 +2243,7 @@ async def test_global_clear_removes_snapshot_saved_during_detach_window(
try:
with patch.object(
workflow.tree_queue,
- "get_message_ids_for_chat",
+ "get_clearable_message_ids_for_chat",
new=block_id_read,
):
clear_task = asyncio.create_task(
@@ -2298,8 +2320,8 @@ async def test_global_clear_invalidates_inflight_prompt_without_waiting_for_stat
@pytest.mark.parametrize(
("status_message_id", "expected_deleted_ids"),
[
- ("101", {"100", "101", "150"}),
- (None, {"100", "150"}),
+ ("101", {"101", "150"}),
+ (None, {"150"}),
],
)
async def test_reply_clear_pending_voice_cancels_and_reports(
@@ -2309,12 +2331,12 @@ async def test_reply_clear_pending_voice_cancels_and_reports(
status_message_id,
expected_deleted_ids,
) -> None:
- message_ids = {"100"}
- if status_message_id is not None:
- message_ids.add(status_message_id)
+ clearable_message_ids = (
+ {status_message_id} if status_message_id is not None else set()
+ )
handler.clear_reply = AsyncMock(
return_value=ReplyClearResult(
- message_ids=frozenset(message_ids),
+ clearable_message_ids=frozenset(clearable_message_ids),
tree_cleared=False,
)
)
@@ -2345,7 +2367,7 @@ async def test_reply_clear_deletes_owned_result_ids(
) -> None:
handler.clear_reply = AsyncMock(
return_value=ReplyClearResult(
- message_ids=frozenset({"voice", "tree_status"}),
+ clearable_message_ids=frozenset({"tree_status"}),
tree_cleared=True,
)
)
@@ -2365,10 +2387,10 @@ async def test_reply_clear_deletes_owned_result_ids(
handler.clear_reply.assert_awaited_once_with(incoming.scope, "voice")
assert set(deleted_ids) == {
- "voice",
"tree_status",
"clear",
}
+ assert "voice" not in deleted_ids
mock_platform.queue_send_message.assert_not_awaited()
@@ -2394,7 +2416,7 @@ async def test_reply_clear_joins_voice_then_unions_authoritative_branch_ids(
branch = BranchRemovalResult(
cancellation=CancellationResult(),
removed_tree_identity=None,
- message_ids=frozenset({"voice", "tree_status"}),
+ clearable_message_ids=frozenset({"tree_status"}),
)
mock_platform.cancel_pending_voice.side_effect = cancel_voice
with (
@@ -2414,7 +2436,7 @@ async def test_reply_clear_joins_voice_then_unions_authoritative_branch_ids(
await asyncio.sleep(0)
assert result == ReplyClearResult(
- message_ids=frozenset({"voice", "voice_status", "tree_status"}),
+ clearable_message_ids=frozenset({"voice_status", "tree_status"}),
tree_cleared=True,
)
assert events == ["voice", "resolve"]
diff --git a/tests/messaging/test_message_tree_transitions.py b/tests/messaging/test_message_tree_transitions.py
index 4e3d4475..9bed0d0c 100644
--- a/tests/messaging/test_message_tree_transitions.py
+++ b/tests/messaging/test_message_tree_transitions.py
@@ -157,6 +157,19 @@ async def test_cancelled_queue_member_is_never_claimed() -> None:
assert completion.next_claim.node.node_id == "b"
+async def test_branch_removal_separates_references_from_clearable_messages() -> None:
+ tree = _tree()
+ await _add(tree, "child", "status-child")
+
+ removed = await tree.remove_branch("root")
+
+ assert removed.reference_ids == frozenset(
+ {"root", "status-root", "child", "status-child"}
+ )
+ assert removed.clearable_message_ids == frozenset({"status-root", "status-child"})
+
+
@pytest.mark.asyncio
async def test_concurrent_duplicate_enqueue_produces_one_claim_only() -> None:
tree = _tree()
diff --git a/tests/messaging/test_session_store_edge_cases.py b/tests/messaging/test_session_store_edge_cases.py
index bea8acb5..a8ee2f03 100644
--- a/tests/messaging/test_session_store_edge_cases.py
+++ b/tests/messaging/test_session_store_edge_cases.py
@@ -579,17 +579,62 @@ class TestSessionStoreClearAll:
store2 = SessionStore(storage_path=path)
assert store2.load_conversation_snapshot().is_empty
- def test_message_log_persists_and_dedups(self, tmp_path):
+ def test_clearable_message_log_persists_and_dedups(self, tmp_path):
path = str(tmp_path / "sessions.json")
store = SessionStore(storage_path=path)
- store.record_message_id("telegram", "c1", "1", direction="in", kind="command")
- store.record_message_id("telegram", "c1", "2", direction="out", kind="command")
- store.record_message_id("telegram", "c1", "2", direction="out", kind="command")
+ store.record_outbound_message_id("telegram", "c1", "2", "command")
+ store.record_outbound_message_id("telegram", "c1", "2", "command")
+ store.record_clear_command_id("telegram", "c1", "3")
- ids = store.get_message_ids_for_chat("telegram", "c1")
- assert ids == ["1", "2"]
+ ids = store.get_clearable_message_ids_for_chat("telegram", "c1")
+ assert ids == ["2", "3"]
store.flush_pending_save()
store2 = SessionStore(storage_path=path)
- assert store2.get_message_ids_for_chat("telegram", "c1") == ["1", "2"]
+ assert store2.get_clearable_message_ids_for_chat("telegram", "c1") == [
+ "2",
+ "3",
+ ]
+
+ def test_load_drops_legacy_user_messages_from_clearable_log(self, tmp_path):
+ path = tmp_path / "sessions.json"
+ path.write_text(
+ json.dumps(
+ {
+ "conversation": {"trees": []},
+ "message_log": {
+ "telegram:c1": [
+ {
+ "message_id": "prompt",
+ "direction": "in",
+ "kind": "content",
+ },
+ {
+ "message_id": "old-command",
+ "direction": "in",
+ "kind": "command",
+ },
+ {
+ "message_id": "status",
+ "direction": "out",
+ "kind": "status",
+ },
+ {
+ "message_id": "clear-command",
+ "direction": "in",
+ "kind": "clear_command",
+ },
+ ]
+ },
+ }
+ ),
+ encoding="utf-8",
+ )
+
+ store = SessionStore(storage_path=str(path))
+
+ assert store.get_clearable_message_ids_for_chat("telegram", "c1") == [
+ "status",
+ "clear-command",
+ ]
diff --git a/tests/messaging/test_tree_concurrency.py b/tests/messaging/test_tree_concurrency.py
index 385223db..750e6d3b 100644
--- a/tests/messaging/test_tree_concurrency.py
+++ b/tests/messaging/test_tree_concurrency.py
@@ -241,9 +241,7 @@ async def test_branch_removal_atomically_unindexes_subtree_and_preserves_sibling
)
assert result.removed_tree_identity is None
- assert result.message_ids == frozenset(
- {"branch", "status-branch", "leaf", "status-leaf"}
- )
+ assert result.clearable_message_ids == frozenset({"status-branch", "status-leaf"})
assert {
effect.node.node_id: effect.ui_owner for effect in result.cancellation.effects
} == {
@@ -291,9 +289,7 @@ async def test_root_removal_atomically_cancels_and_unindexes_entire_tree() -> No
assert result.removed_tree_identity is not None
assert result.removed_tree_identity.scope == _SCOPE
assert result.removed_tree_identity.root_id == "root"
- assert result.message_ids == frozenset(
- {"root", "status-root", "child", "status-child"}
- )
+ assert result.clearable_message_ids == frozenset({"status-root", "status-child"})
assert {
effect.node.node_id: effect.ui_owner for effect in result.cancellation.effects
} == {
diff --git a/tests/messaging/test_tree_customer_regressions.py b/tests/messaging/test_tree_customer_regressions.py
index c93cca87..7f3307c1 100644
--- a/tests/messaging/test_tree_customer_regressions.py
+++ b/tests/messaging/test_tree_customer_regressions.py
@@ -65,13 +65,11 @@ async def test_same_telegram_ids_in_different_chats_remain_independent_after_res
assert restored.get_tree_count() == 2
assert _snapshot_chat_ids(await restored.snapshot()) == {"chat-a", "chat-b"}
- assert await restored.get_message_ids_for_chat("telegram", "chat-a") == {
- "42",
- "99",
+ assert await restored.get_clearable_message_ids_for_chat("telegram", "chat-a") == {
+ "99"
}
- assert await restored.get_message_ids_for_chat("telegram", "chat-b") == {
- "42",
- "99",
+ assert await restored.get_clearable_message_ids_for_chat("telegram", "chat-b") == {
+ "99"
}
assert await restored.get_node(chat_a, "42") is not None
assert await restored.get_node(chat_b, "42") is not None
diff --git a/tests/messaging/test_tree_ownership_concurrency.py b/tests/messaging/test_tree_ownership_concurrency.py
index b1073311..f18bb7af 100644
--- a/tests/messaging/test_tree_ownership_concurrency.py
+++ b/tests/messaging/test_tree_ownership_concurrency.py
@@ -329,7 +329,7 @@ async def test_branch_removal_cannot_leave_a_detached_running_descendant() -> No
parent_node_id="branch",
)
- assert removed.message_ids == frozenset({"branch", "status-branch"})
+ assert removed.clearable_message_ids == frozenset({"status-branch"})
assert await manager.resolve_node_id(_SCOPE, "branch") is None
assert late.accepted is True
late_node = await manager.get_node(_SCOPE, "late")
diff --git a/tests/messaging/test_tree_repository.py b/tests/messaging/test_tree_repository.py
index 18e817c4..4938d843 100644
--- a/tests/messaging/test_tree_repository.py
+++ b/tests/messaging/test_tree_repository.py
@@ -182,9 +182,8 @@ async def test_claim_state_and_session_updates_produce_detached_snapshots() -> N
view = await manager.get_node(TELEGRAM_CHAT, "status-root")
assert view is not None and view.state is MessageState.COMPLETED
assert view.session_id == "session-root"
- assert await manager.get_message_ids_for_chat("telegram", "chat") == {
- "root",
- "status-root",
+ assert await manager.get_clearable_message_ids_for_chat("telegram", "chat") == {
+ "status-root"
}
release.set()
diff --git a/tests/messaging/test_voice_services.py b/tests/messaging/test_voice_services.py
index c2d18e6a..9fd9a0ee 100644
--- a/tests/messaging/test_voice_services.py
+++ b/tests/messaging/test_voice_services.py
@@ -54,7 +54,7 @@ async def test_cancel_before_status_binding_rejects_late_flow() -> None:
voice_message_id="voice-1",
status_message_id=None,
)
- assert cancellation.message_ids == frozenset({"voice-1"})
+ assert cancellation.clearable_message_ids == frozenset()
assert await registry.bind_status(claim, "status-1") is False
assert await registry.handoff(claim, callback) is VoiceHandoffOutcome.REJECTED
assert callback_called is False
@@ -119,7 +119,7 @@ async def test_cancel_removes_then_drains_handoff_without_holding_lock() -> None
voice_message_id="voice-1",
status_message_id="status-1",
)
- assert cancellation.message_ids == frozenset({"voice-1", "status-1"})
+ assert cancellation.clearable_message_ids == frozenset({"status-1"})
assert await asyncio.wait_for(handoff_task, timeout=1) is (
VoiceHandoffOutcome.CANCELLED
)
@@ -584,8 +584,8 @@ async def test_cancel_all_deduplicates_aliases_and_excludes_current_child() -> N
assert cancellations is not None
assert len(cancellations) == 1
assert {result.scope for result in cancellations} == {TELEGRAM_CHAT}
- assert {result.message_ids for result in cancellations} == {
- frozenset({"voice-1", "status-1"}),
+ assert {result.clearable_message_ids for result in cancellations} == {
+ frozenset({"status-1"}),
}
diff --git a/tests/runtime/test_application_runtime.py b/tests/runtime/test_application_runtime.py
index 1a1df315..881f8751 100644
--- a/tests/runtime/test_application_runtime.py
+++ b/tests/runtime/test_application_runtime.py
@@ -531,20 +531,18 @@ async def test_close_retries_real_workflow_persistence_without_losing_latest_sta
with patch.object(persistence_module.threading, "Timer"):
store = SessionStore(storage_path=str(store_path))
- store.record_message_id(
+ store.record_outbound_message_id(
"telegram",
"chat_1",
"old",
- direction="in",
- kind="prompt",
+ "status",
)
store.flush_pending_save()
- store.record_message_id(
+ store.record_outbound_message_id(
"telegram",
"chat_1",
"latest",
- direction="in",
- kind="prompt",
+ "status",
)
workflow = MessagingWorkflow(outbound, cli_manager, store)
runtime._messaging_runtime = messaging
@@ -563,13 +561,13 @@ async def test_close_retries_real_workflow_persistence_without_losing_latest_sta
assert runtime._cli_manager is cli_manager
assert runtime.is_closed is False
assert store.dirty is True
- assert store.get_message_ids_for_chat("telegram", "chat_1") == [
+ assert store.get_clearable_message_ids_for_chat("telegram", "chat_1") == [
"old",
"latest",
]
- assert SessionStore(storage_path=str(store_path)).get_message_ids_for_chat(
- "telegram", "chat_1"
- ) == ["old"]
+ assert SessionStore(
+ storage_path=str(store_path)
+ ).get_clearable_message_ids_for_chat("telegram", "chat_1") == ["old"]
assert await runtime.close() is True
@@ -578,10 +576,12 @@ async def test_close_retries_real_workflow_persistence_without_losing_latest_sta
assert runtime._cli_manager is None
assert runtime.is_closed is True
assert store.dirty is False
- assert SessionStore(storage_path=str(store_path)).get_message_ids_for_chat(
- "telegram",
- "chat_1",
- ) == ["old", "latest"]
+ assert SessionStore(
+ storage_path=str(store_path)
+ ).get_clearable_message_ids_for_chat("telegram", "chat_1") == [
+ "old",
+ "latest",
+ ]
assert events == [
"messaging.quiesce",
"messaging.quiesce",
diff --git a/uv.lock b/uv.lock
index 734f0f16..aa08cd8e 100644
--- a/uv.lock
+++ b/uv.lock
@@ -561,7 +561,7 @@ wheels = [
[[package]]
name = "free-claude-code"
-version = "3.5.12"
+version = "3.5.13"
source = { editable = "." }
dependencies = [
{ name = "aiohttp" },