Skip to content

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

feat(platform): add Microsoft 365 Copilot transport (#14202)

Nicholas Tindlee71c2c99c600
diff --git a/autogpt_platform/backend/.env.default b/autogpt_platform/backend/.env.default
index 79c5f9b4c1..0fb6eb855a 100644
--- a/autogpt_platform/backend/.env.default
+++ b/autogpt_platform/backend/.env.default
@@ -302,7 +302,9 @@ AUTOPILOT_BOT_TELEGRAM_WEBHOOK_SECRET=
# mandatory: new registrations are single-tenant only since 2025-07-31. In
# channels the bot only sees messages that @mention it — commands included,
# e.g. "@AutoGPT /setup".
-MICROSOFT_CLIENT_ID=
+# Public Entra application ID used by Microsoft 365 Copilot device auth and,
+# when the server-only values below are set, by the Teams bot adapter.
+MICROSOFT_CLIENT_ID=ce01a4d6-be71-42a0-86b1-6540838eb17c
MICROSOFT_CLIENT_SECRET=
MICROSOFT_TENANT_ID=
# Local only: accept unsigned activities so the M365 Agents Playground (which
diff --git a/autogpt_platform/backend/backend/api/features/chat/routes.py b/autogpt_platform/backend/backend/api/features/chat/routes.py
index 65554b0fb0..4a18a8750a 100644
--- a/autogpt_platform/backend/backend/api/features/chat/routes.py
+++ b/autogpt_platform/backend/backend/api/features/chat/routes.py
@@ -606,8 +606,8 @@ class SetDefaultTransportRequest(BaseModel):
"""The connection new chats should start on.
``auth_provider: null`` clears the choice and hands the decision back to
- the server. Sending ``codex`` requires naming the credential, so the
- default keeps pointing at one account rather than "whichever ChatGPT".
+ the server. A user-backed provider requires naming the credential, so the
+ default keeps pointing at one account rather than whichever account exists.
"""
model_config = ConfigDict(extra="forbid")
@@ -645,7 +645,7 @@ async def set_default_chat_transport(
)
except InvalidDefaultChatRoute as e:
raise HTTPException(
- status_code=404 if e.detail == "codex_credential_not_found" else 422,
+ status_code=404 if e.detail.endswith("_credential_not_found") else 422,
detail=e.detail,
) from e
return ChatTransportsResponse(transports=transports)
@@ -662,10 +662,10 @@ async def _resolve_new_session_llm_route(
await enforce_codex_access_http(user_id)
if request is not None and request.builder_graph_id is not None:
- if auth_provider == "codex" or credential_id is not None:
+ if auth_provider != "platform" or credential_id is not None:
raise HTTPException(
status_code=422,
- detail="codex_builder_session_unsupported",
+ detail=f"{auth_provider}_builder_session_unsupported",
)
if not is_deployment_chat_available():
raise HTTPException(
@@ -685,10 +685,10 @@ async def _resolve_new_session_llm_route(
status_code=422,
detail="codex_credential_not_allowed",
)
- if auth_provider == "codex" and credential_id is None:
+ if auth_provider != "platform" and credential_id is None:
raise HTTPException(
status_code=422,
- detail="codex_credential_required",
+ detail=f"{auth_provider}_credential_required",
)
selected_route = next(
(
@@ -701,10 +701,10 @@ async def _resolve_new_session_llm_route(
None,
)
if selected_route is None:
- if auth_provider == "codex":
+ if auth_provider != "platform":
raise HTTPException(
status_code=404,
- detail="codex_credential_not_found",
+ detail=f"{auth_provider}_credential_not_found",
)
raise HTTPException(
status_code=503,
@@ -801,10 +801,10 @@ async def create_session(
)
if builder_graph_id:
- if llm_auth_provider == "codex":
+ if llm_auth_provider != "platform":
raise HTTPException(
status_code=422,
- detail="codex_builder_session_unsupported",
+ detail=f"{llm_auth_provider}_builder_session_unsupported",
)
session = await get_or_create_builder_session(
user_id,
@@ -959,8 +959,11 @@ async def change_session_connection_route(
if auth_provider == "platform" and credential_id is not None:
raise HTTPException(status_code=422, detail="codex_credential_not_allowed")
- if auth_provider == "codex" and credential_id is None:
- raise HTTPException(status_code=422, detail="codex_credential_required")
+ if auth_provider != "platform" and credential_id is None:
+ raise HTTPException(
+ status_code=422,
+ detail=f"{auth_provider}_credential_required",
+ )
transports = await get_chat_transports(user_id)
target = next(
@@ -976,8 +979,11 @@ async def change_session_connection_route(
if target is None:
# Same shapes the session-creation path uses, so a client that already
# handles them does not need a second vocabulary for the same refusals.
- if auth_provider == "codex":
- raise HTTPException(status_code=404, detail="codex_credential_not_found")
+ if auth_provider != "platform":
+ raise HTTPException(
+ status_code=404,
+ detail=f"{auth_provider}_credential_not_found",
+ )
raise HTTPException(status_code=503, detail="chat_transport_not_configured")
changed = await update_session_llm_route(
@@ -1551,23 +1557,6 @@ async def stream_chat_post(
request: Request body with message, is_user_message, and optional context.
user_id: Authenticated user ID.
"""
- # The Advanced tier is a paid capability, and it was only enforced where
- # the picker decides what to grey out. A client that skips the picker and
- # posts model="advanced" was served it, on our credits. Checked first,
- # before the session is touched or the message stored: a turn we are going
- # to refuse should leave nothing behind.
- if request.model == "advanced":
- try:
- entitled = await advanced_tier_entitled(user_id)
- except EntitlementUnavailable:
- # Not knowing is not permission. The picker stays generous when
- # the lookup is down; spending does not.
- raise HTTPException(
- status_code=503, detail="advanced_tier_unavailable"
- ) from None
- if not entitled:
- raise HTTPException(status_code=403, detail="advanced_tier_not_entitled")
-
import time
stream_start_time = time.perf_counter()
@@ -1585,6 +1574,22 @@ async def stream_chat_post(
)
session = await _validate_and_get_writable_session(session_id, user_id)
+ # Microsoft 365 Copilot owns its model choice and ignores AutoGPT's tier.
+ # Every other route can spend platform-gated premium inference, so a client
+ # that skips the picker still has to hold the Advanced entitlement.
+ if (
+ request.model == "advanced"
+ and session.metadata.llm_auth_provider != "microsoft_365_copilot"
+ ):
+ try:
+ entitled = await advanced_tier_entitled(user_id)
+ except EntitlementUnavailable:
+ raise HTTPException(
+ status_code=503, detail="advanced_tier_unavailable"
+ ) from None
+ if not entitled:
+ raise HTTPException(status_code=403, detail="advanced_tier_not_entitled")
+
# Fire-and-forget; per-user Redis dedup inside the helper provides
# cross-process / cross-restart idempotency. Same pattern as
# graphiti/ingest.py's ensure_dream_system_scheduled registration.
diff --git a/autogpt_platform/backend/backend/api/features/chat/routes_test.py b/autogpt_platform/backend/backend/api/features/chat/routes_test.py
index 8e7434efcc..22ce6f6abf 100644
--- a/autogpt_platform/backend/backend/api/features/chat/routes_test.py
+++ b/autogpt_platform/backend/backend/api/features/chat/routes_test.py
@@ -15,6 +15,7 @@ from backend.api.features.chat import routes as chat_routes
from backend.api.features.chat.routes import _strip_injected_context
from backend.copilot import transports as chat_transports
from backend.copilot.config import CopilotLlmAuthProvider
+from backend.copilot.model import ChatSession
from backend.copilot.offers import EntitlementUnavailable
from backend.copilot.rate_limit import SubscriptionTier
from backend.copilot.tools.models import ExpertSoulUpdatedResponse
@@ -25,6 +26,10 @@ from backend.integrations.codex.auth_bundle import (
CodexAuthTokensV1,
encode_provider_state,
)
+from backend.integrations.oauth.microsoft_365_copilot import (
+ Microsoft365CopilotDeviceAuthHandler,
+)
+from backend.integrations.providers import ProviderName
from backend.util.exceptions import NotFoundError
from backend.util.settings import BehaveAs
@@ -1215,6 +1220,18 @@ def _codex_credentials(
)
+def _microsoft_365_copilot_credentials(
+ credential_id: str = "cred-microsoft",
+) -> OAuth2Credentials:
+ return OAuth2Credentials(
+ id=credential_id,
+ provider=ProviderName.MICROSOFT_365_COPILOT,
+ access_token=SecretStr("access"),
+ refresh_token=SecretStr("refresh"),
+ scopes=Microsoft365CopilotDeviceAuthHandler.DEFAULT_SCOPES,
+ )
+
+
def _set_self_hosted_chat_config(
mocker: pytest_mock.MockerFixture,
*,
@@ -1281,6 +1298,36 @@ def test_list_chat_transports_hosted_defaults_to_platform_with_codex(
}
+def test_list_chat_transports_includes_microsoft_365_copilot(
+ test_user_id: str,
+) -> None:
+ lookup = chat_transports.credentials_manager.store.get_creds_by_provider
+ credential = _microsoft_365_copilot_credentials()
+ lookup.side_effect = lambda _user_id, provider: (
+ [credential] if provider == ProviderName.MICROSOFT_365_COPILOT else []
+ )
+
+ response = client.get("/transports")
+
+ assert response.status_code == 200
+ assert response.json()["transports"] == [
+ {
+ "auth_provider": "platform",
+ "credential_id": None,
+ "label": "AutoGPT Platform",
+ "available": True,
+ "default": True,
+ },
+ {
+ "auth_provider": "microsoft_365_copilot",
+ "credential_id": "cred-microsoft",
+ "label": "Microsoft 365 Copilot",
+ "available": True,
+ "default": False,
+ },
+ ]
+
+
def test_list_chat_transports_hosted_omits_codex_without_required_plan(
mocker: pytest_mock.MockerFixture,
test_user_id: str,
@@ -1308,7 +1355,7 @@ def test_list_chat_transports_hosted_omits_codex_without_required_plan(
]
}
access.assert_awaited_once_with(test_user_id)
- lookup.assert_not_awaited()
+ lookup.assert_awaited_once_with(test_user_id, ProviderName.MICROSOFT_365_COPILOT)
def test_list_chat_transports_omits_invalid_codex_credentials(
@@ -1649,7 +1696,7 @@ def test_create_session_codex_route_rejects_unowned_credential(
assert response.status_code == 404
assert response.json()["detail"] == "codex_credential_not_found"
- lookup.assert_awaited_once_with(test_user_id, "codex")
+ lookup.assert_any_await(test_user_id, "codex")
def test_create_session_codex_route_rejects_user_without_required_plan(
@@ -1717,6 +1764,44 @@ def test_create_session_codex_route_persists_owned_credential(
mock_paywall.assert_not_awaited()
+def test_create_session_microsoft_route_persists_owned_credential(
+ mocker: pytest_mock.MockerFixture,
+) -> None:
+ mock_create = _mock_create_chat_session(mocker)
+ mock_paywall = mocker.patch(
+ "backend.api.features.chat.routes.enforce_payment_paywall",
+ new_callable=AsyncMock,
+ )
+ codex_gate = mocker.patch.object(
+ chat_routes,
+ "enforce_codex_access_http",
+ new=AsyncMock(),
+ )
+ credential = _microsoft_365_copilot_credentials("cred-msft")
+ lookup = chat_transports.credentials_manager.store.get_creds_by_provider
+ lookup.side_effect = lambda _user_id, provider: (
+ [credential] if provider == ProviderName.MICROSOFT_365_COPILOT else []
+ )
+
+ response = client.post(
+ "/sessions",
+ json={
+ "llm_auth_provider": "microsoft_365_copilot",
+ "llm_credential_id": "cred-msft",
+ },
+ )
+
+ assert response.status_code == 200
+ assert response.json()["metadata"]["llm_auth_provider"] == ("microsoft_365_copilot")
+ assert response.json()["metadata"]["llm_credential_id"] == "cred-msft"
+ assert mock_create.call_args.kwargs["llm_auth_provider"] == (
+ "microsoft_365_copilot"
+ )
+ assert mock_create.call_args.kwargs["llm_credential_id"] == "cred-msft"
+ mock_paywall.assert_not_awaited()
+ codex_gate.assert_not_awaited()
+
+
def test_create_session_hosted_defaults_to_platform_with_codex_connected(
mocker: pytest_mock.MockerFixture,
test_user_id: str,
@@ -1737,7 +1822,7 @@ def test_create_session_hosted_defaults_to_platform_with_codex_connected(
assert response.json()["metadata"]["llm_credential_id"] is None
assert mock_create.call_args.kwargs["llm_auth_provider"] == "platform"
assert mock_create.call_args.kwargs["llm_credential_id"] is None
- lookup.assert_awaited_once_with(test_user_id, "codex")
+ lookup.assert_any_await(test_user_id, "codex")
mock_paywall.assert_awaited_once_with(test_user_id)
@@ -1868,7 +1953,8 @@ def test_create_session_respects_explicit_platform_route(
assert response.status_code == 200
assert response.json()["metadata"]["llm_auth_provider"] == "platform"
assert mock_create.call_args.kwargs["llm_auth_provider"] == "platform"
- lookup.assert_awaited_once()
+ lookup.assert_any_await(TEST_USER_ID, "codex")
+ lookup.assert_any_await(TEST_USER_ID, ProviderName.MICROSOFT_365_COPILOT)
def test_create_session_platform_route_still_enforces_paywall(
@@ -4042,6 +4128,7 @@ def test_advanced_tier_is_refused_without_the_entitlement(
validate = mocker.patch(
"backend.api.features.chat.routes._validate_and_get_writable_session",
new_callable=AsyncMock,
+ return_value=ChatSession.new(TEST_USER_ID, dry_run=False),
)
response = client.post(
@@ -4051,8 +4138,7 @@ def test_advanced_tier_is_refused_without_the_entitlement(
assert response.status_code == 403
assert response.json()["detail"] == "advanced_tier_not_entitled"
- # Refused before the session is even loaded, so nothing is left behind.
- validate.assert_not_called()
+ validate.assert_awaited_once_with("sess-1", TEST_USER_ID)
def test_advanced_tier_is_refused_when_entitlement_cannot_be_resolved(
@@ -4075,6 +4161,7 @@ def test_advanced_tier_is_refused_when_entitlement_cannot_be_resolved(
validate = mocker.patch(
"backend.api.features.chat.routes._validate_and_get_writable_session",
new_callable=AsyncMock,
+ return_value=ChatSession.new(TEST_USER_ID, dry_run=False),
)
response = client.post(
@@ -4087,7 +4174,47 @@ def test_advanced_tier_is_refused_when_entitlement_cannot_be_resolved(
assert detail == "advanced_tier_unavailable"
# The underlying failure is not handed to the client.
assert "billing down" not in str(detail)
- validate.assert_not_called()
+ validate.assert_awaited_once_with("sess-1", TEST_USER_ID)
+
+
+def test_advanced_tier_is_not_applied_to_microsoft_365_copilot(
+ mocker: pytest_mock.MockerFixture,
+) -> None:
+ entitled = mocker.patch(
+ "backend.api.features.chat.routes.advanced_tier_entitled",
+ new_callable=AsyncMock,
+ return_value=False,
+ )
+ session = ChatSession.new(
+ TEST_USER_ID,
+ dry_run=False,
+ llm_auth_provider="microsoft_365_copilot",
+ llm_credential_id="cred-msft",
+ )
+ mocker.patch(
+ "backend.api.features.chat.routes._validate_and_get_writable_session",
+ new=AsyncMock(return_value=session),
+ )
+ mocker.patch(
+ "backend.copilot.briefing.scheduling.ensure_morning_briefing_scheduled",
+ return_value=None,
+ )
+ mocker.patch.object(chat_routes, "spawn_background_task")
+ mocker.patch.object(
+ chat_routes,
+ "is_turn_in_flight",
+ new=AsyncMock(
+ side_effect=fastapi.HTTPException(status_code=418, detail="stop here")
+ ),
+ )
+
+ response = client.post(
+ "/sessions/sess-1/stream",
+ json={"message": "hello", "model": "advanced"},
+ )
+
+ assert response.status_code == 418
+ entitled.assert_not_awaited()
def test_standard_tier_is_not_gated(
diff --git a/autogpt_platform/backend/backend/blocks/_static_provider_configs.py b/autogpt_platform/backend/backend/blocks/_static_provider_configs.py
index a733298448..ede78eec87 100644
--- a/autogpt_platform/backend/backend/blocks/_static_provider_configs.py
+++ b/autogpt_platform/backend/backend/blocks/_static_provider_configs.py
@@ -24,6 +24,10 @@ _STATIC_PROVIDER_CONFIGS: dict[str, tuple[str, tuple[CredentialsType, ...]]] = {
"aiml_api": ("Unified access to 100+ AI models", ("api_key",)),
"anthropic": ("Claude language models", ("api_key",)),
"codex": ("Use your ChatGPT plan with Codex App Server", ("oauth2",)),
+ "microsoft_365_copilot": (
+ "Use your work or school Microsoft 365 Copilot plan",
+ ("device_code",),
+ ),
"groq": ("Fast LLM inference", ("api_key",)),
"llama_api": ("Llama model hosting", ("api_key",)),
"ollama": ("Run open-source LLMs locally", ("api_key",)),
diff --git a/autogpt_platform/backend/backend/copilot/config.py b/autogpt_platform/backend/backend/copilot/config.py
index 2b63e486ea..34ddb765a6 100644
--- a/autogpt_platform/backend/backend/copilot/config.py
+++ b/autogpt_platform/backend/backend/copilot/config.py
@@ -56,7 +56,7 @@ _DEFAULT_SIMULATION_MODEL = "google/gemini-2.5-flash-lite"
_DEFAULT_FAST_ADVANCED_MODEL = "anthropic/claude-opus-4-8"
TransportName = Literal["subscription", "openrouter", "direct_anthropic", "local"]
-CopilotLlmAuthProvider = Literal["platform", "codex"]
+CopilotLlmAuthProvider = Literal["platform", "codex", "microsoft_365_copilot"]
class TransportProfile(BaseModel):
diff --git a/autogpt_platform/backend/backend/copilot/executor/processor.py b/autogpt_platform/backend/backend/copilot/executor/processor.py
index 782c5a308f..9c62c96b6a 100644
--- a/autogpt_platform/backend/backend/copilot/executor/processor.py
+++ b/autogpt_platform/backend/backend/copilot/executor/processor.py
@@ -28,8 +28,17 @@ from backend.copilot.sdk import service as sdk_service
from backend.copilot.sdk.dummy import stream_chat_completion_dummy
from backend.copilot.stream_heartbeat import wrap_stream_with_heartbeat
from backend.copilot.trial_cost_context import trial_cost_context
+from backend.data.model import OAuth2Credentials
from backend.executor.cluster_lock import ClusterLock
from backend.integrations.codex.transport import CodexCredentialIntegrityError
+from backend.integrations.creds_manager import IntegrationCredentialsManager
+from backend.integrations.microsoft_365_copilot.service import (
+ stream_chat_completion_microsoft_365,
+)
+from backend.integrations.oauth.microsoft_365_copilot import (
+ Microsoft365CopilotDeviceAuthHandler,
+)
+from backend.integrations.providers import ProviderName
from backend.util.decorator import error_logged
from backend.util.exceptions import (
ExpertNotFoundError,
@@ -596,6 +605,45 @@ class CoPilotProcessor:
raise RuntimeError("codex_credential_not_found") from None
stream_fn = sdk_service.stream_chat_completion_sdk
log.info("Using Claude SDK with Codex subscription transport")
+ elif entry.llm_auth_provider == "microsoft_365_copilot":
+ if entry.user_id is None:
+ raise RuntimeError("microsoft_365_copilot_user_required")
+ if entry.llm_credential_id is None:
+ raise RuntimeError("microsoft_365_copilot_credential_required")
+ try:
+ credential_lease = (
+ await IntegrationCredentialsManager().acquire_lease(
+ entry.user_id,
+ entry.llm_credential_id,
+ )
+ )
+ credentials = credential_lease.credentials
+ required_scopes = set(
+ Microsoft365CopilotDeviceAuthHandler.CHAT_SCOPES
+ )
+ if (
+ not isinstance(credentials, OAuth2Credentials)
+ or credentials.provider != ProviderName.MICROSOFT_365_COPILOT
+ or not required_scopes.issubset(credentials.scopes)
+ ):
+ raise ValueError("invalid Microsoft 365 Copilot credential")
+ except asyncio.CancelledError:
+ raise
+ except Exception as error:
+ if credential_lease is not None:
+ await credential_lease.release()
+ credential_lease = None
+ # Only a missing or unusable credential is "not found";
+ # a refresh failure or lock contention on a valid account
+ # keeps its own cause so it is not reported as missing.
+ code = (
+ "microsoft_365_copilot_credential_not_found"
+ if isinstance(error, ValueError)
+ else "microsoft_365_copilot_credential_unavailable"
+ )
+ raise RuntimeError(code) from error
+ stream_fn = cast(Callable, stream_chat_completion_microsoft_365)
+ log.info("Using Microsoft 365 Copilot Chat API transport")
else:
if entry.llm_credential_id is not None:
raise RuntimeError("codex_session_route_mismatch")
@@ -725,7 +773,7 @@ class CoPilotProcessor:
f"Failed to checkpoint Codex credential: {release_err}"
)
except Exception as release_err:
- log.error(f"Failed to release Codex credential: {release_err}")
+ log.error(f"Failed to release chat credential: {release_err}")
finally:
try:
await stream_registry.mark_session_completed(
diff --git a/autogpt_platform/backend/backend/copilot/executor/processor_test.py b/autogpt_platform/backend/backend/copilot/executor/processor_test.py
index 43633f74ed..2e8420165e 100644
--- a/autogpt_platform/backend/backend/copilot/executor/processor_test.py
+++ b/autogpt_platform/backend/backend/copilot/executor/processor_test.py
@@ -16,6 +16,7 @@ from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
+from pydantic import SecretStr
from backend.copilot.engine import resolve_use_sdk
from backend.copilot.executor.processor import (
@@ -32,6 +33,7 @@ from backend.copilot.expert_context import (
)
from backend.copilot.model import ChatSession
from backend.copilot.rate_limit import UserPaywalledError
+from backend.data.model import OAuth2Credentials
from backend.integrations.codex.transport import (
CodexCredentialBusyError,
CodexCredentialIntegrityError,
@@ -720,6 +722,103 @@ def _codex_session(
return session
+def _microsoft_365_copilot_entry() -> CoPilotExecutionEntry:
+ return CoPilotExecutionEntry(
+ session_id="sess-microsoft",
+ turn_id="turn-microsoft",
+ user_id="user-1",
+ message="hi",
+ llm_auth_provider="microsoft_365_copilot",
+ llm_credential_id="cred-microsoft",
+ )
+
+
+def _microsoft_365_copilot_session() -> ChatSession:
+ session = ChatSession.new(
+ "user-1",
+ dry_run=False,
+ llm_auth_provider="microsoft_365_copilot",
+ llm_credential_id="cred-microsoft",
+ )
+ session.session_id = "sess-microsoft"
+ return session
+
+
+async def test_microsoft_365_copilot_route_acquires_oauth_lease_and_streams():
+ from backend.integrations.oauth.microsoft_365_copilot import (
+ Microsoft365CopilotDeviceAuthHandler,
+ )
+
+ published = _TrackedStream(events=[])
+ lease = MagicMock()
+ lease.credentials = OAuth2Credentials(
+ provider="microsoft_365_copilot",
+ id="cred-microsoft",
+ access_token=SecretStr("graph-token"),
+ refresh_token=SecretStr("refresh-token"),
+ scopes=Microsoft365CopilotDeviceAuthHandler.CHAT_SCOPES,
+ )
+ lease.release = AsyncMock()
+ manager = MagicMock()
+ manager.acquire_lease = AsyncMock(return_value=lease)
+ microsoft_stream = MagicMock(return_value=MagicMock())
+ baseline_stream = MagicMock()
+ sdk_stream = MagicMock()
+
+ with (
+ patch(
+ "backend.copilot.model.get_chat_session",
+ new=AsyncMock(return_value=_microsoft_365_copilot_session()),
+ ),
+ patch(
+ "backend.copilot.executor.processor.IntegrationCredentialsManager",
+ return_value=manager,
+ ),
+ patch(
+ "backend.copilot.executor.processor.stream_chat_completion_microsoft_365",
+ microsoft_stream,
+ ),
+ patch(
+ "backend.copilot.executor.processor.stream_chat_completion_baseline",
+ baseline_stream,
+ ),
+ patch(
+ "backend.copilot.sdk.service.stream_chat_completion_sdk",
+ sdk_stream,
+ ),
+ patch(
+ "backend.copilot.executor.processor.wrap_stream_with_heartbeat",
+ return_value=MagicMock(),
+ ),
+ patch(
+ "backend.copilot.executor.processor.stream_registry.stream_and_publish",
+ return_value=published,
+ ),
+ patch(
+ "backend.copilot.executor.processor.stream_registry.publish_chunk",
+ new=AsyncMock(),
+ ),
+ patch(
+ "backend.copilot.executor.processor.stream_registry.mark_session_completed",
+ new=AsyncMock(),
+ ),
+ ):
+ await CoPilotProcessor()._execute_async(
+ _microsoft_365_copilot_entry(),
+ threading.Event(),
+ MagicMock(),
+ _make_log(),
+ )
+
+ manager.acquire_lease.assert_awaited_once_with("user-1", "cred-microsoft")
+ lease.release.assert_awaited_once()
+ microsoft_stream.assert_called_once()
+ assert microsoft_stream.call_args.kwargs["credential_lease"] is lease
+ baseline_stream.assert_not_called()
+ sdk_stream.assert_not_called()
+
+
@pytest.mark.asyncio
async def test_codex_route_uses_claude_sdk_for_builder_and_releases_lease():
published = _TrackedStream(events=[])
diff --git a/autogpt_platform/backend/backend/copilot/model.py b/autogpt_platform/backend/backend/copilot/model.py
index 409216f663..b0ded94ebb 100644
--- a/autogpt_platform/backend/backend/copilot/model.py
+++ b/autogpt_platform/backend/backend/copilot/model.py
@@ -105,6 +105,7 @@ class ChatSessionMetadata(BaseModel):
dry_run: bool = False
llm_auth_provider: CopilotLlmAuthProvider = "platform"
llm_credential_id: str | None = None
+ llm_provider_session_ids: dict[str, str] = Field(default_factory=dict)
# Builder-panel binding: when set, the session is locked to the given
# graph. ``edit_agent`` / ``run_agent`` default their ``agent_id`` to
diff --git a/autogpt_platform/backend/backend/copilot/offers.py b/autogpt_platform/backend/backend/copilot/offers.py
index 84d43ed24e..177cbaee0b 100644
--- a/autogpt_platform/backend/backend/copilot/offers.py
+++ b/autogpt_platform/backend/backend/copilot/offers.py
@@ -62,6 +62,7 @@ class ConnectionTier(BaseModel):
class AIConnectionOffer(BaseModel):
offer_id: str
+ auth_provider: CopilotLlmAuthProvider
provider_family: str
display_name: str
auth_method: str
@@ -142,6 +143,7 @@ async def _locked_codex_offer(
return AIConnectionOffer(
offer_id="codex:locked",
+ auth_provider="codex",
provider_family="openai",
display_name="ChatGPT",
auth_method="chatgpt_oauth",
@@ -236,6 +238,7 @@ def _offer(
) -> AIConnectionOffer:
return AIConnectionOffer(
offer_id=offer_id_for(transport),
+ auth_provider=transport.auth_provider,
provider_family=_provider_family(transport.auth_provider),
display_name=transport.label,
auth_method=_auth_method(transport.auth_provider),
@@ -245,38 +248,59 @@ def _offer(
state="ready" if transport.available else "unavailable",
selectable=transport.available,
is_default=transport.default,
- tiers=[
- ConnectionTier(
- tier=tier,
- label=label,
- selectable=(
- transport.available and (advanced_allowed or tier != "advanced")
- ),
- display_model=(
- platform_models.get(tier)
- if transport.auth_provider == "platform"
- else codex_models.get(tier)
- ),
- lock_reason=(
- None
- if advanced_allowed or tier != "advanced"
- else ADVANCED_TIER_LOCK_REASON
- ),
- )
- for tier, label in TIER_LABELS.items()
- ],
+ tiers=_tiers_for(
+ transport,
+ platform_models,
+ codex_models,
+ advanced_allowed,
+ ),
limitations=_limitations(transport),
)
+def _tiers_for(
+ transport: ChatTransportResponse,
+ platform_models: dict[CopilotLLMModel, str | None],
+ codex_models: dict[CopilotLLMModel, str | None],
+ advanced_allowed: bool,
+) -> list[ConnectionTier]:
+ if transport.auth_provider == "microsoft_365_copilot":
+ return []
+ models = platform_models if transport.auth_provider == "platform" else codex_models
+ return [
+ ConnectionTier(
+ tier=tier,
+ label=label,
+ selectable=(
+ transport.available and (advanced_allowed or tier != "advanced")
+ ),
+ display_model=models.get(tier),
+ lock_reason=(
+ None
+ if advanced_allowed or tier != "advanced"
+ else ADVANCED_TIER_LOCK_REASON
+ ),
+ )
+ for tier, label in TIER_LABELS.items()
+ ]
+
+
def _provider_family(auth_provider: CopilotLlmAuthProvider) -> str:
# Presentation grouping, not the credential discriminator: ChatGPT OAuth
# and an OpenAI API key are one family and two very different credentials.
- return "openai" if auth_provider == "codex" else "autogpt"
+ if auth_provider == "codex":
+ return "openai"
+ if auth_provider == "microsoft_365_copilot":
+ return "microsoft"
+ return "autogpt"
def _auth_method(auth_provider: CopilotLlmAuthProvider) -> str:
- return "chatgpt_oauth" if auth_provider == "codex" else "deployment"
+ if auth_provider == "codex":
+ return "chatgpt_oauth"
+ if auth_provider == "microsoft_365_copilot":
+ return "device_code"
+ return "deployment"
def _is_hosted() -> bool:
@@ -286,6 +310,8 @@ def _is_hosted() -> bool:
def _backed_by_label(transport: ChatTransportResponse) -> str:
if transport.auth_provider == "codex":
return "Your ChatGPT plan"
+ if transport.auth_provider == "microsoft_365_copilot":
+ return "Your Microsoft 365 Copilot plan"
return "Your AutoGPT plan" if _is_hosted() else "This server's chat provider"
@@ -298,8 +324,12 @@ def _description(transport: ChatTransportResponse) -> str:
"""
if transport.auth_provider == "codex":
return (
- "New chats are backed by your ChatGPT plan, and spend no "
- "AutoGPT credits."
+ "New chats are backed by your ChatGPT plan, and spend no AutoGPT credits."
+ )
+ if transport.auth_provider == "microsoft_365_copilot":
+ return (
+ "New chats are backed by your work or school Microsoft 365 "
+ "Copilot plan, and spend no AutoGPT credits."
)
if _is_hosted():
return "New chats are backed by your AutoGPT plan, and spend AutoGPT credits."
@@ -308,10 +338,17 @@ def _description(transport: ChatTransportResponse) -> str:
def _limitations(transport: ChatTransportResponse) -> list[str]:
limitations: list[str] = []
- if transport.auth_provider == "codex":
+ if transport.auth_provider in {"codex", "microsoft_365_copilot"}:
# Stated because it is a real edge a user can hit, not a policy note:
# the builder panel rejects a codex route outright.
limitations.append("The agent builder's chat panel always runs on AutoGPT.")
+ if transport.auth_provider == "microsoft_365_copilot":
+ limitations.extend(
+ [
+ "Microsoft 365 Copilot returns text and does not run AutoGPT tools.",
+ "Local files are unsupported; use OneDrive or SharePoint links.",
+ ]
+ )
if transport.auth_provider == "platform" and not is_deployment_chat_available():
limitations.append("No chat provider is configured on this server yet.")
return limitations
diff --git a/autogpt_platform/backend/backend/copilot/offers_test.py b/autogpt_platform/backend/backend/copilot/offers_test.py
index bc88f459c6..cae7f37ce1 100644
--- a/autogpt_platform/backend/backend/copilot/offers_test.py
+++ b/autogpt_platform/backend/backend/copilot/offers_test.py
@@ -117,6 +117,31 @@ async def test_provider_family_groups_without_becoming_the_credential(
assert chatgpt.credential_id == "cred-1"
+async def test_microsoft_offer_uses_device_auth_and_has_no_fake_model_tiers(
+ mocker: pytest_mock.MockerFixture,
+) -> None:
+ _mock_transports(
+ mocker,
+ [
+ _transport(
+ "microsoft_365_copilot",
+ "cred-msft",
+ "Microsoft 365 Copilot",
+ )
+ ],
+ )
+
+ (offer,) = await get_connection_offers(USER_ID)
+
+ assert offer.auth_provider == "microsoft_365_copilot"
+ assert offer.provider_family == "microsoft"
+ assert offer.auth_method == "device_code"
+ assert offer.backed_by_label == "Your Microsoft 365 Copilot plan"
+ assert offer.tiers == []
+ assert "spend no AutoGPT credits" in offer.description
+
+
@pytest.mark.asyncio
async def test_offer_ids_are_stable_and_per_account(
mocker: pytest_mock.MockerFixture,
diff --git a/autogpt_platform/backend/backend/copilot/transports.py b/autogpt_platform/backend/backend/copilot/transports.py
index f7c1c0357a..124af8d423 100644
--- a/autogpt_platform/backend/backend/copilot/transports.py
+++ b/autogpt_platform/backend/backend/copilot/transports.py
@@ -12,17 +12,22 @@ this contract is the one the UI will keep.
"""
import logging
+import time
from typing import Optional, get_args
from pydantic import BaseModel
from backend.copilot.config import ChatConfig, CopilotLlmAuthProvider
-from backend.data.model import Credentials
+from backend.data.model import Credentials, OAuth2Credentials
from backend.data.user import get_user_default_chat_route, set_user_default_chat_route
from backend.integrations.codex.access import has_codex_access_for_discovery
from backend.integrations.codex.auth_bundle import CodexAuthBundleError
from backend.integrations.codex.credential_codec import bundle_from_credentials
from backend.integrations.creds_manager import IntegrationCredentialsManager
+from backend.integrations.oauth.microsoft_365_copilot import (
+ Microsoft365CopilotDeviceAuthHandler,
+)
+from backend.integrations.providers import ProviderName
from backend.util.settings import BehaveAs, Settings
logger = logging.getLogger(__name__)
@@ -97,6 +102,16 @@ async def get_chat_transports(user_id: str) -> list[ChatTransportResponse]:
)
for credentials in await _valid_codex_credentials(user_id)
)
+ transports.extend(
+ ChatTransportResponse(
+ auth_provider="microsoft_365_copilot",
+ credential_id=credentials.id,
+ label="Microsoft 365 Copilot",
+ available=True,
+ default=False,
+ )
+ for credentials in await _valid_microsoft_365_copilot_credentials(user_id)
+ )
saved_provider, saved_credential_id = await get_user_default_chat_route(user_id)
_mark_default(transports, saved_provider, saved_credential_id)
@@ -126,6 +141,12 @@ async def resolve_default_chat_route(
default = next((transport for transport in transports if transport.default), None)
if default is None:
return "platform", None
+ if default.auth_provider == "microsoft_365_copilot":
+ # Copilot Chat returns prose and never runs AutoGPT tools, so a
+ # schedule, briefing or bot turn routed there would silently do
+ # nothing. Unattended callers stay on the platform route; the saved
+ # default still applies to chats the user opens themselves.
+ return "platform", None
return default.auth_provider, default.credential_id
@@ -141,8 +162,8 @@ async def save_default_chat_route(
if route.auth_provider == "platform" and route.credential_id is not None:
raise InvalidDefaultChatRoute("codex_credential_not_allowed")
- if route.auth_provider == "codex" and route.credential_id is None:
- raise InvalidDefaultChatRoute("codex_credential_required")
+ if route.auth_provider != "platform" and route.credential_id is None:
+ raise InvalidDefaultChatRoute(f"{route.auth_provider}_credential_required")
transports = await get_chat_transports(user_id)
if _find_transport(transports, route.auth_provider, route.credential_id) is None:
@@ -150,8 +171,8 @@ async def save_default_chat_route(
# is indistinguishable from one that doesn't exist — deliberately, so
# this never confirms another user's credential id.
raise InvalidDefaultChatRoute(
- "codex_credential_not_found"
- if route.auth_provider == "codex"
+ f"{route.auth_provider}_credential_not_found"
+ if route.auth_provider != "platform"
else "chat_transport_not_configured"
)
@@ -205,8 +226,20 @@ def _automatic_default(
)
if platform is not None:
return platform
- codex = [transport for transport in available if transport.auth_provider == "codex"]
- return codex[0] if len(codex) == 1 else None
+ user_connections = [
+ transport for transport in available if transport.auth_provider != "platform"
+ ]
+ # Before Microsoft was added, one usable ChatGPT credential was the
+ # automatic self-host default. Preserve that existing choice when a newly
+ # linked provider appears; the user can explicitly move the default later.
+ codex = [
+ transport
+ for transport in user_connections
+ if transport.auth_provider == "codex"
+ ]
+ if len(codex) == 1:
+ return codex[0]
+ return user_connections[0] if len(user_connections) == 1 else None
def _find_transport(
@@ -247,3 +280,37 @@ def _is_valid_codex_credentials(credentials: Credentials | None) -> bool:
except CodexAuthBundleError:
return False
return True
+
+
+async def _valid_microsoft_365_copilot_credentials(
+ user_id: str,
+) -> list[Credentials]:
+ credentials = await credentials_manager.store.get_creds_by_provider(
+ user_id, ProviderName.MICROSOFT_365_COPILOT
+ )
+ return [
+ credential
+ for credential in credentials
+ if _is_valid_microsoft_365_copilot_credentials(credential)
+ ]
+
+
+def _is_valid_microsoft_365_copilot_credentials(
+ credentials: Credentials | None,
+) -> bool:
+ return (
+ isinstance(credentials, OAuth2Credentials)
+ and credentials.provider == ProviderName.MICROSOFT_365_COPILOT
+ and set(Microsoft365CopilotDeviceAuthHandler.CHAT_SCOPES).issubset(
+ credentials.scopes
+ )
+ and _microsoft_365_copilot_token_usable(credentials)
+ )
+
+
+def _microsoft_365_copilot_token_usable(credentials: OAuth2Credentials) -> bool:
+ """An expired access token with no refresh token can never chat again."""
+ expires_at = credentials.access_token_expires_at
+ if expires_at is None or expires_at > int(time.time()):
+ return True
+ return credentials.refresh_token is not None
diff --git a/autogpt_platform/backend/backend/copilot/transports_test.py b/autogpt_platform/backend/backend/copilot/transports_test.py
index 30c359a51e..35498a3c3f 100644
--- a/autogpt_platform/backend/backend/copilot/transports_test.py
+++ b/autogpt_platform/backend/backend/copilot/transports_test.py
@@ -48,6 +48,22 @@ def _codex_credentials(credential_id: str = "cred-codex") -> OAuth2Credentials:
)
+def _microsoft_credentials(
+ credential_id: str = "cred-microsoft",
+) -> OAuth2Credentials:
+ from backend.integrations.oauth.microsoft_365_copilot import (
+ Microsoft365CopilotDeviceAuthHandler,
+ )
+
+ return OAuth2Credentials(
+ id=credential_id,
+ provider="microsoft_365_copilot",
+ access_token=SecretStr("access"),
+ refresh_token=SecretStr("refresh"),
+ scopes=Microsoft365CopilotDeviceAuthHandler.CHAT_SCOPES,
+ )
+
+
@pytest.fixture(autouse=True)
def transport_env(mocker: pytest_mock.MockerFixture):
"""Hosted deployment, entitled user, no connections, nothing saved."""
@@ -115,6 +131,50 @@ async def test_saved_choice_beats_the_server_pick() -> None:
assert _default_of(await get_chat_transports(USER_ID)) == ("codex", "cred-codex")
+async def test_microsoft_365_copilot_is_a_secretless_user_connection() -> None:
+ transports.credentials_manager.store.get_creds_by_provider.side_effect = (
+ lambda _user_id, provider: (
+ [_microsoft_credentials()] if provider == "microsoft_365_copilot" else []
+ )
+ )
+ _saved("microsoft_365_copilot", "cred-microsoft")
+
+ transport_list = await get_chat_transports(USER_ID)
+
+ microsoft = next(
+ transport
+ for transport in transport_list
+ if transport.auth_provider == "microsoft_365_copilot"
+ )
+ assert microsoft.credential_id == "cred-microsoft"
+ assert microsoft.label == "Microsoft 365 Copilot"
+ assert microsoft.default is True
+
+
+async def test_linking_microsoft_preserves_the_existing_self_host_chatgpt_default(
+ mocker: pytest_mock.MockerFixture,
+) -> None:
+ _self_hosted_without_deployment(mocker)
+ transports.credentials_manager.store.get_creds_by_provider.side_effect = (
+ lambda _user_id, provider: (
+ [_codex_credentials()]
+ if provider == "codex"
+ else (
+ [_microsoft_credentials()]
+ if provider == "microsoft_365_copilot"
+ else []
+ )
+ )
+ )
+
+ assert _default_of(await get_chat_transports(USER_ID)) == (
+ "codex",
+ "cred-codex",
+ )
+
+
@pytest.mark.asyncio
async def test_exactly_one_transport_is_ever_default() -> None:
_connect("cred-a", "cred-b")
@@ -269,6 +329,18 @@ async def test_chatgpt_without_an_account_is_rejected() -> None:
transports.set_user_default_chat_route.assert_not_awaited()
+async def test_microsoft_copilot_without_an_account_is_rejected() -> None:
+ with pytest.raises(InvalidDefaultChatRoute) as error:
+ await save_default_chat_route(
+ USER_ID,
+ DefaultChatRoute(auth_provider="microsoft_365_copilot"),
+ )
+
+ assert error.value.detail == "microsoft_365_copilot_credential_required"
+ transports.set_user_default_chat_route.assert_not_awaited()
+
+
@pytest.mark.asyncio
async def test_platform_with_an_account_is_rejected() -> None:
with pytest.raises(InvalidDefaultChatRoute) as error:
@@ -334,3 +406,45 @@ async def test_platform_is_not_saveable_where_it_is_unavailable(
assert error.value.detail == "chat_transport_not_configured"
transports.set_user_default_chat_route.assert_not_awaited()
+
+
+# ─── Microsoft 365 Copilot cannot run tools ─────────────────────────────
+
+
+async def test_unattended_callers_never_route_to_microsoft() -> None:
+ transports.credentials_manager.store.get_creds_by_provider.side_effect = (
+ lambda _user_id, provider: (
+ [_microsoft_credentials()] if provider == "microsoft_365_copilot" else []
+ )
+ )
+ _saved("microsoft_365_copilot", "cred-microsoft")
+
+ # The saved default still shows for chats the user opens themselves...
+ assert _default_of(await get_chat_transports(USER_ID)) == (
+ "microsoft_365_copilot",
+ "cred-microsoft",
+ )
+ # ...but a schedule, briefing or bot turn stays on a route that runs tools.
+ assert await transports.resolve_default_chat_route(USER_ID) == (
+ "platform",
+ None,
+ )
+
+
+async def test_expired_microsoft_token_without_refresh_is_not_listed() -> None:
+ dead = _microsoft_credentials()
+ dead.access_token_expires_at = 1
+ dead.refresh_token = None
+ transports.credentials_manager.store.get_creds_by_provider.side_effect = (
+ lambda _user_id, provider: (
+ [dead] if provider == "microsoft_365_copilot" else []
+ )
+ )
+
+ assert not [
+ transport
+ for transport in await get_chat_transports(USER_ID)
+ if transport.auth_provider == "microsoft_365_copilot"
+ ]
diff --git a/autogpt_platform/backend/backend/copilot/turn_queue_test.py b/autogpt_platform/backend/backend/copilot/turn_queue_test.py
index fa40f051f2..a8c5f65fa0 100644
--- a/autogpt_platform/backend/backend/copilot/turn_queue_test.py
+++ b/autogpt_platform/backend/backend/copilot/turn_queue_test.py
@@ -463,6 +463,41 @@ async def test_promotion_uses_current_codex_route_not_stale_platform_tier() -> N
assert dispatch_turn_mock.await_args.kwargs["model"] == "advanced"
+async def test_microsoft_promotion_skips_platform_billing_gates() -> None:
+ head = _mock_session()
+ head.metadata.llm_auth_provider = "microsoft_365_copilot"
+ head.metadata.llm_credential_id = "cred-microsoft"
+ pending = _pyd_message(metadata={"model": "advanced"})
+ db = MagicMock()
+ db.update_chat_session_status = AsyncMock(return_value=True)
+ db.get_latest_user_message_in_session = AsyncMock(return_value=pending)
+ dispatch_turn_mock = AsyncMock()
+ platform_gate = AsyncMock(
+ side_effect=AssertionError("platform billing gate checked for Microsoft")
+ )
+
+ with (
+ _patch_queued_list([head]),
+ patch.object(turn_queue, "chat_db", return_value=db),
+ patch.object(turn_queue, "is_user_paywalled", new=platform_gate),
+ patch.object(turn_queue, "advanced_tier_entitled", new=platform_gate),
+ patch.object(
+ turn_queue, "claim_queued_session", new=AsyncMock(return_value=True)
+ ),
+ patch.object(turn_queue, "invalidate_session_cache", new=AsyncMock()),
+ patch("backend.copilot.executor.utils.dispatch_turn", new=dispatch_turn_mock),
+ ):
+ promoted = await turn_queue.dispatch_next_for_user("u1")
+
+ assert promoted is True
+ platform_gate.assert_not_awaited()
+ assert (
+ dispatch_turn_mock.await_args.kwargs["llm_auth_provider"]
+ == "microsoft_365_copilot"
+ )
+
+
@pytest.mark.asyncio
async def test_codex_dispatch_leaves_queued_when_user_lacks_access() -> None:
head = _mock_session()
diff --git a/autogpt_platform/backend/backend/integrations/credential_lease.py b/autogpt_platform/backend/backend/integrations/credential_lease.py
index effa869bc6..cb0d511db8 100644
--- a/autogpt_platform/backend/backend/integrations/credential_lease.py
+++ b/autogpt_platform/backend/backend/integrations/credential_lease.py
@@ -29,8 +29,6 @@ class CredentialLease:
def start_heartbeat(self) -> None:
if self.credentials.type != "oauth2":
return
- if self.credentials.refresh_strategy != "provider_runtime":
- return
if self._heartbeat_task is None:
self._heartbeat_task = asyncio.create_task(self._heartbeat())
diff --git a/autogpt_platform/backend/backend/integrations/credential_lease_test.py b/autogpt_platform/backend/backend/integrations/credential_lease_test.py
index 1da7ddaf14..aff10dfc94 100644
--- a/autogpt_platform/backend/backend/integrations/credential_lease_test.py
+++ b/autogpt_platform/backend/backend/integrations/credential_lease_test.py
@@ -60,6 +60,29 @@ async def test_release_stops_heartbeat_before_unlocking():
lock.release.assert_awaited_once()
+async def test_oauth_handler_lease_heartbeats_during_long_runtime_use():
+ credentials = _provider_runtime_credentials().model_copy(
+ update={"refresh_strategy": "oauth_handler"}
+ )
+ lock = AsyncMock()
+ lock.locked.return_value = True
+ lock.owned.return_value = True
+ lock.timeout = 0.03
+ lock.extend.return_value = True
+ lease = CredentialLease(credentials, lock, AsyncMock())
+
+ lease.start_heartbeat()
+ for _ in range(100):
+ if lock.extend.await_count:
+ break
+ await asyncio.sleep(0.001)
+ await lease.release()
+
+ lock.extend.assert_awaited()
+ lock.release.assert_awaited_once()
+
+
@pytest.mark.asyncio
async def test_wait_for_failure_reports_heartbeat_loss_immediately():
credentials = _provider_runtime_credentials()
diff --git a/autogpt_platform/backend/backend/integrations/microsoft_365_copilot/__init__.py b/autogpt_platform/backend/backend/integrations/microsoft_365_copilot/__init__.py
new file mode 100644
index 0000000000..3ad2ffc37b
--- /dev/null
+++ b/autogpt_platform/backend/backend/integrations/microsoft_365_copilot/__init__.py
@@ -0,0 +1 @@
+"""Microsoft 365 Copilot Chat API transport."""
diff --git a/autogpt_platform/backend/backend/integrations/microsoft_365_copilot/client.py b/autogpt_platform/backend/backend/integrations/microsoft_365_copilot/client.py
new file mode 100644
index 0000000000..9337056248
--- /dev/null
+++ b/autogpt_platform/backend/backend/integrations/microsoft_365_copilot/client.py
@@ -0,0 +1,280 @@
+import asyncio
+import codecs
+import json
+import logging
+from collections.abc import AsyncIterator
+from typing import Any
+
+import aiohttp
+from pydantic import BaseModel
+
+logger = logging.getLogger(__name__)
+
+GRAPH_BASE_URL = "https://graph.microsoft.com/beta"
+
+
+class Microsoft365CopilotError(RuntimeError):
+ def __init__(self, message: str, *, status: int | None = None):
+ super().__init__(message)
+ self.status = status
+
+
+class Microsoft365CopilotDeclined(Microsoft365CopilotError):
+ """Copilot refused the request under its Responsible AI policy."""
+
+ def __init__(self) -> None:
+ super().__init__(
+ "Microsoft 365 Copilot declined this request under its "
+ "Responsible AI policy; rephrase and try again"
+ )
+
+
+def build_chat_request(
+ message: str,
+ *,
+ timezone: str,
+ additional_context: list[str] | None = None,
+ web_enabled: bool | None = None,
+ file_uris: list[str] | None = None,
+) -> dict[str, Any]:
+ body: dict[str, Any] = {
+ "message": {"text": message},
+ "locationHint": {"timeZone": timezone},
+ }
+ if additional_context:
+ body["additionalContext"] = [
+ {"text": context} for context in additional_context if context
+ ]
+
+ contextual_resources: dict[str, Any] = {}
+ if web_enabled is not None:
+ contextual_resources["webContext"] = {"isWebEnabled": web_enabled}
+ if file_uris:
+ contextual_resources["files"] = [{"uri": uri} for uri in file_uris]
+ if contextual_resources:
+ body["contextualResources"] = contextual_resources
+ return body
+
+
+async def _iter_sse_json(chunks: AsyncIterator[bytes]) -> AsyncIterator[dict[str, Any]]:
+ buffer = ""
+ data_lines: list[str] = []
+ decoder = codecs.getincrementaldecoder("utf-8")()
+
+ def parse_event() -> dict[str, Any] | None:
+ payload = "\n".join(data_lines)
+ if not payload or payload == "[DONE]":
+ return None
+ try:
+ parsed = json.loads(payload)
+ except json.JSONDecodeError as error:
+ raise Microsoft365CopilotError(
+ "Microsoft 365 Copilot returned an invalid stream response"
+ ) from error
+ return parsed if isinstance(parsed, dict) else None
+
+ async for chunk in chunks:
+ buffer += decoder.decode(chunk)
+ while "\n" in buffer:
+ raw_line, buffer = buffer.split("\n", 1)
+ line = raw_line.removesuffix("\r")
+ if not line:
+ if data_lines:
+ event = parse_event()
+ data_lines = []
+ if event is not None:
+ yield event
+ continue
+ if line.startswith("data:"):
+ data_lines.append(line[5:].lstrip())
+
+ buffer += decoder.decode(b"", final=True)
+ trailing_line = buffer.removesuffix("\r")
+ if trailing_line.startswith("data:"):
+ data_lines.append(trailing_line[5:].lstrip())
+ if data_lines:
+ event = parse_event()
+ if event is not None:
+ yield event
+
+
+class CopilotTextUpdate(BaseModel):
+ text: str
+ delta: str
+
+
+async def iter_copilot_text_updates(
+ chunks: AsyncIterator[bytes],
+) -> AsyncIterator[CopilotTextUpdate]:
+ response_message_id: str | None = None
+ previous_text = ""
+ preview_frozen = False
+
+ async for conversation in _iter_sse_json(chunks):
+ # Responsible AI refusals arrive as ordinary 200 snapshots with the
+ # conversation flagged; without this they would end as an empty or
+ # partial "successful" answer.
+ if conversation.get("state") == "disengagedForRai":
+ raise Microsoft365CopilotDeclined()
+ messages = conversation.get("messages")
+ if not isinstance(messages, list) or not messages:
+ continue
+
+ selected: dict[str, Any] | None = None
+ if response_message_id:
+ selected = next(
+ (
+ message
+ for message in messages
+ if isinstance(message, dict)
+ and message.get("id") == response_message_id
+ ),
+ None,
+ )
+ if selected is None and response_message_id is None:
+ candidate = messages[-1]
+ if isinstance(candidate, dict):
+ selected = candidate
+ candidate_id = candidate.get("id")
+ if isinstance(candidate_id, str):
+ response_message_id = candidate_id
+ if selected is None:
+ continue
+
+ text = selected.get("text")
+ if not isinstance(text, str):
+ continue
+ if text == previous_text:
+ continue
+ if not text.startswith(previous_text):
+ # Append-only previews cannot replace prose. Preserve Graph's
+ # canonical snapshot for persistence and the UI's finish/refetch.
+ preview_frozen = True
+ delta = "" if preview_frozen else text[len(previous_text) :]
+ previous_text = text
+ yield CopilotTextUpdate(text=text, delta=delta)
+
+
+class Microsoft365CopilotClient:
+ def __init__(
+ self,
+ access_token: str,
+ *,
+ base_url: str = GRAPH_BASE_URL,
+ timeout_seconds: float = 120.0,
+ ):
+ self._access_token = access_token
+ self._base_url = base_url.rstrip("/")
+ # A grounded Copilot answer may legitimately stream for several minutes.
+ # Limit connection setup and periods with no bytes, not the total lifetime
+ # of the SSE response.
+ self._timeout = aiohttp.ClientTimeout(
+ total=None,
+ connect=30.0,
+ sock_connect=30.0,
+ sock_read=timeout_seconds,
+ )
+ self._session: aiohttp.ClientSession | None = None
+
+ async def __aenter__(self) -> "Microsoft365CopilotClient":
+ self._session = aiohttp.ClientSession(timeout=self._timeout)
+ return self
+
+ async def __aexit__(self, *_args: object) -> None:
+ if self._session:
+ await self._session.close()
+ self._session = None
+
+ @property
+ def _headers(self) -> dict[str, str]:
+ return {
+ "Authorization": f"Bearer {self._access_token}",
+ "Accept": "application/json, text/event-stream",
+ "Content-Type": "application/json",
+ }
+
+ def _client(self) -> aiohttp.ClientSession:
+ if self._session is None:
+ raise RuntimeError(
+ "Microsoft365CopilotClient must be used as a context manager"
+ )
+ return self._session
+
+ async def create_conversation(self) -> str:
+ url = f"{self._base_url}/copilot/conversations"
+ try:
+ async with self._client().post(
+ url, headers=self._headers, json={}
+ ) as response:
+ await self._raise_for_error(response, "create a Copilot conversation")
+ try:
+ payload = await response.json()
+ except (json.JSONDecodeError, UnicodeDecodeError) as error:
+ raise Microsoft365CopilotError(
+ "Microsoft 365 Copilot returned an invalid conversation response"
+ ) from error
+ except Microsoft365CopilotError:
+ raise
+ except (aiohttp.ClientError, asyncio.TimeoutError) as error:
+ raise Microsoft365CopilotError(
+ "Microsoft 365 Copilot could not create a Copilot conversation"
+ ) from error
+ conversation_id = payload.get("id") if isinstance(payload, dict) else None
+ if not isinstance(conversation_id, str) or not conversation_id:
+ raise Microsoft365CopilotError(
+ "Microsoft 365 Copilot returned a conversation without an ID"
+ )
+ return conversation_id
+
+ async def stream_chat(
+ self,
+ conversation_id: str,
+ message: str,
+ *,
+ timezone: str,
+ additional_context: list[str] | None = None,
+ web_enabled: bool | None = None,
+ file_uris: list[str] | None = None,
+ ) -> AsyncIterator[CopilotTextUpdate]:
+ url = f"{self._base_url}/copilot/conversations/{conversation_id}/chatOverStream"
+ request = build_chat_request(
+ message,
+ timezone=timezone,
+ additional_context=additional_context,
+ web_enabled=web_enabled,
+ file_uris=file_uris,
+ )
+ try:
+ async with self._client().post(
+ url, headers=self._headers, json=request
+ ) as response:
+ await self._raise_for_error(response, "continue a Copilot conversation")
+ async for update in iter_copilot_text_updates(
+ response.content.iter_any()
+ ):
+ yield update
+ except Microsoft365CopilotError:
+ raise
+ except (aiohttp.ClientError, asyncio.TimeoutError) as error:
+ raise Microsoft365CopilotError(
+ "Microsoft 365 Copilot could not continue a Copilot conversation"
+ ) from error
+
+ async def _raise_for_error(
+ self, response: aiohttp.ClientResponse, action: str
+ ) -> None:
+ if 200 <= response.status < 300:
+ return
+ error_code = None
+ try:
+ payload = await response.json()
+ error = payload.get("error") if isinstance(payload, dict) else None
+ if isinstance(error, dict) and isinstance(error.get("code"), str):
+ error_code = error["code"]
+ except (aiohttp.ContentTypeError, json.JSONDecodeError):
+ pass
+ suffix = f" ({error_code})" if error_code else ""
+ raise Microsoft365CopilotError(
+ f"Microsoft 365 Copilot could not {action}{suffix}",
+ status=response.status,
+ )
diff --git a/autogpt_platform/backend/backend/integrations/microsoft_365_copilot/client_test.py b/autogpt_platform/backend/backend/integrations/microsoft_365_copilot/client_test.py
new file mode 100644
index 0000000000..327d130839
--- /dev/null
+++ b/autogpt_platform/backend/backend/integrations/microsoft_365_copilot/client_test.py
@@ -0,0 +1,176 @@
+import asyncio
+from collections.abc import AsyncIterator
+from unittest.mock import MagicMock
+
+import aiohttp
+import pytest
+
+
+async def _chunks() -> AsyncIterator[bytes]:
+ yield b'data: {"id":"conversation","messages":[{"id":"answer","text":"Hello"}]}\r\n'
+ yield b'id:1\r\n\r\ndata: {"id":"conversation","messages":[]}\n\n'
+ yield (
+ b'data: {"id":"conversation","messages":['
+ b'{"id":"question","text":"Hi"},'
+ b'{"id":"answer","text":"Hello world"}]}\n\n'
+ )
+ yield b"data: [DONE]\n\n"
+
+
+async def _split_utf8_chunks() -> AsyncIterator[bytes]:
+ payload = (
+ 'data: {"id":"conversation","messages":[{"id":"answer","text":"Hello 👋"}]}\n\n'
+ ).encode()
+ emoji_start = payload.index("👋".encode())
+ yield payload[: emoji_start + 1]
+ yield payload[emoji_start + 1 :]
+
+
+async def _invalid_json_chunks() -> AsyncIterator[bytes]:
+ yield b"data: {not-json}\n\n"
+
+
+async def test_stream_parser_emits_only_new_text_from_full_snapshots() -> None:
+ from backend.integrations.microsoft_365_copilot.client import (
+ iter_copilot_text_updates,
+ )
+
+ deltas = [update.delta async for update in iter_copilot_text_updates(_chunks())]
+
+ assert deltas == ["Hello", " world"]
+
+
+async def test_stream_parser_handles_utf8_characters_split_between_chunks() -> None:
+ from backend.integrations.microsoft_365_copilot.client import (
+ iter_copilot_text_updates,
+ )
+
+ deltas = [
+ update.delta async for update in iter_copilot_text_updates(_split_utf8_chunks())
+ ]
+
+ assert deltas == ["Hello 👋"]
+
+
+async def test_stream_parser_normalizes_invalid_json() -> None:
+ from backend.integrations.microsoft_365_copilot.client import (
+ Microsoft365CopilotError,
+ iter_copilot_text_updates,
+ )
+
+ with pytest.raises(Microsoft365CopilotError, match="invalid stream response"):
+ async for _ in iter_copilot_text_updates(_invalid_json_chunks()):
+ pass
+
+
+def test_chat_request_includes_timezone_context_and_web_grounding() -> None:
+ from backend.integrations.microsoft_365_copilot.client import build_chat_request
+
+ request = build_chat_request(
+ "Summarize the launch discussion",
+ timezone="America/Chicago",
+ additional_context=["Use the application launch brief."],
+ web_enabled=False,
+ )
+
+ assert request == {
+ "message": {"text": "Summarize the launch discussion"},
+ "locationHint": {"timeZone": "America/Chicago"},
+ "additionalContext": [{"text": "Use the application launch brief."}],
+ "contextualResources": {"webContext": {"isWebEnabled": False}},
+ }
+
+
+def test_client_timeout_does_not_cap_total_stream_lifetime() -> None:
+ from backend.integrations.microsoft_365_copilot.client import (
+ Microsoft365CopilotClient,
+ )
+
+ client = Microsoft365CopilotClient("token", timeout_seconds=45)
+
+ assert client._timeout.total is None
+ assert client._timeout.connect == 30
+ assert client._timeout.sock_connect == 30
+ assert client._timeout.sock_read == 45
+
+
+async def test_create_conversation_normalizes_network_errors() -> None:
+ from backend.integrations.microsoft_365_copilot.client import (
+ Microsoft365CopilotClient,
+ Microsoft365CopilotError,
+ )
+
+ client = Microsoft365CopilotClient("token")
+ client._session = MagicMock()
+ client._session.post.side_effect = aiohttp.ClientConnectionError("private detail")
+
+ with pytest.raises(Microsoft365CopilotError, match="could not create") as raised:
+ await client.create_conversation()
+
+ assert "private detail" not in str(raised.value)
+
+
+async def test_stream_chat_normalizes_idle_timeout() -> None:
+ from backend.integrations.microsoft_365_copilot.client import (
+ Microsoft365CopilotClient,
+ Microsoft365CopilotError,
+ )
+
+ client = Microsoft365CopilotClient("token")
+ client._session = MagicMock()
+ client._session.post.side_effect = asyncio.TimeoutError("private detail")
+
+ with pytest.raises(Microsoft365CopilotError, match="could not continue") as raised:
+ async for _ in client.stream_chat(
+ "conversation",
+ "hello",
+ timezone="UTC",
+ ):
+ pass
+
+ assert "private detail" not in str(raised.value)
+
+
+async def _refusal_chunks() -> AsyncIterator[bytes]:
+ yield b'data: {"id":"conversation","messages":[{"id":"answer","text":"I"}]}\n\n'
+ yield (
+ b'data: {"id":"conversation","state":"disengagedForRai",'
+ b'"messages":[{"id":"answer","text":""}]}\n\n'
+ )
+
+
+async def _rewrite_chunks() -> AsyncIterator[bytes]:
+ yield b'data: {"id":"conversation","messages":[{"id":"answer","text":"Hello world"}]}\n\n'
+ # Graph rewrote already-streamed prose to add a citation marker.
+ yield b'data: {"id":"conversation","messages":[{"id":"answer","text":"Hello [1] world"}]}\n\n'
+ yield b'data: {"id":"conversation","messages":[{"id":"answer","text":"Hello [1] world!"}]}\n\n'
+
+
+async def test_stream_parser_raises_on_responsible_ai_refusal() -> None:
+ from backend.integrations.microsoft_365_copilot.client import (
+ Microsoft365CopilotDeclined,
+ iter_copilot_text_updates,
+ )
+
+ with pytest.raises(Microsoft365CopilotDeclined):
+ async for _ in iter_copilot_text_updates(_refusal_chunks()):
+ pass
+
+
+async def test_stream_parser_stops_preview_deltas_after_a_snapshot_rewrite() -> None:
+ from backend.integrations.microsoft_365_copilot.client import (
+ iter_copilot_text_updates,
+ )
+
+ deltas = [
+ update.delta async for update in iter_copilot_text_updates(_rewrite_chunks())
+ ]
+
+ assert deltas == ["Hello world", "", ""]
diff --git a/autogpt_platform/backend/backend/integrations/microsoft_365_copilot/conversation_errors_test.py b/autogpt_platform/backend/backend/integrations/microsoft_365_copilot/conversation_errors_test.py
new file mode 100644
index 0000000000..67d9a55e22
--- /dev/null
+++ b/autogpt_platform/backend/backend/integrations/microsoft_365_copilot/conversation_errors_test.py
@@ -0,0 +1,41 @@
+import json
+from unittest.mock import AsyncMock, MagicMock
+
+import aiohttp
+import pytest
+
+from backend.integrations.microsoft_365_copilot.client import (
+ Microsoft365CopilotClient,
+ Microsoft365CopilotError,
+)
+
+
+ "payload,decode_error",
+ [
+ (b'{"private": invalid}', json.JSONDecodeError),
+ (b'"private\xff"', UnicodeDecodeError),
+ ],
+)
+async def test_malformed_successful_conversation_response_is_normalized(
+ payload: bytes, decode_error: type[Exception]
+) -> None:
+ async def decode_json():
+ return json.loads(payload.decode("utf-8"))
+
+ response = MagicMock(spec=aiohttp.ClientResponse)
+ response.status = 201
+ response.json = AsyncMock(side_effect=decode_json)
+ session = MagicMock(spec=aiohttp.ClientSession)
+ session.post.return_value.__aenter__.return_value = response
+ client = Microsoft365CopilotClient("token")
+ client._session = session
+
+ with pytest.raises(
+ Microsoft365CopilotError, match="invalid conversation response"
+ ) as raised:
+ await client.create_conversation()
+
+ assert isinstance(raised.value.__cause__, decode_error)
+ assert "private" not in str(raised.value)
diff --git a/autogpt_platform/backend/backend/integrations/microsoft_365_copilot/empty_stream_test.py b/autogpt_platform/backend/backend/integrations/microsoft_365_copilot/empty_stream_test.py
new file mode 100644
index 0000000000..2ee42f4667
--- /dev/null
+++ b/autogpt_platform/backend/backend/integrations/microsoft_365_copilot/empty_stream_test.py
@@ -0,0 +1,88 @@
+from unittest.mock import AsyncMock, MagicMock
+
+import pytest
+
+from backend.copilot.model import ChatSession
+from backend.copilot.response_model import StreamError
+from backend.integrations.microsoft_365_copilot import service
+from backend.integrations.microsoft_365_copilot.service_test import _credential_lease
+
+
[email protected]("replace_conversation", [False, True])
+ "stream_bytes",
+ [
+ b"",
+ b"data: [DONE]\n\n",
+ b'data: {"messages":[]}\n\n',
+ b'data: {"messages":[{"id":"answer","text":null}]}\n\n',
+ ],
+)
+async def test_stream_with_no_updates_fails_without_persisting_an_answer(
+ mocker, stream_bytes: bytes, replace_conversation: bool
+) -> None:
+ async def chunks():
+ yield stream_bytes
+
+ response = MagicMock(status=200)
+ response.content.iter_any = chunks
+ stream_request = MagicMock()
+ stream_request.__aenter__.return_value = response
+ requests = [stream_request]
+ if replace_conversation:
+ expired_request = MagicMock()
+ expired_request.__aenter__.return_value = MagicMock(
+ status=410, json=AsyncMock(return_value={"error": {"code": "expired"}})
+ )
+ create_request = MagicMock()
+ create_request.__aenter__.return_value = MagicMock(
+ status=201, json=AsyncMock(return_value={"id": "replacement"})
+ )
+ requests = [expired_request, create_request, stream_request]
+ http_session = MagicMock(close=AsyncMock())
+ http_session.post.side_effect = requests
+ mocker.patch(
+ "backend.integrations.microsoft_365_copilot.client.aiohttp.ClientSession",
+ return_value=http_session,
+ )
+ upsert = mocker.patch.object(
+ service, "upsert_chat_session", new=AsyncMock(side_effect=lambda value: value)
+ )
+ usage = mocker.patch.object(service, "persist_and_record_usage", new=AsyncMock())
+ session = ChatSession.new(
+ "user-1",
+ dry_run=False,
+ llm_auth_provider="microsoft_365_copilot",
+ llm_credential_id="credential-1",
+ )
+ session.metadata.llm_provider_session_ids["microsoft_365_copilot:credential-1"] = (
+ "conversation-1"
+ )
+
+ events = [
+ event
+ async for event in service.stream_chat_completion_microsoft_365(
+ session_id=session.session_id,
+ session=session,
+ message="Hi",
+ credential_lease=_credential_lease(),
+ )
+ ]
+
+ assert [event.type.value for event in events] == [
+ "start",
+ "start-step",
+ "text-start",
+ "text-end",
+ "finish-step",
+ "error",
+ "finish",
+ ]
+ error = next(event for event in events if isinstance(event, StreamError))
+ assert error.code == "microsoft_365_copilot_request_failed"
+ assert error.errorText == "Microsoft 365 Copilot returned no answer"
+ assert all(message.role != "assistant" for message in session.messages)
+ usage.assert_not_awaited()
+ assert upsert.await_count == int(replace_conversation)
+ assert http_session.post.call_count == (3 if replace_conversation else 1)
diff --git a/autogpt_platform/backend/backend/integrations/microsoft_365_copilot/rewrite_test.py b/autogpt_platform/backend/backend/integrations/microsoft_365_copilot/rewrite_test.py
new file mode 100644
index 0000000000..d1b36c028f
--- /dev/null
+++ b/autogpt_platform/backend/backend/integrations/microsoft_365_copilot/rewrite_test.py
@@ -0,0 +1,111 @@
+import json
+from unittest.mock import AsyncMock, MagicMock
+
+import pytest
+from pydantic import SecretStr
+
+from backend.copilot.model import ChatSession
+from backend.copilot.response_model import StreamTextDelta
+from backend.data.model import OAuth2Credentials
+from backend.integrations.microsoft_365_copilot import service
+from backend.integrations.microsoft_365_copilot.client import Microsoft365CopilotError
+from backend.integrations.oauth.microsoft_365_copilot import (
+ Microsoft365CopilotDeviceAuthHandler,
+)
+
+
+ "snapshots,fail_after_rewrite,replace_conversation",
+ [
+ (["Hello world", "Hello [1] world"], False, False),
+ (["Hello world", "Goodbye"], False, False),
+ (["Hello world", ""], False, False),
+ (["Hello world", ""], False, True),
+ (["Hello world", ""], True, False),
+ (["Hello world", "Hello [1] world", "Hello [1] world!"], False, False),
+ ],
+)
+async def test_final_graph_snapshot_is_persisted_without_corrupting_preview(
+ mocker, snapshots: list[str], fail_after_rewrite: bool, replace_conversation: bool
+) -> None:
+ async def chunks():
+ for text in snapshots:
+ payload = {"messages": [{"id": "answer", "text": text}]}
+ yield f"data: {json.dumps(payload)}\n\n".encode()
+ if fail_after_rewrite:
+ raise Microsoft365CopilotError("expired", status=410)
+
+ response = MagicMock(status=200)
+ response.content.iter_any = chunks
+ request = MagicMock()
+ request.__aenter__ = AsyncMock(return_value=response)
+ request.__aexit__ = AsyncMock(return_value=None)
+ http_session = MagicMock()
+ requests = [request]
+ if replace_conversation:
+ expired = MagicMock()
+ expired.__aenter__.return_value = MagicMock(
+ status=410, json=AsyncMock(return_value={"error": {"code": "expired"}})
+ )
+ create = MagicMock()
+ create.__aenter__.return_value = MagicMock(
+ status=201, json=AsyncMock(return_value={"id": "replacement"})
+ )
+ requests = [expired, create, request]
+ http_session.post.side_effect = requests
+ http_session.close = AsyncMock()
+ mocker.patch(
+ "backend.integrations.microsoft_365_copilot.client.aiohttp.ClientSession",
+ return_value=http_session,
+ )
+ upsert = mocker.patch.object(
+ service, "upsert_chat_session", new=AsyncMock(side_effect=lambda value: value)
+ )
+ usage = mocker.patch.object(service, "persist_and_record_usage", new=AsyncMock())
+ session = ChatSession.new(
+ "user-1",
+ dry_run=False,
+ llm_auth_provider="microsoft_365_copilot",
+ llm_credential_id="credential-1",
+ )
+ session.metadata.llm_provider_session_ids["microsoft_365_copilot:credential-1"] = (
+ "conversation-1"
+ )
+ lease = MagicMock(
+ credentials=OAuth2Credentials(
+ id="credential-1",
+ provider="microsoft_365_copilot",
+ access_token=SecretStr("graph-token"),
+ refresh_token=SecretStr("refresh-token"),
+ scopes=Microsoft365CopilotDeviceAuthHandler.CHAT_SCOPES,
+ )
+ )
+
+ events = [
+ event
+ async for event in service.stream_chat_completion_microsoft_365(
+ session_id=session.session_id,
+ session=session,
+ message="Hi",
+ credential_lease=lease,
+ )
+ ]
+
+ if fail_after_rewrite:
+ assert http_session.post.call_count == 1
+ assert all(message.role != "assistant" for message in session.messages)
+ usage.assert_not_awaited()
+ assert [event.type.value for event in events][-2:] == ["error", "finish"]
+ return
+
+ assert session.messages[-1].content == snapshots[-1]
+ assert upsert.await_args.args[0].messages[-1].content == snapshots[-1]
+ assert usage.await_args.kwargs["completion_tokens"] == service._estimate_tokens(
+ snapshots[-1]
+ )
+ assert (
+ "".join(event.delta for event in events if isinstance(event, StreamTextDelta))
+ == snapshots[0]
+ )
+ assert events[-1].type.value == "finish"
diff --git a/autogpt_platform/backend/backend/integrations/microsoft_365_copilot/service.py b/autogpt_platform/backend/backend/integrations/microsoft_365_copilot/service.py
new file mode 100644
index 0000000000..f76b1d4dd2
--- /dev/null
+++ b/autogpt_platform/backend/backend/integrations/microsoft_365_copilot/service.py
@@ -0,0 +1,267 @@
+import json
+import logging
+from collections.abc import AsyncGenerator
+from typing import Any
+from uuid import uuid4
+
+from backend.copilot.config import CopilotLLMModel, CopilotMode
+from backend.copilot.model import (
+ ChatMessage,
+ ChatSession,
+ get_chat_session,
+ maybe_append_user_message,
+ upsert_chat_session,
+)
+from backend.copilot.response_model import (
+ StreamBaseResponse,
+ StreamError,
+ StreamFinish,
+ StreamFinishStep,
+ StreamStart,
+ StreamStartStep,
+ StreamTextDelta,
+ StreamTextEnd,
+ StreamTextStart,
+)
+from backend.copilot.service import strip_user_context_tags
+from backend.copilot.token_tracking import persist_and_record_usage
+from backend.data.model import OAuth2Credentials
+from backend.data.user import get_user_by_id
+from backend.integrations.credential_lease import CredentialLease
+from backend.integrations.oauth.microsoft_365_copilot import (
+ Microsoft365CopilotDeviceAuthHandler,
+)
+from backend.integrations.providers import ProviderName
+from backend.util.exceptions import NotFoundError
+from backend.util.timezone_utils import get_user_timezone_or_utc
+
+from .client import (
+ Microsoft365CopilotClient,
+ Microsoft365CopilotDeclined,
+ Microsoft365CopilotError,
+)
+
+logger = logging.getLogger(__name__)
+
+_MODEL_NAME = "microsoft-365-copilot"
+_MAX_ADDITIONAL_CONTEXT_CHARS = 20_000
+
+
+def _estimate_tokens(text: str) -> int:
+ return max(1, (len(text) + 3) // 4)
+
+
+def _build_additional_context(context: dict[str, str] | None) -> list[str] | None:
+ if not context:
+ return None
+ provider_context = {
+ key: value
+ for key, value in context.items()
+ if key not in {"microsoft_365_web_enabled", "microsoft_365_file_uris"}
+ }
+ if not provider_context:
+ return None
+ serialized = json.dumps(provider_context, ensure_ascii=False, default=str)
+ return [serialized[:_MAX_ADDITIONAL_CONTEXT_CHARS]]
+
+
+def _web_enabled(context: dict[str, str] | None) -> bool | None:
+ raw_value = context.get("microsoft_365_web_enabled") if context else None
+ if raw_value is None:
+ return None
+ return str(raw_value).lower() not in {"0", "false", "no", "off"}
+
+
+def _file_uris(context: dict[str, str] | None) -> list[str] | None:
+ raw_value = context.get("microsoft_365_file_uris") if context else None
+ if not raw_value:
+ return None
+ try:
+ parsed = json.loads(raw_value)
+ except (TypeError, json.JSONDecodeError):
+ return None
+ if not isinstance(parsed, list):
+ return None
+ uris = [value for value in parsed if isinstance(value, str) and value]
+ return uris or None
+
+
+async def _get_timezone(user_id: str | None) -> str:
+ if not user_id:
+ return "UTC"
+ try:
+ user = await get_user_by_id(user_id)
+ except Exception:
+ logger.warning("Could not load user timezone for Microsoft 365 Copilot")
+ return "UTC"
+ return get_user_timezone_or_utc(user.timezone)
+
+
+def _validate_credential_lease(credential_lease: CredentialLease | None) -> str:
+ if credential_lease is None:
+ raise RuntimeError("microsoft_365_copilot_credential_required")
+ credentials = credential_lease.credentials
+ required_scopes = set(Microsoft365CopilotDeviceAuthHandler.CHAT_SCOPES)
+ if (
+ not isinstance(credentials, OAuth2Credentials)
+ or credentials.provider != ProviderName.MICROSOFT_365_COPILOT
+ or not required_scopes.issubset(credentials.scopes)
+ ):
+ raise RuntimeError("microsoft_365_copilot_credential_not_found")
+ return credentials.access_token.get_secret_value()
+
+
+def _conversation_key(session: ChatSession) -> str:
+ credential_id = session.metadata.llm_credential_id or "unknown"
+ return f"microsoft_365_copilot:{credential_id}"
+
+
+async def stream_chat_completion_microsoft_365(
+ session_id: str,
+ message: str | None = None,
+ is_user_message: bool = True,
+ user_id: str | None = None,
+ session: ChatSession | None = None,
+ file_ids: list[str] | None = None,
+ context: dict[str, str] | None = None,
+ mode: CopilotMode | None = None,
+ model: CopilotLLMModel | None = None,
+ credential_lease: CredentialLease | None = None,
+ **_kwargs: Any,
+) -> AsyncGenerator[StreamBaseResponse, None]:
+ del mode, model
+ if session is None:
+ session = await get_chat_session(session_id, user_id)
+ if not session:
+ raise NotFoundError(
+ f"Session {session_id} not found. Please create a new session first."
+ )
+ if session.metadata.llm_auth_provider != "microsoft_365_copilot":
+ raise RuntimeError("microsoft_365_copilot_session_route_mismatch")
+ if file_ids:
+ yield StreamError(
+ errorText=(
+ "Microsoft 365 Copilot can only attach OneDrive or SharePoint "
+ "links, not local workspace files."
+ ),
+ code="microsoft_365_copilot_local_files_unsupported",
+ )
+ return
+
+ access_token = _validate_credential_lease(credential_lease)
+ sanitized_message = strip_user_context_tags(message or "").strip()
+ if not sanitized_message:
+ yield StreamError(
+ errorText="Microsoft 365 Copilot requires a text message.",
+ code="microsoft_365_copilot_message_required",
+ )
+ return
+ # The route persists the original text before enqueueing. Deduplicate
+ # against that exact value; sanitization is only for what leaves our trust
+ # boundary and must not create a second user row in chat history.
+ maybe_append_user_message(session, message, is_user_message)
+
+ message_id = str(uuid4())
+ text_id = f"{message_id}-text"
+ response_text = ""
+ received_response = False
+ timezone = await _get_timezone(user_id)
+ stream_started = False
+
+ try:
+ async with Microsoft365CopilotClient(access_token) as client:
+ conversation_key = _conversation_key(session)
+ conversation_id = session.metadata.llm_provider_session_ids.get(
+ conversation_key
+ )
+ if not conversation_id:
+ conversation_id = await client.create_conversation()
+ session.metadata.llm_provider_session_ids[conversation_key] = (
+ conversation_id
+ )
+ session = await upsert_chat_session(session)
+
+ yield StreamStart(messageId=message_id, sessionId=session_id)
+ yield StreamStartStep()
+ yield StreamTextStart(id=text_id)
+ stream_started = True
+
+ additional_context = _build_additional_context(context)
+ web_enabled = _web_enabled(context)
+ file_uris = _file_uris(context)
+ try:
+ async for update in client.stream_chat(
+ conversation_id,
+ sanitized_message,
+ timezone=timezone,
+ additional_context=additional_context,
+ web_enabled=web_enabled,
+ file_uris=file_uris,
+ ):
+ received_response = True
+ response_text = update.text
+ if update.delta:
+ yield StreamTextDelta(id=text_id, delta=update.delta)
+ except Microsoft365CopilotError as error:
+ # Graph can retire a conversation while our local chat session
+ # remains active. A 404/410 received before any answer bytes is
+ # safe to recover once by replacing the stored provider thread.
+ if error.status not in {404, 410} or received_response:
+ raise
+ conversation_id = await client.create_conversation()
+ session.metadata.llm_provider_session_ids[conversation_key] = (
+ conversation_id
+ )
+ session = await upsert_chat_session(session)
+ async for update in client.stream_chat(
+ conversation_id,
+ sanitized_message,
+ timezone=timezone,
+ additional_context=additional_context,
+ web_enabled=web_enabled,
+ file_uris=file_uris,
+ ):
+ received_response = True
+ response_text = update.text
+ if update.delta:
+ yield StreamTextDelta(id=text_id, delta=update.delta)
+ if not received_response:
+ raise Microsoft365CopilotError(
+ "Microsoft 365 Copilot returned no answer"
+ )
+ except Microsoft365CopilotError as error:
+ if stream_started:
+ yield StreamTextEnd(id=text_id)
+ yield StreamFinishStep()
+ yield StreamError(
+ errorText=str(error),
+ code=(
+ "microsoft_365_copilot_declined"
+ if isinstance(error, Microsoft365CopilotDeclined)
+ else "microsoft_365_copilot_request_failed"
+ ),
+ )
+ if stream_started:
+ yield StreamFinish()
+ return
+
+ session.messages.append(
+ ChatMessage(role="assistant", content=response_text, model=_MODEL_NAME)
+ )
+ await persist_and_record_usage(
+ session=session,
+ user_id=user_id,
+ prompt_tokens=_estimate_tokens(sanitized_message),
+ completion_tokens=_estimate_tokens(response_text),
+ log_prefix="[Microsoft365Copilot]",
+ cost_usd=None,
+ model=_MODEL_NAME,
+ provider=ProviderName.MICROSOFT_365_COPILOT.value,
+ credential_id_override=session.metadata.llm_credential_id,
+ extra_metadata={"billing_mode": "user_subscription"},
+ )
+ await upsert_chat_session(session)
+
+ yield StreamTextEnd(id=text_id)
+ yield StreamFinishStep()
+ yield StreamFinish()
diff --git a/autogpt_platform/backend/backend/integrations/microsoft_365_copilot/service_test.py b/autogpt_platform/backend/backend/integrations/microsoft_365_copilot/service_test.py
new file mode 100644
index 0000000000..7777f2d726
--- /dev/null
+++ b/autogpt_platform/backend/backend/integrations/microsoft_365_copilot/service_test.py
@@ -0,0 +1,285 @@
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, MagicMock
+
+import pytest
+from pydantic import SecretStr
+
+from backend.copilot.model import ChatMessage, ChatSession
+from backend.data.model import OAuth2Credentials
+from backend.integrations.microsoft_365_copilot.client import (
+ CopilotTextUpdate,
+ Microsoft365CopilotError,
+)
+from backend.integrations.oauth.microsoft_365_copilot import (
+ Microsoft365CopilotDeviceAuthHandler,
+)
+
+
+class _FakeClient:
+ instances: list["_FakeClient"] = []
+
+ def __init__(self, access_token: str):
+ self.access_token = access_token
+ self.stream_kwargs = None
+ self.instances.append(self)
+
+ async def __aenter__(self):
+ return self
+
+ async def __aexit__(self, *_args):
+ return None
+
+ async def create_conversation(self) -> str:
+ return "conversation-1"
+
+ async def stream_chat(self, conversation_id: str, message: str, **kwargs):
+ self.stream_kwargs = {
+ "conversation_id": conversation_id,
+ "message": message,
+ **kwargs,
+ }
+ yield CopilotTextUpdate(text="Hello", delta="Hello")
+ yield CopilotTextUpdate(text="Hello world", delta=" world")
+
+
+class _ExpiredConversationClient(_FakeClient):
+ async def create_conversation(self) -> str:
+ return "conversation-replacement"
+
+ async def stream_chat(self, conversation_id: str, message: str, **kwargs):
+ if conversation_id == "conversation-expired":
+ raise Microsoft365CopilotError("expired", status=410)
+ async for delta in super().stream_chat(conversation_id, message, **kwargs):
+ yield delta
+
+
+class _MidStreamFailureClient(_FakeClient):
+ async def stream_chat(self, conversation_id: str, message: str, **kwargs):
+ yield CopilotTextUpdate(text="Partial", delta="Partial")
+ raise Microsoft365CopilotError("Copilot connection ended")
+
+
+def _credential_lease() -> MagicMock:
+ credentials = OAuth2Credentials(
+ id="credential-1",
+ provider="microsoft_365_copilot",
+ access_token=SecretStr("graph-token"),
+ refresh_token=SecretStr("refresh-token"),
+ scopes=Microsoft365CopilotDeviceAuthHandler.CHAT_SCOPES,
+ )
+ return MagicMock(credentials=credentials)
+
+
+async def test_service_streams_and_persists_graph_conversation(mocker) -> None:
+ from backend.integrations.microsoft_365_copilot import service
+
+ session = ChatSession.new(
+ "user-1",
+ dry_run=False,
+ llm_auth_provider="microsoft_365_copilot",
+ llm_credential_id="credential-1",
+ )
+ session.session_id = "session-1"
+ lease = _credential_lease()
+ upsert = mocker.patch.object(
+ service, "upsert_chat_session", new=AsyncMock(side_effect=lambda value: value)
+ )
+ record_usage = mocker.patch.object(
+ service, "persist_and_record_usage", new=AsyncMock(return_value=4)
+ )
+ mocker.patch.object(service, "Microsoft365CopilotClient", _FakeClient)
+ mocker.patch.object(
+ service,
+ "get_user_by_id",
+ new=AsyncMock(return_value=SimpleNamespace(timezone="America/Chicago")),
+ )
+
+ events = [
+ event
+ async for event in service.stream_chat_completion_microsoft_365(
+ session_id="session-1",
+ message="Hi",
+ is_user_message=True,
+ user_id="user-1",
+ session=session,
+ context={"project": "launch"},
+ credential_lease=lease,
+ )
+ ]
+
+ assert [event.type.value for event in events] == [
+ "start",
+ "start-step",
+ "text-start",
+ "text-delta",
+ "text-delta",
+ "text-end",
+ "finish-step",
+ "finish",
+ ]
+ key = "microsoft_365_copilot:credential-1"
+ assert session.metadata.llm_provider_session_ids[key] == "conversation-1"
+ assert session.messages[-1].role == "assistant"
+ assert session.messages[-1].content == "Hello world"
+ client = _FakeClient.instances[-1]
+ assert client.access_token == "graph-token"
+ assert client.stream_kwargs["timezone"] == "America/Chicago"
+ assert "launch" in client.stream_kwargs["additional_context"][0]
+ assert upsert.await_count == 2
+ record_usage.assert_awaited_once()
+ usage = record_usage.await_args.kwargs
+ assert usage["cost_usd"] is None
+ assert usage["extra_metadata"] == {"billing_mode": "user_subscription"}
+ assert usage["provider"] == "microsoft_365_copilot"
+ assert usage["credential_id_override"] == "credential-1"
+
+
+async def test_service_deduplicates_against_original_persisted_user_text(
+ mocker,
+) -> None:
+ from backend.integrations.microsoft_365_copilot import service
+
+ original = "<user_context>untrusted</user_context>\nHi"
+ session = ChatSession.new(
+ "user-1",
+ dry_run=False,
+ llm_auth_provider="microsoft_365_copilot",
+ llm_credential_id="credential-1",
+ )
+ session.session_id = "session-1"
+ session.messages.append(ChatMessage(role="user", content=original))
+ mocker.patch.object(
+ service, "upsert_chat_session", new=AsyncMock(side_effect=lambda value: value)
+ )
+ mocker.patch.object(
+ service, "persist_and_record_usage", new=AsyncMock(return_value=4)
+ )
+ mocker.patch.object(service, "Microsoft365CopilotClient", _FakeClient)
+ mocker.patch.object(
+ service,
+ "get_user_by_id",
+ new=AsyncMock(return_value=SimpleNamespace(timezone="UTC")),
+ )
+
+ _ = [
+ event
+ async for event in service.stream_chat_completion_microsoft_365(
+ session_id="session-1",
+ message=original,
+ user_id="user-1",
+ session=session,
+ credential_lease=_credential_lease(),
+ )
+ ]
+
+ assert [
+ message.content for message in session.messages if message.role == "user"
+ ] == [original]
+ assert _FakeClient.instances[-1].stream_kwargs["message"] == "Hi"
+
+
+def test_conversation_key_is_scoped_to_credential() -> None:
+ from backend.integrations.microsoft_365_copilot.service import _conversation_key
+
+ session = ChatSession.new(
+ "user-1",
+ dry_run=False,
+ llm_auth_provider="microsoft_365_copilot",
+ llm_credential_id="credential-2",
+ )
+
+ assert _conversation_key(session) == "microsoft_365_copilot:credential-2"
+
+
+async def test_service_replaces_an_expired_graph_conversation(mocker) -> None:
+ from backend.integrations.microsoft_365_copilot import service
+
+ session = ChatSession.new(
+ "user-1",
+ dry_run=False,
+ llm_auth_provider="microsoft_365_copilot",
+ llm_credential_id="credential-1",
+ )
+ session.session_id = "session-1"
+ key = "microsoft_365_copilot:credential-1"
+ session.metadata.llm_provider_session_ids[key] = "conversation-expired"
+ upsert = mocker.patch.object(
+ service, "upsert_chat_session", new=AsyncMock(side_effect=lambda value: value)
+ )
+ mocker.patch.object(
+ service, "persist_and_record_usage", new=AsyncMock(return_value=4)
+ )
+ mocker.patch.object(
+ service, "Microsoft365CopilotClient", _ExpiredConversationClient
+ )
+ mocker.patch.object(
+ service,
+ "get_user_by_id",
+ new=AsyncMock(return_value=SimpleNamespace(timezone="UTC")),
+ )
+
+ events = [
+ event
+ async for event in service.stream_chat_completion_microsoft_365(
+ session_id="session-1",
+ message="Hi",
+ user_id="user-1",
+ session=session,
+ credential_lease=_credential_lease(),
+ )
+ ]
+
+ assert session.metadata.llm_provider_session_ids[key] == "conversation-replacement"
+ assert [event.type.value for event in events][-3:] == [
+ "text-end",
+ "finish-step",
+ "finish",
+ ]
+ assert upsert.await_count == 2
+
+
+async def test_service_closes_stream_after_midstream_failure(mocker) -> None:
+ from backend.integrations.microsoft_365_copilot import service
+
+ session = ChatSession.new(
+ "user-1",
+ dry_run=False,
+ llm_auth_provider="microsoft_365_copilot",
+ llm_credential_id="credential-1",
+ )
+ session.session_id = "session-1"
+ session.metadata.llm_provider_session_ids["microsoft_365_copilot:credential-1"] = (
+ "conversation-1"
+ )
+ mocker.patch.object(service, "Microsoft365CopilotClient", _MidStreamFailureClient)
+ mocker.patch.object(
+ service,
+ "get_user_by_id",
+ new=AsyncMock(return_value=SimpleNamespace(timezone="UTC")),
+ )
+
+ events = [
+ event
+ async for event in service.stream_chat_completion_microsoft_365(
+ session_id="session-1",
+ message="Hi",
+ user_id="user-1",
+ session=session,
+ credential_lease=_credential_lease(),
+ )
+ ]
+
+ assert [event.type.value for event in events] == [
+ "start",
+ "start-step",
+ "text-start",
+ "text-delta",
+ "text-end",
+ "finish-step",
+ "error",
+ "finish",
+ ]
diff --git a/autogpt_platform/backend/backend/integrations/oauth/__init__.py b/autogpt_platform/backend/backend/integrations/oauth/__init__.py
index 1133e09f1a..5affcc4d2d 100644
--- a/autogpt_platform/backend/backend/integrations/oauth/__init__.py
+++ b/autogpt_platform/backend/backend/integrations/oauth/__init__.py
@@ -10,6 +10,7 @@ from .device_base import BaseDeviceAuthHandler
from .discord import DiscordOAuthHandler
from .github import GitHubOAuthHandler
from .google import GoogleOAuthHandler
+from .microsoft_365_copilot import Microsoft365CopilotDeviceAuthHandler
from .notion import NotionOAuthHandler
from .reddit import RedditOAuthHandler
from .rmfg import RMFGDeviceAuthHandler
@@ -235,6 +236,7 @@ CREDENTIALS_BY_PROVIDER: dict[str, SDKAwareCredentials] = SDKAwareCredentialsDic
# ------------------------------------------------------------------ #
_ORIGINAL_DEVICE_HANDLERS: list[type[BaseDeviceAuthHandler]] = [
CodexDeviceAuthHandler,
+ Microsoft365CopilotDeviceAuthHandler,
RMFGDeviceAuthHandler,
StripeLinkDeviceAuthHandler,
]
diff --git a/autogpt_platform/backend/backend/integrations/oauth/microsoft_365_copilot.py b/autogpt_platform/backend/backend/integrations/oauth/microsoft_365_copilot.py
new file mode 100644
index 0000000000..5826880a6e
--- /dev/null
+++ b/autogpt_platform/backend/backend/integrations/oauth/microsoft_365_copilot.py
@@ -0,0 +1,225 @@
+import logging
+import time
+from typing import ClassVar
+
+import httpx
+from pydantic import SecretStr
+
+from backend.data.model import OAuth2Credentials
+from backend.integrations.oauth.device_base import (
+ BaseDeviceAuthHandler,
+ DeviceAuthInitiation,
+ DeviceAuthPollResult,
+)
+from backend.integrations.providers import ProviderName
+from backend.util.settings import Settings
+
+MICROSOFT_365_COPILOT_PUBLIC_CLIENT_ID = "ce01a4d6-be71-42a0-86b1-6540838eb17c"
+MICROSOFT_DEVICE_CODE_URL = (
+ "https://login.microsoftonline.com/organizations/oauth2/v2.0/devicecode"
+)
+MICROSOFT_TOKEN_URL = (
+ "https://login.microsoftonline.com/organizations/oauth2/v2.0/token"
+)
+MICROSOFT_PROFILE_URL = "https://graph.microsoft.com/v1.0/me"
+MICROSOFT_AUTH_TIMEOUT_SECONDS = 20.0
+
+logger = logging.getLogger(__name__)
+
+
+def _client_id() -> str:
+ return (
+ Settings().secrets.microsoft_client_id or MICROSOFT_365_COPILOT_PUBLIC_CLIENT_ID
+ )
+
+
+class Microsoft365CopilotDeviceAuthHandler(BaseDeviceAuthHandler):
+ PROVIDER_NAME: ClassVar[ProviderName | str] = ProviderName.MICROSOFT_365_COPILOT
+ CHAT_SCOPES: ClassVar[list[str]] = [
+ "Sites.Read.All",
+ "Mail.Read",
+ "People.Read.All",
+ "OnlineMeetingTranscript.Read.All",
+ "Chat.Read",
+ "ChannelMessage.Read.All",
+ "ExternalItem.Read.All",
+ ]
+ DEFAULT_SCOPES: ClassVar[list[str]] = ["User.Read", *CHAT_SCOPES]
+
+ async def initiate_device_auth(self, scopes: list[str]) -> DeviceAuthInitiation:
+ effective_scopes = self._authorization_scopes(scopes)
+ async with httpx.AsyncClient(timeout=MICROSOFT_AUTH_TIMEOUT_SECONDS) as client:
+ response = await client.post(
+ MICROSOFT_DEVICE_CODE_URL,
+ data={
+ "client_id": _client_id(),
+ "scope": " ".join(effective_scopes),
+ },
+ headers={"Content-Type": "application/x-www-form-urlencoded"},
+ )
+ response.raise_for_status()
+ data = response.json()
+ return DeviceAuthInitiation(
+ device_code=data["device_code"],
+ user_code=data["user_code"],
+ verification_url=data["verification_uri"],
+ verification_url_complete=data.get("verification_uri_complete"),
+ expires_in=int(data["expires_in"]),
+ interval=int(data.get("interval", 5)),
+ )
+
+ async def poll_for_tokens(self, device_code: str) -> DeviceAuthPollResult:
+ async with httpx.AsyncClient(timeout=MICROSOFT_AUTH_TIMEOUT_SECONDS) as client:
+ response = await client.post(
+ MICROSOFT_TOKEN_URL,
+ data={
+ "grant_type": "urn:ietf:params:oauth:grant-type:device_code",
+ "device_code": device_code,
+ "client_id": _client_id(),
+ },
+ headers={"Content-Type": "application/x-www-form-urlencoded"},
+ )
+ if response.status_code == 200:
+ credentials = self._credentials_from_token_response(response.json())
+ await self._populate_account(client, credentials)
+ return DeviceAuthPollResult(status="approved", credentials=credentials)
+
+ error_code = self._error_code(response)
+ if error_code == "authorization_pending":
+ return DeviceAuthPollResult(status="pending")
+ if error_code == "slow_down":
+ return DeviceAuthPollResult(
+ status="slow_down",
+ next_poll_interval=10,
+ )
+ if error_code in {"authorization_declined", "access_denied"}:
+ return DeviceAuthPollResult(status="denied")
+ if error_code in {"expired_token", "bad_verification_code"}:
+ return DeviceAuthPollResult(status="expired")
+ raise RuntimeError(
+ "Microsoft device token request failed "
+ f"(status={response.status_code}, code={error_code or 'unknown'})"
+ )
+
+ async def _populate_account(
+ self,
+ client: httpx.AsyncClient,
+ credentials: OAuth2Credentials,
+ ) -> None:
+ try:
+ response = await client.get(
+ MICROSOFT_PROFILE_URL,
+ params={"$select": "displayName,mail,userPrincipalName,id"},
+ headers={"Authorization": credentials.auth_header()},
+ )
+ response.raise_for_status()
+ profile = response.json()
+ except Exception as error:
+ logger.warning(
+ "Could not resolve Microsoft 365 Copilot account profile: %s",
+ type(error).__name__,
+ )
+ return
+
+ if not isinstance(profile, dict):
+ return
+ username = profile.get("mail") or profile.get("userPrincipalName")
+ display_name = profile.get("displayName")
+ account_id = profile.get("id")
+ if isinstance(username, str) and username:
+ credentials.username = username
+ if isinstance(display_name, str) and display_name:
+ credentials.title = display_name
+ if isinstance(account_id, str) and account_id:
+ credentials.metadata["microsoft_account_id"] = account_id
+
+ async def _refresh_tokens(
+ self, credentials: OAuth2Credentials
+ ) -> OAuth2Credentials:
+ if not credentials.refresh_token:
+ raise ValueError("Microsoft 365 Copilot credentials have no refresh token")
+ async with httpx.AsyncClient(timeout=MICROSOFT_AUTH_TIMEOUT_SECONDS) as client:
+ response = await client.post(
+ MICROSOFT_TOKEN_URL,
+ data={
+ "client_id": _client_id(),
+ "refresh_token": credentials.refresh_token.get_secret_value(),
+ "grant_type": "refresh_token",
+ "scope": " ".join(self._authorization_scopes(credentials.scopes)),
+ },
+ headers={"Content-Type": "application/x-www-form-urlencoded"},
+ )
+ response.raise_for_status()
+ return self._credentials_from_token_response(response.json(), credentials)
+
+ async def revoke_tokens(self, credentials: OAuth2Credentials) -> bool:
+ return False
+
+ def _authorization_scopes(self, scopes: list[str]) -> list[str]:
+ effective = self.handle_default_scopes(scopes)
+ return list(dict.fromkeys([*effective, "offline_access"]))
+
+ @staticmethod
+ def _error_code(response: httpx.Response) -> str:
+ try:
+ data = response.json()
+ except ValueError:
+ return ""
+ return str(data.get("error") or "") if isinstance(data, dict) else ""
+
+ def _credentials_from_token_response(
+ self,
+ token_data: dict,
+ current: OAuth2Credentials | None = None,
+ ) -> OAuth2Credentials:
+ access_token = token_data.get("access_token")
+ if not isinstance(access_token, str) or not access_token:
+ raise ValueError("Microsoft token response did not include an access token")
+
+ refresh_token = token_data.get("refresh_token")
+ if not isinstance(refresh_token, str) or not refresh_token:
+ refresh_token = (
+ current.refresh_token.get_secret_value()
+ if current and current.refresh_token
+ else None
+ )
+ if not refresh_token:
+ raise ValueError("Microsoft token response did not include a refresh token")
+
+ raw_scopes = token_data.get("scope", "")
+ scopes = (
+ [scope.rsplit("/", 1)[-1] for scope in raw_scopes.split()]
+ if isinstance(raw_scopes, str)
+ else []
+ )
+ if not scopes:
+ scopes = list(current.scopes if current else self.DEFAULT_SCOPES)
+
+ expires_in = token_data.get("expires_in")
+ try:
+ expires_at = (
+ int(time.time()) + int(expires_in)
+ if isinstance(expires_in, (int, str))
+ else None
+ )
+ except ValueError:
+ expires_at = None
+ token_update = {
+ "access_token": SecretStr(access_token),
+ "refresh_token": SecretStr(refresh_token),
+ "access_token_expires_at": expires_at,
+ "scopes": scopes,
+ }
+ if current:
+ # Refresh changes token material, not the linked account's stored
+ # identity or caller-owned metadata.
+ return current.model_copy(update=token_update)
+ return OAuth2Credentials(
+ provider=self.PROVIDER_NAME,
+ title="Microsoft 365 Copilot",
+ access_token=SecretStr(access_token),
+ refresh_token=SecretStr(refresh_token),
+ access_token_expires_at=expires_at,
+ refresh_token_expires_at=None,
+ scopes=scopes,
+ )
diff --git a/autogpt_platform/backend/backend/integrations/oauth/microsoft_365_copilot_test.py b/autogpt_platform/backend/backend/integrations/oauth/microsoft_365_copilot_test.py
new file mode 100644
index 0000000000..8659b640b4
--- /dev/null
+++ b/autogpt_platform/backend/backend/integrations/oauth/microsoft_365_copilot_test.py
@@ -0,0 +1,200 @@
+import time
+from unittest.mock import AsyncMock, MagicMock
+
+import pytest
+from pydantic import SecretStr
+
+from backend.data.model import OAuth2Credentials
+from backend.integrations.oauth.microsoft_365_copilot import (
+ MICROSOFT_365_COPILOT_PUBLIC_CLIENT_ID,
+ Microsoft365CopilotDeviceAuthHandler,
+)
+
+
+def _mock_client(mocker, responses: list[MagicMock]) -> AsyncMock:
+ client = AsyncMock()
+ client.post = AsyncMock(side_effect=responses)
+ client.get = AsyncMock()
+ context = MagicMock()
+ context.__aenter__ = AsyncMock(return_value=client)
+ context.__aexit__ = AsyncMock(return_value=None)
+ mocker.patch(
+ "backend.integrations.oauth.microsoft_365_copilot.httpx.AsyncClient",
+ return_value=context,
+ )
+ return client
+
+
+async def test_device_auth_uses_public_client_without_secret(
+ mocker, monkeypatch
+) -> None:
+ monkeypatch.delenv("MICROSOFT_CLIENT_ID", raising=False)
+ response = MagicMock(status_code=200)
+ response.json.return_value = {
+ "device_code": "device-code",
+ "user_code": "ABCD-EFGH",
+ "verification_uri": "https://microsoft.com/devicelogin",
+ "expires_in": 900,
+ "interval": 5,
+ }
+ client = _mock_client(mocker, [response])
+
+ result = await Microsoft365CopilotDeviceAuthHandler().initiate_device_auth([])
+
+ assert result.user_code == "ABCD-EFGH"
+ body = client.post.await_args.kwargs["data"]
+ assert body["client_id"] == MICROSOFT_365_COPILOT_PUBLIC_CLIENT_ID
+ assert "client_secret" not in body
+ assert "offline_access" in body["scope"].split()
+ assert "User.Read" in body["scope"].split()
+ assert set(Microsoft365CopilotDeviceAuthHandler.DEFAULT_SCOPES).issubset(
+ body["scope"].split()
+ )
+
+
+async def test_poll_and_refresh_rotate_tokens_without_secret(
+ mocker,
+) -> None:
+ mocker.patch(
+ "backend.integrations.oauth.microsoft_365_copilot._client_id",
+ return_value="configured-client",
+ )
+ poll = MagicMock(status_code=200)
+ poll.json.return_value = {
+ "access_token": "access-one",
+ "refresh_token": "refresh-one",
+ "expires_in": 3600,
+ "scope": "User.Read Sites.Read.All Mail.Read",
+ }
+ profile = MagicMock(status_code=200)
+ profile.json.return_value = {
+ "id": "microsoft-user-id",
+ "displayName": "Nick Example",
+ "mail": "[email protected]",
+ "userPrincipalName": "[email protected]",
+ }
+ refresh = MagicMock(status_code=200)
+ refresh.json.return_value = {
+ "access_token": "access-two",
+ "refresh_token": "refresh-two",
+ "expires_in": 7200,
+ "scope": "User.Read Sites.Read.All Mail.Read",
+ }
+ client = _mock_client(mocker, [poll, refresh])
+ client.get.return_value = profile
+ mocker.patch.object(time, "time", return_value=1_000)
+ handler = Microsoft365CopilotDeviceAuthHandler()
+
+ result = await handler.poll_for_tokens("device-code")
+ assert result.status == "approved"
+ assert result.credentials is not None
+ assert result.credentials.username == "[email protected]"
+ assert result.credentials.title == "Nick Example"
+ assert result.credentials.metadata["microsoft_account_id"] == "microsoft-user-id"
+ result.credentials.id = "credential-id"
+ refreshed = await handler.refresh_tokens(result.credentials)
+
+ assert refreshed.id == "credential-id"
+ assert refreshed.access_token.get_secret_value() == "access-two"
+ assert refreshed.refresh_token
+ assert refreshed.refresh_token.get_secret_value() == "refresh-two"
+ assert refreshed.access_token_expires_at == 8_200
+ assert refreshed.username == "[email protected]"
+ assert refreshed.title == "Nick Example"
+ assert refreshed.metadata["microsoft_account_id"] == "microsoft-user-id"
+ for call in client.post.await_args_list:
+ assert call.kwargs["data"]["client_id"] == "configured-client"
+ assert "client_secret" not in call.kwargs["data"]
+ client.get.assert_awaited_once()
+
+
+async def test_profile_failure_does_not_discard_authorized_tokens(mocker) -> None:
+ poll = MagicMock(status_code=200)
+ poll.json.return_value = {
+ "access_token": "access-one",
+ "refresh_token": "refresh-one",
+ "expires_in": 3600,
+ "scope": "User.Read Sites.Read.All",
+ }
+ client = _mock_client(mocker, [poll])
+ client.get.side_effect = RuntimeError("profile unavailable")
+
+ result = await Microsoft365CopilotDeviceAuthHandler().poll_for_tokens("code")
+
+ assert result.status == "approved"
+ assert result.credentials is not None
+ assert result.credentials.username is None
+
+
+ ("error", "status"),
+ [
+ ("authorization_pending", "pending"),
+ ("slow_down", "slow_down"),
+ ("authorization_declined", "denied"),
+ ("expired_token", "expired"),
+ ],
+)
+async def test_poll_maps_microsoft_device_statuses(mocker, error, status) -> None:
+ response = MagicMock(status_code=400)
+ response.json.return_value = {"error": error}
+ _mock_client(mocker, [response])
+
+ result = await Microsoft365CopilotDeviceAuthHandler().poll_for_tokens("code")
+
+ assert result.status == status
+
+
+async def test_refresh_keeps_existing_refresh_token_when_omitted(mocker) -> None:
+ response = MagicMock(status_code=200)
+ response.json.return_value = {
+ "access_token": "new-access",
+ "expires_in": 3600,
+ "scope": "Sites.Read.All",
+ }
+ _mock_client(mocker, [response])
+ credentials = OAuth2Credentials(
+ id="credential-id",
+ provider="microsoft_365_copilot",
+ access_token=SecretStr("old-access"),
+ refresh_token=SecretStr("old-refresh"),
+ scopes=["Sites.Read.All"],
+ )
+
+ refreshed = await Microsoft365CopilotDeviceAuthHandler().refresh_tokens(credentials)
+
+ assert refreshed.refresh_token
+ assert refreshed.refresh_token.get_secret_value() == "old-refresh"
+
+
+def test_initial_token_without_scope_keeps_requested_default_scopes() -> None:
+ credentials = (
+ Microsoft365CopilotDeviceAuthHandler()._credentials_from_token_response(
+ {
+ "access_token": "access",
+ "refresh_token": "refresh",
+ "expires_in": 3600,
+ }
+ )
+ )
+
+ assert credentials.scopes == Microsoft365CopilotDeviceAuthHandler.DEFAULT_SCOPES
+
+
+def test_malformed_token_expiry_does_not_crash_authentication() -> None:
+ credentials = (
+ Microsoft365CopilotDeviceAuthHandler()._credentials_from_token_response(
+ {
+ "access_token": "access",
+ "refresh_token": "refresh",
+ "expires_in": "not-a-number",
+ }
+ )
+ )
+
+ assert credentials.access_token_expires_at is None
diff --git a/autogpt_platform/backend/backend/integrations/providers.py b/autogpt_platform/backend/backend/integrations/providers.py
index 8e0a9f2808..d11a12fc28 100644
--- a/autogpt_platform/backend/backend/integrations/providers.py
+++ b/autogpt_platform/backend/backend/integrations/providers.py
@@ -35,6 +35,7 @@ class ProviderName(str, Enum):
MCP = "mcp"
MEDIUM = "medium"
MEM0 = "mem0"
+ MICROSOFT_365_COPILOT = "microsoft_365_copilot"
NOTION = "notion"
NVIDIA = "nvidia"
OLLAMA = "ollama"
diff --git a/autogpt_platform/backend/backend/util/settings.py b/autogpt_platform/backend/backend/util/settings.py
index 6eb01bd2ff..9aa436d607 100644
--- a/autogpt_platform/backend/backend/util/settings.py
+++ b/autogpt_platform/backend/backend/util/settings.py
@@ -996,8 +996,10 @@ class Secrets(UpdateTrackingModel["Secrets"], BaseSettings):
microsoft_client_id: str = Field(
default="",
description="Entra application (client) ID, shared by Microsoft "
- "integrations. Set together with the client secret and tenant ID to "
- "mount the Teams bot adapter on the main API.",
+ "integrations. Microsoft 365 Copilot device auth falls back to "
+ "AutoGPT's public client ID when this is empty; set it together with "
+ "the server-only client secret and tenant ID to mount the Teams bot "
+ "adapter.",
)
microsoft_client_secret: str = Field(
default="",
diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/ConnectStep/ConnectStep.tsx b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/ConnectStep/ConnectStep.tsx
index de6cfe3493..333e1f8677 100644
--- a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/ConnectStep/ConnectStep.tsx
+++ b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/ConnectStep/ConnectStep.tsx
@@ -3,14 +3,12 @@
import { Button } from "@/components/atoms/Button/Button";
import { FadeIn } from "@/components/atoms/FadeIn/FadeIn";
import { Text } from "@/components/atoms/Text/Text";
+import { DeviceAuthConnectButton } from "@/components/contextual/DeviceAuth/DeviceAuthConnectButton";
import { BotAvatar } from "@/components/molecules/BotAvatar/BotAvatar";
import { AUTOPILOT_AVATAR } from "@/components/molecules/BotAvatar/helpers";
import { ProviderBox } from "./components/ProviderBox";
import { useConnectStep } from "./useConnectStep";
-// Subscriptions the experts could run on. Only ChatGPT has an adapter and
-// provider approval today; the rest are named so the user knows what is
-// coming, without claiming they work yet.
const UPCOMING = [
{ name: "Grok", logoSrc: "/integrations/xai.webp" },
{ name: "GitHub Copilot", logoSrc: "/integrations/github.png" },
@@ -24,7 +22,14 @@ const UPCOMING = [
* skippable so a user with keys is not blocked by a wizard.
*/
export function ConnectStep() {
- const { connect, isConnecting, skip, isAlreadyLinked } = useConnectStep();
+ const {
+ connect,
+ finishConnection,
+ isConnecting,
+ skip,
+ isChatGPTLinked,
+ isMicrosoftLinked,
+ } = useConnectStep();
return (
<FadeIn>
@@ -41,7 +46,7 @@ export function ConnectStep() {
Already paying for an AI subscription?
</Text>
<Text variant="large" as="p" tone="muted" className="max-w-md">
- Add it and your experts run on it. No API keys, no billing setup.
+ Connect it for AutoGPT chats. No API keys, no billing setup.
</Text>
</div>
@@ -52,7 +57,7 @@ export function ConnectStep() {
<ProviderBox
name="ChatGPT"
logoSrc="/integrations/openai.png"
- state={isAlreadyLinked ? "connected" : "available"}
+ state={isChatGPTLinked ? "connected" : "available"}
isBusy={isConnecting}
onClick={connect}
/>
@@ -65,6 +70,29 @@ export function ConnectStep() {
))}
</div>
+ <div className="w-full rounded-2xl border border-zinc-200 bg-white p-4">
+ {isMicrosoftLinked ? (
+ <Text variant="body" as="p">
+ Your Microsoft 365 Copilot is connected. It can answer chats but
+ does not run AutoGPT tools.
+ </Text>
+ ) : (
+ <>
+ <DeviceAuthConnectButton
+ provider="microsoft_365_copilot"
+ providerName="Microsoft 365 Copilot"
+ onSuccess={finishConnection}
+ />
+ <Text variant="small" as="p" tone="muted" className="mt-3">
+ Requires a paid Microsoft Copilot or Copilot Business add-on
+ from your work or school organization. The included Microsoft
+ 365 Copilot Chat does not qualify. This connection answers chats
+ but does not run AutoGPT tools.
+ </Text>
+ </>
+ )}
+ </div>
+
<Button size="small" onClick={skip} className="h-10 w-56 rounded-xl">
Next
</Button>
diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/ConnectStep/__tests__/ConnectStep.test.tsx b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/ConnectStep/__tests__/ConnectStep.test.tsx
index 4ce6c5ac67..e5bfb9a56e 100644
--- a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/ConnectStep/__tests__/ConnectStep.test.tsx
+++ b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/ConnectStep/__tests__/ConnectStep.test.tsx
@@ -13,7 +13,11 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
import { useOnboardingWizardStore } from "../../../store";
import { ConnectStep } from "../ConnectStep";
-import { hasLinkedSubscription, linkedModelsSentence } from "../helpers";
+import {
+ hasLinkedSubscription,
+ linkedModelsSentence,
+ linkedSubscriptionName,
+} from "../helpers";
const connect = vi.fn();
let onConnected: (() => void) | undefined;
@@ -27,10 +31,33 @@ vi.mock(
}),
);
+vi.mock("@/components/contextual/DeviceAuth/DeviceAuthConnectButton", () => {
+ interface Props {
+ provider: string;
+ providerName: string;
+ onSuccess: () => void;
+ }
+
+ function MockDeviceAuthConnectButton({
+ provider,
+ providerName,
+ onSuccess,
+ }: Props) {
+ return (
+ <button data-provider={provider} onClick={onSuccess}>
+ Connect {providerName}
+ </button>
+ );
+ }
+
+ return { DeviceAuthConnectButton: MockDeviceAuthConnectButton };
+});
+
function offer(over: Partial<AIConnectionOffer> = {}): AIConnectionOffer {
return {
offer_id: "platform:deployment",
provider_family: "autogpt",
+ auth_provider: "platform",
display_name: "Self-hosted chat",
auth_method: "deployment",
credential_id: null,
@@ -44,13 +71,14 @@ function offer(over: Partial<AIConnectionOffer> = {}): AIConnectionOffer {
lock_reason: null,
unlock_href: null,
...over,
- } as AIConnectionOffer;
+ };
}
function chatgpt(over: Partial<AIConnectionOffer> = {}): AIConnectionOffer {
return offer({
offer_id: "codex:cred-1",
provider_family: "openai",
+ auth_provider: "codex",
display_name: "ChatGPT",
auth_method: "chatgpt_oauth",
credential_id: "cred-1",
@@ -84,6 +112,21 @@ function chatgptTiers(): ProviderTiers {
} as ProviderTiers;
}
+function microsoftCopilot(
+ over: Partial<AIConnectionOffer> = {},
+): AIConnectionOffer {
+ return offer({
+ offer_id: "microsoft_365_copilot:cred-msft",
+ provider_family: "microsoft",
+ auth_provider: "microsoft_365_copilot",
+ display_name: "Microsoft 365 Copilot",
+ auth_method: "device_code",
+ credential_id: "cred-msft",
+ is_default: false,
+ ...over,
+ });
+}
+
function mockOffers(
offers: AIConnectionOffer[],
providers: ProviderTiers[] = [],
@@ -185,6 +228,91 @@ describe("ConnectStep", () => {
expect(screen.queryByRole("button", { name: /ChatGPT/ })).toBeNull();
expect(screen.getByRole("button", { name: "Next" })).toBeDefined();
});
+
+ it("offers Microsoft device sign-in alongside subscription cards", async () => {
+ mockOffers([offer()]);
+ render(<ConnectStep />);
+
+ expect(
+ await screen.findByRole("button", {
+ name: /Connect Microsoft 365 Copilot/,
+ }),
+ ).toBeDefined();
+ expect(
+ screen.getByText(/included Microsoft 365 Copilot Chat does not qualify/i),
+ ).toBeDefined();
+ expect(screen.getByRole("button", { name: /ChatGPT/ })).toBeDefined();
+ expect(screen.getByRole("button", { name: "Next" })).toBeDefined();
+ });
+
+ it("refreshes Microsoft connection status without advancing the wizard", async () => {
+ mockOffers([offer()]);
+ render(
+ <>
+ <QueryClientProbe />
+ <ConnectStep />
+ </>,
+ );
+ await screen.findByRole("button", {
+ name: /Connect Microsoft 365 Copilot/,
+ });
+ await waitFor(() =>
+ expect(
+ queryClient?.getQueryState(getGetV2ListChatConnectionsQueryKey())
+ ?.fetchStatus,
+ ).toBe("idle"),
+ );
+ mockOffers([offer(), microsoftCopilot()]);
+
+ await userEvent.click(
+ screen.getByRole("button", { name: /Connect Microsoft 365 Copilot/ }),
+ );
+
+ expect(
+ await screen.findByText(/Your Microsoft 365 Copilot is connected/),
+ ).toBeDefined();
+ expect(useOnboardingWizardStore.getState().currentStep).toBe(3);
+ expect(screen.getByRole("button", { name: /ChatGPT/ })).toBeDefined();
+ expect(
+ screen.queryByRole("button", { name: /Connect Microsoft 365 Copilot/ }),
+ ).toBeNull();
+ });
+
+ it("keeps ChatGPT available when only Microsoft is linked", async () => {
+ mockOffers([offer(), microsoftCopilot()]);
+ render(<ConnectStep />);
+
+ expect(
+ await screen.findByText(/Your Microsoft 365 Copilot is connected/),
+ ).toBeDefined();
+ expect(screen.getByRole("button", { name: /ChatGPT/ })).toBeDefined();
+ expect(screen.queryByText("Connected")).toBeNull();
+ expect(screen.getByText(/does not run AutoGPT tools/)).toBeDefined();
+ });
+
+ it("keeps Microsoft available when only ChatGPT is linked", async () => {
+ mockOffers([offer(), chatgpt()]);
+ render(<ConnectStep />);
+
+ expect(await screen.findByText("Connected")).toBeDefined();
+ expect(
+ screen.getByRole("button", { name: /Connect Microsoft 365 Copilot/ }),
+ ).toBeDefined();
+ });
+
+ it("shows both connected providers without offering either sign-in", async () => {
+ mockOffers([offer(), chatgpt(), microsoftCopilot()]);
+ render(<ConnectStep />);
+
+ expect(
+ await screen.findByText(/Your Microsoft 365 Copilot is connected/),
+ ).toBeDefined();
+ expect(screen.getByText("Connected")).toBeDefined();
+ expect(screen.queryByRole("button", { name: /ChatGPT/ })).toBeNull();
+ expect(
+ screen.queryByRole("button", { name: /Connect Microsoft 365 Copilot/ }),
+ ).toBeNull();
+ });
});
describe("ConnectStep helpers", () => {
@@ -193,6 +321,9 @@ describe("ConnectStep helpers", () => {
// an API key in a file -- which is what this step offers a way around.
expect(hasLinkedSubscription([offer()])).toBe(false);
expect(hasLinkedSubscription([offer(), chatgpt()])).toBe(true);
+ expect(linkedSubscriptionName([offer(), microsoftCopilot()])).toBe(
+ "Microsoft 365 Copilot",
+ );
});
it("names the models from the catalog rather than hardcoding them", () => {
diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/ConnectStep/helpers.ts b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/ConnectStep/helpers.ts
index b8c868caba..6a0aa8f553 100644
--- a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/ConnectStep/helpers.ts
+++ b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/ConnectStep/helpers.ts
@@ -11,10 +11,17 @@ import type { ProviderTiers } from "@/app/api/__generated__/models/providerTiers
export function hasLinkedSubscription(
offers: AIConnectionOffer[] | undefined,
): boolean {
- return (offers ?? []).some(
+ return linkedSubscriptionName(offers) !== null;
+}
+
+export function linkedSubscriptionName(
+ offers: AIConnectionOffer[] | undefined,
+): string | null {
+ const linked = (offers ?? []).find(
(offer) =>
offer.auth_method !== "deployment" && Boolean(offer.credential_id),
);
+ return linked?.display_name ?? null;
}
/**
diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/ConnectStep/useConnectStep.ts b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/ConnectStep/useConnectStep.ts
index 49ea37635a..bde29cf8c6 100644
--- a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/ConnectStep/useConnectStep.ts
+++ b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/ConnectStep/useConnectStep.ts
@@ -8,7 +8,6 @@ import { useQueryClient } from "@tanstack/react-query";
import { useOAuthConnect } from "@/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/useOAuthConnect";
import { useOnboardingWizardStore } from "../../store";
-import { hasLinkedSubscription } from "./helpers";
export function useConnectStep() {
const nextStep = useOnboardingWizardStore((s) => s.nextStep);
@@ -22,20 +21,30 @@ export function useConnectStep() {
? connectionsQuery.data.data.offers
: undefined;
- // A successful sign-in does not move the wizard on: the box turns to
- // "Connected" and the user goes on with Next when they are ready.
+ function finishConnection() {
+ void queryClient.invalidateQueries({
+ queryKey: getGetV2ListChatConnectionsQueryKey(),
+ });
+ }
+
const { connect, isPending } = useOAuthConnect({
provider: "codex",
- onSuccess: () =>
- void queryClient.invalidateQueries({
- queryKey: getGetV2ListChatConnectionsQueryKey(),
- }),
+ onSuccess: finishConnection,
});
return {
connect,
+ finishConnection,
isConnecting: isPending,
skip: nextStep,
- isAlreadyLinked: hasLinkedSubscription(offers),
+ isChatGPTLinked: (offers ?? []).some(
+ (offer) =>
+ offer.auth_provider === "codex" && Boolean(offer.credential_id),
+ ),
+ isMicrosoftLinked: (offers ?? []).some(
+ (offer) =>
+ offer.auth_provider === "microsoft_365_copilot" &&
+ Boolean(offer.credential_id),
+ ),
};
}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useHydrateOnStreamEnd.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useHydrateOnStreamEnd.test.ts
index 68e69536f4..f67b62e1b5 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useHydrateOnStreamEnd.test.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useHydrateOnStreamEnd.test.ts
@@ -94,6 +94,35 @@ function runForceHydrate({
}
describe("useHydrateOnStreamEnd — sliding-window history retention (SECRT-2424)", () => {
+ it.each(["Hello [1] world", "Goodbye", ""])(
+ "reconciles the streamed preview with rewritten provider text: %j",
+ (finalText) => {
+ const preview: Messages = [
+ seqMessage(1),
+ {
+ id: "live-assistant",
+ role: "assistant",
+ parts: [{ type: "text", text: "Hello world", state: "done" }],
+ },
+ ];
+ const canonical: Messages = [
+ seqMessage(1),
+ {
+ id: `${SESSION_ID}-seq-2`,
+ role: "assistant",
+ parts: [{ type: "text", text: finalText, state: "done" }],
+ },
+ ];
+ expect(
+ runForceHydrate({
+ prev: preview,
+ staleWindow: [seqMessage(1)],
+ freshWindow: canonical,
+ }),
+ ).toEqual(canonical);
+ },
+ );
+
afterEach(() => {
_resetInterruptedToastLedgerForTests();
cleanup();
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/ConnectionPicker/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/ConnectionPicker/helpers.ts
index 5346b645d9..cee98731ce 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/ConnectionPicker/helpers.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/ConnectionPicker/helpers.ts
@@ -7,8 +7,11 @@ export function offerToSelection(
if (offer.auth_method === "deployment") {
return { authProvider: "platform", credentialId: null };
}
- if (!offer.credential_id) return null;
- return { authProvider: "codex", credentialId: offer.credential_id };
+ if (offer.auth_provider === "platform" || !offer.credential_id) return null;
+ return {
+ authProvider: offer.auth_provider,
+ credentialId: offer.credential_id,
+ };
}
export function matchesSelection(
@@ -16,10 +19,10 @@ export function matchesSelection(
selection: CopilotLlmAuthSelection | null,
): boolean {
if (!selection) return false;
- if (selection.authProvider === "platform") {
- return offer.auth_method === "deployment";
- }
- return offer.credential_id === selection.credentialId;
+ return (
+ offer.auth_provider === selection.authProvider &&
+ offer.credential_id === selection.credentialId
+ );
}
export function isSelectable(offer: AIConnectionOffer): boolean {
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/__tests__/ConnectionPicker.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/__tests__/ConnectionPicker.test.tsx
index e00a90214f..f2a749dce9 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/__tests__/ConnectionPicker.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/__tests__/ConnectionPicker.test.tsx
@@ -29,6 +29,7 @@ function tier(
function offer(over: Partial<AIConnectionOffer> = {}): AIConnectionOffer {
return {
offer_id: "platform:deployment",
+ auth_provider: "platform",
provider_family: "autogpt",
display_name: "AutoGPT Platform",
auth_method: "deployment",
@@ -50,6 +51,7 @@ function offer(over: Partial<AIConnectionOffer> = {}): AIConnectionOffer {
const chatgpt = (over: Partial<AIConnectionOffer> = {}) =>
offer({
offer_id: "codex:cred-1",
+ auth_provider: "codex",
provider_family: "openai",
display_name: "ChatGPT",
auth_method: "chatgpt_oauth",
@@ -67,6 +69,7 @@ const chatgpt = (over: Partial<AIConnectionOffer> = {}) =>
const locked = (over: Partial<AIConnectionOffer> = {}) =>
offer({
offer_id: "codex:locked",
+ auth_provider: "codex",
provider_family: "openai",
display_name: "ChatGPT",
auth_method: "chatgpt_oauth",
@@ -84,6 +87,23 @@ const locked = (over: Partial<AIConnectionOffer> = {}) =>
...over,
});
+const microsoft = (over: Partial<AIConnectionOffer> = {}) =>
+ offer({
+ offer_id: "microsoft_365_copilot:cred-msft",
+ auth_provider: "microsoft_365_copilot",
+ provider_family: "microsoft",
+ display_name: "Microsoft 365 Copilot",
+ auth_method: "device_code",
+ credential_id: "cred-msft",
+ backed_by_label: "Your Microsoft 365 Copilot plan",
+ is_default: false,
+ tiers: [],
+ limitations: [
+ "Microsoft 365 Copilot returns text and does not run AutoGPT tools.",
+ ],
+ ...over,
+ });
+
function mockOffers(offers: AIConnectionOffer[]) {
server.use(getGetV2ListChatConnectionsMockHandler200({ offers }));
}
@@ -241,6 +261,23 @@ describe("ConnectionPicker", () => {
});
});
+ it("preserves a Microsoft 365 Copilot credential selection", async () => {
+ mockOffers([offer(), microsoft()]);
+ render(<ConnectionPicker />);
+
+ await userEvent.click(await openPicker());
+ await userEvent.click(
+ await screen.findByRole("radio", { name: /Microsoft 365 Copilot/ }),
+ );
+
+ await waitFor(() =>
+ expect(useCopilotUIStore.getState().copilotLlmAuth).toEqual({
+ authProvider: "microsoft_365_copilot",
+ credentialId: "cred-msft",
+ }),
+ );
+ });
+
it("ignores arrow keys an IME is composing", async () => {
// Both radiogroups pass `event.key` straight into nextRovingValue, so the
// composition guard sits on the handler rather than on a key comparison.
@@ -723,7 +760,7 @@ describe("ConnectionPicker", () => {
render(<ConnectionPicker />);
- const trigger = await screen.findByRole("button", { name: /Runs on/ });
+ const trigger = await openPicker();
expect(trigger.getAttribute("aria-label")).not.toMatch(/your plan/);
});
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/__tests__/MaxUpgrade.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/__tests__/MaxUpgrade.test.tsx
index 2f9dc77d8b..a8ab345627 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/__tests__/MaxUpgrade.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/__tests__/MaxUpgrade.test.tsx
@@ -78,6 +78,7 @@ describe("contextual Max upsell", () => {
deploymentOffer(),
deploymentOffer({
offer_id: "codex:locked",
+ auth_provider: "codex",
provider_family: "openai",
display_name: "ChatGPT",
auth_method: "chatgpt_oauth",
@@ -112,6 +113,7 @@ describe("contextual Max upsell", () => {
it("keeps a connected provider's available Advanced tier selectable", async () => {
const linked = deploymentOffer({
offer_id: "codex:cred-1",
+ auth_provider: "codex",
provider_family: "openai",
display_name: "ChatGPT",
auth_method: "chatgpt_oauth",
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/__tests__/maxUpgradeFixtures.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/__tests__/maxUpgradeFixtures.tsx
index 22d85b4a81..6a55d13498 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/__tests__/maxUpgradeFixtures.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/__tests__/maxUpgradeFixtures.tsx
@@ -14,6 +14,7 @@ export function deploymentOffer(
): AIConnectionOffer {
return {
offer_id: "platform:deployment",
+ auth_provider: "platform",
provider_family: "autogpt",
display_name: "AutoGPT Platform",
auth_method: "deployment",
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ProviderLimitDialog/__tests__/helpers.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ProviderLimitDialog/__tests__/helpers.test.ts
index 8d93ba739d..f8b3d925f0 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ProviderLimitDialog/__tests__/helpers.test.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ProviderLimitDialog/__tests__/helpers.test.ts
@@ -8,6 +8,7 @@ function offer(over: Partial<AIConnectionOffer> = {}): AIConnectionOffer {
return {
offer_id: "platform:deployment",
provider_family: "autogpt",
+ auth_provider: "platform",
display_name: "AutoGPT Platform",
auth_method: "deployment",
credential_id: null,
@@ -21,13 +22,14 @@ function offer(over: Partial<AIConnectionOffer> = {}): AIConnectionOffer {
lock_reason: null,
unlock_href: null,
...over,
- } as AIConnectionOffer;
+ };
}
function chatgpt(over: Partial<AIConnectionOffer> = {}): AIConnectionOffer {
return offer({
offer_id: "codex:cred-1",
provider_family: "openai",
+ auth_provider: "codex",
display_name: "ChatGPT",
auth_method: "chatgpt_oauth",
credential_id: "cred-1",
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/copilotLlmAuth.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/copilotLlmAuth.ts
index 0f4490d952..7103bb02c6 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/copilotLlmAuth.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/copilotLlmAuth.ts
@@ -20,7 +20,7 @@ export function getChatTransportSelection(
}
if (transport.credential_id === null) return null;
return {
- authProvider: "codex",
+ authProvider: transport.auth_provider,
credentialId: transport.credential_id,
};
}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/store.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/store.ts
index 205b93c4b4..0e53acc93e 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/store.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/store.ts
@@ -81,7 +81,8 @@ export type CopilotLlmModel = "standard" | "advanced";
export type CopilotLlmAuthSelection =
| { authProvider: "platform"; credentialId: null }
- | { authProvider: "codex"; credentialId: string };
+ | { authProvider: "codex"; credentialId: string }
+ | { authProvider: "microsoft_365_copilot"; credentialId: string };
/** Context panel tab: "files" is the inline workspace-files card, "artifacts"
* the docked artifacts library. */
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useChatSession.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/useChatSession.ts
index edbac2452a..bf3f2c28dc 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/useChatSession.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useChatSession.ts
@@ -243,7 +243,7 @@ export function useChatSession({
variant: "destructive",
title: "Otto needs an AI connection",
description:
- "Sign in with ChatGPT under OpenAI in Settings → Integrations, or configure a chat API or local model on this server.",
+ "Connect ChatGPT or Microsoft 365 Copilot in Settings → Integrations, or configure a chat API or local model on this server.",
});
throw new Error("chat_transport_not_configured");
}
@@ -286,7 +286,7 @@ export function useChatSession({
// user actually picks, and null means "use whatever the server says".
if (copilotLlmAuth !== null) {
sessionData.llm_auth_provider = resolvedLLMAuth.authProvider;
- if (resolvedLLMAuth.authProvider === "codex") {
+ if (resolvedLLMAuth.authProvider !== "platform") {
sessionData.llm_credential_id = resolvedLLMAuth.credentialId;
}
}
@@ -358,12 +358,20 @@ export function useChatSession({
freshSessionData as { chat_status?: string } | undefined
)?.chat_status;
- const sessionLlmAuthProvider: "platform" | "codex" | null =
- sessionId && sessionQuery.data?.status === 200
- ? sessionQuery.data.data.metadata?.llm_auth_provider === "codex"
- ? "codex"
- : "platform"
+ const storedLlmAuthProvider =
+ sessionQuery.data?.status === 200
+ ? sessionQuery.data.data.metadata?.llm_auth_provider
: null;
+ const sessionLlmAuthProvider:
+ | "platform"
+ | "codex"
+ | "microsoft_365_copilot"
+ | null = sessionId
+ ? storedLlmAuthProvider === "codex" ||
+ storedLlmAuthProvider === "microsoft_365_copilot"
+ ? storedLlmAuthProvider
+ : "platform"
+ : null;
const sessionLlmCredentialId =
sessionId && sessionQuery.data?.status === 200
? (sessionQuery.data.data.metadata?.llm_credential_id ?? null)
diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.json
index d724ede488..e4be259924 100644
--- a/autogpt_platform/frontend/src/app/api/openapi.json
+++ b/autogpt_platform/frontend/src/app/api/openapi.json
@@ -16172,6 +16172,11 @@
"AIConnectionOffer": {
"properties": {
"offer_id": { "type": "string", "title": "Offer Id" },
+ "auth_provider": {
+ "type": "string",
+ "enum": ["platform", "codex", "microsoft_365_copilot"],
+ "title": "Auth Provider"
+ },
"provider_family": { "type": "string", "title": "Provider Family" },
"display_name": { "type": "string", "title": "Display Name" },
"auth_method": { "type": "string", "title": "Auth Method" },
@@ -16206,6 +16211,7 @@
"type": "object",
"required": [
"offer_id",
+ "auth_provider",
"provider_family",
"display_name",
"auth_method",
@@ -18137,7 +18143,7 @@
"properties": {
"llm_auth_provider": {
"type": "string",
- "enum": ["platform", "codex"],
+ "enum": ["platform", "codex", "microsoft_365_copilot"],
"title": "Llm Auth Provider"
},
"llm_credential_id": {
@@ -18195,7 +18201,7 @@
},
"llm_auth_provider": {
"type": "string",
- "enum": ["platform", "codex"],
+ "enum": ["platform", "codex", "microsoft_365_copilot"],
"title": "Llm Auth Provider",
"default": "platform"
},
@@ -18203,6 +18209,11 @@
"anyOf": [{ "type": "string" }, { "type": "null" }],
"title": "Llm Credential Id"
},
+ "llm_provider_session_ids": {
+ "additionalProperties": { "type": "string" },
+ "type": "object",
+ "title": "Llm Provider Session Ids"
+ },
"builder_graph_id": {
"anyOf": [{ "type": "string" }, { "type": "null" }],
"title": "Builder Graph Id"
@@ -18286,7 +18297,7 @@
"properties": {
"auth_provider": {
"type": "string",
- "enum": ["platform", "codex"],
+ "enum": ["platform", "codex", "microsoft_365_copilot"],
"title": "Auth Provider"
},
"credential_id": {
@@ -19148,7 +19159,7 @@
},
"llm_auth_provider": {
"type": "string",
- "enum": ["platform", "codex"],
+ "enum": ["platform", "codex", "microsoft_365_copilot"],
"title": "Llm Auth Provider",
"default": "platform"
},
@@ -19190,6 +19201,7 @@
"default": {
"dry_run": false,
"llm_auth_provider": "platform",
+ "llm_provider_session_ids": {},
"kind": "normal"
}
},
@@ -27655,6 +27667,7 @@
"default": {
"dry_run": false,
"llm_auth_provider": "platform",
+ "llm_provider_session_ids": {},
"kind": "normal"
}
},
@@ -27718,7 +27731,10 @@
"properties": {
"auth_provider": {
"anyOf": [
- { "type": "string", "enum": ["platform", "codex"] },
+ {
+ "type": "string",
+ "enum": ["platform", "codex", "microsoft_365_copilot"]
+ },
{ "type": "null" }
],
"title": "Auth Provider"
@@ -27734,7 +27750,7 @@
"additionalProperties": false,
"type": "object",
"title": "SetDefaultTransportRequest",
- "description": "The connection new chats should start on.\n\n``auth_provider: null`` clears the choice and hands the decision back to\nthe server. Sending ``codex`` requires naming the credential, so the\ndefault keeps pointing at one account rather than \"whichever ChatGPT\"."
+ "description": "The connection new chats should start on.\n\n``auth_provider: null`` clears the choice and hands the decision back to\nthe server. A user-backed provider requires naming the credential, so the\ndefault keeps pointing at one account rather than whichever account exists."
},
"SetGraphActiveVersion": {
"properties": {
diff --git a/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/AIConnectionsSection/AIConnectionsSection.tsx b/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/AIConnectionsSection/AIConnectionsSection.tsx
index 01d2efff4b..e24188ffde 100644
--- a/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/AIConnectionsSection/AIConnectionsSection.tsx
+++ b/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/AIConnectionsSection/AIConnectionsSection.tsx
@@ -21,6 +21,7 @@ export function AIConnectionsSection() {
const {
connections,
accountFor,
+ credentialFor,
selectedKey,
chooseDefault,
isSaving,
@@ -79,7 +80,8 @@ export function AIConnectionsSection() {
onSelect={() => chooseDefault(connection)}
onManage={
connection.credential_id &&
- connection.auth_method === "chatgpt_oauth"
+ (connection.auth_provider === "codex" ||
+ connection.auth_provider === "microsoft_365_copilot")
? () => setManaging(connection)
: undefined
}
@@ -92,7 +94,7 @@ export function AIConnectionsSection() {
<ManageConnectionDialog
connection={managing}
- account={managing ? accountFor(managing) : undefined}
+ credential={managing ? credentialFor(managing) : undefined}
onOpenChange={(open) => {
if (!open) setManaging(null);
}}
@@ -141,7 +143,8 @@ function ConnectionRow({
<Text variant="body-medium" as="span" className="text-black">
{connection.display_name}
</Text>
- {connection.auth_method === "chatgpt_oauth" &&
+ {connection.auth_method !== "deployment" &&
+ connection.credential_id &&
isSelectable(connection) && (
<span className="inline-flex items-center gap-1 rounded-[10px] bg-[#E8F8F0] px-2 py-[2px] text-[13px] font-medium leading-[20px] text-[#157E58]">
<Icon icon={CheckmarkCircle02Icon} size={13} />
diff --git a/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/AIConnectionsSection/ManageConnectionDialog.tsx b/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/AIConnectionsSection/ManageConnectionDialog.tsx
index 6fa597f7e0..ab1fdb3797 100644
--- a/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/AIConnectionsSection/ManageConnectionDialog.tsx
+++ b/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/AIConnectionsSection/ManageConnectionDialog.tsx
@@ -3,6 +3,7 @@
import { useState } from "react";
import { useGetV1CodexAccount } from "@/app/api/__generated__/endpoints/integrations/integrations";
import type { AIConnectionOffer } from "@/app/api/__generated__/models/aIConnectionOffer";
+import type { CredentialsMetaResponse } from "@/app/api/__generated__/models/credentialsMetaResponse";
import { Button } from "@/components/atoms/Button/Button";
import { Text } from "@/components/atoms/Text/Text";
import { Dialog } from "@/components/molecules/Dialog/Dialog";
@@ -10,10 +11,11 @@ import { Dialog } from "@/components/molecules/Dialog/Dialog";
import { useOAuthConnect } from "../ConnectServiceDialog/components/DetailView/useOAuthConnect";
import { DeleteConfirmDialog } from "../DeleteConfirmDialog/DeleteConfirmDialog";
import { useDeleteIntegration } from "../hooks/useDeleteIntegration";
+import { microsoftAccessLabels } from "./helpers";
interface Props {
connection: AIConnectionOffer | null;
- account?: string;
+ credential?: CredentialsMetaResponse;
onOpenChange: (open: boolean) => void;
}
@@ -25,11 +27,36 @@ interface Props {
*/
export function ManageConnectionDialog({
connection,
- account,
+ credential,
+ onOpenChange,
+}: Props) {
+ if (connection?.auth_provider === "microsoft_365_copilot") {
+ return (
+ <Microsoft365CopilotConnectionDialog
+ connection={connection}
+ credential={credential}
+ onOpenChange={onOpenChange}
+ />
+ );
+ }
+
+ return (
+ <ChatGPTConnectionDialog
+ connection={connection}
+ credential={credential}
+ onOpenChange={onOpenChange}
+ />
+ );
+}
+
+function ChatGPTConnectionDialog({
+ connection,
+ credential,
onOpenChange,
}: Props) {
const credentialId = connection?.credential_id ?? null;
const [forceMessage, setForceMessage] = useState<string | null>(null);
+ const account = credential?.username ?? undefined;
// Asked for only while this dialog is open. Reading it leases a runtime
// against the provider, so it must never run on the list behind — and it
@@ -185,3 +212,147 @@ export function ManageConnectionDialog({
</>
);
}
+
+interface MicrosoftProps {
+ connection: AIConnectionOffer;
+ credential?: CredentialsMetaResponse;
+ onOpenChange: (open: boolean) => void;
+}
+
+function Microsoft365CopilotConnectionDialog({
+ connection,
+ credential,
+ onOpenChange,
+}: MicrosoftProps) {
+ const [forceMessage, setForceMessage] = useState<string | null>(null);
+ const { remove, isPending: isDisconnecting } = useDeleteIntegration();
+ const credentialId = connection.credential_id;
+ const accessLabels = microsoftAccessLabels(credential?.scopes);
+ const displayName =
+ credential?.title && credential.title !== "Microsoft 365 Copilot"
+ ? credential.title
+ : undefined;
+
+ const accountName = credential?.username ?? "Microsoft 365 Copilot";
+
+ function setManageOpen(open: boolean) {
+ if (!open) setForceMessage(null);
+ onOpenChange(open);
+ }
+
+ async function disconnect(force = false) {
+ if (!credentialId) return;
+ const target = {
+ id: credentialId,
+ provider: "microsoft_365_copilot",
+ name: accountName,
+ };
+ const result = await remove([target], force);
+ const confirmation = result.needsConfirmation[0];
+ if (confirmation) {
+ setForceMessage(confirmation.message);
+ return;
+ }
+ if (result.succeeded.length === 0) return;
+
+ setForceMessage(null);
+ setManageOpen(false);
+ }
+
+ return (
+ <>
+ <Dialog
+ title="Microsoft 365 Copilot"
+ styling={{ maxWidth: "32rem" }}
+ controlled={{
+ isOpen: forceMessage === null,
+ set: (open) => {
+ if (!open && forceMessage !== null) return;
+ setManageOpen(open);
+ },
+ }}
+ >
+ <Dialog.Content>
+ <div className="flex flex-col gap-5">
+ <div className="flex flex-col gap-1">
+ <Text variant="small" className="text-[#8A8A90]">
+ Connected work account
+ </Text>
+ <Text variant="body-medium" className="text-black">
+ {displayName ??
+ credential?.username ??
+ "Microsoft 365 Copilot account"}
+ </Text>
+ {displayName && credential?.username && (
+ <Text variant="small" className="text-[#505057]">
+ {credential.username}
+ </Text>
+ )}
+ {!credential?.username && (
+ <Text variant="small" className="text-[#8A8A90]">
+ Reconnect once to show the signed-in account here.
+ </Text>
+ )}
+ </div>
+
+ <div className="flex flex-col gap-2">
+ <Text variant="small-medium" className="text-[#505057]">
+ Access granted
+ </Text>
+ {accessLabels.length > 0 ? (
+ <div className="flex flex-wrap gap-2">
+ {accessLabels.map((label) => (
+ <span
+ key={label}
+ className="rounded-[10px] bg-[#EFF1F4] px-2 py-[2px] text-[13px] font-medium leading-[20px] text-[#505057]"
+ >
+ {label}
+ </span>
+ ))}
+ </div>
+ ) : (
+ <Text variant="small" className="text-[#8A8A90]">
+ Reconnect once to refresh the access shown here.
+ </Text>
+ )}
+ </div>
+
+ <Text variant="small" className="text-[#505057]">
+ Microsoft still limits every answer to content this work account
+ can already access in Microsoft 365.
+ </Text>
+
+ <div className="flex justify-end pt-1">
+ <Button
+ variant="destructive"
+ size="small"
+ onClick={() => void disconnect()}
+ loading={isDisconnecting}
+ >
+ Disconnect
+ </Button>
+ </div>
+
+ <Text variant="small" className="text-[#8A8A90]">
+ Disconnecting stops new chats using this Copilot subscription.
+ Your chat history is kept, and your other integrations are
+ unaffected.
+ </Text>
+ </div>
+ </Dialog.Content>
+ </Dialog>
+
+ <DeleteConfirmDialog
+ open={forceMessage !== null}
+ onOpenChange={(open) => {
+ if (!open) setForceMessage(null);
+ }}
+ itemNames={[accountName]}
+ isPending={isDisconnecting}
+ onConfirm={() => void disconnect(true)}
+ variant="force"
+ notice={forceMessage ?? undefined}
+ />
+ </>
+ );
+}
diff --git a/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/AIConnectionsSection/__tests__/AIConnectionsSection.test.tsx b/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/AIConnectionsSection/__tests__/AIConnectionsSection.test.tsx
index dd3a6724eb..f2deed5d91 100644
--- a/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/AIConnectionsSection/__tests__/AIConnectionsSection.test.tsx
+++ b/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/AIConnectionsSection/__tests__/AIConnectionsSection.test.tsx
@@ -91,9 +91,36 @@ function lockedChatgpt(): AIConnectionOffer {
};
}
+function microsoft(isDefault: boolean, id = "cred-msft"): AIConnectionOffer {
+ return {
+ offer_id: `microsoft_365_copilot:${id}`,
+ auth_provider: "microsoft_365_copilot",
+ provider_family: "microsoft",
+ display_name: "Microsoft 365 Copilot",
+ auth_method: "device_oauth",
+ credential_id: id,
+ backed_by_label: "Your Microsoft Copilot plan",
+ description:
+ "New chats are backed by your Microsoft Copilot subscription and work context.",
+ state: "ready",
+ selectable: true,
+ is_default: isDefault,
+ tiers: [],
+ limitations: [],
+ } as AIConnectionOffer;
+}
+
+interface MockCredential {
+ id: string;
+ username?: string;
+ provider?: string;
+ title?: string;
+ scopes?: string[];
+}
+
function mockTransports(
offers: AIConnectionOffer[],
- credentials: { id: string; username: string }[] = [],
+ credentials: MockCredential[] = [],
) {
server.use(
getGetV2ListChatConnectionsMockHandler200({ offers }),
@@ -101,11 +128,11 @@ function mockTransports(
getGetV1ListCredentialsMockHandler200(
credentials.map((credential) => ({
id: credential.id,
- provider: "codex",
+ provider: credential.provider ?? "codex",
type: "oauth2" as const,
- title: "ChatGPT for Codex",
- scopes: [],
- username: credential.username,
+ title: credential.title ?? "ChatGPT for Codex",
+ scopes: credential.scopes ?? [],
+ username: credential.username ?? null,
})),
),
);
@@ -228,6 +255,89 @@ describe("AIConnectionsSection", () => {
);
});
+ it("shows the Microsoft account and its granted access", async () => {
+ mockTransports(
+ [platform(false), microsoft(true)],
+ [
+ {
+ id: "cred-msft",
+ provider: "microsoft_365_copilot",
+ username: "[email protected]",
+ title: "Nick Example",
+ scopes: ["User.Read", "Mail.Read", "Chat.Read"],
+ },
+ ],
+ );
+
+ render(<AIConnectionsSection />);
+
+ expect(await screen.findByText("[email protected]")).toBeDefined();
+ expect(screen.getByText("Connected")).toBeDefined();
+ await userEvent.click(screen.getByRole("button", { name: "Manage" }));
+
+ expect(await screen.findByText("Nick Example")).toBeDefined();
+ expect(screen.getByText("Basic account profile")).toBeDefined();
+ expect(screen.getByText("Outlook mail")).toBeDefined();
+ expect(screen.getByText("Teams chats")).toBeDefined();
+ });
+
+ it("keeps the Microsoft manage dialog open when disconnect fails", async () => {
+ mockTransports(
+ [platform(false), microsoft(true)],
+ [
+ {
+ id: "cred-msft",
+ provider: "microsoft_365_copilot",
+ username: "[email protected]",
+ },
+ ],
+ );
+ server.use(
+ getDeleteV1DeleteCredentialsMockHandler401({ detail: "Not authorized" }),
+ );
+
+ render(<AIConnectionsSection />);
+ await userEvent.click(
+ await screen.findByRole("button", { name: "Manage" }),
+ );
+ await userEvent.click(screen.getByRole("button", { name: "Disconnect" }));
+
+ await waitFor(() =>
+ expect(screen.getByRole("button", { name: "Disconnect" })).toBeDefined(),
+ );
+ });
+
+ it("asks before force-removing an in-use Microsoft connection", async () => {
+ mockTransports([platform(false), microsoft(true)]);
+ server.use(
+ getDeleteV1DeleteCredentialsMockHandler200(({ request }) =>
+ new URL(request.url).searchParams.get("force") === "true"
+ ? { deleted: true, revoked: true }
+ : {
+ deleted: false,
+ need_confirmation: true,
+ message: "Used by an active schedule",
+ },
+ ),
+ );
+
+ render(<AIConnectionsSection />);
+ await userEvent.click(
+ await screen.findByRole("button", { name: "Manage" }),
+ );
+ await userEvent.click(screen.getByRole("button", { name: "Disconnect" }));
+
+ expect(
+ await screen.findByRole("button", { name: "Force remove" }),
+ ).toBeDefined();
+ expect(await screen.findByText("Used by an active schedule")).toBeDefined();
+ await userEvent.click(screen.getByRole("button", { name: "Force remove" }));
+
+ await waitFor(() =>
+ expect(screen.queryByRole("button", { name: "Disconnect" })).toBeNull(),
+ );
+ });
+
it("marks the saved default, and only that one", async () => {
mockTransports([platform(false), chatgpt(true)]);
diff --git a/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/AIConnectionsSection/helpers.ts b/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/AIConnectionsSection/helpers.ts
index 2378216cca..b6319b3dfc 100644
--- a/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/AIConnectionsSection/helpers.ts
+++ b/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/AIConnectionsSection/helpers.ts
@@ -2,6 +2,31 @@ import type { AIConnectionOffer } from "@/app/api/__generated__/models/aIConnect
import type { SetDefaultTransportRequest } from "@/app/api/__generated__/models/setDefaultTransportRequest";
import type { SetDefaultTransportRequestAuthProvider } from "@/app/api/__generated__/models/setDefaultTransportRequestAuthProvider";
+const MICROSOFT_SCOPE_LABELS: Record<string, string> = {
+ "User.Read": "Basic account profile",
+ "Sites.Read.All": "SharePoint and OneDrive files",
+ "Mail.Read": "Outlook mail",
+ "People.Read.All": "People in your organization",
+ "OnlineMeetingTranscript.Read.All": "Teams meeting transcripts",
+ "Chat.Read": "Teams chats",
+ "ChannelMessage.Read.All": "Teams channel messages",
+ "ExternalItem.Read.All": "External Microsoft Search items",
+ offline_access: "Stay connected",
+ openid: "Sign-in identity",
+ profile: "Basic account profile",
+ email: "Email address",
+};
+
+export function microsoftAccessLabels(
+ scopes: string[] | null | undefined,
+): string[] {
+ return Array.from(
+ new Set(
+ (scopes ?? []).map((scope) => MICROSOFT_SCOPE_LABELS[scope] ?? scope),
+ ),
+ );
+}
+
/**
* The route to send when making a connection the default.
*
diff --git a/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/AIConnectionsSection/useAIConnectionsSection.ts b/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/AIConnectionsSection/useAIConnectionsSection.ts
index 4cc8fae74f..0aed137aed 100644
--- a/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/AIConnectionsSection/useAIConnectionsSection.ts
+++ b/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/AIConnectionsSection/useAIConnectionsSection.ts
@@ -10,6 +10,7 @@ import {
} from "@/app/api/__generated__/endpoints/chat/chat";
import { useGetV1ListCredentials } from "@/app/api/__generated__/endpoints/integrations/integrations";
import type { AIConnectionOffer } from "@/app/api/__generated__/models/aIConnectionOffer";
+import type { CredentialsMetaResponse } from "@/app/api/__generated__/models/credentialsMetaResponse";
import { toast } from "@/components/molecules/Toast/use-toast";
import { routeOf, visibleOffers } from "./helpers";
@@ -41,15 +42,22 @@ export function useAIConnectionsSection() {
select: (response) => (response.status === 200 ? response.data : []),
},
});
- const accountByCredentialId = new Map(
- (credentialsQuery.data ?? [])
- .filter((credential) => credential.username)
- .map((credential) => [credential.id, credential.username as string]),
+ const credentialById = new Map(
+ (credentialsQuery.data ?? []).map((credential) => [
+ credential.id,
+ credential,
+ ]),
);
- function accountFor(offer: AIConnectionOffer): string | undefined {
+ function credentialFor(
+ offer: AIConnectionOffer,
+ ): CredentialsMetaResponse | undefined {
if (!offer.credential_id) return undefined;
- return accountByCredentialId.get(offer.credential_id);
+ return credentialById.get(offer.credential_id);
+ }
+
+ function accountFor(offer: AIConnectionOffer): string | undefined {
+ return credentialFor(offer)?.username ?? undefined;
}
const { mutate: setDefault, isPending: isSaving } =
@@ -90,6 +98,7 @@ export function useAIConnectionsSection() {
return {
connections: offers,
accountFor,
+ credentialFor,
selectedKey,
chooseDefault,
isSaving,