mirror of
https://github.com/rennf93/roboco.git
synced 2026-08-03 07:23:24 +02:00
feat(tg): Mini App V4 — Today brief, native approvals, live data, bot tier, chat bridges (#576)
* feat(tg): P0 — dev mock bridge + Telegram-native foundations
Mini App V4 phase 0. The (tg) shell gains the groundwork every later
phase builds on:
- Dev mock bridge: outside Telegram, a development build falls back to a
no-op WebApp object and skips the webapp-auth POST (the regular panel
session cookie authorizes API calls), so the cockpit is workable in a
plain browser. Production keeps the "Open from Telegram" wall.
- Telegram theme adoption: themeParams map onto the shadcn CSS variables
scoped to #tg-shell (desktop dashboard untouched), colorScheme drives
the dark class, themeChanged re-applies live. Non-hex values are
dropped at the trust boundary.
- Viewport/swipe correctness: shell height rides Telegram's own
--tg-viewport-stable-height (100dvh fallback), vertical swipe-to-close
disabled so list scrolling can't dismiss the app.
- Native chrome bindings: TgWebAppProvider context plus useMainButton /
useBackButton declarative hooks and a null-safe haptics helper —
consumers never touch window.Telegram directly.
* feat(tg): P1 — Today home tab + one-round-trip /telegram/today brief
Mini App V4 phase 1: the cockpit now opens on a "Today" brief answering
"does anything need me?" in one glance.
Backend: GET /api/telegram/today (CEO-gated, rate-limited) returns the
whole brief in one round trip via the new TgCockpitService — needs-you
items (awaiting-CEO + blocked tasks capped for a phone screen, held-draft
counts across release/X/video/roadmap queues), a fleet snapshot with
per-agent current-task titles, today's spend from the day rollup
(degrading to zeros on a usage hiccup, mirroring the CEO overview), and
ship state. Deliberately DB-only: no live GitHub calls, no readiness
snapshot (that path clones), no orchestrator singleton — the CI
red/green proxy is the set of open ci_watch fix tasks.
Panel: TgTodayTab is the new default tab (Gauge icon) — needs-you rows
and draft chips deep-link into the tab that acts on them (with a haptic
tap), fleet/spend/ship render as dense cards, 45s refetch until the P3
WebSocket wiring lands.
* fix(tg): dev mock engages when the CDN bridge loads outside Telegram
Live browser smoke caught it: a bare tab still loads telegram-web-app.js,
so window.Telegram.WebApp EXISTS outside Telegram — just with empty
initData. The dev fallback keyed on a null bridge only, so a dev browser
went down the real-auth path and posted empty initData instead of
mounting the mock. The fallback now treats bridge-with-no-initData the
same as no bridge (a real Telegram launch always carries initData);
production behavior is unchanged.
* feat(tg): P2 — native approvals card stack
Mini App V4 phase 2: the Approvals tab stops stacking the four desktop
queue cards and becomes a phone-native flow — one normalized list across
release proposal / X drafts / video drafts / proposed roadmap items, and
a full-context detail per item:
- Release: version/bump/gate badges, changelog draft, gaps, migration
notes, in-flight + failed-execute banners; approve runs the fail-closed
executor, reject requires a substantive change request (10 chars).
- X: editable body with the live 280 counter, replied-to mention quoted;
approve sends the edited body only when actually edited.
- Video: cut-toggled player (blob-fetched through the authed client — a
bare <video src> would 401), per-platform caption edits with 280/2200
counters; approve sends only checked-in edits.
- Roadmap: the PO's full pitch (description, rationale, ACs); approve
materializes into the backlog per item.
The detail's primary action rides Telegram's native MainButton and back
navigation rides the BackButton, with visible fallbacks outside Telegram
(dev mock, old clients). Haptics fire on outcomes. An acted-on item
vanishes from the refetched queue, popping back to the list by
construction. A failed queue source is surfaced ("list may be
incomplete" / "couldn't load") instead of masquerading as an empty
queue — caught live in the browser smoke.
* feat(tg): dev demo mode — /tg?demo=1 renders canned cockpit data
Development-only: with the flag param present, the Today brief and the
four approval queues resolve typed fixtures (dynamically imported, so
production bundles never carry them) instead of hitting the backend —
the cockpit is fully browsable with zero stack running. Mutations still
go to the real API and fail loudly; it's a showroom, not a simulator.
* feat(tg): P3 — cockpit rides /ws/system live
Chat adopts the desktop A2A invalidate-on-frame idiom over the shared
ref-counted /ws/system socket: every a2a.message frame refreshes the
conversation list and the affected thread, missed-frame gaps are healed
by a reconnect refetch, and the 10s thread poll turns off entirely while
the socket is up (it remains the fallback). The Today brief refreshes on
each USAGE_SNAPSHOT push so the spend line tracks the sweeper live, with
the 45s poll as the socket-down fallback. No new sockets, no backend
changes — the WS gate already accepts the cloud-auth session cookie.
* feat(tg): P4 — deterministic bot command tier + self-syncing menu
Mini App V4 phase 4 (deterministic half): three new bot commands beside
/status /queue /task —
- /agents: who's mid-task right now, from the same TgCockpitService
fleet snapshot the Today brief renders (now public `fleet()`).
- /usage: today's spend from the day rollup.
- /blocked: awaiting-you + blocked tasks, deep-linked into the panel,
capped per section, titles HTML-escaped.
BOT_COMMANDS is the single registry driving /help AND a once-per-process
Bot API setMyCommands sync on the first poll cycle (new client method,
best-effort), so the Telegram command menu can never drift from what the
code implements. The interactive tier (/secretary, /newtask riding a
live Intake interview in-thread) is specced but not in this commit.
* feat(tg): direction-C styling pass — Telegram palette, RoboCo voice
The cockpit stops wearing default-shadcn and gets its own visual
language on top of the P0 themeParams bridge (colors stay CSS-variable
driven, so inside Telegram everything still adopts the user's theme):
- Shared primitives (components/tg/ui.tsx): TgSection grouped cards with
tracked micro-label headers, TgRow list rows (44px targets, press
feedback, 1/2-line clamp), TgRowIcon glyph tiles, TgStat tabular-nums
figures. Every tab composes the same three, so density and rhythm are
identical across the surface.
- Shell renders a centered 430px column (sm:border-x) — the phone UI no
longer stretches across a desktop dev browser.
- Tab bar: tighter type, active stroke-weight shift, backdrop blur.
- Today: needs-you count badge, divided task rows with inline blocked
marker, fleet as mono-named rows, spend/ship as stat tiles.
- Approvals rows as icon-tile cards; detail header gains the kind glyph.
- Inbox/Chat rows aligned to the same card language.
* feat(tg): P5 — /secretary and /newtask live-chat bridges
The bot's interactive tier: both commands bridge the CEO's Telegram chat
into the same in-process runtimes the panel drives — the persistent
Secretary container and the scoped Intake interview.
There is no synchronous send→reply seam (replies land on the session's
single-consumer relay queue), so each bridged session runs one long-lived
consumer task (roboco/services/telegram_bridge.py) that drains
PrompterLiveRegistry.stream and pushes one Telegram message per completed
turn. While a session is live, plain chat text IS the conversation;
/end closes it.
/newtask resolves the intake scope (single project auto-picked, multiple
offered as a tap-to-pick keyboard holding the initial text), and the
interview happens in-thread. A draft proposal renders as a card with
Send-to-Board / Discard buttons: confirm routes through the normal
board-review path (PrompterService.confirm_live_draft, route=board) and
PARKS the session — board feedback later streams straight back into the
same thread, closing the redraft loop from the phone. MegaTask batches
still confirm in the panel only.
The consumer's open stream arms the registry's 60s keepalive, so the
bridge runs its own idle TTL (same setting, parked sessions exempt).
State is per-process in-memory by design (the _PENDING_REPLIES posture);
intake/secretary containers are process-wide singletons, so a bridged
session preempts a live panel session of the same kind by construction.
* feat(tg): cockpit skin — RoboCo dark deck with a constant amber accent
The cockpit no longer inherits the dashboard's white default outside
Telegram: #tg-shell carries its own standing skin (deep slate surfaces,
amber primary) so the Mini App looks like RoboCo everywhere. Inside
Telegram the themeParams bridge now overrides SURFACE tokens only —
background/card/text/hint/border repaint to the user's Telegram theme
while --primary/--ring stay RoboCo amber: Telegram's surfaces, RoboCo's
voice. Demo fixtures also rewritten to neutral content (they previously
depicted unbuilt forge work and already-shipped roadmap items as live).
---------
Co-authored-by: Renn F <rennf93@users.noreply.github.com>
This commit is contained in:
@@ -0,0 +1,304 @@
|
||||
"""Telegram ↔ live-chat bridge (P5): session lifecycle, free-text routing,
|
||||
the stream consumer's turn/draft forwarding, idle sweep, and the engine's
|
||||
/secretary /newtask /end + intake-callback wiring.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
from typing import Any
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
from roboco.services import telegram_bridge as bridge
|
||||
from roboco.services import telegram_inbound as ti
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _clean_state() -> Any:
|
||||
bridge._SESSIONS.clear()
|
||||
bridge._PENDING_NEWTASK.clear()
|
||||
yield
|
||||
bridge._SESSIONS.clear()
|
||||
bridge._PENDING_NEWTASK.clear()
|
||||
|
||||
|
||||
def _fake_session_db() -> MagicMock:
|
||||
session = MagicMock()
|
||||
session.commit = AsyncMock()
|
||||
session.execute = AsyncMock()
|
||||
return session
|
||||
|
||||
|
||||
def _engine() -> ti.TelegramInboundEngine:
|
||||
return ti.TelegramInboundEngine(_fake_session_db())
|
||||
|
||||
|
||||
CREDS = SimpleNamespace(bot_token="123:ABC", chat_id="777")
|
||||
|
||||
|
||||
class FakeRegistry:
|
||||
def __init__(self, events: list[dict[str, Any]] | None = None) -> None:
|
||||
self.events = events or []
|
||||
self.delivered: list[tuple[str, str]] = []
|
||||
self.parked: list[tuple[str, str]] = []
|
||||
|
||||
async def deliver(self, session_id: str, text: str) -> bool:
|
||||
self.delivered.append((session_id, text))
|
||||
return True
|
||||
|
||||
def park(self, session_id: str, task_id: str) -> bool:
|
||||
self.parked.append((session_id, task_id))
|
||||
return True
|
||||
|
||||
async def stream(self, _session_id: str):
|
||||
for event in self.events:
|
||||
yield event
|
||||
|
||||
|
||||
def _bridge_session(
|
||||
kind: str = "secretary", *, parked: bool = False
|
||||
) -> bridge.BridgeSession:
|
||||
sess = bridge.BridgeSession(kind=kind, session_id=uuid4().hex, client=AsyncMock())
|
||||
sess.parked = parked
|
||||
return sess
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# bridge module — lifecycle + routing
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_deliver_text_routes_only_bridged_chats(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
registry = FakeRegistry()
|
||||
monkeypatch.setattr(
|
||||
"roboco.services.prompter_live.get_live_registry", lambda: registry
|
||||
)
|
||||
|
||||
assert await bridge.deliver_text("777", "hello") is None
|
||||
|
||||
sess = _bridge_session()
|
||||
bridge._SESSIONS["777"] = sess
|
||||
assert await bridge.deliver_text("777", "hello") == ""
|
||||
assert registry.delivered == [(sess.session_id, "hello")]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_end_session_reaps_by_kind(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
orch = SimpleNamespace(
|
||||
reap_secretary_session=AsyncMock(), reap_intake_session=AsyncMock()
|
||||
)
|
||||
monkeypatch.setattr(bridge, "_orchestrator", lambda: orch)
|
||||
|
||||
sess = _bridge_session("intake")
|
||||
bridge._SESSIONS["777"] = sess
|
||||
assert await bridge.end_session("777") == "Ended."
|
||||
orch.reap_intake_session.assert_awaited_once_with(sess.session_id)
|
||||
assert "777" not in bridge._SESSIONS
|
||||
|
||||
assert await bridge.end_session("777") == "No active session."
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_sweep_idle_skips_parked_sessions(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
orch = SimpleNamespace(
|
||||
reap_secretary_session=AsyncMock(), reap_intake_session=AsyncMock()
|
||||
)
|
||||
monkeypatch.setattr(bridge, "_orchestrator", lambda: orch)
|
||||
monkeypatch.setattr(bridge.settings, "interactive_idle_reap_seconds", 100)
|
||||
|
||||
idle = _bridge_session("secretary")
|
||||
idle.last_user_turn -= 1000
|
||||
parked = _bridge_session("intake", parked=True)
|
||||
parked.last_user_turn -= 1000
|
||||
bridge._SESSIONS["idle-chat"] = idle
|
||||
bridge._SESSIONS["parked-chat"] = parked
|
||||
|
||||
await bridge.sweep_idle()
|
||||
|
||||
assert "idle-chat" not in bridge._SESSIONS
|
||||
assert "parked-chat" in bridge._SESSIONS
|
||||
orch.reap_secretary_session.assert_awaited_once()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_consumer_accumulates_turns_and_surfaces_drafts(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
draft = {"title": "Fix <thing>", "team": "backend", "description": "d"}
|
||||
registry = FakeRegistry(
|
||||
[
|
||||
{"kind": "text", "text": "Hello "},
|
||||
{"kind": "text", "text": "CEO."},
|
||||
{"kind": "turn_end", "text": ""},
|
||||
{"kind": "draft", "text": "", "data": draft},
|
||||
]
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"roboco.services.prompter_live.get_live_registry", lambda: registry
|
||||
)
|
||||
|
||||
sess = _bridge_session("intake")
|
||||
bridge._SESSIONS["777"] = sess
|
||||
await bridge._consume("777", sess)
|
||||
|
||||
calls = sess.client.send_message.await_args_list
|
||||
# Turn text, then the draft card, then the end-of-session note.
|
||||
assert calls[0].args[0] == "Hello CEO."
|
||||
assert "Fix <thing>" in calls[1].args[0]
|
||||
keyboard = calls[1].kwargs["reply_markup"]["inline_keyboard"][0]
|
||||
assert keyboard[0]["callback_data"].startswith("apv:intake:")
|
||||
assert keyboard[1]["callback_data"].startswith("rej:intake:")
|
||||
assert sess.pending_draft == draft
|
||||
assert calls[-1].args[0] == "Session ended."
|
||||
# Stream ended → session evicted, client closed.
|
||||
assert "777" not in bridge._SESSIONS
|
||||
sess.client.close.assert_awaited_once()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_start_secretary_opens_session_and_consumer(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
orch = SimpleNamespace(start_secretary_session=AsyncMock())
|
||||
monkeypatch.setattr(bridge, "_orchestrator", lambda: orch)
|
||||
monkeypatch.setattr(bridge, "_build_client", lambda _c: AsyncMock())
|
||||
consume = AsyncMock()
|
||||
monkeypatch.setattr(bridge, "_consume", consume)
|
||||
|
||||
message = await bridge.start_secretary("777", "plan my day", CREDS)
|
||||
|
||||
assert "On it" in message
|
||||
sess = bridge._SESSIONS["777"]
|
||||
assert sess.kind == "secretary"
|
||||
orch.start_secretary_session.assert_awaited_once_with(
|
||||
sess.session_id, initial_message="plan my day"
|
||||
)
|
||||
await sess.consumer # the mocked _consume task completes cleanly
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# engine wiring — commands + callbacks
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_secretary_command_starts_or_continues(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
start = AsyncMock(return_value="🎩 On it…")
|
||||
monkeypatch.setattr(bridge, "start_secretary", start)
|
||||
client = AsyncMock()
|
||||
|
||||
await _engine()._dispatch_command(
|
||||
"secretary", "plan", client, chat_id="777", creds=CREDS
|
||||
)
|
||||
start.assert_awaited_once_with("777", "plan", CREDS)
|
||||
|
||||
bridge._SESSIONS["777"] = _bridge_session("intake")
|
||||
await _engine()._dispatch_command(
|
||||
"secretary", "plan", client, chat_id="777", creds=CREDS
|
||||
)
|
||||
assert "mid /newtask" in client.send_message.await_args.args[0]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_newtask_with_multiple_projects_asks_which(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
projects = [
|
||||
SimpleNamespace(id=uuid4(), slug="roboco", name="RoboCo"),
|
||||
SimpleNamespace(id=uuid4(), slug="website", name="Website"),
|
||||
]
|
||||
svc = MagicMock(list_all=AsyncMock(return_value=projects))
|
||||
monkeypatch.setattr(ti, "get_project_service", lambda _s: svc)
|
||||
client = AsyncMock()
|
||||
|
||||
await _engine()._dispatch_command(
|
||||
"newtask", "ship a thing", client, chat_id="777", creds=CREDS
|
||||
)
|
||||
|
||||
assert bridge._PENDING_NEWTASK["777"] == "ship a thing"
|
||||
keyboard = client.send_message.await_args.kwargs["reply_markup"]
|
||||
labels = [row[0]["text"] for row in keyboard["inline_keyboard"]]
|
||||
assert labels == ["RoboCo", "Website"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_project_pick_callback_starts_intake_with_stored_text(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
project = SimpleNamespace(id=uuid4(), slug="roboco", name="RoboCo")
|
||||
svc = MagicMock(list_all=AsyncMock(return_value=[project]))
|
||||
monkeypatch.setattr(ti, "get_project_service", lambda _s: svc)
|
||||
start = AsyncMock(return_value="📝 Intake on RoboCo")
|
||||
monkeypatch.setattr(bridge, "start_intake", start)
|
||||
bridge._PENDING_NEWTASK["777"] = "ship a thing"
|
||||
client = AsyncMock()
|
||||
|
||||
parsed = ti.parse_callback(f"sel:proj:{str(project.id)[:8]}")
|
||||
assert parsed is not None
|
||||
await _engine()._handle_bridge_callback(parsed, "777", 5, CREDS, client)
|
||||
|
||||
start.assert_awaited_once_with("777", "ship a thing", CREDS, project=project)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_intake_confirm_routes_board_and_parks(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
task_id = uuid4()
|
||||
prompter = MagicMock(confirm_live_draft=AsyncMock(return_value=task_id))
|
||||
monkeypatch.setattr(
|
||||
"roboco.services.prompter.get_prompter_service", lambda _s: prompter
|
||||
)
|
||||
registry = FakeRegistry()
|
||||
monkeypatch.setattr(
|
||||
"roboco.services.prompter_live.get_live_registry", lambda: registry
|
||||
)
|
||||
|
||||
project_id = uuid4()
|
||||
sess = _bridge_session("intake")
|
||||
sess.project_id = str(project_id)
|
||||
sess.pending_draft = {"title": "T"}
|
||||
bridge._SESSIONS["777"] = sess
|
||||
|
||||
ok, text = await _engine()._confirm_intake_draft("777")
|
||||
|
||||
assert ok is True
|
||||
assert "Board review" in text
|
||||
prompter.confirm_live_draft.assert_awaited_once_with(
|
||||
{"title": "T"}, ti._CEO_UUID, project_id=project_id, route="board"
|
||||
)
|
||||
assert registry.parked == [(sess.session_id, str(task_id))]
|
||||
assert sess.parked is True
|
||||
assert sess.pending_draft is None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_intake_discard_keeps_session(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
sess = _bridge_session("intake")
|
||||
sess.pending_draft = {"title": "T"}
|
||||
bridge._SESSIONS["777"] = sess
|
||||
engine = _engine()
|
||||
finish = AsyncMock()
|
||||
monkeypatch.setattr(engine, "_finish_action", finish)
|
||||
client = AsyncMock()
|
||||
|
||||
parsed = ti.parse_callback(f"rej:intake:{sess.session_id[:8]}")
|
||||
assert parsed is not None
|
||||
await engine._handle_bridge_callback(parsed, "777", 5, CREDS, client)
|
||||
|
||||
assert sess.pending_draft is None
|
||||
assert "777" in bridge._SESSIONS
|
||||
assert finish.await_args.args[2] is True
|
||||
@@ -0,0 +1,175 @@
|
||||
"""V4 bot-command tier: the BOT_COMMANDS registry drives /help and the
|
||||
once-per-process setMyCommands sync; /agents, /usage, and /blocked render
|
||||
from the same services the panel reads.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
from typing import Any
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
import pytest
|
||||
from roboco.services import telegram_inbound as ti
|
||||
|
||||
COMMAND_COUNT = len(ti.BOT_COMMANDS)
|
||||
|
||||
|
||||
def _fake_session() -> MagicMock:
|
||||
session = MagicMock()
|
||||
session.commit = AsyncMock()
|
||||
session.execute = AsyncMock()
|
||||
return session
|
||||
|
||||
|
||||
def _engine() -> ti.TelegramInboundEngine:
|
||||
return ti.TelegramInboundEngine(_fake_session())
|
||||
|
||||
|
||||
def _uuid_with_prefix(prefix: str) -> UUID:
|
||||
return UUID(hex=prefix + uuid4().hex[len(prefix) :])
|
||||
|
||||
|
||||
def _task(id8: str, title: str) -> SimpleNamespace:
|
||||
return SimpleNamespace(id=_uuid_with_prefix(id8), title=title)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# registry ↔ help ↔ dispatch coherence
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_help_text_derives_from_the_registry() -> None:
|
||||
for entry in ti.BOT_COMMANDS:
|
||||
assert f"/{entry['command']} — {entry['description']}" in ti._HELP_TEXT
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("cmd", ["agents", "usage", "blocked"])
|
||||
async def test_registry_commands_dispatch_to_a_renderer(
|
||||
cmd: str, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
engine = _engine()
|
||||
renderer = AsyncMock(return_value="rendered")
|
||||
monkeypatch.setattr(engine, f"_render_{cmd}", renderer)
|
||||
client = AsyncMock()
|
||||
|
||||
await engine._dispatch_command(cmd, "", client)
|
||||
|
||||
renderer.assert_awaited_once()
|
||||
assert client.send_message.await_args.args[0] == "rendered"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# setMyCommands sync — once per process
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_run_cycle_syncs_commands_exactly_once(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
monkeypatch.setattr(ti.TelegramInboundEngine, "_commands_synced", False)
|
||||
monkeypatch.setattr(ti.settings, "telegram_enabled", True)
|
||||
monkeypatch.setattr(ti.settings, "telegram_inbound_enabled", True)
|
||||
|
||||
creds = SimpleNamespace(bot_token="123:ABC", chat_id="777")
|
||||
creds_svc = MagicMock(get_decrypted=AsyncMock(return_value=creds))
|
||||
monkeypatch.setattr(ti, "get_telegram_credentials_service", lambda _s: creds_svc)
|
||||
settings_svc = MagicMock(get_int=AsyncMock(return_value=0), set=AsyncMock())
|
||||
monkeypatch.setattr(ti, "get_settings_service", lambda _s: settings_svc)
|
||||
|
||||
client = AsyncMock()
|
||||
client.configured = True
|
||||
client.get_updates = AsyncMock(return_value=[])
|
||||
|
||||
engine = ti.TelegramInboundEngine(_fake_session(), client=client)
|
||||
await engine.run_cycle()
|
||||
await engine.run_cycle()
|
||||
|
||||
client.set_my_commands.assert_awaited_once_with(list(ti.BOT_COMMANDS))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# renderers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_render_agents_lists_working_agents(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
fleet: dict[str, Any] = {
|
||||
"total": 26,
|
||||
"by_status": {"active": 4, "idle": 22},
|
||||
"working": [
|
||||
{"name": "be-dev-1", "task_title": "GitProvider seam"},
|
||||
{"name": "fe-qa", "task_title": None},
|
||||
],
|
||||
}
|
||||
cockpit = MagicMock(fleet=AsyncMock(return_value=fleet))
|
||||
monkeypatch.setattr(ti, "get_tg_cockpit_service", lambda _s: cockpit)
|
||||
|
||||
text = await _engine()._render_agents()
|
||||
|
||||
assert "26 total" in text
|
||||
assert "4 active" in text
|
||||
assert "be-dev-1" in text
|
||||
assert "GitProvider seam" in text
|
||||
assert "fe-qa" in text
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_render_usage_formats_today_summary(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
usage = MagicMock(
|
||||
get_today_summary=AsyncMock(
|
||||
return_value={"tokens_today": 2_400_000, "cost_today_usd": 18.7}
|
||||
)
|
||||
)
|
||||
monkeypatch.setattr(ti, "get_usage_service", lambda _s: usage)
|
||||
|
||||
text = await _engine()._render_usage()
|
||||
|
||||
assert "$18.70" in text
|
||||
assert "2,400,000 tokens" in text
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_render_blocked_sections_and_links(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
tasks = MagicMock(
|
||||
list_awaiting_ceo_approval=AsyncMock(
|
||||
return_value=[_task("aaaa1111", "Root PR ready")]
|
||||
),
|
||||
list_blocked=AsyncMock(return_value=[_task("bbbb2222", "Infra <wedge>")]),
|
||||
)
|
||||
monkeypatch.setattr(ti, "get_task_service", lambda _s: tasks)
|
||||
monkeypatch.setattr(ti.settings, "panel_base_url", "https://nas.example")
|
||||
|
||||
text = await _engine()._render_blocked()
|
||||
|
||||
assert "Awaiting you" in text
|
||||
assert "Blocked" in text
|
||||
assert '<a href="https://nas.example/tasks/aaaa1111">Root PR ready</a>' in text
|
||||
assert "aaaa1111" in text
|
||||
# HTML-escaped title, never raw.
|
||||
assert "Infra <wedge>" in text
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_render_blocked_all_clear(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
tasks = MagicMock(
|
||||
list_awaiting_ceo_approval=AsyncMock(return_value=[]),
|
||||
list_blocked=AsyncMock(return_value=[]),
|
||||
)
|
||||
monkeypatch.setattr(ti, "get_task_service", lambda _s: tasks)
|
||||
|
||||
text = await _engine()._render_blocked()
|
||||
|
||||
assert "Nothing is blocked" in text
|
||||
@@ -95,7 +95,7 @@ async def test_authorized_chat_message_dispatches_command(
|
||||
{"chat": {"id": 777}, "text": "/status"}, CREDS, client
|
||||
)
|
||||
|
||||
dispatch.assert_awaited_once_with("status", "", client)
|
||||
dispatch.assert_awaited_once_with("status", "", client, chat_id="777", creds=CREDS)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -155,7 +155,7 @@ async def test_message_with_matching_sender_dispatches(
|
||||
{"chat": {"id": 777}, "from": {"id": 777}, "text": "/status"}, CREDS, client
|
||||
)
|
||||
|
||||
dispatch.assert_awaited_once_with("status", "", client)
|
||||
dispatch.assert_awaited_once_with("status", "", client, chat_id="777", creds=CREDS)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -173,7 +173,7 @@ async def test_message_without_from_keeps_prior_behavior(
|
||||
{"chat": {"id": 777}, "text": "/status"}, CREDS, client
|
||||
)
|
||||
|
||||
dispatch.assert_awaited_once_with("status", "", client)
|
||||
dispatch.assert_awaited_once_with("status", "", client, chat_id="777", creds=CREDS)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
|
||||
@@ -0,0 +1,187 @@
|
||||
"""TgCockpitService coverage: the /telegram/today aggregate composes
|
||||
needs-you counts, fleet snapshot, spend, and ship state from seeded rows —
|
||||
and degrades to an all-zeros brief on an empty company.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
from roboco.config import settings
|
||||
from roboco.db.tables import AgentTable, TaskTable
|
||||
from roboco.foundation import identity as _foundation
|
||||
from roboco.foundation.policy.content import markers
|
||||
from roboco.models.base import (
|
||||
AgentRole,
|
||||
AgentStatus,
|
||||
Complexity,
|
||||
Team,
|
||||
)
|
||||
from roboco.models.base import TaskNature as TN
|
||||
from roboco.models.base import TaskStatus as TS
|
||||
from roboco.models.base import TaskType as TT
|
||||
from roboco.services.task import (
|
||||
RELEASE_MANAGER_SOURCE,
|
||||
ROADMAP_SOURCE,
|
||||
VIDEO_POST_SOURCE,
|
||||
X_POST_SOURCE,
|
||||
)
|
||||
from roboco.services.tg_cockpit import get_tg_cockpit_service
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from uuid import UUID
|
||||
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
SYSTEM_UUID = _foundation.AGENTS["system"].uuid
|
||||
|
||||
CI_WATCH_SOURCE = "ci_watch"
|
||||
|
||||
# 1 awaiting + 1 blocked + 4 held drafts (release/x/video/roadmap-item).
|
||||
EXPECTED_NEEDS_YOU_TOTAL = 6
|
||||
|
||||
|
||||
async def _seed_system_agent(session: AsyncSession) -> None:
|
||||
if await session.get(AgentTable, SYSTEM_UUID) is None:
|
||||
session.add(
|
||||
AgentTable(
|
||||
id=SYSTEM_UUID,
|
||||
name="system",
|
||||
slug="system",
|
||||
role=AgentRole.SYSTEM,
|
||||
team=None,
|
||||
status=AgentStatus.ACTIVE,
|
||||
model_config={},
|
||||
system_prompt="x",
|
||||
capabilities=[],
|
||||
permissions={},
|
||||
metrics={},
|
||||
)
|
||||
)
|
||||
await session.flush()
|
||||
|
||||
|
||||
def _task(
|
||||
title: str,
|
||||
task_status: TS,
|
||||
*,
|
||||
source: str | None = None,
|
||||
team: Team = Team.BACKEND,
|
||||
) -> TaskTable:
|
||||
return TaskTable(
|
||||
id=uuid4(),
|
||||
title=title,
|
||||
description="A description long enough to satisfy any length floor.",
|
||||
acceptance_criteria=["it is visible on the Today brief"],
|
||||
status=task_status,
|
||||
priority=2,
|
||||
task_type=TT.ADMINISTRATIVE,
|
||||
nature=TN.NON_TECHNICAL,
|
||||
estimated_complexity=Complexity.LOW,
|
||||
created_by=SYSTEM_UUID,
|
||||
team=team,
|
||||
source=source,
|
||||
confirmed_by_human=True,
|
||||
)
|
||||
|
||||
|
||||
async def _seed_working_agent(session: AsyncSession, current_task_id: UUID) -> None:
|
||||
session.add(
|
||||
AgentTable(
|
||||
id=uuid4(),
|
||||
name="be-dev-1",
|
||||
slug="be-dev-1",
|
||||
role=AgentRole.DEVELOPER,
|
||||
team=Team.BACKEND,
|
||||
status=AgentStatus.ACTIVE,
|
||||
model_config={},
|
||||
system_prompt="x",
|
||||
capabilities=[],
|
||||
permissions={},
|
||||
metrics={},
|
||||
current_task_id=current_task_id,
|
||||
)
|
||||
)
|
||||
await session.flush()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_today_is_all_zeros_on_an_empty_company(
|
||||
db_session: AsyncSession,
|
||||
) -> None:
|
||||
brief = await get_tg_cockpit_service(db_session).today()
|
||||
|
||||
assert brief["needs_you"]["total"] == 0
|
||||
assert brief["needs_you"]["awaiting_ceo"] == []
|
||||
assert brief["needs_you"]["blocked"] == []
|
||||
assert brief["fleet"]["working"] == []
|
||||
assert brief["spend"] == {"tokens_today": 0, "cost_today_usd": 0.0}
|
||||
assert brief["ship"]["version"] == settings.app_version
|
||||
assert brief["ship"]["open_release_proposal"] is False
|
||||
assert brief["ship"]["ci_fix_tasks"] == 0
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_today_composes_needs_you_fleet_and_ship(
|
||||
db_session: AsyncSession,
|
||||
) -> None:
|
||||
await _seed_system_agent(db_session)
|
||||
|
||||
awaiting = _task("Root PR ready", TS.AWAITING_CEO_APPROVAL)
|
||||
blocked = _task("Stuck on infra", TS.BLOCKED)
|
||||
x_draft = _task("X draft", TS.PENDING, source=X_POST_SOURCE, team=Team.BOARD)
|
||||
video_draft = _task(
|
||||
"Video draft", TS.PENDING, source=VIDEO_POST_SOURCE, team=Team.BOARD
|
||||
)
|
||||
release_prop = _task(
|
||||
"Release 0.26.0", TS.PENDING, source=RELEASE_MANAGER_SOURCE, team=Team.BOARD
|
||||
)
|
||||
ci_fix = _task("Fix red CI", TS.PENDING, source=CI_WATCH_SOURCE)
|
||||
cycle = _task("Roadmap cycle", TS.PENDING, source=ROADMAP_SOURCE, team=Team.BOARD)
|
||||
for row in (
|
||||
awaiting,
|
||||
blocked,
|
||||
x_draft,
|
||||
video_draft,
|
||||
release_prop,
|
||||
ci_fix,
|
||||
cycle,
|
||||
):
|
||||
db_session.add(row)
|
||||
await db_session.flush()
|
||||
markers.set_roadmap_cycle(
|
||||
cycle,
|
||||
{
|
||||
"goal": "g",
|
||||
"items": [
|
||||
{"id": "item-0", "status": "proposed"},
|
||||
{"id": "item-1", "status": "approved"},
|
||||
],
|
||||
},
|
||||
)
|
||||
await _seed_working_agent(db_session, awaiting.id)
|
||||
|
||||
brief = await get_tg_cockpit_service(db_session).today()
|
||||
|
||||
needs = brief["needs_you"]
|
||||
assert needs["awaiting_ceo_count"] == 1
|
||||
assert needs["awaiting_ceo"][0]["title"] == "Root PR ready"
|
||||
assert needs["awaiting_ceo"][0]["status"] == "awaiting_ceo_approval"
|
||||
assert needs["blocked_count"] == 1
|
||||
assert needs["held_drafts"] == {
|
||||
"release_proposals": 1,
|
||||
"x_posts": 1,
|
||||
"video_posts": 1,
|
||||
"roadmap_items": 1,
|
||||
}
|
||||
assert needs["total"] == EXPECTED_NEEDS_YOU_TOTAL
|
||||
|
||||
working = brief["fleet"]["working"]
|
||||
assert len(working) == 1
|
||||
assert working[0]["name"] == "be-dev-1"
|
||||
assert working[0]["task_title"] == "Root PR ready"
|
||||
|
||||
assert brief["ship"]["open_release_proposal"] is True
|
||||
assert brief["ship"]["ci_fix_tasks"] == 1
|
||||
Reference in New Issue
Block a user