Skip to content

HarnessRouter Community Edition: the self-hosted, Apache-2.0 edition of the unified interface for agent harnesses. Run Codex, Claude Code, Hermes, PI, DSH, and more through one API, with sessions, streaming, files, cancellation, and failure handling. Implements the Unified Harness Protocol (UHP), an open standard. Your keys, your infrastructure.

gateway + console: a conversation is never answered or drawn as empty because a read failed (#540)

github-actions[bot]3668370c1025
diff --git a/gateway/app.py b/gateway/app.py
index ebf0e612..0e7ce5b0 100644
--- a/gateway/app.py
+++ b/gateway/app.py
@@ -2017,6 +2017,12 @@ async def _blob_get(file_id: str, kb: str = BLOB_KB) -> bytes | None:
return await BACKING.blob.get(kb, file_id)
+async def _blob_get_or_raise(file_id: str, kb: str = BLOB_KB) -> bytes | None:
+ """`_blob_get`, except that a read that failed raises (backing.BlobUnavailable): None only when
+ the object is not there."""
+ return await BACKING.blob.get_or_raise(kb, file_id)
+
+
async def _blob_put(file_id: str, data: bytes, kb: str = BLOB_KB) -> bool:
return await BACKING.blob.put(kb, file_id, data)
@@ -4844,6 +4850,7 @@ async def readyz(response: Response) -> dict:
checks["redis"] = {"configured": bool(REDIS_URL), **_redis_ok} # reported, not gating
checks["bus_drops"] = dict(_bus_drops.counts) # cumulative live-event drops (HR-INF-018 visibility)
checks["billing_drops"] = dict(_billing_drops.counts) # lost usage reports (HR-INF-023 visibility)
+ checks["turns_reads"] = dict(_turns_reads.counts) # conversation reads that failed; turns taken from their session
checks["identity"] = {"mode": HR_IDENTITY_MODE, **_identity_obs.counts} # LIVE-B rollout visibility
checks["credit"] = {"mode": HR_CREDIT_GATE, **_credit_obs.counts} # HR-INF-023 admission-gate rollout
checks["build"] = HR_BUILD_SHA # deploy fingerprint: bind a live instance to its source revision
@@ -8291,14 +8298,38 @@ async def _resp_put(rid: str, stored: dict, org: str, sid: str, prev: str | None
# when the turn began, to the millisecond: created_at is whole seconds, too coarse to tell
# this turn's trace chunks from the previous turn's (_turn_since_ms)
stored = {**stored, "_created_ms": int(float(created_at) * 1000)}
- try:
- _resp_cache_forget(rid)
- await _blob_put(f"responses/{rid}.json", json.dumps(stored, default=str).encode(), kb=RESP_BLOB_KB)
- except Exception: # noqa: BLE001
- pass
- await _vg_upsert("HarnessResponse", rid, {"org": org, "session_id": sid,
- "previous_response_id": prev or "", "status": status,
- "created_at": str(created_at), "store": "1" if store else "0"})
+ # The record and its index entry, each tried twice: either one missing hides the turn from its
+ # conversation (the index finds it, the record is the turn), and both failures used to pass in
+ # silence. A failure still never fails the turn: it is counted on /readyz (turns_reads) and
+ # logged, and the conversation takes the session's current turn from the session itself
+ # (_session_turns_data). A blob put answers False for a write the store refused, as well as
+ # raising for one it never reached; both are a failed write.
+ body = json.dumps(stored, default=str).encode()
+ for attempt in (1, 2):
+ try:
+ _resp_cache_forget(rid)
+ if await _blob_put(f"responses/{rid}.json", body, kb=RESP_BLOB_KB):
+ break
+ err = "refused"
+ except Exception as e: # noqa: BLE001
+ err = type(e).__name__
+ if attempt == 2:
+ _turns_reads.bump("record_write_failed")
+ print(f"[turns] the turn's record could not be written resp={rid}: {err}", flush=True)
+ else:
+ await asyncio.sleep(0.3)
+ idx = {"org": org, "session_id": sid, "previous_response_id": prev or "", "status": status,
+ "created_at": str(created_at), "store": "1" if store else "0"}
+ for attempt in (1, 2):
+ try:
+ await _vg_upsert("HarnessResponse", rid, idx, raise_on_fail=True)
+ break
+ except Exception as e: # noqa: BLE001
+ if attempt == 2:
+ _turns_reads.bump("index_write_failed")
+ print(f"[turns] the turn's index entry could not be written resp={rid}: {type(e).__name__}", flush=True)
+ else:
+ await asyncio.sleep(0.3)
# A response record is written while its turn runs and once more when it ends; after that it is
@@ -8315,12 +8346,15 @@ def _resp_cache_forget(rid: str) -> None:
_RESP_CACHE.pop(rid, None)
-async def _resp_get(rid: str) -> dict | None:
+async def _resp_get(rid: str, *, strict: bool = False) -> dict | None:
+ """A turn's record, None when there is none. strict: a read that failed raises instead of
+ answering None, for a reader that must not show a failure as a missing turn."""
hit = _RESP_CACHE.get(rid)
if hit is not None:
_RESP_CACHE.move_to_end(rid)
return hit
- b = await _blob_get(f"responses/{rid}.json", kb=RESP_BLOB_KB)
+ key = f"responses/{rid}.json"
+ b = await (_blob_get_or_raise(key, kb=RESP_BLOB_KB) if strict else _blob_get(key, kb=RESP_BLOB_KB))
if not b:
return None
try:
@@ -8743,7 +8777,7 @@ async def _resp_execute(translator: _RespTranslator, *, org: str, member: str, s
if not seen and resume:
try:
_turns = (await _session_turns_data(sid)).get("turns") or []
- seen = [str(t.get("_model") or "") for t in _turns if t.get("_model")]
+ seen = [str(t.get("model") or "") for t in _turns if t.get("model")]
except Exception: # noqa: BLE001
seen = []
rec["model_req"], rec["models_before"] = model_req, [m for m in seen if m != model_req]
@@ -10469,8 +10503,8 @@ async def session_turns(sid: str, request: Request, limit: int = 0) -> dict:
oldest-first. Powers the Workbench 'open a recent session → see its chat history' flow.
?limit=N returns only the LAST N turns (HR-INF-015: bounds the per-open blob fan-out on
long-horizon sessions; 0/absent = all, preserving existing callers)."""
- await _owned_session(request, sid) # LIVE-B: enforce org ownership before returning content
- return await _session_turns_data(sid, limit=limit)
+ _org, v = await _owned_session(request, sid) # LIVE-B: enforce org ownership before returning content
+ return await _session_turns_data(sid, limit=limit, strict=True, v=v)
def _unix_s(ts) -> int | None:
@@ -10482,15 +10516,44 @@ def _unix_s(ts) -> int | None:
return None
-async def _session_turns_data(sid: str, limit: int = 0) -> dict:
+# A session's turns come from the store's index (HarnessResponse by session_id) and each turn's
+# record. A read of either that failed used to be answered as no turn at all (find swallows its
+# error into [], a blob read its error into None), so a finished task could draw as a new, empty
+# one. For a reader (strict: the conversation and a shared link) it is now said, 503 server_error
+# (errors.md: retrying MAY succeed); for a follow-up's history it is counted and logged and the turn
+# goes on. And the session's own current turn (running_response_id) always shows, taken from the
+# session when the index does not hold it yet (its write may lag or have failed).
+_turns_reads = _OpsDrops("turns", 60, ("index_failed", "record_failed", "from_session",
+ "record_write_failed", "index_write_failed"))
+_TURNS_UNREADABLE = "This conversation could not be loaded just now. Try again in a moment."
+
+
+async def _session_turns_data(sid: str, limit: int = 0, *, strict: bool = False, v: dict | None = None) -> dict:
# find this session's response ids (HarnessResponse vertices carry session_id)
ids: list[str] = []
safe_sid = re.sub(r"[^A-Za-z0-9_-]", "", sid)
- rows = await BACKING.graph.find("HarnessResponse", {"session_id": safe_sid})
+ try:
+ rows = await BACKING.graph.find_strict("HarnessResponse", {"session_id": safe_sid})
+ except Exception as e: # noqa: BLE001
+ _turns_reads.bump("index_failed")
+ print(f"[turns] the turn index could not be read sid={safe_sid}: {type(e).__name__}", flush=True)
+ if strict:
+ raise uhp_error(503, "server_error", _TURNS_UNREADABLE) from e
+ rows = []
rows.sort(key=lambda x: str(x.get("created_at") or ""))
ids = [str(x.get("id")) for x in rows if x.get("id")]
# each row's birth as the index holds it: a turn's time when its record carries none
born = {str(x.get("id")): x.get("created_at") for x in rows if x.get("id")}
+ if v is None and strict:
+ v = await _vertex_get(sid) or {}
+ # The session's current turn when the index does not hold it. Counted only once its record shows:
+ # the id is stamped at accept, before the turn's first record write, so a queued turn has none yet.
+ from_session = str((v or {}).get("running_response_id") or "")
+ if from_session in ids:
+ from_session = ""
+ elif from_session:
+ ids.append(from_session)
+ born[from_session] = (v or {}).get("turn_at")
if limit and limit > 0:
ids = ids[-limit:] # last N turns only — bounds blob fetches AND response size
turns = []
@@ -10500,12 +10563,19 @@ async def _session_turns_data(sid: str, limit: int = 0) -> dict:
async def _fetch(rid: str) -> dict | None:
async with _sem:
- return await _resp_get(rid)
+ return await _resp_get(rid, strict=strict)
- recs = await asyncio.gather(*(_fetch(rid) for rid in ids))
+ try:
+ recs = await asyncio.gather(*(_fetch(rid) for rid in ids))
+ except Exception as e: # noqa: BLE001 — only a strict read raises: a record that could not be read
+ _turns_reads.bump("record_failed")
+ print(f"[turns] a turn's record could not be read sid={safe_sid}: {type(e).__name__}", flush=True)
+ raise uhp_error(503, "server_error", _TURNS_UNREADABLE) from e
for rid, rec in zip(ids, recs):
if not rec or rec.get("_deleted"):
continue
+ if rid == from_session:
+ _turns_reads.bump("from_session")
# user text + attached input files from the stored input items; assistant text +
# tool calls + files from the output. Attachments hydrate the user bubble's file
# chips after a refresh (the bytes live in the session workspace; the by-path
@@ -10853,7 +10923,7 @@ async def share_turns(token: str) -> dict:
sid = await _share_sid(token)
if not sid:
raise HTTPException(404, "share not found")
- return await _session_turns_data(sid)
+ return await _session_turns_data(sid, strict=True)
@app.get("/share/{token}/files")
diff --git a/gateway/backing.py b/gateway/backing.py
index 96f3e52e..94e8f0ed 100644
--- a/gateway/backing.py
+++ b/gateway/backing.py
@@ -52,6 +52,9 @@ class GraphStore(Protocol):
async def upsert(self, label: str, vid: str, props: dict, *, raise_on_fail: bool = False) -> None: ...
async def add_edge(self, label: str, src: str, dst: str) -> None: ...
async def find(self, label: str, eq: dict | None = None, neq: dict | None = None) -> list[dict]: ...
+ async def find_strict(self, label: str, eq: dict | None = None, neq: dict | None = None) -> list[dict]:
+ """`find`, raising when the store cannot answer: an empty list means nothing matches."""
+ ...
async def delete(self, vid: str, label: str | None = None) -> bool:
"""Remove one vertex and its edges; False when there was none (or the label differs)."""
...
@@ -61,8 +64,16 @@ class GraphStore(Protocol):
...
+class BlobUnavailable(RuntimeError):
+ """The blob store could not answer a read (as opposed to: the object is not there)."""
+
+
class BlobStore(Protocol):
async def get(self, kb: str, file_id: str) -> bytes | None: ...
+ async def get_or_raise(self, kb: str, file_id: str) -> bytes | None:
+ """`get`, except that only a missing object answers None: a read that failed raises
+ BlobUnavailable, for a reader that must not show a failure as nothing there."""
+ ...
async def put(self, kb: str, file_id: str, data: bytes) -> bool: ...
async def delete(self, kb: str, file_id: str) -> bool: ...
async def list(self, kb: str, prefix: str, limit: int = 20, cursor: str | None = None) -> dict: ...
@@ -233,6 +244,12 @@ class SqliteGraphStore:
return False
async def find(self, label: str, eq: dict | None = None, neq: dict | None = None) -> list[dict]:
+ try:
+ return await self.find_strict(label, eq, neq)
+ except Exception: # noqa: BLE001
+ return []
+
+ async def find_strict(self, label: str, eq: dict | None = None, neq: dict | None = None) -> list[dict]:
def _do():
with self._conn() as c:
rows = c.execute("SELECT vid, props FROM vertices WHERE label=?", (label,)).fetchall()
@@ -245,10 +262,7 @@ class SqliteGraphStore:
continue
out.append({"id": vid, **p})
return out
- try:
- return await asyncio.to_thread(_do)
- except Exception: # noqa: BLE001
- return []
+ return await asyncio.to_thread(_do)
async def probe(self) -> None:
def _do():
@@ -281,6 +295,16 @@ class FileBlobStore:
return None
return await asyncio.to_thread(_do)
+ async def get_or_raise(self, kb: str, file_id: str) -> bytes | None:
+ def _do():
+ try:
+ return self._p(kb, file_id).read_bytes()
+ except (FileNotFoundError, NotADirectoryError, ValueError):
+ return None # not there (or an id that is no key at all)
+ except OSError as e:
+ raise BlobUnavailable(type(e).__name__) from e
+ return await asyncio.to_thread(_do)
+
async def put(self, kb: str, file_id: str, data: bytes) -> bool:
if not data:
return False
diff --git a/gateway/tests/test_public_artifacts.py b/gateway/tests/test_public_artifacts.py
index a1f5bf74..d6bade16 100644
--- a/gateway/tests/test_public_artifacts.py
+++ b/gateway/tests/test_public_artifacts.py
@@ -37,7 +37,7 @@ def shared(monkeypatch):
async def trace_base(sid):
return None
- async def turns(sid):
+ async def turns(sid, **kw):
return {"turns": []}
async def files(sid):
diff --git a/gateway/tests/test_turn_times.py b/gateway/tests/test_turn_times.py
index ebef0aa5..eb368729 100644
--- a/gateway/tests/test_turn_times.py
+++ b/gateway/tests/test_turn_times.py
@@ -43,6 +43,8 @@ class Store:
async def find(self, label, props):
return [dict(r) for r in self.rows.values() if r.get("session_id") == props.get("session_id")]
+ find_strict = find
+
def record(self, rid: str) -> dict:
return json.loads(self.blobs[f"responses/{rid}.json"])
@@ -52,6 +54,7 @@ def store(monkeypatch):
s = Store()
monkeypatch.setattr(A, "_blob_put", s.blob_put)
monkeypatch.setattr(A, "_blob_get", s.blob_get)
+ monkeypatch.setattr(A, "_blob_get_or_raise", s.blob_get)
monkeypatch.setattr(A, "_vg_upsert", s.vg_upsert)
monkeypatch.setattr(A.BACKING, "graph", s, raising=False)
diff --git a/gateway/tests/test_turns_feed_model.py b/gateway/tests/test_turns_feed_model.py
index 87581992..2d1495be 100644
--- a/gateway/tests/test_turns_feed_model.py
+++ b/gateway/tests/test_turns_feed_model.py
@@ -12,3 +12,11 @@ def test_the_feed_carries_the_requested_model_per_turn():
body = src[src.index("async def _session_turns_data"):][:8000]
assert '"model": rec.get("model") or None' in body
assert '"connection": rec.get("connection")' in body
+
+
+def test_the_codex_switch_check_reads_the_model_the_feed_answers():
+ # The feed strips its private "_model" before it answers. The codex switch check's fallback (a
+ # session with no models_seen) read "_model", so it never found a model (2026-09-05 to 10-21).
+ src = Path(gw.__file__).read_text()
+ body = src[src.index("if not seen and resume:"):][:400]
+ assert 't.get("model")' in body and '"_model"' not in body
diff --git a/gateway/tests/test_turns_never_silently_empty.py b/gateway/tests/test_turns_never_silently_empty.py
new file mode 100644
index 00000000..f9c5abae
--- /dev/null
+++ b/gateway/tests/test_turns_never_silently_empty.py
@@ -0,0 +1,217 @@
+"""A conversation is never answered as empty because a read failed (hosted, 2026-10-21: a finished task
+showed as a new, empty one for about two minutes; its turns read 200 with none). A session's turns come
+from the store's index and each turn's record, and a read of either that failed was answered as no turn
+at all: the graph's find swallowed its error into [], a blob read its error into None. What these pin,
+on the self-hosted stores themselves (SQLite and files) where they can be:
+ the index or a record unreadable: the conversation and a shared link say so (503 server_error, the
+ protocol's code), never fewer turns; a record that is simply not there is still no turn;
+ a follow-up's history read that fails goes on (no turns), counted and logged;
+ the session's current turn shows even when the index does not hold it, taken from the session;
+ the record and its index entry are tried twice, a refused write counts as a failed one, and a failure
+ is counted and never fails the turn."""
+from __future__ import annotations
+
+import asyncio
+import json
+import os
+import sys
+from pathlib import Path
+
+import pytest
+from fastapi import HTTPException
+from fastapi.testclient import TestClient
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+os.environ.setdefault("HR_BACKING", "local")
+import app as gw # noqa: E402
+import backing # noqa: E402
+
+ORG = "local"
+_n = [0]
+
+
+def _rec(rid: str, sid: str, text: str) -> dict:
+ return {"id": rid, "object": "response", "created_at": 1792560576, "status": "completed", "error": None,
+ "_session_id": sid, "_org": ORG, "_input": [{"role": "user", "content": f"ask {text}"}],
+ "output": [{"type": "message", "role": "assistant", "content": [{"type": "output_text", "text": text}]}]}
+
+
+def stores(monkeypatch, tmp_path):
+ graph = backing.SqliteGraphStore(str(tmp_path / "graph.db"))
+ blob = backing.FileBlobStore(str(tmp_path / "blobs"))
+ monkeypatch.setattr(gw.BACKING, "graph", graph)
+ monkeypatch.setattr(gw.BACKING, "blob", blob)
+ monkeypatch.setattr(gw, "_turns_reads", gw._OpsDrops("turns", 60, tuple(gw._turns_reads.counts)))
+ monkeypatch.setattr(gw, "_prefix_from_vertex", lambda sid, v: None)
+ monkeypatch.setattr(gw, "VG_GATEWAY_URL", "")
+
+ async def principal(request):
+ return {"org": ORG, "member": "me@local"}
+ monkeypatch.setattr(gw, "_principal", principal)
+ gw._SHARE_TOKEN_CACHE.clear()
+ return graph, blob, tmp_path
+
+
+def _task(turns: int = 2) -> tuple[str, list[str]]:
+ """A finished task of `turns` turns, written the way a turn writes it."""
+ _n[0] += 1
+ sid = f"hsessturns{_n[0]}{os.urandom(3).hex()}"
+ rids = [f"resp_turns{_n[0]}x{i}" for i in range(turns)]
+ for i, rid in enumerate(rids):
+ asyncio.run(gw._resp_put(rid, _rec(rid, sid, f"answer {i}"), ORG, sid, rids[i - 1] if i else None,
+ "completed", 1792560576.0 + i, True))
+ asyncio.run(gw._vertex_upsert(sid, {"tenant": ORG, "status": "done", "turn_status": "done",
+ "member_id": "me@local", "running_response_id": rids[-1]}))
+ for rid in rids:
+ gw._resp_cache_forget(rid) # a fresh gateway: no record served from memory
+ return sid, rids
+
+
+def _unreadable(tmp_path: Path, rid: str) -> Path:
+ """The record's file is there and cannot be read (a directory in its place: EISDIR, as EIO or
+ EMFILE would be): not the same thing as a record that is not there."""
+ p = tmp_path / "blobs" / gw.RESP_BLOB_KB / "responses" / f"{rid}.json"
+ p.rename(p.with_suffix(".aside"))
+ p.mkdir()
+ return p
+
+
+def test_a_finished_task_reads_back_whole(stores):
+ sid, rids = _task()
+ r = TestClient(gw.app).get(f"/v1/sessions/{sid}/turns")
+ assert r.status_code == 200, r.text
+ assert [t["id"] for t in r.json()["turns"]] == rids and r.json()["turns"][-1]["assistant"] == "answer 1"
+
+
+def test_a_record_that_cannot_be_read_is_said_never_a_shorter_conversation(stores):
+ _, _, tmp = stores
+ sid, rids = _task()
+ _unreadable(tmp, rids[-1])
+ api = TestClient(gw.app)
+ r = api.get(f"/v1/sessions/{sid}/turns")
+ assert r.status_code == 503, r.text
+ err = r.json()["error"]
+ assert err["type"] == "server_error" and err["code"] == "server_error"
+ assert err["message"] == "This conversation could not be loaded just now. Try again in a moment."
+ assert gw._turns_reads.counts["record_failed"] == 1
+ # the shared link reads the same conversation, and says the same
+ token = api.post(f"/v1/sessions/{sid}/share").json()["token"]
+ assert api.get(f"/share/{token}/turns").status_code == 503
+
+
+def test_a_record_that_is_not_there_is_still_no_turn(stores):
+ _, _, tmp = stores
+ sid, rids = _task()
+ (tmp / "blobs" / gw.RESP_BLOB_KB / "responses" / f"{rids[0]}.json").unlink()
+ r = TestClient(gw.app).get(f"/v1/sessions/{sid}/turns")
+ assert r.status_code == 200 and [t["id"] for t in r.json()["turns"]] == rids[1:]
+ assert gw._turns_reads.counts["record_failed"] == 0
+
+
+def test_an_unreadable_index_is_said_to_a_reader_and_a_follow_ups_history_goes_on(stores, monkeypatch):
+ sid, _ = _task()
+
+ async def find_strict(label, eq=None, neq=None):
+ raise RuntimeError("database is locked")
+ monkeypatch.setattr(gw.BACKING.graph, "find_strict", find_strict)
+ r = TestClient(gw.app).get(f"/v1/sessions/{sid}/turns")
+ assert r.status_code == 503 and r.json()["error"]["type"] == "server_error"
+ assert gw._turns_reads.counts["index_failed"] == 1
+ # a follow-up's history (not strict): no turns, counted, the follow-up runs
+ assert asyncio.run(gw._session_turns_data(sid))["turns"] == []
+ assert gw._turns_reads.counts["index_failed"] == 2
+
+
+def test_the_sqlite_index_raises_when_it_cannot_answer_and_find_still_answers_empty(tmp_path):
+ g = backing.SqliteGraphStore(str(tmp_path / "graph.db"))
+ asyncio.run(g.upsert("HarnessResponse", "resp_a", {"session_id": "s1"}))
+ assert [r["id"] for r in asyncio.run(g.find_strict("HarnessResponse", {"session_id": "s1"}))] == ["resp_a"]
+ assert asyncio.run(g.find_strict("HarnessResponse", {"session_id": "s2"})) == []
+ g._path = str(tmp_path) # a directory: SQLite cannot open it
+ with pytest.raises(Exception):
+ asyncio.run(g.find_strict("HarnessResponse", {"session_id": "s1"}))
+ assert asyncio.run(g.find("HarnessResponse", {"session_id": "s1"})) == []
+
+
+def test_the_file_store_tells_a_missing_object_from_an_unreadable_one(tmp_path):
+ b = backing.FileBlobStore(str(tmp_path))
+ assert asyncio.run(b.put("kb", "a/x.json", b"{}"))
+ assert asyncio.run(b.get_or_raise("kb", "a/x.json")) == b"{}"
+ assert asyncio.run(b.get_or_raise("kb", "a/none.json")) is None
+ assert asyncio.run(b.get_or_raise("kb", "x.json/under-a-file")) is None # a file where a folder would be
+ assert asyncio.run(b.get_or_raise("kb", "../escape")) is None
+ (tmp_path / "kb" / "a" / "dir.json").mkdir()
+ with pytest.raises(backing.BlobUnavailable):
+ asyncio.run(b.get_or_raise("kb", "a/dir.json"))
+ assert asyncio.run(b.get("kb", "a/dir.json")) is None # get keeps its old answer
+
+
+def test_the_current_turn_shows_from_the_session_when_the_index_does_not_hold_it(stores):
+ graph, _, _ = stores
+ sid, rids = _task()
+ assert asyncio.run(graph.delete(rids[-1], "HarnessResponse")) # its index write failed
+ r = TestClient(gw.app).get(f"/v1/sessions/{sid}/turns")
+ assert r.status_code == 200 and [t["id"] for t in r.json()["turns"]] == rids
+ assert r.json()["turns"][-1]["assistant"] == "answer 1"
+ assert gw._turns_reads.counts["from_session"] == 1
+ # a turn the index holds is not added twice
+ sid2, rids2 = _task()
+ assert [t["id"] for t in TestClient(gw.app).get(f"/v1/sessions/{sid2}/turns").json()["turns"]] == rids2
+ assert gw._turns_reads.counts["from_session"] == 1
+
+
+def test_a_queued_turn_with_no_record_yet_is_not_counted(stores):
+ sid, rids = _task(1)
+ asyncio.run(gw._vertex_upsert(sid, {"running_response_id": "resp_queued", "status": "running"}))
+ r = TestClient(gw.app).get(f"/v1/sessions/{sid}/turns")
+ assert r.status_code == 200 and [t["id"] for t in r.json()["turns"]] == rids
+ assert gw._turns_reads.counts["from_session"] == 0
+
+
+def test_a_follow_ups_history_never_takes_the_new_turn_from_the_session(stores):
+ graph, _, _ = stores
+ sid, rids = _task()
+ asyncio.run(graph.delete(rids[-1], "HarnessResponse"))
+ assert [t["id"] for t in asyncio.run(gw._session_turns_data(sid))["turns"]] == rids[:1]
+
+
+def test_the_record_and_its_index_entry_are_tried_twice_and_a_failure_never_fails_the_turn(stores, monkeypatch):
+ calls = {"blob": 0, "idx": 0}
+ answers = [False, True] # refused once, then written
+
+ async def blob_put(key, data, kb=None):
+ calls["blob"] += 1
+ return answers.pop(0)
+
+ async def vg_upsert(label, vid, props, *, raise_on_fail=False):
+ if label == "HarnessResponse":
+ calls["idx"] += 1
+ assert raise_on_fail
+ raise HTTPException(502, "graph write failed") # both tries fail
+
+ async def nosleep(_s):
+ return None
+ monkeypatch.setattr(gw, "_blob_put", blob_put)
+ monkeypatch.setattr(gw, "_vg_upsert", vg_upsert)
+ monkeypatch.setattr(gw.asyncio, "sleep", nosleep)
+ asyncio.run(gw._resp_put("resp_w", _rec("resp_w", "hsessw", "x"), ORG, "hsessw", None, "running", 1792560576.0, True))
+ assert calls == {"blob": 2, "idx": 2}
+ assert gw._turns_reads.counts["record_write_failed"] == 0 and gw._turns_reads.counts["index_write_failed"] == 1
+
+
+def test_a_record_the_store_refuses_twice_is_counted(stores, monkeypatch):
+ async def blob_put(key, data, kb=None):
+ return False # the store refused: put answers False
+
+ async def nosleep(_s):
+ return None
+ monkeypatch.setattr(gw, "_blob_put", blob_put)
+ monkeypatch.setattr(gw.asyncio, "sleep", nosleep)
+ asyncio.run(gw._resp_put("resp_r", _rec("resp_r", "hsessr", "x"), ORG, "hsessr", None, "running", 1792560576.0, True))
+ assert gw._turns_reads.counts["record_write_failed"] == 1
+
+
+def test_readyz_counts_the_conversation_reads(stores):
+ body = json.dumps(TestClient(gw.app).get("/readyz").json())
+ assert '"turns_reads"' in body and '"record_failed"' in body
diff --git a/ui/src/app/share/[token]/page.test.tsx b/ui/src/app/share/[token]/page.test.tsx
new file mode 100644
index 00000000..9b116019
--- /dev/null
+++ b/ui/src/app/share/[token]/page.test.tsx
@@ -0,0 +1,49 @@
+/** @jest-environment jsdom */
+// The public share page: a conversation that could not be read is said, with Try again, never drawn
+// as a conversation with nothing in it (the gateway answers a failed read with a 503).
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+
+jest.mock('@/app/revamp.css', () => ({}));
+jest.mock('iconify-icon', () => ({}));
+jest.mock('next/navigation', () => ({ useParams: () => ({ token: 'shr1' }) }));
+jest.mock('react-markdown', () => ({ __esModule: true, default: ({ children }: { children: string }) => <p>{children}</p> }));
+jest.mock('remark-gfm', () => ({ __esModule: true, default: () => null }));
+jest.mock('@/components/FileTypeIcon', () => ({ FileTypeIcon: () => null }));
+
+import SharePage from './page';
+
+Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
+let root: Root; let el: HTMLElement;
+const json = (status: number, body: unknown) => Promise.resolve({ ok: status < 400, status, json: async () => body } as Response);
+const flush = async () => { for (let i = 0; i < 6; i++) await act(async () => { await Promise.resolve(); }); };
+afterEach(() => { act(() => root.unmount()); el.remove(); });
+
+test('a conversation that could not be read says so, and Try again reads it again', async () => {
+ let turnsAnswer = 503;
+ global.fetch = jest.fn((url: string) => (String(url).endsWith('/meta') ? json(200, { title: 'Pet Food' })
+ : String(url).endsWith('/files') ? json(200, { files: [] })
+ : turnsAnswer === 503 ? json(503, { error: { type: 'server_error', code: 'server_error' } })
+ : json(200, { turns: [{ id: 'resp_1', user: 'Pet food', assistant: 'Done.' }] }))) as unknown as typeof fetch;
+ el = document.createElement('div'); document.body.appendChild(el); root = createRoot(el);
+ await act(async () => { root.render(<SharePage />); });
+ await flush();
+ expect(el.querySelector('[role="alert"]')?.textContent).toContain('This conversation could not be loaded just now.');
+ expect(el.textContent).not.toContain('No conversation content.');
+ turnsAnswer = 200;
+ await act(async () => { (Array.from(el.querySelectorAll('button')).find((b) => b.textContent === 'Try again') as HTMLButtonElement).click(); });
+ await flush();
+ expect(el.textContent).toContain('Done.');
+ expect(el.querySelector('[role="alert"]')).toBeNull();
+});
+
+test('a conversation with no turns still says so plainly', async () => {
+ global.fetch = jest.fn((url: string) => (String(url).endsWith('/meta') ? json(200, { title: 'Pet Food' })
+ : String(url).endsWith('/files') ? json(200, { files: [] })
+ : json(200, { turns: [] }))) as unknown as typeof fetch;
+ el = document.createElement('div'); document.body.appendChild(el); root = createRoot(el);
+ await act(async () => { root.render(<SharePage />); });
+ await flush();
+ expect(el.textContent).toContain('No conversation content.');
+ expect(el.querySelector('[role="alert"]')).toBeNull();
+});
diff --git a/ui/src/app/share/[token]/page.tsx b/ui/src/app/share/[token]/page.tsx
index 8ba051de..2cbc4431 100644
--- a/ui/src/app/share/[token]/page.tsx
+++ b/ui/src/app/share/[token]/page.tsx
@@ -35,6 +35,10 @@ export default function SharePage() {
const [turns, setTurns] = useState<ShareTurn[] | null>(null);
const [files, setFiles] = useState<ShareFile[] | null>(null);
const [gone, setGone] = useState(false);
+ // the conversation could not be read (the service answered an error): said, with a way to read
+ // again, never drawn as a conversation with nothing in it
+ const [turnsFailed, setTurnsFailed] = useState(false);
+ const [turnsTry, setTurnsTry] = useState(0);
useEffect(() => {
if (!token) return;
@@ -43,16 +47,22 @@ export default function SharePage() {
.then((r) => (r.ok ? r.json() : Promise.reject(new Error(String(r.status)))))
.then((d) => { if (alive) setMeta(d); })
.catch(() => { if (alive) setGone(true); });
- fetch(`/api/share/${encodeURIComponent(token)}/turns`, { cache: 'no-store' })
- .then((r) => (r.ok ? r.json() : Promise.reject(new Error(String(r.status)))))
- .then((d) => { if (alive) setTurns(d.turns || []); })
- .catch(() => { if (alive) setTurns([]); });
fetch(`/api/share/${encodeURIComponent(token)}/files`, { cache: 'no-store' })
.then((r) => (r.ok ? r.json() : Promise.reject(new Error(String(r.status)))))
.then((d) => { if (alive) setFiles(d.files || []); })
.catch(() => { if (alive) setFiles([]); });
return () => { alive = false; };
}, [token]);
+ useEffect(() => {
+ if (!token) return;
+ let alive = true;
+ setTurnsFailed(false);
+ fetch(`/api/share/${encodeURIComponent(token)}/turns`, { cache: 'no-store' })
+ .then((r) => (r.ok ? r.json() : Promise.reject(new Error(String(r.status)))))
+ .then((d) => { if (alive) setTurns(Array.isArray(d?.turns) ? d.turns : []); })
+ .catch(() => { if (alive) { setTurns(null); setTurnsFailed(true); } });
+ return () => { alive = false; };
+ }, [token, turnsTry]);
// Canonical artifact address: /{harness}/{session}/workspace/{path} (single cached
// shared-flag check server-side). Token route stays as the fallback while meta loads.
@@ -94,7 +104,11 @@ export default function SharePage() {
</div>
<div className="share-conv">
- {turns === null && <span className="sk" style={{ display: 'block', height: 120, borderRadius: 10 }} />}
+ {turns === null && !turnsFailed && <span className="sk" style={{ display: 'block', height: 120, borderRadius: 10 }} />}
+ {turnsFailed ? (
+ <div className="session-empty" role="alert">This conversation could not be loaded just now.{' '}
+ <button type="button" className="hr-btn" onClick={() => setTurnsTry((n) => n + 1)}>Try again</button></div>
+ ) : null}
{turns?.map((t) => (
<div key={t.id} className="share-turn">
{t.user && <div className="share-user"><div className="share-user-bubble">{t.user}</div></div>}
diff --git a/ui/src/components/TaskChat.tsx b/ui/src/components/TaskChat.tsx
index 6e0b473f..8f358ca0 100644
--- a/ui/src/components/TaskChat.tsx
+++ b/ui/src/components/TaskChat.tsx
@@ -459,7 +459,7 @@ function Conversation({ harnessId, sessionId, target, models, onModel, onRan, on
// The turn lifecycle (store binding, history load, send, reconcile, stop) lives in the shared
// controller so Tasks and Arena run the exact same machine; this component owns only the view
// and its own composer state.
- const { msgs, busy, loading, stopping, outOfCredits, clearOutOfCredits,
+ const { msgs, busy, loading, loadFailed, reload, stopping, outOfCredits, clearOutOfCredits,
liveSessionId, send, stop, setMsgs, updateLast } = useConversationTurn({
onMissing,
harnessId, sessionId, target, onRan, onSession, extraHeaders,
@@ -481,7 +481,7 @@ function Conversation({ harnessId, sessionId, target, models, onModel, onRan, on
const [copiedIdx, setCopiedIdx] = useState<number | null>(null);
const taRef = useRef<HTMLTextAreaElement>(null); // shared Composer auto-grows it (15-row cap)
// A fresh draft is for typing: the caret is already in the box when the page settles on it.
- const hero = !loading && msgs.length === 0 && !busy;
+ const hero = !loading && !loadFailed && msgs.length === 0 && !busy;
useEffect(() => { if (hero) taRef.current?.focus(); }, [hero, harnessId]); // a fresh draft in another harness is a fresh box too
const [files, setFiles] = useState<{ name: string; dataUri: string }[]>([]);
const [preview, setPreview] = useState<{ url: string; name: string } | null>(null);
@@ -548,7 +548,7 @@ function Conversation({ harnessId, sessionId, target, models, onModel, onRan, on
<div ref={convRef} className={'wbx-conv' + (preview || browserDocked ? ' split' : '')}>
{/* A fresh draft centers on what it is for: the harness, named under its base's mark, with
the composer right under it. The first message turns it into the running thread. */}
- <div className={'wbx-conv-main' + (!loading && msgs.length === 0 && !busy ? ' is-hero' : '')}>
+ <div className={'wbx-conv-main' + (hero ? ' is-hero' : '')}>
{/* The bar exists for one thing: the header-values gear of a harness with declared headers.
The host page names the harness above; nothing else belongs here. */}
{declared.length > 0 && (
@@ -587,7 +587,13 @@ function Conversation({ harnessId, sessionId, target, models, onModel, onRan, on
)}
<div className="wbx-conv-msgs" ref={scrollRef} onScroll={onScroll}>
{loading && <div className="hr-empty" style={{ marginTop: 40 }}>Loading conversation…</div>}
- {!loading && msgs.length === 0 && (
+ {!loading && loadFailed && (
+ <div className="hr-empty" role="alert" style={{ marginTop: 40 }}>
+ This task could not be read just now.{' '}
+ <button type="button" className="hr-btn" onClick={reload}>Try again</button>
+ </div>
+ )}
+ {!loading && !loadFailed && msgs.length === 0 && (
<div className="wbx-hero">
<h1>{target.baseId ? <HarnessLogo id={target.baseId} size={30} /> : null}<span>{target.name}</span></h1>
</div>
@@ -703,7 +709,7 @@ function Conversation({ harnessId, sessionId, target, models, onModel, onRan, on
<iconify-icon icon="tabler:player-stop-filled"></iconify-icon>{stopping ? 'Stopping…' : 'Stop'}
</button>
) : (
- <button className="hr-btn primary wbx-send" type="button" onClick={() => send(input, files)} disabled={!target.backend || busy || (!input.trim() && files.length === 0)}>Send</button>
+ <button className="hr-btn primary wbx-send" type="button" onClick={() => send(input, files)} disabled={!target.backend || busy || loadFailed || (!input.trim() && files.length === 0)}>Send</button>
))}
tray={models.length > 0 ? (
// The route chip, as in Arena: the runtime, the model for this task, a menu to change it.
diff --git a/ui/src/lib/chat-turns.test.ts b/ui/src/lib/chat-turns.test.ts
new file mode 100644
index 00000000..ac780606
--- /dev/null
+++ b/ui/src/lib/chat-turns.test.ts
@@ -0,0 +1,37 @@
+// A task's turns that could not be read are never a task with no turns (the gateway answers 503 when
+// it cannot read a conversation): loadSessionTurns throws, and only a 404 is a task that is gone.
+import { loadSessionTurns, TurnsReadError } from './chat';
+import { harnessFetch } from '@/lib/hfetch';
+
+jest.mock('@/lib/hfetch', () => ({ harnessFetch: jest.fn() }));
+jest.mock('@/lib/auth', () => ({ getSession: () => null }));
+jest.mock('@/lib/workspace', () => ({ workspaceHeaders: () => ({}) }));
+jest.mock('reifyui', () => ({ pumpResponsesStream: jest.fn(), readSSEStream: jest.fn() }));
+
+const answer = (status: number, body: unknown) =>
+ (harnessFetch as jest.Mock).mockResolvedValue({ ok: status < 400, status, json: async () => body });
+
+test('a read the gateway could not answer throws, never answers no turns', async () => {
+ answer(503, { error: { type: 'server_error', code: 'server_error' } });
+ const err = await loadSessionTurns('hsess1').catch((e) => e);
+ expect(err).toBeInstanceOf(TurnsReadError);
+ expect(err.status).toBe(503);
+});
+
+test('a body that is not the turns throws too', async () => {
+ answer(200, { nothing: true });
+ await expect(loadSessionTurns('hsess1')).rejects.toBeInstanceOf(TurnsReadError);
+});
+
+test('a task that is gone is a 404, and says so', async () => {
+ answer(404, { error: { code: 'session_not_found' } });
+ await expect(loadSessionTurns('hsess1')).resolves.toEqual({ turns: [], lastResponseId: null, missing: true });
+});
+
+test('the turns, as read', async () => {
+ answer(200, { turns: [{ id: 'resp_1', status: 'completed', user: 'hi', assistant: 'Done.' }], last_response_id: 'resp_1' });
+ const r = await loadSessionTurns('hsess1');
+ expect(r.turns.map((t) => t.id)).toEqual(['resp_1']);
+ expect(r.lastResponseId).toBe('resp_1');
+ expect(r.missing).toBeUndefined();
+});
diff --git a/ui/src/lib/chat.ts b/ui/src/lib/chat.ts
index 219038ce..18799e8f 100644
--- a/ui/src/lib/chat.ts
+++ b/ui/src/lib/chat.ts
@@ -106,9 +106,18 @@ export interface SessionTurn {
export async function loadSessionTurns(sid: string): Promise<{ turns: SessionTurn[]; lastResponseId: string | null; missing?: boolean }> {
const res = await harnessFetch(`${BASE}/v1/sessions/${encodeURIComponent(sid)}/turns?limit=200`, { headers: authHeaders() });
// 404 is a task that no longer exists (deleted): the caller must not keep a composer on it
- if (!res.ok) return { turns: [], lastResponseId: null, missing: res.status === 404 };
- const d = await res.json();
- return { turns: d.turns || [], lastResponseId: d.last_response_id || null };
+ if (res.status === 404) return { turns: [], lastResponseId: null, missing: true };
+ // Any other failure is a read that failed (the gateway answers 503 when it cannot read the
+ // conversation), never a task with no turns: the caller says so and offers a retry.
+ if (!res.ok) throw new TurnsReadError(res.status);
+ const d = await res.json().catch(() => null) as { turns?: unknown; last_response_id?: unknown } | null;
+ if (!d || typeof d !== 'object' || !Array.isArray(d.turns)) throw new TurnsReadError(res.status);
+ return { turns: d.turns as SessionTurn[], lastResponseId: typeof d.last_response_id === 'string' && d.last_response_id ? d.last_response_id : null };
+}
+
+/** A task's turns could not be read (not a 404): the caller shows that, never an empty task. */
+export class TurnsReadError extends Error {
+ constructor(public status: number) { super('This task could not be read just now.'); this.name = 'TurnsReadError'; }
}
/** Stop a running session's turn (kills the CLI in the sandbox; terminal event follows on the bus).
diff --git a/ui/src/lib/conversation-load.test.tsx b/ui/src/lib/conversation-load.test.tsx
new file mode 100644
index 00000000..2e782705
--- /dev/null
+++ b/ui/src/lib/conversation-load.test.tsx
@@ -0,0 +1,92 @@
+/** @jest-environment jsdom */
+// Opening a task whose turns could not be read writes nothing: the task is not drawn new and empty,
+// the page is told (loadFailed) with a way to read again (reload), and no message is sent from it
+// until a read succeeds. A 404 is still a task that is gone.
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+
+const mockLoad = jest.fn();
+const mockStream = jest.fn();
+jest.mock('@/lib/chat', () => ({
+ loadSessionTurns: (...a: unknown[]) => mockLoad(...a),
+ streamResponse: (...a: unknown[]) => mockStream(...a),
+ subscribeHarnessEvents: () => () => {},
+ cancelSession: jest.fn(async () => ({ cancelled: true, status: 'cancelled' })),
+}));
+jest.mock('@/lib/workspace', () => ({ getCurrentWorkspaceRef: () => null }));
+jest.mock('@/lib/analytics', () => ({ track: jest.fn() }));
+jest.mock('@/app/(app)/billing/lib', () => ({ billing: { refresh: jest.fn(), get: () => null } }));
+jest.mock('@/lib/harness', () => ({ oobById: () => null }));
+jest.mock('@/lib/tool-steps', () => ({ fillStep: (s: unknown) => s }));
+jest.mock('reifyui', () => {
+ const { useSyncExternalStore } = jest.requireActual('react');
+ const store = new Map<string, Record<string, unknown>>();
+ const subs = new Map<string, Set<() => void>>();
+ const get = (k: string) => { let s = store.get(k); if (!s) { s = { msgs: [], busy: false, prevId: null, firstTurn: true, loaded: false }; store.set(k, s); } return s; };
+ const set = (k: string, p: unknown) => { const cur = get(k); store.set(k, { ...cur, ...(typeof p === 'function' ? (p as (c: unknown) => object)(cur) : p as object) }); subs.get(k)?.forEach((f) => f()); };
+ const use = (k: string) => useSyncExternalStore((cb: () => void) => { const x = subs.get(k) || new Set(); subs.set(k, x); x.add(cb); return () => { x.delete(cb); }; }, () => get(k), () => get(k));
+ const id = <T,>(x: T) => x;
+ return { createConversationStore: () => ({ get, set, use, seed: (k: string, v: Record<string, unknown>) => store.set(k, v), updateLastAssistant: () => undefined }),
+ withText: id, withReasoning: id, withStep: id, withResult: id };
+});
+
+import { useConversationTurn, getConvState } from './conversation';
+
+Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
+let api: ReturnType<typeof useConversationTurn>;
+let root: Root; let el: HTMLDivElement;
+const missing = jest.fn();
+function Conv({ sid }: { sid: string }) {
+ api = useConversationTurn({ harnessId: 'h1', sessionId: sid, target: { name: 'Helper', backend: 'codex' } as never, onRan: () => {}, onMissing: missing });
+ return null;
+}
+const flush = async (ms = 0) => {
+ await act(async () => { await jest.advanceTimersByTimeAsync(ms); });
+ for (let i = 0; i < 6; i++) await act(async () => { await Promise.resolve(); });
+};
+const turn = { id: 'resp_1', status: 'completed', user: 'hi', assistant: 'Done.', tools: [], files: [] };
+
+beforeEach(() => { jest.useFakeTimers(); mockLoad.mockReset(); mockStream.mockReset(); missing.mockReset();
+ el = document.createElement('div'); document.body.appendChild(el); root = createRoot(el); });
+afterEach(() => { act(() => root.unmount()); el.remove(); jest.useRealTimers(); });
+
+test('a read that fails twice writes nothing and says so; Try again reads it', async () => {
+ mockLoad.mockRejectedValue(new Error('503'));
+ await act(async () => { root.render(<Conv sid="hsessA" />); });
+ await flush();
+ expect(mockLoad).toHaveBeenCalledTimes(1);
+ expect(api.loadFailed).toBe(false); // one quiet second try first
+ await flush(1500);
+ expect(mockLoad).toHaveBeenCalledTimes(2);
+ expect(api.loadFailed).toBe(true);
+ expect(api.loading).toBe(false);
+ expect(getConvState('hsessA').msgs).toEqual([]);
+ expect(getConvState('hsessA').loaded).toBe(false); // not opened as a task with no turns
+ // nothing is sent from a task whose conversation is not known
+ await act(async () => { await api.send('next'); });
+ expect(mockStream).not.toHaveBeenCalled();
+ // Try again
+ mockLoad.mockResolvedValue({ turns: [turn], lastResponseId: 'resp_1' });
+ await act(async () => { api.reload(); });
+ await flush();
+ expect(api.loadFailed).toBe(false);
+ expect(getConvState('hsessA').loaded).toBe(true);
+ expect(getConvState('hsessA').msgs.length).toBe(2);
+ expect(getConvState('hsessA').prevId).toBe('resp_1');
+});
+
+test('a read that fails once and then answers loads quietly', async () => {
+ mockLoad.mockRejectedValueOnce(new Error('503')).mockResolvedValue({ turns: [turn], lastResponseId: 'resp_1' });
+ await act(async () => { root.render(<Conv sid="hsessB" />); });
+ await flush(1500);
+ expect(api.loadFailed).toBe(false);
+ expect(getConvState('hsessB').msgs.length).toBe(2);
+});
+
+test('a task that is gone is still let go of', async () => {
+ mockLoad.mockResolvedValue({ turns: [], lastResponseId: null, missing: true });
+ await act(async () => { root.render(<Conv sid="hsessC" />); });
+ await flush();
+ expect(missing).toHaveBeenCalledWith('hsessC');
+ expect(api.loadFailed).toBe(false);
+});
diff --git a/ui/src/lib/conversation.ts b/ui/src/lib/conversation.ts
index 663f2944..705381f2 100644
--- a/ui/src/lib/conversation.ts
+++ b/ui/src/lib/conversation.ts
@@ -385,6 +385,15 @@ export function useConversationTurn({ harnessId, sessionId, target, onRan, onSes
const setPrevId = (id: string | null) => setConvState(convKeyRef.current, { prevId: id });
const setFirstTurn = (b: boolean) => setConvState(convKeyRef.current, { firstTurn: b });
const [loading, setLoading] = useState(false);
+ // The task's record could not be read on open (not a 404: a 5xx, the network, a body that is not
+ // its turns). Nothing was written from it: the store keeps what it held, and the page says the
+ // read failed, with Try again (`reload`). Until a read succeeds, a message is not sent from here,
+ // since the conversation it would follow is not known.
+ const [loadFailed, setLoadFailed] = useState(false);
+ const loadFailedRef = useRef(false);
+ loadFailedRef.current = loadFailed;
+ const [loadTry, setLoadTry] = useState(0);
+ const loadSeq = useRef(0);
const [outOfCredits, setOutOfCredits] = useState<{ balance: number | null } | null>(null);
// Stop is one-shot: disabled the moment it is clicked so a slow cancel cannot be spammed.
const [stopping, setStopping] = useState(false);
@@ -420,13 +429,22 @@ export function useConversationTurn({ harnessId, sessionId, target, onRan, onSes
// shown done with its content even if the store was left stuck at busy:true (e.g. a terminal bus
// event was dropped on a full queue / reconnect race), which previously stranded it at "Working…"
// until a hard refresh. A genuinely in-flight turn keeps its live placeholder for the bus to stream.
+ // A read that fails (one quiet second try, then an end) writes nothing: an empty answer here would
+ // open the task empty, or wipe a live turn and end it.
useEffect(() => {
+ const seq = ++loadSeq.current;
+ const current = () => seq === loadSeq.current;
+ setLoadFailed(false);
const existing = getConvState(convKey);
- if (!sessionId) { if (!existing.loaded) setConvState(convKey, { loaded: true }); return; }
+ if (!sessionId) { setLoading(false); if (!existing.loaded) setConvState(convKey, { loaded: true }); return; }
// Already loaded, idle, and has content → trust it (no refetch on every open).
- if (existing.loaded && !existing.busy && existing.msgs.length) return;
+ if (existing.loaded && !existing.busy && existing.msgs.length) { setLoading(false); return; }
setLoading(true);
- loadSessionTurns(sessionId).then(({ turns, lastResponseId, missing }) => {
+ loadSessionTurns(sessionId).catch(() => new Promise((r) => setTimeout(r, 1500)).then(() => {
+ if (!current()) throw new Error('superseded');
+ return loadSessionTurns(sessionId);
+ })).then(({ turns, lastResponseId, missing }) => {
+ if (!current()) return;
if (missing) {
// a deleted task: nothing to show and nothing to send to (a follow-up typed into one ran on
// the deleted session and billed, 2026-09-07); the page lets go of it
@@ -447,8 +465,12 @@ export function useConversationTurn({ harnessId, sessionId, target, onRan, onSes
setConvState(convKey, { loaded: true });
}
setLoading(false);
- }).catch(() => setLoading(false));
- }, [convKey, sessionId]); // eslint-disable-line react-hooks/exhaustive-deps
+ }).catch(() => {
+ if (!current()) return;
+ setLoading(false);
+ setLoadFailed(true);
+ });
+ }, [convKey, sessionId, loadTry]); // eslint-disable-line react-hooks/exhaustive-deps
// RECONCILIATION: SSE (POST stream or bus) is best-effort delivery, a reconnect gap, a
// replica switch, or a dropped terminal event must NEVER strand the conversation at
@@ -537,6 +559,8 @@ export function useConversationTurn({ harnessId, sessionId, target, onRan, onSes
// reader watches the answer arrive three times over. The latch is a ref because it has to
// flip now, not at the next render.
if ((!text && attach.length === 0) || busy || sendingRef.current || !target.backend) return;
+ // a task whose record could not be read: what this message would follow is not known (Try again)
+ if (loadFailedRef.current && sessionId) return;
sendingRef.current = true;
const sent = attach;
// OpenAI Responses input: a string, or a user MESSAGE whose content is text + file parts.
@@ -686,6 +710,8 @@ export function useConversationTurn({ harnessId, sessionId, target, onRan, onSes
}
return { msgs, busy, loading, stopping, prevId, firstTurn, outOfCredits,
+ /** the task's record could not be read on open; `reload` reads it again */
+ loadFailed, reload: () => setLoadTry((n) => n + 1),
clearOutOfCredits: () => setOutOfCredits(null),
liveSessionId: sessionId ?? sidRef.current, convKey,
send, stop, setMsgs, updateLast };