Skip to content
Merged
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
17 changes: 8 additions & 9 deletions apps/presentation/dashboard/src/data/chat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1095,10 +1095,10 @@ const chatMessagePageSchema = z.object({
visible_page_sha256: z.string().regex(/^[a-f0-9]{64}$/).optional(),
});

// A long original transcript can outlive the interactive request budget even
// when each verified page succeeds. Apply the same bounded read deadline to
// its pages and fresh source checks; caller cancellation still takes priority.
const CHAT_HISTORY_READ_TIMEOUT_MS = 30_000;
// Apply one bounded read deadline to transcript pages and fresh source checks.
export const CHAT_HISTORY_READ_TIMEOUT_MS = 30_000;
const MAX_VERIFIED_HISTORY_MESSAGES = 50_000;
const MAX_VERIFIED_HISTORY_BASIS_CHARS = 6 + Math.ceil(MAX_VERIFIED_HISTORY_MESSAGES / 200) * 64;

type ChatHistoryReadProgress = {
first: ChatSessionSnapshot;
Expand Down Expand Up @@ -1213,14 +1213,13 @@ async function readChatSessionHistory(session: ChatSessionSummary | string, sign
}

function historyBasisMatches(basis: string, count: number) {
const match = /^([1-9][0-9]{0,3}):([a-f0-9]+)$/.exec(basis);
return match !== null && count >= 1 && count <= 5000 && Number(match[1]) === count
const match = /^([1-9][0-9]{0,4}):([a-f0-9]+)$/.exec(basis);
return match !== null && count >= 1 && count <= MAX_VERIFIED_HISTORY_MESSAGES && Number(match[1]) === count
&& match[2].length === Math.ceil(count / 200) * 64;
}

function historyImageHeaders(linkImages: boolean): HeadersInit | undefined {
// The linked bytes are same-origin resources. A separately configured Chat
// server still uses the compatible inline representation.
// The linked bytes are same-origin resources; a separate Chat origin stays inline.
return linkImages && !configuredChatOrigin ? {"X-LoopX-History-Images": "linked"} : undefined;
}

Expand All @@ -1240,7 +1239,7 @@ async function tryResumeChatSessionHistory(session: ChatSessionSummary, saved: C
}
if (!snapshot || snapshot.history_resume === undefined) return null; // Restart or older service.
const proof = z.object({schema_version: z.literal("loopx_chat_history_resume_v1"),
base: z.literal(basis), next: z.string().max(1605)}).safeParse(snapshot.history_resume);
base: z.literal(basis), next: z.string().max(MAX_VERIFIED_HISTORY_BASIS_CHARS)}).safeParse(snapshot.history_resume);
if (!proof.success || snapshot.ok !== true || snapshot.schema_version !== "loopx_chat_store_v1"
|| !snapshot.session || !sameHistorySource(snapshot.session, session) || Object.hasOwn(snapshot, "message_page")
|| !Array.isArray(snapshot.messages) || snapshot.messages.length > 200
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { useEffect, useState } from "react";
import { resolveBoundConversation,
import { CHAT_HISTORY_READ_TIMEOUT_MS, resolveBoundConversation,
type BoundConversationTarget, type ChatSessionSummary, type BoundConversationSource } from "./chat";

/** Reads the source's title and executor. Admission remains with the Core owner. */
Expand All @@ -12,7 +12,7 @@ export function useBoundConversation(target: BoundConversationTarget | null, ena
if (!enabled || bindingId === undefined || sessionId === undefined) return;
let active = true;
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 5000);
const timeout = setTimeout(() => controller.abort(), CHAT_HISTORY_READ_TIMEOUT_MS);
resolveBoundConversation({ bindingId, sessionId }, controller.signal)
.then(({session, source}) => {
if (!active) return;
Expand Down
39 changes: 34 additions & 5 deletions loopx/capabilities/manager_context/chat_history.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,45 @@
from __future__ import annotations

import base64
from collections import OrderedDict
import hashlib
import json
from typing import Any
from threading import Lock

from ...control_plane.content_digest import BARE_SHA256_PATTERN

MAX_KNOWN_HISTORY_MESSAGES = 50_000
_SNAPSHOT_DIGEST_CACHE_MAX = 64
_SNAPSHOT_DIGEST_LOCK = Lock()
_SNAPSHOT_DIGEST_CACHE: OrderedDict[tuple[str, str | None, bytes, bytes, int], str] = OrderedDict()

def page_chat_messages(session_id: str, messages: list[dict[str, Any]], *,
limit: int, cursor: str | None = None, turn_id: str | None = None) -> dict[str, Any]:

def _snapshot_prefix_digest(
session_id: str, turn_id: str | None, messages: list[dict[str, object]], total: int,
) -> str:
journal_sha256 = getattr(messages, "journal_sha256", None)
markers_sha256 = getattr(messages, "markers_sha256", b"")
cache_key: tuple[str, str | None, bytes, bytes, int] | None = None
if isinstance(journal_sha256, bytes) and isinstance(markers_sha256, bytes):
cache_key = (session_id, turn_id, journal_sha256, markers_sha256, total)
with _SNAPSHOT_DIGEST_LOCK:
cached = _SNAPSHOT_DIGEST_CACHE.get(cache_key)
if cached is not None:
_SNAPSHOT_DIGEST_CACHE.move_to_end(cache_key)
return cached
digest = hashlib.sha256(json.dumps(messages[:total], sort_keys=True,
ensure_ascii=False, separators=(",", ":")).encode("utf-8")).hexdigest()
if cache_key is not None:
with _SNAPSHOT_DIGEST_LOCK:
_SNAPSHOT_DIGEST_CACHE[cache_key] = digest
_SNAPSHOT_DIGEST_CACHE.move_to_end(cache_key)
while len(_SNAPSHOT_DIGEST_CACHE) > _SNAPSHOT_DIGEST_CACHE_MAX:
_SNAPSHOT_DIGEST_CACHE.popitem(last=False)
return digest


def page_chat_messages(session_id: str, messages: list[dict[str, object]], *,
limit: int, cursor: str | None = None, turn_id: str | None = None) -> dict[str, object]:
"""Page an append-ordered frozen prefix; a cursor is a read hint, not authority."""
if type(limit) is not int or not 1 <= limit <= 200:
raise ValueError("message_limit must be between 1 and 200")
Expand All @@ -31,8 +61,7 @@ def page_chat_messages(session_id: str, messages: list[dict[str, Any]], *,
raise ValueError()
except (ValueError, TypeError, UnicodeDecodeError) as exc:
raise ValueError("invalid history cursor") from exc
digest = hashlib.sha256(json.dumps(messages[:total], sort_keys=True,
ensure_ascii=False, separators=(",", ":")).encode("utf-8")).hexdigest()
digest = _snapshot_prefix_digest(session_id, turn_id, messages, total)
if expected_digest is not None and expected_digest != digest:
raise ValueError("history cursor source changed; restart the read")
end = min(offset + limit, total)
Expand Down
52 changes: 51 additions & 1 deletion loopx/capabilities/manager_context/presentation.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
"""Owner-local collaboration readback in the conversation that delegated it."""

from collections import OrderedDict
from pathlib import Path
import sys
from threading import Lock

from . import _read, _root, _hash
from .tracking import _entry, _receipt
from .roundtrip import reply_status
Expand All @@ -15,6 +20,51 @@
)
from ...control_plane.collaboration.inbox import controlled_request_readback

_TERMINAL_STATUSES = frozenset({"completed", "interrupted", "timed_out", "failed"})
_PLAIN_TURN_CACHE_MAX = 16384
_PLAIN_TURN_LOCK = Lock()
_PLAIN_TURN_FINGERPRINTS: OrderedDict[Path, tuple[int, int, int, int, int]] = OrderedDict()


def _load_collaboration_turn(store, session_id: str, turn_id: str):
turn_path_fn = getattr(store, "_turn_path", None)
fp: tuple[int, int, int, int, int] | None = None
path: Path | None = None
if sys.platform != "win32" and callable(turn_path_fn):
try:
candidate = turn_path_fn(session_id, turn_id)
if isinstance(candidate, Path):
path = candidate
st = path.stat()
fp = (st.st_dev, st.st_ino, st.st_mtime_ns, st.st_ctime_ns, st.st_size)
with _PLAIN_TURN_LOCK:
if _PLAIN_TURN_FINGERPRINTS.get(path) == fp:
_PLAIN_TURN_FINGERPRINTS.move_to_end(path)
return {"response": {}}
except (OSError, ValueError):
fp = None
load_turn = getattr(store, "load_turn")
turn = load_turn(session_id, turn_id) or {}
if path is not None and fp is not None and isinstance(turn, dict):
response = turn.get("response")
if (
turn.get("status") in _TERMINAL_STATUSES
and isinstance(response, dict)
and response.get("context_handoff_receipts") is None
and not response.get("context_handoff_receipt")
):
try:
st_after = path.stat()
if (st_after.st_dev, st_after.st_ino, st_after.st_mtime_ns, st_after.st_ctime_ns, st_after.st_size) == fp:
with _PLAIN_TURN_LOCK:
_PLAIN_TURN_FINGERPRINTS[path] = fp
_PLAIN_TURN_FINGERPRINTS.move_to_end(path)
while len(_PLAIN_TURN_FINGERPRINTS) > _PLAIN_TURN_CACHE_MAX:
_PLAIN_TURN_FINGERPRINTS.popitem(last=False)
except OSError:
pass
return turn


def project_collaboration(
store, root, session_id, messages, *, registry, context_messages=None
Expand Down Expand Up @@ -50,7 +100,7 @@ def project_collaboration(
for message in messages:
tid = message.get("turn_id")
if tid and carriers.get(tid) == message.get("message_id") and tid not in turns:
turns[tid] = store.load_turn(session_id, tid) or {}
turns[tid] = _load_collaboration_turn(store, session_id, tid)
missing_clients = {
turn.get("client_turn_id")
for turn in turns.values()
Expand Down
35 changes: 14 additions & 21 deletions loopx/capabilities/manager_context/roundtrip.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
from os import scandir
from pathlib import Path
from contextlib import contextmanager, ExitStack, nullcontext
from copy import deepcopy
from urllib.parse import quote
from datetime import datetime, timezone

Expand Down Expand Up @@ -465,8 +466,11 @@ def project_chat_session_snapshot(root, store, session_id, *, registry,
strict = message_limit is not None or resume_from is not None or report_message_id is not None
# Read the status first: terminal completion persists its answer before
# publishing completed. An older message prefix must not appear final.
snapshot = (store.session_snapshot(session_id, strict_messages=True) if strict
else store.session_snapshot(session_id))
snapshot = (
store.session_snapshot(session_id, strict_messages=True, copy_messages=False)
if strict and hasattr(store, "_paged_history_messages")
else store.session_snapshot(session_id, strict_messages=True) if strict else store.session_snapshot(session_id)
)
report_context = None
if report_message_id is not None:
snapshot["messages"], report_context = _saved_answer_rows(snapshot["messages"], report_message_id, turn_id)
Expand All @@ -475,17 +479,12 @@ def project_chat_session_snapshot(root, store, session_id, *, registry,
elif turn is not None:
status = turn["status"]
snapshot["selected_turn"] = {"turn_id": turn_id, "status": status, "terminal": status in TERMINAL_TURN_STATES}
# Failure records persist the reason with the status, before appending the message.
error = turn.get("error")
if include_turn_error and status in {"failed", "timed_out"} and isinstance(error, str) and error.strip():
snapshot["selected_turn"]["error"] = error
snapshot["active_turn"] = None
# OriginalRequest already displays only this Turn. Select it before
# paging/projection, retaining every message and the strict journal read.
snapshot["messages"] = [row for row in snapshot["messages"] if row.get("turn_id") == turn_id]
elif project_history_messages is not None:
# Extension-owned, presentation-only rows must join the frozen page
# prefix. A selected Turn only reads its canonical messages.
snapshot["messages"] = project_history_messages(snapshot["messages"])
if resume_from is not None and not 0 <= len(snapshot["messages"]) - resume_from <= 200:
return None # Bound the complete visible stream, including provider-only notices.
Expand All @@ -500,19 +499,12 @@ def project_chat_session_snapshot(root, store, session_id, *, registry,
root, session_id, snapshot["messages"], source_store=store, registry=registry
)
from .presentation import project_collaboration
# Use the frozen context to choose the carrier, projecting only this page.
# A question and answer can straddle pages without duplicating a commitment
# or re-reading every off-page Turn for each page.
projected = project_collaboration(store, root, session_id, snapshot["messages"],
registry=registry, context_messages=context_messages)
if report_message_id is not None:
# Collaboration may include the original receipt carrier. The saved
# answer only exposes its precise answer and the question it displays.
visible_ids = {row.get("message_id") for row in snapshot["messages"]}
projected = [row for row in projected if row.get("message_id") in visible_ids]
snapshot["messages"] = projected
# Provider-owned history joins the selected page at the composition root.
# Core capabilities never import an extension projection sink.
snapshot["messages"] = deepcopy(projected) if (page is not None or report_message_id is not None) else projected
if page is not None:
snapshot["message_page"] = page["message_page"]
return snapshot
Expand All @@ -521,6 +513,7 @@ def project_chat_session_snapshot(root, store, session_id, *, registry,

def parse_chat_history_selection(query):
"""Validate one HTTP history selection before any recovery observation."""
from .chat_history import MAX_KNOWN_HISTORY_MESSAGES
keys = set(query)
report = "report_message_id" in keys
if (keys - {"message_limit", "message_cursor", "turn_id", "known_history",
Expand All @@ -543,10 +536,10 @@ def parse_chat_history_selection(query):
if limit != 200 or "turn_id" in query or "message_cursor" in query:
raise ValueError("invalid history resume arguments")
count_text, _, proof = basis.partition(":")
if not re.fullmatch(r"[1-9][0-9]{0,3}", count_text):
if not re.fullmatch(r"[1-9][0-9]{0,4}", count_text):
raise ValueError("invalid known history proof")
count = int(count_text)
if count > 5000 or len(proof) != ((count + 199) // 200) * 64 or not re.fullmatch(r"[a-f0-9]+", proof):
if count > MAX_KNOWN_HISTORY_MESSAGES or len(proof) != ((count + 199) // 200) * 64 or not re.fullmatch(r"[a-f0-9]+", proof):
raise ValueError("invalid known history proof")
parsed_basis = (basis, count, proof)
return {"message_limit": limit, "message_cursor": query.get("message_cursor", [None])[0],
Expand Down Expand Up @@ -587,6 +580,7 @@ def _visible_history_page_digest(session_id, offset, messages):
def read_chat_history_selection(root, store, session_id, *, registry, selection, project_provider,
project_history_messages=None):
"""Compose the same provider projections for page reads and suffix proof."""
from .chat_history import MAX_KNOWN_HISTORY_MESSAGES
basis = selection["known_history"]
if basis is None:
snapshot = project_chat_session_snapshot(root, store, session_id, registry=registry,
Expand All @@ -597,7 +591,7 @@ def read_chat_history_selection(root, store, session_id, *, registry, selection,
snapshot["messages"] = project_provider(snapshot["messages"])
if selection["message_limit"] == 200 and selection["turn_id"] is None:
page = snapshot["message_page"]
if 1 <= page["total"] <= 5000:
if 1 <= page["total"] <= MAX_KNOWN_HISTORY_MESSAGES:
page["visible_page_sha256"] = _visible_history_page_digest(
session_id, page["offset"], snapshot["messages"])
return snapshot
Expand All @@ -607,7 +601,7 @@ def read_chat_history_selection(root, store, session_id, *, registry, selection,
restart = {"ok": True, **resume, "status": "restart"}
snapshot = project_chat_session_snapshot(root, store, session_id, registry=registry, resume_from=count,
project_history_messages=project_history_messages)
if snapshot is None or len(snapshot["messages"]) > 5000:
if snapshot is None or len(snapshot["messages"]) > MAX_KNOWN_HISTORY_MESSAGES:
return restart
messages = project_provider(snapshot["messages"])
current_prefix = "".join(
Expand All @@ -616,12 +610,11 @@ def read_chat_history_selection(root, store, session_id, *, registry, selection,
if current_prefix != proof:
return restart
total = len(messages)
# The old last page may have been short; earlier pages were just verified.
unchanged = count if total == count else count - count % 200
next_proof = proof[:((unchanged + 199) // 200) * 64] + "".join(
_visible_history_page_digest(session_id, offset, messages[offset:offset + 200])
for offset in range(unchanged, total, 200))
return {**snapshot, "messages": messages[count:], "history_resume": {
return {**snapshot, "messages": deepcopy(messages[count:]), "history_resume": {
**resume, "base": basis, "next": f"{total}:{next_proof}",
}}

Expand Down
2 changes: 2 additions & 0 deletions loopx/capabilities/native_chat/queue_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,8 @@ def _session_queue(self, session_id: str) -> None:
self._send_error("chat session was not found", status=404)
except ValueError as exc:
self._send_error(str(exc), status=400)
except (BrokenPipeError, ConnectionResetError):
return
except (OSError, RuntimeError):
self._send_error("Queued messages are temporarily unavailable", status=503)

Expand Down
12 changes: 12 additions & 0 deletions loopx/chat/journal.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,18 @@
from typing import Any


class CachedJournalRows(list): # type: ignore[type-arg]
"""Immutable cached transcript rows tagged with their verified byte digest."""

journal_sha256: bytes
markers_sha256: bytes

def __init__(self, rows: list[object], *, journal_sha256: bytes, markers_sha256: bytes = b"") -> None:
super().__init__(rows)
self.journal_sha256 = journal_sha256
self.markers_sha256 = markers_sha256


def decode_chat_journal(lines: list[bytes], *, strict: bool) -> list[dict[str, Any]]:
rows: list[dict[str, Any]] = []
for line in lines:
Expand Down
6 changes: 3 additions & 3 deletions loopx/chat_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -762,15 +762,15 @@ def _session_snapshot(self, session_id: str) -> None:
self._send_error("chat session was not found", status=404)
except ValueError as exc:
self._send_error(str(exc), status=400)
except (BrokenPipeError, ConnectionResetError):
return
except OSError:
self._send_error("Chat history is temporarily unavailable", status=503)

def _list_sessions(self) -> None:
query = parse_qs(urlparse(self.path).query, keep_blank_values=True)
if "managed_agent_id" in query:
# Agent registration is distinct from the executor's agent_id.
# Reuse Core's exact original identity admission; an older service
# ignoring this selector must not look like a successful discovery.
# Agent registration is distinct from the executor's agent_id. Reuse Core's exact identity admission.
from .capabilities.native_chat.steward_managed_mode import StewardManagedMode, managed_session_identity
if (set(query) != {"goal_id", "managed_agent_id"}
or any(len(values) != 1 or not values[0] for values in query.values())):
Expand Down
Loading
Loading