Skip to content

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

Go

fix(apps): send team account requests to the admin they concern (MUL-10072) (#11418)

Bohan Jiangdff965b06cbc
diff --git a/packages/views/agents/components/agent-apps-section.test.tsx b/packages/views/agents/components/agent-apps-section.test.tsx
index 1c7f63f152..87774ce5af 100644
--- a/packages/views/agents/components/agent-apps-section.test.tsx
+++ b/packages/views/agents/components/agent-apps-section.test.tsx
@@ -119,7 +119,7 @@ describe("AgentAppsSection", () => {
await screen.findByText("PostHog");
await user.click(within(row("team", "posthog")).getByRole("button", { name: "Ask an admin" }));
expect(api.requestTeamApp).toHaveBeenCalledWith("posthog", "a1");
- await waitFor(() => expect(row("team", "posthog")).toHaveTextContent("Requested · admins notified"));
+ await waitFor(() => expect(row("team", "posthog")).toHaveTextContent("Requested · admin notified"));
expect(within(row("team", "posthog")).getByRole("button", { name: "Withdraw" })).toBeVisible();
expect(toast.success).toHaveBeenCalled();
});
diff --git a/packages/views/apps/components/apps-page.test.tsx b/packages/views/apps/components/apps-page.test.tsx
index 4c9790d2fb..4512e09ed9 100644
--- a/packages/views/apps/components/apps-page.test.tsx
+++ b/packages/views/apps/components/apps-page.test.tsx
@@ -295,7 +295,7 @@ describe("AppsPage › Accounts", () => {
expect(within(team).getAllByText(/^(Notion|Linear|Slack)$/).map((el) => el.textContent)).toEqual(["Notion", "Linear", "Slack"]);
expect(screen.getByRole("tab", { name: /Accounts/ })).toHaveTextContent("5");
expect(within(row("team", "notion")).getAllByText("Needs reconnecting").length).toBeGreaterThan(0);
- expect(within(row("team", "linear")).getAllByText(/Requested · admins notified/).length).toBeGreaterThan(0);
+ expect(within(row("team", "linear")).getAllByText(/Requested · admin notified/).length).toBeGreaterThan(0);
expect(row("team", "linear")).toHaveTextContent("Name a2 needs it");
// A member asks an admin; nothing connects an account apart from an app.
expect(within(row("team", "notion")).getByRole("button", { name: "Ask an admin" })).toBeInTheDocument();
diff --git a/packages/views/locales/en/settings.json b/packages/views/locales/en/settings.json
index 3678789d7e..818b511f8a 100644
--- a/packages/views/locales/en/settings.json
+++ b/packages/views/locales/en/settings.json
@@ -1972,7 +1972,7 @@
"title_member_ask": "{{name}} asked for a team {{app}} account",
"waiting_for_admin": "Waiting for an admin",
"team_note": "Every agent that acts as the team account can use it.",
- "admins_notified": "Workspace admins were notified in Inbox.",
+ "admins_notified": "A workspace admin was notified in Inbox.",
"connect_team": "Connect for the team"
},
"tools": {
@@ -2021,7 +2021,7 @@
"personal": "Your account"
},
"account_row": {
- "admins_notified": "admins notified",
+ "admins_notified": "admin notified",
"withdraw": "Withdraw",
"decline": "Decline",
"toast_declined": "Requests declined. Waiting agents continue without it.",
diff --git a/packages/views/locales/es/settings.json b/packages/views/locales/es/settings.json
index bc7e7cc90f..9c29db1ced 100644
--- a/packages/views/locales/es/settings.json
+++ b/packages/views/locales/es/settings.json
@@ -1941,7 +1941,7 @@
"personal": "Tu cuenta"
},
"account_row": {
- "admins_notified": "administradores avisados",
+ "admins_notified": "administrador avisado",
"withdraw": "Retirar",
"decline": "Rechazar",
"toast_declined": "Solicitudes rechazadas. Los agentes en espera siguen sin ella.",
@@ -2002,7 +2002,7 @@
"title_member_ask": "{{name}} pidió una cuenta del equipo de {{app}}",
"waiting_for_admin": "Esperando a un administrador",
"team_note": "Todos los agentes que actúan con la cuenta del equipo podrán usarla.",
- "admins_notified": "Se avisó a los administradores en la bandeja de entrada.",
+ "admins_notified": "Se avisó a un administrador en la bandeja de entrada.",
"connect_team": "Conectar para el equipo"
},
"tools": {
diff --git a/packages/views/locales/fr/settings.json b/packages/views/locales/fr/settings.json
index 00789890be..b752c8ae90 100644
--- a/packages/views/locales/fr/settings.json
+++ b/packages/views/locales/fr/settings.json
@@ -1941,7 +1941,7 @@
"personal": "Votre compte"
},
"account_row": {
- "admins_notified": "admins prévenus",
+ "admins_notified": "admin prévenu",
"withdraw": "Retirer",
"decline": "Refuser",
"toast_declined": "Demandes refusées. Les agents en attente continuent sans.",
@@ -2002,7 +2002,7 @@
"title_member_ask": "{{name}} a demandé un compte d'équipe {{app}}",
"waiting_for_admin": "En attente d'un admin",
"team_note": "Tous les agents qui agissent avec le compte d'équipe pourront l'utiliser.",
- "admins_notified": "Les admins de l'espace de travail ont été prévenus dans la boîte de réception.",
+ "admins_notified": "Un admin de l'espace de travail a été prévenu dans la boîte de réception.",
"connect_team": "Connecter pour l'équipe"
},
"tools": {
diff --git a/packages/views/locales/ru/settings.json b/packages/views/locales/ru/settings.json
index 973e509b14..fa4c294137 100644
--- a/packages/views/locales/ru/settings.json
+++ b/packages/views/locales/ru/settings.json
@@ -1975,7 +1975,7 @@
"personal": "Ваш аккаунт"
},
"account_row": {
- "admins_notified": "администраторы уведомлены",
+ "admins_notified": "администратор уведомлён",
"withdraw": "Отозвать",
"decline": "Отклонить",
"toast_declined": "Запросы отклонены. Ожидающие агенты продолжат без аккаунта.",
@@ -2040,7 +2040,7 @@
"title_member_ask": "{{name}} запросил аккаунт команды {{app}}",
"waiting_for_admin": "Ждёт администратора",
"team_note": "Им смогут пользоваться все агенты, которые действуют от аккаунта команды.",
- "admins_notified": "Администраторы рабочего пространства получили уведомление во «Входящих».",
+ "admins_notified": "Администратор рабочего пространства получил уведомление во «Входящих».",
"connect_team": "Подключить для команды"
},
"tools": {
diff --git a/server/internal/connectedapps/requests.go b/server/internal/connectedapps/requests.go
index 1e7a2b5dda..f0c1161caa 100644
--- a/server/internal/connectedapps/requests.go
+++ b/server/internal/connectedapps/requests.go
@@ -137,16 +137,19 @@ func (s *Service) WithdrawTeamAsk(ctx context.Context, workspaceID, memberID pgt
return err
}
s.withdraw(ctx, req)
- s.archiveAdminNotifications(ctx, req)
+ s.archiveAdminNotifications(ctx, req, pgtype.UUID{}, "app_request_withdrawn")
return nil
}
-func (s *Service) archiveAdminNotifications(ctx context.Context, req db.AppActionRequest) {
+// archiveAdminNotifications archives the admins' open notifications for a
+// team account request nobody needs to answer any more, except keep's: the
+// admin who decided it keeps theirs where they acted on it.
+func (s *Service) archiveAdminNotifications(ctx context.Context, req db.AppActionRequest, keep pgtype.UUID, reason string) {
rows, err := s.q.ArchiveAppRequestInbox(ctx, db.ArchiveAppRequestInboxParams{
- WorkspaceID: req.WorkspaceID, RequestID: util.UUIDToString(req.ID),
+ WorkspaceID: req.WorkspaceID, RequestID: util.UUIDToString(req.ID), KeepRecipientID: keep,
})
if err != nil {
- slog.Warn("connectedapps: archive withdrawn request notifications failed", "request_id", util.UUIDToString(req.ID), "error", err)
+ slog.Warn("connectedapps: archive team request notifications failed", "request_id", util.UUIDToString(req.ID), "error", err)
return
}
if s.bus == nil {
@@ -162,7 +165,7 @@ func (s *Service) archiveAdminNotifications(ctx context.Context, req db.AppActio
Payload: map[string]any{
"recipient_id": util.UUIDToString(row.RecipientID),
"count": int64(1),
- "reason": "app_request_withdrawn",
+ "reason": reason,
},
})
}
@@ -214,6 +217,9 @@ func (s *Service) Approve(ctx context.Context, workspaceID, actorID, requestID p
return db.AppActionRequest{}, err
}
if decided.Kind == KindConnect {
+ if isTeamConnect(decided) {
+ s.archiveAdminNotifications(ctx, decided, actorID, "app_request_decided")
+ }
if !decided.TaskID.Valid {
s.publishChange(decided)
s.notify(ctx, decided, NotifActionResult)
@@ -335,6 +341,9 @@ func (s *Service) Reject(ctx context.Context, workspaceID, actorID, requestID pg
outcome: "rejected", requestID: decided.ID,
})
}
+ if isTeamConnect(decided) {
+ s.archiveAdminNotifications(ctx, decided, actorID, "app_request_decided")
+ }
s.publishChange(decided)
if !decided.TaskID.Valid {
if decided.DecidedBy != decided.ApproverUserID {
@@ -656,27 +665,62 @@ func (s *Service) notify(ctx context.Context, req db.AppActionRequest, notifType
s.deliver(ctx, req, notifType, req.ApproverUserID)
}
-// notifyAdmins tells the workspace's admins a team account is wanted. Only
-// the first open request for an app notifies: the rest wait in the same
-// place, and connecting the account answers them all.
+// notifyAdmins tells the admins a team account is wanted, but only the ones
+// it concerns: the person who started the run when they are an admin, else
+// the agent's owner when they are an admin, else every admin. An admin who
+// already holds an open notification for this app is not told again: they
+// answer every request for it at once.
func (s *Service) notifyAdmins(ctx context.Context, req db.AppActionRequest) {
- open, err := s.q.ListPendingTeamConnectRequests(ctx, db.ListPendingTeamConnectRequestsParams{
- WorkspaceID: req.WorkspaceID, ToolkitSlug: req.ToolkitSlug,
- })
- if err == nil && len(open) > 0 && open[0].ID != req.ID {
+ recipients := s.teamConnectRecipients(ctx, req)
+ if len(recipients) == 0 {
return
}
+ notified, err := s.q.ListTeamConnectNotifiedRecipients(ctx, db.ListTeamConnectNotifiedRecipientsParams{
+ WorkspaceID: req.WorkspaceID, ToolkitSlug: req.ToolkitSlug, RecipientIds: recipients,
+ })
+ if err != nil {
+ slog.Warn("connectedapps: list notified admins for team request failed", "toolkit", req.ToolkitSlug, "error", err)
+ }
+ told := make(map[pgtype.UUID]bool, len(notified))
+ for _, id := range notified {
+ told[id] = true
+ }
+ for _, admin := range recipients {
+ if !told[admin] {
+ s.deliver(ctx, req, NotifConnectRequested, admin)
+ }
+ }
+}
+
+// teamConnectRecipients picks who is asked to connect a team account. A
+// member asking outside any run is never asked themselves.
+func (s *Service) teamConnectRecipients(ctx context.Context, req db.AppActionRequest) []pgtype.UUID {
+ eligible := func(id pgtype.UUID) bool {
+ if !id.Valid || (id == req.ApproverUserID && !req.TaskID.Valid) {
+ return false
+ }
+ return s.IsAdmin(ctx, req.WorkspaceID, id)
+ }
+ if req.TaskID.Valid && eligible(req.ApproverUserID) {
+ return []pgtype.UUID{req.ApproverUserID}
+ }
+ if req.AgentID.Valid {
+ if agent, err := s.q.GetAgent(ctx, req.AgentID); err == nil && eligible(agent.OwnerID) {
+ return []pgtype.UUID{agent.OwnerID}
+ }
+ }
admins, err := s.q.ListWorkspaceManagerUserIDs(ctx, req.WorkspaceID)
if err != nil {
slog.Warn("connectedapps: list admins for team request failed", "toolkit", req.ToolkitSlug, "error", err)
- return
+ return nil
}
+ out := make([]pgtype.UUID, 0, len(admins))
for _, admin := range admins {
- if admin == req.ApproverUserID && !req.TaskID.Valid {
- continue
+ if admin != req.ApproverUserID || req.TaskID.Valid {
+ out = append(out, admin)
}
- s.deliver(ctx, req, NotifConnectRequested, admin)
}
+ return out
}
func (s *Service) deliver(ctx context.Context, req db.AppActionRequest, notifType string, recipient pgtype.UUID) {
diff --git a/server/internal/handler/connected_apps_requests_test.go b/server/internal/handler/connected_apps_requests_test.go
index a7dc94a780..b32397311b 100644
--- a/server/internal/handler/connected_apps_requests_test.go
+++ b/server/internal/handler/connected_apps_requests_test.go
@@ -205,6 +205,83 @@ func TestConnectedApps_AgentTeamConnectRequestGoesToAdmins(t *testing.T) {
}
}
+// teamNotices counts a member's team account notifications for one app,
+// open or archived.
+func teamNotices(t *testing.T, recipient, slug string, archived bool) int {
+ t.Helper()
+ return dbfx.Count(t, `SELECT count(*) FROM inbox_item WHERE workspace_id=$1 AND recipient_id=$2 AND type=$3
+ AND details->>'toolkit_slug'=$4 AND archived=$5`, testWorkspaceID, recipient, connectedapps.NotifConnectRequested, slug, archived)
+}
+
+// A team account request goes to the admin it concerns: the run's starter
+// when they are an admin, else the agent's owner when they are one, else
+// every admin. Deciding it archives the other admins' notifications.
+func TestConnectedApps_TeamConnectRequestRecipients(t *testing.T) {
+ f := newAppsFixture(t)
+ other := createTestUserAndMember(t, "admin")
+ plain := createTestUserAndMember(t, "member")
+ team := []map[string]string{}
+ for _, slug := range []string{"notion", "slack", "linear"} {
+ team = append(team, map[string]string{"toolkit_slug": slug, "account_scope": "team", "level": "write"})
+ }
+ if w := f.putAgentApps(t, testUserID, team); w.Code != http.StatusOK {
+ t.Fatalf("attach: %d %s", w.Code, w.Body.String())
+ }
+ ask := func(slug, originator, owner string) {
+ t.Helper()
+ dbfx.Exec(t, `UPDATE agent_task_queue SET originator_user_id=$1, accountable_user_id=$1 WHERE id=$2`, originator, f.taskID)
+ dbfx.Exec(t, `UPDATE agent SET owner_id=$1 WHERE id=$2`, owner, f.agentID)
+ if _, text, isErr := f.gateway(t, f.token(t), "apps_request_connection", map[string]any{"app": slug}); isErr {
+ t.Fatalf("request %s: %s", slug, text)
+ }
+ }
+ want := func(slug string, counts map[string]int) {
+ t.Helper()
+ for user, n := range counts {
+ if got := teamNotices(t, user, slug, false); got != n {
+ t.Fatalf("%s: open notifications for %s = %d, want %d", slug, user, got, n)
+ }
+ }
+ }
+
+ // The run's starter is an admin: only they are asked.
+ ask("notion", testUserID, other)
+ want("notion", map[string]int{testUserID: 1, other: 0, f.member: 0})
+
+ // The starter is not an admin, the agent's owner is: only the owner.
+ ask("slack", f.member, other)
+ want("slack", map[string]int{testUserID: 0, other: 1, f.member: 0})
+
+ // Neither is an admin: every admin.
+ ask("linear", f.member, f.member)
+ want("linear", map[string]int{testUserID: 1, other: 1, f.member: 0})
+
+ // A later request for the same app reaches an admin nobody asked yet,
+ // and does not repeat for one who already holds an open notification.
+ if code := f.requestTeamApp(t, plain, map[string]any{"toolkit_slug": "slack"}); code != http.StatusNoContent {
+ t.Fatalf("member asks for slack: %d", code)
+ }
+ want("slack", map[string]int{testUserID: 1, other: 1, plain: 0})
+
+ // Connecting answers every request: the other admins' notifications are
+ // archived, the connecting admin's stays where they acted on it.
+ f.teamAccount(t, "linear")
+ f.h.ConnectedApps.ResolveTeamConnectRequests(context.Background(), parseUUID(testWorkspaceID), parseUUID(testUserID), "linear")
+ want("linear", map[string]int{testUserID: 1, other: 0})
+ if n := teamNotices(t, other, "linear", true); n != 1 {
+ t.Fatalf("archived linear notifications for the other admin = %d, want 1", n)
+ }
+
+ // So does declining.
+ if code := f.dismissTeamRequests(t, other, "slack"); code != http.StatusNoContent {
+ t.Fatalf("decline slack: %d", code)
+ }
+ want("slack", map[string]int{testUserID: 0, other: 1})
+ if n := dbfx.Count(t, `SELECT count(*) FROM app_action_request WHERE workspace_id=$1 AND toolkit_slug='slack' AND status='pending'`, testWorkspaceID); n != 0 {
+ t.Fatalf("pending slack requests after decline = %d", n)
+ }
+}
+
func TestConnectedApps_PersonalConnectionImpact(t *testing.T) {
f := newAppsFixture(t)
if w := f.putAgentApps(t, testUserID, []map[string]string{{"toolkit_slug": "gmail", "account_scope": "personal"}}); w.Code != http.StatusOK {
diff --git a/server/pkg/db/generated/connected_apps.sql.go b/server/pkg/db/generated/connected_apps.sql.go
index 8f1be57297..63625c2e06 100644
--- a/server/pkg/db/generated/connected_apps.sql.go
+++ b/server/pkg/db/generated/connected_apps.sql.go
@@ -39,12 +39,14 @@ const archiveAppRequestInbox = `-- name: ArchiveAppRequestInbox :many
UPDATE inbox_item SET archived = true, snoozed_until = NULL, snoozed_at = NULL, returned_at = NULL
WHERE workspace_id = $1 AND type = 'app_connect_requested' AND archived = false
AND details->>'request_id' = $2::text
+ AND recipient_id IS DISTINCT FROM $3::uuid
RETURNING recipient_type, recipient_id
`
type ArchiveAppRequestInboxParams struct {
- WorkspaceID pgtype.UUID `json:"workspace_id"`
- RequestID string `json:"request_id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ RequestID string `json:"request_id"`
+ KeepRecipientID pgtype.UUID `json:"keep_recipient_id"`
}
type ArchiveAppRequestInboxRow struct {
@@ -52,9 +54,11 @@ type ArchiveAppRequestInboxRow struct {
RecipientID pgtype.UUID `json:"recipient_id"`
}
-// A withdrawn ask leaves the admins nothing to answer.
+// A withdrawn or decided team account request leaves the admins nothing to
+// answer. keep_recipient_id, when set, is the admin who decided it: their
+// item stays where they acted on it.
func (q *Queries) ArchiveAppRequestInbox(ctx context.Context, arg ArchiveAppRequestInboxParams) ([]ArchiveAppRequestInboxRow, error) {
- rows, err := q.db.Query(ctx, archiveAppRequestInbox, arg.WorkspaceID, arg.RequestID)
+ rows, err := q.db.Query(ctx, archiveAppRequestInbox, arg.WorkspaceID, arg.RequestID, arg.KeepRecipientID)
if err != nil {
return nil, err
}
@@ -1832,6 +1836,44 @@ func (q *Queries) ListTeamAppToolCalls(ctx context.Context, arg ListTeamAppToolC
return items, nil
}
+const listTeamConnectNotifiedRecipients = `-- name: ListTeamConnectNotifiedRecipients :many
+SELECT DISTINCT i.recipient_id FROM inbox_item i
+JOIN app_action_request r ON r.id = (i.details->>'request_id')::uuid
+WHERE i.workspace_id = $1 AND i.recipient_type = 'member'
+ AND i.recipient_id = ANY($3::uuid[])
+ AND i.type = 'app_connect_requested' AND NOT i.archived
+ AND r.workspace_id = $1 AND r.toolkit_slug = $2 AND r.kind = 'connect'
+ AND r.account_scope = 'team' AND r.status = 'pending'
+`
+
+type ListTeamConnectNotifiedRecipientsParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ ToolkitSlug string `json:"toolkit_slug"`
+ RecipientIds []pgtype.UUID `json:"recipient_ids"`
+}
+
+// Of recipient_ids, the members who already hold an open notification for a
+// pending request for this app's team account, so are not told again.
+func (q *Queries) ListTeamConnectNotifiedRecipients(ctx context.Context, arg ListTeamConnectNotifiedRecipientsParams) ([]pgtype.UUID, error) {
+ rows, err := q.db.Query(ctx, listTeamConnectNotifiedRecipients, arg.WorkspaceID, arg.ToolkitSlug, arg.RecipientIds)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []pgtype.UUID{}
+ for rows.Next() {
+ var recipient_id pgtype.UUID
+ if err := rows.Scan(&recipient_id); err != nil {
+ return nil, err
+ }
+ items = append(items, recipient_id)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
const listUserComposioConnectionsAnyStatus = `-- name: ListUserComposioConnectionsAnyStatus :many
SELECT id, user_id, toolkit_slug, auth_config_id, connected_account_id, composio_user_id, status, connected_at, last_used_at, created_at, updated_at, workspace_id FROM user_composio_connection
WHERE user_id = $1 AND status <> 'revoked'
diff --git a/server/pkg/db/queries/connected_apps.sql b/server/pkg/db/queries/connected_apps.sql
index 030239313a..1486419c28 100644
--- a/server/pkg/db/queries/connected_apps.sql
+++ b/server/pkg/db/queries/connected_apps.sql
@@ -368,12 +368,26 @@ WHERE workspace_id = $1 AND toolkit_slug = $2 AND approver_user_id = $3
LIMIT 1;
-- name: ArchiveAppRequestInbox :many
--- A withdrawn ask leaves the admins nothing to answer.
+-- A withdrawn or decided team account request leaves the admins nothing to
+-- answer. keep_recipient_id, when set, is the admin who decided it: their
+-- item stays where they acted on it.
UPDATE inbox_item SET archived = true, snoozed_until = NULL, snoozed_at = NULL, returned_at = NULL
WHERE workspace_id = $1 AND type = 'app_connect_requested' AND archived = false
AND details->>'request_id' = sqlc.arg('request_id')::text
+ AND recipient_id IS DISTINCT FROM sqlc.narg('keep_recipient_id')::uuid
RETURNING recipient_type, recipient_id;
+-- name: ListTeamConnectNotifiedRecipients :many
+-- Of recipient_ids, the members who already hold an open notification for a
+-- pending request for this app's team account, so are not told again.
+SELECT DISTINCT i.recipient_id FROM inbox_item i
+JOIN app_action_request r ON r.id = (i.details->>'request_id')::uuid
+WHERE i.workspace_id = $1 AND i.recipient_type = 'member'
+ AND i.recipient_id = ANY(sqlc.arg('recipient_ids')::uuid[])
+ AND i.type = 'app_connect_requested' AND NOT i.archived
+ AND r.workspace_id = $1 AND r.toolkit_slug = $2 AND r.kind = 'connect'
+ AND r.account_scope = 'team' AND r.status = 'pending';
+
-- name: ListTeamAccountRequestSummaries :many
-- One row per app with open requests for a team account: who is waiting and
-- which agents, oldest first. A person or agent waiting on several requests