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(channels): support link to join for group channels (#4815)

Will Hutchinsone02939c6e818
diff --git a/.sqlx/query-e2c696b916af0f7591d95a280d75c01e2e6e9dee46a74504fde48b78587934b6.json b/.sqlx/query-5e2a8bea55fc6e3ef9440c274fd1152ae70049c9c7e73f45f0fda9b223dab753.json
similarity index 63%
rename from .sqlx/query-e2c696b916af0f7591d95a280d75c01e2e6e9dee46a74504fde48b78587934b6.json
rename to .sqlx/query-5e2a8bea55fc6e3ef9440c274fd1152ae70049c9c7e73f45f0fda9b223dab753.json
index aadf5b33e9..6010c36706 100644
--- a/.sqlx/query-e2c696b916af0f7591d95a280d75c01e2e6e9dee46a74504fde48b78587934b6.json
+++ b/.sqlx/query-5e2a8bea55fc6e3ef9440c274fd1152ae70049c9c7e73f45f0fda9b223dab753.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n INSERT INTO comms_channel_participants (channel_id, user_id, role)\n VALUES ($1, $2, $3)\n ",
+ "query": "\n INSERT INTO comms_channel_participants (channel_id, user_id, role)\n VALUES ($1, $2, $3)\n ON CONFLICT (channel_id, user_id) DO UPDATE\n SET role = EXCLUDED.role,\n joined_at = now(),\n left_at = NULL\n WHERE comms_channel_participants.left_at IS NOT NULL\n ",
"describe": {
"columns": [],
"parameters": {
@@ -23,5 +23,5 @@
},
"nullable": []
},
- "hash": "e2c696b916af0f7591d95a280d75c01e2e6e9dee46a74504fde48b78587934b6"
+ "hash": "5e2a8bea55fc6e3ef9440c274fd1152ae70049c9c7e73f45f0fda9b223dab753"
}
diff --git a/.sqlx/query-d20cae5f1b3d196e190d4405a906f59f012ca8f4e2c1729e320b70ffdc9724b0.json b/.sqlx/query-d20cae5f1b3d196e190d4405a906f59f012ca8f4e2c1729e320b70ffdc9724b0.json
new file mode 100644
index 0000000000..7043de9b37
--- /dev/null
+++ b/.sqlx/query-d20cae5f1b3d196e190d4405a906f59f012ca8f4e2c1729e320b70ffdc9724b0.json
@@ -0,0 +1,58 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT id, name, channel_type AS \"channel_type: ChannelType\", org_id, team_id\n FROM comms_channels\n WHERE join_code = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "name",
+ "type_info": "Varchar"
+ },
+ {
+ "ordinal": 2,
+ "name": "channel_type: ChannelType",
+ "type_info": {
+ "Custom": {
+ "name": "comms_channel_type",
+ "kind": {
+ "Enum": [
+ "public",
+ "private",
+ "direct_message",
+ "team"
+ ]
+ }
+ }
+ }
+ },
+ {
+ "ordinal": 3,
+ "name": "org_id",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 4,
+ "name": "team_id",
+ "type_info": "Uuid"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ true,
+ false,
+ true,
+ true
+ ]
+ },
+ "hash": "d20cae5f1b3d196e190d4405a906f59f012ca8f4e2c1729e320b70ffdc9724b0"
+}
diff --git a/.sqlx/query-fe12a262c4362f704e10cde39172b88f5be5362bd0e3d6768480962469b5a154.json b/.sqlx/query-fe12a262c4362f704e10cde39172b88f5be5362bd0e3d6768480962469b5a154.json
new file mode 100644
index 0000000000..bab1bc44d6
--- /dev/null
+++ b/.sqlx/query-fe12a262c4362f704e10cde39172b88f5be5362bd0e3d6768480962469b5a154.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE comms_channels\n SET join_code = COALESCE(join_code, $2)\n WHERE id = $1\n RETURNING join_code AS \"join_code!\"\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "join_code!",
+ "type_info": "Uuid"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ true
+ ]
+ },
+ "hash": "fe12a262c4362f704e10cde39172b88f5be5362bd0e3d6768480962469b5a154"
+}
diff --git a/apps/web/src/features/channel-invitations/ChannelInviteAcceptance.test.tsx b/apps/web/src/features/channel-invitations/ChannelInviteAcceptance.test.tsx
new file mode 100644
index 0000000000..8c8637f35a
--- /dev/null
+++ b/apps/web/src/features/channel-invitations/ChannelInviteAcceptance.test.tsx
@@ -0,0 +1,188 @@
+/**
+ * @vitest-environment jsdom
+ */
+
+import { ThrownResultError } from '@core/util/result';
+import { fireEvent } from '@testing-library/dom';
+import { render } from 'solid-js/web';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ authenticated: true,
+ code: '9b2b1535-ab93-4071-871f-c18ad1f98164' as string | undefined,
+ error: null as Error | null,
+ isError: false,
+ isPending: false,
+ navigate: vi.fn(),
+ mutate: vi.fn(),
+ pathname: '/channel-invite',
+ search: '?code=9b2b1535-ab93-4071-871f-c18ad1f98164',
+ succeedOnMutate: false,
+}));
+
+vi.mock('@queries/auth', () => ({
+ useUserInfo: () => () => ({ authenticated: mocks.authenticated }),
+}));
+
+vi.mock('@queries/channel/join-links', () => ({
+ useJoinChannelByCodeMutation: (callbacks?: { onSuccess?: () => void }) => ({
+ get error() {
+ return mocks.error;
+ },
+ get isError() {
+ return mocks.isError;
+ },
+ get isPending() {
+ return mocks.isPending;
+ },
+ mutate(args: { joinCode: string }) {
+ mocks.mutate(args);
+ if (mocks.succeedOnMutate) callbacks?.onSuccess?.();
+ },
+ }),
+}));
+
+vi.mock('@solidjs/router', () => ({
+ useLocation: () => ({
+ get pathname() {
+ return mocks.pathname;
+ },
+ get search() {
+ return mocks.search;
+ },
+ }),
+ useNavigate: () => mocks.navigate,
+ useSearchParams: () => [
+ {
+ get code() {
+ return mocks.code;
+ },
+ },
+ ],
+}));
+
+vi.mock('@core/component/LoadingBlock', () => ({
+ LoadingBlock: () => <div>Joining channel…</div>,
+}));
+
+vi.mock('@core/component/PcNoiseGrid', () => ({
+ PcNoiseGrid: () => null,
+}));
+
+import { ChannelInviteAcceptance } from './ChannelInviteAcceptance';
+
+let dispose: (() => void) | undefined;
+
+function renderAcceptance(): HTMLElement {
+ const container = document.createElement('div');
+ document.body.appendChild(container);
+ const disposeRender = render(() => <ChannelInviteAcceptance />, container);
+ dispose = () => {
+ disposeRender();
+ container.remove();
+ };
+ return container;
+}
+
+function buttonWithText(
+ container: HTMLElement,
+ text: string
+): HTMLButtonElement {
+ const button = [...container.querySelectorAll('button')].find((element) =>
+ element.textContent?.includes(text)
+ );
+ if (!button) throw new Error(`Expected button containing "${text}"`);
+ return button;
+}
+
+beforeEach(() => {
+ mocks.authenticated = true;
+ mocks.code = '9b2b1535-ab93-4071-871f-c18ad1f98164';
+ mocks.error = null;
+ mocks.isError = false;
+ mocks.isPending = false;
+ mocks.pathname = '/channel-invite';
+ mocks.search = `?code=${mocks.code}`;
+ mocks.succeedOnMutate = false;
+ mocks.mutate.mockReset();
+ mocks.navigate.mockReset();
+});
+
+afterEach(() => {
+ dispose?.();
+ dispose = undefined;
+});
+
+describe('ChannelInviteAcceptance', () => {
+ it('shows an invalid-link state when the code is missing', () => {
+ mocks.code = undefined;
+ mocks.search = '';
+
+ const container = renderAcceptance();
+
+ expect(container.textContent).toContain('Invalid Invite Link');
+ expect(mocks.mutate).not.toHaveBeenCalled();
+ });
+
+ it('preserves the full invitation route when sending signed-out users to login', () => {
+ mocks.authenticated = false;
+ mocks.search = '?code=code%2Fwith%2Bcharacters';
+
+ const container = renderAcceptance();
+ fireEvent.click(buttonWithText(container, 'Sign In to Continue'));
+
+ expect(mocks.navigate).toHaveBeenCalledWith(
+ `/login?redirect=${encodeURIComponent(
+ '/channel-invite?code=code%2Fwith%2Bcharacters'
+ )}`
+ );
+ expect(mocks.mutate).not.toHaveBeenCalled();
+ });
+
+ it('waits for confirmation before joining and returns home after success', () => {
+ mocks.succeedOnMutate = true;
+
+ const container = renderAcceptance();
+
+ expect(mocks.mutate).not.toHaveBeenCalled();
+ fireEvent.click(buttonWithText(container, 'Join Channel'));
+
+ expect(mocks.mutate).toHaveBeenCalledWith({ joinCode: mocks.code });
+ expect(mocks.navigate).toHaveBeenCalledWith('/', { replace: true });
+ });
+
+ it('shows the pending state while the join request is running', () => {
+ mocks.isPending = true;
+
+ const container = renderAcceptance();
+
+ expect(container.textContent).toContain('Joining channel…');
+ expect(container.textContent).not.toContain(
+ 'Confirm that you want to join'
+ );
+ });
+
+ it('shows invalid-link feedback for an unknown code', () => {
+ mocks.isError = true;
+ mocks.error = new ThrownResultError([
+ { code: 'NOT_FOUND', message: 'channel not found' },
+ ]);
+
+ const container = renderAcceptance();
+
+ expect(container.textContent).toContain('Invalid Invite Link');
+ });
+
+ it('shows a retryable message for a server error', () => {
+ mocks.isError = true;
+ mocks.error = new ThrownResultError([
+ { code: 'SERVER_ERROR', message: 'unavailable' },
+ ]);
+
+ const container = renderAcceptance();
+ expect(container.textContent).toContain('Unable to Join Channel');
+
+ fireEvent.click(buttonWithText(container, 'Try Again'));
+ expect(mocks.mutate).toHaveBeenCalledWith({ joinCode: mocks.code });
+ });
+});
diff --git a/apps/web/src/features/channel-invitations/ChannelInviteAcceptance.tsx b/apps/web/src/features/channel-invitations/ChannelInviteAcceptance.tsx
new file mode 100644
index 0000000000..64cd3af95b
--- /dev/null
+++ b/apps/web/src/features/channel-invitations/ChannelInviteAcceptance.tsx
@@ -0,0 +1,178 @@
+import { LoadingBlock } from '@core/component/LoadingBlock';
+import { PcNoiseGrid } from '@core/component/PcNoiseGrid';
+import { ThrownResultError } from '@core/util/result';
+import LogoIcon from '@icon/macro-logo.svg';
+import UsersThreeIcon from '@phosphor/users-three.svg';
+import { useUserInfo } from '@queries/auth';
+import { useJoinChannelByCodeMutation } from '@queries/channel/join-links';
+import { useLocation, useNavigate, useSearchParams } from '@solidjs/router';
+import { Button, Surface } from '@ui';
+import { Match, Switch } from 'solid-js';
+
+export function ChannelInviteAcceptance() {
+ const [searchParams] = useSearchParams();
+ const location = useLocation();
+ const navigate = useNavigate();
+ const userInfo = useUserInfo();
+
+ const joinCode = () => {
+ const code = searchParams.code;
+ return typeof code === 'string' && code.length > 0 ? code : undefined;
+ };
+
+ const joinMutation = useJoinChannelByCodeMutation({
+ onSuccess() {
+ navigate('/', { replace: true });
+ },
+ });
+
+ function handleLogin() {
+ const invitationRoute = `${location.pathname}${location.search}`;
+ navigate(`/login?redirect=${encodeURIComponent(invitationRoute)}`);
+ }
+
+ function handleJoin() {
+ const code = joinCode();
+ if (!code) return;
+ joinMutation.mutate({ joinCode: code });
+ }
+
+ const errorCode = () => {
+ const error = joinMutation.error;
+ if (!(error instanceof ThrownResultError)) return undefined;
+ return error.errors[0]?.code;
+ };
+
+ return (
+ <div class="flex items-center justify-center size-full p-8 overflow-hidden relative">
+ <div class="inset-0 absolute text-edge bg-surface opacity-10 -z-1">
+ <PcNoiseGrid
+ cellSize={30}
+ warp={0}
+ crunch={0.2}
+ freq={0.001}
+ size={[0, 0.3]}
+ rounding={0}
+ fill={0}
+ stroke={1}
+ speed={[0.017, 0.209]}
+ />
+ </div>
+
+ <div class="w-full max-w-105">
+ <Surface>
+ <div class="flex flex-col gap-6 p-6">
+ <div class="flex justify-center">
+ <LogoIcon class="size-10 text-accent" />
+ </div>
+ <div class="flex flex-col items-center">
+ <Switch>
+ <Match when={!joinCode()}>
+ <InvalidInviteLink />
+ </Match>
+ <Match when={!userInfo()?.authenticated}>
+ <UnauthenticatedView onLogin={handleLogin} />
+ </Match>
+ <Match when={joinMutation.isPending}>
+ <LoadingBlock />
+ </Match>
+ <Match when={errorCode() === 'NOT_FOUND'}>
+ <InvalidInviteLink />
+ </Match>
+ <Match when={joinMutation.isError}>
+ <ServerError onRetry={handleJoin} />
+ </Match>
+ <Match when={joinCode()}>
+ <JoinConfirmation onJoin={handleJoin} />
+ </Match>
+ </Switch>
+ </div>
+ </div>
+ </Surface>
+ </div>
+ </div>
+ );
+}
+
+function InvalidInviteLink() {
+ const navigate = useNavigate();
+
+ return (
+ <div class="w-full flex flex-col items-center gap-4 text-center">
+ <h2 class="text-lg font-medium text-ink">Invalid Invite Link</h2>
+ <p class="text-sm text-ink-muted">
+ This channel invitation is invalid or no longer available.
+ </p>
+ <Button
+ variant="base"
+ size="md"
+ class="w-full rounded-xs"
+ onClick={() => navigate('/')}
+ >
+ Go to Home
+ </Button>
+ </div>
+ );
+}
+
+function UnauthenticatedView(props: { onLogin: () => void }) {
+ return (
+ <div class="w-full flex flex-col items-center gap-4 text-center">
+ <h2 class="text-lg font-medium text-ink">You've Been Invited</h2>
+ <p class="text-sm text-ink-muted">
+ Sign in or create an account to accept this channel invitation.
+ </p>
+ <Button
+ variant="base"
+ size="md"
+ class="w-full rounded-xs"
+ onClick={props.onLogin}
+ >
+ Sign In to Continue
+ </Button>
+ </div>
+ );
+}
+
+function JoinConfirmation(props: { onJoin: () => void }) {
+ return (
+ <div class="flex flex-col items-center gap-6 text-center w-full">
+ <div class="flex flex-col gap-2">
+ <h2 class="flex items-center justify-center gap-2 text-lg font-medium text-ink">
+ <UsersThreeIcon class="size-5" />
+ Join Channel
+ </h2>
+ <p class="text-sm text-ink-muted">
+ Confirm that you want to join this channel.
+ </p>
+ </div>
+ <Button
+ variant="base"
+ size="md"
+ class="w-full rounded-xs"
+ onClick={props.onJoin}
+ >
+ Join Channel
+ </Button>
+ </div>
+ );
+}
+
+function ServerError(props: { onRetry: () => void }) {
+ return (
+ <div class="w-full flex flex-col items-center gap-4 text-center">
+ <h2 class="text-lg font-medium text-ink">Unable to Join Channel</h2>
+ <p class="text-sm text-ink-muted">
+ Something went wrong while joining the channel. Please try again.
+ </p>
+ <Button
+ variant="base"
+ size="md"
+ class="w-full rounded-xs"
+ onClick={props.onRetry}
+ >
+ Try Again
+ </Button>
+ </div>
+ );
+}
diff --git a/apps/web/src/features/channel/Participants/ChannelJoinLinkButton.test.tsx b/apps/web/src/features/channel/Participants/ChannelJoinLinkButton.test.tsx
new file mode 100644
index 0000000000..ec81401b3d
--- /dev/null
+++ b/apps/web/src/features/channel/Participants/ChannelJoinLinkButton.test.tsx
@@ -0,0 +1,142 @@
+/**
+ * @vitest-environment jsdom
+ */
+
+import { fireEvent, render, screen, waitFor } from '@solidjs/testing-library';
+import type { JSX } from 'solid-js';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { ChannelJoinLinkButton } from './ChannelJoinLinkButton';
+
+const mocks = vi.hoisted(() => ({
+ isPending: false,
+ mutateAsync: vi.fn(),
+ toastFailure: vi.fn(),
+ writeText: vi.fn(),
+}));
+
+vi.mock('@core/component/Toast/Toast', () => ({
+ toast: { failure: mocks.toastFailure },
+}));
+
+vi.mock('@core/util/webOrigin', () => ({
+ getWebOrigin: () => 'https://app.example.com',
+}));
+
+vi.mock('@queries/channel/join-links', () => ({
+ useGetChannelJoinLinkMutation: () => ({
+ get isPending() {
+ return mocks.isPending;
+ },
+ mutateAsync: mocks.mutateAsync,
+ }),
+}));
+
+vi.mock('@ui', () => ({
+ Button: (props: {
+ children: JSX.Element;
+ disabled?: boolean;
+ onClick?: JSX.EventHandlerUnion<HTMLButtonElement, MouseEvent>;
+ }) => (
+ <button type="button" disabled={props.disabled} onClick={props.onClick}>
+ {props.children}
+ </button>
+ ),
+}));
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.isPending = false;
+ mocks.mutateAsync.mockResolvedValue({ join_code: 'join-code' });
+ mocks.writeText.mockResolvedValue(undefined);
+ Object.defineProperty(navigator, 'clipboard', {
+ configurable: true,
+ value: { writeText: mocks.writeText },
+ });
+});
+
+describe('ChannelJoinLinkButton', () => {
+ it('generates the link lazily and copies the invitation URL', async () => {
+ render(() => <ChannelJoinLinkButton channelId="channel-1" />);
+
+ expect(mocks.mutateAsync).not.toHaveBeenCalled();
+
+ fireEvent.click(screen.getByRole('button', { name: 'Copy invite link' }));
+
+ await waitFor(() => {
+ expect(mocks.mutateAsync).toHaveBeenCalledWith({
+ channelId: 'channel-1',
+ });
+ expect(mocks.writeText).toHaveBeenCalledWith(
+ 'https://app.example.com/app/channel-invite?code=join-code'
+ );
+ expect(screen.getByRole('button', { name: 'Copied' })).toBeTruthy();
+ });
+ });
+
+ it('reuses the generated code on later clicks', async () => {
+ render(() => <ChannelJoinLinkButton channelId="channel-1" />);
+ const button = screen.getByRole('button', { name: 'Copy invite link' });
+
+ fireEvent.click(button);
+ await waitFor(() => expect(mocks.writeText).toHaveBeenCalledOnce());
+ fireEvent.click(button);
+ await waitFor(() => expect(mocks.writeText).toHaveBeenCalledTimes(2));
+
+ expect(mocks.mutateAsync).toHaveBeenCalledOnce();
+ });
+
+ it('does not generate competing codes on rapid clicks', async () => {
+ let resolveResponse: (response: { join_code: string }) => void = () => {};
+ mocks.mutateAsync.mockReturnValue(
+ new Promise((resolve) => {
+ resolveResponse = resolve;
+ })
+ );
+ render(() => <ChannelJoinLinkButton channelId="channel-1" />);
+ const button = screen.getByRole('button', { name: 'Copy invite link' });
+
+ fireEvent.click(button);
+ fireEvent.click(button);
+
+ expect(mocks.mutateAsync).toHaveBeenCalledOnce();
+ resolveResponse({ join_code: 'join-code' });
+ await waitFor(() => expect(mocks.writeText).toHaveBeenCalledTimes(2));
+ });
+
+ it('shows failure feedback when clipboard access fails', async () => {
+ vi.spyOn(console, 'error').mockImplementation(() => undefined);
+ mocks.writeText.mockRejectedValue(new Error('clipboard unavailable'));
+ render(() => <ChannelJoinLinkButton channelId="channel-1" />);
+
+ fireEvent.click(screen.getByRole('button', { name: 'Copy invite link' }));
+
+ await waitFor(() => {
+ expect(mocks.toastFailure).toHaveBeenCalledWith(
+ 'Failed to copy channel join link'
+ );
+ });
+ expect(
+ screen.getByRole('button', { name: 'Copy invite link' })
+ ).toBeTruthy();
+ });
+
+ it('does not copy when link generation fails', async () => {
+ mocks.mutateAsync.mockRejectedValue(new Error('generation failed'));
+ render(() => <ChannelJoinLinkButton channelId="channel-1" />);
+
+ fireEvent.click(screen.getByRole('button', { name: 'Copy invite link' }));
+
+ await waitFor(() => expect(mocks.mutateAsync).toHaveBeenCalledOnce());
+ expect(mocks.writeText).not.toHaveBeenCalled();
+ });
+
+ it('disables the control and prevents requests while pending', () => {
+ mocks.isPending = true;
+ render(() => <ChannelJoinLinkButton channelId="channel-1" />);
+
+ const button = screen.getByRole('button', { name: 'Generating link' });
+ expect(button).toHaveProperty('disabled', true);
+ fireEvent.click(button);
+ expect(mocks.mutateAsync).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/web/src/features/channel/Participants/ChannelJoinLinkButton.tsx b/apps/web/src/features/channel/Participants/ChannelJoinLinkButton.tsx
new file mode 100644
index 0000000000..fa049cd4b3
--- /dev/null
+++ b/apps/web/src/features/channel/Participants/ChannelJoinLinkButton.tsx
@@ -0,0 +1,91 @@
+import { toast } from '@core/component/Toast/Toast';
+import { getWebOrigin } from '@core/util/webOrigin';
+import CheckIcon from '@phosphor/check.svg';
+import LinkIcon from '@phosphor/link.svg';
+import SpinnerIcon from '@phosphor/spinner.svg';
+import { useGetChannelJoinLinkMutation } from '@queries/channel/join-links';
+import { Button } from '@ui';
+import { createSignal, onCleanup, Show } from 'solid-js';
+
+export function ChannelJoinLinkButton(props: { channelId: string }) {
+ const getJoinLinkMutation = useGetChannelJoinLinkMutation();
+ const [joinCode, setJoinCode] = createSignal<string>();
+ const [copied, setCopied] = createSignal(false);
+ let copyResetTimeout: ReturnType<typeof setTimeout> | undefined;
+ let joinCodeRequest: Promise<string | undefined> | undefined;
+
+ onCleanup(() => clearTimeout(copyResetTimeout));
+
+ const generateJoinCode = async (): Promise<string | undefined> => {
+ try {
+ const response = await getJoinLinkMutation.mutateAsync({
+ channelId: props.channelId,
+ });
+ setJoinCode(response.join_code);
+ return response.join_code;
+ } catch {
+ // The mutation displays the standard generation failure toast.
+ return undefined;
+ }
+ };
+
+ const getJoinCode = async (): Promise<string | undefined> => {
+ const existingCode = joinCode();
+ if (existingCode) return existingCode;
+ if (joinCodeRequest) return await joinCodeRequest;
+
+ joinCodeRequest = generateJoinCode();
+ try {
+ return await joinCodeRequest;
+ } finally {
+ joinCodeRequest = undefined;
+ }
+ };
+
+ const buttonLabel = () => {
+ if (getJoinLinkMutation.isPending) return 'Generating link';
+ if (copied()) return 'Copied';
+ return 'Copy invite link';
+ };
+
+ const copyJoinLink = async () => {
+ if (getJoinLinkMutation.isPending) return;
+
+ const code = await getJoinCode();
+ if (!code) return;
+
+ try {
+ await navigator.clipboard.writeText(
+ `${getWebOrigin()}/app/channel-invite?code=${code}`
+ );
+ } catch (error) {
+ console.error('Failed to copy channel join link', error);
+ toast.failure('Failed to copy channel join link');
+ return;
+ }
+
+ setCopied(true);
+ clearTimeout(copyResetTimeout);
+ copyResetTimeout = setTimeout(() => setCopied(false), 2000);
+ };
+
+ return (
+ <Button
+ variant="base"
+ size="sm"
+ class="rounded-xs"
+ disabled={getJoinLinkMutation.isPending}
+ onClick={() => void copyJoinLink()}
+ >
+ <Show
+ when={!getJoinLinkMutation.isPending}
+ fallback={<SpinnerIcon class="size-4 animate-spin" />}
+ >
+ <Show when={copied()} fallback={<LinkIcon class="size-4" />}>
+ <CheckIcon class="size-4" />
+ </Show>
+ </Show>
+ {buttonLabel()}
+ </Button>
+ );
+}
diff --git a/apps/web/src/features/channel/Participants/ChannelParticipantsTab.tsx b/apps/web/src/features/channel/Participants/ChannelParticipantsTab.tsx
index e410c37d86..77589fd37e 100644
--- a/apps/web/src/features/channel/Participants/ChannelParticipantsTab.tsx
+++ b/apps/web/src/features/channel/Participants/ChannelParticipantsTab.tsx
@@ -13,6 +13,7 @@ import { ChannelType } from '@service-storage/generated/schemas/channelType';
import { Panel } from '@ui';
import { createSignal, Show } from 'solid-js';
import { ChannelBotsPanel } from './ChannelBotsPanel';
+import { ChannelJoinLinkButton } from './ChannelJoinLinkButton';
import { ParticipantsAddPanel } from './ParticipantsAddPanel';
import { ParticipantsList } from './ParticipantsList';
import { ParticipantsSearchInput } from './ParticipantsSearchInput';
@@ -87,8 +88,11 @@ export function ChannelParticipantsTab(props: {
<div class="h-full overflow-hidden flex justify-center p-2">
<div class="max-w-200 size-full flex flex-col gap-2">
<Panel depth={2} class="min-h-0 flex-1 overflow-hidden text-ink">
- <Panel.Header class="px-6">
+ <Panel.Header class="justify-between gap-2 px-6">
<div class="text-sm font-semibold">Participants</div>
+ <Show when={channelType() === ChannelType.private}>
+ <ChannelJoinLinkButton channelId={props.channelId} />
+ </Show>
</Panel.Header>
<Panel.Toolbar class="h-15.25 px-2">
<ParticipantsSearchInput
diff --git a/apps/web/src/lib/queries/channel/join-links.ts b/apps/web/src/lib/queries/channel/join-links.ts
new file mode 100644
index 0000000000..bb49cf92a5
--- /dev/null
+++ b/apps/web/src/lib/queries/channel/join-links.ts
@@ -0,0 +1,97 @@
+import { toast } from '@core/component/Toast/Toast';
+import { throwOnErr } from '@core/util/result';
+import { type MutationCallbacks, withCallbacks } from '@queries/utils';
+import { storageServiceClient } from '@service-storage/client';
+import type { ChannelJoinCodeResponse } from '@service-storage/generated/schemas/channelJoinCodeResponse';
+import { useMutation } from '@tanstack/solid-query';
+import { queryClient } from '../client';
+import { channelKeys } from './keys';
+
+export type GetChannelJoinLinkArgs = {
+ channelId: string;
+};
+
+type GetChannelJoinLinkCallbacks = MutationCallbacks<
+ ChannelJoinCodeResponse,
+ Error,
+ GetChannelJoinLinkArgs,
+ undefined
+>;
+
+export function getChannelJoinLinkMutationOptions(
+ callbacks?: GetChannelJoinLinkCallbacks
+) {
+ return {
+ gcTime: 0,
+ mutationFn: async ({ channelId }: GetChannelJoinLinkArgs) =>
+ await throwOnErr(() =>
+ storageServiceClient.getChannelJoinLink({ channel_id: channelId })
+ ),
+ ...withCallbacks<
+ ChannelJoinCodeResponse,
+ Error,
+ GetChannelJoinLinkArgs,
+ undefined
+ >(
+ {
+ onError(error) {
+ console.error('failed to get channel join link', error);
+ toast.failure('Failed to generate channel join link');
+ },
+ },
+ callbacks
+ ),
+ };
+}
+
+/** Lazily gets or creates a channel join code when mutate is called. */
+export function useGetChannelJoinLinkMutation(
+ callbacks?: GetChannelJoinLinkCallbacks
+) {
+ return useMutation(() => getChannelJoinLinkMutationOptions(callbacks));
+}
+
+export type JoinChannelByCodeArgs = {
+ joinCode: string;
+};
+
+type JoinChannelByCodeCallbacks = MutationCallbacks<
+ void,
+ Error,
+ JoinChannelByCodeArgs,
+ undefined
+>;
+
+export function joinChannelByCodeMutationOptions(
+ callbacks?: JoinChannelByCodeCallbacks
+) {
+ return {
+ gcTime: 0,
+ mutationFn: async ({ joinCode }: JoinChannelByCodeArgs) => {
+ await throwOnErr(() =>
+ storageServiceClient.joinChannelByCode({ join_code: joinCode })
+ );
+ },
+ ...withCallbacks<void, Error, JoinChannelByCodeArgs, undefined>(
+ {
+ onSuccess() {
+ void queryClient.invalidateQueries({
+ queryKey: channelKeys.listChannels.queryKey,
+ });
+ },
+ onError(error) {
+ console.error('failed to join channel by code', error);
+ toast.failure('Failed to join channel');
+ },
+ },
+ callbacks
+ ),
+ };
+}
+
+/** Joins a channel using its reusable join code. */
+export function useJoinChannelByCodeMutation(
+ callbacks?: JoinChannelByCodeCallbacks
+) {
+ return useMutation(() => joinChannelByCodeMutationOptions(callbacks));
+}
diff --git a/apps/web/src/lib/queries/channel/tests/channel-join-links.test.ts b/apps/web/src/lib/queries/channel/tests/channel-join-links.test.ts
new file mode 100644
index 0000000000..e48cb37234
--- /dev/null
+++ b/apps/web/src/lib/queries/channel/tests/channel-join-links.test.ts
@@ -0,0 +1,122 @@
+import { toast } from '@core/component/Toast/Toast';
+import { storageServiceClient } from '@service-storage/client';
+import { QueryClient } from '@tanstack/solid-query';
+import { err, ok } from 'neverthrow';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+let testQueryClient: QueryClient;
+
+vi.mock('../../client', () => ({
+ get queryClient() {
+ return testQueryClient;
+ },
+}));
+
+vi.mock('@core/component/Toast/Toast', () => ({
+ toast: { failure: vi.fn(), success: vi.fn() },
+}));
+
+vi.mock('@service-storage/client', () => ({
+ storageServiceClient: {
+ getChannelJoinLink: vi.fn(),
+ joinChannelByCode: vi.fn(),
+ },
+}));
+
+import {
+ getChannelJoinLinkMutationOptions,
+ joinChannelByCodeMutationOptions,
+} from '../join-links';
+import { channelKeys } from '../keys';
+
+const mutationContext = () => ({
+ client: testQueryClient,
+ meta: undefined,
+ mutationKey: undefined,
+});
+
+describe('channel join-link mutations', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ testQueryClient = new QueryClient({
+ defaultOptions: {
+ queries: { retry: false },
+ mutations: { retry: false },
+ },
+ });
+ });
+
+ it('does not request a join code until the lazy mutation executes', async () => {
+ vi.mocked(storageServiceClient.getChannelJoinLink).mockResolvedValue(
+ ok({ join_code: 'join-code' })
+ );
+
+ const options = getChannelJoinLinkMutationOptions();
+
+ expect(storageServiceClient.getChannelJoinLink).not.toHaveBeenCalled();
+
+ await expect(
+ options.mutationFn({ channelId: 'channel-1' })
+ ).resolves.toEqual({ join_code: 'join-code' });
+ expect(storageServiceClient.getChannelJoinLink).toHaveBeenCalledWith({
+ channel_id: 'channel-1',
+ });
+ });
+
+ it('joins with the supplied code and invalidates the channel list', async () => {
+ vi.mocked(storageServiceClient.joinChannelByCode).mockResolvedValue(
+ ok(undefined)
+ );
+ const invalidateQueries = vi.spyOn(testQueryClient, 'invalidateQueries');
+ const options = joinChannelByCodeMutationOptions();
+ const args = { joinCode: 'join-code' };
+
+ await expect(options.mutationFn(args)).resolves.toBeUndefined();
+ expect(storageServiceClient.joinChannelByCode).toHaveBeenCalledWith({
+ join_code: 'join-code',
+ });
+
+ await options.onSuccess?.(undefined, args, undefined, mutationContext());
+ expect(invalidateQueries).toHaveBeenCalledWith({
+ queryKey: channelKeys.listChannels.queryKey,
+ });
+ });
+
+ it('throws and shows the standard failure toast when link generation fails', async () => {
+ vi.mocked(storageServiceClient.getChannelJoinLink).mockResolvedValue(
+ err([{ code: 'SERVER_ERROR', message: 'unavailable' }])
+ );
+ const options = getChannelJoinLinkMutationOptions();
+ const args = { channelId: 'channel-1' };
+
+ await expect(options.mutationFn(args)).rejects.toThrow();
+ await options.onError?.(
+ new Error('unavailable'),
+ args,
+ undefined,
+ mutationContext()
+ );
+
+ expect(toast.failure).toHaveBeenCalledWith(
+ 'Failed to generate channel join link'
+ );
+ });
+
+ it('throws and shows the standard failure toast when joining fails', async () => {
+ vi.mocked(storageServiceClient.joinChannelByCode).mockResolvedValue(
+ err([{ code: 'SERVER_ERROR', message: 'unavailable' }])
+ );
+ const options = joinChannelByCodeMutationOptions();
+ const args = { joinCode: 'invalid-code' };
+
+ await expect(options.mutationFn(args)).rejects.toThrow();
+ await options.onError?.(
+ new Error('unavailable'),
+ args,
+ undefined,
+ mutationContext()
+ );
+
+ expect(toast.failure).toHaveBeenCalledWith('Failed to join channel');
+ });
+});
diff --git a/apps/web/src/lib/service-clients/service-storage/client.ts b/apps/web/src/lib/service-clients/service-storage/client.ts
index 22bcdc9ad7..1c4fc9bec4 100644
--- a/apps/web/src/lib/service-clients/service-storage/client.ts
+++ b/apps/web/src/lib/service-clients/service-storage/client.ts
@@ -62,6 +62,7 @@ import type { ApiThreadReply } from './generated/schemas/apiThreadReply';
import type { Bot } from './generated/schemas/bot';
import type { BotChannel } from './generated/schemas/botChannel';
import type { BotToken } from './generated/schemas/botToken';
+import type { ChannelJoinCodeResponse } from './generated/schemas/channelJoinCodeResponse';
import type { ChannelMessageFilters } from './generated/schemas/channelMessageFilters';
import { ChannelType } from './generated/schemas/channelType';
import {
@@ -793,6 +794,19 @@ export const storageServiceClient = {
).map((result) => result);
},
+ async getChannelJoinLink(args: WithChannelId) {
+ return await dssFetch<ChannelJoinCodeResponse>(
+ `/channels/${args.channel_id}/join-link`,
+ { method: 'GET' }
+ );
+ },
+
+ async joinChannelByCode(args: { join_code: string }) {
+ return await dssFetch(`/channels/join/${args.join_code}`, {
+ method: 'POST',
+ });
+ },
+
async leaveChannel(args: WithChannelId) {
const { channel_id } = args;
return (
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/channelJoinCodeResponse.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/channelJoinCodeResponse.ts
new file mode 100644
index 0000000000..758cc8702f
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/channelJoinCodeResponse.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Response containing a channel's reusable join code.
+ */
+export interface ChannelJoinCodeResponse {
+ /** Reusable code for joining the channel. */
+ join_code: string;
+}
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts
index fcd126ae0c..5be11740ba 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts
@@ -183,6 +183,7 @@ export * from './channelFilters';
export * from './channelFiltersImportance';
export * from './channelFiltersOrgId';
export * from './channelFiltersTeamId';
+export * from './channelJoinCodeResponse';
export * from './channelMessage';
export * from './channelMessageDeletedAt';
export * from './channelMessageFilters';
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts b/apps/web/src/lib/service-clients/service-storage/generated/zod.ts
index 7cc3d01160..8de46a9756 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/zod.ts
@@ -1543,6 +1543,13 @@ export const getOrCreatePrivateResponse = zod
})
.describe('Response for get-or-create channel operations.');
+/**
+ * @summary Handler for `POST /channels/join/{join_code}`.
+ */
+export const joinChannelByCodeParams = zod.object({
+ join_code: zod.uuid().describe('Channel join code'),
+});
+
/**
* @summary Handler for `POST /channels/mentions`.
*/
@@ -1972,6 +1979,19 @@ export const joinChannelParams = zod.object({
channel_id: zod.uuid().describe('Channel ID'),
});
+/**
+ * @summary Handler for `GET /channels/{channel_id}/join-link`.
+ */
+export const getChannelJoinLinkParams = zod.object({
+ channel_id: zod.uuid().describe('Channel ID'),
+});
+
+export const getChannelJoinLinkResponse = zod
+ .object({
+ join_code: zod.uuid().describe('Reusable code for joining the channel.'),
+ })
+ .describe("Response containing a channel's reusable join code.");
+
/**
* @summary Handler for `POST /channels/{channel_id}/leave`.
*/
diff --git a/apps/web/src/lib/service-clients/service-storage/openapi.json b/apps/web/src/lib/service-clients/service-storage/openapi.json
index ee32f287cd..cdd667a31f 100644
--- a/apps/web/src/lib/service-clients/service-storage/openapi.json
+++ b/apps/web/src/lib/service-clients/service-storage/openapi.json
@@ -1799,6 +1799,80 @@
}
}
},
+ "/channels/join/{join_code}": {
+ "post": {
+ "tags": ["channels"],
+ "summary": "Handler for `POST /channels/join/{join_code}`.",
+ "operationId": "join_channel_by_code",
+ "parameters": [
+ {
+ "name": "join_code",
+ "in": "path",
+ "description": "Channel join code",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": ""
+ },
+ "400": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "403": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/channels/mentions": {
"post": {
"tags": ["channels"],
@@ -2473,6 +2547,87 @@
}
}
},
+ "/channels/{channel_id}/join-link": {
+ "get": {
+ "tags": ["channels"],
+ "summary": "Handler for `GET /channels/{channel_id}/join-link`.",
+ "operationId": "get_channel_join_link",
+ "parameters": [
+ {
+ "name": "channel_id",
+ "in": "path",
+ "description": "Channel ID",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ChannelJoinCodeResponse"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "403": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/channels/{channel_id}/leave": {
"post": {
"tags": ["channels"],
@@ -11501,6 +11656,18 @@
}
}
},
+ "ChannelJoinCodeResponse": {
+ "type": "object",
+ "description": "Response containing a channel's reusable join code.",
+ "required": ["join_code"],
+ "properties": {
+ "join_code": {
+ "type": "string",
+ "format": "uuid",
+ "description": "Reusable code for joining the channel."
+ }
+ }
+ },
"ChannelMessage": {
"type": "object",
"description": "Lightweight channel message for soup payloads.",
diff --git a/apps/web/src/routes/Root.tsx b/apps/web/src/routes/Root.tsx
index 51bed8a2fc..66f155004b 100644
--- a/apps/web/src/routes/Root.tsx
+++ b/apps/web/src/routes/Root.tsx
@@ -6,6 +6,7 @@ import { MobileAuthWelcome } from '@app/features/auth/mobile-onboarding/MobileAu
import { MobileOnboarding } from '@app/features/auth/mobile-onboarding/MobileOnboarding';
import { setCookie } from '@app/features/auth/Shared';
import { Signup } from '@app/features/auth/Signup';
+import { ChannelInviteAcceptance } from '@app/features/channel-invitations/ChannelInviteAcceptance';
import { GlobalShareInboxConflictDialog } from '@app/features/inbox/ShareInboxConflictDialog';
import { SearchProvider } from '@app/features/next-soup/search-context';
import { usePendingNotificationNavigationEffect } from '@app/features/notifications/PendingNotificationNavigationEffect';
@@ -383,6 +384,10 @@ const ROUTES: RouteDefinition[] = [
path: '/team-invite',
component: TeamInviteAcceptance,
},
+ {
+ path: '/channel-invite',
+ component: ChannelInviteAcceptance,
+ },
{
// This splat route must be last to catch all unmatched routes
path: '*404',
diff --git a/crates/bots/src/inbound/channel_webhook_router.rs b/crates/bots/src/inbound/channel_webhook_router.rs
index 8bea646770..a5b415543a 100644
--- a/crates/bots/src/inbound/channel_webhook_router.rs
+++ b/crates/bots/src/inbound/channel_webhook_router.rs
@@ -345,6 +345,7 @@ impl IntoResponse for ChannelBotWebhookHandlerErr {
StatusCode::NOT_FOUND
}
Self::Channel(ChannelMutationErr::BadRequest(_)) => StatusCode::BAD_REQUEST,
+ Self::Channel(ChannelMutationErr::Forbidden(_)) => StatusCode::FORBIDDEN,
Self::Bot(BotError::Repo(_))
| Self::Channel(ChannelMutationErr::Repo(_))
| Self::Channel(ChannelMutationErr::Gateway(_))
diff --git a/crates/channels/src/domain/models.rs b/crates/channels/src/domain/models.rs
index ca54d37183..5a1b533f9e 100644
--- a/crates/channels/src/domain/models.rs
+++ b/crates/channels/src/domain/models.rs
@@ -705,6 +705,14 @@ pub struct CreateChannelRequest {
pub participants: HashSet<MacroUserIdStr<'static>>,
}
+/// Response containing a channel's reusable join code.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
+pub struct ChannelJoinCodeResponse {
+ /// Reusable code for joining the channel.
+ pub join_code: Uuid,
+}
+
/// Response returned after creating a channel.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
diff --git a/crates/channels/src/domain/ports.rs b/crates/channels/src/domain/ports.rs
index cfcc182152..a0a3296351 100644
--- a/crates/channels/src/domain/ports.rs
+++ b/crates/channels/src/domain/ports.rs
@@ -4,14 +4,15 @@ use crate::domain::models::RecentChannelMessage;
use crate::domain::models::{
Activity, ActivityType, AddParticipantsRequest, AttachmentEntityReference, BotId,
BotSenderProfile, ChannelAttachment, ChannelAttachmentType, ChannelContextMessage, ChannelInfo,
- ChannelMessageFilters, ChannelMetadata, ChannelParticipant, ChannelPreview, ChannelPreviewRow,
- CountedReaction, CreateChannelRequest, CreateChannelResponse, CreateEntityMentionOptions,
- DeleteMessageQuery, EntityMention, GetOrCreateChannelResponse, GetOrCreateDmRequest,
- GetOrCreatePrivateRequest, MessageAttachment, MessagePageDirection, MutatedAttachment,
- MutatedMessage, NewChannelAttachment, PatchChannelRequest, PatchMessageRequest,
- PostMessageRequest, PostMessageResponse, PostReactionRequest, PostTypingRequest,
- ReferencedShareItem, RemoveParticipantsRequest, ResolvedChannelMessage, Sender, SimpleMention,
- ThreadData, ThreadReply, ThreadReplyRow, TopLevelMessageRow,
+ ChannelJoinCodeResponse, ChannelMessageFilters, ChannelMetadata, ChannelParticipant,
+ ChannelPreview, ChannelPreviewRow, CountedReaction, CreateChannelRequest,
+ CreateChannelResponse, CreateEntityMentionOptions, DeleteMessageQuery, EntityMention,
+ GetOrCreateChannelResponse, GetOrCreateDmRequest, GetOrCreatePrivateRequest, MessageAttachment,
+ MessagePageDirection, MutatedAttachment, MutatedMessage, NewChannelAttachment,
+ PatchChannelRequest, PatchMessageRequest, PostMessageRequest, PostMessageResponse,
+ PostReactionRequest, PostTypingRequest, ReferencedShareItem, RemoveParticipantsRequest,
+ ResolvedChannelMessage, Sender, SimpleMention, ThreadData, ThreadReply, ThreadReplyRow,
+ TopLevelMessageRow,
};
#[cfg(feature = "list")]
use crate::domain::models::{
@@ -223,6 +224,18 @@ pub trait ChannelRepo: Send + Sync + 'static {
channel_id: Uuid,
) -> impl Future<Output = Result<ChannelInfo, Self::Err>> + Send;
+ /// Atomically assign a channel join code if absent and return the persisted code.
+ fn get_or_create_channel_join_code(
+ &self,
+ channel_id: Uuid,
+ ) -> impl Future<Output = Result<Uuid, Self::Err>> + Send;
+
+ /// Resolve channel metadata by its join code.
+ fn get_channel_info_by_join_code(
+ &self,
+ join_code: Uuid,
+ ) -> impl Future<Output = Result<Option<ChannelInfo>, Self::Err>> + Send;
+
/// Resolve channel metadata from a user's perspective.
fn get_channel_metadata(
&self,
@@ -289,13 +302,13 @@ pub trait ChannelRepo: Send + Sync + 'static {
user_id: String,
) -> impl Future<Output = Result<(), Self::Err>> + Send;
- /// Add a participant.
+ /// Atomically add or reactivate a participant, returning whether membership changed.
fn add_participant<'a>(
&self,
channel_id: Uuid,
user_id: MacroUserIdStr<'a>,
role: super::models::ParticipantRole,
- ) -> impl Future<Output = Result<(), Self::Err>> + Send;
+ ) -> impl Future<Output = Result<bool, Self::Err>> + Send;
/// Remove a participant.
fn remove_participant(
@@ -773,6 +786,18 @@ pub trait ChannelService: Send + Sync + 'static {
}
}
+ /// Get or create the reusable join code for a private channel.
+ fn get_channel_join_code(
+ &self,
+ _channel_id: Uuid,
+ ) -> impl Future<Output = Result<ChannelJoinCodeResponse, ChannelMutationErr>> + Send {
+ async move {
+ Err(ChannelMutationErr::NotFound(
+ "channel mutations are not configured".to_string(),
+ ))
+ }
+ }
+
/// Join a channel.
fn join_channel(
&self,
@@ -786,6 +811,19 @@ pub trait ChannelService: Send + Sync + 'static {
}
}
+ /// Join a private channel using its reusable join code.
+ fn join_channel_by_code(
+ &self,
+ _actor: Sender,
+ _join_code: Uuid,
+ ) -> impl Future<Output = Result<(), ChannelMutationErr>> + Send {
+ async move {
+ Err(ChannelMutationErr::NotFound(
+ "channel mutations are not configured".to_string(),
+ ))
+ }
+ }
+
/// Leave a channel.
fn leave_channel(
&self,
@@ -1039,6 +1077,9 @@ pub enum ChannelMutationErr {
/// Unauthorized mutation attempt.
#[error("{0}")]
Unauthorized(String),
+ /// Authenticated caller is forbidden from performing the mutation.
+ #[error("{0}")]
+ Forbidden(String),
/// Not found.
#[error("{0}")]
NotFound(String),
diff --git a/crates/channels/src/domain/service.rs b/crates/channels/src/domain/service.rs
index 64ac7bd782..998770d679 100644
--- a/crates/channels/src/domain/service.rs
+++ b/crates/channels/src/domain/service.rs
@@ -2,8 +2,8 @@ use crate::domain::{
events::ChannelEvent,
models::{
Activity, ActivityType, AddParticipantsRequest, AttachmentEntityReference, BotId,
- BotSenderProfile, ChannelAttachmentType, ChannelContextMessage, ChannelMessage,
- ChannelMessageFilters, ChannelMetadata, ChannelParticipant, ChannelPreview,
+ BotSenderProfile, ChannelAttachmentType, ChannelContextMessage, ChannelJoinCodeResponse,
+ ChannelMessage, ChannelMessageFilters, ChannelMetadata, ChannelParticipant, ChannelPreview,
ChannelPreviewData, ChannelType, CreateEntityMentionOptions, DeleteMessageQuery,
EntityMention, GetOrCreateAction, GetOrCreateChannelResponse, GetOrCreateDmRequest,
GetOrCreatePrivateRequest, MessagePageDirection, NewChannelAttachment, ParticipantRole,
@@ -1038,13 +1038,36 @@ where
Ok(())
}
+ #[tracing::instrument(err, skip(self))]
+ async fn get_channel_join_code(
+ &self,
+ channel_id: Uuid,
+ ) -> Result<ChannelJoinCodeResponse, ChannelMutationErr> {
+ let info = self
+ .repo
+ .get_channel_info(channel_id)
+ .await
+ .map_err(|e| ChannelMutationErr::Repo(e.into()))?;
+ if info.channel_type != ChannelType::Private {
+ return Err(ChannelMutationErr::Forbidden(
+ "join links are only available for private channels".to_string(),
+ ));
+ }
+
+ let join_code = self
+ .repo
+ .get_or_create_channel_join_code(channel_id)
+ .await
+ .map_err(|e| ChannelMutationErr::Repo(e.into()))?;
+ Ok(ChannelJoinCodeResponse { join_code })
+ }
+
#[tracing::instrument(err, skip(self))]
async fn join_channel(
&self,
actor: Sender,
channel_id: Uuid,
) -> Result<(), ChannelMutationErr> {
- let actor_user = require_user_actor(&actor)?;
let info = self
.repo
.get_channel_info(channel_id)
@@ -1055,25 +1078,55 @@ where
"cannot join direct message channel".to_string(),
));
}
+ self.join_channel_with_info(actor, info).await
+ }
+
+ #[tracing::instrument(err, skip(self))]
+ async fn join_channel_by_code(
+ &self,
+ actor: Sender,
+ join_code: Uuid,
+ ) -> Result<(), ChannelMutationErr> {
+ let info = self
+ .repo
+ .get_channel_info_by_join_code(join_code)
+ .await
+ .map_err(|e| ChannelMutationErr::Repo(e.into()))?
+ .ok_or_else(|| {
+ ChannelMutationErr::NotFound("channel join code not found".to_string())
+ })?;
+ if info.channel_type != ChannelType::Private {
+ return Err(ChannelMutationErr::Forbidden(
+ "join links are only valid for private channels".to_string(),
+ ));
+ }
+ self.join_channel_with_info(actor, info).await
+ }
+
+ async fn join_channel_with_info(
+ &self,
+ actor: Sender,
+ info: crate::domain::models::ChannelInfo,
+ ) -> Result<(), ChannelMutationErr> {
+ let actor_user = require_user_actor(&actor)?;
let before = self
.repo
- .get_participants(channel_id)
+ .get_participants(info.id)
.await
.map_err(|e| ChannelMutationErr::Repo(e.into()))?;
- self.repo
- .add_participant(channel_id, actor_user.copied(), ParticipantRole::Member)
+ let mut active_participant_user_ids = participant_ids(&before);
+ let changed = self
+ .repo
+ .add_participant(info.id, actor_user.copied(), ParticipantRole::Member)
.await
.map_err(|e| ChannelMutationErr::Repo(e.into()))?;
-
- let mut active_participant_user_ids = participant_ids(&before);
- if !active_participant_user_ids
- .iter()
- .any(|participant| participant == &actor_user)
- {
- active_participant_user_ids.push(actor_user.clone());
+ if !changed {
+ return Ok(());
}
+
+ active_participant_user_ids.push(actor_user.clone());
self.events.dispatch(ChannelEvent::ParticipantJoined {
- channel_id,
+ channel_id: info.id,
channel_type: info.channel_type,
user_id: Sender::new_from_user(actor_user),
active_participant_user_ids,
@@ -1763,6 +1816,13 @@ where
ChannelServiceImpl::remove_participants(self, actor, channel_id, req).await
}
+ async fn get_channel_join_code(
+ &self,
+ channel_id: Uuid,
+ ) -> Result<ChannelJoinCodeResponse, ChannelMutationErr> {
+ ChannelServiceImpl::get_channel_join_code(self, channel_id).await
+ }
+
async fn join_channel(
&self,
actor: Sender,
@@ -1771,6 +1831,14 @@ where
ChannelServiceImpl::join_channel(self, actor, channel_id).await
}
+ async fn join_channel_by_code(
+ &self,
+ actor: Sender,
+ join_code: Uuid,
+ ) -> Result<(), ChannelMutationErr> {
+ ChannelServiceImpl::join_channel_by_code(self, actor, join_code).await
+ }
+
async fn leave_channel(
&self,
actor: Sender,
diff --git a/crates/channels/src/domain/service/test.rs b/crates/channels/src/domain/service/test.rs
index 6495beaff7..e63f99bbaf 100644
--- a/crates/channels/src/domain/service/test.rs
+++ b/crates/channels/src/domain/service/test.rs
@@ -283,9 +283,12 @@ struct FakeMutationRepo {
struct FakeMutationRepoState {
channel_id: Uuid,
+ channel_type: ChannelType,
+ join_code: Option<Uuid>,
message: MutatedMessage,
owner: String,
participants: Vec<ChannelParticipant>,
+ participant_additions: usize,
thread_participants: Vec<MacroUserIdStr<'static>>,
attachments: Vec<MutatedAttachment>,
patched_content: Option<String>,
@@ -313,6 +316,8 @@ impl FakeMutationRepo {
Self {
state: Arc::new(Mutex::new(FakeMutationRepoState {
channel_id,
+ channel_type: ChannelType::Private,
+ join_code: None,
owner: sender.to_string(),
message,
participants: vec![
@@ -331,6 +336,7 @@ impl FakeMutationRepo {
left_at: None,
},
],
+ participant_additions: 0,
thread_participants: vec![
MacroUserIdStr::try_from("macro|[email protected]".to_string()).unwrap(),
],
@@ -452,15 +458,36 @@ impl ChannelRepo for FakeMutationRepo {
}
async fn get_channel_info(&self, channel_id: Uuid) -> Result<ChannelInfo, Self::Err> {
+ let state = self.state.lock().unwrap();
Ok(ChannelInfo {
id: channel_id,
name: Some("Project".to_string()),
- channel_type: ChannelType::Private,
+ channel_type: state.channel_type,
org_id: None,
team_id: None,
})
}
+ async fn get_or_create_channel_join_code(&self, _channel_id: Uuid) -> Result<Uuid, Self::Err> {
+ let mut state = self.state.lock().unwrap();
+ let join_code = *state.join_code.get_or_insert_with(Uuid::new_v4);
+ Ok(join_code)
+ }
+
+ async fn get_channel_info_by_join_code(
+ &self,
+ join_code: Uuid,
+ ) -> Result<Option<ChannelInfo>, Self::Err> {
+ let state = self.state.lock().unwrap();
+ Ok((state.join_code == Some(join_code)).then(|| ChannelInfo {
+ id: state.channel_id,
+ name: Some("Project".to_string()),
+ channel_type: state.channel_type,
+ org_id: None,
+ team_id: None,
+ }))
+ }
+
async fn get_channel_metadata(
&self,
_channel_id: Uuid,
@@ -532,11 +559,33 @@ impl ChannelRepo for FakeMutationRepo {
async fn add_participant(
&self,
- _channel_id: Uuid,
- _user_id: MacroUserIdStr<'_>,
- _role: ParticipantRole,
- ) -> Result<(), Self::Err> {
- Ok(())
+ channel_id: Uuid,
+ user_id: MacroUserIdStr<'_>,
+ role: ParticipantRole,
+ ) -> Result<bool, Self::Err> {
+ let mut state = self.state.lock().unwrap();
+ if let Some(participant) = state
+ .participants
+ .iter_mut()
+ .find(|participant| participant.user_id == user_id.as_ref())
+ {
+ if participant.left_at.is_none() {
+ return Ok(false);
+ }
+ participant.role = role;
+ participant.joined_at = Utc::now();
+ participant.left_at = None;
+ } else {
+ state.participants.push(ChannelParticipant {
+ channel_id,
+ user_id: user_id.as_ref().to_string(),
+ role,
+ joined_at: Utc::now(),
+ left_at: None,
+ });
+ }
+ state.participant_additions += 1;
+ Ok(true)
}
async fn remove_participant(
@@ -1978,3 +2027,126 @@ async fn patch_message_attachments_event_carries_deltas() {
other => panic!("expected one AttachmentsChanged event, got {other:?}"),
}
}
+
+#[tokio::test]
+async fn private_channel_join_code_is_reused() {
+ let channel_id = Uuid::new_v4();
+ let repo = FakeMutationRepo::new(channel_id, "macro|[email protected]");
+ let svc = mutation_service(repo, FakeEvents::default(), FakeReferenceSharing::default());
+
+ let first = svc.get_channel_join_code(channel_id).await.unwrap();
+ let second = svc.get_channel_join_code(channel_id).await.unwrap();
+
+ assert_eq!(first, second);
+}
+
+#[tokio::test]
+async fn join_code_generation_is_forbidden_for_non_private_channels() {
+ for channel_type in [
+ ChannelType::Public,
+ ChannelType::DirectMessage,
+ ChannelType::Team,
+ ] {
+ let channel_id = Uuid::new_v4();
+ let repo = FakeMutationRepo::new(channel_id, "macro|[email protected]");
+ repo.state.lock().unwrap().channel_type = channel_type;
+ let svc = mutation_service(
+ repo.clone(),
+ FakeEvents::default(),
+ FakeReferenceSharing::default(),
+ );
+
+ let error = svc.get_channel_join_code(channel_id).await.unwrap_err();
+
+ assert!(matches!(error, ChannelMutationErr::Forbidden(_)));
+ assert!(repo.state.lock().unwrap().join_code.is_none());
+ }
+}
+
+#[tokio::test]
+async fn unknown_join_code_returns_not_found() {
+ let channel_id = Uuid::new_v4();
+ let repo = FakeMutationRepo::new(channel_id, "macro|[email protected]");
+ let svc = mutation_service(repo, FakeEvents::default(), FakeReferenceSharing::default());
+
+ let error = svc
+ .join_channel_by_code(sender("macro|[email protected]"), Uuid::new_v4())
+ .await
+ .unwrap_err();
+
+ assert!(matches!(error, ChannelMutationErr::NotFound(_)));
+}
+
+#[tokio::test]
+async fn join_by_code_rejects_non_private_channel() {
+ let channel_id = Uuid::new_v4();
+ let join_code = Uuid::new_v4();
+ let repo = FakeMutationRepo::new(channel_id, "macro|[email protected]");
+ {
+ let mut state = repo.state.lock().unwrap();
+ state.join_code = Some(join_code);
+ state.channel_type = ChannelType::Public;
+ }
+ let svc = mutation_service(repo, FakeEvents::default(), FakeReferenceSharing::default());
+
+ let error = svc
+ .join_channel_by_code(sender("macro|[email protected]"), join_code)
+ .await
+ .unwrap_err();
+
+ assert!(matches!(error, ChannelMutationErr::Forbidden(_)));
+}
+
+#[tokio::test]
+async fn join_by_code_adds_participant_and_dispatches_event() {
+ let channel_id = Uuid::new_v4();
+ let join_code = Uuid::new_v4();
+ let repo = FakeMutationRepo::new(channel_id, "macro|[email protected]");
+ repo.state.lock().unwrap().join_code = Some(join_code);
+ let events = FakeEvents::default();
+ let svc = mutation_service(
+ repo.clone(),
+ events.clone(),
+ FakeReferenceSharing::default(),
+ );
+
+ svc.join_channel_by_code(sender("macro|[email protected]"), join_code)
+ .await
+ .unwrap();
+
+ let state = repo.state.lock().unwrap();
+ assert_eq!(state.participant_additions, 1);
+ assert!(
+ state
+ .participants
+ .iter()
+ .any(|participant| participant.user_id == "macro|[email protected]")
+ );
+ drop(state);
+ assert!(matches!(
+ events.events.lock().unwrap().as_slice(),
+ [ChannelEvent::ParticipantJoined { channel_id: event_channel_id, .. }]
+ if event_channel_id == &channel_id
+ ));
+}
+
+#[tokio::test]
+async fn join_by_code_is_idempotent_for_active_participant() {
+ let channel_id = Uuid::new_v4();
+ let join_code = Uuid::new_v4();
+ let repo = FakeMutationRepo::new(channel_id, "macro|[email protected]");
+ repo.state.lock().unwrap().join_code = Some(join_code);
+ let events = FakeEvents::default();
+ let svc = mutation_service(
+ repo.clone(),
+ events.clone(),
+ FakeReferenceSharing::default(),
+ );
+
+ svc.join_channel_by_code(sender("macro|[email protected]"), join_code)
+ .await
+ .unwrap();
+
+ assert_eq!(repo.state.lock().unwrap().participant_additions, 0);
+ assert!(events.events.lock().unwrap().is_empty());
+}
diff --git a/crates/channels/src/inbound/axum_router.rs b/crates/channels/src/inbound/axum_router.rs
index 9373f20a65..d6c1812ee5 100644
--- a/crates/channels/src/inbound/axum_router.rs
+++ b/crates/channels/src/inbound/axum_router.rs
@@ -9,13 +9,13 @@ use crate::domain::models::{
ParticipantRole, ResolvedChannelMessage, Sender, ThreadInfo, ThreadReply,
};
pub use crate::domain::models::{
- AddParticipantsRequest, ChannelPreview, ChannelPreviewData, CreateChannelRequest,
- CreateChannelResponse, CreateEntityMentionRequest, CreateEntityMentionResponse,
- DeleteEntityMentionResponse, DeleteMessageQuery, GetBatchChannelPreviewRequest,
- GetBatchChannelPreviewResponse, GetOrCreateChannelResponse, GetOrCreateDmRequest,
- GetOrCreatePrivateRequest, PatchChannelRequest, PatchMessageRequest, PostMessageRequest,
- PostMessageResponse, PostReactionRequest, PostTypingRequest, RemoveParticipantsRequest,
- WithChannelId,
+ AddParticipantsRequest, ChannelJoinCodeResponse, ChannelPreview, ChannelPreviewData,
+ CreateChannelRequest, CreateChannelResponse, CreateEntityMentionRequest,
+ CreateEntityMentionResponse, DeleteEntityMentionResponse, DeleteMessageQuery,
+ GetBatchChannelPreviewRequest, GetBatchChannelPreviewResponse, GetOrCreateChannelResponse,
+ GetOrCreateDmRequest, GetOrCreatePrivateRequest, PatchChannelRequest, PatchMessageRequest,
+ PostMessageRequest, PostMessageResponse, PostReactionRequest, PostTypingRequest,
+ RemoveParticipantsRequest, WithChannelId,
};
pub use crate::domain::models::{ChannelMessageFilters, NotificationFilters};
use crate::domain::ports::{
@@ -286,6 +286,10 @@ where
delete(delete_message_handler::<S, Svc>),
)
.route("/{channel_id}/join", post(join_channel_handler::<S, Svc>))
+ .route(
+ "/join/{join_code}",
+ post(join_channel_by_code_handler::<S, Svc>),
+ )
.route("/{channel_id}/leave", post(leave_channel_handler::<S, Svc>))
.route(
"/{channel_id}/participants",
@@ -306,6 +310,10 @@ where
{
channel_mutation_router::<S, Svc>()
.route("/{channel_id}", get(get_channel_handler::<S, Svc>))
+ .route(
+ "/{channel_id}/join-link",
+ get(get_channel_join_link_handler::<S, Svc>),
+ )
.route(
"/{channel_id}/messages",
get(get_channel_messages_handler::<S, Svc>)
@@ -727,6 +735,65 @@ pub async fn remove_participants_handler<S: ChannelService, Svc: EntityAccessSer
Ok(StatusCode::OK)
}
+/// Handler for `GET /channels/{channel_id}/join-link`.
+#[utoipa::path(
+ get,
+ tag = "channels",
+ operation_id = "get_channel_join_link",
+ path = "/channels/{channel_id}/join-link",
+ params(
+ ("channel_id" = Uuid, Path, description = "Channel ID")
+ ),
+ responses(
+ (status = 200, body = ChannelJoinCodeResponse),
+ (status = 400, body = ErrorResponse),
+ (status = 401, body = ErrorResponse),
+ (status = 403, body = ErrorResponse),
+ (status = 404, body = ErrorResponse),
+ (status = 500, body = ErrorResponse),
+ )
+)]
+#[tracing::instrument(err, skip_all)]
+pub async fn get_channel_join_link_handler<S: ChannelService, Svc: EntityAccessService>(
+ State(state): State<ChannelsRouterState<S, Svc>>,
+ access: ChannelAccessLevelExtractor<MemberParticipantRole, Svc>,
+) -> Result<Json<ChannelJoinCodeResponse>, ChannelsHandlerErr> {
+ let channel_id = channel_id_from_receipt(&access.entity_access_receipt)?;
+ let response = state.service.get_channel_join_code(channel_id).await?;
+ Ok(Json(response))
+}
+
+/// Handler for `POST /channels/join/{join_code}`.
+#[utoipa::path(
+ post,
+ tag = "channels",
+ operation_id = "join_channel_by_code",
+ path = "/channels/join/{join_code}",
+ params(
+ ("join_code" = Uuid, Path, description = "Channel join code")
+ ),
+ responses(
+ (status = 200),
+ (status = 400, body = ErrorResponse),
+ (status = 401, body = ErrorResponse),
+ (status = 403, body = ErrorResponse),
+ (status = 404, body = ErrorResponse),
+ (status = 500, body = ErrorResponse),
+ )
+)]
+#[tracing::instrument(err, skip_all)]
+pub async fn join_channel_by_code_handler<S: ChannelService, Svc: EntityAccessService>(
+ State(state): State<ChannelsRouterState<S, Svc>>,
+ Path(join_code): Path<Uuid>,
+ user: MacroUserExtractor,
+) -> Result<StatusCode, ChannelsHandlerErr> {
+ state
+ .service
+ .join_channel_by_code(Sender::new_from_user(user.macro_user_id), join_code)
+ .await?;
+ Ok(StatusCode::OK)
+}
+
/// Handler for `POST /channels/{channel_id}/join`.
#[utoipa::path(
post,
@@ -2201,6 +2268,7 @@ impl IntoResponse for ChannelsHandlerErr {
let status = match &err {
ChannelMutationErr::BadRequest(_) => StatusCode::BAD_REQUEST,
ChannelMutationErr::Unauthorized(_) => StatusCode::UNAUTHORIZED,
+ ChannelMutationErr::Forbidden(_) => StatusCode::FORBIDDEN,
ChannelMutationErr::NotFound(_) => StatusCode::NOT_FOUND,
ChannelMutationErr::Repo(_)
| ChannelMutationErr::Gateway(_)
diff --git a/crates/channels/src/inbound/axum_router/test.rs b/crates/channels/src/inbound/axum_router/test.rs
index 52837e669b..17d353851b 100644
--- a/crates/channels/src/inbound/axum_router/test.rs
+++ b/crates/channels/src/inbound/axum_router/test.rs
@@ -489,6 +489,118 @@ impl ChannelService for ParticipantsService {
}
}
+#[derive(Clone)]
+struct JoinLinkService {
+ join_code: Uuid,
+ private_channel_id: Uuid,
+ forbidden_channel_ids: Arc<Vec<Uuid>>,
+ requested_channel_ids: Arc<Mutex<Vec<Uuid>>>,
+ joined_users: Arc<Mutex<Vec<Sender>>>,
+}
+
+impl JoinLinkService {
+ fn new(private_channel_id: Uuid, join_code: Uuid, forbidden_channel_ids: Vec<Uuid>) -> Self {
+ Self {
+ join_code,
+ private_channel_id,
+ forbidden_channel_ids: Arc::new(forbidden_channel_ids),
+ requested_channel_ids: Arc::default(),
+ joined_users: Arc::default(),
+ }
+ }
+}
+
+impl ChannelService for JoinLinkService {
+ async fn get_channel_messages(
+ &self,
+ _channel_id: Uuid,
+ _query: Query<Uuid, CreatedAt, ()>,
+ _direction: MessagePageDirection,
+ _limit: u16,
+ _filters: &ChannelMessageFilters,
+ _notification_user_id: Option<MacroUserIdStr<'static>>,
+ ) -> Result<ChannelMessagesQueryResult, ChannelMessagesErr> {
+ unimplemented!()
+ }
+
+ async fn get_channel_attachments(
+ &self,
+ _channel_id: Uuid,
+ _query: Query<Uuid, CreatedAt, ()>,
+ _limit: u16,
+ _attachment_type: Option<ChannelAttachmentType>,
+ ) -> Result<ChannelAttachmentsPage, ChannelMessagesErr> {
+ unimplemented!()
+ }
+
+ async fn get_channel_participants(
+ &self,
+ _channel_id: Uuid,
+ ) -> Result<Vec<ChannelParticipant>, ChannelMessagesErr> {
+ unimplemented!()
+ }
+
+ async fn get_attachment_references(
+ &self,
+ _entity_type: String,
+ _entity_id: String,
+ _user_id: String,
+ ) -> Result<Vec<crate::domain::models::AttachmentEntityReference>, ChannelMessagesErr> {
+ unimplemented!()
+ }
+
+ async fn get_channel_messages_around(
+ &self,
+ _channel_id: Uuid,
+ _message_id: Uuid,
+ _limit: u16,
+ ) -> Result<ChannelMessagesQueryResult, ChannelMessagesErr> {
+ unimplemented!()
+ }
+
+ async fn get_thread_replies(
+ &self,
+ _channel_id: Uuid,
+ _message_id: Uuid,
+ ) -> Result<Vec<crate::domain::models::ThreadReply>, ChannelMessagesErr> {
+ unimplemented!()
+ }
+
+ async fn get_channel_join_code(
+ &self,
+ channel_id: Uuid,
+ ) -> Result<ChannelJoinCodeResponse, ChannelMutationErr> {
+ self.requested_channel_ids.lock().unwrap().push(channel_id);
+ if self.forbidden_channel_ids.contains(&channel_id) {
+ return Err(ChannelMutationErr::Forbidden(
+ "join links are only available for private channels".to_string(),
+ ));
+ }
+ if channel_id != self.private_channel_id {
+ return Err(ChannelMutationErr::NotFound(
+ "channel not found".to_string(),
+ ));
+ }
+ Ok(ChannelJoinCodeResponse {
+ join_code: self.join_code,
+ })
+ }
+
+ async fn join_channel_by_code(
+ &self,
+ actor: Sender,
+ join_code: Uuid,
+ ) -> Result<(), ChannelMutationErr> {
+ if join_code != self.join_code {
+ return Err(ChannelMutationErr::NotFound(
+ "channel join code not found".to_string(),
+ ));
+ }
+ self.joined_users.lock().unwrap().push(actor);
+ Ok(())
+ }
+}
+
#[derive(Clone, Default)]
struct RecordingMutationService {
posts: Arc<Mutex<Vec<(Sender, Uuid, PostMessageRequest)>>>,
@@ -741,6 +853,163 @@ fn not_found_router() -> Router {
.layer(user_extension())
}
+#[tokio::test]
+async fn active_participant_can_get_persisted_channel_join_code() {
+ let channel_id = Uuid::new_v4();
+ let join_code = Uuid::new_v4();
+ let service = JoinLinkService::new(channel_id, join_code, vec![]);
+ let requested_channel_ids = service.requested_channel_ids.clone();
+ let router = channels_router(ChannelsRouterState::new(
+ service,
+ TestAccessService::allow(),
+ ))
+ .layer(user_extension());
+
+ let response = router
+ .oneshot(
+ Request::builder()
+ .uri(format!("/{channel_id}/join-link"))
+ .body(axum::body::Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::OK);
+ let body = response.into_body().collect().await.unwrap().to_bytes();
+ assert_eq!(
+ serde_json::from_slice::<serde_json::Value>(&body).unwrap(),
+ serde_json::json!({ "join_code": join_code })
+ );
+ assert_eq!(*requested_channel_ids.lock().unwrap(), vec![channel_id]);
+}
+
+#[tokio::test]
+async fn non_participant_cannot_get_channel_join_code() {
+ let channel_id = Uuid::new_v4();
+ let service = JoinLinkService::new(channel_id, Uuid::new_v4(), vec![]);
+ let requested_channel_ids = service.requested_channel_ids.clone();
+ let router = channels_router(ChannelsRouterState::new(service, TestAccessService::deny()))
+ .layer(user_extension());
+
+ let response = router
+ .oneshot(
+ Request::builder()
+ .uri(format!("/{channel_id}/join-link"))
+ .body(axum::body::Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
+ assert!(requested_channel_ids.lock().unwrap().is_empty());
+}
+
+#[tokio::test]
+async fn non_private_channels_cannot_get_join_codes() {
+ let non_private_channels = [
+ ("public", Uuid::new_v4()),
+ ("direct_message", Uuid::new_v4()),
+ ("team", Uuid::new_v4()),
+ ];
+ let service = JoinLinkService::new(
+ Uuid::new_v4(),
+ Uuid::new_v4(),
+ non_private_channels.iter().map(|(_, id)| *id).collect(),
+ );
+ let router = channels_router(ChannelsRouterState::new(
+ service,
+ TestAccessService::allow(),
+ ))
+ .layer(user_extension());
+
+ for (channel_type, channel_id) in non_private_channels {
+ let response = router
+ .clone()
+ .oneshot(
+ Request::builder()
+ .uri(format!("/{channel_id}/join-link"))
+ .body(axum::body::Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.status(),
+ StatusCode::FORBIDDEN,
+ "expected {channel_type} channel to be forbidden"
+ );
+ }
+}
+
+#[tokio::test]
+async fn join_channel_by_code_handles_malformed_and_unknown_codes() {
+ let service = JoinLinkService::new(Uuid::new_v4(), Uuid::new_v4(), vec![]);
+ let router = channels_router(ChannelsRouterState::new(service, TestAccessService::deny()))
+ .layer(user_extension());
+
+ let malformed_response = router
+ .clone()
+ .oneshot(
+ Request::builder()
+ .method("POST")
+ .uri("/join/not-a-uuid")
+ .body(axum::body::Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(malformed_response.status(), StatusCode::BAD_REQUEST);
+
+ let unknown_response = router
+ .oneshot(
+ Request::builder()
+ .method("POST")
+ .uri(format!("/join/{}", Uuid::new_v4()))
+ .body(axum::body::Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(unknown_response.status(), StatusCode::NOT_FOUND);
+}
+
+#[tokio::test]
+async fn authenticated_user_can_join_by_code_without_channel_access() {
+ let join_code = Uuid::new_v4();
+ let service = JoinLinkService::new(Uuid::new_v4(), join_code, vec![]);
+ let joined_users = service.joined_users.clone();
+ let router = channels_router(ChannelsRouterState::new(service, TestAccessService::deny()))
+ .layer(user_extension());
+
+ let response = router
+ .oneshot(
+ Request::builder()
+ .method("POST")
+ .uri(format!("/join/{join_code}"))
+ .body(axum::body::Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::OK);
+ assert_eq!(
+ response
+ .into_body()
+ .collect()
+ .await
+ .unwrap()
+ .to_bytes()
+ .len(),
+ 0
+ );
+ let users = joined_users.lock().unwrap();
+ assert_eq!(users.len(), 1);
+ assert_eq!(users[0].as_ref(), "macro|[email protected]");
+}
+
#[tokio::test]
async fn post_message_route_uses_entity_access_and_mutation_service() {
let mutation_service = RecordingMutationService::default();
diff --git a/crates/channels/src/outbound/pg_channels_repo.rs b/crates/channels/src/outbound/pg_channels_repo.rs
index d204b5ba95..22211229ca 100644
--- a/crates/channels/src/outbound/pg_channels_repo.rs
+++ b/crates/channels/src/outbound/pg_channels_repo.rs
@@ -2529,6 +2529,48 @@ impl ChannelRepo for PgChannelsRepo {
})
}
+ async fn get_or_create_channel_join_code(&self, channel_id: Uuid) -> Result<Uuid, Self::Err> {
+ let candidate_join_code = macro_uuid::generate_uuid_v7();
+ let join_code = sqlx::query_scalar!(
+ r#"
+ UPDATE comms_channels
+ SET join_code = COALESCE(join_code, $2)
+ WHERE id = $1
+ RETURNING join_code AS "join_code!"
+ "#,
+ channel_id,
+ candidate_join_code,
+ )
+ .fetch_one(&self.pool)
+ .await
+ .context("failed to get or create channel join code")?;
+ Ok(join_code)
+ }
+
+ async fn get_channel_info_by_join_code(
+ &self,
+ join_code: Uuid,
+ ) -> Result<Option<ChannelInfo>, Self::Err> {
+ let row = sqlx::query_as!(
+ ChannelInfoRow,
+ r#"
+ SELECT id, name, channel_type AS "channel_type: ChannelType", org_id, team_id
+ FROM comms_channels
+ WHERE join_code = $1
+ "#,
+ join_code,
+ )
+ .fetch_optional(&self.pool)
+ .await?;
+ Ok(row.map(|row| ChannelInfo {
+ id: row.id,
+ name: row.name,
+ channel_type: row.channel_type,
+ org_id: row.org_id,
+ team_id: row.team_id,
+ }))
+ }
+
async fn get_channel_metadata(
&self,
channel_id: Uuid,
@@ -2834,11 +2876,16 @@ impl ChannelRepo for PgChannelsRepo {
channel_id: Uuid,
user_id: MacroUserIdStr<'_>,
role: ParticipantRole,
- ) -> Result<(), Self::Err> {
- sqlx::query!(
+ ) -> Result<bool, Self::Err> {
+ let result = sqlx::query!(
r#"
INSERT INTO comms_channel_participants (channel_id, user_id, role)
VALUES ($1, $2, $3)
+ ON CONFLICT (channel_id, user_id) DO UPDATE
+ SET role = EXCLUDED.role,
+ joined_at = now(),
+ left_at = NULL
+ WHERE comms_channel_participants.left_at IS NOT NULL
"#,
channel_id,
user_id.as_ref(),
@@ -2847,7 +2894,7 @@ impl ChannelRepo for PgChannelsRepo {
.execute(&self.pool)
.await
.context("unable to add participant to channel")?;
- Ok(())
+ Ok(result.rows_affected() > 0)
}
async fn remove_participant(&self, channel_id: Uuid, user_id: String) -> Result<(), Self::Err> {
diff --git a/crates/channels/src/outbound/pg_channels_repo/tests.rs b/crates/channels/src/outbound/pg_channels_repo/tests.rs
index 690227d016..411fe29e3e 100644
--- a/crates/channels/src/outbound/pg_channels_repo/tests.rs
+++ b/crates/channels/src/outbound/pg_channels_repo/tests.rs
@@ -78,6 +78,82 @@ fn report_err(e: rootcause::Report) -> anyhow::Error {
anyhow::anyhow!("{e:?}")
}
+#[sqlx::test(
+ fixtures(path = "../../../fixtures", scripts("channels_repo")),
+ migrator = "MACRO_DB_MIGRATIONS"
+)]
+async fn add_participant_atomically_adds_or_reactivates(pool: Pool<Postgres>) {
+ let repo = repo(pool);
+
+ assert!(
+ !repo
+ .add_participant(CH1, macro_user_id(USER_A), ParticipantRole::Member)
+ .await
+ .unwrap()
+ );
+ assert!(
+ repo.add_participant(CH1, macro_user_id(LEFT_USER), ParticipantRole::Member)
+ .await
+ .unwrap()
+ );
+ assert!(
+ !repo
+ .add_participant(CH1, macro_user_id(LEFT_USER), ParticipantRole::Member)
+ .await
+ .unwrap()
+ );
+ assert!(
+ repo.add_participant(CH1, macro_user_id(NON_MEMBER), ParticipantRole::Member)
+ .await
+ .unwrap()
+ );
+}
+
+#[sqlx::test(
+ fixtures(path = "../../../fixtures", scripts("channels_repo")),
+ migrator = "MACRO_DB_MIGRATIONS"
+)]
+async fn channel_join_code_is_generated_once_and_reused(pool: Pool<Postgres>) {
+ let repo = repo(pool);
+
+ let first = repo.get_or_create_channel_join_code(CH1).await.unwrap();
+ let second = repo.get_or_create_channel_join_code(CH1).await.unwrap();
+
+ assert_eq!(first, second);
+}
+
+#[sqlx::test(
+ fixtures(path = "../../../fixtures", scripts("channels_repo")),
+ migrator = "MACRO_DB_MIGRATIONS"
+)]
+async fn channel_can_be_resolved_by_join_code(pool: Pool<Postgres>) {
+ let repo = repo(pool);
+ let join_code = repo.get_or_create_channel_join_code(CH1).await.unwrap();
+
+ let channel = repo
+ .get_channel_info_by_join_code(join_code)
+ .await
+ .unwrap()
+ .unwrap();
+
+ assert_eq!(channel.id, CH1);
+}
+
+#[sqlx::test(
+ fixtures(path = "../../../fixtures", scripts("channels_repo")),
+ migrator = "MACRO_DB_MIGRATIONS"
+)]
+async fn unknown_channel_join_code_resolves_to_none(pool: Pool<Postgres>) {
+ let repo = repo(pool);
+
+ let channel = repo
+ .get_channel_info_by_join_code(Uuid::new_v4())
+ .await
+ .unwrap();
+
+ assert!(channel.is_none());
+}
+
async fn insert_channel_message_notification(
pool: &Pool<Postgres>,
user_id: &str,
diff --git a/crates/macro_db_client/migrations/20260714162749_add_channel_join_code.sql b/crates/macro_db_client/migrations/20260714162749_add_channel_join_code.sql
new file mode 100644
index 0000000000..2f98498b88
--- /dev/null
+++ b/crates/macro_db_client/migrations/20260714162749_add_channel_join_code.sql
@@ -0,0 +1,2 @@
+ALTER TABLE public.comms_channels
+ADD COLUMN join_code UUID;
diff --git a/crates/macro_db_client/migrations/20260714172454_add_channel_join_code_unique_index.sql b/crates/macro_db_client/migrations/20260714172454_add_channel_join_code_unique_index.sql
new file mode 100644
index 0000000000..82163df55d
--- /dev/null
+++ b/crates/macro_db_client/migrations/20260714172454_add_channel_join_code_unique_index.sql
@@ -0,0 +1,5 @@
+-- no-transaction
+
+CREATE UNIQUE INDEX CONCURRENTLY comms_channels_join_code_uq
+ON public.comms_channels (join_code)
+WHERE join_code IS NOT NULL;
diff --git a/services/document_storage_service/src/api/swagger.rs b/services/document_storage_service/src/api/swagger.rs
index 72e01974c3..977dcae0af 100644
--- a/services/document_storage_service/src/api/swagger.rs
+++ b/services/document_storage_service/src/api/swagger.rs
@@ -224,6 +224,8 @@ use utoipa::OpenApi;
channels::inbound::axum_router::post_typing_handler,
channels::inbound::axum_router::add_participants_handler,
channels::inbound::axum_router::remove_participants_handler,
+ channels::inbound::axum_router::get_channel_join_link_handler,
+ channels::inbound::axum_router::join_channel_by_code_handler,
channels::inbound::axum_router::join_channel_handler,
channels::inbound::axum_router::leave_channel_handler,
channels::inbound::axum_router::get_channel_messages_handler,