Skip to content

Self-improving AI Employees for everyone

feat(chat): notes, follow-ups and cited sources for the answering agent

trohitg3a51edced959
diff --git a/server/core/database.py b/server/core/database.py
index 402161cf..173192db 100644
--- a/server/core/database.py
+++ b/server/core/database.py
@@ -59,6 +59,7 @@ from models.approvals import ( # noqa: F401 - registers SQLModel tables
ApprovalRequest,
)
from models.chat import ( # noqa: F401 - registers SQLModel tables
+ ChatNote,
ChatRun,
ChatRunPart,
ChatThread,
@@ -526,17 +527,22 @@ class Database:
logger.warning(f"Generation runtime-data migration check failed: {exc}")
async def _migrate_chat_runs(self):
- """Give an older ``chat_runs`` table the columns added since."""
+ """Give older ``chat_runs`` and ``chat_threads`` tables the columns
+ added since."""
+ additions = {
+ "chat_runs": {"stop_requested_at": "DATETIME"},
+ "chat_threads": {"next_source": "INTEGER NOT NULL DEFAULT 1"},
+ }
try:
async with self.engine.begin() as conn:
- result = await conn.execute(text("PRAGMA table_info(chat_runs)"))
- columns = {row[1] for row in result.fetchall()}
- if not columns:
- return
- additions = {"stop_requested_at": "DATETIME"}
- for column, definition in additions.items():
- if column not in columns:
- await conn.execute(text(f"ALTER TABLE chat_runs ADD COLUMN {column} {definition}"))
+ for table, columns_added in additions.items():
+ result = await conn.execute(text(f"PRAGMA table_info({table})"))
+ columns = {row[1] for row in result.fetchall()}
+ if not columns:
+ continue
+ for column, definition in columns_added.items():
+ if column not in columns:
+ await conn.execute(text(f"ALTER TABLE {table} ADD COLUMN {column} {definition}"))
except Exception as exc:
logger.warning(f"Chat run migration check failed: {exc}")
@@ -1591,8 +1597,9 @@ class Database:
return [self.chat_row(m) for m in reversed(result.scalars().all())]
async def clear_chat_messages(self, session_id: str) -> int:
- """Clear a session's chat: its messages, and the runs, run parts and
- thread state that belong to them. Returns the messages deleted."""
+ """Clear a session's chat: its messages, and the runs, run parts,
+ notes and thread state that belong to them. Returns the messages
+ deleted."""
from sqlalchemy import delete as sa_delete
try:
@@ -1608,6 +1615,7 @@ class Database:
run_ids = select(ChatRun.run_id).where(ChatRun.session_id == session_id)
await session.execute(sa_delete(ChatRunPart).where(ChatRunPart.run_id.in_(run_ids)))
await session.execute(sa_delete(ChatRun).where(ChatRun.session_id == session_id))
+ await session.execute(sa_delete(ChatNote).where(ChatNote.session_id == session_id))
await session.execute(sa_delete(ChatThread).where(ChatThread.session_id == session_id))
await session.commit()
diff --git a/server/models/chat.py b/server/models/chat.py
index 55538e5d..babfe362 100644
--- a/server/models/chat.py
+++ b/server/models/chat.py
@@ -17,7 +17,8 @@ agent_context_flow.md). A second message while one is live is refused with
``ChatRunPart`` collects what a run's tools produce for its reply (generated
UI, sources, artifacts, approvals), keyed so an activity retry writes the
same row again. ``ChatThread`` holds a session's active leaf: the message the
-shown path ends at, which branches will move.
+shown path ends at, which branches will move, and its source counter.
+``ChatNote`` holds what the employee should learn on its next turn.
"""
from __future__ import annotations
@@ -47,6 +48,9 @@ class ChatThread(SQLModel, table=True):
session_id: str = Field(primary_key=True, max_length=255)
active_leaf_uid: Optional[str] = Field(default=None, max_length=64)
revision: int = Field(default=0)
+ #: The number the conversation's next cited source gets
+ #: (services/chat/sources.py), so a number never repeats in it.
+ next_source: int = Field(default=1)
updated_at: datetime = Field(default_factory=_utcnow, sa_column=Column(DateTime(timezone=True), nullable=False))
@@ -99,4 +103,27 @@ class ChatRunPart(SQLModel, table=True):
created_at: datetime = Field(default_factory=_utcnow, sa_column=Column(DateTime(timezone=True), nullable=False))
-__all__ = ["ChatRun", "ChatRunPart", "ChatThread", "LIVE_STATES", "TERMINAL_STATES"]
+class ChatNote(SQLModel, table=True):
+ """Something the employee should learn at the start of its next turn in a
+ chat (services/chat/notes.py): one bracketed line, keyed per session so a
+ newer note of the same kind replaces an older one not yet told."""
+
+ __tablename__ = "chat_notes"
+ __table_args__ = (UniqueConstraint("session_id", "key", name="uq_chat_notes_key"),)
+
+ id: Optional[int] = Field(default=None, primary_key=True)
+ session_id: str = Field(index=True, max_length=255)
+ key: str = Field(max_length=255)
+ #: ``ui-state`` (what the owner set in an interface).
+ kind: str = Field(max_length=20)
+ text: str = Field(max_length=20000)
+ created_at: datetime = Field(default_factory=_utcnow, sa_column=Column(DateTime(timezone=True), nullable=False))
+ updated_at: datetime = Field(default_factory=_utcnow, sa_column=Column(DateTime(timezone=True), nullable=False))
+ #: The run whose turn carries it, once claimed.
+ claimed_run_id: Optional[str] = Field(default=None, index=True, max_length=64)
+ claimed_at: Optional[datetime] = Field(default=None, sa_column=Column(DateTime(timezone=True), nullable=True))
+ #: When that run ended having told it; None while still to tell.
+ delivered_at: Optional[datetime] = Field(default=None, sa_column=Column(DateTime(timezone=True), nullable=True))
+
+
+__all__ = ["ChatNote", "ChatRun", "ChatRunPart", "ChatThread", "LIVE_STATES", "TERMINAL_STATES"]
diff --git a/server/nodes/chat/chat_reply/__init__.py b/server/nodes/chat/chat_reply/__init__.py
index d5f0b9d4..9449e800 100644
--- a/server/nodes/chat/chat_reply/__init__.py
+++ b/server/nodes/chat/chat_reply/__init__.py
@@ -7,7 +7,9 @@ in the editor's chat pane. The write goes through services/chat_thread.py,
which stamps the live generation and announces ``chat.updated``.
A message that is empty, or exactly NO_REPLY (the agent had nothing to
-say), posts nothing.
+say), posts nothing. A ``<followups>`` block the answer ends with is never
+shown as text: in a chat run it becomes the reply's follow-up buttons
+(``services/chat/guide.py``), elsewhere it is dropped.
In a run the owner's chat message started, the reply is that chat run's
answer (``run_scope``, set by MachinaWorkflow): it is saved under the run's
@@ -86,11 +88,15 @@ class ChatReplyNode(ActionNode):
@Operation("reply")
async def reply(self, ctx: NodeContext, params: ChatReplyParams) -> ChatReplyOutput:
+ from services.chat.guide import split_followups
from services.chat_thread import record_chat_message
from services.plugin.deps import get_database
text = params.message.strip()
- if not text or text == NO_REPLY:
+ # The <followups> block an answer may end with shows as buttons, never
+ # as text: a message that is only the block says nothing.
+ visible = split_followups(text)[0].strip()
+ if not visible or visible == NO_REPLY:
return ChatReplyOutput(posted=False)
if not ctx.workflow_id:
raise NodeUserError("Reply in Chat posts to the workflow's chat: save the workflow first.")
@@ -99,10 +105,10 @@ class ChatReplyNode(ActionNode):
run_id = scope.get("run_id") if isinstance(scope, dict) else None
if isinstance(run_id, str) and run_id:
return await self._reply_to_run(database, ctx, run_id, text)
- saved = await record_chat_message(database, ctx.workflow_id, "assistant", text)
+ saved = await record_chat_message(database, ctx.workflow_id, "assistant", visible)
if not saved:
raise RuntimeError("The reply could not be saved to the chat")
- return ChatReplyOutput(posted=True, message=text, message_id=_message_id(saved))
+ return ChatReplyOutput(posted=True, message=visible, message_id=_message_id(saved))
async def _reply_to_run(self, database, ctx: NodeContext, run_id: str, text: str) -> ChatReplyOutput:
from services.chat import ledger
@@ -117,7 +123,7 @@ class ChatReplyNode(ActionNode):
database, run=run, node_id=ctx.node_id, text=text, execution_id=chat_execution_id(control)
)
await announce_chat_updated(run.session_id, "assistant")
- return ChatReplyOutput(posted=True, message=text, message_id=saved.get("uid"), run_id=run_id)
+ return ChatReplyOutput(posted=True, message=saved.get("message", text), message_id=saved.get("uid"), run_id=run_id)
@classmethod
async def reset_execution_state(
diff --git a/server/nodes/search/brave_search/__init__.py b/server/nodes/search/brave_search/__init__.py
index 2732ca1e..85c2c665 100644
--- a/server/nodes/search/brave_search/__init__.py
+++ b/server/nodes/search/brave_search/__init__.py
@@ -90,6 +90,7 @@ class BraveSearchNode(ActionNode):
annotations = {"destructive": False, "readonly": True, "open_world": True}
task_queue = TaskQueue.REST_API
chat_step = "Searched the web"
+ chat_sources = True
usable_as_tool = True
Params = BraveSearchParams
diff --git a/server/nodes/search/duckduckgo_search/__init__.py b/server/nodes/search/duckduckgo_search/__init__.py
index 229d4a28..b7d00801 100644
--- a/server/nodes/search/duckduckgo_search/__init__.py
+++ b/server/nodes/search/duckduckgo_search/__init__.py
@@ -53,6 +53,7 @@ class DuckDuckGoSearchNode(ToolNode):
annotations = {"destructive": False, "readonly": True, "open_world": True}
task_queue = TaskQueue.REST_API
chat_step = "Searched the web"
+ chat_sources = True
Params = DuckDuckGoSearchParams
Output = DuckDuckGoSearchOutput
diff --git a/server/nodes/search/perplexity_search/__init__.py b/server/nodes/search/perplexity_search/__init__.py
index 299d05eb..b11aec4b 100644
--- a/server/nodes/search/perplexity_search/__init__.py
+++ b/server/nodes/search/perplexity_search/__init__.py
@@ -94,6 +94,7 @@ class PerplexitySearchNode(ActionNode):
annotations = {"destructive": False, "readonly": True, "open_world": True}
task_queue = TaskQueue.REST_API
chat_step = "Searched the web"
+ chat_sources = True
usable_as_tool = True
Params = PerplexitySearchParams
diff --git a/server/nodes/search/serper_search/__init__.py b/server/nodes/search/serper_search/__init__.py
index 6feae6a3..a28ad428 100644
--- a/server/nodes/search/serper_search/__init__.py
+++ b/server/nodes/search/serper_search/__init__.py
@@ -89,6 +89,7 @@ class SerperSearchNode(ActionNode):
annotations = {"destructive": False, "readonly": True, "open_world": True}
task_queue = TaskQueue.REST_API
chat_step = "Searched the web"
+ chat_sources = True
usable_as_tool = True
Params = SerperSearchParams
diff --git a/server/services/chat/guide.py b/server/services/chat/guide.py
new file mode 100644
index 00000000..0c39cf88
--- /dev/null
+++ b/server/services/chat/guide.py
@@ -0,0 +1,100 @@
+"""What the agent answering the owner's chat reads besides its own system
+prompt, and reading its follow-up suggestions back out of its answer
+(docs-internal/chat_protocol.md, "Notes to the employee" and "Follow-ups").
+
+``CHAT_REPLY_GUIDE`` is fixed text, the same byte for byte on every turn, so
+the agent's system prompt stays stable for prompt caching. It is appended by
+``agent.prepare_payload`` only for the agent whose answer is the chat's reply
+(the one with a ``chat_stream``).
+
+``split_followups`` takes the ``<followups>`` block off a reply: the chat
+shows its questions as buttons (``parts.followups``) and the block itself
+never shows (the stream holds it back too, ``services/chat/stream.py``).
+"""
+
+from __future__ import annotations
+
+import json
+import re
+from typing import Any, List, Mapping, Tuple
+
+from core.logging import get_logger
+from services.chat.stream import FOLLOWUPS_OPEN
+
+logger = get_logger(__name__)
+
+FOLLOWUPS_CLOSE = "</followups>"
+#: The most suggestions a reply keeps, and how long each may be.
+MAX_FOLLOWUPS = 3
+MAX_FOLLOWUP_CHARS = 160
+
+CHAT_REPLY_GUIDE = (
+ "You are answering the owner in a chat.\n"
+ "- A line in square brackets at the start of the owner's message comes from OpenCompany, not from the owner: "
+ "[ui-event]{...}[/ui-event] is a button they pressed in an interface you showed (with what they picked), and "
+ "[ui-state]{...}[/ui-state] is what they set in one without pressing anything. Treat it as the owner's choice.\n"
+ "- A search result numbered n is a source: cite the ones you rely on as [n] right after what they support.\n"
+ "- When a few short next questions would help the owner, end your reply with "
+ '<followups>["...", "..."]</followups>: at most 3, each a short question in the owner\'s own words. The chat '
+ "shows them as buttons; the block itself is never shown."
+)
+
+_LIST_MARK = re.compile(r"^\s*(?:[-*•]|\d+[.)])\s*")
+
+
+def with_chat_guide(system_message: str) -> str:
+ """The system prompt with the guide after it (once)."""
+ text = system_message or ""
+ if CHAT_REPLY_GUIDE in text:
+ return text
+ return f"{text.rstrip()}\n\n{CHAT_REPLY_GUIDE}" if text.strip() else CHAT_REPLY_GUIDE
+
+
+async def chat_turn(database: Any, chat_stream: Mapping[str, Any], *, system_message: str, prompt: str) -> Tuple[str, str]:
+ """The answering agent's turn: its system prompt with the guide, and the
+ owner's message with the session's untold notes ahead of it (claimed for
+ this run). Notes that cannot be read are left for the next turn."""
+ from services.chat.notes import claim_notes, notes_prompt
+
+ system = with_chat_guide(system_message)
+ try:
+ claimed = await claim_notes(database, session_id=str(chat_stream["session_id"]), run_id=str(chat_stream["run_id"]))
+ except Exception: # noqa: BLE001 - the turn goes on without them
+ logger.warning("Chat notes could not be read for a turn", run_id=chat_stream.get("run_id"), exc_info=True)
+ claimed = []
+ if claimed:
+ lines = notes_prompt(claimed)
+ prompt = f"{lines}\n\n{prompt}" if prompt else lines
+ return system, prompt
+
+
+def _items(body: str) -> List[str]:
+ body = body.strip()
+ raw: List[str]
+ try:
+ parsed = json.loads(body)
+ raw = [item for item in parsed if isinstance(item, str)] if isinstance(parsed, list) else []
+ except ValueError:
+ raw = [_LIST_MARK.sub("", line).strip().strip('"') for line in body.splitlines()]
+ kept: List[str] = []
+ for item in raw:
+ text = " ".join(item.split())[:MAX_FOLLOWUP_CHARS]
+ if text and text not in kept:
+ kept.append(text)
+ return kept[:MAX_FOLLOWUPS]
+
+
+def split_followups(text: str) -> Tuple[str, List[str]]:
+ """``(the reply without its last <followups> block, the suggestions in
+ it)``. A block left open runs to the end of the reply."""
+ start = text.rfind(FOLLOWUPS_OPEN)
+ if start == -1:
+ return text, []
+ body = text[start + len(FOLLOWUPS_OPEN):]
+ end = body.find(FOLLOWUPS_CLOSE)
+ inner, after = (body[:end], body[end + len(FOLLOWUPS_CLOSE):]) if end != -1 else (body, "")
+ visible = (text[:start] + after).rstrip()
+ return visible, _items(inner)
+
+
+__all__ = ["CHAT_REPLY_GUIDE", "FOLLOWUPS_CLOSE", "MAX_FOLLOWUPS", "chat_turn", "split_followups", "with_chat_guide"]
diff --git a/server/services/chat/handlers.py b/server/services/chat/handlers.py
index 6933abc0..d388c6ed 100644
--- a/server/services/chat/handlers.py
+++ b/server/services/chat/handlers.py
@@ -373,10 +373,12 @@ async def handle_stop_chat_run(data: Dict[str, Any], websocket: WebSocket) -> Di
async def handle_chat_ui_state(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
"""What the owner set in an interface the employee showed
(``changes: [{path, value}]``, the last value per path winning). Kept on
- the reply (``parts.ui[].state``), so a reload shows it. Answers the
- state's new ``state_revision``; ``not_found`` when the session has no
- such interface, ``invalid_request`` for a change that does not fit."""
- from services.chat import parts
+ the reply (``parts.ui[].state``), so a reload shows it, and told to the
+ employee at the start of its next turn (a ``[ui-state]`` note,
+ ``services/chat/notes.py``). Answers the state's new ``state_revision``;
+ ``not_found`` when the session has no such interface,
+ ``invalid_request`` for a change that does not fit."""
+ from services.chat import notes, parts
session_id = session_id_of(data)
database = container.database()
@@ -391,6 +393,16 @@ async def handle_chat_ui_state(data: Dict[str, Any], websocket: WebSocket) -> Di
return {"success": False, "error": "invalid_request", "detail": str(exc)}
if updated is None:
return {"success": False, "error": "not_found"}
+ try:
+ await notes.upsert_note(
+ database,
+ session_id=session_id,
+ key=f"ui-state:{part_id}",
+ kind="ui-state",
+ text=parts.ui_state_message(part_id=part_id, state=updated["state"]),
+ )
+ except Exception: # noqa: BLE001 - the state is saved and shows; only the note is lost
+ logger.warning("The employee could not be told what the owner set", part_id=part_id, exc_info=True)
return {"success": True, "part_id": part_id, "state_revision": updated["state_revision"]}
diff --git a/server/services/chat/ledger.py b/server/services/chat/ledger.py
index dd1d02e7..d0d5937f 100644
--- a/server/services/chat/ledger.py
+++ b/server/services/chat/ledger.py
@@ -38,7 +38,9 @@ ended by the watchdog, which also cancels its workflow.
**Steps** (``record_step``) are saved on the run as they finish, so a reload
can say how long it worked and what it did. **Parts** (what its tools
showed, such as generated UI) are sealed into its reply as it ends
-(``services/chat/parts.py``), before the end is published.
+(``services/chat/parts.py``), before the end is published, and a run that
+answered marks the notes its turn carried as told (``services/chat/
+notes.py``).
Every transition commits before its event is published, so a client that
reads the run after an event never sees an older state than the event.
@@ -278,7 +280,12 @@ async def post_reply(
saved. Another reply node in the same run gets ``a_<run id>.<n>``. A
retry from the same node returns the row it saved. Serialized by the
write reservation, so two reply nodes at once cannot take the same id.
+ A ``<followups>`` block the agent ended with is taken off the text and
+ saved as the reply's ``parts.followups`` (``services/chat/guide.py``).
"""
+ from services.chat.guide import split_followups
+
+ text, followups = split_followups(text)
async with database.reserved_session() as session:
result = await session.execute(
select(ChatMessage)
@@ -303,6 +310,8 @@ async def post_reply(
found = await session.execute(select(ChatRunPart).where(ChatRunPart.run_id == run.run_id).order_by(ChatRunPart.id))
parts = grouped_parts(list(found.scalars().all())) or None
+ if followups:
+ parts = {**(parts or {}), "followups": followups}
row = await database.append_chat_row(
session,
session_id=run.session_id,
@@ -432,10 +441,27 @@ async def _settle(database: Any, run: ChatRun, values: Dict[str, Any]) -> Option
return None
settled = await get_run(database, run.run_id)
if settled is not None and settled.state in TERMINAL_STATES:
+ await _tell_notes(database, settled)
publish_terminal(settled)
return settled
+async def _tell_notes(database: Any, run: ChatRun) -> None:
+ """Mark the notes the run's turn carried as told (``services/chat/
+ notes.py``) when it answered: it finished, or it stopped having written
+ something. A run that failed, or stopped before writing, leaves them for
+ the next turn."""
+ answered = run.state == "finished" or (run.state == "stopped" and bool((run.result or {}).get("reply_message_id")))
+ if not answered:
+ return
+ from services.chat.notes import deliver_notes
+
+ try:
+ await deliver_notes(database, run.run_id)
+ except Exception: # noqa: BLE001 - untold notes are told again next turn
+ logger.warning("Chat notes could not be marked told", run_id=run.run_id, exc_info=True)
+
+
async def _seal(database: Any, run: ChatRun) -> None:
"""Put what the run's tools showed on its reply (``services/chat/
parts.py``), and tell open threads when that changed the thread."""
diff --git a/server/services/chat/notes.py b/server/services/chat/notes.py
new file mode 100644
index 00000000..929b56b4
--- /dev/null
+++ b/server/services/chat/notes.py
@@ -0,0 +1,112 @@
+"""Notes to the employee: what it should learn at the start of its next turn
+in a chat (docs-internal/chat_protocol.md, "Notes to the employee").
+
+A note is one bracketed line, keyed per session so a newer note of the same
+kind replaces an older one not yet told (``[ui-state]`` for an interface the
+owner changed without pressing anything). The next run's payload claims the
+session's untold notes (``claim_notes``, from ``agent.prepare_payload``) and
+puts them ahead of the owner's message; the run's end marks them told
+(``deliver_notes``) when it finished or stopped. A run that failed leaves
+them untold, so the next turn offers them again, and a note changed after it
+was claimed stays untold too.
+"""
+
+from __future__ import annotations
+
+from datetime import datetime, timezone
+from typing import Any, List
+
+from sqlmodel import select
+
+from core.logging import get_logger
+from models.chat import ChatNote
+
+logger = get_logger(__name__)
+
+#: The most notes one turn carries; older ones wait for the next.
+MAX_NOTES_PER_TURN = 8
+
+
+def _utcnow() -> datetime:
+ return datetime.now(timezone.utc)
+
+
+def _aware(moment: Any) -> Any:
+ if moment is not None and moment.tzinfo is None:
+ return moment.replace(tzinfo=timezone.utc)
+ return moment
+
+
+async def upsert_note(database: Any, *, session_id: str, key: str, kind: str, text: str) -> None:
+ """Keep ``text`` as the note under ``key``: a new note, or the newer
+ version of one (told again even when the older one was told)."""
+ now = _utcnow()
+ async with database.reserved_session() as session:
+ found = await session.execute(select(ChatNote).where(ChatNote.session_id == session_id, ChatNote.key == key))
+ note = found.scalar_one_or_none()
+ if note is None:
+ note = ChatNote(session_id=session_id, key=key, kind=kind, text=text, created_at=now, updated_at=now)
+ else:
+ note.kind = kind
+ note.text = text
+ note.updated_at = now
+ note.delivered_at = None
+ session.add(note)
+ await session.commit()
+
+
+async def claim_notes(database: Any, *, session_id: str, run_id: str) -> List[ChatNote]:
+ """The session's untold notes, oldest first, claimed by ``run_id`` (a
+ retried claim by the same run returns the same notes)."""
+ now = _utcnow()
+ async with database.reserved_session() as session:
+ found = await session.execute(
+ select(ChatNote)
+ .where(ChatNote.session_id == session_id, ChatNote.delivered_at.is_(None))
+ .order_by(ChatNote.updated_at, ChatNote.id)
+ .limit(MAX_NOTES_PER_TURN)
+ )
+ notes = list(found.scalars().all())
+ for note in notes:
+ note.claimed_run_id = run_id
+ note.claimed_at = now
+ session.add(note)
+ await session.commit()
+ for note in notes:
+ session.expunge(note)
+ return notes
+
+
+async def deliver_notes(database: Any, run_id: str) -> int:
+ """Mark the notes ``run_id`` claimed as told, except any changed since
+ it claimed them. Returns how many."""
+ async with database.reserved_session() as session:
+ found = await session.execute(select(ChatNote).where(ChatNote.claimed_run_id == run_id, ChatNote.delivered_at.is_(None)))
+ told = 0
+ now = _utcnow()
+ for note in found.scalars().all():
+ claimed, updated = _aware(note.claimed_at), _aware(note.updated_at)
+ if claimed is not None and updated is not None and updated > claimed:
+ continue
+ note.delivered_at = now
+ session.add(note)
+ told += 1
+ await session.commit()
+ return told
+
+
+async def clear_notes(database: Any, session_id: str) -> None:
+ """Forget a session's notes (its conversation was cleared or reset)."""
+ from sqlalchemy import delete
+
+ async with database.get_session() as session:
+ await session.execute(delete(ChatNote).where(ChatNote.session_id == session_id))
+ await session.commit()
+
+
+def notes_prompt(notes: List[ChatNote]) -> str:
+ """The notes as the lines ahead of the owner's message."""
+ return "\n".join(note.text for note in notes)
+
+
+__all__ = ["MAX_NOTES_PER_TURN", "claim_notes", "clear_notes", "deliver_notes", "notes_prompt", "upsert_note"]
diff --git a/server/services/chat/parts.py b/server/services/chat/parts.py
index a9c77588..e4804144 100644
--- a/server/services/chat/parts.py
+++ b/server/services/chat/parts.py
@@ -8,11 +8,14 @@ first kind: ``show_ui`` saves the checked spec and publishes it as an empty
``activity.snapshot`` followed by one ``activity.delta`` per patch
(``services/genui/patches.py``); the client paces what arrives.
+Sources are the other kind (``services/chat/sources.py``): the numbered
+results of a search the answering agent ran.
+
When the run ends, ``seal_parts`` copies its parts into the reply message's
-``parts`` (``{"ui": [...]}``), creating an empty reply when the run showed
-something but wrote nothing, so a reload draws what the run showed. Every
-write here is best effort for the run: a part that cannot be saved is
-logged, and the run goes on.
+``parts`` (``{"ui": [...], "sources": [...]}``), creating an empty reply when
+the run showed something but wrote nothing, so a reload draws what the run
+showed. Every write here is best effort for the run: a part that cannot be
+saved is logged, and the run goes on.
"""
from __future__ import annotations
@@ -32,8 +35,8 @@ logger = get_logger(__name__)
#: The ``activity_type`` of a generated UI's events.
JSON_RENDER = "json_render"
-#: The kinds of part a reply's ``parts`` holds, in the order they render.
-PART_KINDS = ("ui",)
+#: The kinds of part a run collects for its reply.
+PART_KINDS = ("ui", "sources")
def ui_part_id(run_id: str, tool_call_id: str) -> str:
@@ -121,15 +124,21 @@ async def show_ui(database: Any, stream: Mapping[str, Any], *, tool_call_id: str
#: What names one item of each kind, for merging a run's parts into a reply.
-_ITEM_KEYS = {"ui": "part_id"}
+_ITEM_KEYS = {"ui": "part_id", "sources": "n"}
def grouped_parts(parts: List[ChatRunPart]) -> Dict[str, List[Dict[str, Any]]]:
- """A run's parts as a reply's ``parts`` holds them: ``{kind: [payload]}``."""
+ """A run's parts as a reply's ``parts`` holds them: ``{"ui": [payload],
+ "sources": [item]}`` (a sources part holds one tool call's items)."""
grouped: "OrderedDict[str, List[Dict[str, Any]]]" = OrderedDict()
for part in parts:
- if part.kind in PART_KINDS:
- grouped.setdefault(part.kind, []).append(dict(part.payload or {}))
+ if part.kind not in PART_KINDS:
+ continue
+ payload = dict(part.payload or {})
+ if part.kind == "sources":
+ grouped.setdefault("sources", []).extend(dict(item) for item in payload.get("items") or [] if isinstance(item, dict))
+ else:
+ grouped.setdefault(part.kind, []).append(payload)
return dict(grouped)
@@ -165,6 +174,10 @@ async def seal_parts(database: Any, run: ChatRun) -> bool:
reply.parts = {**current, **merged}
session.add(reply)
else:
+ # Sources show only where a reply cites them: alone they
+ # are no reason to make one.
+ if not grouped.get("ui"):
+ return False
current = await session.get(ChatRun, run.run_id)
stopped = current is not None and current.state in ("stopping", "stopped")
await database.append_chat_row(
@@ -292,6 +305,15 @@ def ui_event_message(*, part_id: str, element_id: str, label: str, action: str,
return f"[ui-event]{json.dumps(payload, ensure_ascii=False, separators=(', ', ': '))}[/ui-event]"
+def ui_state_message(*, part_id: str, state: Mapping[str, Any]) -> str:
+ """What the employee reads for what the owner set in an interface
+ without pressing anything: its whole state, one bracketed line."""
+ import json
+
+ payload = {"ui_id": part_id, "state": dict(state)}
+ return f"[ui-state]{json.dumps(payload, ensure_ascii=False, separators=(', ', ': '), default=str)}[/ui-state]"
+
+
async def update_ui_state(database: Any, session_id: str, part_id: str, changes: Any) -> Optional[Dict[str, Any]]:
"""Apply what the owner set (``[{path, value}]``, the last value per path
winning) to the interface's saved state. Returns ``{state,
@@ -360,5 +382,6 @@ __all__ = [
"show_ui",
"ui_event_message",
"ui_part_id",
+ "ui_state_message",
"update_ui_state",
]
diff --git a/server/services/chat/sources.py b/server/services/chat/sources.py
new file mode 100644
index 00000000..86457a27
--- /dev/null
+++ b/server/services/chat/sources.py
@@ -0,0 +1,88 @@
+"""Sources an answer can cite (docs-internal/chat_protocol.md, "Sources").
+
+A tool whose plugin declares ``chat_sources`` (the web searches) returns
+results with addresses. When the agent answering a chat run calls it,
+``number_tool_sources`` numbers those results for the conversation (the
+session's counter on ``chat_threads.next_source``, so a number never repeats
+in a conversation and an older ``[n]`` keeps meaning what it meant), writes
+the number on each result the model reads (``n``), and saves them as a
+``sources`` part of the run. The agent cites ``[n]``; the reply lists the
+sources it cited, numbered 1, 2, ... in the order it cites them (the
+client's job).
+"""
+
+from __future__ import annotations
+
+from typing import Any, Dict, List, Mapping, Optional
+from urllib.parse import urlsplit
+
+from core.logging import get_logger
+from models.chat import ChatThread
+
+logger = get_logger(__name__)
+
+#: The most results one call numbers.
+MAX_SOURCES_PER_CALL = 10
+_MAX_TITLE = 160
+_MAX_DETAIL = 240
+_MAX_URL = 2048
+
+
+def _clean(item: Mapping[str, Any]) -> Optional[Dict[str, Any]]:
+ url = item.get("url")
+ if not isinstance(url, str) or len(url) > _MAX_URL:
+ return None
+ parts = urlsplit(url.strip())
+ if parts.scheme not in ("http", "https") or not parts.netloc:
+ return None
+ title = item.get("title")
+ title = " ".join(title.split())[:_MAX_TITLE] if isinstance(title, str) and title.strip() else parts.netloc
+ detail = item.get("snippet") if isinstance(item.get("snippet"), str) else item.get("detail")
+ source: Dict[str, Any] = {"title": title, "url": url.strip()}
+ if isinstance(detail, str) and detail.strip():
+ source["detail"] = " ".join(detail.split())[:_MAX_DETAIL]
+ return source
+
+
+async def next_numbers(database: Any, session_id: str, count: int) -> int:
+ """Take ``count`` numbers from the session's counter; returns the first."""
+ async with database.reserved_session() as session:
+ thread = await session.get(ChatThread, session_id)
+ if thread is None:
+ thread = ChatThread(session_id=session_id)
+ first = thread.next_source or 1
+ thread.next_source = first + count
+ session.add(thread)
+ await session.commit()
+ return first
+
+
+async def number_tool_sources(database: Any, stream: Mapping[str, Any], *, tool_call_id: str, payload: Any) -> List[Dict[str, Any]]:
+ """Number the results with addresses in a tool's result (``payload``,
+ the dict holding ``results``), writing ``n`` on each, and save them on
+ the run. Returns the sources saved; nothing changes without results."""
+ from services.chat.parts import record_part
+
+ if not isinstance(payload, dict) or not isinstance(payload.get("results"), list):
+ return []
+ picked = []
+ for item in payload["results"]:
+ if len(picked) >= MAX_SOURCES_PER_CALL:
+ break
+ if isinstance(item, dict):
+ source = _clean(item)
+ if source is not None:
+ picked.append((item, source))
+ if not picked:
+ return []
+ first = await next_numbers(database, stream["session_id"], len(picked))
+ saved = []
+ for offset, (item, source) in enumerate(picked):
+ n = first + offset
+ item["n"] = n
+ saved.append({"n": n, **source})
+ await record_part(database, stream["run_id"], kind="sources", key=f"sources:{tool_call_id}", payload={"items": saved})
+ return saved
+
+
+__all__ = ["MAX_SOURCES_PER_CALL", "next_numbers", "number_tool_sources"]
diff --git a/server/services/chat/steps.py b/server/services/chat/steps.py
index 4b514847..6933cc73 100644
--- a/server/services/chat/steps.py
+++ b/server/services/chat/steps.py
@@ -17,6 +17,9 @@ call carries a ``tool_call_id``, which is the step id.
- **Stopped runs.** A tool call of a run the owner stopped is not run: it
gets a result saying so, which keeps the conversation whole (every call
answered) while the agent's next model step ends the run.
+- **Sources.** The web results of a ``chat_sources`` tool (the searches) are
+ numbered for the conversation in the result the model reads
+ (``number_sources``, ``services/chat/sources.py``).
Nothing here fails a tool call: publishing and saving are best effort.
"""
@@ -144,6 +147,25 @@ async def run_stopped(context: Mapping[str, Any]) -> bool:
return False
+async def number_sources(context: Mapping[str, Any], node_class: Any, result: Any) -> None:
+ """Number the web results of a ``chat_sources`` tool the answering agent
+ called, in the result the model reads (``services/chat/sources.py``)."""
+ if not getattr(node_class, "chat_sources", False):
+ return
+ stream = _stream_of(context)
+ tool_call_id = context.get("tool_call_id")
+ if stream is None or not isinstance(tool_call_id, str) or not tool_call_id or not isinstance(result, dict):
+ return
+ payload = result.get("result") if isinstance(result.get("result"), dict) else result
+ try:
+ from core.container import container
+ from services.chat.sources import number_tool_sources
+
+ await number_tool_sources(container.database(), stream, tool_call_id=tool_call_id, payload=payload)
+ except Exception: # noqa: BLE001 - the answer goes on without numbers
+ logger.warning("Chat sources could not be numbered", run_id=stream.get("run_id"), exc_info=True)
+
+
def take_detail(result: Any) -> Optional[str]:
"""Remove a tool's ``_step_detail`` from its result, wherever the
plugin's result shape puts it, and return it."""
@@ -156,4 +178,14 @@ def take_detail(result: Any) -> Optional[str]:
return detail if isinstance(detail, str) and detail.strip() else None
-__all__ = ["STEP_DETAIL_KEY", "STOPPED_RESULT", "Step", "begin", "end", "run_stopped", "step_label", "take_detail"]
+__all__ = [
+ "STEP_DETAIL_KEY",
+ "STOPPED_RESULT",
+ "Step",
+ "begin",
+ "end",
+ "number_sources",
+ "run_stopped",
+ "step_label",
+ "take_detail",
+]
diff --git a/server/services/plugin/base.py b/server/services/plugin/base.py
index ca073031..39501272 100644
--- a/server/services/plugin/base.py
+++ b/server/services/plugin/base.py
@@ -280,10 +280,13 @@ class BaseNode:
# ``chat_step``: how a call of this tool reads as a working step while
# the employee answers ("Checked Google Calendar"); empty falls back to
# "Used <display name>". ``chat_step_hidden``: housekeeping (the clock,
- # a checklist) that shows no step.
+ # a checklist) that shows no step. ``chat_sources``: the tool returns
+ # web results (``results: [{title, snippet, url}]``) the answer may cite,
+ # numbered for the conversation (services/chat/sources.py).
answers_chat_run: ClassVar[bool] = False
chat_step: ClassVar[str] = ""
chat_step_hidden: ClassVar[bool] = False
+ chat_sources: ClassVar[bool] = False
# Set by __init_subclass__: {op_name: OperationSpec}
_operations: ClassVar[Dict[str, OperationSpec]] = {}
@@ -1220,6 +1223,8 @@ class BaseNode:
# payload, error_message).
step_detail = chat_steps.take_detail(result)
success, payload, error = cls.interpret_result(result)
+ if success:
+ await chat_steps.number_sources(context, cls, result)
if chat_step is not None and not (
not success and result.get("error_type") == NODE_WAIT_INTERRUPTED
):
diff --git a/server/services/temporal/agent_activities.py b/server/services/temporal/agent_activities.py
index 9d7ff417..1f4f2dca 100644
--- a/server/services/temporal/agent_activities.py
+++ b/server/services/temporal/agent_activities.py
@@ -1487,11 +1487,23 @@ async def prepare_agent_payload(context: Dict[str, Any]) -> Dict[str, Any]:
)
from services.chat.stream import chat_run_id_of, chat_stream_for
+ chat_stream = chat_stream_for(context)
+ if chat_stream:
+ # The agent answering the owner's chat reads the chat's guide after
+ # its own system prompt (the same bytes every turn), and what the
+ # owner did in the chat since its last turn ahead of their message
+ # (services/chat/guide.py, services/chat/notes.py).
+ from services.chat.guide import chat_turn
+
+ system_message, prompt = await chat_turn(
+ database, chat_stream, system_message=system_message, prompt=prompt
+ )
+
return {
# The chat run this agent works for (stops when the owner presses
# Stop), and, for the agent that answers it, where its text streams.
"chat_run_id": chat_run_id_of(context),
- "chat_stream": chat_stream_for(context),
+ "chat_stream": chat_stream,
"node_id": node_id,
"node_type": node_type,
"workflow_id": workflow_id,
diff --git a/server/tests/services/chat/test_notes.py b/server/tests/services/chat/test_notes.py
new file mode 100644
index 00000000..e7a62076
--- /dev/null
+++ b/server/tests/services/chat/test_notes.py
@@ -0,0 +1,175 @@
+"""Notes to the employee (services/chat/notes.py) and the guide and
+follow-ups of a chat reply (services/chat/guide.py): a note is told once,
+on the turn after it was written, again when a turn that claimed it failed
+or when it changed meanwhile; the newest note of a kind replaces an untold
+one; what the owner sets in an interface becomes a [ui-state] note; the
+reply's <followups> block becomes buttons and never shows."""
+
+from __future__ import annotations
+
+import json
+
+import pytest
+
+from services.chat import guide, ledger, notes, parts
+from tests.services.chat._helpers import talking
+
+CLAIM = dict(temporal_workflow_id="tw-1", temporal_run_id="tr-1")
+
+
+async def test_a_note_is_told_once_on_the_next_turn(database):
+ await notes.upsert_note(database, session_id="wf", key="ui-state:ui_1", kind="ui-state", text="[ui-state]{}[/ui-state]")
+ claimed = await notes.claim_notes(database, session_id="wf", run_id="r_1")
+ assert [note.text for note in claimed] == ["[ui-state]{}[/ui-state]"]
+ # A retried claim by the same run gets the same notes; another session none.
+ assert [note.key for note in await notes.claim_notes(database, session_id="wf", run_id="r_1")] == ["ui-state:ui_1"]
+ assert await notes.claim_notes(database, session_id="other", run_id="r_x") == []
+ assert await notes.deliver_notes(database, "r_1") == 1
+ assert await notes.claim_notes(database, session_id="wf", run_id="r_2") == []
+
+
+async def test_a_failed_turn_leaves_its_notes_for_the_next(database):
+ await notes.upsert_note(database, session_id="wf", key="k", kind="ui-state", text="first")
+ await notes.claim_notes(database, session_id="wf", run_id="r_failed")
+ # Nothing delivered for the failed run; the next one gets the note.
+ [note] = await notes.claim_notes(database, session_id="wf", run_id="r_next")
+ assert note.claimed_run_id == "r_next"
+
+
+async def test_a_newer_note_replaces_an_untold_one_and_is_told_again(database):
+ await notes.upsert_note(database, session_id="wf", key="k", kind="ui-state", text="slot s1")
+ await notes.claim_notes(database, session_id="wf", run_id="r_1")
+ # Changed after the claim: told again, even though r_1 finished.
+ await notes.upsert_note(database, session_id="wf", key="k", kind="ui-state", text="slot s2")
+ assert await notes.deliver_notes(database, "r_1") == 0
+ [note] = await notes.claim_notes(database, session_id="wf", run_id="r_2")
+ assert note.text == "slot s2"
+ await notes.deliver_notes(database, "r_2")
+ # Changed after it was told: told again.
+ await notes.upsert_note(database, session_id="wf", key="k", kind="ui-state", text="slot s3")
+ assert [n.text for n in await notes.claim_notes(database, session_id="wf", run_id="r_3")] == ["slot s3"]
+ await notes.clear_notes(database, "wf")
+ assert await notes.claim_notes(database, session_id="wf", run_id="r_4") == []
+
+
+async def test_a_finished_run_tells_its_notes_and_a_failed_one_does_not(database, hub):
+ for success in (False, True):
+ admission = await ledger.admit_message(database, session_id="wf", workflow_id="wf", execution_id="g", text="hi", track=True)
+ run = await ledger.start_run(database, run_id=admission.run.run_id, **CLAIM)
+ await notes.upsert_note(database, session_id="wf", key="k", kind="ui-state", text=f"try {success}")
+ await notes.claim_notes(database, session_id="wf", run_id=run.run_id)
+ await ledger.finish_run(database, run_id=run.run_id, success=success, error=None if success else "boom", **CLAIM)
+ assert await notes.claim_notes(database, session_id="wf", run_id="r_after") == []
+
+
+async def test_a_run_stopped_before_writing_leaves_its_notes(database, hub):
+ admission = await ledger.admit_message(database, session_id="wf", workflow_id="wf", execution_id="g", text="hi", track=True)
+ run = await ledger.start_run(database, run_id=admission.run.run_id, **CLAIM)
+ await notes.upsert_note(database, session_id="wf", key="k", kind="ui-state", text="slot s1")
+ await notes.claim_notes(database, session_id="wf", run_id=run.run_id)
+ await ledger.request_stop(database, run.run_id)
+ ended = await ledger.finish_run(database, run_id=run.run_id, success=True, **CLAIM)
+ assert ended.state == "stopped" and ended.result == {"no_reply": True}
+ assert [note.key for note in await notes.claim_notes(database, session_id="wf", run_id="r_next")] == ["k"]
+
+
+async def test_what_the_owner_sets_becomes_a_ui_state_note(chat):
+ from services.genui.spec import check_spec
+
+ await talking(chat.database)
+ sent = await chat.handlers.handle_send_chat_message({"message": "Book Saturday", "session_id": "wf"}, None)
+ run = await ledger.start_run(chat.database, run_id=sent["run_id"], **CLAIM)
+ spec = check_spec({"root": "r", "state": {"slot": "s1"}, "elements": {"r": {"type": "Toggle", "props": {"label": "Remind", "checked": {"$bindState": "/remind"}}}}}).spec
+ stream = {"run_id": run.run_id, "session_id": "wf", "workflow_id": "wf"}
+ part_id = await parts.show_ui(chat.database, stream, tool_call_id="call_1", spec=spec)
+ await chat.handlers.handle_chat_ui_state({"session_id": "wf", "part_id": part_id, "changes": [{"path": "/remind", "value": True}]}, None)
+ [note] = await notes.claim_notes(chat.database, session_id="wf", run_id="r_next")
+ assert note.kind == "ui-state" and note.text.startswith("[ui-state]") and note.text.endswith("[/ui-state]")
+ assert json.loads(note.text[len("[ui-state]"):-len("[/ui-state]")]) == {"ui_id": part_id, "state": {"slot": "s1", "remind": True}}
+ # Clearing the chat forgets them.
+ await chat.handlers.handle_clear_chat_messages({"session_id": "wf"}, None)
+ assert await notes.claim_notes(chat.database, session_id="wf", run_id="r_later") == []
+
+
+# ----- the guide and follow-ups -----
+
+
+def test_the_guide_is_added_once_and_never_changes():
+ once = guide.with_chat_guide("You are Maya.")
+ assert once.startswith("You are Maya.\n\n") and once.endswith(guide.CHAT_REPLY_GUIDE)
+ assert guide.with_chat_guide(once) == once
+ assert guide.with_chat_guide("") == guide.CHAT_REPLY_GUIDE
+ assert "[ui-event]" in guide.CHAT_REPLY_GUIDE and "<followups>" in guide.CHAT_REPLY_GUIDE
+
+
+async def test_the_answering_agent_reads_the_guide_and_the_untold_notes(database):
+ await notes.upsert_note(database, session_id="wf", key="k", kind="ui-state", text="[ui-state]{}[/ui-state]")
+ stream = {"run_id": "r_1", "session_id": "wf"}
+ system, prompt = await guide.chat_turn(database, stream, system_message="You are Maya.", prompt="Book it")
+ assert system == guide.with_chat_guide("You are Maya.")
+ assert prompt == "[ui-state]{}[/ui-state]\n\nBook it"
+ # Nothing untold: the owner's message as it is.
+ other = {"run_id": "r_2", "session_id": "other"}
+ assert await guide.chat_turn(database, other, system_message="", prompt="Hi") == (guide.CHAT_REPLY_GUIDE, "Hi")
+
+ class Broken:
+ def reserved_session(self):
+ raise RuntimeError("database down")
+
+ # Notes that cannot be read wait for the next turn; this one goes on.
+ assert await guide.chat_turn(Broken(), stream, system_message="S", prompt="Hi") == (guide.with_chat_guide("S"), "Hi")
+
+
+def test_only_the_agent_answering_the_chat_reads_the_guide():
+ import inspect
+
+ from services.temporal import agent_activities
+
+ source = inspect.getsource(agent_activities.prepare_agent_payload)
+ assert "chat_stream = chat_stream_for(context)" in source
+ assert "if chat_stream:" in source and "await chat_turn(" in source
+
+
+ ("text", "visible", "items"),
+ [
+ ('Booked.\n<followups>["Move it?", "Cancel it?"]</followups>', "Booked.", ["Move it?", "Cancel it?"]),
+ ("Booked.\n<followups>\n- Move it?\n- Cancel it?\n</followups>", "Booked.", ["Move it?", "Cancel it?"]),
+ ('Done.<followups>["a", "a", "b", "c", "d", " "]', "Done.", ["a", "b", "c"]),
+ ("No block here.", "No block here.", []),
+ ('<followups>["Only this?"]</followups>', "", ["Only this?"]),
+ ('Text <followups>["x"]</followups> after', "Text after", ["x"]),
+ ],
+)
+def test_followups_are_taken_off_the_reply(text, visible, items):
+ assert guide.split_followups(text) == (visible, items)
+
+
+async def test_reply_in_chat_saves_followups_as_buttons(database, hub):
+ admission = await ledger.admit_message(database, session_id="wf", workflow_id="wf", execution_id="g", text="hi", track=True)
+ run = await ledger.start_run(database, run_id=admission.run.run_id, **CLAIM)
+ reply = await ledger.post_reply(
+ database, run=run, node_id="n", text='Two today.\n<followups>["And tomorrow?"]</followups>', execution_id="g"
+ )
+ assert reply["message"] == "Two today."
+ assert reply["parts"]["followups"] == ["And tomorrow?"]
+
+
+async def test_reply_in_chat_never_shows_the_block(monkeypatch, database, hub):
+ from nodes.chat.chat_reply import ChatReplyNode, ChatReplyParams
+
+ saved = []
+
+ async def record_chat_message(database, session_id, role, text):
+ saved.append(text)
+ return {"uid": "m_1"}
+
+ monkeypatch.setattr("services.chat_thread.record_chat_message", record_chat_message)
+ monkeypatch.setattr("services.plugin.deps.get_database", lambda: database)
+ node = ChatReplyNode()
+ ctx = type("Ctx", (), {"workflow_id": "wf", "node_id": "wf:chatReply:1", "raw": {}})()
+ out = await node.reply(ctx, ChatReplyParams(message='Done.\n<followups>["More?"]</followups>'))
+ assert (out.posted, out.message, saved) == (True, "Done.", ["Done."])
+ # A message that is only the block says nothing.
+ out = await node.reply(ctx, ChatReplyParams(message='<followups>["More?"]</followups>'))
+ assert out.posted is False and saved == ["Done."]
diff --git a/server/tests/services/chat/test_sources.py b/server/tests/services/chat/test_sources.py
new file mode 100644
index 00000000..318525e6
--- /dev/null
+++ b/server/tests/services/chat/test_sources.py
@@ -0,0 +1,56 @@
+"""Sources an answer can cite (services/chat/sources.py): the web results of
+a search the answering agent ran are numbered for the conversation (never
+repeating, across calls and turns), each result the model reads carries its
+number, and the reply carries the sources it may cite."""
+
+from __future__ import annotations
+
+from services.chat import ledger, parts, sources
+
+CLAIM = dict(temporal_workflow_id="tw-1", temporal_run_id="tr-1")
+
+
+async def running(database):
+ admission = await ledger.admit_message(database, session_id="wf", workflow_id="wf", execution_id="g", text="Find a florist", track=True)
+ return await ledger.start_run(database, run_id=admission.run.run_id, **CLAIM)
+
+
+def stream_of(run):
+ return {"run_id": run.run_id, "session_id": run.session_id, "workflow_id": run.workflow_id}
+
+
+def results(*names):
+ return {"results": [{"title": f"{name} Flowers", "snippet": f"{name} delivers.", "url": f"https://{name}.test/"} for name in names]}
+
+
+async def test_results_are_numbered_for_the_conversation(database, hub):
+ run = await running(database)
+ first = results("bloom", "petal")
+ saved = await sources.number_tool_sources(database, stream_of(run), tool_call_id="call_1", payload=first)
+ assert [item["n"] for item in first["results"]] == [1, 2]
+ assert saved == [
+ {"n": 1, "title": "bloom Flowers", "url": "https://bloom.test/", "detail": "bloom delivers."},
+ {"n": 2, "title": "petal Flowers", "url": "https://petal.test/", "detail": "petal delivers."},
+ ]
+ second = results("stem")
+ await sources.number_tool_sources(database, stream_of(run), tool_call_id="call_2", payload=second)
+ assert second["results"][0]["n"] == 3
+
+ reply = await ledger.post_reply(database, run=run, node_id="n", text="Try Bloom [1] or Stem [3].", execution_id="g")
+ assert [item["n"] for item in reply["parts"]["sources"]] == [1, 2, 3]
+
+
+async def test_results_without_an_address_are_not_sources(database, hub):
+ run = await running(database)
+ payload = {"results": [{"title": "No link"}, {"title": "Bad", "url": "javascript:alert(1)"}, {"url": "https://ok.test"}]}
+ saved = await sources.number_tool_sources(database, stream_of(run), tool_call_id="call_1", payload=payload)
+ assert saved == [{"n": 1, "title": "ok.test", "url": "https://ok.test"}]
+ assert "n" not in payload["results"][0] and payload["results"][2]["n"] == 1
+ assert await sources.number_tool_sources(database, stream_of(run), tool_call_id="call_2", payload={"answer": "x"}) == []
+
+
+async def test_sources_and_ui_seal_side_by_side(database, hub):
+ run = await running(database)
+ await sources.number_tool_sources(database, stream_of(run), tool_call_id="call_1", payload=results("bloom"))
+ grouped = parts.grouped_parts(await parts.run_parts(database, run.run_id))
+ assert grouped == {"sources": [{"n": 1, "title": "bloom Flowers", "url": "https://bloom.test/", "detail": "bloom delivers."}]}
diff --git a/server/tests/services/chat/test_step_activity.py b/server/tests/services/chat/test_step_activity.py
index 43f7204c..4def27a5 100644
--- a/server/tests/services/chat/test_step_activity.py
+++ b/server/tests/services/chat/test_step_activity.py
@@ -1,7 +1,8 @@
"""A tool call run as a node activity (``BaseNode.as_activity``) for the
agent answering a chat run: it shows as a working step with the detail the
-tool gave, the detail never reaches the model, and a call of a run the owner
-stopped is answered without running."""
+tool gave, the detail never reaches the model, a call of a run the owner
+stopped is answered without running, and a search numbers the results the
+answer may cite."""
from __future__ import annotations
@@ -105,3 +106,46 @@ async def test_a_node_outside_a_chat_run_is_untouched(surroundings):
result = await ActivityEnvironment().run(activity_fn, {"node_id": "wf:braveSearch:1", "workflow_id": "wf", "node_data": {}})
surroundings.service.execute_node.assert_awaited_once()
assert result["success"] is True and surroundings.published == []
+
+
+async def test_a_search_numbers_the_results_the_answer_may_cite(surroundings, monkeypatch):
+ from services.chat import parts, sources
+
+ surroundings.service.execute_node.return_value = {
+ "success": True,
+ "result": {"results": [{"title": "Bloom", "url": "https://bloom.test/"}, {"title": "No link"}]},
+ }
+ recorded = []
+
+ async def next_numbers(database, session_id, count):
+ assert (database, session_id, count) == ("db", "wf", 1)
+ return 5
+
+ async def record_part(database, run_id, *, kind, key, payload):
+ recorded.append((run_id, kind, key, payload))
+
+ monkeypatch.setattr(sources, "next_numbers", next_numbers)
+ monkeypatch.setattr(parts, "record_part", record_part)
+ activity_fn = get_node_class("braveSearch").as_activity()
+ result = await ActivityEnvironment().run(activity_fn, dict(CONTEXT))
+ # The model reads the number on the result it may cite.
+ assert result["result"]["results"][0]["n"] == 5 and "n" not in result["result"]["results"][1]
+ assert recorded == [("r_1", "sources", "sources:call_1", {"items": [{"n": 5, "title": "Bloom", "url": "https://bloom.test/"}]})]
+
+
+async def test_results_are_numbered_only_for_a_search_of_the_answering_agent(monkeypatch):
+ from services.chat import sources
+
+ calls = []
+
+ async def number_tool_sources(*args, **kwargs):
+ calls.append(kwargs)
+
+ monkeypatch.setattr(sources, "number_tool_sources", number_tool_sources)
+ result = {"success": True, "result": {"results": [{"url": "https://ok.test"}]}}
+ await steps.number_sources(CONTEXT, get_node_class("calculatorTool"), result)
+ await steps.number_sources({**CONTEXT, "chat_stream": None}, get_node_class("braveSearch"), result)
+ await steps.number_sources({**CONTEXT, "tool_call_id": None}, get_node_class("braveSearch"), result)
+ assert calls == []
+ for search in ("braveSearch", "serperSearch", "perplexitySearch", "duckduckgoSearch"):
+ assert get_node_class(search).chat_sources is True