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.

A deleted task is final, and every Gemini CLI helper alias runs on the turn's model (#117)

github-actions[bot]894fc3f07c08
diff --git a/gateway/app.py b/gateway/app.py
index ca57c8a7..6220bcc0 100644
--- a/gateway/app.py
+++ b/gateway/app.py
@@ -4125,7 +4125,15 @@ async def delete_trace(sid: str, request: Request) -> dict:
"""Delete a session for good: its trace manifest + event chunks, its durable workspace
tarball, and tombstone the session vertex. /v1/sessions/{sid} is the protocol's name for it;
/v1/traces/{sid} is the older path the Traces app calls, the same handler."""
- org, v = await _owned_session(request, sid)
+ p = await _principal(request)
+ org = str(p.get("org") or "")
+ v = await _vertex_get(sid)
+ if not v or str(v.get("tenant") or "") != org:
+ raise uhp_error(404, "session_not_found", "No session with that id.", "session_id")
+ # A tombstoned session may be deleted again. A card of it can outlive the first delete (a
+ # follow-up that reached the tombstone rewrote the card as "?", 2026-09-07), and this button
+ # is the only way a person has to remove it; refusing the second delete with 404 left the
+ # ghost in the list for good. Every step below is idempotent.
# The tombstone goes down FIRST. Stopping a live turn below triggers its finalize, and a
# reconcile can land at any moment; both write session cards, and the indexer drops a write
# whose session is tombstoned. Written last, the tombstone missed exactly those writes and
@@ -5980,20 +5988,24 @@ async def _resp_resolve_session(org: str, member: str, prev: str | None, backend
await _recover_trace_cursor(tr)
resume = (v or await _vertex_get(sid) or {}).get("cli_session_id") or None
return sid, resume
- if prev:
- rec = await _resp_get(prev)
- sid = (rec or {}).get("_session_id")
- if sid:
- # Same cross-tenant guard as session_hint below: a leaked/stored response id of another
- # org's session must not let a caller continue (and re-bill/re-stamp) that session —
- # fall through and start a fresh session in the caller's own org instead.
- v = await _vertex_get(sid)
- if v and str(v.get("tenant") or "") == org:
- return await _continue(sid, v)
- if session_hint:
- v = await _vertex_get(session_hint)
- if v and str(v.get("tenant") or "") == org: # exists + belongs to this org (no cross-tenant continue)
- return await _continue(session_hint, v)
+ if prev or session_hint:
+ try:
+ if prev:
+ rec = await _resp_get(prev)
+ sid = (rec or {}).get("_session_id")
+ v = await _vertex_get(sid) if sid else None
+ else:
+ sid, v = session_hint, await _vertex_get(session_hint)
+ except Exception as e: # noqa: BLE001
+ raise uhp_error(503, "server_error", "The session could not be read right now. Try again.") from e
+ if v and str(v.get("tenant") or "") == org and str(v.get("status") or "") != "deleted":
+ return await _continue(sid, v)
+ if v:
+ # a leaked/stored id of another org's session must not let a caller continue it; nor a
+ # deleted one of this org's: a tombstone is final, and a follow-up that reached one ran,
+ # billed, and rewrote the task's card as if it were live (2026-09-07)
+ raise uhp_error(404, "session_not_found", "No session with that id.")
+ raise uhp_error(404, "session_not_found", "No session with that id.")
sid = "hsess" + uuid.uuid4().hex
created = time.time()
inv = _inv_ts(created)
diff --git a/gateway/tests/test_deleted_session.py b/gateway/tests/test_deleted_session.py
new file mode 100644
index 00000000..2a4780bd
--- /dev/null
+++ b/gateway/tests/test_deleted_session.py
@@ -0,0 +1,76 @@
+"""A deleted task is final (2026-09-07): a follow-up sent to a deleted Codex task was accepted, ran,
+billed, and rewrote the task's card as "?", and the delete button then refused the tombstone with
+404, so the ghost card stayed in the list for good. The turn resolver refuses a tombstone the way
+it refuses another org's session, and a tombstoned session can be deleted again."""
+import asyncio
+import os
+import pathlib
+import sys
+
+import pytest
+from fastapi.testclient import TestClient
+
+sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
+os.environ.setdefault("HR_BACKING", "local")
+import app as gw # noqa: E402
+
+HEADERS = {"x-harness-internal": "test-internal-key", "x-harness-org": "local", "x-harness-member": "m"}
+
+
+def _resolve(session_hint: str):
+ return asyncio.run(gw._resp_resolve_session("org.a", "m", None, "codex", session_hint=session_hint))
+
+
+def test_a_deleted_session_is_not_continued(monkeypatch):
+ async def vertex(sid):
+ return {"tenant": "org.a", "status": "deleted", "cli_session_id": "c1"}
+ monkeypatch.setattr(gw, "_vertex_get", vertex)
+ with pytest.raises(Exception) as ei:
+ _resolve("hsessdead")
+ assert getattr(ei.value, "status_code", None) == 404
+
+
+def test_another_orgs_session_is_not_continued(monkeypatch):
+ async def vertex(sid):
+ return {"tenant": "org.b", "status": "done", "cli_session_id": "c1"}
+ monkeypatch.setattr(gw, "_vertex_get", vertex)
+ with pytest.raises(Exception) as ei:
+ _resolve("hsessother")
+ assert getattr(ei.value, "status_code", None) == 404
+
+
+def test_an_unknown_session_id_is_refused_rather_than_replaced(monkeypatch):
+ async def vertex(sid):
+ return None
+ monkeypatch.setattr(gw, "_vertex_get", vertex)
+ with pytest.raises(Exception) as ei:
+ _resolve("hsessnone")
+ assert getattr(ei.value, "status_code", None) == 404
+
+
+def test_a_live_session_of_the_org_is_continued(monkeypatch):
+ async def vertex(sid):
+ return {"tenant": "org.a", "status": "done", "cli_session_id": "c1", "trace_blob": "org.a/1_" + sid}
+ async def cursor(tr):
+ return None
+ monkeypatch.setattr(gw, "_vertex_get", vertex)
+ monkeypatch.setattr(gw, "_recover_trace_cursor", cursor)
+ assert _resolve("hsesslive") == ("hsesslive", "c1")
+
+
+def test_a_tombstoned_session_can_be_deleted_again():
+ sid = "hsessdeletetwice"
+ asyncio.run(gw._vertex_upsert(sid, {"tenant": "local", "status": "done", "created_at_inv": "98211493921626",
+ "trace_blob": "local/98211493921626_" + sid}))
+ c = TestClient(gw.app)
+ first = c.delete(f"/v1/sessions/{sid}", headers=HEADERS)
+ second = c.delete(f"/v1/sessions/{sid}", headers=HEADERS)
+ assert (first.status_code, second.status_code) == (200, 200), (first.text, second.text)
+ assert (asyncio.run(gw._vertex_get(sid)) or {}).get("status") == "deleted"
+ # ownership still gates it: another org cannot delete (or learn about) the tombstone
+ other = c.delete(f"/v1/sessions/{sid}", headers={**HEADERS, "x-harness-org": "other"})
+ assert other.status_code == 404
+ # and a turn on the tombstone is refused before anything runs
+ with pytest.raises(Exception) as ei:
+ asyncio.run(gw._resp_resolve_session("local", "m", None, "codex", session_hint=sid))
+ assert getattr(ei.value, "status_code", None) == 404
diff --git a/runner/server.py b/runner/server.py
index b0324523..a309a678 100644
--- a/runner/server.py
+++ b/runner/server.py
@@ -2985,6 +2985,19 @@ def _build_qwen(provider: str, auth: Auth, model: str, prompt: str, cwd: str, en
# of this set until the gateway side decides how (or whether) to broker it; see the gateway's
# _BROKERABLE_PROVIDERS comment for bedrock/vertex.
GEMINI_PROVIDERS = {"google"}
+# gemini-cli 0.58.0's model-config aliases that carry a model of their own (alias -> parent). Read
+# off the CLI's DEFAULT_MODEL_CONFIGS table; a CLI bump re-reads it. The chat-model aliases
+# (gemini-2.5-pro, ...) are not here: a turn runs its chat model through the id resolutions.
+# "classifier" is the model router's own alias (flash-lite in the table, asked for by name through
+# generateJson); it carries a model like the others and is pinned with them.
+GEMINI_HELPER_ALIASES = {
+ "gemini-2.5-flash-base": "base", "gemini-3-flash-base": "base", "gemini-3.5-flash-base": "base",
+ "prompt-completion": "base", "fast-ack-helper": "base", "edit-corrector": "base",
+ "summarizer-default": "base", "summarizer-shell": "base", "classifier": "base", "loop-detection-double-check": "base",
+ "chat-compression-3-pro": "", "chat-compression-3-flash": "", "chat-compression-3.1-flash-lite": "",
+ "chat-compression-2.5-pro": "", "chat-compression-2.5-flash": "", "chat-compression-2.5-flash-lite": "",
+ "chat-compression-default": "", "agent-history-provider-summarizer": "",
+}
# Every Gemini id the gateway's gemini catalog lists. gemini-cli's resolver rewrites ids on the
# API-key auth path (every "-flash" id to gemini-3.5-flash, 3.1-pro-preview to its customtools
# variant, and by context in its default resolution table); with dynamicModelConfiguration on, -m
@@ -3044,6 +3057,17 @@ def _gemini_settings(home: pathlib.Path, mcp_servers: list[dict] | None, model:
own = [{"model": model or GEMINI_DEFAULT_MODEL, "isLastResort": True, "maxAttempts": 3,
"actions": {"terminal": "prompt", "transient": "prompt", "not_found": "prompt", "unknown": "prompt"},
"stateTransitions": {"terminal": "terminal", "transient": "sticky_retry", "not_found": "terminal", "unknown": "sticky_retry"}}]
+ turn_model = model or GEMINI_DEFAULT_MODEL
+ # The tiers cover the classifier only. The CLI's other helpers (edit correction, the shell and
+ # tool summarizers, the next-speaker and loop checks, web fetch, chat compression, the history
+ # summarizer) are model-config ALIASES whose model is written into the alias table itself
+ # ("gemini-3-flash-base" is gemini-3-flash-preview, "edit-corrector" is flash-lite, ...), and
+ # an alias's model is never passed through the id resolutions. A one-pager build on
+ # gemini-3.8-flash made three such calls on gemini-3-flash-preview and failed as a
+ # substitution (hosted, 2026-09-07 04:58Z). Custom aliases replace the table's entries by
+ # name, so every alias that names a model is rewritten to the turn's model, its parent kept.
+ aliases = {name: ({"extends": parent} if parent else {}) | {"modelConfig": {"model": turn_model}}
+ for name, parent in GEMINI_HELPER_ALIASES.items()}
cfg: dict = {"security": {"auth": {"selectedType": "gemini-api-key"}},
# the ids are honest: -m resolves through this table, and each entry pins an id to itself
"experimental": {"dynamicModelConfiguration": True},
@@ -3054,7 +3078,8 @@ def _gemini_settings(home: pathlib.Path, mcp_servers: list[dict] | None, model:
# "gemini-3-flash-preview" too and failed as a substitution (2026-09-07, both trees).
# Every model the CLI calls in a turn is the one asked for: both tiers pin to it.
"modelConfigs": {"modelIdResolutions": {m: {"default": m, "contexts": []} for m in pinned},
- "classifierIdResolutions": {t: {"default": model or GEMINI_DEFAULT_MODEL, "contexts": []} for t in ("flash", "pro")},
+ "classifierIdResolutions": {t: {"default": turn_model, "contexts": []} for t in ("flash", "pro")},
+ "customAliases": aliases,
"modelChains": {k: own for k in ("preview", "default", "lite", "auto-preview", "auto-default")}}}
if servers:
cfg["mcpServers"] = servers
diff --git a/runner/tests/test_gemini_build.py b/runner/tests/test_gemini_build.py
index 9d7a9317..aa4da49f 100644
--- a/runner/tests/test_gemini_build.py
+++ b/runner/tests/test_gemini_build.py
@@ -8,8 +8,8 @@ import sys
import tempfile
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
-from server import (Auth, _agent_doc_path, _build_gemini, _gemini_to_claude, # noqa: E402
- _gemini_usage, _norm_token_usage, BACKENDS, GEMINI_MODELS, _HERMES_RELAY)
+from server import (Auth, _agent_doc_path, _build_gemini, _gemini_settings, _gemini_to_claude, # noqa: E402
+ _gemini_usage, _norm_token_usage, BACKENDS, GEMINI_HELPER_ALIASES, GEMINI_MODELS, _HERMES_RELAY)
def _argv(**kw):
@@ -282,3 +282,21 @@ def test_the_helper_model_tiers_are_the_turns_own_model():
stats = {"input_tokens": 10, "output_tokens": 2, "cached": 0, "models": {"gemini-3.8-flash": {}, "gemini-3-flash-preview": {}}}
out = _gemini_to_claude({"type": "result", "status": "success", "stats": stats}, {"model": "gemini-3.8-flash", "final": "done"})
assert out[0]["is_error"] is True and out[0]["result"] == "the CLI ran gemini-3-flash-preview instead of gemini-3.8-flash"
+
+
+def test_every_helper_alias_of_the_cli_runs_on_the_turns_model(tmp_path):
+ """The CLI's helper aliases name their model in the alias table (gemini-3-flash-base is
+ gemini-3-flash-preview, edit-corrector is flash-lite) and bypass the id resolutions; a turn on
+ gemini-3.8-flash made three helper calls on gemini-3-flash-preview (2026-09-07). Every one is
+ rewritten to the turn's model with its parent kept."""
+ _gemini_settings(tmp_path, [], "gemini-3.8-flash")
+ cfg = json.loads((tmp_path / ".gemini" / "settings.json").read_text())
+ custom = cfg["modelConfigs"]["customAliases"]
+ assert set(custom) == set(GEMINI_HELPER_ALIASES)
+ for name, parent in GEMINI_HELPER_ALIASES.items():
+ assert custom[name]["modelConfig"] == {"model": "gemini-3.8-flash"}
+ assert custom[name].get("extends") == (parent or None)
+ for must in ("gemini-3-flash-base", "edit-corrector", "chat-compression-3-flash", "agent-history-provider-summarizer",
+ "summarizer-shell", "loop-detection-double-check", "classifier"):
+ assert must in custom
+ assert len(custom) == 18
diff --git a/ui/src/components/TaskChat.tsx b/ui/src/components/TaskChat.tsx
index 00564235..710921be 100644
--- a/ui/src/components/TaskChat.tsx
+++ b/ui/src/components/TaskChat.tsx
@@ -386,6 +386,7 @@ export function ConfigChat({ oob, ch, harnessId, harnessName, deepSid, onClearDe
must not be interrupted by a diagnostics peek. */}
<div className="run-detail-fill" style={{ display: detailTab === 'conversation' ? undefined : 'none' }}>
<Conversation key={`conv-${harnessId}-${selectedSid ?? 'new'}-${newTaskNonce}`} harnessId={harnessId} sessionId={selectedSid}
+ onMissing={(sid) => { setDeepErr(`The Task (${sid.slice(0, 18)}…) doesn't exist, it may have been deleted.`); setSelectedSid(null); setActiveSid(null); onClearDeepSid?.(); }}
target={{ name: harnessName, backend, model, baseId: oob?.id ?? oobById(draft?.base || '')?.id,
runtime: (oob ?? oobById(draft?.base || ''))?.name, defaultModel: oob ? (oobDefaultModel(oob) || '') : normModel(ch?.defaultModel) }}
additionalHeaders={(draft?.additionalHeaders || []).filter(Boolean)}
@@ -419,9 +420,11 @@ function ModelSelect({ models, value, onChange, backend }: {
// ── Recents: this user's sessions for this harness (clickable → loads its chat history) ─────────
-function Conversation({ harnessId, sessionId, target, models, onModel, onRan, onSession, additionalHeaders, onTotals }: {
+function Conversation({ harnessId, sessionId, target, models, onModel, onRan, onSession, onMissing, additionalHeaders, onTotals }: {
harnessId: string; sessionId: string | null; target: ChatTarget;
models: string[]; onModel: (m: string) => void; onRan: () => void; onSession?: (sid: string) => void;
+ /** the task no longer exists (deleted): the page lets go of it instead of keeping a composer on it */
+ onMissing?: (sid: string) => void;
additionalHeaders?: string[]; onTotals?: (t: ConvTotals) => void;
}) {
// Additional Headers (app-level auth): per-harness VALUES for the declared header names, kept
@@ -448,6 +451,7 @@ function Conversation({ harnessId, sessionId, target, models, onModel, onRan, on
// and its own composer state.
const { msgs, busy, loading, stopping, outOfCredits, clearOutOfCredits,
liveSessionId, send, stop, setMsgs, updateLast } = useConversationTurn({
+ onMissing,
harnessId, sessionId, target, onRan, onSession, extraHeaders,
onSendStart: () => { setInput(''); setFiles([]); setAtBottom(true); },
});
diff --git a/ui/src/lib/chat.ts b/ui/src/lib/chat.ts
index 8d0c101a..219038ce 100644
--- a/ui/src/lib/chat.ts
+++ b/ui/src/lib/chat.ts
@@ -103,9 +103,10 @@ export interface SessionTurn {
/** Load a past session's conversation (user + assistant per turn) to show its chat history.
* Bounded to the last 200 turns, far beyond any real session, but it keeps a pathological
* long-horizon history from fanning out hundreds of storage reads on every open. */
-export async function loadSessionTurns(sid: string): Promise<{ turns: SessionTurn[]; lastResponseId: string | null }> {
+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() });
- if (!res.ok) return { turns: [], lastResponseId: null };
+ // 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 };
}
diff --git a/ui/src/lib/conversation.ts b/ui/src/lib/conversation.ts
index c75c5288..7038628c 100644
--- a/ui/src/lib/conversation.ts
+++ b/ui/src/lib/conversation.ts
@@ -259,12 +259,14 @@ export function useHarnessBus(harnessId: string, onActivity?: () => void) {
* Owns NO composer state on purpose. `send(text, files)` is given what to send, which is what lets
* Tasks drive one of these from its own composer and Arena drive six from one shared composer.
*/
-export function useConversationTurn({ harnessId, sessionId, target, onRan, onSession, onSendStart, extraHeaders }: {
+export function useConversationTurn({ harnessId, sessionId, target, onRan, onSession, onSendStart, onMissing, extraHeaders }: {
harnessId: string;
sessionId: string | null;
target: ChatTarget;
onRan: () => void;
onSession?: (sid: string) => void;
+ /** the task no longer exists (its feed answers 404, it was deleted): the thread must let go of it */
+ onMissing?: (sid: string) => void;
/** Fired the instant a send is accepted, so a view can clear its composer. */
onSendStart?: () => void;
/** App-auth pass-through header values for this harness. */
@@ -321,7 +323,12 @@ export function useConversationTurn({ harnessId, sessionId, target, onRan, onSes
// Already loaded, idle, and has content → trust it (no refetch on every open).
if (existing.loaded && !existing.busy && existing.msgs.length) return;
setLoading(true);
- loadSessionTurns(sessionId).then(({ turns, lastResponseId }) => {
+ loadSessionTurns(sessionId).then(({ turns, lastResponseId, missing }) => {
+ 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
+ setLoading(false); onMissing?.(sessionId); return;
+ }
const { msgs: m, running } = msgsFromTurns(turns);
const cur = getConvState(convKey);
if (!running) {