Linger is An Open-Source Personal Agent That Runs Fully on Your PC. We aim to break Big Tech’s grip on AI by bringing powerful local AI to everyday computers through efficient model–harness co-design, so everyone can run their own.
fix(teamhub): identify and read Discord through Composio tools
shoudi zhengf82c1517ef5e
diff --git a/apps/teamhub/internal/composio/apps_test.go b/apps/teamhub/internal/composio/apps_test.goindex d155563c..ef5bc481 100644--- a/apps/teamhub/internal/composio/apps_test.go+++ b/apps/teamhub/internal/composio/apps_test.go@@ -6,6 +6,7 @@ import ("errors""net/http""net/http/httptest"+ "reflect""strings""testing""time"@@ -13,12 +14,31 @@ import (func TestDiscordAndGoogleCalendarProxyPaginationAndRendering(t *testing.T) {var requests []proxyRequest+ toolRequests := map[string]discordToolRequest{}server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- if r.Method == http.MethodGet && r.URL.Path == "/api/v3.1/connected_accounts/discord-account" {- _ = json.NewEncoder(w).Encode(map[string]any{- "toolkit": map[string]string{"slug": "discordbot"},- "state": map[string]any{"val": map[string]any{"guild": map[string]string{"id": "guild-1", "name": "Workspace Guild"}}},- })+ if slug, ok := strings.CutPrefix(r.URL.Path, "/api/v3.1/tools/execute/DISCORDBOT_"); ok {+ var request discordToolRequest+ if err := json.NewDecoder(r.Body).Decode(&request); err != nil || r.Method != http.MethodPost {+ t.Errorf("tool request %s err=%v", r.Method, err)+ }+ toolRequests[slug] = request+ var data json.RawMessage+ switch slug {+ case "GET_CONNECTED_GUILD":+ data = json.RawMessage(`{"id":"GUILD","name":"Workspace Guild"}`)+ case "LIST_GUILD_CHANNELS":+ data = json.RawMessage(`{"channels":[{"id":"channel-1","guild_id":"GUILD","parent_id":null,"name":"product","type":0},{"id":"voice-1","guild_id":"GUILD","name":"standup","type":2}]}`)+ case "GET_ACTIVE_GUILD_THREADS":+ data = json.RawMessage(`{"threads":[{"id":"thread-1","guild_id":"GUILD","parent_id":"channel-1","name":"launch","type":11,"thread_metadata":{"archive_timestamp":"2026-08-10T10:00:00Z"}}],"has_more":false,"members":[]}`)+ case "LIST_PUBLIC_ARCHIVED_THREADS":+ data = json.RawMessage(`{"threads":[{"id":"thread-2","guild_id":"GUILD","parent_id":"channel-1","name":"archive","type":11,"thread_metadata":{"archive_timestamp":"2026-08-09T10:00:00Z"}}],"has_more":true}`)+ case "LIST_MESSAGES":+ data = json.RawMessage(`{"messages":[{"id":"message-1","channel_id":"channel-1","content":"Hello <team>","timestamp":"2026-08-10T08:30:00Z","edited_timestamp":null,"type":0,"author":{"id":"user-1","username":"alice","global_name":"Alice","bot":false},"member":{"nick":"Alice P"},"attachments":[]}]}`)+ default:+ t.Errorf("unexpected Discord tool %s", slug)+ }+ data = json.RawMessage(strings.ReplaceAll(string(data), "GUILD", "1537440822578913330"))+ _ = json.NewEncoder(w).Encode(map[string]any{"successful": true, "data": data})return}var request proxyRequest@@ -30,16 +50,6 @@ func TestDiscordAndGoogleCalendarProxyPaginationAndRendering(t *testing.T) {requests = append(requests, request)var data json.RawMessageswitch request.Endpoint {- case "/guilds/guild-1":- data = json.RawMessage(`{"id":"guild-1","name":"Workspace Guild"}`)- case "/guilds/guild-1/channels":- data = json.RawMessage(`[{"id":"channel-1","guild_id":"guild-1","name":"product","type":0},{"id":"voice-1","guild_id":"guild-1","name":"standup","type":2}]`)- case "/guilds/guild-1/threads/active":- data = json.RawMessage(`{"threads":[{"id":"thread-1","guild_id":"guild-1","parent_id":"channel-1","name":"launch","type":11,"thread_metadata":{"archive_timestamp":"2026-08-10T10:00:00Z"}}]}`)- case "/channels/channel-1/threads/archived/public":- data = json.RawMessage(`{"threads":[{"id":"thread-2","guild_id":"guild-1","parent_id":"channel-1","name":"archive","type":11,"thread_metadata":{"archive_timestamp":"2026-08-09T10:00:00Z"}}],"has_more":true}`)- case "/channels/channel-1/messages":- data = json.RawMessage(`[{"id":"message-1","channel_id":"channel-1","content":"Hello <team>","timestamp":"2026-08-10T08:30:00Z","type":0,"author":{"id":"user-1","username":"alice","global_name":"Alice","bot":false},"member":{"nick":"Alice P"},"attachments":[]}]`)case "/users/me/calendarList/primary":data = json.RawMessage(`{"id":"[email protected]","summary":"Alice","timeZone":"Asia/Shanghai","primary":true}`)case "/users/me/calendarList":@@ -59,11 +69,14 @@ func TestDiscordAndGoogleCalendarProxyPaginationAndRendering(t *testing.T) {if err != nil {t.Fatal(err)}+ client.SetConnectionAuthority(func(context.Context, string) (ConnectionBinding, error) {+ return ConnectionBinding{UserID: "binding-user"}, nil+ })ctx := context.Background()start, end := time.Date(2026, 8, 9, 0, 0, 0, 0, time.UTC), time.Date(2026, 8, 11, 0, 0, 0, 0, time.UTC)discordIdentity, err := client.IdentifyDiscord(ctx, "discord-account")- if err != nil || discordIdentity.GuildID != "guild-1" {+ if err != nil || discordIdentity.GuildID != "1537440822578913330" {t.Fatalf("Discord identity=%+v err=%v", discordIdentity, err)}channels, err := client.ListDiscordChannels(ctx, "discord-account", discordIdentity.GuildID)@@ -83,7 +96,7 @@ func TestDiscordAndGoogleCalendarProxyPaginationAndRendering(t *testing.T) {t.Fatalf("Discord messages=%+v err=%v", messages, err)}discordDocuments, err := RenderDiscordDocumentsWithLimits(discordIdentity, map[string]DiscordChannel{"channel-1": channels[0]}, messages.Messages, DefaultAppImportLimits())- if err != nil || len(discordDocuments) != 1 || !strings.Contains(string(discordDocuments[0].Markdown), "Author: Alice P") || !strings.Contains(string(discordDocuments[0].Markdown), "Hello <team>") || !strings.Contains(string(discordDocuments[0].Markdown), "discord.com/channels/guild-1/channel-1/message-1") {+ if err != nil || len(discordDocuments) != 1 || !strings.Contains(string(discordDocuments[0].Markdown), "Author: Alice P") || !strings.Contains(string(discordDocuments[0].Markdown), "Hello <team>") || !strings.Contains(string(discordDocuments[0].Markdown), "discord.com/channels/1537440822578913330/channel-1/message-1") {t.Fatalf("Discord documents=%+v err=%v", discordDocuments, err)}@@ -104,8 +117,23 @@ func TestDiscordAndGoogleCalendarProxyPaginationAndRendering(t *testing.T) {t.Fatalf("Calendar documents=%+v err=%v", calendarDocuments, err)}- assertProxyParameter(t, requests, "/channels/channel-1/threads/archived/public", "before", "archive-cursor")- assertProxyParameter(t, requests, "/channels/channel-1/messages", "before", "message-cursor")+ firstPage, err := client.ListDiscordMessages(ctx, "discord-account", "channel-1", "", 100)+ if err != nil || firstPage.NextBefore != "" || !firstPage.Messages[0].EditedTimestamp.IsZero() {+ t.Fatalf("Discord first message page=%+v err=%v", firstPage, err)+ }+ wantArguments := map[string]map[string]any{+ "GET_CONNECTED_GUILD": {},+ "LIST_GUILD_CHANNELS": {"guild_id": "1537440822578913330"},+ "GET_ACTIVE_GUILD_THREADS": {"guild_id": "1537440822578913330"},+ "LIST_PUBLIC_ARCHIVED_THREADS": {"channel_id": "channel-1", "limit": float64(100), "before": "archive-cursor"},+ "LIST_MESSAGES": {"channel_id": "channel-1", "limit": float64(100)},+ }+ for slug, want := range wantArguments {+ request := toolRequests[slug]+ if request.ConnectedAccountID != "discord-account" || request.UserID != "binding-user" || request.Version != "20261116_00" || !reflect.DeepEqual(request.Arguments, want) {+ t.Fatalf("Discord tool %s request=%+v want arguments %v", slug, request, want)+ }+ }assertProxyParameter(t, requests, "/users/me/calendarList", "pageToken", "calendar-cursor")assertProxyParameter(t, requests, "/calendars/[email protected]/events", "pageToken", "event-cursor")for _, request := range requests {@@ -151,47 +179,92 @@ func TestGoogleCalendarDeletedTombstoneWithoutStartRemainsImportable(t *testing.}}-func TestDiscordIdentityFailsClosedWithoutAuthorizedGuild(t *testing.T) {- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {- _ = json.NewEncoder(w).Encode(map[string]any{"toolkit": map[string]string{"slug": "discordbot"}, "state": map[string]any{"val": map[string]any{}}})- }))- defer server.Close()+func newDiscordIdentityTestClient(t *testing.T, handler http.HandlerFunc) *Client {+ t.Helper()+ server := httptest.NewServer(handler)+ t.Cleanup(server.Close)client, err := newTestClient(Config{BaseURL: server.URL, APIKey: "key", HTTPClient: server.Client(), RetryLimit: -1})if err != nil {t.Fatal(err)}- if _, err = client.IdentifyDiscord(context.Background(), "discord-account"); !errors.Is(err, ErrDiscordGuildRequired) {- t.Fatalf("Discord identity error=%v want ErrDiscordGuildRequired", err)- }+ client.SetConnectionAuthority(func(context.Context, string) (ConnectionBinding, error) {+ return ConnectionBinding{UserID: "binding-user"}, nil+ })+ return client}-func TestDiscordIdentityRequiresExplicitGuildWhenStateIsRedacted(t *testing.T) {- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- if strings.Contains(r.URL.Path, "/guilds/") {- t.Fatalf("redacted guild id must not be sent to Discord: %s", r.URL.Path)- }- _ = json.NewEncoder(w).Encode(map[string]any{- "toolkit": map[string]string{"slug": "discordbot"},- "state": map[string]any{"val": map[string]any{- "guild": map[string]string{"id": "REDACTED", "name": "REDACTED"},- }},+func TestDiscordIdentityReadsConnectedGuildTool(t *testing.T) {+ for name, data := range map[string]any{+ "object": map[string]any{"id": "1537440822578913330", "name": "Workspace Guild", "owner_id": "1"},+ "string": `{"id":"1537440822578913330","name":"Workspace Guild"}`,+ } {+ t.Run(name, func(t *testing.T) {+ client := newDiscordIdentityTestClient(t, func(w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodPost || r.URL.Path != "/api/v3.1/tools/execute/DISCORDBOT_GET_CONNECTED_GUILD" {+ t.Errorf("unexpected request %s %s", r.Method, r.URL.Path)+ w.WriteHeader(http.StatusBadRequest)+ return+ }+ var body struct {+ ConnectedAccountID string `json:"connected_account_id"`+ UserID string `json:"user_id"`+ Version string `json:"version"`+ Arguments map[string]json.RawMessage `json:"arguments"`+ }+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil || body.ConnectedAccountID != "discord-account" || body.UserID != "binding-user" || body.Version != "20261116_00" || body.Arguments == nil || len(body.Arguments) != 0 {+ t.Errorf("tool request=%+v err=%v", body, err)+ }+ _ = json.NewEncoder(w).Encode(map[string]any{"successful": true, "data": data})+ })+ identity, err := client.IdentifyDiscord(context.Background(), "discord-account")+ if err != nil || identity != (DiscordIdentity{GuildID: "1537440822578913330", GuildName: "Workspace Guild"}) {+ t.Fatalf("Discord identity=%+v err=%v", identity, err)+ }})- }))- defer server.Close()- client, err := newTestClient(Config{BaseURL: server.URL, APIKey: "key", HTTPClient: server.Client(), RetryLimit: -1})- if err != nil {- t.Fatal(err)}- if _, err = client.IdentifyDiscord(context.Background(), "discord-account"); !errors.Is(err, ErrDiscordGuildRequired) {- t.Fatalf("Discord identity error=%v want ErrDiscordGuildRequired", err)+}++func TestDiscordIdentityRejectsUnusableGuild(t *testing.T) {+ cases := map[string]struct {+ response map[string]any+ guildMissing bool+ }{+ "unsuccessful": {response: map[string]any{"successful": false, "data": map[string]string{"id": "1537440822578913330", "name": "Guild"}}},+ "array data": {response: map[string]any{"successful": true, "data": []string{"1537440822578913330"}}},+ "number data": {response: map[string]any{"successful": true, "data": 1537440822578913330}},+ "non-object string": {response: map[string]any{"successful": true, "data": "not json"}},+ "redacted id": {response: map[string]any{"successful": true, "data": map[string]string{"id": "REDACTED", "name": "Guild"}}, guildMissing: true},+ "non-numeric id": {response: map[string]any{"successful": true, "data": map[string]string{"id": "15374408225789133x0", "name": "Guild"}}, guildMissing: true},+ "short id": {response: map[string]any{"successful": true, "data": map[string]string{"id": "1234567890", "name": "Guild"}}, guildMissing: true},+ "empty id": {response: map[string]any{"successful": true, "data": map[string]string{"id": "", "name": "Guild"}}, guildMissing: true},+ "redacted name": {response: map[string]any{"successful": true, "data": map[string]string{"id": "1537440822578913330", "name": "redacted"}}, guildMissing: true},+ "empty name": {response: map[string]any{"successful": true, "data": map[string]string{"id": "1537440822578913330", "name": ""}}, guildMissing: true},+ "whitespace name": {response: map[string]any{"successful": true, "data": map[string]string{"id": "1537440822578913330", "name": " "}}, guildMissing: true},+ }+ for name, tc := range cases {+ t.Run(name, func(t *testing.T) {+ client := newDiscordIdentityTestClient(t, func(w http.ResponseWriter, r *http.Request) {+ if r.URL.Path != "/api/v3.1/tools/execute/DISCORDBOT_GET_CONNECTED_GUILD" {+ t.Errorf("unexpected request %s", r.URL.Path)+ }+ _ = json.NewEncoder(w).Encode(tc.response)+ })+ _, err := client.IdentifyDiscord(context.Background(), "discord-account")+ if err == nil || errors.Is(err, ErrDiscordGuildRequired) != tc.guildMissing {+ t.Fatalf("Discord identity error=%v want guild required=%v", err, tc.guildMissing)+ }+ })}}func TestDiscordGuildMapsMissingOrForbiddenServerToAccessibleError(t *testing.T) {for _, remoteStatus := range []int{http.StatusForbidden, http.StatusNotFound} {t.Run(http.StatusText(remoteStatus), func(t *testing.T) {- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {- _ = json.NewEncoder(w).Encode(proxyResponse{Status: remoteStatus, Data: json.RawMessage(`{}`)})+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.URL.Path != "/api/v3.1/tools/execute/DISCORDBOT_GET_GUILD" {+ t.Errorf("unexpected request %s", r.URL.Path)+ }+ _ = json.NewEncoder(w).Encode(map[string]any{"successful": false, "error": "denied", "data": map[string]any{"message": "denied", "status_code": remoteStatus}})}))defer server.Close()client, err := newTestClient(Config{BaseURL: server.URL, APIKey: "key", HTTPClient: server.Client(), RetryLimit: -1})@@ -205,6 +278,44 @@ func TestDiscordGuildMapsMissingOrForbiddenServerToAccessibleError(t *testing.T)}}+type discordToolRequest struct {+ ConnectedAccountID string `json:"connected_account_id"`+ UserID string `json:"user_id"`+ Version string `json:"version"`+ Arguments map[string]any `json:"arguments"`+}++func TestDiscordToolFailureUsesStructuredStatus(t *testing.T) {+ for name, data := range map[string]any{+ "rate limited": map[string]any{"message": "slow down", "status_code": 429},+ "unauthorized": map[string]any{"message": "no", "status_code": 401},+ "no status": map[string]any{"message": "Forbidden 403"},+ } {+ t.Run(name, func(t *testing.T) {+ client := newDiscordIdentityTestClient(t, func(w http.ResponseWriter, _ *http.Request) {+ _ = json.NewEncoder(w).Encode(map[string]any{"successful": false, "error": "status 403", "data": data})+ })+ _, err := client.ListDiscordChannels(context.Background(), "discord-account", "1537440822578913330")+ var limited *RateLimitError+ _, hasStatus := ErrorStatus(err)+ switch name {+ case "rate limited":+ if !errors.As(err, &limited) {+ t.Fatalf("error=%v want RateLimitError", err)+ }+ case "unauthorized":+ if !IsAuthFailure(err) {+ t.Fatalf("error=%v want auth failure", err)+ }+ default:+ if err == nil || hasStatus || errors.As(err, &limited) {+ t.Fatalf("error=%v want plain error", err)+ }+ }+ })+ }+}+func TestAppProxyPreservesRateLimitForJobRetry(t *testing.T) {requests := 0server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {diff --git a/apps/teamhub/internal/composio/discord.go b/apps/teamhub/internal/composio/discord.goindex 0e1b7ebe..a4101b95 100644--- a/apps/teamhub/internal/composio/discord.go+++ b/apps/teamhub/internal/composio/discord.go@@ -8,7 +8,6 @@ import ("net/http""net/url""sort"- "strconv""strings""time""unicode/utf8"@@ -52,68 +51,100 @@ type DiscordMessagePage struct {NextBefore string}-func (c *Client) IdentifyDiscord(ctx context.Context, connectedAccountID string) (DiscordIdentity, error) {- if _, err := c.authorizeConnection(ctx, connectedAccountID); err != nil {- return DiscordIdentity{}, err- }- var account struct {- Toolkit struct {- Slug string `json:"slug"`- } `json:"toolkit"`- State *struct {- Val json.RawMessage `json:"val"`- } `json:"state"`+// Discord tools are pinned so a TeamHub release keeps its behavior when+// Composio publishes a new tool version. Composio disables Proxy Execute for+// discordbot, so every Discord read goes through these tools.+const discordToolVersion = "20261116_00"++// executeDiscordTool runs a read-only Discord tool for the bound user and+// decodes its data into target. A failed execution is classified only by the+// structured data.status_code, never by the error prose.+func (c *Client) executeDiscordTool(ctx context.Context, connectedAccountID, slug string, arguments map[string]any, target any, operation string) error {+ binding, err := c.authorizeConnection(ctx, connectedAccountID)+ if err != nil {+ return err+ }+ request := struct {+ ConnectedAccountID string `json:"connected_account_id"`+ UserID string `json:"user_id"`+ Version string `json:"version"`+ Arguments map[string]any `json:"arguments"`+ }{ConnectedAccountID: connectedAccountID, UserID: binding.UserID, Version: discordToolVersion, Arguments: arguments}+ var response struct {+ Data json.RawMessage `json:"data"`+ Successful bool `json:"successful"`+ }+ endpoint := "/api/v3.1/tools/execute/" + url.PathEscape(slug)+ if err := c.requestJSON(ctx, http.MethodPost, endpoint, request, &response, operation); err != nil {+ return err+ }+ if !response.Successful {+ var failure struct {+ StatusCode int `json:"status_code"`+ }+ _ = decodeDiscordToolData(response.Data, &failure)+ switch {+ case failure.StatusCode == http.StatusTooManyRequests:+ return &RateLimitError{Operation: operation}+ case failure.StatusCode > 0:+ return &remoteError{operation: operation, status: failure.StatusCode}+ default:+ return fmt.Errorf("Composio %s failed", operation)+ }}- endpoint := "/api/v3.1/connected_accounts/" + url.PathEscape(connectedAccountID)- if err := c.requestJSON(ctx, http.MethodGet, endpoint, nil, &account, "identify Discord installation"); err != nil {- return DiscordIdentity{}, err+ if err := decodeDiscordToolData(response.Data, target); err != nil {+ return fmt.Errorf("Composio %s returned an invalid response", operation)}- if account.Toolkit.Slug != "discordbot" || account.State == nil {- return DiscordIdentity{}, errors.New("Discord installation response was incomplete")- }- var state struct {- Guild struct {- ID string `json:"id"`- Name string `json:"name"`- } `json:"guild"`- GuildID string `json:"guild_id"`- OAuth2 struct {- Guild struct {- ID string `json:"id"`- Name string `json:"name"`- } `json:"guild"`- } `json:"oauth2"`- }- payload := account.State.Val- var encoded string- if len(payload) > 0 && payload[0] == '"' && json.Unmarshal(payload, &encoded) == nil {- payload = []byte(encoded)- }- if err := json.Unmarshal(payload, &state); err != nil {- return DiscordIdentity{}, errors.New("Discord installation state was invalid")- }- guildID, guildName := state.Guild.ID, state.Guild.Name- if guildID == "" {- guildID = state.OAuth2.Guild.ID- guildName = state.OAuth2.Guild.Name+ return nil+}++// decodeDiscordToolData accepts data as an object or as a string holding an+// object: Composio documents a string, but the live tools return objects.+func decodeDiscordToolData(data json.RawMessage, target any) error {+ payload := data+ if len(payload) > 0 && payload[0] == '"' {+ var encoded string+ if err := json.Unmarshal(payload, &encoded); err != nil {+ return err+ }+ payload = []byte(strings.TrimSpace(encoded))}- if guildID == "" {- guildID = state.GuildID+ if len(payload) == 0 || payload[0] != '{' {+ return errors.New("Discord tool data was not an object")}- if guildID == "" || strings.EqualFold(strings.TrimSpace(guildID), "REDACTED") {- return DiscordIdentity{}, ErrDiscordGuildRequired+ return json.Unmarshal(payload, target)+}++// IdentifyDiscord returns the server the bot connection was installed in. It+// fails closed with ErrDiscordGuildRequired unless Composio reports a valid+// server id and a readable name.+func (c *Client) IdentifyDiscord(ctx context.Context, connectedAccountID string) (DiscordIdentity, error) {+ var guild struct {+ ID string `json:"id"`+ Name string `json:"name"`}- guild, err := c.GetDiscordGuild(ctx, connectedAccountID, guildID)- if err != nil {+ if err := c.executeDiscordTool(ctx, connectedAccountID, "DISCORDBOT_GET_CONNECTED_GUILD", map[string]any{}, &guild, "identify Discord installation"); err != nil {return DiscordIdentity{}, err}- if guild.GuildName != "" {- guildName = guild.GuildName+ name := strings.TrimSpace(guild.Name)+ if !validDiscordGuildID(guild.ID) || name == "" || strings.EqualFold(name, "REDACTED") {+ return DiscordIdentity{}, ErrDiscordGuildRequired}- if strings.TrimSpace(guildName) == "" {- return DiscordIdentity{}, errors.New("Discord installation guild name was missing")+ return DiscordIdentity{GuildID: guild.ID, GuildName: name}, nil+}++// validDiscordGuildID accepts only Discord snowflakes so a redacted or+// malformed value never becomes a bound identity.+func validDiscordGuildID(id string) bool {+ if len(id) < 17 || len(id) > 20 {+ return false+ }+ for _, r := range id {+ if r < '0' || r > '9' {+ return false+ }}- return DiscordIdentity{GuildID: guildID, GuildName: guildName}, nil+ return true}func (c *Client) GetDiscordGuild(ctx context.Context, connectedAccountID, guildID string) (DiscordIdentity, error) {@@ -124,8 +155,7 @@ func (c *Client) GetDiscordGuild(ctx context.Context, connectedAccountID, guildIID string `json:"id"`Name string `json:"name"`}- endpoint := "/guilds/" + url.PathEscape(guildID)- if err := c.proxy(ctx, proxyRequest{ConnectedAccountID: connectedAccountID, Endpoint: endpoint, Method: http.MethodGet}, &wire, "get Discord guild"); err != nil {+ if err := c.executeDiscordTool(ctx, connectedAccountID, "DISCORDBOT_GET_GUILD", map[string]any{"guild_id": guildID}, &wire, "get Discord guild"); err != nil {var remote *remoteErrorif errors.As(err, &remote) && (remote.status == http.StatusForbidden || remote.status == http.StatusNotFound) {return DiscordIdentity{}, ErrDiscordGuildNotAccessible@@ -139,19 +169,20 @@ func (c *Client) GetDiscordGuild(ctx context.Context, connectedAccountID, guildI}func (c *Client) ListDiscordChannels(ctx context.Context, connectedAccountID, guildID string) ([]DiscordChannel, error) {- var wire []struct {- ID string `json:"id"`- GuildID string `json:"guild_id"`- ParentID string `json:"parent_id"`- Name string `json:"name"`- Type int `json:"type"`+ var wire struct {+ Channels []struct {+ ID string `json:"id"`+ GuildID string `json:"guild_id"`+ ParentID string `json:"parent_id"`+ Name string `json:"name"`+ Type int `json:"type"`+ } `json:"channels"`}- endpoint := "/guilds/" + url.PathEscape(guildID) + "/channels"- if err := c.proxy(ctx, proxyRequest{ConnectedAccountID: connectedAccountID, Endpoint: endpoint, Method: http.MethodGet}, &wire, "list Discord guild channels"); err != nil {+ if err := c.executeDiscordTool(ctx, connectedAccountID, "DISCORDBOT_LIST_GUILD_CHANNELS", map[string]any{"guild_id": guildID}, &wire, "list Discord guild channels"); err != nil {return nil, err}- channels := make([]DiscordChannel, 0, len(wire))- for _, item := range wire {+ channels := make([]DiscordChannel, 0, len(wire.Channels))+ for _, item := range wire.Channels {if item.ID == "" || item.GuildID != guildID || strings.TrimSpace(item.Name) == "" {return nil, errors.New("Discord channel response was incomplete")}@@ -166,8 +197,7 @@ func (c *Client) ListDiscordActiveThreads(ctx context.Context, connectedAccountIvar wire struct {Threads []discordThreadWire `json:"threads"`}- endpoint := "/guilds/" + url.PathEscape(guildID) + "/threads/active"- if err := c.proxy(ctx, proxyRequest{ConnectedAccountID: connectedAccountID, Endpoint: endpoint, Method: http.MethodGet}, &wire, "list active Discord threads"); err != nil {+ if err := c.executeDiscordTool(ctx, connectedAccountID, "DISCORDBOT_GET_ACTIVE_GUILD_THREADS", map[string]any{"guild_id": guildID}, &wire, "list active Discord threads"); err != nil {return nil, err}return normalizeDiscordThreads(guildID, wire.Threads)@@ -177,16 +207,15 @@ func (c *Client) ListDiscordArchivedThreads(ctx context.Context, connectedAccounif guildID == "" || channelID == "" || limit < 1 || limit > 100 {return DiscordThreadPage{}, errors.New("invalid Discord archived thread request")}- parameters := []proxyParameter{{Name: "limit", Value: strconv.Itoa(limit), Type: "query"}}+ arguments := map[string]any{"channel_id": channelID, "limit": limit}if cursor != "" {- parameters = append(parameters, proxyParameter{Name: "before", Value: cursor, Type: "query"})+ arguments["before"] = cursor}var wire struct {Threads []discordThreadWire `json:"threads"`HasMore bool `json:"has_more"`}- endpoint := "/channels/" + url.PathEscape(channelID) + "/threads/archived/public"- if err := c.proxy(ctx, proxyRequest{ConnectedAccountID: connectedAccountID, Endpoint: endpoint, Method: http.MethodGet, Parameters: parameters}, &wire, "list archived Discord threads"); err != nil {+ if err := c.executeDiscordTool(ctx, connectedAccountID, "DISCORDBOT_LIST_PUBLIC_ARCHIVED_THREADS", arguments, &wire, "list archived Discord threads"); err != nil {return DiscordThreadPage{}, err}threads, err := normalizeDiscordThreads(guildID, wire.Threads)@@ -243,36 +272,17 @@ func (c *Client) ListDiscordMessages(ctx context.Context, connectedAccountID, chif channelID == "" || limit < 1 || limit > 100 {return DiscordMessagePage{}, errors.New("invalid Discord message page request")}- parameters := []proxyParameter{{Name: "limit", Value: strconv.Itoa(limit), Type: "query"}}+ arguments := map[string]any{"channel_id": channelID, "limit": limit}if before != "" {- parameters = append(parameters, proxyParameter{Name: "before", Value: before, Type: "query"})- }- var wire []struct {- ID string `json:"id"`- ChannelID string `json:"channel_id"`- Content string `json:"content"`- Timestamp string `json:"timestamp"`- EditedTimestamp string `json:"edited_timestamp"`- Type int `json:"type"`- Author struct {- ID string `json:"id"`- Username string `json:"username"`- GlobalName string `json:"global_name"`- Bot bool `json:"bot"`- } `json:"author"`- Member struct {- Nick string `json:"nick"`- } `json:"member"`- Attachments []struct {- ID string `json:"id"`- Filename string `json:"filename"`- URL string `json:"url"`- } `json:"attachments"`+ arguments["before"] = before}- endpoint := "/channels/" + url.PathEscape(channelID) + "/messages"- if err := c.proxy(ctx, proxyRequest{ConnectedAccountID: connectedAccountID, Endpoint: endpoint, Method: http.MethodGet, Parameters: parameters}, &wire, "list Discord messages"); err != nil {+ var envelope struct {+ Messages []discordMessageWire `json:"messages"`+ }+ if err := c.executeDiscordTool(ctx, connectedAccountID, "DISCORDBOT_LIST_MESSAGES", arguments, &envelope, "list Discord messages"); err != nil {return DiscordMessagePage{}, err}+ wire := envelope.Messagespage := DiscordMessagePage{}for _, item := range wire {timestamp, err := time.Parse(time.RFC3339Nano, item.Timestamp)@@ -305,6 +315,29 @@ func (c *Client) ListDiscordMessages(ctx context.Context, connectedAccountID, chreturn page, nil}+type discordMessageWire struct {+ ID string `json:"id"`+ ChannelID string `json:"channel_id"`+ Content string `json:"content"`+ Timestamp string `json:"timestamp"`+ EditedTimestamp string `json:"edited_timestamp"`+ Type int `json:"type"`+ Author struct {+ ID string `json:"id"`+ Username string `json:"username"`+ GlobalName string `json:"global_name"`+ Bot bool `json:"bot"`+ } `json:"author"`+ Member struct {+ Nick string `json:"nick"`+ } `json:"member"`+ Attachments []struct {+ ID string `json:"id"`+ Filename string `json:"filename"`+ URL string `json:"url"`+ } `json:"attachments"`+}+func RenderDiscordDocumentsWithLimits(identity DiscordIdentity, channels map[string]DiscordChannel, messages []DiscordMessage, limits AppImportLimits) ([]AppDocument, error) {type groupKey struct{ channelID, day string }grouped := map[groupKey][]DiscordMessage{}diff --git a/apps/web/src/features/apps/app-manage-dialog.tsx b/apps/web/src/features/apps/app-manage-dialog.tsxindex 9fee5fe1..40ec1649 100644--- a/apps/web/src/features/apps/app-manage-dialog.tsx+++ b/apps/web/src/features/apps/app-manage-dialog.tsx@@ -17,7 +17,10 @@ import type {TeamHubExternalConnection,} from "@/features/teamhub/teamhub-types";-import { INSUFFICIENT_PERMISSION_MESSAGE } from "./authorization-error";+import {+ DISCORD_SERVER_UNCONFIRMED_MESSAGE,+ INSUFFICIENT_PERMISSION_MESSAGE,+} from "./authorization-error";import {externalConnectionQueryOptions,externalConnectionsQueryKey,@@ -28,6 +31,7 @@ import {externalConnectionNeedsAttention,openPendingExternalConnection,accountIdentityText,+ unconfirmedExternalConnections,} from "./connection-state";export function AppManageDialog({@@ -43,12 +47,16 @@ export function AppManageDialog({useState<TeamHubExternalConnection | null>(null);// Without a Composio key, Connect opens the key dialog on top of this one.const connectFlow = useConnectAppFlow();- const listed = establishedExternalConnections(connections);- // Accounts that need reconnecting stay listed so the Human can repair them.- const rows = [- ...listed,- ...connections.filter(externalConnectionNeedsAttention),- ];+ const established = establishedExternalConnections(connections);+ const unconfirmed = unconfirmedExternalConnections(connections);+ // Accounts that need reconnecting or confirming stay listed so the Human+ // can repair them.+ const rows = connections.filter(+ (connection) =>+ established.includes(connection) ||+ unconfirmed.includes(connection) ||+ externalConnectionNeedsAttention(connection),+ );const canConnect = connectFlow.canStart(app);const supportsAutoReminders = app.capabilities.includes("proactive_reminders",@@ -67,7 +75,7 @@ export function AppManageDialog({{canConnect ? (<Buttonaria-label={- listed.length+ established.length? `Add another ${app.display_name} account`: `Connect ${app.display_name}`}@@ -82,7 +90,7 @@ export function AppManageDialog({tone="secondary"><Icon icon={PlusSignIcon} size={14} />- {listed.length ? "Add account" : "Connect"}+ {established.length ? "Add account" : "Connect"}</Button>) : (<Button disabled size="compact">@@ -157,6 +165,8 @@ function ConnectionRow({const checking = Boolean(connection.status_check_requested_at);const duplicateIdentity =connection.status_error_code === "duplicate_remote_principal";+ const unconfirmed = unconfirmedExternalConnections([connection]).length > 0;+ const label = connection.identity_label ?? connection.provider;return (<div className="flex min-h-[58px] flex-wrap items-center gap-3 py-2.5">@@ -171,18 +181,21 @@ function ConnectionRow({{needsReconnecting ? (<StatusPill tone="warning">Needs reconnecting</StatusPill>) : (- <ConnectionStatus status={connection.status} />+ <ConnectionStatus+ status={connection.status}+ unconfirmed={unconfirmed}+ />)}</div></div><div className="flex flex-wrap items-center gap-1.5">- {connection.status === "active" ? (+ {connection.status === "active" || unconfirmed ? (<Button- aria-label={`Check ${connection.identity_label ?? connection.provider}`}+ aria-label={unconfirmed ? `Check again ${label}` : `Check ${label}`}disabled={statusCheck.isPending || checking}onClick={() => statusCheck.mutate()}size="compactIcon"- title="Check connection"+ title={unconfirmed ? "Check again" : "Check connection"}tone="ghost"><Icon@@ -217,10 +230,11 @@ function ConnectionRow({</Button>) : null}</div>- {connection.status_error_code === "discord_guild_required" ? (+ {unconfirmed ? (<p className="basis-full text-xs text-app-danger" role="alert">- Discord could not verify the authorized Server. Check the Composio- project credential masking setting, then reconnect.+ {connection.status_error_code === "discord_guild_required"+ ? `${DISCORD_SERVER_UNCONFIRMED_MESSAGE} Check again, or disconnect and reconnect.`+ : "The connection couldn't be confirmed yet. Check again."}</p>) : null}{connection.status_error_code === "provider_auth_failed" ? (@@ -388,12 +402,18 @@ export function DisconnectConnectionDialog({function ConnectionStatus({status,+ unconfirmed,}: {status: TeamHubExternalConnection["status"];+ unconfirmed: boolean;}) {return (<StatusPill tone={status === "active" ? "success" : "warning"}>- {status === "active" ? "Active" : "Disconnecting"}+ {status === "active"+ ? "Active"+ : unconfirmed+ ? "Not confirmed"+ : "Disconnecting"}</StatusPill>);}diff --git a/apps/web/src/features/apps/authorization-error.ts b/apps/web/src/features/apps/authorization-error.tsindex 9b1c3156..5cfda0b8 100644--- a/apps/web/src/features/apps/authorization-error.ts+++ b/apps/web/src/features/apps/authorization-error.ts@@ -1,12 +1,15 @@export const INSUFFICIENT_PERMISSION_MESSAGE ="This app did not grant enough permission. Reconnect and approve all requested access.";+export const DISCORD_SERVER_UNCONFIRMED_MESSAGE =+ "Discord is authorized, but the Server couldn't be confirmed.";+export function connectionStatusErrorMessage(statusErrorCode: string | null | undefined,): string | undefined {switch (statusErrorCode) {case "discord_guild_required":- return "Discord could not verify the authorized Server. Reconnect from Apps.";+ return `${DISCORD_SERVER_UNCONFIRMED_MESSAGE} Check it again from Apps.`;case "duplicate_remote_principal":return "This account is already connected.";case "provider_auth_failed":diff --git a/apps/web/src/features/apps/connected-apps-page.test.tsx b/apps/web/src/features/apps/connected-apps-page.test.tsxindex f00a4bb6..ce369de0 100644--- a/apps/web/src/features/apps/connected-apps-page.test.tsx+++ b/apps/web/src/features/apps/connected-apps-page.test.tsx@@ -570,18 +570,27 @@ describe("Connected apps", () => {).toBeVisible();});- it("hides a pending Discord account that never finished connecting", async () => {+ it("shows an unconfirmed Discord connection and checks it again", async () => {const runtime = await testRuntime();const template = (await runtime.client.listExternalConnections()).connections[0]!;- const pending = {+ const unconfirmed = {...template,id: "pending-discord",identity_label: "Discord server",provider: "discord" as const,+ revision: 4,status: "pending" as const,status_error_code: "discord_guild_required",};+ const duplicate = {+ ...template,+ id: "duplicate-discord",+ identity_label: "Duplicate server",+ provider: "discord" as const,+ status: "pending" as const,+ status_error_code: "duplicate_remote_principal",+ };const catalog = await runtime.client.listExternalApps();vi.spyOn(runtime.client, "listExternalApps").mockResolvedValue({provider_configured: true,@@ -593,23 +602,69 @@ describe("Connected apps", () => {),});vi.spyOn(runtime.client, "listExternalConnections").mockResolvedValue({- connections: [pending],+ connections: [unconfirmed, duplicate],});- vi.spyOn(runtime.client, "getExternalConnection").mockResolvedValue(- pending,- );- renderPage(runtime, "/apps?app=discord");+ const check = vi+ .spyOn(runtime.client, "createExternalConnectionStatusCheck")+ .mockResolvedValue({+ ...unconfirmed,+ status_check_requested_at: "2026-11-19T00:00:00.000Z",+ });+ renderPage(runtime);++ const card = await screen.findByRole("button", { name: "Discord" });+ expect(+ await within(card).findByText("Couldn't confirm connection"),+ ).toBeVisible();+ expect(within(card).queryByText("Connected")).toBeNull();+ expect(+ screen.getByRole("button", { name: "Connect Discord" }),+ ).toBeEnabled();++ fireEvent.click(card);const dialog = await screen.findByRole("dialog", { name: "Discord" });+ expect(within(dialog).getByText("Discord server")).toBeVisible();+ expect(within(dialog).queryByText("Duplicate server")).toBeNull();expect(- within(dialog).queryByText("Discord server"),- ).not.toBeInTheDocument();+ within(dialog).getByText(+ "Discord is authorized, but the Server couldn't be confirmed. Check again, or disconnect and reconnect.",+ ),+ ).toBeVisible();expect(- screen.queryByText(/Discord could not verify the authorized Server/),- ).not.toBeInTheDocument();- expect(screen.queryByLabelText("Discord Server ID")).toBeNull();+ within(dialog).getByRole("button", { name: "Disconnect Discord server" }),+ ).toBeVisible();+ fireEvent.click(+ within(dialog).getByRole("button", {+ name: "Check again Discord server",+ }),+ );+ await waitFor(() =>+ expect(check).toHaveBeenCalledWith("pending-discord", 4),+ );+ });++ it("asks to check again when another provider check is unconfirmed", async () => {+ const runtime = await testRuntime();+ const existing = (await runtime.client.listExternalConnections())+ .connections[0]!;+ vi.spyOn(runtime.client, "listExternalConnections").mockResolvedValue({+ connections: [+ {+ ...existing,+ status: "pending",+ status_error_code: "provider_identity_unavailable",+ },+ ],+ });++ renderPage(runtime, "/apps?app=gmail");++ const dialog = await screen.findByRole("dialog", { name: "Gmail" });expect(- within(dialog).getByRole("button", { name: "Connect Discord" }),- ).toBeEnabled();+ within(dialog).getByText(+ "The connection couldn't be confirmed yet. Check again.",+ ),+ ).toBeVisible();});it("lists a Gmail account that failed authorization for reconnecting", async () => {diff --git a/apps/web/src/features/apps/connected-apps-page.tsx b/apps/web/src/features/apps/connected-apps-page.tsxindex 889dde55..8ccedb89 100644--- a/apps/web/src/features/apps/connected-apps-page.tsx+++ b/apps/web/src/features/apps/connected-apps-page.tsx@@ -25,6 +25,7 @@ import {activeExternalConnections,externalConnectionNeedsAttention,openPendingExternalConnection,+ unconfirmedExternalConnections,} from "./connection-state";import {externalAppsQueryOptions,@@ -242,12 +243,15 @@ function CatalogAppCard({: null;const authorizing =createConnection.isPending || Boolean(createConnection.blockedConnectUrl);+ const unconfirmed = unconfirmedExternalConnections(connections);const summary =connectFlow.configured && app.availability === "unavailable"? "Unavailable": authorizing? "Authorizing…"- : appSummary(app);+ : unconfirmed.length+ ? "Couldn't confirm connection"+ : appSummary(app);return (<articlediff --git a/apps/web/src/features/apps/connection-state.test.ts b/apps/web/src/features/apps/connection-state.test.tsindex cdd890d5..3f638576 100644--- a/apps/web/src/features/apps/connection-state.test.ts+++ b/apps/web/src/features/apps/connection-state.test.ts@@ -7,6 +7,7 @@ import {activeExternalConnections,connectLinkOpen,establishedExternalConnections,+ unconfirmedExternalConnections,usableConnectUrl,} from "./connection-state";@@ -32,6 +33,8 @@ describe("external connection state projection", () => {connection("active", "active"),connection("pending", "pending"),connection("pending-error", "pending", "discord_guild_required"),+ connection("pending-retry", "pending", "provider_identity_unavailable"),+ connection("pending-duplicate", "pending", "duplicate_remote_principal"),connection("expired", "expired"),connection("failed", "failed"),connection("duplicate", "failed", "duplicate_remote_principal"),@@ -51,6 +54,12 @@ describe("external connection state projection", () => {establishedExternalConnections(connections).map((item) => item.id),).toEqual(["active", "disconnecting", "revoke-pending"]);});++ it("treats a pending connection with a check failure as unconfirmed, except a duplicate", () => {+ expect(+ unconfirmedExternalConnections(connections).map((item) => item.id),+ ).toEqual(["pending-error", "pending-retry"]);+ });});describe("Connect Link reuse", () => {diff --git a/apps/web/src/features/apps/connection-state.ts b/apps/web/src/features/apps/connection-state.tsindex ccdbd356..a4b4cc69 100644--- a/apps/web/src/features/apps/connection-state.ts+++ b/apps/web/src/features/apps/connection-state.ts@@ -39,6 +39,22 @@ export function establishedExternalConnections();}+/**+ * Pending connections whose identity check failed after authorization. They+ * stay listed so the user can check again or disconnect; a duplicate identity+ * is excluded because checking again cannot resolve it.+ */+export function unconfirmedExternalConnections(+ connections: TeamHubExternalConnection[],+) {+ return connections.filter(+ (connection) =>+ connection.status === "pending" &&+ Boolean(connection.status_error_code) &&+ connection.status_error_code !== "duplicate_remote_principal",+ );+}+export function activeExternalConnections(connections: TeamHubExternalConnection[],) {