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.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(chat): project pending Tasks by managing Session (#1327)
Call White7f48d0a10b79
diff --git a/core/scheduled_tasks.py b/core/scheduled_tasks.pyindex c0f9bc681..d8427a9e2 100644--- a/core/scheduled_tasks.py+++ b/core/scheduled_tasks.py@@ -121,6 +121,7 @@ from storage.background import (compute_next_run_at,notice_write_expectation,owed_notice_eligible,+ require_task_resumable,resolve_run_at,)from storage.models import agent_sessions, scope_settings, scopes@@ -1652,6 +1653,12 @@ class ScheduledTaskStore:@_serialize_task_mirrordef set_enabled(self, task_id: str, enabled: bool) -> ScheduledTask:task = self._tasks[task_id]+ if enabled and not task.enabled:+ require_task_resumable(+ task_id,+ metadata=task.metadata,+ session_id=task.session_id,+ )expect = self._read_state(task)task.enabled = enabledtask.updated_at = _utc_now_iso()diff --git a/docs/plans/unified-background-work-banner.md b/docs/plans/unified-background-work-banner.mdindex 0a9a60025..b19bbb227 100644--- a/docs/plans/unified-background-work-banner.md+++ b/docs/plans/unified-background-work-banner.md@@ -18,8 +18,11 @@ The banner's source of truth is a **union assembled at runtime-state build time*2. **Harness items** — derived LIVE from the durable store at assembly time, never duplicatedinto the registry (a watch survives restarts; the registry does not — deriving from the DBkeeps the banner correct-by-construction after a restart):- - enabled watches whose callback session is this session;- - pending/scheduled tasks targeting this session;+ - enabled watches whose callback targets this session;+ - pending/scheduled tasks managed by this session; the task definition's+ creation provenance (`metadata_json.created_by.caller.session_id`) is+ authoritative, with its bound execution `session_id` used only as a+ fallback for legacy tasks without provenance;- active delegated agent runs whose callback returns to this session (work this sessiondispatched and is waiting on). A linked Delivery still in the FIFO `queued` state ispresented as queued even when its executor Run has already moved to `running`.@@ -63,12 +66,15 @@ run detail.3. **Length discipline.** The pill has a max width (~420px); the first-item summary truncateswith ellipsis; the count badge is always visible. The expanded list has a max height(~340px ≈ 5 rows); more items scroll inside the popover.-4. **Row navigation = Harness with an automatic SESSION filter.** Clicking a Watch/task row- opens the Harness page's matching tab with a session filter applied (route param, e.g.- `?session=<id>`), shown as a removable chip ("仅看:本会话") — WITHOUT the filter the page- would show everything, which is wrong coming from a session context. A delegated-run row- opens the runs view similarly filtered/anchored to that run. **This adds Harness-page scope:- the route param + filter chip + filtered queries are part of this PR** (declare the files).+4. **Row navigation = Harness with an automatic OWNER filter.** Clicking a Watch/task row+ opens the Harness page's matching tab with the originating Session's filter applied (route+ param, e.g. `?session=<id>`), shown as a removable chip ("仅看:本会话") — WITHOUT the+ filter the page would show everything, which is wrong coming from a session context. The+ filtered Task query uses the same owner-first rule as the banner, so per-run and pure+ command definitions remain discoverable even without a bound execution Session; Watch+ filtering continues to use its callback target. A delegated-run row opens the runs view+ similarly filtered/anchored to that run. **This adds Harness-page scope: the route param ++ filter chip + filtered queries are part of this PR** (declare the files).5. Ordering inside the popover: active/running first, then by start time descending.## Non-goals (this phase)diff --git a/storage/alembic/versions/20260811_0052_reconcile_orphaned_task_owners.py b/storage/alembic/versions/20260811_0052_reconcile_orphaned_task_owners.pynew file mode 100644index 000000000..e14fcda9e--- /dev/null+++ b/storage/alembic/versions/20260811_0052_reconcile_orphaned_task_owners.py@@ -0,0 +1,70 @@+"""pause enabled scheduled Tasks whose owner is no longer available++Revision ID: 20260811_0052+Revises: 20260811_0051+Create Date: 2026-08-11+"""++from __future__ import annotations++from datetime import datetime, timezone++from alembic import op+import sqlalchemy as sa++revision = "20260811_0052"+down_revision = "20260811_0051"+branch_labels = None+depends_on = None+++_SQLITE_WHITESPACE_EXPR = "' ' || char(9) || char(10) || char(11) || char(12) || char(13)"+_OWNER_SESSION_EXPR = (+ "CASE WHEN json_valid(run_definitions.metadata_json) = 1 THEN "+ "CASE WHEN json_type(run_definitions.metadata_json, '$.created_by.caller.session_id') = 'text' "+ "THEN nullif(trim(json_extract(run_definitions.metadata_json, "+ "'$.created_by.caller.session_id'), " + _SQLITE_WHITESPACE_EXPR + "), '') "+ "END END"+)+++def upgrade() -> None:+ """Stop pre-owner-teardown Tasks that have no surviving execution target.++ Pure command and create-per-run Tasks deliberately leave ``session_id`` blank.+ If their creating Session was removed before owner-aware teardown shipped, an+ enabled definition would continue firing invisibly and an already-paused one+ could later be resumed into that state. Mark both; only enabled rows need their+ enabled state changed.+ """++ bind = op.get_bind()+ now = datetime.now(timezone.utc).isoformat()+ owner_expr = _OWNER_SESSION_EXPR+ bind.execute(+ sa.text(+ "UPDATE run_definitions "+ "SET enabled = CASE WHEN enabled <> 0 THEN 0 ELSE enabled END, "+ "metadata_json = json_set(metadata_json, '$.orphaned_task_owner', "+ "json_object('reason_code', 'task_owner_session_unavailable', "+ "'owner_session_id', (" + owner_expr + "))), "+ "updated_at = :updated_at "+ "WHERE definition_type = 'scheduled' "+ "AND deleted_at IS NULL "+ "AND nullif(trim(session_id, " + _SQLITE_WHITESPACE_EXPR + "), '') IS NULL "+ "AND (" + owner_expr + ") IS NOT NULL "+ "AND NOT EXISTS ("+ "SELECT 1 FROM agent_sessions "+ "WHERE agent_sessions.id = (" + owner_expr + ") "+ "AND agent_sessions.status <> 'archived'"+ ")"+ ),+ {"updated_at": now},+ )+++def downgrade() -> None:+ # The previous enabled/metadata values are not recoverable without a separate+ # audit table; leaving reconciled definitions paused is safer than resuming+ # work with no Session owner or execution target.+ passdiff --git a/storage/background.py b/storage/background.pyindex 272960c16..a2948c3c7 100644--- a/storage/background.py+++ b/storage/background.py@@ -334,6 +334,127 @@ _BLANK_DEFINITION_SUMMARY: dict[str, Any] = {# Where a definition's session binding hides when it has no ``session_id``: a# legacy IM binding, then a ``create_per_run`` delivery target. Precedence order._DEFINITION_SESSION_KEY_FIELDS = ("session_key", "deliver_key")+ORPHANED_TASK_OWNER_METADATA_KEY = "orphaned_task_owner"+TASK_OWNER_UNAVAILABLE_REASON_CODE = "task_owner_session_unavailable"+_SQLITE_TRIM_WHITESPACE = " \t\n\r\f\v"+++def definition_owner_session_id(metadata: Any) -> Optional[str]:+ """Return a valid creation-owner Session ID from definition metadata."""++ if not isinstance(metadata, dict):+ return None+ created_by = metadata.get("created_by")+ if not isinstance(created_by, dict):+ return None+ caller = created_by.get("caller")+ if not isinstance(caller, dict):+ return None+ raw_owner = caller.get("session_id")+ if not isinstance(raw_owner, str):+ return None+ return raw_owner.strip() or None+++def task_resume_block(metadata: Any, session_id: Any) -> Optional[dict[str, str]]:+ """Return the durable reason an orphaned Task cannot be resumed yet."""++ if str(session_id or "").strip() or not isinstance(metadata, dict):+ return None+ marker = metadata.get(ORPHANED_TASK_OWNER_METADATA_KEY)+ if not isinstance(marker, dict):+ return None+ if marker.get("reason_code") != TASK_OWNER_UNAVAILABLE_REASON_CODE:+ return None+ owner_session_id = str(marker.get("owner_session_id") or "").strip()+ if not owner_session_id:+ return None+ return {+ "code": TASK_OWNER_UNAVAILABLE_REASON_CODE,+ "owner_session_id": owner_session_id,+ }+++def definition_owner_session_id_expression() -> Any:+ """Return the durable Session that manages a scheduled definition, when known.++ Definitions created from an Avibe Agent shell preserve their creation+ provenance under ``metadata_json.created_by.caller.session_id``. That is+ the owner used by user-facing Session projections: the execution target may+ be a newly-created Session, or absent for a pure command / per-run task.+ Invalid and legacy metadata deliberately resolve to ``NULL`` so callers can+ fall back to the historical bound ``run_definitions.session_id``. A recorded+ owner that has since been archived or removed is treated the same way for+ projections, preserving visibility for pre-upgrade orphaned definitions.+ """++ metadata_json = run_definitions.c.metadata_json+ raw_owner = func.json_extract(+ metadata_json,+ "$.created_by.caller.session_id",+ )+ return case(+ (+ func.json_valid(metadata_json) == 1,+ case(+ (+ func.json_type(metadata_json, "$.created_by.caller.session_id")+ == "text",+ func.nullif(func.trim(raw_owner, _SQLITE_TRIM_WHITESPACE), ""),+ ),+ else_=None,+ ),+ ),+ else_=None,+ )+++def scheduled_definition_owned_by_session_expression(session_id: str) -> Any:+ """Return the owner-first Session predicate for scheduled Task projections.++ Creation ownership wins while that owner Session still exists and is not+ archived. Once the owner is gone, the execution target resumes the legacy+ fallback so persisted Tasks remain visible instead of becoming orphaned.+ """++ owner_session_id = definition_owner_session_id_expression()+ owner_session_is_live = exists(+ select(literal(1))+ .select_from(agent_sessions)+ .where(+ agent_sessions.c.id == owner_session_id,+ agent_sessions.c.status != "archived",+ )+ )+ return or_(+ and_(owner_session_id == session_id, owner_session_is_live),+ and_(+ or_(owner_session_id.is_(None), ~owner_session_is_live),+ run_definitions.c.session_id == session_id,+ ),+ )+++def scheduled_definition_reclaimable_by_session_expression(session_id: str) -> Any:+ """Return the teardown predicate for scheduled Tasks touching a Session.++ Teardown is broader than banner projection: removing an execution target must+ also stop a Task created by a different Session from firing into that dead+ target. Owner-first remains the projection rule; this expression is only for+ reclaim and archive accounting.+ """++ # Teardown must retain the raw provenance match even after the owner row is+ # archived; that is the event that caused this cleanup. Projection uses the+ # liveness-aware owner-first expression above, while teardown covers both+ # owner identity and execution target identity.+ owner_session_id = definition_owner_session_id_expression()+ return or_(+ owner_session_id == session_id,+ run_definitions.c.session_id == session_id,+ )++# The exit code a waiter that ran out of lifetime carries. Written by# ``core/watches.py`` (the ``timeout`` convention), read here to tell an ending# that ran out of time from one that failed.@@ -419,6 +540,84 @@ class DefinitionWriteConflict(RuntimeError):self.definition_type = str(definition_type)+class TaskResumeBlocked(RuntimeError):+ """A paused Task has neither a surviving owner nor an execution target."""++ code = TASK_OWNER_UNAVAILABLE_REASON_CODE++ def __init__(self, definition_id: str, owner_session_id: str) -> None:+ super().__init__(+ f"task {definition_id} cannot be resumed because its owner Session "+ f"{owner_session_id} is unavailable and it has no execution target"+ )+ self.definition_id = str(definition_id)+ self.owner_session_id = str(owner_session_id)+++def require_task_resumable(+ definition_id: str,+ *,+ metadata: Any,+ session_id: Any,+) -> None:+ blocked = task_resume_block(metadata, session_id)+ if blocked is not None:+ raise TaskResumeBlocked(definition_id, blocked["owner_session_id"])+++def clear_task_resume_blocks_for_available_owner(+ conn: Any,+ owner_session_id: str,+) -> int:+ """Clear stale orphan markers when a refused teardown leaves the owner live."""++ sid = str(owner_session_id or "").strip()+ if not sid:+ return 0+ owner_is_live = conn.execute(+ select(literal(1))+ .select_from(agent_sessions)+ .where(agent_sessions.c.id == sid, agent_sessions.c.status != "archived")+ .limit(1)+ ).first()+ if owner_is_live is None:+ return 0++ rows = (+ conn.execute(+ select(+ run_definitions.c.id,+ run_definitions.c.session_id,+ run_definitions.c.metadata_json,+ )+ .where(run_definitions.c.definition_type == "scheduled")+ .where(run_definitions.c.deleted_at.is_(None))+ )+ .mappings()+ .all()+ )+ cleared = 0+ now = _utc_now_iso()+ for row in rows:+ metadata = _json_loads(row["metadata_json"], {})+ if definition_owner_session_id(metadata) != sid:+ continue+ blocked = task_resume_block(metadata, row["session_id"])+ if blocked is None or blocked["owner_session_id"] != sid:+ continue+ metadata = dict(metadata)+ metadata.pop(ORPHANED_TASK_OWNER_METADATA_KEY, None)+ result = conn.execute(+ update(run_definitions)+ .where(run_definitions.c.id == row["id"])+ .where(run_definitions.c.deleted_at.is_(None))+ .where(run_definitions.c.metadata_json == row["metadata_json"])+ .values(metadata_json=_json_dumps(metadata), updated_at=now)+ )+ cleared += int(result.rowcount or 0)+ return cleared++@dataclass(frozen=True)class DefinitionWriteExpectation:"""The definition state a FULL-ROW payload was derived from.@@ -2895,6 +3094,11 @@ class SQLiteBackgroundTaskStore:definition_type: Optional[str] = None,) -> bool:with self.engine.begin() as conn:+ if enabled:+ # The resumability decision and enabling UPDATE are one atomic+ # transition. Without the writer reservation, /new can stamp an+ # orphan-owner block after the SELECT and before this UPDATE.+ reserve_write_lock(conn)values: dict[str, Any] = {"enabled": 1 if enabled else 0, "updated_at": _utc_now_iso()}if enabled:# Resuming may start a new lifecycle, and the old one must stop@@ -2909,6 +3113,7 @@ class SQLiteBackgroundTaskStore:run_definitions.c.definition_type,run_definitions.c.mode,run_definitions.c.enabled,+ run_definitions.c.session_id,run_definitions.c.metadata_json,).where(run_definitions.c.id == definition_id)@@ -2918,6 +3123,12 @@ class SQLiteBackgroundTaskStore:.first())if current is not None and not current["enabled"]:+ if current["definition_type"] == "scheduled":+ require_task_resumable(+ definition_id,+ metadata=_json_loads(current["metadata_json"], {}),+ session_id=current["session_id"],+ )clear_columns = definition_resume_clear_columns(current["definition_type"], current["mode"])@@ -3750,10 +3961,20 @@ class SQLiteBackgroundTaskStore:stmt.where(run_definitions.c.definition_type == definition_type).where(run_definitions.c.deleted_at.is_(None)))- # Precise bound-session filter (ix_run_definitions_session) — powers the- # Harness "只看本会话" chip that background-work banner rows navigate into.+ # This Session filter powers the Harness "只看本会话" chip that the+ # background-work banner navigates into. Scheduled Tasks use creation+ # provenance as the authoritative owner: a create-per-run or pure command+ # definition may have no bound execution Session at all. Legacy Task rows+ # without provenance retain the historical bound-session behavior.if session_id:- stmt = stmt.where(run_definitions.c.session_id == session_id)+ if definition_type == "scheduled":+ stmt = stmt.where(+ scheduled_definition_owned_by_session_expression(session_id)+ )+ else:+ # A Watch is an event callback surface: its callback target, not+ # the Session that created the definition, owns its banner row.+ stmt = stmt.where(run_definitions.c.session_id == session_id)if status and status != "all":states = DEFINITION_STATUS_FILTERS.get(status)if not states:@@ -7684,6 +7905,7 @@ class SQLiteBackgroundTaskStore:@staticmethoddef _scheduled_task_from_row(row: Any) -> dict[str, Any]:+ metadata = _json_loads(row["metadata_json"], {})return {"id": row["id"],"name": row["name"],@@ -7711,7 +7933,8 @@ class SQLiteBackgroundTaskStore:"last_run_at": row["last_run_at"],"last_run_id": row["last_run_id"],"last_error": row["last_error"],- "metadata": _json_loads(row["metadata_json"], {}),+ "metadata": metadata,+ "resume_blocked": task_resume_block(metadata, row["session_id"]),"lifecycle_state": _row_lifecycle_state(row),}diff --git a/storage/session_reclaim.py b/storage/session_reclaim.pyindex fb3a28cb9..1dc00b80d 100644--- a/storage/session_reclaim.py+++ b/storage/session_reclaim.py@@ -1,7 +1,7 @@-"""Reclaim the definitions bound to a Session that is going away.+"""Reclaim the definitions managed by or targeting a Session that is going away.Two teardown paths, one contract. ``archive_session`` already reclaimed —-it vacates the anchor and soft-deletes bound ``run_definitions`` — while the IM+it vacates the anchor and soft-deletes affected ``run_definitions`` — while the IM``/new`` path hard-deleted the session rows and reclaimed nothing, so a``create_once`` task pinned to that session fired and failed forever with nobodytold. This module owns the shared half so a new teardown path cannot forget it.@@ -31,7 +31,7 @@ from contextvars import ContextVarfrom datetime import datetime, timezonefrom typing import Any, Iterable, Iterator, Literal-from sqlalchemy import select, update+from sqlalchemy import and_, or_, select, updatefrom sqlalchemy.engine import Connectionfrom storage.models import agent_sessions, run_definitions@@ -294,7 +294,7 @@ def reclaim_bound_definitions(mode: ReclaimMode,reason: str | None = None,) -> dict[str, int]:- """Detach scheduled tasks / watches from a session that is going away.+ """Detach scheduled tasks / watches affected by a session going away.``mode`` is required: ``delete`` soft-deletes (terminal teardown), ``pause``sets ``enabled=0`` and records ``last_error`` (recoverable teardown). Runs in@@ -314,15 +314,37 @@ def reclaim_bound_definitions(if not sid:return summary+ # A scheduled Task is managed by its creating Session for projection, but+ # teardown must also reclaim Tasks whose execution target is the Session being+ # removed. Otherwise an owner-targeted Task can keep firing into a dead target.+ from storage.background import (+ ORPHANED_TASK_OWNER_METADATA_KEY,+ TASK_OWNER_UNAVAILABLE_REASON_CODE,+ definition_owner_session_id,+ scheduled_definition_reclaimable_by_session_expression,+ )++ definition_binding = or_(+ and_(+ run_definitions.c.definition_type == "watch",+ run_definitions.c.session_id == sid,+ ),+ and_(+ run_definitions.c.definition_type == "scheduled",+ scheduled_definition_reclaimable_by_session_expression(sid),+ ),+ )+rows = (conn.execute(select(run_definitions.c.id,run_definitions.c.definition_type,run_definitions.c.enabled,+ run_definitions.c.session_id,run_definitions.c.metadata_json,)- .where(run_definitions.c.session_id == sid)+ .where(definition_binding).where(run_definitions.c.deleted_at.is_(None))).mappings()@@ -339,11 +361,29 @@ def reclaim_bound_definitions(for row in rows:values: dict[str, Any] = {"updated_at": now}counters: list[str] = []+ metadata = _json_object(row["metadata_json"])+ metadata_changed = Falseif snapshot is not None:- metadata = _json_object(row["metadata_json"])metadata[SESSION_SETTINGS_SNAPSHOT_KEY] = snapshot- values["metadata_json"] = _dump_json(metadata)+ metadata_changed = Truecounters.append("snapshotted")+ if (+ mode == RECLAIM_PAUSE+ and row["definition_type"] == "scheduled"+ and not str(row["session_id"] or "").strip()+ and definition_owner_session_id(metadata) == sid+ ):+ # A pure-command/create-per-run Task has no execution target to fall+ # back to once its managing Session disappears. Preserve one stable+ # marker for migration and live teardown alike so every resume path+ # applies the same policy instead of making it fire invisibly.+ metadata[ORPHANED_TASK_OWNER_METADATA_KEY] = {+ "reason_code": TASK_OWNER_UNAVAILABLE_REASON_CODE,+ "owner_session_id": sid,+ }+ metadata_changed = True+ if metadata_changed:+ values["metadata_json"] = _dump_json(metadata)changed = Falseif mode == RECLAIM_DELETE:values["deleted_at"] = now@@ -373,11 +413,18 @@ def reclaim_bound_definitions(# belongs to -- so a later ``create_once`` rebind carries the wrong model# forward. Both re-asserted: the binding this reclaim was decided for, and the# live ``deleted_at`` state.+ current_binding = (+ run_definitions.c.session_id == sid+ if row["definition_type"] == "watch"+ else scheduled_definition_reclaimable_by_session_expression(sid)+ )reclaimed = conn.execute(update(run_definitions).where(run_definitions.c.id == row["id"])- # Still bound to the session that is going away.- .where(run_definitions.c.session_id == sid)+ # Still reclaimable by the Session that is going away. The scheduled-task+ # branch covers either creation ownership or the execution target; the+ # Watch branch uses its callback target.+ .where(current_binding)# Still live: a definition deleted inside the window stays deleted, and its# ``deleted_at`` must not be restamped with this teardown's clock..where(run_definitions.c.deleted_at.is_(None))@@ -413,7 +460,7 @@ def reclaim_bound_definitions(if summary["paused"] or summary["deleted"]:logger.info(- "Reclaimed definitions bound to session %s mode=%s paused=%d deleted=%d",+ "Reclaimed definitions for session %s mode=%s paused=%d deleted=%d",sid,mode,summary["paused"],diff --git a/storage/sessions_service.py b/storage/sessions_service.pyindex 750898720..b806fef8c 100644--- a/storage/sessions_service.py+++ b/storage/sessions_service.py@@ -2294,9 +2294,11 @@ def _delete_agent_session_rows(# the read pins a snapshot, and the reclaim's UPDATE then fails outright with# ``SQLITE_BUSY_SNAPSHOT`` ("database is locked") on exactly the interleaving this# whole guard exists to survive. Measured, not assumed. Leaving the reclaim in- # place is also the recoverable half: the definitions were bound to the session+ # place is also the recoverable half: the definitions were owned by the session# the user asked to clear, ``pause`` keeps them re-enablable, and the kept row is- # a superseded one the thread has already moved off.+ # a superseded one the thread has already moved off. Owner-only Tasks briefly+ # receive the same orphan marker as a successful teardown; the refused-claim+ # branch removes it again once it proves the owner row is still live.reclaim_bound_definitions(conn, session_id, mode=reclaim_mode, reason=reclaim_reason)claimed = bool(conn.execute(@@ -2307,6 +2309,10 @@ def _delete_agent_session_rows().rowcount)if not claimed:+ if reclaim_mode == RECLAIM_PAUSE:+ from storage.background import clear_task_resume_blocks_for_available_owner++ clear_task_resume_blocks_for_available_owner(conn, session_id)logger.warning("Skipped hard-deleting session %s: it stopped matching the teardown ""query concurrently (superseded, re-anchored or already gone)",diff --git a/storage/workbench_sessions_service.py b/storage/workbench_sessions_service.pyindex afb5d9e8d..e684e68e1 100644--- a/storage/workbench_sessions_service.py+++ b/storage/workbench_sessions_service.py@@ -848,14 +848,29 @@ def is_session_archived(conn: Connection, session_id: str) -> bool:def count_bound_resources(conn: Connection, session_id: str) -> dict[str, int]:- """Count what archiving ``session_id`` will permanently reclaim: bound- scheduled tasks + watches (live, not-yet-deleted definitions) and- not-yet-terminal runs. Shared by the archive teardown and the confirm-dialog- preview so both agree on the numbers shown vs. acted on."""+ """Count what archiving ``session_id`` will permanently reclaim.++ Scheduled Tasks are counted when either their creation owner or execution+ target is this Session; Watches remain callback-targeted. This is deliberately+ broader than the owner-first banner projection so the archive preview matches+ teardown and no Task survives with a dead execution target.+ """+ from storage.background import scheduled_definition_reclaimable_by_session_expression++ definition_binding = or_(+ and_(+ run_definitions.c.definition_type == "watch",+ run_definitions.c.session_id == session_id,+ ),+ and_(+ run_definitions.c.definition_type == "scheduled",+ scheduled_definition_reclaimable_by_session_expression(session_id),+ ),+ )types = (conn.execute(select(run_definitions.c.definition_type)- .where(run_definitions.c.session_id == session_id)+ .where(definition_binding).where(run_definitions.c.deleted_at.is_(None))).scalars()@@ -956,8 +971,11 @@ def derive_session_harness_activities(conn: Connection, session_id: str) -> listconstruction across restarts (a watch survives a restart; the registry doesnot). Three sources, all scoped to ``session_id``:- - enabled, live (not soft-deleted) watches bound to this session;- - enabled, live scheduled tasks bound to this session;+ - enabled, live (not soft-deleted) watches whose callback targets this+ session;+ - enabled, live scheduled tasks managed by this session; creation provenance+ is authoritative, with the bound session as a legacy fallback for+ definitions that predate provenance capture;- queued/running delegated agent runs whose callback returns here (work thissession dispatched and is waiting on).@@ -971,7 +989,11 @@ def derive_session_harness_activities(conn: Connection, session_id: str) -> list# Watches + scheduled tasks live in ``run_definitions``, discriminated by# ``definition_type`` (see storage/background.py). Both must be enabled and- # not soft-deleted to count as ongoing background work for the session.+ # not soft-deleted to count as ongoing background work for the session. The+ # Task owner expression is shared with the Harness session filter so a+ # row remains discoverable after the banner navigates to that filtered page.+ from storage.background import scheduled_definition_owned_by_session_expression+definition_rows = (conn.execute(select(@@ -984,7 +1006,18 @@ def derive_session_harness_activities(conn: Connection, session_id: str) -> listrun_definitions.c.created_at,run_definitions.c.updated_at,)- .where(run_definitions.c.session_id == session_id)+ .where(+ or_(+ and_(+ run_definitions.c.definition_type == "watch",+ run_definitions.c.session_id == session_id,+ ),+ and_(+ run_definitions.c.definition_type == "scheduled",+ scheduled_definition_owned_by_session_expression(session_id),+ ),+ )+ ).where(run_definitions.c.deleted_at.is_(None)).where(run_definitions.c.enabled == 1).order_by(run_definitions.c.created_at, run_definitions.c.id)@@ -1107,8 +1140,8 @@ def archive_session(conn: Connection, session_id: str) -> dict[str, Any]:Archive is terminal (there is no un-archive) — so we don't just flip a flag,we tear down the resources that would otherwise keep firing into a hidden- session: bound scheduled tasks + watches are soft-deleted, queued/running- runs are cancelled, and the Show Page is taken offline. All of it rides the+ session: affected scheduled tasks + callback-targeted watches are soft-deleted,+ queued/running runs are cancelled, and the Show Page is taken offline. All of it rides thecaller's transaction so the teardown is atomic with the status flip.The one piece that can't live here is cancelling an in-flight chat turn: it@@ -1165,7 +1198,8 @@ def archive_session(conn: Connection, session_id: str) -> dict[str, Any]:# Tally before teardown so the response reports what was reclaimed.reclaimed = count_bound_resources(conn, session_id)- # 2) Soft-delete bound scheduled tasks + watches (same table, distinguished by+ # 2) Soft-delete scheduled tasks affected by this Session (creation owner or+ # execution target) + callback-targeted watches (same table, distinguished by# ``definition_type``). Deleting — not pausing — is deliberate: a paused# definition could be re-enabled later and would then target a dead session.# Shared with the hard-delete teardown path, which passes ``pause`` insteaddiff --git a/tests/scenarios/harness_command_task/catalog.yaml b/tests/scenarios/harness_command_task/catalog.yamlindex 79f1d5e5d..dc2ec823b 100644--- a/tests/scenarios/harness_command_task/catalog.yaml+++ b/tests/scenarios/harness_command_task/catalog.yaml@@ -8,6 +8,7 @@ capability:- tests/test_scheduled_tasks.py- tests/test_command_runner.py- tests/test_cli_task_command.py+ - tests/test_background_work_banner.pyshared_harness: []status_legend:covered: deterministic scenario or contract coverage exists@@ -672,3 +673,10 @@ scenarios:# wherever ``--cwd`` set both and differ exactly where the user separated them, so# the stored command half now outranks the Session's: SCT-051's rule -- only the# explicit flag replaces a stored directory -- in the retarget lane.+ - id: SCT-060+ name: pending definitions remain visible in their creating Session's background banner+ status: covered+ kind: routing+ layer: contract+ backend: shared+ test: tests/test_background_work_banner.py::test_definition_banner_uses_creation_owner_before_execution_targetdiff --git a/tests/test_background_work_banner.py b/tests/test_background_work_banner.pyindex 90b90e517..5b908d522 100644--- a/tests/test_background_work_banner.py+++ b/tests/test_background_work_banner.py@@ -10,21 +10,26 @@ banner stays correct across a restart.from __future__ import annotations+import jsonfrom contextlib import nullcontextfrom pathlib import Pathfrom types import SimpleNamespace-from sqlalchemy import insert+from sqlalchemy import insert, selectfrom core.session_activities import SessionActivityRegistryfrom core.session_turns import SessionTurnManagerfrom storage import message_deliveries as delivery_storefrom storage.agent_session_rows import create_agent_session_row-from storage.background import SQLiteBackgroundTaskStore+from storage.background import SQLiteBackgroundTaskStore, task_resume_blockfrom storage.db import create_sqlite_enginefrom storage.importer import ensure_sqlite_statefrom storage.models import agent_runs, run_definitions-from storage.workbench_sessions_service import derive_session_harness_activities+from storage.session_reclaim import RECLAIM_DELETE, RECLAIM_PAUSE, reclaim_bound_definitions+from storage.workbench_sessions_service import (+ count_bound_resources,+ derive_session_harness_activities,+)_NOW = "2026-07-16T00:00:00Z"@@ -229,6 +234,323 @@ def test_task_label_falls_back_to_prompt_when_unnamed(tmp_path: Path):assert items[0]["label"] == "summarize the daily standup notes"+def test_definition_banner_uses_creation_owner_before_execution_target(tmp_path: Path):+ """SCT-060: pending definitions belong to their creating Session, not their fire target."""+ engine, _ = _make_engine(tmp_path)+ owner_metadata = json.dumps(+ {"created_by": {"caller": {"session_id": "ses-owner"}}}+ )+ with engine.begin() as conn:+ for session_id, session_anchor in (+ ("ses-owner", "banner-owner"),+ ("ses-other", "banner-other"),+ ):+ create_agent_session_row(+ conn,+ scope_id=None,+ session_id=session_id,+ session_anchor=session_anchor,+ agent_backend="codex",+ workdir="/tmp",+ now=_NOW,+ )+ _insert_definition(+ engine,+ id="task-per-run",+ definition_type="scheduled",+ name="per run",+ metadata_json=owner_metadata,+ )+ _insert_definition(+ engine,+ id="task-command",+ definition_type="scheduled",+ name="command",+ metadata_json=owner_metadata,+ )+ _insert_definition(+ engine,+ id="task-create-once",+ definition_type="scheduled",+ name="new session",+ session_id="ses-execution",+ metadata_json=owner_metadata,+ )+ # A legacy row has no creation provenance and keeps the old bound-session+ # fallback. A row with provenance pointing elsewhere must not leak through+ # its execution target.+ _insert_definition(+ engine,+ id="task-legacy",+ definition_type="scheduled",+ name="legacy",+ session_id="ses-owner",+ )+ _insert_definition(+ engine,+ id="task-owned-elsewhere",+ definition_type="scheduled",+ name="owned elsewhere",+ session_id="ses-owner",+ metadata_json=json.dumps(+ {"created_by": {"caller": {"session_id": "ses-other"}}}+ ),+ )+ # Schema-invalid owner values must not suppress the legacy bound-session fallback.+ for task_id, owner_value in (+ ("task-owner-object", {}),+ ("task-owner-number", 42),+ ):+ _insert_definition(+ engine,+ id=task_id,+ definition_type="scheduled",+ name=task_id,+ session_id="ses-owner",+ metadata_json=json.dumps(+ {"created_by": {"caller": {"session_id": owner_value}}}+ ),+ )++ with engine.connect() as conn:+ owner_items = derive_session_harness_activities(conn, "ses-owner")+ execution_items = derive_session_harness_activities(conn, "ses-execution")++ assert {item["id"] for item in owner_items} == {+ "task:task-per-run",+ "task:task-command",+ "task:task-create-once",+ "task:task-legacy",+ "task:task-owner-object",+ "task:task-owner-number",+ }+ assert {item["id"] for item in execution_items} == set()+++def test_definition_banner_falls_back_to_live_target_when_owner_is_gone(tmp_path: Path):+ """Orphaned Owner provenance falls back to the live execution target."""+ engine, _ = _make_engine(tmp_path)+ with engine.begin() as conn:+ create_agent_session_row(+ conn,+ scope_id=None,+ session_id="ses-execution",+ session_anchor="banner-execution",+ agent_backend="codex",+ workdir="/tmp",+ now=_NOW,+ )+ create_agent_session_row(+ conn,+ scope_id=None,+ session_id="ses-archived-owner",+ session_anchor="banner-archived-owner",+ agent_backend="codex",+ workdir="/tmp",+ status="archived",+ now=_NOW,+ )++ for task_id, owner_session_id in (+ ("task-missing-owner", "ses-removed-owner"),+ ("task-archived-owner", "ses-archived-owner"),+ ):+ _insert_definition(+ engine,+ id=task_id,+ definition_type="scheduled",+ name=task_id,+ session_id="ses-execution",+ metadata_json=json.dumps(+ {"created_by": {"caller": {"session_id": owner_session_id}}}+ ),+ )++ with engine.connect() as conn:+ execution_items = derive_session_harness_activities(conn, "ses-execution")++ assert {item["id"] for item in execution_items} == {+ "task:task-missing-owner",+ "task:task-archived-owner",+ }+++def test_owner_session_teardown_reclaims_task_even_when_execution_target_differs(+ tmp_path: Path,+):+ """Teardown covers both the managing owner and a dying execution target."""+ engine, _ = _make_engine(tmp_path)+ owner_metadata = json.dumps(+ {"created_by": {"caller": {"session_id": "ses-owner"}}}+ )+ foreign_owner_metadata = json.dumps(+ {"created_by": {"caller": {"session_id": "ses-other"}}}+ )+ with engine.begin() as conn:+ create_agent_session_row(+ conn,+ scope_id=None,+ session_id="ses-owner",+ session_anchor="anchor-owner",+ agent_backend="codex",+ workdir="/tmp",+ now=_NOW,+ )+ create_agent_session_row(+ conn,+ scope_id=None,+ session_id="ses-execution",+ session_anchor="anchor-execution",+ agent_backend="codex",+ workdir="/tmp",+ now=_NOW,+ )+ _insert_definition(+ engine,+ id="task-owner-targeted",+ definition_type="scheduled",+ name="owner-targeted",+ session_id="ses-execution",+ metadata_json=owner_metadata,+ )+ _insert_definition(+ engine,+ id="task-target-only",+ definition_type="scheduled",+ name="target-only",+ session_id="ses-execution",+ metadata_json=foreign_owner_metadata,+ )++ with engine.begin() as conn:+ assert count_bound_resources(conn, "ses-owner")["tasks"] == 1+ summary = reclaim_bound_definitions(+ conn,+ "ses-owner",+ mode=RECLAIM_DELETE,+ reason="archive_session:ses-owner",+ )+ row = conn.execute(+ select(run_definitions.c.deleted_at).where(+ run_definitions.c.id == "task-owner-targeted"+ )+ ).scalar_one()+ assert count_bound_resources(conn, "ses-execution")["tasks"] == 1+ target_summary = reclaim_bound_definitions(+ conn,+ "ses-execution",+ mode=RECLAIM_DELETE,+ reason="archive_session:ses-execution",+ )+ target_row = conn.execute(+ select(run_definitions.c.deleted_at).where(+ run_definitions.c.id == "task-target-only"+ )+ ).scalar_one()++ assert summary["deleted"] == 1+ assert row is not None+ assert target_summary["deleted"] == 1+ assert target_row is not None+++def test_owner_session_pause_marks_unbound_task_as_not_resumable(tmp_path: Path):+ """Live /new teardown and upgrade reconciliation share one resume policy."""++ engine, _ = _make_engine(tmp_path)+ with engine.begin() as conn:+ create_agent_session_row(+ conn,+ scope_id=None,+ session_id="ses-owner",+ session_anchor="anchor-owner",+ agent_backend="codex",+ workdir="/tmp",+ now=_NOW,+ )+ _insert_definition(+ engine,+ id="task-owner-only",+ definition_type="scheduled",+ name="owner-only",+ session_id=" ",+ metadata_json=json.dumps(+ {"created_by": {"caller": {"session_id": "ses-owner"}}}+ ),+ )++ with engine.begin() as conn:+ summary = reclaim_bound_definitions(+ conn,+ "ses-owner",+ mode=RECLAIM_PAUSE,+ reason="session cleared by /new",+ )+ row = (+ conn.execute(+ select(+ run_definitions.c.enabled,+ run_definitions.c.session_id,+ run_definitions.c.metadata_json,+ ).where(run_definitions.c.id == "task-owner-only")+ )+ .mappings()+ .one()+ )++ metadata = json.loads(row["metadata_json"])+ assert summary["paused"] == 1+ assert row["enabled"] == 0+ assert task_resume_block(metadata, row["session_id"]) == {+ "code": "task_owner_session_unavailable",+ "owner_session_id": "ses-owner",+ }+++def test_archived_owner_teardown_reclaims_task_by_creation_provenance(tmp_path: Path):+ """Teardown still uses archived Owner identity even though projection falls back."""+ engine, _ = _make_engine(tmp_path)+ owner_metadata = json.dumps(+ {"created_by": {"caller": {"session_id": "ses-archived-owner"}}}+ )+ with engine.begin() as conn:+ create_agent_session_row(+ conn,+ scope_id=None,+ session_id="ses-archived-owner",+ session_anchor="archive-owner",+ agent_backend="codex",+ workdir="/tmp",+ status="archived",+ now=_NOW,+ )+ _insert_definition(+ engine,+ id="task-archived-owner",+ definition_type="scheduled",+ name="archived-owner",+ session_id="ses-execution",+ metadata_json=owner_metadata,+ )++ with engine.begin() as conn:+ assert count_bound_resources(conn, "ses-archived-owner")["tasks"] == 1+ summary = reclaim_bound_definitions(+ conn,+ "ses-archived-owner",+ mode=RECLAIM_DELETE,+ reason="archive_session:ses-archived-owner",+ )+ deleted_at = conn.execute(+ select(run_definitions.c.deleted_at).where(+ run_definitions.c.id == "task-archived-owner"+ )+ ).scalar_one()++ assert summary["deleted"] == 1+ assert deleted_at is not None++def test_excludes_disabled_deleted_and_foreign_and_terminal(tmp_path: Path):engine, _ = _make_engine(tmp_path)# Disabled watch: paused, not ongoing background work.@@ -401,24 +723,80 @@ def test_banner_enabled_pref_round_trip(tmp_path: Path):assert get_background_work_banner_enabled(db_path=db_path) is True-def test_definition_session_filter_scopes_watches_and_tasks(tmp_path: Path):- # Spec req 4: the Harness "只看本会话" chip filters definitions by bound- # session. Rows for session A must exclude session B's definitions.+def test_definition_session_filter_scopes_watches_and_tasks_by_owner(tmp_path: Path):+ # The Harness "只看本会话" chip follows the same creation-owner rule as+ # the banner. Legacy definitions without provenance still use their bound+ # session as the fallback.engine, db_path = _make_engine(tmp_path)+ with engine.begin() as conn:+ for session_id, session_anchor in (("ses-A", "filter-a"), ("ses-B", "filter-b")):+ create_agent_session_row(+ conn,+ scope_id=None,+ session_id=session_id,+ session_anchor=session_anchor,+ agent_backend="codex",+ workdir="/tmp",+ now=_NOW,+ )_insert_definition(engine, id="w-a", definition_type="watch", name="wa", session_id="ses-A")_insert_definition(engine, id="w-b", definition_type="watch", name="wb", session_id="ses-B")+ _insert_definition(+ engine,+ id="w-callback-wins",+ definition_type="watch",+ name="wc",+ session_id="ses-B",+ metadata_json=json.dumps(+ {"created_by": {"caller": {"session_id": "ses-A"}}}+ ),+ )_insert_definition(engine, id="t-a", definition_type="scheduled", name="ta", session_id="ses-A")_insert_definition(engine, id="t-b", definition_type="scheduled", name="tb", session_id="ses-B")+ owner_metadata = json.dumps(+ {"created_by": {"caller": {"session_id": "ses-A"}}}+ )+ _insert_definition(+ engine,+ id="t-owner-only",+ definition_type="scheduled",+ name="owner-only",+ session_id=None,+ metadata_json=owner_metadata,+ )+ _insert_definition(+ engine,+ id="t-owner-wins",+ definition_type="scheduled",+ name="owner-wins",+ session_id="ses-B",+ metadata_json=owner_metadata,+ )+ _insert_definition(+ engine,+ id="t-orphan-owner",+ definition_type="scheduled",+ name="orphan-owner",+ session_id="ses-B",+ metadata_json=json.dumps(+ {"created_by": {"caller": {"session_id": "ses-removed"}}}+ ),+ )store = SQLiteBackgroundTaskStore(db_path=db_path)try:watches_a = store.list_watches_page(session_id="ses-A", page_request=None)assert [w["id"] for w in watches_a.items] == ["w-a"]+ watches_b = store.list_watches_page(session_id="ses-B", page_request=None)+ assert {w["id"] for w in watches_b.items} == {"w-b", "w-callback-wins"}tasks_a = store.list_scheduled_tasks_page(session_id="ses-A", page_request=None)- assert [t["id"] for t in tasks_a.items] == ["t-a"]+ assert {t["id"] for t in tasks_a.items} == {"t-a", "t-owner-only", "t-owner-wins"}+ tasks_b = store.list_scheduled_tasks_page(session_id="ses-B", page_request=None)+ assert {t["id"] for t in tasks_b.items} == {"t-b", "t-orphan-owner"}assert store.count_watches(session_id="ses-A")["total"] == 1- assert store.count_scheduled_tasks(session_id="ses-B")["total"] == 1+ assert store.count_scheduled_tasks(session_id="ses-B")["total"] == 2# No filter → both sessions' definitions are returned.- assert len(store.list_watches_page(page_request=None).items) == 2+ assert len(store.list_watches_page(page_request=None).items) == 3+ assert len(store.list_scheduled_tasks_page(page_request=None).items) == 5finally:store.close()diff --git a/tests/test_cli_task_command.py b/tests/test_cli_task_command.pyindex ab733eb5a..b4273c660 100644--- a/tests/test_cli_task_command.py+++ b/tests/test_cli_task_command.py@@ -102,6 +102,58 @@ def test_disabled_agent_cannot_run(tmp_path: Path) -> None:assert payload["error"] == "agent 'worker' is disabled"+def test_task_resume_rejects_orphaned_owner_without_execution_target(+ monkeypatch, tmp_path: Path+) -> None:+ """A migrated orphan cannot resume into an invisible firing state."""++ from storage.importer import ensure_sqlite_state++ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ ensure_sqlite_state()+ store = cli.ScheduledTaskStore()+ task = store.add_task(+ name="Orphaned command",+ session_key="",+ prompt="",+ schedule_type="cron",+ cron="0 * * * *",+ timezone_name="UTC",+ shell_command="true",+ metadata={+ "orphaned_task_owner": {+ "reason_code": "task_owner_session_unavailable",+ "owner_session_id": "ses-removed",+ }+ },+ )+ task.enabled = False+ store.upsert_task(task)++ with (+ patch("vibe.cli._task_store", return_value=store),+ patch("vibe.cli._memory_cli_language", return_value="zh"),+ ):+ result, payload = _capture_stderr_json(+ cli.cmd_task_set_enabled,+ task.id,+ True,+ )++ assert result == 1+ assert payload["code"] == "task_owner_session_unavailable"+ assert payload["error"] == "这个 Task 的管理 Session 已不可用。"+ assert payload["hint"] == (+ "请从可用的 Agent Session 创建替代 Task,再用 "+ f"`vibe task remove {task.id}` 删除这条失去管理者的定义。"+ )+ assert payload["details"] == {+ "task_id": task.id,+ "owner_session_id": "ses-removed",+ }+ assert cli.ScheduledTaskStore().get_task(task.id).enabled is False++def test_task_update_preserves_archived_agent_reference(capsys) -> None:db_path = cli.paths.get_sqlite_state_path()agent_store = cli.VibeAgentStore(db_path)diff --git a/tests/test_sqlite_sessions_store.py b/tests/test_sqlite_sessions_store.pyindex df023c265..2e6acfc98 100644--- a/tests/test_sqlite_sessions_store.py+++ b/tests/test_sqlite_sessions_store.py@@ -5895,8 +5895,9 @@ def _bind_definition(conn, # noqa: ANN001*,definition_id: str,- session_id: str,+ session_id: str | None,metadata: dict | None = None,+ enabled: int = 1,) -> None:"""A scheduled task pinned to ``session_id``, in the shape reclaim reads."""conn.execute(@@ -5912,7 +5913,7 @@ def _bind_definition(prompt="run the nightly check",schedule_type="cron",cron="0 3 * * *",- enabled=1,+ enabled=enabled,created_at="2026-07-28T00:00:00Z",updated_at="2026-07-28T00:00:00Z",metadata_json=json.dumps(metadata or {"origin": "cli"}),@@ -5920,14 +5921,18 @@ def _bind_definition()-#: The decision read of ``reclaim_bound_definitions``: every live definition bound to-#: the session going away. Everything the loop then writes -- pause / soft-delete, the-#: settings snapshot, the summary counters and the teardown ledger -- is decided from-#: this one row set.+#: The decision read of ``reclaim_bound_definitions``: every live definition that+#: either belongs to the session or targets it for execution. Everything the loop then+#: writes -- pause / soft-delete, the settings snapshot, the summary counters and the+#: teardown ledger -- is decided from this one row set._RECLAIM_DECISION_SELECT = ("SELECT run_definitions.id, run_definitions.definition_type, run_definitions.enabled, "- "run_definitions.metadata_json FROM run_definitions WHERE run_definitions.session_id = ? "- "AND run_definitions.deleted_at IS NULL"+ "run_definitions.session_id, run_definitions.metadata_json FROM run_definitions WHERE ("+ "run_definitions.definition_type = ? AND run_definitions.session_id = ? OR "+ "run_definitions.definition_type = ? AND (CASE WHEN (json_valid(run_definitions.metadata_json) = ?) "+ "THEN CASE WHEN (json_type(run_definitions.metadata_json, ?) = ?) THEN "+ "nullif(trim(json_extract(run_definitions.metadata_json, ?), ?), ?) END END = ? OR "+ "run_definitions.session_id = ?)) AND run_definitions.deleted_at IS NULL")@@ -6543,6 +6548,16 @@ def test_new_teardown_keeps_a_session_superseded_inside_its_window(tmp_path: Patworkdir=str(tmp_path),)_bind_definition(conn, definition_id="def-pinned", session_id=superseded_id)+ _bind_definition(+ conn,+ definition_id="def-owner-only",+ session_id=None,+ enabled=0,+ metadata={+ "created_by": {"caller": {"session_id": superseded_id}},+ "origin": "cli",+ },+ )def _winner_supersedes(other_conn) -> None: # noqa: ANN001other_conn.execute(@@ -6583,6 +6598,24 @@ def test_new_teardown_keeps_a_session_superseded_inside_its_window(tmp_path: Pat.mappings().first())+ owner_only = (+ conn.execute(select(run_definitions).where(run_definitions.c.id == "def-owner-only"))+ .mappings()+ .one()+ )+ from storage.background import SQLiteBackgroundTaskStore, task_resume_block++ metadata = json.loads(owner_only["metadata_json"])+ assert task_resume_block(metadata, owner_only["session_id"]) is None+ task_store = SQLiteBackgroundTaskStore(db_path)+ try:+ assert task_store.set_definition_enabled(+ "def-owner-only",+ True,+ definition_type="scheduled",+ )+ finally:+ task_store.close()finally:service.close()@@ -6611,6 +6644,13 @@ def test_new_teardown_keeps_a_session_superseded_inside_its_window(tmp_path: Pat)+_DEFINITION_RESUME_SELECT = (+ "SELECT run_definitions.definition_type, run_definitions.mode, run_definitions.enabled, "+ "run_definitions.session_id, run_definitions.metadata_json FROM run_definitions "+ "WHERE run_definitions.id = ? AND run_definitions.deleted_at IS NULL"+)++# --- Meta-guard: every writer of the session ROUTE must stay marker-aware ---## Deliberately NOT catalogued as a product scenario: it asserts nothing a user can@@ -6975,6 +7015,72 @@ def _refuse_a_competing_writer_at(engine, db_path: Path, *, read: str, write) ->return state+def test_direct_task_resume_reserves_write_lock_before_resumability_read(tmp_path: Path) -> None:+ """A Harness resume cannot overtake an orphan marker from Session teardown."""++ from storage.background import SQLiteBackgroundTaskStore++ db_path = tmp_path / "vibe.sqlite"+ service = SQLiteSessionsService(db_path)+ try:+ with service.engine.begin() as conn:+ _bind_definition(+ conn,+ definition_id="def-resume-race",+ session_id=None,+ enabled=0,+ metadata={+ "created_by": {"caller": {"session_id": "ses-owner"}},+ "origin": "cli",+ },+ )+ finally:+ service.close()++ store = SQLiteBackgroundTaskStore(db_path)+ try:+ def _stamp_orphan_marker(other_conn) -> None: # noqa: ANN001+ other_conn.execute(+ run_definitions.update()+ .where(run_definitions.c.id == "def-resume-race")+ .values(+ enabled=0,+ metadata_json=json.dumps(+ {+ "created_by": {"caller": {"session_id": "ses-owner"}},+ "origin": "cli",+ "orphaned_task_owner": {+ "reason_code": "task_owner_session_unavailable",+ "owner_session_id": "ses-owner",+ },+ }+ ),+ updated_at="2026-08-11T00:00:01Z",+ )+ )++ race = _refuse_a_competing_writer_at(+ store.engine,+ db_path,+ read=_DEFINITION_RESUME_SELECT,+ write=_stamp_orphan_marker,+ )++ assert store.set_definition_enabled(+ "def-resume-race",+ True,+ definition_type="scheduled",+ )+ saved = store.get_scheduled_task("def-resume-race")+ finally:+ store.close()++ assert race["fired"] == 1, "the test did not observe the resumability decision read"+ assert race["committed"] == 0, "Session teardown wrote inside the resume window"+ assert race["refused"], "the resume path did not hold SQLite's writer slot"+ assert saved is not None and saved["enabled"] is True++def _record_statements(engine) -> list[str]:"""Collect the normalised SQL the engine emits, in order."""diff --git a/tests/test_sqlite_state_migration.py b/tests/test_sqlite_state_migration.pyindex 7cda5dfb1..9f9002060 100644--- a/tests/test_sqlite_state_migration.py+++ b/tests/test_sqlite_state_migration.py@@ -31,7 +31,7 @@ from vibe.message_types import build_partial_index_predicatepytestmark = pytest.mark.no_sqlite_template-HEAD_REVISION = "20260811_0051"+HEAD_REVISION = "20260811_0052"MESSAGE_PARTIAL_INDEX_PREDICATES = {"ix_messages_inbox_activity": ("session_id is not null and type in "@@ -1967,6 +1967,122 @@ def test_retirement_marker_migration_is_forward_only(tmp_path: Path) -> None:assert version == (HEAD_REVISION,)+def test_orphaned_owner_task_migration_marks_unbound_definitions(tmp_path: Path) -> None:+ """0052 blocks every resumable orphan and stops the ones still enabled."""+ db_path = tmp_path / "vibe.sqlite"+ run_migrations(db_path, revision="20260811_0051")++ with sqlite3.connect(db_path) as conn:+ _insert_scope(conn, "sc1")+ for session_id, anchor in (+ ("ses-live-owner", "live-owner"),+ ("ses-target", "target"),+ ("ses-archived-owner", "archived-owner"),+ ):+ _insert_agent_session(+ conn,+ row_id=session_id,+ scope_id="sc1",+ anchor=anchor,+ workdir="/tmp",+ backend="codex",+ native=f"native-{session_id}",+ last_active="2026-08-11T00:00:00+00:00",+ )+ conn.execute(+ "update agent_sessions set status = 'archived' where id = 'ses-archived-owner'"+ )++ def insert_task(+ task_id: str,+ owner_session_id: str | None,+ *,+ session_id: str | None = None,+ session_policy: str | None = "create_per_run",+ enabled: int = 1,+ last_error: str | None = None,+ ) -> None:+ metadata = (+ json.dumps({"created_by": {"caller": {"session_id": owner_session_id}}})+ if owner_session_id is not None+ else "{}"+ )+ conn.execute(+ """+ insert into run_definitions (+ id, definition_type, name, session_policy, session_id, enabled,+ last_error, created_at, updated_at, metadata_json+ ) values (?, 'scheduled', ?, ?, ?, ?, ?, ?, ?, ?)+ """,+ (+ task_id,+ task_id,+ session_policy,+ session_id,+ enabled,+ last_error,+ "2026-08-11T00:00:00+00:00",+ "2026-08-11T00:00:00+00:00",+ metadata,+ ),+ )++ insert_task("missing-owner", "ses-removed-owner")+ insert_task("pure-command", "ses-removed-owner", session_policy=None)+ insert_task("blank-target", "ses-removed-owner", session_id=" ")+ insert_task("whitespace-target", "ses-removed-owner", session_id="\t\n\r")+ insert_task("archived-owner", "ses-archived-owner")+ insert_task("live-owner", "ses-live-owner")+ insert_task("target-fallback", "ses-removed-owner", session_id="ses-target")+ insert_task("legacy-unowned", None)+ insert_task(+ "already-paused",+ "ses-removed-owner",+ enabled=0,+ last_error="manual pause",+ )+ conn.commit()++ run_migrations(db_path)++ with sqlite3.connect(db_path) as conn:+ rows = {+ row[0]: row[1:]+ for row in conn.execute(+ "select id, enabled, session_id, last_error, metadata_json from run_definitions"+ )+ }++ def owner_marker(task_id: str) -> dict | None:+ metadata = json.loads(rows[task_id][3])+ return metadata.get("orphaned_task_owner")++ expected_paused = {+ "missing-owner": (None, "ses-removed-owner"),+ "pure-command": (None, "ses-removed-owner"),+ "blank-target": (" ", "ses-removed-owner"),+ "whitespace-target": ("\t\n\r", "ses-removed-owner"),+ "archived-owner": (None, "ses-archived-owner"),+ }+ for task_id, (session_id, owner_session_id) in expected_paused.items():+ assert rows[task_id][:3] == (0, session_id, None)+ assert owner_marker(task_id) == {+ "reason_code": "task_owner_session_unavailable",+ "owner_session_id": owner_session_id,+ }++ assert rows["live-owner"][:3] == (1, None, None)+ assert rows["target-fallback"][:3] == (1, "ses-target", None)+ assert rows["legacy-unowned"][:3] == (1, None, None)+ assert rows["already-paused"][:3] == (0, None, "manual pause")+ assert owner_marker("already-paused") == {+ "reason_code": "task_owner_session_unavailable",+ "owner_session_id": "ses-removed-owner",+ }+ for task_id in ("live-owner", "target-fallback", "legacy-unowned"):+ assert owner_marker(task_id) is None++def test_show_annotation_migration_changes_only_the_user_send_index(tmp_path: Path,) -> None:diff --git a/tests/test_ui_server_fastapi.py b/tests/test_ui_server_fastapi.pyindex 34dd7bb20..660966223 100644--- a/tests/test_ui_server_fastapi.py+++ b/tests/test_ui_server_fastapi.py@@ -1245,6 +1245,65 @@ def test_harness_routes_page_filter_and_return_counts(monkeypatch, tmp_path):assert counts["runs"]["all"] == 4+def test_harness_task_resume_rejects_orphaned_owner_without_target(+ monkeypatch, tmp_path+):+ from storage.background import SQLiteBackgroundTaskStore++ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ ensure_sqlite_state()+ store = SQLiteBackgroundTaskStore()+ try:+ store.upsert_scheduled_task(+ {+ "id": "orphaned-task",+ "name": "Orphaned task",+ "prompt": "run it",+ "schedule_type": "cron",+ "cron": "0 * * * *",+ "enabled": False,+ "created_at": "2026-08-11T00:00:00+00:00",+ "updated_at": "2026-08-11T00:00:00+00:00",+ "metadata": {+ "orphaned_task_owner": {+ "reason_code": "task_owner_session_unavailable",+ "owner_session_id": "ses-removed",+ }+ },+ }+ )+ finally:+ store.close()++ client = app.test_client()+ response = client.patch(+ "/api/harness/tasks/orphaned-task",+ json={"enabled": True},+ headers=csrf_headers(client),+ )++ assert response.status_code == 409+ body = response.get_json()+ assert body["code"] == "task_owner_session_unavailable"+ assert body["error"]["code"] == "task_owner_session_unavailable"+ assert "Create a replacement Task" in body["hint"]+ assert body["details"] == {+ "task_id": "orphaned-task",+ "owner_session_id": "ses-removed",+ }+ store = SQLiteBackgroundTaskStore()+ try:+ saved = store.get_scheduled_task("orphaned-task")+ finally:+ store.close()+ assert saved is not None+ assert saved["enabled"] is False+ assert saved["resume_blocked"] == {+ "code": "task_owner_session_unavailable",+ "owner_session_id": "ses-removed",+ }++def test_harness_bootstrap_returns_counts_and_selected_page(monkeypatch, tmp_path):from storage.background import SQLiteBackgroundTaskStorediff --git a/ui/src/components/workbench/HarnessPage.test.tsx b/ui/src/components/workbench/HarnessPage.test.tsxindex eaa2d7646..b94268176 100644--- a/ui/src/components/workbench/HarnessPage.test.tsx+++ b/ui/src/components/workbench/HarnessPage.test.tsx@@ -541,6 +541,23 @@ describe('TaskDetail command task', () => {expect(html).not.toContain('/chat/');});+ it('localizes an orphan-owner pause reason stored as a machine code', () => {+ const html = detail(+ task({+ enabled: false,+ lifecycle_state: 'paused',+ resume_blocked: {+ code: 'task_owner_session_unavailable',+ owner_session_id: 'ses-removed',+ },+ }),+ );++ expect(html).toContain(`>${i18n.t('harness.detail.pauseReason')}<`);+ expect(html).toContain(i18n.t('harness.taskPauseReason.ownerSessionUnavailable'));+ expect(html).not.toContain('task_owner_session_unavailable');+ });+it('drops the Agent routing a pure command task deliberately has none of', () => {// SCT-043. The label helpers resolve a null to a concrete answer, so a// command created with the CLI's default ``--on-failure none`` — no Agent,diff --git a/ui/src/components/workbench/HarnessPage.tsx b/ui/src/components/workbench/HarnessPage.tsxindex d064421ce..452e54847 100644--- a/ui/src/components/workbench/HarnessPage.tsx+++ b/ui/src/components/workbench/HarnessPage.tsx@@ -1474,6 +1474,13 @@ export const TaskDetail: React.FC<TaskDetailProps> = ({ task, agent, onToggleEna</pre></DetailField>)}+ {task.resume_blocked?.code === 'task_owner_session_unavailable' && (+ <DetailField label={t('harness.detail.pauseReason')}>+ <span className="text-[12px] text-muted">+ {t('harness.taskPauseReason.ownerSessionUnavailable')}+ </span>+ </DetailField>+ )}<DetailField label={t('harness.detail.id')}><code className="font-mono text-[11px] text-muted">{task.id}</code></DetailField>diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsxindex c7fa7d5af..1b7520796 100644--- a/ui/src/context/ApiContext.tsx+++ b/ui/src/context/ApiContext.tsx@@ -1369,6 +1369,10 @@ export type HarnessTask = HarnessSessionSummary & HarnessDefinitionState & {last_run_at: string | null;last_run_id: string | null;last_error: string | null;+ resume_blocked?: {+ code: string;+ owner_session_id: string;+ } | null;// Command tasks: a scheduled definition that runs a subprocess instead of// prompting an Agent. Non-null ``shell_command`` OR a non-empty ``command``// argv is what makes a row one (see ``taskIsCommand``); its ``prompt`` isdiff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex 6eacee0f0..f4b7f7365 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -1245,6 +1245,7 @@"retry": "Retry"},"errors": {+ "task_owner_session_unavailable": "This Task's managing Session is no longer available. Create a replacement Task from an available Agent Session.","share_id_taken": "That custom link is already taken. Pick another.","invalid_share_id": "A custom link may use only 3–64 letters, numbers, dash, or underscore, starting and ending with a letter or number.","missing_share_id": "Enter a custom link first.",@@ -2955,6 +2956,7 @@"runtime": "Runtime","eventProcessing": "Event processing","lastError": "Last error",+ "pauseReason": "Pause reason","type": "Type","triggeredBy": "Triggered by","result": "Result",@@ -2987,6 +2989,9 @@"taskKind": {"command": "Command"},+ "taskPauseReason": {+ "ownerSessionUnavailable": "The Session that managed this Task is no longer available. Create a replacement Task from an available Agent Session."+ },"onFailure": {"none": "Notice only (no Agent)","agent": "Escalate to an Agent"diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex 3f9c68789..933d4b4e3 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -1245,6 +1245,7 @@"retry": "重试"},"errors": {+ "task_owner_session_unavailable": "这个 Task 的管理 Session 已不可用。请从可用的 Agent Session 创建替代 Task。","share_id_taken": "这个自定义链接已被占用,换一个。","invalid_share_id": "自定义链接只能用 3–64 位字母、数字、短横线或下划线,且首尾为字母或数字。","missing_share_id": "请先输入自定义链接。",@@ -2955,6 +2956,7 @@"runtime": "运行时","eventProcessing": "事件处理","lastError": "上次错误",+ "pauseReason": "暂停原因","type": "类型","triggeredBy": "触发来源","result": "结果",@@ -2987,6 +2989,9 @@"taskKind": {"command": "命令"},+ "taskPauseReason": {+ "ownerSessionUnavailable": "管理这个 Task 的 Session 已不可用。请从可用的 Agent Session 创建替代 Task。"+ },"onFailure": {"none": "仅通知(无 Agent)","agent": "升级给 Agent 处理"diff --git a/vibe/cli.py b/vibe/cli.pyindex 2008f9cb8..caae065f7 100644--- a/vibe/cli.py+++ b/vibe/cli.py@@ -76,6 +76,7 @@ from storage.db import create_sqlite_enginefrom storage.background import (DefinitionWriteConflict,SQLiteBackgroundTaskStore,+ TaskResumeBlocked,compute_next_run_at,normalize_run_status,)@@ -1981,6 +1982,7 @@ _DEFINITION_FAILURE_FIELDS = ("processing_recent_failures",# The one field that says WHY, dropped from the brief list payload before."last_error",+ "resume_blocked",)@@ -3685,6 +3687,21 @@ def cmd_task_set_enabled(task_id: str, enabled: bool):return 1try:updated = store.set_enabled(task_id, enabled)+ except TaskResumeBlocked as exc:+ lang = _memory_cli_language()+ _print_task_error(+ TaskCliError(+ i18n_t("error.taskOwnerUnavailable.message", lang),+ code=exc.code,+ hint=i18n_t("error.taskOwnerUnavailable.hint", lang, id=task_id),+ help_command=f"vibe task remove {task_id}",+ details={+ "task_id": task_id,+ "owner_session_id": exc.owner_session_id,+ },+ )+ )+ return 1except DefinitionWriteConflict as exc:# Pause/resume is also a full-row write, so it is refused when a teardown# changed the definition first. Reporting the switch as flipped would be a liediff --git a/vibe/i18n/en.json b/vibe/i18n/en.jsonindex ce14783a8..6807f6303 100644--- a/vibe/i18n/en.json+++ b/vibe/i18n/en.json@@ -226,6 +226,10 @@"message": "Agent `{agent}` is unavailable for this project.","hint": "Choose an enabled Agent and apply the project setting again."},+ "taskOwnerUnavailable": {+ "message": "This Task's managing Session is no longer available.",+ "hint": "Create a replacement Task from an available Agent Session, then remove this orphaned definition with `vibe task remove {id}`."+ },"sessionFork": {"agentUnavailable": {"message": "The source session's Agent is no longer available for a new fork.",diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.jsonindex 7cf9969d9..d27d465a0 100644--- a/vibe/i18n/zh.json+++ b/vibe/i18n/zh.json@@ -226,6 +226,10 @@"message": "Agent `{agent}` 无法用于此项目。","hint": "请选择一个已启用的 Agent 后重新保存项目设置。"},+ "taskOwnerUnavailable": {+ "message": "这个 Task 的管理 Session 已不可用。",+ "hint": "请从可用的 Agent Session 创建替代 Task,再用 `vibe task remove {id}` 删除这条失去管理者的定义。"+ },"sessionFork": {"agentUnavailable": {"message": "源会话的 Agent 已无法用于创建新的复刻会话。",diff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex d5ef9609f..015804bb9 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -4162,6 +4162,22 @@ def _project_agent_unavailable_response(exc):)+def _task_resume_blocked_response(exc):+ from core.services import settings as settings_service++ lang = settings_service.load_config_or_default().language+ return _coded_error_response(+ exc.code,+ t("error.taskOwnerUnavailable.message", lang),+ 409,+ hint=t("error.taskOwnerUnavailable.hint", lang, id=exc.definition_id),+ details={+ "task_id": exc.definition_id,+ "owner_session_id": exc.owner_session_id,+ },+ )++def _show_page_error_response(exc):code = getattr(exc, "code", "invalid_show_page_request")# A conflict (not a malformed request) when the page is in the wrong state or@@ -9190,10 +9206,15 @@ def harness_task_patch(task_id: str):if "enabled" not in payload:return jsonify({"ok": False, "code": "invalid_payload", "message": "missing 'enabled'"}), 400enabled = bool(payload["enabled"])+ from storage.background import TaskResumeBlocked+with _harness_store() as store:if not store.get_scheduled_task(task_id):return jsonify({"ok": False, "code": "task_not_found"}), 404- store.set_definition_enabled(task_id, enabled, definition_type="scheduled")+ try:+ store.set_definition_enabled(task_id, enabled, definition_type="scheduled")+ except TaskResumeBlocked as exc:+ return _task_resume_blocked_response(exc)task = store.get_scheduled_task(task_id)from core.inbox_events import publish_definitions_updated