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 -->
259 行
8.2 KiB
Python
259 行
8.2 KiB
Python
import asyncio
|
|
from dataclasses import FrozenInstanceError
|
|
|
|
import pytest
|
|
|
|
from free_claude_code.messaging.models import MessageScope
|
|
from free_claude_code.messaging.trees.node import MessageNode, MessageState
|
|
from free_claude_code.messaging.trees.runtime import MessageTree
|
|
|
|
_SCOPE = MessageScope(platform="telegram", chat_id="chat")
|
|
|
|
|
|
def _tree() -> MessageTree:
|
|
return MessageTree(
|
|
MessageNode(
|
|
node_id="root",
|
|
scope=_SCOPE,
|
|
prompt="prompt root",
|
|
status_message_id="status-root",
|
|
)
|
|
)
|
|
|
|
|
|
async def _add(
|
|
tree: MessageTree,
|
|
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,
|
|
_SCOPE,
|
|
f"prompt {node_id}",
|
|
status_message_id,
|
|
parent_id,
|
|
parent_reference_id or parent_id,
|
|
)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_enqueue_finish_and_claim_next_are_atomic_and_fifo() -> None:
|
|
tree = _tree()
|
|
|
|
root = await tree.enqueue_or_claim("root")
|
|
child_a = await _add(tree, "child-a", "status-a")
|
|
child_b = await _add(tree, "child-b", "status-b")
|
|
|
|
assert root.accepted and root.claim is not None and root.position is None
|
|
assert child_a.claim is None and child_a.position == 1
|
|
assert child_b.claim is None and child_b.position == 2
|
|
|
|
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 == "child-a"
|
|
assert [(entry.node.node_id, entry.position) for entry in completion.queue] == [
|
|
("child-b", 1)
|
|
]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_duplicate_unknown_and_terminal_admission_are_rejected_without_wedge() -> (
|
|
None
|
|
):
|
|
tree = _tree()
|
|
|
|
first = await tree.enqueue_or_claim("root")
|
|
duplicate = await tree.enqueue_or_claim("root")
|
|
unknown = await tree.enqueue_or_claim("status-root")
|
|
assert first.claim is not None
|
|
assert duplicate.accepted is False
|
|
assert unknown.accepted is False
|
|
assert duplicate.snapshot is None
|
|
assert unknown.snapshot is None
|
|
|
|
await tree.complete_claim(first.claim.claim_id, "session")
|
|
await tree.finish_and_claim_next(first.claim.claim_id)
|
|
terminal = await tree.enqueue_or_claim("root")
|
|
assert terminal.accepted is False
|
|
assert terminal.snapshot is None
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_stale_claim_id_cannot_clear_a_newer_claim() -> None:
|
|
tree = _tree()
|
|
first = await tree.enqueue_or_claim("root")
|
|
assert first.claim is not None
|
|
await tree.finish_and_claim_next(first.claim.claim_id)
|
|
|
|
second = await _add(tree, "child", "status-child")
|
|
assert second.claim is not None
|
|
|
|
stale = await tree.finish_and_claim_next(first.claim.claim_id)
|
|
assert stale.next_claim is None
|
|
assert await tree.record_session(second.claim.claim_id, "session") is not None
|
|
await tree.finish_and_claim_next(second.claim.claim_id)
|
|
third = await _add(tree, "third", "status-third")
|
|
assert third.claim is not None
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_cancellation_keeps_active_identity_until_matching_finish() -> None:
|
|
tree = _tree()
|
|
root = await tree.enqueue_or_claim("root")
|
|
queued = await _add(tree, "queued", "status-queued")
|
|
assert root.claim is not None and queued.position == 1
|
|
|
|
cancelled = await tree.cancel_node("root")
|
|
|
|
assert cancelled.active_claim == root.claim
|
|
assert [node.node_id for node in cancelled.nodes] == ["root"]
|
|
|
|
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 == "queued"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("propagate", [False, True])
|
|
async def test_cancelled_claim_rejects_late_failure_and_descendant_propagation(
|
|
propagate: bool,
|
|
) -> None:
|
|
tree = _tree()
|
|
root = await tree.enqueue_or_claim("root")
|
|
queued = await _add(tree, "queued", "status-queued")
|
|
assert root.claim is not None and queued.position == 1
|
|
|
|
await tree.cancel_node("root")
|
|
late_failure = await tree.fail_claim(
|
|
root.claim.claim_id,
|
|
propagate=propagate,
|
|
)
|
|
|
|
assert late_failure.snapshot is None
|
|
assert late_failure.affected == ()
|
|
assert late_failure.queue_update is None
|
|
queued_view = await tree.node_view("queued")
|
|
assert queued_view is not None
|
|
assert queued_view.state is MessageState.PENDING
|
|
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 == "queued"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_cancelled_queue_member_is_never_claimed() -> None:
|
|
tree = _tree()
|
|
root = await tree.enqueue_or_claim("root")
|
|
await _add(tree, "a", "status-a")
|
|
await _add(tree, "b", "status-b")
|
|
assert root.claim is not None
|
|
|
|
cancelled = await tree.cancel_node("a")
|
|
assert [node.node_id for node in cancelled.nodes] == ["a"]
|
|
|
|
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 == "b"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_prompt_subtree_removal_returns_every_platform_message() -> None:
|
|
tree = _tree()
|
|
await _add(tree, "child", "status-child")
|
|
|
|
removed = await tree.remove_message_subtree("root")
|
|
|
|
assert removed.removed_message_ids == frozenset(
|
|
{"root", "status-root", "child", "status-child"}
|
|
)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
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
|
|
async def test_concurrent_duplicate_enqueue_produces_one_claim_only() -> None:
|
|
tree = _tree()
|
|
gate = asyncio.Event()
|
|
|
|
async def enqueue():
|
|
await gate.wait()
|
|
return await tree.enqueue_or_claim("root")
|
|
|
|
tasks = [asyncio.create_task(enqueue()) for _ in range(20)]
|
|
gate.set()
|
|
results = await asyncio.gather(*tasks)
|
|
|
|
assert sum(result.claim is not None for result in results) == 1
|
|
assert sum(result.accepted for result in results) == 1
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_results_are_frozen_and_do_not_expose_mutable_nodes() -> None:
|
|
tree = _tree()
|
|
decision = await tree.enqueue_or_claim("root")
|
|
assert decision.claim is not None
|
|
|
|
with pytest.raises(FrozenInstanceError):
|
|
decision.claim.__setattr__("claim_id", "replacement")
|
|
assert not hasattr(decision.claim, "__dict__")
|
|
assert not isinstance(decision.claim.node, MessageNode)
|
|
|
|
|
|
def test_message_tree_has_no_lock_or_partial_mutation_escape_hatches() -> None:
|
|
forbidden = {
|
|
"with_lock",
|
|
"enqueue",
|
|
"dequeue",
|
|
"put_queue_unlocked",
|
|
"remove_from_queue",
|
|
"set_processing_state",
|
|
"clear_current_node",
|
|
"set_current_task",
|
|
"cancel_current_task",
|
|
"set_node_error_sync",
|
|
"drain_queue_and_mark_cancelled",
|
|
"reset_processing_state",
|
|
}
|
|
|
|
assert forbidden.isdisjoint(vars(MessageTree))
|