alishahryar1--free-claude-code
3fba1c6fc3
## Problem Messaging `/clear` did not follow the selected platform message boundary. Reply clears preserved the selected user prompt, while standalone clears preserved user-authored messages and could reset FCC state outside the invoking chat. ## Changes | Before | After | | --- | --- | | Reply `/clear` removed a logical conversation branch but retained the selected message. | Reply `/clear` deletes the selected message and its literal reply subtree, including the clear command. | | Standalone `/clear` retained user prompts and voice notes while resetting global messaging state. | Standalone `/clear` deletes every tracked message and resets FCC state only in the invoking platform and chat. | | Trees recorded only logical execution parentage. | Trees separately persist logical execution ancestry and exact prompt/status reply ownership. | | Clear coordination used one global admission boundary. | Per-chat clear generations coordinate admission, voice cancellation, persistence, and best-effort platform deletion. | | Persistence tracked only FCC-authored clearable output. | Persistence tracks managed inbound and outbound messages and migrates legacy entries. | <!-- greptile_comment --> <details open><summary><h3>Greptile Summary</h3></summary> This PR gives messaging `/clear` exact per-chat and reply-subtree behavior. The main changes are: - Per-chat clear generations for admission and startup-notice cleanup. - Managed inbound and outbound message tracking for deletion. - Exact prompt/status reply ownership in message trees. - Scoped voice cancellation and clear persistence updates. - Updated docs, smoke coverage, and messaging tests. </details> <h3>Confidence Score: 4/5</h3> The clear flow is mostly well-contained, with one upgrade-path issue in legacy tree restoration. Newly created prompt/status subtrees use the new exact reference fields consistently, and legacy snapshots can map old status replies to prompt references. However, reply `/clear` on an upgraded status can miss descendants and leave stale state/messages. src/free_claude_code/messaging/trees/snapshot.py <details><summary><h3><a href="https://www.greptile.com/trex"><img alt="T-Rex" src="https://greptile-static-assets.s3.amazonaws.com/trex/trex_green.svg" height="20" align="absmiddle"></a> T-Rex Logs</h3></summary> **What T-Rex did** - T-Rex attempted to prepare and run a focused legacy snapshot reproduction harness for legacy status replies detach, but tool access was blocked before execution. - A messaging clear smoke test harness was executed and reported a passing result: 20 items collected and 20 passed in 1.69 seconds, with traces for test\_reply\_clear\_uses\_literal and related paths shown in the log. <a href="https://app.greptile.com/trex/runs/14131337/artifacts"><picture><source media="(prefers-color-scheme: dark)" srcset="https://greptile-static-assets.s3.amazonaws.com/badges/ViewAllArtifactsDark.svg?v=4"><source media="(prefers-color-scheme: light)" srcset="https://greptile-static-assets.s3.amazonaws.com/badges/ViewAllArtifacts.svg?v=4"><img alt="View all artifacts" src="https://greptile-static-assets.s3.amazonaws.com/badges/ViewAllArtifacts.svg?v=4"></picture></a> <sub><a href="https://www.greptile.com/trex"><img alt="T-Rex" src="https://greptile-static-assets.s3.amazonaws.com/trex/trex_green.svg" height="14" align="absmiddle"></a> Ran code and verified through T-Rex</sub> </details> <details open><summary><h3>Important Files Changed</h3></summary> | Filename | Overview | |----------|----------| | src/free_claude_code/messaging/workflow.py | Adds per-chat clear generations, managed inbound recording, scoped clears, and startup-notice invalidation. | | src/free_claude_code/messaging/trees/graph.py | Adds exact prompt/status reference resolution and literal reply-subtree traversal. | | src/free_claude_code/messaging/trees/runtime.py | Adds exact message-subtree removal and status-only clearing behavior. | | src/free_claude_code/messaging/trees/snapshot.py | Adds parent_reference_id persistence and legacy fallback; the fallback can miss legacy status-reply descendants. | | src/free_claude_code/messaging/session/managed_message_log.py | Replaces the clearable output log with managed inbound and outbound message tracking. | | src/free_claude_code/messaging/commands.py | Routes reply and standalone `/clear` through the new exact deletion ID flows. | </details> <details open><summary><h3>Flowchart</h3></summary> <a href="#gh-light-mode-only"> ```mermaid %%{init: {'theme': 'neutral'}}%% flowchart TD A[Incoming message] --> B{Standalone /clear?} B -- yes --> C[Clear invoking chat] C --> D[Cancel scoped voice work] C --> E[Collect managed and tree message IDs] C --> F[Advance chat clear generation] F --> G[Detach scoped trees] G --> H[Clear scoped session store] H --> I[Best-effort platform deletes] B -- no --> J[Record managed inbound message] J --> K[Admit with stop and clear token] K --> L{Reply /clear?} L -- yes --> M[Resolve exact prompt or status reference] M --> N[Remove literal reference subtree] N --> I L -- no --> O[Queue or run tree node] ``` </a> <a href="#gh-dark-mode-only"> ```mermaid %%{init: {'theme': 'base', 'themeVariables': {"darkMode": true, "background": "#0d1117", "primaryColor": "#21262d", "primaryTextColor": "#e6edf3", "primaryBorderColor": "#8b949e", "lineColor": "#8b949e", "textColor": "#e6edf3", "edgeLabelBackground": "#161b22", "actorBkg": "#21262d", "actorBorder": "#8b949e", "actorTextColor": "#e6edf3", "actorLineColor": "#8b949e", "signalColor": "#8b949e", "signalTextColor": "#e6edf3", "noteBkgColor": "#373320", "noteBorderColor": "#d4a72c", "noteTextColor": "#f0e6c0", "labelBoxBkgColor": "#21262d", "labelBoxBorderColor": "#8b949e", "labelTextColor": "#e6edf3", "loopTextColor": "#e6edf3", "activationBkgColor": "#30363d", "activationBorderColor": "#8b949e"}}}%% flowchart TD A[Incoming message] --> B{Standalone /clear?} B -- yes --> C[Clear invoking chat] C --> D[Cancel scoped voice work] C --> E[Collect managed and tree message IDs] C --> F[Advance chat clear generation] F --> G[Detach scoped trees] G --> H[Clear scoped session store] H --> I[Best-effort platform deletes] B -- no --> J[Record managed inbound message] J --> K[Admit with stop and clear token] K --> L{Reply /clear?} L -- yes --> M[Resolve exact prompt or status reference] M --> N[Remove literal reference subtree] N --> I L -- no --> O[Queue or run tree node] ``` </a> </details> <a href="https://app.greptile.com/api/ide/codex?prompt=IMPORTANT%3A%20Work%20in%20the%20repository%20%22alishahryar1%2Ffree-claude-code%22%20on%20the%20existing%20branch%20%22ali%2Fclear-message-subtree%22.%20Checkout%20that%20branch%20%E2%80%94%20do%20NOT%20create%20a%20new%20branch%20or%20open%20a%20new%20PR.%20Push%20your%20changes%20to%20%22ali%2Fclear-message-subtree%22.%0A%0AFix%20the%20following%201%20code%20review%20issue.%20Work%20through%20them%20one%20at%20a%20time%2C%20proposing%20concise%20fixes.%0A%0A---%0A%0A%23%23%23%20Issue%201%20of%201%0Asrc%2Ffree_claude_code%2Fmessaging%2Ftrees%2Fsnapshot.py%3A192-193%0A**Legacy%20Status%20Replies%20Detach**%0A%0AWhen%20an%20upgraded%20legacy%20snapshot%20contains%20a%20child%20that%20originally%20replied%20to%20its%20parent%20status%2C%20this%20fallback%20rewrites%20the%20missing%20exact%20reference%20to%20the%20parent%20prompt.%20A%20later%20reply%20%60%2Fclear%60%20on%20that%20status%20traverses%20from%20the%20status%20ID%2C%20finds%20no%20migrated%20child%20edge%2C%20and%20leaves%20the%20old%20status-reply%20descendants%20and%20their%20managed%20messages%20behind.%0A%0A&repo=alishahryar1%2Ffree-claude-code&pr=1072&platform=github"><picture><source media="(prefers-color-scheme: dark)" srcset="https://greptile-static-assets.s3.amazonaws.com/badges/FixAllInCodexDark.svg?v=6"><source media="(prefers-color-scheme: light)" srcset="https://greptile-static-assets.s3.amazonaws.com/badges/FixAllInCodex.svg?v=6"><img alt="Fix All in Codex" src="https://greptile-static-assets.s3.amazonaws.com/badges/FixAllInCodex.svg?v=6"></picture></a> <sub>Reviews (1): Last reviewed commit: ["Give messaging clear exact subtree seman..."](https://github.com/alishahryar1/free-claude-code/commit/0a3baecf9470da4bb866c864c1d1f01abd517085) | [Re-trigger Greptile](https://app.greptile.com/api/retrigger?id=43593126)</sub> > Greptile also left **1 inline comment** on this PR. <!-- /greptile_comment -->
195 行
6.6 KiB
Python
195 行
6.6 KiB
Python
"""Persistence and restored-manager contracts for messaging trees."""
|
|
|
|
import asyncio
|
|
|
|
import pytest
|
|
|
|
from free_claude_code.messaging.models import IncomingMessage, MessageScope
|
|
from free_claude_code.messaging.trees import (
|
|
ConversationSnapshot,
|
|
MessageState,
|
|
NodeClaim,
|
|
TreeIdentity,
|
|
TreeQueueManager,
|
|
TreeSnapshot,
|
|
)
|
|
from free_claude_code.messaging.trees.node import MessageNode
|
|
from free_claude_code.messaging.trees.snapshot import node_to_snapshot
|
|
|
|
TELEGRAM_CHAT = MessageScope(platform="telegram", chat_id="chat")
|
|
ROOT_IDENTITY = TreeIdentity(scope=TELEGRAM_CHAT, root_id="root")
|
|
|
|
|
|
def _incoming(node_id: str, *, reply_to: str | None = None) -> IncomingMessage:
|
|
return IncomingMessage(
|
|
text=f"prompt {node_id}",
|
|
chat_id="chat",
|
|
user_id="user",
|
|
message_id=node_id,
|
|
platform="telegram",
|
|
reply_to_message_id=reply_to,
|
|
)
|
|
|
|
|
|
async def _wait_for_no_tasks(manager: TreeQueueManager) -> None:
|
|
loop = asyncio.get_running_loop()
|
|
for _ in range(20):
|
|
if manager.task_count() == 0:
|
|
return
|
|
checkpoint = asyncio.Event()
|
|
loop.call_soon(checkpoint.set)
|
|
await checkpoint.wait()
|
|
assert manager.task_count() == 0
|
|
|
|
|
|
def _interrupted_conversation() -> ConversationSnapshot:
|
|
root = MessageNode(
|
|
node_id="root",
|
|
scope=TELEGRAM_CHAT,
|
|
prompt="prompt root",
|
|
status_message_id="status-root",
|
|
state=MessageState.COMPLETED,
|
|
session_id="session-root",
|
|
children_ids=["pending", "failed"],
|
|
)
|
|
pending = MessageNode(
|
|
node_id="pending",
|
|
scope=TELEGRAM_CHAT,
|
|
prompt="prompt pending",
|
|
status_message_id="status-pending",
|
|
parent_id="root",
|
|
state=MessageState.PENDING,
|
|
children_ids=["running"],
|
|
)
|
|
running = MessageNode(
|
|
node_id="running",
|
|
scope=TELEGRAM_CHAT,
|
|
prompt="prompt running",
|
|
status_message_id="status-running",
|
|
parent_id="pending",
|
|
state=MessageState.IN_PROGRESS,
|
|
)
|
|
failed = MessageNode(
|
|
node_id="failed",
|
|
scope=TELEGRAM_CHAT,
|
|
prompt="prompt failed",
|
|
status_message_id="status-failed",
|
|
parent_id="root",
|
|
state=MessageState.ERROR,
|
|
)
|
|
snapshot = TreeSnapshot(
|
|
scope=TELEGRAM_CHAT,
|
|
root_id="root",
|
|
nodes={
|
|
node.node_id: node_to_snapshot(node)
|
|
for node in (root, pending, running, failed)
|
|
},
|
|
)
|
|
return ConversationSnapshot(trees={snapshot.identity: snapshot})
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_restore_reconciles_interrupted_nodes_before_manager_exposure() -> None:
|
|
processed: list[str] = []
|
|
|
|
async def process(claim: NodeClaim) -> None:
|
|
processed.append(claim.node.node_id)
|
|
|
|
manager = TreeQueueManager.from_snapshot(_interrupted_conversation(), process)
|
|
|
|
assert len(manager.restored_stale_targets) == 2
|
|
assert manager.restored_snapshot is not None
|
|
assert manager.restored_snapshot == await manager.snapshot()
|
|
assert manager.task_count() == 0
|
|
assert processed == []
|
|
|
|
root = await manager.get_node(TELEGRAM_CHAT, "root")
|
|
pending = await manager.get_node(TELEGRAM_CHAT, "pending")
|
|
running = await manager.get_node(TELEGRAM_CHAT, "status-running")
|
|
failed = await manager.get_node(TELEGRAM_CHAT, "failed")
|
|
assert root is not None and root.state is MessageState.COMPLETED
|
|
assert root.session_id == "session-root"
|
|
assert pending is not None and pending.state is MessageState.ERROR
|
|
assert running is not None and running.state is MessageState.ERROR
|
|
assert failed is not None and failed.state is MessageState.ERROR
|
|
assert await manager.resolve_node_id(TELEGRAM_CHAT, "status-pending") == "pending"
|
|
assert {
|
|
(target.scope, target.node_id) for target in manager.restored_stale_targets
|
|
} == {
|
|
(TELEGRAM_CHAT, "pending"),
|
|
(TELEGRAM_CHAT, "running"),
|
|
}
|
|
|
|
normalized = await manager.snapshot()
|
|
normalized_tree = normalized.get_tree(ROOT_IDENTITY)
|
|
assert normalized_tree is not None
|
|
assert normalized_tree.nodes["pending"]["state"] == "error"
|
|
assert normalized_tree.nodes["running"]["state"] == "error"
|
|
assert normalized_tree.nodes["failed"]["state"] == "error"
|
|
assert all("error_message" not in node for node in normalized_tree.nodes.values())
|
|
|
|
|
|
@pytest.mark.parametrize("corruption", ["cross_scope", "duplicate_reference"])
|
|
def test_restore_rejects_tree_that_violates_scoped_reference_invariants(
|
|
corruption: str,
|
|
) -> None:
|
|
snapshot = _interrupted_conversation()
|
|
tree = snapshot.get_tree(ROOT_IDENTITY)
|
|
assert tree is not None
|
|
if corruption == "cross_scope":
|
|
tree.nodes["pending"]["incoming"] = {
|
|
"platform": "telegram",
|
|
"chat_id": "other-chat",
|
|
}
|
|
else:
|
|
tree.nodes["failed"]["status_message_id"] = "status-pending"
|
|
|
|
manager = TreeQueueManager.from_snapshot(snapshot, lambda _claim: asyncio.sleep(0))
|
|
|
|
assert manager.get_tree_count() == 0
|
|
assert manager.restored_snapshot == ConversationSnapshot()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_claim_state_and_session_updates_produce_detached_snapshots() -> None:
|
|
release = asyncio.Event()
|
|
started = asyncio.Event()
|
|
|
|
async def process(_claim: NodeClaim) -> None:
|
|
started.set()
|
|
await release.wait()
|
|
|
|
manager = TreeQueueManager(process)
|
|
decision = await manager.admit(_incoming("root"), "status-root")
|
|
assert decision.claim is not None
|
|
await started.wait()
|
|
|
|
session_snapshot = await manager.record_session(decision.claim, "session-root")
|
|
completed_snapshot = await manager.complete_claim(
|
|
decision.claim,
|
|
"session-root",
|
|
)
|
|
|
|
assert session_snapshot is not None
|
|
assert session_snapshot.nodes["root"]["state"] == "in_progress"
|
|
assert session_snapshot.nodes["root"]["session_id"] == "session-root"
|
|
assert completed_snapshot is not None
|
|
assert completed_snapshot.nodes["root"]["state"] == "completed"
|
|
assert completed_snapshot.nodes["root"]["session_id"] == "session-root"
|
|
|
|
assert decision.snapshot is not None
|
|
decision.snapshot.nodes["root"]["state"] = "mutated-copy"
|
|
view = await manager.get_node(TELEGRAM_CHAT, "status-root")
|
|
assert view is not None and view.state is MessageState.COMPLETED
|
|
assert view.session_id == "session-root"
|
|
assert await manager.get_message_ids_for_chat("telegram", "chat") == {
|
|
"root",
|
|
"status-root",
|
|
}
|
|
|
|
release.set()
|
|
await _wait_for_no_tasks(manager)
|
|
assert await manager.snapshot() == ConversationSnapshot(
|
|
trees={ROOT_IDENTITY: completed_snapshot}
|
|
)
|