Skip to content

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

Go

fix(apps): hand admins' team account notice to the next request when one ends (MUL-10097) (#11522)

Bohan Jiang4088262917b2
diff --git a/server/internal/connectedapps/requests.go b/server/internal/connectedapps/requests.go
index f0c1161caa..3e3b447abd 100644
--- a/server/internal/connectedapps/requests.go
+++ b/server/internal/connectedapps/requests.go
@@ -137,7 +137,6 @@ func (s *Service) WithdrawTeamAsk(ctx context.Context, workspaceID, memberID pgt
return err
}
s.withdraw(ctx, req)
- s.archiveAdminNotifications(ctx, req, pgtype.UUID{}, "app_request_withdrawn")
return nil
}
@@ -174,6 +173,14 @@ func (s *Service) archiveAdminNotifications(ctx context.Context, req db.AppActio
// Approve executes an approved request with args (nil keeps the agent's) and
// resumes the agent with the outcome. Only the approver may approve.
func (s *Service) Approve(ctx context.Context, workspaceID, actorID, requestID pgtype.UUID, args map[string]any) (db.AppActionRequest, error) {
+ decided, err := s.approve(ctx, workspaceID, actorID, requestID, args)
+ if err == nil {
+ s.endTeamRequests(ctx, actorID, "app_request_decided", decided)
+ }
+ return decided, err
+}
+
+func (s *Service) approve(ctx context.Context, workspaceID, actorID, requestID pgtype.UUID, args map[string]any) (db.AppActionRequest, error) {
req, asAdmin, err := s.pendingForDecider(ctx, workspaceID, actorID, requestID)
if err != nil {
return db.AppActionRequest{}, err
@@ -217,9 +224,6 @@ 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)
@@ -290,12 +294,16 @@ func (s *Service) ResolveTeamConnectRequests(ctx context.Context, workspaceID, a
slog.Warn("connectedapps: list team connect requests failed", "toolkit", slug, "error", err)
return
}
+ var decided []db.AppActionRequest
for _, r := range rows {
- if _, err := s.Approve(ctx, workspaceID, adminID, r.ID, nil); err != nil &&
- !errors.Is(err, ErrNotPending) && !errors.Is(err, ErrNoLongerAllowed) && !errors.Is(err, ErrCannotAddApp) {
+ row, err := s.approve(ctx, workspaceID, adminID, r.ID, nil)
+ if err == nil {
+ decided = append(decided, row)
+ } else if !errors.Is(err, ErrNotPending) && !errors.Is(err, ErrNoLongerAllowed) && !errors.Is(err, ErrCannotAddApp) {
slog.Warn("connectedapps: resolve team connect request failed", "request_id", util.UUIDToString(r.ID), "error", err)
}
}
+ s.endTeamRequests(ctx, adminID, "app_request_decided", decided...)
}
// DeclineTeamConnectRequests is an admin declining everything waiting for
@@ -307,16 +315,30 @@ func (s *Service) DeclineTeamConnectRequests(ctx context.Context, workspaceID, a
if err != nil {
return err
}
+ var decided []db.AppActionRequest
+ defer func() { s.endTeamRequests(ctx, adminID, "app_request_decided", decided...) }()
for _, r := range rows {
- if _, err := s.Reject(ctx, workspaceID, adminID, r.ID, ""); err != nil && !errors.Is(err, ErrNotPending) {
+ row, err := s.reject(ctx, workspaceID, adminID, r.ID, "")
+ if err != nil && !errors.Is(err, ErrNotPending) {
return err
}
+ if err == nil {
+ decided = append(decided, row)
+ }
}
return nil
}
// Reject declines a request and resumes the agent so it can adapt.
func (s *Service) Reject(ctx context.Context, workspaceID, actorID, requestID pgtype.UUID, reason string) (db.AppActionRequest, error) {
+ decided, err := s.reject(ctx, workspaceID, actorID, requestID, reason)
+ if err == nil {
+ s.endTeamRequests(ctx, actorID, "app_request_decided", decided)
+ }
+ return decided, err
+}
+
+func (s *Service) reject(ctx context.Context, workspaceID, actorID, requestID pgtype.UUID, reason string) (db.AppActionRequest, error) {
_, asAdmin, err := s.pendingForDecider(ctx, workspaceID, actorID, requestID)
if err != nil {
return db.AppActionRequest{}, err
@@ -341,9 +363,6 @@ 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 {
@@ -575,7 +594,16 @@ func (s *Service) withdraw(ctx context.Context, req db.AppActionRequest) {
if err != nil {
return
}
- s.publishChange(row)
+ s.RequestsCancelled(ctx, row)
+}
+
+// RequestsCancelled follows up requests that were cancelled while pending,
+// here or by a member leaving the workspace.
+func (s *Service) RequestsCancelled(ctx context.Context, cancelled ...db.AppActionRequest) {
+ for _, r := range cancelled {
+ s.publishChange(r)
+ }
+ s.endTeamRequests(ctx, pgtype.UUID{}, "app_request_withdrawn", cancelled...)
}
func (s *Service) resume(ctx context.Context, req db.AppActionRequest, actorID pgtype.UUID, note string) {
@@ -617,6 +645,7 @@ func (s *Service) Sweep(ctx context.Context) {
s.publishChange(r)
s.notify(ctx, r, NotifActionResult)
}
+ s.endTeamRequests(ctx, pgtype.UUID{}, "", expired...)
due, err := s.q.ClaimAppActionRequestReminders(ctx)
if err != nil {
slog.Warn("connectedapps: claim reminders failed", "error", err)
@@ -692,6 +721,95 @@ func (s *Service) notifyAdmins(ctx context.Context, req db.AppActionRequest) {
}
}
+// endTeamRequests runs once team account requests stopped pending. An
+// admin's one open notification for an app stands for every request waiting
+// for it (notifyAdmins), so whoever held one for an ended request is told
+// about the oldest request still waiting that concerns them. Admins who
+// archived theirs, or never held one, are not told. archiveReason, when set,
+// archives the ended requests' notifications, except keep's: the admin who
+// decided them keeps theirs where they acted on it. Expired ones stay.
+func (s *Service) endTeamRequests(ctx context.Context, keep pgtype.UUID, archiveReason string, ended ...db.AppActionRequest) {
+ type app struct {
+ workspaceID pgtype.UUID
+ slug string
+ }
+ var apps []app
+ byApp := map[app][]db.AppActionRequest{}
+ for _, r := range ended {
+ if !isTeamConnect(r) {
+ continue
+ }
+ k := app{r.WorkspaceID, r.ToolkitSlug}
+ if _, seen := byApp[k]; !seen {
+ apps = append(apps, k)
+ }
+ byApp[k] = append(byApp[k], r)
+ }
+ for _, k := range apps {
+ reqs := byApp[k]
+ ids := make([]string, len(reqs))
+ for i, r := range reqs {
+ ids[i] = util.UUIDToString(r.ID)
+ }
+ holders, err := s.q.ListAppRequestInboxHolders(ctx, db.ListAppRequestInboxHoldersParams{
+ WorkspaceID: k.workspaceID, RequestIds: ids,
+ })
+ if err != nil {
+ slog.Warn("connectedapps: list team request notification holders failed", "toolkit", k.slug, "error", err)
+ }
+ if archiveReason != "" {
+ for _, r := range reqs {
+ s.archiveAdminNotifications(ctx, r, keep, archiveReason)
+ }
+ }
+ s.handOffTeamNotices(ctx, k.workspaceID, k.slug, holders)
+ }
+}
+
+// handOffTeamNotices tells each of holders about the oldest request still
+// waiting for slug's team account that they are a recipient of, unless they
+// already hold an open notification for one.
+func (s *Service) handOffTeamNotices(ctx context.Context, workspaceID pgtype.UUID, slug string, holders []pgtype.UUID) {
+ if len(holders) == 0 {
+ return
+ }
+ waiting, err := s.q.ListPendingTeamConnectRequests(ctx, db.ListPendingTeamConnectRequestsParams{
+ WorkspaceID: workspaceID, ToolkitSlug: slug,
+ })
+ if err != nil {
+ slog.Warn("connectedapps: list team connect requests failed", "toolkit", slug, "error", err)
+ return
+ }
+ if len(waiting) == 0 {
+ return
+ }
+ notified, err := s.q.ListTeamConnectNotifiedRecipients(ctx, db.ListTeamConnectNotifiedRecipientsParams{
+ WorkspaceID: workspaceID, ToolkitSlug: slug, RecipientIds: holders,
+ })
+ if err != nil {
+ slog.Warn("connectedapps: list notified admins for team request failed", "toolkit", slug, "error", err)
+ return
+ }
+ left := make(map[pgtype.UUID]bool, len(holders))
+ for _, id := range holders {
+ left[id] = true
+ }
+ for _, id := range notified {
+ delete(left, id)
+ }
+ for _, r := range waiting {
+ if len(left) == 0 {
+ return
+ }
+ for _, admin := range s.teamConnectRecipients(ctx, r) {
+ if left[admin] {
+ s.deliver(ctx, r, NotifConnectRequested, admin)
+ delete(left, 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 {
diff --git a/server/internal/handler/connected_apps_requests_test.go b/server/internal/handler/connected_apps_requests_test.go
index b32397311b..c1d0a8537e 100644
--- a/server/internal/handler/connected_apps_requests_test.go
+++ b/server/internal/handler/connected_apps_requests_test.go
@@ -282,6 +282,158 @@ func TestConnectedApps_TeamConnectRequestRecipients(t *testing.T) {
}
}
+// waitingNotices counts a member's open notifications for the pending team
+// account request approver is waiting on.
+func waitingNotices(t *testing.T, recipient, approver string) int {
+ t.Helper()
+ return dbfx.Count(t, `SELECT count(*) 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_id=$2 AND i.type=$3 AND NOT i.archived
+ AND r.approver_user_id=$4 AND r.status='pending'`,
+ testWorkspaceID, recipient, connectedapps.NotifConnectRequested, approver)
+}
+
+func pendingTeamAsk(t *testing.T, approver string) string {
+ t.Helper()
+ var id string
+ dbfx.QueryRow(t, `SELECT id FROM app_action_request WHERE workspace_id=$1 AND approver_user_id=$2 AND status='pending'`,
+ testWorkspaceID, approver).Scan(&id)
+ return id
+}
+
+// One open notification stands for every request for an app, so when the
+// request it names ends, however it ends, the admin who held it is told
+// about the one still waiting.
+func TestConnectedApps_TeamConnectRequestEndsWhileAnotherWaits(t *testing.T) {
+ ctx := context.Background()
+ for name, tc := range map[string]struct {
+ // end finishes the first of the two requests.
+ end func(t *testing.T, f *appsFixture, first string)
+ // openForAdmin counts the admin's open notifications afterwards: a
+ // decided or expired one stays besides the new one.
+ openForAdmin int
+ }{
+ "withdrawn by the person waiting": {func(t *testing.T, f *appsFixture, first string) {
+ if _, err := f.h.ConnectedApps.Reject(ctx, parseUUID(testWorkspaceID), parseUUID(f.member), parseUUID(first), ""); err != nil {
+ t.Fatalf("withdraw: %v", err)
+ }
+ }, 1},
+ "ask withdrawn from the Apps page": {func(t *testing.T, f *appsFixture, _ string) {
+ if code := f.dismissTeamRequests(t, f.member, "notion"); code != http.StatusNoContent {
+ t.Fatalf("withdraw ask: %d", code)
+ }
+ }, 1},
+ "declined alone by an admin": {func(t *testing.T, f *appsFixture, first string) {
+ if _, err := f.h.ConnectedApps.Reject(ctx, parseUUID(testWorkspaceID), parseUUID(testUserID), parseUUID(first), ""); err != nil {
+ t.Fatalf("decline: %v", err)
+ }
+ }, 2},
+ "expired": {func(t *testing.T, f *appsFixture, first string) {
+ dbfx.Exec(t, `UPDATE app_action_request SET expires_at = now() - interval '1 minute' WHERE id=$1`, first)
+ f.h.ConnectedApps.Sweep(ctx)
+ }, 2},
+ "asker removed from the workspace": {func(t *testing.T, f *appsFixture, _ string) {
+ member, err := f.h.Queries.GetMemberByUserAndWorkspace(ctx, db.GetMemberByUserAndWorkspaceParams{
+ UserID: parseUUID(f.member), WorkspaceID: parseUUID(testWorkspaceID),
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := f.h.revokeAndRemoveMember(ctx, member.WorkspaceID, member.UserID, member.ID, parseUUID(testUserID)); err != nil {
+ t.Fatalf("remove member: %v", err)
+ }
+ }, 1},
+ } {
+ t.Run(name, func(t *testing.T) {
+ f := newAppsFixture(t)
+ second := createTestUserAndMember(t, "member")
+ for _, asker := range []string{f.member, second} {
+ if code := f.requestTeamApp(t, asker, map[string]any{"toolkit_slug": "notion"}); code != http.StatusNoContent {
+ t.Fatalf("ask: %d", code)
+ }
+ }
+ if n := teamNotices(t, testUserID, "notion", false); n != 1 {
+ t.Fatalf("open notifications before = %d, want 1", n)
+ }
+
+ tc.end(t, f, pendingTeamAsk(t, f.member))
+
+ if n := teamNotices(t, testUserID, "notion", false); n != tc.openForAdmin {
+ t.Fatalf("open notifications after = %d, want %d", n, tc.openForAdmin)
+ }
+ if n := waitingNotices(t, testUserID, second); n != 1 {
+ t.Fatalf("open notifications for the request still waiting = %d, want 1", n)
+ }
+ })
+ }
+}
+
+// The notification passes only to admins who held one for the ended request
+// and whom a waiting request concerns, once per app however many end.
+func TestConnectedApps_TeamConnectNoticeHandOff(t *testing.T) {
+ ctx := context.Background()
+ f := newAppsFixture(t)
+ other := createTestUserAndMember(t, "admin")
+ second := createTestUserAndMember(t, "member")
+ third := createTestUserAndMember(t, "member")
+ ask := func(slug string, askers ...string) {
+ t.Helper()
+ for _, asker := range askers {
+ if code := f.requestTeamApp(t, asker, map[string]any{"toolkit_slug": slug}); code != http.StatusNoContent {
+ t.Fatalf("%s asks for %s: %d", asker, slug, code)
+ }
+ }
+ }
+
+ // An admin who dismissed theirs is not told again.
+ ask("notion", f.member, second)
+ dbfx.Exec(t, `UPDATE inbox_item SET archived = true WHERE workspace_id=$1 AND recipient_id=$2 AND type=$3`,
+ testWorkspaceID, other, connectedapps.NotifConnectRequested)
+ if code := f.dismissTeamRequests(t, f.member, "notion"); code != http.StatusNoContent {
+ t.Fatalf("withdraw ask: %d", code)
+ }
+ if n := waitingNotices(t, testUserID, second); n != 1 {
+ t.Fatalf("notion: holder's notifications for the request left = %d, want 1", n)
+ }
+ if n := teamNotices(t, other, "notion", false); n != 0 {
+ t.Fatalf("notion: dismissing admin has %d open notifications, want 0", n)
+ }
+
+ // Requests expiring together hand over once.
+ ask("linear", f.member, second, third)
+ dbfx.Exec(t, `UPDATE app_action_request SET expires_at = now() - interval '1 minute'
+ WHERE workspace_id=$1 AND toolkit_slug='linear' AND approver_user_id = ANY($2::uuid[])`,
+ testWorkspaceID, []string{f.member, second})
+ f.h.ConnectedApps.Sweep(ctx)
+ if n := waitingNotices(t, testUserID, third); n != 1 {
+ t.Fatalf("linear: notifications for the request left = %d, want 1", n)
+ }
+ if n := teamNotices(t, testUserID, "linear", false); n != 2 {
+ t.Fatalf("linear: open notifications = %d, want 2: the expired one and the one left", n)
+ }
+
+ // A request that concerns one admin only is not handed to another: the
+ // agent's run was started by an admin, so only they are asked.
+ if w := f.putAgentApps(t, testUserID, []map[string]string{{"toolkit_slug": "slack", "account_scope": "team", "level": "write"}}); w.Code != http.StatusOK {
+ t.Fatalf("attach: %d %s", w.Code, w.Body.String())
+ }
+ ask("slack", f.member)
+ if _, text, isErr := f.gateway(t, f.token(t), "apps_request_connection", map[string]any{"app": "slack"}); isErr {
+ t.Fatalf("agent asks for slack: %s", text)
+ }
+ if n := teamNotices(t, other, "slack", false); n != 1 {
+ t.Fatalf("slack: other admin's open notifications before = %d, want 1", n)
+ }
+ if code := f.dismissTeamRequests(t, f.member, "slack"); code != http.StatusNoContent {
+ t.Fatalf("withdraw ask: %d", code)
+ }
+ if n := waitingNotices(t, testUserID, testUserID); n != 1 {
+ t.Fatalf("slack: run starter's notifications for the agent's request = %d, want 1", n)
+ }
+ if n := teamNotices(t, other, "slack", false); n != 0 {
+ t.Fatalf("slack: admin the agent's request does not concern has %d open notifications, want 0", 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/internal/handler/workspace_revoke.go b/server/internal/handler/workspace_revoke.go
index 13a8698676..2154949991 100644
--- a/server/internal/handler/workspace_revoke.go
+++ b/server/internal/handler/workspace_revoke.go
@@ -258,9 +258,10 @@ func (h *Handler) revokeMember(ctx context.Context, workspaceID, userID, memberI
// App requests waiting on the member would otherwise let a later OAuth
// connect, or a stale tab, resume an agent in a workspace they left.
- if _, err := qtx.CancelPendingAppActionRequestsForApprover(ctx, db.CancelPendingAppActionRequestsForApproverParams{
+ cancelledAppRequests, err := qtx.CancelPendingAppActionRequestsForApprover(ctx, db.CancelPendingAppActionRequestsForApproverParams{
WorkspaceID: workspaceID, ApproverUserID: userID,
- }); err != nil {
+ })
+ if err != nil {
return empty, err
}
@@ -348,6 +349,11 @@ func (h *Handler) revokeMember(ctx context.Context, workspaceID, userID, memberI
if err := tx.Commit(ctx); err != nil {
return empty, err
}
+ // After commit, like publishRevocation: admins are told about what is
+ // still waiting only once the cancellations are final.
+ if h.ConnectedApps != nil {
+ h.ConnectedApps.RequestsCancelled(ctx, cancelledAppRequests...)
+ }
return result, nil
}
diff --git a/server/pkg/db/generated/connected_apps.sql.go b/server/pkg/db/generated/connected_apps.sql.go
index 63625c2e06..925f32a6db 100644
--- a/server/pkg/db/generated/connected_apps.sql.go
+++ b/server/pkg/db/generated/connected_apps.sql.go
@@ -1099,6 +1099,39 @@ func (q *Queries) ListAppActionRulesForRun(ctx context.Context, arg ListAppActio
return items, nil
}
+const listAppRequestInboxHolders = `-- name: ListAppRequestInboxHolders :many
+SELECT DISTINCT recipient_id FROM inbox_item
+WHERE workspace_id = $1 AND type = 'app_connect_requested' AND NOT archived
+ AND recipient_type = 'member'
+ AND details->>'request_id' = ANY($2::text[])
+`
+
+type ListAppRequestInboxHoldersParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ RequestIds []string `json:"request_ids"`
+}
+
+// The members holding an open notification for any of the requests.
+func (q *Queries) ListAppRequestInboxHolders(ctx context.Context, arg ListAppRequestInboxHoldersParams) ([]pgtype.UUID, error) {
+ rows, err := q.db.Query(ctx, listAppRequestInboxHolders, arg.WorkspaceID, arg.RequestIds)
+ 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 listAppToolClassOverrides = `-- name: ListAppToolClassOverrides :many
SELECT workspace_id, toolkit_slug, tool_slug, action_class, updated_by, updated_at FROM app_tool_class_override
WHERE workspace_id = $1 AND toolkit_slug = $2
diff --git a/server/pkg/db/queries/connected_apps.sql b/server/pkg/db/queries/connected_apps.sql
index 1486419c28..ae327e90ab 100644
--- a/server/pkg/db/queries/connected_apps.sql
+++ b/server/pkg/db/queries/connected_apps.sql
@@ -377,6 +377,13 @@ WHERE workspace_id = $1 AND type = 'app_connect_requested' AND archived = false
AND recipient_id IS DISTINCT FROM sqlc.narg('keep_recipient_id')::uuid
RETURNING recipient_type, recipient_id;
+-- name: ListAppRequestInboxHolders :many
+-- The members holding an open notification for any of the requests.
+SELECT DISTINCT recipient_id FROM inbox_item
+WHERE workspace_id = $1 AND type = 'app_connect_requested' AND NOT archived
+ AND recipient_type = 'member'
+ AND details->>'request_id' = ANY(sqlc.arg('request_ids')::text[]);
+
-- 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.