初步集成消息通道,支持Telegram + Lark机器人

This commit is contained in:
xintaofei
2026-03-30 22:51:49 +08:00
parent 544abbd15d
commit d18cec33bf
44 changed files with 4106 additions and 11 deletions

View File

@@ -0,0 +1,5 @@
import { ChatChannelSettings } from "@/components/settings/chat-channel-settings"
export default function SettingsChatChannelsPage() {
return <ChatChannelSettings />
}

View File

@@ -0,0 +1,245 @@
"use client"
import { useCallback, useState } from "react"
import { Loader2 } from "lucide-react"
import { useTranslations } from "next-intl"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import {
Dialog,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog"
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select"
import { Switch } from "@/components/ui/switch"
import {
createChatChannel,
saveChatChannelToken,
} from "@/lib/api"
import type { ChannelType } from "@/lib/types"
interface AddChatChannelDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
onChannelAdded: () => void
}
export function AddChatChannelDialog({
open,
onOpenChange,
onChannelAdded,
}: AddChatChannelDialogProps) {
const t = useTranslations("ChatChannelSettings")
const [loading, setLoading] = useState(false)
const [error, setError] = useState<string | null>(null)
const [name, setName] = useState("")
const [channelType, setChannelType] = useState<ChannelType>("telegram")
const [token, setToken] = useState("")
const [chatId, setChatId] = useState("")
const [appId, setAppId] = useState("")
const [dailyReportEnabled, setDailyReportEnabled] = useState(false)
const [dailyReportTime, setDailyReportTime] = useState("18:00")
const resetForm = useCallback(() => {
setName("")
setChannelType("telegram")
setToken("")
setChatId("")
setAppId("")
setDailyReportEnabled(false)
setDailyReportTime("18:00")
setError(null)
}, [])
const handleOpenChange = useCallback(
(nextOpen: boolean) => {
if (!nextOpen) resetForm()
onOpenChange(nextOpen)
},
[onOpenChange, resetForm],
)
const handleSubmit = useCallback(async () => {
if (!name.trim()) {
setError(t("nameRequired"))
return
}
if (!token.trim()) {
setError(t("tokenRequired"))
return
}
if (!chatId.trim()) {
setError(t("chatIdRequired"))
return
}
setLoading(true)
setError(null)
try {
const configJson =
channelType === "lark"
? JSON.stringify({ app_id: appId, chat_id: chatId })
: JSON.stringify({ chat_id: chatId })
const channel = await createChatChannel({
name: name.trim(),
channelType,
configJson,
enabled: true,
dailyReportEnabled,
dailyReportTime: dailyReportEnabled ? dailyReportTime : null,
})
await saveChatChannelToken(channel.id, token.trim())
handleOpenChange(false)
onChannelAdded()
} catch (err) {
const msg = err instanceof Error ? err.message : String(err)
setError(msg)
} finally {
setLoading(false)
}
}, [
name,
token,
chatId,
channelType,
appId,
dailyReportEnabled,
dailyReportTime,
handleOpenChange,
onChannelAdded,
t,
])
return (
<Dialog open={open} onOpenChange={handleOpenChange}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle>{t("addChannel")}</DialogTitle>
</DialogHeader>
<div className="space-y-4">
<div className="space-y-1.5">
<label className="text-xs font-medium">{t("channelName")}</label>
<Input
value={name}
onChange={(e) => setName(e.target.value)}
placeholder={t("channelNamePlaceholder")}
/>
</div>
<div className="space-y-1.5">
<label className="text-xs font-medium">{t("channelType")}</label>
<Select
value={channelType}
onValueChange={(v) => setChannelType(v as ChannelType)}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="telegram">Telegram</SelectItem>
<SelectItem value="lark">
{t("lark")}
</SelectItem>
</SelectContent>
</Select>
</div>
{channelType === "lark" && (
<div className="space-y-1.5">
<label className="text-xs font-medium">App ID</label>
<Input
value={appId}
onChange={(e) => setAppId(e.target.value)}
placeholder="cli_xxxxx"
/>
</div>
)}
<div className="space-y-1.5">
<label className="text-xs font-medium">
{channelType === "telegram" ? "Bot Token" : "App Secret"}
</label>
<Input
type="password"
value={token}
onChange={(e) => setToken(e.target.value)}
placeholder={
channelType === "telegram"
? "123456:ABC-DEF..."
: "xxxxx"
}
/>
</div>
<div className="space-y-1.5">
<label className="text-xs font-medium">Chat ID</label>
<Input
value={chatId}
onChange={(e) => setChatId(e.target.value)}
placeholder={
channelType === "telegram" ? "-100123456789" : "oc_xxxxx"
}
/>
</div>
<div className="flex items-center justify-between">
<label className="text-xs font-medium">
{t("dailyReport")}
</label>
<Switch
checked={dailyReportEnabled}
onCheckedChange={setDailyReportEnabled}
/>
</div>
{dailyReportEnabled && (
<div className="space-y-1.5">
<label className="text-xs font-medium">
{t("dailyReportTime")}
</label>
<Input
type="time"
value={dailyReportTime}
onChange={(e) => setDailyReportTime(e.target.value)}
/>
</div>
)}
{error && (
<div className="rounded-md border border-red-500/30 bg-red-500/5 px-3 py-2 text-xs text-red-400">
{error}
</div>
)}
</div>
<DialogFooter>
<Button
variant="outline"
onClick={() => handleOpenChange(false)}
disabled={loading}
>
{t("cancel")}
</Button>
<Button onClick={handleSubmit} disabled={loading}>
{loading && <Loader2 className="h-3.5 w-3.5 animate-spin mr-1" />}
{t("create")}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}

View File

@@ -0,0 +1,300 @@
"use client"
import { useCallback, useEffect, useState } from "react"
import {
Loader2,
MessageCircle,
Plus,
Power,
PowerOff,
TestTube,
Trash2,
} from "lucide-react"
import { useTranslations } from "next-intl"
import { toast } from "sonner"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import { Switch } from "@/components/ui/switch"
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from "@/components/ui/alert-dialog"
import {
listChatChannels,
deleteChatChannel,
connectChatChannel,
disconnectChatChannel,
testChatChannel,
updateChatChannel,
getChatChannelStatus,
} from "@/lib/api"
import type { ChatChannelInfo, ChannelStatusInfo } from "@/lib/types"
import { AddChatChannelDialog } from "./add-chat-channel-dialog"
export function ChatChannelSettings() {
const t = useTranslations("ChatChannelSettings")
const [channels, setChannels] = useState<ChatChannelInfo[]>([])
const [statuses, setStatuses] = useState<ChannelStatusInfo[]>([])
const [loading, setLoading] = useState(true)
const [addDialogOpen, setAddDialogOpen] = useState(false)
const [deleteTarget, setDeleteTarget] = useState<ChatChannelInfo | null>(null)
const [actionLoading, setActionLoading] = useState<number | null>(null)
const loadChannels = useCallback(async () => {
try {
const [chs, sts] = await Promise.all([
listChatChannels(),
getChatChannelStatus().catch(() => []),
])
setChannels(chs)
setStatuses(sts)
} catch (err) {
toast.error(t("loadFailed"))
} finally {
setLoading(false)
}
}, [t])
useEffect(() => {
loadChannels().catch(console.error)
}, [loadChannels])
const handleToggleEnabled = useCallback(
async (ch: ChatChannelInfo) => {
try {
await updateChatChannel({ id: ch.id, enabled: !ch.enabled })
await loadChannels()
} catch (err) {
toast.error(t("saveFailed"))
}
},
[loadChannels, t],
)
const handleConnect = useCallback(
async (id: number) => {
setActionLoading(id)
try {
await connectChatChannel(id)
toast.success(t("connectSuccess"))
await loadChannels()
} catch (err) {
const msg = err instanceof Error ? err.message : String(err)
toast.error(t("connectFailed") + ": " + msg)
} finally {
setActionLoading(null)
}
},
[loadChannels, t],
)
const handleDisconnect = useCallback(
async (id: number) => {
setActionLoading(id)
try {
await disconnectChatChannel(id)
toast.success(t("disconnectSuccess"))
await loadChannels()
} catch (err) {
toast.error(t("disconnectFailed"))
} finally {
setActionLoading(null)
}
},
[loadChannels, t],
)
const handleTest = useCallback(
async (id: number) => {
setActionLoading(id)
try {
await testChatChannel(id)
toast.success(t("testSuccess"))
} catch (err) {
const msg = err instanceof Error ? err.message : String(err)
toast.error(t("testFailed") + ": " + msg)
} finally {
setActionLoading(null)
}
},
[t],
)
const handleDelete = useCallback(async () => {
if (!deleteTarget) return
try {
await deleteChatChannel(deleteTarget.id)
toast.success(t("deleteSuccess"))
setDeleteTarget(null)
await loadChannels()
} catch (err) {
toast.error(t("deleteFailed"))
}
}, [deleteTarget, loadChannels, t])
const getChannelStatus = (id: number) =>
statuses.find((s) => s.channel_id === id)?.status ?? "disconnected"
if (loading) {
return (
<div className="h-full flex items-center justify-center text-sm text-muted-foreground gap-2">
<Loader2 className="h-4 w-4 animate-spin" />
{t("loading")}
</div>
)
}
return (
<div className="h-full overflow-auto">
<div className="w-full space-y-4">
<section className="space-y-1">
<div className="flex items-center justify-between">
<div>
<h1 className="text-sm font-semibold">{t("sectionTitle")}</h1>
<p className="text-sm text-muted-foreground">
{t("sectionDescription")}
</p>
</div>
<Button size="sm" onClick={() => setAddDialogOpen(true)}>
<Plus className="h-3.5 w-3.5 mr-1" />
{t("addChannel")}
</Button>
</div>
</section>
{channels.length === 0 ? (
<section className="rounded-xl border bg-card p-8 text-center">
<MessageCircle className="h-8 w-8 mx-auto text-muted-foreground mb-2" />
<p className="text-sm text-muted-foreground">
{t("noChannels")}
</p>
</section>
) : (
<section className="space-y-2">
{channels.map((ch) => {
const status = getChannelStatus(ch.id)
const isConnected = status === "connected"
const isLoading = actionLoading === ch.id
return (
<div
key={ch.id}
className="rounded-xl border bg-card p-4 flex items-center gap-4"
>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2">
<span className="text-sm font-medium">{ch.name}</span>
<Badge variant="outline" className="text-xs">
{ch.channel_type}
</Badge>
<span
className={`inline-block h-2 w-2 rounded-full ${
isConnected
? "bg-green-500"
: status === "connecting"
? "bg-yellow-500 animate-pulse"
: status === "error"
? "bg-red-500"
: "bg-gray-400"
}`}
/>
</div>
<div className="flex items-center gap-3 mt-1">
{ch.daily_report_enabled && (
<span className="text-xs text-muted-foreground">
{t("dailyReport")}: {ch.daily_report_time || "18:00"}
</span>
)}
</div>
</div>
<div className="flex items-center gap-2">
<Switch
checked={ch.enabled}
onCheckedChange={() => handleToggleEnabled(ch)}
/>
{isConnected ? (
<Button
variant="ghost"
size="sm"
disabled={isLoading}
onClick={() => handleDisconnect(ch.id)}
>
{isLoading ? (
<Loader2 className="h-3.5 w-3.5 animate-spin" />
) : (
<PowerOff className="h-3.5 w-3.5" />
)}
</Button>
) : (
<Button
variant="ghost"
size="sm"
disabled={isLoading || !ch.enabled}
onClick={() => handleConnect(ch.id)}
>
{isLoading ? (
<Loader2 className="h-3.5 w-3.5 animate-spin" />
) : (
<Power className="h-3.5 w-3.5" />
)}
</Button>
)}
<Button
variant="ghost"
size="sm"
disabled={isLoading}
onClick={() => handleTest(ch.id)}
>
<TestTube className="h-3.5 w-3.5" />
</Button>
<Button
variant="ghost"
size="sm"
onClick={() => setDeleteTarget(ch)}
>
<Trash2 className="h-3.5 w-3.5 text-destructive" />
</Button>
</div>
</div>
)
})}
</section>
)}
</div>
<AddChatChannelDialog
open={addDialogOpen}
onOpenChange={setAddDialogOpen}
onChannelAdded={loadChannels}
/>
<AlertDialog
open={!!deleteTarget}
onOpenChange={(open) => !open && setDeleteTarget(null)}
>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>{t("deleteConfirmTitle")}</AlertDialogTitle>
<AlertDialogDescription>
{t("deleteConfirmMessage")}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>{t("cancel")}</AlertDialogCancel>
<AlertDialogAction onClick={handleDelete}>
{t("delete")}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
)
}

View File

@@ -12,6 +12,7 @@ import {
GitBranch,
Globe,
Keyboard,
MessageCircle,
Palette,
PlugZap,
Settings,
@@ -33,6 +34,7 @@ interface SettingsNavItem {
| "skills"
| "shortcuts"
| "version_control"
| "chat_channels"
| "system"
| "web_service"
icon: ComponentType<{ className?: string }>
@@ -69,6 +71,11 @@ const SETTINGS_NAV_ITEMS: SettingsNavItem[] = [
labelKey: "version_control",
icon: GitBranch,
},
{
href: "/settings/chat-channels",
labelKey: "chat_channels",
icon: MessageCircle,
},
{
href: "/settings/web-service",
labelKey: "web_service",

View File

@@ -92,6 +92,7 @@
"shortcuts": "Shortcuts",
"version_control": "Version Control",
"system": "System",
"chat_channels": "Chat Channels",
"web_service": "Web Service"
}
},
@@ -1670,5 +1671,36 @@
"emptyDirectory": "This directory is empty",
"errorLoadingDir": "Failed to load directory",
"permissionDenied": "Permission denied"
},
"ChatChannelSettings": {
"loading": "Loading...",
"sectionTitle": "Chat Channels",
"sectionDescription": "Configure IM bots to receive event notifications and query coding activity.",
"addChannel": "Add Channel",
"noChannels": "No chat channels configured yet.",
"channelName": "Name",
"channelNamePlaceholder": "My Telegram Bot",
"channelType": "Channel Type",
"lark": "Lark (Feishu)",
"dailyReport": "Daily Report",
"dailyReportTime": "Report Time",
"nameRequired": "Channel name is required.",
"tokenRequired": "Token is required.",
"chatIdRequired": "Chat ID is required.",
"loadFailed": "Failed to load channels.",
"saveFailed": "Failed to save changes.",
"connectSuccess": "Channel connected.",
"connectFailed": "Failed to connect",
"disconnectSuccess": "Channel disconnected.",
"disconnectFailed": "Failed to disconnect.",
"testSuccess": "Connection test passed.",
"testFailed": "Connection test failed",
"deleteSuccess": "Channel deleted.",
"deleteFailed": "Failed to delete channel.",
"deleteConfirmTitle": "Delete Channel",
"deleteConfirmMessage": "This will permanently delete the channel and its message logs. Are you sure?",
"cancel": "Cancel",
"delete": "Delete",
"create": "Create"
}
}

View File

@@ -92,6 +92,7 @@
"shortcuts": "快捷键",
"version_control": "版本控制",
"system": "系统",
"chat_channels": "消息渠道",
"web_service": "Web 服务"
}
},
@@ -1670,5 +1671,36 @@
"emptyDirectory": "此目录为空",
"errorLoadingDir": "加载目录失败",
"permissionDenied": "权限不足"
},
"ChatChannelSettings": {
"loading": "加载中...",
"sectionTitle": "消息渠道",
"sectionDescription": "配置 IM 机器人,接收事件通知和查询编码活动。",
"addChannel": "添加渠道",
"noChannels": "尚未配置任何消息渠道。",
"channelName": "名称",
"channelNamePlaceholder": "我的 Telegram 机器人",
"channelType": "渠道类型",
"lark": "飞书",
"dailyReport": "每日报告",
"dailyReportTime": "推送时间",
"nameRequired": "请输入渠道名称。",
"tokenRequired": "请输入 Token。",
"chatIdRequired": "请输入 Chat ID。",
"loadFailed": "加载渠道失败。",
"saveFailed": "保存失败。",
"connectSuccess": "渠道已连接。",
"connectFailed": "连接失败",
"disconnectSuccess": "渠道已断开。",
"disconnectFailed": "断开连接失败。",
"testSuccess": "连接测试通过。",
"testFailed": "连接测试失败",
"deleteSuccess": "渠道已删除。",
"deleteFailed": "删除渠道失败。",
"deleteConfirmTitle": "删除渠道",
"deleteConfirmMessage": "将永久删除该渠道及其消息日志,确定吗?",
"cancel": "取消",
"delete": "删除",
"create": "创建"
}
}

View File

@@ -54,6 +54,9 @@ import type {
McpMarketplaceProvider,
McpMarketplaceItem,
McpMarketplaceServerDetail,
ChatChannelInfo,
ChannelStatusInfo,
ChatChannelMessageLog,
} from "./types"
export async function listConversations(params?: {
@@ -1304,3 +1307,98 @@ export async function stopWebServer(): Promise<void> {
export async function getWebServerStatus(): Promise<WebServerInfo | null> {
return getTransport().call("get_web_server_status")
}
// ─── Chat Channels ───
export async function listChatChannels(): Promise<ChatChannelInfo[]> {
return getTransport().call("list_chat_channels")
}
export async function createChatChannel(params: {
name: string
channelType: string
configJson: string
enabled: boolean
dailyReportEnabled: boolean
dailyReportTime?: string | null
}): Promise<ChatChannelInfo> {
return getTransport().call("create_chat_channel", {
name: params.name,
channelType: params.channelType,
configJson: params.configJson,
enabled: params.enabled,
dailyReportEnabled: params.dailyReportEnabled,
dailyReportTime: params.dailyReportTime ?? null,
})
}
export async function updateChatChannel(params: {
id: number
name?: string | null
enabled?: boolean | null
configJson?: string | null
eventFilterJson?: string | null
dailyReportEnabled?: boolean | null
dailyReportTime?: string | null
}): Promise<ChatChannelInfo> {
return getTransport().call("update_chat_channel", {
id: params.id,
name: params.name ?? null,
enabled: params.enabled ?? null,
configJson: params.configJson ?? null,
eventFilterJson: params.eventFilterJson ?? null,
dailyReportEnabled: params.dailyReportEnabled ?? null,
dailyReportTime: params.dailyReportTime ?? null,
})
}
export async function deleteChatChannel(id: number): Promise<void> {
return getTransport().call("delete_chat_channel", { id })
}
export async function saveChatChannelToken(
channelId: number,
token: string,
): Promise<void> {
return getTransport().call("save_chat_channel_token", { channelId, token })
}
export async function getChatChannelHasToken(
channelId: number,
): Promise<boolean> {
return getTransport().call("get_chat_channel_has_token", { channelId })
}
export async function deleteChatChannelToken(
channelId: number,
): Promise<void> {
return getTransport().call("delete_chat_channel_token", { channelId })
}
export async function connectChatChannel(id: number): Promise<void> {
return getTransport().call("connect_chat_channel", { id })
}
export async function disconnectChatChannel(id: number): Promise<void> {
return getTransport().call("disconnect_chat_channel", { id })
}
export async function testChatChannel(id: number): Promise<void> {
return getTransport().call("test_chat_channel", { id })
}
export async function getChatChannelStatus(): Promise<ChannelStatusInfo[]> {
return getTransport().call("get_chat_channel_status")
}
export async function listChatChannelMessages(params: {
channelId: number
limit?: number
offset?: number
}): Promise<ChatChannelMessageLog[]> {
return getTransport().call("list_chat_channel_messages", {
channelId: params.channelId,
limit: params.limit ?? null,
offset: params.offset ?? null,
})
}

View File

@@ -841,3 +841,44 @@ export interface PreflightResult {
passed: boolean
checks: CheckItem[]
}
// ─── Chat Channels ───
export type ChannelType = "lark" | "telegram"
export type ChannelConnectionStatus =
| "connected"
| "connecting"
| "disconnected"
| "error"
export interface ChatChannelInfo {
id: number
name: string
channel_type: ChannelType
enabled: boolean
config_json: string
event_filter_json: string | null
daily_report_enabled: boolean
daily_report_time: string | null
created_at: string
updated_at: string
}
export interface ChannelStatusInfo {
channel_id: number
name: string
channel_type: ChannelType
status: ChannelConnectionStatus
}
export interface ChatChannelMessageLog {
id: number
channel_id: number
direction: "outbound" | "inbound"
message_type: string
content_preview: string
status: "sent" | "failed"
error_detail: string | null
created_at: string
}