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.

feat(onboarding): require work-domain teams and send a domain notice (#8811)

Jacob Beckerman5b3877e39712
diff --git a/.sqlx/query-de215a50bb11bfc6aba4c44cc351073edac7e411ff471ddda100fceac1b3142d.json b/.sqlx/query-216722678439bc75d580745e8c5c229c60c8e88934e8725bc1fb61c0321e261e.json
similarity index 61%
rename from .sqlx/query-de215a50bb11bfc6aba4c44cc351073edac7e411ff471ddda100fceac1b3142d.json
rename to .sqlx/query-216722678439bc75d580745e8c5c229c60c8e88934e8725bc1fb61c0321e261e.json
index 790c3308ee..5284ea2088 100644
--- a/.sqlx/query-de215a50bb11bfc6aba4c44cc351073edac7e411ff471ddda100fceac1b3142d.json
+++ b/.sqlx/query-216722678439bc75d580745e8c5c229c60c8e88934e8725bc1fb61c0321e261e.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n INSERT INTO team (id, name, slug, owner_id, seat_count, subscription_id, paying)\n VALUES ($1, $2, $3, $4, 1, $5, $6)\n RETURNING id, name, slug, owner_id, enterprise, allow_non_admin_invites,\n default_link_share as \"default_link_share: LinkShare\",\n language as \"language: Language\"\n ",
+ "query": "\n INSERT INTO team (\n id, name, slug, owner_id, seat_count, subscription_id, paying, auto_join_domain\n )\n VALUES ($1, $2, $3, $4, 1, $5, $6, $7)\n RETURNING id, name, slug, owner_id, enterprise, allow_non_admin_invites,\n auto_join_domain,\n default_link_share as \"default_link_share: LinkShare\",\n language as \"language: Language\"\n ",
"describe": {
"columns": [
{
@@ -35,11 +35,16 @@
},
{
"ordinal": 6,
- "name": "default_link_share: LinkShare",
+ "name": "auto_join_domain",
"type_info": "Text"
},
{
"ordinal": 7,
+ "name": "default_link_share: LinkShare",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 8,
"name": "language: Language",
"type_info": "Text"
}
@@ -51,7 +56,8 @@
"Varchar",
"Text",
"Text",
- "Bool"
+ "Bool",
+ "Text"
]
},
"nullable": [
@@ -62,8 +68,9 @@
false,
false,
true,
+ true,
true
]
},
- "hash": "de215a50bb11bfc6aba4c44cc351073edac7e411ff471ddda100fceac1b3142d"
+ "hash": "216722678439bc75d580745e8c5c229c60c8e88934e8725bc1fb61c0321e261e"
}
diff --git a/.sqlx/query-a8080ff3d4a2ec860380f02d239a7a671c0afe3c37aacc59ccc6408ee0f56080.json b/.sqlx/query-4cad27014c25da5f4f2b65889d82346c6ddd0a48914c27791790357a4c25e8ee.json
similarity index 55%
rename from .sqlx/query-a8080ff3d4a2ec860380f02d239a7a671c0afe3c37aacc59ccc6408ee0f56080.json
rename to .sqlx/query-4cad27014c25da5f4f2b65889d82346c6ddd0a48914c27791790357a4c25e8ee.json
index a8276feb05..9121191688 100644
--- a/.sqlx/query-a8080ff3d4a2ec860380f02d239a7a671c0afe3c37aacc59ccc6408ee0f56080.json
+++ b/.sqlx/query-4cad27014c25da5f4f2b65889d82346c6ddd0a48914c27791790357a4c25e8ee.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n WITH claimed AS (\n INSERT INTO team_joined_macro_email (team_id, email)\n SELECT t.id, c.email\n FROM team t\n CROSS JOIN UNNEST($2::text[], $3::text[]) AS c(email, user_id)\n WHERE t.id = $1\n AND t.auto_join_domain IS NOT NULL\n AND split_part(c.email, '@', 2) = t.auto_join_domain\n AND NOT EXISTS (\n SELECT 1 FROM team_user tu\n WHERE tu.team_id = t.id AND tu.user_id = c.user_id\n )\n AND NOT EXISTS (\n SELECT 1 FROM team_invite ti\n WHERE ti.team_id = t.id AND ti.email = c.email\n )\n ON CONFLICT (team_id, email) DO NOTHING\n RETURNING email\n )\n SELECT claimed.email AS \"email!\", t.name AS \"team_name!\"\n FROM claimed\n JOIN team t ON t.id = $1\n ",
+ "query": "\n WITH claimed AS (\n INSERT INTO team_joined_macro_email (team_id, email)\n SELECT t.id, c.email\n FROM team t\n CROSS JOIN UNNEST($2::text[], $3::text[]) AS c(email, user_id)\n WHERE t.id = $1\n AND t.auto_join_domain IS NOT NULL\n AND split_part(c.email, '@', 2) = t.auto_join_domain\n AND NOT EXISTS (\n SELECT 1 FROM team_user tu\n WHERE tu.team_id = t.id AND tu.user_id = c.user_id\n )\n AND NOT EXISTS (\n SELECT 1 FROM team_invite ti\n WHERE ti.team_id = t.id AND ti.email = c.email\n )\n AND NOT EXISTS (\n SELECT 1 FROM \"User\" u WHERE lower(u.email) = lower(c.email)\n )\n AND NOT EXISTS (\n SELECT 1 FROM team_joined_macro_email e\n WHERE e.team_id = t.id AND e.email = c.email\n )\n ORDER BY c.email\n LIMIT GREATEST(\n $4::bigint\n - (SELECT count(*) FROM team_joined_macro_email e WHERE e.team_id = $1),\n 0\n )\n ON CONFLICT (team_id, email) DO NOTHING\n RETURNING email\n )\n SELECT claimed.email AS \"email!\", t.name AS \"team_name!\"\n FROM claimed\n JOIN team t ON t.id = $1\n ",
"describe": {
"columns": [
{
@@ -18,7 +18,8 @@
"Left": [
"Uuid",
"TextArray",
- "TextArray"
+ "TextArray",
+ "Int8"
]
},
"nullable": [
@@ -26,5 +27,5 @@
false
]
},
- "hash": "a8080ff3d4a2ec860380f02d239a7a671c0afe3c37aacc59ccc6408ee0f56080"
+ "hash": "4cad27014c25da5f4f2b65889d82346c6ddd0a48914c27791790357a4c25e8ee"
}
diff --git a/.sqlx/query-fcc9ce38182386213a11fa16aebfaebdd4f4675585e7319e229c230f3cc95ec6.json b/.sqlx/query-fcc9ce38182386213a11fa16aebfaebdd4f4675585e7319e229c230f3cc95ec6.json
new file mode 100644
index 0000000000..d79c77d1d1
--- /dev/null
+++ b/.sqlx/query-fcc9ce38182386213a11fa16aebfaebdd4f4675585e7319e229c230f3cc95ec6.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT id FROM team WHERE id = $1 FOR UPDATE",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "fcc9ce38182386213a11fa16aebfaebdd4f4675585e7319e229c230f3cc95ec6"
+}
diff --git a/Cargo.lock b/Cargo.lock
index 490b329df9..7b665d3497 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -18601,7 +18601,6 @@ dependencies = [
"macro_user_id",
"mention_utils",
"messages",
- "notification",
"reqwest 0.13.4",
"rootcause",
"serde",
@@ -18609,7 +18608,6 @@ dependencies = [
"sha2 0.10.9",
"slack_integration",
"sqlx",
- "teams",
"tokio",
"tokio-util",
"tracing",
diff --git a/apps/web/src/features/onboarding/browser-test/onboarding.browser.e2e.ts b/apps/web/src/features/onboarding/browser-test/onboarding.browser.e2e.ts
index 0e8bd7422e..48103295a4 100644
--- a/apps/web/src/features/onboarding/browser-test/onboarding.browser.e2e.ts
+++ b/apps/web/src/features/onboarding/browser-test/onboarding.browser.e2e.ts
@@ -84,7 +84,8 @@ test('a deep link survives the inbox OAuth round-trip', async ({ page }) => {
await page.getByRole('button', { name: 'Continue' }).click();
await page.getByRole('button', { name: 'Skip for now' }).click();
await page.getByRole('button', { name: 'Continue' }).click();
- await page.getByRole('button', { name: 'Skip for now' }).click();
+ // A work domain must create its team; there is no Skip on this step.
+ await page.getByRole('button', { name: 'Create team & invite 2' }).click();
await page.getByRole('button', { name: 'Continue with Free' }).last().click();
await expectLanded(page, 'Entered Macro at /channel/launch');
diff --git a/apps/web/src/features/onboarding/context/onboarding-context.tsx b/apps/web/src/features/onboarding/context/onboarding-context.tsx
index 40acf3b259..3462b92e4b 100644
--- a/apps/web/src/features/onboarding/context/onboarding-context.tsx
+++ b/apps/web/src/features/onboarding/context/onboarding-context.tsx
@@ -115,7 +115,13 @@ export type OnboardingContext = {
configureGithubRepositories(): void;
createTeamDirectory(): TeamDirectorySource;
/** Rejects on failure; the capability reports its own errors. */
- createTeam(input: { name: string; invites: string[] }): Promise<void>;
+ /** `allowDomainJoin` lets people on the owner's work domain join, and
+ * tells the owner's same-domain contacts the team exists. */
+ createTeam(input: {
+ name: string;
+ invites: string[];
+ allowDomainJoin: boolean;
+ }): Promise<void>;
/** Rejects on failure; the capability reports its own errors. */
joinTeam(inviteId: string): Promise<void>;
/** The invite promotion the account holds; null when it has none. */
diff --git a/apps/web/src/features/onboarding/create-app-onboarding-context.ts b/apps/web/src/features/onboarding/create-app-onboarding-context.ts
index 29ca2b2919..19f2f7493b 100644
--- a/apps/web/src/features/onboarding/create-app-onboarding-context.ts
+++ b/apps/web/src/features/onboarding/create-app-onboarding-context.ts
@@ -217,10 +217,11 @@ export function createAppOnboardingContext(): OnboardingContext {
},
};
},
- createTeam: async ({ name, invites }) => {
+ createTeam: async ({ name, invites, allowDomainJoin }) => {
await createTeam.mutateAsync({
name,
invites: invites.map((email) => ({ email })),
+ allowDomainJoin,
});
},
joinTeam: async (inviteId) => {
diff --git a/apps/web/src/features/onboarding/primitives/team-step.ts b/apps/web/src/features/onboarding/primitives/team-step.ts
index 5296330c94..ecbd7fa9a3 100644
--- a/apps/web/src/features/onboarding/primitives/team-step.ts
+++ b/apps/web/src/features/onboarding/primitives/team-step.ts
@@ -109,6 +109,9 @@ export function createTeamForm(
seed.prefilled.length > 0 ? [...seed.prefilled, ''] : ['', '']
);
const [pending, setPending] = createSignal(false);
+ // Only a work domain can be joined by domain; on by default.
+ const [allowDomainJoin, setAllowDomainJoin] = createSignal(true);
+ const domainJoin = () => seed.domain !== undefined && allowDomainJoin();
const invites = () => validInviteEmails(slots(), options.ownEmail);
const canCreate = () => name().trim().length > 0 && !pending();
@@ -118,7 +121,11 @@ export function createTeamForm(
const sent = invites();
setPending(true);
try {
- await context.createTeam({ name: name().trim(), invites: sent });
+ await context.createTeam({
+ name: name().trim(),
+ invites: sent,
+ allowDomainJoin: domainJoin(),
+ });
} catch {
// The capability reports its own failure; keep the form intact.
return;
@@ -133,6 +140,7 @@ export function createTeamForm(
invites_removed: seed.prefilled.filter((address) => !kept.has(address))
.length,
used_domain_suggestion: seed.domain !== undefined,
+ allow_domain_join: domainJoin(),
});
options.onCreated();
};
@@ -151,6 +159,10 @@ export function createTeamForm(
invites,
pending,
canCreate,
+ /** The work domain colleagues can join by, when there is one. */
+ domain: seed.domain,
+ allowDomainJoin,
+ setAllowDomainJoin,
suggested: seed.prefilled.length > 0,
create,
};
diff --git a/apps/web/src/features/onboarding/tests/fake-onboarding-context.ts b/apps/web/src/features/onboarding/tests/fake-onboarding-context.ts
index ef59f67ea2..b25107f4ec 100644
--- a/apps/web/src/features/onboarding/tests/fake-onboarding-context.ts
+++ b/apps/web/src/features/onboarding/tests/fake-onboarding-context.ts
@@ -305,8 +305,10 @@ export function createFakeOnboarding(
contacts: () => ({ t: 'ready', value: world.contacts }),
retry: () => call('retryTeams'),
}),
- createTeam: async ({ name, invites }) => {
- call(`createTeam:${name}:${invites.join(',')}`);
+ createTeam: async ({ name, invites, allowDomainJoin }) => {
+ call(
+ `createTeam:${name}:${invites.join(',')}${allowDomainJoin ? '' : ':closed'}`
+ );
fail('createTeam');
update((draft) => {
draft.teams = [{ name }];
diff --git a/apps/web/src/features/onboarding/views/onboarding-flow-view.test.tsx b/apps/web/src/features/onboarding/views/onboarding-flow-view.test.tsx
index 3b143e5732..2a75e6f131 100644
--- a/apps/web/src/features/onboarding/views/onboarding-flow-view.test.tsx
+++ b/apps/web/src/features/onboarding/views/onboarding-flow-view.test.tsx
@@ -137,6 +137,36 @@ describe('onboarding flow', () => {
await heading('Connect your tools.');
});
+ it('requires a team for a work domain and lets the creator close it to the domain', async () => {
+ const { fake } = setup({ resume: 'team' });
+ await heading('Built for teams.');
+ await screen.findByDisplayValue('Acme');
+
+ expect(screen.queryByRole('button', { name: 'Skip for now' })).toBeNull();
+ const domainJoin = screen.getByRole('switch', {
+ name: 'Allow @acme.com emails to join',
+ });
+ expect((domainJoin as HTMLInputElement).checked).toBe(true);
+
+ fireEvent.click(domainJoin);
+ click('Create team & invite 2');
+ await waitFor(() =>
+ expect(fake.calls()).toContain(
+ 'createTeam:Acme:[email protected],[email protected]:closed'
+ )
+ );
+ });
+
+ it('lets personal-domain accounts skip the team without a domain switch', async () => {
+ setup({
+ resume: 'team',
+ world: { record: { status: 'active', suggestedTeamDomain: undefined } },
+ });
+ await heading('Built for teams.');
+ await screen.findByRole('button', { name: 'Skip for now' });
+ expect(screen.queryByRole('switch')).toBeNull();
+ });
+
it('opens a step link on that step and records it as the entry', async () => {
const { fake } = setup({
step: 'plan',
@@ -306,6 +336,44 @@ describe('onboarding flow', () => {
});
});
+ it('passes over the team step for someone who already joined a team', async () => {
+ const { fake } = setup({
+ resume: 'tools',
+ world: { teams: [{ name: 'Acme' }] },
+ });
+ await heading('Connect your tools.');
+ click('Continue');
+ await heading('Free Claude & GPT for 30 days.');
+ expect(screen.queryByText("You're on Acme")).toBeNull();
+ expect(fake.events()).toContainEqual({
+ event: 'onboarding_v4_team',
+ data: { action: 'already_on_team' },
+ });
+ click('Back to previous step');
+ await heading('Connect your tools.');
+ });
+
+ it('finishes from the tools step for a licensed member of a team', async () => {
+ const { navigate } = setup({
+ resume: 'tools',
+ world: {
+ teams: [{ name: 'Acme' }],
+ viewer: {
+ id: FAKE_VIEWER_ID,
+ email: '[email protected]',
+ tutorialComplete: false,
+ licensed: true,
+ },
+ },
+ });
+ await heading('Connect your tools.');
+ click('Continue');
+ await waitFor(() =>
+ expect(navigate).toHaveBeenCalledExactlyOnceWith('/home')
+ );
+ expect(screen.queryByText("You're on Acme")).toBeNull();
+ });
+
it('confirms an existing team membership', async () => {
const { fake } = setup({
resume: 'team',
diff --git a/apps/web/src/features/onboarding/views/onboarding-flow-view.tsx b/apps/web/src/features/onboarding/views/onboarding-flow-view.tsx
index e0b94a9e1a..9b5a7288dc 100644
--- a/apps/web/src/features/onboarding/views/onboarding-flow-view.tsx
+++ b/apps/web/src/features/onboarding/views/onboarding-flow-view.tsx
@@ -45,6 +45,7 @@ export function OnboardingFlowView(props: {
// Read once for the completion rollup; only the tools step polls.
const connectedTools = context.createConnectedTools({ poll: false });
const record = context.createOnboardingRecord();
+ const teamDirectory = context.createTeamDirectory();
const finish = createFlowFinish(context, {
next: () => props.next,
@@ -99,19 +100,28 @@ export function OnboardingFlowView(props: {
queueMicrotask(() => focusStepHeading(content));
});
};
+ // Someone who already joined a team (invite link or domain) has nothing to
+ // do on the team step, so the flow passes over it in both directions.
+ const passesTeam = (target: OnboardingStep | undefined) => {
+ const teams = teamDirectory.teams();
+ return target === 'team' && teams.t === 'ready' && teams.value.length > 0;
+ };
const advance = (outcome: StepOutcome = 'completed') => {
if (finish.finishing()) return;
const next = flow.leave(outcome);
+ const skipsTeam = passesTeam(next);
+ if (skipsTeam)
+ context.track('onboarding_v4_team', { action: 'already_on_team' });
const viewer = context.viewer();
if (
- step() === 'team' &&
+ (step() === 'team' || skipsTeam) &&
viewer.t === 'signed-in' &&
viewer.viewer.licensed
) {
fireAndForget(finish.finishPremium(), 'onboarding');
return;
}
- goTo(next);
+ goTo(skipsTeam ? 'plan' : next);
};
const viewerEmail = () => {
const viewer = context.viewer();
@@ -129,7 +139,8 @@ export function OnboardingFlowView(props: {
const back = () => {
const current = step();
const previous = current && previousOnboardingStep(current);
- return previous && !finish.finishing() ? () => goTo(previous) : undefined;
+ const target = passesTeam(previous) ? 'tools' : previous;
+ return target && !finish.finishing() ? () => goTo(target) : undefined;
};
return (
diff --git a/apps/web/src/features/onboarding/views/team-step.tsx b/apps/web/src/features/onboarding/views/team-step.tsx
index cb232b24c8..308e789567 100644
--- a/apps/web/src/features/onboarding/views/team-step.tsx
+++ b/apps/web/src/features/onboarding/views/team-step.tsx
@@ -1,4 +1,5 @@
import { fireAndForget } from '@core/util/fireAndForget';
+import { ToggleSwitch } from '@ui';
import { createMemo, Match, Show, Switch } from 'solid-js';
import { ContinueButton, SkipButton } from '../components/controls';
import {
@@ -126,7 +127,24 @@ function TeamForm(props: {
onEmailChange={form.setSlot}
onRemoveEmail={form.removeSlot}
onAddEmail={form.addSlot}
- />
+ >
+ <Show when={form.domain}>
+ {(domain) => (
+ <ToggleSwitch
+ size="md"
+ class="w-full gap-3 border-t border-edge-muted pt-6"
+ controlClass="shrink-0"
+ checked={form.allowDomainJoin()}
+ onChange={form.setAllowDomainJoin}
+ label={
+ <span class="text-sm text-ink">
+ Allow @{domain()} emails to join
+ </span>
+ }
+ />
+ )}
+ </Show>
+ </TeamSetupFields>
<ContinueButton
label={
props.finishing
@@ -140,10 +158,13 @@ function TeamForm(props: {
disabled={!form.canCreate() || props.finishing}
onClick={() => fireAndForget(form.create(), 'onboarding')}
/>
- <SkipButton
- disabled={form.pending() || props.finishing}
- onClick={props.onSkip}
- />
+ {/* A work domain always gets a team; only personal addresses may skip. */}
+ <Show when={!form.domain}>
+ <SkipButton
+ disabled={form.pending() || props.finishing}
+ onClick={props.onSkip}
+ />
+ </Show>
</div>
);
}
diff --git a/apps/web/src/lib/analytics/app-events.ts b/apps/web/src/lib/analytics/app-events.ts
index 0c50f986e4..fc5e75a6cf 100644
--- a/apps/web/src/lib/analytics/app-events.ts
+++ b/apps/web/src/lib/analytics/app-events.ts
@@ -103,6 +103,8 @@ export type AppEvents = {
/** How many of those the user removed before creating the team. */
invites_removed?: number;
used_domain_suggestion?: boolean;
+ /** Whether people on the work domain may join, which also sends the notice. */
+ allow_domain_join?: boolean;
};
/**
* The flow finished (free, premium, or plan skipped) with a rollup of
diff --git a/apps/web/src/lib/queries/team/teams.ts b/apps/web/src/lib/queries/team/teams.ts
index 663366bcc5..3e1454b53b 100644
--- a/apps/web/src/lib/queries/team/teams.ts
+++ b/apps/web/src/lib/queries/team/teams.ts
@@ -1,7 +1,11 @@
import { toast } from '@core/component/Toast/Toast';
import { useIsAuthenticated, useUserId } from '@core/context/user';
import { fireAndForget } from '@core/util/fireAndForget';
-import { ThrownResultError, throwOnErr } from '@core/util/result';
+import {
+ catchToResult,
+ ThrownResultError,
+ throwOnErr,
+} from '@core/util/result';
import {
authServiceClient,
type ToggleAutoJoinDomainErrorCode,
@@ -354,6 +358,10 @@ export function useDeleteTeamMutation(callbacks?: DeleteTeamCallbacks) {
type CreateTeamWithInvitesArgs = {
name: string;
invites?: { email: string }[];
+ /** Whether people on the owner's work domain join automatically. When
+ * explicitly `true`, the owner's same-domain contacts are also told the
+ * team exists. Omitted keeps the server default without the notice. */
+ allowDomainJoin?: boolean;
};
type CreateTeamWithInvitesContext = { previousTeams: Team[] | undefined };
type CreateTeamWithInvitesCallbacks = MutationCallbacks<
@@ -367,15 +375,33 @@ export function useCreateTeamWithInvitesMutation(
callbacks?: CreateTeamWithInvitesCallbacks
) {
return useMutation(() => ({
- mutationFn: async ({ name, invites }: CreateTeamWithInvitesArgs) => {
+ mutationFn: async ({
+ name,
+ invites,
+ allowDomainJoin,
+ }: CreateTeamWithInvitesArgs) => {
const team = await throwOnErr(() =>
- authServiceClient.createTeam({ name })
+ authServiceClient.createTeam({
+ name,
+ allow_domain_join: allowDomainJoin,
+ })
);
if (invites && invites.length > 0) {
await throwOnErr(() => authServiceClient.inviteToTeam({ invites }));
}
+ // After the invites, so invitees aren't also sent the notice. The
+ // team already exists, so a failed notice doesn't fail creation.
+ if (allowDomainJoin === true && team.auto_join_domain) {
+ const notice = await catchToResult(() =>
+ throwOnErr(() => authServiceClient.sendTeamDomainNotice())
+ );
+ if (notice.isErr()) {
+ console.error('Failed to send team domain notice', notice);
+ }
+ }
+
return team;
},
diff --git a/apps/web/src/lib/service-clients/service-auth/client.ts b/apps/web/src/lib/service-clients/service-auth/client.ts
index 13afbefc80..3104dce8e7 100644
--- a/apps/web/src/lib/service-clients/service-auth/client.ts
+++ b/apps/web/src/lib/service-clients/service-auth/client.ts
@@ -75,6 +75,7 @@ import type { ProfilePictures } from './generated/schemas/profilePictures';
import type { PublicGtmInviteLink } from './generated/schemas/publicGtmInviteLink';
import type { PutProfilePictureParams } from './generated/schemas/putProfilePictureParams';
import type { PutUserNameQueryParams } from './generated/schemas/putUserNameQueryParams';
+import type { SendDomainNoticeResponse } from './generated/schemas/sendDomainNoticeResponse';
import type { StatusUpdate } from './generated/schemas/statusUpdate';
import type { SystemStatus } from './generated/schemas/systemStatus';
import type { SystemStatusHistory } from './generated/schemas/systemStatusHistory';
@@ -1399,6 +1400,20 @@ export const authServiceClient = {
).map(() => undefined);
},
+ /**
+ * Emails the caller's same-domain contacts who aren't on Macro yet that
+ * the caller's team exists. Call it after inviting, so invitees are
+ * skipped. Admin/Owner only; the server caps a team at 25 recipients.
+ */
+ async sendTeamDomainNotice() {
+ return (
+ await fetchWithAuth<SendDomainNoticeResponse>(
+ `${authHost}/team/domain-notice`,
+ { method: 'POST' }
+ )
+ ).map((result) => result);
+ },
+
async inviteToTeam(args: InviteToTeamRequest) {
return (
await fetchWithAuth<{}>(`${authHost}/team/invite`, {
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/client.ts b/apps/web/src/lib/service-clients/service-auth/generated/client.ts
index 9fb4d0dcb3..d456da7630 100644
--- a/apps/web/src/lib/service-clients/service-auth/generated/client.ts
+++ b/apps/web/src/lib/service-clients/service-auth/generated/client.ts
@@ -87,6 +87,7 @@ import type {
PutUserNameParams,
RedeemGtmInviteLinkRequest,
ResendFusionauthVerifyUserEmailRequest,
+ SendDomainNoticeResponse,
SendInviteBody,
SendMobileWelcomeEmailRequest,
SendMobileWelcomeEmailResponse,
@@ -4869,6 +4870,73 @@ export const patchTeamCrmSettings = async (
} as patchTeamCrmSettingsResponse;
};
+/**
+ * @summary Emails the caller's contacts on the team's auto-join domain that the team
+exists, so they can sign up and join. Contacts already on Macro, on the
+team, invited, or emailed before are skipped, and a team emails at most 25
+people in total. Call it after sending the team's invites. Requires the
+caller to be an Admin or Owner of the team.
+ */
+export type sendTeamDomainNoticeResponse200 = {
+ data: SendDomainNoticeResponse;
+ status: 200;
+};
+
+export type sendTeamDomainNoticeResponse401 = {
+ data: ErrorResponse;
+ status: 401;
+};
+
+export type sendTeamDomainNoticeResponse403 = {
+ data: ErrorResponse;
+ status: 403;
+};
+
+export type sendTeamDomainNoticeResponse500 = {
+ data: ErrorResponse;
+ status: 500;
+};
+
+export type sendTeamDomainNoticeResponseSuccess =
+ sendTeamDomainNoticeResponse200 & {
+ headers: Headers;
+ };
+export type sendTeamDomainNoticeResponseError = (
+ | sendTeamDomainNoticeResponse401
+ | sendTeamDomainNoticeResponse403
+ | sendTeamDomainNoticeResponse500
+) & {
+ headers: Headers;
+};
+
+export type sendTeamDomainNoticeResponse =
+ | sendTeamDomainNoticeResponseSuccess
+ | sendTeamDomainNoticeResponseError;
+
+export const getSendTeamDomainNoticeUrl = () => {
+ return `/team/domain-notice`;
+};
+
+export const sendTeamDomainNotice = async (
+ options?: RequestInit
+): Promise<sendTeamDomainNoticeResponse> => {
+ const res = await fetch(getSendTeamDomainNoticeUrl(), {
+ ...options,
+ method: 'POST',
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: sendTeamDomainNoticeResponse['data'] = body
+ ? JSON.parse(body)
+ : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as sendTeamDomainNoticeResponse;
+};
+
/**
* @summary Invites a user to a team.
*/
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/createTeamRequest.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/createTeamRequest.ts
index 7dc633cb25..505534a3b1 100644
--- a/apps/web/src/lib/service-clients/service-auth/generated/schemas/createTeamRequest.ts
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/createTeamRequest.ts
@@ -9,6 +9,9 @@
* The request body to create a new team
*/
export interface CreateTeamRequest {
+ /** Whether colleagues who sign up with the owner's work email domain join
+the team automatically. Ignored for generic email providers. */
+ allow_domain_join?: boolean;
/** The name of the team */
name: string;
}
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/index.ts
index 2a9b1535f3..91bae7518b 100644
--- a/apps/web/src/lib/service-clients/service-auth/generated/schemas/index.ts
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/index.ts
@@ -205,6 +205,7 @@ export * from './resendFusionauthVerifyUserEmailRequest';
export * from './savedAgentApiKey';
export * from './scheduledSeatPlan';
export * from './seatPlan';
+export * from './sendDomainNoticeResponse';
export * from './sendInviteBody';
export * from './sendMobileWelcomeEmailRequest';
export * from './sendMobileWelcomeEmailResponse';
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/sendDomainNoticeResponse.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/sendDomainNoticeResponse.ts
new file mode 100644
index 0000000000..1c3d12fb6a
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/sendDomainNoticeResponse.ts
@@ -0,0 +1,17 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * authentication_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Response for the domain notice endpoint.
+ */
+export interface SendDomainNoticeResponse {
+ /**
+ * How many colleagues were emailed by this call.
+ * @minimum 0
+ */
+ sent: number;
+}
diff --git a/apps/web/src/lib/service-clients/service-auth/openapi.json b/apps/web/src/lib/service-clients/service-auth/openapi.json
index 77d4bd111d..4cfe94ebd6 100644
--- a/apps/web/src/lib/service-clients/service-auth/openapi.json
+++ b/apps/web/src/lib/service-clients/service-auth/openapi.json
@@ -4198,6 +4198,55 @@
}
}
},
+ "/team/domain-notice": {
+ "post": {
+ "tags": ["teams::inbound::axum_router::domain_notice"],
+ "summary": "Emails the caller's contacts on the team's auto-join domain that the team\nexists, so they can sign up and join. Contacts already on Macro, on the\nteam, invited, or emailed before are skipped, and a team emails at most 25\npeople in total. Call it after sending the team's invites. Requires the\ncaller to be an Admin or Owner of the team.",
+ "operationId": "send_team_domain_notice",
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/SendDomainNoticeResponse"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "403": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/team/invite": {
"post": {
"tags": ["teams::inbound::axum_router::invite_to_team"],
@@ -6627,6 +6676,10 @@
"description": "The request body to create a new team",
"required": ["name"],
"properties": {
+ "allow_domain_join": {
+ "type": "boolean",
+ "description": "Whether colleagues who sign up with the owner's work email domain join\nthe team automatically. Ignored for generic email providers."
+ },
"name": {
"type": "string",
"description": "The name of the team"
@@ -8310,6 +8363,19 @@
"description": "The paid plan a seat is billed at. Every member of a paying team has one;\na team may mix them, and its Stripe subscription carries one seat item per\nplan in use.",
"enum": ["premium", "max"]
},
+ "SendDomainNoticeResponse": {
+ "type": "object",
+ "description": "Response for the domain notice endpoint.",
+ "required": ["sent"],
+ "properties": {
+ "sent": {
+ "type": "integer",
+ "format": "int32",
+ "description": "How many colleagues were emailed by this call.",
+ "minimum": 0
+ }
+ }
+ },
"SendInviteBody": {
"type": "object",
"description": "The body which is used to describe the recipient email",
diff --git a/crates/agent_code_mode/src/domain/operations.json b/crates/agent_code_mode/src/domain/operations.json
index cce3ab58f5..741251bf27 100644
--- a/crates/agent_code_mode/src/domain/operations.json
+++ b/crates/agent_code_mode/src/domain/operations.json
@@ -118,6 +118,7 @@
"auth.createTeam": "Create Team",
"auth.toggleTeamAutoJoinDomain": "Toggle Team Auto Join Domain",
"auth.patchTeamCrmSettings": "Patch Team Crm Settings",
+ "auth.sendTeamDomainNotice": "Send Team Domain Notice",
"auth.inviteToTeam": "Invite To Team",
"auth.deleteTeamInviteLink": "Delete Team Invite Link",
"auth.getTeamInviteLink": "Get Team Invite Link",
diff --git a/crates/code_execution/src/outbound/deno/sdk.mjs b/crates/code_execution/src/outbound/deno/sdk.mjs
index 309c05d794..ce00e399c1 100644
--- a/crates/code_execution/src/outbound/deno/sdk.mjs
+++ b/crates/code_execution/src/outbound/deno/sdk.mjs
@@ -9,7 +9,7 @@ async function cO($,O,j){if(!Number.isInteger(O)||O<1)throw RangeError(`concurre
`);U=y.pop()??"";for(let a of y){let i=a.split(`
`),F=[],v;for(let R of i)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))v=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let m=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(m))V=m}let M,h=!1;if(F.length){let R=F.join(`
-`);try{M=JSON.parse(R),h=!0}catch{M=R}}if(h){if(S)await S(M);if(x)M=await x(M)}if(j?.({data:M,event:v,id:J,retry:V}),F.length)yield M}}}finally{H.removeEventListener("abort",g),T.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var vS=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},hS=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},mS=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},hj=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((G)=>encodeURIComponent(G))).join(hS(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=vS(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return CO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},CO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},mj=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let G=[];Object.entries(S).forEach(([Q,J])=>{G=[...G,Q,$?J:encodeURIComponent(J)]});let L=G.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=mS(x),X=Object.entries(S).map(([G,L])=>CO({allowReserved:$,name:x==="deepObject"?`${j}[${G}]`:G,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var uS=/\{[^{}]+\}/g,cS=({path:$,url:O})=>{let j=O,x=O.match(uS);if(x)for(let S of x){let K=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))K=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let G=$[Z];if(G===void 0||G===null)continue;if(Array.isArray(G)){j=j.replace(S,hj({explode:K,name:Z,style:X,value:G}));continue}if(typeof G==="object"){j=j.replace(S,mj({explode:K,name:Z,style:X,value:G,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${CO({name:Z,value:G})}`);continue}let L=encodeURIComponent(X==="label"?`.${G}`:G);j=j.replace(S,L)}return j},U2=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=cS({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function px($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var z2=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var I2={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var H2=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let G=hj({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(G)S.push(G)}else if(typeof Z==="object"){let G=mj({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(G)S.push(G)}else{let G=CO({allowReserved:X.allowReserved,name:K,value:Z});if(G)S.push(G)}}return S.join("&")}},T2=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},dS=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function R2($){for(let O of $.security??[]){if(dS($,O.name))continue;let j=await z2(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var ax=($)=>U2({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:H2($.querySerializer),url:$.url}),ix=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=cj($.headers,O.headers),j},lS=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},cj=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?lS(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class uj{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var D2=()=>({error:new uj,request:new uj,response:new uj}),rS=H2({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),pS={"Content-Type":"application/json"},jj=($={})=>({...I2,headers:pS,parseAs:"auto",querySerializer:rS,...$});var nx=($={})=>{let O=ix(jj(),$),j=()=>({...O}),x=(Q)=>{return O=ix(O,Q),j()},S=D2(),K=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:cj(O.headers,Q.headers),serializedBody:void 0};if(J.security)await R2(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let I=J,z=ax(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(Q),H={redirect:"follow",...V,body:px(V)};z=new Request(B,H);for(let N of S.request.fns)if(N)z=await N(z,V);let C=V.fetch;W=await C(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?T2(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let T;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":T=await W[N]();break;case"json":{let U=await W.text();T=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(T);if(V.responseTransformer)T=await V.responseTransformer(T)}return V.responseStyle==="data"?T:{data:T,...D}}let _=await W.text(),w;try{w=JSON.parse(_)}catch{}throw w??_}catch(V){let B=V;for(let H of S.error.fns)if(H)B=await H(B,W,z,Q);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(Q)=>(J)=>Z({...J,method:Q}),G=(Q)=>async(J)=>{let{opts:I,url:z}=await K(J);return N2({...I,body:I.body,method:Q,onRequest:async(W,V)=>{let B=new Request(W,V);for(let H of S.request.fns)if(H)B=await H(B,I);return B},serializedBody:px(I),url:z})};return{buildUrl:(Q)=>ax({...O,...Q}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:G("CONNECT"),delete:G("DELETE"),get:G("GET"),head:G("HEAD"),options:G("OPTIONS"),patch:G("PATCH"),post:G("POST"),put:G("PUT"),trace:G("TRACE")},trace:X("TRACE")}};var _2=nx(jj());class M2{client;constructor($){this.client=$?.client??_2}}class A2{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class dj extends M2{static __registry=new A2;constructor($){super($);dj.__registry.set(this,$?.key)}deleteAgentApiKey($){return($.client??this.client).delete({url:"/agents/{agent_id}/api-key",...$})}getAgentApiKey($){return($.client??this.client).get({url:"/agents/{agent_id}/api-key",...$})}putAgentApiKey($){return($.client??this.client).put({url:"/agents/{agent_id}/api-key",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateAiBillingAutoReload($){return($.client??this.client).patch({url:"/ai-billing/auto-reload",...$,headers:{"Content-Type":"application/json",...$.headers}})}createAiCreditCheckout($){return($.client??this.client).post({url:"/ai-billing/credits/checkout",...$,headers:{"Content-Type":"application/json",...$.headers}})}purchaseAiCredits($){return($.client??this.client).post({url:"/ai-billing/credits/purchase",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateAiBillingOverage($){return($.client??this.client).patch({url:"/ai-billing/overage",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAiBillingPlans($){return($?.client??this.client).get({url:"/ai-billing/plans",...$})}getAiBillingSummary($){return($?.client??this.client).get({url:"/ai-billing/summary",...$})}disconnectCodex($){return($?.client??this.client).delete({url:"/codex",...$})}getCodexConnection($){return($?.client??this.client).get({url:"/codex",...$})}configureCodex($){return($.client??this.client).put({url:"/codex/config",...$,headers:{"Content-Type":"application/json",...$.headers}})}listCodexEnvironments($){return($?.client??this.client).get({url:"/codex/environments",...$})}startCodexLogin($){return($?.client??this.client).post({url:"/codex/login",...$})}cancelCodexLogin($){return($.client??this.client).delete({url:"/codex/login/{attempt_id}",...$})}pollCodexLogin($){return($.client??this.client).get({url:"/codex/login/{attempt_id}",...$})}deleteCursorApiKey($){return($?.client??this.client).delete({url:"/cursor-api-key",...$})}getCursorApiKey($){return($?.client??this.client).get({url:"/cursor-api-key",...$})}putCursorApiKey($){return($.client??this.client).put({url:"/cursor-api-key",...$,headers:{"Content-Type":"application/json",...$.headers}})}putCursorDefaultModel($){return($.client??this.client).put({url:"/cursor-api-key/default-model",...$,headers:{"Content-Type":"application/json",...$.headers}})}listCursorModels($){return($?.client??this.client).get({url:"/cursor-api-key/models",...$})}verifyFusionauthUserEmail($){return($.client??this.client).get({url:"/email/fusionauth/verify/{verification_id}",...$})}resendFusionauthVerifyUserEmail($){return($.client??this.client).post({url:"/email/fusionauth_resend",...$,headers:{"Content-Type":"application/json",...$.headers}})}generateEmailLink($){return($.client??this.client).post({url:"/email/generate/link",...$,headers:{"Content-Type":"application/json",...$.headers}})}verifyEmailLink($){return($.client??this.client).get({url:"/email/verify/{verification_id}",...$})}setGithubPullRequestDraft($){return($.client??this.client).post({url:"/github_pull_requests/draft",...$,headers:{"Content-Type":"application/json",...$.headers}})}enrichGithubPullRequests($){return($.client??this.client).post({url:"/github_pull_requests/enrich",...$,headers:{"Content-Type":"application/json",...$.headers}})}mergeGithubPullRequest($){return($.client??this.client).post({url:"/github_pull_requests/merge",...$,headers:{"Content-Type":"application/json",...$.headers}})}getGithubPullRequestMergeability($){return($.client??this.client).post({url:"/github_pull_requests/mergeability",...$,headers:{"Content-Type":"application/json",...$.headers}})}setGithubPullRequestState($){return($.client??this.client).post({url:"/github_pull_requests/state",...$,headers:{"Content-Type":"application/json",...$.headers}})}listGtmInviteLinks($){return($?.client??this.client).get({url:"/gtm-invite/links",...$})}createGtmInviteLink($){return($.client??this.client).post({url:"/gtm-invite/links",...$,headers:{"Content-Type":"application/json",...$.headers}})}revokeGtmInviteLink($){return($.client??this.client).delete({url:"/gtm-invite/links/{id}",...$})}getGtmInviteOffer($){return($?.client??this.client).get({url:"/gtm-invite/offer",...$})}resolveGtmInviteLink($){return($.client??this.client).get({url:"/gtm-invite/public/{token}",...$})}redeemGtmInviteLink($){return($.client??this.client).post({url:"/gtm-invite/redeem",...$,headers:{"Content-Type":"application/json",...$.headers}})}healthHandler($){return($?.client??this.client).get({url:"/health",...$})}macroApiToken($){return($.client??this.client).get({url:"/jwt/macro_api_token",...$})}refresh($){return($?.client??this.client).post({url:"/jwt/refresh",...$})}createInProgressLink($){return($?.client??this.client).post({url:"/link",...$})}emailConnectionProviders($){return($?.client??this.client).get({url:"/link/email/providers",...$})}deleteGithubLink($){return($?.client??this.client).delete({url:"/link/github",...$})}initGithubLink($){return($.client??this.client).post({url:"/link/github",...$})}checkGithubLinkStatus($){return($?.client??this.client).get({url:"/link/github/status",...$})}initGmailLink($){return($.client??this.client).post({url:"/link/gmail",...$})}checkGmailLinkStatus($){return($?.client??this.client).get({url:"/link/gmail/status",...$})}initOutlookLink($){return($?.client??this.client).post({url:"/link/outlook",...$})}appleLogin($){return($.client??this.client).post({url:"/login/apple",...$,headers:{"Content-Type":"application/json",...$.headers}})}passwordLogin($){return($.client??this.client).post({url:"/login/password",...$,headers:{"Content-Type":"application/json",...$.headers}})}passwordlessLogin($){return($.client??this.client).post({url:"/login/passwordless",...$,headers:{"Content-Type":"application/json",...$.headers}})}ssoLogin($){return($.client??this.client).get({url:"/login/sso",...$})}logout($){return($?.client??this.client).post({url:"/logout",...$})}createMergeRequest($){return($.client??this.client).post({url:"/merge",...$,headers:{"Content-Type":"application/json",...$.headers}})}verifyMergeRequest($){return($.client??this.client).get({url:"/merge/verify/{code}",...$})}sendMobileWelcomeEmail($){return($.client??this.client).post({url:"/mobile-welcome-email",...$,headers:{"Content-Type":"application/json",...$.headers}})}passwordlessCallback($){return($.client??this.client).get({url:"/oauth/passwordless/{code}",...$})}oauthRedirect($){return($?.client??this.client).get({url:"/oauth/redirect",...$})}oauth2Callback($){return($.client??this.client).get({url:"/oauth2/{provider}/callback",...$})}getPermissions($){return($?.client??this.client).get({url:"/permissions",...$})}getUserPermissions($){return($?.client??this.client).get({url:"/permissions/me",...$})}getReferralCode($){return($?.client??this.client).get({url:"/referral/code",...$})}sendReferralCode($){return($.client??this.client).post({url:"/referral/send",...$,headers:{"Content-Type":"application/json",...$.headers}})}sessionCreation($){return($?.client??this.client).post({url:"/session",...$})}sessionLogin($){return($.client??this.client).get({url:"/session/login/{session_code}",...$})}getSystemStatus($){return($?.client??this.client).get({url:"/system-status",...$})}setSystemStatus($){return($.client??this.client).post({url:"/system-status",...$,headers:{"Content-Type":"application/json",...$.headers}})}listSystemStatusHistory($){return($?.client??this.client).get({url:"/system-status/history",...$})}deleteTeam($){return($?.client??this.client).delete({url:"/team",...$})}getTeam($){return($?.client??this.client).get({url:"/team",...$})}patchTeam($){return($.client??this.client).patch({url:"/team",...$,headers:{"Content-Type":"application/json",...$.headers}})}createTeam($){return($.client??this.client).post({url:"/team",...$,headers:{"Content-Type":"application/json",...$.headers}})}toggleTeamAutoJoinDomain($){return($?.client??this.client).post({url:"/team/auto-join-domain/toggle",...$})}patchTeamCrmSettings($){return($.client??this.client).patch({url:"/team/crm",...$,headers:{"Content-Type":"application/json",...$.headers}})}inviteToTeam($){return($.client??this.client).post({url:"/team/invite",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteTeamInviteLink($){return($?.client??this.client).delete({url:"/team/invite-link",...$})}getTeamInviteLink($){return($?.client??this.client).get({url:"/team/invite-link",...$})}createTeamInviteLink($){return($?.client??this.client).post({url:"/team/invite-link",...$})}joinTeamByInviteLink($){return($.client??this.client).post({url:"/team/invite-link/join",...$,headers:{"Content-Type":"application/json",...$.headers}})}getTeamByInviteLink($){return($.client??this.client).post({url:"/team/invite-link/team",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteTeamInviteHandler($){return($.client??this.client).delete({url:"/team/invite/{team_invite_id}",...$})}getTeamInvites($){return($?.client??this.client).get({url:"/team/invites",...$})}rejectInvitation($){return($.client??this.client).delete({url:"/team/join/{team_invite_id}",...$})}joinTeam($){return($.client??this.client).get({url:"/team/join/{team_invite_id}",...$})}patchTeamMemberPlan($){return($.client??this.client).patch({url:"/team/members/{member_user_id}/plan",...$,headers:{"Content-Type":"application/json",...$.headers}})}toggleTeamNonAdminInvites($){return($?.client??this.client).post({url:"/team/non-admin-invites/toggle",...$})}removeUserFromTeam($){return($.client??this.client).delete({url:"/team/remove/{remove_user_id}",...$})}getUserTeams($){return($?.client??this.client).get({url:"/team/user",...$})}getUserInvites($){return($?.client??this.client).get({url:"/team/user/invites",...$})}getUserNames($){return($.client??this.client).post({url:"/user/get_names",...$,headers:{"Content-Type":"application/json",...$.headers}})}getUserNamesWithEmail($){return($.client??this.client).post({url:"/user/get_names_with_email",...$,headers:{"Content-Type":"application/json",...$.headers}})}patchUserGroup($){return($.client??this.client).patch({url:"/user/group",...$,headers:{"Content-Type":"application/json",...$.headers}})}getUserLanguage($){return($?.client??this.client).get({url:"/user/language",...$})}putUserLanguage($){return($.client??this.client).put({url:"/user/language",...$,headers:{"Content-Type":"application/json",...$.headers}})}getLegacyUserPermissions($){return($?.client??this.client).get({url:"/user/legacy_user_permissions",...$})}getUserLinkExists($){return($.client??this.client).get({url:"/user/link_exists",...$})}deleteUser($){return($?.client??this.client).delete({url:"/user/me",...$})}getUserInfo($){return($?.client??this.client).get({url:"/user/me",...$})}getUserName($){return($?.client??this.client).get({url:"/user/name",...$})}putUserName($){return($?.client??this.client).put({url:"/user/name",...$})}patchUserOnboarding($){return($.client??this.client).patch({url:"/user/onboarding",...$,headers:{"Content-Type":"application/json",...$.headers}})}getUserOrganization($){return($?.client??this.client).get({url:"/user/organization",...$})}putProfilePicture($){return($.client??this.client).put({url:"/user/profile_picture",...$})}postProfilePictures($){return($.client??this.client).post({url:"/user/profile_pictures",...$,headers:{"Content-Type":"application/json",...$.headers}})}getUserQuota($){return($?.client??this.client).get({url:"/user/quota",...$})}createCheckoutSessionV2($){return($.client??this.client).post({url:"/user/stripe/checkoutv2",...$,headers:{"Content-Type":"application/json",...$.headers}})}getSubscriptionStatus($){return($?.client??this.client).get({url:"/user/stripe/plan",...$})}changePlan($){return($.client??this.client).post({url:"/user/stripe/plan",...$,headers:{"Content-Type":"application/json",...$.headers}})}createPortalSession($){return($.client??this.client).post({url:"/user/stripe/portal",...$,headers:{"Content-Type":"application/json",...$.headers}})}getTrialEligibility($){return($?.client??this.client).get({url:"/user/stripe/trial_eligibility",...$})}patchUserTutorial($){return($.client??this.client).patch({url:"/user/tutorial",...$,headers:{"Content-Type":"application/json",...$.headers}})}}function P2({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:G,url:L,...Q}){let J,I=G??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,H=Q.signal??new AbortController().signal;while(!0){if(H.aborted)break;B++;let C=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)C.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:C,signal:H},_=new Request(L,D);if($)_=await $(L,D);let N=await(Q.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let T=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{T.cancel()}catch{}};H.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await T.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
+`);try{M=JSON.parse(R),h=!0}catch{M=R}}if(h){if(S)await S(M);if(x)M=await x(M)}if(j?.({data:M,event:v,id:J,retry:V}),F.length)yield M}}}finally{H.removeEventListener("abort",g),T.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var vS=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},hS=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},mS=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},hj=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((G)=>encodeURIComponent(G))).join(hS(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=vS(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return CO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},CO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},mj=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let G=[];Object.entries(S).forEach(([Q,J])=>{G=[...G,Q,$?J:encodeURIComponent(J)]});let L=G.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=mS(x),X=Object.entries(S).map(([G,L])=>CO({allowReserved:$,name:x==="deepObject"?`${j}[${G}]`:G,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var uS=/\{[^{}]+\}/g,cS=({path:$,url:O})=>{let j=O,x=O.match(uS);if(x)for(let S of x){let K=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))K=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let G=$[Z];if(G===void 0||G===null)continue;if(Array.isArray(G)){j=j.replace(S,hj({explode:K,name:Z,style:X,value:G}));continue}if(typeof G==="object"){j=j.replace(S,mj({explode:K,name:Z,style:X,value:G,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${CO({name:Z,value:G})}`);continue}let L=encodeURIComponent(X==="label"?`.${G}`:G);j=j.replace(S,L)}return j},U2=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=cS({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function px($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var z2=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var I2={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var H2=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let G=hj({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(G)S.push(G)}else if(typeof Z==="object"){let G=mj({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(G)S.push(G)}else{let G=CO({allowReserved:X.allowReserved,name:K,value:Z});if(G)S.push(G)}}return S.join("&")}},T2=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},dS=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function R2($){for(let O of $.security??[]){if(dS($,O.name))continue;let j=await z2(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var ax=($)=>U2({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:H2($.querySerializer),url:$.url}),ix=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=cj($.headers,O.headers),j},lS=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},cj=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?lS(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class uj{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var D2=()=>({error:new uj,request:new uj,response:new uj}),rS=H2({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),pS={"Content-Type":"application/json"},jj=($={})=>({...I2,headers:pS,parseAs:"auto",querySerializer:rS,...$});var nx=($={})=>{let O=ix(jj(),$),j=()=>({...O}),x=(Q)=>{return O=ix(O,Q),j()},S=D2(),K=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:cj(O.headers,Q.headers),serializedBody:void 0};if(J.security)await R2(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let I=J,z=ax(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(Q),H={redirect:"follow",...V,body:px(V)};z=new Request(B,H);for(let N of S.request.fns)if(N)z=await N(z,V);let C=V.fetch;W=await C(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?T2(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let T;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":T=await W[N]();break;case"json":{let U=await W.text();T=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(T);if(V.responseTransformer)T=await V.responseTransformer(T)}return V.responseStyle==="data"?T:{data:T,...D}}let _=await W.text(),w;try{w=JSON.parse(_)}catch{}throw w??_}catch(V){let B=V;for(let H of S.error.fns)if(H)B=await H(B,W,z,Q);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(Q)=>(J)=>Z({...J,method:Q}),G=(Q)=>async(J)=>{let{opts:I,url:z}=await K(J);return N2({...I,body:I.body,method:Q,onRequest:async(W,V)=>{let B=new Request(W,V);for(let H of S.request.fns)if(H)B=await H(B,I);return B},serializedBody:px(I),url:z})};return{buildUrl:(Q)=>ax({...O,...Q}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:G("CONNECT"),delete:G("DELETE"),get:G("GET"),head:G("HEAD"),options:G("OPTIONS"),patch:G("PATCH"),post:G("POST"),put:G("PUT"),trace:G("TRACE")},trace:X("TRACE")}};var _2=nx(jj());class M2{client;constructor($){this.client=$?.client??_2}}class A2{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class dj extends M2{static __registry=new A2;constructor($){super($);dj.__registry.set(this,$?.key)}deleteAgentApiKey($){return($.client??this.client).delete({url:"/agents/{agent_id}/api-key",...$})}getAgentApiKey($){return($.client??this.client).get({url:"/agents/{agent_id}/api-key",...$})}putAgentApiKey($){return($.client??this.client).put({url:"/agents/{agent_id}/api-key",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateAiBillingAutoReload($){return($.client??this.client).patch({url:"/ai-billing/auto-reload",...$,headers:{"Content-Type":"application/json",...$.headers}})}createAiCreditCheckout($){return($.client??this.client).post({url:"/ai-billing/credits/checkout",...$,headers:{"Content-Type":"application/json",...$.headers}})}purchaseAiCredits($){return($.client??this.client).post({url:"/ai-billing/credits/purchase",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateAiBillingOverage($){return($.client??this.client).patch({url:"/ai-billing/overage",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAiBillingPlans($){return($?.client??this.client).get({url:"/ai-billing/plans",...$})}getAiBillingSummary($){return($?.client??this.client).get({url:"/ai-billing/summary",...$})}disconnectCodex($){return($?.client??this.client).delete({url:"/codex",...$})}getCodexConnection($){return($?.client??this.client).get({url:"/codex",...$})}configureCodex($){return($.client??this.client).put({url:"/codex/config",...$,headers:{"Content-Type":"application/json",...$.headers}})}listCodexEnvironments($){return($?.client??this.client).get({url:"/codex/environments",...$})}startCodexLogin($){return($?.client??this.client).post({url:"/codex/login",...$})}cancelCodexLogin($){return($.client??this.client).delete({url:"/codex/login/{attempt_id}",...$})}pollCodexLogin($){return($.client??this.client).get({url:"/codex/login/{attempt_id}",...$})}deleteCursorApiKey($){return($?.client??this.client).delete({url:"/cursor-api-key",...$})}getCursorApiKey($){return($?.client??this.client).get({url:"/cursor-api-key",...$})}putCursorApiKey($){return($.client??this.client).put({url:"/cursor-api-key",...$,headers:{"Content-Type":"application/json",...$.headers}})}putCursorDefaultModel($){return($.client??this.client).put({url:"/cursor-api-key/default-model",...$,headers:{"Content-Type":"application/json",...$.headers}})}listCursorModels($){return($?.client??this.client).get({url:"/cursor-api-key/models",...$})}verifyFusionauthUserEmail($){return($.client??this.client).get({url:"/email/fusionauth/verify/{verification_id}",...$})}resendFusionauthVerifyUserEmail($){return($.client??this.client).post({url:"/email/fusionauth_resend",...$,headers:{"Content-Type":"application/json",...$.headers}})}generateEmailLink($){return($.client??this.client).post({url:"/email/generate/link",...$,headers:{"Content-Type":"application/json",...$.headers}})}verifyEmailLink($){return($.client??this.client).get({url:"/email/verify/{verification_id}",...$})}setGithubPullRequestDraft($){return($.client??this.client).post({url:"/github_pull_requests/draft",...$,headers:{"Content-Type":"application/json",...$.headers}})}enrichGithubPullRequests($){return($.client??this.client).post({url:"/github_pull_requests/enrich",...$,headers:{"Content-Type":"application/json",...$.headers}})}mergeGithubPullRequest($){return($.client??this.client).post({url:"/github_pull_requests/merge",...$,headers:{"Content-Type":"application/json",...$.headers}})}getGithubPullRequestMergeability($){return($.client??this.client).post({url:"/github_pull_requests/mergeability",...$,headers:{"Content-Type":"application/json",...$.headers}})}setGithubPullRequestState($){return($.client??this.client).post({url:"/github_pull_requests/state",...$,headers:{"Content-Type":"application/json",...$.headers}})}listGtmInviteLinks($){return($?.client??this.client).get({url:"/gtm-invite/links",...$})}createGtmInviteLink($){return($.client??this.client).post({url:"/gtm-invite/links",...$,headers:{"Content-Type":"application/json",...$.headers}})}revokeGtmInviteLink($){return($.client??this.client).delete({url:"/gtm-invite/links/{id}",...$})}getGtmInviteOffer($){return($?.client??this.client).get({url:"/gtm-invite/offer",...$})}resolveGtmInviteLink($){return($.client??this.client).get({url:"/gtm-invite/public/{token}",...$})}redeemGtmInviteLink($){return($.client??this.client).post({url:"/gtm-invite/redeem",...$,headers:{"Content-Type":"application/json",...$.headers}})}healthHandler($){return($?.client??this.client).get({url:"/health",...$})}macroApiToken($){return($.client??this.client).get({url:"/jwt/macro_api_token",...$})}refresh($){return($?.client??this.client).post({url:"/jwt/refresh",...$})}createInProgressLink($){return($?.client??this.client).post({url:"/link",...$})}emailConnectionProviders($){return($?.client??this.client).get({url:"/link/email/providers",...$})}deleteGithubLink($){return($?.client??this.client).delete({url:"/link/github",...$})}initGithubLink($){return($.client??this.client).post({url:"/link/github",...$})}checkGithubLinkStatus($){return($?.client??this.client).get({url:"/link/github/status",...$})}initGmailLink($){return($.client??this.client).post({url:"/link/gmail",...$})}checkGmailLinkStatus($){return($?.client??this.client).get({url:"/link/gmail/status",...$})}initOutlookLink($){return($?.client??this.client).post({url:"/link/outlook",...$})}appleLogin($){return($.client??this.client).post({url:"/login/apple",...$,headers:{"Content-Type":"application/json",...$.headers}})}passwordLogin($){return($.client??this.client).post({url:"/login/password",...$,headers:{"Content-Type":"application/json",...$.headers}})}passwordlessLogin($){return($.client??this.client).post({url:"/login/passwordless",...$,headers:{"Content-Type":"application/json",...$.headers}})}ssoLogin($){return($.client??this.client).get({url:"/login/sso",...$})}logout($){return($?.client??this.client).post({url:"/logout",...$})}createMergeRequest($){return($.client??this.client).post({url:"/merge",...$,headers:{"Content-Type":"application/json",...$.headers}})}verifyMergeRequest($){return($.client??this.client).get({url:"/merge/verify/{code}",...$})}sendMobileWelcomeEmail($){return($.client??this.client).post({url:"/mobile-welcome-email",...$,headers:{"Content-Type":"application/json",...$.headers}})}passwordlessCallback($){return($.client??this.client).get({url:"/oauth/passwordless/{code}",...$})}oauthRedirect($){return($?.client??this.client).get({url:"/oauth/redirect",...$})}oauth2Callback($){return($.client??this.client).get({url:"/oauth2/{provider}/callback",...$})}getPermissions($){return($?.client??this.client).get({url:"/permissions",...$})}getUserPermissions($){return($?.client??this.client).get({url:"/permissions/me",...$})}getReferralCode($){return($?.client??this.client).get({url:"/referral/code",...$})}sendReferralCode($){return($.client??this.client).post({url:"/referral/send",...$,headers:{"Content-Type":"application/json",...$.headers}})}sessionCreation($){return($?.client??this.client).post({url:"/session",...$})}sessionLogin($){return($.client??this.client).get({url:"/session/login/{session_code}",...$})}getSystemStatus($){return($?.client??this.client).get({url:"/system-status",...$})}setSystemStatus($){return($.client??this.client).post({url:"/system-status",...$,headers:{"Content-Type":"application/json",...$.headers}})}listSystemStatusHistory($){return($?.client??this.client).get({url:"/system-status/history",...$})}deleteTeam($){return($?.client??this.client).delete({url:"/team",...$})}getTeam($){return($?.client??this.client).get({url:"/team",...$})}patchTeam($){return($.client??this.client).patch({url:"/team",...$,headers:{"Content-Type":"application/json",...$.headers}})}createTeam($){return($.client??this.client).post({url:"/team",...$,headers:{"Content-Type":"application/json",...$.headers}})}toggleTeamAutoJoinDomain($){return($?.client??this.client).post({url:"/team/auto-join-domain/toggle",...$})}patchTeamCrmSettings($){return($.client??this.client).patch({url:"/team/crm",...$,headers:{"Content-Type":"application/json",...$.headers}})}sendTeamDomainNotice($){return($?.client??this.client).post({url:"/team/domain-notice",...$})}inviteToTeam($){return($.client??this.client).post({url:"/team/invite",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteTeamInviteLink($){return($?.client??this.client).delete({url:"/team/invite-link",...$})}getTeamInviteLink($){return($?.client??this.client).get({url:"/team/invite-link",...$})}createTeamInviteLink($){return($?.client??this.client).post({url:"/team/invite-link",...$})}joinTeamByInviteLink($){return($.client??this.client).post({url:"/team/invite-link/join",...$,headers:{"Content-Type":"application/json",...$.headers}})}getTeamByInviteLink($){return($.client??this.client).post({url:"/team/invite-link/team",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteTeamInviteHandler($){return($.client??this.client).delete({url:"/team/invite/{team_invite_id}",...$})}getTeamInvites($){return($?.client??this.client).get({url:"/team/invites",...$})}rejectInvitation($){return($.client??this.client).delete({url:"/team/join/{team_invite_id}",...$})}joinTeam($){return($.client??this.client).get({url:"/team/join/{team_invite_id}",...$})}patchTeamMemberPlan($){return($.client??this.client).patch({url:"/team/members/{member_user_id}/plan",...$,headers:{"Content-Type":"application/json",...$.headers}})}toggleTeamNonAdminInvites($){return($?.client??this.client).post({url:"/team/non-admin-invites/toggle",...$})}removeUserFromTeam($){return($.client??this.client).delete({url:"/team/remove/{remove_user_id}",...$})}getUserTeams($){return($?.client??this.client).get({url:"/team/user",...$})}getUserInvites($){return($?.client??this.client).get({url:"/team/user/invites",...$})}getUserNames($){return($.client??this.client).post({url:"/user/get_names",...$,headers:{"Content-Type":"application/json",...$.headers}})}getUserNamesWithEmail($){return($.client??this.client).post({url:"/user/get_names_with_email",...$,headers:{"Content-Type":"application/json",...$.headers}})}patchUserGroup($){return($.client??this.client).patch({url:"/user/group",...$,headers:{"Content-Type":"application/json",...$.headers}})}getUserLanguage($){return($?.client??this.client).get({url:"/user/language",...$})}putUserLanguage($){return($.client??this.client).put({url:"/user/language",...$,headers:{"Content-Type":"application/json",...$.headers}})}getLegacyUserPermissions($){return($?.client??this.client).get({url:"/user/legacy_user_permissions",...$})}getUserLinkExists($){return($.client??this.client).get({url:"/user/link_exists",...$})}deleteUser($){return($?.client??this.client).delete({url:"/user/me",...$})}getUserInfo($){return($?.client??this.client).get({url:"/user/me",...$})}getUserName($){return($?.client??this.client).get({url:"/user/name",...$})}putUserName($){return($?.client??this.client).put({url:"/user/name",...$})}patchUserOnboarding($){return($.client??this.client).patch({url:"/user/onboarding",...$,headers:{"Content-Type":"application/json",...$.headers}})}getUserOrganization($){return($?.client??this.client).get({url:"/user/organization",...$})}putProfilePicture($){return($.client??this.client).put({url:"/user/profile_picture",...$})}postProfilePictures($){return($.client??this.client).post({url:"/user/profile_pictures",...$,headers:{"Content-Type":"application/json",...$.headers}})}getUserQuota($){return($?.client??this.client).get({url:"/user/quota",...$})}createCheckoutSessionV2($){return($.client??this.client).post({url:"/user/stripe/checkoutv2",...$,headers:{"Content-Type":"application/json",...$.headers}})}getSubscriptionStatus($){return($?.client??this.client).get({url:"/user/stripe/plan",...$})}changePlan($){return($.client??this.client).post({url:"/user/stripe/plan",...$,headers:{"Content-Type":"application/json",...$.headers}})}createPortalSession($){return($.client??this.client).post({url:"/user/stripe/portal",...$,headers:{"Content-Type":"application/json",...$.headers}})}getTrialEligibility($){return($?.client??this.client).get({url:"/user/stripe/trial_eligibility",...$})}patchUserTutorial($){return($.client??this.client).patch({url:"/user/tutorial",...$,headers:{"Content-Type":"application/json",...$.headers}})}}function P2({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:G,url:L,...Q}){let J,I=G??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,H=Q.signal??new AbortController().signal;while(!0){if(H.aborted)break;B++;let C=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)C.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:C,signal:H},_=new Request(L,D);if($)_=await $(L,D);let N=await(Q.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let T=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{T.cancel()}catch{}};H.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await T.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
`);let y=U.split(`
`);U=y.pop()??"";for(let a of y){let i=a.split(`
diff --git a/crates/email_formatting/src/lib.rs b/crates/email_formatting/src/lib.rs
index 1e4e3a6856..9e23bec421 100644
--- a/crates/email_formatting/src/lib.rs
+++ b/crates/email_formatting/src/lib.rs
@@ -111,18 +111,12 @@ impl EmailDigestNotification {
}
let num_truncated = input_len - preview_len;
- let mut unsubscribe_url = signing::append_path(
+ let unsubscribe_url = signing::unsubscribe_url(
NotificationServiceUrl::new_for_environment(env)?.parse_url()?,
- &format!(
- "/user_notifications/preferences/{}/disable",
- Self::TYPE_NAME
- ),
+ Self::TYPE_NAME,
+ digest.user_id.as_ref(),
+ sha,
);
- unsubscribe_url
- .query_pairs_mut()
- .append_pair("id", digest.user_id.as_ref())
- .finish();
- let unsubscribe_url = SignedUrl::new(unsubscribe_url, sha);
let inner_html_string = DigestTemplate {
notifs,
diff --git a/crates/invite_email/AGENTS.md b/crates/invite_email/AGENTS.md
index d6f9ac489a..41f72ba6a0 100644
--- a/crates/invite_email/AGENTS.md
+++ b/crates/invite_email/AGENTS.md
@@ -14,7 +14,10 @@ invites, and the colleague-joined email.
- `src/call_invite.rs`, `src/colleague_joined.rs`: the remaining notification
metadata types, one file each.
- `templates/*.html`: the actual email markup (Askama/Jinja2-compatible
- syntax).
+ syntax). An email that needs an unsubscribe link puts
+ `notification::domain::models::signing::unsubscribe_placeholder(TYPE_NAME)` in
+ the `href`; the notification service signs it per recipient at send time, and
+ the type must be in the service's blockable list.
- `preview_invite.py`: renders `templates/invite.html` with dummy data via
Jinja2 and opens it in a browser — use this to check template changes
without sending an email (`pip3 install jinja2` if needed).
diff --git a/crates/invite_email/src/colleague_joined.rs b/crates/invite_email/src/colleague_joined.rs
index 7a45e3d458..9c66f2cf61 100644
--- a/crates/invite_email/src/colleague_joined.rs
+++ b/crates/invite_email/src/colleague_joined.rs
@@ -2,7 +2,9 @@ use super::*;
const DISPLAY_NAME_MAX_CHARS: usize = 64;
-/// Tells someone whose address matches a team's auto-join domain that a colleague joined Macro.
+/// Tells someone whose address matches a team's auto-join domain that a team now exists for their
+/// organization and that signing up with their work email joins it. It is an informational,
+/// one-time notice that names who set the team up rather than announcing a sign-up.
#[derive(Debug, Clone, Serialize, Deserialize, Template)]
#[template(path = "colleague_joined_macro.html")]
pub struct ColleagueJoinedMacro {
@@ -34,11 +36,6 @@ impl ColleagueJoinedMacro {
(!name.is_empty()).then(|| name.to_owned())
}
- fn joined_display(&self) -> String {
- self.display_name()
- .unwrap_or_else(|| self.joined_email().to_owned())
- }
-
fn joined_email(&self) -> &str {
self.joined_by.email_str()
}
@@ -50,6 +47,11 @@ impl ColleagueJoinedMacro {
fn signup_url(&self) -> Url {
signup_url(Environment::new_or_prod())
}
+
+ /// The notification service signs this into a link that stops these notices.
+ fn unsubscribe_href(&self) -> String {
+ notification::domain::models::signing::unsubscribe_placeholder(Self::TYPE_NAME)
+ }
}
impl Notification for ColleagueJoinedMacro {
@@ -59,7 +61,7 @@ impl Notification for ColleagueJoinedMacro {
impl NotificationExtEmail for ColleagueJoinedMacro {
fn format_email(&self) -> EmailContent {
EmailContent {
- subject: format!("{} joined Macro", self.joined_display()),
+ subject: "A team has been created for your organization".to_string(),
body: self
.render()
.expect("ColleagueJoinedMacro template render failed in format_email"),
diff --git a/crates/invite_email/src/test.rs b/crates/invite_email/src/test.rs
index 48ce15961b..b94a022f88 100644
--- a/crates/invite_email/src/test.rs
+++ b/crates/invite_email/src/test.rs
@@ -29,24 +29,35 @@ fn make_colleague_joined() -> ColleagueJoinedMacro {
}
}
+const COLLEAGUE_SUBJECT: &str = "A team has been created for your organization";
+
#[test]
-fn colleague_joined_names_the_colleague_and_links_to_signup() {
+fn colleague_joined_is_an_organization_notice_that_links_to_signup() {
let email = make_colleague_joined().format_email();
- assert_eq!(email.subject, "Alice Example joined Macro");
+ assert_eq!(email.subject, COLLEAGUE_SUBJECT);
assert!(
email
.body
- .contains("Alice Example ([email protected]) joined Macro with the")
+ .contains("Alice Example ([email protected]) set up the")
);
- assert!(email.body.contains("<strong>Acme</strong> team."));
+ assert!(email.body.contains("<strong>Acme</strong> team on Macro"));
assert!(
email
.body
.contains("Sign up with <strong>[email protected]</strong>")
);
+ assert!(email.body.contains("one-time notice"));
+ assert!(
+ email
+ .body
+ .contains("href=\"macro-unsubscribe:colleague_joined_macro\"")
+ );
+ assert!(email.body.contains("54 W 21st St, Suite 503, New York, NY"));
assert!(email.body.contains("/app/signup\""));
assert!(email.body.contains(">Join Acme</a"));
assert!(!email.body.contains("referral_code"));
+ // The notice is not framed as someone signing up.
+ assert!(!email.body.contains("joined Macro"));
}
#[test]
@@ -57,8 +68,8 @@ fn colleague_joined_falls_back_to_the_email_without_a_usable_name() {
..make_colleague_joined()
}
.format_email();
- assert_eq!(email.subject, "[email protected] joined Macro");
- assert!(email.body.contains("[email protected] joined Macro with the"));
+ assert_eq!(email.subject, COLLEAGUE_SUBJECT);
+ assert!(email.body.contains("[email protected] set up the"));
assert!(!email.body.contains("([email protected])"));
}
}
@@ -70,10 +81,11 @@ fn colleague_joined_puts_long_multiline_names_on_one_capped_line() {
..make_colleague_joined()
}
.format_email();
- assert_eq!(
- email.subject,
- format!("Alice Example {} joined Macro", "x".repeat(50))
- );
+ assert_eq!(email.subject, COLLEAGUE_SUBJECT);
+ assert!(email.body.contains(&format!(
+ "Alice Example {} ([email protected])",
+ "x".repeat(50)
+ )));
}
#[test]
@@ -83,7 +95,7 @@ fn colleague_joined_escapes_the_untrusted_name_in_the_body() {
..make_colleague_joined()
}
.format_email();
- assert_eq!(email.subject, "<b>x</b> joined Macro");
+ assert_eq!(email.subject, COLLEAGUE_SUBJECT);
assert!(!email.body.contains("<b>x</b>"));
assert!(
email
diff --git a/crates/invite_email/templates/colleague_joined_macro.html b/crates/invite_email/templates/colleague_joined_macro.html
index a54c45c039..cc4508b7b6 100644
--- a/crates/invite_email/templates/colleague_joined_macro.html
+++ b/crates/invite_email/templates/colleague_joined_macro.html
@@ -10,7 +10,7 @@
/>
<meta name="color-scheme" content="light" />
<meta name="supported-color-schemes" content="light" />
- <title>{{ self.joined_display() }} joined Macro</title>
+ <title>A team has been created for your organization</title>
<!--[if mso]>
<noscript
><xml
@@ -53,7 +53,7 @@
mso-hide: all;
"
>
- Sign up with your work email to join {{ team_name }} on Macro.
+ {{ team_name }} is now on Macro. Sign up with your work email to join automatically.
</div>
<table
role="presentation"
@@ -125,7 +125,7 @@
color: #222222;
"
>
- {{ team_name }} is on Macro.
+ A team has been created for your organization.
</h1>
<p
style="
@@ -139,8 +139,9 @@
{{ name }} ({{ self.joined_email() }})
{%- else -%}
{{ self.joined_email() }}
- {%- endif %} joined Macro with the
- <strong>{{ team_name }}</strong> team.
+ {%- endif %} set up the
+ <strong>{{ team_name }}</strong> team on Macro for your
+ organization.
</p>
<p
style="
@@ -200,12 +201,24 @@
color: #737373;
"
>
- Need a hand?
+ You are receiving this one-time notice because your email
+ address belongs to your organization's domain. No action is
+ needed.
+ <br />
+ <a
+ href="{{ self.unsubscribe_href() }}"
+ style="color: #525252; text-decoration: underline"
+ >Unsubscribe</a
+ >
+ &middot;
<a
href="mailto:[email protected]"
style="color: #525252; text-decoration: underline"
>Contact support</a
>
+ <br />
+ Coparse, Inc. dba Macro, 54 W 21st St, Suite 503, New York, NY
+ 10010
</td>
</tr>
</table>
diff --git a/crates/notification/AGENTS.md b/crates/notification/AGENTS.md
index d1b8ec3aac..d693da4d71 100644
--- a/crates/notification/AGENTS.md
+++ b/crates/notification/AGENTS.md
@@ -23,7 +23,9 @@ through the same service.
worker, and the PostgreSQL LISTEN adapter that forwards delete events.
- `src/outbound/`: one file per channel/concern — `fanout_realtime.rs` +
`kafka_realtime.rs` (live WebSocket fan-out), `mobile.rs` + `sns_endpoint.rs`
- (push), `email.rs` + `digest_batcher.rs` (digest emails), `repository.rs`
+ (push), `email.rs` + `digest_batcher.rs` (digest emails; `email.rs`'s
+ `SignedUnsubscribeLinks` signs `domain/models/signing.rs` unsubscribe
+ placeholders per recipient), `repository.rs`
(owned Postgres queries), `withdrawal.rs` (durable suppression),
`item_preferences.rs` (snooze/mute).
- `outbound/notification_consumer/health.rs`: periodic per-instance Kafka
diff --git a/crates/notification/src/domain/models/signing.rs b/crates/notification/src/domain/models/signing.rs
index bd8f2009bc..a54bcdd4bd 100644
--- a/crates/notification/src/domain/models/signing.rs
+++ b/crates/notification/src/domain/models/signing.rs
@@ -94,6 +94,63 @@ impl SignedUrl {
}
}
+/// Marks an unsubscribe link in an email body that the producer cannot sign. The notification
+/// service holds the signing key and replaces `macro-unsubscribe:<type name>` with a signed URL
+/// that turns that notification type off for the recipient.
+pub const UNSUBSCRIBE_PLACEHOLDER_PREFIX: &str = "macro-unsubscribe:";
+
+/// The placeholder an email template puts in its unsubscribe `href` for `type_name`.
+pub fn unsubscribe_placeholder(type_name: &str) -> String {
+ format!("{UNSUBSCRIBE_PLACEHOLDER_PREFIX}{type_name}")
+}
+
+/// The signed URL that turns `type_name` off for `user_id` without signing in.
+pub fn unsubscribe_url(
+ notification_service_url: Url,
+ type_name: &str,
+ user_id: &str,
+ mac: Hmac<Sha256>,
+) -> SignedUrl {
+ let mut url = append_path(
+ notification_service_url,
+ &format!("/user_notifications/preferences/{type_name}/disable"),
+ );
+ url.query_pairs_mut().append_pair("id", user_id).finish();
+ SignedUrl::new(url, mac)
+}
+
+/// Replaces every unsubscribe placeholder in an HTML `body` with a signed URL for `user_id`.
+/// Returns `None` when the body has no placeholder.
+pub fn sign_unsubscribe_placeholders(
+ body: &str,
+ notification_service_url: &Url,
+ user_id: &str,
+ mac: &Hmac<Sha256>,
+) -> Option<String> {
+ if !body.contains(UNSUBSCRIBE_PLACEHOLDER_PREFIX) {
+ return None;
+ }
+ let mut signed = String::with_capacity(body.len() + 256);
+ let mut rest = body;
+ while let Some(start) = rest.find(UNSUBSCRIBE_PLACEHOLDER_PREFIX) {
+ signed.push_str(&rest[..start]);
+ let after = &rest[start + UNSUBSCRIBE_PLACEHOLDER_PREFIX.len()..];
+ let type_len = after
+ .find(|c: char| !(c.is_ascii_alphanumeric() || c == '_' || c == '-'))
+ .unwrap_or(after.len());
+ let url = unsubscribe_url(
+ notification_service_url.clone(),
+ &after[..type_len],
+ user_id,
+ mac.clone(),
+ );
+ signed.push_str(&url.as_ref().as_str().replace('&', "&amp;"));
+ rest = &after[type_len..];
+ }
+ signed.push_str(rest);
+ Some(signed)
+}
+
impl AsRef<Url> for SignedUrl {
fn as_ref(&self) -> &Url {
&self.0
diff --git a/crates/notification/src/domain/models/signing/test.rs b/crates/notification/src/domain/models/signing/test.rs
index 221a6dedfa..be8009063f 100644
--- a/crates/notification/src/domain/models/signing/test.rs
+++ b/crates/notification/src/domain/models/signing/test.rs
@@ -127,3 +127,54 @@ fn signed_url_roundtrips_on_both_public_hosts() {
assert!(SignedUrl::verify(signed.as_ref().clone(), secret.clone()).is_some());
}
}
+
+#[test]
+fn unsubscribe_placeholders_become_signed_links_for_the_recipient() {
+ let secret = make_secret(b"test-secret");
+ let base = Url::parse("https://notifications.example.com").unwrap();
+ let body = format!(
+ "<a href=\"{}\">Unsubscribe</a>",
+ unsubscribe_placeholder("colleague_joined_macro")
+ );
+
+ let signed = sign_unsubscribe_placeholders(&body, &base, "macro|[email protected]", &secret)
+ .expect("the body has a placeholder");
+
+ assert!(!signed.contains(UNSUBSCRIBE_PLACEHOLDER_PREFIX));
+ let href = signed
+ .strip_prefix("<a href=\"")
+ .and_then(|s| s.split('"').next())
+ .unwrap()
+ .replace("&amp;", "&");
+ let url = Url::parse(&href).unwrap();
+ assert_eq!(
+ url.path(),
+ "/user_notifications/preferences/colleague_joined_macro/disable"
+ );
+ assert!(
+ url.query_pairs()
+ .any(|(k, v)| k == "id" && v == "macro|[email protected]")
+ );
+ assert!(SignedUrl::verify(url, secret).is_some());
+}
+
+#[test]
+fn bodies_without_a_placeholder_are_left_alone() {
+ let secret = make_secret(b"test-secret");
+ let base = Url::parse("https://notifications.example.com").unwrap();
+ assert!(sign_unsubscribe_placeholders("<p>hi</p>", &base, "macro|[email protected]", &secret).is_none());
+}
+
+#[test]
+fn hyphenated_type_names_are_signed_whole() {
+ let secret = make_secret(b"test-secret");
+ let base = Url::parse("https://notifications.example.com").unwrap();
+ let body = format!(
+ "<a href=\"{}\">x</a>",
+ unsubscribe_placeholder("email-digest-notification")
+ );
+
+ let signed = sign_unsubscribe_placeholders(&body, &base, "macro|[email protected]", &secret).unwrap();
+
+ assert!(signed.contains("/preferences/email-digest-notification/disable"));
+}
diff --git a/crates/notification/src/outbound/email.rs b/crates/notification/src/outbound/email.rs
index 8860235e60..0857ca540a 100644
--- a/crates/notification/src/outbound/email.rs
+++ b/crates/notification/src/outbound/email.rs
@@ -1,11 +1,15 @@
//! Email notification adapter.
use aws_sdk_sesv2::types::{Body, Content, Destination, EmailContent as SesEmailContent, Message};
+use hmac::Hmac;
use macro_user_id::email::ReadEmailParts;
use macro_user_id::user_id::MacroUserIdStr;
use rootcause::Report;
+use sha2::Sha256;
+use url::Url;
use crate::domain::models::queue_message::EmailContent;
+use crate::domain::models::signing::sign_unsubscribe_placeholders;
use crate::domain::ports::EmailSender;
/// Email notification adapter.
@@ -97,3 +101,47 @@ impl<E: EmailServiceOps + Send + Sync + 'static> EmailSender for EmailAdapter<E>
.await
}
}
+
+/// Signs the unsubscribe placeholders an email body carries before handing it to `inner`.
+///
+/// Producers render email bodies without the URL signing key, so a template marks its
+/// unsubscribe link with [`crate::domain::models::signing::unsubscribe_placeholder`]. This
+/// sender knows the recipient and holds the key.
+pub struct SignedUnsubscribeLinks<S> {
+ inner: S,
+ notification_service_url: Url,
+ signing_key: Hmac<Sha256>,
+}
+
+impl<S> SignedUnsubscribeLinks<S> {
+ /// Wraps `inner`, signing links against the notification service's public URL.
+ pub fn new(inner: S, notification_service_url: Url, signing_key: Hmac<Sha256>) -> Self {
+ Self {
+ inner,
+ notification_service_url,
+ signing_key,
+ }
+ }
+}
+
+impl<S: EmailSender> EmailSender for SignedUnsubscribeLinks<S> {
+ async fn send_email(
+ &self,
+ recipient: MacroUserIdStr<'_>,
+ content: &EmailContent,
+ ) -> Result<(), Report> {
+ let Some(body) = sign_unsubscribe_placeholders(
+ &content.body,
+ &self.notification_service_url,
+ recipient.as_ref(),
+ &self.signing_key,
+ ) else {
+ return self.inner.send_email(recipient, content).await;
+ };
+ let signed = EmailContent {
+ subject: content.subject.clone(),
+ body,
+ };
+ self.inner.send_email(recipient, &signed).await
+ }
+}
diff --git a/crates/slack_integration/src/domain/importer.rs b/crates/slack_integration/src/domain/importer.rs
index e550836f87..8a19fa2eea 100644
--- a/crates/slack_integration/src/domain/importer.rs
+++ b/crates/slack_integration/src/domain/importer.rs
@@ -24,7 +24,7 @@ pub mod targets;
use targets::{ImportTargets, TargetFacts, TargetKind, TargetPlan};
-impl<R, S, L, T, H, A, J> ImportWorker for ConversationImporter<R, S, L, T, H, A, J>
+impl<R, S, L, T, H, A> ImportWorker for ConversationImporter<R, S, L, T, H, A>
where
R: ExecutionRepo,
S: ImportStorage,
@@ -32,7 +32,6 @@ where
T: ImportTargets,
H: HistoricalSink,
A: ImportAuthorizer,
- J: JoinAnnouncer,
{
async fn claim(&self, event: &ImportEvent, owner: WorkerId) -> PortResult<ClaimOutcome> {
self.claim(event, owner).await
@@ -57,23 +56,18 @@ pub struct ImporterConfig {
}
/// Domain workflow over persistence, storage, ledger, target and authorization ports.
-pub struct ConversationImporter<R, S, L, T, H, A, J> {
+pub struct ConversationImporter<R, S, L, T, H, A> {
repo: R,
storage: S,
ledger: L,
targets: T,
sink: H,
authorizer: A,
- announcer: J,
limits: ImportLimits,
}
-impl<R, S, L, T, H, A, J> ConversationImporter<R, S, L, T, H, A, J> {
+impl<R, S, L, T, H, A> ConversationImporter<R, S, L, T, H, A> {
/// Construct with validated bounds; no environment access in the domain.
- #[expect(
- clippy::too_many_arguments,
- reason = "each persistence port stays a separate generic at the composition root"
- )]
pub fn new(
repo: R,
storage: S,
@@ -81,7 +75,6 @@ impl<R, S, L, T, H, A, J> ConversationImporter<R, S, L, T, H, A, J> {
targets: T,
sink: H,
authorizer: A,
- announcer: J,
config: ImporterConfig,
) -> Result<Self, ImportError> {
let ImporterConfig { limits } = config;
@@ -103,13 +96,12 @@ impl<R, S, L, T, H, A, J> ConversationImporter<R, S, L, T, H, A, J> {
targets,
sink,
authorizer,
- announcer,
limits,
})
}
}
-impl<R, S, L, T, H, A, J> ConversationImporter<R, S, L, T, H, A, J>
+impl<R, S, L, T, H, A> ConversationImporter<R, S, L, T, H, A>
where
R: ExecutionRepo,
S: ImportStorage,
@@ -117,7 +109,6 @@ where
T: ImportTargets,
H: HistoricalSink,
A: ImportAuthorizer,
- J: JoinAnnouncer,
{
/// Revalidate the durable requester BEFORE claiming/reclaiming. An unauthorized
/// request cannot acquire a lease; the driver reconciles exhausted deliveries.
@@ -345,34 +336,9 @@ where
}
self.ledger.complete(&reservation, metadata.kind).await?;
self.targets.bind(&context.lease, &plan, &warnings).await?;
- self.announce_join(context.lease.event.job_id, &plan, users)
- .await;
Ok(Some(plan))
}
- async fn announce_join(&self, job: JobId, plan: &TargetPlan, users: &UserDirectory) {
- let mut members: Vec<_> = plan.members.iter().cloned().collect();
- members.sort_by(|left, right| left.as_ref().cmp(right.as_ref()));
- let candidate_count = members.len();
- let announcement = JoinAnnouncement {
- team_id: plan.team_id,
- joined: plan.requested_by.clone(),
- joined_name: users.name_of(&plan.requested_by).map(str::to_owned),
- members,
- };
- if let Err(e) = self.announcer.announce(announcement).await {
- tracing::warn!(
- team_id = %plan.team_id,
- job_id = %job,
- conversation_id = %plan.metadata.slack_channel_id,
- channel_id = %plan.channel_id,
- candidate_count,
- error = ?e,
- "colleague join announcement failed"
- );
- }
- }
-
async fn authorize(
&self,
context: &ClaimedConversation,
diff --git a/crates/slack_integration/src/domain/importer/test.rs b/crates/slack_integration/src/domain/importer/test.rs
index 2b20a8aba3..7eb29a9f23 100644
--- a/crates/slack_integration/src/domain/importer/test.rs
+++ b/crates/slack_integration/src/domain/importer/test.rs
@@ -31,8 +31,6 @@ struct State {
receipts: Vec<Uuid>,
polls: Vec<Uuid>,
recorded_search: Vec<SearchState>,
- announcements: Vec<JoinAnnouncement>,
- fail_announce: bool,
fail_bind: bool,
trace: Vec<&'static str>,
}
@@ -40,7 +38,7 @@ struct State {
#[derive(Clone, Default)]
struct Fake(Arc<Mutex<State>>);
-type Importer = ConversationImporter<Fake, Fake, Fake, Fake, Fake, Fake, Fake>;
+type Importer = ConversationImporter<Fake, Fake, Fake, Fake, Fake, Fake>;
fn user(email: &str) -> MacroUserIdStr<'static> {
MacroUserIdStr::try_from_email(email).unwrap()
@@ -60,7 +58,6 @@ fn importer(fake: &Fake, limits: ImportLimits) -> Importer {
fake.clone(),
fake.clone(),
fake.clone(),
- fake.clone(),
ImporterConfig { limits },
)
.unwrap()
@@ -287,19 +284,6 @@ impl ImportTargets for Fake {
}
}
-impl JoinAnnouncer for Fake {
- async fn announce(&self, announcement: JoinAnnouncement) -> PortResult<()> {
- let mut state = self.0.lock().unwrap();
- state.trace.push("announce");
- state.announcements.push(announcement);
- if state.fail_announce {
- Err(ImportError::Internal.into())
- } else {
- Ok(())
- }
- }
-}
-
impl HistoricalSink for Fake {
async fn lookup(
&self,
@@ -987,51 +971,7 @@ async fn failed_missing_and_stale_search_receipts_retry_and_only_publication_com
}
#[tokio::test]
-async fn new_public_channel_announces_sorted_members_once_after_bind() {
- let (fake, context) = fixture(ConversationKind::PublicChannel, &[]);
- importer(&fake, ImportLimits::default())
- .import(&context)
- .await
- .unwrap();
- let state = fake.0.lock().unwrap();
- assert_eq!(state.trace, ["bind", "announce"]);
- assert_eq!(state.announcements.len(), 1);
- let announcement = &state.announcements[0];
- assert_eq!(announcement.team_id, context.team_id);
- assert_eq!(announcement.joined, user("[email protected]"));
- assert_eq!(announcement.joined_name.as_deref(), Some("Importer Admin"));
- assert_eq!(
- announcement.members,
- vec![
- ]
- );
- assert_eq!(state.settlements, [(ConversationStatus::Completed, None)]);
-}
-
-#[tokio::test]
-async fn resolved_dm_announces_its_two_members() {
- let (fake, context) = fixture(ConversationKind::DirectMessage, &[]);
- importer(&fake, ImportLimits::default())
- .import(&context)
- .await
- .unwrap();
- let state = fake.0.lock().unwrap();
- assert_eq!(state.announcements.len(), 1);
- let announcement = &state.announcements[0];
- assert_eq!(announcement.joined, context.requested_by);
- assert_eq!(announcement.joined_name.as_deref(), Some("Importer Admin"));
- assert_eq!(
- announcement.members,
- vec![user("[email protected]"), user("[email protected]")]
- );
- assert!(!announcement.members.contains(&context.requested_by));
-}
-
-#[tokio::test]
-async fn unresolvable_dm_announces_nothing() {
+async fn unresolvable_dm_skips_before_bind() {
let (fake, mut context) = fixture(ConversationKind::DirectMessage, &[]);
context.metadata.member_ids = vec!["U1".parse().unwrap(), "U3".parse().unwrap()];
importer(&fake, ImportLimits::default())
@@ -1039,13 +979,12 @@ async fn unresolvable_dm_announces_nothing() {
.await
.unwrap();
let state = fake.0.lock().unwrap();
- assert!(state.announcements.is_empty());
assert!(state.trace.is_empty());
assert_eq!(state.settlements[0].0, ConversationStatus::Skipped);
}
#[tokio::test]
-async fn unauthorized_existing_target_announces_nothing() {
+async fn unauthorized_existing_target_skips_before_bind() {
let (fake, context) = fixture(ConversationKind::PublicChannel, &[]);
let id = Uuid::now_v7();
{
@@ -1066,7 +1005,6 @@ async fn unauthorized_existing_target_announces_nothing() {
.await
.unwrap();
let state = fake.0.lock().unwrap();
- assert!(state.announcements.is_empty());
assert!(state.plans.is_empty());
assert!(state.trace.is_empty());
assert_eq!(
@@ -1076,7 +1014,7 @@ async fn unauthorized_existing_target_announces_nothing() {
}
#[tokio::test]
-async fn failed_bind_announces_nothing() {
+async fn failed_bind_records_no_plan_or_settlement() {
let (fake, context) = fixture(ConversationKind::PublicChannel, &[]);
fake.0.lock().unwrap().fail_bind = true;
let error = importer(&fake, ImportLimits::default())
@@ -1085,30 +1023,7 @@ async fn failed_bind_announces_nothing() {
.unwrap_err();
assert_eq!(error.into_current_context(), ImportError::Internal);
let state = fake.0.lock().unwrap();
- assert!(state.announcements.is_empty());
assert!(state.plans.is_empty());
assert!(state.trace.is_empty());
assert!(state.settlements.is_empty());
}
-
-#[tokio::test]
-async fn announcer_error_still_completes_after_one_announcement() {
- let (fake, context) = fixture(ConversationKind::PublicChannel, &[]);
- fake.0.lock().unwrap().fail_announce = true;
- importer(&fake, ImportLimits::default())
- .import(&context)
- .await
- .unwrap();
- let state = fake.0.lock().unwrap();
- assert_eq!(state.trace, ["bind", "announce"]);
- assert_eq!(state.announcements.len(), 1);
- assert_eq!(
- state.announcements[0].members,
- vec![
- ]
- );
- assert_eq!(state.settlements, [(ConversationStatus::Completed, None)]);
-}
diff --git a/crates/slack_integration/src/domain/ports.rs b/crates/slack_integration/src/domain/ports.rs
index c8ba5ab2d8..4ac5527a0d 100644
--- a/crates/slack_integration/src/domain/ports.rs
+++ b/crates/slack_integration/src/domain/ports.rs
@@ -339,31 +339,6 @@ pub trait ImportProgressAccess: Send + Sync + 'static {
) -> impl Future<Output = PortResult<Vec<Uuid>>> + Send;
}
-/// Members of a conversation that just bound, offered for the "x joined Macro" email.
-/// Built by the importer after `ImportTargets::bind` succeeded; may include `joined`.
-#[derive(Debug, Clone, PartialEq, Eq)]
-pub struct JoinAnnouncement {
- /// Importing team.
- pub team_id: TeamId,
- /// The importing admin, "x".
- pub joined: MacroUserIdStr<'static>,
- /// x's archive display name when the export has one; untrusted.
- pub joined_name: Option<String>,
- /// `TargetPlan.members`, sorted for determinism.
- pub members: Vec<MacroUserIdStr<'static>>,
-}
-
-/// Best-effort colleague email. Called on every attempt and re-import; implementations
-/// must be idempotent per (team, recipient) forever. The importer logs errors and never
-/// lets them change the import result.
-pub trait JoinAnnouncer: Send + Sync + 'static {
- /// Offer this conversation's resolved members. Idempotent for the life of the team.
- fn announce(
- &self,
- announcement: JoinAnnouncement,
- ) -> impl Future<Output = PortResult<()>> + Send;
-}
-
/// Best-effort invalidation only; persisted polling is the source of truth.
pub trait ImportNotifier: Send + Sync + 'static {
/// Notify the requesting administrator's gateway entity of a job revision using
diff --git a/crates/slack_integration/src/domain/slack/users.rs b/crates/slack_integration/src/domain/slack/users.rs
index 3835b5742d..b1b94ca209 100644
--- a/crates/slack_integration/src/domain/slack/users.rs
+++ b/crates/slack_integration/src/domain/slack/users.rs
@@ -122,18 +122,6 @@ impl UserDirectory {
Ok(directory)
}
- /// Display name of the first non-bot export user, in Slack id order, whose
- /// [`Self::participant`] is `user`. Precedence is profile display name, real name,
- /// then username. `None` when no such user has a name. Archive text is untrusted.
- pub fn name_of(&self, user: &MacroUserIdStr<'_>) -> Option<&str> {
- self.users
- .iter()
- .find_map(|(id, export)| {
- (self.participant(id).as_ref() == Some(user)).then(|| export.display_name())
- })
- .flatten()
- }
-
/// Display name for source membership labels, including no-email/unknown members.
pub fn display_name<'a>(&'a self, id: &'a SlackUserId) -> &'a str {
self.users
diff --git a/crates/slack_integration/src/domain/slack/users/test.rs b/crates/slack_integration/src/domain/slack/users/test.rs
index 13fe89da68..0ea9b4af33 100644
--- a/crates/slack_integration/src/domain/slack/users/test.rs
+++ b/crates/slack_integration/src/domain/slack/users/test.rs
@@ -182,51 +182,6 @@ fn invalid_emails_and_blank_display_names_fall_back_safely() {
}
}
-fn directory_from(json: serde_json::Value) -> UserDirectory {
- UserDirectory::new(serde_json::from_value::<Vec<ExportUser>>(json).unwrap()).unwrap()
-}
-
-#[test]
-fn name_of_matches_email_case_insensitively() {
- let directory = directory_from(serde_json::json!([{
- "id": "U17",
- "name": "ignored",
- "real_name": "Also ignored",
- "profile": {
- "email": "[email protected]",
- "display_name": "T Seventeen",
- "real_name": "Ignored Real"
- }
- }]));
- let id = MacroUserIdStr::try_from_email("[email protected]").unwrap();
- assert_eq!(directory.name_of(&id), Some("T Seventeen"));
-}
-
-#[test]
-fn name_of_is_the_first_slack_id_when_emails_collide() {
- let directory = directory_from(serde_json::json!([
- {"id":"U2","name":"Second","profile":{"email":"[email protected]","display_name":"Second"}},
- {"id":"U1","name":"First","profile":{"email":"[email protected]","display_name":"First"}}
- ]));
- let id = MacroUserIdStr::try_from_email("[email protected]").unwrap();
- assert_eq!(directory.name_of(&id), Some("First"));
-}
-
-#[test]
-fn name_of_is_none_for_unknown_or_bot_only_matches() {
- let directory = directory_from(serde_json::json!([
- {"id":"U0","name":"Bot","is_bot":true,"profile":{"email":"[email protected]","display_name":"Bot Name"}},
- {"id":"U8","name":"Only Bot","is_bot":true,"profile":{"email":"[email protected]","display_name":"Only Bot"}},
- {"id":"U9","name":"Human","profile":{"email":"[email protected]","display_name":"Human Name"}}
- ]));
- let t17 = MacroUserIdStr::try_from_email("[email protected]").unwrap();
- let bot_only = MacroUserIdStr::try_from_email("[email protected]").unwrap();
- let unknown = MacroUserIdStr::try_from_email("[email protected]").unwrap();
- assert_eq!(directory.name_of(&t17), Some("Human Name"));
- assert_eq!(directory.name_of(&bot_only), None);
- assert_eq!(directory.name_of(&unknown), None);
-}
-
#[test]
fn repeated_ids_are_idempotent_but_conflicting_ids_fail_closed() {
let user: ExportUser =
diff --git a/crates/teams/AGENTS.md b/crates/teams/AGENTS.md
index 4ddfdc5d53..4f1206a318 100644
--- a/crates/teams/AGENTS.md
+++ b/crates/teams/AGENTS.md
@@ -15,6 +15,10 @@ event contract (schema, sanitization, delivery semantics).
- `src/domain/team_service/invite_link.rs`: the team's shareable invite link
(`TeamInviteLinkService`) — who may see, create, reset, or turn it off, and
joining through it via the same direct-join path as domain auto-join.
+- `src/domain/domain_notice.rs` + `join_announcement.rs`: the one-time email a
+ new work-domain team sends to the creator's same-domain contacts who are not
+ on Macro yet (`POST /team/domain-notice`, at most 25 per team). Its
+ unsubscribe link is signed by the notification service at send time.
- `src/domain/team_service/invite_reminders.rs` +
`src/inbound/invite_reminder_worker.rs`: reminder emails for unanswered
invites, swept hourly in `authentication_service`. The repository claims
@@ -36,7 +40,7 @@ event contract (schema, sanitization, delivery semantics).
## Boundaries
-- Depends on: `entity_access`, `channels` (feature `backfill_binary`),
+- Depends on: `entity_access`, `contacts` (feature `outbound`), `channels` (feature `backfill_binary`),
`analytics_client`, `ai_toolset` (feature `ai_tools`).
- Used by: `services/authentication_service`, `services/document_storage_service`,
`services/calendar_service`, `services/agent_harness_service`,
diff --git a/crates/teams/src/domain.rs b/crates/teams/src/domain.rs
index 189f1a0b49..3d7cb30e1e 100644
--- a/crates/teams/src/domain.rs
+++ b/crates/teams/src/domain.rs
@@ -1,6 +1,7 @@
pub mod contacts_enqueuer;
pub mod crm_enqueuer;
pub mod customer_repo;
+pub mod domain_notice;
pub mod events;
#[cfg(feature = "ports")]
pub mod join_announcement;
diff --git a/crates/teams/src/domain/domain_notice.rs b/crates/teams/src/domain/domain_notice.rs
new file mode 100644
index 0000000000..ea3db149d4
--- /dev/null
+++ b/crates/teams/src/domain/domain_notice.rs
@@ -0,0 +1,117 @@
+//! The one-time notice a team admin sends after creating a team for their work domain.
+//!
+//! It goes to the admin's contacts on that domain who are not on Macro yet. The join
+//! announcement claim decides who is eligible and caps each team at
+//! [`MAX_RECIPIENTS_PER_TEAM`](super::join_announcement::MAX_RECIPIENTS_PER_TEAM).
+
+#[cfg(test)]
+mod test;
+
+use entity_access::domain::models::{AdminTeamRole, EntityAccessReceipt};
+use macro_user_id::{email::ReadEmailParts, user_id::MacroUserIdStr};
+use rootcause::{Report, prelude::*};
+
+use super::join_announcement::{AnnounceJoin, AnnounceReport, JoinAnnouncementService};
+
+/// Errors from sending a team's domain notice.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
+pub enum DomainNoticeError {
+ /// The receipt does not name a team and a user.
+ #[error("the request does not name a team and a user")]
+ InvalidReceipt,
+ /// Reading contacts or claiming recipients failed.
+ #[error("sending the domain notice failed")]
+ Storage,
+}
+
+/// The people a user has corresponded with.
+pub trait ColleagueDirectory: Send + Sync + 'static {
+ /// The user's contacts, in no particular order.
+ fn contacts(
+ &self,
+ user_id: &MacroUserIdStr<'_>,
+ ) -> impl Future<Output = Result<Vec<MacroUserIdStr<'static>>, Report>> + Send;
+}
+
+/// Sends a team's domain notice.
+pub trait DomainNoticeService: Send + Sync + 'static {
+ /// Emails the admin's same-domain contacts that the team exists. Contacts already on Macro,
+ /// on the team, invited, or emailed before are skipped.
+ fn send_domain_notice(
+ &self,
+ receipt: EntityAccessReceipt<AdminTeamRole>,
+ ) -> impl Future<Output = Result<AnnounceReport, Report<DomainNoticeError>>> + Send;
+}
+
+/// The [`DomainNoticeService`] over a contacts directory and the join announcer.
+pub struct DomainNoticeServiceImpl<D, J> {
+ directory: D,
+ announcer: J,
+}
+
+impl<D, J> DomainNoticeServiceImpl<D, J> {
+ /// Creates the service.
+ pub fn new(directory: D, announcer: J) -> Self {
+ Self {
+ directory,
+ announcer,
+ }
+ }
+}
+
+impl<D, J> DomainNoticeService for DomainNoticeServiceImpl<D, J>
+where
+ D: ColleagueDirectory,
+ J: JoinAnnouncementService,
+{
+ #[tracing::instrument(
+ name = "teams.domain_notice",
+ skip_all,
+ fields(team_id, candidates, claimed, sent),
+ err
+ )]
+ async fn send_domain_notice(
+ &self,
+ receipt: EntityAccessReceipt<AdminTeamRole>,
+ ) -> Result<AnnounceReport, Report<DomainNoticeError>> {
+ let team_id = macro_uuid::string_to_uuid(&receipt.entity().entity_id)
+ .map_err(|_| Report::new(DomainNoticeError::InvalidReceipt))?;
+ let sender = receipt
+ .acting_user_id()
+ .cloned()
+ .ok_or_else(|| Report::new(DomainNoticeError::InvalidReceipt))?;
+ let span = tracing::Span::current();
+ span.record("team_id", tracing::field::display(team_id));
+
+ let sender_email = sender.email_part().lowercase();
+ let domain = sender_email.domain_part();
+ let candidates: Vec<_> = self
+ .directory
+ .contacts(&sender)
+ .await
+ .context(DomainNoticeError::Storage)?
+ .into_iter()
+ .filter(|contact| {
+ contact
+ .email_part()
+ .domain_part()
+ .eq_ignore_ascii_case(domain)
+ })
+ .collect();
+ span.record("candidates", candidates.len());
+
+ let report = self
+ .announcer
+ .announce_join(AnnounceJoin {
+ team_id,
+ joined: sender,
+ joined_name: None,
+ candidates,
+ })
+ .await
+ .context(DomainNoticeError::Storage)?;
+ span.record("claimed", report.claimed);
+ span.record("sent", report.sent);
+ Ok(report)
+ }
+}
diff --git a/crates/teams/src/domain/domain_notice/test.rs b/crates/teams/src/domain/domain_notice/test.rs
new file mode 100644
index 0000000000..123d5b957f
--- /dev/null
+++ b/crates/teams/src/domain/domain_notice/test.rs
@@ -0,0 +1,104 @@
+use std::sync::Mutex;
+
+use model_entity::EntityType;
+use uuid::Uuid;
+
+use super::*;
+use crate::domain::join_announcement::JoinAnnouncementError;
+
+const TEAM: Uuid = Uuid::from_u128(0x2222);
+
+fn user(email: &str) -> MacroUserIdStr<'static> {
+ MacroUserIdStr::try_from_email(email).unwrap()
+}
+
+fn receipt(sender: &str) -> EntityAccessReceipt<AdminTeamRole> {
+ EntityAccessReceipt::dangerously_assert_authenticated_user(
+ user(sender),
+ &TEAM.to_string(),
+ EntityType::Team,
+ )
+}
+
+struct FakeDirectory {
+ contacts: Vec<&'static str>,
+ fail: bool,
+}
+
+impl ColleagueDirectory for FakeDirectory {
+ async fn contacts(
+ &self,
+ _user_id: &MacroUserIdStr<'_>,
+ ) -> Result<Vec<MacroUserIdStr<'static>>, Report> {
+ if self.fail {
+ return Err(rootcause::report!("contacts unavailable"));
+ }
+ Ok(self.contacts.iter().map(|email| user(email)).collect())
+ }
+}
+
+#[derive(Default)]
+struct FakeAnnouncer {
+ requests: Mutex<Vec<AnnounceJoin>>,
+}
+
+impl JoinAnnouncementService for FakeAnnouncer {
+ async fn announce_join(
+ &self,
+ request: AnnounceJoin,
+ ) -> Result<AnnounceReport, Report<JoinAnnouncementError>> {
+ let sent = request.candidates.len() as u32;
+ self.requests.lock().unwrap().push(request);
+ Ok(AnnounceReport {
+ claimed: sent,
+ sent,
+ released: 0,
+ })
+ }
+}
+
+#[tokio::test]
+async fn only_contacts_on_the_senders_domain_are_announced_to() {
+ let service = DomainNoticeServiceImpl::new(
+ FakeDirectory {
+ fail: false,
+ },
+ FakeAnnouncer::default(),
+ );
+
+ let report = service
+ .send_domain_notice(receipt("[email protected]"))
+ .await
+ .unwrap();
+
+ assert_eq!(report.sent, 2);
+ let requests = service.announcer.requests.lock().unwrap();
+ let [request] = requests.as_slice() else {
+ panic!("expected one announcement");
+ };
+ assert_eq!(request.team_id, TEAM);
+ assert_eq!(request.joined, user("[email protected]"));
+ assert_eq!(request.joined_name, None);
+ let candidates: Vec<&str> = request.candidates.iter().map(|c| c.email_str()).collect();
+ assert_eq!(candidates, vec!["[email protected]", "[email protected]"]);
+}
+
+#[tokio::test]
+async fn a_contacts_failure_sends_nothing() {
+ let service = DomainNoticeServiceImpl::new(
+ FakeDirectory {
+ contacts: vec!["[email protected]"],
+ fail: true,
+ },
+ FakeAnnouncer::default(),
+ );
+
+ let error = service
+ .send_domain_notice(receipt("[email protected]"))
+ .await
+ .unwrap_err();
+
+ assert_eq!(*error.current_context(), DomainNoticeError::Storage);
+ assert!(service.announcer.requests.lock().unwrap().is_empty());
+}
diff --git a/crates/teams/src/domain/join_announcement.rs b/crates/teams/src/domain/join_announcement.rs
index 65445cf776..16ccc228be 100644
--- a/crates/teams/src/domain/join_announcement.rs
+++ b/crates/teams/src/domain/join_announcement.rs
@@ -1,4 +1,5 @@
-//! "x joined Macro" emails to colleagues who share a team's auto-join domain.
+//! One-time notices to colleagues who share a team's auto-join domain that a team
+//! now exists for their organization.
//!
//! Each address is claimed once per team, forever, before its email is enqueued. The claim
//! decides eligibility. This module only shapes and sends the emails it accepted.
@@ -17,6 +18,10 @@ use uuid::Uuid;
const MAX_UNSENT_CLAIMS_PER_CRASH: usize = 50;
+/// The most addresses ever emailed about one team. A small cap keeps the notice from looking
+/// like bulk mail to the domain's mail filters.
+pub const MAX_RECIPIENTS_PER_TEAM: u32 = 25;
+
const NOTIFICATION_ID_NAMESPACE: Uuid = Uuid::from_u128(0x7465_616d_2d6a_6f69_6e65_642d_6d61_6372);
/// A user who joined a team, and the colleagues who might hear about it.
@@ -62,14 +67,15 @@ pub struct ClaimedJoinEmail {
/// Storage for the once-per-address claims.
pub trait JoinAnnouncementRepository: Send + Sync + 'static {
- /// Claims every candidate who matches the team's auto-join domain, is neither a member nor
- /// invited, and was never claimed for this team. It is one statement, so concurrent claims
- /// of an address have exactly one winner. Returns nothing when the team has no auto-join
- /// domain.
+ /// Claims every candidate who matches the team's auto-join domain, is neither a member, an
+ /// invitee, nor a Macro user, and was never claimed for this team, until the team has
+ /// `team_limit` claims. It is one statement, so concurrent claims of an address have
+ /// exactly one winner. Returns nothing when the team has no auto-join domain.
fn claim(
&self,
team_id: Uuid,
candidates: &[MacroUserIdStr<'static>],
+ team_limit: u32,
) -> impl Future<Output = Result<Vec<ClaimedJoinEmail>, Report<JoinAnnouncementError>>> + Send;
/// Undoes one claim whose email was not enqueued, so a later announcement can retry it.
@@ -80,7 +86,7 @@ pub trait JoinAnnouncementRepository: Send + Sync + 'static {
) -> impl Future<Output = Result<(), Report<JoinAnnouncementError>>> + Send;
}
-/// Tells colleagues that someone joined Macro.
+/// Tells colleagues that a team was set up for their organization.
pub trait JoinAnnouncementService: Send + Sync + 'static {
/// Emails each candidate other than `joined` whom
/// [`JoinAnnouncementRepository::claim`] accepts. Every address is claimed before its
@@ -140,7 +146,10 @@ where
for ClaimedJoinEmail {
recipient,
team_name,
- } in self.repository.claim(team_id, chunk).await?
+ } in self
+ .repository
+ .claim(team_id, chunk, MAX_RECIPIENTS_PER_TEAM)
+ .await?
{
report.claimed += 1;
let request = SendNotificationRequestBuilder {
diff --git a/crates/teams/src/domain/join_announcement/test.rs b/crates/teams/src/domain/join_announcement/test.rs
index 80208277e1..67f043e3c1 100644
--- a/crates/teams/src/domain/join_announcement/test.rs
+++ b/crates/teams/src/domain/join_announcement/test.rs
@@ -50,6 +50,7 @@ impl JoinAnnouncementRepository for FakeRepository {
&self,
_team_id: Uuid,
candidates: &[MacroUserIdStr<'static>],
+ team_limit: u32,
) -> Result<Vec<ClaimedJoinEmail>, Report<JoinAnnouncementError>> {
self.claim_calls.lock().unwrap().push(
candidates
@@ -65,6 +66,7 @@ impl JoinAnnouncementRepository for FakeRepository {
.iter()
.filter(|candidate| {
self.eligible.contains(candidate.email_str())
+ && claimed.len() < team_limit as usize
&& claimed.insert(candidate.email_str().to_owned())
})
.map(|candidate| ClaimedJoinEmail {
@@ -225,7 +227,7 @@ async fn a_claimed_colleague_gets_one_email_from_the_joiner() {
);
assert_eq!(
request["build_email"]["content"]["subject"],
- "Alice Example joined Macro"
+ "A team has been created for your organization"
);
assert_eq!(request["build_apns"], serde_json::Value::Null);
assert_eq!(request["send_conn_gateway"], false);
@@ -281,6 +283,21 @@ async fn large_candidate_lists_are_claimed_in_chunks_of_fifty() {
assert_eq!(chunk_sizes, vec![50, 50, 20]);
}
+#[tokio::test]
+async fn a_team_emails_at_most_twenty_five_colleagues() {
+ let emails: Vec<String> = (0..60).map(|i| format!("user{i:03}@acme.com")).collect();
+ let candidates: Vec<&str> = emails.iter().map(String::as_str).collect();
+ let service = JoinAnnouncementServiceImpl::new(
+ FakeRepository::eligible(&candidates),
+ FakeIngress::default(),
+ );
+
+ let report = service.announce_join(announce(&candidates)).await.unwrap();
+
+ assert_eq!(report.claimed, MAX_RECIPIENTS_PER_TEAM);
+ assert_eq!(report.sent, MAX_RECIPIENTS_PER_TEAM);
+}
+
#[tokio::test]
async fn a_storage_failure_is_an_error_and_sends_nothing() {
let service = JoinAnnouncementServiceImpl::new(
diff --git a/crates/teams/src/domain/team_repo.rs b/crates/teams/src/domain/team_repo.rs
index a31f430a50..107b5f3acc 100644
--- a/crates/teams/src/domain/team_repo.rs
+++ b/crates/teams/src/domain/team_repo.rs
@@ -61,7 +61,7 @@ pub trait TeamRepository: Clone + Send + Sync + 'static {
/// Creates a new team with the provided normalized slug. `subscription_id` is `None` for
/// free teams. Membership is not capped by team size. `owner_plan` is the plan the owner's
- /// own seat is already billed at.
+ /// own seat is already billed at. `auto_join_domain` is stored as the team's auto-join domain.
fn create_team(
&self,
user_id: &MacroUserIdStr<'_>,
@@ -69,6 +69,7 @@ pub trait TeamRepository: Clone + Send + Sync + 'static {
team_slug: &str,
subscription_id: Option<&stripe::SubscriptionId>,
owner_plan: SeatPlan,
+ auto_join_domain: Option<&str>,
) -> impl Future<Output = Result<Team, CreateTeamError>> + Send;
/// Moves any user-owned GitHub App installation rows to the given team.
@@ -381,12 +382,15 @@ pub trait TeamMembersService: Clone + Send + Sync + 'static {
/// The TeamService defines a set of actions to perform on the teams
pub trait TeamService: Clone + Send + Sync + 'static {
/// Creates a new team. `subscription_id` is `None` for free teams.
- /// Membership is not capped by team size.
+ /// Membership is not capped by team size. With `allow_domain_join`, a team
+ /// whose owner has a work email starts with the owner's domain as its
+ /// auto-join domain.
fn create_team(
&self,
user_id: &MacroUserIdStr<'_>,
team_name: &str,
subscription_id: Option<&stripe::SubscriptionId>,
+ allow_domain_join: bool,
) -> impl Future<Output = Result<Team, CreateTeamError>> + Send;
/// Returns the user's active or trialing Stripe subscription id, if any.
diff --git a/crates/teams/src/domain/team_service.rs b/crates/teams/src/domain/team_service.rs
index ccf3cb5a4a..053ed26e32 100644
--- a/crates/teams/src/domain/team_service.rs
+++ b/crates/teams/src/domain/team_service.rs
@@ -1370,6 +1370,7 @@ where
user_id: &MacroUserIdStr<'_>,
team_name: &str,
subscription_id: Option<&stripe::SubscriptionId>,
+ allow_domain_join: bool,
) -> Result<Team, CreateTeamError> {
// New teams start with `team_crm_settings.crm_enabled = false`
// (seeded by `team_repository.create_team`), so there's nothing
@@ -1386,9 +1387,23 @@ where
.await
.map_err(|e| CreateTeamError::StorageLayerError(e.into()))?,
);
+ // Colleagues who sign up with the owner's work domain join the team
+ // automatically unless the owner opted out. Owners can change it in
+ // settings.
+ let owner_email = user_id.email_part().lowercase();
+ let auto_join_domain = (allow_domain_join
+ && !is_generic_email_domain(owner_email.domain_part()))
+ .then(|| owner_email.domain_part().to_owned());
let team = self
.team_repository
- .create_team(user_id, team_name, &team_slug, subscription_id, owner_plan)
+ .create_team(
+ user_id,
+ team_name,
+ &team_slug,
+ subscription_id,
+ owner_plan,
+ auto_join_domain.as_deref(),
+ )
.await?;
let owner_id = user_id.clone().into_owned();
self.channel_service
@@ -1416,22 +1431,6 @@ where
.move_github_app_installation_to_team_if_exists(user_id, team.id())
.await?;
- // Auto-join is on by default for corporate domains: colleagues who
- // sign up with the same domain are added to the team automatically.
- // Owners can turn it off in settings. Best-effort - creation
- // succeeds even if this fails.
- let owner_email = user_id.email_part().lowercase();
- let auto_join_domain = if is_generic_email_domain(owner_email.domain_part()) {
- None
- } else {
- self.team_repository
- .toggle_auto_join_domain(team.id())
- .await
- .inspect_err(|e| tracing::error!(error=?e, "unable to default auto-join domain on"))
- .ok()
- .flatten()
- };
-
self.track_team_analytics_event(TeamAnalyticsEvent::TeamCreated {
team_id: *team.id(),
owner_id: user_id.clone().into_owned(),
diff --git a/crates/teams/src/domain/team_service/test.rs b/crates/teams/src/domain/team_service/test.rs
index 1cf0a082f7..a575e0c814 100644
--- a/crates/teams/src/domain/team_service/test.rs
+++ b/crates/teams/src/domain/team_service/test.rs
@@ -129,6 +129,7 @@ struct MockTeamRepository {
add_user_to_team_calls: Arc<Mutex<usize>>,
remove_user_calls: Arc<Mutex<usize>>,
auto_join_toggle_calls: Arc<Mutex<Vec<uuid::Uuid>>>,
+ created_auto_join_domains: Arc<Mutex<Vec<Option<String>>>>,
auto_join_toggle_result: Option<String>,
fail_auto_join_toggle: bool,
allow_non_admin_invites: bool,
@@ -216,6 +217,7 @@ impl MockTeamRepository {
add_user_to_team_calls: Arc::new(Mutex::new(0)),
remove_user_calls: Arc::new(Mutex::new(0)),
auto_join_toggle_calls: Arc::new(Mutex::new(Vec::new())),
+ created_auto_join_domains: Arc::new(Mutex::new(Vec::new())),
auto_join_toggle_result: Some("example.com".to_string()),
fail_auto_join_toggle: false,
allow_non_admin_invites: true,
@@ -369,11 +371,16 @@ impl TeamRepository for MockTeamRepository {
team_slug: &str,
_: Option<&stripe::SubscriptionId>,
_: SeatPlan,
+ auto_join_domain: Option<&str>,
) -> impl Future<Output = Result<Team, CreateTeamError>> + Send {
self.create_team_calls
.lock()
.unwrap()
.push((team_name.to_string(), team_slug.to_string()));
+ self.created_auto_join_domains
+ .lock()
+ .unwrap()
+ .push(auto_join_domain.map(str::to_owned));
let team = self.created_team.clone();
async move { Ok(team) }
}
@@ -2083,7 +2090,7 @@ async fn team_event_create_publishes_actual_domain_and_billing_flags() {
let subscription_id: stripe::SubscriptionId = "sub_test".parse().unwrap();
service
- .create_team(&owner, "Enterprise Team", Some(&subscription_id))
+ .create_team(&owner, "Enterprise Team", Some(&subscription_id), true)
.await
.unwrap();
@@ -2094,7 +2101,8 @@ async fn team_event_create_publishes_actual_domain_and_billing_flags() {
assert_eq!(metadata["team_id"], team_id.to_string());
assert_eq!(metadata["enterprise"], true);
assert_eq!(metadata["paid"], true);
- assert_eq!(metadata["auto_join_domain"], "example.com");
+ // The owner's own work domain, stored with the team.
+ assert_eq!(metadata["auto_join_domain"], "corporate.test");
}
#[tokio::test]
@@ -2109,7 +2117,7 @@ async fn team_event_create_generic_domain_is_unpaid_without_auto_join() {
let service = build_service_with_event_broker(team_repository, event_broker.clone());
service
- .create_team(&owner, "Personal Team", None)
+ .create_team(&owner, "Personal Team", None, true)
.await
.unwrap();
@@ -2132,7 +2140,7 @@ async fn team_event_create_failure_emits_nothing_and_broker_failure_is_swallowed
assert!(
service
- .create_team(&owner, "Failed Team", None)
+ .create_team(&owner, "Failed Team", None, true)
.await
.is_err()
);
@@ -2146,7 +2154,7 @@ async fn team_event_create_failure_emits_nothing_and_broker_failure_is_swallowed
let service = build_service_with_event_broker(team_repository, RecordingEventBroker::failing());
assert!(
service
- .create_team(&owner, "Successful Team", None)
+ .create_team(&owner, "Successful Team", None, true)
.await
.is_ok()
);
@@ -2831,7 +2839,10 @@ async fn create_team_sets_slug_from_name_or_uses_default() {
NoOpTeamCrmSettingsRepository,
);
- service.create_team(&owner, team_name, None).await.unwrap();
+ service
+ .create_team(&owner, team_name, None, true)
+ .await
+ .unwrap();
assert_eq!(
*create_team_calls.lock().unwrap(),
@@ -2872,7 +2883,7 @@ async fn create_team_creates_default_team_channel() {
);
service
- .create_team(&owner, "Requested Team Name", None)
+ .create_team(&owner, "Requested Team Name", None, true)
.await
.unwrap();
@@ -2930,7 +2941,7 @@ async fn create_team_fails_when_default_team_channel_creation_fails() {
.with_event_broker(event_broker.clone());
let result = service
- .create_team(&owner, "Failed Channel Team", None)
+ .create_team(&owner, "Failed Channel Team", None, true)
.await;
assert!(matches!(result, Err(CreateTeamError::StorageLayerError(_))));
@@ -2965,7 +2976,12 @@ async fn test_create_team_moves_github_installation_to_created_team() {
);
let created_team = service
- .create_team(&user_id, "New Team", Some(&"sub_test".parse().unwrap()))
+ .create_team(
+ &user_id,
+ "New Team",
+ Some(&"sub_test".parse().unwrap()),
+ true,
+ )
.await
.unwrap();
@@ -3004,7 +3020,12 @@ async fn test_create_team_propagates_github_installation_move_failure() {
);
let err = service
- .create_team(&user_id, "New Team", Some(&"sub_test".parse().unwrap()))
+ .create_team(
+ &user_id,
+ "New Team",
+ Some(&"sub_test".parse().unwrap()),
+ true,
+ )
.await
.err()
.unwrap();
@@ -3046,6 +3067,7 @@ async fn team_analytics_create_team_emits_created_event_with_team_id() {
&user_id,
"Analytics Team",
Some(&"sub_test".parse().unwrap()),
+ true,
)
.await
.unwrap();
@@ -3096,6 +3118,7 @@ async fn team_analytics_failure_is_swallowed_by_create_team() {
&user_id,
"Analytics Team",
Some(&"sub_test".parse().unwrap()),
+ true,
)
.await;
@@ -3133,6 +3156,7 @@ async fn team_analytics_create_team_does_not_emit_when_side_effect_fails() {
&user_id,
"Analytics Team",
Some(&"sub_test".parse().unwrap()),
+ true,
)
.await
.err()
@@ -7621,7 +7645,7 @@ async fn create_team_without_subscription_skips_convert_and_defaults_auto_join()
let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
let mark_sent_calls = Arc::new(Mutex::new(Vec::new()));
let team_repo = MockTeamRepository::new(Vec::new(), "Free Team", mark_sent_calls);
- let auto_join_toggle_calls = team_repo.auto_join_toggle_calls.clone();
+ let created_auto_join_domains = team_repo.created_auto_join_domains.clone();
let created_team_id = *team_repo.created_team.id();
let customer_repo = MockCustomerRepository::default();
@@ -7638,16 +7662,16 @@ async fn create_team_without_subscription_skips_convert_and_defaults_auto_join()
);
let team = service
- .create_team(&user_id, "Free Team", None)
+ .create_team(&user_id, "Free Team", None, true)
.await
.unwrap();
assert_eq!(*team.id(), created_team_id);
assert!(convert_calls.lock().unwrap().is_empty());
- // example.com is not a generic email domain, so auto-join defaults on.
+ // example.com is not a generic email domain, so the team is created with it.
assert_eq!(
- *auto_join_toggle_calls.lock().unwrap(),
- vec![created_team_id]
+ *created_auto_join_domains.lock().unwrap(),
+ vec![Some("example.com".to_owned())]
);
}
@@ -7656,8 +7680,7 @@ async fn create_team_with_subscription_converts_and_defaults_auto_join() {
let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
let mark_sent_calls = Arc::new(Mutex::new(Vec::new()));
let team_repo = MockTeamRepository::new(Vec::new(), "Paid Team", mark_sent_calls);
- let auto_join_toggle_calls = team_repo.auto_join_toggle_calls.clone();
- let created_team_id = *team_repo.created_team.id();
+ let created_auto_join_domains = team_repo.created_auto_join_domains.clone();
let customer_repo = MockCustomerRepository::default();
let convert_calls = customer_repo.convert_calls.clone();
@@ -7674,14 +7697,14 @@ async fn create_team_with_subscription_converts_and_defaults_auto_join() {
let subscription_id: stripe::SubscriptionId = "sub_test".parse().unwrap();
service
- .create_team(&user_id, "Paid Team", Some(&subscription_id))
+ .create_team(&user_id, "Paid Team", Some(&subscription_id), true)
.await
.unwrap();
assert_eq!(convert_calls.lock().unwrap().len(), 1);
assert_eq!(
- *auto_join_toggle_calls.lock().unwrap(),
- vec![created_team_id]
+ *created_auto_join_domains.lock().unwrap(),
+ vec![Some("example.com".to_owned())]
);
}
@@ -7690,6 +7713,32 @@ async fn create_team_generic_domain_does_not_default_auto_join() {
let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
let mark_sent_calls = Arc::new(Mutex::new(Vec::new()));
let team_repo = MockTeamRepository::new(Vec::new(), "Personal Team", mark_sent_calls);
+ let created_auto_join_domains = team_repo.created_auto_join_domains.clone();
+
+ let service = TeamServiceImpl::new(
+ team_repo,
+ MockCustomerRepository::default(),
+ RecordingChannelService::default(),
+ MockUserRolesAndPermissionsService::default(),
+ Arc::new(MockNotificationIngress::new(HashSet::new())),
+ NoOpCrmEnqueuer,
+ NoOpTeamCrmSettingsRepository,
+ );
+
+ service
+ .create_team(&user_id, "Personal Team", None, true)
+ .await
+ .unwrap();
+
+ assert_eq!(*created_auto_join_domains.lock().unwrap(), vec![None]);
+}
+
+#[tokio::test]
+async fn create_team_without_domain_join_leaves_auto_join_off() {
+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+ let mark_sent_calls = Arc::new(Mutex::new(Vec::new()));
+ let team_repo = MockTeamRepository::new(Vec::new(), "Closed Team", mark_sent_calls);
+ let created_auto_join_domains = team_repo.created_auto_join_domains.clone();
let auto_join_toggle_calls = team_repo.auto_join_toggle_calls.clone();
let service = TeamServiceImpl::new(
@@ -7703,10 +7752,11 @@ async fn create_team_generic_domain_does_not_default_auto_join() {
);
service
- .create_team(&user_id, "Personal Team", None)
+ .create_team(&user_id, "Closed Team", None, false)
.await
.unwrap();
+ assert_eq!(*created_auto_join_domains.lock().unwrap(), vec![None]);
assert!(auto_join_toggle_calls.lock().unwrap().is_empty());
}
diff --git a/crates/teams/src/inbound/axum_router.rs b/crates/teams/src/inbound/axum_router.rs
index 7c7c1579f5..a6b3f740ee 100644
--- a/crates/teams/src/inbound/axum_router.rs
+++ b/crates/teams/src/inbound/axum_router.rs
@@ -6,6 +6,8 @@ pub mod create_team;
pub mod delete_team;
/// Delete a team invite.
pub mod delete_team_invite;
+/// Email a new team's domain contacts that it exists.
+pub mod domain_notice;
/// Get a team by ID.
pub mod get_team;
/// Get all invites for a team.
diff --git a/crates/teams/src/inbound/axum_router/create_team.rs b/crates/teams/src/inbound/axum_router/create_team.rs
index 3359ba2dbd..4972ec73bd 100644
--- a/crates/teams/src/inbound/axum_router/create_team.rs
+++ b/crates/teams/src/inbound/axum_router/create_team.rs
@@ -14,6 +14,14 @@ use super::TeamRouterState;
pub struct CreateTeamRequest {
/// The name of the team
pub name: String,
+ /// Whether colleagues who sign up with the owner's work email domain join
+ /// the team automatically. Ignored for generic email providers.
+ #[serde(default = "default_allow_domain_join")]
+ pub allow_domain_join: bool,
+}
+
+fn default_allow_domain_join() -> bool {
+ true
}
/// Creates a new team.
@@ -45,7 +53,12 @@ pub async fn handler<T: TeamService, Eas: EntityAccessService, Auth: MacroAuthor
let team = state
.service
- .create_team(&user.macro_user_id, &req.name, subscription_id.as_ref())
+ .create_team(
+ &user.macro_user_id,
+ &req.name,
+ subscription_id.as_ref(),
+ req.allow_domain_join,
+ )
.await?;
Ok(Json(team))
diff --git a/crates/teams/src/inbound/axum_router/domain_notice.rs b/crates/teams/src/inbound/axum_router/domain_notice.rs
new file mode 100644
index 0000000000..2a637c5bd4
--- /dev/null
+++ b/crates/teams/src/inbound/axum_router/domain_notice.rs
@@ -0,0 +1,136 @@
+use std::sync::Arc;
+
+use axum::{
+ Json, Router,
+ extract::{FromRef, State},
+ http::StatusCode,
+ response::{IntoResponse, Response},
+ routing::post,
+};
+use entity_access::{
+ domain::{models::AdminTeamRole, ports::EntityAccessService},
+ inbound::axum_extractors::MacroUserTeamExtractorV2,
+};
+use macro_authorization::{MacroAuthorizationService, MacroAuthorizationState};
+use model_error_response::ErrorResponse;
+use rootcause::Report;
+
+use crate::domain::domain_notice::{DomainNoticeError, DomainNoticeService};
+
+/// Router state for the domain notice endpoint.
+pub struct DomainNoticeRouterState<D, Eas, Auth> {
+ /// The domain notice service.
+ pub service: Arc<D>,
+ /// The entity access service.
+ pub entity_access_service: Arc<Eas>,
+ /// State for request authorization.
+ pub authorization_state: MacroAuthorizationState<Auth>,
+}
+
+impl<D, Eas, Auth> Clone for DomainNoticeRouterState<D, Eas, Auth> {
+ fn clone(&self) -> Self {
+ Self {
+ service: self.service.clone(),
+ entity_access_service: self.entity_access_service.clone(),
+ authorization_state: self.authorization_state.clone(),
+ }
+ }
+}
+
+impl<D, Eas, Auth> FromRef<DomainNoticeRouterState<D, Eas, Auth>> for Arc<Eas> {
+ fn from_ref(state: &DomainNoticeRouterState<D, Eas, Auth>) -> Self {
+ state.entity_access_service.clone()
+ }
+}
+
+impl<D, Eas, Auth> FromRef<DomainNoticeRouterState<D, Eas, Auth>>
+ for MacroAuthorizationState<Auth>
+{
+ fn from_ref(state: &DomainNoticeRouterState<D, Eas, Auth>) -> Self {
+ state.authorization_state.clone()
+ }
+}
+
+/// Response for the domain notice endpoint.
+#[derive(serde::Serialize, utoipa::ToSchema)]
+pub struct SendDomainNoticeResponse {
+ /// How many colleagues were emailed by this call.
+ pub sent: u32,
+}
+
+/// Routes for the domain notice, to merge at the service root.
+pub fn domain_notice_router<D, Eas, Auth, S>(
+ state: DomainNoticeRouterState<D, Eas, Auth>,
+) -> Router<S>
+where
+ D: DomainNoticeService,
+ Eas: EntityAccessService,
+ Auth: MacroAuthorizationService,
+ S: Send + Sync + 'static,
+{
+ Router::new()
+ .route("/team/domain-notice", post(handler::<D, Eas, Auth>))
+ .with_state(state)
+}
+
+/// Emails the caller's contacts on the team's auto-join domain that the team
+/// exists, so they can sign up and join. Contacts already on Macro, on the
+/// team, invited, or emailed before are skipped, and a team emails at most 25
+/// people in total. Call it after sending the team's invites. Requires the
+/// caller to be an Admin or Owner of the team.
+#[utoipa::path(
+ post,
+ path = "/team/domain-notice",
+ operation_id = "send_team_domain_notice",
+ responses(
+ (status = 200, body = SendDomainNoticeResponse),
+ (status = 401, body = ErrorResponse),
+ (status = 403, body = ErrorResponse),
+ (status = 500, body = ErrorResponse),
+ ),
+)]
+#[tracing::instrument(skip_all, err)]
+pub async fn handler<
+ D: DomainNoticeService,
+ Eas: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
+ access: MacroUserTeamExtractorV2<AdminTeamRole, Eas, Auth>,
+ State(state): State<DomainNoticeRouterState<D, Eas, Auth>>,
+) -> Result<Json<SendDomainNoticeResponse>, DomainNoticeHttpError> {
+ let report = state
+ .service
+ .send_domain_notice(access.entity_access_receipt)
+ .await
+ .map_err(DomainNoticeHttpError)?;
+ Ok(Json(SendDomainNoticeResponse { sent: report.sent }))
+}
+
+/// An HTTP view of [`DomainNoticeError`].
+#[derive(Debug)]
+pub struct DomainNoticeHttpError(Report<DomainNoticeError>);
+
+impl std::fmt::Display for DomainNoticeHttpError {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(f, "{}", self.0.current_context())
+ }
+}
+
+impl IntoResponse for DomainNoticeHttpError {
+ fn into_response(self) -> Response {
+ let status = match self.0.current_context() {
+ DomainNoticeError::InvalidReceipt => StatusCode::BAD_REQUEST,
+ DomainNoticeError::Storage => {
+ tracing::error!(error = ?self.0, "domain notice failed");
+ StatusCode::INTERNAL_SERVER_ERROR
+ }
+ };
+ (
+ status,
+ Json(ErrorResponse {
+ message: self.0.current_context().to_string().into(),
+ }),
+ )
+ .into_response()
+ }
+}
diff --git a/crates/teams/src/inbound/axum_router/test.rs b/crates/teams/src/inbound/axum_router/test.rs
index e809915ca4..580dbe6c59 100644
--- a/crates/teams/src/inbound/axum_router/test.rs
+++ b/crates/teams/src/inbound/axum_router/test.rs
@@ -299,6 +299,7 @@ impl TeamService for FakeTeamService {
_user_id: &MacroUserIdStr<'_>,
_team_name: &str,
_subscription_id: Option<&stripe::SubscriptionId>,
+ _allow_domain_join: bool,
) -> Result<Team, CreateTeamError> {
panic!("unexpected create_team call")
}
diff --git a/crates/teams/src/outbound.rs b/crates/teams/src/outbound.rs
index 4952248e58..dc41d8f0a7 100644
--- a/crates/teams/src/outbound.rs
+++ b/crates/teams/src/outbound.rs
@@ -1,3 +1,4 @@
+pub mod colleague_directory;
pub mod contacts_enqueuer;
pub mod crm_enqueuer;
pub mod customer_repo;
diff --git a/crates/teams/src/outbound/colleague_directory.rs b/crates/teams/src/outbound/colleague_directory.rs
new file mode 100644
index 0000000000..5032c24501
--- /dev/null
+++ b/crates/teams/src/outbound/colleague_directory.rs
@@ -0,0 +1,28 @@
+//! [`ColleagueDirectory`] adapter backed by the contacts graph.
+
+use contacts::domain::ports::ContactsRepository;
+use macro_user_id::user_id::MacroUserIdStr;
+use rootcause::Report;
+
+use crate::domain::domain_notice::ColleagueDirectory;
+
+/// Reads a user's contacts from the contacts crate's repository.
+pub struct ContactsColleagueDirectory<R> {
+ repository: R,
+}
+
+impl<R> ContactsColleagueDirectory<R> {
+ /// Creates the directory over the contacts repository.
+ pub fn new(repository: R) -> Self {
+ Self { repository }
+ }
+}
+
+impl<R: ContactsRepository> ColleagueDirectory for ContactsColleagueDirectory<R> {
+ async fn contacts(
+ &self,
+ user_id: &MacroUserIdStr<'_>,
+ ) -> Result<Vec<MacroUserIdStr<'static>>, Report> {
+ self.repository.get_contacts(user_id.clone()).await
+ }
+}
diff --git a/crates/teams/src/outbound/join_announcement_repo.rs b/crates/teams/src/outbound/join_announcement_repo.rs
index 298693bfab..df0bbe65d9 100644
--- a/crates/teams/src/outbound/join_announcement_repo.rs
+++ b/crates/teams/src/outbound/join_announcement_repo.rs
@@ -36,6 +36,7 @@ impl JoinAnnouncementRepository for JoinAnnouncementRepositoryImpl {
&self,
team_id: Uuid,
candidates: &[MacroUserIdStr<'static>],
+ team_limit: u32,
) -> Result<Vec<ClaimedJoinEmail>, Report<JoinAnnouncementError>> {
let by_email: HashMap<&str, &MacroUserIdStr<'static>> = candidates
.iter()
@@ -49,6 +50,17 @@ impl JoinAnnouncementRepository for JoinAnnouncementRepositoryImpl {
.iter()
.map(|candidate| candidate.to_string())
.collect();
+ let mut transaction = self
+ .pool
+ .begin()
+ .await
+ .context(JoinAnnouncementError::Storage)?;
+ // Serialize claims per team, so concurrent announcements can't each read the same
+ // count and together exceed `team_limit`.
+ sqlx::query!("SELECT id FROM team WHERE id = $1 FOR UPDATE", team_id)
+ .fetch_optional(&mut *transaction)
+ .await
+ .context(JoinAnnouncementError::Storage)?;
let rows = sqlx::query!(
r#"
WITH claimed AS (
@@ -67,6 +79,19 @@ impl JoinAnnouncementRepository for JoinAnnouncementRepositoryImpl {
SELECT 1 FROM team_invite ti
WHERE ti.team_id = t.id AND ti.email = c.email
)
+ AND NOT EXISTS (
+ SELECT 1 FROM "User" u WHERE lower(u.email) = lower(c.email)
+ )
+ AND NOT EXISTS (
+ SELECT 1 FROM team_joined_macro_email e
+ WHERE e.team_id = t.id AND e.email = c.email
+ )
+ ORDER BY c.email
+ LIMIT GREATEST(
+ $4::bigint
+ - (SELECT count(*) FROM team_joined_macro_email e WHERE e.team_id = $1),
+ 0
+ )
ON CONFLICT (team_id, email) DO NOTHING
RETURNING email
)
@@ -77,10 +102,15 @@ impl JoinAnnouncementRepository for JoinAnnouncementRepositoryImpl {
team_id,
&emails[..],
&user_ids[..],
+ i64::from(team_limit),
)
- .fetch_all(&self.pool)
+ .fetch_all(&mut *transaction)
.await
.context(JoinAnnouncementError::Storage)?;
+ transaction
+ .commit()
+ .await
+ .context(JoinAnnouncementError::Storage)?;
Ok(rows
.into_iter()
.filter_map(|row| {
diff --git a/crates/teams/src/outbound/join_announcement_repo/test.rs b/crates/teams/src/outbound/join_announcement_repo/test.rs
index 78b4a7a4fb..166a2eafa2 100644
--- a/crates/teams/src/outbound/join_announcement_repo/test.rs
+++ b/crates/teams/src/outbound/join_announcement_repo/test.rs
@@ -22,7 +22,7 @@ fn team1_claims(emails: &[&str]) -> Vec<(String, String)> {
}
async fn claim(repo: &JoinAnnouncementRepositoryImpl, emails: &[&str]) -> Vec<(String, String)> {
- repo.claim(TEAM1, &users(emails))
+ repo.claim(TEAM1, &users(emails), 25)
.await
.unwrap()
.into_iter()
@@ -124,8 +124,8 @@ async fn concurrent_claims_never_share_an_address(pool: PgPool) {
let candidates: Vec<MacroUserIdStr<'static>> = emails.iter().map(|email| user(email)).collect();
let (left, right) = tokio::join!(
- left_repo.claim(TEAM1, &candidates),
- right_repo.claim(TEAM1, &candidates)
+ left_repo.claim(TEAM1, &candidates, 100),
+ right_repo.claim(TEAM1, &candidates, 100)
);
let left: HashSet<String> = left
@@ -178,3 +178,86 @@ async fn deleting_the_team_deletes_its_claims(pool: PgPool) {
assert!(ledger(&pool).await.is_empty());
}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("teams"))
+)]
+async fn people_already_on_macro_are_not_claimed(pool: PgPool) {
+ set_auto_join_domain(&pool, "user.com").await;
+ let macro_user_id = Uuid::from_u128(0xe1);
+ sqlx::query!(
+ r#"INSERT INTO macro_user (id, username, email, stripe_customer_id) VALUES ($1, $2, $2, 'cus_existing')"#,
+ macro_user_id,
+ )
+ .execute(&pool)
+ .await
+ .unwrap();
+ sqlx::query!(
+ r#"INSERT INTO "User" (id, email, macro_user_id) VALUES ($1, $2, $3)"#,
+ macro_user_id,
+ )
+ .execute(&pool)
+ .await
+ .unwrap();
+ let repo = JoinAnnouncementRepositoryImpl::new(pool.clone());
+
+ assert_eq!(
+ claim(&repo, &["[email protected]", "[email protected]"]).await,
+ team1_claims(&["[email protected]"])
+ );
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("teams"))
+)]
+async fn claims_stop_at_the_team_limit_across_calls(pool: PgPool) {
+ set_auto_join_domain(&pool, "user.com").await;
+ let repo = JoinAnnouncementRepositoryImpl::new(pool.clone());
+
+ let first = repo
+ .claim(TEAM1, &users(&["[email protected]", "[email protected]"]), 3)
+ .await
+ .unwrap();
+ let second = repo
+ .claim(
+ TEAM1,
+ 3,
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(first.len(), 2);
+ assert_eq!(second.len(), 1);
+ assert_eq!(
+ ledger(&pool).await,
+ );
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("teams"))
+)]
+async fn concurrent_claims_share_the_team_limit(pool: PgPool) {
+ set_auto_join_domain(&pool, "user.com").await;
+ let left_repo = JoinAnnouncementRepositoryImpl::new(pool.clone());
+ let right_repo = JoinAnnouncementRepositoryImpl::new(pool.clone());
+ let left_emails: Vec<String> = (0..20).map(|i| format!("left{i:02}@user.com")).collect();
+ let right_emails: Vec<String> = (0..20).map(|i| format!("right{i:02}@user.com")).collect();
+ let left_candidates: Vec<_> = left_emails.iter().map(|email| user(email)).collect();
+ let right_candidates: Vec<_> = right_emails.iter().map(|email| user(email)).collect();
+
+ let (left, right) = tokio::join!(
+ left_repo.claim(TEAM1, &left_candidates, 25),
+ right_repo.claim(TEAM1, &right_candidates, 25)
+ );
+
+ assert_eq!(left.unwrap().len() + right.unwrap().len(), 25);
+ assert_eq!(ledger(&pool).await.len(), 25);
+}
diff --git a/crates/teams/src/outbound/team_repo.rs b/crates/teams/src/outbound/team_repo.rs
index 647c323fa2..a7b510e34b 100644
--- a/crates/teams/src/outbound/team_repo.rs
+++ b/crates/teams/src/outbound/team_repo.rs
@@ -80,6 +80,7 @@ impl TeamRepositoryImpl {
team_slug: &str,
subscription_id: Option<&stripe::SubscriptionId>,
owner_plan: SeatPlan,
+ auto_join_domain: Option<&str>,
) -> Result<Team, sqlx::Error> {
let mut transaction = self.pool.begin().await?;
@@ -87,9 +88,12 @@ impl TeamRepositoryImpl {
let team = sqlx::query!(
r#"
- INSERT INTO team (id, name, slug, owner_id, seat_count, subscription_id, paying)
- VALUES ($1, $2, $3, $4, 1, $5, $6)
+ INSERT INTO team (
+ id, name, slug, owner_id, seat_count, subscription_id, paying, auto_join_domain
+ )
+ VALUES ($1, $2, $3, $4, 1, $5, $6, $7)
RETURNING id, name, slug, owner_id, enterprise, allow_non_admin_invites,
+ auto_join_domain,
default_link_share as "default_link_share: LinkShare",
language as "language: Language"
"#,
@@ -99,6 +103,7 @@ impl TeamRepositoryImpl {
user_id.as_ref(),
subscription_id.map(|s| s.to_string()),
subscription_id.is_some(),
+ auto_join_domain,
)
.try_map(|row| {
Ok(Team {
@@ -110,8 +115,7 @@ impl TeamRepositoryImpl {
.into_owned(),
// New teams have no team_crm_settings row yet.
crm_enabled: false,
- // New teams start without an auto-join domain.
- auto_join_domain: None,
+ auto_join_domain: row.auto_join_domain,
enterprise: row.enterprise,
allow_non_admin_invites: row.allow_non_admin_invites,
default_link_share: row.default_link_share,
@@ -350,14 +354,22 @@ impl TeamRepository for TeamRepositoryImpl {
team_slug: &str,
subscription_id: Option<&stripe::SubscriptionId>,
owner_plan: SeatPlan,
+ auto_join_domain: Option<&str>,
) -> Result<Team, CreateTeamError> {
if team_name.is_empty() || team_name.len() > 50 {
return Err(CreateTeamError::InvalidTeamName(team_name.to_string()));
}
- self.create_team_inner(user_id, team_name, team_slug, subscription_id, owner_plan)
- .await
- .map_err(|e| e.into())
+ self.create_team_inner(
+ user_id,
+ team_name,
+ team_slug,
+ subscription_id,
+ owner_plan,
+ auto_join_domain,
+ )
+ .await
+ .map_err(|e| e.into())
}
#[tracing::instrument(skip(self), err)]
diff --git a/crates/teams/src/outbound/team_repo/test.rs b/crates/teams/src/outbound/team_repo/test.rs
index c98f2db73d..81e79cc8fa 100644
--- a/crates/teams/src/outbound/team_repo/test.rs
+++ b/crates/teams/src/outbound/team_repo/test.rs
@@ -180,10 +180,12 @@ async fn test_create_team(pool: Pool<Postgres>) -> anyhow::Result<()> {
"PRODUCT_TEAM",
Some(&"sub_test".parse().unwrap()),
SeatPlan::Premium,
+ Some("user.com"),
)
.await?;
assert!(!result.id.to_string().is_empty());
+ assert_eq!(result.auto_join_domain(), Some("user.com"));
assert_eq!(result.name, "Product Team");
assert_eq!(result.slug, "PRODUCT_TEAM");
assert_eq!(result.owner_id.0.as_ref(), "macro|[email protected]");
@@ -191,7 +193,7 @@ async fn test_create_team(pool: Pool<Postgres>) -> anyhow::Result<()> {
// Create team with too large a name
let err = team_repo
- .create_team(&user_id, "12345678901234567890123456789012345678901234567890123456789000000000000000000000000000000000000000000000", "MACRO", Some(&"sub_test".parse().unwrap()), SeatPlan::Premium)
+ .create_team(&user_id, "12345678901234567890123456789012345678901234567890123456789000000000000000000000000000000000000000000000", "MACRO", Some(&"sub_test".parse().unwrap()), SeatPlan::Premium, None)
.await
.err()
.unwrap();
@@ -236,6 +238,7 @@ async fn test_move_github_app_installation_to_team_moves_existing_user_rows(
"GITHUB_OWNER_TEAM",
Some(&"sub_test".parse().unwrap()),
SeatPlan::Premium,
+ None,
)
.await?;
let team_id = team.id().to_string();
@@ -359,6 +362,7 @@ async fn test_move_github_app_installation_to_team_noops_when_user_has_no_rows(
"GITHUB_OWNER_TEAM",
Some(&"sub_test".parse().unwrap()),
SeatPlan::Premium,
+ None,
)
.await?;
diff --git a/docs/agent-guide/login.md b/docs/agent-guide/login.md
index 3f1cd96d33..e484ee2300 100644
--- a/docs/agent-guide/login.md
+++ b/docs/agent-guide/login.md
@@ -244,12 +244,23 @@ with native preference for known overlapping providers and Slack alias deduplica
Connection status failures have an explicit retry; they must not prevent
independent providers such as native GitHub from connecting. Verify unknown
status never launches a duplicate OAuth flow and continuation remains possible.
-Team setup retains existing membership, invite acceptance, domain suggestions,
-and editable invite recipients; submitting the form sends real invitations.
+Someone already on a team when they leave the tools step (joined by invite
+link or by domain) never sees the team step: Continue goes to the plan step, or
+finishes for a licensed member, and Back from plan returns to tools. Pending
+email invites still show on the team step for acceptance, and a team created
+there shows the **You're on <team>** confirmation. Team setup retains invite
+acceptance, domain suggestions, and editable invite recipients; submitting the
+form sends real invitations.
On the create-team form, type a workspace name and edit a teammate address,
then allow onboarding/contacts queries to refresh. The same inputs must retain
their values and focus as suggestions arrive or a background request fails.
Pending queries must show local loading states without suspending the flow.
+When the server suggests a work domain, the create form has no Skip button and
+shows an **Allow @domain emails to join** switch, on by default. Creating the
+team with it on sets the team's auto-join domain and, after the invites, emails
+up to 25 of the creator's same-domain contacts who are not on Macro or invited
+yet (`POST /team/domain-notice`). Personal-domain accounts keep Skip and see no
+switch.
Members with an active or trialing license, including a license from their team,
finish directly from the team step without visiting the plan page. The Continue
diff --git a/docs/runbooks/slack-archive-import-contract.md b/docs/runbooks/slack-archive-import-contract.md
index 5b31e5e13f..5d250a456d 100644
--- a/docs/runbooks/slack-archive-import-contract.md
+++ b/docs/runbooks/slack-archive-import-contract.md
@@ -394,8 +394,7 @@ current batch. Preserve `orphaned_thread_ts` when missing/skipped, without a lat
repair promise. Convert reactions, dedupe mapped reactors, and use source message
time when reaction time is absent. Ignore files/attachments and skip empty
converted messages. No live-message notifications, activity rows, Kafka, bots,
-contacts, sharing changes or realtime sends. The colleague join email is the one
-deliberate exception. Historical activity timestamps use
+contacts, sharing changes, emails or realtime sends. Historical activity timestamps use
`GREATEST` so newer live activity never regresses.
`SearchBackfillClient` submits only affected channel IDs (empty scope means no
@@ -412,29 +411,6 @@ Staging may expire after 14 days. Job/staging cleanup must not delete user-visib
history, long-lived dedupe mappings, canonical reservations or source bindings.
Team/channel deletion semantics belong to owning schema migrations.
-## Colleague join email
-
-`SLACK_IMPORT_JOIN_EMAIL_ENABLED` gates this email and defaults to off. When it
-is on, the worker sends the email after a conversation binds. That send runs on
-every bind, including a retry of the same attempt and a later re-import. Public
-channels, private channels, DMs, and group DMs all participate.
-
-A member is eligible only when all four of these conditions hold.
-
-- The team has `auto_join_domain` set.
-- The member's email domain equals the team's `auto_join_domain`.
-- The member is not a `team_user`.
-- The member has no pending `team_invite`.
-
-`team_joined_macro_email` records one row per team and email. The worker sends
-the email at most once for that pair, including across channels and later
-imports. If the enqueue fails, the worker removes the row so a later import can
-try again. x is the importing admin. The email shows x's Slack display name when
-the export has one, and x's email otherwise.
-
-The worker logs a send failure and continues. The failure does not change the
-import result, and it does not retry the import.
-
## Native links and deferred source references
The pure `slack::mrkdwn::MrkdwnConverter` retains its existing `message`/`convert`
diff --git a/infra/stacks/cloud-storage-service/SLACK_IMPORT_ROLLOUT.md b/infra/stacks/cloud-storage-service/SLACK_IMPORT_ROLLOUT.md
index a3dfea39f9..aabc77ce5b 100644
--- a/infra/stacks/cloud-storage-service/SLACK_IMPORT_ROLLOUT.md
+++ b/infra/stacks/cloud-storage-service/SLACK_IMPORT_ROLLOUT.md
@@ -40,18 +40,15 @@ from the runtime `SLACK_IMPORT_ENABLED` intake flag.
4. Infrastructure supplies `ENVIRONMENT`, `UPLOAD_STAGING_BUCKET` (bulk-upload's
bucket output), `OVERRIDE_SLACK_IMPORT_QUEUE`, `OVERRIDE_SLACK_IMPORT_DLQ`,
`OVERRIDE_CONNECTION_GATEWAY_URL`, `OVERRIDE_SEARCH_PROCESSING_SERVICE_URL`,
- `DD_SERVICE`, `DD_ENV`, and `SLACK_IMPORT_JOIN_EMAIL_ENABLED`.
- `SLACK_IMPORT_JOIN_EMAIL_ENABLED` comes from the stack config key
- `slack_import_join_email_enabled`, which defaults to false. Leave that key
- out of the Doppler sync. A missing Doppler key fails task start. The task
- definition sets the value from stack config. Document/register the
+ `DD_SERVICE`, and `DD_ENV`. A missing Doppler key fails task start.
+ Document/register the
infrastructure-supplied names in Doppler's service configuration inventory,
but do not add competing overrides. There is no `SEARCH_SERVICE_URL`
dependency. No Slack OAuth/bot credentials are needed.
5. Ensure private-subnet egress can reach MacroDB, AWS endpoints and the gateway.
The task role receives the `SlackImportQueue` worker policy only. That policy
- allows reading Slack staging objects, operating the import main queue and DLQ,
- and `sqs:SendMessage` on the notification ingress queue. The task role does
+ allows reading Slack staging objects and operating the import main queue and
+ DLQ. The worker sends no emails or notifications. The task role does
not inherit DSS's permissions. The execution role reads the worker's Doppler
sync, not the task role.
@@ -82,18 +79,6 @@ instead, so maintenance and DLQ reconciliation continue.
Then set `SLACK_IMPORT_ENABLED=true` and redeploy the worker before opening
admission. This flag pauses claims/outbox sends, **not** maintenance/DLQ
reconciliation; even paused tasks require working DB/queue/search configuration.
-- Colleague join email stays off until you set
- `slack_import_join_email_enabled`. From `infra/stacks/cloud-storage-service/`,
- set the stack config, then deploy that stack through the normal deployment
- workflow:
-
- ```sh
- pulumi config set cloud-storage-service:slack_import_join_email_enabled true --stack <dev-or-prod>
- ```
-
- The `sqs:SendMessage` grant on the notification ingress queue is already on
- the worker policy. The config key only changes `SLACK_IMPORT_JOIN_EMAIL_ENABLED`
- in the task definition.
- Monitor ECS deployment failure alarms, task OOM/restarts, queue age, the existing
DLQ alarm, import leases and search receipts. Pause admission and set the worker
flag false to stop new imports; do not purge queues or delete imported data.
@@ -130,6 +115,5 @@ Local env wiring uses `bulk-upload-staging`, full LocalStack queue URL overrides
`http://connection-gateway:8080`, and
`http://search-processing-service:8080`. The local `INTERNAL_API_KEY` matches
search-processing's internal auth key. The default worker flag is false unless
-explicitly overridden. `SLACK_IMPORT_JOIN_EMAIL_ENABLED` also defaults to false
-unless the env file sets it to `true`. Do not inject a deployed
+explicitly overridden. Do not inject a deployed
`APP_SECRETS_JSON` locally.
diff --git a/infra/stacks/cloud-storage-service/index.ts b/infra/stacks/cloud-storage-service/index.ts
index a99ae5dc1d..81b7f323ec 100644
--- a/infra/stacks/cloud-storage-service/index.ts
+++ b/infra/stacks/cloud-storage-service/index.ts
@@ -209,7 +209,6 @@ const bulkUploadBucketName = bulkUploadStack
const slackImportQueue = new SlackImportQueue(`slack-import-${stack}`, {
stagingBucketArn: pulumi.interpolate`arn:aws:s3:::${bulkUploadBucketName}`,
- notificationIngressQueueArn,
tags,
});
diff --git a/infra/stacks/cloud-storage-service/slack-import-queue.test.ts b/infra/stacks/cloud-storage-service/slack-import-queue.test.ts
index 2aaf57e234..9593e19012 100644
--- a/infra/stacks/cloud-storage-service/slack-import-queue.test.ts
+++ b/infra/stacks/cloud-storage-service/slack-import-queue.test.ts
@@ -5,8 +5,6 @@ const resources: pulumi.runtime.MockResourceArgs[] = [];
const bucketArn = 'arn:aws:s3:::bulk-upload-staging-dev';
const mainArn = 'arn:aws:sqs:us-east-1:123456789012:slack-import-queue-dev';
const dlqArn = 'arn:aws:sqs:us-east-1:123456789012:slack-import-dlq-dev';
-const notificationIngressQueueArn =
- 'arn:aws:sqs:us-east-1:123456789012:notification-ingress';
beforeAll(async () => {
pulumi.runtime.setAllConfig({ 'aws:region': 'us-east-1' });
@@ -38,7 +36,6 @@ beforeAll(async () => {
const { SlackImportQueue } = await import('./slack-import-queue');
new SlackImportQueue('slack-import-dev', {
stagingBucketArn: bucketArn,
- notificationIngressQueueArn,
tags: {},
});
await pulumi.runtime.waitForRPCs();
@@ -126,11 +123,6 @@ describe('Slack import queue and IAM', () => {
Action: ['sqs:SendMessage'],
Resource: [mainArn],
},
- {
- Effect: 'Allow',
- Action: ['sqs:SendMessage'],
- Resource: [notificationIngressQueueArn],
- },
],
});
expect(JSON.stringify(policy)).not.toContain('sqs:*');
diff --git a/infra/stacks/cloud-storage-service/slack-import-queue.ts b/infra/stacks/cloud-storage-service/slack-import-queue.ts
index 11e487869d..8348ecfa41 100644
--- a/infra/stacks/cloud-storage-service/slack-import-queue.ts
+++ b/infra/stacks/cloud-storage-service/slack-import-queue.ts
@@ -4,7 +4,6 @@ import { Queue } from '../../packages/resources/src/resources/queue';
interface SlackImportQueueArgs {
stagingBucketArn: pulumi.Input<string>;
- notificationIngressQueueArn: pulumi.Input<string>;
tags: { [key: string]: string };
}
@@ -17,11 +16,7 @@ export class SlackImportQueue extends pulumi.ComponentResource {
constructor(
name: string,
- {
- stagingBucketArn,
- notificationIngressQueueArn,
- tags,
- }: SlackImportQueueArgs,
+ { stagingBucketArn, tags }: SlackImportQueueArgs,
opts?: pulumi.ComponentResourceOptions
) {
super('my:components:SlackImportQueue', name, {}, opts);
@@ -82,11 +77,6 @@ export class SlackImportQueue extends pulumi.ComponentResource {
Action: ['sqs:SendMessage'],
Resource: [this.queue.arn],
},
- {
- Effect: 'Allow',
- Action: ['sqs:SendMessage'],
- Resource: [notificationIngressQueueArn],
- },
],
},
tags,
diff --git a/packages/sdk-docs/reference/generated/auth/types.gen/README.md b/packages/sdk-docs/reference/generated/auth/types.gen/README.md
index 89c54d5e64..57e95fa1a0 100644
--- a/packages/sdk-docs/reference/generated/auth/types.gen/README.md
+++ b/packages/sdk-docs/reference/generated/auth/types.gen/README.md
@@ -556,6 +556,7 @@
- [SavedAgentApiKey](type-aliases/SavedAgentApiKey.md)
- [ScheduledSeatPlan](type-aliases/ScheduledSeatPlan.md)
- [SeatPlan](type-aliases/SeatPlan.md)
+- [SendDomainNoticeResponse](type-aliases/SendDomainNoticeResponse.md)
- [SendInviteBody](type-aliases/SendInviteBody.md)
- [SendMobileWelcomeEmailData](type-aliases/SendMobileWelcomeEmailData.md)
- [SendMobileWelcomeEmailError](type-aliases/SendMobileWelcomeEmailError.md)
@@ -569,6 +570,11 @@
- [SendReferralCodeErrors](type-aliases/SendReferralCodeErrors.md)
- [SendReferralCodeResponse](type-aliases/SendReferralCodeResponse.md)
- [SendReferralCodeResponses](type-aliases/SendReferralCodeResponses.md)
+- [SendTeamDomainNoticeData](type-aliases/SendTeamDomainNoticeData.md)
+- [SendTeamDomainNoticeError](type-aliases/SendTeamDomainNoticeError.md)
+- [SendTeamDomainNoticeErrors](type-aliases/SendTeamDomainNoticeErrors.md)
+- [SendTeamDomainNoticeResponse](type-aliases/SendTeamDomainNoticeResponse.md)
+- [SendTeamDomainNoticeResponses](type-aliases/SendTeamDomainNoticeResponses.md)
- [SessionCreationData](type-aliases/SessionCreationData.md)
- [SessionCreationError](type-aliases/SessionCreationError.md)
- [SessionCreationErrors](type-aliases/SessionCreationErrors.md)
diff --git a/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/CreateTeamRequest.md b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/CreateTeamRequest.md
index f29876ef8c..3e2a1a4611 100644
--- a/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/CreateTeamRequest.md
+++ b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/CreateTeamRequest.md
@@ -1,6 +1,6 @@
# Type Alias: CreateTeamRequest
-> **CreateTeamRequest** = \{ `name`: `string`; \}
+> **CreateTeamRequest** = \{ `allow_domain_join?`: `boolean`; `name`: `string`; \}
The request body to create a new team
@@ -8,4 +8,5 @@ The request body to create a new team
| Property | Type | Description |
| ------ | ------ | ------ |
+| <a id="property-allow_domain_join"></a> `allow_domain_join?` | `boolean` | Whether colleagues who sign up with the owner's work email domain join the team automatically. Ignored for generic email providers. |
| <a id="property-name"></a> `name` | `string` | The name of the team |
diff --git a/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/SendDomainNoticeResponse.md b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/SendDomainNoticeResponse.md
new file mode 100644
index 0000000000..3352d9e473
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/SendDomainNoticeResponse.md
@@ -0,0 +1,11 @@
+# Type Alias: SendDomainNoticeResponse
+
+> **SendDomainNoticeResponse** = \{ `sent`: `number`; \}
+
+Response for the domain notice endpoint.
+
+## Properties
+
+| Property | Type | Description |
+| ------ | ------ | ------ |
+| <a id="property-sent"></a> `sent` | `number` | How many colleagues were emailed by this call. |
diff --git a/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/SendTeamDomainNoticeData.md b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/SendTeamDomainNoticeData.md
new file mode 100644
index 0000000000..fdac458a72
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/SendTeamDomainNoticeData.md
@@ -0,0 +1,12 @@
+# Type Alias: SendTeamDomainNoticeData
+
+> **SendTeamDomainNoticeData** = \{ `body?`: `never`; `path?`: `never`; `query?`: `never`; `url`: `"/team/domain-notice"`; \}
+
+## Properties
+
+| Property | Type |
+| ------ | ------ |
+| <a id="property-body"></a> `body?` | `never` |
+| <a id="property-path"></a> `path?` | `never` |
+| <a id="property-query"></a> `query?` | `never` |
+| <a id="property-url"></a> `url` | `"/team/domain-notice"` |
diff --git a/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/SendTeamDomainNoticeError.md b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/SendTeamDomainNoticeError.md
new file mode 100644
index 0000000000..f5ece26904
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/SendTeamDomainNoticeError.md
@@ -0,0 +1,3 @@
+# Type Alias: SendTeamDomainNoticeError
+
+> **SendTeamDomainNoticeError** = [`SendTeamDomainNoticeErrors`](SendTeamDomainNoticeErrors.md)\[keyof [`SendTeamDomainNoticeErrors`](SendTeamDomainNoticeErrors.md)\]
diff --git a/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/SendTeamDomainNoticeErrors.md b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/SendTeamDomainNoticeErrors.md
new file mode 100644
index 0000000000..834fc6c90f
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/SendTeamDomainNoticeErrors.md
@@ -0,0 +1,11 @@
+# Type Alias: SendTeamDomainNoticeErrors
+
+> **SendTeamDomainNoticeErrors** = \{ `401`: [`ErrorResponse`](ErrorResponse.md); `403`: [`ErrorResponse`](ErrorResponse.md); `500`: [`ErrorResponse`](ErrorResponse.md); \}
+
+## Properties
+
+| Property | Type |
+| ------ | ------ |
+| <a id="property-401"></a> `401` | [`ErrorResponse`](ErrorResponse.md) |
+| <a id="property-403"></a> `403` | [`ErrorResponse`](ErrorResponse.md) |
+| <a id="property-500"></a> `500` | [`ErrorResponse`](ErrorResponse.md) |
diff --git a/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/SendTeamDomainNoticeResponse.md b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/SendTeamDomainNoticeResponse.md
new file mode 100644
index 0000000000..51a579f455
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/SendTeamDomainNoticeResponse.md
@@ -0,0 +1,3 @@
+# Type Alias: SendTeamDomainNoticeResponse
+
+> **SendTeamDomainNoticeResponse** = [`SendTeamDomainNoticeResponses`](SendTeamDomainNoticeResponses.md)\[keyof [`SendTeamDomainNoticeResponses`](SendTeamDomainNoticeResponses.md)\]
diff --git a/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/SendTeamDomainNoticeResponses.md b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/SendTeamDomainNoticeResponses.md
new file mode 100644
index 0000000000..5b41897a49
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/SendTeamDomainNoticeResponses.md
@@ -0,0 +1,9 @@
+# Type Alias: SendTeamDomainNoticeResponses
+
+> **SendTeamDomainNoticeResponses** = \{ `200`: [`SendDomainNoticeResponse`](SendDomainNoticeResponse.md); \}
+
+## Properties
+
+| Property | Type |
+| ------ | ------ |
+| <a id="property-200"></a> `200` | [`SendDomainNoticeResponse`](SendDomainNoticeResponse.md) |
diff --git a/packages/sdk/generated/auth/index.ts b/packages/sdk/generated/auth/index.ts
index a438890eb6..9311612973 100644
--- a/packages/sdk/generated/auth/index.ts
+++ b/packages/sdk/generated/auth/index.ts
@@ -1,4 +1,4 @@
// This file is auto-generated by @hey-api/openapi-ts
export { type Options, Sdk } from './sdk.gen';
-export type { AbGroup, AgentApiKey, AgentApiKeyProvider, AiBillingErrorBody, AppleLoginData, AppleLoginError, AppleLoginErrors, AppleLoginRequest, AppleLoginResponse, AppleLoginResponses, AutoReloadDefaults, AutoReloadMonthlyBudget, AutoReloadSnapshot, CancelCodexLoginData, CancelCodexLoginResponse, CancelCodexLoginResponses, ChangePlanData, ChangePlanError, ChangePlanErrors, ChangePlanRequest, ChangePlanResponse, ChangePlanResponse2, ChangePlanResponses, CheckGithubLinkStatusData, CheckGithubLinkStatusError, CheckGithubLinkStatusErrors, CheckGithubLinkStatusResponse, CheckGithubLinkStatusResponses, CheckGmailLinkStatusData, CheckGmailLinkStatusError, CheckGmailLinkStatusErrors, CheckGmailLinkStatusResponse, CheckGmailLinkStatusResponses, CheckoutSessionMetadata, CheckoutSessionV2Response, ClientOptions, CodexConfigRequest, CodexConnectionStatus, CodexEnvironment, CodexEnvironmentRepository, CodexLoginPoll, CodexLoginStart, CodexLoginState, ConfigureCodexData, ConfigureCodexResponse, ConfigureCodexResponses, CreateAccountMergeRequest, CreateAiCreditCheckoutData, CreateAiCreditCheckoutError, CreateAiCreditCheckoutErrors, CreateAiCreditCheckoutResponse, CreateAiCreditCheckoutResponses, CreateCheckoutSessionV2Data, CreateCheckoutSessionV2Error, CreateCheckoutSessionV2Errors, CreateCheckoutSessionV2Request, CreateCheckoutSessionV2Response, CreateCheckoutSessionV2Responses, CreatedTeamInviteLinkResponse, CreateGtmInviteLinkData, CreateGtmInviteLinkError, CreateGtmInviteLinkErrors, CreateGtmInviteLinkRequest, CreateGtmInviteLinkResponse, CreateGtmInviteLinkResponses, CreateInProgressLinkData, CreateInProgressLinkError, CreateInProgressLinkErrors, CreateInProgressLinkResponse, CreateInProgressLinkResponse2, CreateInProgressLinkResponses, CreateMergeRequestData, CreateMergeRequestError, CreateMergeRequestErrors, CreateMergeRequestResponse, CreateMergeRequestResponses, CreatePortalSessionData, CreatePortalSessionError, CreatePortalSessionErrors, CreatePortalSessionRequest, CreatePortalSessionResponse, CreatePortalSessionResponses, CreateTeamData, CreateTeamError, CreateTeamErrors, CreateTeamInviteLinkData, CreateTeamInviteLinkError, CreateTeamInviteLinkErrors, CreateTeamInviteLinkResponse, CreateTeamInviteLinkResponses, CreateTeamRequest, CreateTeamResponse, CreateTeamResponses, CreditCheckoutRequestBody, CreditCheckoutResponse, CreditPurchaseRequestBody, CreditPurchaseResponse, CreditPurchaseSnapshot, CreditPurchaseStatus, CurrentSystemStatus, CursorApiKeyStatus, CursorModelOption, CursorModelsResponse, DeleteAgentApiKeyData, DeleteAgentApiKeyError, DeleteAgentApiKeyErrors, DeleteAgentApiKeyResponse, DeleteAgentApiKeyResponses, DeleteCursorApiKeyData, DeleteCursorApiKeyError, DeleteCursorApiKeyErrors, DeleteCursorApiKeyResponse, DeleteCursorApiKeyResponses, DeleteGithubLinkData, DeleteGithubLinkError, DeleteGithubLinkErrors, DeleteGithubLinkResponse, DeleteGithubLinkResponses, DeleteTeamData, DeleteTeamError, DeleteTeamErrors, DeleteTeamInviteHandlerData, DeleteTeamInviteHandlerError, DeleteTeamInviteHandlerErrors, DeleteTeamInviteHandlerResponses, DeleteTeamInviteLinkData, DeleteTeamInviteLinkError, DeleteTeamInviteLinkErrors, DeleteTeamInviteLinkResponse, DeleteTeamInviteLinkResponses, DeleteTeamResponses, DeleteUserData, DeleteUserError, DeleteUserErrors, DeleteUserResponse, DeleteUserResponses, DenyReason, DisconnectCodexData, DisconnectCodexResponse, DisconnectCodexResponses, EmailConnectionProviders, EmailConnectionProvidersData, EmailConnectionProvidersError, EmailConnectionProvidersErrors, EmailConnectionProvidersResponse, EmailConnectionProvidersResponses, EmptyResponse, EnrichedGithubPullRequest, EnrichGithubPullRequestsData, EnrichGithubPullRequestsError, EnrichGithubPullRequestsErrors, EnrichGithubPullRequestsProxyRequest, EnrichGithubPullRequestsResponse, EnrichGithubPullRequestsResponse2, EnrichGithubPullRequestsResponses, ErrorResponse, GenerateEmailLinkData, GenerateEmailLinkError, GenerateEmailLinkErrors, GenerateEmailLinkRequest, GenerateEmailLinkResponse, GenerateEmailLinkResponses, GenericSuccessResponse, GetAgentApiKeyData, GetAgentApiKeyError, GetAgentApiKeyErrors, GetAgentApiKeyResponse, GetAgentApiKeyResponses, GetAiBillingPlansData, GetAiBillingPlansResponse, GetAiBillingPlansResponses, GetAiBillingSummaryData, GetAiBillingSummaryError, GetAiBillingSummaryErrors, GetAiBillingSummaryResponse, GetAiBillingSummaryResponses, GetCodexConnectionData, GetCodexConnectionResponse, GetCodexConnectionResponses, GetCursorApiKeyData, GetCursorApiKeyError, GetCursorApiKeyErrors, GetCursorApiKeyResponse, GetCursorApiKeyResponses, GetGithubPullRequestMergeabilityData, GetGithubPullRequestMergeabilityError, GetGithubPullRequestMergeabilityErrors, GetGithubPullRequestMergeabilityResponse, GetGithubPullRequestMergeabilityResponses, GetGtmInviteOfferData, GetGtmInviteOfferError, GetGtmInviteOfferErrors, GetGtmInviteOfferResponse, GetGtmInviteOfferResponses, GetLegacyUserPermissionsData, GetLegacyUserPermissionsError, GetLegacyUserPermissionsErrors, GetLegacyUserPermissionsResponse, GetLegacyUserPermissionsResponse2, GetLegacyUserPermissionsResponses, GetNamesWithEmailRequestBody, GetPermissionsData, GetPermissionsError, GetPermissionsErrors, GetPermissionsResponse, GetPermissionsResponses, GetProfilePicturesRequestBody, GetReferralCodeData, GetReferralCodeError, GetReferralCodeErrors, GetReferralCodeResponse, GetReferralCodeResponses, GetSubscriptionStatusData, GetSubscriptionStatusError, GetSubscriptionStatusErrors, GetSubscriptionStatusResponse, GetSubscriptionStatusResponses, GetSystemStatusData, GetSystemStatusError, GetSystemStatusErrors, GetSystemStatusResponse, GetSystemStatusResponses, GetTeamByInviteLinkData, GetTeamByInviteLinkError, GetTeamByInviteLinkErrors, GetTeamByInviteLinkResponse, GetTeamByInviteLinkResponses, GetTeamData, GetTeamError, GetTeamErrors, GetTeamInviteLinkData, GetTeamInviteLinkError, GetTeamInviteLinkErrors, GetTeamInviteLinkResponse, GetTeamInviteLinkResponses, GetTeamInvitesData, GetTeamInvitesError, GetTeamInvitesErrors, GetTeamInvitesResponse, GetTeamInvitesResponses, GetTeamResponse, GetTeamResponses, GetTrialEligibilityData, GetTrialEligibilityError, GetTrialEligibilityErrors, GetTrialEligibilityResponse, GetTrialEligibilityResponses, GetUserInfo, GetUserInfoData, GetUserInfoError, GetUserInfoErrors, GetUserInfoResponse, GetUserInfoResponses, GetUserInvitesData, GetUserInvitesError, GetUserInvitesErrors, GetUserInvitesResponse, GetUserInvitesResponses, GetUserLanguageData, GetUserLanguageError, GetUserLanguageErrors, GetUserLanguageResponse, GetUserLanguageResponses, GetUserLinkExistsData, GetUserLinkExistsError, GetUserLinkExistsErrors, GetUserLinkExistsResponse, GetUserLinkExistsResponses, GetUserNameData, GetUserNameError, GetUserNameErrors, GetUserNameResponse, GetUserNameResponses, GetUserNamesData, GetUserNamesError, GetUserNamesErrors, GetUserNamesResponse, GetUserNamesResponses, GetUserNamesWithEmailData, GetUserNamesWithEmailError, GetUserNamesWithEmailErrors, GetUserNamesWithEmailResponse, GetUserNamesWithEmailResponses, GetUserOrganizationData, GetUserOrganizationError, GetUserOrganizationErrors, GetUserOrganizationResponse, GetUserOrganizationResponses, GetUserPermissionsData, GetUserPermissionsError, GetUserPermissionsErrors, GetUserPermissionsResponse, GetUserPermissionsResponses, GetUserQuotaData, GetUserQuotaError, GetUserQuotaErrors, GetUserQuotaResponse, GetUserQuotaResponses, GetUserTeamsData, GetUserTeamsError, GetUserTeamsErrors, GetUserTeamsResponse, GetUserTeamsResponses, GithubLinkStatusResponse, GithubMergeMethod, GithubPullRequestCheckRun, GithubPullRequestComment, GithubPullRequestLabel, GithubPullRequestMergeability, GithubPullRequestMergeabilityEntry, GithubPullRequestMergeabilityRequest, GithubPullRequestMergeabilityResponse, GithubPullRequestNumber, GithubPullRequestRef, GithubPullRequestReview, GithubPullRequestReviewState, GithubPullRequestState, GithubPullRequestStatus, GithubPullRequestUser, GmailLinkStatusResponse, GtmInviteLink, GtmInviteLinkList, GtmInviteLinkStatus, GtmInviteOffer, GtmInviteOfferStatus, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, InitGithubLinkData, InitGithubLinkError, InitGithubLinkErrors, InitGithubLinkResponse, InitGithubLinkResponse2, InitGithubLinkResponses, InitGmailLinkData, InitGmailLinkError, InitGmailLinkErrors, InitGmailLinkResponse, InitGmailLinkResponse2, InitGmailLinkResponses, InitOutlookLinkData, InitOutlookLinkError, InitOutlookLinkErrors, InitOutlookLinkResponse, InitOutlookLinkResponse2, InitOutlookLinkResponses, InviteEntry, InviteToTeamData, InviteToTeamError, InviteToTeamErrors, InviteToTeamRequest, InviteToTeamResponses, JoinTeamByInviteLinkData, JoinTeamByInviteLinkError, JoinTeamByInviteLinkErrors, JoinTeamByInviteLinkResponse, JoinTeamByInviteLinkResponse2, JoinTeamByInviteLinkResponses, JoinTeamData, JoinTeamError, JoinTeamErrors, JoinTeamResponses, Language, LinkShare, ListCodexEnvironmentsData, ListCodexEnvironmentsResponse, ListCodexEnvironmentsResponses, ListCursorModelsData, ListCursorModelsError, ListCursorModelsErrors, ListCursorModelsResponse, ListCursorModelsResponses, ListGtmInviteLinksData, ListGtmInviteLinksError, ListGtmInviteLinksErrors, ListGtmInviteLinksResponse, ListGtmInviteLinksResponses, ListSystemStatusHistoryData, ListSystemStatusHistoryError, ListSystemStatusHistoryErrors, ListSystemStatusHistoryResponse, ListSystemStatusHistoryResponses, LogoutData, LogoutResponse, LogoutResponses, MacroApiTokenData, MacroApiTokenError, MacroApiTokenErrors, MacroApiTokenResponse, MacroApiTokenResponse2, MacroApiTokenResponses, MergeGithubPullRequestData, MergeGithubPullRequestError, MergeGithubPullRequestErrors, MergeGithubPullRequestRequest, MergeGithubPullRequestResponse, MergeGithubPullRequestResponse2, MergeGithubPullRequestResponses, Oauth2CallbackData, Oauth2CallbackError, Oauth2CallbackErrors, Oauth2CallbackResponses, OauthRedirectData, OauthRedirectError, OauthRedirectErrors, OauthRedirectResponses, PasswordlessCallbackData, PasswordlessCallbackError, PasswordlessCallbackErrors, PasswordlessCallbackResponse, PasswordlessCallbackResponses, PasswordlessLoginData, PasswordlessLoginError, PasswordlessLoginErrors, PasswordlessLoginResponse, PasswordlessLoginResponses, PasswordlessRequest, PasswordlessStartedResponse, PasswordLoginData, PasswordLoginError, PasswordLoginErrors, PasswordLoginResponse, PasswordLoginResponses, PasswordRequest, PatchTeamCrmSettingsData, PatchTeamCrmSettingsError, PatchTeamCrmSettingsErrors, PatchTeamCrmSettingsRequest, PatchTeamCrmSettingsResponse, PatchTeamCrmSettingsResponse2, PatchTeamCrmSettingsResponses, PatchTeamData, PatchTeamError, PatchTeamErrors, PatchTeamMemberPlanData, PatchTeamMemberPlanError, PatchTeamMemberPlanErrors, PatchTeamMemberPlanRequest, PatchTeamMemberPlanResponse, PatchTeamMemberPlanResponses, PatchTeamRequest, PatchTeamResponses, PatchTeamUserRole, PatchUserGroupData, PatchUserGroupError, PatchUserGroupErrors, PatchUserGroupRequest, PatchUserGroupResponse, PatchUserGroupResponses, PatchUserOnboardingData, PatchUserOnboardingError, PatchUserOnboardingErrors, PatchUserOnboardingRequest, PatchUserOnboardingResponse, PatchUserOnboardingResponses, PatchUserTutorialData, PatchUserTutorialError, PatchUserTutorialErrors, PatchUserTutorialRequest, PatchUserTutorialResponse, PatchUserTutorialResponses, Permission, PlanCatalogEntry, PlanCatalogResponse, PlanTier, PollCodexLoginData, PollCodexLoginResponse, PollCodexLoginResponses, PostGetNamesRequestBody, PostProfilePicturesData, PostProfilePicturesError, PostProfilePicturesErrors, PostProfilePicturesResponse, PostProfilePicturesResponses, ProfilePictureQueryParams, ProfilePictures, PublicGtmInviteLink, PurchaseAiCreditsData, PurchaseAiCreditsError, PurchaseAiCreditsErrors, PurchaseAiCreditsResponse, PurchaseAiCreditsResponses, PutAgentApiKeyData, PutAgentApiKeyError, PutAgentApiKeyErrors, PutAgentApiKeyRequest, PutAgentApiKeyResponse, PutAgentApiKeyResponses, PutCursorApiKeyData, PutCursorApiKeyError, PutCursorApiKeyErrors, PutCursorApiKeyRequest, PutCursorApiKeyResponse, PutCursorApiKeyResponses, PutCursorDefaultModelData, PutCursorDefaultModelError, PutCursorDefaultModelErrors, PutCursorDefaultModelRequest, PutCursorDefaultModelResponse, PutCursorDefaultModelResponses, PutProfilePictureData, PutProfilePictureError, PutProfilePictureErrors, PutProfilePictureResponse, PutProfilePictureResponses, PutUserLanguageData, PutUserLanguageError, PutUserLanguageErrors, PutUserLanguageResponse, PutUserLanguageResponses, PutUserNameData, PutUserNameError, PutUserNameErrors, PutUserNameQueryParams, PutUserNameResponse, PutUserNameResponses, RedeemGtmInviteLinkData, RedeemGtmInviteLinkError, RedeemGtmInviteLinkErrors, RedeemGtmInviteLinkRequest, RedeemGtmInviteLinkResponse, RedeemGtmInviteLinkResponses, RefreshData, RefreshError, RefreshErrors, RefreshResponse, RefreshResponses, RejectInvitationData, RejectInvitationError, RejectInvitationErrors, RejectInvitationResponses, RemoveUserFromTeamData, RemoveUserFromTeamError, RemoveUserFromTeamErrors, RemoveUserFromTeamResponses, ResendFusionauthVerifyUserEmailData, ResendFusionauthVerifyUserEmailError, ResendFusionauthVerifyUserEmailErrors, ResendFusionauthVerifyUserEmailRequest, ResendFusionauthVerifyUserEmailResponse, ResendFusionauthVerifyUserEmailResponses, ResolveGtmInviteLinkData, ResolveGtmInviteLinkError, ResolveGtmInviteLinkErrors, ResolveGtmInviteLinkResponse, ResolveGtmInviteLinkResponses, RevokeGtmInviteLinkData, RevokeGtmInviteLinkError, RevokeGtmInviteLinkErrors, RevokeGtmInviteLinkResponse, RevokeGtmInviteLinkResponses, SavedAgentApiKey, ScheduledSeatPlan, SeatPlan, SendInviteBody, SendMobileWelcomeEmailData, SendMobileWelcomeEmailError, SendMobileWelcomeEmailErrors, SendMobileWelcomeEmailRequest, SendMobileWelcomeEmailResponse, SendMobileWelcomeEmailResponse2, SendMobileWelcomeEmailResponses, SendReferralCodeData, SendReferralCodeError, SendReferralCodeErrors, SendReferralCodeResponse, SendReferralCodeResponses, SessionCreationData, SessionCreationError, SessionCreationErrors, SessionCreationResponse, SessionCreationResponses, SessionLoginData, SessionLoginError, SessionLoginErrors, SessionLoginResponse, SessionLoginResponses, SetGithubPullRequestDraftData, SetGithubPullRequestDraftError, SetGithubPullRequestDraftErrors, SetGithubPullRequestDraftRequest, SetGithubPullRequestDraftResponse, SetGithubPullRequestDraftResponse2, SetGithubPullRequestDraftResponses, SetGithubPullRequestStateData, SetGithubPullRequestStateError, SetGithubPullRequestStateErrors, SetGithubPullRequestStateRequest, SetGithubPullRequestStateResponse, SetGithubPullRequestStateResponse2, SetGithubPullRequestStateResponses, SetSystemStatusData, SetSystemStatusError, SetSystemStatusErrors, SetSystemStatusResponse, SetSystemStatusResponses, SsoLoginData, SsoLoginError, SsoLoginErrors, SsoLoginResponses, SsoRequiredResponse, StartCodexLoginData, StartCodexLoginResponse, StartCodexLoginResponses, StatusUpdate, StripeSessionResponse, SubscriptionStatus, SystemStatus, SystemStatusHistory, Team, TeamInviteDetails, TeamInviteLinkResponse, TeamInviteLinkTeam, TeamInviteLinkToken, TeamInviteLinkTokenRequest, TeamInvitesResponse, TeamMember, TeamPlan, TeamRole, TeamWithMembers, ToggleAutoJoinDomainResponse, ToggleNonAdminInvitesResponse, ToggleTeamAutoJoinDomainData, ToggleTeamAutoJoinDomainError, ToggleTeamAutoJoinDomainErrors, ToggleTeamAutoJoinDomainResponse, ToggleTeamAutoJoinDomainResponses, ToggleTeamNonAdminInvitesData, ToggleTeamNonAdminInvitesError, ToggleTeamNonAdminInvitesErrors, ToggleTeamNonAdminInvitesResponse, ToggleTeamNonAdminInvitesResponses, TrialEligibility, UpdateAiBillingAutoReloadData, UpdateAiBillingAutoReloadError, UpdateAiBillingAutoReloadErrors, UpdateAiBillingAutoReloadResponse, UpdateAiBillingAutoReloadResponses, UpdateAiBillingOverageData, UpdateAiBillingOverageError, UpdateAiBillingOverageErrors, UpdateAiBillingOverageResponse, UpdateAiBillingOverageResponses, UpdateAutoReloadRequest, UpdateOverageRequest, UpstreamErrorCode, UpstreamErrorResponse, UsageSnapshot, UserLanguage, UserLinkResponse, UserName, UserNames, UserOrganizationResponse, UserProfilePicture, UserQuota, UserTokensResponse, VerifyEmailLinkData, VerifyEmailLinkError, VerifyEmailLinkErrors, VerifyEmailLinkResponse, VerifyEmailLinkResponses, VerifyFusionauthUserEmailData, VerifyFusionauthUserEmailError, VerifyFusionauthUserEmailErrors, VerifyFusionauthUserEmailResponse, VerifyFusionauthUserEmailResponses, VerifyMergeRequestData, VerifyMergeRequestError, VerifyMergeRequestErrors, VerifyMergeRequestResponse, VerifyMergeRequestResponses } from './types.gen';
+export type { AbGroup, AgentApiKey, AgentApiKeyProvider, AiBillingErrorBody, AppleLoginData, AppleLoginError, AppleLoginErrors, AppleLoginRequest, AppleLoginResponse, AppleLoginResponses, AutoReloadDefaults, AutoReloadMonthlyBudget, AutoReloadSnapshot, CancelCodexLoginData, CancelCodexLoginResponse, CancelCodexLoginResponses, ChangePlanData, ChangePlanError, ChangePlanErrors, ChangePlanRequest, ChangePlanResponse, ChangePlanResponse2, ChangePlanResponses, CheckGithubLinkStatusData, CheckGithubLinkStatusError, CheckGithubLinkStatusErrors, CheckGithubLinkStatusResponse, CheckGithubLinkStatusResponses, CheckGmailLinkStatusData, CheckGmailLinkStatusError, CheckGmailLinkStatusErrors, CheckGmailLinkStatusResponse, CheckGmailLinkStatusResponses, CheckoutSessionMetadata, CheckoutSessionV2Response, ClientOptions, CodexConfigRequest, CodexConnectionStatus, CodexEnvironment, CodexEnvironmentRepository, CodexLoginPoll, CodexLoginStart, CodexLoginState, ConfigureCodexData, ConfigureCodexResponse, ConfigureCodexResponses, CreateAccountMergeRequest, CreateAiCreditCheckoutData, CreateAiCreditCheckoutError, CreateAiCreditCheckoutErrors, CreateAiCreditCheckoutResponse, CreateAiCreditCheckoutResponses, CreateCheckoutSessionV2Data, CreateCheckoutSessionV2Error, CreateCheckoutSessionV2Errors, CreateCheckoutSessionV2Request, CreateCheckoutSessionV2Response, CreateCheckoutSessionV2Responses, CreatedTeamInviteLinkResponse, CreateGtmInviteLinkData, CreateGtmInviteLinkError, CreateGtmInviteLinkErrors, CreateGtmInviteLinkRequest, CreateGtmInviteLinkResponse, CreateGtmInviteLinkResponses, CreateInProgressLinkData, CreateInProgressLinkError, CreateInProgressLinkErrors, CreateInProgressLinkResponse, CreateInProgressLinkResponse2, CreateInProgressLinkResponses, CreateMergeRequestData, CreateMergeRequestError, CreateMergeRequestErrors, CreateMergeRequestResponse, CreateMergeRequestResponses, CreatePortalSessionData, CreatePortalSessionError, CreatePortalSessionErrors, CreatePortalSessionRequest, CreatePortalSessionResponse, CreatePortalSessionResponses, CreateTeamData, CreateTeamError, CreateTeamErrors, CreateTeamInviteLinkData, CreateTeamInviteLinkError, CreateTeamInviteLinkErrors, CreateTeamInviteLinkResponse, CreateTeamInviteLinkResponses, CreateTeamRequest, CreateTeamResponse, CreateTeamResponses, CreditCheckoutRequestBody, CreditCheckoutResponse, CreditPurchaseRequestBody, CreditPurchaseResponse, CreditPurchaseSnapshot, CreditPurchaseStatus, CurrentSystemStatus, CursorApiKeyStatus, CursorModelOption, CursorModelsResponse, DeleteAgentApiKeyData, DeleteAgentApiKeyError, DeleteAgentApiKeyErrors, DeleteAgentApiKeyResponse, DeleteAgentApiKeyResponses, DeleteCursorApiKeyData, DeleteCursorApiKeyError, DeleteCursorApiKeyErrors, DeleteCursorApiKeyResponse, DeleteCursorApiKeyResponses, DeleteGithubLinkData, DeleteGithubLinkError, DeleteGithubLinkErrors, DeleteGithubLinkResponse, DeleteGithubLinkResponses, DeleteTeamData, DeleteTeamError, DeleteTeamErrors, DeleteTeamInviteHandlerData, DeleteTeamInviteHandlerError, DeleteTeamInviteHandlerErrors, DeleteTeamInviteHandlerResponses, DeleteTeamInviteLinkData, DeleteTeamInviteLinkError, DeleteTeamInviteLinkErrors, DeleteTeamInviteLinkResponse, DeleteTeamInviteLinkResponses, DeleteTeamResponses, DeleteUserData, DeleteUserError, DeleteUserErrors, DeleteUserResponse, DeleteUserResponses, DenyReason, DisconnectCodexData, DisconnectCodexResponse, DisconnectCodexResponses, EmailConnectionProviders, EmailConnectionProvidersData, EmailConnectionProvidersError, EmailConnectionProvidersErrors, EmailConnectionProvidersResponse, EmailConnectionProvidersResponses, EmptyResponse, EnrichedGithubPullRequest, EnrichGithubPullRequestsData, EnrichGithubPullRequestsError, EnrichGithubPullRequestsErrors, EnrichGithubPullRequestsProxyRequest, EnrichGithubPullRequestsResponse, EnrichGithubPullRequestsResponse2, EnrichGithubPullRequestsResponses, ErrorResponse, GenerateEmailLinkData, GenerateEmailLinkError, GenerateEmailLinkErrors, GenerateEmailLinkRequest, GenerateEmailLinkResponse, GenerateEmailLinkResponses, GenericSuccessResponse, GetAgentApiKeyData, GetAgentApiKeyError, GetAgentApiKeyErrors, GetAgentApiKeyResponse, GetAgentApiKeyResponses, GetAiBillingPlansData, GetAiBillingPlansResponse, GetAiBillingPlansResponses, GetAiBillingSummaryData, GetAiBillingSummaryError, GetAiBillingSummaryErrors, GetAiBillingSummaryResponse, GetAiBillingSummaryResponses, GetCodexConnectionData, GetCodexConnectionResponse, GetCodexConnectionResponses, GetCursorApiKeyData, GetCursorApiKeyError, GetCursorApiKeyErrors, GetCursorApiKeyResponse, GetCursorApiKeyResponses, GetGithubPullRequestMergeabilityData, GetGithubPullRequestMergeabilityError, GetGithubPullRequestMergeabilityErrors, GetGithubPullRequestMergeabilityResponse, GetGithubPullRequestMergeabilityResponses, GetGtmInviteOfferData, GetGtmInviteOfferError, GetGtmInviteOfferErrors, GetGtmInviteOfferResponse, GetGtmInviteOfferResponses, GetLegacyUserPermissionsData, GetLegacyUserPermissionsError, GetLegacyUserPermissionsErrors, GetLegacyUserPermissionsResponse, GetLegacyUserPermissionsResponse2, GetLegacyUserPermissionsResponses, GetNamesWithEmailRequestBody, GetPermissionsData, GetPermissionsError, GetPermissionsErrors, GetPermissionsResponse, GetPermissionsResponses, GetProfilePicturesRequestBody, GetReferralCodeData, GetReferralCodeError, GetReferralCodeErrors, GetReferralCodeResponse, GetReferralCodeResponses, GetSubscriptionStatusData, GetSubscriptionStatusError, GetSubscriptionStatusErrors, GetSubscriptionStatusResponse, GetSubscriptionStatusResponses, GetSystemStatusData, GetSystemStatusError, GetSystemStatusErrors, GetSystemStatusResponse, GetSystemStatusResponses, GetTeamByInviteLinkData, GetTeamByInviteLinkError, GetTeamByInviteLinkErrors, GetTeamByInviteLinkResponse, GetTeamByInviteLinkResponses, GetTeamData, GetTeamError, GetTeamErrors, GetTeamInviteLinkData, GetTeamInviteLinkError, GetTeamInviteLinkErrors, GetTeamInviteLinkResponse, GetTeamInviteLinkResponses, GetTeamInvitesData, GetTeamInvitesError, GetTeamInvitesErrors, GetTeamInvitesResponse, GetTeamInvitesResponses, GetTeamResponse, GetTeamResponses, GetTrialEligibilityData, GetTrialEligibilityError, GetTrialEligibilityErrors, GetTrialEligibilityResponse, GetTrialEligibilityResponses, GetUserInfo, GetUserInfoData, GetUserInfoError, GetUserInfoErrors, GetUserInfoResponse, GetUserInfoResponses, GetUserInvitesData, GetUserInvitesError, GetUserInvitesErrors, GetUserInvitesResponse, GetUserInvitesResponses, GetUserLanguageData, GetUserLanguageError, GetUserLanguageErrors, GetUserLanguageResponse, GetUserLanguageResponses, GetUserLinkExistsData, GetUserLinkExistsError, GetUserLinkExistsErrors, GetUserLinkExistsResponse, GetUserLinkExistsResponses, GetUserNameData, GetUserNameError, GetUserNameErrors, GetUserNameResponse, GetUserNameResponses, GetUserNamesData, GetUserNamesError, GetUserNamesErrors, GetUserNamesResponse, GetUserNamesResponses, GetUserNamesWithEmailData, GetUserNamesWithEmailError, GetUserNamesWithEmailErrors, GetUserNamesWithEmailResponse, GetUserNamesWithEmailResponses, GetUserOrganizationData, GetUserOrganizationError, GetUserOrganizationErrors, GetUserOrganizationResponse, GetUserOrganizationResponses, GetUserPermissionsData, GetUserPermissionsError, GetUserPermissionsErrors, GetUserPermissionsResponse, GetUserPermissionsResponses, GetUserQuotaData, GetUserQuotaError, GetUserQuotaErrors, GetUserQuotaResponse, GetUserQuotaResponses, GetUserTeamsData, GetUserTeamsError, GetUserTeamsErrors, GetUserTeamsResponse, GetUserTeamsResponses, GithubLinkStatusResponse, GithubMergeMethod, GithubPullRequestCheckRun, GithubPullRequestComment, GithubPullRequestLabel, GithubPullRequestMergeability, GithubPullRequestMergeabilityEntry, GithubPullRequestMergeabilityRequest, GithubPullRequestMergeabilityResponse, GithubPullRequestNumber, GithubPullRequestRef, GithubPullRequestReview, GithubPullRequestReviewState, GithubPullRequestState, GithubPullRequestStatus, GithubPullRequestUser, GmailLinkStatusResponse, GtmInviteLink, GtmInviteLinkList, GtmInviteLinkStatus, GtmInviteOffer, GtmInviteOfferStatus, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, InitGithubLinkData, InitGithubLinkError, InitGithubLinkErrors, InitGithubLinkResponse, InitGithubLinkResponse2, InitGithubLinkResponses, InitGmailLinkData, InitGmailLinkError, InitGmailLinkErrors, InitGmailLinkResponse, InitGmailLinkResponse2, InitGmailLinkResponses, InitOutlookLinkData, InitOutlookLinkError, InitOutlookLinkErrors, InitOutlookLinkResponse, InitOutlookLinkResponse2, InitOutlookLinkResponses, InviteEntry, InviteToTeamData, InviteToTeamError, InviteToTeamErrors, InviteToTeamRequest, InviteToTeamResponses, JoinTeamByInviteLinkData, JoinTeamByInviteLinkError, JoinTeamByInviteLinkErrors, JoinTeamByInviteLinkResponse, JoinTeamByInviteLinkResponse2, JoinTeamByInviteLinkResponses, JoinTeamData, JoinTeamError, JoinTeamErrors, JoinTeamResponses, Language, LinkShare, ListCodexEnvironmentsData, ListCodexEnvironmentsResponse, ListCodexEnvironmentsResponses, ListCursorModelsData, ListCursorModelsError, ListCursorModelsErrors, ListCursorModelsResponse, ListCursorModelsResponses, ListGtmInviteLinksData, ListGtmInviteLinksError, ListGtmInviteLinksErrors, ListGtmInviteLinksResponse, ListGtmInviteLinksResponses, ListSystemStatusHistoryData, ListSystemStatusHistoryError, ListSystemStatusHistoryErrors, ListSystemStatusHistoryResponse, ListSystemStatusHistoryResponses, LogoutData, LogoutResponse, LogoutResponses, MacroApiTokenData, MacroApiTokenError, MacroApiTokenErrors, MacroApiTokenResponse, MacroApiTokenResponse2, MacroApiTokenResponses, MergeGithubPullRequestData, MergeGithubPullRequestError, MergeGithubPullRequestErrors, MergeGithubPullRequestRequest, MergeGithubPullRequestResponse, MergeGithubPullRequestResponse2, MergeGithubPullRequestResponses, Oauth2CallbackData, Oauth2CallbackError, Oauth2CallbackErrors, Oauth2CallbackResponses, OauthRedirectData, OauthRedirectError, OauthRedirectErrors, OauthRedirectResponses, PasswordlessCallbackData, PasswordlessCallbackError, PasswordlessCallbackErrors, PasswordlessCallbackResponse, PasswordlessCallbackResponses, PasswordlessLoginData, PasswordlessLoginError, PasswordlessLoginErrors, PasswordlessLoginResponse, PasswordlessLoginResponses, PasswordlessRequest, PasswordlessStartedResponse, PasswordLoginData, PasswordLoginError, PasswordLoginErrors, PasswordLoginResponse, PasswordLoginResponses, PasswordRequest, PatchTeamCrmSettingsData, PatchTeamCrmSettingsError, PatchTeamCrmSettingsErrors, PatchTeamCrmSettingsRequest, PatchTeamCrmSettingsResponse, PatchTeamCrmSettingsResponse2, PatchTeamCrmSettingsResponses, PatchTeamData, PatchTeamError, PatchTeamErrors, PatchTeamMemberPlanData, PatchTeamMemberPlanError, PatchTeamMemberPlanErrors, PatchTeamMemberPlanRequest, PatchTeamMemberPlanResponse, PatchTeamMemberPlanResponses, PatchTeamRequest, PatchTeamResponses, PatchTeamUserRole, PatchUserGroupData, PatchUserGroupError, PatchUserGroupErrors, PatchUserGroupRequest, PatchUserGroupResponse, PatchUserGroupResponses, PatchUserOnboardingData, PatchUserOnboardingError, PatchUserOnboardingErrors, PatchUserOnboardingRequest, PatchUserOnboardingResponse, PatchUserOnboardingResponses, PatchUserTutorialData, PatchUserTutorialError, PatchUserTutorialErrors, PatchUserTutorialRequest, PatchUserTutorialResponse, PatchUserTutorialResponses, Permission, PlanCatalogEntry, PlanCatalogResponse, PlanTier, PollCodexLoginData, PollCodexLoginResponse, PollCodexLoginResponses, PostGetNamesRequestBody, PostProfilePicturesData, PostProfilePicturesError, PostProfilePicturesErrors, PostProfilePicturesResponse, PostProfilePicturesResponses, ProfilePictureQueryParams, ProfilePictures, PublicGtmInviteLink, PurchaseAiCreditsData, PurchaseAiCreditsError, PurchaseAiCreditsErrors, PurchaseAiCreditsResponse, PurchaseAiCreditsResponses, PutAgentApiKeyData, PutAgentApiKeyError, PutAgentApiKeyErrors, PutAgentApiKeyRequest, PutAgentApiKeyResponse, PutAgentApiKeyResponses, PutCursorApiKeyData, PutCursorApiKeyError, PutCursorApiKeyErrors, PutCursorApiKeyRequest, PutCursorApiKeyResponse, PutCursorApiKeyResponses, PutCursorDefaultModelData, PutCursorDefaultModelError, PutCursorDefaultModelErrors, PutCursorDefaultModelRequest, PutCursorDefaultModelResponse, PutCursorDefaultModelResponses, PutProfilePictureData, PutProfilePictureError, PutProfilePictureErrors, PutProfilePictureResponse, PutProfilePictureResponses, PutUserLanguageData, PutUserLanguageError, PutUserLanguageErrors, PutUserLanguageResponse, PutUserLanguageResponses, PutUserNameData, PutUserNameError, PutUserNameErrors, PutUserNameQueryParams, PutUserNameResponse, PutUserNameResponses, RedeemGtmInviteLinkData, RedeemGtmInviteLinkError, RedeemGtmInviteLinkErrors, RedeemGtmInviteLinkRequest, RedeemGtmInviteLinkResponse, RedeemGtmInviteLinkResponses, RefreshData, RefreshError, RefreshErrors, RefreshResponse, RefreshResponses, RejectInvitationData, RejectInvitationError, RejectInvitationErrors, RejectInvitationResponses, RemoveUserFromTeamData, RemoveUserFromTeamError, RemoveUserFromTeamErrors, RemoveUserFromTeamResponses, ResendFusionauthVerifyUserEmailData, ResendFusionauthVerifyUserEmailError, ResendFusionauthVerifyUserEmailErrors, ResendFusionauthVerifyUserEmailRequest, ResendFusionauthVerifyUserEmailResponse, ResendFusionauthVerifyUserEmailResponses, ResolveGtmInviteLinkData, ResolveGtmInviteLinkError, ResolveGtmInviteLinkErrors, ResolveGtmInviteLinkResponse, ResolveGtmInviteLinkResponses, RevokeGtmInviteLinkData, RevokeGtmInviteLinkError, RevokeGtmInviteLinkErrors, RevokeGtmInviteLinkResponse, RevokeGtmInviteLinkResponses, SavedAgentApiKey, ScheduledSeatPlan, SeatPlan, SendDomainNoticeResponse, SendInviteBody, SendMobileWelcomeEmailData, SendMobileWelcomeEmailError, SendMobileWelcomeEmailErrors, SendMobileWelcomeEmailRequest, SendMobileWelcomeEmailResponse, SendMobileWelcomeEmailResponse2, SendMobileWelcomeEmailResponses, SendReferralCodeData, SendReferralCodeError, SendReferralCodeErrors, SendReferralCodeResponse, SendReferralCodeResponses, SendTeamDomainNoticeData, SendTeamDomainNoticeError, SendTeamDomainNoticeErrors, SendTeamDomainNoticeResponse, SendTeamDomainNoticeResponses, SessionCreationData, SessionCreationError, SessionCreationErrors, SessionCreationResponse, SessionCreationResponses, SessionLoginData, SessionLoginError, SessionLoginErrors, SessionLoginResponse, SessionLoginResponses, SetGithubPullRequestDraftData, SetGithubPullRequestDraftError, SetGithubPullRequestDraftErrors, SetGithubPullRequestDraftRequest, SetGithubPullRequestDraftResponse, SetGithubPullRequestDraftResponse2, SetGithubPullRequestDraftResponses, SetGithubPullRequestStateData, SetGithubPullRequestStateError, SetGithubPullRequestStateErrors, SetGithubPullRequestStateRequest, SetGithubPullRequestStateResponse, SetGithubPullRequestStateResponse2, SetGithubPullRequestStateResponses, SetSystemStatusData, SetSystemStatusError, SetSystemStatusErrors, SetSystemStatusResponse, SetSystemStatusResponses, SsoLoginData, SsoLoginError, SsoLoginErrors, SsoLoginResponses, SsoRequiredResponse, StartCodexLoginData, StartCodexLoginResponse, StartCodexLoginResponses, StatusUpdate, StripeSessionResponse, SubscriptionStatus, SystemStatus, SystemStatusHistory, Team, TeamInviteDetails, TeamInviteLinkResponse, TeamInviteLinkTeam, TeamInviteLinkToken, TeamInviteLinkTokenRequest, TeamInvitesResponse, TeamMember, TeamPlan, TeamRole, TeamWithMembers, ToggleAutoJoinDomainResponse, ToggleNonAdminInvitesResponse, ToggleTeamAutoJoinDomainData, ToggleTeamAutoJoinDomainError, ToggleTeamAutoJoinDomainErrors, ToggleTeamAutoJoinDomainResponse, ToggleTeamAutoJoinDomainResponses, ToggleTeamNonAdminInvitesData, ToggleTeamNonAdminInvitesError, ToggleTeamNonAdminInvitesErrors, ToggleTeamNonAdminInvitesResponse, ToggleTeamNonAdminInvitesResponses, TrialEligibility, UpdateAiBillingAutoReloadData, UpdateAiBillingAutoReloadError, UpdateAiBillingAutoReloadErrors, UpdateAiBillingAutoReloadResponse, UpdateAiBillingAutoReloadResponses, UpdateAiBillingOverageData, UpdateAiBillingOverageError, UpdateAiBillingOverageErrors, UpdateAiBillingOverageResponse, UpdateAiBillingOverageResponses, UpdateAutoReloadRequest, UpdateOverageRequest, UpstreamErrorCode, UpstreamErrorResponse, UsageSnapshot, UserLanguage, UserLinkResponse, UserName, UserNames, UserOrganizationResponse, UserProfilePicture, UserQuota, UserTokensResponse, VerifyEmailLinkData, VerifyEmailLinkError, VerifyEmailLinkErrors, VerifyEmailLinkResponse, VerifyEmailLinkResponses, VerifyFusionauthUserEmailData, VerifyFusionauthUserEmailError, VerifyFusionauthUserEmailErrors, VerifyFusionauthUserEmailResponse, VerifyFusionauthUserEmailResponses, VerifyMergeRequestData, VerifyMergeRequestError, VerifyMergeRequestErrors, VerifyMergeRequestResponse, VerifyMergeRequestResponses } from './types.gen';
diff --git a/packages/sdk/generated/auth/sdk.gen.ts b/packages/sdk/generated/auth/sdk.gen.ts
index 0b3314dd01..50ac4eafe4 100644
--- a/packages/sdk/generated/auth/sdk.gen.ts
+++ b/packages/sdk/generated/auth/sdk.gen.ts
@@ -2,7 +2,7 @@
import type { Client, ClientMeta, Options as Options2, RequestResult, TDataShape } from './client';
import { client } from './client.gen';
-import type { AppleLoginData, AppleLoginErrors, AppleLoginResponses, CancelCodexLoginData, CancelCodexLoginResponses, ChangePlanData, ChangePlanErrors, ChangePlanResponses, CheckGithubLinkStatusData, CheckGithubLinkStatusErrors, CheckGithubLinkStatusResponses, CheckGmailLinkStatusData, CheckGmailLinkStatusErrors, CheckGmailLinkStatusResponses, ConfigureCodexData, ConfigureCodexResponses, CreateAiCreditCheckoutData, CreateAiCreditCheckoutErrors, CreateAiCreditCheckoutResponses, CreateCheckoutSessionV2Data, CreateCheckoutSessionV2Errors, CreateCheckoutSessionV2Responses, CreateGtmInviteLinkData, CreateGtmInviteLinkErrors, CreateGtmInviteLinkResponses, CreateInProgressLinkData, CreateInProgressLinkErrors, CreateInProgressLinkResponses, CreateMergeRequestData, CreateMergeRequestErrors, CreateMergeRequestResponses, CreatePortalSessionData, CreatePortalSessionErrors, CreatePortalSessionResponses, CreateTeamData, CreateTeamErrors, CreateTeamInviteLinkData, CreateTeamInviteLinkErrors, CreateTeamInviteLinkResponses, CreateTeamResponses, DeleteAgentApiKeyData, DeleteAgentApiKeyErrors, DeleteAgentApiKeyResponses, DeleteCursorApiKeyData, DeleteCursorApiKeyErrors, DeleteCursorApiKeyResponses, DeleteGithubLinkData, DeleteGithubLinkErrors, DeleteGithubLinkResponses, DeleteTeamData, DeleteTeamErrors, DeleteTeamInviteHandlerData, DeleteTeamInviteHandlerErrors, DeleteTeamInviteHandlerResponses, DeleteTeamInviteLinkData, DeleteTeamInviteLinkErrors, DeleteTeamInviteLinkResponses, DeleteTeamResponses, DeleteUserData, DeleteUserErrors, DeleteUserResponses, DisconnectCodexData, DisconnectCodexResponses, EmailConnectionProvidersData, EmailConnectionProvidersErrors, EmailConnectionProvidersResponses, EnrichGithubPullRequestsData, EnrichGithubPullRequestsErrors, EnrichGithubPullRequestsResponses, GenerateEmailLinkData, GenerateEmailLinkErrors, GenerateEmailLinkResponses, GetAgentApiKeyData, GetAgentApiKeyErrors, GetAgentApiKeyResponses, GetAiBillingPlansData, GetAiBillingPlansResponses, GetAiBillingSummaryData, GetAiBillingSummaryErrors, GetAiBillingSummaryResponses, GetCodexConnectionData, GetCodexConnectionResponses, GetCursorApiKeyData, GetCursorApiKeyErrors, GetCursorApiKeyResponses, GetGithubPullRequestMergeabilityData, GetGithubPullRequestMergeabilityErrors, GetGithubPullRequestMergeabilityResponses, GetGtmInviteOfferData, GetGtmInviteOfferErrors, GetGtmInviteOfferResponses, GetLegacyUserPermissionsData, GetLegacyUserPermissionsErrors, GetLegacyUserPermissionsResponses, GetPermissionsData, GetPermissionsErrors, GetPermissionsResponses, GetReferralCodeData, GetReferralCodeErrors, GetReferralCodeResponses, GetSubscriptionStatusData, GetSubscriptionStatusErrors, GetSubscriptionStatusResponses, GetSystemStatusData, GetSystemStatusErrors, GetSystemStatusResponses, GetTeamByInviteLinkData, GetTeamByInviteLinkErrors, GetTeamByInviteLinkResponses, GetTeamData, GetTeamErrors, GetTeamInviteLinkData, GetTeamInviteLinkErrors, GetTeamInviteLinkResponses, GetTeamInvitesData, GetTeamInvitesErrors, GetTeamInvitesResponses, GetTeamResponses, GetTrialEligibilityData, GetTrialEligibilityErrors, GetTrialEligibilityResponses, GetUserInfoData, GetUserInfoErrors, GetUserInfoResponses, GetUserInvitesData, GetUserInvitesErrors, GetUserInvitesResponses, GetUserLanguageData, GetUserLanguageErrors, GetUserLanguageResponses, GetUserLinkExistsData, GetUserLinkExistsErrors, GetUserLinkExistsResponses, GetUserNameData, GetUserNameErrors, GetUserNameResponses, GetUserNamesData, GetUserNamesErrors, GetUserNamesResponses, GetUserNamesWithEmailData, GetUserNamesWithEmailErrors, GetUserNamesWithEmailResponses, GetUserOrganizationData, GetUserOrganizationErrors, GetUserOrganizationResponses, GetUserPermissionsData, GetUserPermissionsErrors, GetUserPermissionsResponses, GetUserQuotaData, GetUserQuotaErrors, GetUserQuotaResponses, GetUserTeamsData, GetUserTeamsErrors, GetUserTeamsResponses, HealthHandlerData, HealthHandlerResponses, InitGithubLinkData, InitGithubLinkErrors, InitGithubLinkResponses, InitGmailLinkData, InitGmailLinkErrors, InitGmailLinkResponses, InitOutlookLinkData, InitOutlookLinkErrors, InitOutlookLinkResponses, InviteToTeamData, InviteToTeamErrors, InviteToTeamResponses, JoinTeamByInviteLinkData, JoinTeamByInviteLinkErrors, JoinTeamByInviteLinkResponses, JoinTeamData, JoinTeamErrors, JoinTeamResponses, ListCodexEnvironmentsData, ListCodexEnvironmentsResponses, ListCursorModelsData, ListCursorModelsErrors, ListCursorModelsResponses, ListGtmInviteLinksData, ListGtmInviteLinksErrors, ListGtmInviteLinksResponses, ListSystemStatusHistoryData, ListSystemStatusHistoryErrors, ListSystemStatusHistoryResponses, LogoutData, LogoutResponses, MacroApiTokenData, MacroApiTokenErrors, MacroApiTokenResponses, MergeGithubPullRequestData, MergeGithubPullRequestErrors, MergeGithubPullRequestResponses, Oauth2CallbackData, Oauth2CallbackErrors, Oauth2CallbackResponses, OauthRedirectData, OauthRedirectErrors, OauthRedirectResponses, PasswordlessCallbackData, PasswordlessCallbackErrors, PasswordlessCallbackResponses, PasswordlessLoginData, PasswordlessLoginErrors, PasswordlessLoginResponses, PasswordLoginData, PasswordLoginErrors, PasswordLoginResponses, PatchTeamCrmSettingsData, PatchTeamCrmSettingsErrors, PatchTeamCrmSettingsResponses, PatchTeamData, PatchTeamErrors, PatchTeamMemberPlanData, PatchTeamMemberPlanErrors, PatchTeamMemberPlanResponses, PatchTeamResponses, PatchUserGroupData, PatchUserGroupErrors, PatchUserGroupResponses, PatchUserOnboardingData, PatchUserOnboardingErrors, PatchUserOnboardingResponses, PatchUserTutorialData, PatchUserTutorialErrors, PatchUserTutorialResponses, PollCodexLoginData, PollCodexLoginResponses, PostProfilePicturesData, PostProfilePicturesErrors, PostProfilePicturesResponses, PurchaseAiCreditsData, PurchaseAiCreditsErrors, PurchaseAiCreditsResponses, PutAgentApiKeyData, PutAgentApiKeyErrors, PutAgentApiKeyResponses, PutCursorApiKeyData, PutCursorApiKeyErrors, PutCursorApiKeyResponses, PutCursorDefaultModelData, PutCursorDefaultModelErrors, PutCursorDefaultModelResponses, PutProfilePictureData, PutProfilePictureErrors, PutProfilePictureResponses, PutUserLanguageData, PutUserLanguageErrors, PutUserLanguageResponses, PutUserNameData, PutUserNameErrors, PutUserNameResponses, RedeemGtmInviteLinkData, RedeemGtmInviteLinkErrors, RedeemGtmInviteLinkResponses, RefreshData, RefreshErrors, RefreshResponses, RejectInvitationData, RejectInvitationErrors, RejectInvitationResponses, RemoveUserFromTeamData, RemoveUserFromTeamErrors, RemoveUserFromTeamResponses, ResendFusionauthVerifyUserEmailData, ResendFusionauthVerifyUserEmailErrors, ResendFusionauthVerifyUserEmailResponses, ResolveGtmInviteLinkData, ResolveGtmInviteLinkErrors, ResolveGtmInviteLinkResponses, RevokeGtmInviteLinkData, RevokeGtmInviteLinkErrors, RevokeGtmInviteLinkResponses, SendMobileWelcomeEmailData, SendMobileWelcomeEmailErrors, SendMobileWelcomeEmailResponses, SendReferralCodeData, SendReferralCodeErrors, SendReferralCodeResponses, SessionCreationData, SessionCreationErrors, SessionCreationResponses, SessionLoginData, SessionLoginErrors, SessionLoginResponses, SetGithubPullRequestDraftData, SetGithubPullRequestDraftErrors, SetGithubPullRequestDraftResponses, SetGithubPullRequestStateData, SetGithubPullRequestStateErrors, SetGithubPullRequestStateResponses, SetSystemStatusData, SetSystemStatusErrors, SetSystemStatusResponses, SsoLoginData, SsoLoginErrors, SsoLoginResponses, StartCodexLoginData, StartCodexLoginResponses, ToggleTeamAutoJoinDomainData, ToggleTeamAutoJoinDomainErrors, ToggleTeamAutoJoinDomainResponses, ToggleTeamNonAdminInvitesData, ToggleTeamNonAdminInvitesErrors, ToggleTeamNonAdminInvitesResponses, UpdateAiBillingAutoReloadData, UpdateAiBillingAutoReloadErrors, UpdateAiBillingAutoReloadResponses, UpdateAiBillingOverageData, UpdateAiBillingOverageErrors, UpdateAiBillingOverageResponses, VerifyEmailLinkData, VerifyEmailLinkErrors, VerifyEmailLinkResponses, VerifyFusionauthUserEmailData, VerifyFusionauthUserEmailErrors, VerifyFusionauthUserEmailResponses, VerifyMergeRequestData, VerifyMergeRequestErrors, VerifyMergeRequestResponses } from './types.gen';
+import type { AppleLoginData, AppleLoginErrors, AppleLoginResponses, CancelCodexLoginData, CancelCodexLoginResponses, ChangePlanData, ChangePlanErrors, ChangePlanResponses, CheckGithubLinkStatusData, CheckGithubLinkStatusErrors, CheckGithubLinkStatusResponses, CheckGmailLinkStatusData, CheckGmailLinkStatusErrors, CheckGmailLinkStatusResponses, ConfigureCodexData, ConfigureCodexResponses, CreateAiCreditCheckoutData, CreateAiCreditCheckoutErrors, CreateAiCreditCheckoutResponses, CreateCheckoutSessionV2Data, CreateCheckoutSessionV2Errors, CreateCheckoutSessionV2Responses, CreateGtmInviteLinkData, CreateGtmInviteLinkErrors, CreateGtmInviteLinkResponses, CreateInProgressLinkData, CreateInProgressLinkErrors, CreateInProgressLinkResponses, CreateMergeRequestData, CreateMergeRequestErrors, CreateMergeRequestResponses, CreatePortalSessionData, CreatePortalSessionErrors, CreatePortalSessionResponses, CreateTeamData, CreateTeamErrors, CreateTeamInviteLinkData, CreateTeamInviteLinkErrors, CreateTeamInviteLinkResponses, CreateTeamResponses, DeleteAgentApiKeyData, DeleteAgentApiKeyErrors, DeleteAgentApiKeyResponses, DeleteCursorApiKeyData, DeleteCursorApiKeyErrors, DeleteCursorApiKeyResponses, DeleteGithubLinkData, DeleteGithubLinkErrors, DeleteGithubLinkResponses, DeleteTeamData, DeleteTeamErrors, DeleteTeamInviteHandlerData, DeleteTeamInviteHandlerErrors, DeleteTeamInviteHandlerResponses, DeleteTeamInviteLinkData, DeleteTeamInviteLinkErrors, DeleteTeamInviteLinkResponses, DeleteTeamResponses, DeleteUserData, DeleteUserErrors, DeleteUserResponses, DisconnectCodexData, DisconnectCodexResponses, EmailConnectionProvidersData, EmailConnectionProvidersErrors, EmailConnectionProvidersResponses, EnrichGithubPullRequestsData, EnrichGithubPullRequestsErrors, EnrichGithubPullRequestsResponses, GenerateEmailLinkData, GenerateEmailLinkErrors, GenerateEmailLinkResponses, GetAgentApiKeyData, GetAgentApiKeyErrors, GetAgentApiKeyResponses, GetAiBillingPlansData, GetAiBillingPlansResponses, GetAiBillingSummaryData, GetAiBillingSummaryErrors, GetAiBillingSummaryResponses, GetCodexConnectionData, GetCodexConnectionResponses, GetCursorApiKeyData, GetCursorApiKeyErrors, GetCursorApiKeyResponses, GetGithubPullRequestMergeabilityData, GetGithubPullRequestMergeabilityErrors, GetGithubPullRequestMergeabilityResponses, GetGtmInviteOfferData, GetGtmInviteOfferErrors, GetGtmInviteOfferResponses, GetLegacyUserPermissionsData, GetLegacyUserPermissionsErrors, GetLegacyUserPermissionsResponses, GetPermissionsData, GetPermissionsErrors, GetPermissionsResponses, GetReferralCodeData, GetReferralCodeErrors, GetReferralCodeResponses, GetSubscriptionStatusData, GetSubscriptionStatusErrors, GetSubscriptionStatusResponses, GetSystemStatusData, GetSystemStatusErrors, GetSystemStatusResponses, GetTeamByInviteLinkData, GetTeamByInviteLinkErrors, GetTeamByInviteLinkResponses, GetTeamData, GetTeamErrors, GetTeamInviteLinkData, GetTeamInviteLinkErrors, GetTeamInviteLinkResponses, GetTeamInvitesData, GetTeamInvitesErrors, GetTeamInvitesResponses, GetTeamResponses, GetTrialEligibilityData, GetTrialEligibilityErrors, GetTrialEligibilityResponses, GetUserInfoData, GetUserInfoErrors, GetUserInfoResponses, GetUserInvitesData, GetUserInvitesErrors, GetUserInvitesResponses, GetUserLanguageData, GetUserLanguageErrors, GetUserLanguageResponses, GetUserLinkExistsData, GetUserLinkExistsErrors, GetUserLinkExistsResponses, GetUserNameData, GetUserNameErrors, GetUserNameResponses, GetUserNamesData, GetUserNamesErrors, GetUserNamesResponses, GetUserNamesWithEmailData, GetUserNamesWithEmailErrors, GetUserNamesWithEmailResponses, GetUserOrganizationData, GetUserOrganizationErrors, GetUserOrganizationResponses, GetUserPermissionsData, GetUserPermissionsErrors, GetUserPermissionsResponses, GetUserQuotaData, GetUserQuotaErrors, GetUserQuotaResponses, GetUserTeamsData, GetUserTeamsErrors, GetUserTeamsResponses, HealthHandlerData, HealthHandlerResponses, InitGithubLinkData, InitGithubLinkErrors, InitGithubLinkResponses, InitGmailLinkData, InitGmailLinkErrors, InitGmailLinkResponses, InitOutlookLinkData, InitOutlookLinkErrors, InitOutlookLinkResponses, InviteToTeamData, InviteToTeamErrors, InviteToTeamResponses, JoinTeamByInviteLinkData, JoinTeamByInviteLinkErrors, JoinTeamByInviteLinkResponses, JoinTeamData, JoinTeamErrors, JoinTeamResponses, ListCodexEnvironmentsData, ListCodexEnvironmentsResponses, ListCursorModelsData, ListCursorModelsErrors, ListCursorModelsResponses, ListGtmInviteLinksData, ListGtmInviteLinksErrors, ListGtmInviteLinksResponses, ListSystemStatusHistoryData, ListSystemStatusHistoryErrors, ListSystemStatusHistoryResponses, LogoutData, LogoutResponses, MacroApiTokenData, MacroApiTokenErrors, MacroApiTokenResponses, MergeGithubPullRequestData, MergeGithubPullRequestErrors, MergeGithubPullRequestResponses, Oauth2CallbackData, Oauth2CallbackErrors, Oauth2CallbackResponses, OauthRedirectData, OauthRedirectErrors, OauthRedirectResponses, PasswordlessCallbackData, PasswordlessCallbackErrors, PasswordlessCallbackResponses, PasswordlessLoginData, PasswordlessLoginErrors, PasswordlessLoginResponses, PasswordLoginData, PasswordLoginErrors, PasswordLoginResponses, PatchTeamCrmSettingsData, PatchTeamCrmSettingsErrors, PatchTeamCrmSettingsResponses, PatchTeamData, PatchTeamErrors, PatchTeamMemberPlanData, PatchTeamMemberPlanErrors, PatchTeamMemberPlanResponses, PatchTeamResponses, PatchUserGroupData, PatchUserGroupErrors, PatchUserGroupResponses, PatchUserOnboardingData, PatchUserOnboardingErrors, PatchUserOnboardingResponses, PatchUserTutorialData, PatchUserTutorialErrors, PatchUserTutorialResponses, PollCodexLoginData, PollCodexLoginResponses, PostProfilePicturesData, PostProfilePicturesErrors, PostProfilePicturesResponses, PurchaseAiCreditsData, PurchaseAiCreditsErrors, PurchaseAiCreditsResponses, PutAgentApiKeyData, PutAgentApiKeyErrors, PutAgentApiKeyResponses, PutCursorApiKeyData, PutCursorApiKeyErrors, PutCursorApiKeyResponses, PutCursorDefaultModelData, PutCursorDefaultModelErrors, PutCursorDefaultModelResponses, PutProfilePictureData, PutProfilePictureErrors, PutProfilePictureResponses, PutUserLanguageData, PutUserLanguageErrors, PutUserLanguageResponses, PutUserNameData, PutUserNameErrors, PutUserNameResponses, RedeemGtmInviteLinkData, RedeemGtmInviteLinkErrors, RedeemGtmInviteLinkResponses, RefreshData, RefreshErrors, RefreshResponses, RejectInvitationData, RejectInvitationErrors, RejectInvitationResponses, RemoveUserFromTeamData, RemoveUserFromTeamErrors, RemoveUserFromTeamResponses, ResendFusionauthVerifyUserEmailData, ResendFusionauthVerifyUserEmailErrors, ResendFusionauthVerifyUserEmailResponses, ResolveGtmInviteLinkData, ResolveGtmInviteLinkErrors, ResolveGtmInviteLinkResponses, RevokeGtmInviteLinkData, RevokeGtmInviteLinkErrors, RevokeGtmInviteLinkResponses, SendMobileWelcomeEmailData, SendMobileWelcomeEmailErrors, SendMobileWelcomeEmailResponses, SendReferralCodeData, SendReferralCodeErrors, SendReferralCodeResponses, SendTeamDomainNoticeData, SendTeamDomainNoticeErrors, SendTeamDomainNoticeResponses, SessionCreationData, SessionCreationErrors, SessionCreationResponses, SessionLoginData, SessionLoginErrors, SessionLoginResponses, SetGithubPullRequestDraftData, SetGithubPullRequestDraftErrors, SetGithubPullRequestDraftResponses, SetGithubPullRequestStateData, SetGithubPullRequestStateErrors, SetGithubPullRequestStateResponses, SetSystemStatusData, SetSystemStatusErrors, SetSystemStatusResponses, SsoLoginData, SsoLoginErrors, SsoLoginResponses, StartCodexLoginData, StartCodexLoginResponses, ToggleTeamAutoJoinDomainData, ToggleTeamAutoJoinDomainErrors, ToggleTeamAutoJoinDomainResponses, ToggleTeamNonAdminInvitesData, ToggleTeamNonAdminInvitesErrors, ToggleTeamNonAdminInvitesResponses, UpdateAiBillingAutoReloadData, UpdateAiBillingAutoReloadErrors, UpdateAiBillingAutoReloadResponses, UpdateAiBillingOverageData, UpdateAiBillingOverageErrors, UpdateAiBillingOverageResponses, VerifyEmailLinkData, VerifyEmailLinkErrors, VerifyEmailLinkResponses, VerifyFusionauthUserEmailData, VerifyFusionauthUserEmailErrors, VerifyFusionauthUserEmailResponses, VerifyMergeRequestData, VerifyMergeRequestErrors, VerifyMergeRequestResponses } from './types.gen';
export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown> = Options2<TData, ThrowOnError, TResponse> & {
/**
@@ -826,6 +826,17 @@ export class Sdk extends HeyApiClient {
});
}
+ /**
+ * Emails the caller's contacts on the team's auto-join domain that the team
+ * exists, so they can sign up and join. Contacts already on Macro, on the
+ * team, invited, or emailed before are skipped, and a team emails at most 25
+ * people in total. Call it after sending the team's invites. Requires the
+ * caller to be an Admin or Owner of the team.
+ */
+ public sendTeamDomainNotice<ThrowOnError extends boolean = false>(options?: Options<SendTeamDomainNoticeData, ThrowOnError>): RequestResult<SendTeamDomainNoticeResponses, SendTeamDomainNoticeErrors, ThrowOnError> {
+ return (options?.client ?? this.client).post<SendTeamDomainNoticeResponses, SendTeamDomainNoticeErrors, ThrowOnError>({ url: '/team/domain-notice', ...options });
+ }
+
/**
* Invites a user to a team.
*/
diff --git a/packages/sdk/generated/auth/types.gen.ts b/packages/sdk/generated/auth/types.gen.ts
index 0f7935721b..e699e19524 100644
--- a/packages/sdk/generated/auth/types.gen.ts
+++ b/packages/sdk/generated/auth/types.gen.ts
@@ -334,6 +334,11 @@ export type CreatePortalSessionRequest = {
* The request body to create a new team
*/
export type CreateTeamRequest = {
+ /**
+ * Whether colleagues who sign up with the owner's work email domain join
+ * the team automatically. Ignored for generic email providers.
+ */
+ allow_domain_join?: boolean;
/**
* The name of the team
*/
@@ -1621,6 +1626,16 @@ export type ScheduledSeatPlan = {
*/
export type SeatPlan = 'premium' | 'max';
+/**
+ * Response for the domain notice endpoint.
+ */
+export type SendDomainNoticeResponse = {
+ /**
+ * How many colleagues were emailed by this call.
+ */
+ sent: number;
+};
+
/**
* The body which is used to describe the recipient email
*/
@@ -3957,6 +3972,27 @@ export type PatchTeamCrmSettingsResponses = {
export type PatchTeamCrmSettingsResponse2 = PatchTeamCrmSettingsResponses[keyof PatchTeamCrmSettingsResponses];
+export type SendTeamDomainNoticeData = {
+ body?: never;
+ path?: never;
+ query?: never;
+ url: '/team/domain-notice';
+};
+
+export type SendTeamDomainNoticeErrors = {
+ 401: ErrorResponse;
+ 403: ErrorResponse;
+ 500: ErrorResponse;
+};
+
+export type SendTeamDomainNoticeError = SendTeamDomainNoticeErrors[keyof SendTeamDomainNoticeErrors];
+
+export type SendTeamDomainNoticeResponses = {
+ 200: SendDomainNoticeResponse;
+};
+
+export type SendTeamDomainNoticeResponse = SendTeamDomainNoticeResponses[keyof SendTeamDomainNoticeResponses];
+
export type InviteToTeamData = {
body: InviteToTeamRequest;
path?: never;
diff --git a/packages/sdk/specs/auth.json b/packages/sdk/specs/auth.json
index 77d4bd111d..4cfe94ebd6 100644
--- a/packages/sdk/specs/auth.json
+++ b/packages/sdk/specs/auth.json
@@ -4198,6 +4198,55 @@
}
}
},
+ "/team/domain-notice": {
+ "post": {
+ "tags": ["teams::inbound::axum_router::domain_notice"],
+ "summary": "Emails the caller's contacts on the team's auto-join domain that the team\nexists, so they can sign up and join. Contacts already on Macro, on the\nteam, invited, or emailed before are skipped, and a team emails at most 25\npeople in total. Call it after sending the team's invites. Requires the\ncaller to be an Admin or Owner of the team.",
+ "operationId": "send_team_domain_notice",
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/SendDomainNoticeResponse"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "403": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/team/invite": {
"post": {
"tags": ["teams::inbound::axum_router::invite_to_team"],
@@ -6627,6 +6676,10 @@
"description": "The request body to create a new team",
"required": ["name"],
"properties": {
+ "allow_domain_join": {
+ "type": "boolean",
+ "description": "Whether colleagues who sign up with the owner's work email domain join\nthe team automatically. Ignored for generic email providers."
+ },
"name": {
"type": "string",
"description": "The name of the team"
@@ -8310,6 +8363,19 @@
"description": "The paid plan a seat is billed at. Every member of a paying team has one;\na team may mix them, and its Stripe subscription carries one seat item per\nplan in use.",
"enum": ["premium", "max"]
},
+ "SendDomainNoticeResponse": {
+ "type": "object",
+ "description": "Response for the domain notice endpoint.",
+ "required": ["sent"],
+ "properties": {
+ "sent": {
+ "type": "integer",
+ "format": "int32",
+ "description": "How many colleagues were emailed by this call.",
+ "minimum": 0
+ }
+ }
+ },
"SendInviteBody": {
"type": "object",
"description": "The body which is used to describe the recipient email",
diff --git a/packages/sdk/src/coverage/skipped.ts b/packages/sdk/src/coverage/skipped.ts
index 630ceb1a69..7e510b187a 100644
--- a/packages/sdk/src/coverage/skipped.ts
+++ b/packages/sdk/src/coverage/skipped.ts
@@ -135,6 +135,7 @@ export const authExcluded = [
'resolveGtmInviteLink',
'revokeGtmInviteLink',
'sendMobileWelcomeEmail',
+ 'sendTeamDomainNotice',
'sendReferralCode',
'sessionCreation',
'sessionLogin',
diff --git a/services/authentication_service/src/api.rs b/services/authentication_service/src/api.rs
index fffa988ce7..fbd72ee204 100644
--- a/services/authentication_service/src/api.rs
+++ b/services/authentication_service/src/api.rs
@@ -142,6 +142,15 @@ fn api_router(state: ApiContext) -> Router<ApiContext> {
},
),
)
+ .merge(
+ teams::inbound::axum_router::domain_notice::domain_notice_router(
+ teams::inbound::axum_router::domain_notice::DomainNoticeRouterState {
+ service: state.domain_notice_service.clone(),
+ entity_access_service: state.entity_access_service.clone(),
+ authorization_state: state.authorization_state.clone(),
+ },
+ ),
+ )
.nest(
"/referral",
referral::inbound::axum_router::referral_router(
diff --git a/services/authentication_service/src/api/context.rs b/services/authentication_service/src/api/context.rs
index 5dc8019afc..168fb69b14 100644
--- a/services/authentication_service/src/api/context.rs
+++ b/services/authentication_service/src/api/context.rs
@@ -113,6 +113,16 @@ pub(crate) type SubscriptionStatusServiceType =
>,
>;
+pub(crate) type DomainNoticeServiceType = teams::domain::domain_notice::DomainNoticeServiceImpl<
+ teams::outbound::colleague_directory::ContactsColleagueDirectory<
+ contacts::outbound::repository::DbContactsRepository,
+ >,
+ teams::domain::join_announcement::JoinAnnouncementServiceImpl<
+ teams::outbound::join_announcement_repo::JoinAnnouncementRepositoryImpl,
+ NotificationIngressType,
+ >,
+>;
+
pub(crate) type TeamsServiceType = teams::domain::team_service::TeamServiceImpl<
teams::outbound::team_repo::TeamRepositoryImpl,
teams::outbound::customer_repo::CustomerRepositoryImpl,
@@ -234,6 +244,7 @@ pub(crate) struct ApiContext {
pub user_roles_and_permissions_service:
Arc<UserRolesAndPermissionsServiceImpl<MacroDB, MacroDB>>, // Note: since FromRef doesn't support generics we have to specify the concrete types here
pub teams_service: Arc<TeamsServiceType>,
+ pub domain_notice_service: Arc<DomainNoticeServiceType>,
pub channel_service: Arc<ChannelServiceType>,
pub channel_messages: Arc<dyn messages::domain::api::MessageCommands>,
pub favorites_service: Arc<FavoritesServiceType>,
diff --git a/services/authentication_service/src/api/swagger.rs b/services/authentication_service/src/api/swagger.rs
index 557c09707b..1aadf916b9 100644
--- a/services/authentication_service/src/api/swagger.rs
+++ b/services/authentication_service/src/api/swagger.rs
@@ -20,6 +20,7 @@ use teams::domain::model::{
PatchTeamRequest, PatchTeamUserRole, Team, TeamInviteDetails, TeamInviteLinkTeam,
TeamInviteLinkToken, TeamMember, TeamPlan, TeamRole, TeamWithMembers,
};
+use teams::inbound::axum_router::domain_notice::SendDomainNoticeResponse;
use teams::inbound::axum_router::get_team_invites::TeamInvitesResponse as TeamTeamInvitesResponse;
use teams::inbound::axum_router::get_user_invites::TeamInvitesResponse as UserTeamInvitesResponse;
use teams::inbound::axum_router::invite_link::{
@@ -191,6 +192,7 @@ use model::user::{
teams::inbound::axum_router::patch_team::handler::<crate::api::context::TeamsServiceType, crate::api::context::EntityAccessServiceType, crate::api::context::AuthorizationService>,
teams::inbound::axum_router::patch_team_crm_settings::handler::<crate::api::context::TeamsServiceType, crate::api::context::EntityAccessServiceType, crate::api::context::AuthorizationService>,
teams::inbound::axum_router::toggle_auto_join_domain::handler::<crate::api::context::TeamsServiceType, crate::api::context::EntityAccessServiceType, crate::api::context::AuthorizationService>,
+ teams::inbound::axum_router::domain_notice::handler::<crate::api::context::DomainNoticeServiceType, crate::api::context::EntityAccessServiceType, crate::api::context::AuthorizationService>,
teams::inbound::axum_router::toggle_non_admin_invites::handler::<crate::api::context::TeamsServiceType, crate::api::context::EntityAccessServiceType, crate::api::context::AuthorizationService>,
teams::inbound::axum_router::reject_invitation::handler::<crate::api::context::TeamsServiceType, crate::api::context::EntityAccessServiceType, crate::api::context::AuthorizationService>,
teams::inbound::axum_router::get_user_invites::handler::<crate::api::context::TeamsServiceType, crate::api::context::EntityAccessServiceType, crate::api::context::AuthorizationService>,
@@ -359,6 +361,7 @@ use model::user::{
PatchTeamCrmSettingsRequest,
PatchTeamCrmSettingsResponse,
ToggleAutoJoinDomainResponse,
+ SendDomainNoticeResponse,
ToggleNonAdminInvitesResponse,
TeamInviteLinkResponse,
CreatedTeamInviteLinkResponse,
diff --git a/services/authentication_service/src/server.rs b/services/authentication_service/src/server.rs
index 14d681c6dd..2891e2f7ce 100644
--- a/services/authentication_service/src/server.rs
+++ b/services/authentication_service/src/server.rs
@@ -671,6 +671,23 @@ pub async fn run() -> anyhow::Result<()> {
.with_open_seat_release((*ai_billing_service).clone())
.with_owned_entity_cleanup(team_owned_entity_cleanup);
let teams_service = Arc::new(teams_service_impl);
+ let domain_notice_service =
+ Arc::new(teams::domain::domain_notice::DomainNoticeServiceImpl::new(
+ teams::outbound::colleague_directory::ContactsColleagueDirectory::new(
+ contacts::outbound::repository::DbContactsRepository::new(db.clone()),
+ ),
+ teams::domain::join_announcement::JoinAnnouncementServiceImpl::new(
+ teams::outbound::join_announcement_repo::JoinAnnouncementRepositoryImpl::new(
+ db.clone(),
+ ),
+ SqsNotificationIngress {
+ queue: SqsQueue::new(
+ aws_sdk_sqs::Client::new(&aws_config),
+ notification_queue.to_string(),
+ ),
+ },
+ ),
+ ));
// Reminds people of team invites they have not answered. Replicas claim
// disjoint invites, so every replica sweeps.
let invite_reminders_stop = CancellationToken::new();
@@ -773,6 +790,7 @@ pub async fn run() -> anyhow::Result<()> {
stripe_webhook_secret,
user_roles_and_permissions_service: Arc::new(user_roles_and_permissions_service),
teams_service,
+ domain_notice_service,
channel_service: Arc::new(channel_service),
channel_messages,
favorites_service: Arc::new(favorites_service),
diff --git a/services/notification_service/src/api/user_notification.rs b/services/notification_service/src/api/user_notification.rs
index 8c248f7f63..39077b5677 100644
--- a/services/notification_service/src/api/user_notification.rs
+++ b/services/notification_service/src/api/user_notification.rs
@@ -33,6 +33,7 @@ use crate::api::context::AuthorizationService;
pub(crate) static BLOCKABLE_NOTIFICATIONS: LazyLock<HashSet<&'static str>> = LazyLock::new(|| {
HashSet::from([
EmailDigestNotification::TYPE_NAME,
+ model_notifications::ColleagueJoinedMacro::TYPE_NAME,
NewEmailMetadata::TYPE_NAME,
AiResponseMetadata::TYPE_NAME,
ChannelMessageSendMetadata::TYPE_NAME,
diff --git a/services/notification_service/src/main.rs b/services/notification_service/src/main.rs
index abe5eb6699..9556a9059e 100644
--- a/services/notification_service/src/main.rs
+++ b/services/notification_service/src/main.rs
@@ -5,7 +5,7 @@ use ::notification::domain::models::email_notification_digest::ports::DigestBatc
use ::notification::domain::service::NotificationEgressService;
use ::notification::inbound::notification_events_listener::NotificationEventsListener;
use ::notification::inbound::worker::NotificationWorker;
-use ::notification::outbound::email::EmailAdapter;
+use ::notification::outbound::email::{EmailAdapter, SignedUnsubscribeLinks};
use ::notification::outbound::fanout_notification_realtime::FanoutNotificationRealtimePublisher;
use ::notification::outbound::fanout_realtime::FanoutRealtimeSender;
use ::notification::outbound::kafka_notification_realtime::KafkaNotificationRealtimePublisher;
@@ -232,7 +232,12 @@ pub async fn main() -> anyhow::Result<()> {
};
let ses_client = aws_sdk_sesv2::Client::new(&aws_config);
- let email_adapter = EmailAdapter::new(ses_client, crate::env::SENDER_ADDRESS.clone());
+ let email_adapter = SignedUnsubscribeLinks::new(
+ EmailAdapter::new(ses_client, crate::env::SENDER_ADDRESS.clone()),
+ macro_service_urls::NotificationServiceUrl::new_for_environment(config.environment)?
+ .parse_url()?,
+ hmac_key.clone(),
+ );
let redis_multiplexed_conn = redis_client
.get_multiplexed_async_connection()
diff --git a/services/slack_import_worker/AGENTS.md b/services/slack_import_worker/AGENTS.md
index f7f0407359..09e2d1f29d 100644
--- a/services/slack_import_worker/AGENTS.md
+++ b/services/slack_import_worker/AGENTS.md
@@ -4,8 +4,7 @@
Onboards new Channels (chat) customers from Slack: a composition root for
importing Slack archive exports. Writes conversations, messages, and
-references into Macro as channels, and sends one best-effort colleague-join
-email.
+references into Macro as channels. It sends no emails or notifications.
## Start here
@@ -16,8 +15,7 @@ email.
- `src/composition/channel_sink.rs`: writes imported conversations as channels.
- `src/composition/reference_reconciliation.rs` + `src/composition/references.rs`:
resolving cross-message references (replies, mentions) after import.
-- `src/composition/authorizer.rs`, `src/composition/join_announcer.rs`: access
- checks and the join-email side effect.
+- `src/composition/authorizer.rs`: access checks.
- `tests/archive_import.rs` + `tests/archive_import/`: end-to-end import tests,
including kill/recovery behavior (`process_recovery.rs`, `kill_boundaries.sql`).
diff --git a/services/slack_import_worker/Cargo.toml b/services/slack_import_worker/Cargo.toml
index 4693db30a9..f613a21819 100644
--- a/services/slack_import_worker/Cargo.toml
+++ b/services/slack_import_worker/Cargo.toml
@@ -21,13 +21,11 @@ macro_service_urls = { path = "../../crates/macro_service_urls" }
macro_user_id = { path = "../../crates/macro_user_id" }
mention_utils = { path = "../../crates/mention_utils" }
messages = { path = "../../crates/messages", features = ["outbound"] }
-notification = { path = "../../crates/notification" }
rootcause = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
slack_integration = { path = "../../crates/slack_integration", features = ["postgres", "s3", "sqs", "search", "worker"] }
sqlx = { workspace = true }
-teams = { path = "../../crates/teams", default-features = false, features = ["outbound"] }
tokio = { workspace = true }
tokio-util = { workspace = true }
tracing = { workspace = true }
diff --git a/services/slack_import_worker/src/composition.rs b/services/slack_import_worker/src/composition.rs
index c41487a92a..16c48631a3 100644
--- a/services/slack_import_worker/src/composition.rs
+++ b/services/slack_import_worker/src/composition.rs
@@ -2,7 +2,6 @@
pub mod authorizer;
pub mod channel_sink;
-pub mod join_announcer;
pub mod reference_reconciliation;
pub mod references;
diff --git a/services/slack_import_worker/src/composition/join_announcer.rs b/services/slack_import_worker/src/composition/join_announcer.rs
deleted file mode 100644
index 81a3d9e9e9..0000000000
--- a/services/slack_import_worker/src/composition/join_announcer.rs
+++ /dev/null
@@ -1,53 +0,0 @@
-//! Forwards a bound conversation to the teams join-announcement service.
-
-#[cfg(test)]
-mod test;
-
-use slack_integration::domain::{
- models::ImportError,
- ports::{JoinAnnouncement, JoinAnnouncer, PortResult},
-};
-use teams::domain::join_announcement::{AnnounceJoin, JoinAnnouncementService};
-use uuid::Uuid;
-
-/// Forwards a bound conversation when the deployment kill switch is on.
-#[derive(Clone)]
-pub struct WorkerJoinAnnouncer<S> {
- service: S,
- enabled: bool,
-}
-
-impl<S> WorkerJoinAnnouncer<S> {
- /// `enabled` is the kill switch. Off drops the announcement before the service runs.
- pub fn new(service: S, enabled: bool) -> Self {
- Self { service, enabled }
- }
-}
-
-impl<S: JoinAnnouncementService> JoinAnnouncer for WorkerJoinAnnouncer<S> {
- async fn announce(&self, announcement: JoinAnnouncement) -> PortResult<()> {
- if !self.enabled {
- return Ok(());
- }
- let team_id = Uuid::from(announcement.team_id);
- let report = self
- .service
- .announce_join(AnnounceJoin {
- team_id,
- joined: announcement.joined,
- joined_name: announcement.joined_name,
- candidates: announcement.members,
- })
- .await
- .map_err(|error| error.context(ImportError::Internal))?;
- if report.claimed > 0 {
- tracing::info!(
- operation = "join_announcement",
- %team_id,
- ?report,
- "colleague join emails enqueued"
- );
- }
- Ok(())
- }
-}
diff --git a/services/slack_import_worker/src/composition/join_announcer/test.rs b/services/slack_import_worker/src/composition/join_announcer/test.rs
deleted file mode 100644
index 5bee7470b0..0000000000
--- a/services/slack_import_worker/src/composition/join_announcer/test.rs
+++ /dev/null
@@ -1,83 +0,0 @@
-use std::sync::{Arc, Mutex};
-
-use macro_user_id::user_id::MacroUserIdStr;
-use rootcause::Report;
-use slack_integration::domain::{
- models::ImportError,
- ports::{JoinAnnouncement, JoinAnnouncer},
-};
-use teams::domain::join_announcement::{
- AnnounceJoin, AnnounceReport, JoinAnnouncementError, JoinAnnouncementService,
-};
-use uuid::Uuid;
-
-use super::WorkerJoinAnnouncer;
-
-#[derive(Clone, Default)]
-struct RecordingService {
- calls: Arc<Mutex<Vec<AnnounceJoin>>>,
- fail: bool,
-}
-
-impl JoinAnnouncementService for RecordingService {
- async fn announce_join(
- &self,
- request: AnnounceJoin,
- ) -> Result<AnnounceReport, Report<JoinAnnouncementError>> {
- self.calls.lock().unwrap().push(request);
- if self.fail {
- Err(Report::new(JoinAnnouncementError::Storage))
- } else {
- Ok(AnnounceReport {
- claimed: 1,
- sent: 1,
- released: 0,
- })
- }
- }
-}
-
-fn announcement() -> JoinAnnouncement {
- JoinAnnouncement {
- team_id: Uuid::from_u128(1).try_into().unwrap(),
- joined: MacroUserIdStr::try_from_email("[email protected]").unwrap(),
- joined_name: Some("Admin".to_owned()),
- members: vec![
- MacroUserIdStr::try_from_email("[email protected]").unwrap(),
- MacroUserIdStr::try_from_email("[email protected]").unwrap(),
- ],
- }
-}
-
-#[tokio::test]
-async fn disabled_announcer_drops_the_offer() {
- let service = RecordingService::default();
- let announcer = WorkerJoinAnnouncer::new(service.clone(), false);
- announcer.announce(announcement()).await.unwrap();
- assert!(service.calls.lock().unwrap().is_empty());
-}
-
-#[tokio::test]
-async fn enabled_announcer_maps_the_offer_unchanged() {
- let service = RecordingService::default();
- let announcer = WorkerJoinAnnouncer::new(service.clone(), true);
- let announcement = announcement();
- announcer.announce(announcement.clone()).await.unwrap();
- let calls = service.calls.lock().unwrap();
- assert_eq!(calls.len(), 1);
- assert_eq!(calls[0].team_id, Uuid::from(announcement.team_id));
- assert_eq!(calls[0].joined, announcement.joined);
- assert_eq!(calls[0].joined_name.as_deref(), Some("Admin"));
- assert_eq!(calls[0].candidates, announcement.members);
-}
-
-#[tokio::test]
-async fn service_storage_error_becomes_internal() {
- let service = RecordingService {
- fail: true,
- ..RecordingService::default()
- };
- let announcer = WorkerJoinAnnouncer::new(service, true);
- let error = announcer.announce(announcement()).await.unwrap_err();
- assert_eq!(error.into_current_context(), ImportError::Internal);
-}
diff --git a/services/slack_import_worker/src/config.rs b/services/slack_import_worker/src/config.rs
index 28a1b5fae9..f3aad08361 100644
--- a/services/slack_import_worker/src/config.rs
+++ b/services/slack_import_worker/src/config.rs
@@ -19,9 +19,6 @@ pub struct Config {
/// Pause new claims and outbox sends, not reconciliation or queues.
#[macro_config_default(false)]
pub slack_import_enabled: bool,
- /// One-time colleague emails on import. Off by default: emails cannot be recalled.
- #[macro_config_default(false)]
- pub slack_import_join_email_enabled: bool,
/// Initially one; fail startup above two rather than silently widening work.
#[macro_config_default(1)]
pub slack_import_concurrency: u8,
diff --git a/services/slack_import_worker/src/config/test.rs b/services/slack_import_worker/src/config/test.rs
index 295cc986a4..2c96d709a3 100644
--- a/services/slack_import_worker/src/config/test.rs
+++ b/services/slack_import_worker/src/config/test.rs
@@ -9,23 +9,10 @@ fn rollout_defaults_are_disabled_and_single_slot() {
}))
.unwrap();
assert!(!config.slack_import_enabled);
- assert!(!config.slack_import_join_email_enabled);
assert_eq!(config.slack_import_concurrency, 1);
assert!(config.worker().is_ok());
}
-#[test]
-fn join_email_flag_follows_slack_import_join_email_enabled() {
- let config: Config = serde_json::from_value(serde_json::json!({
- "DATABASE_URL": "postgres://localhost/test",
- "UPLOAD_STAGING_BUCKET": "test-staging",
- "INTERNAL_API_KEY": "test-only",
- "SLACK_IMPORT_JOIN_EMAIL_ENABLED": true
- }))
- .unwrap();
- assert!(config.slack_import_join_email_enabled);
-}
-
#[test]
fn rejects_unbounded_or_zero_concurrency_at_startup() {
for concurrency in [0, 3, 255] {
diff --git a/services/slack_import_worker/src/lib.rs b/services/slack_import_worker/src/lib.rs
index aad0b0f16b..27c0a8bd8d 100644
--- a/services/slack_import_worker/src/lib.rs
+++ b/services/slack_import_worker/src/lib.rs
@@ -1,4 +1,4 @@
#![deny(missing_docs)]
-//! Composition for fenced Slack archive persistence and one best-effort colleague join email.
+//! Composition for fenced Slack archive persistence.
pub mod composition;
diff --git a/services/slack_import_worker/src/main.rs b/services/slack_import_worker/src/main.rs
index b5fa013d47..e625caf788 100644
--- a/services/slack_import_worker/src/main.rs
+++ b/services/slack_import_worker/src/main.rs
@@ -9,12 +9,11 @@ use chrono::{DateTime, Utc};
use entity_access::{domain::service::EntityAccessServiceImpl, outbound::PgAccessRepository};
use import::outbound::pg_import_repo::PgImportRepo;
use macro_entrypoint::{MacroEntrypoint, shutdown_signal};
-use macro_queues::{NotificationIngressQueue, SlackImportDlq, SlackImportQueue};
+use macro_queues::{SlackImportDlq, SlackImportQueue};
use macro_service_urls::SearchProcessingServiceUrl;
-use notification::{domain::service::SqsNotificationIngress, outbound::queue::SqsQueue};
use slack_import_worker::composition::{
authorizer::WorkerAuthorizer, channel_sink::ChannelImportSink,
- join_announcer::WorkerJoinAnnouncer, reference_reconciliation::WorkerReferenceReconciler,
+ reference_reconciliation::WorkerReferenceReconciler,
};
use slack_integration::{
domain::{
@@ -31,10 +30,6 @@ use slack_integration::{
},
};
use sqlx::postgres::PgPoolOptions;
-use teams::{
- domain::join_announcement::JoinAnnouncementServiceImpl,
- outbound::join_announcement_repo::JoinAnnouncementRepositoryImpl,
-};
use tokio_util::sync::CancellationToken;
use uuid::Uuid;
@@ -77,22 +72,9 @@ async fn run() -> Result<(), rootcause::Report> {
limits,
)?;
let sqs = aws_sdk_sqs::Client::new(&macro_aws_config::get_macro_aws_config().await);
- let queue = SqsImportQueue::new(
- sqs.clone(),
- &SlackImportQueue::new(),
- &SlackImportDlq::new(),
- )
- .await
- .map_err(|error| *error.current_context())?;
- let announcer = WorkerJoinAnnouncer::new(
- JoinAnnouncementServiceImpl::new(
- JoinAnnouncementRepositoryImpl::new(pool.clone()),
- SqsNotificationIngress {
- queue: SqsQueue::new(sqs, NotificationIngressQueue::new().to_string()),
- },
- ),
- config.slack_import_join_email_enabled,
- );
+ let queue = SqsImportQueue::new(sqs, &SlackImportQueue::new(), &SlackImportDlq::new())
+ .await
+ .map_err(|error| *error.current_context())?;
let search = HttpSearchBackfill::new(
SearchProcessingServiceUrl::new()?.as_ref(),
&config.internal_api_key,
@@ -104,7 +86,6 @@ async fn run() -> Result<(), rootcause::Report> {
sink.clone(),
sink,
authorizer,
- announcer,
ImporterConfig { limits },
)?;
let maintenance = ImportMaintenance::new(
diff --git a/services/slack_import_worker/tests/archive_import.rs b/services/slack_import_worker/tests/archive_import.rs
index e3ce93f7d9..313ad212da 100644
--- a/services/slack_import_worker/tests/archive_import.rs
+++ b/services/slack_import_worker/tests/archive_import.rs
@@ -20,11 +20,10 @@ use entity_access::{
use import::outbound::pg_import_repo::PgImportRepo;
use macro_queues::{SlackImportDlq, SlackImportQueue};
use macro_user_id::user_id::MacroUserIdStr;
-use notification::{domain::service::SqsNotificationIngress, outbound::queue::SqsQueue};
use sha2::{Digest, Sha256};
use slack_import_worker::composition::{
authorizer::WorkerAuthorizer, channel_sink::ChannelImportSink,
- join_announcer::WorkerJoinAnnouncer, reference_reconciliation::WorkerReferenceReconciler,
+ reference_reconciliation::WorkerReferenceReconciler,
};
use slack_integration::{
domain::{
@@ -41,10 +40,6 @@ use slack_integration::{
},
};
use sqlx::PgPool;
-use teams::{
- domain::join_announcement::JoinAnnouncementServiceImpl,
- outbound::join_announcement_repo::JoinAnnouncementRepositoryImpl,
-};
use tokio::time::{sleep, timeout};
use tokio_util::sync::CancellationToken;
use uuid::Uuid;
@@ -120,8 +115,6 @@ struct Resources {
storage: S3ImportStorage,
queue: SqsImportQueue,
process: process_recovery::ProcessConfig,
- sqs: aws_sdk_sqs::Client,
- ingress_url: String,
}
async fn resources(endpoint: &str) -> Resources {
@@ -129,7 +122,6 @@ async fn resources(endpoint: &str) -> Resources {
let bucket = format!("archive-test-{suffix}");
let main = format!("archive-main-{suffix}");
let dlq = format!("archive-dlq-{suffix}");
- let ingress = format!("archive-ingress-{suffix}");
let s3 = aws_sdk_s3::Client::from_conf(
aws_sdk_s3::Config::builder()
.behavior_version(BehaviorVersion::latest())
@@ -160,7 +152,7 @@ async fn resources(endpoint: &str) -> Resources {
.endpoint_url(endpoint)
.build(),
);
- for name in [&main, &dlq, &ingress] {
+ for name in [&main, &dlq] {
sqs.create_queue().queue_name(name).send().await.unwrap();
}
use aws_sdk_sqs::types::QueueAttributeName;
@@ -180,14 +172,6 @@ async fn resources(endpoint: &str) -> Resources {
.unwrap()
.queue_url
.unwrap();
- let ingress_url = sqs
- .get_queue_url()
- .queue_name(&ingress)
- .send()
- .await
- .unwrap()
- .queue_url
- .unwrap();
let attributes = sqs
.get_queue_attributes()
.queue_url(dlq_url)
@@ -223,8 +207,6 @@ async fn resources(endpoint: &str) -> Resources {
storage,
queue,
process,
- sqs,
- ingress_url,
}
}
@@ -589,77 +571,11 @@ async fn assert_no_notification_or_activity_rows(pool: &PgPool) {
);
}
-async fn assert_one_external_colleague(pool: &PgPool, team: TeamId) {
- let count = sqlx::query_scalar!(r#"SELECT count(*) FROM team_joined_macro_email"#)
- .fetch_one(pool)
- .await
- .unwrap();
- assert_eq!(count, Some(1));
- let rows = sqlx::query!(r#"SELECT team_id, email FROM team_joined_macro_email"#)
- .fetch_all(pool)
- .await
- .unwrap();
- assert_eq!(rows.len(), 1);
- assert_eq!(rows[0].team_id, Uuid::from(team));
- assert_eq!(rows[0].email, "[email protected]");
-}
-
-async fn ingress_bodies(sqs: &aws_sdk_sqs::Client, url: &str) -> Vec<serde_json::Value> {
- let mut bodies = Vec::new();
- loop {
- let page = sqs
- .receive_message()
- .queue_url(url)
- .max_number_of_messages(10)
- .wait_time_seconds(1)
- .send()
- .await
- .unwrap();
- let Some(messages) = page.messages.filter(|messages| !messages.is_empty()) else {
- break;
- };
- for message in messages {
- bodies.push(serde_json::from_str(message.body.as_deref().unwrap()).unwrap());
- sqs.delete_message()
- .queue_url(url)
- .receipt_handle(message.receipt_handle.unwrap())
- .send()
- .await
- .unwrap();
- }
- }
- bodies
-}
-
-fn assert_colleague_joined(body: &serde_json::Value, team: Uuid) {
- let request = &body["request"];
- assert_eq!(
- request["req"]["notification"]["tag"],
- "colleague_joined_macro"
- );
- assert_eq!(request["req"]["sender_id"], "macro|[email protected]");
- assert_eq!(
- request["req"]["recipient_ids"],
- serde_json::json!(["macro|[email protected]"])
- );
- let id = Uuid::new_v5(
- &Uuid::from_u128(0x7465_616d_2d6a_6f69_6e65_642d_6d61_6372),
- format!("{team}:[email protected]").as_bytes(),
- );
- assert_eq!(request["uuid_to_write"], id.to_string());
-}
-
#[ignore = "requires Docker with localstack/localstack:4 and a local PostgreSQL test role"]
#[sqlx::test(migrations = "../../crates/macro_db_client/migrations")]
async fn sealed_uploads_queue_replay_and_search_completion_barrier(pool: PgPool) {
let (_container, endpoint) = LocalStack::start().await;
- let Resources {
- storage,
- queue,
- sqs,
- ingress_url,
- ..
- } = resources(&endpoint).await;
+ let Resources { storage, queue, .. } = resources(&endpoint).await;
let team = team(&pool).await;
let limits = ImportLimits::default();
let repo = PgSlackImportRepo::new(pool.clone(), limits);
@@ -695,15 +611,6 @@ async fn sealed_uploads_queue_replay_and_search_completion_barrier(pool: PgPool)
sink.clone(),
sink.clone(),
authorizer,
- WorkerJoinAnnouncer::new(
- JoinAnnouncementServiceImpl::new(
- JoinAnnouncementRepositoryImpl::new(pool.clone()),
- SqsNotificationIngress {
- queue: SqsQueue::new(sqs.clone(), ingress_url.clone()),
- },
- ),
- true,
- ),
ImporterConfig { limits },
)
.unwrap(),
@@ -711,7 +618,7 @@ async fn sealed_uploads_queue_replay_and_search_completion_barrier(pool: PgPool)
assert_no_notification_or_activity_rows(&pool).await;
// Shape creation followed by history and an exact repeat reuse the same IDs.
let mut canonical = None;
- for (attempt, history) in [false, true, true].into_iter().enumerate() {
+ for history in [false, true, true] {
search.0.store(false, Ordering::SeqCst);
let job = upload_job(&service, team, history).await;
let events = repo.pending_events(50).await.unwrap();
@@ -766,14 +673,6 @@ async fn sealed_uploads_queue_replay_and_search_completion_barrier(pool: PgPool)
.await
.unwrap()
.unwrap();
- assert_one_external_colleague(&pool, team).await;
- let messages = ingress_bodies(&sqs, &ingress_url).await;
- if attempt == 0 {
- assert_eq!(messages.len(), 1);
- assert_colleague_joined(&messages[0], Uuid::from(team));
- } else {
- assert!(messages.is_empty());
- }
// Reconcile links and publish search without a competing maintenance loop.
maintenance.reconcile().await.unwrap();
let receipt = progress(&repo, team, job).await;
@@ -947,8 +846,6 @@ async fn sealed_uploads_queue_replay_and_search_completion_barrier(pool: PgPool)
.await
.expect("disabled worker did not persist exhausted work as Failed");
assert_no_notification_or_activity_rows(&pool).await;
- assert_one_external_colleague(&pool, team).await;
- assert!(ingress_bodies(&sqs, &ingress_url).await.is_empty());
stop.cancel();
timeout(Duration::from_secs(35), driver)
.await