Skip to content

Self-improving AI Employees for everyone

Fix employee hire navigation and access request correlation

trohitgbae935c7d567
diff --git a/client/src/features/home/__tests__/employeeAccess.test.tsx b/client/src/features/home/__tests__/employeeAccess.test.tsx
index 13c311b7..dee49aab 100644
--- a/client/src/features/home/__tests__/employeeAccess.test.tsx
+++ b/client/src/features/home/__tests__/employeeAccess.test.tsx
@@ -21,7 +21,7 @@ describe('employee app access', () => {
show(true);
expect(await screen.findByText('Allow Maya’s team to use Calendar to manage appointments?')).toBeInTheDocument();
await userEvent.click(screen.getByRole('button', { name: 'Allow' }));
- await waitFor(() => expect(sendRequest).toHaveBeenCalledWith('decide_employee_access', { request_id: 'permission', allow: true }));
+ await waitFor(() => expect(sendRequest).toHaveBeenCalledWith('decide_employee_access', { access_request_id: 'permission', allow: true }));
expect(screen.getByRole('button', { name: 'Not now' })).toBeInTheDocument();
});
@@ -29,7 +29,16 @@ describe('employee app access', () => {
sendRequest.mockResolvedValue({ success: true, access: [{ id: 'permission', app: 'Calendar', action: 'manage appointments', approved: true, revoked: false }] });
show();
await userEvent.click(await screen.findByRole('button', { name: 'Remove access' }));
- expect(sendRequest).toHaveBeenCalledWith('decide_employee_access', { request_id: 'permission', allow: false });
+ expect(sendRequest).toHaveBeenCalledWith('decide_employee_access', { access_request_id: 'permission', allow: false });
+ });
+
+ it('declines access using its permission identity without replacing socket correlation', async () => {
+ sendRequest.mockResolvedValue({ success: true, access: [{ id: 'permission', app: 'Calendar', approved: false, revoked: false }] });
+ show(true);
+ await userEvent.click(await screen.findByRole('button', { name: 'Not now' }));
+ expect(sendRequest).toHaveBeenCalledWith('decide_employee_access', { access_request_id: 'permission', allow: false });
+ const [, payload] = sendRequest.mock.calls.find(([type]) => type === 'decide_employee_access')!;
+ expect(payload).not.toHaveProperty('request_id');
});
it('hides rejected requests from the conversational permission prompt', async () => {
@@ -44,7 +53,7 @@ describe('employee app access', () => {
show();
expect(await screen.findByText('Maya’s team no longer has access to Calendar.')).toBeInTheDocument();
await userEvent.click(screen.getByRole('button', { name: 'Allow again' }));
- expect(sendRequest).toHaveBeenCalledWith('decide_employee_access', { request_id: 'permission', allow: true });
+ expect(sendRequest).toHaveBeenCalledWith('decide_employee_access', { access_request_id: 'permission', allow: true });
expect(screen.queryByRole('button', { name: 'Not now' })).not.toBeInTheDocument();
});
diff --git a/client/src/features/home/employee/EmployeeAccess.tsx b/client/src/features/home/employee/EmployeeAccess.tsx
index 35365571..03e3a550 100644
--- a/client/src/features/home/employee/EmployeeAccess.tsx
+++ b/client/src/features/home/employee/EmployeeAccess.tsx
@@ -15,7 +15,7 @@ export function EmployeeAccess({ workflowId, name, pendingOnly = false }: { work
return response.access || [];
}, refetchInterval: 5000 });
const decide = useMutation({ mutationFn: async ({ id, allow }: { id: string; allow: boolean }) => {
- const response = await sendRequest<{ success: boolean }>('decide_employee_access', { request_id: id, allow });
+ const response = await sendRequest<{ success: boolean }>('decide_employee_access', { access_request_id: id, allow });
if (!response?.success) throw new Error('That permission could not be changed.');
}, onSuccess: () => cache.invalidateQueries({ queryKey: key }), onError: (error: Error) => pillToast(error.message, { tone: 'error' }) });
const rows = (access.data || []).filter((row) => !row.parent_grant_id && (!pendingOnly || (!row.approved && !row.revoked)));
diff --git a/client/src/features/home/genui/HireDraftPanel.tsx b/client/src/features/home/genui/HireDraftPanel.tsx
index 3fe856f4..95de010f 100644
--- a/client/src/features/home/genui/HireDraftPanel.tsx
+++ b/client/src/features/home/genui/HireDraftPanel.tsx
@@ -260,6 +260,11 @@ export function HireDraftPanel({ onConnect }: { onConnect: (providerId: string)
</div>
{status === 'working' && <WorkingLine token={token} onCancel={actions.cancel} />}
+ {hiring && (
+ <p role="status" className="m-0 text-sm text-fg-muted">
+ Hiring your employee…
+ </p>
+ )}
{status === 'failed' && failure && (
<FailureNotice failure={failure} onRetry={() => void actions.retry()} onConnectAi={openConnectAI} />
)}
diff --git a/client/src/features/home/genui/__tests__/HireDraftPanel.test.tsx b/client/src/features/home/genui/__tests__/HireDraftPanel.test.tsx
index 166904da..124fd942 100644
--- a/client/src/features/home/genui/__tests__/HireDraftPanel.test.tsx
+++ b/client/src/features/home/genui/__tests__/HireDraftPanel.test.tsx
@@ -156,6 +156,7 @@ describe('HireDraftPanel', () => {
const hires = sendRequest.mock.calls.filter(([type]) => type === 'hire_employee');
expect(hires).toHaveLength(1);
expect(hires[0][1]).toMatchObject({ name: 'Maya', rules: { ask_first: true } });
+ expect(screen.getByText('Hiring your employee…')).toHaveAttribute('role', 'status');
await act(async () => {
finish(hired());
@@ -168,6 +169,43 @@ describe('HireDraftPanel', () => {
expect(useHomeStore.getState().glow?.workflowId).toBe('w1');
expect(useHomeStore.getState().view).toEqual({ kind: 'employee', workflowId: 'w1' });
expect(useHomeStore.getState().hireNotice).toBeNull();
+ expect(screen.queryByText('Hiring your employee…')).not.toBeInTheDocument();
+ });
+
+ it('opens Arjun’s page after a scheduled hire even when WhatsApp is not connected', async () => {
+ const setup = JSON.parse(reply);
+ setup.text = 'Meet Arjun, your weather reporter.';
+ setup.spec.elements.b.props = {
+ name: 'Arjun', role: 'Weather Reporter', description: 'Monitors Bangalore weather and sends your daily forecast.',
+ apps: ['Web browser', 'WhatsApp'], status: 'ready',
+ };
+ setup.spec.elements.c.props.steps = [
+ { title: 'Every day at 08:00', detail: 'Starts daily forecast routine.', role: 'trigger' },
+ { title: 'Check Bangalore weather', detail: 'Looks up temperatures and rain chances.', role: 'tool', app: 'Web browser' },
+ { title: 'Prepare brief forecast', detail: 'Summarizes conditions.', role: 'agent' },
+ { title: 'Send morning summary', detail: 'Delivers to WhatsApp.', role: 'tool', app: 'WhatsApp' },
+ ];
+ setup.spec.elements.i.props = {
+ label: 'Hire Arjun', variant: 'primary', action: 'hire_employee',
+ actionParams: { name: 'Arjun', role: 'Weather Reporter', apps: ['Web browser', 'WhatsApp'],
+ trigger: { kind: 'schedule', every: 'day', at: '08:00' }, sendsVia: 'WhatsApp' },
+ };
+ seedReadyDraft(JSON.stringify(setup));
+ useDraftStore.setState({ job: 'Monitor Bangalore weather and send a daily forecast to WhatsApp' });
+ sendRequest.mockImplementation((_type: string, payload: Record<string, unknown>) => Promise.resolve(hired({
+ type: 'hire_employee_result', request_id: 'wire-hire-arjun', operation_request_id: payload.idempotency_key,
+ started: false, activation_state: 'blocked',
+ employee: { workflow_id: 'arjun-workflow', name: 'Arjun', role: 'Weather Reporter', status: 'ready', control: {}, revision: 1 },
+ missing_apps: [{ app_id: 'whatsapp', name: 'WhatsApp', connected: false }],
+ })));
+ renderPanel();
+ const hire = await screen.findByRole('button', { name: 'Hire Arjun' });
+ await act(async () => { fireEvent.click(hire); });
+ await waitFor(() => expect(useHomeStore.getState().view).toEqual({ kind: 'employee', workflowId: 'arjun-workflow' }));
+ expect(useDraftStore.getState()).toMatchObject({ status: 'idle', hiring: false });
+ expect(sendRequest).toHaveBeenCalledWith('hire_employee', expect.objectContaining({
+ name: 'Arjun', trigger: { kind: 'schedule', every: 'day', at: '08:00' }, rules: expect.objectContaining({ ask_first: true }),
+ }), expect.any(Number));
});
it('keeps what the hire said for the new employee’s page, and asks for an AI model when there is none', async () => {
diff --git a/client/src/features/home/genui/useHire.ts b/client/src/features/home/genui/useHire.ts
index c8effffe..912a2579 100644
--- a/client/src/features/home/genui/useHire.ts
+++ b/client/src/features/home/genui/useHire.ts
@@ -46,6 +46,10 @@ export function hireErrorMessage(code: unknown): string {
}
export interface HireResponse {
+ /** WebSocket correlation ID; the server owns the transport envelope. */
+ request_id?: string;
+ /** Stable hiring identity, kept separate from each retry's socket ID. */
+ operation_request_id?: string;
success?: boolean;
error?: string;
employee?: unknown;
diff --git a/server/routers/websocket.py b/server/routers/websocket.py
index f25cf1eb..f64994d4 100644
--- a/server/routers/websocket.py
+++ b/server/routers/websocket.py
@@ -1452,7 +1452,14 @@ async def _execute_handler(handler: MessageHandler, data: Dict[str, Any], websoc
result = await handler(data, websocket)
if request_id:
- await _safe_send(websocket, {"type": f"{msg_type}_result", "request_id": request_id, **result})
+ # request_id belongs to the socket's pending-request registry.
+ # Hiring and delivery also return durable operation IDs; those
+ # must not orphan the browser request after the operation saves.
+ response = {"type": f"{msg_type}_result", **result, "request_id": request_id}
+ operation_request_id = result.get("request_id")
+ if operation_request_id is not None and operation_request_id != request_id:
+ response["operation_request_id"] = operation_request_id
+ await _safe_send(websocket, response)
else:
await _safe_send(websocket, result)
diff --git a/server/services/employees/handlers.py b/server/services/employees/handlers.py
index 7687b9b2..36839060 100644
--- a/server/services/employees/handlers.py
+++ b/server/services/employees/handlers.py
@@ -291,7 +291,12 @@ async def handle_list_employee_access(data: Dict[str, Any], websocket: WebSocket
async def handle_decide_employee_access(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
from core.container import container
from services.employees.permissions import decide_access
- request_id = str(data.get("request_id") or "")
+ # request_id belongs to the socket transport. Older direct service calls
+ # without a message type may still supply the domain ID under that name.
+ identifier = data.get("access_request_id")
+ if "access_request_id" not in data and "type" not in data:
+ identifier = data.get("request_id")
+ request_id = identifier.strip() if isinstance(identifier, str) else ""
if not request_id or not isinstance(data.get("allow"), bool):
return {"success": False, "error": "invalid_request"}
allowed = await decide_access(container.database(), request_id, execution_principal(data, websocket), data["allow"])
diff --git a/server/tests/services/employees/test_hire_handler.py b/server/tests/services/employees/test_hire_handler.py
index ad12f9b5..30853657 100644
--- a/server/tests/services/employees/test_hire_handler.py
+++ b/server/tests/services/employees/test_hire_handler.py
@@ -151,6 +151,41 @@ async def test_the_same_key_finds_the_same_employee(harness):
assert len(harness.starts) == 1
+async def test_scheduled_hire_with_disconnected_whatsapp_replies_to_each_transport_request(harness, monkeypatch):
+ import routers.websocket as router
+
+ replies = []
+
+ async def send(_socket, frame):
+ replies.append(frame)
+
+ monkeypatch.setattr(router, "_safe_send", send)
+ data = payload(
+ idempotency_key="hire-arjun",
+ name="Arjun",
+ role="Weather Reporter",
+ job="Monitor Bangalore weather and send a daily forecast to WhatsApp",
+ apps=["Web browser", "WhatsApp"],
+ steps=[{"title": "Check Bangalore weather", "role": "tool", "app": "Web browser"}],
+ trigger={"kind": "schedule", "every": "day", "at": "08:00"},
+ sends_via="WhatsApp",
+ )
+ for request_id in ("wire-first-hire", "wire-retry"):
+ await router._execute_handler(hire.handle_hire_employee, {**data, "request_id": request_id}, SOCKET, "hire_employee", request_id)
+ reply = replies[-1]
+ assert reply["success"] is True, reply
+ assert reply["request_id"] == request_id
+ assert reply["operation_request_id"] == "hire-arjun"
+ assert reply["employee"]["name"] == "Arjun"
+ assert reply["started"] is False
+ assert any(app["app_id"] == "whatsapp" for app in reply["missing_apps"])
+
+ assert replies[1]["idempotent"] is True
+ assert replies[0]["employee"]["workflow_id"] == replies[1]["employee"]["workflow_id"]
+ assert len(await harness.database.get_all_workflows()) == 1
+ assert harness.starts == []
+
+
async def test_a_changed_payload_under_the_same_key_is_refused(harness):
await hire.handle_hire_employee(payload(), SOCKET)
changed = await hire.handle_hire_employee(payload(name="Bea"), SOCKET)
diff --git a/server/tests/services/employees/test_permissions.py b/server/tests/services/employees/test_permissions.py
index ff4a1047..03d36669 100644
--- a/server/tests/services/employees/test_permissions.py
+++ b/server/tests/services/employees/test_permissions.py
@@ -1,4 +1,5 @@
import pytest
+from types import SimpleNamespace
from models.employees import EmployeeGrant
from services.employees.permissions import assert_runtime_access, decide_access, list_access
@@ -58,3 +59,48 @@ async def test_access_listing_is_owner_scoped(real_database):
assert await list_access(real_database, "7", "another-owner") == []
assert await list_access(real_database, "another-workflow", "owner") == []
assert len(await list_access(real_database, "7", "owner")) == 2
+
+
+def permission_socket(real_database, monkeypatch):
+ import core.container as container_module
+ monkeypatch.setattr(container_module, "container", SimpleNamespace(database=lambda: real_database))
+ return SimpleNamespace(scope={"path": "/ws/status"}, state=SimpleNamespace(user_id="owner"))
+
+
[email protected]("allow", [True, False])
+async def test_permission_handler_separates_grant_identity_from_transport_id(real_database, permission_socket, allow):
+ from services.employees.handlers import handle_decide_employee_access
+ await install(real_database)
+ await decide_access(real_database, "bundle", "owner", not allow)
+ async with real_database.get_session() as session:
+ session.add(EmployeeGrant(id="transport-id", workflow_id="7", owner_id="owner", capability="calendar", limits={"approved": True}))
+ await session.commit()
+ result = await handle_decide_employee_access({"type": "decide_employee_access", "request_id": "transport-id",
+ "access_request_id": "bundle", "allow": allow, "user_id": "another-owner"}, permission_socket)
+ assert result == {"success": True}
+ async with real_database.get_session() as session:
+ grant = await session.get(EmployeeGrant, "bundle")
+ assert grant.limits["approved"] is allow
+ assert (grant.revoked_at is None) is allow
+ assert (await session.get(EmployeeGrant, "transport-id")).limits["approved"] is True
+
+
+async def test_permission_handler_keeps_legacy_direct_calls_but_never_uses_socket_correlation_as_grant(real_database, permission_socket):
+ from services.employees.handlers import handle_decide_employee_access
+ await install(real_database)
+ assert await handle_decide_employee_access({"request_id": "bundle", "allow": False}, permission_socket) == {"success": True}
+ assert await handle_decide_employee_access({"type": "decide_employee_access", "request_id": "bundle", "allow": True}, permission_socket) == {
+ "success": False, "error": "invalid_request"}
+ async with real_database.get_session() as session:
+ assert (await session.get(EmployeeGrant, "bundle")).revoked_at is not None
+
+
+async def test_permission_handler_enforces_owner_for_explicit_grant_identity(real_database, permission_socket):
+ from services.employees.handlers import handle_decide_employee_access
+ await install(real_database)
+ permission_socket.state.user_id = "another-owner"
+ assert await handle_decide_employee_access({"type": "decide_employee_access", "request_id": "transport-id",
+ "access_request_id": "bundle", "allow": False, "user_id": "owner"}, permission_socket) == {"success": False, "error": "not_found"}
+ async with real_database.get_session() as session:
+ assert (await session.get(EmployeeGrant, "bundle")).revoked_at is None
diff --git a/server/tests/test_ws_response_correlation.py b/server/tests/test_ws_response_correlation.py
new file mode 100644
index 00000000..217f17d5
--- /dev/null
+++ b/server/tests/test_ws_response_correlation.py
@@ -0,0 +1,57 @@
+"""Business request identities must never replace WebSocket correlation IDs."""
+
+from types import SimpleNamespace
+from unittest.mock import AsyncMock
+
+import pytest
+
+from routers.websocket import _execute_handler
+
+
+class Socket:
+ def __init__(self):
+ self.client_state = SimpleNamespace(name="CONNECTED")
+ self.send_json = AsyncMock()
+
+
+ ("operation", "success"),
+ [("hire_employee", True), ("hire_employee", False), ("resolve_employee_delivery", True)],
+)
+async def test_business_request_id_cannot_orphan_the_pending_client_request(operation, success):
+ result = {"success": success, "request_id": "durable-operation", "state": "saved"}
+ original = dict(result)
+ handler = AsyncMock(return_value=result)
+ socket = Socket()
+
+ await _execute_handler(handler, {"request_id": "socket-request"}, socket, operation, "socket-request")
+
+ frame = socket.send_json.call_args.args[0]
+ assert frame["request_id"] == "socket-request"
+ assert frame["operation_request_id"] == "durable-operation"
+ assert frame["type"] == f"{operation}_result"
+ assert frame["success"] is success and frame["state"] == "saved"
+ assert result == original
+
+
+async def test_handler_specific_response_types_remain_compatible():
+ socket = Socket()
+ await _execute_handler(AsyncMock(return_value={"success": True, "type": "status"}), {}, socket, "hire_employee", "wire")
+ assert socket.send_json.call_args.args[0]["type"] == "status"
+
+
[email protected]("returned_id", [None, "socket-request"])
+async def test_ordinary_responses_keep_their_existing_shape(returned_id):
+ result = {"success": True, "employee": {"workflow_id": "1"}}
+ if returned_id:
+ result["request_id"] = returned_id
+ socket = Socket()
+ await _execute_handler(AsyncMock(return_value=result), {}, socket, "hire_employee", "socket-request")
+ assert socket.send_json.call_args.args[0] == {**result, "type": "hire_employee_result", "request_id": "socket-request"}
+
+
+async def test_uncorrelated_handler_results_are_unchanged():
+ result = {"success": True, "request_id": "business-only", "type": "progress"}
+ socket = Socket()
+ await _execute_handler(AsyncMock(return_value=result), {}, socket, "progress", None)
+ socket.send_json.assert_awaited_once_with(result)