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.

share: a share link survives a transient index failure instead of 404ing for ten seconds (#573)

Rudy Mizrahi Celeklidb36b7f4e806
diff --git a/gateway/app.py b/gateway/app.py
index 2e36c3dd..dae4c402 100644
--- a/gateway/app.py
+++ b/gateway/app.py
@@ -11138,8 +11138,15 @@ async def get_session_share(sid: str, request: Request) -> dict:
return _share_out(str(v.get("shared") or "") == "1", str(v.get("share_token") or ""))
+_SHARE_UNREADABLE = "This shared Task could not be loaded just now. Try again in a moment."
+
+
async def _share_sid(token: str) -> str | None:
- """Resolve a share token to its session id — only while sharing is enabled."""
+ """Resolve a share token to its session id — only while sharing is enabled.
+
+ None means "no such live share", and the callers turn that into 404. A store that could not
+ answer is NOT that: it raises, so the link-holder is told to retry rather than shown the one
+ answer a recipient reads as permanent."""
tok = re.sub(r"[^A-Za-z0-9]", "", token or "")
if not tok:
return None
@@ -11150,9 +11157,17 @@ async def _share_sid(token: str) -> str | None:
if hit and time.time() - hit[0] < _SHARE_TTL:
sid = hit[1]
else:
- rows = await BACKING.graph.find("HarnessSession", {"share_token": tok, "shared": "1"})
+ # `find_strict`, because `find` answers a read it could not perform with [] — which here
+ # is indistinguishable from "no such token", and would then be negative-cached for
+ # _SHARE_TTL. A live share link would 404 for ten seconds past the store's recovery.
+ try:
+ rows = await BACKING.graph.find_strict("HarnessSession", {"share_token": tok, "shared": "1"})
+ except Exception as e: # noqa: BLE001
+ # the class only: a share token is the link's secret, and no part of it goes to a log
+ print(f"[share] the share index could not be read: {type(e).__name__}", flush=True)
+ raise uhp_error(503, "server_error", _SHARE_UNREADABLE) from e
sid = str(rows[0].get("id") or "") if rows else ""
- _SHARE_TOKEN_CACHE[tok] = (time.time(), sid)
+ _SHARE_TOKEN_CACHE[tok] = (time.time(), sid) # a real miss is cacheable; a failure never got here
if not sid:
return None
# A token lookup is not an authorization grant: another replica may have revoked the
diff --git a/gateway/tests/test_public_artifacts.py b/gateway/tests/test_public_artifacts.py
index d6bade16..0869ce86 100644
--- a/gateway/tests/test_public_artifacts.py
+++ b/gateway/tests/test_public_artifacts.py
@@ -16,9 +16,11 @@ def shared(monkeypatch):
async def get(sid):
return dict(state) if sid == state["id"] else None
- async def find(label, props):
+ async def find(label, eq=None, neq=None):
# Deliberately emulate an eventually consistent index: the point read must be
- # authoritative even when the lookup still returns a revoked session.
+ # authoritative even when the lookup still returns a revoked session. Stubbed under
+ # both names because the share resolver reads strictly — a failed index read must not
+ # reach it as an empty answer — while `find` is the lenient wrapper over it.
return [{"id": state["id"]}]
async def upsert(sid, props):
@@ -47,6 +49,7 @@ def shared(monkeypatch):
monkeypatch.setattr(gw, "_vertex_get", get)
monkeypatch.setattr(gw, "_vertex_upsert", upsert)
monkeypatch.setattr(gw.BACKING.graph, "find", find)
+ monkeypatch.setattr(gw.BACKING.graph, "find_strict", find)
monkeypatch.setattr(gw, "_principal", principal)
monkeypatch.setattr(gw, "_container_file_bytes", file_bytes)
monkeypatch.setattr(gw, "_trace_base", trace_base)
diff --git a/gateway/tests/test_share_selfhost.py b/gateway/tests/test_share_selfhost.py
index 3cd0467d..205874e1 100644
--- a/gateway/tests/test_share_selfhost.py
+++ b/gateway/tests/test_share_selfhost.py
@@ -118,3 +118,39 @@ def test_deleting_the_session_takes_its_share_with_it(api, monkeypatch):
assert api.get(url + "/turns").status_code == 404, (
"the turns behind the view are rebuilt from response records deletion does not remove — "
"the resolver is the only gate, so it must refuse")
+
+
+def test_a_transient_index_failure_does_not_404_the_link_or_poison_the_cache(api, monkeypatch):
+ """`find` answers a read it could not perform with [], which the resolver could not tell from
+ "no such token" — so it negative-cached the miss for _SHARE_TTL seconds. A live share link
+ 404'd through a blip and KEPT 404ing for ten seconds after the store came back."""
+ sid = "hsessshare" + os.urandom(4).hex()
+ _session(sid)
+ url = api.post(f"/v1/sessions/{sid}/share").json()["url"]
+ assert api.get(url + "/meta").status_code == 200
+ gw._SHARE_TOKEN_CACHE.clear()
+
+ real = gw.BACKING.graph.find_strict
+ broken = {"on": True}
+
+ async def flaky(label, eq=None, neq=None):
+ if broken["on"]:
+ raise RuntimeError("index unreachable")
+ return await real(label, eq, neq)
+ monkeypatch.setattr(gw.BACKING.graph, "find_strict", flaky)
+
+ r = api.get(url + "/meta")
+ assert r.status_code == 503, "a read that failed must not be reported as a share that is gone"
+
+ broken["on"] = False
+ assert api.get(url + "/meta").status_code == 200, (
+ "the failure must not be negative-cached: the retry after recovery has to resolve")
+
+
+def test_a_genuinely_unknown_token_is_still_404_and_still_cached(api):
+ """The distinction the fix turns on: an empty strict answer IS "no such token", stays a 404,
+ and stays cacheable — only a failed read is excluded from the cache."""
+ tok = "shr" + "0" * 32
+ assert api.get(f"/share/{tok}/meta").status_code == 404
+ assert gw._SHARE_TOKEN_CACHE.get(tok) is not None, "a real miss is still a cacheable answer"
+ assert gw._SHARE_TOKEN_CACHE[tok][1] == ""
diff --git a/ui/src/app/share/[token]/page.test.tsx b/ui/src/app/share/[token]/page.test.tsx
index af16232f..d1ad8a5f 100644
--- a/ui/src/app/share/[token]/page.test.tsx
+++ b/ui/src/app/share/[token]/page.test.tsx
@@ -75,3 +75,34 @@ test('a Task with no artifacts still says so plainly', async () => {
expect(el.textContent).toContain('0 files');
expect(alertWith('The artifacts could not be loaded just now.')).toBeUndefined();
});
+
+// #573: the link could not be read just now (503) is not a link that is gone (404). Only a 404 may say
+// the link was revoked or never existed; anything else says to try again, and Try again reads it again.
+test('a share the server could not read just now says so with Try again, never that the link is gone', async () => {
+ let metaAnswer = 503;
+ global.fetch = jest.fn((url: string) => (String(url).endsWith('/meta')
+ ? (metaAnswer === 503 ? json(503, { error: { type: 'server_error' } }) : json(200, { title: 'Pet Food' }))
+ : String(url).endsWith('/files') ? json(200, { files: [] })
+ : 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.textContent).toContain('This shared Task could not be loaded just now');
+ expect(el.textContent).not.toContain('unavailable');
+ expect(el.textContent).not.toContain('revoked');
+ metaAnswer = 200;
+ await act(async () => { (Array.from(el.querySelectorAll('button')).find((b) => b.textContent === 'Try again') as HTMLButtonElement).click(); });
+ await flush();
+ expect(el.textContent).toContain('Pet Food');
+ expect(el.textContent).toContain('Done.');
+});
+
+test('a link the server says is gone (404) says it is unavailable', async () => {
+ global.fetch = jest.fn((url: string) => (String(url).endsWith('/meta') ? json(404, { detail: 'share not found' })
+ : json(404, { detail: 'share not found' }))) 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('This shared Task is unavailable');
+ expect(el.textContent).not.toContain('could not be loaded just now');
+});
diff --git a/ui/src/app/share/[token]/page.tsx b/ui/src/app/share/[token]/page.tsx
index c906ebf5..2c20a893 100644
--- a/ui/src/app/share/[token]/page.tsx
+++ b/ui/src/app/share/[token]/page.tsx
@@ -34,7 +34,11 @@ export default function SharePage() {
const [meta, setMeta] = useState<ShareMeta | null>(null);
const [turns, setTurns] = useState<ShareTurn[] | null>(null);
const [files, setFiles] = useState<ShareFile[] | null>(null);
+ // the link is gone (the server says 404: revoked, or never shared), or it could not be read just
+ // now (any other answer, or none): only the first may say the link is dead (#573)
const [gone, setGone] = useState(false);
+ const [metaFailed, setMetaFailed] = useState(false);
+ const [metaTry, setMetaTry] = useState(0);
// 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);
@@ -47,16 +51,17 @@ export default function SharePage() {
if (!token) return;
let alive = true;
setFilesFailed(false);
+ setMetaFailed(false);
fetch(`/api/share/${encodeURIComponent(token)}/meta`, { cache: 'no-store' })
.then((r) => (r.ok ? r.json() : Promise.reject(new Error(String(r.status)))))
.then((d) => { if (alive) setMeta(d); })
- .catch(() => { if (alive) setGone(true); });
+ .catch((e: Error) => { if (alive) { if (e.message === '404') setGone(true); else setMetaFailed(true); } });
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(null); setFilesFailed(true); } });
return () => { alive = false; };
- }, [token]);
+ }, [token, metaTry]);
useEffect(() => {
if (!token) return;
let alive = true;
@@ -77,6 +82,18 @@ export default function SharePage() {
return `/api/share/${encodeURIComponent(token)}/f/${enc}`;
}, [token, meta]);
+ if (metaFailed && !meta) {
+ return (
+ <main style={{ marginLeft: 0, height: '100vh', overflowY: 'auto' }}>
+ <div className="page" style={{ maxWidth: 720 }}>
+ <div className="page-header" role="alert"><div><h1>This shared Task could not be loaded just now</h1>
+ <p>Try again in a moment.</p>
+ <button type="button" className="hr-btn" onClick={() => { setMetaTry((n) => n + 1); setTurnsTry((n) => n + 1); }}>Try again</button></div></div>
+ </div>
+ </main>
+ );
+ }
+
if (gone) {
return (
<main style={{ marginLeft: 0, height: '100vh', overflowY: 'auto' }}>