Skip to content

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

Go
14.0 KB
Raw Blame
package wecom

// wecom_resolvers.go — the ResolverSet the engine.Router routes through when
// the inbound channel_type is "wecom". Each interface method translates
// between the engine's normalized channel.InboundMessage and the wecom store
// / services. Platform-specific fields the normalized envelope does not carry
// (BotID, sender userid) come out of the wecom InboundMessage stashed in
// channel.InboundMessage.Raw.

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"strings"

	"github.com/jackc/pgx/v5"
	"github.com/jackc/pgx/v5/pgtype"

	"github.com/multica-ai/multica/server/internal/integrations/channel"
	"github.com/multica-ai/multica/server/internal/integrations/channel/engine"
	db "github.com/multica-ai/multica/server/pkg/db/generated"
	"github.com/multica-ai/multica/server/pkg/dbid"
)

// originWecomChat is the issue.origin_type label written for issues created
// via the wecom /issue command. Matches the "lark_chat" pattern (platform +
// "_chat") so analytics keeps the origin family consistent.
const originWecomChat = "wecom_chat"

// wecomMsgFromRaw decodes the wecom-side InboundMessage from
// channel.InboundMessage.Raw. Every resolver ends up doing this at least
// once; we centralize the JSON tag so a Raw shape change is a single-file
// edit.
func wecomMsgFromRaw(msg channel.InboundMessage) (InboundMessage, error) {
	if len(msg.Raw) == 0 {
		return InboundMessage{}, errors.New("wecom: inbound message Raw is empty")
	}
	var wm InboundMessage
	if err := json.Unmarshal(msg.Raw, &wm); err != nil {
		return InboundMessage{}, fmt.Errorf("wecom: decode inbound raw: %w", err)
	}
	return wm, nil
}

// NewResolverSet assembles the wecom ResolverSet from the store, the shared
// chat-session service, and an outbound replier. wecom has no typing-
// indicator affordance, so Typing is left nil — the Router treats a nil
// Typing as a no-op.
//
// The replier is optional: pass nil to disable outbound binding prompts.
// Media is optional too: pass nil when no object-storage backend is
// configured, and inbound attachments degrade to their placeholder text.
func NewResolverSet(
	store *Store,
	session engineSessionBinder,
	replier engine.OutboundReplier,
	media engine.MediaResolver,
) engine.ResolverSet {
	set := engine.ResolverSet{
		Installation: &installationResolver{store: store},
		Identity:     &identityResolver{store: store},
		Dedup:        NewDeduper(store),
		Session:      &sessionBinder{session: session},
		Audit:        &auditor{store: store},
		OriginType:   originWecomChat,
		// Assigned straight through: media is already an interface, so a nil
		// argument lands as a nil interface and the Router's `set.Media !=
		// nil` guard holds. (DingTalk guards the same assignment with an if,
		// which is redundant for that same reason — its media parameter is an
		// engine.MediaResolver too. The typed-nil hazard there is on the if
		// above it, where ack is a concrete *ackNotifier.)
		Media: media,
	}
	if replier != nil {
		set.Replier = replier
	}
	return set
}

// engineSessionBinder is the slice of engine.ChatSession the wecom binder
// drives. Declared as an interface so the platform-specific param mapping
// can be exercised with a fake in unit tests; *engine.ChatSession is the
// production value.
type engineSessionBinder interface {
	EnsureSession(ctx context.Context, in engine.EnsureSessionInput) (pgtype.UUID, error)
	StartSession(ctx context.Context, in engine.StartSessionInput) (engine.StartSessionResult, error)
	MarkPendingFresh(ctx context.Context, sessionID pgtype.UUID, messageID string) error
	AppendUserMessage(ctx context.Context, in engine.AppendInput) (engine.AppendResult, error)
	BindMediaRefs(ctx context.Context, in engine.BindMediaInput) error
}

func (r *sessionBinder) StartSession(ctx context.Context, p engine.StartSessionParams) (engine.StartSessionResult, error) {
	result, err := r.session.StartSession(ctx, engine.StartSessionInput{
		EnsureSessionInput: engine.EnsureSessionInput{
			WorkspaceID: p.Installation.WorkspaceID, AgentID: p.Installation.AgentID,
			InstallationID: p.Installation.ID, Sender: p.Creator,
			BindingKey: p.Message.Source.ChatID, ChatType: p.Message.Source.ChatType,
		},
		Initiator: p.Sender,
		Body:      p.Message.Text, CommandText: p.Message.CommandText, MessageID: p.Message.MessageID,
		ClaimToken: p.ClaimToken, MediaPendingSeconds: p.MediaPendingSeconds,
		PersistMessage: p.PersistMessage, HistoryBoundaryPending: p.HistoryBoundaryPending,
		BeforeCommit: p.BeforeCommit,
	})
	return engine.StartSessionResult{SessionID: result.SessionID, BindingID: result.BindingID, RouteRevision: result.RouteRevision, Append: result.Append}, err
}

// ---- installation routing ----

type installationResolver struct{ store *Store }

// ResolveInstallation looks up the wecom installation by the BotID carried
// on the inbound event. Every aibot_msg_callback frame identifies the bot
// via the WebSocket connection it arrived on (one bot per connection); the
// connector stamps BotID into InboundMessage.Raw so this resolver stays a
// pure DB lookup rather than needing socket-side plumbing.
func (r *installationResolver) ResolveInstallation(ctx context.Context, msg channel.InboundMessage) (engine.ResolvedInstallation, error) {
	wm, err := wecomMsgFromRaw(msg)
	if err != nil {
		return engine.ResolvedInstallation{}, err
	}
	if wm.BotID == "" {
		return engine.ResolvedInstallation{}, engine.ErrInstallationNotFound
	}
	inst, err := r.store.GetInstallationByBotID(ctx, wm.BotID)
	if err != nil {
		if errors.Is(err, pgx.ErrNoRows) {
			return engine.ResolvedInstallation{}, engine.ErrInstallationNotFound
		}
		return engine.ResolvedInstallation{}, err
	}
	return engine.ResolvedInstallation{
		ID:              inst.ID,
		WorkspaceID:     inst.WorkspaceID,
		AgentID:         inst.AgentID,
		InstallerUserID: inst.InstallerUserID,
		Active:          inst.Status == InstallationActive,
		Platform:        inst,
	}, nil
}

// ---- identity ----

type identityResolver struct{ store *Store }

// ResolveSender maps the WeCom smart-bot userid (the anonymized "T"-prefixed
// id the aibot API assigns per bot, from Source.SenderID) to a Multica user
// via the channel_user_binding table. First-time senders have no row and
// return engine.ErrSenderUnbound, which the Router pairs with the outbound
// binding prompt (see OutboundReplier.sendBindingPrompt).
//
// Why explicit binding rather than an implicit heuristic: aibot's userids
// have no relationship to real enterprise userids or emails — they are
// per-(bot, user) anonymized stable ids — so email-prefix matching (the
// pattern the internal customer-service adapter used) cannot work. See
// binding.go for the rationale.
//
// Membership re-check: the binding row's existence does NOT prove current
// workspace membership — a removed member's binding survives until an admin
// vacuums it. ErrSenderNotMember lets the Router drop silently rather than
// re-prompt (the correct product outcome, avoids leaking that a user was
// once a member).
func (r *identityResolver) ResolveSender(ctx context.Context, inst engine.ResolvedInstallation, msg channel.InboundMessage) (engine.ResolvedIdentity, error) {
	senderID := strings.TrimSpace(msg.Source.SenderID)
	if senderID == "" {
		return engine.ResolvedIdentity{}, engine.ErrSenderUnbound
	}
	binding, err := r.store.Queries.GetChannelUserBindingByUserID(ctx, db.GetChannelUserBindingByUserIDParams{
		InstallationID: inst.ID,
		ChannelUserID:  senderID,
	})
	if err != nil {
		if errors.Is(err, pgx.ErrNoRows) {
			return engine.ResolvedIdentity{}, engine.ErrSenderUnbound
		}
		return engine.ResolvedIdentity{}, err
	}
	isMember, err := r.store.IsWorkspaceMember(ctx, inst.WorkspaceID, binding.MulticaUserID)
	if err != nil {
		return engine.ResolvedIdentity{}, err
	}
	if !isMember {
		return engine.ResolvedIdentity{}, engine.ErrSenderNotMember
	}
	return engine.ResolvedIdentity{UserID: binding.MulticaUserID}, nil
}

// ---- dedup ----

// NewDeduper builds the claim store the Router and the adapter share. Both must
// go through it: they claim the same (installation, message) key on the same
// table, which is what keeps one message from being answered in both places.
func NewDeduper(store *Store) engine.Deduper { return &deduper{store: store} }

// deduper is the wecom Deduper. It uses the shared channel_inbound_message_dedup
// sqlc queries — the same table Feishu / Slack use — so the two-phase
// idempotency invariant is enforced uniformly across channels.
type deduper struct{ store *Store }

func (d *deduper) Claim(ctx context.Context, installationID pgtype.UUID, messageID string) (pgtype.UUID, error) {
	row, err := d.store.Queries.ClaimChannelInboundDedup(ctx, db.ClaimChannelInboundDedupParams{
		InstallationID: installationID,
		MessageID:      messageID,
	})
	if err != nil {
		if errors.Is(err, pgx.ErrNoRows) {
			return pgtype.UUID{}, engine.ErrDuplicate
		}
		return pgtype.UUID{}, err
	}
	return row.ClaimToken, nil
}

func (d *deduper) Mark(ctx context.Context, installationID pgtype.UUID, messageID string, claimToken pgtype.UUID) error {
	_, err := d.store.Queries.MarkChannelInboundDedupProcessed(ctx, db.MarkChannelInboundDedupProcessedParams{
		InstallationID: installationID,
		MessageID:      messageID,
		ClaimToken:     claimToken,
	})
	return err
}

func (d *deduper) Release(ctx context.Context, installationID pgtype.UUID, messageID string, claimToken pgtype.UUID) error {
	_, err := d.store.Queries.ReleaseChannelInboundDedup(ctx, db.ReleaseChannelInboundDedupParams{
		InstallationID: installationID,
		MessageID:      messageID,
		ClaimToken:     claimToken,
	})
	return err
}

// ---- session binding ----

type sessionBinder struct{ session engineSessionBinder }

// EnsureSession picks the wecom session-isolation key. For single (p2p)
// chats the wecom ChatID already IS the userid, one session per user;
// for group chats we key on the chatid so all group traffic lands in one
// session — the aibot API does not have a first-class thread concept.
func (r *sessionBinder) EnsureSession(ctx context.Context, p engine.EnsureSessionParams) (pgtype.UUID, error) {
	return r.session.EnsureSession(ctx, engine.EnsureSessionInput{
		WorkspaceID:    p.Installation.WorkspaceID,
		AgentID:        p.Installation.AgentID,
		InstallationID: p.Installation.ID,
		Sender:         p.Sender,
		BindingKey:     p.Message.Source.ChatID,
		ChatType:       p.Message.Source.ChatType,
	})
}

func (r *sessionBinder) MarkPendingFresh(ctx context.Context, sessionID pgtype.UUID, messageID string) error {
	return r.session.MarkPendingFresh(ctx, sessionID, messageID)
}

func (r *sessionBinder) AppendMessage(ctx context.Context, p engine.AppendParams) (engine.AppendResult, error) {
	// The adapter's own command source wins, and Text is only the fallback.
	// Overwriting it with Text — which this used to do — threw away the
	// mention-stripped line the adapter had already worked out, so in a group
	// the /issue parser was handed "@Multica Bot /issue …" and saw prose.
	// Same two lines as lark/feishu_resolvers.go:206 and slack/resolvers.go:337.
	commandText := p.Message.CommandText
	if commandText == "" {
		commandText = p.Message.Text
	}
	return r.session.AppendUserMessage(ctx, engine.AppendInput{
		SessionID:      p.SessionID,
		Sender:         p.Sender,
		InstallationID: p.InstallationID,
		Body:           p.Message.Text,
		CommandText:    commandText,
		MessageID:      p.Message.MessageID,
		ClaimToken:     p.ClaimToken,
		ForceFresh:     p.Message.ForceFresh,
		// How long the chat task waits before it runs. Without this the run
		// fires the moment the message lands and the agent is handed the
		// "[Image]" placeholder while the download is still going.
		MediaPendingSeconds: p.MediaPendingSeconds,
	})
}

// BindMedia attaches the objects the resolver stored to the message they came
// with. Until the media resolver existed this was correctly a no-op — there
// was nothing to bind — and returning nil reads to the Router as "bound
// fine", so leaving it that way once media resolves means every attachment is
// downloaded, decrypted, stored, and then silently discarded.
//
// IssueID is what makes an /issue turn's attachments belong to the issue
// rather than to the chat message that created it; the other issue fields are
// what let the description reference them. Feishu passes all of them
// (lark/feishu_resolvers.go:223).
func (r *sessionBinder) BindMedia(ctx context.Context, p engine.BindMediaParams) (engine.BindMediaResult, error) {
	in := engine.BindMediaInput{
		MessageID:            p.MessageID,
		SessionID:            p.SessionID,
		WorkspaceID:          p.WorkspaceID,
		Sender:               p.Sender,
		IssueID:              p.IssueID,
		IssueDescriptionBase: p.IssueDescriptionBase,
		IssueCommandText:     p.IssueCommandText,
		Body:                 p.Body,
		MediaRefs:            p.MediaRefs,
	}
	if richer, ok := r.session.(interface {
		BindMediaRefsWithResult(context.Context, engine.BindMediaInput) (engine.BindMediaResult, error)
	}); ok {
		return richer.BindMediaRefsWithResult(ctx, in)
	}
	return engine.BindMediaResult{}, r.session.BindMediaRefs(ctx, in)
}

// ---- audit ----

type auditor struct{ store *Store }

func (a *auditor) RecordDrop(ctx context.Context, instID pgtype.UUID, msg channel.InboundMessage, reason engine.DropReason) error {
	var eventType string
	if wm, err := wecomMsgFromRaw(msg); err == nil {
		eventType = wm.MsgType
	}
	var instIDArg pgtype.UUID
	if instID.Valid {
		instIDArg = instID
	}
	return a.store.Queries.RecordChannelInboundDrop(ctx, db.RecordChannelInboundDropParams{
		ID:               dbid.NewV7(),
		InstallationID:   instIDArg,
		ChannelType:      channelTypeWecom,
		ChannelChatID:    textOrNull(msg.Source.ChatID),
		EventType:        eventType,
		ChannelEventID:   textOrNull(msg.EventID),
		ChannelMessageID: textOrNull(msg.MessageID),
		DropReason:       string(reason),
	})
}

// textOrNull maps an empty string to a NULL pgtype.Text — the shared
// RecordChannelInboundDrop query uses sqlc.narg on the id columns so we
// need to pass NULL rather than "".
func textOrNull(s string) pgtype.Text {
	if s == "" {
		return pgtype.Text{}
	}
	return pgtype.Text{String: s, Valid: true}
}