Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

fix(invitation): drop stale pending-invitation rows when an invite concludes elsewhere (MUL-7389)

苗大ad6b42f0930b
diff --git a/packages/core/realtime/use-realtime-sync-invitations.test.tsx b/packages/core/realtime/use-realtime-sync-invitations.test.tsx
new file mode 100644
index 0000000000..689c0e4362
--- /dev/null
+++ b/packages/core/realtime/use-realtime-sync-invitations.test.tsx
@@ -0,0 +1,280 @@
+/** @vitest-environment jsdom */
+import { QueryClientProvider, useQuery } from "@tanstack/react-query";
+import { act, cleanup, renderHook, waitFor } from "@testing-library/react";
+import type { ReactNode } from "react";
+import { afterEach, expect, it, vi } from "vitest";
+import { setApiInstance } from "../api";
+import type { ApiClient } from "../api/client";
+import { WSClient } from "../api/ws-client";
+import { createQueryClient } from "../query-client";
+import type { Invitation } from "../types";
+import { myInvitationListOptions, workspaceKeys } from "../workspace/queries";
+import { useRealtimeSync, type RealtimeSyncStores } from "./use-realtime-sync";
+
+vi.mock("../platform/workspace-storage", () => ({
+ getCurrentWsId: () => "ws-1",
+ getCurrentSlug: () => "test-ws",
+ createWorkspaceAwareStorage: (adapter: unknown) => adapter,
+ registerForWorkspaceRehydration: () => {},
+}));
+vi.mock("../paths", () => ({
+ useHasOnboarded: () => true,
+ resolvePostAuthDestination: () => "/",
+}));
+
+afterEach(() => {
+ cleanup();
+ vi.restoreAllMocks();
+});
+
+// Global QueryClient defaults are staleTime: Infinity + no focus refetch, so
+// the pending-invitations list only moves when something invalidates it. The
+// invitation:accepted / invitation:declined handlers must include it: the
+// accepting client may have concluded the invite from another surface, and
+// its own stale sidebar row otherwise survives until restart.
+it.each(["invitation:accepted", "invitation:declined"] as const)(
+ "refreshes the pending-invitations list on %s when the actor is the current user",
+ async (event) => {
+ const qc = createQueryClient();
+ const invitation: Invitation = {
+ id: "inv-1",
+ workspace_id: "ws-2",
+ inviter_id: "u2",
+ invitee_email: "[email protected]",
+ invitee_user_id: "u1",
+ role: "member",
+ status: "pending",
+ created_at: "2026-09-14T00:00:00Z",
+ updated_at: "2026-09-14T00:00:00Z",
+ expires_at: "2026-09-21T00:00:00Z",
+ workspace_name: "Second Workspace",
+ inviter_name: "Inviter",
+ inviter_email: "[email protected]",
+ };
+ let rows = [invitation];
+ const listMyInvitations = vi.fn(async () => rows);
+ setApiInstance({
+ listMyInvitations,
+ } as unknown as ApiClient);
+
+ const handlers: Record<string, (payload: unknown, actorId?: string, actorType?: string) => void> = {};
+ const ws = {
+ on: (e: string, handler: (payload: unknown) => void) => {
+ handlers[e] = handler;
+ return () => {
+ delete handlers[e];
+ };
+ },
+ onAny: () => () => {},
+ onReconnect: () => () => {},
+ } as unknown as WSClient;
+ const stores = {
+ authStore: { getState: () => ({ user: { id: "u1" } }) },
+ } as unknown as RealtimeSyncStores;
+ function Wrapper({ children }: { children: ReactNode }) {
+ return <QueryClientProvider client={qc}>{children}</QueryClientProvider>;
+ }
+ vi.spyOn(document, "hasFocus").mockReturnValue(true);
+
+ const page = renderHook(() => useQuery(myInvitationListOptions()), {
+ wrapper: Wrapper,
+ });
+ renderHook(() => useRealtimeSync(ws, stores), { wrapper: Wrapper });
+ try {
+ await waitFor(() => expect(page.result.current.data).toEqual(rows));
+ expect(listMyInvitations).toHaveBeenCalledTimes(1);
+
+ rows = [];
+ await act(async () => {
+ // ws-client unpacks a frame into (payload, actorId, actorType) — the
+ // actor rides the frame envelope, not the payload.
+ handlers[event]!({ invitation_id: "inv-1" }, "u1", "member");
+ });
+ await waitFor(() => expect(listMyInvitations).toHaveBeenCalledTimes(2));
+ await waitFor(() => expect(page.result.current.data).toEqual([]));
+ expect(qc.getQueryState(workspaceKeys.myInvitations())?.data).toEqual([]);
+ } finally {
+ page.unmount();
+ }
+ },
+);
+
+// The workspace broadcast fans the event out to every online member; the
+// account-level pending list must only move for the actor, or every
+// accept/decline refetches the list once per member. The workspace-scoped
+// admin list still refreshes unconditionally — admins rely on the broadcast.
+it.each(["invitation:accepted", "invitation:declined"] as const)(
+ "does not refresh the pending-invitations list on %s for a non-actor member",
+ async (event) => {
+ const qc = createQueryClient();
+ const listMyInvitations = vi.fn(async () => []);
+ setApiInstance({
+ listMyInvitations,
+ } as unknown as ApiClient);
+
+ const handlers: Record<string, (payload: unknown, actorId?: string, actorType?: string) => void> = {};
+ const ws = {
+ on: (e: string, handler: (payload: unknown) => void) => {
+ handlers[e] = handler;
+ return () => {
+ delete handlers[e];
+ };
+ },
+ onAny: () => () => {},
+ onReconnect: () => () => {},
+ } as unknown as WSClient;
+ const stores = {
+ authStore: { getState: () => ({ user: { id: "u1" } }) },
+ } as unknown as RealtimeSyncStores;
+ function Wrapper({ children }: { children: ReactNode }) {
+ return <QueryClientProvider client={qc}>{children}</QueryClientProvider>;
+ }
+
+ qc.setQueryData(workspaceKeys.invitations("ws-1"), []);
+ qc.setQueryData(workspaceKeys.myInvitations(), []);
+ const page = renderHook(() => useQuery(myInvitationListOptions()), {
+ wrapper: Wrapper,
+ });
+ renderHook(() => useRealtimeSync(ws, stores), { wrapper: Wrapper });
+ try {
+ // Cache hit + staleTime: Infinity: the list mounts fresh and never
+ // fetches, so any call after the event means a (wrong) invalidation.
+ await waitFor(() => expect(page.result.current.data).toEqual([]));
+ expect(listMyInvitations).not.toHaveBeenCalled();
+
+ await act(async () => {
+ handlers[event]!({ invitation_id: "inv-1" }, "u2", "member");
+ });
+ // Give any (wrong) invalidation a chance to trigger a refetch.
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ });
+ expect(listMyInvitations).not.toHaveBeenCalled();
+ expect(qc.getQueryState(workspaceKeys.myInvitations())?.isInvalidated).toBe(
+ false,
+ );
+ expect(
+ qc.getQueryState(workspaceKeys.invitations("ws-1"))?.isInvalidated,
+ ).toBe(true);
+ } finally {
+ page.unmount();
+ }
+ },
+);
+
+// --- Wire contract ---
+//
+// The tests above feed (payload, actorId, actorType) directly — the shape
+// ws-client hands to handlers — but they cannot catch drift in that shape
+// itself. These drive a real WSClient through a fake WebSocket and feed the
+// exact frames server/cmd/server/listeners.go marshals for these events
+// ({type, payload, actor_id, actor_type}), pinning frame → onmessage unpack
+// → handler → gate end to end.
+class FakeWebSocket {
+ static lastInstance: FakeWebSocket | null = null;
+ onopen: (() => void) | null = null;
+ onmessage: ((ev: { data: string }) => void) | null = null;
+ onclose: (() => void) | null = null;
+ onerror: (() => void) | null = null;
+ readyState = 1;
+ constructor() {
+ FakeWebSocket.lastInstance = this;
+ }
+ close() {}
+ send() {}
+}
+
+function wireFrame(
+ event: "invitation:accepted" | "invitation:declined",
+ payload: Record<string, unknown>,
+ actorId: string,
+): string {
+ return JSON.stringify({
+ type: event,
+ payload,
+ actor_id: actorId,
+ actor_type: "member",
+ });
+}
+
+it.each(["invitation:accepted", "invitation:declined"] as const)(
+ "unpacks a real %s frame: refreshes the actor's list, holds a non-actor's",
+ async (event) => {
+ vi.stubGlobal("WebSocket", FakeWebSocket as unknown as typeof WebSocket);
+ const qc = createQueryClient();
+ const invitation: Invitation = {
+ id: "inv-1",
+ workspace_id: "ws-2",
+ inviter_id: "u2",
+ invitee_email: "[email protected]",
+ invitee_user_id: "u1",
+ role: "member",
+ status: "pending",
+ created_at: "2026-09-14T00:00:00Z",
+ updated_at: "2026-09-14T00:00:00Z",
+ expires_at: "2026-09-21T00:00:00Z",
+ workspace_name: "Second Workspace",
+ inviter_name: "Inviter",
+ inviter_email: "[email protected]",
+ };
+ let rows = [invitation];
+ const listMyInvitations = vi.fn(async () => rows);
+ setApiInstance({
+ listMyInvitations,
+ } as unknown as ApiClient);
+
+ const client = new WSClient("ws://example.test/ws");
+ client.setAuth("tok", "test-ws");
+ client.connect();
+ const stores = {
+ authStore: { getState: () => ({ user: { id: "u1" } }) },
+ } as unknown as RealtimeSyncStores;
+ function Wrapper({ children }: { children: ReactNode }) {
+ return <QueryClientProvider client={qc}>{children}</QueryClientProvider>;
+ }
+ vi.spyOn(document, "hasFocus").mockReturnValue(true);
+
+ const page = renderHook(() => useQuery(myInvitationListOptions()), {
+ wrapper: Wrapper,
+ });
+ renderHook(() => useRealtimeSync(client, stores), { wrapper: Wrapper });
+ try {
+ await waitFor(() => expect(page.result.current.data).toEqual(rows));
+ expect(listMyInvitations).toHaveBeenCalledTimes(1);
+
+ rows = [];
+ // Minimal stand-ins for the payloads the server publishes on each
+ // producer path (invitation.go): member on accept, email on decline.
+ const payload =
+ event === "invitation:accepted"
+ ? { invitation_id: "inv-1", member: { user_id: "u1", role: "member" } }
+ : { invitation_id: "inv-1", invitee_email: "[email protected]" };
+
+ // The acting invitee's device hears the conclusion (direct send or
+ // broadcast) — its stale row must drop within a WS tick.
+ await act(async () => {
+ FakeWebSocket.lastInstance!.onmessage!({
+ data: wireFrame(event, payload, "u1"),
+ });
+ });
+ await waitFor(() => expect(listMyInvitations).toHaveBeenCalledTimes(2));
+ await waitFor(() => expect(page.result.current.data).toEqual([]));
+
+ // A non-actor member receiving the same broadcast must not refresh.
+ await act(async () => {
+ FakeWebSocket.lastInstance!.onmessage!({
+ data: wireFrame(event, payload, "u2"),
+ });
+ });
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ });
+ expect(listMyInvitations).toHaveBeenCalledTimes(2);
+ expect(page.result.current.data).toEqual([]);
+ } finally {
+ page.unmount();
+ client.disconnect();
+ vi.unstubAllGlobals();
+ }
+ },
+);
diff --git a/packages/core/realtime/use-realtime-sync.ts b/packages/core/realtime/use-realtime-sync.ts
index 50682ee4d3..7df45f638b 100644
--- a/packages/core/realtime/use-realtime-sync.ts
+++ b/packages/core/realtime/use-realtime-sync.ts
@@ -1313,20 +1313,40 @@ export function useRealtimeSync(
);
});
- // invitation:accepted / declined / revoked — refresh invitation lists
- const unsubInvitationAccepted = ws.on("invitation:accepted", () => {
- const currentWsId = getCurrentWsId();
- if (currentWsId) {
- qc.invalidateQueries({ queryKey: workspaceKeys.invitations(currentWsId) });
- qc.invalidateQueries({ queryKey: workspaceKeys.members(currentWsId) });
- }
- });
- const unsubInvitationDeclined = ws.on("invitation:declined", () => {
- const currentWsId = getCurrentWsId();
- if (currentWsId) {
- qc.invalidateQueries({ queryKey: workspaceKeys.invitations(currentWsId) });
- }
- });
+ // invitation:accepted / declined / revoked — refresh invitation lists.
+ // The workspace broadcast reaches every online member, so the admin lists
+ // refresh unconditionally. The account-level pending list is gated on the
+ // acting user: only the invitee who concluded the invite (possibly from
+ // another surface or device) needs their stale pending row dropped —
+ // staleTime is Infinity, so nothing refetches it on its own. Without the
+ // gate every accept/decline fanout refetches the list once per online
+ // member. The actor rides the frame envelope (ws-client hands it to the
+ // handler as its second argument), not the event payload.
+ const unsubInvitationAccepted = ws.on(
+ "invitation:accepted",
+ (_payload, actorId) => {
+ const currentWsId = getCurrentWsId();
+ if (currentWsId) {
+ qc.invalidateQueries({ queryKey: workspaceKeys.invitations(currentWsId) });
+ qc.invalidateQueries({ queryKey: workspaceKeys.members(currentWsId) });
+ }
+ if (actorId === authStore.getState().user?.id) {
+ qc.invalidateQueries({ queryKey: workspaceKeys.myInvitations() });
+ }
+ },
+ );
+ const unsubInvitationDeclined = ws.on(
+ "invitation:declined",
+ (_payload, actorId) => {
+ const currentWsId = getCurrentWsId();
+ if (currentWsId) {
+ qc.invalidateQueries({ queryKey: workspaceKeys.invitations(currentWsId) });
+ }
+ if (actorId === authStore.getState().user?.id) {
+ qc.invalidateQueries({ queryKey: workspaceKeys.myInvitations() });
+ }
+ },
+ );
const unsubInvitationRevoked = ws.on("invitation:revoked", () => {
qc.invalidateQueries({ queryKey: workspaceKeys.myInvitations() });
});
diff --git a/packages/views/layout/app-sidebar.test.tsx b/packages/views/layout/app-sidebar.test.tsx
index 520ba132ea..f3ac633b45 100644
--- a/packages/views/layout/app-sidebar.test.tsx
+++ b/packages/views/layout/app-sidebar.test.tsx
@@ -9,13 +9,21 @@ import { ApiError } from "@multica/core/api";
import { renderWithI18n } from "../test/i18n";
import { AppSidebar } from "./app-sidebar";
-const { appForeground, chatSessions, chatStore, detail, deletePin, navigation, pins, sidebarState, summary, workspaces } = vi.hoisted(() => ({
+const { appForeground, chatSessions, chatStore, detail, deletePin, invitationApi, navigation, pins, sidebarState, summary, workspaces } = vi.hoisted(() => ({
appForeground: { current: true },
sidebarState: { setOpenMobile: vi.fn() },
chatSessions: { current: [] as { id?: string; unread_count?: number }[] },
chatStore: { current: { activeSessionId: null as string | null, isOpen: false } },
detail: { current: { isPending: false, isError: false, data: null as unknown, error: null as unknown } },
deletePin: vi.fn(),
+ // Captures the sidebar's invitation accept/decline mutations so the
+ // self-heal wiring (error → invalidate the pending list) is observable.
+ invitationApi: {
+ accept: vi.fn(),
+ decline: vi.fn(),
+ invalidateQueries: vi.fn(),
+ mutations: [] as Array<Record<string, unknown>>,
+ },
navigation: { current: { pathname: "/acme/issues" } },
summary: { current: [] as { workspace_id: string; count: number }[] },
workspaces: {
@@ -151,6 +159,8 @@ vi.mock("@multica/core/api", async (importOriginal) => {
api: {
...actual.api,
getBaseUrl: () => "http://127.0.0.1:8080",
+ acceptInvitation: invitationApi.accept,
+ declineInvitation: invitationApi.decline,
},
};
});
@@ -184,7 +194,10 @@ vi.mock("@multica/core/workspace/queries", () => ({
}));
vi.mock("@tanstack/react-query", async (importOriginal) => ({
...(await importOriginal<typeof import("@tanstack/react-query")>()),
- useMutation: () => ({ isPending: false, mutate: vi.fn() }),
+ useMutation: (options: Record<string, unknown> = {}) => {
+ invitationApi.mutations.push(options);
+ return { isPending: false, mutate: vi.fn() };
+ },
useQuery: ({ queryKey }: { queryKey: readonly unknown[] }) => {
if (queryKey[0] === "pins") return { data: pins.current };
if (queryKey[0] === "issue") return detail.current;
@@ -193,7 +206,7 @@ vi.mock("@tanstack/react-query", async (importOriginal) => ({
if (queryKey[0] === "chat" && queryKey[2] === "sessions") return { data: chatSessions.current };
return { data: [] };
},
- useQueryClient: () => ({ fetchQuery: vi.fn(), invalidateQueries: vi.fn() }),
+ useQueryClient: () => ({ fetchQuery: vi.fn(), invalidateQueries: invitationApi.invalidateQueries }),
}));
describe("PinRow", () => {
@@ -489,3 +502,39 @@ describe("personal nav — Chat", () => {
expect(chatBadge(container)).toHaveAttribute("aria-label", "5");
});
});
+
+describe("Pending invitation self-heal", () => {
+ beforeEach(() => {
+ invitationApi.accept.mockReset();
+ invitationApi.decline.mockReset();
+ invitationApi.invalidateQueries.mockClear();
+ invitationApi.mutations.length = 0;
+ invitationApi.accept.mockRejectedValue(new Error("invitation is not pending"));
+ invitationApi.decline.mockRejectedValue(new Error("invitation is not pending"));
+ navigation.current.pathname = "/acme/issues";
+ workspaces.current = [];
+ });
+
+ // "invitation is not pending" means the row on screen was concluded from
+ // another surface. Both mutations must invalidate the pending list on
+ // failure so the stale row drops instead of surviving until restart.
+ it("invalidates the pending-invitations list when accept or decline fails", async () => {
+ render(<AppSidebar />);
+ expect(invitationApi.mutations).toHaveLength(2);
+
+ for (const options of invitationApi.mutations as Array<{
+ mutationFn: (id: string) => Promise<unknown>;
+ onError?: (...args: unknown[]) => unknown;
+ onSettled?: (...args: unknown[]) => unknown;
+ }>) {
+ const settle = options.onError ?? options.onSettled;
+ expect(settle).toBeTypeOf("function");
+ invitationApi.invalidateQueries.mockClear();
+ await expect(options.mutationFn("inv-1")).rejects.toThrow("invitation is not pending");
+ await settle!(new Error("invitation is not pending"), "inv-1", undefined, undefined);
+ expect(invitationApi.invalidateQueries).toHaveBeenCalledWith({ queryKey: ["invitations"] });
+ }
+ expect(invitationApi.accept).toHaveBeenCalledTimes(1);
+ expect(invitationApi.decline).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/packages/views/layout/app-sidebar.tsx b/packages/views/layout/app-sidebar.tsx
index 876786f0bb..b1fc58bb79 100644
--- a/packages/views/layout/app-sidebar.tsx
+++ b/packages/views/layout/app-sidebar.tsx
@@ -589,10 +589,20 @@ export function AppSidebar({ topSlot, searchSlot, headerClassName, headerStyle }
push(paths.workspace(joined.slug).issues());
}
},
+ onError: () => {
+ // "invitation is not pending" means the invite was concluded from
+ // another surface while this row was on screen. Refetch so the stale
+ // row drops instead of sticking around until restart — a silent
+ // failure here reads as "the button does nothing".
+ queryClient.invalidateQueries({ queryKey: workspaceKeys.myInvitations() });
+ },
});
const declineInvitationMut = useMutation({
mutationFn: (id: string) => api.declineInvitation(id),
- onSuccess: () => {
+ // Either outcome must refresh the list: success drops the declined row,
+ // and a failure ("invitation is not pending") means the invite was
+ // concluded from another surface — refetch drops the stale row.
+ onSettled: () => {
queryClient.invalidateQueries({ queryKey: workspaceKeys.myInvitations() });
},
});
diff --git a/server/cmd/server/listeners.go b/server/cmd/server/listeners.go
index 78b3464952..5dc32524fe 100644
--- a/server/cmd/server/listeners.go
+++ b/server/cmd/server/listeners.go
@@ -177,6 +177,30 @@ func registerListeners(bus *events.Bus, b realtime.Broadcaster) {
}
})
+ // invitation:accepted / invitation:declined — also send to the invitee so
+ // their pending list updates. The actor is the invitee on every producer
+ // path, but they are usually NOT in the workspace room yet: a client binds
+ // its socket to the workspace it currently has open, so a user concluding
+ // an invitation with no workspace open (or a different one open) never
+ // receives the broadcast below and their stale pending row survives until
+ // restart (#8432). Pass excludeWorkspace so clients already in the room
+ // (reached via BroadcastToWorkspace in SubscribeAll) don't get it twice.
+ // invitation:revoked keeps its invitee_user_id routing above: its actor is
+ // the revoking admin, not the affected invitee.
+ for _, eventType := range []string{protocol.EventInvitationAccepted, protocol.EventInvitationDeclined} {
+ bus.Subscribe(eventType, func(e events.Event) {
+ if e.ActorID == "" {
+ return
+ }
+ data, err := json.Marshal(map[string]any{"type": e.Type, "payload": projectOutbound(e.Type, e.Payload), "actor_id": e.ActorID, "actor_type": e.ActorType})
+ if err != nil {
+ return
+ }
+ realtime.M.RecordEvent(e.Type)
+ b.SendToUser(e.ActorID, data, e.WorkspaceID)
+ })
+ }
+
// A Chat session is creator-private. Its initial title may be derived from
// the creator's first message, so the list-invalidation event must not be
// broadcast to every workspace member. ActorID is the creator on every
diff --git a/server/cmd/server/listeners_scope_test.go b/server/cmd/server/listeners_scope_test.go
index 72357edb64..8978718336 100644
--- a/server/cmd/server/listeners_scope_test.go
+++ b/server/cmd/server/listeners_scope_test.go
@@ -151,3 +151,103 @@ func TestRegisterListeners_TaskChatGoToWorkspace(t *testing.T) {
})
}
}
+
+// An invitation conclusion must reach the invitee BOTH ways: the workspace
+// broadcast keeps admin pending lists fresh, and a targeted send reaches the
+// invitee's own clients — which are usually bound to a different workspace
+// room (or no room at all, #8432), so the broadcast alone never arrives.
+// The targeted frame passes excludeWorkspace so clients already in the room
+// don't get the event twice.
+func TestRegisterListeners_InvitationConcludedReachesActorAndWorkspace(t *testing.T) {
+ cases := []struct {
+ name string
+ eventType string
+ }{
+ {"invitation:accepted", protocol.EventInvitationAccepted},
+ {"invitation:declined", protocol.EventInvitationDeclined},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ bus := events.New()
+ fb := &fakeBroadcaster{}
+ registerListeners(bus, fb)
+
+ bus.Publish(events.Event{
+ Type: tc.eventType, WorkspaceID: "ws-1",
+ ActorType: "member", ActorID: "invitee-1",
+ Payload: map[string]any{"invitation_id": "inv-1"},
+ })
+
+ if len(fb.workspaceCalls) != 1 || fb.workspaceCalls[0].workspaceID != "ws-1" {
+ t.Fatalf("workspace fanout = %+v, want exactly ws-1 (admin lists depend on it)", fb.workspaceCalls)
+ }
+ if len(fb.userCalls) != 1 {
+ t.Fatalf("targeted sends = %+v, want exactly one", fb.userCalls)
+ }
+ send := fb.userCalls[0]
+ if send.userID != "invitee-1" {
+ t.Fatalf("targeted recipient = %q, want the acting invitee invitee-1", send.userID)
+ }
+ if len(send.exclude) != 1 || send.exclude[0] != "ws-1" {
+ t.Fatalf("excludeWorkspace = %v, want [ws-1] to dedupe the room broadcast", send.exclude)
+ }
+ var frame struct {
+ Type string `json:"type"`
+ ActorID string `json:"actor_id"`
+ Payload struct {
+ InvitationID string `json:"invitation_id"`
+ } `json:"payload"`
+ }
+ if err := json.Unmarshal(send.msg, &frame); err != nil {
+ t.Fatalf("decode targeted frame: %v", err)
+ }
+ if frame.Type != tc.eventType || frame.ActorID != "invitee-1" || frame.Payload.InvitationID != "inv-1" {
+ t.Fatalf("targeted frame = type %q actor %q payload %+v", frame.Type, frame.ActorID, frame.Payload)
+ }
+ })
+ }
+}
+
+// Without an acting invitee there is nobody to target; the workspace
+// broadcast must still go out.
+func TestRegisterListeners_InvitationConcludedWithoutActorSkipsTargetedSend(t *testing.T) {
+ bus := events.New()
+ fb := &fakeBroadcaster{}
+ registerListeners(bus, fb)
+
+ bus.Publish(events.Event{
+ Type: protocol.EventInvitationDeclined, WorkspaceID: "ws-1",
+ ActorType: "member",
+ Payload: map[string]any{"invitation_id": "inv-1"},
+ })
+
+ if len(fb.workspaceCalls) != 1 {
+ t.Fatalf("workspace fanout = %+v, want exactly one", fb.workspaceCalls)
+ }
+ if len(fb.userCalls) != 0 {
+ t.Fatalf("targeted sends = %+v, want none without an actor", fb.userCalls)
+ }
+}
+
+// invitation:revoked keeps its invitee_user_id routing: its actor is the
+// revoking admin, so targeting the actor would refresh the wrong user's list.
+func TestRegisterListeners_InvitationRevokedStillTargetsInviteeNotActor(t *testing.T) {
+ bus := events.New()
+ fb := &fakeBroadcaster{}
+ registerListeners(bus, fb)
+
+ bus.Publish(events.Event{
+ Type: protocol.EventInvitationRevoked, WorkspaceID: "ws-1",
+ ActorType: "member", ActorID: "admin-1",
+ Payload: map[string]any{"invitee_user_id": inviteePtr("invitee-2")},
+ })
+
+ if len(fb.workspaceCalls) != 0 {
+ t.Fatalf("revoked reached workspace fanout: %+v (still a personal event)", fb.workspaceCalls)
+ }
+ if len(fb.userCalls) != 1 || fb.userCalls[0].userID != "invitee-2" {
+ t.Fatalf("revoked fanout = %+v, want invitee-2 only", fb.userCalls)
+ }
+}
+
+func inviteePtr(s string) *string { return &s }
diff --git a/server/internal/handler/invitation.go b/server/internal/handler/invitation.go
index 64d9d876c9..836c46dc6c 100644
--- a/server/internal/handler/invitation.go
+++ b/server/internal/handler/invitation.go
@@ -2,6 +2,7 @@ package handler
import (
"encoding/json"
+ "errors"
"log/slog"
"net/http"
"strings"
@@ -9,6 +10,7 @@ import (
"github.com/go-chi/chi/v5"
"github.com/google/uuid"
+ "github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
"github.com/multica-ai/multica/server/internal/analytics"
"github.com/multica-ai/multica/server/internal/logger"
@@ -479,6 +481,34 @@ func (h *Handler) AcceptInvitation(w http.ResponseWriter, r *http.Request) {
}
if inv.Status != "pending" {
+ // Installed clients can hold a stale pending-invitation row for an
+ // invitation that was already concluded from another surface (the
+ // web invite page, another device). A 400 here leaves that row
+ // stuck: the sidebar swallows the error and keeps showing the row
+ // until restart. Re-accepting is idempotent while the membership
+ // from the first accept still exists — return it so the client's
+ // refetch drops the row. A membership that no longer exists (the
+ // user left the workspace afterwards) still fails: leaving was
+ // explicit and must not be undone by a stale client retry.
+ if inv.Status == "accepted" {
+ member, memberErr := h.Queries.GetMemberByUserAndWorkspace(r.Context(), db.GetMemberByUserAndWorkspaceParams{
+ UserID: user.ID,
+ WorkspaceID: inv.WorkspaceID,
+ })
+ switch {
+ case memberErr == nil:
+ writeJSON(w, http.StatusOK, h.memberWithUserResponse(member, user))
+ return
+ case errors.Is(memberErr, pgx.ErrNoRows):
+ // The membership from the first accept is gone; fall through
+ // to the 400 below.
+ default:
+ // A transient read failure must surface as 500, not collapse
+ // into the business 400 that clients swallow silently.
+ writeError(w, http.StatusInternalServerError, "failed to load membership")
+ return
+ }
+ }
writeError(w, http.StatusBadRequest, "invitation is not pending")
return
}
@@ -636,7 +666,12 @@ func (h *Handler) DeclineInvitation(w http.ResponseWriter, r *http.Request) {
}
if inv.Status != "pending" {
- writeError(w, http.StatusBadRequest, "invitation is not pending")
+ // Declining a concluded invitation is a no-op: it was already
+ // accepted, declined, revoked or expired from another surface, and
+ // this invitation is over either way. A stale client holding the
+ // pending row only needs its refetch to drop it, so acknowledge
+ // with 204 instead of a 400 it would swallow silently.
+ w.WriteHeader(http.StatusNoContent)
return
}
diff --git a/server/internal/handler/invitation_test.go b/server/internal/handler/invitation_test.go
index c8221dee83..b3546a7b49 100644
--- a/server/internal/handler/invitation_test.go
+++ b/server/internal/handler/invitation_test.go
@@ -19,6 +19,7 @@ import (
obsmetrics "github.com/multica-ai/multica/server/internal/metrics"
"github.com/multica-ai/multica/server/internal/middleware"
"github.com/multica-ai/multica/server/internal/seatcapacity"
+ "github.com/multica-ai/multica/server/internal/testutil"
)
const invitationTestEmail = "[email protected]"
@@ -768,3 +769,92 @@ func TestCreateInvitation_RouteRequiresAdminRole(t *testing.T) {
t.Errorf("owner status = %d, want 201: %s", rec.Code, rec.Body.String())
}
}
+
+// An installed client can still show a pending-invitation row the user
+// already accepted from another surface (web invite page, another device).
+// Re-accept must be idempotent for the membership the first accept created,
+// so the client's refetch drops the stale row instead of sticking forever.
+func TestAcceptInvitation_AlreadyAcceptedIsIdempotentForExistingMember(t *testing.T) {
+ email := "idempotent-accept-" + uuid.NewString() + "@multica.ai"
+ userID := dbfx.User(t, "Idempotent Accept Invitee", email)
+ invitationID := dbfx.Insert(t, "workspace_invitation", testutil.Cols{
+ "workspace_id": testWorkspaceID,
+ "inviter_id": testUserID,
+ "invitee_email": email,
+ "invitee_user_id": userID,
+ "role": "member",
+ "status": "accepted",
+ "expires_at": testutil.Raw("now() + interval '1 day'"),
+ })
+ memberID := dbfx.Member(t, testWorkspaceID, userID, "member")
+
+ req := newRequest("POST", "/api/invitations/"+invitationID+"/accept", nil)
+ req.Header.Set("X-User-ID", userID)
+ req = withURLParam(req, "id", invitationID)
+ var member MemberWithUserResponse
+ testutil.Call(t, testHandler.AcceptInvitation, req).Want(http.StatusOK).JSON(&member)
+ if member.ID != memberID {
+ t.Fatalf("member id = %q, want %q", member.ID, memberID)
+ }
+ if members := dbfx.Count(t, `SELECT count(*) FROM member WHERE workspace_id = $1 AND user_id = $2`, parseUUID(testWorkspaceID), parseUUID(userID)); members != 1 {
+ t.Fatalf("member count = %d, want 1", members)
+ }
+}
+
+// A concluded invitation whose membership is gone (the user left the
+// workspace afterwards) must not be re-acceptable: leaving was explicit.
+func TestAcceptInvitation_AlreadyAcceptedWithoutMembershipStillFails(t *testing.T) {
+ email := "stale-accept-no-member-" + uuid.NewString() + "@multica.ai"
+ userID := dbfx.User(t, "Stale Accept Invitee", email)
+ invitationID := dbfx.Insert(t, "workspace_invitation", testutil.Cols{
+ "workspace_id": testWorkspaceID,
+ "inviter_id": testUserID,
+ "invitee_email": email,
+ "invitee_user_id": userID,
+ "role": "member",
+ "status": "accepted",
+ "expires_at": testutil.Raw("now() + interval '1 day'"),
+ })
+
+ req := newRequest("POST", "/api/invitations/"+invitationID+"/accept", nil)
+ req.Header.Set("X-User-ID", userID)
+ req = withURLParam(req, "id", invitationID)
+ testutil.Call(t, testHandler.AcceptInvitation, req).Want(http.StatusBadRequest)
+ if members := dbfx.Count(t, `SELECT count(*) FROM member WHERE workspace_id = $1 AND user_id = $2`, parseUUID(testWorkspaceID), parseUUID(userID)); members != 0 {
+ t.Fatalf("member count = %d, want 0", members)
+ }
+}
+
+// Declining a concluded invitation is a no-op: the row only lingers in
+// clients that concluded the same invitation elsewhere, and a 204 lets their
+// refetch drop it.
+func TestDeclineInvitation_AlreadyAcceptedIsNoOp(t *testing.T) {
+ email := "idempotent-decline-" + uuid.NewString() + "@multica.ai"
+ userID := dbfx.User(t, "Idempotent Decline Invitee", email)
+ invitationID := dbfx.Insert(t, "workspace_invitation", testutil.Cols{
+ "workspace_id": testWorkspaceID,
+ "inviter_id": testUserID,
+ "invitee_email": email,
+ "invitee_user_id": userID,
+ "role": "member",
+ "status": "accepted",
+ "expires_at": testutil.Raw("now() + interval '1 day'"),
+ })
+ dbfx.Member(t, testWorkspaceID, userID, "member")
+
+ req := newRequest("POST", "/api/invitations/"+invitationID+"/decline", nil)
+ req.Header.Set("X-User-ID", userID)
+ req = withURLParam(req, "id", invitationID)
+ testutil.Call(t, testHandler.DeclineInvitation, req).Want(http.StatusNoContent)
+
+ var status string
+ if err := testPool.QueryRow(context.Background(), `SELECT status FROM workspace_invitation WHERE id = $1`, parseUUID(invitationID)).Scan(&status); err != nil {
+ t.Fatal(err)
+ }
+ if status != "accepted" {
+ t.Fatalf("invitation status = %q, want accepted", status)
+ }
+ if members := dbfx.Count(t, `SELECT count(*) FROM member WHERE workspace_id = $1 AND user_id = $2`, parseUUID(testWorkspaceID), parseUUID(userID)); members != 1 {
+ t.Fatalf("member count = %d, want 1", members)
+ }
+}
diff --git a/server/internal/handler/share_link.go b/server/internal/handler/share_link.go
index f26e13c2a4..e04f1eeaf9 100644
--- a/server/internal/handler/share_link.go
+++ b/server/internal/handler/share_link.go
@@ -338,6 +338,42 @@ func (h *Handler) JoinByShareLink(w http.ResponseWriter, r *http.Request) {
return
}
+ // Settle a matching pending email invitation in the same transaction
+ // (#8432). A user invited by email who joins through the share link
+ // instead would leave that row pending forever: it keeps its seat
+ // reservation, keeps showing in their pending list, and a later Accept
+ // on it dies on the CreateMember 409. The link's role wins — the user
+ // chose this entry point, so the member is created with link.Role below
+ // and the invitation row is only settled, its role left untouched.
+ // idx_invitation_unique_pending guarantees at most one pending row per
+ // (workspace, email).
+ var settledInvitationID pgtype.UUID
+ pendingInv, pendingErr := qtx.GetPendingInvitationByEmail(r.Context(), db.GetPendingInvitationByEmailParams{
+ WorkspaceID: link.WorkspaceID,
+ InviteeEmail: strings.ToLower(user.Email),
+ })
+ switch {
+ case pendingErr == nil:
+ // AcceptInvitation re-checks status='pending' under the row lock, so
+ // a decline concluded concurrently leaves nothing to settle and the
+ // join still proceeds.
+ settled, settleErr := qtx.AcceptInvitation(r.Context(), pendingInv.ID)
+ switch {
+ case settleErr == nil:
+ settledInvitationID = settled.ID
+ case errors.Is(settleErr, pgx.ErrNoRows):
+ // Concluded elsewhere in between; its own path released the seat.
+ default:
+ writeError(w, http.StatusInternalServerError, "failed to join workspace")
+ return
+ }
+ case errors.Is(pendingErr, pgx.ErrNoRows):
+ // No pending invitation for this email — the common case.
+ default:
+ writeError(w, http.StatusInternalServerError, "failed to join workspace")
+ return
+ }
+
member, err := qtx.CreateMember(r.Context(), db.CreateMemberParams{
WorkspaceID: link.WorkspaceID,
UserID: user.ID,
@@ -365,6 +401,16 @@ func (h *Handler) JoinByShareLink(w http.ResponseWriter, r *http.Request) {
return
}
}
+ if settledInvitationID.Valid && h.seatCapacityEnabled() {
+ // The settled invitation was holding a seat reservation (managed
+ // mode); the share join's own confirmed claim now covers the seat,
+ // so release the invitation's reservation instead of double-charging
+ // the workspace for one joining user.
+ if err := enqueueCapacityRelease(r.Context(), qtx, uuid.UUID(link.WorkspaceID.Bytes), uuid.UUID(settledInvitationID.Bytes)); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to join workspace")
+ return
+ }
+ }
if err := tx.Commit(r.Context()); err != nil {
writeError(w, http.StatusInternalServerError, "failed to join workspace")
@@ -373,6 +419,12 @@ func (h *Handler) JoinByShareLink(w http.ResponseWriter, r *http.Request) {
if capacityToken != uuid.Nil {
h.confirmCapacityIntent(r.Context(), uuid.UUID(link.WorkspaceID.Bytes), capacityToken, uuid.UUID(member.ID.Bytes))
}
+ if settledInvitationID.Valid && h.seatCapacityEnabled() {
+ // Best-effort immediate release of the settled invitation's
+ // reservation; if the capacity service is unavailable the enqueued
+ // release above is retried by the outbox worker.
+ h.compensateCapacityIntent(r.Context(), uuid.UUID(settledInvitationID.Bytes))
+ }
wsID := uuidToString(link.WorkspaceID)
slog.Info("user joined via share link", "user_id", userID, "workspace_id", wsID)
@@ -387,6 +439,14 @@ func (h *Handler) JoinByShareLink(w http.ResponseWriter, r *http.Request) {
h.publish(protocol.EventMemberAdded, wsID, "member", userID, map[string]any{
"member": memberResp,
})
+ if settledInvitationID.Valid {
+ // Same signal the accept path sends: workspace admins refresh their
+ // pending-invitation list, and the joiner's own clients converge.
+ h.publish(protocol.EventInvitationAccepted, wsID, "member", userID, map[string]any{
+ "invitation_id": uuidToString(settledInvitationID),
+ "member": memberResp,
+ })
+ }
h.notifyDaemonWorkspacesChanged(userID)
writeJSON(w, http.StatusOK, map[string]any{
diff --git a/server/internal/handler/share_link_test.go b/server/internal/handler/share_link_test.go
index 50661f5a17..ba09bee1cc 100644
--- a/server/internal/handler/share_link_test.go
+++ b/server/internal/handler/share_link_test.go
@@ -14,17 +14,23 @@ import (
"github.com/go-chi/chi/v5"
"github.com/google/uuid"
"github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/events"
"github.com/multica-ai/multica/server/internal/middleware"
"github.com/multica-ai/multica/server/internal/seatcapacity"
+ "github.com/multica-ai/multica/server/internal/testutil"
db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/protocol"
)
var testSeq atomic.Int64
type shareJoinCapacityStub struct {
- mu sync.Mutex
- claimTokens []uuid.UUID
- claimGate *sync.WaitGroup
+ mu sync.Mutex
+ claimTokens []uuid.UUID
+ releaseTokens []uuid.UUID
+ claimGate *sync.WaitGroup
+ claimDecision *seatcapacity.Decision
+ releaseDecision *seatcapacity.Decision
}
func (*shareJoinCapacityStub) RecoveryAvailable() bool { return true }
@@ -40,7 +46,11 @@ func (s *shareJoinCapacityStub) ClaimShareJoin(_ context.Context, _ uuid.UUID, t
s.claimGate.Done()
s.claimGate.Wait()
}
- return seatcapacity.Decision{Managed: true, Allowed: true}, nil
+ decision := seatcapacity.Decision{Managed: true, Allowed: true}
+ if s.claimDecision != nil {
+ decision = *s.claimDecision
+ }
+ return decision, nil
}
func (s *shareJoinCapacityStub) Consume(context.Context, uuid.UUID, uuid.UUID) (seatcapacity.Decision, error) {
return seatcapacity.Decision{Managed: true, Allowed: true}, nil
@@ -48,8 +58,15 @@ func (s *shareJoinCapacityStub) Consume(context.Context, uuid.UUID, uuid.UUID) (
func (s *shareJoinCapacityStub) Confirm(context.Context, uuid.UUID, uuid.UUID, uuid.UUID) (seatcapacity.Decision, error) {
return seatcapacity.Decision{Managed: true, Allowed: true}, nil
}
-func (s *shareJoinCapacityStub) Release(context.Context, uuid.UUID, uuid.UUID) (seatcapacity.Decision, error) {
- return seatcapacity.Decision{Managed: true, Allowed: true}, nil
+func (s *shareJoinCapacityStub) Release(_ context.Context, _ uuid.UUID, token uuid.UUID) (seatcapacity.Decision, error) {
+ s.mu.Lock()
+ s.releaseTokens = append(s.releaseTokens, token)
+ decision := seatcapacity.Decision{Managed: true, Allowed: true}
+ if s.releaseDecision != nil {
+ decision = *s.releaseDecision
+ }
+ s.mu.Unlock()
+ return decision, nil
}
func (s *shareJoinCapacityStub) ReleaseMember(context.Context, uuid.UUID, uuid.UUID) (seatcapacity.Decision, error) {
return seatcapacity.Decision{Managed: true, Allowed: true}, nil
@@ -64,6 +81,12 @@ func (s *shareJoinCapacityStub) tokens() []uuid.UUID {
return append([]uuid.UUID(nil), s.claimTokens...)
}
+func (s *shareJoinCapacityStub) releases() []uuid.UUID {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ return append([]uuid.UUID(nil), s.releaseTokens...)
+}
+
func pgInt32(v int32) *int32 { return &v }
func clearShareLinksForTestWorkspace(t *testing.T) {
@@ -523,6 +546,235 @@ func TestJoinShareLink_ConcurrentSameUserUsesOneCapacityOperation(t *testing.T)
}
}
+// pendingInvitationForShareJoiner inserts a pending email invitation for a
+// share-link join test user and returns its id. role is the invitation's own
+// role, which the join must NOT propagate to the member.
+func pendingInvitationForShareJoiner(t *testing.T, userID, email, role string) string {
+ t.Helper()
+ return dbfx.Insert(t, "workspace_invitation", testutil.Cols{
+ "workspace_id": testWorkspaceID,
+ "inviter_id": testUserID,
+ "invitee_email": email,
+ "invitee_user_id": userID,
+ "role": role,
+ "status": "pending",
+ "expires_at": testutil.Raw("now() + interval '1 day'"),
+ })
+}
+
+func shareJoinerEmail(t *testing.T, userID string) string {
+ t.Helper()
+ var email string
+ if err := testPool.QueryRow(context.Background(),
+ `SELECT email FROM "user" WHERE id = $1`, parseUUID(userID),
+ ).Scan(&email); err != nil {
+ t.Fatalf("load share-join test user email: %v", err)
+ }
+ return email
+}
+
+func invitationStatusOf(t *testing.T, invitationID string) (string, string) {
+ t.Helper()
+ var status, role string
+ if err := testPool.QueryRow(context.Background(),
+ `SELECT status, role FROM workspace_invitation WHERE id = $1`, parseUUID(invitationID),
+ ).Scan(&status, &role); err != nil {
+ t.Fatalf("reload invitation: %v", err)
+ }
+ return status, role
+}
+
+// A user invited by email who joins through the share link instead must have
+// that pending invitation settled in the same transaction: otherwise the row
+// keeps holding its seat reservation, keeps showing in their pending list,
+// and a later Accept on it dies on the CreateMember 409. The link's role
+// wins — the user chose this entry point — and the invitation row keeps its
+// own role, only its status is settled.
+func TestJoinShareLink_SettlesPendingInvitation(t *testing.T) {
+ clearShareLinksForTestWorkspace(t)
+ link := createTestShareLink(t, testWorkspaceID, "member", 5, 0)
+ userID := createTestUserAndMember(t, "")
+ invitationID := pendingInvitationForShareJoiner(t, userID, shareJoinerEmail(t, userID), "admin")
+
+ req := newRequest("POST", "/api/share-links/join", JoinByShareLinkRequest{Code: link.Code})
+ req.Header.Set("X-User-ID", userID)
+ w := httptest.NewRecorder()
+ testHandler.JoinByShareLink(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("join: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+
+ status, role := invitationStatusOf(t, invitationID)
+ if status != "accepted" {
+ t.Fatalf("invitation status = %q, want accepted", status)
+ }
+ if role != "admin" {
+ t.Fatalf("invitation role = %q, want untouched admin", role)
+ }
+ var memberRole string
+ if err := testPool.QueryRow(context.Background(),
+ `SELECT role FROM member WHERE workspace_id = $1 AND user_id = $2`,
+ parseUUID(testWorkspaceID), parseUUID(userID),
+ ).Scan(&memberRole); err != nil {
+ t.Fatalf("load member: %v", err)
+ }
+ if memberRole != "member" {
+ t.Fatalf("member role = %q, want the share link's member role", memberRole)
+ }
+}
+
+// The settled invitation signals its conclusion on the same channel the
+// accept path uses, so workspace admins refresh their pending-invitation
+// list instead of holding a row that is already over.
+func TestJoinShareLink_SettledInvitationPublishesAcceptedEvent(t *testing.T) {
+ clearShareLinksForTestWorkspace(t)
+ link := createTestShareLink(t, testWorkspaceID, "member", 5, 0)
+ userID := createTestUserAndMember(t, "")
+ invitationID := pendingInvitationForShareJoiner(t, userID, shareJoinerEmail(t, userID), "member")
+
+ gotEvent := make(chan map[string]any, 1)
+ testHandler.Bus.Subscribe(protocol.EventInvitationAccepted, func(e events.Event) {
+ if payload, ok := e.Payload.(map[string]any); ok {
+ select {
+ case gotEvent <- payload:
+ default:
+ }
+ }
+ })
+
+ req := newRequest("POST", "/api/share-links/join", JoinByShareLinkRequest{Code: link.Code})
+ req.Header.Set("X-User-ID", userID)
+ w := httptest.NewRecorder()
+ testHandler.JoinByShareLink(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("join: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+
+ var payload map[string]any
+ select {
+ case payload = <-gotEvent:
+ default:
+ t.Fatalf("no invitation:accepted event published for the settled invitation")
+ }
+ if payload["invitation_id"] != invitationID {
+ t.Fatalf("event invitation_id = %v, want %s", payload["invitation_id"], invitationID)
+ }
+}
+
+// In managed capacity mode the settled invitation was holding a seat
+// reservation keyed by the invitation id; the join's own confirmed claim now
+// covers the seat, so the reservation must be released — otherwise the same
+// user holds a member seat and an invitation reservation at once.
+func TestJoinShareLink_SettledInvitationReleasesSeatReservation(t *testing.T) {
+ clearShareLinksForTestWorkspace(t)
+ link := createTestShareLink(t, testWorkspaceID, "member", 5, 0)
+ userID := createTestUserAndMember(t, "")
+ email := shareJoinerEmail(t, userID)
+ invitationUUID := parseUUID(pendingInvitationForShareJoiner(t, userID, email, "member"))
+
+ stub := &shareJoinCapacityStub{}
+ useSeatCapacity(t, stub)
+ // Pre-create the reservation intent the way CreateInvitation does.
+ queries := db.New(testPool)
+ if _, err := queries.UpsertSeatCapacityIntent(context.Background(), db.UpsertSeatCapacityIntentParams{
+ WorkspaceID: link.WorkspaceID,
+ OperationToken: invitationUUID,
+ Action: seatcapacity.ActionReserveInvitation,
+ NextAttemptAt: pgtype.Timestamptz{Time: time.Now(), Valid: true},
+ SubjectID: invitationUUID,
+ InvitationID: invitationUUID,
+ ExpiresAt: pgtype.Timestamptz{Time: time.Now().Add(24 * time.Hour), Valid: true},
+ }); err != nil {
+ t.Fatalf("seed invitation reservation intent: %v", err)
+ }
+
+ req := newRequest("POST", "/api/share-links/join", JoinByShareLinkRequest{Code: link.Code})
+ req.Header.Set("X-User-ID", userID)
+ w := httptest.NewRecorder()
+ testHandler.JoinByShareLink(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("join: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+
+ released := stub.releases()
+ if len(released) != 1 || released[0] != uuid.UUID(invitationUUID.Bytes) {
+ t.Fatalf("release calls = %v, want the invitation reservation %s", released, invitationUUID)
+ }
+ var intents int
+ if err := testPool.QueryRow(context.Background(),
+ `SELECT count(*) FROM seat_capacity_outbox WHERE operation_token = $1`, invitationUUID,
+ ).Scan(&intents); err != nil {
+ t.Fatal(err)
+ }
+ if intents != 0 {
+ t.Fatalf("seat_capacity_outbox rows for the invitation = %d, want 0 after release", intents)
+ }
+ if status, _ := invitationStatusOf(t, invitationUUID.String()); status != "accepted" {
+ t.Fatalf("invitation status = %q, want accepted", status)
+ }
+}
+
+// Unmanaged capacity keeps no durable reservation for an invitation, so the
+// settle must still succeed end to end and leave nothing stranded in the
+// outbox.
+func TestJoinShareLink_SettlesPendingInvitationUnmanagedCapacity(t *testing.T) {
+ clearShareLinksForTestWorkspace(t)
+ link := createTestShareLink(t, testWorkspaceID, "member", 5, 0)
+ userID := createTestUserAndMember(t, "")
+ invitationUUID := parseUUID(pendingInvitationForShareJoiner(t, userID, shareJoinerEmail(t, userID), "member"))
+
+ unmanaged := seatcapacity.Decision{Managed: false, Allowed: false}
+ stub := &shareJoinCapacityStub{claimDecision: &unmanaged, releaseDecision: &unmanaged}
+ useSeatCapacity(t, stub)
+
+ req := newRequest("POST", "/api/share-links/join", JoinByShareLinkRequest{Code: link.Code})
+ req.Header.Set("X-User-ID", userID)
+ w := httptest.NewRecorder()
+ testHandler.JoinByShareLink(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("join: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+
+ if status, _ := invitationStatusOf(t, invitationUUID.String()); status != "accepted" {
+ t.Fatalf("invitation status = %q, want accepted", status)
+ }
+ var intents int
+ if err := testPool.QueryRow(context.Background(),
+ `SELECT count(*) FROM seat_capacity_outbox WHERE operation_token = $1`, invitationUUID,
+ ).Scan(&intents); err != nil {
+ t.Fatal(err)
+ }
+ if intents != 0 {
+ t.Fatalf("seat_capacity_outbox rows for the invitation = %d, want 0", intents)
+ }
+}
+
+// A share-link join for a user without a pending invitation proceeds as
+// before — the settle lookup misses and changes nothing.
+func TestJoinShareLink_NoPendingInvitationJoinsNormally(t *testing.T) {
+ clearShareLinksForTestWorkspace(t)
+ link := createTestShareLink(t, testWorkspaceID, "admin", 5, 0)
+ userID := createTestUserAndMember(t, "")
+
+ req := newRequest("POST", "/api/share-links/join", JoinByShareLinkRequest{Code: link.Code})
+ req.Header.Set("X-User-ID", userID)
+ w := httptest.NewRecorder()
+ testHandler.JoinByShareLink(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("join: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+ var members int
+ if err := testPool.QueryRow(context.Background(),
+ `SELECT count(*) FROM member WHERE workspace_id = $1 AND user_id = $2`,
+ parseUUID(testWorkspaceID), parseUUID(userID),
+ ).Scan(&members); err != nil {
+ t.Fatal(err)
+ }
+ if members != 1 {
+ t.Fatalf("member rows=%d, want 1", members)
+ }
+}
+
func TestGetShareLinkInfo_PublicResponseSlim(t *testing.T) {
clearShareLinksForTestWorkspace(t)
link := createTestShareLink(t, testWorkspaceID, "admin", 0, 0)