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(harness): keep a delegated run's Watch in the dispatcher's background bar (#2824)

Call White3b83a6492e04
diff --git a/docs/plans/unified-background-work-banner.md b/docs/plans/unified-background-work-banner.md
index 2943b13f3..4a707c18d 100644
--- a/docs/plans/unified-background-work-banner.md
+++ b/docs/plans/unified-background-work-banner.md
@@ -28,6 +28,12 @@ The banner's source of truth is a **union assembled at runtime-state build time*
presented as queued even when its executor Run has already moved to `running`. Accepted
Deliveries that share one target Turn project as one running item, represented by the
Delivery with the greatest `turn_position`; queued Deliveries remain separate items.
+ - enabled, live watches that such a delegated run created in its target session
+ (creation provenance `metadata_json.created_by.caller.run_id`), whether or not the run
+ has finished: a worker that answers and leaves a Watch on review or CI is still doing the
+ work this session dispatched. These rows carry the worker's session, so their navigation
+ filters the Harness by it. Live definitions are read through the partial index
+ `ix_run_definitions_live` (migration 0070), because a removed definition keeps `enabled`.
Each unified item carries: `kind` (`backend_activity` | `watch` | `task` | `agent_run`),
`label` (watch name / task summary / target agent + short message head / activity description),
diff --git a/storage/alembic/versions/20261018_0070_run_definitions_live_index.py b/storage/alembic/versions/20261018_0070_run_definitions_live_index.py
new file mode 100644
index 000000000..a778d1615
--- /dev/null
+++ b/storage/alembic/versions/20261018_0070_run_definitions_live_index.py
@@ -0,0 +1,62 @@
+"""index the live definitions of each type
+
+The background-work banner reads a session's Watches left running by the work it
+dispatched: enabled Watches not soft-deleted, joined to their creator Run. A
+removed definition keeps ``enabled = 1`` beside its ``deleted_at``, so
+``ix_run_definitions_type_enabled`` walks every Watch ever removed::
+
+ SEARCH run_definitions USING INDEX ix_run_definitions_type_enabled (definition_type=? AND enabled=?)
+
+That grows with definition history, not with live work. A partial index over the
+rows not deleted makes the same seek touch only live definitions:
+``SEARCH run_definitions USING INDEX ix_run_definitions_live (definition_type=? AND enabled=?)``.
+
+Index only: downgrade drops it, and an older build reads the same rows without
+it.
+
+Revision ID: 20261018_0070
+Revises: 20261016_0069
+Create Date: 2026-10-18
+"""
+
+from __future__ import annotations
+
+from alembic import op
+
+revision = "20261018_0070"
+down_revision = "20261016_0069"
+branch_labels = None
+depends_on = None
+MIGRATION_SAFETY = "additive"
+
+_INDEX = "ix_run_definitions_live"
+# Exported so the head-schema repair path in ``storage/migrations.py`` executes THIS
+# statement rather than a retyped copy: SQLite matches a partial index's predicate
+# against a query's by text.
+DROP_INDEX_SQL = f"drop index if exists {_INDEX}"
+CREATE_INDEX_SQL = (
+ f"create index {_INDEX} on run_definitions (definition_type, enabled) "
+ "where deleted_at is null"
+)
+
+
+def _tables(bind) -> set[str]:
+ return {
+ str(row[0])
+ for row in bind.exec_driver_sql("select name from sqlite_master where type = 'table'")
+ }
+
+
+def upgrade() -> None:
+ bind = op.get_bind()
+ if "run_definitions" not in _tables(bind):
+ return
+ bind.exec_driver_sql(DROP_INDEX_SQL)
+ bind.exec_driver_sql(CREATE_INDEX_SQL)
+
+
+def downgrade() -> None:
+ bind = op.get_bind()
+ if "run_definitions" not in _tables(bind):
+ return
+ bind.exec_driver_sql(DROP_INDEX_SQL)
diff --git a/storage/migrations.py b/storage/migrations.py
index b21cf3464..2194c6cf5 100644
--- a/storage/migrations.py
+++ b/storage/migrations.py
@@ -810,6 +810,14 @@ def _ensure_new_background_indexes(conn: sqlite3.Connection) -> None:
conn.execute('create index if not exists ix_agent_runs_agent_created on agent_runs (agent_name, created_at)')
conn.execute('create index if not exists ix_agent_runs_callback_status on agent_runs (callback_status, completed_at)')
conn.execute('create index if not exists ix_agent_runs_updated on agent_runs (updated_at)')
+ live_index = import_module("storage.alembic.versions.20261018_0070_run_definitions_live_index")
+ live_row = conn.execute(
+ "select sql from sqlite_master where type = 'index' and name = ?",
+ (live_index._INDEX,),
+ ).fetchone()
+ if live_row is None or _normalized_index_sql(live_row[0]) != _normalized_index_sql(live_index.CREATE_INDEX_SQL):
+ conn.execute(live_index.DROP_INDEX_SQL)
+ conn.execute(live_index.CREATE_INDEX_SQL)
if not _agent_runs_managed_indexes_ready(conn):
_ensure_agent_runs_managed_indexes(conn)
diff --git a/storage/models.py b/storage/models.py
index 1fa242e7f..9749a23f6 100644
--- a/storage/models.py
+++ b/storage/models.py
@@ -306,6 +306,13 @@ run_definitions = Table(
Column("last_run_id", String, nullable=True),
Column("metadata_json", Text, nullable=False),
Index("ix_run_definitions_type_enabled", "definition_type", "enabled"),
+ # Live definitions only (migration 0070): a removed one keeps ``enabled``.
+ Index(
+ "ix_run_definitions_live",
+ "definition_type",
+ "enabled",
+ sqlite_where=text("deleted_at is null"),
+ ),
Index("ix_run_definitions_session", "session_id"),
Index("ix_run_definitions_agent", "agent_name"),
Index("ix_run_definitions_updated", "updated_at"),
diff --git a/storage/workbench_sessions_service.py b/storage/workbench_sessions_service.py
index 70a689c6d..31e646881 100644
--- a/storage/workbench_sessions_service.py
+++ b/storage/workbench_sessions_service.py
@@ -20,7 +20,7 @@ from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Mapping, Optional
-from sqlalchemy import Integer, and_, cast, func, or_, select, update
+from sqlalchemy import Integer, and_, case, cast, func, or_, select, update
from sqlalchemy.dialects.sqlite import insert as sqlite_insert
from sqlalchemy.engine import Connection
@@ -1593,7 +1593,10 @@ def derive_session_harness_activities(conn: Connection, session_id: str) -> list
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 this
- session dispatched and is waiting on).
+ session dispatched and is waiting on);
+ - enabled, live watches such a delegated run created in its target session
+ (creation provenance ``metadata_json.created_by.caller.run_id``), whether or
+ not the run has finished: the work it dispatched goes on in them.
Each row is shaped like a serialized background activity plus the unified
banner fields (see ``_harness_banner_item``).
@@ -1672,6 +1675,57 @@ def derive_session_harness_activities(conn: Connection, session_id: str) -> list
)
)
+ # Watches left by work this session dispatched. A delegated run whose result
+ # returns here may answer and finish while a Watch it created in its target
+ # session keeps that work going (review, CI); the work is not done, so its
+ # Watches stay here too, routed to the session they run in. A Watch of this
+ # session is already listed above. Live definitions are reached through
+ # ``ix_run_definitions_live`` and each creator Run by its primary key, so the
+ # read is bounded by live Watches, not by definition or run history.
+ metadata_json = run_definitions.c.metadata_json
+ creator_run_id = case(
+ (func.json_valid(metadata_json) == 1, func.json_extract(metadata_json, "$.created_by.caller.run_id")),
+ )
+ delegated_watch_rows = (
+ conn.execute(
+ select(
+ run_definitions.c.id,
+ run_definitions.c.name,
+ run_definitions.c.session_id,
+ run_definitions.c.created_at,
+ run_definitions.c.updated_at,
+ agent_runs.c.agent_name,
+ agent_runs.c.agent_backend,
+ )
+ .select_from(run_definitions.join(agent_runs, agent_runs.c.id == creator_run_id))
+ .where(run_definitions.c.definition_type == "watch")
+ .where(run_definitions.c.enabled == 1)
+ .where(run_definitions.c.deleted_at.is_(None))
+ .where(run_definitions.c.session_id != session_id)
+ .where(agent_runs.c.run_type == "agent_run")
+ .where(agent_runs.c.callback_session_id == session_id)
+ .order_by(run_definitions.c.created_at, run_definitions.c.id)
+ )
+ .mappings()
+ .all()
+ )
+ for row in delegated_watch_rows:
+ name = _banner_label(row["name"])
+ agent_name = str(row["agent_name"] or "").strip()
+ since = str(row["created_at"] or "")
+ items.append(
+ _harness_banner_item(
+ item_id=f"watch:{row['id']}",
+ item_kind="watch",
+ session_id=str(row["session_id"]),
+ status="enabled",
+ label=_banner_label(f"{agent_name}: {name}") if agent_name and name else agent_name or name,
+ since=since,
+ updated_at=str(row["updated_at"] or since),
+ backend=str(row["agent_backend"] or ""),
+ )
+ )
+
# Delegated agent runs this session dispatched and is waiting on: the run
# executes elsewhere but its result returns here (``callback_session_id``)
# and it is not yet terminal. ``run_type='agent_run'`` excludes task/watch
diff --git a/tests/test_agent_context_seq_migration.py b/tests/test_agent_context_seq_migration.py
index a669ee513..590e631f1 100644
--- a/tests/test_agent_context_seq_migration.py
+++ b/tests/test_agent_context_seq_migration.py
@@ -56,7 +56,7 @@ def test_context_seq_upgrade_and_downgrade_keep_released_rows(tmp_path):
migrations.run_migrations(path)
with sqlite3.connect(path) as conn:
- assert conn.execute("SELECT version_num FROM alembic_version").fetchone() == ("20261016_0069",)
+ assert conn.execute("SELECT version_num FROM alembic_version").fetchone() == ("20261018_0070",)
assert_released_rows_unchanged(conn)
assert _index_sql(conn, "ix_agent_events_turn_sequence_id") is not None
for table, (first, same_session, other_session) in _IDS.items():
diff --git a/tests/test_background_work_banner.py b/tests/test_background_work_banner.py
index 900c6989a..42fa6e5b6 100644
--- a/tests/test_background_work_banner.py
+++ b/tests/test_background_work_banner.py
@@ -757,6 +757,89 @@ def test_sync_run_without_pending_callback_is_excluded(tmp_path: Path):
assert items == []
+def test_a_watch_a_delegated_run_left_stays_after_the_run_answers(tmp_path: Path):
+ # The PM dispatched a worker; the worker answered ("the Watch will continue")
+ # and left a forever Watch on review and CI in its own session. The run is
+ # finished, but the work it dispatched is not, so the PM still sees it, routed
+ # to the worker's session (where the Harness filter finds it).
+ engine, _ = _make_engine(tmp_path)
+ _insert_run(
+ engine,
+ id="run-worker",
+ agent_name="claude",
+ status="succeeded",
+ callback_status="sent",
+ session_id="ses-worker",
+ callback_session_id="ses-pm",
+ )
+ created_by = {"created_by": {"kind": "caller_context", "caller": {"session_id": "ses-worker", "run_id": "run-worker"}}}
+ _insert_definition(
+ engine,
+ id="w-review",
+ definition_type="watch",
+ name="pr-2821 review",
+ session_id="ses-worker",
+ metadata_json=json.dumps(created_by),
+ )
+ # Not this session's work: a Watch the worker removed or paused, and one left
+ # by a run another session dispatched.
+ _insert_definition(engine, id="w-removed", definition_type="watch", session_id="ses-worker", deleted_at=_NOW, metadata_json=json.dumps(created_by))
+ _insert_definition(engine, id="w-paused", definition_type="watch", session_id="ses-worker", enabled=0, metadata_json=json.dumps(created_by))
+ _insert_run(engine, id="run-other", status="succeeded", session_id="ses-worker", callback_session_id="ses-other")
+ _insert_definition(
+ engine,
+ id="w-foreign",
+ definition_type="watch",
+ session_id="ses-worker",
+ metadata_json=json.dumps({"created_by": {"caller": {"session_id": "ses-worker", "run_id": "run-other"}}}),
+ )
+ _insert_definition(engine, id="w-unreadable", definition_type="watch", session_id="ses-worker", metadata_json="not json")
+
+ with engine.connect() as conn:
+ items = derive_session_harness_activities(conn, "ses-pm")
+
+ assert [(item["id"], item["label"], item["session_id"], item["status"]) for item in items] == [
+ ("watch:w-review", "claude: pr-2821 review", "ses-worker", "enabled"),
+ ]
+
+
+def test_delegated_watches_are_read_through_live_definitions_only(tmp_path: Path):
+ # The banner is re-read on every runtime-state build. A removed Watch keeps
+ # ``enabled = 1``, so seeking (definition_type, enabled) alone walks every Watch
+ # ever removed; the read must touch live definitions and each creator Run by
+ # its key, never a scan of either growing table.
+ import sqlite3
+
+ from sqlalchemy import event
+
+ engine, db_path = _make_engine(tmp_path)
+ _insert_run(engine, id="run-worker", status="succeeded", session_id="ses-worker", callback_session_id="ses-pm")
+ for index in range(20):
+ _insert_definition(engine, id=f"w-removed-{index}", definition_type="watch", session_id="ses-worker", deleted_at=_NOW)
+ captured: list[tuple[str, object]] = []
+
+ def capture(conn, cursor, statement, parameters, context, executemany):
+ if "json_extract" in statement and "agent_runs" in statement:
+ captured.append((statement, parameters))
+
+ event.listen(engine, "before_cursor_execute", capture)
+ try:
+ with engine.connect() as conn:
+ derive_session_harness_activities(conn, "ses-pm")
+ finally:
+ event.remove(engine, "before_cursor_execute", capture)
+
+ [(statement, parameters)] = captured
+ raw = sqlite3.connect(str(db_path))
+ try:
+ plan = "\n".join(row[-1] for row in raw.execute("EXPLAIN QUERY PLAN " + statement, parameters))
+ finally:
+ raw.close()
+ assert "SEARCH run_definitions USING INDEX ix_run_definitions_live (definition_type=? AND enabled=?)" in plan, plan
+ assert "SEARCH agent_runs USING INDEX sqlite_autoindex_agent_runs_1 (id=?)" in plan, plan
+ assert "SCAN" not in plan.replace("USE TEMP B-TREE", ""), plan
+
+
def test_items_derive_from_db_so_banner_survives_restart(tmp_path: Path):
# The registry is process-local and empty after a restart; harness items must
# come from the durable store. Simulate a restart by disposing the engine and
diff --git a/tests/test_skill_observability_migration.py b/tests/test_skill_observability_migration.py
index 155f6b398..977281443 100644
--- a/tests/test_skill_observability_migration.py
+++ b/tests/test_skill_observability_migration.py
@@ -35,7 +35,7 @@ def test_skill_schema_upgrade_downgrade_preserves_existing_events(tmp_path):
migrations.run_migrations(path)
with sqlite3.connect(path) as conn:
assert conn.execute(f"SELECT {columns} FROM agent_events ORDER BY id").fetchall() == original
- assert conn.execute("SELECT version_num FROM alembic_version").fetchone() == ("20261016_0069",)
+ assert conn.execute("SELECT version_num FROM alembic_version").fetchone() == ("20261018_0070",)
assert conn.execute("SELECT count(*) FROM skill_usage_daily").fetchone() == (0,)
assert {row[2] for row in conn.execute("PRAGMA foreign_key_list(skill_usage_daily)")} == {
"scopes",
diff --git a/tests/test_sqlite_state_migration.py b/tests/test_sqlite_state_migration.py
index ca9c18765..db4441193 100644
--- a/tests/test_sqlite_state_migration.py
+++ b/tests/test_sqlite_state_migration.py
@@ -38,7 +38,7 @@ from vibe.message_types import build_partial_index_predicate
pytestmark = pytest.mark.no_sqlite_template
-HEAD_REVISION = "20261016_0069"
+HEAD_REVISION = "20261018_0070"
PREVIOUS_HEAD_REVISION = "20261016_0068"
_SCOPE_ID_DRIFT_TABLES = ("messages", "agent_events", "media_objects")
# ``storage.models`` builds a bare ``MetaData()``, so its foreign keys are unnamed and
@@ -3770,7 +3770,8 @@ def test_scope_id_nullability_repair_is_noop_on_correct_schema(
"pragma schema_version"
).fetchone()[0]
- run_migrations(db_path)
+ # Only 0069 itself: a later revision may change the schema on purpose.
+ run_migrations(db_path, revision="20261016_0069")
with sqlite3.connect(db_path) as conn:
after = conn.execute(
@@ -3786,7 +3787,7 @@ def test_scope_id_nullability_repair_is_noop_on_correct_schema(
assert after == before
assert after_schema_version == before_schema_version
- assert version == (HEAD_REVISION,)
+ assert version == ("20261016_0069",)
def test_scope_id_nullability_repair_replays_after_head_shape_stamp(
@@ -4002,6 +4003,7 @@ def test_run_migrations_repairs_head_indexes_before_stamping_head(tmp_path: Path
conn.execute("drop index if exists ix_message_deliveries_message")
conn.execute("drop index if exists ix_agent_sessions_scope_status_activity")
conn.execute("drop index if exists ix_agent_sessions_agent_status")
+ conn.execute("drop index if exists ix_run_definitions_live")
conn.execute("drop index if exists ix_messages_session_created_id")
conn.execute("drop index if exists ix_messages_session_type_created_id")
conn.execute("drop index if exists ix_messages_platform_session_created_id")
@@ -4020,6 +4022,7 @@ def test_run_migrations_repairs_head_indexes_before_stamping_head(tmp_path: Path
assert "context_seq is null" in _index_sql(conn, "ix_messages_vibey_recovery_input")
assert "message_id is not null" in _index_sql(conn, "ix_message_deliveries_message")
assert "(agent_status, status)" in _index_sql(conn, "ix_agent_sessions_agent_status")
+ assert "deleted_at is null" in _index_sql(conn, "ix_run_definitions_live")
run_migrations(db_path)
diff --git a/tests/test_web_push_provider_invalidation_migration.py b/tests/test_web_push_provider_invalidation_migration.py
index 2f60a6ce3..f9bd43523 100644
--- a/tests/test_web_push_provider_invalidation_migration.py
+++ b/tests/test_web_push_provider_invalidation_migration.py
@@ -69,7 +69,7 @@ def test_upgrade_keeps_legacy_disabled_failure_opted_out(tmp_path):
web_push_service.mark_send_failure(conn, endpoint=enabled["endpoint"], disable=True)
with sqlite3.connect(path) as conn:
assert conn.execute("select version_num from alembic_version").fetchone() == (
- "20261016_0069",
+ "20261018_0070",
)
command.downgrade(migrations.alembic_config(path), "20260907_0061")
diff --git a/ui/src/lib/backgroundActivity.test.ts b/ui/src/lib/backgroundActivity.test.ts
index 1fe2eb8e1..52dfd9481 100644
--- a/ui/src/lib/backgroundActivity.test.ts
+++ b/ui/src/lib/backgroundActivity.test.ts
@@ -175,6 +175,12 @@ describe('harnessNavPath', () => {
);
});
+ it("filters a Watch a delegated run left by the session it runs in", () => {
+ expect(harnessNavPath({ id: 'watch:w2', item_kind: 'watch', session_id: 'ses-worker' }, 'ses-pm')).toBe(
+ '/harness?tab=watches&session=ses-worker',
+ );
+ });
+
it('anchors a delegated run by id (no session filter — it runs elsewhere)', () => {
expect(harnessNavPath({ id: 'agent_run:r1', item_kind: 'agent_run' }, 'ses-1')).toBe(
'/harness?tab=runs&run=r1',
diff --git a/ui/src/lib/backgroundActivity.ts b/ui/src/lib/backgroundActivity.ts
index e9d7967a3..bef04ca51 100644
--- a/ui/src/lib/backgroundActivity.ts
+++ b/ui/src/lib/backgroundActivity.ts
@@ -92,20 +92,22 @@ export function sortBackgroundActivities(items: SessionActivityState[]): Session
}
// Where a harness banner row navigates (spec req 4). Watch/task rows open the
-// matching Harness tab filtered to the originating session (route param, shown
-// as a removable chip). A delegated run executes in another session, so it can't
+// matching Harness tab filtered to the row's own session (route param, shown as a
+// removable chip): the viewing session, or for a Watch a delegated run left, the
+// session that run went to. A delegated run executes in another session, so it can't
// be session-filtered — it opens the runs tab anchored to that run instead.
// Backend activities never navigate (guarded by the caller); they fall back to
// the bare Harness page.
export function harnessNavPath(
- item: Pick<SessionActivityState, 'id' | 'item_kind'>,
+ item: Pick<SessionActivityState, 'id' | 'item_kind'> & { session_id?: string | null },
sessionId: string | null | undefined,
): string {
const kind = activityItemKind(item);
const params = new URLSearchParams();
if (kind === 'watch' || kind === 'task') {
params.set('tab', kind === 'watch' ? 'watches' : 'tasks');
- if (sessionId) params.set('session', sessionId);
+ const filter = item.session_id || sessionId;
+ if (filter) params.set('session', filter);
} else if (kind === 'agent_run') {
params.set('tab', 'runs');
const runId = harnessItemNativeId(item);