Skip to content

Self-improving AI Employees for everyone

feat(employees): say how a hire's start went, and latch two first steps

trohitg835b92cc4ace
diff --git a/server/core/database.py b/server/core/database.py
index 1b1083d5..5c010dee 100644
--- a/server/core/database.py
+++ b/server/core/database.py
@@ -327,6 +327,8 @@ class Database:
"getting_started_ran_example",
"getting_started_built_workflow",
"getting_started_tried_theme",
+ "getting_started_said_hello",
+ "getting_started_approved_draft",
]:
if col not in columns:
await conn.execute(text(f"ALTER TABLE user_settings ADD COLUMN {col} BOOLEAN DEFAULT 0"))
@@ -2474,6 +2476,8 @@ class Database:
"getting_started_ran_example": settings.getting_started_ran_example,
"getting_started_built_workflow": settings.getting_started_built_workflow,
"getting_started_tried_theme": settings.getting_started_tried_theme,
+ "getting_started_said_hello": settings.getting_started_said_hello,
+ "getting_started_approved_draft": settings.getting_started_approved_draft,
"default_llm_provider": settings.default_llm_provider,
"default_llm_model": settings.default_llm_model,
"auto_add_skill_for_tools": settings.auto_add_skill_for_tools,
diff --git a/server/models/database.py b/server/models/database.py
index ad92ccc4..c433d46c 100644
--- a/server/models/database.py
+++ b/server/models/database.py
@@ -331,6 +331,8 @@ class UserSettings(SQLModel, table=True):
getting_started_ran_example: bool = Field(default=False) # Latched: chatted while a workflow was deployed
getting_started_built_workflow: bool = Field(default=False) # Latched: saved a self-built workflow with nodes
getting_started_tried_theme: bool = Field(default=False) # Latched: switched visual theme at least once
+ getting_started_said_hello: bool = Field(default=False) # Latched: messaged their first employee (Home's checklist)
+ getting_started_approved_draft: bool = Field(default=False) # Latched: sent a draft an employee held for them
default_llm_provider: Optional[str] = Field(default=None, max_length=50) # Global default AI provider
default_llm_model: Optional[str] = Field(default=None, max_length=200) # Global default AI model
auto_add_skill_for_tools: bool = Field(
diff --git a/server/services/employees/activation.py b/server/services/employees/activation.py
index 10a675ba..83e757ed 100644
--- a/server/services/employees/activation.py
+++ b/server/services/employees/activation.py
@@ -36,12 +36,20 @@ async def activate_pending(database: Any, workflow_id: str | None = None) -> Non
result = await start_saved_workflow(intent.workflow_id, owner_id=intent.owner_id, idempotency_key=intent.id)
state = "running" if result.get("success") else "failed"
detail = str(result.get("error") or "") or None
+ changed = False
async with database.reserved_session() as session:
current = await session.get(EmployeeActivation, intent.id)
if current and current.state != "running":
+ changed = (current.state, current.detail) != (state, detail)
current.state, current.detail = state, detail
current.updated_at = datetime.now(timezone.utc)
await session.commit()
+ # The summary says how the hire's start went (``activation_state``).
+ # A start that is blocked or fails before Start made a control row
+ # changes nothing else the page hears about, so it is announced here.
+ if changed:
+ from services.employees.events import employee_changed_now
+ employee_changed_now(intent.workflow_id)
async def recovery_loop(database: Any) -> None:
diff --git a/server/services/employees/hire.py b/server/services/employees/hire.py
index 39c2fdd3..0cd5ec58 100644
--- a/server/services/employees/hire.py
+++ b/server/services/employees/hire.py
@@ -20,8 +20,11 @@
what to connect.
Response: ``{employee, started, missing_apps, needs_ai, unsupported_apps,
-warnings, idempotent}``. Errors: ``invalid_request``, ``too_large``,
-``conflict``, ``busy``, ``not_allowed``, ``build_failed``, ``save_failed``.
+node_count, warnings, idempotent, request_id, activation_state,
+readiness_issue}``. ``node_count`` is the saved graph's size (the new hire's
+first day says "Workflow built · 9 blocks"). Errors: ``invalid_request``,
+``too_large``, ``conflict``, ``busy``, ``not_allowed``, ``build_failed``,
+``save_failed``.
"""
from __future__ import annotations
@@ -180,12 +183,15 @@ async def _response_for(database: Any, auth_service: Any, workflow_id: str, **ex
summary = await get_employee_summary(database, workflow_id, auth_service=auth_service)
if summary is None:
return _fail("save_failed")
+ workflow = await database.get_workflow(workflow_id)
return {
"success": True,
"employee": summary,
"missing_apps": summary["missing_apps"],
"needs_ai": summary["needs_ai"],
"unsupported_apps": summary["unsupported_apps"],
+ # Read from the saved graph, so a replay of the same key says the same.
+ "node_count": len((getattr(workflow, "data", None) or {}).get("nodes") or []),
**extra,
}
diff --git a/server/services/employees/summaries.py b/server/services/employees/summaries.py
index 409269b2..3b8761b0 100644
--- a/server/services/employees/summaries.py
+++ b/server/services/employees/summaries.py
@@ -22,6 +22,11 @@ node ids are the ones that report status; otherwise the saved graph.
``pending_changes`` says the saved graph would run differently from the
live generation (a tool added in Talk, an edit in Dev mode), so a restart
("Apply") is waiting.
+
+``activation_state`` says how a hire's own start went (``saved`` until it
+is tried, then ``blocked``, ``running`` or ``failed``; activation.py), so a
+new hire's page can tell a start still under way from one that will not
+come without the owner. It is null for a workflow built in the editor.
"""
from __future__ import annotations
@@ -266,6 +271,7 @@ async def _summary(
needs_ai: bool,
pending: int,
done_today: int,
+ activation_state: Optional[str] = None,
) -> Dict[str, Any]:
from services.workspace_capabilities import workspace_nodes
@@ -333,6 +339,7 @@ async def _summary(
getattr(control_row, "updated_at", None),
),
"hired_at": employee.hired_at.isoformat() if employee is not None and employee.hired_at else None,
+ "activation_state": activation_state,
}
@@ -347,6 +354,24 @@ async def _pending_counts(database: Any, workflow_ids: Iterable[str]) -> Dict[st
return {}
+async def _activation_states(database: Any, workflow_ids: Iterable[str]) -> Dict[str, str]:
+ """How each hire's own start went, per workflow (employee_activations)."""
+ from sqlmodel import select
+
+ from models.employees import EmployeeActivation
+
+ ids = list(workflow_ids)
+ if not ids:
+ return {}
+ try:
+ async with database.get_session() as session:
+ rows = (await session.execute(select(EmployeeActivation).where(EmployeeActivation.workflow_id.in_(ids)))).scalars().all()
+ except Exception:
+ logger.warning("Could not read how hires started", exc_info=True)
+ return {}
+ return {row.workflow_id: row.state for row in rows}
+
+
async def _owner_zone(database: Any) -> ZoneInfo:
"""The owner's time zone (Settings > Profile), UTC when unset or unreadable."""
try:
@@ -403,6 +428,7 @@ async def list_employee_summaries(database: Any, *, auth_service: Any, owner_id:
controls = await database.list_latest_workflow_controls(ids)
pending = await _pending_counts(database, ids)
done = await _done_today(database, ids)
+ activations = await _activation_states(database, ids)
connections_by_owner = {}
summaries = []
for workflow in workflows:
@@ -419,6 +445,7 @@ async def list_employee_summaries(database: Any, *, auth_service: Any, owner_id:
needs_ai=needs_ai,
pending=pending.get(workflow.id, 0),
done_today=done.get(workflow.id, 0),
+ activation_state=activations.get(workflow.id),
))
return summaries
@@ -431,6 +458,7 @@ async def _load_one(database: Any, workflow_id: str, *, auth_service: Any) -> Op
control = await database.get_latest_workflow_control(workflow_id)
pending = await _pending_counts(database, [workflow_id])
done = await _done_today(database, [workflow_id])
+ activations = await _activation_states(database, [workflow_id])
connections = Connections(auth_service, principal=employee_owner(workflow, employee))
summary = await _summary(
workflow,
@@ -440,6 +468,7 @@ async def _load_one(database: Any, workflow_id: str, *, auth_service: Any) -> Op
needs_ai=not await connections.has_ai(),
pending=pending.get(workflow_id, 0),
done_today=done.get(workflow_id, 0),
+ activation_state=activations.get(workflow_id),
)
if employee and employee.team_plan:
from services.employees.jobs import job_progress
diff --git a/server/tests/services/employees/test_activation.py b/server/tests/services/employees/test_activation.py
index 58b88d96..d133cc01 100644
--- a/server/tests/services/employees/test_activation.py
+++ b/server/tests/services/employees/test_activation.py
@@ -44,3 +44,38 @@ async def test_readiness_blocks_teams_but_preserves_legacy_activation_identity(r
assert saved.state == "running" and saved.detail is None
await activation.activate_pending(real_database)
assert admit.await_count == 1
+
+
+async def test_a_change_in_how_the_start_went_is_announced_once(real_database, monkeypatch):
+ """A start that is blocked or fails makes no control row, so the page
+ hears of it from here: once per change, not on every recovery pass."""
+ import core.container as container_module
+ import services.deployment.handlers as handlers
+ import services.employees.events as events
+ import services.employees.start as start
+ import services.employees.summaries as summaries
+ import services.employees.team_runtime as runtime
+
+ monkeypatch.setattr(container_module, "container", SimpleNamespace(auth_service=lambda: SimpleNamespace()))
+ summary = {"missing_apps": [{"app_id": "whatsapp"}], "needs_ai": False}
+ monkeypatch.setattr(summaries, "get_employee_summary", AsyncMock(side_effect=lambda *_args, **_kwargs: summary))
+ monkeypatch.setattr(start, "heal_agent_models", AsyncMock())
+ monkeypatch.setattr(runtime, "team_runtime_error", lambda: None)
+ monkeypatch.setattr(handlers, "start_saved_workflow", AsyncMock(return_value={"success": False, "error": "temporal_unavailable"}))
+ announced = []
+ monkeypatch.setattr(events, "employee_changed_now", announced.append)
+ async with real_database.get_session() as session:
+ session.add(Employee(id="employee", workflow_id="7", owner_id="owner", hire_state="ready"))
+ session.add(EmployeeActivation(id="hire:employee", workflow_id="7", owner_id="owner"))
+ await session.commit()
+
+ await activation.activate_pending(real_database)
+ await activation.activate_pending(real_database)
+ assert announced == ["7"]
+
+ summary = {"missing_apps": [], "needs_ai": False}
+ await activation.activate_pending(real_database)
+ assert announced == ["7", "7"]
+ async with real_database.get_session() as session:
+ saved = await session.get(EmployeeActivation, "hire:employee")
+ assert (saved.state, saved.detail) == ("failed", "temporal_unavailable")
diff --git a/server/tests/services/employees/test_hire_handler.py b/server/tests/services/employees/test_hire_handler.py
index c87f6681..592a3144 100644
--- a/server/tests/services/employees/test_hire_handler.py
+++ b/server/tests/services/employees/test_hire_handler.py
@@ -128,6 +128,8 @@ async def test_a_hire_saves_a_valid_workflow_and_starts_it(harness):
workflow = await harness.database.get_workflow(workflow_id)
types = {node["type"] for node in workflow.data["nodes"]}
assert {"chatTrigger", "aiAgent", "ai_employee", "taskTrigger", "context", "console", "writeTodos", "canvas"} <= types
+ # The first day's "Workflow built · N blocks".
+ assert result["node_count"] == len(workflow.data["nodes"])
assert "employeeJob" not in types
assert workflow.data["owner_id"] == "owner"
row = await store.get_by_workflow(harness.database, workflow_id)
@@ -148,6 +150,7 @@ async def test_the_same_key_finds_the_same_employee(harness):
again = await hire.handle_hire_employee(payload(), SOCKET)
assert again["success"] is True and again["idempotent"] is True
assert again["employee"]["workflow_id"] == first["employee"]["workflow_id"]
+ assert again["node_count"] == first["node_count"] > 0
await asyncio.sleep(0)
assert len(harness.starts) == 1
diff --git a/server/tests/services/employees/test_list_employees.py b/server/tests/services/employees/test_list_employees.py
index c8635f5e..8b0a13eb 100644
--- a/server/tests/services/employees/test_list_employees.py
+++ b/server/tests/services/employees/test_list_employees.py
@@ -179,6 +179,23 @@ async def test_a_hired_employee_waiting_on_an_app(real_database):
assert summary["revision"] > 0
+async def test_a_hire_says_how_its_own_start_went(real_database):
+ from models.employees import EmployeeActivation
+
+ await save(real_database, "1", "Maya", RECEPTIONIST)
+ await hire(real_database, "1", role="Receptionist", apps=["whatsapp"], trigger={"kind": "app_event", "app": "whatsapp"})
+ await save(real_database, "2", "Support bot", graph(node("2:aiAgent:1", "aiAgent", "Support")))
+ async with real_database.get_session() as session:
+ session.add(EmployeeActivation(id="hire:k1", workflow_id="1", owner_id="owner", state="blocked", detail="missing_apps"))
+ await session.commit()
+ auth = FakeAuth(keys={"openai"})
+ listed = {summary["workflow_id"]: summary for summary in await list_employee_summaries(real_database, auth_service=auth)}
+ assert listed["1"]["activation_state"] == "blocked"
+ # A workflow built in the editor was never started by a hire.
+ assert listed["2"]["activation_state"] is None
+ assert (await get_employee_summary(real_database, "1", auth_service=auth))["activation_state"] == "blocked"
+
+
async def test_an_editor_workflow_is_described_from_its_graph(real_database):
await save(
real_database,
diff --git a/server/tests/services/test_getting_started_settings.py b/server/tests/services/test_getting_started_settings.py
index 86486560..cf532cea 100644
--- a/server/tests/services/test_getting_started_settings.py
+++ b/server/tests/services/test_getting_started_settings.py
@@ -22,6 +22,8 @@ GETTING_STARTED_COLUMNS = [
"getting_started_ran_example",
"getting_started_built_workflow",
"getting_started_tried_theme",
+ "getting_started_said_hello",
+ "getting_started_approved_draft",
]
diff --git a/server/tests/test_user_settings_contract.py b/server/tests/test_user_settings_contract.py
index d95d352f..b3255aba 100644
--- a/server/tests/test_user_settings_contract.py
+++ b/server/tests/test_user_settings_contract.py
@@ -24,6 +24,8 @@ GETTING_STARTED_FIELDS = [
"getting_started_ran_example",
"getting_started_built_workflow",
"getting_started_tried_theme",
+ "getting_started_said_hello",
+ "getting_started_approved_draft",
]
# Bookkeeping columns the save path never writes and the getter formats