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.
refactor(teamhub): look up a Discord channel's server through the typed client
shoudi zheng6a1d402f9ca2
diff --git a/apps/teamhub/internal/agentconnectedapps/confirmation.go b/apps/teamhub/internal/agentconnectedapps/confirmation.goindex 3fd4f13c..1597b3d1 100644--- a/apps/teamhub/internal/agentconnectedapps/confirmation.go+++ b/apps/teamhub/internal/agentconnectedapps/confirmation.go@@ -200,11 +200,6 @@ func (s *Service) readTool(ctx context.Context, connection externalsource.AgentTif !execution.Successful || !ok {return nil, &Error{Code: "tool_execution_failed", Message: "The connected application did not return the draft"}}- return toolData(data), nil-}--// toolData returns a read's own result object.-func toolData(data map[string]any) map[string]any {// Some tools wrap their result in their own execution envelope.if inner, ok := data["data"].(map[string]any); ok {if _, wrapped := data["successful"]; wrapped {@@ -214,7 +209,7 @@ func toolData(data map[string]any) map[string]any {if inner, ok := data["response_data"].(map[string]any); ok {data = inner}- return data+ return data, nil}func digestOf(value any) string {diff --git a/apps/teamhub/internal/agentconnectedapps/discord_scope.go b/apps/teamhub/internal/agentconnectedapps/discord_scope.goindex 9b7dda74..4e341c9d 100644--- a/apps/teamhub/internal/agentconnectedapps/discord_scope.go+++ b/apps/teamhub/internal/agentconnectedapps/discord_scope.go@@ -2,18 +2,13 @@ package agentconnectedappsimport ("context"+ "errors""net/http""github.com/simplexai-labs/linger/apps/teamhub/internal/composio""github.com/simplexai-labs/linger/apps/teamhub/internal/externalsource")-// discordChannelLookupVersion is the DISCORDBOT_GET_CHANNEL version TeamHub-// reads a channel's server with. It is pinned here, not taken from the-// Agent's call, so the scope check reads the response shape it was written-// against whatever version the Agent pins.-const discordChannelLookupVersion = "20261116_00"-// discordScope says what each Discord read names: nothing beyond the// connected server, a server by guild_id, or a channel or thread by// channel_id. The managed Discord bot is one application shared by every@@ -61,19 +56,13 @@ func (s *Service) discordReadInScope(ctx context.Context, connection externalsouif channelID == "" || connection.RemoteTeamID == "" {return false, nil}- execution, err := s.provider.ExecuteTool(ctx, connection.UpstreamConnectionID, connection.UserID,- "DISCORDBOT_GET_CHANNEL", discordChannelLookupVersion, map[string]any{"channel_id": channelID})+ guildID, err := s.provider.GetDiscordChannelGuild(ctx, connection.UpstreamConnectionID, channelID)if err != nil {- if refusedLookup(err) {+ if errors.Is(err, composio.ErrDiscordToolRefused) || errors.Is(err, composio.ErrDiscordChannelGuildUnknown) || refusedLookup(err) {return false, nil}return false, mapToolError(&providerOperationError{phase: "discord_channel_lookup", err: err}, "execute")}- data, ok := execution.Data.(map[string]any)- if !execution.Successful || !ok {- return false, nil- }- guildID, _ := toolData(data)["guild_id"].(string)return guildID == connection.RemoteTeamID, nildefault:return false, nildiff --git a/apps/teamhub/internal/agentconnectedapps/discord_scope_test.go b/apps/teamhub/internal/agentconnectedapps/discord_scope_test.goindex 90547bb2..e7224419 100644--- a/apps/teamhub/internal/agentconnectedapps/discord_scope_test.go+++ b/apps/teamhub/internal/agentconnectedapps/discord_scope_test.go@@ -3,6 +3,7 @@ package agentconnectedappsimport ("context""errors"+ "fmt""net/http""reflect""strings"@@ -22,9 +23,10 @@ type discordCall struct {type discordProvider struct {fakeToolProvidertool composio.Tool- lookup composio.ToolExecution+ lookup stringlookupErr errorcalls []discordCall+ lookups []string}func (provider *discordProvider) GetTool(context.Context, string, string) (composio.Tool, error) {@@ -33,12 +35,14 @@ func (provider *discordProvider) GetTool(context.Context, string, string) (compofunc (provider *discordProvider) ExecuteTool(_ context.Context, _, _, slug, version string, arguments map[string]any) (composio.ToolExecution, error) {provider.calls = append(provider.calls, discordCall{slug: slug, version: version, arguments: arguments})- if slug == "DISCORDBOT_GET_CHANNEL" && version == discordChannelLookupVersion {- return provider.lookup, provider.lookupErr- }return composio.ToolExecution{Successful: true, Data: map[string]any{"ok": true}}, nil}+func (provider *discordProvider) GetDiscordChannelGuild(_ context.Context, connectedAccountID, channelID string) (string, error) {+ provider.lookups = append(provider.lookups, connectedAccountID+"/"+channelID)+ return provider.lookup, provider.lookupErr+}+// ran reports whether the Agent's own call reached the provider.func (provider *discordProvider) ran() bool {for _, call := range provider.calls {@@ -61,10 +65,6 @@ func executeDiscord(t *testing.T, provider *discordProvider, slug, remoteTeamID}, func(context.Context) (externalsource.AgentToolConnection, error) { return connection, nil })}-func channelIn(guildID string) composio.ToolExecution {- return composio.ToolExecution{Successful: true, Data: map[string]any{"id": "c1", "guild_id": guildID}}-}-func TestDiscordReadsOfEveryKindAreScoped(t *testing.T) {for slug := range readTools {if strings.HasPrefix(slug, "DISCORDBOT_") && discordReadScopes[slug] == 0 {@@ -81,7 +81,7 @@ func TestDiscordReadsOfEveryKindAreScoped(t *testing.T) {func TestDiscordConnectedGuildReadRunsWithoutLookup(t *testing.T) {provider := &discordProvider{}result, err := executeDiscord(t, provider, "DISCORDBOT_GET_CONNECTED_GUILD", "g1", map[string]any{})- if err != nil || result.Confirmation != nil || len(provider.calls) != 1 || !provider.ran() {+ if err != nil || result.Confirmation != nil || len(provider.calls) != 1 || !provider.ran() || len(provider.lookups) != 0 {t.Fatalf("result=%+v err=%v calls=%+v", result, err, provider.calls)}}@@ -110,29 +110,23 @@ func TestDiscordGuildReadRunsOnlyInTheConnectedGuild(t *testing.T) {}func TestDiscordChannelReadLooksUpTheChannelsGuild(t *testing.T) {- provider := &discordProvider{lookup: composio.ToolExecution{Successful: true, Data: map[string]any{- "successful": true, "data": map[string]any{"guild_id": "g1"},- }}}+ provider := &discordProvider{lookup: "g1"}result, err := executeDiscord(t, provider, "DISCORDBOT_LIST_MESSAGES", "g1", map[string]any{"channel_id": "c1", "limit": 5})- if err != nil || result.Confirmation != nil || !provider.ran() || len(provider.calls) != 2 {- t.Fatalf("result=%+v err=%v calls=%+v", result, err, provider.calls)- }- lookup := provider.calls[0]- if lookup.slug != "DISCORDBOT_GET_CHANNEL" || lookup.version != discordChannelLookupVersion ||- !reflect.DeepEqual(lookup.arguments, map[string]any{"channel_id": "c1"}) {- t.Fatalf("lookup=%+v", lookup)+ if err != nil || result.Confirmation != nil || !provider.ran() || len(provider.calls) != 1 ||+ !reflect.DeepEqual(provider.lookups, []string{"ca-1/c1"}) {+ t.Fatalf("result=%+v err=%v calls=%+v lookups=%v", result, err, provider.calls, provider.lookups)}}func TestDiscordChannelReadOutsideTheGuildIsHeld(t *testing.T) {for name, provider := range map[string]*discordProvider{- "another guild": {lookup: channelIn("g2")},- "no guild": {lookup: composio.ToolExecution{Successful: true, Data: map[string]any{"id": "c1"}}},- "unsuccessful": {lookup: composio.ToolExecution{Successful: false}},+ "another guild": {lookup: "g2"},+ "no guild": {lookupErr: composio.ErrDiscordChannelGuildUnknown},+ "unsuccessful": {lookupErr: fmt.Errorf("Composio get Discord channel failed: %w", composio.ErrDiscordToolRefused)},"forbidden": {lookupErr: composio.RemoteStatusError("execute tool", http.StatusForbidden)},"not found": {lookupErr: composio.RemoteStatusError("execute tool", http.StatusNotFound)},- "bad argument": {lookup: channelIn("g1")},- "no remote guild": {lookup: channelIn("")},+ "bad argument": {lookup: "g1"},+ "no remote guild": {lookup: ""},} {arguments, remote := map[string]any{"channel_id": "c1"}, "g1"switch name {@@ -155,6 +149,7 @@ func TestDiscordChannelLookupFailureIsReturned(t *testing.T) {}{"server error": {composio.RemoteStatusError("execute tool", http.StatusBadGateway), "provider_unavailable"},"rate limited": {composio.RemoteStatusError("execute tool", http.StatusTooManyRequests), "provider_rate_limited"},+ "rate limit": {&composio.RateLimitError{Operation: "get Discord channel"}, "provider_rate_limited"},"timeout": {context.DeadlineExceeded, "provider_unavailable"},} {provider := &discordProvider{lookupErr: test.err}diff --git a/apps/teamhub/internal/agentconnectedapps/service.go b/apps/teamhub/internal/agentconnectedapps/service.goindex fc121023..2f957250 100644--- a/apps/teamhub/internal/agentconnectedapps/service.go+++ b/apps/teamhub/internal/agentconnectedapps/service.go@@ -49,6 +49,7 @@ type ToolProvider interface {GetTool(context.Context, string, string) (composio.Tool, error)ExecuteTool(context.Context, string, string, string, string, map[string]any) (composio.ToolExecution, error)GetConnectionStatusForToolkit(context.Context, string, string) (composio.ConnectionStatus, error)+ GetDiscordChannelGuild(context.Context, string, string) (string, error)}type Service struct {diff --git a/apps/teamhub/internal/agentconnectedapps/service_test.go b/apps/teamhub/internal/agentconnectedapps/service_test.goindex 23550810..7f7aa52e 100644--- a/apps/teamhub/internal/agentconnectedapps/service_test.go+++ b/apps/teamhub/internal/agentconnectedapps/service_test.go@@ -207,6 +207,10 @@ func (*fakeToolProvider) GetConnectionStatusForToolkit(context.Context, string,return composio.ConnectionActive, nil}+func (*fakeToolProvider) GetDiscordChannelGuild(context.Context, string, string) (string, error) {+ return "", errors.New("unexpected Discord channel lookup")+}+func tool(slug, toolkit string) composio.Tool {result := composio.Tool{Slug: slug, Version: "20260817_01", Name: slug,diff --git a/apps/teamhub/internal/composio/apps_test.go b/apps/teamhub/internal/composio/apps_test.goindex ef5bc481..65161cd7 100644--- a/apps/teamhub/internal/composio/apps_test.go+++ b/apps/teamhub/internal/composio/apps_test.go@@ -398,3 +398,63 @@ func assertProxyParameter(t *testing.T, requests []proxyRequest, endpoint, name,}t.Fatalf("missing %s=%s query parameter for %s: %+v", name, value, endpoint, requests)}++func TestDiscordChannelGuildReadsPinnedChannelTool(t *testing.T) {+ var request discordToolRequest+ 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_CHANNEL" {+ t.Errorf("unexpected request %s %s", r.Method, r.URL.Path)+ }+ if err := json.NewDecoder(r.Body).Decode(&request); err != nil {+ t.Error(err)+ }+ _ = json.NewEncoder(w).Encode(map[string]any{"successful": true, "data": map[string]any{"id": "c1", "guild_id": "g1"}})+ })+ guildID, err := client.GetDiscordChannelGuild(context.Background(), "discord-account", "c1")+ want := discordToolRequest{ConnectedAccountID: "discord-account", UserID: "binding-user", Version: discordToolVersion, Arguments: map[string]any{"channel_id": "c1"}}+ if err != nil || guildID != "g1" || !reflect.DeepEqual(request, want) {+ t.Fatalf("guild=%q err=%v request=%+v", guildID, err, request)+ }+}++func TestDiscordChannelGuildClassifiesFailures(t *testing.T) {+ for name, response := range map[string]map[string]any{+ "missing guild": {"successful": true, "data": map[string]any{"id": "c1"}},+ "non-string guild": {"successful": true, "data": map[string]any{"id": "c1", "guild_id": 7}},+ "refused": {"successful": false, "data": map[string]any{"message": "no"}},+ "forbidden": {"successful": false, "data": map[string]any{"status_code": 403}},+ "rate limited": {"successful": false, "data": map[string]any{"status_code": 429}},+ } {+ t.Run(name, func(t *testing.T) {+ client := newDiscordIdentityTestClient(t, func(w http.ResponseWriter, _ *http.Request) {+ _ = json.NewEncoder(w).Encode(response)+ })+ guildID, err := client.GetDiscordChannelGuild(context.Background(), "discord-account", "c1")+ status, _ := ErrorStatus(err)+ var limited *RateLimitError+ var ok bool+ switch name {+ case "missing guild", "non-string guild":+ ok = errors.Is(err, ErrDiscordChannelGuildUnknown)+ case "refused":+ ok = errors.Is(err, ErrDiscordToolRefused)+ case "forbidden":+ ok = status == http.StatusForbidden && !errors.Is(err, ErrDiscordToolRefused)+ case "rate limited":+ ok = errors.As(err, &limited)+ }+ if !ok || guildID != "" {+ t.Fatalf("guild=%q err=%v", guildID, err)+ }+ })+ }+}++func TestDiscordChannelGuildRequiresChannelID(t *testing.T) {+ client := newDiscordIdentityTestClient(t, func(http.ResponseWriter, *http.Request) {+ t.Error("empty channel id reached Composio")+ })+ if _, err := client.GetDiscordChannelGuild(context.Background(), "discord-account", ""); err == nil {+ t.Fatal("empty channel id was accepted")+ }+}diff --git a/apps/teamhub/internal/composio/discord.go b/apps/teamhub/internal/composio/discord.goindex a4101b95..b81dce91 100644--- a/apps/teamhub/internal/composio/discord.go+++ b/apps/teamhub/internal/composio/discord.go@@ -20,6 +20,13 @@ type DiscordIdentity struct {var (ErrDiscordGuildRequired = errors.New("Discord server must be selected")ErrDiscordGuildNotAccessible = errors.New("Discord server is not accessible")+ // ErrDiscordToolRefused marks a Discord tool execution that Composio+ // reported unsuccessful without a status code, so callers can tell a+ // refusal from a transient failure without reading its text.+ ErrDiscordToolRefused = errors.New("Discord tool execution was refused")+ // ErrDiscordChannelGuildUnknown marks a channel lookup that succeeded but+ // did not name the channel's server.+ ErrDiscordChannelGuildUnknown = errors.New("Discord channel response was incomplete"))type DiscordChannel struct {@@ -89,7 +96,7 @@ func (c *Client) executeDiscordTool(ctx context.Context, connectedAccountID, slucase failure.StatusCode > 0:return &remoteError{operation: operation, status: failure.StatusCode}default:- return fmt.Errorf("Composio %s failed", operation)+ return fmt.Errorf("Composio %s failed: %w", operation, ErrDiscordToolRefused)}}if err := decodeDiscordToolData(response.Data, target); err != nil {@@ -168,6 +175,26 @@ func (c *Client) GetDiscordGuild(ctx context.Context, connectedAccountID, guildIreturn DiscordIdentity{GuildID: wire.ID, GuildName: wire.Name}, nil}+// GetDiscordChannelGuild returns the server a channel or thread belongs to.+// A response without a string guild_id fails with+// ErrDiscordChannelGuildUnknown.+func (c *Client) GetDiscordChannelGuild(ctx context.Context, connectedAccountID, channelID string) (string, error) {+ if channelID == "" {+ return "", errors.New("Discord channel id is required")+ }+ var wire struct {+ GuildID any `json:"guild_id"`+ }+ if err := c.executeDiscordTool(ctx, connectedAccountID, "DISCORDBOT_GET_CHANNEL", map[string]any{"channel_id": channelID}, &wire, "get Discord channel"); err != nil {+ return "", err+ }+ guildID, _ := wire.GuildID.(string)+ if guildID == "" {+ return "", ErrDiscordChannelGuildUnknown+ }+ return guildID, nil+}+func (c *Client) ListDiscordChannels(ctx context.Context, connectedAccountID, guildID string) ([]DiscordChannel, error) {var wire struct {Channels []struct {diff --git a/apps/teamhub/internal/externalsource/lifecycle_test.go b/apps/teamhub/internal/externalsource/lifecycle_test.goindex fc6c9273..3f9a12e5 100644--- a/apps/teamhub/internal/externalsource/lifecycle_test.go+++ b/apps/teamhub/internal/externalsource/lifecycle_test.go@@ -23,6 +23,11 @@ func TestConnectionIdentityFailurePolicyRequiresDiscordGuildWithoutRapidRetry(tif code != "provider_identity_unavailable" || retryAfter != time.Minute || failConnection {t.Fatalf("fallback policy=(%q,%s,%t)", code, retryAfter, failConnection)}+ refused := fmt.Errorf("Composio identify Discord installation failed: %w", composio.ErrDiscordToolRefused)+ code, retryAfter, failConnection = connectionIdentityFailurePolicy("discord", refused)+ if code != "provider_identity_unavailable" || retryAfter != time.Minute || failConnection {+ t.Fatalf("refused Discord tool policy=(%q,%s,%t)", code, retryAfter, failConnection)+ }}func TestConnectionIdentityFailurePolicyFailsInsufficientPermission(t *testing.T) {diff --git a/apps/teamhub/tests/integration/connected_apps_execution_lease_test.go b/apps/teamhub/tests/integration/connected_apps_execution_lease_test.goindex fa81b5bb..88e16e00 100644--- a/apps/teamhub/tests/integration/connected_apps_execution_lease_test.go+++ b/apps/teamhub/tests/integration/connected_apps_execution_lease_test.go@@ -146,6 +146,10 @@ type leaseProbeToolProvider struct {func (p *leaseProbeToolProvider) SearchTools(context.Context, composio.ToolSearchRequest) ([]composio.Tool, error) {return nil, nil}+func (p *leaseProbeToolProvider) GetDiscordChannelGuild(context.Context, string, string) (string, error) {+ p.probe("discord_channel_lookup")+ return "", errors.New("unexpected Discord channel lookup")+}func (p *leaseProbeToolProvider) GetConnectionStatusForToolkit(context.Context, string, string) (composio.ConnectionStatus, error) {p.probe("connection_status")return composio.ConnectionActive, nildiff --git a/apps/teamhub/tests/integration/connector_confirmation_test.go b/apps/teamhub/tests/integration/connector_confirmation_test.goindex 36079a89..cc8ae34a 100644--- a/apps/teamhub/tests/integration/connector_confirmation_test.go+++ b/apps/teamhub/tests/integration/connector_confirmation_test.go@@ -400,6 +400,9 @@ type confirmationToolProvider struct {func (p *confirmationToolProvider) SearchTools(context.Context, composio.ToolSearchRequest) ([]composio.Tool, error) {return nil, nil}+func (p *confirmationToolProvider) GetDiscordChannelGuild(context.Context, string, string) (string, error) {+ return "", errors.New("unexpected Discord channel lookup")+}func (p *confirmationToolProvider) GetConnectionStatusForToolkit(context.Context, string, string) (composio.ConnectionStatus, error) {return composio.ConnectionActive, nil}