feat: 多 IM 远程桥接系统 + Bridge 一级导航 + bug 修复
**Bridge 系统核心(src/lib/bridge/)** - bridge-manager: 生命周期编排、adapter 事件循环、会话级并发控制 - channel-adapter: 抽象基类 + 注册式 adapter 工厂 - channel-router: IM 地址 → CodePilot session 自动映射 - conversation-engine: 服务端消费 streamClaude() SSE 流 - permission-broker: 权限请求转发到 IM 内联按钮 - delivery-layer: 出站分片、限流、重试退避、HTML 降级 - telegram-adapter: Telegram 长轮询 + offset 安全水位 + 幂等去重 - security/: 路径校验、危险输入检测、滑动窗口限流 **Telegram 通知 Bot(src/lib/telegram-bot.ts)** - 独立通知模式,与 bridge 模式互斥 - bridgeModeActive 使用 globalThis 存储,避免 HMR 重置导致轮询冲突 **API 路由** - /api/bridge: GET 状态查询 + POST start/stop/auto-start - /api/bridge/channels: 活跃通道列表 - /api/bridge/settings: bridge 设置读写 - /api/settings/telegram: 凭据管理(含 allowed_users 白名单) - /api/settings/telegram/verify: 连接验证 + chat ID 自动检测 **UI 重构:Bridge 提升为一级导航** - NavRail 新增 Bridge 图标导航项 - /bridge 页面:BridgeLayout hash 路由,Bridge + Telegram 两个子 tab - BridgeSection: 总开关、状态、启停、通道开关、适配器状态、默认设置 - TelegramBridgeSection: 凭据配置 + 白名单 + Setup Guide(6 步) - Settings 移除 Telegram 和 Bridge tab,只保留 4 个核心 tab **Bug 修复** - bridge-manager: runAdapterLoop 在 state.running=true 之前被调用, while 条件同步求值为 false 导致消费者循环不启动。修复为先设 running 再启动 loop - telegram-bot: bridgeModeActive 改用 globalThis 防止 HMR 丢失状态 - settings/telegram route: TELEGRAM_KEYS 补充 telegram_bridge_allowed_users **Electron** - 窗口关闭时 bridge 活跃则最小化到系统托盘而非退出 - 启动时通过 auto-start API 恢复桥接 - preload 暴露 bridge 相关 IPC **文档** - docs/bridge-system.md: 完整架构文档 - docs/chat-sdk-integration-feasibility.md: Chat SDK 集成调研 - CLAUDE.md 添加 bridge 文档链接 chore: bump v0.21.0 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
1 parent
f7735e0b9c
commit
6ad821d3af
35 files changed
+5525
-8
No files matched your search
@@ -0,0 +1,93 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useCallback, useSyncExternalStore } from "react";
|
||||
import { HugeiconsIcon } from "@hugeicons/react";
|
||||
import type { IconSvgElement } from "@hugeicons/react";
|
||||
import { Wifi01Icon, TelegramIcon } from "@hugeicons/core-free-icons";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { BridgeSection } from "./BridgeSection";
|
||||
import { TelegramBridgeSection } from "./TelegramBridgeSection";
|
||||
import { useTranslation } from "@/hooks/useTranslation";
|
||||
import type { TranslationKey } from "@/i18n";
|
||||
|
||||
type Section = "bridge" | "telegram";
|
||||
|
||||
interface SidebarItem {
|
||||
id: Section;
|
||||
label: string;
|
||||
icon: IconSvgElement;
|
||||
}
|
||||
|
||||
const sidebarItems: SidebarItem[] = [
|
||||
{ id: "bridge", label: "Bridge", icon: Wifi01Icon },
|
||||
{ id: "telegram", label: "Telegram", icon: TelegramIcon },
|
||||
];
|
||||
|
||||
function getSectionFromHash(): Section {
|
||||
if (typeof window === "undefined") return "bridge";
|
||||
const hash = window.location.hash.replace("#", "");
|
||||
if (sidebarItems.some((item) => item.id === hash)) {
|
||||
return hash as Section;
|
||||
}
|
||||
return "bridge";
|
||||
}
|
||||
|
||||
function subscribeToHash(callback: () => void) {
|
||||
window.addEventListener("hashchange", callback);
|
||||
return () => window.removeEventListener("hashchange", callback);
|
||||
}
|
||||
|
||||
export function BridgeLayout() {
|
||||
const hashSection = useSyncExternalStore(subscribeToHash, getSectionFromHash, () => "bridge" as Section);
|
||||
const [overrideSection, setOverrideSection] = useState<Section | null>(null);
|
||||
const activeSection = overrideSection ?? hashSection;
|
||||
|
||||
const { t } = useTranslation();
|
||||
|
||||
const bridgeLabelKeys: Record<string, TranslationKey> = {
|
||||
'Bridge': 'bridge.title',
|
||||
'Telegram': 'bridge.telegramSettings',
|
||||
};
|
||||
|
||||
const handleSectionChange = useCallback((section: Section) => {
|
||||
setOverrideSection(section);
|
||||
window.history.replaceState(null, "", `/bridge#${section}`);
|
||||
queueMicrotask(() => setOverrideSection(null));
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="flex h-full flex-col">
|
||||
<div className="border-b border-border/50 px-6 pt-4 pb-4">
|
||||
<h1 className="text-xl font-semibold">{t('bridge.title')}</h1>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t('bridge.description')}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="flex min-h-0 flex-1">
|
||||
<nav className="flex w-52 shrink-0 flex-col gap-1 border-r border-border/50 p-3">
|
||||
{sidebarItems.map((item) => (
|
||||
<button
|
||||
key={item.id}
|
||||
onClick={() => handleSectionChange(item.id)}
|
||||
className={cn(
|
||||
"flex items-center gap-3 rounded-md px-3 py-2 text-sm font-medium transition-colors text-left",
|
||||
activeSection === item.id
|
||||
? "bg-accent text-accent-foreground"
|
||||
: "text-muted-foreground hover:bg-accent/50 hover:text-foreground"
|
||||
)}
|
||||
>
|
||||
<HugeiconsIcon icon={item.icon} className="h-4 w-4 shrink-0" />
|
||||
{t(bridgeLabelKeys[item.label])}
|
||||
</button>
|
||||
))}
|
||||
</nav>
|
||||
|
||||
<div className="flex-1 overflow-auto p-6">
|
||||
{activeSection === "bridge" && <BridgeSection />}
|
||||
{activeSection === "telegram" && <TelegramBridgeSection />}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,509 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useCallback, useEffect, useRef } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectGroup,
|
||||
SelectItem,
|
||||
SelectLabel,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import { HugeiconsIcon } from "@hugeicons/react";
|
||||
import { Loading02Icon, CheckmarkCircle02Icon, Alert02Icon, TelegramIcon } from "@hugeicons/core-free-icons";
|
||||
import { useTranslation } from "@/hooks/useTranslation";
|
||||
import type { ProviderModelGroup } from "@/types";
|
||||
|
||||
interface AdapterStatus {
|
||||
channelType: string;
|
||||
running: boolean;
|
||||
connectedAt: string | null;
|
||||
lastMessageAt: string | null;
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
interface BridgeStatus {
|
||||
running: boolean;
|
||||
startedAt: string | null;
|
||||
adapters: AdapterStatus[];
|
||||
}
|
||||
|
||||
interface BridgeSettings {
|
||||
remote_bridge_enabled: string;
|
||||
bridge_telegram_enabled: string;
|
||||
bridge_auto_start: string;
|
||||
bridge_default_work_dir: string;
|
||||
bridge_default_model: string;
|
||||
bridge_default_provider_id: string;
|
||||
}
|
||||
|
||||
const DEFAULT_SETTINGS: BridgeSettings = {
|
||||
remote_bridge_enabled: "",
|
||||
bridge_telegram_enabled: "",
|
||||
bridge_auto_start: "",
|
||||
bridge_default_work_dir: "",
|
||||
bridge_default_model: "",
|
||||
bridge_default_provider_id: "",
|
||||
};
|
||||
|
||||
export function BridgeSection() {
|
||||
const [settings, setSettings] = useState<BridgeSettings>(DEFAULT_SETTINGS);
|
||||
const [bridgeStatus, setBridgeStatus] = useState<BridgeStatus | null>(null);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [starting, setStarting] = useState(false);
|
||||
const [stopping, setStopping] = useState(false);
|
||||
const [workDir, setWorkDir] = useState("");
|
||||
const [model, setModel] = useState("");
|
||||
const [providerGroups, setProviderGroups] = useState<ProviderModelGroup[]>([]);
|
||||
const pollRef = useRef<ReturnType<typeof setInterval> | null>(null);
|
||||
const { t } = useTranslation();
|
||||
|
||||
const fetchSettings = useCallback(async () => {
|
||||
try {
|
||||
const res = await fetch("/api/bridge/settings");
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
const s = { ...DEFAULT_SETTINGS, ...data.settings };
|
||||
setSettings(s);
|
||||
setWorkDir(s.bridge_default_work_dir);
|
||||
// Build composite value for Select: "provider_id::model"
|
||||
if (s.bridge_default_provider_id && s.bridge_default_model) {
|
||||
setModel(`${s.bridge_default_provider_id}::${s.bridge_default_model}`);
|
||||
} else if (s.bridge_default_model) {
|
||||
setModel(s.bridge_default_model);
|
||||
} else {
|
||||
setModel("");
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}, []);
|
||||
|
||||
const fetchStatus = useCallback(async () => {
|
||||
try {
|
||||
const res = await fetch("/api/bridge");
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
setBridgeStatus(data);
|
||||
}
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}, []);
|
||||
|
||||
const fetchModels = useCallback(async () => {
|
||||
try {
|
||||
const res = await fetch("/api/providers/models");
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
if (data.groups && data.groups.length > 0) {
|
||||
setProviderGroups(data.groups);
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
fetchSettings();
|
||||
fetchStatus();
|
||||
fetchModels();
|
||||
}, [fetchSettings, fetchStatus, fetchModels]);
|
||||
|
||||
// Poll bridge status while bridge is running
|
||||
useEffect(() => {
|
||||
if (bridgeStatus?.running) {
|
||||
pollRef.current = setInterval(fetchStatus, 5000);
|
||||
} else if (pollRef.current) {
|
||||
clearInterval(pollRef.current);
|
||||
pollRef.current = null;
|
||||
}
|
||||
return () => {
|
||||
if (pollRef.current) {
|
||||
clearInterval(pollRef.current);
|
||||
}
|
||||
};
|
||||
}, [bridgeStatus?.running, fetchStatus]);
|
||||
|
||||
const saveSettings = async (updates: Partial<BridgeSettings>) => {
|
||||
setSaving(true);
|
||||
try {
|
||||
const res = await fetch("/api/bridge/settings", {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ settings: updates }),
|
||||
});
|
||||
if (res.ok) {
|
||||
setSettings((prev) => ({ ...prev, ...updates }));
|
||||
}
|
||||
} catch {
|
||||
// ignore
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleToggleEnabled = (checked: boolean) => {
|
||||
saveSettings({ remote_bridge_enabled: checked ? "true" : "" });
|
||||
};
|
||||
|
||||
const handleToggleTelegram = (checked: boolean) => {
|
||||
saveSettings({ bridge_telegram_enabled: checked ? "true" : "" });
|
||||
};
|
||||
|
||||
const handleSaveDefaults = () => {
|
||||
// Split composite "provider_id::model" value
|
||||
const parts = model.split("::");
|
||||
const providerId = parts.length === 2 ? parts[0] : "";
|
||||
const modelValue = parts.length === 2 ? parts[1] : model;
|
||||
saveSettings({
|
||||
bridge_default_work_dir: workDir,
|
||||
bridge_default_model: modelValue,
|
||||
bridge_default_provider_id: providerId,
|
||||
});
|
||||
};
|
||||
|
||||
const handleBrowseFolder = async () => {
|
||||
try {
|
||||
const api = (window as unknown as Record<string, unknown>).electronAPI as
|
||||
| { dialog: { openFolder: (opts?: { defaultPath?: string; title?: string }) => Promise<{ canceled: boolean; filePaths: string[] }> } }
|
||||
| undefined;
|
||||
if (api?.dialog?.openFolder) {
|
||||
const result = await api.dialog.openFolder({
|
||||
defaultPath: workDir || undefined,
|
||||
title: t("bridge.defaultWorkDir"),
|
||||
});
|
||||
if (!result.canceled && result.filePaths[0]) {
|
||||
setWorkDir(result.filePaths[0]);
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Not in Electron or dialog unavailable
|
||||
}
|
||||
};
|
||||
|
||||
const handleStartBridge = async () => {
|
||||
setStarting(true);
|
||||
try {
|
||||
await fetch("/api/bridge", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ action: "start" }),
|
||||
});
|
||||
await fetchStatus();
|
||||
} catch {
|
||||
// ignore
|
||||
} finally {
|
||||
setStarting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleStopBridge = async () => {
|
||||
setStopping(true);
|
||||
try {
|
||||
await fetch("/api/bridge", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ action: "stop" }),
|
||||
});
|
||||
await fetchStatus();
|
||||
} catch {
|
||||
// ignore
|
||||
} finally {
|
||||
setStopping(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleToggleAutoStart = (checked: boolean) => {
|
||||
saveSettings({ bridge_auto_start: checked ? "true" : "" });
|
||||
};
|
||||
|
||||
const isEnabled = settings.remote_bridge_enabled === "true";
|
||||
const isTelegramEnabled = settings.bridge_telegram_enabled === "true";
|
||||
const isAutoStart = settings.bridge_auto_start === "true";
|
||||
const isRunning = bridgeStatus?.running ?? false;
|
||||
const adapterCount = bridgeStatus?.adapters?.length ?? 0;
|
||||
|
||||
return (
|
||||
<div className="max-w-3xl space-y-6">
|
||||
{/* Enable/Disable Master Toggle */}
|
||||
<div
|
||||
className={`rounded-lg border p-4 transition-shadow hover:shadow-sm ${
|
||||
isEnabled
|
||||
? "border-blue-500/50 bg-blue-500/5"
|
||||
: "border-border/50"
|
||||
}`}
|
||||
>
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h2 className="text-sm font-medium">{t("bridge.title")}</h2>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t("bridge.description")}
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
checked={isEnabled}
|
||||
onCheckedChange={handleToggleEnabled}
|
||||
disabled={saving}
|
||||
/>
|
||||
</div>
|
||||
{isEnabled && (
|
||||
<div className="mt-3 flex items-center gap-2 rounded-md bg-blue-500/10 px-3 py-2 text-xs text-blue-600 dark:text-blue-400">
|
||||
<span className="h-2 w-2 shrink-0 rounded-full bg-blue-500" />
|
||||
{t("bridge.activeHint")}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Bridge Status + Start/Stop */}
|
||||
{isEnabled && (
|
||||
<div className="rounded-lg border border-border/50 p-4 space-y-4 transition-shadow hover:shadow-sm">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h2 className="text-sm font-medium">{t("bridge.status")}</h2>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{isRunning
|
||||
? t("bridge.activeBindings", { count: String(adapterCount) })
|
||||
: t("bridge.noBindings")}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
<div
|
||||
className={`flex items-center gap-2 rounded-md px-3 py-1.5 text-xs ${
|
||||
isRunning
|
||||
? "bg-green-500/10 text-green-600 dark:text-green-400"
|
||||
: "bg-muted text-muted-foreground"
|
||||
}`}
|
||||
>
|
||||
<HugeiconsIcon
|
||||
icon={isRunning ? CheckmarkCircle02Icon : Alert02Icon}
|
||||
className="h-3.5 w-3.5 shrink-0"
|
||||
/>
|
||||
{isRunning
|
||||
? t("bridge.statusConnected")
|
||||
: t("bridge.statusDisconnected")}
|
||||
</div>
|
||||
{isRunning ? (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={handleStopBridge}
|
||||
disabled={stopping}
|
||||
>
|
||||
{stopping ? (
|
||||
<HugeiconsIcon
|
||||
icon={Loading02Icon}
|
||||
className="h-3.5 w-3.5 animate-spin mr-1.5"
|
||||
/>
|
||||
) : null}
|
||||
{stopping ? t("bridge.stopping") : t("bridge.stop")}
|
||||
</Button>
|
||||
) : (
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={handleStartBridge}
|
||||
disabled={starting}
|
||||
>
|
||||
{starting ? (
|
||||
<HugeiconsIcon
|
||||
icon={Loading02Icon}
|
||||
className="h-3.5 w-3.5 animate-spin mr-1.5"
|
||||
/>
|
||||
) : null}
|
||||
{starting ? t("bridge.starting") : t("bridge.start")}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Channel Toggles */}
|
||||
{isEnabled && (
|
||||
<div className="rounded-lg border border-border/50 p-4 space-y-4 transition-shadow hover:shadow-sm">
|
||||
<div>
|
||||
<h2 className="text-sm font-medium">{t("bridge.channels")}</h2>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t("bridge.channelsDesc")}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-3">
|
||||
<HugeiconsIcon
|
||||
icon={TelegramIcon}
|
||||
className="h-4 w-4 text-muted-foreground"
|
||||
/>
|
||||
<div>
|
||||
<p className="text-sm">{t("bridge.telegramChannel")}</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t("bridge.telegramChannelDesc")}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<Switch
|
||||
checked={isTelegramEnabled}
|
||||
onCheckedChange={handleToggleTelegram}
|
||||
disabled={saving}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between border-t border-border/30 pt-3">
|
||||
<div>
|
||||
<p className="text-sm">{t("bridge.autoStart")}</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t("bridge.autoStartDesc")}
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
checked={isAutoStart}
|
||||
onCheckedChange={handleToggleAutoStart}
|
||||
disabled={saving}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Adapter Status */}
|
||||
{isEnabled && isRunning && adapterCount > 0 && (
|
||||
<div className="rounded-lg border border-border/50 p-4 space-y-4 transition-shadow hover:shadow-sm">
|
||||
<div>
|
||||
<h2 className="text-sm font-medium">{t("bridge.adapters")}</h2>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t("bridge.adaptersDesc")}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
{bridgeStatus?.adapters.map((adapter) => (
|
||||
<div
|
||||
key={adapter.channelType}
|
||||
className="rounded-md border border-border/30 px-3 py-2 space-y-1"
|
||||
>
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-xs font-medium capitalize">
|
||||
{adapter.channelType}
|
||||
</span>
|
||||
<div
|
||||
className={`rounded px-2 py-0.5 text-xs ${
|
||||
adapter.running
|
||||
? "bg-green-500/10 text-green-600 dark:text-green-400"
|
||||
: "bg-muted text-muted-foreground"
|
||||
}`}
|
||||
>
|
||||
{adapter.running
|
||||
? t("bridge.adapterRunning")
|
||||
: t("bridge.adapterStopped")}
|
||||
</div>
|
||||
</div>
|
||||
{adapter.lastMessageAt && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t("bridge.adapterLastMessage")}: {new Date(adapter.lastMessageAt).toLocaleString()}
|
||||
</p>
|
||||
)}
|
||||
{adapter.error && (
|
||||
<p className="text-xs text-red-500">
|
||||
{t("bridge.adapterLastError")}: {adapter.error}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Default Settings */}
|
||||
{isEnabled && (
|
||||
<div className="rounded-lg border border-border/50 p-4 space-y-4 transition-shadow hover:shadow-sm">
|
||||
<div>
|
||||
<h2 className="text-sm font-medium">{t("bridge.defaults")}</h2>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t("bridge.defaultsDesc")}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-3">
|
||||
<div>
|
||||
<label className="text-xs font-medium text-muted-foreground mb-1 block">
|
||||
{t("bridge.defaultWorkDir")}
|
||||
</label>
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
value={workDir}
|
||||
onChange={(e) => setWorkDir(e.target.value)}
|
||||
placeholder="/path/to/project"
|
||||
className="font-mono text-sm"
|
||||
/>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={handleBrowseFolder}
|
||||
className="shrink-0"
|
||||
>
|
||||
{t("bridge.browse")}
|
||||
</Button>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground mt-1">
|
||||
{t("bridge.defaultWorkDirHint")}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="text-xs font-medium text-muted-foreground mb-1 block">
|
||||
{t("bridge.defaultModel")}
|
||||
</label>
|
||||
{providerGroups.length > 0 ? (
|
||||
<Select value={model} onValueChange={setModel}>
|
||||
<SelectTrigger className="w-full text-sm font-mono">
|
||||
<SelectValue placeholder={t("bridge.defaultModelHint")} />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{providerGroups.map((group) => (
|
||||
<SelectGroup key={group.provider_id}>
|
||||
<SelectLabel>{group.provider_name}</SelectLabel>
|
||||
{group.models.map((m) => (
|
||||
<SelectItem
|
||||
key={`${group.provider_id}::${m.value}`}
|
||||
value={`${group.provider_id}::${m.value}`}
|
||||
>
|
||||
{m.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectGroup>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
) : (
|
||||
<Input
|
||||
value={model}
|
||||
onChange={(e) => setModel(e.target.value)}
|
||||
placeholder="sonnet"
|
||||
className="font-mono text-sm"
|
||||
/>
|
||||
)}
|
||||
<p className="text-xs text-muted-foreground mt-1">
|
||||
{t("bridge.defaultModelHint")}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={handleSaveDefaults}
|
||||
disabled={saving}
|
||||
>
|
||||
{saving ? t("common.loading") : t("common.save")}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,310 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useCallback, useEffect } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { HugeiconsIcon } from "@hugeicons/react";
|
||||
import { Loading02Icon, CheckmarkCircle02Icon, Alert02Icon } from "@hugeicons/core-free-icons";
|
||||
import { useTranslation } from "@/hooks/useTranslation";
|
||||
|
||||
interface TelegramBridgeSettings {
|
||||
telegram_bot_token: string;
|
||||
telegram_chat_id: string;
|
||||
telegram_bridge_allowed_users: string;
|
||||
}
|
||||
|
||||
const DEFAULT_SETTINGS: TelegramBridgeSettings = {
|
||||
telegram_bot_token: "",
|
||||
telegram_chat_id: "",
|
||||
telegram_bridge_allowed_users: "",
|
||||
};
|
||||
|
||||
export function TelegramBridgeSection() {
|
||||
const [settings, setSettings] = useState<TelegramBridgeSettings>(DEFAULT_SETTINGS);
|
||||
const [botToken, setBotToken] = useState("");
|
||||
const [chatId, setChatId] = useState("");
|
||||
const [allowedUsers, setAllowedUsers] = useState("");
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [verifying, setVerifying] = useState(false);
|
||||
const [detecting, setDetecting] = useState(false);
|
||||
const [verifyResult, setVerifyResult] = useState<{
|
||||
ok: boolean;
|
||||
message: string;
|
||||
} | null>(null);
|
||||
const { t } = useTranslation();
|
||||
|
||||
const fetchSettings = useCallback(async () => {
|
||||
try {
|
||||
const res = await fetch("/api/settings/telegram");
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
const s = { ...DEFAULT_SETTINGS, ...data.settings };
|
||||
setSettings(s);
|
||||
setBotToken(s.telegram_bot_token);
|
||||
setChatId(s.telegram_chat_id);
|
||||
setAllowedUsers(s.telegram_bridge_allowed_users);
|
||||
}
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
fetchSettings();
|
||||
}, [fetchSettings]);
|
||||
|
||||
const saveSettings = async (updates: Partial<TelegramBridgeSettings>) => {
|
||||
setSaving(true);
|
||||
try {
|
||||
const res = await fetch("/api/settings/telegram", {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ settings: updates }),
|
||||
});
|
||||
if (res.ok) {
|
||||
setSettings((prev) => ({ ...prev, ...updates }));
|
||||
}
|
||||
} catch {
|
||||
// ignore
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSaveCredentials = () => {
|
||||
const updates: Partial<TelegramBridgeSettings> = {};
|
||||
if (botToken && !botToken.startsWith("***")) {
|
||||
updates.telegram_bot_token = botToken;
|
||||
}
|
||||
updates.telegram_chat_id = chatId;
|
||||
updates.telegram_bridge_allowed_users = allowedUsers;
|
||||
saveSettings(updates);
|
||||
};
|
||||
|
||||
const handleDetectChatId = async () => {
|
||||
if (!botToken) {
|
||||
setVerifyResult({
|
||||
ok: false,
|
||||
message: t("telegram.enterTokenFirst"),
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
setDetecting(true);
|
||||
setVerifyResult(null);
|
||||
try {
|
||||
const res = await fetch("/api/settings/telegram/verify", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
action: "detect_chat_id",
|
||||
bot_token: botToken,
|
||||
}),
|
||||
});
|
||||
const data = await res.json();
|
||||
|
||||
if (data.ok && data.chatId) {
|
||||
setChatId(data.chatId);
|
||||
setVerifyResult({
|
||||
ok: true,
|
||||
message: t("telegram.chatIdDetected", {
|
||||
id: data.chatId,
|
||||
name: data.chatTitle || data.chatId,
|
||||
}),
|
||||
});
|
||||
} else {
|
||||
setVerifyResult({
|
||||
ok: false,
|
||||
message: data.error || t("telegram.chatIdDetectFailed"),
|
||||
});
|
||||
}
|
||||
} catch {
|
||||
setVerifyResult({
|
||||
ok: false,
|
||||
message: t("telegram.chatIdDetectFailed"),
|
||||
});
|
||||
} finally {
|
||||
setDetecting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleVerify = async () => {
|
||||
setVerifying(true);
|
||||
setVerifyResult(null);
|
||||
try {
|
||||
if (!botToken) {
|
||||
setVerifyResult({
|
||||
ok: false,
|
||||
message: t("telegram.enterTokenFirst"),
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const res = await fetch("/api/settings/telegram/verify", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
bot_token: botToken,
|
||||
chat_id: chatId || undefined,
|
||||
}),
|
||||
});
|
||||
const data = await res.json();
|
||||
|
||||
if (data.verified) {
|
||||
setVerifyResult({
|
||||
ok: true,
|
||||
message: data.botName
|
||||
? t("telegram.verifiedAs", { name: data.botName })
|
||||
: t("telegram.verified"),
|
||||
});
|
||||
} else {
|
||||
setVerifyResult({
|
||||
ok: false,
|
||||
message: data.error || t("telegram.verifyFailed"),
|
||||
});
|
||||
}
|
||||
} catch {
|
||||
setVerifyResult({ ok: false, message: t("telegram.verifyFailed") });
|
||||
} finally {
|
||||
setVerifying(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="max-w-3xl space-y-6">
|
||||
{/* Bot Credentials */}
|
||||
<div className="rounded-lg border border-border/50 p-4 space-y-4 transition-shadow hover:shadow-sm">
|
||||
<div>
|
||||
<h2 className="text-sm font-medium">{t("telegram.credentials")}</h2>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t("telegram.credentialsDesc")}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-3">
|
||||
<div>
|
||||
<label className="text-xs font-medium text-muted-foreground mb-1 block">
|
||||
{t("telegram.botToken")}
|
||||
</label>
|
||||
<Input
|
||||
type="password"
|
||||
value={botToken}
|
||||
onChange={(e) => setBotToken(e.target.value)}
|
||||
placeholder="123456:ABC-DEF..."
|
||||
className="font-mono text-sm"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="text-xs font-medium text-muted-foreground mb-1 block">
|
||||
{t("telegram.chatId")}
|
||||
</label>
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
value={chatId}
|
||||
onChange={(e) => setChatId(e.target.value)}
|
||||
placeholder="-1001234567890"
|
||||
className="font-mono text-sm"
|
||||
/>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={handleDetectChatId}
|
||||
disabled={detecting || !botToken}
|
||||
className="shrink-0"
|
||||
>
|
||||
{detecting ? (
|
||||
<HugeiconsIcon
|
||||
icon={Loading02Icon}
|
||||
className="h-3.5 w-3.5 animate-spin mr-1.5"
|
||||
/>
|
||||
) : null}
|
||||
{t("telegram.detectChatId")}
|
||||
</Button>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground mt-1">
|
||||
{t("telegram.chatIdHint")}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={handleSaveCredentials}
|
||||
disabled={saving}
|
||||
>
|
||||
{saving ? t("common.loading") : t("common.save")}
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={handleVerify}
|
||||
disabled={verifying || !botToken}
|
||||
>
|
||||
{verifying ? (
|
||||
<HugeiconsIcon
|
||||
icon={Loading02Icon}
|
||||
className="h-3.5 w-3.5 animate-spin mr-1.5"
|
||||
/>
|
||||
) : null}
|
||||
{t("telegram.verify")}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{verifyResult && (
|
||||
<div
|
||||
className={`flex items-center gap-2 rounded-md px-3 py-2 text-xs ${
|
||||
verifyResult.ok
|
||||
? "bg-green-500/10 text-green-600 dark:text-green-400"
|
||||
: "bg-red-500/10 text-red-600 dark:text-red-400"
|
||||
}`}
|
||||
>
|
||||
<HugeiconsIcon
|
||||
icon={verifyResult.ok ? CheckmarkCircle02Icon : Alert02Icon}
|
||||
className="h-4 w-4 shrink-0"
|
||||
/>
|
||||
{verifyResult.message}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Allowed Users */}
|
||||
<div className="rounded-lg border border-border/50 p-4 space-y-4 transition-shadow hover:shadow-sm">
|
||||
<div>
|
||||
<h2 className="text-sm font-medium">{t("bridge.allowedUsers")}</h2>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t("bridge.allowedUsersDesc")}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Input
|
||||
value={allowedUsers}
|
||||
onChange={(e) => setAllowedUsers(e.target.value)}
|
||||
placeholder="123456789, 987654321"
|
||||
className="font-mono text-sm"
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground mt-1">
|
||||
{t("bridge.allowedUsersHint")}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Setup Guide */}
|
||||
<div className="rounded-lg border border-border/50 p-4 transition-shadow hover:shadow-sm">
|
||||
<h2 className="text-sm font-medium mb-2">
|
||||
{t("telegram.setupGuide")}
|
||||
</h2>
|
||||
<ol className="text-xs text-muted-foreground space-y-1.5 list-decimal pl-4">
|
||||
<li>{t("telegram.step1")}</li>
|
||||
<li>{t("telegram.step2")}</li>
|
||||
<li>{t("telegram.step3")}</li>
|
||||
<li>{t("telegram.step4")}</li>
|
||||
<li>{t("telegram.step5")}</li>
|
||||
<li>{t("telegram.step6")}</li>
|
||||
</ol>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
Plug01Icon,
|
||||
Image01Icon,
|
||||
Settings02Icon,
|
||||
Wifi01Icon,
|
||||
Moon02Icon,
|
||||
Sun02Icon,
|
||||
} from "@hugeicons/core-free-icons";
|
||||
@@ -38,6 +39,7 @@ const navItems = [
|
||||
{ href: "/skills", label: "Skills", icon: ZapIcon },
|
||||
{ href: "/mcp", label: "MCP", icon: Plug01Icon },
|
||||
{ href: "/gallery", label: "Gallery", icon: Image01Icon },
|
||||
{ href: "/bridge", label: "Bridge", icon: Wifi01Icon },
|
||||
{ href: "/settings", label: "Settings", icon: Settings02Icon },
|
||||
] as const;
|
||||
|
||||
@@ -51,6 +53,7 @@ export function NavRail({ onToggleChatList, hasUpdate, readyToInstall, skipPermi
|
||||
'Skills': 'extensions.skills',
|
||||
'MCP': 'extensions.mcpServers',
|
||||
'Gallery': 'gallery.title',
|
||||
'Bridge': 'nav.bridge',
|
||||
'Settings': 'nav.settings',
|
||||
};
|
||||
const emptySubscribe = useCallback(() => () => {}, []);
|
||||
|
||||
Reference in new issue
Block a user