Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion loopx/capabilities/native_chat/conversation_bindings.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
_read_json as _read_json,
)
from ...control_plane.effect_runtime import effect_runtime_request_scope
from ...control_plane.runtime.time import chronology_key
from ...file_lock import exclusive_file_lock as exclusive_file_lock
from .conversation_binding_agents import (
agent_candidates_flow,
Expand Down Expand Up @@ -425,10 +426,13 @@ def local_session_snapshot(
current, sessions, source = self._observe_local_sessions(
binding_id, app_steward_entry=app_steward_entry
)
ordered = sorted(
sessions, key=lambda session: chronology_key(session.get("updated_at")), reverse=True,
)
payload = LocalSessionSnapshotDict(
{
"sessions": [
self.controller.store.public_session(session) for session in sessions
self.controller.store.public_session(session) for session in ordered
],
"conversation_source": source,
}
Expand Down
67 changes: 67 additions & 0 deletions regression/BoundChatSessionOrder.lean
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import Std

/-
Run with Lean 4.22.0 using
`lean -DwarningAsError=true regression/BoundChatSessionOrder.lean`.

`approved` represents Core's validated Session list. Rejection has no list.
The model begins after timestamp parsing. It uses UTC microseconds and a
rank for the original timestamp text, which is the final sort tie breaker.
Python applies the sort to the validated rows in `local_session_snapshot`.
The HTTP regressions exercise actual binding checks and timestamp parsing.
-/

namespace BoundChatSessionOrder

structure Row where
session : Nat
time : Option Int
rawRank : Nat

def beforeOrAt (a b : Row) : Bool :=
match a.time, b.time with
| some left, some right =>
decide (right < left ∨ (left = right ∧ b.rawRank ≤ a.rawRank))
| some _, none => true
| none, some _ => false
| none, none => decide (b.rawRank ≤ a.rawRank)

def display (approved : Option (List Row)) : Option (List Row) :=
approved.map (fun rows => rows.mergeSort beforeOrAt)

theorem rejection_remains_unavailable : display none = none := rfl

theorem display_keeps_every_approved_row (approved displayed : List Row)
(result : display (some approved) = some displayed) : displayed.Perm approved := by
have ordered : approved.mergeSort beforeOrAt = displayed := by
simpa [display] using result
rw [← ordered]
exact List.mergeSort_perm approved beforeOrAt

theorem displayed_rows_have_recency_order (approved displayed : List Row)
(result : display (some approved) = some displayed) :
displayed.Pairwise (fun a b => beforeOrAt a b = true) := by
have ordered : approved.mergeSort beforeOrAt = displayed := by
simpa [display] using result
rw [← ordered]
apply List.sorted_mergeSort
· rintro ⟨s, a, ar⟩ ⟨t, b, br⟩ ⟨u, c, cr⟩ hab hbc
cases a <;> cases b <;> cases c <;> simp [beforeOrAt] at * <;> omega
· rintro ⟨s, a, ar⟩ ⟨t, b, br⟩
cases a <;> cases b <;> simp [beforeOrAt, Bool.or_eq_true] <;> omega

theorem equal_instants_keep_raw_tie_rank (instant : Int) (a b ar br : Nat) :
beforeOrAt ⟨a, some instant, ar⟩ ⟨b, some instant, br⟩ = decide (br ≤ ar) := by
simp [beforeOrAt]

theorem old_text_comparison_can_put_an_older_session_first :
"2026-02-03T10:00:00Z" > "2026-02-03T10:00:00.000001Z" ∧
beforeOrAt ⟨1, some 1, 0⟩ ⟨0, some 0, 1⟩ = true := by decide

#print axioms rejection_remains_unavailable
#print axioms display_keeps_every_approved_row
#print axioms displayed_rows_have_recency_order
#print axioms equal_instants_keep_raw_tie_rank
#print axioms old_text_comparison_can_put_an_older_session_first

end BoundChatSessionOrder
56 changes: 56 additions & 0 deletions tests/test_chat_conversation_bindings.py
Original file line number Diff line number Diff line change
Expand Up @@ -1517,6 +1517,62 @@ def _bound_project(fixture):
return bindings, args, binding, session, turn


def test_bound_history_http_orders_verified_sessions_by_utc(ordinary, monkeypatch): # noqa: F811
from loopx.capabilities.native_chat.external_conversations import ChatExternalConversations

store, runtime, contexts, request, capture, _fake, workspace = ordinary
observation = {"transport_ref": "notes-app", "provider_ref": "c" * 24,
"operator_ref": "d" * 24, "verified": True}
bindings = ChatConversationBindings(
root=store.root, project_contexts=contexts, observe=lambda _: observation,
)
contexts.conversation_bindings = bindings
ChatExternalConversations(runtime)
binding = bindings.configure(
transport_ref="notes-app", project_ref=contexts.available()[0]["project_ref"],
executor_endpoint_id="codex", project_grant="workspace_read",
)

try:
with monkeypatch.context() as clock:
clock.setattr("loopx.chat_store.utc_now", lambda: "2026-02-03T10:00:00Z")
older, _ = runtime.open_session(
goal_id=None, agent_id="codex", work_dir=workspace, objective="",
mode="resume_latest", conversation_binding_id=binding["binding_id"],
source_context={"source_ref": "a" * 24, "sender_ref": observation["operator_ref"],
"private_human_message": True},
)
for session_id, timestamp in (
("session-offset-tie", "2026-02-03T18:00:00+08:00"),
("session-later", "2026-02-03T10:00:00.000001Z"),
):
with monkeypatch.context() as clock:
clock.setattr("loopx.chat_store.utc_now", lambda: timestamp)
store.create_session(
goal_id=None, agent_id="codex", adapter_kind="codex_app_server",
upstream_thread_id=f"fixture-{session_id}", session_id=session_id,
channel_id=older["channel_id"], project_context=older["project_context"],
)
expected = ["session-later", "session-offset-tie", older["session_id"]]
before = {session_id: store.load_session(session_id) for session_id in expected}
before_calls = capture.read_bytes()

status, history = request(
f"/api/chat/sessions?conversation_binding_id={binding['binding_id']}"
)

assert status == 200, history
assert history["conversation_binding_id"] == binding["binding_id"]
assert [row["session_id"] for row in history["sessions"]] == expected
assert [row["updated_at"] for row in history["sessions"]] == [
before[session_id]["updated_at"] for session_id in expected
]
assert {session_id: store.load_session(session_id) for session_id in expected} == before
assert capture.read_bytes() == before_calls
finally:
runtime.close()


def test_bound_http_continuation_preserves_identity_after_json_key_reordering(ordinary): # noqa: F811
store, runtime, _contexts, request, capture, _fake, _workspace = ordinary
bindings, _args, binding, session, active = _bound_project(ordinary)
Expand Down
Loading