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

Give messaging clear exact subtree semantics (#1072)

Ali Khokhar3fba1c6fc3a6
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md
index 791344d7..34dbca1c 100644
--- a/ARCHITECTURE.md
+++ b/ARCHITECTURE.md
@@ -911,27 +911,26 @@ when voice does not use it.
[messaging/workflow.py](src/free_claude_code/messaging/workflow.py) contains `MessagingWorkflow`, the
platform-agnostic coordinator. It owns dependencies, render settings, the
-state-transaction lock, admission epoch, stop/clear side effects, and
-shutdown-visible state. Each inbound turn snapshots the epoch before external
-status I/O and rechecks it while committing admission; global `/stop` and
-`/clear` advance the epoch so an older provisional turn is discarded instead of
-crossing that boundary. Before taking the workflow lock, those global commands
-cancel and join every older voice handoff; they then cancel any tree that won
-admission during the join. Reply-scoped commands first join the matching voice
-claim and then resolve its authoritative tree, so either the voice cancellation
-or the admitted-tree transition wins and the same scoped request is never
-double-counted. Stop operations return one typed outcome after assigning every
-terminal status owner. The outcome records which message scopes own terminal
+state-transaction lock, global stop generation, per-chat clear generations,
+stop/clear side effects, and shutdown-visible state. Each inbound turn snapshots
+both applicable generations before external status I/O and rechecks them while
+committing admission. Global `/stop` invalidates every older provisional turn;
+standalone `/clear` invalidates only the invoking `MessageScope`. Before taking
+the workflow lock, those commands cancel and join their applicable older voice
+handoffs; they then cancel any matching tree that won admission during the join.
+Reply-scoped commands first join the matching voice claim and then apply an exact
+reference transition, so either the voice cancellation or admitted-tree
+transition wins without double-counting. Stop operations return one typed
+outcome after assigning every terminal status owner. The outcome records which message scopes own terminal
status feedback. Existing task statuses are the sole success UI when every
affected status is in the invoking scope; the command adapter sends a message
for a no-op, any cross-scope work, or the rare voice cancellation that wins
-before a status ID is bound. Epoch validation, tree admission, processor
+before a status ID is bound. Generation validation, tree admission, processor
publication, and persistence of the detached snapshot complete as one
workflow-owned operation; caller cancellation is restored only after that
transaction finishes. Stop and clear use the same completion-driven boundary,
-so caller cancellation cannot
-leave a committed state transition without its remaining persistence or CLI
-cleanup. At startup it restores and normalizes
+so caller cancellation cannot leave a committed state transition without its
+remaining cancellation and persistence cleanup. At startup it restores and normalizes
persisted state before ingress begins, then repairs interrupted platform
statuses after outbound delivery starts. Diagnostic detail policy is captured
at construction and passed into the processor; messaging does not read global
@@ -940,25 +939,27 @@ 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
+workflow. The workflow owns platform rendering and snapshots the notice chat's
+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;
+the ID only if no standalone clear in that chat 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 clearable-message log so a later `/clear` can
+attempts to restore the ID to the current managed-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 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/turn_intake.py](src/free_claude_code/messaging/turn_intake.py) owns slash command dispatch,
+status-echo filtering, initial status messages, and rendering detached frozen
+admission/queue effects. The workflow records each accepted inbound prompt,
+voice note, or command before intake performs external status I/O. 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 starts an independent root. A previously resolved exact parent that a
+concurrent clear removes is instead rejected as `PARENT_REMOVED`; intake then
+best-effort deletes both the stale child prompt and its provisional status.
+Duplicate delivery deletes only its provisional status.
[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,
@@ -985,7 +986,13 @@ depend on the concrete workflow object or on platform SDK runtimes.
`MessageTree` aggregate. Its lock is private, and complete operations own every
graph/queue/claim invariant: add-and-admit, enqueue-or-claim,
finish-and-claim-next, semantic state writes, cancellation, and atomic branch
-removal. `TreeIdentity` is `(platform, chat_id, root_message_id)`, because
+removal. Logical `parent_id` owns execution/session ancestry, while
+`parent_reference_id` records the exact prompt or FCC status that received the
+platform reply. The aggregate derives literal reference adjacency from those
+canonical fields instead of maintaining a second graph. Removing a prompt
+therefore removes its status and every literal descendant; removing a status
+preserves its prompt and prompt-level siblings while invalidating that prompt's
+session. `TreeIdentity` is `(platform, chat_id, root_message_id)`, because
platform message IDs are not globally unique. Every execution receives a fresh
opaque claim ID, so a task from an older runtime generation cannot mutate or
collide with a re-admitted tree. Active execution ownership is separate from the
@@ -1008,16 +1015,16 @@ transition-owned snapshots. Claim completion re-enters that same lock: the
manager verifies the exact aggregate is still published and publishes any
successor task slot before a competing detach can commit. Cancellation and
removal entrypoints finish their exact transition despite caller cancellation,
-so a committed detach cannot lose its UI or persistence result. Reply `/clear`
-is one cancel-and-detach transition before platform I/O; global clear atomically
-detaches every aggregate before
-task draining. Reply `/stop` cancels exactly one request; its matching finisher
+so a committed detach cannot lose its persistence result. Reply `/clear` is one
+exact-reference cancel-and-detach transition before platform I/O; standalone
+clear atomically detaches every aggregate in the invoking scope before 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. 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.
+Global `/stop` drains every queue instead, and reply `/clear` removes the selected
+literal message subtree before any survivor can advance. Separate scopes and
+trees still progress independently. Subtree transitions return exact reference
+IDs for both repository unindexing and authorized platform deletion, including
+user-authored messages selected by the explicit command.
[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
@@ -1045,8 +1052,11 @@ status-message lookup state, and
[messaging/trees/snapshot.py](src/free_claude_code/messaging/trees/snapshot.py) owns typed persisted
conversation snapshots. New snapshots serialize scoped trees as a list, while
loading derives scope from existing pre-scope `sessions.json` tree roots. Nodes
-persist only their canonical parent relation; runtime child indexes are rebuilt
-on restore, and transport ingress payloads do not leak into aggregate storage.
+persist logical and exact-reference parent relations; runtime child indexes are
+rebuilt on restore, and transport ingress payloads do not leak into aggregate
+storage. Old snapshots without an exact parent reference attach conservatively
+to the logical parent prompt. A cleared optional status is valid only for an
+inert node; runnable restored nodes must still have a status.
A malformed tree carrying neither current scope nor legacy root ingress is
reported and skipped because assigning it to an inferred chat would violate the
same ownership boundary.
@@ -1063,24 +1073,24 @@ Timer-triggered saves are best effort and leave the store dirty on failure;
explicit flushes and authoritative writes propagate failure while preserving
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
-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.
+Standalone `/clear` detaches and drains only the invoking scope, then writes an
+authoritative scoped removal while other chats remain intact. Per-chat deletion
+ownership lives in
+[messaging/session/managed_message_log.py](src/free_claude_code/messaging/session/managed_message_log.py).
+The registry accepts managed inbound prompts, voice notes, and commands as well
+as FCC output. It migrates legacy `message_log` entries and persists the final
+shape as `managed_messages`. Startup notices use the same registry. An incoming
+standalone `/clear` defers insertion because the command handler already owns its
+ID on success; this prevents the command from evicting an older deletion target
+when an explicit cap is configured. Failed or cancelled clear attempts record
+the command before propagating so a later clear can discover it.
+
+`/clear` commits FCC state cleanup first and then best-effort deletes the exact
+authorized message-ID set through the list-based outbound port. Standalone clear
+deletes every tracked user and FCC message in its chat; reply clear deletes only
+the selected literal reply subtree plus its command. Discord/Telegram can still
+reject individual deletions for platform reasons such as permissions, age, or
+missing messages; such failures never restore cleared FCC state.
```mermaid
sequenceDiagram
diff --git a/README.md b/README.md
index ea83544a..940d19d7 100644
--- a/README.md
+++ b/README.md
@@ -291,7 +291,9 @@ Configure integrations from **Admin UI → Messaging**, then click **Validate**
<summary><strong>Discord bot</strong></summary>
1. Create a bot in the [Discord Developer Portal](https://discord.com/developers/applications).
-2. Enable **Message Content Intent** and invite it with read, send, and message-history permissions.
+2. Enable **Message Content Intent** and invite it with read, send,
+ message-history, and **Manage Messages** permissions so `/clear` can remove
+ user prompts.
3. Set **Messaging Platform** to **discord**.
4. Enter **Discord Bot Token**, **Allowed Discord Channels**, and an absolute **Allowed Directory**.
5. Apply the settings and restart the server if requested.
@@ -303,6 +305,7 @@ Configure integrations from **Admin UI → Messaging**, then click **Validate**
1. Create a bot with [@BotFather](https://t.me/BotFather).
2. Get your numeric user ID from [@userinfobot](https://t.me/userinfobot).
+ In groups, grant the bot permission to delete messages.
3. Set **Messaging Platform** to **telegram**.
4. Enter **Telegram Bot Token**, **Allowed Telegram User ID**, and an absolute **Allowed Directory**.
5. Apply the settings and restart the server if requested.
@@ -310,11 +313,11 @@ 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 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.
+FCC state and removes every tracked message in that chat—including user prompts,
+voice notes, FCC replies, Telegram's online notice, and the clear command itself.
+`/stats` shows session state. Reply with `/stop` to cancel only that request while
+other queued requests continue. Reply with `/clear` to delete the selected message
+and its literal platform reply subtree while preserving its ancestors and siblings.
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 db9af0d8..d2e241b6 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
[project]
name = "free-claude-code"
-version = "3.5.14"
+version = "3.5.15"
description = "Local proxy connecting Claude Code and Codex to OpenAI-compatible AI providers"
readme = "README.md"
requires-python = ">=3.14.0"
diff --git a/smoke/README.md b/smoke/README.md
index c9129677..4087a00a 100644
--- a/smoke/README.md
+++ b/smoke/README.md
@@ -59,7 +59,7 @@ Default targets do not send real bot messages or load voice backends:
| `clients` | VS Code and JetBrains protocol payloads | configured provider |
| `config` | env precedence, removed-env migration, proxy/timeouts | none |
| `extensibility` | provider runtime and platform factory construction | none |
-| `messaging` | fake Discord/Telegram full flow, commands, trees, persistence, voice cancel | none |
+| `messaging` | fake Discord/Telegram full flow, literal clear scopes, trees, persistence, voice cancel | none |
| `providers` | multi-turn text, adaptive thinking history, tools, disconnect, errors | configured providers, optional `FCC_SMOKE_MODEL_*` |
| `tools` | forced tool_use and tool_result continuation | tool-capable configured provider |
| `rate_limit` | disconnect cleanup and follow-up request | configured provider |
diff --git a/smoke/capabilities.py b/smoke/capabilities.py
index d32680d4..9193da98 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",
- "state cleanup with status-owned UI and user-authored messages preserved",
+ "chat-wide cleanup or literal reply-subtree deletion",
"terminal status edit, no-op feedback, or best-effort platform cleanup",
(
"tests/messaging/test_handler.py",
@@ -382,6 +382,7 @@ CAPABILITY_CONTRACTS: tuple[CapabilityContract, ...] = (
),
(
"test_messaging_commands_stop_clear_stats_e2e",
+ "test_reply_clear_uses_literal_platform_subtree_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 27c929fa..dff65b85 100644
--- a/smoke/features.py
+++ b/smoke/features.py
@@ -438,7 +438,7 @@ FEATURE_INVENTORY: tuple[FeatureCoverage, ...] = (
),
FeatureCoverage(
"messaging_commands",
- "Messaging commands mutate FCC state while preserving user-authored messages",
+ "Messaging commands clear exact reply subtrees or whole managed chats",
"public_surface",
(
"tests/messaging/test_handler.py",
@@ -448,6 +448,7 @@ FEATURE_INVENTORY: tuple[FeatureCoverage, ...] = (
(),
(
"test_messaging_commands_stop_clear_stats_e2e",
+ "test_reply_clear_uses_literal_platform_subtree_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/lib/e2e.py b/smoke/lib/e2e.py
index 872c7ca8..6bdd216b 100644
--- a/smoke/lib/e2e.py
+++ b/smoke/lib/e2e.py
@@ -440,6 +440,7 @@ class FakePlatform:
scope=scope,
voice_message_id=voice_message_id,
status_message_id=status_message_id,
+ delete_message_ids=frozenset({voice_message_id, status_message_id}),
)
self._pending_voice[(scope, voice_message_id)] = result
self._pending_voice[(scope, status_message_id)] = result
@@ -453,7 +454,19 @@ class FakePlatform:
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
+ delete_message_ids = {result.voice_message_id, result.status_message_id}
+ if reply_id == result.status_message_id:
+ delete_message_ids = {result.status_message_id}
+ return VoiceCancellationResult(
+ scope=result.scope,
+ voice_message_id=result.voice_message_id,
+ status_message_id=result.status_message_id,
+ delete_message_ids=frozenset(
+ message_id
+ for message_id in delete_message_ids
+ if message_id is not None
+ ),
+ )
async def cancel_all_pending_voices(
self,
@@ -467,6 +480,23 @@ class FakePlatform:
self._pending_voice.clear()
return results
+ async def cancel_pending_voices_in_scope(
+ self,
+ scope: MessageScope,
+ ) -> tuple[VoiceCancellationResult, ...]:
+ results = tuple(
+ {
+ result.voice_message_id: result
+ for (entry_scope, _reference_id), result in self._pending_voice.items()
+ if entry_scope == scope
+ }.values()
+ )
+ for result in results:
+ 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 results
+
@property
def pending_voice_count(self) -> int:
return len(
diff --git a/smoke/product/test_messaging_product_live.py b/smoke/product/test_messaging_product_live.py
index 3e5ff94b..eb4ffd0f 100644
--- a/smoke/product/test_messaging_product_live.py
+++ b/smoke/product/test_messaging_product_live.py
@@ -74,17 +74,89 @@ async def test_messaging_commands_stop_clear_stats_e2e(
await driver.send("/stats", message_id="stats_1")
await driver.send("/stop", message_id="stop_1", reply_to=root.message_id)
await driver.send("/clear", message_id="clear_1", reply_to=root.message_id)
+ global_prompt = await driver.send("clear globally", message_id="global_prompt")
+ global_status_id = driver.platform.sent[-1]["message_id"]
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 {root_status_id, "clear_1", "clear_all"} <= deleted
- assert root.message_id not in deleted
+ assert {
+ root.message_id,
+ root_status_id,
+ global_prompt.message_id,
+ global_status_id,
+ "clear_1",
+ "clear_all",
+ } <= deleted
assert driver.session_store.load_conversation_snapshot().trees == {}
[email protected]("platform_name", ["discord", "telegram"])
+async def test_reply_clear_uses_literal_platform_subtree_e2e(
+ platform_name: str,
+ tmp_path,
+) -> None:
+ driver = FakePlatformDriver(platform_name, tmp_path)
+ root = await driver.send("root", message_id="root")
+ root_status = driver.platform.sent[-1]["message_id"]
+ sibling = await driver.send(
+ "prompt sibling",
+ message_id="sibling",
+ reply_to=root.message_id,
+ )
+ sibling_status = driver.platform.sent[-1]["message_id"]
+ descendant = await driver.send(
+ "status descendant",
+ message_id="descendant",
+ reply_to=root_status,
+ )
+ descendant_status = driver.platform.sent[-1]["message_id"]
+
+ await driver.send(
+ "/clear",
+ message_id="clear-status",
+ reply_to=root_status,
+ )
+
+ deleted = {entry["message_id"] for entry in driver.platform.deletes}
+ assert {
+ root_status,
+ descendant.message_id,
+ descendant_status,
+ "clear-status",
+ } <= deleted
+ assert {root.message_id, sibling.message_id, sibling_status}.isdisjoint(deleted)
+ root_view = await driver.workflow.tree_queue.get_node(root.scope, root.message_id)
+ sibling_view = await driver.workflow.tree_queue.get_node(
+ sibling.scope, sibling.message_id
+ )
+ assert root_view is not None and root_view.state is MessageState.ERROR
+ assert root_view.session_id is None
+ assert sibling_view is not None and sibling_view.state is MessageState.COMPLETED
+ assert (
+ await driver.workflow.tree_queue.get_node(
+ descendant.scope, descendant.message_id
+ )
+ is None
+ )
+
+ await driver.send(
+ "fresh continuation",
+ message_id="fresh",
+ reply_to=root.message_id,
+ )
+ fresh_call = next(
+ call
+ for session in driver.cli_manager.sessions
+ for call in session.calls
+ if call["prompt"] == "fresh continuation"
+ )
+ assert fresh_call["session_id"] is None
+
+
@pytest.mark.asyncio
async def test_messaging_startup_notice_is_clearable_e2e(tmp_path) -> None:
first_driver = FakePlatformDriver("telegram", tmp_path)
@@ -113,7 +185,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_clearable_message_ids_for_chat(
+ assert driver.session_store.get_tracked_message_ids_for_chat(
scope.platform, scope.chat_id
) == [first_startup_id, second_startup_id]
@@ -122,7 +194,7 @@ 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_clearable_message_ids_for_chat(
+ driver.session_store.get_tracked_message_ids_for_chat(
scope.platform, scope.chat_id
)
== []
@@ -335,7 +407,7 @@ async def test_restart_restore_and_session_persistence_e2e(tmp_path) -> None:
session_file = tmp_path / "telegram-sessions.json"
payload = json.loads(session_file.read_text(encoding="utf-8"))
assert payload["conversation"]["trees"]
- assert payload["message_log"]
+ assert payload["managed_messages"]
restored = FakePlatformDriver("telegram", tmp_path)
restored.platform.continue_message_sequence_after(first.platform)
@@ -401,11 +473,10 @@ 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_status_1", "clear_voice"} <= deleted
- assert "voice_msg_1" not in deleted
+ assert {"voice_msg_1", "voice_status_1", "clear_voice"} <= 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
+ assert "Voice note cancelled" not in sent_text
assert len(driver.platform.sent) == sent_before_stop
assert any(
edit["message_id"] == "voice_status_2" and "Stopped" in edit["text"]
diff --git a/src/free_claude_code/config/admin/manifest.py b/src/free_claude_code/config/admin/manifest.py
index 10e8ea03..1c026a8d 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 Clearable Messages Per Chat",
+ "Max Tracked 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 d11379f2..5a46f521 100644
--- a/src/free_claude_code/messaging/command_context.py
+++ b/src/free_claude_code/messaging/command_context.py
@@ -11,10 +11,10 @@ from .transcript import RenderCtx
@dataclass(frozen=True, slots=True)
class ReplyClearResult:
- """Customer-facing result of clearing one replied-to owner."""
+ """Customer-facing result of clearing one literal reply subtree."""
- clearable_message_ids: frozenset[str]
- tree_cleared: bool
+ delete_message_ids: frozenset[str]
+ tree_matched: bool
@dataclass(frozen=True, slots=True)
@@ -69,20 +69,20 @@ class MessagingCommandContext(Protocol):
scope: MessageScope,
reply_id: str,
) -> ReplyClearResult | None:
- """Clear the exact voice/tree owner of a replied-to message."""
+ """Clear the literal subtree rooted at a replied-to message."""
...
- async def clear_all_state(self, platform: str, chat_id: str) -> frozenset[str]:
- """Clear FCC state and return authorized invoking-chat deletion IDs."""
+ async def clear_chat(self, platform: str, chat_id: str) -> frozenset[str]:
+ """Clear one chat and return every tracked platform message ID."""
...
- def forget_clearable_message_ids(
+ def forget_tracked_message_ids(
self,
platform: str,
chat_id: str,
message_ids: set[str],
) -> None:
- """Forget deleted platform message IDs authorized for clear."""
+ """Forget platform message IDs removed from the managed conversation."""
...
def record_outgoing_message(
@@ -92,7 +92,7 @@ class MessagingCommandContext(Protocol):
msg_id: str | None,
kind: str,
) -> bool:
- """Record an outgoing platform message ID and report clear-log ownership."""
+ """Record an outgoing platform message ID and report registry ownership."""
...
diff --git a/src/free_claude_code/messaging/commands.py b/src/free_claude_code/messaging/commands.py
index 1e7bdf09..fd042ca3 100644
--- a/src/free_claude_code/messaging/commands.py
+++ b/src/free_claude_code/messaging/commands.py
@@ -112,6 +112,7 @@ async def _delete_message_ids(
else:
numeric.append((n, mid))
numeric.sort(reverse=True)
+ non_numeric.sort(reverse=True)
ordered = [mid for _, mid in numeric] + non_numeric
failed = 0
@@ -139,8 +140,8 @@ async def handle_clear_command(
"""
Handle /clear command.
- Reply-scoped: reply to a message to clear that branch (node + descendants).
- Standalone: global clear (stop all, reset state, delete invoking-chat history).
+ Reply-scoped: delete the selected message and its literal reply subtree.
+ Standalone: reset and delete the invoking chat's managed conversation.
"""
if incoming.is_reply() and incoming.reply_to_message_id:
result = await handler.clear_reply(
@@ -161,31 +162,18 @@ async def handle_clear_command(
)
return
- clearable_message_ids = set(result.clearable_message_ids)
+ delete_message_ids = set(result.delete_message_ids)
if incoming.message_id is not None:
- clearable_message_ids.add(str(incoming.message_id))
- await _delete_message_ids(handler, incoming.chat_id, clearable_message_ids)
- handler.forget_clearable_message_ids(
+ delete_message_ids.add(str(incoming.message_id))
+ await _delete_message_ids(handler, incoming.chat_id, delete_message_ids)
+ handler.forget_tracked_message_ids(
incoming.platform,
incoming.chat_id,
- clearable_message_ids,
+ delete_message_ids,
)
- if not result.tree_cleared:
- msg_id = await handler.outbound.queue_send_message(
- incoming.chat_id,
- handler.format_status("🗑", "Cleared.", "Voice note cancelled."),
- fire_and_forget=False,
- message_thread_id=incoming.message_thread_id,
- )
- handler.record_outgoing_message(
- incoming.platform,
- incoming.chat_id,
- msg_id,
- "command",
- )
return
- msg_ids = set(await handler.clear_all_state(incoming.platform, incoming.chat_id))
+ msg_ids = set(await handler.clear_chat(incoming.platform, incoming.chat_id))
# Also delete the command message itself.
if incoming.message_id is not None:
diff --git a/src/free_claude_code/messaging/models.py b/src/free_claude_code/messaging/models.py
index 0eb291eb..07a7541c 100644
--- a/src/free_claude_code/messaging/models.py
+++ b/src/free_claude_code/messaging/models.py
@@ -13,6 +13,14 @@ class MessageScope:
chat_id: str
+@dataclass(frozen=True, slots=True)
+class AdmissionToken:
+ """Generations that must still match when a turn commits."""
+
+ stop_generation: int
+ clear_generation: int
+
+
@dataclass
class IncomingMessage:
"""
diff --git a/src/free_claude_code/messaging/node_runner.py b/src/free_claude_code/messaging/node_runner.py
index f67fcbc3..ad4bfa3f 100644
--- a/src/free_claude_code/messaging/node_runner.py
+++ b/src/free_claude_code/messaging/node_runner.py
@@ -345,9 +345,10 @@ class MessagingNodeRunner:
node_id=node_id,
)
logger.warning(f"HANDLER: Task cancelled for node {node_id}")
- if exc.args and exc.args[0] is CancellationReason.STOP:
+ reason = exc.args[0] if exc.args else None
+ if reason is CancellationReason.STOP:
await update_ui(self._format_status("⏹", "Stopped.", None), force=True)
- else:
+ elif reason is not CancellationReason.CLEAR:
transcript.apply({"type": "error", "message": "Task was cancelled"})
await update_ui(
self._format_status("❌", "Cancelled", None), force=True
diff --git a/src/free_claude_code/messaging/platforms/discord.py b/src/free_claude_code/messaging/platforms/discord.py
index eba53331..1a77b5e9 100644
--- a/src/free_claude_code/messaging/platforms/discord.py
+++ b/src/free_claude_code/messaging/platforms/discord.py
@@ -150,6 +150,13 @@ class DiscordRuntime:
"""Cancel every pending voice transcription and handoff."""
return await self._voice_flow.cancel_all_pending_voices()
+ async def cancel_pending_voices_in_scope(
+ self,
+ scope: MessageScope,
+ ) -> tuple[VoiceCancellationResult, ...]:
+ """Cancel pending voice transcriptions belonging to one chat."""
+ return await self._voice_flow.cancel_pending_voices_in_scope(scope)
+
async def _handle_voice_note(
self, message: Any, attachment: Any, channel_id: str
) -> bool:
diff --git a/src/free_claude_code/messaging/platforms/ports.py b/src/free_claude_code/messaging/platforms/ports.py
index 318b01a3..4e5c9af8 100644
--- a/src/free_claude_code/messaging/platforms/ports.py
+++ b/src/free_claude_code/messaging/platforms/ports.py
@@ -82,6 +82,11 @@ class VoiceCancellation(Protocol):
self,
) -> tuple[VoiceCancellationResult, ...]: ...
+ async def cancel_pending_voices_in_scope(
+ self,
+ scope: MessageScope,
+ ) -> tuple[VoiceCancellationResult, ...]: ...
+
@dataclass(frozen=True, slots=True)
class MessagingPlatformComponents:
diff --git a/src/free_claude_code/messaging/platforms/telegram.py b/src/free_claude_code/messaging/platforms/telegram.py
index 900f2e0f..4556b7c8 100644
--- a/src/free_claude_code/messaging/platforms/telegram.py
+++ b/src/free_claude_code/messaging/platforms/telegram.py
@@ -95,6 +95,13 @@ class TelegramRuntime:
"""Cancel every pending voice transcription and handoff."""
return await self._voice_flow.cancel_all_pending_voices()
+ async def cancel_pending_voices_in_scope(
+ self,
+ scope: MessageScope,
+ ) -> tuple[VoiceCancellationResult, ...]:
+ """Cancel pending voice transcriptions belonging to one chat."""
+ return await self._voice_flow.cancel_pending_voices_in_scope(scope)
+
async def start(self) -> None:
"""Initialize and connect to Telegram."""
if not self.bot_token:
diff --git a/src/free_claude_code/messaging/platforms/voice_flow.py b/src/free_claude_code/messaging/platforms/voice_flow.py
index e8053a2e..c8b42089 100644
--- a/src/free_claude_code/messaging/platforms/voice_flow.py
+++ b/src/free_claude_code/messaging/platforms/voice_flow.py
@@ -134,6 +134,13 @@ class VoiceNoteFlow:
"""Cancel every pending voice transcription and published handoff."""
return await self._pending_voice.cancel_all()
+ async def cancel_pending_voices_in_scope(
+ self,
+ scope: MessageScope,
+ ) -> tuple[VoiceCancellationResult, ...]:
+ """Cancel pending voice transcriptions belonging to one chat."""
+ return await self._pending_voice.cancel_scope(scope)
+
async def handle(
self,
request: VoiceNoteRequest,
diff --git a/src/free_claude_code/messaging/session/clearable_message_log.py b/src/free_claude_code/messaging/session/managed_message_log.py
similarity index 61%
rename from src/free_claude_code/messaging/session/clearable_message_log.py
rename to src/free_claude_code/messaging/session/managed_message_log.py
index 1ecb4306..c62e2adc 100644
--- a/src/free_claude_code/messaging/session/clearable_message_log.py
+++ b/src/free_claude_code/messaging/session/managed_message_log.py
@@ -1,11 +1,11 @@
-"""Persist platform messages that `/clear` is authorized to delete."""
+"""Persist platform messages belonging to FCC-managed conversations."""
from datetime import UTC, datetime
from typing import Any
-class ClearableMessageLog:
- """Track FCC output and explicit clear-command IDs in insertion order."""
+class ManagedMessageLog:
+ """Track managed inbound and outbound messages in insertion order."""
def __init__(self, *, cap: int | None = None) -> None:
self._items: dict[str, list[dict[str, Any]]] = {}
@@ -17,8 +17,8 @@ class ClearableMessageLog:
return self._cap
@classmethod
- def from_json(cls, raw_log: Any, *, cap: int | None = None) -> ClearableMessageLog:
- """Load clearable IDs while dropping legacy user-content entries."""
+ def from_json(cls, raw_log: Any, *, cap: int | None = None) -> ManagedMessageLog:
+ """Load current and legacy message-log entries."""
log = cls(cap=cap)
if not isinstance(raw_log, dict):
return log
@@ -29,11 +29,9 @@ class ClearableMessageLog:
if not isinstance(item, dict):
continue
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":
+ if message_id is None or direction not in {"in", "out"} or not kind:
continue
log._append(
chat_key,
@@ -47,46 +45,31 @@ class ClearableMessageLog:
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_outbound(
+ def record(
self,
*,
platform: str,
chat_id: str,
message_id: str,
+ direction: str,
kind: str,
) -> bool:
- """Record one FCC-authored platform message."""
+ """Record one managed platform message."""
+ if direction not in {"in", "out"}:
+ raise ValueError("Managed message direction must be 'in' or 'out'")
+ if not kind:
+ raise ValueError("Managed message kind cannot be empty")
return self._append(
make_chat_key(platform, chat_id),
str(message_id),
ts=datetime.now(UTC).isoformat(),
- direction="out",
+ direction=direction,
kind=str(kind),
)
- 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"))
- for item in self._items.get(chat_key, [])
- if item.get("message_id") is not None
- ]
+ return [str(item["message_id"]) for item in self._items.get(chat_key, [])]
def remove_ids(self, platform: str, chat_id: str, message_ids: set[str]) -> bool:
chat_key = make_chat_key(platform, chat_id)
@@ -94,25 +77,24 @@ class ClearableMessageLog:
return False
before_count = len(self._items[chat_key])
- self._items[chat_key] = [
+ retained = [
item
for item in self._items[chat_key]
- if str(item.get("message_id")) not in message_ids
+ if str(item["message_id"]) not in message_ids
]
- if not self._items[chat_key]:
- self._items.pop(chat_key, None)
- self._ids.pop(chat_key, None)
+ if retained:
+ self._items[chat_key] = retained
+ self._ids[chat_key] = {str(item["message_id"]) for item in retained}
else:
- self._ids[chat_key] = {
- str(item.get("message_id"))
- for item in self._items[chat_key]
- if item.get("message_id") is not None
- }
- return len(self._items.get(chat_key, [])) != before_count
+ self._items.pop(chat_key)
+ self._ids.pop(chat_key, None)
+ return len(retained) != before_count
- def clear(self) -> None:
- self._items.clear()
- self._ids.clear()
+ def clear_chat(self, platform: str, chat_id: str) -> bool:
+ chat_key = make_chat_key(platform, chat_id)
+ removed = self._items.pop(chat_key, None) is not None
+ self._ids.pop(chat_key, None)
+ return removed
def _append(
self,
@@ -144,12 +126,9 @@ class ClearableMessageLog:
items = self._items.get(chat_key, [])
if len(items) <= self._cap:
return
- self._items[chat_key] = items[-self._cap :]
- self._ids[chat_key] = {
- str(item.get("message_id"))
- for item in self._items[chat_key]
- if item.get("message_id") is not None
- }
+ retained = items[-self._cap :]
+ self._items[chat_key] = retained
+ self._ids[chat_key] = {str(item["message_id"]) for item in retained}
def make_chat_key(platform: str, chat_id: str) -> str:
diff --git a/src/free_claude_code/messaging/session/store.py b/src/free_claude_code/messaging/session/store.py
index 5260827d..674aa720 100644
--- a/src/free_claude_code/messaging/session/store.py
+++ b/src/free_claude_code/messaging/session/store.py
@@ -5,19 +5,20 @@ from copy import deepcopy
from loguru import logger
+from free_claude_code.messaging.models import MessageScope
from free_claude_code.messaging.trees import (
ConversationSnapshot,
TreeIdentity,
TreeSnapshot,
)
-from .clearable_message_log import ClearableMessageLog
+from .managed_message_log import ManagedMessageLog
from .persistence import DebouncedJsonPersistence
class SessionStore:
"""
- Persistent storage for conversation snapshots and clearable platform messages.
+ Persistent storage for conversation snapshots and managed 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
@@ -28,12 +29,12 @@ class SessionStore:
self,
storage_path: str = "sessions.json",
*,
- message_log_cap: int | None = None,
+ managed_message_cap: int | None = None,
) -> None:
self.storage_path = storage_path
self._lock = threading.RLock()
self._conversation = ConversationSnapshot()
- self._clearable_messages = ClearableMessageLog(cap=message_log_cap)
+ self._managed_messages = ManagedMessageLog(cap=managed_message_cap)
self._dirty = False
self._persistence = DebouncedJsonPersistence(
storage_path,
@@ -63,15 +64,18 @@ class SessionStore:
with self._lock:
self._conversation = ConversationSnapshot.from_json(conversation_data)
- self._clearable_messages = ClearableMessageLog.from_json(
- data.get("message_log", {}) if isinstance(data, dict) else {},
- cap=self._clearable_messages.cap,
+ raw_messages = {}
+ if isinstance(data, dict):
+ raw_messages = data.get("managed_messages", data.get("message_log", {}))
+ self._managed_messages = ManagedMessageLog.from_json(
+ raw_messages,
+ cap=self._managed_messages.cap,
)
message_count = sum(
- len(items) for items in self._clearable_messages.to_json().values()
+ len(items) for items in self._managed_messages.to_json().values()
)
logger.info(
- "Loaded {} trees and {} clearable message IDs from {}",
+ "Loaded {} trees and {} managed message IDs from {}",
len(self._conversation.trees),
message_count,
self.storage_path,
@@ -81,7 +85,7 @@ class SessionStore:
with self._lock:
return {
"conversation": self._conversation.to_json(),
- "message_log": self._clearable_messages.to_json(),
+ "managed_messages": self._managed_messages.to_json(),
}
def load_conversation_snapshot(self) -> ConversationSnapshot:
@@ -107,53 +111,38 @@ class SessionStore:
def flush_pending_save(self) -> None:
self._persistence.flush()
- def record_outbound_message_id(
+ def record_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._clearable_messages.record_outbound(
+ recorded = self._managed_messages.record(
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 record_clear_command_id(
- self,
- platform: str,
- chat_id: str,
- message_id: str,
- ) -> None:
- if message_id is None:
- return
- with self._lock:
- 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(
+ def get_tracked_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))
+ return self._managed_messages.ids_for_chat(str(platform), str(chat_id))
- def forget_clearable_message_ids(
+ def forget_tracked_message_ids(
self, platform: str, chat_id: str, message_ids: set[str]
) -> None:
with self._lock:
- removed = self._clearable_messages.remove_ids(
+ removed = self._managed_messages.remove_ids(
str(platform),
str(chat_id),
{str(message_id) for message_id in message_ids},
@@ -161,16 +150,11 @@ class SessionStore:
if removed:
self._persistence.schedule_save()
- def clear_all(self) -> None:
- with self._lock:
- self._conversation = ConversationSnapshot()
- self._clearable_messages.clear()
- self._write_current_state()
-
- def clear_conversation_snapshot(self) -> None:
- """Authoritatively clear trees while preserving newer message logs."""
+ def clear_scope(self, scope: MessageScope) -> None:
+ """Authoritatively clear one platform chat while preserving others."""
with self._lock:
- self._conversation = ConversationSnapshot()
+ self._conversation = self._conversation.without_scope(scope)
+ self._managed_messages.clear_chat(scope.platform, scope.chat_id)
self._write_current_state()
def _write_current_state(self) -> None:
diff --git a/src/free_claude_code/messaging/trees/__init__.py b/src/free_claude_code/messaging/trees/__init__.py
index f911769f..318776f4 100644
--- a/src/free_claude_code/messaging/trees/__init__.py
+++ b/src/free_claude_code/messaging/trees/__init__.py
@@ -2,14 +2,15 @@
from .identity import TreeIdentity
from .manager import TreeQueueManager
-from .node import MessageState
+from .node import MessageReferenceKind, MessageState
from .snapshot import ConversationSnapshot, TreeSnapshot
from .transitions import (
- BranchRemovalResult,
+ AdmissionRejection,
CancellationReason,
CancellationResult,
CancellationUiOwner,
FailureResult,
+ MessageSubtreeRemovalResult,
NodeClaim,
NodeUiTarget,
NodeView,
@@ -19,13 +20,15 @@ from .transitions import (
)
__all__ = [
- "BranchRemovalResult",
+ "AdmissionRejection",
"CancellationReason",
"CancellationResult",
"CancellationUiOwner",
"ConversationSnapshot",
"FailureResult",
+ "MessageReferenceKind",
"MessageState",
+ "MessageSubtreeRemovalResult",
"NodeClaim",
"NodeUiTarget",
"NodeView",
diff --git a/src/free_claude_code/messaging/trees/graph.py b/src/free_claude_code/messaging/trees/graph.py
index 008a455a..d120df08 100644
--- a/src/free_claude_code/messaging/trees/graph.py
+++ b/src/free_claude_code/messaging/trees/graph.py
@@ -4,7 +4,7 @@ from loguru import logger
from ..models import MessageScope
from .identity import TreeIdentity
-from .node import MessageNode, MessageState
+from .node import MessageNode, MessageReferenceKind, MessageState
from .snapshot import (
TreeSnapshot,
node_from_snapshot,
@@ -17,15 +17,17 @@ class MessageTreeGraph:
"""Own parent/child links, node lookup, and status-message lookup."""
def __init__(self, root_node: MessageNode) -> None:
+ if root_node.status_message_id == root_node.node_id:
+ raise ValueError("Prompt and status message IDs must be distinct")
self.root_id = root_node.node_id
self.identity = TreeIdentity(
scope=root_node.scope,
root_id=root_node.node_id,
)
self._nodes: dict[str, MessageNode] = {root_node.node_id: root_node}
- self._status_to_node: dict[str, str] = {
- root_node.status_message_id: root_node.node_id
- }
+ self._status_to_node: dict[str, str] = {}
+ if root_node.status_message_id is not None:
+ self._status_to_node[root_node.status_message_id] = root_node.node_id
def add_node(
self,
@@ -35,13 +37,19 @@ class MessageTreeGraph:
prompt: str,
status_message_id: str,
parent_id: str,
+ parent_reference_id: str,
) -> MessageNode:
if scope != self.identity.scope:
raise ValueError("A reply cannot cross platform chat boundaries")
if parent_id not in self._nodes:
raise ValueError(f"Parent node {parent_id} not found in tree")
+ parent_reference = self.resolve_reference(parent_reference_id)
+ if parent_reference is None or parent_reference[0].node_id != parent_id:
+ raise ValueError("Reply reference does not belong to its logical parent")
if node_id in self._nodes:
raise ValueError(f"Node {node_id} already exists in tree")
+ if status_message_id == node_id:
+ raise ValueError("Prompt and status message IDs must be distinct")
if node_id in self._status_to_node:
raise ValueError(f"Message reference {node_id} already exists in tree")
if status_message_id in self._status_to_node:
@@ -59,6 +67,7 @@ class MessageTreeGraph:
prompt=prompt,
status_message_id=status_message_id,
parent_id=parent_id,
+ parent_reference_id=parent_reference_id,
state=MessageState.PENDING,
)
self._nodes[node_id] = node
@@ -87,6 +96,18 @@ class MessageTreeGraph:
node_id = self._status_to_node.get(status_msg_id)
return self._nodes.get(node_id) if node_id else None
+ def resolve_reference(
+ self, reference_id: str
+ ) -> tuple[MessageNode, MessageReferenceKind] | None:
+ """Resolve an exact prompt or FCC status reference."""
+ node = self._nodes.get(reference_id)
+ if node is not None:
+ return node, MessageReferenceKind.PROMPT
+ node = self.find_node_by_status_message(reference_id)
+ if node is not None:
+ return node, MessageReferenceKind.STATUS
+ return None
+
def all_nodes(self) -> list[MessageNode]:
return list(self._nodes.values())
@@ -103,28 +124,57 @@ class MessageTreeGraph:
stack.extend(node.children_ids)
return result
- def remove_branch(self, branch_root_id: str) -> None:
- if branch_root_id not in self._nodes:
- return
+ def get_reference_descendants(self, reference_id: str) -> list[str]:
+ """Return the literal platform reply subtree rooted at a reference."""
+ if self.resolve_reference(reference_id) is None:
+ return []
+
+ children: dict[str, list[str]] = {}
+ for node in self._nodes.values():
+ if node.status_message_id is not None:
+ children.setdefault(node.node_id, []).append(node.status_message_id)
+ if node.parent_reference_id is not None:
+ children.setdefault(node.parent_reference_id, []).append(node.node_id)
- parent = self.get_parent(branch_root_id)
- removed_count = 0
- for node_id in self.get_descendants(branch_root_id):
+ result: list[str] = []
+ stack = [reference_id]
+ while stack:
+ current_id = stack.pop()
+ result.append(current_id)
+ stack.extend(children.get(current_id, ()))
+ return result
+
+ def remove_nodes(self, node_ids: set[str]) -> None:
+ """Remove an exact set of nodes after reference-subtree calculation."""
+ for node_id in node_ids:
node = self._nodes.get(node_id)
- if not node:
+ if node is None:
continue
- removed_count += 1
- del self._nodes[node_id]
- self._status_to_node.pop(node.status_message_id, None)
-
- if parent and branch_root_id in parent.children_ids:
- parent.children_ids = [
- child_id
- for child_id in parent.children_ids
- if child_id != branch_root_id
- ]
+ if node.parent_id is not None:
+ parent = self._nodes.get(node.parent_id)
+ if parent is not None:
+ parent.children_ids = [
+ child_id
+ for child_id in parent.children_ids
+ if child_id != node_id
+ ]
+ if node.status_message_id is not None:
+ self._status_to_node.pop(node.status_message_id, None)
+ self._nodes.pop(node_id, None)
+
+ def clear_status(self, node_id: str) -> None:
+ """Remove one status reference while preserving its prompt node."""
+ node = self._nodes.get(node_id)
+ if node is None or node.status_message_id is None:
+ return
+ self._status_to_node.pop(node.status_message_id, None)
+ node.clear_status()
- logger.debug("Removed branch {} ({} nodes)", branch_root_id, removed_count)
+ def all_reference_ids(self) -> set[str]:
+ """Return every prompt and live FCC status reference in the tree."""
+ references = set(self._nodes)
+ references.update(self._status_to_node)
+ return references
def snapshot(self) -> TreeSnapshot:
return TreeSnapshot(
@@ -146,10 +196,9 @@ class MessageTreeGraph:
if root_node.node_id != snapshot.root_id:
raise ValueError("Tree snapshot root key does not match its node ID")
graph = cls(root_node)
- reference_owner = {
- root_node.node_id: root_node.node_id,
- root_node.status_message_id: root_node.node_id,
- }
+ reference_owner = {root_node.node_id: root_node.node_id}
+ if root_node.status_message_id is not None:
+ reference_owner[root_node.status_message_id] = root_node.node_id
for snapshot_node_id, node_data in snapshot.nodes.items():
if snapshot_node_id == snapshot.root_id:
continue
@@ -160,9 +209,14 @@ class MessageTreeGraph:
node = node_from_snapshot(node_data, snapshot.scope)
if str(snapshot_node_id) != node.node_id:
raise ValueError("Tree snapshot node key does not match its node ID")
+ if node.status_message_id == node.node_id:
+ raise ValueError("Prompt and status message IDs must be distinct")
if node.node_id in graph._nodes:
raise ValueError(f"Duplicate node {node.node_id} in tree snapshot")
- for reference in {node.node_id, node.status_message_id}:
+ references = {node.node_id}
+ if node.status_message_id is not None:
+ references.add(node.status_message_id)
+ for reference in references:
owner = reference_owner.get(reference)
if owner is not None and owner != node.node_id:
raise ValueError(
@@ -170,15 +224,26 @@ class MessageTreeGraph:
)
reference_owner[reference] = node.node_id
graph._nodes[node.node_id] = node
- graph._status_to_node[node.status_message_id] = node.node_id
+ if node.status_message_id is not None:
+ graph._status_to_node[node.status_message_id] = node.node_id
- if root_node.parent_id is not None:
+ if root_node.parent_id is not None or root_node.parent_reference_id is not None:
raise ValueError("Tree snapshot root cannot have a parent")
for node in graph._nodes.values():
if node.node_id == graph.root_id:
continue
if node.parent_id is None or node.parent_id not in graph._nodes:
raise ValueError(f"Node {node.node_id} has no valid parent")
+ if node.parent_reference_id is None:
+ raise ValueError(f"Node {node.node_id} has no exact parent reference")
+ parent_reference = graph.resolve_reference(node.parent_reference_id)
+ if (
+ parent_reference is None
+ or parent_reference[0].node_id != node.parent_id
+ ):
+ raise ValueError(
+ f"Node {node.node_id} has an invalid exact parent reference"
+ )
graph._nodes[node.parent_id].children_ids.append(node.node_id)
if set(graph.get_descendants(graph.root_id)) != set(graph._nodes):
raise ValueError("Tree snapshot contains a disconnected branch")
diff --git a/src/free_claude_code/messaging/trees/manager.py b/src/free_claude_code/messaging/trees/manager.py
index ff86fd39..472055ae 100644
--- a/src/free_claude_code/messaging/trees/manager.py
+++ b/src/free_claude_code/messaging/trees/manager.py
@@ -20,12 +20,13 @@ from .repository import TreeRepository
from .runtime import MessageTree
from .snapshot import ConversationSnapshot, TreeSnapshot
from .transitions import (
- BranchRemovalResult,
+ AdmissionRejection,
CancellationEffect,
CancellationReason,
CancellationResult,
CancellationUiOwner,
FailureResult,
+ MessageSubtreeRemovalResult,
NodeClaim,
NodeUiTarget,
NodeView,
@@ -119,7 +120,7 @@ class TreeQueueManager:
incoming: IncomingMessage,
status_message_id: str,
*,
- parent_node_id: str | None = None,
+ parent_reference_id: str | None = None,
) -> QueueDecision:
"""Publish one admission before its processor can begin."""
node_id = str(incoming.message_id)
@@ -137,10 +138,20 @@ class TreeQueueManager:
tree: MessageTree | None = None
resolved_parent: ReplyTarget | None = None
- if parent_node_id is not None:
- tree = self._repository.get_tree_for_reference(scope, parent_node_id)
+ if parent_reference_id is not None:
+ tree = self._repository.get_tree_for_reference(
+ scope, parent_reference_id
+ )
if tree is not None:
- resolved_parent = await tree.resolve_reply(parent_node_id)
+ resolved_parent = await tree.resolve_reply(parent_reference_id)
+
+ if tree is None or resolved_parent is None:
+ return QueueDecision(
+ claim=None,
+ position=None,
+ snapshot=None,
+ rejection=AdmissionRejection.PARENT_REMOVED,
+ )
if tree is not None and resolved_parent is not None:
decision = await tree.add_and_enqueue(
@@ -149,6 +160,7 @@ class TreeQueueManager:
prompt,
status_message_id,
resolved_parent.node_id,
+ resolved_parent.reference_id,
)
self._repository.register_node(
identity=tree.identity,
@@ -409,21 +421,25 @@ class TreeQueueManager:
snapshots.append(snapshot)
return CancellationResult(effects=tuple(effects), snapshots=tuple(snapshots))
- async def clear_all(
+ async def clear_scope(
self,
+ scope: MessageScope,
*,
reason: CancellationReason | None = None,
) -> CancellationResult:
- """Atomically detach all trees, then drain their exact active tasks."""
- return await _finish_transition(self._clear_all(reason))
+ """Atomically detach one chat's trees, then drain their active tasks."""
+ return await _finish_transition(self._clear_scope(scope, reason))
- async def _clear_all(
+ async def _clear_scope(
self,
+ scope: MessageScope,
reason: CancellationReason | None,
) -> CancellationResult:
transitions: list[tuple[TreeCancellation, CancelledTask | None]] = []
async with self._lock:
for tree in self._repository.trees():
+ if tree.identity.scope != scope:
+ continue
transition = await tree.cancel_all()
cancelled_task = (
self._processor.cancel(transition.active_claim, reason)
@@ -431,7 +447,7 @@ class TreeQueueManager:
else None
)
transitions.append((transition, cancelled_task))
- self._repository = TreeRepository()
+ self._repository.remove_tree(tree.identity)
await _drain_cancelled_tasks(
[
@@ -445,42 +461,44 @@ class TreeQueueManager:
effects.extend(self._external_effects(transition, cancelled_task))
return CancellationResult(effects=tuple(effects))
- async def remove_branch(
+ async def remove_message_subtree(
self,
scope: MessageScope,
- branch_root_id: str,
+ reference_id: str,
*,
reason: CancellationReason | None = None,
- ) -> BranchRemovalResult:
- """Atomically cancel, detach, and unindex one scoped branch."""
+ ) -> MessageSubtreeRemovalResult:
+ """Atomically cancel, detach, and unindex one literal reply subtree."""
return await _finish_transition(
- self._remove_branch(scope, branch_root_id, reason)
+ self._remove_message_subtree(scope, reference_id, reason)
)
- async def _remove_branch(
+ async def _remove_message_subtree(
self,
scope: MessageScope,
- branch_root_id: str,
+ reference_id: str,
reason: CancellationReason | None,
- ) -> BranchRemovalResult:
+ ) -> MessageSubtreeRemovalResult:
async with self._lock:
- tree = self._repository.get_tree_for_reference(scope, branch_root_id)
+ tree = self._repository.get_tree_for_reference(scope, reference_id)
if tree is None:
- return BranchRemovalResult(
+ return MessageSubtreeRemovalResult(
cancellation=CancellationResult(),
removed_tree_identity=None,
- clearable_message_ids=frozenset(),
+ delete_message_ids=frozenset(),
+ tree_matched=False,
)
- target = await tree.resolve_reply(branch_root_id)
+ target = await tree.resolve_reply(reference_id)
if target is None:
- return BranchRemovalResult(
+ return MessageSubtreeRemovalResult(
cancellation=CancellationResult(),
removed_tree_identity=None,
- clearable_message_ids=frozenset(),
+ delete_message_ids=frozenset(),
+ tree_matched=False,
)
identity = tree.identity
- transition = await tree.remove_branch(target.node_id)
- lookup_ids = set(transition.reference_ids)
+ transition = await tree.remove_message_subtree(target.reference_id)
+ lookup_ids = set(transition.removed_message_ids)
if transition.removed_entire_tree:
self._repository.remove_tree(identity)
else:
@@ -509,12 +527,13 @@ class TreeQueueManager:
),
snapshots=(snapshot,) if snapshot is not None else (),
)
- return BranchRemovalResult(
+ return MessageSubtreeRemovalResult(
cancellation=cancellation,
removed_tree_identity=(
identity if transition.removed_entire_tree else None
),
- clearable_message_ids=transition.clearable_message_ids,
+ delete_message_ids=transition.removed_message_ids,
+ tree_matched=True,
)
def get_tree_count(self) -> int:
@@ -527,16 +546,12 @@ class TreeQueueManager:
"""Wait until every processor-owned claim has finished cleanup."""
await self._processor.wait_idle()
- async def get_clearable_message_ids_for_chat(
- self, platform: str, chat_id: str
- ) -> set[str]:
+ async def get_message_ids_for_chat(self, platform: str, chat_id: str) -> set[str]:
async with self._lock:
- clearable_message_ids: set[str] = set()
+ message_ids: set[str] = set()
for tree in self._repository.trees():
- clearable_message_ids.update(
- await tree.clearable_message_ids_for_chat(platform, chat_id)
- )
- return clearable_message_ids
+ message_ids.update(await tree.message_ids_for_chat(platform, chat_id))
+ return message_ids
async def snapshot(self) -> ConversationSnapshot:
async with self._lock:
diff --git a/src/free_claude_code/messaging/trees/node.py b/src/free_claude_code/messaging/trees/node.py
index c2655008..9596883c 100644
--- a/src/free_claude_code/messaging/trees/node.py
+++ b/src/free_claude_code/messaging/trees/node.py
@@ -15,6 +15,13 @@ class MessageState(Enum):
ERROR = "error"
+class MessageReferenceKind(Enum):
+ """Kind of platform message represented by a tree reference."""
+
+ PROMPT = "prompt"
+ STATUS = "status"
+
+
@dataclass
class MessageNode:
"""A single user prompt/status node in a messaging conversation tree."""
@@ -22,9 +29,10 @@ class MessageNode:
node_id: str
scope: MessageScope
prompt: str
- status_message_id: str
+ status_message_id: str | None
state: MessageState = MessageState.PENDING
parent_id: str | None = None
+ parent_reference_id: str | None = None
session_id: str | None = None
children_ids: list[str] = field(default_factory=list)
@@ -40,3 +48,9 @@ class MessageNode:
def mark_error(self) -> None:
self.update_state(MessageState.ERROR)
+
+ def clear_status(self) -> None:
+ """Invalidate the response and resume point while retaining its prompt."""
+ self.status_message_id = None
+ self.session_id = None
+ self.mark_error()
diff --git a/src/free_claude_code/messaging/trees/runtime.py b/src/free_claude_code/messaging/trees/runtime.py
index bb1e8a87..c3d2b32a 100644
--- a/src/free_claude_code/messaging/trees/runtime.py
+++ b/src/free_claude_code/messaging/trees/runtime.py
@@ -9,19 +9,20 @@ from loguru import logger
from ..models import MessageScope
from .graph import MessageTreeGraph
from .identity import TreeIdentity
-from .node import MessageNode, MessageState
+from .node import MessageNode, MessageReferenceKind, MessageState
from .queue import MessageNodeQueue
from .snapshot import TreeSnapshot
from .transitions import (
+ AdmissionRejection,
CompletionResult,
FailureResult,
+ MessageSubtreeRemoval,
NodeClaim,
NodeUiTarget,
NodeView,
QueueDecision,
QueueEntry,
ReplyTarget,
- TreeBranchRemoval,
TreeCancellation,
)
@@ -70,6 +71,8 @@ class MessageTree:
return self._restored_stale_targets
def _ui_target(self, node: MessageNode) -> NodeUiTarget:
+ if node.status_message_id is None:
+ raise ValueError("Runnable node has no status message")
return NodeUiTarget(
scope=node.scope,
node_id=node.node_id,
@@ -106,6 +109,7 @@ class MessageTree:
claim=None,
position=None,
snapshot=None,
+ rejection=AdmissionRejection.DUPLICATE,
)
if self._active is None:
@@ -121,6 +125,7 @@ class MessageTree:
claim=None,
position=None,
snapshot=None,
+ rejection=AdmissionRejection.DUPLICATE,
)
position = self._queue.qsize()
@@ -143,6 +148,7 @@ class MessageTree:
prompt: str,
status_message_id: str,
parent_id: str,
+ parent_reference_id: str,
) -> QueueDecision:
"""Atomically add a reply and admit it to this tree."""
async with self._lock:
@@ -152,6 +158,7 @@ class MessageTree:
prompt=prompt,
status_message_id=status_message_id,
parent_id=parent_id,
+ parent_reference_id=parent_reference_id,
)
return self._enqueue_or_claim(node_id)
@@ -266,31 +273,39 @@ class MessageTree:
queue_update=() if queued_ids else None,
)
- async def remove_branch(
+ async def remove_message_subtree(
self,
- branch_root_id: str,
- ) -> TreeBranchRemoval:
- """Atomically cancel and detach one subtree before external effects."""
+ reference_id: str,
+ ) -> MessageSubtreeRemoval:
+ """Atomically cancel and detach one literal platform reply subtree."""
async with self._lock:
- branch_ids = tuple(self._graph.get_descendants(branch_root_id))
- if not branch_ids:
+ resolved = self._graph.resolve_reference(reference_id)
+ reference_ids = tuple(self._graph.get_reference_descendants(reference_id))
+ if resolved is None or not reference_ids:
empty = TreeCancellation(
nodes=(),
active_claim=None,
queue_update=None,
)
- return TreeBranchRemoval(
+ return MessageSubtreeRemoval(
cancellation=empty,
- reference_ids=frozenset(),
- clearable_message_ids=frozenset(),
+ removed_message_ids=frozenset(),
removed_entire_tree=False,
)
- branch_set = set(branch_ids)
+ owner, reference_kind = resolved
+ removed_node_ids = {
+ candidate
+ for candidate in reference_ids
+ if self._graph.get_node(candidate) is not None
+ }
+ affected_node_ids = set(removed_node_ids)
+ if reference_kind is MessageReferenceKind.STATUS:
+ affected_node_ids.add(owner.node_id)
active_claim = (
self._active.claim
if self._active is not None
- and self._active.claim.node.node_id in branch_set
+ and self._active.claim.node.node_id in affected_node_ids
else None
)
if active_claim is not None:
@@ -298,23 +313,17 @@ class MessageTree:
if active is not None:
active.cancellation_requested = True
cancelled_nodes: list[NodeUiTarget] = []
- reference_ids: set[str] = set()
- clearable_message_ids: set[str] = set()
queue_changed = False
- for node_id in branch_ids:
+ for node_id in affected_node_ids:
node = self._graph.get_node(node_id)
if node is None:
continue
- reference_ids.add(node.node_id)
- if 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):
+ target = self._ui_target(node)
node.mark_error()
- cancelled_nodes.append(self._ui_target(node))
+ cancelled_nodes.append(target)
elif (
node.state is MessageState.ERROR
and active_claim is not None
@@ -322,17 +331,18 @@ class MessageTree:
):
cancelled_nodes.append(self._ui_target(node))
- removed_entire_tree = branch_root_id == self.root_id
- self._graph.remove_branch(branch_root_id)
+ if reference_kind is MessageReferenceKind.STATUS:
+ self._graph.clear_status(owner.node_id)
+ removed_entire_tree = self.root_id in removed_node_ids
+ self._graph.remove_nodes(removed_node_ids)
cancellation = TreeCancellation(
nodes=tuple(cancelled_nodes),
active_claim=active_claim,
queue_update=self._queue_entries() if queue_changed else None,
)
- return TreeBranchRemoval(
+ return MessageSubtreeRemoval(
cancellation=cancellation,
- reference_ids=frozenset(reference_ids),
- clearable_message_ids=frozenset(clearable_message_ids),
+ removed_message_ids=frozenset(reference_ids),
removed_entire_tree=removed_entire_tree,
)
@@ -418,13 +428,14 @@ class MessageTree:
async def resolve_reply(self, reference_id: str) -> ReplyTarget | None:
"""Resolve a node/status reference without exposing the mutable graph."""
async with self._lock:
- node = self._graph.get_node(reference_id)
- if node is None:
- node = self._graph.find_node_by_status_message(reference_id)
- if node is None:
+ resolved = self._graph.resolve_reference(reference_id)
+ if resolved is None:
return None
+ node, reference_kind = resolved
return ReplyTarget(
node_id=node.node_id,
+ reference_id=reference_id,
+ reference_kind=reference_kind,
queue_position=(self._queue.qsize() + 1)
if self._active is not None
else None,
@@ -449,20 +460,14 @@ class MessageTree:
async with self._lock:
return self._graph.snapshot()
- 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 def message_ids_for_chat(self, platform: str, chat_id: str) -> set[str]:
+ """Copy every prompt and FCC status 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()
- clearable_message_ids: set[str] = set()
- for node in self._graph.all_nodes():
- if node.status_message_id:
- clearable_message_ids.add(str(node.status_message_id))
- return clearable_message_ids
+ return self._graph.all_reference_ids()
@classmethod
def from_snapshot(cls, snapshot: TreeSnapshot) -> MessageTree:
diff --git a/src/free_claude_code/messaging/trees/snapshot.py b/src/free_claude_code/messaging/trees/snapshot.py
index fa4b0e3a..83ec27ab 100644
--- a/src/free_claude_code/messaging/trees/snapshot.py
+++ b/src/free_claude_code/messaging/trees/snapshot.py
@@ -120,6 +120,16 @@ class ConversationSnapshot:
trees.pop(identity, None)
return ConversationSnapshot(trees=trees)
+ def without_scope(self, scope: MessageScope) -> ConversationSnapshot:
+ """Remove every tree belonging to one platform chat."""
+ return ConversationSnapshot(
+ trees={
+ identity: tree
+ for identity, tree in self.trees.items()
+ if identity.scope != scope
+ }
+ )
+
def _legacy_scope(
root_id: str,
@@ -159,21 +169,36 @@ def node_to_snapshot(node: MessageNode) -> dict[str, Any]:
"status_message_id": node.status_message_id,
"state": node.state.value,
"parent_id": node.parent_id,
+ "parent_reference_id": node.parent_reference_id,
"session_id": node.session_id,
}
def node_from_snapshot(data: dict[str, Any], scope: MessageScope) -> MessageNode:
+ state = MessageState(data["state"])
+ status_message_id = _optional_id(
+ data.get("status_message_id"),
+ "status_message_id",
+ )
+ if state in (MessageState.PENDING, MessageState.IN_PROGRESS) and (
+ status_message_id is None
+ ):
+ raise ValueError("Runnable tree snapshot node requires a status message")
+ parent_id = _optional_id(data.get("parent_id"), "parent_id")
+ parent_reference_id = _optional_id(
+ data.get("parent_reference_id"),
+ "parent_reference_id",
+ )
+ if parent_reference_id is None:
+ parent_reference_id = parent_id
return MessageNode(
node_id=_required_id(data.get("node_id"), "node_id"),
scope=scope,
prompt="",
- status_message_id=_required_id(
- data.get("status_message_id"),
- "status_message_id",
- ),
- state=MessageState(data["state"]),
- parent_id=_optional_id(data.get("parent_id"), "parent_id"),
+ status_message_id=status_message_id,
+ state=state,
+ parent_id=parent_id,
+ parent_reference_id=parent_reference_id,
session_id=_optional_id(data.get("session_id"), "session_id"),
)
diff --git a/src/free_claude_code/messaging/trees/transitions.py b/src/free_claude_code/messaging/trees/transitions.py
index 6951bb26..38b99016 100644
--- a/src/free_claude_code/messaging/trees/transitions.py
+++ b/src/free_claude_code/messaging/trees/transitions.py
@@ -5,7 +5,7 @@ from enum import Enum
from ..models import MessageScope
from .identity import TreeIdentity
-from .node import MessageState
+from .node import MessageReferenceKind, MessageState
from .snapshot import TreeSnapshot
@@ -17,9 +17,17 @@ class CancellationUiOwner(Enum):
class CancellationReason(Enum):
- """Why a running messaging claim was cancelled."""
+ """Customer operation that cancelled a running messaging claim."""
STOP = "stop"
+ CLEAR = "clear"
+
+
+class AdmissionRejection(Enum):
+ """Why a turn was not admitted to an execution tree."""
+
+ DUPLICATE = "duplicate"
+ PARENT_REMOVED = "parent_removed"
@dataclass(frozen=True, slots=True)
@@ -57,6 +65,7 @@ class QueueDecision:
claim: NodeClaim | None
position: int | None
snapshot: TreeSnapshot | None
+ rejection: AdmissionRejection | None = None
@property
def accepted(self) -> bool:
@@ -97,22 +106,22 @@ class CancellationResult:
@dataclass(frozen=True, slots=True)
-class TreeBranchRemoval:
- """Single-tree atomic cancellation and graph-removal transition."""
+class MessageSubtreeRemoval:
+ """Single-tree atomic cancellation and reference-subtree removal."""
cancellation: TreeCancellation
- reference_ids: frozenset[str]
- clearable_message_ids: frozenset[str]
+ removed_message_ids: frozenset[str]
removed_entire_tree: bool
@dataclass(frozen=True, slots=True)
-class BranchRemovalResult:
- """Manager result for a branch clear."""
+class MessageSubtreeRemovalResult:
+ """Manager result for a literal message-subtree clear."""
cancellation: CancellationResult
removed_tree_identity: TreeIdentity | None
- clearable_message_ids: frozenset[str]
+ delete_message_ids: frozenset[str]
+ tree_matched: bool
@dataclass(frozen=True, slots=True)
@@ -120,6 +129,8 @@ class ReplyTarget:
"""Resolved reply destination and advisory position before admission."""
node_id: str
+ reference_id: str
+ reference_kind: MessageReferenceKind
queue_position: int | None
@@ -144,19 +155,20 @@ class FailureResult:
__all__ = [
- "BranchRemovalResult",
+ "AdmissionRejection",
"CancellationEffect",
"CancellationReason",
"CancellationResult",
"CancellationUiOwner",
"CompletionResult",
"FailureResult",
+ "MessageSubtreeRemoval",
+ "MessageSubtreeRemovalResult",
"NodeClaim",
"NodeUiTarget",
"NodeView",
"QueueDecision",
"QueueEntry",
"ReplyTarget",
- "TreeBranchRemoval",
"TreeCancellation",
]
diff --git a/src/free_claude_code/messaging/turn_intake.py b/src/free_claude_code/messaging/turn_intake.py
index 2e1bae34..a16b2a23 100644
--- a/src/free_claude_code/messaging/turn_intake.py
+++ b/src/free_claude_code/messaging/turn_intake.py
@@ -12,11 +12,16 @@ from .command_dispatcher import (
dispatch_command,
parse_command_base,
)
-from .models import IncomingMessage, MessageScope
+from .models import AdmissionToken, IncomingMessage, MessageScope
from .platforms.ports import OutboundMessenger
-from .safe_diagnostics import format_exception_for_log
from .session import SessionStore
-from .trees import NodeClaim, QueueDecision, QueueEntry, ReplyTarget
+from .trees import (
+ AdmissionRejection,
+ NodeClaim,
+ QueueDecision,
+ QueueEntry,
+ ReplyTarget,
+)
class MessagingTurnIntake:
@@ -31,13 +36,12 @@ class MessagingTurnIntake:
command_context: MessagingCommandContext,
resolve_reply: Callable[[MessageScope, str], Awaitable[ReplyTarget | None]],
admit_turn: Callable[
- [IncomingMessage, str, str | None, int],
+ [IncomingMessage, str, str | None, AdmissionToken],
Awaitable[QueueDecision | None],
],
format_status: Callable[[str, str, str | None], str],
get_parse_mode: Callable[[], str | None],
record_outgoing_message: Callable[[str, str, str | None, str], bool],
- log_messaging_error_details: bool = False,
) -> None:
self.platform_name = platform_name
self.outbound = outbound
@@ -48,53 +52,20 @@ class MessagingTurnIntake:
self._format_status = format_status
self._get_parse_mode = get_parse_mode
self._record_outgoing_message = record_outgoing_message
- self._log_messaging_error_details = log_messaging_error_details
-
- 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_clear_command_id(
- incoming.platform,
- incoming.chat_id,
- str(incoming.message_id),
- )
- except Exception as exc:
- logger.debug(
- "Failed to record clear command message_id: {}",
- format_exception_for_log(
- exc,
- log_full_message=self._log_messaging_error_details,
- ),
- )
async def handle_message(
self,
incoming: IncomingMessage,
*,
- admission_epoch: int,
+ admission_token: AdmissionToken,
) -> None:
"""
Handle an inbound platform message and queue it if it is a user prompt.
"""
cmd_base = parse_command_base(incoming.text)
- # 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_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_clear_command(incoming)
- raise
+ if await dispatch_command(self._command_context, incoming, cmd_base):
+ return
text = incoming.text or ""
if any(text.startswith(p) for p in STATUS_MESSAGE_PREFIXES):
@@ -138,19 +109,34 @@ class MessagingTurnIntake:
decision = await self._admit_turn(
incoming,
status_msg_id,
- reply_target.node_id if reply_target is not None else None,
- admission_epoch,
+ reply_target.reference_id if reply_target is not None else None,
+ admission_token,
)
if decision is None:
logger.info(
- "Discarded messaging admission invalidated by global stop/clear for node {}",
+ "Discarded messaging admission invalidated by a stop/clear boundary for node {}",
node_id,
)
- await self._discard_rejected_status(incoming, status_msg_id)
+ await self._discard_rejected_messages(
+ incoming,
+ status_msg_id,
+ include_prompt=False,
+ )
return
if not decision.accepted:
- logger.debug("Ignored duplicate messaging admission for node {}", node_id)
- await self._discard_rejected_status(incoming, status_msg_id)
+ include_prompt = decision.rejection is AdmissionRejection.PARENT_REMOVED
+ logger.debug(
+ "Rejected messaging admission for node {}: {}",
+ node_id,
+ decision.rejection.value
+ if decision.rejection is not None
+ else "unknown",
+ )
+ await self._discard_rejected_messages(
+ incoming,
+ status_msg_id,
+ include_prompt=include_prompt,
+ )
return
if decision.position is not None and status_msg_id:
@@ -174,16 +160,21 @@ class MessagingTurnIntake:
parse_mode=self._get_parse_mode(),
)
- async def _discard_rejected_status(
+ async def _discard_rejected_messages(
self,
incoming: IncomingMessage,
status_message_id: str,
+ *,
+ include_prompt: bool,
) -> None:
- """Remove the provisional status created for a rejected admission."""
+ """Remove messages created by an admission that cannot commit."""
+ message_ids = {status_message_id}
+ if include_prompt:
+ message_ids.add(str(incoming.message_id))
try:
await self.outbound.queue_delete_messages(
incoming.chat_id,
- [status_message_id],
+ list(message_ids),
fire_and_forget=False,
)
except Exception as exc:
@@ -192,10 +183,10 @@ class MessagingTurnIntake:
type(exc).__name__,
)
try:
- self.session_store.forget_clearable_message_ids(
+ self.session_store.forget_tracked_message_ids(
incoming.platform,
incoming.chat_id,
- {status_message_id},
+ message_ids,
)
except Exception as exc:
logger.debug(
diff --git a/src/free_claude_code/messaging/voice.py b/src/free_claude_code/messaging/voice.py
index 98d95953..a52a9746 100644
--- a/src/free_claude_code/messaging/voice.py
+++ b/src/free_claude_code/messaging/voice.py
@@ -68,13 +68,7 @@ class VoiceCancellationResult:
scope: MessageScope
voice_message_id: str
status_message_id: str | None
-
- @property
- 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})
+ delete_message_ids: frozenset[str]
@dataclass(slots=True)
@@ -208,7 +202,7 @@ class PendingVoiceRegistry:
return None
self._remove(entry)
task = entry.handoff_task
- result = self._cancellation_result(entry)
+ result = self._cancellation_result(entry, reply_id)
cancellation = await self._cancel_and_drain(task)
if cancellation is not None:
raise cancellation
@@ -218,6 +212,18 @@ class PendingVoiceRegistry:
async def cancel_all(self) -> tuple[VoiceCancellationResult, ...]:
"""Cancel every unique pending voice note and drain published handoffs."""
+ return await self._cancel_matching_scope(None)
+
+ async def cancel_scope(
+ self, scope: MessageScope
+ ) -> tuple[VoiceCancellationResult, ...]:
+ """Cancel every unique pending voice note in one platform chat."""
+ return await self._cancel_matching_scope(scope)
+
+ async def _cancel_matching_scope(
+ self,
+ scope: MessageScope | None,
+ ) -> tuple[VoiceCancellationResult, ...]:
current_claim = _current_voice_claim.get()
self._protect_claim(current_claim)
try:
@@ -225,8 +231,9 @@ class PendingVoiceRegistry:
entries = tuple(
{
entry.claim: entry
- for entry in self._pending.values()
- if not self._is_excluded(entry, current_claim)
+ for (entry_scope, _reference_id), entry in self._pending.items()
+ if (scope is None or entry_scope == scope)
+ and not self._is_excluded(entry, current_claim)
}.values()
)
for entry in entries:
@@ -312,11 +319,20 @@ class PendingVoiceRegistry:
return not isinstance(error, (asyncio.CancelledError, Exception))
@staticmethod
- def _cancellation_result(entry: _PendingVoice) -> VoiceCancellationResult:
+ def _cancellation_result(
+ entry: _PendingVoice,
+ reference_id: str | None = None,
+ ) -> VoiceCancellationResult:
+ delete_message_ids = {entry.claim.voice_message_id}
+ if reference_id is not None and reference_id != entry.claim.voice_message_id:
+ delete_message_ids.clear()
+ if entry.status_message_id is not None:
+ delete_message_ids.add(entry.status_message_id)
return VoiceCancellationResult(
scope=entry.claim.scope,
voice_message_id=entry.claim.voice_message_id,
status_message_id=entry.status_message_id,
+ delete_message_ids=frozenset(delete_message_ids),
)
def _entry_for_claim(self, claim: PendingVoiceClaim) -> _PendingVoice | None:
diff --git a/src/free_claude_code/messaging/workflow.py b/src/free_claude_code/messaging/workflow.py
index d8215641..f0200365 100644
--- a/src/free_claude_code/messaging/workflow.py
+++ b/src/free_claude_code/messaging/workflow.py
@@ -9,8 +9,9 @@ from loguru import logger
from free_claude_code.core.trace import trace_event
from .command_context import ReplyClearResult, StopOutcome
+from .command_dispatcher import parse_command_base
from .managed_protocols import ManagedClaudeSessionManagerProtocol
-from .models import IncomingMessage, MessageScope
+from .models import AdmissionToken, IncomingMessage, MessageScope
from .node_runner import MessagingNodeRunner
from .platforms.ports import (
MessagingStartupNotice,
@@ -108,8 +109,8 @@ class MessagingWorkflow:
self._log_messaging_error_details = log_messaging_error_details
self._rendering_profile = build_rendering_profile(self.platform_name)
self._state_lock = asyncio.Lock()
- self._admission_epoch = 0
- self._clear_generation = 0
+ self._stop_generation = 0
+ self._clear_generations: dict[MessageScope, int] = {}
self._pending_restored_status_targets: tuple[NodeUiTarget, ...] = ()
self._tree_queue: TreeQueueManager
@@ -138,7 +139,6 @@ class MessagingWorkflow:
format_status=self.format_status,
get_parse_mode=self._parse_mode,
record_outgoing_message=self.record_outgoing_message,
- log_messaging_error_details=log_messaging_error_details,
)
self._tree_queue = self._build_tree_queue()
@@ -217,8 +217,9 @@ class MessagingWorkflow:
async def publish_startup_notice(self, notice: MessagingStartupNotice) -> None:
"""Publish one notice, then transfer its receipt to clear ownership."""
+ scope = MessageScope(platform=self.platform_name, chat_id=notice.chat_id)
async with self._state_lock:
- clear_generation = self._clear_generation
+ clear_generation = self._clear_generations.get(scope, 0)
try:
message_id = await self.outbound.queue_send_message(
@@ -266,7 +267,9 @@ class MessagingWorkflow:
async with self._state_lock:
must_discard = (
publisher_task is not None and publisher_task.cancelling() > 0
- ) or clear_generation != self._clear_generation
+ ) or clear_generation != self._clear_generations.get(
+ MessageScope(platform=self.platform_name, chat_id=notice.chat_id), 0
+ )
if not must_discard:
must_discard = not self.record_outgoing_message(
self.platform_name,
@@ -312,7 +315,7 @@ class MessagingWorkflow:
return
async with self._state_lock:
- self.forget_clearable_message_ids(
+ self.forget_tracked_message_ids(
self.platform_name,
chat_id,
{message_id},
@@ -340,12 +343,27 @@ class MessagingWorkflow:
chat_id=incoming.chat_id,
node_id=incoming.message_id,
):
- async with self._state_lock:
- admission_epoch = self._admission_epoch
- await self.turn_intake.handle_message(
- incoming,
- admission_epoch=admission_epoch,
+ is_standalone_clear = (
+ parse_command_base(incoming.text) == "/clear"
+ and not incoming.is_reply()
)
+ async with self._state_lock:
+ admission_token = AdmissionToken(
+ stop_generation=self._stop_generation,
+ clear_generation=self._clear_generations.get(incoming.scope, 0),
+ )
+ if not is_standalone_clear:
+ self._record_incoming_message(incoming)
+ try:
+ await self.turn_intake.handle_message(
+ incoming,
+ admission_token=admission_token,
+ )
+ except BaseException:
+ if is_standalone_clear:
+ async with self._state_lock:
+ self._record_incoming_message(incoming)
+ raise
async def resolve_reply(
self,
@@ -358,15 +376,15 @@ class MessagingWorkflow:
self,
incoming: IncomingMessage,
status_message_id: str,
- parent_node_id: str | None,
- admission_epoch: int,
+ parent_reference_id: str | None,
+ admission_token: AdmissionToken,
) -> QueueDecision | None:
return await _finish_owned_operation(
self._admit_if_current(
incoming,
status_message_id,
- parent_node_id,
- admission_epoch,
+ parent_reference_id,
+ admission_token,
),
name=f"messaging-admit-{incoming.message_id}",
)
@@ -375,17 +393,21 @@ class MessagingWorkflow:
self,
incoming: IncomingMessage,
status_message_id: str,
- parent_node_id: str | None,
- admission_epoch: int,
+ parent_reference_id: str | None,
+ admission_token: AdmissionToken,
) -> QueueDecision | None:
"""Commit admission and its exact snapshot as one owned transaction."""
async with self._state_lock:
- if admission_epoch != self._admission_epoch:
+ current_token = AdmissionToken(
+ stop_generation=self._stop_generation,
+ clear_generation=self._clear_generations.get(incoming.scope, 0),
+ )
+ if admission_token != current_token:
return None
decision = await self._tree_queue.admit(
incoming,
status_message_id,
- parent_node_id=parent_node_id,
+ parent_reference_id=parent_reference_id,
)
if decision.snapshot is not None:
self.session_store.save_tree_snapshot(decision.snapshot)
@@ -446,30 +468,25 @@ class MessagingWorkflow:
reply_id: str,
) -> ReplyClearResult | None:
voice_result = await self._cancel_pending_voice(scope, reply_id)
- if voice_result is not None:
- self.render_voice_stopped(voice_result)
async with self._state_lock:
- node_id = await self._tree_queue.resolve_node_id(scope, reply_id)
- if node_id is None:
- if voice_result is None:
- return None
- return ReplyClearResult(
- clearable_message_ids=voice_result.clearable_message_ids,
- tree_cleared=False,
- )
-
- branch = await self._tree_queue.remove_branch(scope, node_id)
- self._apply_cancellation_result(branch.cancellation)
- if branch.removed_tree_identity is not None:
- self.session_store.remove_tree_snapshot(branch.removed_tree_identity)
+ subtree = await self._tree_queue.remove_message_subtree(
+ scope,
+ reply_id,
+ reason=CancellationReason.CLEAR,
+ )
+ if not subtree.tree_matched and voice_result is None:
+ return None
+ self._save_cancellation_snapshots(subtree.cancellation)
+ if subtree.removed_tree_identity is not None:
+ self.session_store.remove_tree_snapshot(subtree.removed_tree_identity)
- clearable_message_ids = set(branch.clearable_message_ids)
+ delete_message_ids = set(subtree.delete_message_ids)
if voice_result is not None:
- clearable_message_ids.update(voice_result.clearable_message_ids)
+ delete_message_ids.update(voice_result.delete_message_ids)
return ReplyClearResult(
- clearable_message_ids=frozenset(clearable_message_ids),
- tree_cleared=True,
+ delete_message_ids=frozenset(delete_message_ids),
+ tree_matched=subtree.tree_matched,
)
async def stop_all_tasks(self) -> StopOutcome:
@@ -484,7 +501,7 @@ class MessagingWorkflow:
for voice in voice_results:
self.render_voice_stopped(voice)
async with self._state_lock:
- self._admission_epoch += 1
+ self._stop_generation += 1
logger.info("Cancelling tree queue tasks...")
result = await self._tree_queue.cancel_all(reason=CancellationReason.STOP)
logger.info("Cancelled {} nodes", len(result.effects))
@@ -493,89 +510,58 @@ class MessagingWorkflow:
await self.cli_manager.stop_all()
return _stop_outcome(voice_results, result)
- async def clear_all_state(self, platform: str, chat_id: str) -> frozenset[str]:
+ async def clear_chat(self, platform: str, chat_id: str) -> frozenset[str]:
"""Clear FCC state atomically with respect to later turn admission."""
return await _finish_owned_operation(
- self._clear_all_state(platform, chat_id),
- name="messaging-clear-all",
+ self._clear_chat(platform, chat_id),
+ name=f"messaging-clear-{platform}-{chat_id}",
)
- async def _clear_all_state(
+ async def _clear_chat(
self,
platform: str,
chat_id: str,
) -> frozenset[str]:
- """Globally reset FCC state; return deletion IDs for the invoking chat."""
- voice_results = await self._cancel_all_pending_voices()
- for voice in voice_results:
- self.render_voice_stopped(voice)
+ """Reset one chat's FCC state and return all tracked deletion IDs."""
+ clear_scope = MessageScope(platform=platform, chat_id=chat_id)
+ voice_results = await self._cancel_pending_voices_in_scope(clear_scope)
async with self._state_lock:
- clearable_message_ids: set[str] = set()
- clear_scope = MessageScope(platform=platform, chat_id=chat_id)
+ delete_message_ids: set[str] = set()
for voice in voice_results:
- if voice.scope == clear_scope:
- clearable_message_ids.update(voice.clearable_message_ids)
- try:
- clearable_message_ids.update(
- str(message_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 clearable-message log for /clear: {}",
- type(exc).__name__,
- )
+ delete_message_ids.update(voice.delete_message_ids)
+ delete_message_ids.update(
+ self.session_store.get_tracked_message_ids_for_chat(platform, chat_id)
+ )
- clearable_message_ids.update(
- await self._tree_queue.get_clearable_message_ids_for_chat(
- platform, chat_id
- )
+ delete_message_ids.update(
+ await self._tree_queue.get_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
- # 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:
- logger.warning("Failed to clear session store: {}", type(exc).__name__)
-
+ # the scope generation advances, state removal is one-way work.
+ self._clear_generations[clear_scope] = (
+ self._clear_generations.get(clear_scope, 0) + 1
+ )
failures: list[Exception] = []
- result = CancellationResult()
try:
- result = await self._tree_queue.clear_all(
- reason=CancellationReason.STOP
+ await self._tree_queue.clear_scope(
+ clear_scope,
+ reason=CancellationReason.CLEAR,
)
except Exception as exc:
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 clearable IDs.
try:
- self.session_store.clear_conversation_snapshot()
+ self.session_store.clear_scope(clear_scope)
except Exception as exc:
failures.append(exc)
logger.warning(
"Failed to persist final cleared session state: {}",
type(exc).__name__,
)
- try:
- self._apply_cancellation_result(result)
- except Exception as exc:
- failures.append(exc)
- try:
- await self.cli_manager.stop_all()
- except Exception as exc:
- failures.append(exc)
if len(failures) == 1:
raise failures[0]
if failures:
- raise ExceptionGroup("Global clear failed", failures)
- return frozenset(clearable_message_ids)
+ raise ExceptionGroup("Chat clear failed", failures)
+ return frozenset(delete_message_ids)
async def _cancel_all_pending_voices(
self,
@@ -585,6 +571,15 @@ class MessagingWorkflow:
return ()
return await cancellation.cancel_all_pending_voices()
+ async def _cancel_pending_voices_in_scope(
+ self,
+ scope: MessageScope,
+ ) -> tuple[VoiceCancellationResult, ...]:
+ cancellation = self.voice_cancellation
+ if cancellation is None:
+ return ()
+ return await cancellation.cancel_pending_voices_in_scope(scope)
+
async def _cancel_pending_voice(
self,
scope: MessageScope,
@@ -608,19 +603,19 @@ class MessagingWorkflow:
)
)
- def forget_clearable_message_ids(
+ def forget_tracked_message_ids(
self,
platform: str,
chat_id: str,
message_ids: set[str],
) -> None:
try:
- self.session_store.forget_clearable_message_ids(
+ self.session_store.forget_tracked_message_ids(
platform, chat_id, message_ids
)
except Exception as exc:
logger.warning(
- "Failed to update session store after branch clear: {}",
+ "Failed to update managed-message log after clear: {}",
type(exc).__name__,
)
@@ -635,10 +630,11 @@ class MessagingWorkflow:
if not msg_id:
return False
try:
- self.session_store.record_outbound_message_id(
+ self.session_store.record_message_id(
platform,
chat_id,
str(msg_id),
+ "out",
kind,
)
except Exception as exc:
@@ -652,6 +648,40 @@ class MessagingWorkflow:
return False
return True
+ def _record_incoming_message(self, incoming: IncomingMessage) -> bool:
+ """Record an inbound prompt, voice note, or command for standalone clear."""
+ command = parse_command_base(incoming.text)
+ kind = (
+ "command"
+ if command.startswith("/")
+ else "voice"
+ if incoming.status_message_id is not None
+ else "prompt"
+ )
+ try:
+ self.session_store.record_message_id(
+ incoming.platform,
+ incoming.chat_id,
+ str(incoming.message_id),
+ "in",
+ kind,
+ )
+ except Exception as exc:
+ logger.debug(
+ "Failed to record managed inbound message_id: {}",
+ format_exception_for_log(
+ exc,
+ log_full_message=self._log_messaging_error_details,
+ ),
+ )
+ return False
+ return True
+
+ def _save_cancellation_snapshots(self, result: CancellationResult) -> None:
+ """Persist transition snapshots without publishing cancellation UI."""
+ for snapshot in result.snapshots:
+ self.session_store.save_tree_snapshot(snapshot)
+
def _apply_cancellation_result(self, result: CancellationResult) -> None:
"""Apply detached UI and persistence effects from one transition."""
for effect in result.effects:
@@ -664,8 +694,7 @@ class MessagingWorkflow:
parse_mode=self._parse_mode(),
)
)
- for snapshot in result.snapshots:
- self.session_store.save_tree_snapshot(snapshot)
+ self._save_cancellation_snapshots(result)
def _apply_unexpected_failure(self, result: FailureResult) -> None:
"""Persist and render a failure that escaped the total node runner."""
diff --git a/src/free_claude_code/runtime/application.py b/src/free_claude_code/runtime/application.py
index c2f220fc..1ebbfbae 100644
--- a/src/free_claude_code/runtime/application.py
+++ b/src/free_claude_code/runtime/application.py
@@ -378,7 +378,7 @@ class ApplicationRuntime:
)
session_store = messaging_session.SessionStore(
storage_path=os.path.join(data_path, "sessions.json"),
- message_log_cap=settings.max_message_log_entries_per_chat,
+ managed_message_cap=settings.max_message_log_entries_per_chat,
)
workflow = messaging_workflow_module.MessagingWorkflow(
platform_name=components.name,
diff --git a/tests/conftest.py b/tests/conftest.py
index 54cc9201..813e9787 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -132,6 +132,7 @@ def mock_platform():
platform.queue_delete_messages = AsyncMock()
platform.cancel_pending_voice = AsyncMock(return_value=None)
platform.cancel_all_pending_voices = AsyncMock(return_value=())
+ platform.cancel_pending_voices_in_scope = AsyncMock(return_value=())
def _fire_and_forget(task):
if asyncio.iscoroutine(task):
@@ -151,10 +152,10 @@ def mock_session_store():
store.save_tree = MagicMock()
store.get_tree = MagicMock(return_value=None)
store.register_node = MagicMock()
- store.clear_all = MagicMock()
- store.record_outbound_message_id = MagicMock()
- store.record_clear_command_id = MagicMock()
- store.get_clearable_message_ids_for_chat = MagicMock(return_value=[])
+ store.record_message_id = MagicMock()
+ store.get_tracked_message_ids_for_chat = MagicMock(return_value=[])
+ store.forget_tracked_message_ids = MagicMock()
+ store.clear_scope = MagicMock()
return store
diff --git a/tests/messaging/test_handler.py b/tests/messaging/test_handler.py
index 24924f52..4dac0957 100644
--- a/tests/messaging/test_handler.py
+++ b/tests/messaging/test_handler.py
@@ -8,12 +8,13 @@ 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,
CancellationReason,
CancellationResult,
CancellationUiOwner,
FailureResult,
+ MessageReferenceKind,
MessageState,
+ MessageSubtreeRemovalResult,
NodeClaim,
NodeUiTarget,
QueueEntry,
@@ -129,7 +130,7 @@ async def test_handle_message_turn_trace_always_includes_full_message_text(
@pytest.mark.asyncio
-async def test_user_prompt_is_never_recorded_as_clearable(
+async def test_user_prompt_and_status_are_recorded_for_global_clear(
handler,
mock_session_store,
incoming_message_factory,
@@ -139,12 +140,23 @@ async def test_user_prompt_is_never_recorded_as_clearable(
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",
+ mock_session_store.record_message_id.assert_has_calls(
+ [
+ call(
+ incoming.platform,
+ incoming.chat_id,
+ "user-prompt",
+ "in",
+ "prompt",
+ ),
+ call(
+ incoming.platform,
+ incoming.chat_id,
+ "msg_123",
+ "out",
+ "status",
+ ),
+ ]
)
@@ -152,8 +164,24 @@ async def test_user_prompt_is_never_recorded_as_clearable(
("target", "expected"),
[
(None, "Launching"),
- (ReplyTarget(node_id="parent", queue_position=None), "Continuing"),
- (ReplyTarget(node_id="parent", queue_position=3), "position 3"),
+ (
+ ReplyTarget(
+ node_id="parent",
+ reference_id="parent",
+ reference_kind=MessageReferenceKind.PROMPT,
+ queue_position=None,
+ ),
+ "Continuing",
+ ),
+ (
+ ReplyTarget(
+ node_id="parent",
+ reference_id="status-parent",
+ reference_kind=MessageReferenceKind.STATUS,
+ queue_position=3,
+ ),
+ "position 3",
+ ),
],
)
def test_initial_status_uses_immutable_reply_advice(handler, target, expected):
@@ -309,6 +337,7 @@ async def test_reply_stop_cancels_voice_when_no_tree_was_admitted(
scope=_SCOPE,
voice_message_id="voice",
status_message_id="voice_status",
+ delete_message_ids=frozenset({"voice", "voice_status"}),
)
incoming = incoming_message_factory(
text="/stop",
@@ -334,6 +363,7 @@ async def test_reply_stop_without_voice_status_sends_fallback_confirmation(
scope=_SCOPE,
voice_message_id="voice",
status_message_id=None,
+ delete_message_ids=frozenset({"voice"}),
)
incoming = incoming_message_factory(
text="/stop",
@@ -361,6 +391,7 @@ async def test_reply_stop_resolves_tree_after_joining_voice_handoff(
scope=_SCOPE,
voice_message_id="voice",
status_message_id="voice_status",
+ delete_message_ids=frozenset({"voice", "voice_status"}),
)
async def resolve_tree(*_args) -> str:
@@ -439,6 +470,7 @@ async def test_reply_stop_renders_voice_before_resolve_failure(
scope=_SCOPE,
voice_message_id="voice",
status_message_id="voice_status",
+ delete_message_ids=frozenset({"voice", "voice_status"}),
)
with (
patch.object(
@@ -468,6 +500,7 @@ async def test_cancelled_reply_stop_finishes_after_voice_join_and_lock_wait(
scope=_SCOPE,
voice_message_id="voice",
status_message_id="voice_status",
+ delete_message_ids=frozenset({"voice", "voice_status"}),
)
mock_platform.cancel_pending_voice.side_effect = cancel_voice
@@ -594,7 +627,7 @@ async def test_duplicate_delivery_removes_its_provisional_status(
["status-rejected"],
fire_and_forget=False,
)
- mock_session_store.forget_clearable_message_ids.assert_called_once_with(
+ mock_session_store.forget_tracked_message_ids.assert_called_once_with(
incoming.platform,
incoming.chat_id,
{"status-rejected"},
@@ -757,6 +790,7 @@ async def test_stop_all_joins_voices_before_tree_transaction_and_deduplicates(
scope=_SCOPE,
voice_message_id="voice",
status_message_id=None,
+ delete_message_ids=frozenset({"voice"}),
)
tree_result = CancellationResult(
effects=(
@@ -1308,7 +1342,7 @@ async def test_stop_cancellation_preserves_partial_transcript(
async def test_global_clear_command_deletes_returned_ids(
handler, mock_platform, incoming_message_factory
):
- handler.clear_all_state = AsyncMock(return_value=frozenset({"100", "101"}))
+ handler.clear_chat = AsyncMock(return_value=frozenset({"100", "101"}))
incoming = incoming_message_factory(
text="/clear",
chat_id="chat_1",
@@ -1317,14 +1351,14 @@ async def test_global_clear_command_deletes_returned_ids(
await handler.handle_message(incoming)
- handler.clear_all_state.assert_awaited_once_with("telegram", "chat_1")
+ handler.clear_chat.assert_awaited_once_with("telegram", "chat_1")
mock_platform.queue_delete_messages.assert_awaited_once_with(
"chat_1",
["150", "101", "100"],
fire_and_forget=False,
)
mock_platform.queue_send_message.assert_not_awaited()
- handler.session_store.record_clear_command_id.assert_not_called()
+ handler.session_store.record_message_id.assert_not_called()
@pytest.mark.asyncio
@@ -1340,7 +1374,7 @@ async def test_interrupted_global_clear_records_its_deferred_command_id(
incoming_message_factory,
failure: BaseException,
) -> None:
- handler.clear_all_state = AsyncMock(side_effect=failure)
+ handler.clear_chat = AsyncMock(side_effect=failure)
incoming = incoming_message_factory(
text="/clear",
chat_id="chat_1",
@@ -1350,10 +1384,12 @@ 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_clear_command_id.assert_called_once_with(
+ mock_session_store.record_message_id.assert_called_once_with(
incoming.platform,
incoming.chat_id,
incoming.message_id,
+ "in",
+ "command",
)
mock_platform.queue_delete_messages.assert_not_awaited()
@@ -1374,10 +1410,11 @@ async def test_startup_notice_is_published_and_recorded_for_clear(
parse_mode="MarkdownV2",
fire_and_forget=False,
)
- mock_session_store.record_outbound_message_id.assert_called_once_with(
+ mock_session_store.record_message_id.assert_called_once_with(
_SCOPE.platform,
_SCOPE.chat_id,
"startup_1",
+ "out",
"startup",
)
mock_platform.queue_delete_messages.assert_not_awaited()
@@ -1393,7 +1430,7 @@ async def test_startup_notice_failure_is_nonfatal_and_records_nothing(
await handler.publish_startup_notice(_startup_notice())
- mock_session_store.record_outbound_message_id.assert_not_called()
+ mock_session_store.record_message_id.assert_not_called()
mock_platform.queue_delete_messages.assert_not_awaited()
@@ -1407,7 +1444,7 @@ async def test_startup_notice_without_delivery_receipt_records_nothing(
await handler.publish_startup_notice(_startup_notice())
- mock_session_store.record_outbound_message_id.assert_not_called()
+ mock_session_store.record_message_id.assert_not_called()
mock_platform.queue_delete_messages.assert_not_awaited()
@@ -1418,9 +1455,7 @@ 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_outbound_message_id.side_effect = OSError(
- "store unavailable"
- )
+ mock_session_store.record_message_id.side_effect = OSError("store unavailable")
async def delete_notice(*args, **kwargs) -> None:
assert not handler._state_lock.locked()
@@ -1429,10 +1464,11 @@ async def test_startup_notice_record_failure_is_compensated_outside_state_lock(
await handler.publish_startup_notice(_startup_notice())
- mock_session_store.record_outbound_message_id.assert_called_once_with(
+ mock_session_store.record_message_id.assert_called_once_with(
_SCOPE.platform,
_SCOPE.chat_id,
"startup_1",
+ "out",
"startup",
)
mock_platform.queue_delete_messages.assert_awaited_once_with(
@@ -1440,7 +1476,7 @@ async def test_startup_notice_record_failure_is_compensated_outside_state_lock(
["startup_1"],
fire_and_forget=False,
)
- mock_session_store.forget_clearable_message_ids.assert_called_once_with(
+ mock_session_store.forget_tracked_message_ids.assert_called_once_with(
_SCOPE.platform,
_SCOPE.chat_id,
{"startup_1"},
@@ -1454,7 +1490,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_outbound_message_id.side_effect = (
+ mock_session_store.record_message_id.side_effect = (
OSError("store unavailable"),
None,
)
@@ -1462,22 +1498,24 @@ async def test_failed_startup_notice_compensation_restores_clear_ownership(
await handler.publish_startup_notice(_startup_notice())
- assert mock_session_store.record_outbound_message_id.call_count == 2
- assert mock_session_store.record_outbound_message_id.call_args_list == [
+ 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",
+ "out",
"startup",
),
call(
_SCOPE.platform,
_SCOPE.chat_id,
"startup_1",
+ "out",
"startup",
),
]
- mock_session_store.forget_clearable_message_ids.assert_not_called()
+ mock_session_store.forget_tracked_message_ids.assert_not_called()
@pytest.mark.asyncio
@@ -1505,7 +1543,7 @@ async def test_startup_notice_publication_propagates_cancellation(
with pytest.raises(asyncio.CancelledError):
await task
await send_cancelled.wait()
- mock_session_store.record_outbound_message_id.assert_not_called()
+ mock_session_store.record_message_id.assert_not_called()
mock_platform.queue_delete_messages.assert_not_awaited()
@@ -1549,13 +1587,13 @@ async def test_startup_notice_cancellation_after_receipt_finishes_compensation(
with pytest.raises(asyncio.CancelledError):
await task
- mock_session_store.record_outbound_message_id.assert_not_called()
+ 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_clearable_message_ids.assert_called_once_with(
+ mock_session_store.forget_tracked_message_ids.assert_called_once_with(
_SCOPE.platform,
_SCOPE.chat_id,
{"startup_1"},
@@ -1590,7 +1628,7 @@ async def test_concurrent_global_clear_does_not_wait_for_startup_delivery(
)
await send_started.wait()
clear_task = asyncio.create_task(
- workflow.clear_all_state(_SCOPE.platform, _SCOPE.chat_id)
+ workflow.clear_chat(_SCOPE.platform, _SCOPE.chat_id)
)
try:
done, _pending = await asyncio.wait({clear_task}, timeout=1)
@@ -1600,9 +1638,7 @@ 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_clearable_message_ids_for_chat(_SCOPE.platform, _SCOPE.chat_id) == []
- )
+ assert store.get_tracked_message_ids_for_chat(_SCOPE.platform, _SCOPE.chat_id) == []
mock_platform.queue_delete_messages.assert_awaited_once_with(
_SCOPE.chat_id,
["startup_1"],
@@ -1638,10 +1674,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_outbound_message_id.assert_called_once_with(
+ mock_session_store.record_message_id.assert_called_once_with(
_SCOPE.platform,
_SCOPE.chat_id,
"startup_1",
+ "out",
"startup",
)
mock_platform.queue_delete_messages.assert_not_awaited()
@@ -1664,15 +1701,17 @@ async def test_global_clear_precedes_concurrent_startup_notice_publication(
clear_started = asyncio.Event()
release_clear = asyncio.Event()
- async def clear_trees(*, reason: CancellationReason) -> CancellationResult:
- assert reason is CancellationReason.STOP
+ async def clear_trees(
+ scope: MessageScope, *, reason: CancellationReason
+ ) -> CancellationResult:
+ assert reason is CancellationReason.CLEAR
clear_started.set()
await release_clear.wait()
return CancellationResult()
- with patch.object(workflow.tree_queue, "clear_all", side_effect=clear_trees):
+ with patch.object(workflow.tree_queue, "clear_scope", side_effect=clear_trees):
clear_task = asyncio.create_task(
- workflow.clear_all_state(_SCOPE.platform, _SCOPE.chat_id)
+ workflow.clear_chat(_SCOPE.platform, _SCOPE.chat_id)
)
await clear_started.wait()
publish_task = asyncio.create_task(
@@ -1686,14 +1725,14 @@ async def test_global_clear_precedes_concurrent_startup_notice_publication(
assert await clear_task == frozenset()
await publish_task
- assert store.get_clearable_message_ids_for_chat(
- _SCOPE.platform, _SCOPE.chat_id
- ) == ["msg_123"]
+ assert store.get_tracked_message_ids_for_chat(_SCOPE.platform, _SCOPE.chat_id) == [
+ "msg_123"
+ ]
mock_platform.queue_delete_messages.assert_not_awaited()
@pytest.mark.asyncio
-async def test_clear_command_cannot_evict_startup_notice_at_message_log_cap(
+async def test_clear_command_cannot_evict_startup_notice_at_managed_message_cap(
mock_platform,
mock_cli_manager,
incoming_message_factory,
@@ -1701,7 +1740,7 @@ async def test_clear_command_cannot_evict_startup_notice_at_message_log_cap(
) -> None:
store = SessionStore(
storage_path=str(tmp_path / "sessions.json"),
- message_log_cap=1,
+ managed_message_cap=1,
)
workflow = MessagingWorkflow(
mock_platform,
@@ -1710,10 +1749,11 @@ async def test_clear_command_cannot_evict_startup_notice_at_message_log_cap(
platform_name="telegram",
voice_cancellation=mock_platform,
)
- store.record_outbound_message_id(
+ store.record_message_id(
_SCOPE.platform,
_SCOPE.chat_id,
"100",
+ "out",
"startup",
)
incoming = incoming_message_factory(
@@ -1732,7 +1772,7 @@ async def test_clear_command_cannot_evict_startup_notice_at_message_log_cap(
@pytest.mark.asyncio
-async def test_clear_all_state_is_chat_scoped_for_deletes_and_global_for_fcc_state(
+async def test_clear_chat_is_fully_scoped_to_the_invoking_chat(
handler, mock_cli_manager, mock_session_store, incoming_message_factory
):
root_1 = incoming_message_factory(
@@ -1748,21 +1788,22 @@ 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_clearable_message_ids_for_chat.return_value = ["42"]
+ mock_session_store.get_tracked_message_ids_for_chat.return_value = ["42"]
mock_session_store.reset_mock()
- mock_session_store.get_clearable_message_ids_for_chat.return_value = ["42"]
+ mock_session_store.get_tracked_message_ids_for_chat.return_value = ["42"]
- message_ids = await handler.clear_all_state("telegram", "chat_1")
+ message_ids = await handler.clear_chat("telegram", "chat_1")
- assert message_ids == frozenset({"42", "101"})
+ assert message_ids == frozenset({"42", "100", "101"})
assert "200" not in message_ids
- assert handler.get_tree_count() == 0
- mock_cli_manager.stop_all.assert_awaited_once()
- mock_session_store.clear_all.assert_called_once()
+ assert handler.get_tree_count() == 1
+ assert await handler.tree_queue.get_node(root_2.scope, "200") is not None
+ mock_cli_manager.stop_all.assert_not_awaited()
+ mock_session_store.clear_scope.assert_called_once_with(_SCOPE)
@pytest.mark.asyncio
-async def test_clear_all_joins_voices_before_lock_and_returns_only_current_chat_ids(
+async def test_global_clear_cancels_and_deletes_only_current_chat_voices(
handler,
mock_platform,
mock_session_store,
@@ -1772,79 +1813,62 @@ async def test_clear_all_joins_voices_before_lock_and_returns_only_current_chat_
scope=_SCOPE,
voice_message_id="voice",
status_message_id="voice_status",
- )
- other = VoiceCancellationResult(
- scope=MessageScope(platform="telegram", chat_id="other"),
- voice_message_id="other_voice",
- status_message_id="other_status",
+ delete_message_ids=frozenset({"voice", "voice_status"}),
)
- async def cancel_voices() -> tuple[VoiceCancellationResult, ...]:
+ async def cancel_voices(scope: MessageScope) -> tuple[VoiceCancellationResult, ...]:
assert not handler._state_lock.locked()
+ assert scope == _SCOPE
events.append("voices")
- return (current, other)
+ return (current,)
- async def clear_trees(*, reason: CancellationReason) -> CancellationResult:
- assert reason is CancellationReason.STOP
+ async def clear_trees(
+ scope: MessageScope, *, reason: CancellationReason
+ ) -> CancellationResult:
+ assert reason is CancellationReason.CLEAR
assert handler._state_lock.locked()
events.append("trees")
return CancellationResult()
- mock_platform.cancel_all_pending_voices.side_effect = cancel_voices
- 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")
+ mock_platform.cancel_pending_voices_in_scope.side_effect = cancel_voices
+ mock_session_store.get_tracked_message_ids_for_chat.return_value = ["stored"]
+ with patch.object(handler.tree_queue, "clear_scope", side_effect=clear_trees):
+ message_ids = await handler.clear_chat("telegram", "chat_1")
await asyncio.sleep(0)
assert events == ["voices", "trees"]
- assert message_ids == frozenset({"stored", "voice_status"})
+ assert message_ids == frozenset({"stored", "voice", "voice_status"})
assert "other_voice" not in message_ids
assert "other_status" not in message_ids
- assert {
- call.args[1] for call in mock_platform.queue_edit_message.call_args_list
- } == {
- "voice_status",
- "other_status",
- }
+ mock_platform.queue_edit_message.assert_not_awaited()
@pytest.mark.asyncio
-async def test_global_clear_retries_transient_early_persistence_failure_at_final_write(
+async def test_global_clear_persists_after_tree_detach(
handler,
mock_cli_manager,
mock_session_store,
) -> None:
events: list[str] = []
- def fail_early_clear() -> None:
- events.append("store.clear_all")
- raise OSError("transient early clear failure")
-
- async def clear_trees(*, reason: CancellationReason) -> CancellationResult:
- assert reason is CancellationReason.STOP
- events.append("trees.clear_all")
+ async def clear_trees(
+ scope: MessageScope, *, reason: CancellationReason
+ ) -> CancellationResult:
+ assert scope == _SCOPE
+ assert reason is CancellationReason.CLEAR
+ events.append("trees.clear_scope")
return CancellationResult()
- def finish_persistence() -> None:
- events.append("store.clear_conversation_snapshot")
-
- async def stop_cli() -> None:
- events.append("cli.stop_all")
-
- mock_session_store.clear_all.side_effect = fail_early_clear
- mock_session_store.clear_conversation_snapshot.side_effect = finish_persistence
- mock_cli_manager.stop_all.side_effect = stop_cli
+ mock_session_store.clear_scope.side_effect = lambda scope: events.append(
+ f"store.clear_scope:{scope.chat_id}"
+ )
- with patch.object(handler.tree_queue, "clear_all", side_effect=clear_trees):
- result = await handler.clear_all_state("telegram", "chat_1")
+ with patch.object(handler.tree_queue, "clear_scope", side_effect=clear_trees):
+ result = await handler.clear_chat("telegram", "chat_1")
assert result == frozenset()
- assert events == [
- "store.clear_all",
- "trees.clear_all",
- "store.clear_conversation_snapshot",
- "cli.stop_all",
- ]
+ assert events == ["trees.clear_scope", "store.clear_scope:chat_1"]
+ mock_cli_manager.stop_all.assert_not_awaited()
@pytest.mark.asyncio
@@ -1855,89 +1879,65 @@ async def test_global_clear_finishes_cleanup_before_final_persistence_error_esca
) -> None:
events: list[str] = []
- def early_clear() -> None:
- events.append("store.clear_all")
-
- async def clear_trees(*, reason: CancellationReason) -> CancellationResult:
- assert reason is CancellationReason.STOP
- events.append("trees.clear_all")
+ async def clear_trees(
+ scope: MessageScope, *, reason: CancellationReason
+ ) -> CancellationResult:
+ assert scope == _SCOPE
+ assert reason is CancellationReason.CLEAR
+ events.append("trees.clear_scope")
return CancellationResult()
- def fail_final_clear() -> None:
- events.append("store.clear_conversation_snapshot")
+ def fail_final_clear(scope: MessageScope) -> None:
+ assert scope == _SCOPE
+ events.append("store.clear_scope")
raise OSError("final clear failure")
- async def stop_cli() -> None:
- events.append("cli.stop_all")
-
- mock_session_store.clear_all.side_effect = early_clear
- mock_session_store.clear_conversation_snapshot.side_effect = fail_final_clear
- mock_cli_manager.stop_all.side_effect = stop_cli
+ mock_session_store.clear_scope.side_effect = fail_final_clear
with (
- patch.object(handler.tree_queue, "clear_all", side_effect=clear_trees),
- patch.object(
- handler,
- "_apply_cancellation_result",
- side_effect=lambda _result: events.append("apply_cancellation"),
- ),
+ patch.object(handler.tree_queue, "clear_scope", side_effect=clear_trees),
pytest.raises(OSError, match="final clear failure"),
):
- await handler.clear_all_state("telegram", "chat_1")
+ await handler.clear_chat("telegram", "chat_1")
- assert events == [
- "store.clear_all",
- "trees.clear_all",
- "store.clear_conversation_snapshot",
- "apply_cancellation",
- "cli.stop_all",
- ]
+ assert events == ["trees.clear_scope", "store.clear_scope"]
+ mock_cli_manager.stop_all.assert_not_awaited()
@pytest.mark.asyncio
-async def test_global_clear_preserves_final_persistence_and_cli_stop_failures(
+async def test_global_clear_preserves_tree_and_persistence_failures(
handler,
mock_cli_manager,
mock_session_store,
) -> None:
events: list[str] = []
persistence_error = OSError("final clear failure")
- cli_error = RuntimeError("CLI stop failure")
+ tree_error = RuntimeError("tree clear failure")
- async def clear_trees(*, reason: CancellationReason) -> CancellationResult:
- assert reason is CancellationReason.STOP
- events.append("trees.clear_all")
- return CancellationResult()
+ async def fail_tree_clear(
+ scope: MessageScope, *, reason: CancellationReason
+ ) -> CancellationResult:
+ assert scope == _SCOPE
+ assert reason is CancellationReason.CLEAR
+ events.append("trees.clear_scope")
+ raise tree_error
- def fail_final_clear() -> None:
- events.append("store.clear_conversation_snapshot")
+ def fail_final_clear(scope: MessageScope) -> None:
+ assert scope == _SCOPE
+ events.append("store.clear_scope")
raise persistence_error
- async def fail_cli_stop() -> None:
- events.append("cli.stop_all")
- raise cli_error
-
- mock_session_store.clear_conversation_snapshot.side_effect = fail_final_clear
- mock_cli_manager.stop_all.side_effect = fail_cli_stop
+ mock_session_store.clear_scope.side_effect = fail_final_clear
with (
- patch.object(handler.tree_queue, "clear_all", side_effect=clear_trees),
- patch.object(
- handler,
- "_apply_cancellation_result",
- side_effect=lambda _result: events.append("apply_cancellation"),
- ),
+ patch.object(handler.tree_queue, "clear_scope", side_effect=fail_tree_clear),
pytest.raises(ExceptionGroup) as raised,
):
- await handler.clear_all_state("telegram", "chat_1")
+ await handler.clear_chat("telegram", "chat_1")
- assert raised.value.exceptions == (persistence_error, cli_error)
- assert events == [
- "trees.clear_all",
- "store.clear_conversation_snapshot",
- "apply_cancellation",
- "cli.stop_all",
- ]
+ assert raised.value.exceptions == (tree_error, persistence_error)
+ assert events == ["trees.clear_scope", "store.clear_scope"]
+ mock_cli_manager.stop_all.assert_not_awaited()
@pytest.mark.asyncio
@@ -1949,34 +1949,30 @@ async def test_committed_global_clear_attempts_remaining_steps_after_tree_failur
events: list[str] = []
tree_error = RuntimeError("tree clear failure")
- async def fail_tree_clear(*, reason: CancellationReason) -> CancellationResult:
- assert reason is CancellationReason.STOP
- events.append("trees.clear_all")
+ async def fail_tree_clear(
+ scope: MessageScope, *, reason: CancellationReason
+ ) -> CancellationResult:
+ assert scope == _SCOPE
+ assert reason is CancellationReason.CLEAR
+ events.append("trees.clear_scope")
raise tree_error
- mock_session_store.clear_conversation_snapshot.side_effect = lambda: events.append(
- "store.clear_conversation_snapshot"
+ mock_session_store.clear_scope.side_effect = lambda scope: events.append(
+ f"store.clear_scope:{scope.chat_id}"
)
- mock_cli_manager.stop_all.side_effect = lambda: events.append("cli.stop_all")
with (
- patch.object(handler.tree_queue, "clear_all", side_effect=fail_tree_clear),
- patch.object(
- handler,
- "_apply_cancellation_result",
- side_effect=lambda _result: events.append("apply_cancellation"),
- ),
+ patch.object(handler.tree_queue, "clear_scope", side_effect=fail_tree_clear),
pytest.raises(RuntimeError, match="tree clear failure") as raised,
):
- await handler.clear_all_state("telegram", "chat_1")
+ await handler.clear_chat("telegram", "chat_1")
assert raised.value is tree_error
assert events == [
- "trees.clear_all",
- "store.clear_conversation_snapshot",
- "apply_cancellation",
- "cli.stop_all",
+ "trees.clear_scope",
+ "store.clear_scope:chat_1",
]
+ mock_cli_manager.stop_all.assert_not_awaited()
@pytest.mark.asyncio
@@ -2000,12 +1996,10 @@ async def test_cancelled_global_clear_finishes_owned_transaction_before_propagat
mock_session_store.reset_mock()
with patch.object(
handler.tree_queue,
- "get_clearable_message_ids_for_chat",
+ "get_message_ids_for_chat",
new=block_id_read,
):
- clear_task = asyncio.create_task(
- handler.clear_all_state("telegram", root.chat_id)
- )
+ clear_task = asyncio.create_task(handler.clear_chat("telegram", root.chat_id))
await id_read_started.wait()
clear_task.cancel()
await asyncio.sleep(0)
@@ -2014,18 +2008,17 @@ async def test_cancelled_global_clear_finishes_owned_transaction_before_propagat
with pytest.raises(asyncio.CancelledError):
await clear_task
- assert handler._admission_epoch == 1
+ assert handler._clear_generations[_SCOPE] == 1
assert handler.get_tree_count() == 0
- mock_session_store.clear_all.assert_called_once()
- mock_session_store.clear_conversation_snapshot.assert_called_once()
- mock_cli_manager.stop_all.assert_awaited_once()
+ mock_session_store.clear_scope.assert_called_once_with(_SCOPE)
+ mock_cli_manager.stop_all.assert_not_awaited()
@pytest.mark.asyncio
async def test_clear_with_mention_uses_same_global_command(
handler, mock_platform, incoming_message_factory
):
- handler.clear_all_state = AsyncMock(return_value=frozenset())
+ handler.clear_chat = AsyncMock(return_value=frozenset())
incoming = incoming_message_factory(
text="/clear@MyBot",
chat_id="chat_1",
@@ -2034,7 +2027,7 @@ async def test_clear_with_mention_uses_same_global_command(
await handler.handle_message(incoming)
- handler.clear_all_state.assert_awaited_once_with("telegram", "chat_1")
+ handler.clear_chat.assert_awaited_once_with("telegram", "chat_1")
mock_platform.queue_delete_messages.assert_awaited_once_with(
"chat_1",
["10"],
@@ -2046,7 +2039,7 @@ async def test_clear_with_mention_uses_same_global_command(
async def test_clear_continues_after_platform_delete_failure(
handler, mock_platform, incoming_message_factory
):
- handler.clear_all_state = AsyncMock(return_value=frozenset({"41", "42"}))
+ handler.clear_chat = AsyncMock(return_value=frozenset({"41", "42"}))
mock_platform.queue_delete_messages.side_effect = RuntimeError(
"platform rejected delete"
)
@@ -2055,12 +2048,12 @@ async def test_clear_continues_after_platform_delete_failure(
incoming_message_factory(text="/clear", message_id="150")
)
- handler.clear_all_state.assert_awaited_once()
+ handler.clear_chat.assert_awaited_once()
mock_platform.queue_delete_messages.assert_awaited_once()
@pytest.mark.asyncio
-async def test_reply_clear_removes_only_branch_and_persists_remaining_tree(
+async def test_reply_clear_status_preserves_prompt_and_persists_remaining_tree(
handler,
mock_platform,
mock_session_store,
@@ -2074,7 +2067,7 @@ async def test_reply_clear_removes_only_branch_and_persists_remaining_tree(
)
await handler.tree_queue.admit(root, "101")
await _wait_for_idle(handler)
- await handler.tree_queue.admit(child, "103", parent_node_id="100")
+ await handler.tree_queue.admit(child, "103", parent_reference_id="100")
await _wait_for_idle(handler)
mock_session_store.reset_mock()
deleted_ids: list[str] = []
@@ -2095,15 +2088,20 @@ async def test_reply_clear_removes_only_branch_and_persists_remaining_tree(
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
+ cleared_prompt = await handler.tree_queue.get_node(root.scope, "102")
+ assert cleared_prompt is not None
+ assert cleared_prompt.state is MessageState.ERROR
+ assert cleared_prompt.session_id 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.record_clear_command_id.assert_called_once_with(
+ mock_session_store.record_message_id.assert_called_once_with(
"telegram",
"chat_1",
"150",
+ "in",
+ "command",
)
- mock_session_store.forget_clearable_message_ids.assert_called_once_with(
+ mock_session_store.forget_tracked_message_ids.assert_called_once_with(
"telegram",
"chat_1",
{"103", "150"},
@@ -2123,12 +2121,14 @@ 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_clear_command_id.assert_any_call(
+ mock_session_store.record_message_id.assert_any_call(
incoming.platform,
incoming.chat_id,
incoming.message_id,
+ "in",
+ "command",
)
- mock_session_store.clear_all.assert_not_called()
+ mock_session_store.clear_scope.assert_not_called()
@pytest.mark.asyncio
@@ -2156,8 +2156,7 @@ async def test_reply_clear_root_removes_tree_snapshot(
)
)
- assert set(deleted_ids) == {"101", "150"}
- assert "100" not in deleted_ids
+ assert set(deleted_ids) == {"100", "101", "150"}
mock_session_store.remove_tree_snapshot.assert_called_once_with(
TreeIdentity(scope=root.scope, root_id="100")
)
@@ -2165,8 +2164,12 @@ async def test_reply_clear_root_removes_tree_snapshot(
@pytest.mark.asyncio
-async def test_late_cancelled_runner_cannot_save_after_global_clear(
- handler, mock_cli_manager, mock_session_store, incoming_message_factory
+async def test_late_cancelled_runner_cannot_save_or_render_after_chat_clear(
+ handler,
+ mock_platform,
+ mock_cli_manager,
+ mock_session_store,
+ incoming_message_factory,
):
started = asyncio.Event()
@@ -2188,11 +2191,13 @@ async def test_late_cancelled_runner_cannot_save_after_global_clear(
)
await started.wait()
mock_session_store.reset_mock()
+ mock_platform.queue_edit_message.reset_mock()
- await handler.clear_all_state("telegram", "chat_1")
+ await handler.clear_chat("telegram", "chat_1")
mock_session_store.save_tree_snapshot.assert_not_called()
- mock_session_store.clear_all.assert_called_once()
+ mock_session_store.clear_scope.assert_called_once_with(_SCOPE)
+ mock_platform.queue_edit_message.assert_not_awaited()
assert handler.get_tree_count() == 0
@@ -2233,7 +2238,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_clearable_message_ids_for_chat
+ get_ids = workflow.tree_queue.get_message_ids_for_chat
async def block_id_read(platform: str, chat_id: str) -> set[str]:
id_read_started.set()
@@ -2243,11 +2248,11 @@ async def test_global_clear_removes_snapshot_saved_during_detach_window(
try:
with patch.object(
workflow.tree_queue,
- "get_clearable_message_ids_for_chat",
+ "get_message_ids_for_chat",
new=block_id_read,
):
clear_task = asyncio.create_task(
- workflow.clear_all_state("telegram", incoming.chat_id)
+ workflow.clear_chat("telegram", incoming.chat_id)
)
await id_read_started.wait()
release_runner.set()
@@ -2296,7 +2301,7 @@ async def test_global_clear_invalidates_inflight_prompt_without_waiting_for_stat
)
)
await status_send_started.wait()
- clear_task = asyncio.create_task(handler.clear_all_state("telegram", "chat_1"))
+ clear_task = asyncio.create_task(handler.clear_chat("telegram", "chat_1"))
try:
await asyncio.wait_for(clear_task, timeout=1)
@@ -2320,8 +2325,8 @@ async def test_global_clear_invalidates_inflight_prompt_without_waiting_for_stat
@pytest.mark.parametrize(
("status_message_id", "expected_deleted_ids"),
[
- ("101", {"101", "150"}),
- (None, {"150"}),
+ ("101", {"100", "101", "150"}),
+ (None, {"100", "150"}),
],
)
async def test_reply_clear_pending_voice_cancels_and_reports(
@@ -2331,13 +2336,13 @@ async def test_reply_clear_pending_voice_cancels_and_reports(
status_message_id,
expected_deleted_ids,
) -> None:
- clearable_message_ids = (
- {status_message_id} if status_message_id is not None else set()
- )
+ delete_message_ids = {"100"}
+ if status_message_id is not None:
+ delete_message_ids.add(status_message_id)
handler.clear_reply = AsyncMock(
return_value=ReplyClearResult(
- clearable_message_ids=frozenset(clearable_message_ids),
- tree_cleared=False,
+ delete_message_ids=frozenset(delete_message_ids),
+ tree_matched=False,
)
)
deleted_ids: list[str] = []
@@ -2356,7 +2361,7 @@ async def test_reply_clear_pending_voice_cancels_and_reports(
handler.clear_reply.assert_awaited_once_with(incoming.scope, "100")
assert set(deleted_ids) == expected_deleted_ids
- assert "Voice note cancelled" in mock_platform.queue_send_message.call_args.args[1]
+ mock_platform.queue_send_message.assert_not_awaited()
@pytest.mark.asyncio
@@ -2367,8 +2372,8 @@ async def test_reply_clear_deletes_owned_result_ids(
) -> None:
handler.clear_reply = AsyncMock(
return_value=ReplyClearResult(
- clearable_message_ids=frozenset({"tree_status"}),
- tree_cleared=True,
+ delete_message_ids=frozenset({"tree_status"}),
+ tree_matched=True,
)
)
deleted_ids: list[str] = []
@@ -2407,42 +2412,36 @@ async def test_reply_clear_joins_voice_then_unions_authoritative_branch_ids(
scope=_SCOPE,
voice_message_id="voice",
status_message_id="voice_status",
+ delete_message_ids=frozenset({"voice", "voice_status"}),
)
- async def resolve_tree(*_args) -> str:
- events.append("resolve")
- return "voice"
-
- branch = BranchRemovalResult(
+ branch = MessageSubtreeRemovalResult(
cancellation=CancellationResult(),
removed_tree_identity=None,
- clearable_message_ids=frozenset({"tree_status"}),
+ delete_message_ids=frozenset({"tree_status"}),
+ tree_matched=True,
)
mock_platform.cancel_pending_voice.side_effect = cancel_voice
- with (
- patch.object(
- handler.tree_queue,
- "resolve_node_id",
- side_effect=resolve_tree,
- ) as resolve,
- patch.object(
- handler.tree_queue,
- "remove_branch",
- new_callable=AsyncMock,
- return_value=branch,
- ) as remove_branch,
- ):
+ with patch.object(
+ handler.tree_queue,
+ "remove_message_subtree",
+ new_callable=AsyncMock,
+ return_value=branch,
+ ) as remove_message_subtree:
result = await handler.clear_reply(_SCOPE, "voice")
await asyncio.sleep(0)
assert result == ReplyClearResult(
- clearable_message_ids=frozenset({"voice_status", "tree_status"}),
- tree_cleared=True,
+ delete_message_ids=frozenset({"voice", "voice_status", "tree_status"}),
+ tree_matched=True,
)
- assert events == ["voice", "resolve"]
- resolve.assert_awaited_once_with(_SCOPE, "voice")
- remove_branch.assert_awaited_once_with(_SCOPE, "voice")
- mock_platform.queue_edit_message.assert_awaited_once()
+ assert events == ["voice"]
+ remove_message_subtree.assert_awaited_once_with(
+ _SCOPE,
+ "voice",
+ reason=CancellationReason.CLEAR,
+ )
+ mock_platform.queue_edit_message.assert_not_awaited()
@pytest.mark.asyncio
@@ -2458,13 +2457,25 @@ async def test_cancelled_reply_clear_finishes_voice_only_owner_after_lock_wait(
scope=_SCOPE,
voice_message_id="voice",
status_message_id="voice_status",
+ delete_message_ids=frozenset({"voice", "voice_status"}),
)
mock_platform.cancel_pending_voice.side_effect = cancel_voice
- resolve = AsyncMock(return_value=None)
+ remove_subtree = AsyncMock(
+ return_value=MessageSubtreeRemovalResult(
+ cancellation=CancellationResult(),
+ removed_tree_identity=None,
+ delete_message_ids=frozenset(),
+ tree_matched=False,
+ )
+ )
await handler._state_lock.acquire()
try:
- with patch.object(handler.tree_queue, "resolve_node_id", resolve):
+ with patch.object(
+ handler.tree_queue,
+ "remove_message_subtree",
+ remove_subtree,
+ ):
clear_task = asyncio.create_task(handler.clear_reply(_SCOPE, "voice"))
await voice_returned.wait()
await asyncio.sleep(0)
@@ -2480,6 +2491,9 @@ async def test_cancelled_reply_clear_finishes_voice_only_owner_after_lock_wait(
handler._state_lock.release()
await asyncio.sleep(0)
- resolve.assert_awaited_once_with(_SCOPE, "voice")
- mock_platform.queue_edit_message.assert_awaited_once()
- assert mock_platform.queue_edit_message.call_args.args[1] == "voice_status"
+ remove_subtree.assert_awaited_once_with(
+ _SCOPE,
+ "voice",
+ reason=CancellationReason.CLEAR,
+ )
+ mock_platform.queue_edit_message.assert_not_awaited()
diff --git a/tests/messaging/test_handler_markdown_and_status_edges.py b/tests/messaging/test_handler_markdown_and_status_edges.py
index 4767144b..48156cbf 100644
--- a/tests/messaging/test_handler_markdown_and_status_edges.py
+++ b/tests/messaging/test_handler_markdown_and_status_edges.py
@@ -14,6 +14,7 @@ from free_claude_code.messaging.trees import (
CancellationResult,
CancellationUiOwner,
FailureResult,
+ MessageReferenceKind,
NodeClaim,
NodeUiTarget,
QueueDecision,
@@ -131,13 +132,23 @@ def test_get_initial_status_branches():
handler = MessagingWorkflow(platform, cli_manager, session_store)
s1 = handler.turn_intake._get_initial_status(
- ReplyTarget(node_id="p", queue_position=3)
+ ReplyTarget(
+ node_id="p",
+ reference_id="p",
+ reference_kind=MessageReferenceKind.PROMPT,
+ queue_position=3,
+ )
)
assert "Queued" in s1
assert "position 3" in s1 or "position 3" in s1.replace("\\", "")
s2 = handler.turn_intake._get_initial_status(
- ReplyTarget(node_id="p", queue_position=None)
+ ReplyTarget(
+ node_id="p",
+ reference_id="status-p",
+ reference_kind=MessageReferenceKind.STATUS,
+ queue_position=None,
+ )
)
assert "Continuing" in s2
@@ -329,7 +340,7 @@ async def test_handle_message_unresolved_reply_is_admitted_as_new():
admit.assert_awaited_once_with(
incoming,
"status_1",
- parent_node_id=None,
+ parent_reference_id=None,
)
@@ -415,7 +426,7 @@ async def test_handle_message_incoming_text_none_safe():
admit.assert_awaited_once_with(
incoming,
"status_1",
- parent_node_id=None,
+ parent_reference_id=None,
)
diff --git a/tests/messaging/test_message_tree_transitions.py b/tests/messaging/test_message_tree_transitions.py
index 9bed0d0c..6b0a0b57 100644
--- a/tests/messaging/test_message_tree_transitions.py
+++ b/tests/messaging/test_message_tree_transitions.py
@@ -26,6 +26,7 @@ async def _add(
node_id: str,
status_message_id: str,
parent_id: str = "root",
+ parent_reference_id: str | None = None,
):
return await tree.add_and_enqueue(
node_id,
@@ -33,6 +34,7 @@ async def _add(
f"prompt {node_id}",
status_message_id,
parent_id,
+ parent_reference_id or parent_id,
)
@@ -158,16 +160,54 @@ async def test_cancelled_queue_member_is_never_claimed() -> None:
@pytest.mark.asyncio
-async def test_branch_removal_separates_references_from_clearable_messages() -> None:
+async def test_prompt_subtree_removal_returns_every_platform_message() -> None:
tree = _tree()
await _add(tree, "child", "status-child")
- removed = await tree.remove_branch("root")
+ removed = await tree.remove_message_subtree("root")
- assert removed.reference_ids == frozenset(
+ assert removed.removed_message_ids == frozenset(
{"root", "status-root", "child", "status-child"}
)
- assert removed.clearable_message_ids == frozenset({"status-root", "status-child"})
+
+
+async def test_status_subtree_preserves_prompt_siblings_and_invalidates_resume() -> (
+ None
+):
+ tree = _tree()
+ root = await tree.enqueue_or_claim("root")
+ assert root.claim is not None
+ await tree.record_session(root.claim.claim_id, "session-root")
+ direct_sibling = await _add(tree, "sibling", "status-sibling")
+ status_descendant = await _add(
+ tree,
+ "descendant",
+ "status-descendant",
+ parent_reference_id="status-root",
+ )
+ assert direct_sibling.position == 1
+ assert status_descendant.position == 2
+
+ removed = await tree.remove_message_subtree("status-root")
+
+ assert removed.removed_message_ids == frozenset(
+ {"status-root", "descendant", "status-descendant"}
+ )
+ root_view = await tree.node_view("root")
+ sibling_view = await tree.node_view("sibling")
+ assert root_view is not None
+ assert root_view.state is MessageState.ERROR
+ assert root_view.session_id is None
+ assert sibling_view is not None
+ assert sibling_view.state is MessageState.PENDING
+ assert await tree.node_view("descendant") is None
+ assert await tree.resolve_reply("status-root") is None
+
+ completion = await tree.finish_and_claim_next(root.claim.claim_id)
+ assert completion.next_claim is not None
+ assert completion.next_claim.node.node_id == "sibling"
+ assert completion.next_claim.parent_session_id is None
@pytest.mark.asyncio
diff --git a/tests/messaging/test_platform_voice_flow.py b/tests/messaging/test_platform_voice_flow.py
index 113fe072..40ee4946 100644
--- a/tests/messaging/test_platform_voice_flow.py
+++ b/tests/messaging/test_platform_voice_flow.py
@@ -561,7 +561,11 @@ async def test_global_command_rejects_transcription_that_finishes_late(
await asyncio.wait_for(
workflow.handle_message(
- incoming_message_factory(text=command, message_id="command")
+ incoming_message_factory(
+ text=command,
+ message_id="command",
+ chat_id=VOICE_SCOPE.chat_id,
+ )
),
timeout=1,
)
diff --git a/tests/messaging/test_session_store_edge_cases.py b/tests/messaging/test_session_store_edge_cases.py
index a8ee2f03..077060d1 100644
--- a/tests/messaging/test_session_store_edge_cases.py
+++ b/tests/messaging/test_session_store_edge_cases.py
@@ -15,6 +15,7 @@ from free_claude_code.messaging.session.persistence import DebouncedJsonPersiste
from free_claude_code.messaging.trees import TreeIdentity, TreeSnapshot
TELEGRAM_C1 = MessageScope(platform="telegram", chat_id="c1")
+TELEGRAM_C2 = MessageScope(platform="telegram", chat_id="c2")
def _identity(root_id: str, scope: MessageScope = TELEGRAM_C1) -> TreeIdentity:
@@ -500,7 +501,7 @@ class TestSessionStoreAtomicWrites:
),
pytest.raises(OSError, match="clear replace failed"),
):
- store.clear_all()
+ store.clear_scope(TELEGRAM_C1)
assert store.load_conversation_snapshot().is_empty
assert store.dirty is True
@@ -525,17 +526,17 @@ class TestSessionStoreAtomicWrites:
),
pytest.raises(RuntimeError, match="authoritative snapshot failed"),
):
- store.clear_all()
+ store.clear_scope(TELEGRAM_C1)
assert store.dirty is True
- store.clear_all()
+ store.clear_scope(TELEGRAM_C1)
assert store.dirty is False
-class TestSessionStoreClearAll:
- def test_clear_all_wipes_state_and_persists(self, tmp_path):
+class TestSessionStoreClearScope:
+ def test_clear_scope_wipes_matching_state_and_persists(self, tmp_path):
path = str(tmp_path / "sessions.json")
store = SessionStore(storage_path=path)
@@ -567,37 +568,74 @@ class TestSessionStoreClearAll:
)
)
- store.clear_all()
+ store.clear_scope(TELEGRAM_C1)
assert store.load_conversation_snapshot().is_empty
with open(path, encoding="utf-8") as f:
data = json.load(f)
assert data["conversation"]["trees"] == []
- assert data["message_log"] == {}
+ assert data["managed_messages"] == {}
store2 = SessionStore(storage_path=path)
assert store2.load_conversation_snapshot().is_empty
- def test_clearable_message_log_persists_and_dedups(self, tmp_path):
+ def test_clear_scope_preserves_other_chat_trees_and_messages(self, tmp_path):
+ path = str(tmp_path / "sessions.json")
+ store = SessionStore(storage_path=path)
+ other_tree = TreeSnapshot(
+ scope=TELEGRAM_C2,
+ root_id="root2",
+ nodes={
+ "root2": {
+ "node_id": "root2",
+ "status_message_id": "status2",
+ "state": "completed",
+ "parent_id": None,
+ "parent_reference_id": None,
+ "session_id": "session2",
+ }
+ },
+ )
+ store.save_tree_snapshot(other_tree)
+ store.record_message_id("telegram", "c1", "message1", "in", "prompt")
+ store.record_message_id("telegram", "c2", "message2", "in", "prompt")
+
+ store.clear_scope(TELEGRAM_C1)
+
+ assert (
+ store.load_conversation_snapshot().get_tree(other_tree.identity) is not None
+ )
+ assert store.get_tracked_message_ids_for_chat("telegram", "c1") == []
+ assert store.get_tracked_message_ids_for_chat("telegram", "c2") == ["message2"]
+ restored = SessionStore(storage_path=path)
+ assert (
+ restored.load_conversation_snapshot().get_tree(other_tree.identity)
+ is not None
+ )
+ assert restored.get_tracked_message_ids_for_chat("telegram", "c2") == [
+ "message2"
+ ]
+
+ def test_managed_message_log_persists_and_dedups(self, tmp_path):
path = str(tmp_path / "sessions.json")
store = SessionStore(storage_path=path)
- 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")
+ store.record_message_id("telegram", "c1", "2", "out", "command")
+ store.record_message_id("telegram", "c1", "2", "out", "command")
+ store.record_message_id("telegram", "c1", "3", "in", "command")
- ids = store.get_clearable_message_ids_for_chat("telegram", "c1")
+ ids = store.get_tracked_message_ids_for_chat("telegram", "c1")
assert ids == ["2", "3"]
store.flush_pending_save()
store2 = SessionStore(storage_path=path)
- assert store2.get_clearable_message_ids_for_chat("telegram", "c1") == [
+ assert store2.get_tracked_message_ids_for_chat("telegram", "c1") == [
"2",
"3",
]
- def test_load_drops_legacy_user_messages_from_clearable_log(self, tmp_path):
+ def test_load_preserves_legacy_managed_messages(self, tmp_path):
path = tmp_path / "sessions.json"
path.write_text(
json.dumps(
@@ -634,7 +672,9 @@ class TestSessionStoreClearAll:
store = SessionStore(storage_path=str(path))
- assert store.get_clearable_message_ids_for_chat("telegram", "c1") == [
+ assert store.get_tracked_message_ids_for_chat("telegram", "c1") == [
+ "prompt",
+ "old-command",
"status",
"clear-command",
]
diff --git a/tests/messaging/test_tree_concurrency.py b/tests/messaging/test_tree_concurrency.py
index 750e6d3b..bd0e9518 100644
--- a/tests/messaging/test_tree_concurrency.py
+++ b/tests/messaging/test_tree_concurrency.py
@@ -77,7 +77,7 @@ async def test_one_tree_processes_fifo_with_transition_owned_queue_updates() ->
await manager.admit(
_incoming(node_id, reply_to="root"),
f"status-{node_id}",
- parent_node_id="root",
+ parent_reference_id="root",
)
for node_id in node_ids[1:]
]
@@ -167,12 +167,12 @@ async def test_cancel_all_cancels_active_and_queued_work_across_trees() -> None:
await manager.admit(
_incoming("one-child", reply_to="one"),
"status-one-child",
- parent_node_id="one",
+ parent_reference_id="one",
)
await manager.admit(
_incoming("two-child", reply_to="two"),
"status-two-child",
- parent_node_id="two",
+ parent_reference_id="two",
)
result = await manager.cancel_all(reason=CancellationReason.STOP)
@@ -221,27 +221,29 @@ async def test_branch_removal_atomically_unindexes_subtree_and_preserves_sibling
await manager.admit(
_incoming("branch", reply_to="root"),
"status-branch",
- parent_node_id="root",
+ parent_reference_id="root",
)
await manager.admit(
_incoming("leaf", reply_to="branch"),
"status-leaf",
- parent_node_id="branch",
+ parent_reference_id="branch",
)
await manager.admit(
_incoming("sibling", reply_to="root"),
"status-sibling",
- parent_node_id="root",
+ parent_reference_id="root",
)
- result = await manager.remove_branch(
+ result = await manager.remove_message_subtree(
_SCOPE,
- "status-branch",
+ "branch",
reason=CancellationReason.STOP,
)
assert result.removed_tree_identity is None
- assert result.clearable_message_ids == frozenset({"status-branch", "status-leaf"})
+ assert result.delete_message_ids == frozenset(
+ {"branch", "status-branch", "leaf", "status-leaf"}
+ )
assert {
effect.node.node_id: effect.ui_owner for effect in result.cancellation.effects
} == {
@@ -277,19 +279,21 @@ async def test_root_removal_atomically_cancels_and_unindexes_entire_tree() -> No
await manager.admit(
_incoming("child", reply_to="root"),
"status-child",
- parent_node_id="root",
+ parent_reference_id="root",
)
- result = await manager.remove_branch(
+ result = await manager.remove_message_subtree(
_SCOPE,
- "status-root",
+ "root",
reason=CancellationReason.STOP,
)
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.clearable_message_ids == frozenset({"status-root", "status-child"})
+ assert result.delete_message_ids == frozenset(
+ {"root", "status-root", "child", "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 7f3307c1..45d7e661 100644
--- a/tests/messaging/test_tree_customer_regressions.py
+++ b/tests/messaging/test_tree_customer_regressions.py
@@ -65,12 +65,8 @@ 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_clearable_message_ids_for_chat("telegram", "chat-a") == {
- "99"
- }
- assert await restored.get_clearable_message_ids_for_chat("telegram", "chat-b") == {
- "99"
- }
+ assert await restored.get_message_ids_for_chat("telegram", "chat-a") == {"42", "99"}
+ assert await restored.get_message_ids_for_chat("telegram", "chat-b") == {"42", "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 f18bb7af..e324c9a8 100644
--- a/tests/messaging/test_tree_ownership_concurrency.py
+++ b/tests/messaging/test_tree_ownership_concurrency.py
@@ -7,6 +7,7 @@ from free_claude_code.messaging.models import IncomingMessage, MessageScope
from free_claude_code.messaging.trees import manager as manager_module
from free_claude_code.messaging.trees.manager import TreeQueueManager
from free_claude_code.messaging.trees.transitions import (
+ AdmissionRejection,
CancellationReason,
CancellationUiOwner,
NodeClaim,
@@ -76,7 +77,7 @@ async def test_cancelled_finisher_cannot_erase_or_overlap_a_new_claim() -> None:
child = await manager.admit(
_incoming("child", reply_to="root"),
"status-child",
- parent_node_id="root",
+ parent_reference_id="root",
)
assert child.position == 1
@@ -117,7 +118,7 @@ async def test_cancelled_runner_exception_cannot_fail_or_skip_queued_claim() ->
await manager.admit(
_incoming("child", reply_to="root"),
"status-child",
- parent_node_id="root",
+ parent_reference_id="root",
)
try:
@@ -168,7 +169,7 @@ async def test_terminal_operation_serializes_with_successor_task_publication(
await manager.admit(
_incoming("child", reply_to="root"),
"status-child",
- parent_node_id="root",
+ parent_reference_id="root",
)
tree = manager._repository.get_tree(root.claim.identity)
assert tree is not None
@@ -196,11 +197,11 @@ async def test_terminal_operation_serializes_with_successor_task_publication(
)
elif operation == "global_clear":
operation_task = asyncio.create_task(
- manager.clear_all(reason=CancellationReason.STOP)
+ manager.clear_scope(_SCOPE, reason=CancellationReason.STOP)
)
else:
operation_task = asyncio.create_task(
- manager.remove_branch(
+ manager.remove_message_subtree(
_SCOPE,
"root",
reason=CancellationReason.STOP,
@@ -295,7 +296,7 @@ async def test_callback_failure_does_not_block_the_next_claim() -> None:
await manager.admit(
_incoming("child", reply_to="root"),
"status-child",
- parent_node_id="root",
+ parent_reference_id="root",
)
release_root.set()
@@ -319,22 +320,21 @@ async def test_branch_removal_cannot_leave_a_detached_running_descendant() -> No
await manager.admit(
_incoming("branch", reply_to="root"),
"status-branch",
- parent_node_id="root",
+ parent_reference_id="root",
)
- removed = await manager.remove_branch(_SCOPE, "branch")
+ removed = await manager.remove_message_subtree(_SCOPE, "branch")
late = await manager.admit(
_incoming("late", reply_to="branch"),
"status-late",
- parent_node_id="branch",
+ parent_reference_id="branch",
)
- assert removed.clearable_message_ids == frozenset({"status-branch"})
+ assert removed.delete_message_ids == frozenset({"branch", "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")
- assert late_node is not None
- assert late_node.parent_id is None
+ assert late.accepted is False
+ assert late.rejection is AdmissionRejection.PARENT_REMOVED
+ assert await manager.get_node(_SCOPE, "late") is None
release_root.set()
@@ -359,7 +359,7 @@ async def test_clear_all_drains_terminal_claim_task_before_returning() -> None:
await terminal.wait()
try:
- await manager.clear_all(reason=CancellationReason.STOP)
+ await manager.clear_scope(_SCOPE, reason=CancellationReason.STOP)
assert cleanup_finished.is_set()
assert manager.task_count() == 0
@@ -392,7 +392,9 @@ async def test_clear_all_returns_committed_result_after_caller_cancellation() ->
asyncio.get_running_loop().call_soon(checkpoint.set)
await checkpoint.wait()
- clear_task = asyncio.create_task(manager.clear_all(reason=CancellationReason.STOP))
+ clear_task = asyncio.create_task(
+ manager.clear_scope(_SCOPE, reason=CancellationReason.STOP)
+ )
await runner_cancelled.wait()
try:
@@ -478,7 +480,7 @@ async def test_absorbed_pre_run_cancellation_cannot_start_node_processor() -> No
child = await manager.admit(
_incoming("child", reply_to="root"),
"status-child",
- parent_node_id="root",
+ parent_reference_id="root",
)
assert child.position == 1
@@ -530,7 +532,7 @@ async def test_same_scoped_root_can_be_readmitted_while_detached_claim_finishes(
await old_started.wait()
try:
- cleared = await manager.clear_all(reason=CancellationReason.STOP)
+ cleared = await manager.clear_scope(_SCOPE, reason=CancellationReason.STOP)
await old_cancelled.wait()
assert {effect.node.node_id for effect in cleared.effects} == {"root"}
assert manager.get_tree_count() == 0
diff --git a/tests/messaging/test_tree_processor.py b/tests/messaging/test_tree_processor.py
index 4f747cc8..277688a7 100644
--- a/tests/messaging/test_tree_processor.py
+++ b/tests/messaging/test_tree_processor.py
@@ -102,7 +102,7 @@ async def test_queued_cancel_returns_workflow_effect_and_exact_queue_update() ->
decision = await manager.admit(
_incoming("child", reply_to="root"),
"status-child",
- parent_node_id="root",
+ parent_reference_id="root",
)
assert decision.position == 1
@@ -192,7 +192,7 @@ async def test_escaped_processor_failure_persists_effects_through_manager_owner(
await manager.admit(
_incoming("child", reply_to="root"),
"status-child",
- parent_node_id="root",
+ parent_reference_id="root",
)
release.set()
@@ -229,7 +229,7 @@ async def test_wait_idle_spans_successor_publication_and_completion() -> None:
await manager.admit(
_incoming("child", reply_to="root"),
"status-child",
- parent_node_id="root",
+ parent_reference_id="root",
)
idle_task = asyncio.create_task(manager.wait_idle())
diff --git a/tests/messaging/test_tree_queue.py b/tests/messaging/test_tree_queue.py
index 8bfb4a2d..11692989 100644
--- a/tests/messaging/test_tree_queue.py
+++ b/tests/messaging/test_tree_queue.py
@@ -36,6 +36,7 @@ def _add(
prompt=f"prompt {node_id}",
status_message_id=status_message_id,
parent_id=parent_id,
+ parent_reference_id=parent_id,
)
@@ -54,6 +55,7 @@ def test_node_snapshot_round_trip_preserves_execution_state_only() -> None:
assert restored.status_message_id == "status-root"
assert restored.state is MessageState.COMPLETED
assert restored.session_id == "session-root"
+ assert restored.parent_reference_id is None
assert restored.children_ids == []
assert "children_ids" not in snapshot
assert "created_at" not in snapshot
@@ -95,6 +97,41 @@ def test_graph_restore_normalizes_numeric_ids_to_string_references() -> None:
assert child is not None and child.node_id == "2"
+def test_graph_restore_normalizes_legacy_parent_to_prompt_reference() -> None:
+ graph = MessageTreeGraph(_root())
+ _add(graph, "child", "status-child", "root")
+ snapshot = graph.snapshot()
+ snapshot.nodes["child"].pop("parent_reference_id")
+
+ restored = MessageTreeGraph.from_snapshot(snapshot)
+
+ child = restored.get_node("child")
+ assert child is not None
+ assert child.parent_reference_id == "root"
+ assert restored.snapshot().nodes["child"]["parent_reference_id"] == "root"
+
+
+def test_cleared_status_round_trip_preserves_prompt_anchor() -> None:
+ graph = MessageTreeGraph(_root())
+ graph.clear_status("root")
+
+ restored = MessageTreeGraph.from_snapshot(graph.snapshot())
+
+ root = restored.get_root()
+ assert root.status_message_id is None
+ assert root.state is MessageState.ERROR
+ assert restored.resolve_reference("root") is not None
+ assert restored.resolve_reference("status-root") is None
+
+
+def test_snapshot_rejects_runnable_node_without_status() -> None:
+ snapshot = MessageTreeGraph(_root()).snapshot()
+ snapshot.nodes["root"]["status_message_id"] = None
+
+ with pytest.raises(ValueError, match="requires a status"):
+ MessageTreeGraph.from_snapshot(snapshot)
+
+
def test_graph_rejects_duplicate_node_and_status_identity() -> None:
graph = MessageTreeGraph(_root())
_add(graph, "child", "status-child", "root")
@@ -103,15 +140,20 @@ def test_graph_rejects_duplicate_node_and_status_identity() -> None:
_add(graph, "child", "status-other", "root")
with pytest.raises(ValueError, match="already exists"):
_add(graph, "other", "status-child", "root")
+ with pytest.raises(ValueError, match="must be distinct"):
+ _add(graph, "same", "same", "root")
-def test_graph_remove_branch_removes_descendants_and_status_lookups() -> None:
+def test_graph_reference_subtree_can_remove_exact_nodes_and_status_lookups() -> None:
graph = MessageTreeGraph(_root())
_add(graph, "branch", "status-branch", "root")
_add(graph, "leaf", "status-leaf", "branch")
_add(graph, "sibling", "status-sibling", "root")
- graph.remove_branch("branch")
+ references = graph.get_reference_descendants("branch")
+ graph.remove_nodes(
+ {reference for reference in references if not reference.startswith("status-")}
+ )
assert graph.get_node("branch") is None
assert graph.get_node("leaf") is None
diff --git a/tests/messaging/test_tree_repository.py b/tests/messaging/test_tree_repository.py
index 4938d843..18e817c4 100644
--- a/tests/messaging/test_tree_repository.py
+++ b/tests/messaging/test_tree_repository.py
@@ -182,8 +182,9 @@ 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_clearable_message_ids_for_chat("telegram", "chat") == {
- "status-root"
+ assert await manager.get_message_ids_for_chat("telegram", "chat") == {
+ "root",
+ "status-root",
}
release.set()
diff --git a/tests/messaging/test_voice_services.py b/tests/messaging/test_voice_services.py
index 9fd9a0ee..f8363588 100644
--- a/tests/messaging/test_voice_services.py
+++ b/tests/messaging/test_voice_services.py
@@ -53,8 +53,9 @@ async def test_cancel_before_status_binding_rejects_late_flow() -> None:
scope=TELEGRAM_CHAT,
voice_message_id="voice-1",
status_message_id=None,
+ delete_message_ids=frozenset({"voice-1"}),
)
- assert cancellation.clearable_message_ids == frozenset()
+ assert cancellation.delete_message_ids == frozenset({"voice-1"})
assert await registry.bind_status(claim, "status-1") is False
assert await registry.handoff(claim, callback) is VoiceHandoffOutcome.REJECTED
assert callback_called is False
@@ -118,14 +119,44 @@ async def test_cancel_removes_then_drains_handoff_without_holding_lock() -> None
scope=TELEGRAM_CHAT,
voice_message_id="voice-1",
status_message_id="status-1",
+ delete_message_ids=frozenset({"status-1"}),
)
- assert cancellation.clearable_message_ids == frozenset({"status-1"})
+ assert cancellation.delete_message_ids == frozenset({"status-1"})
assert await asyncio.wait_for(handoff_task, timeout=1) is (
VoiceHandoffOutcome.CANCELLED
)
assert await registry.cancel(TELEGRAM_CHAT, "status-new") is not None
+async def test_voice_reference_authorizes_voice_and_status_deletion() -> None:
+ registry = PendingVoiceRegistry()
+ await _reserve_bound(registry)
+
+ cancellation = await registry.cancel(TELEGRAM_CHAT, "voice-1")
+
+ assert cancellation is not None
+ assert cancellation.delete_message_ids == frozenset({"voice-1", "status-1"})
+
+
+async def test_cancel_scope_preserves_other_platform_chats() -> None:
+ registry = PendingVoiceRegistry()
+ await _reserve_bound(registry)
+ await _reserve_bound(
+ registry,
+ scope=DISCORD_CHAT,
+ voice_id="voice-2",
+ status_id="status-2",
+ )
+
+ cancellations = await registry.cancel_scope(TELEGRAM_CHAT)
+
+ assert len(cancellations) == 1
+ assert cancellations[0].delete_message_ids == frozenset({"voice-1", "status-1"})
+ assert await registry.cancel(DISCORD_CHAT, "status-2") is not None
+
+
@pytest.mark.asyncio
async def test_handoff_propagates_callback_error_when_completion_wins() -> None:
registry = PendingVoiceRegistry()
@@ -275,6 +306,7 @@ async def test_external_cancel_owns_aliases_during_caller_cancelled_drain() -> N
scope=TELEGRAM_CHAT,
voice_message_id="voice-1",
status_message_id="status-1",
+ delete_message_ids=frozenset({"status-1"}),
)
with pytest.raises(asyncio.CancelledError):
await handoff_task
@@ -584,8 +616,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.clearable_message_ids for result in cancellations} == {
- frozenset({"status-1"}),
+ assert {result.delete_message_ids for result in cancellations} == {
+ frozenset({"voice-1", "status-1"}),
}
diff --git a/tests/runtime/test_application_runtime.py b/tests/runtime/test_application_runtime.py
index 881f8751..191eb717 100644
--- a/tests/runtime/test_application_runtime.py
+++ b/tests/runtime/test_application_runtime.py
@@ -531,17 +531,19 @@ 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_outbound_message_id(
+ store.record_message_id(
"telegram",
"chat_1",
"old",
+ "out",
"status",
)
store.flush_pending_save()
- store.record_outbound_message_id(
+ store.record_message_id(
"telegram",
"chat_1",
"latest",
+ "out",
"status",
)
workflow = MessagingWorkflow(outbound, cli_manager, store)
@@ -561,13 +563,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_clearable_message_ids_for_chat("telegram", "chat_1") == [
+ assert store.get_tracked_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"]
+ ).get_tracked_message_ids_for_chat("telegram", "chat_1") == ["old"]
assert await runtime.close() is True
@@ -578,7 +580,7 @@ async def test_close_retries_real_workflow_persistence_without_losing_latest_sta
assert store.dirty is False
assert SessionStore(
storage_path=str(store_path)
- ).get_clearable_message_ids_for_chat("telegram", "chat_1") == [
+ ).get_tracked_message_ids_for_chat("telegram", "chat_1") == [
"old",
"latest",
]
diff --git a/uv.lock b/uv.lock
index dc474a97..c65e5d45 100644
--- a/uv.lock
+++ b/uv.lock
@@ -561,7 +561,7 @@ wheels = [
[[package]]
name = "free-claude-code"
-version = "3.5.14"
+version = "3.5.15"
source = { editable = "." }
dependencies = [
{ name = "aiohttp" },