Skip to content

AI-powered virtual executive team — a single coherent executive persona backed by 8 specialist agents (FastAPI + Next.js).

feat(delegation): show whether the mailbox sign-in includes the calendar (#492)

Rufusb0ffa85f4666
diff --git a/packages/core/openexecutive/api/routes/delegation.py b/packages/core/openexecutive/api/routes/delegation.py
index 7dc36bf2..539b80e1 100644
--- a/packages/core/openexecutive/api/routes/delegation.py
+++ b/packages/core/openexecutive/api/routes/delegation.py
@@ -282,10 +282,13 @@ class DisclosureOut(BaseModel):
class CalendarOut(BaseModel):
- """Read my calendar (delegation.calendar): the caller's own switch, and
- the command that connects their mailbox with calendar access."""
+ """Read my calendar (delegation.calendar): the caller's own switch,
+ whether their mailbox sign-in includes the calendar (None when their
+ mailbox isn't connected or the provider didn't say), and the command that
+ connects it with calendar access."""
enabled: bool
+ granted: bool | None = None
connect_command: str
@@ -535,13 +538,21 @@ def _outlook_connect_command(email: str | None) -> str:
return f"uv run python scripts/connect-own-outlook.py --email {target}"
-def _calendar_out(person: Person) -> CalendarOut:
+async def _calendar_out(person: Person, status: str) -> CalendarOut:
from openexecutive.delegation import calendar
email = person.email or ""
outlook = bool(email) and credential_provider(email) == "microsoft"
command = _outlook_connect_command(email) if outlook else _connect_command(email)
- return CalendarOut(enabled=calendar.enabled(person.id), connect_command=f"{command} --calendar")
+ granted: bool | None = None
+ if status == "connected":
+ # The status check just refreshed the sign-in, so this reads the
+ # scopes it came back with rather than asking again.
+ try:
+ granted = await gmail_for(email).calendar_granted()
+ except Exception:
+ logger.warning("delegation: couldn't tell whether the sign-in includes the calendar", exc_info=True)
+ return CalendarOut(enabled=calendar.enabled(person.id), granted=granted, connect_command=f"{command} --calendar")
def _inbox_out(person_id: int) -> InboxOut:
@@ -608,7 +619,7 @@ async def _state(person: Person) -> DelegationOut:
handle_it=_handle_it_out(_person_id(person)),
training=_training_out(_person_id(person)),
disclosure=_disclosure_out(_person_id(person)),
- calendar=_calendar_out(person),
+ calendar=await _calendar_out(person, status),
team=_team_out(person),
)
diff --git a/packages/core/openexecutive/delegation/calendar.py b/packages/core/openexecutive/delegation/calendar.py
index b2d5f5f0..7a78dd19 100644
--- a/packages/core/openexecutive/delegation/calendar.py
+++ b/packages/core/openexecutive/delegation/calendar.py
@@ -34,8 +34,8 @@ logger = logging.getLogger(__name__)
MAX_DAYS = 31
NOT_GRANTED = (
- "Your saved sign-in doesn't include your calendar. Connect again with --calendar "
- "(Settings → Act as me shows the command), then turn Read my calendar on."
+ "Your saved sign-in doesn't include your calendar. Add it under Read my calendar "
+ "in Delegate → Act as me, then turn Read my calendar on."
)
OFF = "Read my calendar is off. They can turn it on in Settings → Act as me."
diff --git a/packages/core/openexecutive/delegation/gmail.py b/packages/core/openexecutive/delegation/gmail.py
index b3c1af8e..c4042d42 100644
--- a/packages/core/openexecutive/delegation/gmail.py
+++ b/packages/core/openexecutive/delegation/gmail.py
@@ -1211,6 +1211,14 @@ class DelegateGmail:
)
+ async def calendar_granted(self) -> bool | None:
+ """Whether their saved sign-in includes ``calendar.readonly``; None
+ when Google didn't say which scopes it carries."""
+ async with self._client() as client:
+ await self._access_token(client)
+ granted = _GRANTED.get(_token_key(self._cred()), "")
+ return SCOPE_CALENDAR in granted.split() if granted else None
+
async def list_events(self, start: datetime, end: datetime, *, max_results: int = MAX_EVENTS) -> list[CalendarEvent]:
"""The events on their primary calendar between ``start`` and ``end``,
recurring ones expanded, in order. Read-only (``calendar.readonly``)."""
diff --git a/packages/core/openexecutive/delegation/outlook.py b/packages/core/openexecutive/delegation/outlook.py
index 9f134f8d..6b2cdece 100644
--- a/packages/core/openexecutive/delegation/outlook.py
+++ b/packages/core/openexecutive/delegation/outlook.py
@@ -638,6 +638,14 @@ class DelegateOutlook:
a Gmail one) is matched by that sign-in address."""
return normalize_email(str(me.get("mail") or me.get("userPrincipalName") or ""))
+ async def calendar_granted(self) -> bool | None:
+ """Whether their saved sign-in includes ``Calendars.Read``; None when
+ Microsoft didn't say which scopes it carries."""
+ async with self._client() as client:
+ await self._access_token(client)
+ granted = _GRANTED.get(_token_key(self._cred()), "")
+ return bool(CALENDAR_SCOPES & _granted(granted)) if granted else None
+
async def list_events(self, start: datetime, end: datetime, *, max_results: int = MAX_EVENTS) -> list[CalendarEvent]:
"""The events on their calendar between ``start`` and ``end``,
recurring ones expanded, in order (``calendarView``), times in UTC.
diff --git a/packages/core/tests/unit/test_delegation_gmail.py b/packages/core/tests/unit/test_delegation_gmail.py
index 255c40dd..77c9f026 100644
--- a/packages/core/tests/unit/test_delegation_gmail.py
+++ b/packages/core/tests/unit/test_delegation_gmail.py
@@ -346,7 +346,7 @@ def test_the_only_send_is_an_existing_draft_by_its_id() -> None:
# Checks an id's shape (Gmail's and Outlook's differ); no call.
"valid_id",
# Read my calendar (delegation.calendar): read-only.
- "list_events",
+ "list_events", "calendar_granted",
}
# Gmail's send endpoints (/settings/sendAs is a read, and allowed): the
# draft one, once, and never messages.send, which sends any text.
@@ -686,6 +686,17 @@ def test_a_sign_in_without_the_calendar_says_so_before_asking_google() -> None:
assert all(r.url.host == "oauth2.googleapis.com" for r in seen)
+def test_the_sign_in_says_whether_it_includes_the_calendar() -> None:
+ _seen, with_it = _calendar_google(" ".join([*gm.SCOPES, gm.SCOPE_CALENDAR]))
+ assert asyncio.run(with_it.calendar_granted()) is True
+ gm._TOKENS.clear()
+ _seen, without = _calendar_google(" ".join(gm.SCOPES))
+ assert asyncio.run(without.calendar_granted()) is False
+ gm._TOKENS.clear()
+ _seen, unsaid = _calendar_google("")
+ assert asyncio.run(unsaid.calendar_granted()) is None
+
+
def test_a_refused_calendar_read_is_not_granted_not_a_reconnect() -> None:
_seen, client = _calendar_google("", status=403)
with pytest.raises(gm.CalendarNotGranted):
diff --git a/packages/core/tests/unit/test_delegation_outlook.py b/packages/core/tests/unit/test_delegation_outlook.py
index b9e80ac8..a1d4b95f 100644
--- a/packages/core/tests/unit/test_delegation_outlook.py
+++ b/packages/core/tests/unit/test_delegation_outlook.py
@@ -764,6 +764,14 @@ def test_an_outlook_sign_in_without_the_calendar_says_so() -> None:
asyncio.run(refused.list_events(*_DAY))
+def test_an_outlook_sign_in_says_whether_it_includes_the_calendar() -> None:
+ _seen, with_it = _calendar_graph(f"{_MAIL} https://graph.microsoft.com/Calendars.Read")
+ assert asyncio.run(with_it.calendar_granted()) is True
+ ol._TOKENS.clear()
+ _seen, without = _calendar_graph(_MAIL)
+ assert asyncio.run(without.calendar_granted()) is False
+
+
def test_the_outlook_script_asks_for_the_calendar_only_with_the_flag() -> None:
script = _script()
assert "Calendars.Read" not in script.SCOPE
diff --git a/packages/core/tests/unit/test_delegation_route.py b/packages/core/tests/unit/test_delegation_route.py
index ecd678e7..3467c1c4 100644
--- a/packages/core/tests/unit/test_delegation_route.py
+++ b/packages/core/tests/unit/test_delegation_route.py
@@ -424,10 +424,14 @@ def test_a_style_is_written_from_their_words_without_saving(
class _Calendar:
- def __init__(self, outcome: Exception | None = None) -> None:
+ def __init__(self, outcome: Exception | None = None, granted: bool | None = False) -> None:
self.outcome = outcome
+ self.granted = granted
self.asked = 0
+ async def calendar_granted(self) -> bool | None:
+ return self.granted
+
async def list_events(self, start: Any, end: Any, *, max_results: int = 100) -> list[Any]:
self.asked += 1
if self.outcome is not None:
@@ -448,21 +452,24 @@ def test_read_my_calendar_turns_on_only_once_the_calendar_opens(
box = _Calendar(CalendarNotGranted("no"))
monkeypatch.setattr(route, "gmail_for", lambda email: box)
body = client.get("/delegation", headers=OWNER).json()
+ # Not connected: whether the sign-in includes the calendar isn't known.
assert body["calendar"] == {
- "enabled": False, "connect_command": body["gmail"]["connect_command"] + " --calendar",
+ "enabled": False, "granted": None, "connect_command": body["gmail"]["connect_command"] + " --calendar",
}
resp = client.put("/delegation/calendar", json={"enabled": True}, headers=OWNER)
assert resp.status_code == 409 and resp.json()["detail"]["code"] == "act_as_me_off"
gmail["status"] = "connected"
+ assert client.get("/delegation", headers=OWNER).json()["calendar"]["granted"] is False
client.put("/delegation", json={"enabled": True}, headers=OWNER)
resp = client.put("/delegation/calendar", json={"enabled": True}, headers=OWNER)
assert resp.status_code == 409 and resp.json()["detail"]["code"] == "calendar_not_granted"
box.outcome = GmailError("down")
assert client.put("/delegation/calendar", json={"enabled": True}, headers=OWNER).status_code == 503
assert calendar.enabled(ids["principal"]) is False
- box.outcome = None
+ box.outcome, box.granted = None, True
body = client.put("/delegation/calendar", json={"enabled": True}, headers=OWNER).json()
assert body["calendar"]["enabled"] is True and calendar.enabled(ids["principal"]) is True
+ assert body["calendar"]["granted"] is True
assert calendar.enabled(ids["teammate"]) is False
# Act as me off takes it with it, and it is audited privately each way.
client.put("/delegation", json={"enabled": False}, headers=OWNER)
diff --git a/packages/core/tests/unit/test_mail_read_tools.py b/packages/core/tests/unit/test_mail_read_tools.py
index 3830fcd5..d0005a22 100644
--- a/packages/core/tests/unit/test_mail_read_tools.py
+++ b/packages/core/tests/unit/test_mail_read_tools.py
@@ -619,7 +619,7 @@ def test_my_calendar_lists_their_day_in_their_time_zone(calendar_on: None) -> No
def test_my_calendar_says_how_to_add_it_to_their_sign_in(calendar_on: None) -> None:
result = _calendar(_session(CalendarMailbox(granted=False)), {})
- assert result["status"] == "calendar_not_granted" and "--calendar" in result["error"]
+ assert result["status"] == "calendar_not_granted" and "Read my calendar in Delegate → Act as me" in result["error"]
def test_my_calendar_refuses_a_bad_date_and_caps_the_span(calendar_on: None) -> None:
diff --git a/packages/ui/src/components/settings/ActAsMeCard.tsx b/packages/ui/src/components/settings/ActAsMeCard.tsx
index 019855da..fedd0699 100644
--- a/packages/ui/src/components/settings/ActAsMeCard.tsx
+++ b/packages/ui/src/components/settings/ActAsMeCard.tsx
@@ -403,7 +403,8 @@ function InboxSection({
// Read my calendar (PUT /delegation/calendar): the Executive reads your own
// calendar, read-only, when you ask about your day. Turning it on checks the
-// calendar opens; a sign-in made without it shows the command that adds it.
+// calendar opens; a sign-in made without it shows the command that adds it,
+// and one that already includes it shows nothing more.
function CalendarSection({
calendar,
actAsMeOn,
@@ -449,10 +450,12 @@ function CalendarSection({
/>
}
>
- {!on && actAsMeOn && (
+ {!on && actAsMeOn && calendar.granted !== true && (
<div>
<p className="text-sm text-fg-muted leading-relaxed">
- If you connected your mailbox before, run this once to add your calendar to the sign-in:
+ {calendar.granted === false
+ ? "Your mailbox sign-in doesn't include your calendar yet. Run this once to add it:"
+ : "If you connected your mailbox before, run this once to add your calendar to the sign-in:"}
</p>
<pre className="mt-2 whitespace-pre-wrap break-all rounded-xl border border-line bg-surface px-3 py-2 text-xs text-fg font-mono">
{calendar.connect_command}
diff --git a/packages/ui/src/lib/api.ts b/packages/ui/src/lib/api.ts
index 2cb6bb2b..4b3cf1e1 100644
--- a/packages/ui/src/lib/api.ts
+++ b/packages/ui/src/lib/api.ts
@@ -1720,9 +1720,11 @@ export interface Training {
// Read my calendar (delegation/calendar.py): your own calendar, read-only,
// through the same sign-in as your mailbox when it was connected with
-// --calendar (connect_command).
+// --calendar (connect_command). `granted`: whether that sign-in includes the
+// calendar; null (or absent, on an older backend) when it isn't known.
export interface ReadMyCalendar {
enabled: boolean;
+ granted?: boolean | null;
connect_command: string;
}