2026-03-15 10:45:53 +00:00
package handler
import (
"context"
2026-07-27 12:21:13 +00:00
"errors"
2026-03-15 10:45:53 +00:00
"net/http"
feat(im,datasource): support Lark, Feishu's international edition
Lark and Feishu are the same product deployed on two isolated clouds
(open.larksuite.com and open.feishu.cn). WeKnora touches both from two
places — the IM bot and the Wiki data-source connector — and this brings
Lark to parity across both. Neither API surface differs, so rather than
duplicate either implementation, each is parametrized by a Region and
registered twice.
IM (internal/im/feishu):
Every API call routes through a.api(), which prefixes the region's
host, and the WebSocket client passes larkws.WithDomain — the SDK
defaults to open.feishu.cn, so Lark long connections would otherwise
fail to authenticate.
Data source (internal/datasource/connector/feishu):
Lark was half-supported: the client honoured a base_url override and a
LarkBaseURL constant existed, but the connector registered only as
"feishu" and the UI never exposed base_url, so Lark wikis could not be
configured at all. Lark is now its own connector type. base_url is kept
as an explicit override so data sources that pointed a "feishu"
connector at open.larksuite.com keep working.
Bugs found and fixed along the way:
- Wiki resource links were hardcoded to https://feishu.cn/wiki/{token} in
four places, so a Lark wiki linked into the wrong cloud entirely.
- Bot identity is now platform-prefixed (feishu:cli_x vs lark:cli_x).
BotIdentity carries a unique index, so without this a Lark channel
would be rejected as a duplicate of an unrelated Feishu bot sharing an
app_id.
- The card image cache is now keyed by app_id. image_keys are issued per
app on one cloud; a Feishu key handed to a Lark app fails the card
update with code=200570.
- The datasource doc claimed Lark "adapts automatically" — it could not,
since the UI had no way to reach base_url.
Permissions are where the clouds genuinely diverge. Identical APIs do not
mean identical permission catalogues: aily:file:read, aily:file:write and
corehr:file:download exist on Feishu but not on Lark, so pasting Feishu's
scope JSON into Lark fails to import. That JSON is also over-broad (it
covers products WeKnora never calls) and simultaneously incomplete (it
omits the drive:*/docx:* scopes the connector needs). Lark therefore gets
its own list, derived from the 17 endpoints the code actually calls and
checked identifier-by-identifier against Lark's own API reference, plus a
full Feishu→Lark mapping table marking each scope verified, unverified,
or absent. Both features use tenant_access_token only — no user_access_
token exists anywhere in the repo — so the user dimension stays empty.
Known limitation: Region.ThinkingText makes Lark's initial card
placeholder English, but once streaming starts the think-block headers
come from the shared MarkdownThinkStyle and are Chinese on every platform
(Lark, Slack, Telegram, Mattermost alike). Fixing that means threading a
locale through FormatIMDisplayContent, which has no platform context — a
cross-platform change, not a Lark one. Documented as such.
The channel-creation 400 message is now derived from validIMPlatforms so
the list cannot drift as platforms are added.
Tests: region invariants and per-region URL construction on both sides,
the Feishu/Lark bot-identity split, platform-to-channel mapping, base_url
override precedence, an end-to-end SendReply against a fake Open Platform
(token fetch, reply, thread-unsupported fallback, hard-error surfacing),
and a ListResources drive asserting wiki links never leak the other
cloud's host.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-16 15:34:53 +00:00
"sort"
2026-03-17 03:17:17 +00:00
"strings"
2026-03-15 10:45:53 +00:00
"github.com/Tencent/WeKnora/internal/im"
"github.com/Tencent/WeKnora/internal/logger"
2026-03-15 18:23:22 +00:00
"github.com/Tencent/WeKnora/internal/types"
2026-03-15 10:45:53 +00:00
"github.com/gin-gonic/gin"
2026-07-27 12:21:13 +00:00
"gorm.io/gorm"
2026-03-15 10:45:53 +00:00
)
2026-03-24 08:48:13 +00:00
// validIMPlatforms is the set of supported IM platforms.
2026-03-27 03:07:09 +00:00
var validIMPlatforms = map [ string ] bool {
feat(im,datasource): support Lark, Feishu's international edition
Lark and Feishu are the same product deployed on two isolated clouds
(open.larksuite.com and open.feishu.cn). WeKnora touches both from two
places — the IM bot and the Wiki data-source connector — and this brings
Lark to parity across both. Neither API surface differs, so rather than
duplicate either implementation, each is parametrized by a Region and
registered twice.
IM (internal/im/feishu):
Every API call routes through a.api(), which prefixes the region's
host, and the WebSocket client passes larkws.WithDomain — the SDK
defaults to open.feishu.cn, so Lark long connections would otherwise
fail to authenticate.
Data source (internal/datasource/connector/feishu):
Lark was half-supported: the client honoured a base_url override and a
LarkBaseURL constant existed, but the connector registered only as
"feishu" and the UI never exposed base_url, so Lark wikis could not be
configured at all. Lark is now its own connector type. base_url is kept
as an explicit override so data sources that pointed a "feishu"
connector at open.larksuite.com keep working.
Bugs found and fixed along the way:
- Wiki resource links were hardcoded to https://feishu.cn/wiki/{token} in
four places, so a Lark wiki linked into the wrong cloud entirely.
- Bot identity is now platform-prefixed (feishu:cli_x vs lark:cli_x).
BotIdentity carries a unique index, so without this a Lark channel
would be rejected as a duplicate of an unrelated Feishu bot sharing an
app_id.
- The card image cache is now keyed by app_id. image_keys are issued per
app on one cloud; a Feishu key handed to a Lark app fails the card
update with code=200570.
- The datasource doc claimed Lark "adapts automatically" — it could not,
since the UI had no way to reach base_url.
Permissions are where the clouds genuinely diverge. Identical APIs do not
mean identical permission catalogues: aily:file:read, aily:file:write and
corehr:file:download exist on Feishu but not on Lark, so pasting Feishu's
scope JSON into Lark fails to import. That JSON is also over-broad (it
covers products WeKnora never calls) and simultaneously incomplete (it
omits the drive:*/docx:* scopes the connector needs). Lark therefore gets
its own list, derived from the 17 endpoints the code actually calls and
checked identifier-by-identifier against Lark's own API reference, plus a
full Feishu→Lark mapping table marking each scope verified, unverified,
or absent. Both features use tenant_access_token only — no user_access_
token exists anywhere in the repo — so the user dimension stays empty.
Known limitation: Region.ThinkingText makes Lark's initial card
placeholder English, but once streaming starts the think-block headers
come from the shared MarkdownThinkStyle and are Chinese on every platform
(Lark, Slack, Telegram, Mattermost alike). Fixing that means threading a
locale through FormatIMDisplayContent, which has no platform context — a
cross-platform change, not a Lark one. Documented as such.
The channel-creation 400 message is now derived from validIMPlatforms so
the list cannot drift as platforms are added.
Tests: region invariants and per-region URL construction on both sides,
the Feishu/Lark bot-identity split, platform-to-channel mapping, base_url
override precedence, an end-to-end SendReply against a fake Open Platform
(token fetch, reply, thread-unsupported fallback, hard-error surfacing),
and a ListResources drive asserting wiki links never leak the other
cloud's host.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-16 15:34:53 +00:00
"wecom" : true , "feishu" : true , "lark" : true , "slack" : true , "telegram" : true , "dingtalk" : true ,
2026-07-20 05:52:27 +00:00
"mattermost" : true , "wechat" : true , "qqbot" : true , "yunzhijia" : true ,
2026-03-27 03:07:09 +00:00
}
2026-03-24 08:48:13 +00:00
feat(im,datasource): support Lark, Feishu's international edition
Lark and Feishu are the same product deployed on two isolated clouds
(open.larksuite.com and open.feishu.cn). WeKnora touches both from two
places — the IM bot and the Wiki data-source connector — and this brings
Lark to parity across both. Neither API surface differs, so rather than
duplicate either implementation, each is parametrized by a Region and
registered twice.
IM (internal/im/feishu):
Every API call routes through a.api(), which prefixes the region's
host, and the WebSocket client passes larkws.WithDomain — the SDK
defaults to open.feishu.cn, so Lark long connections would otherwise
fail to authenticate.
Data source (internal/datasource/connector/feishu):
Lark was half-supported: the client honoured a base_url override and a
LarkBaseURL constant existed, but the connector registered only as
"feishu" and the UI never exposed base_url, so Lark wikis could not be
configured at all. Lark is now its own connector type. base_url is kept
as an explicit override so data sources that pointed a "feishu"
connector at open.larksuite.com keep working.
Bugs found and fixed along the way:
- Wiki resource links were hardcoded to https://feishu.cn/wiki/{token} in
four places, so a Lark wiki linked into the wrong cloud entirely.
- Bot identity is now platform-prefixed (feishu:cli_x vs lark:cli_x).
BotIdentity carries a unique index, so without this a Lark channel
would be rejected as a duplicate of an unrelated Feishu bot sharing an
app_id.
- The card image cache is now keyed by app_id. image_keys are issued per
app on one cloud; a Feishu key handed to a Lark app fails the card
update with code=200570.
- The datasource doc claimed Lark "adapts automatically" — it could not,
since the UI had no way to reach base_url.
Permissions are where the clouds genuinely diverge. Identical APIs do not
mean identical permission catalogues: aily:file:read, aily:file:write and
corehr:file:download exist on Feishu but not on Lark, so pasting Feishu's
scope JSON into Lark fails to import. That JSON is also over-broad (it
covers products WeKnora never calls) and simultaneously incomplete (it
omits the drive:*/docx:* scopes the connector needs). Lark therefore gets
its own list, derived from the 17 endpoints the code actually calls and
checked identifier-by-identifier against Lark's own API reference, plus a
full Feishu→Lark mapping table marking each scope verified, unverified,
or absent. Both features use tenant_access_token only — no user_access_
token exists anywhere in the repo — so the user dimension stays empty.
Known limitation: Region.ThinkingText makes Lark's initial card
placeholder English, but once streaming starts the think-block headers
come from the shared MarkdownThinkStyle and are Chinese on every platform
(Lark, Slack, Telegram, Mattermost alike). Fixing that means threading a
locale through FormatIMDisplayContent, which has no platform context — a
cross-platform change, not a Lark one. Documented as such.
The channel-creation 400 message is now derived from validIMPlatforms so
the list cannot drift as platforms are added.
Tests: region invariants and per-region URL construction on both sides,
the Feishu/Lark bot-identity split, platform-to-channel mapping, base_url
override precedence, an end-to-end SendReply against a fake Open Platform
(token fetch, reply, thread-unsupported fallback, hard-error surfacing),
and a ListResources drive asserting wiki links never leak the other
cloud's host.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-16 15:34:53 +00:00
// invalidIMPlatformError is the 400 message listing the accepted platforms. It
// is derived from validIMPlatforms so the two cannot drift apart as platforms
// are added.
var invalidIMPlatformError = func ( ) string {
names := make ( [ ] string , 0 , len ( validIMPlatforms ) )
for p := range validIMPlatforms {
names = append ( names , "'" + p + "'" )
}
sort . Strings ( names )
return "platform must be one of: " + strings . Join ( names , ", " )
} ( )
2026-03-15 18:23:22 +00:00
// IMHandler handles IM platform callback requests and channel CRUD.
2026-03-15 10:45:53 +00:00
type IMHandler struct {
imService * im . Service
}
// NewIMHandler creates a new IM handler.
2026-03-15 18:23:22 +00:00
func NewIMHandler ( imService * im . Service ) * IMHandler {
2026-03-15 10:45:53 +00:00
return & IMHandler {
imService : imService ,
}
}
2026-03-15 18:23:22 +00:00
// ── Channel CRUD handlers ──
2026-03-15 10:45:53 +00:00
2026-03-15 18:23:22 +00:00
// CreateIMChannel creates a new IM channel for an agent.
func ( h * IMHandler ) CreateIMChannel ( c * gin . Context ) {
agentID := c . Param ( "id" )
if agentID == "" {
c . JSON ( http . StatusBadRequest , gin . H { "error" : "agent_id is required" } )
return
}
tenantID , ok := c . Request . Context ( ) . Value ( types . TenantIDContextKey ) . ( uint64 )
2026-03-15 10:45:53 +00:00
if ! ok {
2026-03-15 18:23:22 +00:00
c . JSON ( http . StatusUnauthorized , gin . H { "error" : "unauthorized" } )
2026-03-15 10:45:53 +00:00
return
}
2026-03-15 18:23:22 +00:00
var req struct {
2026-03-23 10:27:21 +00:00
Platform string ` json:"platform" binding:"required" `
Name string ` json:"name" `
Mode string ` json:"mode" `
OutputMode string ` json:"output_mode" `
KnowledgeBaseID string ` json:"knowledge_base_id" `
Credentials types . JSON ` json:"credentials" `
Enabled * bool ` json:"enabled" `
2026-03-15 18:23:22 +00:00
}
if err := c . ShouldBindJSON ( & req ) ; err != nil {
c . JSON ( http . StatusBadRequest , gin . H { "error" : err . Error ( ) } )
2026-03-15 10:45:53 +00:00
return
}
2026-03-24 08:48:13 +00:00
if ! validIMPlatforms [ req . Platform ] {
feat(im,datasource): support Lark, Feishu's international edition
Lark and Feishu are the same product deployed on two isolated clouds
(open.larksuite.com and open.feishu.cn). WeKnora touches both from two
places — the IM bot and the Wiki data-source connector — and this brings
Lark to parity across both. Neither API surface differs, so rather than
duplicate either implementation, each is parametrized by a Region and
registered twice.
IM (internal/im/feishu):
Every API call routes through a.api(), which prefixes the region's
host, and the WebSocket client passes larkws.WithDomain — the SDK
defaults to open.feishu.cn, so Lark long connections would otherwise
fail to authenticate.
Data source (internal/datasource/connector/feishu):
Lark was half-supported: the client honoured a base_url override and a
LarkBaseURL constant existed, but the connector registered only as
"feishu" and the UI never exposed base_url, so Lark wikis could not be
configured at all. Lark is now its own connector type. base_url is kept
as an explicit override so data sources that pointed a "feishu"
connector at open.larksuite.com keep working.
Bugs found and fixed along the way:
- Wiki resource links were hardcoded to https://feishu.cn/wiki/{token} in
four places, so a Lark wiki linked into the wrong cloud entirely.
- Bot identity is now platform-prefixed (feishu:cli_x vs lark:cli_x).
BotIdentity carries a unique index, so without this a Lark channel
would be rejected as a duplicate of an unrelated Feishu bot sharing an
app_id.
- The card image cache is now keyed by app_id. image_keys are issued per
app on one cloud; a Feishu key handed to a Lark app fails the card
update with code=200570.
- The datasource doc claimed Lark "adapts automatically" — it could not,
since the UI had no way to reach base_url.
Permissions are where the clouds genuinely diverge. Identical APIs do not
mean identical permission catalogues: aily:file:read, aily:file:write and
corehr:file:download exist on Feishu but not on Lark, so pasting Feishu's
scope JSON into Lark fails to import. That JSON is also over-broad (it
covers products WeKnora never calls) and simultaneously incomplete (it
omits the drive:*/docx:* scopes the connector needs). Lark therefore gets
its own list, derived from the 17 endpoints the code actually calls and
checked identifier-by-identifier against Lark's own API reference, plus a
full Feishu→Lark mapping table marking each scope verified, unverified,
or absent. Both features use tenant_access_token only — no user_access_
token exists anywhere in the repo — so the user dimension stays empty.
Known limitation: Region.ThinkingText makes Lark's initial card
placeholder English, but once streaming starts the think-block headers
come from the shared MarkdownThinkStyle and are Chinese on every platform
(Lark, Slack, Telegram, Mattermost alike). Fixing that means threading a
locale through FormatIMDisplayContent, which has no platform context — a
cross-platform change, not a Lark one. Documented as such.
The channel-creation 400 message is now derived from validIMPlatforms so
the list cannot drift as platforms are added.
Tests: region invariants and per-region URL construction on both sides,
the Feishu/Lark bot-identity split, platform-to-channel mapping, base_url
override precedence, an end-to-end SendReply against a fake Open Platform
(token fetch, reply, thread-unsupported fallback, hard-error surfacing),
and a ListResources drive asserting wiki links never leak the other
cloud's host.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-16 15:34:53 +00:00
c . JSON ( http . StatusBadRequest , gin . H { "error" : invalidIMPlatformError } )
2026-03-15 10:45:53 +00:00
return
}
2026-03-15 18:23:22 +00:00
channel := & im . IMChannel {
2026-03-17 03:17:17 +00:00
TenantID : tenantID ,
AgentID : agentID ,
Platform : req . Platform ,
Name : req . Name ,
Mode : req . Mode ,
OutputMode : req . OutputMode ,
KnowledgeBaseID : req . KnowledgeBaseID ,
Credentials : req . Credentials ,
Enabled : true ,
2026-03-15 18:23:22 +00:00
}
if req . Enabled != nil {
channel . Enabled = * req . Enabled
}
2026-03-23 10:27:21 +00:00
// WeChat uses long-polling mode and full output only
if req . Platform == "wechat" {
channel . Mode = "longpoll"
channel . OutputMode = "full"
} else {
if channel . Mode == "" {
2026-07-20 05:52:27 +00:00
if channel . Platform == "mattermost" || channel . Platform == "yunzhijia" {
2026-03-23 10:27:21 +00:00
channel . Mode = "webhook"
} else {
channel . Mode = "websocket"
}
}
if channel . OutputMode == "" {
channel . OutputMode = "stream"
2026-03-27 03:07:09 +00:00
}
2026-03-15 18:23:22 +00:00
}
if channel . Credentials == nil {
channel . Credentials = types . JSON ( "{}" )
}
if err := h . imService . CreateChannel ( channel ) ; err != nil {
logger . Errorf ( c . Request . Context ( ) , "[IM] Create channel failed: %v" , err )
2026-03-17 03:17:17 +00:00
if strings . HasPrefix ( err . Error ( ) , "duplicate_bot:" ) {
c . JSON ( http . StatusConflict , gin . H { "error" : strings . TrimPrefix ( err . Error ( ) , "duplicate_bot: " ) } )
return
}
2026-03-15 18:23:22 +00:00
c . JSON ( http . StatusInternalServerError , gin . H { "error" : "failed to create channel" } )
return
}
c . JSON ( http . StatusOK , gin . H { "data" : channel } )
}
// ListIMChannels lists all IM channels for an agent.
func ( h * IMHandler ) ListIMChannels ( c * gin . Context ) {
agentID := c . Param ( "id" )
if agentID == "" {
c . JSON ( http . StatusBadRequest , gin . H { "error" : "agent_id is required" } )
return
}
2026-03-17 03:17:17 +00:00
tenantID , ok := c . Request . Context ( ) . Value ( types . TenantIDContextKey ) . ( uint64 )
if ! ok {
c . JSON ( http . StatusUnauthorized , gin . H { "error" : "unauthorized" } )
return
}
channels , err := h . imService . ListChannelsByAgent ( agentID , tenantID )
2026-03-15 10:45:53 +00:00
if err != nil {
2026-03-15 18:23:22 +00:00
c . JSON ( http . StatusInternalServerError , gin . H { "error" : "failed to list channels" } )
2026-03-15 10:45:53 +00:00
return
}
2026-07-02 09:50:04 +00:00
c . JSON ( http . StatusOK , gin . H { "data" : im . SummarizeIMChannels ( channels ) } )
2026-03-15 18:23:22 +00:00
}
feat(im): tenant-wide IM channels overview under the user menu
Until now the IM channels a tenant has connected were only visible from
inside each agent's editor (AgentEditorModal → IMChannelPanel). Finding
out which bots are live across all agents meant clicking through every
one of them. Add a tenant-scoped overview so the set of connected IMs is
always one hop away from the avatar.
Backend
- im.Service.ListChannelsByTenant(tenantID) returns all non-deleted
channels in the tenant, LEFT JOIN'd with custom_agents.name so
built-in agents (which don't have rows in custom_agents) still show
up with an empty agent_name; the frontend substitutes a localized
"built-in agent" label.
- Credentials are intentionally stripped from this response — the list
view is read-only and the editor route (GET /agents/:id/im-channels)
remains the only source for secrets.
- New ChannelWithAgent DTO + IMHandler.ListAllIMChannels wired at
GET /api/v1/im-channels under the existing RegisterIMChannelRoutes
group, so auth middleware is inherited.
Frontend
- IMChannelsOverviewPanel.vue: floating submenu pane, stacked rows
(agent on top, channel below) with identical 20px avatars and 12px
labels so neither identity dominates. Each row is the whole click
target (jumps to the agent editor); the switch uses @click.stop to
toggle in place without triggering navigation.
- UserMenu.vue: new hover-driven submenu entry ("已接入的 IM" + link
icon). The pane is teleported to <body> because the sidebar container
has overflow:hidden that would otherwise clip right-flying content.
Position is computed from the menu item's rect and clamps/flips
against the viewport edges.
- "Live" indicator: a pulsing green dot on the menu item when at least
one channel is enabled. UserMenu prefetches the list once on mount;
the panel re-emits channels-changed after every load/toggle so the
dot stays in sync. Respects prefers-reduced-motion.
- AgentList.vue: supplement the existing onMounted-only
checkAndOpenEditModal with a watch(route.query.edit) so
router.push({ path: '/platform/agents', query: { edit, section } })
from an already-mounted AgentList (the common case when navigating
from the overview) opens the editor immediately instead of only
after a hard refresh.
Assets
- Seven platform SVGs under assets/img/im/, pulled from iconify
(simple-icons / logos / tdesign / icon-park / remix icon) and baked
with brand colors so monochrome sources (wecom/wechat/dingtalk/
feishu) don't render black.
i18n
- New imOverview namespace in zh-CN / en-US / ko-KR / ru-RU covering
the menu label, panel title/subtitle, column headers, builtin-agent
fallback, and the live-indicator tooltip.
Tested
- go build ./...
- go test ./internal/im/...
- vue-tsc --noEmit
- npm run build
2026-04-30 07:23:28 +00:00
// ListAllIMChannels lists every IM channel in the current tenant, across
// agents, for the cross-agent overview page. Credentials are intentionally
2026-07-02 09:50:04 +00:00
// NOT included in the response.
feat(im): tenant-wide IM channels overview under the user menu
Until now the IM channels a tenant has connected were only visible from
inside each agent's editor (AgentEditorModal → IMChannelPanel). Finding
out which bots are live across all agents meant clicking through every
one of them. Add a tenant-scoped overview so the set of connected IMs is
always one hop away from the avatar.
Backend
- im.Service.ListChannelsByTenant(tenantID) returns all non-deleted
channels in the tenant, LEFT JOIN'd with custom_agents.name so
built-in agents (which don't have rows in custom_agents) still show
up with an empty agent_name; the frontend substitutes a localized
"built-in agent" label.
- Credentials are intentionally stripped from this response — the list
view is read-only and the editor route (GET /agents/:id/im-channels)
remains the only source for secrets.
- New ChannelWithAgent DTO + IMHandler.ListAllIMChannels wired at
GET /api/v1/im-channels under the existing RegisterIMChannelRoutes
group, so auth middleware is inherited.
Frontend
- IMChannelsOverviewPanel.vue: floating submenu pane, stacked rows
(agent on top, channel below) with identical 20px avatars and 12px
labels so neither identity dominates. Each row is the whole click
target (jumps to the agent editor); the switch uses @click.stop to
toggle in place without triggering navigation.
- UserMenu.vue: new hover-driven submenu entry ("已接入的 IM" + link
icon). The pane is teleported to <body> because the sidebar container
has overflow:hidden that would otherwise clip right-flying content.
Position is computed from the menu item's rect and clamps/flips
against the viewport edges.
- "Live" indicator: a pulsing green dot on the menu item when at least
one channel is enabled. UserMenu prefetches the list once on mount;
the panel re-emits channels-changed after every load/toggle so the
dot stays in sync. Respects prefers-reduced-motion.
- AgentList.vue: supplement the existing onMounted-only
checkAndOpenEditModal with a watch(route.query.edit) so
router.push({ path: '/platform/agents', query: { edit, section } })
from an already-mounted AgentList (the common case when navigating
from the overview) opens the editor immediately instead of only
after a hard refresh.
Assets
- Seven platform SVGs under assets/img/im/, pulled from iconify
(simple-icons / logos / tdesign / icon-park / remix icon) and baked
with brand colors so monochrome sources (wecom/wechat/dingtalk/
feishu) don't render black.
i18n
- New imOverview namespace in zh-CN / en-US / ko-KR / ru-RU covering
the menu label, panel title/subtitle, column headers, builtin-agent
fallback, and the live-indicator tooltip.
Tested
- go build ./...
- go test ./internal/im/...
- vue-tsc --noEmit
- npm run build
2026-04-30 07:23:28 +00:00
func ( h * IMHandler ) ListAllIMChannels ( c * gin . Context ) {
tenantID , ok := c . Request . Context ( ) . Value ( types . TenantIDContextKey ) . ( uint64 )
if ! ok {
c . JSON ( http . StatusUnauthorized , gin . H { "error" : "unauthorized" } )
return
}
channels , err := h . imService . ListChannelsByTenant ( tenantID )
if err != nil {
c . JSON ( http . StatusInternalServerError , gin . H { "error" : "failed to list channels" } )
return
}
c . JSON ( http . StatusOK , gin . H { "data" : channels } )
}
2026-03-15 18:23:22 +00:00
// UpdateIMChannel updates an IM channel.
2026-05-11 09:37:14 +00:00
//
// UpdateIMChannel godoc
// @Summary 更新 IM 渠道
// @Description 更新指定 IM 渠道的名称、模式、知识库、凭证或启用状态
// @Tags IM 渠道
// @Accept json
// @Produce json
// @Param id path string true "渠道 ID"
// @Param request body map[string]interface{} true "更新字段( name/mode/output_mode/knowledge_base_id/credentials/enabled) "
// @Success 200 {object} map[string]interface{} "更新后的渠道"
// @Failure 400 {object} map[string]interface{} "请求参数错误"
// @Failure 404 {object} map[string]interface{} "渠道不存在"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /im-channels/{id} [put]
2026-03-15 18:23:22 +00:00
func ( h * IMHandler ) UpdateIMChannel ( c * gin . Context ) {
channelID := c . Param ( "id" )
if channelID == "" {
c . JSON ( http . StatusBadRequest , gin . H { "error" : "channel id is required" } )
return
}
2026-03-17 03:17:17 +00:00
tenantID , ok := c . Request . Context ( ) . Value ( types . TenantIDContextKey ) . ( uint64 )
if ! ok {
c . JSON ( http . StatusUnauthorized , gin . H { "error" : "unauthorized" } )
return
}
channel , err := h . imService . GetChannelByIDAndTenant ( channelID , tenantID )
2026-03-15 18:23:22 +00:00
if err != nil {
c . JSON ( http . StatusNotFound , gin . H { "error" : "channel not found" } )
return
}
var req struct {
2026-03-17 03:17:17 +00:00
Name * string ` json:"name" `
Mode * string ` json:"mode" `
OutputMode * string ` json:"output_mode" `
KnowledgeBaseID * string ` json:"knowledge_base_id" `
Credentials types . JSON ` json:"credentials" `
Enabled * bool ` json:"enabled" `
2026-06-24 11:27:39 +00:00
AgentID * string ` json:"agent_id" `
2026-03-15 18:23:22 +00:00
}
if err := c . ShouldBindJSON ( & req ) ; err != nil {
c . JSON ( http . StatusBadRequest , gin . H { "error" : err . Error ( ) } )
return
}
if req . Name != nil {
channel . Name = * req . Name
}
if req . Mode != nil {
channel . Mode = * req . Mode
}
if req . OutputMode != nil {
channel . OutputMode = * req . OutputMode
}
2026-03-17 03:17:17 +00:00
if req . KnowledgeBaseID != nil {
channel . KnowledgeBaseID = * req . KnowledgeBaseID
}
2026-03-15 18:23:22 +00:00
if req . Credentials != nil {
channel . Credentials = req . Credentials
}
if req . Enabled != nil {
channel . Enabled = * req . Enabled
}
2026-06-24 11:27:39 +00:00
if req . AgentID != nil {
newAgentID := strings . TrimSpace ( * req . AgentID )
if newAgentID != "" && newAgentID != channel . AgentID {
if err := h . imService . SetChannelAgentID ( c . Request . Context ( ) , channel , newAgentID ) ; err != nil {
logger . Errorf ( c . Request . Context ( ) , "[IM] Update channel agent failed: %v" , err )
c . JSON ( http . StatusBadRequest , gin . H { "error" : "agent not found" } )
return
}
}
}
2026-03-15 18:23:22 +00:00
if err := h . imService . UpdateChannel ( channel ) ; err != nil {
logger . Errorf ( c . Request . Context ( ) , "[IM] Update channel failed: %v" , err )
2026-03-17 03:17:17 +00:00
if strings . HasPrefix ( err . Error ( ) , "duplicate_bot:" ) {
c . JSON ( http . StatusConflict , gin . H { "error" : strings . TrimPrefix ( err . Error ( ) , "duplicate_bot: " ) } )
return
}
2026-03-15 18:23:22 +00:00
c . JSON ( http . StatusInternalServerError , gin . H { "error" : "failed to update channel" } )
return
}
c . JSON ( http . StatusOK , gin . H { "data" : channel } )
}
// DeleteIMChannel deletes an IM channel.
2026-05-11 09:37:14 +00:00
//
// DeleteIMChannel godoc
// @Summary 删除 IM 渠道
// @Description 删除指定 IM 渠道
// @Tags IM 渠道
// @Produce json
// @Param id path string true "渠道 ID"
// @Success 200 {object} map[string]interface{} "success: true"
// @Failure 400 {object} map[string]interface{} "请求参数错误"
// @Failure 404 {object} map[string]interface{} "渠道不存在"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /im-channels/{id} [delete]
2026-03-15 18:23:22 +00:00
func ( h * IMHandler ) DeleteIMChannel ( c * gin . Context ) {
channelID := c . Param ( "id" )
if channelID == "" {
c . JSON ( http . StatusBadRequest , gin . H { "error" : "channel id is required" } )
return
}
2026-03-17 03:17:17 +00:00
tenantID , ok := c . Request . Context ( ) . Value ( types . TenantIDContextKey ) . ( uint64 )
if ! ok {
c . JSON ( http . StatusUnauthorized , gin . H { "error" : "unauthorized" } )
return
}
if err := h . imService . DeleteChannel ( channelID , tenantID ) ; err != nil {
2026-03-15 18:23:22 +00:00
c . JSON ( http . StatusInternalServerError , gin . H { "error" : "failed to delete channel" } )
2026-03-15 10:45:53 +00:00
return
}
c . JSON ( http . StatusOK , gin . H { "success" : true } )
2026-03-15 18:23:22 +00:00
}
2026-03-15 10:45:53 +00:00
2026-03-15 18:23:22 +00:00
// ToggleIMChannel toggles the enabled state of an IM channel.
2026-05-11 09:37:14 +00:00
//
// ToggleIMChannel godoc
// @Summary 启用/停用 IM 渠道
// @Description 切换指定 IM 渠道的启用状态
// @Tags IM 渠道
// @Produce json
// @Param id path string true "渠道 ID"
// @Success 200 {object} map[string]interface{} "更新后的渠道"
// @Failure 400 {object} map[string]interface{} "请求参数错误"
// @Failure 404 {object} map[string]interface{} "渠道不存在"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /im-channels/{id}/toggle [post]
2026-03-15 18:23:22 +00:00
func ( h * IMHandler ) ToggleIMChannel ( c * gin . Context ) {
channelID := c . Param ( "id" )
if channelID == "" {
c . JSON ( http . StatusBadRequest , gin . H { "error" : "channel id is required" } )
return
}
2026-03-15 10:45:53 +00:00
2026-03-17 03:17:17 +00:00
tenantID , ok := c . Request . Context ( ) . Value ( types . TenantIDContextKey ) . ( uint64 )
if ! ok {
c . JSON ( http . StatusUnauthorized , gin . H { "error" : "unauthorized" } )
return
}
channel , err := h . imService . ToggleChannel ( channelID , tenantID )
2026-03-15 18:23:22 +00:00
if err != nil {
c . JSON ( http . StatusInternalServerError , gin . H { "error" : "failed to toggle channel" } )
return
}
2026-03-15 10:45:53 +00:00
2026-03-15 18:23:22 +00:00
c . JSON ( http . StatusOK , gin . H { "data" : channel } )
2026-03-15 10:45:53 +00:00
}
2026-07-20 05:52:27 +00:00
func writeIMCallbackACK ( c * gin . Context , platform string ) {
if platform == "yunzhijia" {
c . JSON ( http . StatusOK , gin . H {
"success" : true ,
"data" : gin . H {
"type" : 2 ,
"content" : "" ,
} ,
} )
return
}
c . JSON ( http . StatusOK , gin . H { "success" : true } )
}
2026-03-15 18:23:22 +00:00
// ── Callback handlers ──
// IMCallback handles IM platform callback requests for a specific channel.
// Route: POST /api/v1/im/callback/:channel_id
2026-05-11 09:37:14 +00:00
//
// IMCallback godoc
// @Summary IM 平台回调
// @Description 接收各 IM 平台的事件回调;走平台自身签名校验,不使用 API Key
// @Tags IM 回调
// @Accept json
// @Produce json
// @Param channel_id path string true "渠道 ID"
// @Success 200 {object} map[string]interface{} "处理结果"
// @Failure 400 {object} map[string]interface{} "请求参数错误"
// @Failure 401 {object} map[string]interface{} "签名校验失败"
// @Router /im/callback/{channel_id} [get]
// @Router /im/callback/{channel_id} [post]
2026-03-15 18:23:22 +00:00
func ( h * IMHandler ) IMCallback ( c * gin . Context ) {
2026-03-15 10:45:53 +00:00
ctx := c . Request . Context ( )
2026-03-15 18:23:22 +00:00
channelID := c . Param ( "channel_id" )
2026-03-15 10:45:53 +00:00
2026-07-27 12:21:13 +00:00
// Always validate the durable row before using a cached webhook adapter.
// This is the correctness fallback when a replica missed Redis invalidation
// while disconnected, and prevents stale credentials/config from being used.
adapter , channel , err := h . imService . EnsureChannelAdapter ( channelID )
if err != nil {
if errors . Is ( err , gorm . ErrRecordNotFound ) {
2026-03-15 18:23:22 +00:00
logger . Errorf ( ctx , "[IM] Channel not found for callback: %s" , channelID )
c . JSON ( http . StatusNotFound , gin . H { "error" : "channel not found" } )
return
}
2026-07-27 12:37:32 +00:00
if errors . Is ( err , im . ErrChannelDisabled ) {
logger . Errorf ( ctx , "[IM] Channel disabled for callback: %s" , channelID )
c . JSON ( http . StatusServiceUnavailable , gin . H { "error" : "channel is disabled" } )
return
}
2026-07-27 12:21:13 +00:00
logger . Errorf ( ctx , "[IM] Channel unavailable for callback %s: %v" , channelID , err )
c . JSON ( http . StatusServiceUnavailable , gin . H { "error" : "channel not available" } )
2026-03-15 10:45:53 +00:00
return
}
2026-03-27 03:07:09 +00:00
logger . Infof ( ctx , "[IM] Callback received platform=%s path_channel_id=%s" , channel . Platform , channelID )
2026-03-15 18:23:22 +00:00
// Handle URL verification
2026-03-15 10:45:53 +00:00
if adapter . HandleURLVerification ( c ) {
return
}
2026-03-15 18:23:22 +00:00
// Verify callback signature
2026-03-15 10:45:53 +00:00
if err := adapter . VerifyCallback ( c ) ; err != nil {
2026-03-15 18:23:22 +00:00
logger . Errorf ( ctx , "[IM] Callback verification failed for channel %s: %v" , channelID , err )
2026-03-15 10:45:53 +00:00
c . JSON ( http . StatusForbidden , gin . H { "error" : "verification failed" } )
return
}
// Parse the callback message
msg , err := adapter . ParseCallback ( c )
if err != nil {
2026-03-15 18:23:22 +00:00
logger . Errorf ( ctx , "[IM] Parse callback failed for channel %s: %v" , channelID , err )
2026-03-15 10:45:53 +00:00
c . JSON ( http . StatusBadRequest , gin . H { "error" : "parse failed" } )
return
}
2026-03-15 18:23:22 +00:00
// If nil, it's a non-message event - just acknowledge
2026-03-15 10:45:53 +00:00
if msg == nil {
2026-03-27 03:07:09 +00:00
if channel . Platform == "mattermost" {
logger . Infof ( ctx , "[IM] Mattermost callback ignored (no message): path_channel_id=%s — check: (1) trigger word must be the *first word* of the post; (2) if channel+trigger are both set, post must be in that channel; (3) bot_user_id must not match the sender" , channelID )
} else {
logger . Infof ( ctx , "[IM] Callback parsed no message to process platform=%s path_channel_id=%s" , channel . Platform , channelID )
}
2026-07-20 05:52:27 +00:00
writeIMCallbackACK ( c , channel . Platform )
2026-03-15 10:45:53 +00:00
return
}
2026-03-15 18:23:22 +00:00
// Respond immediately to avoid platform timeout
2026-07-20 05:52:27 +00:00
writeIMCallbackACK ( c , channel . Platform )
2026-03-15 10:45:53 +00:00
2026-03-15 18:23:22 +00:00
// Detach from gin request context
2026-03-15 10:45:53 +00:00
asyncCtx := context . WithoutCancel ( ctx )
2026-03-15 18:23:22 +00:00
// Process message asynchronously
2026-03-15 10:45:53 +00:00
go func ( ) {
2026-03-15 18:23:22 +00:00
if err := h . imService . HandleMessage ( asyncCtx , msg , channelID ) ; err != nil {
logger . Errorf ( asyncCtx , "[IM] Handle message error for channel %s: %v" , channelID , err )
2026-03-15 10:45:53 +00:00
}
} ( )
}