Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

fix(turn): tell an IM turn that its runtime died with the service

qiqid298c44ccf22
diff --git a/core/session_turns.py b/core/session_turns.py
index 6c626c573..c054693c5 100644
--- a/core/session_turns.py
+++ b/core/session_turns.py
@@ -40,6 +40,7 @@ from core.run_settlement import (
SETTLED_BY_STOPPED,
SETTLED_BY_TERMINAL_RESULT,
)
+from core.processing_indicator import INTERRUPTED_REACTION_EMOJI
from core.services.dispatch import SOURCE_HUMAN, SOURCE_SCHEDULED, dispatch_turn_with_outcome
from core.services.agent_steering import (
SteerOutcome,
@@ -5348,6 +5349,114 @@ class SessionTurnManager:
return result.state != "reconciling_steer"
return False
+ def _turn_origin_native_message_id(self, turn_id: str) -> str:
+ """The platform message id that opened one Turn, or ``""``.
+
+ Read durably rather than from the live indicator because the caller runs
+ AFTER a restart, where no in-memory handle survived. The Delivery's own
+ snapshot is NOT the source: admission materializes it into ``messages``
+ and clears ``snapshot_json``, so by the time a Turn is active its
+ Delivery no longer carries the native id — only the ledger row it points
+ at does. The snapshot is still consulted first for a Delivery caught
+ before materialization.
+ """
+
+ if not turn_id or not self._durable_schema_available():
+ return ""
+ try:
+ with self._sqlite_engine().connect() as conn:
+ turn = delivery_store.get_turn(conn, turn_id)
+ if turn is None:
+ return ""
+ delivery = delivery_store.get_delivery(
+ conn,
+ str(turn["initial_delivery_id"]),
+ )
+ if delivery is None:
+ return ""
+ payload = delivery_store.delivery_payload(delivery)
+ native_id = str(payload.get("native_message_id") or "").strip()
+ if native_id:
+ return native_id
+ message_id = str(delivery.get("message_id") or "").strip()
+ if not message_id:
+ return ""
+ message = messages_service.get_message(conn, message_id)
+ if message is None:
+ return ""
+ return str(message.get("native_message_id") or "").strip()
+ except Exception:
+ logger.debug(
+ "turn origin lookup failed for turn=%s", turn_id, exc_info=True
+ )
+ return ""
+
+ def _controller_language(self) -> str:
+ language_getter = getattr(self.controller, "_get_lang", None)
+ if callable(language_getter):
+ return language_getter()
+ return getattr(getattr(self.controller, "config", None), "language", "en")
+
+ async def _report_lost_im_turn(
+ self,
+ session_id: str,
+ origin_native_message_id: str,
+ ) -> None:
+ """Tell an IM turn's author that its runtime died with the service.
+
+ An IM turn owns no ``agent_runs`` row, so the Harness interruption lane is
+ structurally unreachable for it: notices are stamped on runs, and
+ ``_settle_agent_run_ids`` returns early for a Turn that has none. Without
+ this report the turn's only trace is a durable row the user cannot read —
+ the thread simply stops, which is indistinguishable from an agent that
+ chose to stay quiet. The reported field case had a user wait five hours
+ before asking what had happened to their request.
+
+ This is deliberately NOT the shape of a Stop, which stays silent because
+ the user caused it and already knows. Nobody asked for this ending, so it
+ has to announce itself.
+ """
+
+ if self.controller is None:
+ return
+ try:
+ context = self._delivery_context(session_id)
+ except Exception:
+ logger.debug(
+ "lost turn report: no delivery context for session=%s",
+ session_id,
+ exc_info=True,
+ )
+ return
+ try:
+ await self.controller.emit_agent_message(
+ context,
+ "notify",
+ i18n_t("turn.interrupted.serviceRestart", self._controller_language()),
+ )
+ except Exception:
+ logger.warning(
+ "lost turn report: failed to notify session=%s",
+ session_id,
+ exc_info=True,
+ )
+ return
+ # The dead process could not clear its own 👀. Retire it here so the
+ # triggering message stops claiming the turn is still running.
+ native_message_id = str(origin_native_message_id or "")
+ service = getattr(self.controller, "processing_indicator", None)
+ stamp = getattr(service, "stamp_orphaned_terminal_reaction", None)
+ if not native_message_id or not callable(stamp):
+ return
+ try:
+ await stamp(context, native_message_id, INTERRUPTED_REACTION_EMOJI)
+ except Exception:
+ logger.debug(
+ "lost turn report: terminal reaction failed for session=%s",
+ session_id,
+ exc_info=True,
+ )
+
async def recover_durable_delivery_state(
self,
session_id: str | None = None,
@@ -5516,6 +5625,11 @@ class SessionTurnManager:
)
for target_session, turn_id, attempt_id, backend in lost_active_turns:
+ # Read Run attribution BEFORE terminalizing: the notice below is owed
+ # only to a turn that has none, and terminalization retires the
+ # deliveries the attribution is derived from.
+ owning_run_ids = self.accepted_agent_run_ids_for_turn(turn_id)
+ origin_message_id = self._turn_origin_native_message_id(turn_id)
terminal = self._terminalize_durable_turn(
turn_id,
"failed",
@@ -5530,6 +5644,8 @@ class SessionTurnManager:
if not terminal.get("changed"):
continue
recovered.append(target_session)
+ if not owning_run_ids:
+ await self._report_lost_im_turn(target_session, origin_message_id)
successor_turn_id = str(terminal.get("successor_turn_id") or "")
if successor_turn_id:
await self._start_persisted_turn(successor_turn_id)
@@ -7291,16 +7407,7 @@ class SessionTurnManager:
if session_row["status"] != "active":
return False
delivery_id = delivery_store.new_delivery_id()
- language_getter = getattr(self.controller, "_get_lang", None)
- language = (
- language_getter()
- if callable(language_getter)
- else getattr(
- getattr(self.controller, "config", None),
- "language",
- "en",
- )
- )
+ language = self._controller_language()
trigger_text = str(
payload.get("agent_initiated_trigger_text")
or i18n_t("harness.agentInitiatedContinuation", language)
diff --git a/tests/test_session_delivery_fsm.py b/tests/test_session_delivery_fsm.py
index 8045cb1f7..3682f86d4 100644
--- a/tests/test_session_delivery_fsm.py
+++ b/tests/test_session_delivery_fsm.py
@@ -25,6 +25,7 @@ from core.run_settlement import (
SETTLED_BY_STOPPED,
SETTLED_BY_TERMINAL_RESULT,
)
+from core.processing_indicator import INTERRUPTED_REACTION_EMOJI
from core.runtime_activation import (
RuntimeActivationRegistry,
RuntimeActivationResolution,
@@ -3182,6 +3183,105 @@ def test_accepted_codex_turn_without_runtime_settles_and_releases_queue(managers
assert [text for _started_turn, text in starts] == ["continue after restart"]
+def _capture_lost_turn_report(manager: SessionTurnManager) -> tuple[list, list]:
+ """Record what a lost turn reports outward, without a real IM client."""
+
+ emitted: list[tuple[str, str]] = []
+ stamped: list[tuple[str, str]] = []
+
+ async def _emit(_context, kind, text, **_kwargs):
+ emitted.append((kind, text))
+
+ async def _stamp(_context, message_id, emoji):
+ stamped.append((message_id, emoji))
+ return True
+
+ manager.controller.emit_agent_message = _emit
+ manager.controller.processing_indicator = SimpleNamespace(
+ stamp_orphaned_terminal_reaction=_stamp
+ )
+ return emitted, stamped
+
+
+def test_lost_im_turn_without_run_reports_interruption(managers) -> None:
+ # An IM turn owns no agent_runs row, so the Harness interruption lane cannot
+ # reach it: without this report the thread just stops, which is
+ # indistinguishable from an agent choosing to stay quiet.
+ first, restarted, engine, _engine_b, _starts = managers
+ context = _context()
+ admitted = asyncio.run(
+ first.deliver(
+ DeliveryRequest(
+ session_id="ses_fsm",
+ priority="p3",
+ content="im turn killed by restart",
+ native_message_id="m-origin",
+ ),
+ context=context,
+ )
+ )
+ turn_id = str(admitted.turn_id)
+ context.platform_specific["turn_token"] = turn_id
+ context.platform_specific["agent_runtime_turn_token"] = f"runtime-{turn_id}"
+ first._active_identity = lambda _backend, _session_id, logical_id: (
+ logical_id,
+ f"native-{logical_id}",
+ )
+ first.on_native_start(
+ context,
+ backend="codex",
+ runtime_key=f"runtime-key-{turn_id}",
+ runtime_turn_id=f"runtime-{turn_id}",
+ )
+ emitted, stamped = _capture_lost_turn_report(restarted)
+ restarted._active_identity = lambda *_args: None
+
+ asyncio.run(restarted.recover_durable_delivery_state("ses_fsm", service_restart=True))
+
+ with engine.connect() as conn:
+ settled = delivery_store.get_turn(conn, turn_id)
+ assert settled is not None and settled["terminal_evidence_kind"] == "restart_runtime_missing"
+ assert [kind for kind, _text in emitted] == ["notify"]
+ assert "interrupted" in emitted[0][1].lower()
+ # The dead process could not clear its own 👀; recovery retires it in place.
+ assert stamped == [("m-origin", INTERRUPTED_REACTION_EMOJI)]
+
+
+def test_lost_turn_owning_a_run_leaves_the_notice_to_the_harness_lane(managers) -> None:
+ # A Harness turn already gets harness.run.interrupted.* stamped on its Run.
+ # Reporting again here would double-notify the same interruption.
+ first, restarted, engine, _engine_b, _starts = managers
+ turn_id, _context_value = asyncio.run(_activate(first, text="harness turn"))
+ with engine.begin() as conn:
+ accepted = delivery_store.delivery_for_turn(conn, turn_id)
+ assert accepted is not None
+ conn.execute(
+ agent_runs.insert().values(
+ id="run-lost-turn",
+ definition_id=None,
+ run_type="scheduled",
+ status="running",
+ cancel_requested=0,
+ session_id="ses_fsm",
+ delivery_id=str(accepted["id"]),
+ created_at="2026-08-01T00:00:00Z",
+ updated_at="2026-08-01T00:00:00Z",
+ metadata_json="{}",
+ )
+ )
+ assert first.accepted_agent_run_ids_for_turn(turn_id) == ["run-lost-turn"]
+ emitted, stamped = _capture_lost_turn_report(restarted)
+ restarted._active_identity = lambda *_args: None
+
+ asyncio.run(restarted.recover_durable_delivery_state("ses_fsm", service_restart=True))
+
+ with engine.connect() as conn:
+ settled = delivery_store.get_turn(conn, turn_id)
+ assert settled is not None and settled["terminal_evidence_kind"] == "restart_runtime_missing"
+ assert emitted == []
+ assert stamped == []
+
+
def test_accepted_opencode_turn_without_restored_identity_stays_live(managers) -> None:
first, restarted, engine, _engine_b, starts = managers
turn_id, _context_value = asyncio.run(_activate(first, text="restorable runtime"))
diff --git a/vibe/i18n/en.json b/vibe/i18n/en.json
index 0584c176e..08aa4d742 100644
--- a/vibe/i18n/en.json
+++ b/vibe/i18n/en.json
@@ -768,5 +768,10 @@
"invalid_oauth_nonce_title": "We couldn't verify this sign-in",
"invalid_oauth_nonce_body": "This sign-in attempt couldn't be verified, so we stopped to keep your account secure. Start over to continue."
}
+ },
+ "turn": {
+ "interrupted": {
+ "serviceRestart": "\u26a0\ufe0f This turn was interrupted \u2014 the Avibe service restarted while it was still running, and its agent runtime could not be resumed. Nothing further will arrive for it. Send the request again if the work still needs doing."
+ }
}
}
diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.json
index bd64dc888..c83ce5f50 100644
--- a/vibe/i18n/zh.json
+++ b/vibe/i18n/zh.json
@@ -768,5 +768,10 @@
"invalid_oauth_nonce_title": "无法验证此次登录",
"invalid_oauth_nonce_body": "本次登录未能通过验证,为保护你的账户已中止。请重新登录以继续。"
}
+ },
+ "turn": {
+ "interrupted": {
+ "serviceRestart": "\u26a0\ufe0f \u672c\u8f6e\u6267\u884c\u88ab\u4e2d\u65ad\u2014\u2014Avibe \u670d\u52a1\u5728\u5b83\u8fd0\u884c\u671f\u95f4\u91cd\u542f\uff0c\u5176 Agent \u8fd0\u884c\u65f6\u65e0\u6cd5\u6062\u590d\u3002\u8fd9\u4e00\u8f6e\u4e0d\u4f1a\u518d\u6709\u4efb\u4f55\u540e\u7eed\u7ed3\u679c\u3002\u5982\u679c\u8fd9\u9879\u5de5\u4f5c\u4ecd\u7136\u9700\u8981\u5b8c\u6210\uff0c\u8bf7\u91cd\u65b0\u53d1\u9001\u8bf7\u6c42\u3002"
+ }
}
}