aiChatControllers.go 14 KB

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