Skip to content

AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.

feat(platform): a scheduled chat says once why its run was skipped (#15374)

Nicholas Tindle54b1c89bdcf2
diff --git a/autogpt_platform/backend/backend/copilot/baseline/service.py b/autogpt_platform/backend/backend/copilot/baseline/service.py
index d425d50c0d..96f08a031a 100644
--- a/autogpt_platform/backend/backend/copilot/baseline/service.py
+++ b/autogpt_platform/backend/backend/copilot/baseline/service.py
@@ -56,6 +56,7 @@ from backend.copilot.gate.held import resolve_answered
from backend.copilot.graphiti.config import is_enabled_for_user
from backend.copilot.graphiti.context import fetch_warm_context
from backend.copilot.graphiti.ingest import enqueue_conversation_turn
+from backend.copilot.hidden_rows import visible_to_model
from backend.copilot.learning.capture import capture_chat_turn, find_initiating_user_row
from backend.copilot.llm_attribution import openrouter_attribution
from backend.copilot.local_context_probe import (
@@ -1624,7 +1625,10 @@ async def _load_prior_transcript(
session_id, restore.message_count, gap
)
if hole or gap:
- _append_gap_to_builder(hole + gap, transcript_builder)
+ # The transcript is what later turns read back as their own history,
+ # so a row kept from the model never enters it. The upload's
+ # watermark still counts it, so it is not found again as a gap.
+ _append_gap_to_builder(visible_to_model(hole + gap), transcript_builder)
logger.info(
"[Baseline] Filled gap: loaded %d transcript msgs + %d hole msgs "
"+ %d gap msgs from DB",
diff --git a/autogpt_platform/backend/backend/copilot/baseline/transcript_integration_test.py b/autogpt_platform/backend/backend/copilot/baseline/transcript_integration_test.py
index 4855364e7c..869408e91b 100644
--- a/autogpt_platform/backend/backend/copilot/baseline/transcript_integration_test.py
+++ b/autogpt_platform/backend/backend/copilot/baseline/transcript_integration_test.py
@@ -253,6 +253,43 @@ class TestLoadPriorTranscript:
# 2 from transcript + 2 gap messages (user+assistant at positions 2,3)
assert builder.entry_count == 4
+ @pytest.mark.asyncio
+ async def test_a_note_kept_from_the_model_stays_out_of_the_transcript(self):
+ """A scheduled chat's note between turns is the owner's card. Written
+ into the transcript this turn uploads, every later turn would read it
+ back as the model's own earlier reply (SECRT-2879)."""
+ builder = TranscriptBuilder()
+ restore = TranscriptDownload(
+ content=_make_transcript_content("user", "assistant").encode("utf-8"),
+ message_count=2,
+ mode="baseline",
+ )
+ messages = _make_session_messages(
+ "user", "assistant", "assistant", "user", "assistant", "user"
+ )
+ messages[2] = ChatMessage(
+ role="assistant",
+ content="Skipped: daily usage limit reached",
+ sequence=2,
+ metadata={"kind": "scheduled_chat_notice", "hidden_from_model": True},
+ )
+
+ with patch(
+ "backend.copilot.baseline.service.download_transcript",
+ new=AsyncMock(return_value=restore),
+ ):
+ covers, dl = await _load_prior_transcript(
+ user_id="user-1",
+ session_id="session-1",
+ session_messages=messages,
+ transcript_builder=builder,
+ )
+
+ assert covers is True and dl is not None
+ # The two real gap rows go in; the note does not.
+ assert builder.entry_count == 4
+ assert "Skipped: daily usage limit reached" not in builder.to_jsonl()
+
@pytest.mark.asyncio
async def test_missing_transcript_allows_upload(self):
"""Nothing in GCS → upload is safe; the turn writes the first snapshot."""
diff --git a/autogpt_platform/backend/backend/copilot/db.py b/autogpt_platform/backend/backend/copilot/db.py
index 0fad0ec727..a18fba0275 100644
--- a/autogpt_platform/backend/backend/copilot/db.py
+++ b/autogpt_platform/backend/backend/copilot/db.py
@@ -36,6 +36,7 @@ from .model import (
cache_chat_session,
)
from .model import get_chat_session as get_chat_session_cached
+from .model import invalidate_session_cache
from .transports import resolve_default_chat_route
logger = logging.getLogger(__name__)
@@ -1605,9 +1606,63 @@ async def append_expert_run_message(
message_id=message_id,
metadata=metadata,
)
+ # The chat page reads the session through the Redis cache: drop a copy
+ # from before this post, or the post shows only once the copy expires.
+ await invalidate_session_cache(session_id)
return session_id
+async def append_session_message(
+ session_id: str,
+ user_id: str,
+ content: str,
+ message_id: str,
+ metadata: dict[str, Any] | None = None,
+) -> bool:
+ """Post an assistant message into one chat the user owns, between turns.
+
+ For a note about that chat, such as why its scheduled run was skipped.
+ Unlike ``append_expert_run_message`` this never creates or re-targets a
+ session: a note about a chat belongs in that chat or nowhere. Returns False
+ when the chat is gone or not the user's, or when *message_id* was already
+ written (deterministic at the caller, so a double fire posts once).
+ """
+ if await PrismaChatMessage.prisma().find_unique(where={"id": message_id}):
+ return False
+ session = await PrismaChatSession.prisma().find_first(
+ where={"id": session_id, "userId": user_id}
+ )
+ if session is None:
+ return False
+
+ async def write_with_fresh_sequence() -> None:
+ await add_chat_message(
+ session_id=session_id,
+ role="assistant",
+ sequence=await get_next_sequence(session_id),
+ content=content,
+ message_id=message_id,
+ metadata=metadata,
+ )
+
+ # Same Redis NX lock as append_expert_run_message: the sequence read and
+ # the insert must not interleave with a turn writing the same sequence.
+ async with _get_session_lock(session_id):
+ try:
+ await write_with_fresh_sequence()
+ except UniqueViolationError as e:
+ if is_duplicate_chat_message_id_error(e):
+ return False
+ # Reachable only in lock-degraded mode (Redis down yields the
+ # lock without acquiring); one retry with a fresh sequence is
+ # enough at this write volume.
+ await write_with_fresh_sequence()
+ # The next turn and the chat page load the session through the Redis cache
+ # first; a stale copy would hide the row just written.
+ await invalidate_session_cache(session_id)
+ return True
+
+
async def append_plain_session_message(
user_id: str,
content: str,
diff --git a/autogpt_platform/backend/backend/copilot/dream/fetch.py b/autogpt_platform/backend/backend/copilot/dream/fetch.py
index db5182580c..669fe760aa 100644
--- a/autogpt_platform/backend/backend/copilot/dream/fetch.py
+++ b/autogpt_platform/backend/backend/copilot/dream/fetch.py
@@ -20,6 +20,7 @@ from pydantic import BaseModel, Field
from backend.copilot.graphiti.falkordb_driver import AutoGPTFalkorDriver, open_driver
from backend.copilot.graphiti.scope import MemoryScope
+from backend.copilot.hidden_rows import visible_to_model
from backend.data.db_accessors import chat_db
logger = logging.getLogger(__name__)
@@ -291,7 +292,7 @@ async def _fetch_recent_sessions(
session_id=sid, limit=20, user_id=user_id
)
if paginated is not None:
- messages = list(getattr(paginated, "messages", []) or [])
+ messages = visible_to_model(getattr(paginated, "messages", []) or [])
except Exception:
logger.debug(
"Failed to fetch messages for session %s — body left empty",
diff --git a/autogpt_platform/backend/backend/copilot/dream/fetch_test.py b/autogpt_platform/backend/backend/copilot/dream/fetch_test.py
index 9c750ae387..aa49afa92e 100644
--- a/autogpt_platform/backend/backend/copilot/dream/fetch_test.py
+++ b/autogpt_platform/backend/backend/copilot/dream/fetch_test.py
@@ -5,6 +5,7 @@ from unittest.mock import AsyncMock
import pytest
from backend.copilot.graphiti.scope import MemoryScope
+from backend.copilot.model import ChatMessage
from . import fetch as fetch_mod
@@ -35,3 +36,32 @@ async def test_expert_dream_fetches_only_that_experts_sessions(mocker):
database.get_user_chat_sessions.assert_awaited_once_with(
"user-1", limit=10, expert_id="expert-1"
)
+
+
+async def test_a_note_for_the_user_is_not_dreamt_about(mocker):
+ """A skipped-run card is the platform talking to the user; a dream would
+ store "usage limit reached" as a fact about them."""
+ session = SimpleNamespace(session_id="session-1", title="Briefing")
+ page = SimpleNamespace(
+ messages=[
+ ChatMessage(role="user", content="brief me"),
+ ChatMessage(
+ role="assistant",
+ content="Skipped: daily usage limit reached",
+ metadata={"hidden_from_model": True},
+ ),
+ ChatMessage(role="assistant", content="here is your brief"),
+ ]
+ )
+ database = SimpleNamespace(
+ get_user_chat_sessions=AsyncMock(return_value=[session]),
+ get_chat_messages_paginated=AsyncMock(return_value=page),
+ )
+ mocker.patch.object(fetch_mod, "chat_db", return_value=database)
+
+ rows = await fetch_mod._fetch_recent_sessions(
+ MemoryScope.for_user("user-1"), datetime.now(timezone.utc), 10
+ )
+
+ assert rows[0].body == "user: brief me\nassistant: here is your brief"
diff --git a/autogpt_platform/backend/backend/copilot/hidden_rows.py b/autogpt_platform/backend/backend/copilot/hidden_rows.py
new file mode 100644
index 0000000000..fafa9eb026
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/hidden_rows.py
@@ -0,0 +1,29 @@
+"""Chat rows the platform posts for the user, which the model never reads back.
+
+A scheduled chat that was skipped or paused gets a card in its chat saying
+why, with the fix on a button. Posted as an assistant row, the next turn
+would read the card as something the model had said itself, and a stale line
+like "Discord still needs to be connected" in a chat's history is what kept an
+every-minute monitor repeating it, run after run, without trying again. So a
+row whose metadata carries ``hidden_from_model`` is dropped from every list of
+messages that becomes model input, the tool that lets an expert read another
+chat included. Drop them after any slicing by count or sequence: the
+transcript watermark counts every row, hidden ones included. They are the
+owner's, so a shared copy of the chat leaves them out as well.
+"""
+
+from collections.abc import Iterable, Mapping
+from typing import TYPE_CHECKING, Any
+
+if TYPE_CHECKING:
+ from backend.copilot.model import ChatMessage
+
+HIDDEN_FROM_MODEL_KEY = "hidden_from_model"
+
+
+def is_hidden_from_model(metadata: Mapping[str, Any] | None) -> bool:
+ return metadata is not None and metadata.get(HIDDEN_FROM_MODEL_KEY) is True
+
+
+def visible_to_model(messages: "Iterable[ChatMessage]") -> "list[ChatMessage]":
+ return [m for m in messages if not is_hidden_from_model(m.metadata)]
diff --git a/autogpt_platform/backend/backend/copilot/hidden_rows_test.py b/autogpt_platform/backend/backend/copilot/hidden_rows_test.py
new file mode 100644
index 0000000000..d0d14d342d
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/hidden_rows_test.py
@@ -0,0 +1,21 @@
+from backend.copilot.hidden_rows import is_hidden_from_model, visible_to_model
+from backend.copilot.model import ChatMessage
+
+
+def test_only_an_explicit_flag_hides_a_row():
+ assert is_hidden_from_model({"hidden_from_model": True})
+ assert not is_hidden_from_model({"hidden_from_model": "true"})
+ assert not is_hidden_from_model({"kind": "expert_run"})
+ assert not is_hidden_from_model(None)
+
+
+def test_visible_to_model_keeps_order_and_drops_only_flagged_rows():
+ rows = [
+ ChatMessage(role="user", content="a"),
+ ChatMessage(
+ role="assistant", content="b", metadata={"hidden_from_model": True}
+ ),
+ ChatMessage(role="assistant", content="c", metadata={"kind": "expert_run"}),
+ ]
+
+ assert [m.content for m in visible_to_model(rows)] == ["a", "c"]
diff --git a/autogpt_platform/backend/backend/copilot/learning/chat_evidence.py b/autogpt_platform/backend/backend/copilot/learning/chat_evidence.py
index 04da3b1607..d33627431c 100644
--- a/autogpt_platform/backend/backend/copilot/learning/chat_evidence.py
+++ b/autogpt_platform/backend/backend/copilot/learning/chat_evidence.py
@@ -2,6 +2,7 @@
import json
+from backend.copilot.hidden_rows import visible_to_model
from backend.copilot.model import ChatMessage
from backend.data.skill_learning import MAX_OUTCOME_SIGNALS
@@ -23,10 +24,13 @@ def build_chat_evidence(
last_sequence: int,
max_chars: int,
) -> EvidenceBundle:
+ # The platform's notes to the owner, such as why a scheduled run was
+ # skipped, go to no model: learnt from, "usage limit reached" would read
+ # as something about the user.
ordered = sorted(
(
m
- for m in messages
+ for m in visible_to_model(messages)
if m.sequence is not None and 0 <= m.sequence <= last_sequence
),
key=lambda m: m.sequence or 0,
diff --git a/autogpt_platform/backend/backend/copilot/learning/chat_evidence_test.py b/autogpt_platform/backend/backend/copilot/learning/chat_evidence_test.py
new file mode 100644
index 0000000000..079fea8cb6
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/learning/chat_evidence_test.py
@@ -0,0 +1,32 @@
+from backend.copilot.model import ChatMessage
+
+from .chat_evidence import build_chat_evidence
+from .contract import LearningScope, SourceRevision
+
+
+def test_a_note_for_the_owner_is_never_evidence():
+ """A scheduled chat's note is the platform talking to its owner. Learnt
+ from, "usage limit reached" would read as something about the user."""
+ source = SourceRevision(
+ source_id="source-1",
+ source_kind="chat_session",
+ source_ref="session-1",
+ scope=LearningScope(user_id="user-1", owner_key="user:user-1"),
+ revision="3",
+ epoch=0,
+ )
+ messages = [
+ ChatMessage(role="user", content="brief me", sequence=0),
+ ChatMessage(
+ role="assistant",
+ content="Skipped: daily usage limit reached",
+ sequence=1,
+ metadata={"kind": "scheduled_chat_notice", "hidden_from_model": True},
+ ),
+ ChatMessage(role="user", content="brief me again", sequence=2),
+ ChatMessage(role="assistant", content="here is your brief", sequence=3),
+ ]
+
+ bundle = build_chat_evidence(source, messages, last_sequence=3, max_chars=10_000)
+
+ assert [span.ref for span in bundle.spans] == ["msg:0", "msg:2", "msg:3"]
diff --git a/autogpt_platform/backend/backend/copilot/scheduled_chats/__init__.py b/autogpt_platform/backend/backend/copilot/scheduled_chats/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/autogpt_platform/backend/backend/copilot/scheduled_chats/notices.py b/autogpt_platform/backend/backend/copilot/scheduled_chats/notices.py
new file mode 100644
index 0000000000..6856a55bcc
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/scheduled_chats/notices.py
@@ -0,0 +1,266 @@
+"""What a scheduled chat tells its owner when one of its runs was skipped.
+
+The scheduler skips a scheduled chat's run when its owner may not start a
+turn: no plan, a lost ChatGPT connection, or a used-up usage limit. A repeating
+schedule stays registered and picks up again by itself once that changes.
+Skipping is right; skipping without a word is not. So the chat gets one note
+per window saying why, with the fix on a button (SECRT-2879).
+
+The note is a card for the owner, not part of the conversation: its metadata
+keeps it out of everything the model reads (``hidden_rows``).
+"""
+
+import uuid
+from datetime import datetime, timezone
+from typing import Any, Literal
+from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
+
+from pydantic import BaseModel
+
+from backend.copilot.hidden_rows import HIDDEN_FROM_MODEL_KEY
+from backend.copilot.turn_queue import TurnRefusal
+from backend.data.db_accessors import chat_db
+
+# The ``kind`` the chat page renders as a card rather than a reply.
+NOTICE_METADATA_KIND = "scheduled_chat_notice"
+
+BILLING_PATH = "/settings/billing"
+INTEGRATIONS_PATH = "/settings/integrations"
+
+_MESSAGE_NAMESPACE = uuid.UUID("5d0a3a4e-2f3b-5c8e-9a51-6e7c0b1d2f43")
+_TITLE_MAX = 60
+
+NoticeReason = Literal["usage", "no_plan", "codex_access"]
+# What became of the skipped run: a repeating schedule keeps its next time, a
+# one-shot either waits for its usage window to reset or is gone.
+SkippedRun = Literal["recurring", "waits_for_reset", "dropped"]
+
+
+class NoticeLink(BaseModel):
+ """A button that opens a page, such as billing."""
+
+ kind: Literal["link"] = "link"
+ label: str
+ href: str
+
+
+class ScheduledChatNotice(BaseModel):
+ reason: NoticeReason
+ headline: str
+ body: str
+ # When the schedule runs again by itself, where it does.
+ resumes_at: datetime | None = None
+ actions: list[NoticeLink]
+ # Names the window this note covers, so a schedule says it once per
+ # window: part of the message id.
+ window_key: str
+
+ @property
+ def content(self) -> str:
+ """The text, for anything that shows the message without the card."""
+ return f"{self.headline}. {self.body}"
+
+ def metadata(self, *, schedule_key: str, title: str) -> dict[str, Any]:
+ return {
+ "kind": NOTICE_METADATA_KIND,
+ HIDDEN_FROM_MODEL_KEY: True,
+ "reason": self.reason,
+ "schedule_key": schedule_key,
+ "title": title,
+ "headline": self.headline,
+ "body": self.body,
+ "resumes_at": self.resumes_at.isoformat() if self.resumes_at else None,
+ "actions": [action.model_dump() for action in self.actions],
+ }
+
+
+def skip_notice(
+ refusal: TurnRefusal,
+ *,
+ title: str,
+ now: datetime,
+ run: SkippedRun,
+ user_timezone: str | None = None,
+) -> ScheduledChatNotice | None:
+ """What to tell the owner about a run *refusal* stopped, or None when
+ there is nothing for them to do (a banned account, or an outage on our
+ side). Times are in *user_timezone*, the one the schedule was made in, else
+ UTC."""
+ if refusal.kind == "usage" and refusal.window in ("daily", "weekly"):
+ return _usage_notice(refusal, title=title, run=run, user_timezone=user_timezone)
+ if refusal.kind == "usage":
+ return _plan_notice(
+ title=title,
+ run=run,
+ headline="Skipped: your trial's usage limit is used up",
+ window_key=f"trial:{_iso_week(now)}",
+ )
+ if refusal.kind == "no_plan":
+ return _plan_notice(
+ title=title,
+ run=run,
+ headline="Skipped: scheduled chats need a plan",
+ window_key=f"no_plan:{_iso_week(now)}",
+ )
+ if refusal.kind == "codex_access":
+ # A one-shot is gone by now; only a repeating schedule comes back.
+ after = (
+ " Reconnect it in Settings and the chat runs again at its next time."
+ if run == "recurring"
+ else " Reconnect it in Settings, then ask for it again."
+ )
+ return ScheduledChatNotice(
+ reason="codex_access",
+ headline="Skipped: your ChatGPT connection isn't available",
+ body=(
+ f"“{title}” didn't run: it runs on your ChatGPT plan, which "
+ f"Otto can't use right now.{after}"
+ ),
+ actions=[NoticeLink(label="Open settings", href=INTEGRATIONS_PATH)],
+ window_key=f"codex_access:{_iso_week(now)}",
+ )
+ return None
+
+
+def _usage_notice(
+ refusal: TurnRefusal,
+ *,
+ title: str,
+ run: SkippedRun,
+ user_timezone: str | None,
+) -> ScheduledChatNotice:
+ daily = refusal.window == "daily"
+ resets_at = refusal.resets_at
+ if resets_at is None:
+ when = "when the limit resets"
+ else:
+ local = _in_timezone(resets_at, user_timezone)
+ clock = f"{local:%H:%M} {local.tzname()}"
+ # Monday 00:00 UTC is still Sunday for someone in Chicago.
+ when = (
+ f"when the limit resets at {clock}"
+ if daily
+ else f"when the limit resets on {local:%A} at {clock}"
+ )
+ if run == "waits_for_reset":
+ body = f"“{title}” will run {when}."
+ elif run == "recurring":
+ body = f"“{title}” didn't run. Scheduled chats run again {when}."
+ else:
+ body = f"“{title}” didn't run."
+ return ScheduledChatNotice(
+ reason="usage",
+ headline=(
+ "Skipped: daily usage limit reached"
+ if daily
+ else "Skipped: weekly usage limit reached"
+ ),
+ body=body,
+ resumes_at=resets_at if run != "dropped" else None,
+ actions=[NoticeLink(label="Upgrade", href=BILLING_PATH)],
+ window_key=(
+ f"usage:{refusal.window}:"
+ f"{resets_at.isoformat() if resets_at else 'unknown'}"
+ ),
+ )
+
+
+def _plan_notice(
+ *, title: str, run: SkippedRun, headline: str, window_key: str
+) -> ScheduledChatNotice:
+ """No window resets these, so a repeating schedule waits for a plan, and
+ the note repeats at most weekly while it does."""
+ body = (
+ f"“{title}” didn't run. Scheduled chats start again once you choose a plan."
+ if run == "recurring"
+ else f"“{title}” didn't run. Scheduled chats need a plan."
+ )
+ return ScheduledChatNotice(
+ reason="no_plan",
+ headline=headline,
+ body=body,
+ actions=[NoticeLink(label="Choose a plan", href=BILLING_PATH)],
+ window_key=window_key,
+ )
+
+
+def schedule_title(*, routine_title: str | None, message: str) -> str:
+ """How the note names the scheduled chat: a routine by its title, a
+ follow-up by the start of the message it sends."""
+ if routine_title:
+ return routine_title
+ first_line = next(
+ (line.strip() for line in message.splitlines() if line.strip()), ""
+ )
+ if len(first_line) <= _TITLE_MAX:
+ return first_line or "Scheduled chat"
+ return f"{first_line[: _TITLE_MAX - 1].rstrip()}…"
+
+
+def notice_message_id(*, user_id: str, schedule_key: str, window_key: str) -> str:
+ """Deterministic, so a second skip in the same window writes nothing."""
+ return str(uuid.uuid5(_MESSAGE_NAMESPACE, f"{user_id}:{schedule_key}:{window_key}"))
+
+
+async def post_notice(
+ notice: ScheduledChatNotice,
+ *,
+ user_id: str,
+ schedule_key: str,
+ title: str,
+ session_id: str | None,
+ expert_id: str | None,
+) -> bool:
+ """Post *notice* where its owner will see it, and say whether it posted.
+
+ Into the scheduled chat's own thread when it has one. A run that would
+ have opened a fresh chat has none yet, so the note goes to the expert's
+ latest thread, or for an AutoPilot schedule into a new chat named for the
+ schedule, where its run would have gone. The message id keeps that to one
+ chat per window.
+ """
+ message_id = notice_message_id(
+ user_id=user_id, schedule_key=schedule_key, window_key=notice.window_key
+ )
+ metadata = notice.metadata(schedule_key=schedule_key, title=title)
+ db = chat_db()
+ if session_id is not None:
+ return await db.append_session_message(
+ session_id=session_id,
+ user_id=user_id,
+ content=notice.content,
+ message_id=message_id,
+ metadata=metadata,
+ )
+ if expert_id is not None:
+ posted_in = await db.append_expert_run_message(
+ user_id=user_id,
+ expert_id=expert_id,
+ content=notice.content,
+ message_id=message_id,
+ metadata=metadata,
+ )
+ else:
+ posted_in = await db.append_plain_session_message(
+ user_id=user_id,
+ content=notice.content,
+ message_id=message_id,
+ metadata=metadata,
+ title=title,
+ )
+ return posted_in is not None
+
+
+def _iso_week(now: datetime) -> str:
+ year, week, _ = now.isocalendar()
+ return f"{year}-W{week:02d}"
+
+
+def _in_timezone(when: datetime, user_timezone: str | None) -> datetime:
+ """*when* on the owner's clock, or UTC when their zone is unknown."""
+ if user_timezone:
+ try:
+ return when.astimezone(ZoneInfo(user_timezone))
+ except (ZoneInfoNotFoundError, ValueError):
+ pass
+ return when.astimezone(timezone.utc)
diff --git a/autogpt_platform/backend/backend/copilot/scheduled_chats/notices_test.py b/autogpt_platform/backend/backend/copilot/scheduled_chats/notices_test.py
new file mode 100644
index 0000000000..181267fa21
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/scheduled_chats/notices_test.py
@@ -0,0 +1,325 @@
+from datetime import datetime, timezone
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+
+from backend.copilot.hidden_rows import is_hidden_from_model
+from backend.copilot.scheduled_chats.notices import (
+ BILLING_PATH,
+ INTEGRATIONS_PATH,
+ NOTICE_METADATA_KIND,
+ notice_message_id,
+ post_notice,
+ schedule_title,
+ skip_notice,
+)
+from backend.copilot.turn_queue import TurnRefusal
+
+_NOW = datetime(2026, 10, 11, 14, 9, tzinfo=timezone.utc)
+_MIDNIGHT = datetime(2026, 10, 12, tzinfo=timezone.utc)
+_MONDAY = datetime(2026, 10, 12, tzinfo=timezone.utc)
+
+
+def _usage(window: str, resets_at: datetime | None = _MIDNIGHT) -> TurnRefusal:
+ return TurnRefusal(
+ reason="rate-limited", kind="usage", window=window, resets_at=resets_at
+ )
+
+
+def test_a_daily_limit_says_when_the_schedule_runs_again():
+ notice = skip_notice(_usage("daily"), title="Briefing", now=_NOW, run="recurring")
+
+ assert notice is not None
+ assert notice.headline == "Skipped: daily usage limit reached"
+ assert notice.body == (
+ "“Briefing” didn't run. Scheduled chats run again when the limit resets "
+ "at 00:00 UTC."
+ )
+ assert notice.resumes_at == _MIDNIGHT
+ assert [(a.label, a.href) for a in notice.actions] == [("Upgrade", BILLING_PATH)]
+
+
+def test_a_weekly_limit_names_the_day_it_resets():
+ notice = skip_notice(
+ _usage("weekly", _MONDAY), title="Briefing", now=_NOW, run="recurring"
+ )
+
+ assert notice is not None
+ assert notice.headline == "Skipped: weekly usage limit reached"
+ assert "resets on Monday at 00:00 UTC" in notice.body
+
+
+def test_the_reset_is_on_the_owners_clock():
+ """The schedule's timezone is on the job: nobody should have to work out
+ what 00:00 UTC is where they live."""
+ notice = skip_notice(
+ _usage("daily"),
+ title="Briefing",
+ now=_NOW,
+ run="recurring",
+ user_timezone="America/Chicago",
+ )
+
+ assert notice is not None
+ assert notice.body.endswith("when the limit resets at 19:00 CDT.")
+ # The window it names is still the UTC one, so the dedupe is unchanged.
+ assert notice.resumes_at == _MIDNIGHT
+
+
+def test_a_weekly_reset_names_the_owners_day():
+ """Monday 00:00 UTC is Sunday evening in Chicago."""
+ notice = skip_notice(
+ _usage("weekly", _MONDAY),
+ title="Briefing",
+ now=_NOW,
+ run="recurring",
+ user_timezone="America/Chicago",
+ )
+
+ assert notice is not None
+ assert "resets on Sunday at 19:00 CDT" in notice.body
+
+
+def test_an_unknown_timezone_falls_back_to_utc():
+ notice = skip_notice(
+ _usage("daily"),
+ title="Briefing",
+ now=_NOW,
+ run="recurring",
+ user_timezone="Mars/Olympus_Mons",
+ )
+
+ assert notice is not None
+ assert notice.body.endswith("at 00:00 UTC.")
+
+
+def test_a_dropped_one_shot_on_a_lost_chatgpt_plan_says_it_did_not_run():
+ notice = skip_notice(
+ TurnRefusal(reason="lacks Codex entitlement", kind="codex_access"),
+ title="Check CI",
+ now=_NOW,
+ run="dropped",
+ )
+
+ assert notice is not None
+ assert notice.body.startswith("“Check CI” didn't run")
+ assert notice.body.endswith("then ask for it again.")
+
+
+def test_a_one_shot_that_waits_says_when_it_will_run():
+ notice = skip_notice(
+ _usage("daily"), title="Check CI", now=_NOW, run="waits_for_reset"
+ )
+
+ assert notice is not None
+ assert notice.body == "“Check CI” will run when the limit resets at 00:00 UTC."
+
+
+def test_a_dropped_one_shot_promises_nothing():
+ notice = skip_notice(_usage("daily"), title="Check CI", now=_NOW, run="dropped")
+
+ assert notice is not None
+ assert notice.body == "“Check CI” didn't run."
+ assert notice.resumes_at is None
+
+
+ ("refusal", "headline"),
+ [
+ (
+ TurnRefusal(reason="paywalled", kind="no_plan"),
+ "Skipped: scheduled chats need a plan",
+ ),
+ (
+ _usage("trial", _NOW),
+ "Skipped: your trial's usage limit is used up",
+ ),
+ ],
+ ids=["no-plan", "trial-used-up"],
+)
+def test_no_plan_offers_a_plan(refusal, headline):
+ notice = skip_notice(refusal, title="Briefing", now=_NOW, run="recurring")
+
+ assert notice is not None
+ assert notice.reason == "no_plan"
+ assert notice.headline == headline
+ assert notice.body == (
+ "“Briefing” didn't run. Scheduled chats start again once you choose a plan."
+ )
+ assert [(a.label, a.href) for a in notice.actions] == [
+ ("Choose a plan", BILLING_PATH)
+ ]
+
+
+def test_a_lost_chatgpt_connection_points_at_settings():
+ notice = skip_notice(
+ TurnRefusal(reason="lacks Codex entitlement", kind="codex_access"),
+ title="Briefing",
+ now=_NOW,
+ run="recurring",
+ )
+
+ assert notice is not None
+ assert notice.reason == "codex_access"
+ assert [(a.label, a.href) for a in notice.actions] == [
+ ("Open settings", INTEGRATIONS_PATH)
+ ]
+
+
+def test_an_outage_on_our_side_says_nothing():
+ refusal = TurnRefusal(reason="unreadable", kind="outage", transient=True)
+
+ assert skip_notice(refusal, title="Briefing", now=_NOW, run="recurring") is None
+
+
+def test_a_banned_account_is_told_nothing():
+ refusal = TurnRefusal(reason="is banned", kind="banned")
+
+ assert skip_notice(refusal, title="Briefing", now=_NOW, run="recurring") is None
+
+
+def test_a_schedule_says_it_once_per_window():
+ """The message id is the dedupe: the same window maps to the same id, and
+ the next window to a new one."""
+ first = skip_notice(_usage("daily"), title="Briefing", now=_NOW, run="recurring")
+ again = skip_notice(_usage("daily"), title="Briefing", now=_NOW, run="recurring")
+ tomorrow = skip_notice(
+ _usage("daily", datetime(2026, 10, 13, tzinfo=timezone.utc)),
+ title="Briefing",
+ now=_NOW,
+ run="recurring",
+ )
+ assert first and again and tomorrow
+
+ def message_id(notice):
+ return notice_message_id(
+ user_id="user-1", schedule_key="routine-1", window_key=notice.window_key
+ )
+
+ assert message_id(first) == message_id(again)
+ assert message_id(first) != message_id(tomorrow)
+
+
+def test_no_plan_says_it_at_most_weekly():
+ """_NOW is a Sunday: the Saturday before is the same ISO week, the Monday
+ after the next one."""
+ refusal = TurnRefusal(reason="paywalled", kind="no_plan")
+ sunday = skip_notice(refusal, title="B", now=_NOW, run="recurring")
+ saturday = skip_notice(
+ refusal,
+ title="B",
+ now=datetime(2026, 10, 10, tzinfo=timezone.utc),
+ run="recurring",
+ )
+ monday = skip_notice(
+ refusal,
+ title="B",
+ now=datetime(2026, 10, 12, tzinfo=timezone.utc),
+ run="recurring",
+ )
+ assert sunday and saturday and monday
+ assert sunday.window_key == saturday.window_key
+ assert sunday.window_key != monday.window_key
+
+
+def test_the_card_is_kept_from_the_model_and_names_its_schedule():
+ notice = skip_notice(_usage("daily"), title="Briefing", now=_NOW, run="recurring")
+ assert notice is not None
+
+ metadata = notice.metadata(schedule_key="routine-1", title="Briefing")
+
+ assert metadata["kind"] == NOTICE_METADATA_KIND
+ assert is_hidden_from_model(metadata)
+ assert metadata["schedule_key"] == "routine-1"
+ assert metadata["resumes_at"] == _MIDNIGHT.isoformat()
+ assert metadata["actions"] == [
+ {"kind": "link", "label": "Upgrade", "href": BILLING_PATH}
+ ]
+
+
+ ("routine_title", "message", "title"),
+ [
+ ("Morning briefing", "Do the thing", "Morning briefing"),
+ (None, "\n Check the deploy \nthen report", "Check the deploy"),
+ (None, "x" * 80, "x" * 59 + "…"),
+ (None, " ", "Scheduled chat"),
+ ],
+ ids=["routine", "follow-up", "long-follow-up", "blank"],
+)
+def test_schedule_title(routine_title, message, title):
+ assert schedule_title(routine_title=routine_title, message=message) == title
+
+
+def _db() -> MagicMock:
+ return MagicMock(
+ append_session_message=AsyncMock(return_value=True),
+ append_expert_run_message=AsyncMock(return_value="expert-thread"),
+ append_plain_session_message=AsyncMock(return_value="new-chat"),
+ )
+
+
+ ("session_id", "expert_id", "called"),
+ [
+ ("session-1", "expert-1", "append_session_message"),
+ (None, "expert-1", "append_expert_run_message"),
+ (None, None, "append_plain_session_message"),
+ ],
+ ids=["own-thread", "expert-thread", "new-chat"],
+)
+async def test_the_note_goes_to_the_schedules_own_chat_first(
+ session_id, expert_id, called
+):
+ notice = skip_notice(_usage("daily"), title="Briefing", now=_NOW, run="recurring")
+ assert notice is not None
+ db = _db()
+
+ with patch("backend.copilot.scheduled_chats.notices.chat_db", return_value=db):
+ posted = await post_notice(
+ notice,
+ user_id="user-1",
+ schedule_key="routine-1",
+ title="Briefing",
+ session_id=session_id,
+ expert_id=expert_id,
+ )
+
+ assert posted is True
+ for name in (
+ "append_session_message",
+ "append_expert_run_message",
+ "append_plain_session_message",
+ ):
+ method = getattr(db, name)
+ assert method.await_count == int(name == called)
+ kwargs = getattr(db, called).await_args.kwargs
+ assert kwargs["content"] == notice.content
+ assert kwargs["message_id"] == notice_message_id(
+ user_id="user-1", schedule_key="routine-1", window_key=notice.window_key
+ )
+ assert kwargs["metadata"]["hidden_from_model"] is True
+ if called == "append_plain_session_message":
+ # The chat it opens is named for the schedule, as its run's would be.
+ assert kwargs["title"] == "Briefing"
+
+
+async def test_a_note_already_posted_this_window_reports_nothing_new():
+ notice = skip_notice(_usage("daily"), title="Briefing", now=_NOW, run="recurring")
+ assert notice is not None
+ db = _db()
+ db.append_plain_session_message.return_value = None
+
+ with patch("backend.copilot.scheduled_chats.notices.chat_db", return_value=db):
+ posted = await post_notice(
+ notice,
+ user_id="user-1",
+ schedule_key="routine-1",
+ title="Briefing",
+ session_id=None,
+ expert_id=None,
+ )
+
+ assert posted is False
diff --git a/autogpt_platform/backend/backend/copilot/sdk/query_builder_test.py b/autogpt_platform/backend/backend/copilot/sdk/query_builder_test.py
index a90cba19c5..0e1f31d733 100644
--- a/autogpt_platform/backend/backend/copilot/sdk/query_builder_test.py
+++ b/autogpt_platform/backend/backend/copilot/sdk/query_builder_test.py
@@ -186,6 +186,68 @@ async def test_build_query_resume_stale_transcript():
assert stats is None # gap context does not compact
+async def test_build_query_resume_stale_transcript_leaves_out_a_note_for_the_user():
+ """A card posted into the chat between turns is in the gap the watermark
+ counts, but it is the user's, not something the model said."""
+ note = ChatMessage(
+ role="assistant",
+ content="Skipped: daily usage limit reached. Connect Discord.",
+ metadata={"kind": "scheduled_chat_notice", "hidden_from_model": True},
+ )
+ session = _make_session(
+ [
+ ChatMessage(role="user", content="turn 1"),
+ ChatMessage(role="assistant", content="reply 1"),
+ note,
+ ChatMessage(role="user", content="turn 2"),
+ ChatMessage(role="assistant", content="reply 2"),
+ ChatMessage(role="user", content="turn 3"),
+ ]
+ )
+ result, _ = await _build_query_message(
+ "turn 3",
+ session,
+ use_resume=True,
+ transcript_msg_count=2,
+ session_id="test-session",
+ )
+ assert "turn 2" in result
+ assert "reply 2" in result
+ assert "Skipped" not in result
+ assert "Discord" not in result
+
+
+async def test_build_query_no_resume_leaves_out_a_note_for_the_user(monkeypatch):
+ async def _mock_compress(msgs, target_tokens=None):
+ return msgs, False, None
+
+ monkeypatch.setattr(
+ "backend.copilot.sdk.service._compress_messages", _mock_compress
+ )
+ session = _make_session(
+ [
+ ChatMessage(role="user", content="older question"),
+ ChatMessage(
+ role="assistant",
+ content="Skipped: daily usage limit reached",
+ metadata={"hidden_from_model": True},
+ ),
+ ChatMessage(role="user", content="new question"),
+ ]
+ )
+ result, _ = await _build_query_message(
+ "new question",
+ session,
+ use_resume=False,
+ transcript_msg_count=0,
+ session_id="test-session",
+ )
+ assert "older question" in result
+ assert "Skipped" not in result
+
+
@pytest.mark.asyncio
async def test_build_query_resume_zero_msg_count():
"""With --resume but transcript_msg_count=0, return raw message."""
diff --git a/autogpt_platform/backend/backend/copilot/sdk/service.py b/autogpt_platform/backend/backend/copilot/sdk/service.py
index 6b93a5caf2..19347e86ee 100644
--- a/autogpt_platform/backend/backend/copilot/sdk/service.py
+++ b/autogpt_platform/backend/backend/copilot/sdk/service.py
@@ -112,6 +112,7 @@ from ..constants import (
from ..session_cleanup import prune_orphan_tool_calls
from ..context import encode_cwd_for_cli, get_workspace_manager
from ..graphiti.config import is_enabled_for_user
+from ..hidden_rows import visible_to_model
from ..model_normalize import normalize_model_for_transport
from backend.data.llm_registry.llm_models import MODEL_DATE_SUFFIX_RE
@@ -3100,7 +3101,9 @@ def _expect_pre_query_compaction(
return _NO_COMPACTION
if target_tokens is not None and target_tokens <= _BARE_MESSAGE_TOKEN_FLOOR:
return _NO_COMPACTION
- source = prior_messages if prior_messages is not None else prior
+ source = visible_to_model(
+ prior_messages if prior_messages is not None else prior
+ )
return _will_compact(source, model)
if transcript_msg_count <= 0:
# ``use_resume`` with no covered rows compresses nothing.
@@ -3114,14 +3117,14 @@ def _expect_pre_query_compaction(
for m in prior
if m.sequence is not None and m.sequence >= transcript_msg_count
]
- return _will_compact(window_gap, model)
+ return _will_compact(visible_to_model(window_gap), model)
if transcript_msg_count < session_msg_ceiling - 1:
if transcript_msg_count > len(prior):
return _NO_COMPACTION
if prior[transcript_msg_count - 1].role != "assistant":
# Misaligned watermark — _build_query_message skips the gap.
return _NO_COMPACTION
- return _will_compact(prior[transcript_msg_count:], model)
+ return _will_compact(visible_to_model(prior[transcript_msg_count:]), model)
# Scenario A: --resume covers the full context; nothing is compressed.
return _NO_COMPACTION
@@ -3469,7 +3472,9 @@ async def _build_query_message(
window_start_seq,
e,
)
- gap = hole + window_gap
+ # Rows posted for the user only drop out here, after the
+ # sequence slicing above has counted them.
+ gap = visible_to_model(hole + window_gap)
compressed, _was_compressed, stats = await _compress_messages(
gap, target_tokens
)
@@ -3516,7 +3521,7 @@ async def _build_query_message(
msg_count,
)
return current_message, compaction_stats
- gap = prior[transcript_msg_count:]
+ gap = visible_to_model(prior[transcript_msg_count:])
compressed, _was_compressed, stats = await _compress_messages(
gap, target_tokens
)
@@ -3575,7 +3580,9 @@ async def _build_query_message(
)
return current_message, compaction_stats
- source = prior_messages if prior_messages is not None else prior
+ source = visible_to_model(
+ prior_messages if prior_messages is not None else prior
+ )
logger.warning(
"[SDK] [%s] No --resume for %d-message session — compressing context "
"(source=%s, target_tokens=%s)",
@@ -4480,7 +4487,10 @@ async def _seed_transcript(
return "", transcript_covers_prefix, transcript_msg_count
_prior = session.messages[: msg_ceiling - 1]
- _comp, _, _ = await _compress_messages(_prior, _SEED_TARGET_TOKENS)
+ # The returned watermark still counts the rows hidden from the model.
+ _comp, _, _ = await _compress_messages(
+ visible_to_model(_prior), _SEED_TARGET_TOKENS
+ )
if not _comp:
return "", transcript_covers_prefix, transcript_msg_count
diff --git a/autogpt_platform/backend/backend/copilot/sdk/service_helpers_test.py b/autogpt_platform/backend/backend/copilot/sdk/service_helpers_test.py
index 0d63e1b811..e3f8e1e2a1 100644
--- a/autogpt_platform/backend/backend/copilot/sdk/service_helpers_test.py
+++ b/autogpt_platform/backend/backend/copilot/sdk/service_helpers_test.py
@@ -1995,6 +1995,17 @@ def _seq_msg(role: str, content: str, sequence: int) -> ChatMessage:
return ChatMessage(role=role, content=content, sequence=sequence)
+def _hidden_note(sequence: int) -> ChatMessage:
+ """A scheduled chat's note: in the history, never sent to the model, so
+ never compacted either. Big enough to trip compaction on its own."""
+ return ChatMessage(
+ role="assistant",
+ content="word " * 300_000,
+ sequence=sequence,
+ metadata={"hidden_from_model": True},
+ )
+
+
def _big_history(n: int = 10) -> list[ChatMessage]:
"""Alternating user/assistant rows whose total comfortably exceeds the
gpt-4o compression target (see TestWillCompact)."""
@@ -2206,6 +2217,31 @@ def _make_session(messages: list[ChatMessage]) -> ChatSession:
_DIFFERENTIAL_CASES: list[dict] = [
# name, use_resume, transcript_msg_count, messages, prior_messages
+ {
+ "name": "no-resume, only a hidden note is big",
+ "use_resume": False,
+ "transcript_msg_count": 0,
+ "messages": [
+ _seq_msg("user", "hi", 0),
+ _hidden_note(1),
+ _seq_msg("assistant", "hello", 2),
+ ],
+ "prior_messages": None,
+ },
+ {
+ "name": "resume, only a hidden note is big in the gap",
+ "use_resume": True,
+ "transcript_msg_count": 2,
+ "messages": [
+ _seq_msg("user", "hi", 0),
+ _seq_msg("assistant", "hello", 1),
+ _hidden_note(2),
+ _seq_msg("user", "again", 3),
+ _seq_msg("assistant", "done", 4),
+ _seq_msg("user", "and now", 5),
+ ],
+ "prior_messages": None,
+ },
{
"name": "no-resume, full db history",
"use_resume": False,
diff --git a/autogpt_platform/backend/backend/copilot/session_message_test.py b/autogpt_platform/backend/backend/copilot/session_message_test.py
new file mode 100644
index 0000000000..35f54bf38f
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/session_message_test.py
@@ -0,0 +1,151 @@
+"""Integration tests for append_session_message (notes posted between turns)."""
+
+import logging
+from datetime import datetime, timezone
+from uuid import uuid4
+
+import pytest
+from prisma.errors import UniqueViolationError
+from prisma.models import ChatMessage, ChatSession, User
+
+from backend.copilot import db as copilot_db
+from backend.copilot.model import get_chat_session
+from backend.copilot.scheduled_chats.notices import post_notice, skip_notice
+from backend.copilot.turn_queue import TurnRefusal
+from backend.util.test import SpinTestServer
+
+logger = logging.getLogger(__name__)
+
+
+async def _create_user(user_id: str) -> None:
+ try:
+ await User.prisma().create(
+ data={
+ "id": user_id,
+ "email": f"session-message-{user_id}@example.com",
+ "name": "Session Message Test",
+ }
+ )
+ except UniqueViolationError:
+ pass
+
+
+async def _create_session(user_id: str) -> str:
+ created = await copilot_db.create_chat_session(
+ session_id=str(uuid4()), user_id=user_id
+ )
+ return created.session_id
+
+
+async def _cleanup(user_id: str) -> None:
+ try:
+ await User.prisma().delete_many(where={"id": user_id})
+ except Exception as exc:
+ logger.warning("cleanup for %s failed: %s", user_id, exc)
+
+
[email protected](loop_scope="session")
+async def test_a_note_lands_in_the_named_chat_once(server: SpinTestServer):
+ user_id = f"session-message-{uuid4()}"
+ await _create_user(user_id)
+ try:
+ session_id = await _create_session(user_id)
+ message_id = str(uuid4())
+ metadata = {"kind": "scheduled_chat_notice", "hidden_from_model": True}
+
+ assert await copilot_db.append_session_message(
+ session_id=session_id,
+ user_id=user_id,
+ content="Skipped: daily usage limit reached.",
+ message_id=message_id,
+ metadata=metadata,
+ )
+ # A second skip in the same window carries the same id: nothing more.
+ assert not await copilot_db.append_session_message(
+ session_id=session_id,
+ user_id=user_id,
+ content="Skipped: daily usage limit reached.",
+ message_id=message_id,
+ metadata=metadata,
+ )
+
+ rows = await ChatMessage.prisma().find_many(where={"sessionId": session_id})
+ assert [(r.id, r.role, r.metadata) for r in rows] == [
+ (message_id, "assistant", metadata)
+ ]
+ # The chat page reads the session back with the note in it, not a
+ # cached copy from before it was written.
+ session = await get_chat_session(session_id, user_id)
+ assert session is not None
+ assert [m.content for m in session.messages] == [
+ "Skipped: daily usage limit reached."
+ ]
+ finally:
+ await _cleanup(user_id)
+
+
[email protected](loop_scope="session")
+async def test_a_note_never_lands_in_someone_elses_chat(server: SpinTestServer):
+ """A note about a chat belongs in that chat or nowhere: no fallback, no
+ new session."""
+ owner = f"session-message-owner-{uuid4()}"
+ other = f"session-message-other-{uuid4()}"
+ await _create_user(owner)
+ await _create_user(other)
+ try:
+ session_id = await _create_session(owner)
+ assert not await copilot_db.append_session_message(
+ session_id=session_id,
+ user_id=other,
+ content="nope",
+ message_id=str(uuid4()),
+ )
+ assert not await copilot_db.append_session_message(
+ session_id=str(uuid4()),
+ user_id=owner,
+ content="nope",
+ message_id=str(uuid4()),
+ )
+ assert await ChatMessage.prisma().count(where={"sessionId": session_id}) == 0
+ finally:
+ await _cleanup(owner)
+ await _cleanup(other)
+
+
[email protected](loop_scope="session")
+async def test_an_autopilot_schedule_without_a_chat_gets_one_note_chat_per_window(
+ server: SpinTestServer,
+):
+ """A skipped AutoPilot schedule that would have opened a fresh chat has
+ no chat of its own yet. Its note opens one, named for the schedule, and a
+ second skip in the same window opens nothing more."""
+ user_id = f"session-message-{uuid4()}"
+ await _create_user(user_id)
+ try:
+ existing = await _create_session(user_id)
+ notice = skip_notice(
+ TurnRefusal(reason="paywalled", kind="no_plan"),
+ title="Morning digest",
+ now=datetime(2026, 10, 19, 9, tzinfo=timezone.utc),
+ run="recurring",
+ )
+ assert notice is not None
+
+ for _ in range(2):
+ await post_notice(
+ notice,
+ user_id=user_id,
+ schedule_key="schedule-1",
+ title="Morning digest",
+ session_id=None,
+ expert_id=None,
+ )
+
+ chats = await ChatSession.prisma().find_many(where={"userId": user_id})
+ opened = [chat for chat in chats if chat.id != existing]
+ assert [chat.title for chat in opened] == ["Morning digest"]
+ notes = await ChatMessage.prisma().find_many(where={"sessionId": opened[0].id})
+ assert [note.content for note in notes] == [notice.content]
+ assert await ChatMessage.prisma().count(where={"sessionId": existing}) == 0
+ finally:
+ await _cleanup(user_id)
diff --git a/autogpt_platform/backend/backend/copilot/sharing/db.py b/autogpt_platform/backend/backend/copilot/sharing/db.py
index 24a776695a..dfe86eadf9 100644
--- a/autogpt_platform/backend/backend/copilot/sharing/db.py
+++ b/autogpt_platform/backend/backend/copilot/sharing/db.py
@@ -29,6 +29,7 @@ from backend.blocks import get_block
from backend.blocks._base import BlockType
from backend.copilot.db import get_chat_messages_paginated
from backend.copilot.expert_kickoff import is_hidden_chat_message
+from backend.copilot.hidden_rows import is_hidden_from_model
from backend.copilot.model import ChatSessionInfo
from backend.copilot.sharing.models import (
ChatShareState,
@@ -353,7 +354,11 @@ async def get_shared_chat_messages_paginated(
messages=[
sanitize_chat_message(message)
for message in page.messages
+ # Hidden control turns, and the platform's notes to the owner: a
+ # scheduled chat's note says what their plan, usage or connections
+ # are, and the shared copy carries no metadata to hide it by.
if not is_hidden_chat_message(message.metadata)
+ and not is_hidden_from_model(message.metadata)
],
has_more=page.has_more,
oldest_sequence=page.oldest_sequence,
diff --git a/autogpt_platform/backend/backend/copilot/sharing/db_test.py b/autogpt_platform/backend/backend/copilot/sharing/db_test.py
index 86d335e7ea..fc54c0b45f 100644
--- a/autogpt_platform/backend/backend/copilot/sharing/db_test.py
+++ b/autogpt_platform/backend/backend/copilot/sharing/db_test.py
@@ -151,6 +151,47 @@ async def test_shared_transcript_omits_hidden_kickoff_messages(
]
+async def test_shared_transcript_omits_the_owners_scheduled_chat_notes(
+ mock_prisma_calls,
+) -> None:
+ """A note says what the owner's plan, usage or connections are. The
+ shared copy carries no metadata, so the viewer would see it as a reply."""
+ mock_prisma_calls["session"].return_value.find_first = AsyncMock(
+ return_value=_mock_session()
+ )
+ page = SimpleNamespace(
+ messages=[
+ ChatMessage(
+ id="note",
+ role="assistant",
+ content="Skipped: no plan",
+ sequence=0,
+ metadata={"kind": "scheduled_chat_notice", "hidden_from_model": True},
+ ),
+ ChatMessage(
+ id="visible",
+ role="assistant",
+ content="Here is today's briefing",
+ sequence=1,
+ ),
+ ],
+ has_more=False,
+ oldest_sequence=0,
+ )
+
+ with patch(
+ "backend.copilot.sharing.db.get_chat_messages_paginated",
+ new=AsyncMock(return_value=page),
+ ):
+ result = await get_shared_chat_messages_paginated("token-A")
+
+ assert result is not None
+ assert [message.content for message in result.messages] == [
+ "Here is today's briefing"
+ ]
+
+
@pytest.fixture()
def mock_transaction():
with patch("backend.copilot.sharing.db.transaction", return_value=_TxStub()) as m:
diff --git a/autogpt_platform/backend/backend/copilot/tools/expert_chats.py b/autogpt_platform/backend/backend/copilot/tools/expert_chats.py
index 67d7ee78c4..f42de4f0d5 100644
--- a/autogpt_platform/backend/backend/copilot/tools/expert_chats.py
+++ b/autogpt_platform/backend/backend/copilot/tools/expert_chats.py
@@ -11,6 +11,7 @@ import logging
from typing import Any
from backend.copilot.expert_kickoff import is_hidden_chat_message
+from backend.copilot.hidden_rows import is_hidden_from_model
from backend.copilot.model import ChatMessage, ChatSession
from backend.copilot.service import strip_injected_context_for_display
from backend.data.db_accessors import chat_db, experts_db
@@ -340,10 +341,13 @@ def _render(
Mirrors the chat API's own read path: control turns the UI hides stay
hidden, and the server-injected ``<…_context>`` prefixes are stripped
- from user rows.
+ from user rows. The platform's notes to the owner are left out too: this
+ goes to a model, and no model reads those back.
"""
if message.sequence is None or is_hidden_chat_message(message.metadata):
return None
+ if is_hidden_from_model(message.metadata):
+ return None
if message.role == "tool" and not include_tool_results:
return None
if message.role not in ("user", "assistant", "tool"):
diff --git a/autogpt_platform/backend/backend/copilot/tools/expert_chats_test.py b/autogpt_platform/backend/backend/copilot/tools/expert_chats_test.py
index ff57160dca..2b12a61014 100644
--- a/autogpt_platform/backend/backend/copilot/tools/expert_chats_test.py
+++ b/autogpt_platform/backend/backend/copilot/tools/expert_chats_test.py
@@ -335,6 +335,26 @@ class TestReadRendering:
assert result.messages[0].content == "real question"
assert "[called: run_agent]" in result.messages[1].content
+ @pytest.mark.asyncio
+ async def test_the_platforms_notes_to_the_owner_are_left_out(self) -> None:
+ db = _FakeChatDB(
+ messages=[
+ _msg(
+ 1,
+ "assistant",
+ "Paused: Discord monitor can't use Discord",
+ metadata={
+ "kind": "scheduled_chat_notice",
+ "hidden_from_model": True,
+ },
+ ),
+ _msg(2, "assistant", "Posted the summary"),
+ ]
+ )
+ result = await _read(db)
+ assert isinstance(result, ExpertChatTranscriptResponse)
+ assert [m.sequence for m in result.messages] == [2]
+
@pytest.mark.asyncio
async def test_tool_output_is_available_on_request(self) -> None:
db = _FakeChatDB(messages=[_msg(1, "tool", "bulk", tool_call_id="c1")])
diff --git a/autogpt_platform/backend/backend/copilot/transcript.py b/autogpt_platform/backend/backend/copilot/transcript.py
index 936f8723cb..8a25acc270 100644
--- a/autogpt_platform/backend/backend/copilot/transcript.py
+++ b/autogpt_platform/backend/backend/copilot/transcript.py
@@ -29,6 +29,7 @@ from backend.util.clients import get_openai_client
from backend.util.prompt import CompressResult, compress_context
from backend.util.workspace_storage import GCSWorkspaceStorage, get_workspace_storage
+from .hidden_rows import visible_to_model
from .model import ChatMessage
logger = logging.getLogger(__name__)
@@ -1054,9 +1055,9 @@ async def extract_context_messages(
preserving structured ``tool_calls``.
Falls back to full prior messages (``session_messages[:-1]``) when no
- transcript is available. Excludes ``role="reasoning"`` rows. The
- current user turn at ``session_messages[-1]`` is excluded — callers append
- it themselves.
+ transcript is available. Excludes ``role="reasoning"`` rows, and rows
+ posted for the user only (``hidden_rows``). The current user turn at
+ ``session_messages[-1]`` is excluded — callers append it themselves.
"""
# Drop reasoning rows — their content lives in transcript paths,
# not the public turn list. Queue lifecycle is tracked on the
@@ -1066,10 +1067,10 @@ async def extract_context_messages(
prior = session_messages[:-1]
if download is None:
- return prior
+ return visible_to_model(prior)
transcript_msgs = _parse_transcript_to_messages(download)
if transcript_msgs is None:
- return prior
+ return visible_to_model(prior)
gap = detect_gap(download, session_messages)
hole: list[ChatMessage] = []
@@ -1077,7 +1078,8 @@ async def extract_context_messages(
hole = await fill_hole_between_transcript_and_gap(
session_id, download.message_count, gap
)
- return transcript_msgs + hole + gap
+ # After the watermark slicing above, which counts hidden rows too.
+ return transcript_msgs + visible_to_model(hole + gap)
async def delete_transcript(user_id: str, session_id: str) -> None:
diff --git a/autogpt_platform/backend/backend/copilot/transcript_test.py b/autogpt_platform/backend/backend/copilot/transcript_test.py
index 4bc75ceea7..c3120eb274 100644
--- a/autogpt_platform/backend/backend/copilot/transcript_test.py
+++ b/autogpt_platform/backend/backend/copilot/transcript_test.py
@@ -1869,6 +1869,32 @@ class TestExtractContextMessages:
"assistant", # gap assistant-7
]
+ @pytest.mark.asyncio
+ async def test_a_note_for_the_user_is_not_context_without_a_transcript(self):
+ """A skipped-run card posted between turns stays out of the model's
+ history, whichever way the history is built."""
+ messages = _msgs("user", "assistant", "assistant", "user")
+ messages[2].metadata = {"hidden_from_model": True}
+
+ result = await extract_context_messages(None, messages)
+
+ assert [m.content for m in result] == ["user-0", "assistant-1"]
+
+ @pytest.mark.asyncio
+ async def test_a_note_for_the_user_in_the_gap_is_dropped_after_slicing(self):
+ """The watermark counts the hidden row, so dropping it before the gap
+ is sliced would shift the gap and lose a real message."""
+ transcript_content = _make_valid_transcript("user", "assistant")
+ dl = TranscriptDownload(
+ content=transcript_content.encode("utf-8"), message_count=2, mode="sdk"
+ )
+ messages = _msgs("user", "assistant", "assistant", "user", "assistant", "user")
+ messages[2].metadata = {"hidden_from_model": True}
+
+ result = await extract_context_messages(dl, messages)
+
+ assert [m.content for m in result[2:]] == ["user-3", "assistant-4"]
+
# ---------------------------------------------------------------------------
# cli_session_cost_usd
diff --git a/autogpt_platform/backend/backend/copilot/turn_queue.py b/autogpt_platform/backend/backend/copilot/turn_queue.py
index 9bba285d4f..01a4f657ab 100644
--- a/autogpt_platform/backend/backend/copilot/turn_queue.py
+++ b/autogpt_platform/backend/backend/copilot/turn_queue.py
@@ -31,6 +31,7 @@ cancels manually.
import logging
import uuid
+from datetime import datetime
from typing import Any, Literal, Mapping
from prisma.errors import UniqueViolationError
@@ -807,10 +808,21 @@ def _promotion_permissions(
)
+TurnRefusalKind = Literal["banned", "codex_access", "no_plan", "usage", "outage"]
+
+
class TurnRefusal(BaseModel):
reason: str
+ # What the owner could do about it, for callers that tell them: reconnect
+ # the Codex route, choose a plan, wait for the usage window, or nothing
+ # (a banned account, or an outage on our side).
+ kind: TurnRefusalKind
# The usage store was unreadable: an outage, not the user's state.
transient: bool = False
+ # Usage refusals only: the window that ran out ("daily", "weekly" or
+ # "trial") and when it resets.
+ window: str | None = None
+ resets_at: datetime | None = None
async def turn_refusal(
@@ -824,15 +836,15 @@ async def turn_refusal(
an unknown means.
"""
if await is_user_banned(user_id):
- return TurnRefusal(reason="is banned")
+ return TurnRefusal(reason="is banned", kind="banned")
if llm_auth_provider == "codex":
if await has_codex_access(user_id):
return None
- return TurnRefusal(reason="lacks Codex entitlement")
+ return TurnRefusal(reason="lacks Codex entitlement", kind="codex_access")
if llm_auth_provider != "platform":
return None
if await is_user_paywalled(user_id):
- return TurnRefusal(reason="paywalled")
+ return TurnRefusal(reason="paywalled", kind="no_plan")
cfg = ChatConfig()
try:
daily_limit, weekly_limit, usage_tier = await get_global_rate_limits(
@@ -847,7 +859,14 @@ async def turn_refusal(
expected_tier=usage_tier,
)
except RateLimitExceeded as exc:
- return TurnRefusal(reason=f"rate-limited ({exc})")
+ return TurnRefusal(
+ reason=f"rate-limited ({exc})",
+ kind="usage",
+ window=exc.window,
+ resets_at=exc.resets_at,
+ )
except RateLimitUnavailable:
- return TurnRefusal(reason="has unreadable usage limits", transient=True)
+ return TurnRefusal(
+ reason="has unreadable usage limits", kind="outage", transient=True
+ )
return None
diff --git a/autogpt_platform/backend/backend/copilot/turn_queue_test.py b/autogpt_platform/backend/backend/copilot/turn_queue_test.py
index b395d70ee1..bfb07495e8 100644
--- a/autogpt_platform/backend/backend/copilot/turn_queue_test.py
+++ b/autogpt_platform/backend/backend/copilot/turn_queue_test.py
@@ -1098,7 +1098,7 @@ async def test_a_banned_owner_is_refused_on_every_route(route) -> None:
):
refusal = await turn_queue.turn_refusal("u1", route)
- assert refusal == turn_queue.TurnRefusal(reason="is banned")
+ assert refusal == turn_queue.TurnRefusal(reason="is banned", kind="banned")
@pytest.mark.asyncio
diff --git a/autogpt_platform/backend/backend/data/db_manager.py b/autogpt_platform/backend/backend/data/db_manager.py
index 245e9edb11..c1a78f3260 100644
--- a/autogpt_platform/backend/backend/data/db_manager.py
+++ b/autogpt_platform/backend/backend/data/db_manager.py
@@ -780,6 +780,8 @@ class DatabaseManager(AppService):
# Exposed so the Prisma-less scheduler process can compose, store and
# post a briefing via db_accessors / the DatabaseManager RPC.
append_plain_session_message = _(chat_db.append_plain_session_message)
+ # And to tell a scheduled chat why its run was skipped, in that chat.
+ append_session_message = _(chat_db.append_session_message)
create_briefing = _(create_briefing)
get_briefing_for_date = _(get_briefing_for_date)
get_latest_briefings = _(get_latest_briefings)
@@ -992,6 +994,7 @@ class DatabaseManagerAsyncClient(AppServiceClient):
# ============ Morning Briefing ============ #
append_plain_session_message = d.append_plain_session_message
+ append_session_message = d.append_session_message
create_briefing = d.create_briefing
get_briefing_for_date = d.get_briefing_for_date
get_latest_briefings = d.get_latest_briefings
diff --git a/autogpt_platform/backend/backend/data/db_manager_test.py b/autogpt_platform/backend/backend/data/db_manager_test.py
index 4a1a8a6ea1..adafd1566b 100644
--- a/autogpt_platform/backend/backend/data/db_manager_test.py
+++ b/autogpt_platform/backend/backend/data/db_manager_test.py
@@ -52,3 +52,11 @@ def test_memory_schedule_rpc_request_schemas_are_constructible() -> None:
def test_the_audience_consumer_can_read_the_opt_out() -> None:
assert hasattr(DatabaseManager, "is_marketing_opted_out")
assert hasattr(DatabaseManagerAsyncClient, "is_marketing_opted_out")
+
+
+def test_the_scheduler_can_post_a_note_into_a_chat() -> None:
+ """The scheduler has no Prisma of its own; a skipped run's note goes
+ through this RPC."""
+ assert hasattr(DatabaseManagerAsyncClient, "append_session_message")
+ manager = DatabaseManager()
+ manager._create_fastapi_endpoint(manager.append_session_message)
diff --git a/autogpt_platform/backend/backend/executor/scheduler.py b/autogpt_platform/backend/backend/executor/scheduler.py
index 9ad7a1dc33..a2bbb3c5e4 100644
--- a/autogpt_platform/backend/backend/executor/scheduler.py
+++ b/autogpt_platform/backend/backend/executor/scheduler.py
@@ -1,5 +1,6 @@
import asyncio
import concurrent.futures
+import functools
import hashlib
import logging
import os
@@ -88,6 +89,12 @@ from backend.copilot.graphiti.scope import MemoryScope
from backend.copilot.model import ChatSessionInfo, create_chat_session, get_chat_session
from backend.copilot.optimize_blocks import optimize_block_descriptions
from backend.copilot.permissions import CopilotPermissions, routine_disabled_tools
+from backend.copilot.scheduled_chats.notices import (
+ SkippedRun,
+ post_notice,
+ schedule_title,
+ skip_notice,
+)
from backend.copilot.session_permissions import resolve_session_permissions
from backend.copilot.transports import resolve_default_chat_route
from backend.copilot.turn_queue import TurnRefusal, turn_refusal
@@ -539,7 +546,7 @@ async def _execute_copilot_turn(**kwargs):
llm_auth_provider, llm_credential_id = await resolve_default_chat_route(
args.user_id
)
- if await _refuse_if_turn_may_not_start(args, llm_auth_provider):
+ if await _refuse_if_turn_may_not_start(args, llm_auth_provider, routine):
return
new_session = await create_chat_session(
args.user_id,
@@ -630,7 +637,7 @@ async def _execute_copilot_turn(**kwargs):
await _skip_inactive_expert_scope(args, expert_status)
return
if await _refuse_if_turn_may_not_start(
- args, session.metadata.llm_auth_provider
+ args, session.metadata.llm_auth_provider, routine
):
return
target_session_id = args.session_id
@@ -742,7 +749,9 @@ async def _execute_copilot_turn(**kwargs):
async def _refuse_if_turn_may_not_start(
- job_args: "CopilotTurnJobArgs", llm_auth_provider: CopilotLlmAuthProvider
+ job_args: "CopilotTurnJobArgs",
+ llm_auth_provider: CopilotLlmAuthProvider,
+ routine: ExpertRoutine | None,
) -> bool:
"""Refuse a fire that may not start, as ``dispatch_next_for_user`` refuses
a queued turn, and say whether it did: the owner has no access to the route
@@ -750,9 +759,11 @@ async def _refuse_if_turn_may_not_start(
A cron schedule stays registered and resumes once the owner has access or
the window resets. APScheduler drops a one-shot once it fires, so one
- refused by an outage (unreadable usage limits or plan) is retried, and any
+ refused by an outage (unreadable usage limits or plan) is retried, one
+ refused by a daily or weekly limit waits for that limit to reset, and any
other is dropped with its routine switched off rather than left pending for
- a time that has passed.
+ a time that has passed. Unless it was our outage, the chat says why
+ (SECRT-2879).
"""
retry = None
try:
@@ -763,28 +774,87 @@ async def _refuse_if_turn_may_not_start(
# Unknown access is no access: skip the fire, and retry a one-shot.
refusal = TurnRefusal(
reason=f"has an unreadable plan ({type(exc).__name__}: {exc})",
+ kind="outage",
transient=True,
)
retry = _reschedule_one_shot_after_plan_unreadable
if refusal is None:
return False
+ waits = refusal.kind == "usage" and refusal.window in ("daily", "weekly")
+ if waits:
+ retry = functools.partial(
+ _reschedule_one_shot_after_usage, resets_at=refusal.resets_at
+ )
+ run: SkippedRun
if job_args.run_at is None:
- outcome = "the schedule stays registered"
+ run, outcome = "recurring", "the schedule stays registered"
elif retry is None:
await _drop_job_from_routine(job_args)
- outcome = "the one-shot is dropped"
+ run, outcome = "dropped", "the one-shot is dropped"
elif await retry(job_args):
- outcome = "the one-shot is retried"
+ run = "waits_for_reset"
+ outcome = (
+ "the one-shot waits for the limit to reset"
+ if waits
+ else "the one-shot is retried"
+ )
else:
- outcome = "the one-shot is dropped"
+ run, outcome = "dropped", "the one-shot is dropped"
logger.log(
logging.WARNING if refusal.transient else logging.INFO,
f"Skipping scheduled copilot turn {job_args.schedule_id}: owner "
f"{refusal.reason}; {outcome}",
)
+ if not refusal.transient:
+ await _tell_owner_why_skipped(job_args, routine, refusal, run=run)
return True
+async def _tell_owner_why_skipped(
+ args: "CopilotTurnJobArgs",
+ routine: ExpertRoutine | None,
+ refusal: TurnRefusal,
+ *,
+ run: SkippedRun,
+) -> None:
+ """Best effort, and bounded: a note that cannot be posted must not hold up
+ the scheduler's thread, and the skip itself already happened."""
+ schedule_key = args.routine_id or args.routine_schedule_id or args.schedule_id
+ if schedule_key is None:
+ return
+ title = schedule_title(
+ routine_title=routine.title if routine is not None else None,
+ message=args.message,
+ )
+ notice = skip_notice(
+ refusal,
+ title=title,
+ now=datetime.now(tz=timezone.utc),
+ run=run,
+ user_timezone=args.user_timezone,
+ )
+ if notice is None:
+ return
+ try:
+ await asyncio.wait_for(
+ post_notice(
+ notice,
+ user_id=args.user_id,
+ schedule_key=schedule_key,
+ title=title,
+ session_id=args.session_id,
+ expert_id=args.expert_id,
+ ),
+ timeout=_NOTICE_TIMEOUT_SECONDS,
+ )
+ except Exception:
+ logger.warning(
+ f"Could not tell the owner why scheduled copilot turn "
+ f"{args.schedule_id} was skipped",
+ exc_info=True,
+ )
+
+
def _credential_pins_for_turn(
args: "CopilotTurnJobArgs", routine: ExpertRoutine | None
) -> CredentialPins:
@@ -819,13 +889,23 @@ _MAX_CAP_RETRIES = 1
_MAX_EXPERT_LOOKUP_RETRIES = 1
_MAX_PLAN_LOOKUP_RETRIES = 1
_MAX_LIMITS_RETRIES = 1
-_RetryKind = Literal["cap", "expert_lookup", "plan_lookup", "limits"]
+# A one-shot refused by a used-up limit waits for the reset rather than being
+# dropped. Twice, because the daily reset can still find the week used up.
+_MAX_USAGE_WAITS = 2
+# Spreads the one-shots waiting for one reset over a few minutes, rather than
+# firing them all on the stroke of midnight.
+_USAGE_WAIT_SPREAD_SECONDS = 300
+_RetryKind = Literal["cap", "expert_lookup", "plan_lookup", "limits", "usage"]
_MAX_RETRIES: dict[_RetryKind, int] = {
"cap": _MAX_CAP_RETRIES,
"expert_lookup": _MAX_EXPERT_LOOKUP_RETRIES,
"plan_lookup": _MAX_PLAN_LOOKUP_RETRIES,
"limits": _MAX_LIMITS_RETRIES,
+ "usage": _MAX_USAGE_WAITS,
}
+# How long a skipped run may spend telling its chat why. It holds a pooled
+# scheduler worker meanwhile, and the skip itself has already happened.
+_NOTICE_TIMEOUT_SECONDS = 10
async def _reschedule_one_shot_after_cap(args: "CopilotTurnJobArgs") -> None:
@@ -870,12 +950,30 @@ async def _reschedule_one_shot_after_expert_unavailable(
)
+async def _reschedule_one_shot_after_usage(
+ args: "CopilotTurnJobArgs", *, resets_at: datetime | None
+) -> bool:
+ """Move a one-shot refused by a used-up limit to when that limit resets."""
+ if resets_at is None:
+ return False
+ key = args.routine_schedule_id or args.schedule_id or args.message
+ spread = int(hashlib.sha256(key.encode()).hexdigest(), 16)
+ return await _reschedule_one_shot(
+ args,
+ reason="used-up usage limit",
+ name_suffix="usage-wait",
+ retry_kind="usage",
+ run_at=resets_at + timedelta(seconds=spread % _USAGE_WAIT_SPREAD_SECONDS),
+ )
+
+
async def _reschedule_one_shot(
args: "CopilotTurnJobArgs",
*,
reason: str,
name_suffix: str,
retry_kind: _RetryKind,
+ run_at: datetime | None = None,
) -> bool:
"""Re-create a one-shot copilot-turn schedule after a transient failure,
and say whether it did.
@@ -884,27 +982,31 @@ async def _reschedule_one_shot(
retried the limit for this failure kind are dropped to avoid loops. Retry
depths round-trip independently through APScheduler's persisted kwargs so
a transient expert lookup does not consume the concurrency-cap budget.
+ The retry fires a few minutes out, or at *run_at* when given.
"""
counts: dict[_RetryKind, int] = {
"cap": args.cap_retry_count,
"expert_lookup": args.expert_lookup_retry_count,
"plan_lookup": args.plan_lookup_retry_count,
"limits": args.limits_retry_count,
+ "usage": args.usage_wait_count,
}
retry_count = counts[retry_kind]
max_retries = _MAX_RETRIES[retry_kind]
counts[retry_kind] = retry_count + 1
if retry_count >= max_retries:
- logger.error(
+ logger.log(
+ # A limit that is still used up is the owner's state, not a fault.
+ logging.INFO if retry_kind == "usage" else logging.ERROR,
f"Dropping one-shot copilot turn for session "
f"{_session_id_label(args)} — exhausted {max_retries} "
- f"retry/retries after {reason}"
+ f"retry/retries after {reason}",
)
await _drop_job_from_routine(args)
return False
try:
- new_run_at = datetime.now(tz=timezone.utc) + timedelta(
+ new_run_at = run_at or datetime.now(tz=timezone.utc) + timedelta(
seconds=_CONCURRENCY_RETRY_DELAY_SECONDS
)
await get_scheduler_client().add_copilot_turn_schedule(
@@ -917,6 +1019,7 @@ async def _reschedule_one_shot(
expert_lookup_retry_count=counts["expert_lookup"],
plan_lookup_retry_count=counts["plan_lookup"],
limits_retry_count=counts["limits"],
+ usage_wait_count=counts["usage"],
# Preserve the user's timezone across the reschedule so the new
# one-shot job's trigger/timezone matches the original request.
user_timezone=args.user_timezone,
@@ -2373,6 +2476,8 @@ class CopilotTurnJobArgs(BaseModel):
expert_lookup_retry_count: int = 0
plan_lookup_retry_count: int = 0
limits_retry_count: int = 0
+ # How often a one-shot has already waited for a used-up limit to reset.
+ usage_wait_count: int = 0
# Persisted so ``_reschedule_one_shot_after_cap`` can preserve the user's
# timezone when re-creating a one-shot job after a concurrency-cap miss —
# otherwise the rescheduled job's trigger defaults to UTC and the timezone
@@ -3195,6 +3300,7 @@ class Scheduler(AppService):
routine_id: str | None = None,
credential_pins: CredentialPins | None = None,
routine_schedule_id: str | None = None,
+ usage_wait_count: int = 0,
purpose: Literal["followup", "resume", "send"] = "followup",
schedule_id: str | None = None,
created_at: datetime | None = None,
@@ -3247,6 +3353,7 @@ class Scheduler(AppService):
expert_lookup_retry_count=expert_lookup_retry_count,
plan_lookup_retry_count=plan_lookup_retry_count,
limits_retry_count=limits_retry_count,
+ usage_wait_count=usage_wait_count,
user_timezone=user_timezone,
organization_id=organization_id,
team_id=team_id,
diff --git a/autogpt_platform/backend/backend/executor/scheduler_unit_test.py b/autogpt_platform/backend/backend/executor/scheduler_unit_test.py
index 637cf1a5fc..09ece8e402 100644
--- a/autogpt_platform/backend/backend/executor/scheduler_unit_test.py
+++ b/autogpt_platform/backend/backend/executor/scheduler_unit_test.py
@@ -37,6 +37,8 @@ from backend.executor.scheduler import (
_MAX_EXPERT_LOOKUP_RETRIES,
_MAX_LIMITS_RETRIES,
_MAX_PLAN_LOOKUP_RETRIES,
+ _MAX_USAGE_WAITS,
+ _USAGE_WAIT_SPREAD_SECONDS,
CopilotTurnJobArgs,
CopilotTurnJobInfo,
GraphExecutionJobArgs,
@@ -112,6 +114,15 @@ def owner_gate(monkeypatch: pytest.MonkeyPatch) -> _OwnerGate:
return gate
[email protected](autouse=True)
+def post_notice(monkeypatch: pytest.MonkeyPatch) -> AsyncMock:
+ """The note a skipped run posts into its chat. Patched for every test so
+ none reaches the DatabaseManager, whose client retries for minutes."""
+ post = AsyncMock(return_value=True)
+ monkeypatch.setattr(f"{_SCHEDULER_PATH}.post_notice", post)
+ return post
+
+
# ---------------------------------------------------------------------------
# _build_trigger
# ---------------------------------------------------------------------------
@@ -2772,9 +2783,9 @@ _HOURLY = {"run_at": None, "cron": "9 * * * *"}
("refuse", "timing", "dropped", "budget"),
[
(_paywalled, _ONE_SHOT, [("routine-1", "sched-1")], None),
- (_over_a_cap, _ONE_SHOT, [("routine-1", "sched-1")], None),
- (_limits_unreadable, _ONE_SHOT, [], "limits"),
- (_lookup_fails, _ONE_SHOT, [], "plan_lookup"),
+ (_over_a_cap, _ONE_SHOT, [], "usage_wait_count"),
+ (_limits_unreadable, _ONE_SHOT, [], "limits_retry_count"),
+ (_lookup_fails, _ONE_SHOT, [], "plan_lookup_retry_count"),
(_paywalled, _HOURLY, [], None),
(_limits_unreadable, _HOURLY, [], None),
(_lookup_fails, _HOURLY, [], None),
@@ -2793,8 +2804,9 @@ async def test_a_refused_one_shot_routine_is_retried_or_switched_off(
owner_gate, refuse, timing, dropped, budget
):
"""APScheduler drops a one-shot once it fires. An outage (unreadable limits
- or plan) is ours, so the one-shot comes back in a few minutes; otherwise,
- left on, it would read as pending for a time that has passed."""
+ or plan) is ours, so the one-shot comes back in a few minutes, and a used-up
+ limit has a reset to wait for; otherwise, left on, it would read as pending
+ for a time that has passed."""
refuse(owner_gate)
scheduler_client = AsyncMock()
routine = ExpertRoutine(
@@ -2824,7 +2836,177 @@ async def test_a_refused_one_shot_routine_is_retried_or_switched_off(
if budget is not None:
assert retry.call_args.kwargs["routine_id"] == "routine-1"
assert retry.call_args.kwargs["routine_schedule_id"] == "sched-1"
- assert retry.call_args.kwargs[f"{budget}_retry_count"] == 1
+ assert retry.call_args.kwargs[budget] == 1
+
+
+def _over_the_daily_limit(gate: _OwnerGate, resets_at: datetime) -> None:
+ gate.check_rate_limit.side_effect = RateLimitExceeded("daily", resets_at)
+
+
[email protected]("window", ["daily", "weekly"])
+async def test_a_one_shot_refused_by_a_used_up_limit_waits_for_the_reset(
+ owner_gate, post_notice, window
+):
+ """Nick (2026-10-10): once usage comes back, the run should happen. A
+ one-shot is moved to the reset, spread over a few minutes, and its chat is
+ told when it will run."""
+ resets_at = datetime.now(tz=timezone.utc).replace(microsecond=0) + timedelta(
+ hours=3
+ )
+ owner_gate.check_rate_limit.side_effect = RateLimitExceeded(window, resets_at)
+ scheduler_client = AsyncMock()
+ with patch(
+ f"{_SCHEDULER_PATH}.get_scheduler_client", return_value=scheduler_client
+ ):
+ mocks = await _fire(_args(run_at=_ONE_SHOT["run_at"]))
+
+ mocks["schedule_turn"].assert_not_awaited()
+ kwargs = scheduler_client.add_copilot_turn_schedule.call_args.kwargs
+ assert resets_at <= kwargs["run_at"]
+ assert kwargs["run_at"] < resets_at + timedelta(seconds=_USAGE_WAIT_SPREAD_SECONDS)
+ assert kwargs["usage_wait_count"] == 1
+ notice = post_notice.call_args.args[0]
+ assert notice.body.startswith("“check CI” will run when the limit resets")
+
+
+async def test_a_one_shot_still_over_its_limit_after_waiting_is_dropped(
+ owner_gate, post_notice
+):
+ _over_the_daily_limit(
+ owner_gate, datetime.now(tz=timezone.utc) + timedelta(hours=3)
+ )
+ scheduler_client = AsyncMock()
+ store = MagicMock(get_routine=AsyncMock(return_value=None))
+ store.mark_routine_unscheduled = AsyncMock()
+ with (
+ patch(f"{_SCHEDULER_PATH}.get_scheduler_client", return_value=scheduler_client),
+ patch(f"{_SCHEDULER_PATH}.experts_db", return_value=store),
+ ):
+ await _fire(_args(routine_id="routine-1", usage_wait_count=_MAX_USAGE_WAITS))
+
+ scheduler_client.add_copilot_turn_schedule.assert_not_awaited()
+ store.mark_routine_unscheduled.assert_awaited_once_with("routine-1", "sched-1")
+ assert post_notice.call_args.args[0].body == "“check CI” didn't run."
+
+
+async def _fire(args: CopilotTurnJobArgs) -> dict[str, AsyncMock]:
+ """Fire *args* into its existing chat, with the dispatch mocked."""
+ mocks = {"schedule_turn": AsyncMock()}
+ session = MagicMock(session_id=args.session_id, expert_id=None)
+ session.metadata.llm_auth_provider = "platform"
+ with (
+ patch(f"{_SCHEDULER_PATH}.get_chat_session", AsyncMock(return_value=session)),
+ patch(f"{_SCHEDULER_PATH}.schedule_turn", mocks["schedule_turn"]),
+ ):
+ await _execute_copilot_turn(**args.model_dump(mode="json"))
+ return mocks
+
+
+ "session_id", [None, "session-1"], ids=["fresh-chat", "existing-chat"]
+)
+ ("refuse", "provider", "reason"),
+ [
+ (_paywalled, "platform", "no_plan"),
+ (_over_a_cap, "platform", "usage"),
+ (_lost_codex, "codex", "codex_access"),
+ ],
+ ids=["paywalled", "over-a-cap", "lost-codex"],
+)
+async def test_a_skipped_run_tells_its_chat_why(
+ owner_gate, post_notice, refuse, provider, reason, session_id
+):
+ """SECRT-2879: skipping without a word is what left the trial account's
+ owner with 33 missing runs a day and nothing to say why."""
+ refuse(owner_gate)
+ await _fire_hourly(session_id, provider)
+
+ post_notice.assert_awaited_once()
+ notice = post_notice.call_args.args[0]
+ kwargs = post_notice.call_args.kwargs
+ assert notice.reason == reason
+ assert kwargs["user_id"] == "user-1"
+ assert kwargs["schedule_key"] == "sched-1"
+ assert kwargs["title"] == "check CI"
+ # A fresh-chat schedule has no chat yet; the note goes to its fallback.
+ assert kwargs["session_id"] == session_id
+ assert kwargs["expert_id"] is None
+
+
+ "refuse", [_limits_unreadable, _lookup_fails], ids=["brown-out", "lookup-fails"]
+)
+async def test_a_run_skipped_by_our_outage_tells_nobody(
+ owner_gate, post_notice, refuse
+):
+ refuse(owner_gate)
+ await _fire_hourly("session-1", "platform")
+
+ post_notice.assert_not_awaited()
+
+
+ ("timing", "outcome"),
+ [
+ ({"run_at": None, "cron": "9 * * * *"}, "the schedule stays registered"),
+ ({}, "the one-shot is dropped"),
+ ],
+ ids=["recurring", "one-shot"],
+)
+async def test_a_banned_owners_run_is_skipped_and_its_chat_told_nothing(
+ post_notice, timing, outcome, caplog
+):
+ """Nothing new starts for a banned account: a recurring schedule stays for
+ when the ban is lifted, a one-shot is dropped as a paywalled one is, and
+ nothing is posted into its chats."""
+ with (
+ patch(f"{_TURN_QUEUE_PATH}.is_user_banned", AsyncMock(return_value=True)),
+ caplog.at_level(logging.INFO, logger=_SCHEDULER_PATH),
+ ):
+ mocks = await _fire(_args(**timing))
+
+ mocks["schedule_turn"].assert_not_awaited()
+ post_notice.assert_not_awaited()
+ assert "owner is banned" in caplog.text
+ assert outcome in caplog.text
+
+
+async def test_a_routine_is_named_by_its_title_and_keyed_by_its_id(
+ owner_gate, post_notice
+):
+ _paywalled(owner_gate)
+ routine = ExpertRoutine(
+ id="routine-1", title="Morning briefing", prompt="Brief me.", enabled=True
+ )
+ store = MagicMock(get_routine=AsyncMock(return_value=routine))
+ with patch(f"{_SCHEDULER_PATH}.experts_db", return_value=store):
+ await _fire(_args(routine_id="routine-1", run_at=None, cron="0 6 * * *"))
+
+ kwargs = post_notice.call_args.kwargs
+ assert kwargs["schedule_key"] == "routine-1"
+ assert kwargs["title"] == "Morning briefing"
+
+
+async def test_a_note_that_cannot_be_posted_does_not_fail_the_tick(
+ owner_gate, post_notice, caplog
+):
+ _paywalled(owner_gate)
+ post_notice.side_effect = RuntimeError("database manager down")
+
+ with caplog.at_level(logging.INFO, logger=_SCHEDULER_PATH):
+ mocks = await _fire(_args(run_at=None, cron="9 * * * *"))
+
+ mocks["schedule_turn"].assert_not_awaited()
+ assert "Could not tell the owner why scheduled copilot turn sched-1" in caplog.text
+ assert "the schedule stays registered" in caplog.text
@pytest.mark.asyncio
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/__tests__/ChatMessagesContainer.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/__tests__/ChatMessagesContainer.test.tsx
index 97a4e880ff..9ca31a4570 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/__tests__/ChatMessagesContainer.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/__tests__/ChatMessagesContainer.test.tsx
@@ -1009,6 +1009,41 @@ describe("ChatMessagesContainer — readOnly mode", () => {
},
);
+ it.each([false, true])(
+ "shows a scheduled chat's note to its owner alone (readOnly=%s)",
+ (readOnly) => {
+ render(
+ <ChatMessagesContainer
+ {...baseProps}
+ readOnly={readOnly}
+ messages={[
+ {
+ id: "notice-1",
+ role: "assistant",
+ parts: [
+ { type: "text", text: "Skipped: daily usage limit reached" },
+ ],
+ metadata: {
+ kind: "scheduled_chat_notice",
+ reason: "no_plan",
+ headline: "Skipped: daily usage limit reached",
+ body: "“Briefing” didn't run.",
+ actions: [],
+ },
+ },
+ ]}
+ />,
+ );
+
+ expect(screen.queryAllByTestId("scheduled-chat-notice")).toHaveLength(
+ readOnly ? 0 : 1,
+ );
+ expect(
+ screen.queryAllByText("Skipped: daily usage limit reached"),
+ ).toHaveLength(readOnly ? 0 : 1);
+ },
+ );
+
it("renders no Sent from badge in a read-only transcript", () => {
const messages: Message[] = [
{
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/MessageRow/MessageRow.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/MessageRow/MessageRow.tsx
index 2d953bb349..69a5f5f407 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/MessageRow/MessageRow.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/MessageRow/MessageRow.tsx
@@ -4,6 +4,7 @@ import { Message, MessageContent } from "@/components/ai-elements/message";
import type { TurnStats } from "../../../../helpers/convertChatSessionToUiMessages";
import type { SentFrom } from "../../../../sentFrom";
import { TurnStatsBar } from "../../../JobStatsBar/TurnStatsBar";
+import { ScheduledChatNoticeCard } from "../../../ScheduledChatNoticeCard/ScheduledChatNoticeCard";
import { WorkCard } from "../../../WorkCard/WorkCard";
import { ChainMessageParts } from "../ChainMessageParts";
import { MessageAttachments } from "../MessageAttachments";
@@ -77,6 +78,7 @@ export const MessageRow = memo(function MessageRow({
const {
runMetadata,
runPreview,
+ notice,
renderableParts,
textParts,
copyText,
@@ -111,6 +113,24 @@ export const MessageRow = memo(function MessageRow({
);
}
+ // A scheduled chat whose run was skipped says why, with the fix on a
+ // button. The model never reads this row back, and it is the owner's: a
+ // shared copy of the chat leaves it out.
+ if (notice) {
+ if (readOnly) return null;
+ return (
+ <Message
+ from={message.role}
+ data-message-id={message.id}
+ className="duration-300 animate-in fade-in slide-in-from-bottom-2 fill-mode-both"
+ >
+ <MessageContent className="group-[.is-assistant]:bg-transparent">
+ <ScheduledChatNoticeCard notice={notice} />
+ </MessageContent>
+ </Message>
+ );
+ }
+
const isAssistant = message.role === "assistant";
const showActions =
isLastInTurn &&
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/MessageRow/useMessageRow.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/MessageRow/useMessageRow.ts
index a964a03412..bcdfee08d8 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/MessageRow/useMessageRow.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/MessageRow/useMessageRow.ts
@@ -5,6 +5,7 @@ import {
isSessionOpeningMessage,
type SentFrom,
} from "../../../../sentFrom";
+import { getScheduledChatNotice } from "../../../ScheduledChatNoticeCard/helpers";
import { getWorkRunMetadata, toPreview } from "../../../WorkCard/helpers";
import { deriveLiveCompaction, deriveRowParts, getRunPreview } from "./helpers";
@@ -23,6 +24,7 @@ export function useMessageRow({
}: Args) {
const { role, parts, metadata } = message;
const runMetadata = useMemo(() => getWorkRunMetadata(metadata), [metadata]);
+ const notice = useMemo(() => getScheduledChatNotice(metadata), [metadata]);
const runPreview = useMemo(
() => (runMetadata ? toPreview(getRunPreview(parts)) : ""),
[runMetadata, parts],
@@ -38,5 +40,12 @@ export function useMessageRow({
: (getSentFromMetadata(metadata) ??
(isSessionOpeningMessage(message) ? sessionSentFrom : null));
- return { runMetadata, runPreview, ...rowParts, ...compaction, sentFrom };
+ return {
+ runMetadata,
+ runPreview,
+ notice,
+ ...rowParts,
+ ...compaction,
+ sentFrom,
+ };
}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ScheduledChatNoticeCard/ScheduledChatNoticeCard.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ScheduledChatNoticeCard/ScheduledChatNoticeCard.tsx
new file mode 100644
index 0000000000..40b0bd131e
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ScheduledChatNoticeCard/ScheduledChatNoticeCard.tsx
@@ -0,0 +1,56 @@
+"use client";
+
+import { Button } from "@/components/atoms/Button/Button";
+import { Icon } from "@/components/atoms/Icon/Icon";
+import {
+ Clock01Icon,
+ CreditCardIcon,
+ PlugSocketIcon,
+} from "@hugeicons/core-free-icons";
+import type { IconSvgElement } from "@hugeicons/react";
+import type { ScheduledChatNotice } from "./helpers";
+
+interface Props {
+ notice: ScheduledChatNotice;
+}
+
+const REASON_ICONS: Record<string, IconSvgElement> = {
+ usage: Clock01Icon,
+ no_plan: CreditCardIcon,
+ codex_access: PlugSocketIcon,
+};
+
+export function ScheduledChatNoticeCard({ notice }: Props) {
+ const icon = REASON_ICONS[notice.reason] ?? Clock01Icon;
+ const showActions = notice.actions.length > 0;
+
+ return (
+ <div
+ className="max-w-md rounded-2xl bg-white p-4 ring-1 ring-inset ring-zinc-200/60"
+ data-testid="scheduled-chat-notice"
+ >
+ <div className="flex items-start gap-3">
+ <Icon icon={icon} size={18} className="mt-0.5 shrink-0 text-zinc-400" />
+ <div className="min-w-0">
+ <p className="text-sm font-medium text-zinc-900">{notice.headline}</p>
+ <p className="mt-1 text-sm text-zinc-500">{notice.body}</p>
+ {showActions ? (
+ <div className="mt-3 flex flex-wrap gap-2">
+ {notice.actions.map((action) => (
+ <Button
+ key={action.href}
+ as="NextLink"
+ href={action.href}
+ variant="secondary"
+ size="small"
+ >
+ {action.label}
+ </Button>
+ ))}
+ </div>
+ ) : null}
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ScheduledChatNoticeCard/__tests__/ScheduledChatNoticeCard.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ScheduledChatNoticeCard/__tests__/ScheduledChatNoticeCard.test.tsx
new file mode 100644
index 0000000000..aac22750f8
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ScheduledChatNoticeCard/__tests__/ScheduledChatNoticeCard.test.tsx
@@ -0,0 +1,25 @@
+import { render, screen } from "@/tests/integrations/test-utils";
+import { describe, expect, it } from "vitest";
+import { ScheduledChatNoticeCard } from "../ScheduledChatNoticeCard";
+import type { ScheduledChatNotice } from "../helpers";
+
+const NOTICE: ScheduledChatNotice = {
+ reason: "usage",
+ headline: "Skipped: daily usage limit reached",
+ body: "“Briefing” didn't run. Scheduled chats run again when the limit resets at 00:00 UTC.",
+ actions: [{ kind: "link", label: "Upgrade", href: "/settings/billing" }],
+};
+
+describe("ScheduledChatNoticeCard", () => {
+ it("says why the run was skipped and links to the fix", () => {
+ render(<ScheduledChatNoticeCard notice={NOTICE} />);
+
+ expect(
+ screen.getByText("Skipped: daily usage limit reached"),
+ ).toBeDefined();
+ expect(screen.getByText(/didn't run/)).toBeDefined();
+ expect(
+ screen.getByRole("link", { name: "Upgrade" }).getAttribute("href"),
+ ).toBe("/settings/billing");
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ScheduledChatNoticeCard/__tests__/helpers.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ScheduledChatNoticeCard/__tests__/helpers.test.ts
new file mode 100644
index 0000000000..2a6aa9519e
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ScheduledChatNoticeCard/__tests__/helpers.test.ts
@@ -0,0 +1,47 @@
+import { describe, expect, it } from "vitest";
+import { getScheduledChatNotice } from "../helpers";
+
+const NOTICE = {
+ kind: "scheduled_chat_notice",
+ hidden_from_model: true,
+ reason: "usage",
+ headline: "Skipped: daily usage limit reached",
+ body: "“Briefing” didn't run.",
+ actions: [{ kind: "link", label: "Upgrade", href: "/settings/billing" }],
+};
+
+describe("getScheduledChatNotice", () => {
+ it("reads the note a skipped scheduled chat leaves", () => {
+ expect(getScheduledChatNotice(NOTICE)).toEqual({
+ reason: "usage",
+ headline: "Skipped: daily usage limit reached",
+ body: "“Briefing” didn't run.",
+ actions: [{ kind: "link", label: "Upgrade", href: "/settings/billing" }],
+ });
+ });
+
+ it("ignores any other message", () => {
+ expect(getScheduledChatNotice(undefined)).toBeNull();
+ expect(getScheduledChatNotice({ kind: "expert_run" })).toBeNull();
+ expect(
+ getScheduledChatNotice({ kind: "scheduled_chat_notice", body: "x" }),
+ ).toBeNull();
+ });
+
+ it("keeps only buttons that stay on the platform", () => {
+ const notice = getScheduledChatNotice({
+ ...NOTICE,
+ actions: [
+ { kind: "link", label: "Upgrade", href: "/settings/billing" },
+ { kind: "link", label: "Elsewhere", href: "https://example.com" },
+ { kind: "link", label: "Protocol-relative", href: "//example.com" },
+ { kind: "link", label: "Backslash", href: "/\\example.com" },
+ { kind: "link", label: "Script", href: "javascript:alert(1)" },
+ { kind: "resume", label: "Resume" },
+ "not an action",
+ ],
+ });
+
+ expect(notice?.actions.map((action) => action.label)).toEqual(["Upgrade"]);
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ScheduledChatNoticeCard/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ScheduledChatNoticeCard/helpers.ts
new file mode 100644
index 0000000000..b40273b061
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ScheduledChatNoticeCard/helpers.ts
@@ -0,0 +1,60 @@
+export interface NoticeLinkAction {
+ kind: "link";
+ label: string;
+ href: string;
+}
+
+export interface ScheduledChatNotice {
+ reason: string;
+ headline: string;
+ body: string;
+ actions: NoticeLinkAction[];
+}
+
+const NOTICE_METADATA_KIND = "scheduled_chat_notice";
+
+function asString(value: unknown): string | null {
+ return typeof value === "string" && value.length > 0 ? value : null;
+}
+
+function toLinkAction(value: unknown): NoticeLinkAction | null {
+ if (!value || typeof value !== "object") return null;
+ const action = value as Record<string, unknown>;
+ const label = asString(action.label);
+ const href = asString(action.href);
+ // In-app paths only: the card never sends anyone off the platform.
+ if (action.kind !== "link" || !label || !href) return null;
+ // A backslash reads as a slash to the browser, so /\host leaves too.
+ if (!href.startsWith("/") || href.startsWith("//")) return null;
+ if (href.includes("\\")) return null;
+ return { kind: "link", label, href };
+}
+
+/**
+ * Read the note a skipped scheduled chat leaves in its chat, from the
+ * message's ``metadata`` bag. Returns null for any other message.
+ */
+export function getScheduledChatNotice(
+ value: unknown,
+): ScheduledChatNotice | null {
+ if (!value || typeof value !== "object") return null;
+ const meta = value as Record<string, unknown>;
+ if (meta.kind !== NOTICE_METADATA_KIND) return null;
+
+ const headline = asString(meta.headline);
+ const body = asString(meta.body);
+ if (!headline || !body) return null;
+
+ const actions = Array.isArray(meta.actions)
+ ? meta.actions
+ .map(toLinkAction)
+ .filter((action): action is NoticeLinkAction => action !== null)
+ : [];
+
+ return {
+ reason: asString(meta.reason) ?? "usage",
+ headline,
+ body,
+ actions,
+ };
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/__tests__/convertChatSessionToUiMessages.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/__tests__/convertChatSessionToUiMessages.test.ts
index c2f4f7e1d5..e6442ba90f 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/__tests__/convertChatSessionToUiMessages.test.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/__tests__/convertChatSessionToUiMessages.test.ts
@@ -33,6 +33,35 @@ describe("convertChatSessionMessagesToUiMessages", () => {
expect(result.messages[1].metadata).toMatchObject({ kind: "expert_run" });
});
+ it("keeps a skipped-run note as its own bubble between two replies", () => {
+ const result = convertChatSessionMessagesToUiMessages(
+ SESSION_ID,
+ [
+ { role: "assistant", content: "Here is your briefing.", sequence: 0 },
+ {
+ role: "assistant",
+ content: "Skipped: daily usage limit reached. It didn't run.",
+ sequence: 1,
+ metadata: {
+ kind: "scheduled_chat_notice",
+ hidden_from_model: true,
+ headline: "Skipped: daily usage limit reached",
+ body: "It didn't run.",
+ },
+ },
+ { role: "assistant", content: "Next briefing.", sequence: 2 },
+ ],
+ { isComplete: true },
+ );
+
+ // Folded either way, the card would vanish into a reply.
+ expect(result.messages).toHaveLength(3);
+ expect(result.messages[1].metadata).toMatchObject({
+ kind: "scheduled_chat_notice",
+ });
+ expect(result.messages[2].metadata).toBeUndefined();
+ });
+
it("does not attach metadata to legacy assistant messages", () => {
const result = convertChatSessionMessagesToUiMessages(
SESSION_ID,
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/convertChatSessionToUiMessages.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/convertChatSessionToUiMessages.ts
index bf3c12137c..0289767e6b 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/convertChatSessionToUiMessages.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/convertChatSessionToUiMessages.ts
@@ -37,10 +37,20 @@ interface SessionChatMessage {
metadata: Record<string, unknown> | null;
}
-function getRunMetadata(metadata: unknown): Record<string, unknown> | null {
- return metadata &&
- typeof metadata === "object" &&
- (metadata as Record<string, unknown>).kind === "expert_run"
+// Assistant rows the backend posts on its own, outside any turn: a run-post
+// WorkCard, or the note a skipped scheduled chat leaves. Each is its own bubble
+// so it never reads as part of a neighbouring reply.
+const STANDALONE_METADATA_KINDS = new Set([
+ "expert_run",
+ "scheduled_chat_notice",
+]);
+
+function getStandaloneBubbleMetadata(
+ metadata: unknown,
+): Record<string, unknown> | null {
+ if (!metadata || typeof metadata !== "object") return null;
+ const kind = (metadata as Record<string, unknown>).kind;
+ return typeof kind === "string" && STANDALONE_METADATA_KINDS.has(kind)
? (metadata as Record<string, unknown>)
: null;
}
@@ -460,10 +470,11 @@ export function convertChatSessionMessagesToUiMessages(
// be keyed ``-seq-5``, and a cross-page assistant at seq=7 would fail
// the ``firstSeq === lastSeq + 1`` check (7 !== 5+1) and split into two
// bubbles instead of joining the ongoing turn.
- // A run-post carries structured ``metadata`` the thread renders as a
- // WorkCard. Keep it as its own bubble — never fold it into a neighbouring
- // assistant turn (either direction), or the card loses its identity.
- const runMetadata = getRunMetadata(msg.metadata);
+ // A run-post or a skipped-run note carries structured ``metadata`` the
+ // thread renders as a card. Keep it as its own bubble — never fold it
+ // into a neighbouring assistant turn (either direction), or the card
+ // loses its identity.
+ const standaloneMetadata = getStandaloneBubbleMetadata(msg.metadata);
// The still-running turn opens its own bubble even when it follows an
// assistant row: merging it into the completed answer above would make
// the resume path (which replays that turn alone) drop both.
@@ -475,8 +486,8 @@ export function convertChatSessionMessagesToUiMessages(
!opensActiveTurn &&
prevUI &&
prevUI.role === "assistant" &&
- !getRunMetadata(prevUI.metadata) &&
- !runMetadata
+ !getStandaloneBubbleMetadata(prevUI.metadata) &&
+ !standaloneMetadata
) {
prevUI.parts.push(...parts);
const oldId = prevUI.id;
diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.json
index 574dad00d7..a057937152 100644
--- a/autogpt_platform/frontend/src/app/api/openapi.json
+++ b/autogpt_platform/frontend/src/app/api/openapi.json
@@ -21539,6 +21539,11 @@
"title": "Limits Retry Count",
"default": 0
},
+ "usage_wait_count": {
+ "type": "integer",
+ "title": "Usage Wait Count",
+ "default": 0
+ },
"user_timezone": {
"anyOf": [{ "type": "string" }, { "type": "null" }],
"title": "User Timezone"