Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

37.3 KB
Raw Blame
#[cfg(test)]
mod test;

use std::{marker::PhantomData, sync::Arc};

use crate::edges::GraphqlAgentSessionLogEntry;
use crate::realtime::AgentSessionLogSubscriptions;
use crate::saved_view::{GraphqlSavedView, GraphqlSavedViewPage, SavedViewMutationRoot};
use agent_session::domain::model::AgentSessionId;
use async_graphql::{Context, ID, MergedObject, MergedSubscription, Object, Schema, Subscription};
use axum::extract::FromRef;
use email::domain::send_attempt::EmailSendService;
use email::{
    domain::ports::{EmailService, EmailUserService, NoOpEmailService},
    inbound::axum::previews_router::EmailRouterState,
};
use entity_access::domain::ports::{EntityAccessService, NoOpEntityAccessService};
use entity_mutation::{EntityMutationService, UnavailableEntityMutationService};
use favorites::domain::ports::FavoritesMutationService;
use graphql_activity::{
    ActivityFeedInput, ActivityOverviewInput, ActivityReader, ActivitySubscriptionRoot,
    ActivitySubscriptionService, GraphqlActivityEvent, GraphqlActivityOverview,
    GraphqlActivityPage, NoOpActivityReader, NoOpActivitySubscriptionService,
    resolve_activity_feed, resolve_activity_overview, resolve_database_activity,
    resolve_form_activity,
};
use graphql_calendar::{CalendarMutationRoot, GraphqlCalendarQuery};
use graphql_channel::{
    ChannelActivityAuthorizer, ChannelActivityMutationService, ChannelMutationRoot,
    NoOpChannelActivityMutationService,
};
use graphql_common::{GraphqlSoupEntityType, parse_id, require_authorized_user};
use graphql_email::{
    GraphqlEmailMutation, GraphqlEmailQuery, NoOpSoupEmailContentEdgeReader, SoupEmailEdgeReader,
    load_email_focus_thread_ids,
};
use graphql_entity_mutation::EntityMutationRoot;
use graphql_favorite::{
    EntityFavoriteEdgeReader, FavoriteMutationRoot, FavoriteQueryReader, FavoritesFilterInput,
    GraphqlFavorite, NoOpEntityFavoriteEdgeReader, NoOpFavoriteMutationService, resolve_favorites,
};
use graphql_initiative::{
    GraphqlInitiativeTasksPage, InitiativeMutationRoot, InitiativeTasksInput, resolve_initiative,
    resolve_initiative_tasks,
};
use graphql_notification::{
    NoOpNotificationMutationService, NoOpSoupNotificationEdgeReader, NotificationMutationRoot,
    NotificationMutationService, NotificationSubscriptionRoot, SoupNotificationEdgeReader,
};
use graphql_notification_inbox::{
    GraphqlNotificationInboxPage, NotificationInboxInput, NotificationInboxMutationRoot,
    NotificationInboxSubscriptionRoot, resolve_notification_inbox,
};
use graphql_permission::{EntityPermissionEdgeReader, NoOpEntityPermissionEdgeReader};
use graphql_properties::{
    EntityPropertyReader, EntityPropertyWriter, GraphqlPropertyDefinition,
    GraphqlPropertyDefinitionScope, GraphqlPropertyOption, NoOpEntityPropertyReader,
    NoOpEntityPropertyWriter, PropertiesMutationRoot, load_property_definitions,
    load_property_options,
};
use graphql_registered_work::{
    GraphqlRegisteredWork, RegisteredWorkSubscriptionRoot, resolve_registered_work,
};
use graphql_scheduled_action::{GraphqlScheduledAction, resolve_scheduled_actions};
use graphql_soup::{
    GraphqlSoupAgentSession, GraphqlSoupEmailThread, GraphqlSoupEntity, GraphqlSoupInitiative,
    GraphqlSoupProject, GroupedSoup, GroupedSoupInput, SoupEmailThreadMutationOutput,
    SoupEntityEdges, SoupInput, SoupPage, SoupPatch, resolve_folders, resolve_grouped_soup,
    resolve_soup, resolve_soup_agent_session, resolve_soup_email_thread,
    resolve_soup_email_threads, resolve_soup_entity, resolve_soup_updates,
};
use graphql_work_feed::{
    GraphqlWorkFeedPage, WorkFeedInput, WorkFeedMutationRoot, WorkFeedSubscriptionRoot,
    resolve_work_feed,
};
use macro_authorization::{
    InternalAuthConfig, MacroAuthorizationService, MacroAuthorizationServiceImpl,
    MacroAuthorizationState, NoopMacroAuthJwtValidator,
};
use macro_user_id::user_id::MacroUserIdStr;
use model_notifications::NotifEvent;
use notification::domain::{
    models::NotificationSubscriptionUpdate,
    ports::{
        NoopWebSocketNotificationSubscriptionService, WebSocketNotificationSubscriptionService,
    },
};
use soup::domain::ports::{NoOpSoupService, SoupService};
use soup_realtime::domain::ports::{
    NoOpSoupRealtimeSubscriptionService, SoupRealtimeSubscriptionService,
};

use crate::SoupEdges;

/// Mutation root combining independent domain GraphQL adapters.
#[derive(MergedObject)]
pub struct CompleteMutationRoot<
    W: EntityPropertyWriter,
    M: EntityMutationService,
    F: FavoritesMutationService,
    E: SoupEntityEdges,
    C: ChannelActivityMutationService,
    N: NotificationMutationService,
    A: ChannelActivityAuthorizer,
    ES: EmailService + EmailSendService,
>(
    PropertiesMutationRoot<W>,
    EntityMutationRoot<M, E>,
    FavoriteMutationRoot<F, E>,
    ChannelMutationRoot<C, A>,
    NotificationMutationRoot<N>,
    GraphqlEmailMutation<ES, SoupEmailThreadMutationOutput<E>>,
    graphql_email::GraphqlEmailSendMutation<ES, SoupEmailThreadMutationOutput<E>>,
    InitiativeMutationRoot<E>,
    CalendarMutationRoot,
    WorkFeedMutationRoot<E>,
    NotificationInboxMutationRoot<E>,
    SavedViewMutationRoot,
);

impl<
    W: EntityPropertyWriter,
    M: EntityMutationService,
    F: FavoritesMutationService,
    E: SoupEntityEdges,
    C: ChannelActivityMutationService,
    N: NotificationMutationService,
    A: ChannelActivityAuthorizer,
    ES: EmailService + EmailSendService,
> CompleteMutationRoot<W, M, F, E, C, N, A, ES>
{
    /// Construct the composed mutation root.
    fn new() -> Self {
        Self(
            PropertiesMutationRoot::<W>::new(),
            EntityMutationRoot::<M, E>::new(),
            FavoriteMutationRoot::<F, E>::new(),
            ChannelMutationRoot::<C, A>::new(),
            NotificationMutationRoot::<N>::new(),
            GraphqlEmailMutation::<ES, SoupEmailThreadMutationOutput<E>>::new(),
            graphql_email::GraphqlEmailSendMutation::<ES, SoupEmailThreadMutationOutput<E>>::default(),
            InitiativeMutationRoot::<E>::default(),
            CalendarMutationRoot,
            WorkFeedMutationRoot::<E>::default(),
            NotificationInboxMutationRoot::<E>::default(),
            SavedViewMutationRoot,
        )
    }
}

/// Root subscription object combining realtime Soup, notification,
/// activity, work feed and notification inbox adapters.
#[derive(MergedSubscription)]
pub struct CompleteSubscriptionRoot<R, NS, AS, Auth, St, NR, PR, ER, FR, AR, AcR>(
    SoupSubscriptionRoot<R, Auth, St, NR, PR, ER, FR, AR, AcR>,
    NotificationSubscriptionRoot<NS>,
    ActivitySubscriptionRoot<AS>,
    WorkFeedSubscriptionRoot<SoupEdges<NR, PR, ER, FR, AR, AcR>>,
    NotificationInboxSubscriptionRoot<SoupEdges<NR, PR, ER, FR, AR, AcR>>,
    RegisteredWorkSubscriptionRoot<SoupEdges<NR, PR, ER, FR, AR, AcR>>,
)
where
    R: SoupRealtimeSubscriptionService,
    NS: WebSocketNotificationSubscriptionService<NotificationSubscriptionUpdate<NotifEvent>>,
    AS: ActivitySubscriptionService,
    Auth: MacroAuthorizationService,
    St: Clone + Send + Sync + 'static,
    MacroAuthorizationState<Auth>: FromRef<St>,
    NR: SoupNotificationEdgeReader,
    PR: EntityPropertyReader,
    ER: SoupEmailEdgeReader,
    FR: EntityFavoriteEdgeReader,
    AR: EntityPermissionEdgeReader,
    AcR: ActivityReader;

/// GraphQL Soup schema type.
///
/// `S` is the soup query service, `R` the realtime Soup subscription service,
/// `NS` the realtime notification subscription service, `AS` the realtime
/// activity subscription service, `E` the email service, `EAS` the entity
/// access service, `Auth` the authorization service, `St` the embedding axum
/// router state, `W` the property mutation writer, `M` the entity mutation
/// service, `C` the channel activity mutation service, `N` the notification
/// mutation service, `NR` the notification edge reader, `PR` the property edge
/// reader, `ER` the email-content edge reader, `FR` the favorite edge reader,
/// `AR` the access edge reader, and `AcR` the activity reader.
pub type SoupSchema<S, R, NS, AS, E, EAS, Auth, St, W, M, FM, C, N, NR, PR, ER, FR, AR, AcR> =
    Schema<
        SoupQueryRoot<S, E, EAS, Auth, St, NR, PR, ER, FR, AR, AcR>,
        CompleteMutationRoot<W, M, FM, SoupEdges<NR, PR, ER, FR, AR, AcR>, C, N, EAS, E>,
        CompleteSubscriptionRoot<R, NS, AS, Auth, St, NR, PR, ER, FR, AR, AcR>,
    >;

/// GraphQL Soup schema type backed by shared query and realtime services.
pub type SharedSoupSchema<S, R, NS, AS, E, EAS, Auth, St, W, M, FM, C, N, NR, PR, ER, FR, AR, AcR> =
    SoupSchema<
        Arc<S>,
        Arc<R>,
        Arc<NS>,
        Arc<AS>,
        E,
        EAS,
        Auth,
        St,
        W,
        M,
        FM,
        C,
        N,
        NR,
        PR,
        ER,
        FR,
        AR,
        AcR,
    >;

/// GraphQL Soup schema type backed by the no-op services, used only for
/// SDL export or introspection.
pub type SchemaOnlySoupSchema = SoupSchema<
    NoOpSoupService,
    NoOpSoupRealtimeSubscriptionService,
    NoopWebSocketNotificationSubscriptionService,
    NoOpActivitySubscriptionService,
    NoOpEmailService,
    NoOpEntityAccessService,
    SchemaOnlyAuthorizationService,
    SchemaOnlyState,
    NoOpEntityPropertyWriter,
    UnavailableEntityMutationService,
    NoOpFavoriteMutationService,
    NoOpChannelActivityMutationService,
    NoOpNotificationMutationService,
    NoOpSoupNotificationEdgeReader,
    NoOpEntityPropertyReader,
    NoOpSoupEmailContentEdgeReader,
    NoOpEntityFavoriteEdgeReader,
    NoOpEntityPermissionEdgeReader,
    NoOpActivityReader,
>;

/// Authorization service used only to construct the GraphQL schema for SDL export.
pub type SchemaOnlyAuthorizationService = MacroAuthorizationServiceImpl<NoopMacroAuthJwtValidator>;

/// Axum-style state used only to construct the GraphQL schema for SDL export.
#[derive(Clone, Copy, Debug, Default)]
pub struct SchemaOnlyState;

impl FromRef<SchemaOnlyState> for EmailRouterState<NoOpEmailService> {
    fn from_ref(_state: &SchemaOnlyState) -> Self {
        EmailRouterState::new(NoOpEmailService)
    }
}

impl FromRef<SchemaOnlyState> for Arc<NoOpEntityAccessService> {
    fn from_ref(_state: &SchemaOnlyState) -> Self {
        Arc::new(NoOpEntityAccessService)
    }
}

impl FromRef<SchemaOnlyState> for MacroAuthorizationState<SchemaOnlyAuthorizationService> {
    fn from_ref(_state: &SchemaOnlyState) -> Self {
        let service = MacroAuthorizationServiceImpl::new(
            NoopMacroAuthJwtValidator,
            InternalAuthConfig {
                api_key: String::new(),
                default_user_id: None,
            },
            macro_authorization::NoBotAuthorizer,
            macro_authorization::NoUserApiKeyAuthorizer,
        );
        MacroAuthorizationState::new(Arc::new(service))
    }
}

/// Zero-sized marker tying the query objects to the adapter, authorization,
/// state, and reader generics without requiring values of those types.
type ServicesMarker<E, EAS, Auth, St, NR, PR, ER, FR, AR, AcR> =
    PhantomData<fn() -> (E, EAS, Auth, St, NR, PR, ER, FR, AR, AcR)>;

/// Root GraphQL query object for Soup.
pub struct SoupQueryRoot<S, E, EAS, Auth, St, NR, PR, ER, FR, AR, AcR> {
    /// Soup domain service used by user-scoped query resolvers.
    service: S,
    /// Associates the root with its adapter and reader types.
    _marker: ServicesMarker<E, EAS, Auth, St, NR, PR, ER, FR, AR, AcR>,
}

impl<S, E, EAS, Auth, St, NR, PR, ER, FR, AR, AcR>
    SoupQueryRoot<S, E, EAS, Auth, St, NR, PR, ER, FR, AR, AcR>
{
    /// Create a root GraphQL query object.
    pub fn new(service: S) -> Self {
        Self {
            service,
            _marker: PhantomData,
        }
    }
}

/// Root GraphQL subscription object for realtime Soup updates.
pub struct SoupSubscriptionRoot<R, Auth, St, NR, PR, ER, FR, AR, AcR> {
    /// Realtime Soup service used by user-scoped subscriptions.
    service: R,
    /// Associates the root with authorization, state, and edge reader types.
    #[allow(clippy::type_complexity)]
    _marker: PhantomData<fn() -> (Auth, St, NR, PR, ER, FR, AR, AcR)>,
}

impl<R, Auth, St, NR, PR, ER, FR, AR, AcR>
    SoupSubscriptionRoot<R, Auth, St, NR, PR, ER, FR, AR, AcR>
{
    /// Creates a root GraphQL subscription object.
    pub fn new(service: R) -> Self {
        Self {
            service,
            _marker: PhantomData,
        }
    }
}

/// The authenticated user (viewer). All user-scoped data hangs off this
/// object so clients (and their normalized caches) observe data ownership
/// structurally rather than implicitly through the session.
pub struct GraphqlUser<S, E, EAS, Auth, St, NR, PR, ER, FR, AR, AcR> {
    /// Soup domain service used by this user's resolvers.
    service: S,
    /// Associates the user object with its adapter and reader types.
    _marker: ServicesMarker<E, EAS, Auth, St, NR, PR, ER, FR, AR, AcR>,
    /// The [MacroUserIdStr] of the resolving user
    user_id: MacroUserIdStr<'static>,
}

/// Input for fetching one email thread by its canonical identifier.
#[derive(async_graphql::InputObject)]
pub struct EmailThreadInput {
    /// The canonical email thread identifier.
    thread_id: ID,
}

/// Input for fetching one Soup entity by its type and identifier.
#[derive(async_graphql::InputObject)]
pub struct SoupEntityInput {
    /// The Soup type of the entity.
    entity_type: GraphqlSoupEntityType,
    /// The entity identifier.
    entity_id: ID,
}

/// Build a GraphQL schema for Soup suitable for SDL export or introspection.
pub fn build_schema() -> SchemaOnlySoupSchema {
    build_schema_with_services(
        NoOpSoupService,
        NoOpSoupRealtimeSubscriptionService,
        NoopWebSocketNotificationSubscriptionService,
        NoOpActivitySubscriptionService,
    )
}

/// Build a GraphQL schema backed by a query service and no-op realtime service.
#[allow(clippy::type_complexity)]
pub fn build_schema_with_service<S, E, EAS, Auth, St, W, M, FM, C, N, NR, PR, ER, FR, AR, AcR>(
    service: S,
) -> SoupSchema<
    S,
    NoOpSoupRealtimeSubscriptionService,
    NoopWebSocketNotificationSubscriptionService,
    NoOpActivitySubscriptionService,
    E,
    EAS,
    Auth,
    St,
    W,
    M,
    FM,
    C,
    N,
    NR,
    PR,
    ER,
    FR,
    AR,
    AcR,
>
where
    S: SoupService + Clone,
    E: EmailService + EmailUserService + EmailSendService,
    EAS: EntityAccessService,
    Auth: MacroAuthorizationService,
    St: Clone + Send + Sync + 'static,
    EmailRouterState<E>: FromRef<St>,
    Arc<EAS>: FromRef<St>,
    MacroAuthorizationState<Auth>: FromRef<St>,
    W: EntityPropertyWriter,
    M: EntityMutationService,
    FM: FavoritesMutationService,
    C: ChannelActivityMutationService,
    N: NotificationMutationService,
    NR: SoupNotificationEdgeReader,
    PR: EntityPropertyReader,
    ER: SoupEmailEdgeReader,
    FR: EntityFavoriteEdgeReader + FavoriteQueryReader,
    AR: EntityPermissionEdgeReader,
    AcR: ActivityReader,
{
    build_schema_with_services(
        service,
        NoOpSoupRealtimeSubscriptionService,
        NoopWebSocketNotificationSubscriptionService,
        NoOpActivitySubscriptionService,
    )
}

/// Build a GraphQL schema backed by query and realtime Soup services.
#[allow(clippy::type_complexity)]
pub fn build_schema_with_services<
    S,
    R,
    NS,
    AS,
    E,
    EAS,
    Auth,
    St,
    W,
    M,
    FM,
    C,
    N,
    NR,
    PR,
    ER,
    FR,
    AR,
    AcR,
>(
    service: S,
    realtime_service: R,
    notification_subscription_service: NS,
    activity_subscription_service: AS,
) -> SoupSchema<S, R, NS, AS, E, EAS, Auth, St, W, M, FM, C, N, NR, PR, ER, FR, AR, AcR>
where
    S: SoupService + Clone,
    R: SoupRealtimeSubscriptionService + Clone,
    NS: WebSocketNotificationSubscriptionService<NotificationSubscriptionUpdate<NotifEvent>>
        + Clone,
    AS: ActivitySubscriptionService,
    E: EmailService + EmailUserService + EmailSendService,
    EAS: EntityAccessService,
    Auth: MacroAuthorizationService,
    St: Clone + Send + Sync + 'static,
    EmailRouterState<E>: FromRef<St>,
    Arc<EAS>: FromRef<St>,
    MacroAuthorizationState<Auth>: FromRef<St>,
    W: EntityPropertyWriter,
    M: EntityMutationService,
    FM: FavoritesMutationService,
    C: ChannelActivityMutationService,
    N: NotificationMutationService,
    NR: SoupNotificationEdgeReader,
    PR: EntityPropertyReader,
    ER: SoupEmailEdgeReader,
    FR: EntityFavoriteEdgeReader + FavoriteQueryReader,
    AR: EntityPermissionEdgeReader,
    AcR: ActivityReader,
{
    Schema::build(
        SoupQueryRoot::new(service),
        CompleteMutationRoot::<W, M, FM, SoupEdges<NR, PR, ER, FR, AR, AcR>, C, N, EAS, E>::new(),
        CompleteSubscriptionRoot(
            SoupSubscriptionRoot::new(realtime_service),
            NotificationSubscriptionRoot::new(notification_subscription_service),
            ActivitySubscriptionRoot::new(activity_subscription_service),
            WorkFeedSubscriptionRoot::default(),
            NotificationInboxSubscriptionRoot::default(),
            RegisteredWorkSubscriptionRoot::default(),
        ),
    )
    .finish()
}

/// Build a GraphQL schema backed by an `Arc`-shared query service.
#[allow(clippy::type_complexity)]
pub fn build_schema_from_arc<S, E, EAS, Auth, St, W, M, FM, C, N, NR, PR, ER, FR, AR, AcR>(
    service: Arc<S>,
) -> SoupSchema<
    Arc<S>,
    NoOpSoupRealtimeSubscriptionService,
    NoopWebSocketNotificationSubscriptionService,
    NoOpActivitySubscriptionService,
    E,
    EAS,
    Auth,
    St,
    W,
    M,
    FM,
    C,
    N,
    NR,
    PR,
    ER,
    FR,
    AR,
    AcR,
>
where
    S: SoupService,
    E: EmailService + EmailUserService + EmailSendService,
    EAS: EntityAccessService,
    Auth: MacroAuthorizationService,
    St: Clone + Send + Sync + 'static,
    EmailRouterState<E>: FromRef<St>,
    Arc<EAS>: FromRef<St>,
    MacroAuthorizationState<Auth>: FromRef<St>,
    W: EntityPropertyWriter,
    M: EntityMutationService,
    FM: FavoritesMutationService,
    C: ChannelActivityMutationService,
    N: NotificationMutationService,
    NR: SoupNotificationEdgeReader,
    PR: EntityPropertyReader,
    ER: SoupEmailEdgeReader,
    FR: EntityFavoriteEdgeReader + FavoriteQueryReader,
    AR: EntityPermissionEdgeReader,
    AcR: ActivityReader,
{
    build_schema_with_service(service)
}

/// Build a GraphQL schema backed by `Arc`-shared query and realtime services.
#[allow(clippy::type_complexity)]
pub fn build_schema_from_arcs<
    S,
    R,
    NS,
    AS,
    E,
    EAS,
    Auth,
    St,
    W,
    M,
    FM,
    C,
    N,
    NR,
    PR,
    ER,
    FR,
    AR,
    AcR,
>(
    service: Arc<S>,
    realtime_service: Arc<R>,
    notification_subscription_service: Arc<NS>,
    activity_subscription_service: Arc<AS>,
) -> SharedSoupSchema<S, R, NS, AS, E, EAS, Auth, St, W, M, FM, C, N, NR, PR, ER, FR, AR, AcR>
where
    S: SoupService,
    R: SoupRealtimeSubscriptionService,
    NS: WebSocketNotificationSubscriptionService<NotificationSubscriptionUpdate<NotifEvent>>,
    AS: ActivitySubscriptionService,
    E: EmailService + EmailUserService + EmailSendService,
    EAS: EntityAccessService,
    Auth: MacroAuthorizationService,
    St: Clone + Send + Sync + 'static,
    EmailRouterState<E>: FromRef<St>,
    Arc<EAS>: FromRef<St>,
    MacroAuthorizationState<Auth>: FromRef<St>,
    W: EntityPropertyWriter,
    M: EntityMutationService,
    FM: FavoritesMutationService,
    C: ChannelActivityMutationService,
    N: NotificationMutationService,
    NR: SoupNotificationEdgeReader,
    PR: EntityPropertyReader,
    ER: SoupEmailEdgeReader,
    FR: EntityFavoriteEdgeReader + FavoriteQueryReader,
    AR: EntityPermissionEdgeReader,
    AcR: ActivityReader,
{
    build_schema_with_services(
        service,
        realtime_service,
        notification_subscription_service,
        activity_subscription_service,
    )
}

/// Root entry point for the complete GraphQL API.
#[Object]
impl<S, E, EAS, Auth, St, NR, PR, ER, FR, AR, AcR>
    SoupQueryRoot<S, E, EAS, Auth, St, NR, PR, ER, FR, AR, AcR>
where
    S: SoupService + Clone,
    E: EmailService + EmailUserService + EmailSendService,
    EAS: EntityAccessService,
    Auth: MacroAuthorizationService,
    St: Clone + Send + Sync + 'static,
    EmailRouterState<E>: FromRef<St>,
    Arc<EAS>: FromRef<St>,
    MacroAuthorizationState<Auth>: FromRef<St>,
    NR: SoupNotificationEdgeReader,
    PR: EntityPropertyReader,
    ER: SoupEmailEdgeReader,
    FR: EntityFavoriteEdgeReader + FavoriteQueryReader,
    AR: EntityPermissionEdgeReader,
    AcR: ActivityReader,
{
    /// The authenticated user.
    async fn user(
        &self,
        ctx: &Context<'_>,
    ) -> async_graphql::Result<GraphqlUser<S, E, EAS, Auth, St, NR, PR, ER, FR, AR, AcR>> {
        let user_id = require_authorized_user::<Auth, St>(ctx).await?;

        Ok(GraphqlUser {
            service: self.service.clone(),
            _marker: PhantomData,
            user_id,
        })
    }
}

/// Root entry point for realtime Soup subscriptions.
#[Subscription]
impl<R, Auth, St, NR, PR, ER, FR, AR, AcR>
    SoupSubscriptionRoot<R, Auth, St, NR, PR, ER, FR, AR, AcR>
where
    R: SoupRealtimeSubscriptionService,
    Auth: MacroAuthorizationService,
    St: Clone + Send + Sync + 'static,
    MacroAuthorizationState<Auth>: FromRef<St>,
    NR: SoupNotificationEdgeReader,
    PR: EntityPropertyReader,
    ER: SoupEmailEdgeReader,
    FR: EntityFavoriteEdgeReader,
    AR: EntityPermissionEdgeReader,
    AcR: ActivityReader,
{
    /// Subscribe to realtime Soup updates for the authenticated user.
    async fn soup_updates(
        &self,
        ctx: &Context<'_>,
    ) -> async_graphql::Result<
        impl async_graphql::futures_util::Stream<
            Item = async_graphql::Result<Vec<SoupPatch<SoupEdges<NR, PR, ER, FR, AR, AcR>>>>,
        >,
    > {
        resolve_soup_updates::<R, Auth, St, SoupEdges<NR, PR, ER, FR, AR, AcR>>(&self.service, ctx)
            .await
    }

    /// Frames appended to one accessible agent session's log from now on,
    /// one run per flush, in log order. Each entry is the row `agentSession.log`
    /// serves, so a subscriber folds the same bytes a reader of the log does.
    /// The stream ends with an error when the subscriber falls behind: rows
    /// were missed, and the log must be refetched.
    async fn agent_session_log_appended(
        &self,
        ctx: &Context<'_>,
        session_id: ID,
    ) -> async_graphql::Result<
        impl async_graphql::futures_util::Stream<
            Item = async_graphql::Result<Vec<GraphqlAgentSessionLogEntry>>,
        > + 'static,
    > {
        let user_id = require_authorized_user::<Auth, St>(ctx).await?;
        let session_id = parse_id(session_id, "sessionId")?;
        // Access is what `agentSession` checks: a session the viewer cannot
        // read is one they cannot follow either.
        let accessible = resolve_soup_agent_session::<SoupEdges<NR, PR, ER, FR, AR, AcR>>(
            ctx, user_id, session_id,
        )
        .await?
        .is_some();
        if !accessible {
            return Err(async_graphql::Error::new("agent session not found"));
        }
        let subscriptions = ctx.data::<AgentSessionLogSubscriptions>()?;
        let mut receiver = subscriptions.subscribe(AgentSessionId::new_from_uuid(session_id));
        Ok(async_stream::stream! {
            while let Some(rows) = receiver.recv().await {
                yield rows
                    .into_iter()
                    .map(GraphqlAgentSessionLogEntry::try_from)
                    .collect::<Result<Vec<_>, _>>()
                    .map_err(|error| async_graphql::Error::new(error.to_string()));
            }
            // The viewer reopens and refetches; this is how often it has to.
            tracing::warn!(
                agent.session.id = %session_id,
                "closing an agent session log subscription that fell behind"
            );
            yield Err(async_graphql::Error::new(
                "agent session log subscription closed after falling behind",
            ));
        })
    }
}

/// The authenticated user and their user-scoped data.
#[Object(name = "GraphqlUser")]
impl<S, E, EAS, Auth, St, NR, PR, ER, FR, AR, AcR>
    GraphqlUser<S, E, EAS, Auth, St, NR, PR, ER, FR, AR, AcR>
where
    S: SoupService,
    E: EmailService + EmailUserService + EmailSendService,
    EAS: EntityAccessService,
    Auth: MacroAuthorizationService,
    St: Clone + Send + Sync + 'static,
    EmailRouterState<E>: FromRef<St>,
    Arc<EAS>: FromRef<St>,
    MacroAuthorizationState<Auth>: FromRef<St>,
    NR: SoupNotificationEdgeReader,
    PR: EntityPropertyReader,
    ER: SoupEmailEdgeReader,
    FR: EntityFavoriteEdgeReader + FavoriteQueryReader,
    AR: EntityPermissionEdgeReader,
    AcR: ActivityReader,
{
    /// Visible personal and effectively shared definitions, bounded after visibility checks.
    async fn saved_views(
        &self,
        ctx: &Context<'_>,
        kind: Option<String>,
        first: Option<i32>,
        after: Option<String>,
    ) -> async_graphql::Result<GraphqlSavedViewPage> {
        crate::saved_view::list(ctx, self.user_id.as_ref(), kind, first, after).await
    }

    /// An authorized definition or null when not found or not visible.
    async fn saved_view(
        &self,
        ctx: &Context<'_>,
        id: ID,
    ) -> async_graphql::Result<Option<GraphqlSavedView>> {
        crate::saved_view::get(ctx, self.user_id.as_ref(), id).await
    }

    /// Stable id of the authenticated user.
    async fn id(&self) -> async_graphql::ID {
        async_graphql::ID(self.user_id.to_string())
    }

    /// A page filtered and ordered across the entire authorized table.
    async fn database_view_rows(
        &self,
        ctx: &Context<'_>,
        database_id: ID,
        input: graphql_databases::DatabaseViewRowsInput,
    ) -> async_graphql::Result<
        graphql_databases::DatabaseViewRowsPage<SoupEdges<NR, PR, ER, FR, AR, AcR>>,
    > {
        graphql_databases::resolve_database_view_rows(ctx, database_id, input).await
    }

    /// One initiative accessible to the authenticated viewer.
    async fn initiative(
        &self,
        ctx: &Context<'_>,
        initiative_id: ID,
    ) -> async_graphql::Result<GraphqlSoupInitiative<SoupEdges<NR, PR, ER, FR, AR, AcR>>> {
        resolve_initiative(ctx, initiative_id).await
    }

    /// A permission-filtered page of task identifiers within an initiative.
    async fn initiative_tasks(
        &self,
        ctx: &Context<'_>,
        initiative_id: ID,
        input: Option<InitiativeTasksInput>,
    ) -> async_graphql::Result<GraphqlInitiativeTasksPage> {
        resolve_initiative_tasks(
            ctx,
            self.user_id.clone(),
            initiative_id,
            input.unwrap_or_default(),
        )
        .await
    }

    /// AI routines the authenticated user can access.
    async fn scheduled_actions(
        &self,
        ctx: &Context<'_>,
    ) -> async_graphql::Result<Vec<GraphqlScheduledAction>> {
        resolve_scheduled_actions(ctx, self.user_id.clone()).await
    }

    /// Authorized property definitions available to this viewer.
    async fn property_definitions(
        &self,
        ctx: &Context<'_>,
        scope: GraphqlPropertyDefinitionScope,
        for_entity_type: Option<graphql_common::GraphqlPropertyEntityType>,
    ) -> async_graphql::Result<Vec<GraphqlPropertyDefinition<PR>>> {
        load_property_definitions::<PR>(ctx, scope, for_entity_type).await
    }

    /// Select options available to the viewer for one property definition.
    async fn property_options(
        &self,
        ctx: &Context<'_>,
        property_definition_id: ID,
    ) -> async_graphql::Result<Vec<GraphqlPropertyOption>> {
        load_property_options::<PR>(ctx, property_definition_id).await
    }

    /// The authenticated user's favorites in manual order, optionally
    /// restricted by entity type and entity id.
    async fn favorites(
        &self,
        ctx: &Context<'_>,
        filter: Option<FavoritesFilterInput>,
    ) -> async_graphql::Result<Vec<GraphqlFavorite>> {
        resolve_favorites::<FR>(ctx, &self.user_id, filter.unwrap_or_default().into_model()?).await
    }

    /// Non-deleted projects the authenticated user can access, as a flat list.
    ///
    /// Clients build the Drive sidebar tree from `parentId`. Membership is
    /// gated by `entity_access` (not view history).
    async fn folders(
        &self,
        ctx: &Context<'_>,
    ) -> async_graphql::Result<Vec<GraphqlSoupProject<SoupEdges<NR, PR, ER, FR, AR, AcR>>>> {
        resolve_folders(ctx, &self.user_id).await
    }

    /// A page of activity, newest first: by default the authenticated
    /// user's own, delegated actions included; in the `TEAM` scope, their
    /// teammates' activity on entities shared with the user.
    async fn activity(
        &self,
        ctx: &Context<'_>,
        input: ActivityFeedInput,
    ) -> async_graphql::Result<GraphqlActivityPage> {
        resolve_activity_feed::<AcR>(ctx, &self.user_id, input).await
    }

    /// The newest activity on a database the authenticated user can view,
    /// newest first. Databases are not Soup items, so this stands in for the
    /// `activity` edge Soup entities carry.
    async fn database_activity(
        &self,
        ctx: &Context<'_>,
        database_id: ID,
        limit: Option<i32>,
    ) -> async_graphql::Result<Vec<GraphqlActivityEvent>> {
        let access = Arc::<EAS>::from_ref(ctx.data::<St>()?);
        resolve_database_activity::<AcR, EAS>(ctx, &*access, &self.user_id, database_id, limit)
            .await
    }

    /// The newest activity on a form the authenticated user can edit, newest
    /// first. Forms are not Soup items, so this stands in for the `activity`
    /// edge Soup entities carry.
    async fn form_activity(
        &self,
        ctx: &Context<'_>,
        form_id: ID,
        limit: Option<i32>,
    ) -> async_graphql::Result<Vec<GraphqlActivityEvent>> {
        let access = Arc::<EAS>::from_ref(ctx.data::<St>()?);
        resolve_form_activity::<AcR, EAS>(ctx, &*access, &self.user_id, form_id, limit).await
    }

    /// The authenticated user's activity over the trailing year, bucketed
    /// into local dates in the requested time zone.
    async fn activity_overview(
        &self,
        ctx: &Context<'_>,
        input: ActivityOverviewInput,
    ) -> async_graphql::Result<GraphqlActivityOverview> {
        resolve_activity_overview::<AcR>(ctx, &self.user_id, input).await
    }

    /// Authenticated user calendar fields supplied by `graphql_calendar`.
    #[graphql(flatten)]
    async fn calendar(&self) -> GraphqlCalendarQuery {
        GraphqlCalendarQuery::new(self.user_id.clone())
    }

    /// A page of the authenticated user's work feed, newest first: items
    /// with outstanding attention (notifications, inbox Signal email,
    /// reminders) and, in `WORK` mode, work the user recently did. Each
    /// item carries its notifications stacked for presentation.
    async fn work_feed(
        &self,
        ctx: &Context<'_>,
        input: Option<WorkFeedInput>,
    ) -> async_graphql::Result<GraphqlWorkFeedPage<SoupEdges<NR, PR, ER, FR, AR, AcR>>> {
        resolve_work_feed::<SoupEdges<NR, PR, ER, FR, AR, AcR>>(
            ctx,
            self.user_id.clone(),
            input.unwrap_or_default(),
        )
        .await
    }

    /// The agent sessions `accountIds` registered as their work that the
    /// authenticated user can view, newest first, at most 50 accounts.
    /// Registrations of sessions the user cannot view are completely hidden.
    async fn registered_work(
        &self,
        ctx: &Context<'_>,
        account_ids: Vec<ID>,
    ) -> async_graphql::Result<Vec<GraphqlRegisteredWork<SoupEdges<NR, PR, ER, FR, AR, AcR>>>> {
        resolve_registered_work::<SoupEdges<NR, PR, ER, FR, AR, AcR>>(
            ctx,
            self.user_id.clone(),
            account_ids,
        )
        .await
    }

    /// A page of the authenticated user's notifications inbox, newest group
    /// first: their pending notifications grouped by the entity they are
    /// filed under and cut into rows, one per conversation thread, channel
    /// top level, email thread, task, request or agent session.
    async fn notification_inbox(
        &self,
        ctx: &Context<'_>,
        input: Option<NotificationInboxInput>,
    ) -> async_graphql::Result<GraphqlNotificationInboxPage<SoupEdges<NR, PR, ER, FR, AR, AcR>>>
    {
        resolve_notification_inbox::<SoupEdges<NR, PR, ER, FR, AR, AcR>>(
            ctx,
            self.user_id.clone(),
            input.unwrap_or_default(),
        )
        .await
    }

    /// Authenticated user email catalog fields supplied by `graphql_email`.
    #[graphql(flatten)]
    async fn email(&self, ctx: &Context<'_>) -> async_graphql::Result<GraphqlEmailQuery<E>> {
        let state = ctx.data::<St>()?;
        let service = EmailRouterState::<E>::from_ref(state).service();
        Ok(GraphqlEmailQuery::new(service, self.user_id.clone()))
    }

    /// Inspect a queued send after reconnect or restart without resending it.
    async fn pending_email_sends(
        &self,
        ctx: &Context<'_>,
        after: Option<String>,
    ) -> async_graphql::Result<graphql_email::PendingEmailSends> {
        let state = ctx.data::<St>()?;
        let service = EmailRouterState::<E>::from_ref(state).service();
        graphql_email::load_pending_sends(service.as_ref(), self.user_id.clone(), after).await
    }

    /// Inspect a queued send after reconnect or restart without resending it.
    async fn email_send_attempt(
        &self,
        ctx: &Context<'_>,
        input: graphql_email::EmailSendAttemptInput,
    ) -> async_graphql::Result<Option<graphql_email::EmailSendAttemptPayload>> {
        let state = ctx.data::<St>()?;
        let service = EmailRouterState::<E>::from_ref(state).service();
        graphql_email::load_send_attempt(service.as_ref(), self.user_id.clone(), input).await
    }

    /// Fetch one accessible email thread by its canonical identifier.
    async fn email_thread(
        &self,
        ctx: &Context<'_>,
        input: EmailThreadInput,
    ) -> async_graphql::Result<Option<GraphqlSoupEmailThread<SoupEdges<NR, PR, ER, FR, AR, AcR>>>>
    {
        let thread_id = parse_id(input.thread_id, "threadId")?;
        let state = ctx.data::<St>()?;
        let service = EmailRouterState::<E>::from_ref(state).service();
        let thread_id = service
            .resolve_thread_read_id(self.user_id.clone(), thread_id)
            .await
            .map_err(|error| {
                tracing::error!(error = ?error, %thread_id, user_id = %self.user_id, "failed to resolve email thread");
                graphql_email::draft_mutation_error(&error)
            })?;
        resolve_soup_email_thread::<SoupEdges<NR, PR, ER, FR, AR, AcR>>(
            ctx,
            self.user_id.clone(),
            thread_id,
        )
        .await
    }

    /// The viewer's Focus: threads in their own inboxes worth their attention,
    /// newest first by latest message time in either direction, with mail in
    /// the last `days` days (default 30, at most 90). Each thread carries a
    /// `focus` field that explains why.
    async fn email_focus(
        &self,
        ctx: &Context<'_>,
        days: Option<i32>,
    ) -> async_graphql::Result<Vec<GraphqlSoupEmailThread<SoupEdges<NR, PR, ER, FR, AR, AcR>>>>
    {
        let days = u16::try_from(days.unwrap_or(30).clamp(1, 90)).unwrap_or(30);
        let thread_ids = load_email_focus_thread_ids(ctx, &self.user_id, days).await?;
        resolve_soup_email_threads::<SoupEdges<NR, PR, ER, FR, AR, AcR>>(
            ctx,
            self.user_id.clone(),
            thread_ids,
        )
        .await
    }

    /// Fetch one accessible agent session by id, with its protocol log
    /// reachable through `log`.
    async fn agent_session(
        &self,
        ctx: &Context<'_>,
        session_id: ID,
    ) -> async_graphql::Result<Option<GraphqlSoupAgentSession<SoupEdges<NR, PR, ER, FR, AR, AcR>>>>
    {
        let session_id = parse_id(session_id, "sessionId")?;
        resolve_soup_agent_session::<SoupEdges<NR, PR, ER, FR, AR, AcR>>(
            ctx,
            self.user_id.clone(),
            session_id,
        )
        .await
    }

    /// Fetch one accessible Soup entity, read from the primary so an entity
    /// opened right after it is created or edited reflects that write.
    async fn soup_entity(
        &self,
        ctx: &Context<'_>,
        input: SoupEntityInput,
    ) -> async_graphql::Result<Option<GraphqlSoupEntity<SoupEdges<NR, PR, ER, FR, AR, AcR>>>> {
        let entity_id = parse_id(input.entity_id, "entityId")?;
        let entity = input
            .entity_type
            .into_model()
            .with_entity_string(entity_id.to_string());
        resolve_soup_entity::<SoupEdges<NR, PR, ER, FR, AR, AcR>>(ctx, self.user_id.clone(), entity)
            .await
    }

    /// Fetch Soup items nested into grouping bins.
    async fn group_soup(
        &self,
        ctx: &Context<'_>,
        input: GroupedSoupInput,
    ) -> async_graphql::Result<GroupedSoup<SoupEdges<NR, PR, ER, FR, AR, AcR>>> {
        resolve_grouped_soup::<S, Auth, St, SoupEdges<NR, PR, ER, FR, AR, AcR>>(
            &self.service,
            ctx,
            input,
        )
        .await
    }

    /// Fetch a page of Soup items using the existing Soup filter AST format.
    async fn soup(
        &self,
        ctx: &Context<'_>,
        input: SoupInput,
    ) -> async_graphql::Result<SoupPage<SoupEdges<NR, PR, ER, FR, AR, AcR>>> {
        resolve_soup::<S, E, EAS, Auth, St, SoupEdges<NR, PR, ER, FR, AR, AcR>>(
            &self.service,
            ctx,
            input,
        )
        .await
    }
}