aiChatControllers.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  1. package controllers
  2. import (
  3. "bufio"
  4. "context"
  5. "encoding/json"
  6. "fmt"
  7. "io"
  8. "os/user"
  9. "path/filepath"
  10. "sort"
  11. "strings"
  12. "time"
  13. "github.com/gofiber/fiber/v2"
  14. "github.com/gofiber/fiber/v2/utils"
  15. "github.com/minio/minio-go/v7"
  16. "go.uber.org/zap"
  17. "fwh-toolbox-server/middleware"
  18. "fwh-toolbox-server/services"
  19. "fwh-toolbox-server/utils/filestore"
  20. minioUtil "fwh-toolbox-server/utils/minio"
  21. )
  22. var acpManager *services.ACPManager
  23. // InitAIChat 初始化 AI Chat 模块
  24. // runAsUser 指定拉起 kiro-cli 子进程时降权到的系统用户名,为空则不降权。
  25. // home 指定 kiro-cli 子进程的 HOME 目录;为空时回退到降权用户的家目录,
  26. // 若仍无法推导则使用默认值。
  27. // debugLog 为调试日志宏开关,开启时向 kiro-cli 子进程注入 KIRO_LOG_LEVEL=debug。
  28. func InitAIChat(serviceDir string, runAsUser string, home string, debugLog bool) {
  29. home = strings.TrimSpace(home)
  30. // 未显式配置 HOME 时的回退:优先推导降权用户的家目录,否则用默认值。
  31. if home == "" {
  32. home = "/home/jerry-remote"
  33. if u := strings.TrimSpace(runAsUser); u != "" {
  34. if usr, err := user.Lookup(u); err == nil {
  35. home = usr.HomeDir
  36. } else {
  37. zap.L().Warn("[AIChat] 查找降权用户失败,沿用默认 HOME",
  38. zap.String("user", u), zap.String("home", home), zap.Error(err))
  39. }
  40. }
  41. }
  42. // 组装传给 kiro-cli 子进程的环境变量。
  43. childEnv := []string{"HOME=" + home}
  44. if debugLog {
  45. // 宏开关:开启 kiro-cli debug 级日志。
  46. // 日志输出路径(Linux,kiro-cli acp 默认):/tmp/kiro-log/logs/kiro-chat.log
  47. childEnv = append(childEnv, "KIRO_LOG_LEVEL=debug")
  48. }
  49. zap.L().Info("[AIChat] 初始化 ACP",
  50. zap.String("runAsUser", runAsUser), zap.String("home", home),
  51. zap.Bool("debugLog", debugLog))
  52. acpManager = services.NewACPManager(serviceDir, childEnv, runAsUser)
  53. }
  54. // AiChat 发送消息(SSE 流式响应)
  55. // POST /ai/chat
  56. func AiChat(c *fiber.Ctx) error {
  57. var req struct {
  58. Message string `json:"message"`
  59. SessionId string `json:"sessionId"`
  60. }
  61. if err := c.BodyParser(&req); err != nil {
  62. return Fail(c, "Invalid request body")
  63. }
  64. if req.Message == "" {
  65. return Fail(c, "message 不能为空")
  66. }
  67. userId := middleware.AuthGetUserName(c)
  68. sess, err := acpManager.GetOrCreateSession(userId)
  69. if err != nil {
  70. return Error(c, fmt.Sprintf("AI 会话创建失败: %v", err))
  71. }
  72. // SSE 流式响应
  73. c.Set("Content-Type", "text/event-stream")
  74. c.Set("Cache-Control", "no-cache")
  75. c.Set("Connection", "keep-alive")
  76. c.Set("X-Accel-Buffering", "no")
  77. c.Context().SetBodyStreamWriter(func(w *bufio.Writer) {
  78. // 连接生命周期上下文:写入失败(客户端断开)时取消,
  79. // 令 service/acp 层尽快停止本轮并解除阻塞。
  80. ctx, cancel := context.WithCancel(context.Background())
  81. defer cancel()
  82. // flush 封装:返回 false 表示连接已断开
  83. flush := func() bool {
  84. if err := w.Flush(); err != nil {
  85. cancel()
  86. return false
  87. }
  88. return true
  89. }
  90. // 发送 session_info 事件,包含实际生效的 agent 和 model
  91. infoContent, _ := json.Marshal(fiber.Map{"agentId": sess.AgentId, "modelId": sess.ModelId})
  92. infoEvent, _ := json.Marshal(services.AIChatEvent{Type: "session_info", Content: string(infoContent)})
  93. fmt.Fprintf(w, "event: session_info\ndata: %s\n\n", string(infoEvent))
  94. if !flush() {
  95. return
  96. }
  97. // 如果有欢迎消息且是新会话,先发送 welcome 事件
  98. if sess.WelcomeMessage != "" {
  99. welcomeEvent, _ := json.Marshal(services.AIChatEvent{Type: "welcome", Content: sess.WelcomeMessage})
  100. fmt.Fprintf(w, "event: welcome\ndata: %s\n\n", string(welcomeEvent))
  101. if !flush() {
  102. return
  103. }
  104. }
  105. eventCh := make(chan services.AIChatEvent, 50)
  106. go acpManager.Prompt(ctx, sess, req.Message, eventCh)
  107. for event := range eventCh {
  108. data, _ := json.Marshal(event)
  109. fmt.Fprintf(w, "event: %s\ndata: %s\n\n", event.Type, string(data))
  110. if !flush() {
  111. // 客户端断开:取消上下文,让 service 层停止转发并排空。
  112. // 继续 range 直到 eventCh 被关闭,避免 goroutine 泄漏。
  113. cancel()
  114. for range eventCh {
  115. }
  116. return
  117. }
  118. }
  119. })
  120. return nil
  121. }
  122. // GetAiSessionList 获取用户的会话历史列表
  123. // GET /ai/sessions/list
  124. func GetAiSessionList(c *fiber.Ctx) error {
  125. userId := middleware.AuthGetUserName(c)
  126. list := acpManager.GetSessionList(userId)
  127. return Success(c, list)
  128. }
  129. // GetCurrentAiSession 获取当前活跃会话信息(含实际生效的 agent/model 与最近用量)
  130. // GET /ai/sessions/current
  131. func GetCurrentAiSession(c *fiber.Ctx) error {
  132. userId := middleware.AuthGetUserName(c)
  133. sess := acpManager.GetSessionInfo(userId)
  134. if sess == nil {
  135. // 无活跃会话,返回空对象
  136. return Success(c, fiber.Map{})
  137. }
  138. var contextUsagePercent float64
  139. var turnDurationMs int64
  140. if sess.Client != nil {
  141. contextUsagePercent, turnDurationMs = sess.Client.GetMeta()
  142. }
  143. return Success(c, fiber.Map{
  144. "sessionId": sess.SessionId,
  145. "title": sess.Title,
  146. "agentId": sess.AgentId,
  147. "modelId": sess.ModelId,
  148. "contextUsagePercent": contextUsagePercent,
  149. "turnDurationMs": turnDurationMs,
  150. })
  151. }
  152. // CreateAiSession 创建新的 AI 会话(保留旧会话到历史)
  153. // POST /ai/sessions/new
  154. func CreateAiSession(c *fiber.Ctx) error {
  155. userId := middleware.AuthGetUserName(c)
  156. // 创建新会话(旧会话自动归档到历史)
  157. sess, err := acpManager.CreateNewSession(userId)
  158. if err != nil {
  159. return Error(c, fmt.Sprintf("创建会话失败: %v", err))
  160. }
  161. return Success(c, fiber.Map{
  162. "sessionId": sess.SessionId,
  163. "welcomeMessage": sess.WelcomeMessage,
  164. "agentId": sess.AgentId,
  165. "modelId": sess.ModelId,
  166. })
  167. }
  168. // SwitchAiSession 切换到历史会话(恢复 AI 上下文,轻量响应)
  169. // POST /ai/sessions/:id
  170. func SwitchAiSession(c *fiber.Ctx) error {
  171. sessionId := utils.CopyString(c.Params("id"))
  172. if sessionId == "" {
  173. return Fail(c, "sessionId 不能为空")
  174. }
  175. userId := middleware.AuthGetUserName(c)
  176. sess, err := acpManager.LoadSession(userId, sessionId)
  177. if err != nil {
  178. return Error(c, fmt.Sprintf("加载会话失败: %v", err))
  179. }
  180. return Success(c, fiber.Map{
  181. "sessionId": sess.SessionId,
  182. "title": sess.Title,
  183. "welcomeMessage": sess.WelcomeMessage,
  184. "agentId": sess.AgentId,
  185. "modelId": sess.ModelId,
  186. })
  187. }
  188. // StreamLoadAiSession SSE 流式推送回放消息
  189. // GET /ai/sessions/:id/load
  190. func StreamLoadAiSession(c *fiber.Ctx) error {
  191. sessionId := utils.CopyString(c.Params("id"))
  192. if sessionId == "" {
  193. return Fail(c, "sessionId 不能为空")
  194. }
  195. userId := middleware.AuthGetUserName(c)
  196. // 获取回放消息(会话必须已通过 SwitchAiSession 加载)
  197. replayMessages := acpManager.GetReplayMessages(userId)
  198. if replayMessages == nil {
  199. return Fail(c, "会话未加载,请先调用切换会话接口")
  200. }
  201. // SSE 流式响应
  202. c.Set("Content-Type", "text/event-stream")
  203. c.Set("Cache-Control", "no-cache")
  204. c.Set("Connection", "keep-alive")
  205. c.Set("X-Accel-Buffering", "no")
  206. c.Context().SetBodyStreamWriter(func(w *bufio.Writer) {
  207. var totalBytes int
  208. for _, msg := range replayMessages {
  209. data, _ := json.Marshal(msg)
  210. totalBytes += len(msg.Content)
  211. fmt.Fprintf(w, "event: message\ndata: %s\n\n", string(data))
  212. w.Flush()
  213. }
  214. // 发送 done 事件,包含统计信息和建议
  215. suggestNewSession := totalBytes >= 100*1024 // 100KB 以上建议新建
  216. donePayload, _ := json.Marshal(fiber.Map{
  217. "sessionId": sessionId,
  218. "totalMessages": len(replayMessages),
  219. "totalBytes": totalBytes,
  220. "suggestNewSession": suggestNewSession,
  221. })
  222. fmt.Fprintf(w, "event: done\ndata: %s\n\n", string(donePayload))
  223. w.Flush()
  224. })
  225. return nil
  226. }
  227. // UpdateAiSessionTitle 更新会话标题
  228. // PATCH /ai/sessions/:id
  229. func UpdateAiSessionTitle(c *fiber.Ctx) error {
  230. sessionId := utils.CopyString(c.Params("id"))
  231. if sessionId == "" {
  232. return Fail(c, "sessionId 不能为空")
  233. }
  234. var req struct {
  235. Title string `json:"title"`
  236. }
  237. if err := c.BodyParser(&req); err != nil {
  238. return Fail(c, "Invalid request body")
  239. }
  240. userId := middleware.AuthGetUserName(c)
  241. acpManager.UpdateSessionTitle(userId, sessionId, req.Title)
  242. return Success[any](c, nil, "标题已更新")
  243. }
  244. // DeleteAiSession 删除 AI 会话
  245. // DELETE /ai/sessions/:id
  246. func DeleteAiSession(c *fiber.Ctx) error {
  247. sessionId := utils.CopyString(c.Params("id"))
  248. userId := middleware.AuthGetUserName(c)
  249. if sessionId == "" {
  250. // 无 id 参数,删除当前活跃会话
  251. acpManager.DeleteSession(userId)
  252. } else {
  253. // 删除指定会话
  254. acpManager.DeleteSessionFromHistory(userId, sessionId)
  255. }
  256. return Success[any](c, nil, "会话已删除")
  257. }
  258. // CancelAiChat 取消当前 AI 操作
  259. // POST /ai/cancel
  260. func CancelAiChat(c *fiber.Ctx) error {
  261. userId := middleware.AuthGetUserName(c)
  262. sess := acpManager.GetSessionInfo(userId)
  263. if sess == nil {
  264. return Fail(c, "没有活跃的会话")
  265. }
  266. acpManager.Cancel(sess)
  267. return Success[any](c, nil, "已取消")
  268. }
  269. // ResolvePermission 前端回传写权限选择
  270. // POST /ai/permission
  271. func ResolvePermission(c *fiber.Ctx) error {
  272. var req struct {
  273. OptionId string `json:"optionId"`
  274. }
  275. if err := c.BodyParser(&req); err != nil {
  276. return Fail(c, "Invalid request body")
  277. }
  278. if req.OptionId == "" {
  279. return Fail(c, "optionId 不能为空")
  280. }
  281. userId := middleware.AuthGetUserName(c)
  282. if err := acpManager.ResolvePermission(userId, req.OptionId); err != nil {
  283. return Fail(c, err.Error())
  284. }
  285. return Success[any](c, nil, "已回复")
  286. }
  287. // DownloadAiFile 下载 AI 生成的文件
  288. // GET /ai/files/download?key=xxx
  289. func DownloadAiFile(c *fiber.Ctx) error {
  290. key := utils.CopyString(c.Query("key"))
  291. if key == "" {
  292. return Fail(c, "key 不能为空")
  293. }
  294. // 直接从 MinIO 读取文件(key 即 objectKey)
  295. obj, err := minioUtil.Client.GetObject(context.Background(), filestore.AIFileBucket, key, minio.GetObjectOptions{})
  296. if err != nil {
  297. return Fail(c, "文件不存在")
  298. }
  299. defer obj.Close()
  300. // 获取文件信息
  301. stat, err := obj.Stat()
  302. if err != nil {
  303. return Fail(c, fmt.Sprintf("文件不存在: %v", err))
  304. }
  305. // 读取全部内容
  306. data, err := io.ReadAll(obj)
  307. if err != nil {
  308. return Error(c, fmt.Sprintf("读取文件失败: %v", err))
  309. }
  310. // 从 key 中提取文件名(key 格式: prefix/userId/sessionId/uuid_fileName)
  311. fileName := filepath.Base(key)
  312. // 去掉 uuid 前缀(前9个字符: 8位uuid + 下划线)
  313. if len(fileName) > 9 {
  314. fileName = fileName[9:]
  315. }
  316. c.Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, fileName))
  317. c.Set("Content-Type", stat.ContentType)
  318. return c.Send(data)
  319. }
  320. // UploadAiFile 上传文件给 AI 分析
  321. // POST /ai/files/upload
  322. func UploadAiFile(c *fiber.Ctx) error {
  323. userId := middleware.AuthGetUserName(c)
  324. sess, err := acpManager.GetOrCreateSession(userId)
  325. if err != nil {
  326. return Error(c, fmt.Sprintf("AI 会话创建失败: %v", err))
  327. }
  328. // 读取上传文件
  329. file, err := c.FormFile("file")
  330. if err != nil {
  331. return Fail(c, "请选择要上传的文件")
  332. }
  333. // 限制文件大小(最大 2MB)
  334. if file.Size > 2*1024*1024 {
  335. return Fail(c, "文件大小不能超过 2MB")
  336. }
  337. // 读取文件内容
  338. f, err := file.Open()
  339. if err != nil {
  340. return Error(c, "打开文件失败")
  341. }
  342. defer f.Close()
  343. data, err := io.ReadAll(f)
  344. if err != nil {
  345. return Error(c, "读取文件失败")
  346. }
  347. // 上传到 MinIO 的 "upload" 前缀(这样 Agent readTextFile 可以读到)
  348. record, err := filestore.UploadFile(userId, sess.SessionId, file.Filename, string(data))
  349. if err != nil {
  350. return Error(c, fmt.Sprintf("保存文件失败: %v", err))
  351. }
  352. return Success(c, fiber.Map{
  353. "key": record.Key,
  354. "fileName": record.FileName,
  355. "size": record.Size,
  356. })
  357. }
  358. // ListAiFiles 获取用户的 AI 文件列表
  359. // GET /ai/files/list?type=upload|download
  360. func ListAiFiles(c *fiber.Ctx) error {
  361. userId := middleware.AuthGetUserName(c)
  362. fileType := utils.CopyString(c.Query("type"))
  363. if fileType != "upload" && fileType != "download" {
  364. return Fail(c, "type 参数必须为 upload 或 download")
  365. }
  366. // 按用户前缀列出 MinIO 文件
  367. prefix := fmt.Sprintf("%s/%s/", fileType, userId)
  368. objects, err := minioUtil.ListFilesObjectFromBucket(filestore.AIFileBucket, prefix, true)
  369. if err != nil {
  370. return Error(c, fmt.Sprintf("获取文件列表失败: %v", err))
  371. }
  372. type FileItem struct {
  373. Key string `json:"key"`
  374. FileName string `json:"fileName"`
  375. Size int64 `json:"size"`
  376. CreatedAt int64 `json:"createdAt"` // Unix ms
  377. ExpiresAt int64 `json:"expiresAt"` // Unix ms(0 表示不过期)
  378. }
  379. now := time.Now()
  380. list := make([]FileItem, 0, len(objects))
  381. for _, obj := range objects {
  382. // 跳过已过期的文件(MinIO 可能延迟清理)
  383. if !obj.Expires.IsZero() && obj.Expires.Before(now) {
  384. continue
  385. }
  386. // 从 key 中提取文件名: {prefix}/{userId}/{sessionId}/{uuid}_{fileName}
  387. fileName := filepath.Base(obj.Key)
  388. if len(fileName) > 9 { // 去掉 "uuid_" 前缀(8位uuid + 下划线)
  389. fileName = fileName[9:]
  390. }
  391. var expiresAt int64
  392. if !obj.Expires.IsZero() {
  393. expiresAt = obj.Expires.UnixMilli()
  394. }
  395. list = append(list, FileItem{
  396. Key: obj.Key,
  397. FileName: fileName,
  398. Size: obj.Size,
  399. CreatedAt: obj.LastModified.UnixMilli(),
  400. ExpiresAt: expiresAt,
  401. })
  402. }
  403. // 按创建时间倒序
  404. sort.Slice(list, func(i, j int) bool {
  405. return list[i].CreatedAt > list[j].CreatedAt
  406. })
  407. return Success(c, list)
  408. }