Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat: ai consent flow (#1459)
Peter Chinman8c68d4f33757
diff --git a/js/app/packages/core/component/AI/component/input/useAiDataConsent.tsx b/js/app/packages/core/component/AI/component/input/useAiDataConsent.tsxnew file mode 100644index 0000000000..ae2af1b010--- /dev/null+++ b/js/app/packages/core/component/AI/component/input/useAiDataConsent.tsx@@ -0,0 +1,88 @@+import { Dialog } from '@kobalte/core/dialog';+import { useAiDataConsent } from '@core/context/user';+import { authServiceClient } from '@service-auth/client';+import { invalidateUserInfo } from '@queries/auth/user-info';+import { DeprecatedButton } from '@core/component/FormControls/DeprecatedButton';+import { DeprecatedIconButton } from '@core/component/DeprecatedIconButton';+import { DialogWrapper } from '@core/component/DialogWrapper';+import { ClippedPanel } from '@core/component/ClippedPanel';+import { beveledCorners } from '@block-theme/signals/themeSignals';+import CloseIcon from '@icon/regular/x.svg';+import { createSignal } from 'solid-js';++export function useAiDataConsentGate() {+ const hasConsent = useAiDataConsent();+ const [open, setOpen] = createSignal(false);++ let storedCallback: (() => void) | undefined;++ function requestConsent(onAccept: () => void) {+ storedCallback = onAccept;+ setOpen(true);+ }++ async function grantConsent() {+ await authServiceClient.patchAiConsent({ aiDataConsent: true });+ await invalidateUserInfo();+ setOpen(false);+ const cb = storedCallback;+ storedCallback = undefined;+ cb?.();+ }++ function denyConsent() {+ setOpen(false);+ storedCallback = undefined;+ }++ function ConsentDialog() {+ return (+ <Dialog open={open()} onOpenChange={(isOpen) => !isOpen && denyConsent()}>+ <Dialog.Portal>+ <Dialog.Overlay class="fixed inset-0 z-modal-overlay bg-transparent" />+ <DialogWrapper width="480px">+ <Dialog.Content class="text-ink max-h-[100%] overflow-y-auto">+ <ClippedPanel tl={!beveledCorners()} active>+ <div class="flex flex-row items-center justify-between px-2 h-[40px] gap-2 border-b-1 border-b-edge-muted">+ <div class="flex flex-row items-center gap-2">+ <Dialog.CloseButton>+ <DeprecatedIconButton+ tooltip={{ label: 'Close' }}+ icon={CloseIcon}+ iconSize={16}+ theme="clear"+ size="sm"+ />+ </Dialog.CloseButton>+ <Dialog.Title>AI Data Sharing</Dialog.Title>+ </div>+ </div>+ <div class="p-3">+ <p class="text-ink-muted text-sm">+ AI Chat sends your messages to Anthropic for processing and+ may access your files in Macro to provide relevant+ responses. Your data is not retained or used for training.+ </p>+ <div class="flex justify-end mt-4 gap-2">+ <DeprecatedButton theme="secondary" onClick={denyConsent}>+ Cancel+ </DeprecatedButton>+ <DeprecatedButton theme="primary" onClick={grantConsent}>+ Accept+ </DeprecatedButton>+ </div>+ </div>+ </ClippedPanel>+ </Dialog.Content>+ </DialogWrapper>+ </Dialog.Portal>+ </Dialog>+ );+ }++ return {+ hasConsent,+ requestConsent,+ ConsentDialog,+ };+}diff --git a/js/app/packages/core/component/AI/component/input/useChatInput.tsx b/js/app/packages/core/component/AI/component/input/useChatInput.tsxindex a2a2f4f1a5..84fd0ceb84 100644--- a/js/app/packages/core/component/AI/component/input/useChatInput.tsx+++ b/js/app/packages/core/component/AI/component/input/useChatInput.tsx@@ -27,6 +27,8 @@ import { ChatAttachMenu } from './ChatAttachMenu';import type { Source } from './ToolsetSelector';import type { UseChatMarkdown } from './useChatMarkdownArea';import { cn } from '@ui/utils/classname';+import { isNativeMobilePlatform } from '@core/mobile/isNativeMobilePlatform';+import { useAiDataConsentGate } from './useAiDataConsent';const { track, TrackingEvents } = withAnalytics();@@ -53,6 +55,7 @@ export function ChatInput(props: ChatInputComponentProps) {let containerRef!: HTMLDivElement;const toolsetSignal = createSignal<ToolSet>({ type: 'all' });+ const { hasConsent, requestConsent, ConsentDialog } = useAiDataConsentGate();const [source] = createSignal<Source>('everything');const [showAttachMenu, setShowAttachMenu] = createSignal(false);@@ -89,6 +92,11 @@ export function ChatInput(props: ChatInputComponentProps) {const sendMessage = createCallback(async (modelOverride?: Model) => {if (!canSendMessage()) return;+ if (isNativeMobilePlatform() && !hasConsent()) {+ requestConsent(() => sendMessage(modelOverride));+ return;+ }+const request = await buildChatSendRequest({chatId: chatId(),userRequest: props.markdown.markdownText(),@@ -283,6 +291,7 @@ export function ChatInput(props: ChatInputComponentProps) {<RightControls /></div></div>+ <ConsentDialog /></div>);}diff --git a/js/app/packages/core/context/user.ts b/js/app/packages/core/context/user.tsindex 743f72cc3b..4f1de4491d 100644--- a/js/app/packages/core/context/user.ts+++ b/js/app/packages/core/context/user.ts@@ -31,6 +31,7 @@ type UserContextValue = {group: Accessor<string | null | undefined>;hasChromeExt: Accessor<boolean | undefined>;hasTrialed: Accessor<boolean | undefined>;+ aiDataConsent: Accessor<boolean>;};export const [UserContextProvider, useUserContext] =@@ -60,6 +61,7 @@ export const [UserContextProvider, useUserContext] =const group = createMemo(() => userInfo()?.group);const hasChromeExt = createMemo(() => userInfo()?.hasChromeExt);const hasTrialed = createMemo(() => userInfo()?.hasTrialed);+ const aiDataConsent = createMemo(() => userInfo()?.aiDataConsent ?? false);return {userInfo,@@ -74,6 +76,7 @@ export const [UserContextProvider, useUserContext] =group,hasChromeExt,hasTrialed,+ aiDataConsent,};});@@ -121,3 +124,7 @@ export function useHasTrialed() {export function useUserInfo() {return useUserContext().userInfo;}++export function useAiDataConsent() {+ return useUserContext().aiDataConsent;+}diff --git a/js/app/packages/service-clients/service-auth/client.ts b/js/app/packages/service-clients/service-auth/client.tsindex 604ede0448..d3649b3aa5 100644--- a/js/app/packages/service-clients/service-auth/client.ts+++ b/js/app/packages/service-clients/service-auth/client.ts@@ -322,6 +322,16 @@ export const authServiceClient = {);},+ async patchAiConsent(args: { aiDataConsent: boolean }) {+ return mapOk(+ await fetchWithAuth<EmptyResponse>(`${authHost}/user/ai_consent`, {+ method: 'PATCH',+ body: JSON.stringify(args),+ }),+ (result) => result+ );+ },+// HTTP methods (migrated from RPC)async getLegacyUserPermissions() {const result = await fetchWithAuth<GetLegacyUserPermissionsResponse>(@@ -341,6 +351,7 @@ export const authServiceClient = {authenticated: !!data.userId,userId: data.userId,hasTrialed: data.hasTrialed,+ aiDataConsent: data.aiDataConsent,}));},diff --git a/js/app/packages/service-clients/service-auth/generated/schemas/getLegacyUserPermissionsResponse.ts b/js/app/packages/service-clients/service-auth/generated/schemas/getLegacyUserPermissionsResponse.tsindex 59e384e486..6d99ebba2e 100644--- a/js/app/packages/service-clients/service-auth/generated/schemas/getLegacyUserPermissionsResponse.ts+++ b/js/app/packages/service-clients/service-auth/generated/schemas/getLegacyUserPermissionsResponse.ts@@ -8,6 +8,8 @@ import type { GetLegacyUserPermissionsResponseGroup } from './getLegacyUserPermiimport type { GetLegacyUserPermissionsResponseName } from './getLegacyUserPermissionsResponseName';export interface GetLegacyUserPermissionsResponse {+ /** Whether the user has consented to AI data sharing */+ aiDataConsent: boolean;/** The user's email */email: string;group?: GetLegacyUserPermissionsResponseGroup;diff --git a/js/app/packages/service-clients/service-auth/openapi.json b/js/app/packages/service-clients/service-auth/openapi.jsonindex 555d1de184..e26d1a60d6 100644--- a/js/app/packages/service-clients/service-auth/openapi.json+++ b/js/app/packages/service-clients/service-auth/openapi.json@@ -2955,9 +2955,14 @@"licenseStatus","tutorialComplete","hasChromeExt",- "hasTrialed"+ "hasTrialed",+ "aiDataConsent"],"properties": {+ "aiDataConsent": {+ "type": "boolean",+ "description": "Whether the user has consented to AI data sharing"+ },"email": {"type": "string","description": "The user's email"diff --git a/rust/cloud-storage/authentication_service/src/api/user/get_legacy_user_permissions.rs b/rust/cloud-storage/authentication_service/src/api/user/get_legacy_user_permissions.rsindex 63b696b878..cded46ddc5 100644--- a/rust/cloud-storage/authentication_service/src/api/user/get_legacy_user_permissions.rs+++ b/rust/cloud-storage/authentication_service/src/api/user/get_legacy_user_permissions.rs@@ -36,6 +36,8 @@ pub struct GetLegacyUserPermissionsResponse {has_chrome_ext: bool,/// Whether the user has trialed through stripehas_trialed: bool,+ /// Whether the user has consented to AI data sharing+ ai_data_consent: bool,}#[derive(serde::Serialize, Debug, utoipa::ToSchema)]@@ -158,5 +160,6 @@ pub async fn handler(},has_chrome_ext: legacy_user_info.has_chrome_ext,has_trialed,+ ai_data_consent: legacy_user_info.ai_data_consent,})}diff --git a/rust/cloud-storage/authentication_service/src/api/user/mod.rs b/rust/cloud-storage/authentication_service/src/api/user/mod.rsindex f5956c19ef..df88f3b691 100644--- a/rust/cloud-storage/authentication_service/src/api/user/mod.rs+++ b/rust/cloud-storage/authentication_service/src/api/user/mod.rs@@ -17,6 +17,7 @@ pub(in crate::api) mod get_user_info;pub(in crate::api) mod get_user_link_exists;pub(in crate::api) mod get_user_organization;pub(in crate::api) mod get_user_quota;+pub(in crate::api) mod patch_ai_consent;pub(in crate::api) mod patch_tutorial;pub(in crate::api) mod patch_user_group;pub(in crate::api) mod patch_user_onboarding;@@ -51,6 +52,7 @@ fn router_with_auth(state: ApiContext, jwt_args: JwtValidationArgs) -> Router<Ap).route("/link_exists", get(get_user_link_exists::handler)).route("/tutorial", patch(patch_tutorial::handler))+ .route("/ai_consent", patch(patch_ai_consent::handler)).route("/quota",get(get_user_quota::handler).layer(axum::middleware::from_fn_with_state(diff --git a/rust/cloud-storage/authentication_service/src/api/user/patch_ai_consent.rs b/rust/cloud-storage/authentication_service/src/api/user/patch_ai_consent.rsnew file mode 100644index 0000000000..975f62aa8c--- /dev/null+++ b/rust/cloud-storage/authentication_service/src/api/user/patch_ai_consent.rs@@ -0,0 +1,90 @@+use axum::{+ Extension, Json,+ extract::{self, State},+ http::StatusCode,+ response::{IntoResponse, Response},+};+use macro_user_id::user_id::MacroUserId;++use crate::api::context::ApiContext;++use model::{+ response::{EmptyResponse, ErrorResponse},+ user::UserContext,+};+use utoipa::ToSchema;++#[derive(Default, Debug, serde::Serialize, serde::Deserialize, ToSchema)]+#[serde(rename_all = "camelCase")]+pub struct PatchAiConsentRequest {+ /// Whether the user has consented to AI data sharing+ pub ai_data_consent: bool,+}++#[derive(thiserror::Error, Debug)]+pub enum PatchAiConsentError {+ #[error("User not found")]+ UserNotFound,+ #[error("unable to parse user id")]+ InvalidMacroUserId,+ #[error("Internal error")]+ InternalError(#[from] anyhow::Error),+}++impl IntoResponse for PatchAiConsentError {+ fn into_response(self) -> Response {+ match self {+ PatchAiConsentError::UserNotFound => (+ StatusCode::NOT_FOUND,+ Json(ErrorResponse {+ message: "user not found",+ }),+ ),+ PatchAiConsentError::InvalidMacroUserId => (+ StatusCode::BAD_REQUEST,+ Json(ErrorResponse {+ message: "invalid user id",+ }),+ ),+ PatchAiConsentError::InternalError(_) => (+ StatusCode::INTERNAL_SERVER_ERROR,+ Json(ErrorResponse {+ message: "internal error",+ }),+ ),+ }+ .into_response()+ }+}++/// Updates the user's AI data consent flag.+#[utoipa::path(+ patch,+ path = "/user/ai_consent",+ operation_id = "patch_ai_consent",+ responses(+ (status = 200, body=EmptyResponse),+ (status = 401, body=String),+ (status = 404, body=String),+ (status = 500, body=ErrorResponse),+ )+ )]+#[tracing::instrument(skip(ctx, user_context), err, fields(user_id=user_context.user_id))]+pub async fn handler(+ State(ctx): State<ApiContext>,+ user_context: Extension<UserContext>,+ extract::Json(req): extract::Json<PatchAiConsentRequest>,+) -> Result<Json<EmptyResponse>, PatchAiConsentError> {+ let user_id = MacroUserId::parse_from_str(&user_context.user_id)+ .map_err(|_| PatchAiConsentError::InvalidMacroUserId)?+ .lowercase();++ macro_db_client::user::patch::patch_ai_consent(&ctx.db, &user_id, req.ai_data_consent)+ .await+ .map_err(|e| match e.to_string().as_str() {+ "user not found" => PatchAiConsentError::UserNotFound,+ _ => PatchAiConsentError::InternalError(e),+ })?;++ Ok(Json(EmptyResponse::default()))+}diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-07ee049852183a95006bcc4c4add942c0331f2c229da351065f2e77111ec647f.json b/rust/cloud-storage/macro_db_client/.sqlx/query-3ebdcbdf2d5d47adc0438e324ff6f6ce9c4a9d638a72f159f319a6f51ebcf4b2.jsonsimilarity index 79%rename from rust/cloud-storage/macro_db_client/.sqlx/query-07ee049852183a95006bcc4c4add942c0331f2c229da351065f2e77111ec647f.jsonrename to rust/cloud-storage/macro_db_client/.sqlx/query-3ebdcbdf2d5d47adc0438e324ff6f6ce9c4a9d638a72f159f319a6f51ebcf4b2.jsonindex de80e474e7..a2bd080005 100644--- a/rust/cloud-storage/macro_db_client/.sqlx/query-07ee049852183a95006bcc4c4add942c0331f2c229da351065f2e77111ec647f.json+++ b/rust/cloud-storage/macro_db_client/.sqlx/query-3ebdcbdf2d5d47adc0438e324ff6f6ce9c4a9d638a72f159f319a6f51ebcf4b2.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT\n \"id\" as \"user_id\",\n \"email\" as \"email\",\n \"stripeCustomerId\" as \"stripe_customer_id?\",\n \"name\" as name,\n \"tutorialComplete\" as tutorial_complete,\n \"group\" as \"group?\",\n \"hasChromeExt\" as has_chrome_ext\n FROM \"User\"\n WHERE \"id\" = $1\n ",+ "query": "\n SELECT\n \"id\" as \"user_id\",\n \"email\" as \"email\",\n \"stripeCustomerId\" as \"stripe_customer_id?\",\n \"name\" as name,\n \"tutorialComplete\" as tutorial_complete,\n \"group\" as \"group?\",\n \"hasChromeExt\" as has_chrome_ext,\n \"aiDataConsent\" as ai_data_consent\n FROM \"User\"\n WHERE \"id\" = $1\n ","describe": {"columns": [{@@ -37,6 +37,11 @@"ordinal": 6,"name": "has_chrome_ext","type_info": "Bool"+ },+ {+ "ordinal": 7,+ "name": "ai_data_consent",+ "type_info": "Bool"}],"parameters": {@@ -51,8 +56,9 @@true,false,true,+ false,false]},- "hash": "07ee049852183a95006bcc4c4add942c0331f2c229da351065f2e77111ec647f"+ "hash": "3ebdcbdf2d5d47adc0438e324ff6f6ce9c4a9d638a72f159f319a6f51ebcf4b2"}diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-47f0213791a57c90d28af2015b1de283865e6bbf5776a9f482a5d21568c14d3e.json b/rust/cloud-storage/macro_db_client/.sqlx/query-47f0213791a57c90d28af2015b1de283865e6bbf5776a9f482a5d21568c14d3e.jsonnew file mode 100644index 0000000000..1d742c4cac--- /dev/null+++ b/rust/cloud-storage/macro_db_client/.sqlx/query-47f0213791a57c90d28af2015b1de283865e6bbf5776a9f482a5d21568c14d3e.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE \"User\"\n SET \"aiDataConsent\" = $1\n WHERE id = $2\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Bool",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "47f0213791a57c90d28af2015b1de283865e6bbf5776a9f482a5d21568c14d3e"+}diff --git a/rust/cloud-storage/macro_db_client/migrations/20260210120000_add_ai_data_consent.sql b/rust/cloud-storage/macro_db_client/migrations/20260210120000_add_ai_data_consent.sqlnew file mode 100644index 0000000000..f10fc2cca6--- /dev/null+++ b/rust/cloud-storage/macro_db_client/migrations/20260210120000_add_ai_data_consent.sql@@ -0,0 +1 @@+ALTER TABLE "User" ADD COLUMN "aiDataConsent" BOOLEAN NOT NULL DEFAULT false;diff --git a/rust/cloud-storage/macro_db_client/src/user/get/get_legacy_user_info.rs b/rust/cloud-storage/macro_db_client/src/user/get/get_legacy_user_info.rsindex 9fe797d873..9fab16b6bc 100644--- a/rust/cloud-storage/macro_db_client/src/user/get/get_legacy_user_info.rs+++ b/rust/cloud-storage/macro_db_client/src/user/get/get_legacy_user_info.rs@@ -9,6 +9,7 @@ pub struct LegacyUserInfo {pub tutorial_complete: bool,pub group: Option<String>,pub has_chrome_ext: bool,+ pub ai_data_consent: bool,}pub async fn get_legacy_user_info(@@ -25,7 +26,8 @@ pub async fn get_legacy_user_info("name" as name,"tutorialComplete" as tutorial_complete,"group" as "group?",- "hasChromeExt" as has_chrome_ext+ "hasChromeExt" as has_chrome_ext,+ "aiDataConsent" as ai_data_consentFROM "User"WHERE "id" = $1"#,diff --git a/rust/cloud-storage/macro_db_client/src/user/patch/mod.rs b/rust/cloud-storage/macro_db_client/src/user/patch/mod.rsindex f346f1d2de..ac5fe0aaaa 100644--- a/rust/cloud-storage/macro_db_client/src/user/patch/mod.rs+++ b/rust/cloud-storage/macro_db_client/src/user/patch/mod.rs@@ -74,6 +74,32 @@ pub async fn patch_user_tutorial(Ok(())}+/// Updates the user's AI data consent flag.+#[tracing::instrument(skip(db), err)]+pub async fn patch_ai_consent(+ db: &sqlx::Pool<sqlx::Postgres>,+ user_id: &MacroUserId<Lowercase<'_>>,+ ai_data_consent: bool,+) -> anyhow::Result<()> {+ let result = sqlx::query!(+ r#"+ UPDATE "User"+ SET "aiDataConsent" = $1+ WHERE id = $2+ "#,+ ai_data_consent,+ user_id.as_ref(),+ )+ .execute(db)+ .await?;++ if result.rows_affected() == 0 {+ anyhow::bail!("user not found");+ }++ Ok(())+}+#[derive(Debug, Clone)]pub struct UserOnboarding<'a> {pub first_name: &'a str,