Commit Graph

26 Commits

Author SHA1 Message Date
hailin e809740fdb feat(agents): add run_professional_assessment tool with payment gate + artifact persistence
Replaces ad-hoc assessment flow with structured pipeline:
- Code-level payment verification (checks PAID ASSESSMENT order)
- Info completeness validation (age, nationality, education, work exp)
- Assessment expert invocation with result parsing
- Automatic persistence as UserArtifact (assessment_report type)
- 30-day dedup (existing report within 30 days returns cached)
- Frontend rendering for all status codes (completed, payment_required,
  info_incomplete, already_assessed, error)
- System prompt updated to mandate new tool for paid assessments
- Post-assessment auto-generation of checklist + timeline

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-08 17:01:56 -08:00
hailin 95f36752c9 feat(agents): add prompt-driven execution tools with DB persistence
Add 4 new tools (generate_document, manage_checklist, create_timeline,
query_user_artifacts) enabling the agent to create and manage persistent
user artifacts. Artifacts are saved to PostgreSQL and support dedup by
title, update-in-place, and cross-session querying. Frontend renders
rich UI cards for each artifact type.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-08 07:35:08 -08:00
hailin 2a8a15fcb6 fix: resolve ClaudeModule DI crash + historical QR code display bug
1. ClaudeModule missing ConversationORM in TypeOrmModule.forFeature —
   ImmigrationToolsService now depends on ConversationORMRepository
   (added in query_user_profile), but ClaudeModule only had TokenUsageORM.
   Fix: add ConversationORM to ClaudeModule's TypeORM imports.

2. Historical messages show "支付创建失败" for payment QR codes —
   toolCall.result is stored as JSON string in DB metadata JSONB.
   Live streaming (useChat.ts) parses it correctly, but REST API
   load (chatStore.ts → MessageBubble.tsx) does not.
   Fix: normalize toolCall.result in ToolCallResult component —
   JSON.parse if string, pass through if already object.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-07 12:24:15 -08:00
hailin 389f975e33 fix(payment): return paymentUrl from adapters, strip base64 from tool output
Alipay/WeChat adapters now return the source payment URL alongside the
QR base64. The generate_payment tool only returns paymentUrl (short text)
to Claude API — base64 qrCodeUrl is stripped to prevent AI from dumping
raw data:image into text responses. Frontend QRCodeSVG renders from
paymentUrl instead of base64.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-07 11:44:54 -08:00
hailin 636b10b733 feat(web): auto-scroll on all state changes + completed agent badges auto-fade
Fix auto-scroll by adding missing dependencies (currentConversationId, isStreaming,
completedAgents). Completed agent badges now show for 2.5s then smoothly fade out
instead of accumulating, keeping the status area clean.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-07 09:12:32 -08:00
hailin af8aea6b03 feat(web): move agent status inline with typing indicator for better UX
Instead of showing agent status in a separate panel below the chat,
display it inline beneath the typing dots ("...") in the message flow.
The dots remain the primary waiting indicator; agent status appears
below as supplementary context during specialist agent invocations.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-07 09:05:41 -08:00
hailin 308dd7798e fix(web): load historical messages when opening a conversation
ChatPage only set currentConversationId but never fetched messages from
the API, causing historical conversations to show the welcome screen.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-07 08:00:26 -08:00
hailin 470ec9a64e feat(web-client): add per-type file size validation on upload
Enforce Claude API file size limits at upload time with user-friendly
error messages:
- Images: max 5MB (Claude API hard limit)
- PDF: max 25MB (32MB request limit minus headroom)
- Other documents: max 50MB (general upload limit)

Replaced duplicate ALLOWED_TYPES/MAX_FILE_SIZE in InputArea with shared
validateFile() from fileService, showing alert() on rejection.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-07 04:57:54 -08:00
hailin a3f2be078b feat(payment): P2 — 订单管理增强,支持取消订单和订单详情查询
## 后端改动

### PaymentClientService 增强
- 新增 `getOrderDetail(orderId)` — 获取完整订单信息(含支付详情)
- 新增 `cancelOrder(orderId)` — 取消未支付订单(调用 POST /orders/:id/cancel)

### 新增 cancel_order 工具
- 工具定义: 接收 orderId,取消未支付订单
- 实现: 调用 PaymentClientService.cancelOrder()
- 成功返回 { success, orderId, status, message }
- 失败返回友好错误信息(如"只有未支付的订单才能取消")
- coordinator-tools.ts 注册,concurrency map 标记 false(写操作)

## 前端改动

### cancel_order 结果渲染
- 成功: 绿色卡片 + CheckCircle 图标 + 成功提示
- 失败: 红色卡片 + AlertCircle 图标 + 错误原因
- 显示订单号

## 注意事项
- payment-service 暂无退款 API,cancel_order 仅限未支付订单
- 退款功能待 payment-service 侧实现后再扩展

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-07 01:23:28 -08:00
hailin db7964a461 feat(chat): P1 — 评估结果可视化卡片,Assessment Expert 输出渲染为结构化报告
## 新建 AssessmentResultCard 组件

- 渲染 Assessment Expert 返回的结构化评估数据
- 综合适合度分数(顶部大字展示,颜色编码)
- 6 个移民类别评估卡片(QMAS/GEP/IANG/TTPS/CIES/TECHTAS)
  - 分数条形图(CSS 实现,无需 chart 库)
  - 颜色梯度:绿色(90+) → 蓝色(70+) → 黄色(50+) → 橙色(30+) → 红色
  - 推荐类别高亮(primary 边框 + Award 图标)
  - 优势(highlights)、风险(concerns)、缺失信息(missingInfo) 分组展示
  - 子类别标签(如 A类、综合计分制)
- 排序:推荐类别优先,其次按分数降序
- 底部建议区块

## ToolCallResult 集成

- 识别 invoke_assessment_expert 工具结果
- 自动 JSON.parse(assessment expert 返回 JSON 字符串)
- 存在 assessments 数组时渲染 AssessmentResultCard

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-07 01:20:12 -08:00
hailin df754ce8b8 feat(payment): P0 — 支付闭环,Agent 可创建真实订单并生成支付二维码
## 后端改动

### 新增 PaymentClientService
- 新建 `infrastructure/payment/payment-client.service.ts`
  - HTTP 客户端封装,调用 payment-service API(端口 3002)
  - 方法: createOrder, createPayment, checkPaymentStatus, getOrderStatus, getUserOrders
  - 基于 native fetch,模式与 KnowledgeClientService 一致
- 新建 `infrastructure/payment/payment.module.ts`
- AgentsModule 导入 PaymentModule

### 重写 generate_payment 工具
- 删除所有 MOCK 数据(fake orderId, placeholder QR URL)
- 实际调用 payment-service: createOrder → createPayment → 返回真实 QR URL
- 返回 orderId, paymentId, qrCodeUrl, paymentUrl, expiresAt

### 新增 check_payment_status 工具
- 查询订单支付状态(调用 payment-service GET /orders/:id/status)
- 返回 status, statusLabel(中文映射), paidAt
- 在 coordinator-tools.ts 和 concurrency map 中注册(只读 safe=true)

### 新增 query_order_history 工具
- 查询用户历史订单列表(调用 payment-service GET /orders)
- 返回 orders 数组含 orderId, serviceType, amount, status, createdAt
- 在 coordinator-tools.ts 和 concurrency map 中注册(只读 safe=true)

## 前端改动

### QR 码渲染
- 安装 qrcode.react 4.2.0
- ToolCallResult 组件使用 QRCodeSVG 渲染真实二维码
- 支持 qrCodeUrl(二维码)和 paymentUrl(跳转链接)两种支付方式
- 显示订单号、金额、过期时间

### 支付状态卡片
- check_payment_status 结果渲染为彩色状态卡片
- 已支付=绿色, 待支付=黄色, 已取消=红色, 已退款=橙色

### 订单历史列表
- query_order_history 结果渲染为订单列表卡片
- 每行显示: 类别、日期、金额、状态标签

### WebSocket 工具事件处理
- tool_result 事件收集到 pendingToolResults(chatStore 新增状态)
- stream_end 时将 toolResults 注入消息 metadata.toolCalls
- stream_start 时清空 pendingToolResults

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-07 01:17:14 -08:00
hailin 16cc0e4c08 feat(agents): implement multi-agent collaboration architecture
借鉴 Claude Code 的架构模式,将单一 Agent 重构为 Coordinator + 6 Specialist 多 Agent 协作系统。

## 新增文件 (36个)

### 架构设计文档 (docs/architecture/, 12个)
- 00-overview.md ~ 11-prompt-templates.md: 完整架构设计,覆盖所有 Agent 的详细设计、
  Prompt 模板、协作流程、工具并发系统、动态上下文注入

### 多 Agent 系统 (infrastructure/agents/, 23个)
- coordinator/coordinator-agent.service.ts: 主协调器,替代 ClaudeAgentServiceV2
- coordinator/agent-loop.ts: 核心递归 async generator 循环(参考 Claude Code aM())
- coordinator/context-injector.service.ts: 动态上下文注入(8种上下文类型按优先级注入)
- specialists/base-specialist.service.ts: Agent 基类(封装 Claude API 调用 + prompt 缓存)
- specialists/policy-expert.service.ts: 政策专家 (Sonnet 4, temp=0)
- specialists/assessment-expert.service.ts: 评估专家 (Sonnet 4, temp=0)
- specialists/strategist.service.ts: 策略顾问 (Sonnet 4, temp=0.3)
- specialists/objection-handler.service.ts: 异议处理 (Sonnet 4, temp=0.2)
- specialists/case-analyst.service.ts: 案例分析 (Haiku, temp=0)
- specialists/memory-manager.service.ts: 记忆管理 (Haiku, temp=0)
- prompts/coordinator-system-prompt.ts: 协调器 Prompt(1095行,13章)
- prompts/{policy,assessment,strategist,objection,case,memory}-*-prompt.ts: 各专家 Prompt
- tools/coordinator-tools.ts: 16个工具定义(6 Agent 调用 + 10 直接工具)
- tools/tool-execution-queue.ts: 并发执行队列(isConcurrencySafe 控制并行/串行)
- types/agent.types.ts: Agent 配置、输入/输出类型定义
- types/stream.types.ts: 流式事件类型(含 agent_start/complete/coordinator_thinking)
- types/context.types.ts: 上下文注入类型
- agents.module.ts: NestJS 模块注册

### 前端 Agent 状态展示 (1个)
- AgentStatusIndicator.tsx: 多 Agent 工作状态组件(含动画)

## 修改文件 (15个)

### 后端集成
- conversation.service.ts: 切换到 CoordinatorAgentService
- conversation.gateway.ts: 新增 agent_start/agent_complete/coordinator_thinking 事件
- claude.module.ts: 引入 AgentsModule
- agents.module.ts: 注册 ImmigrationToolsService(复用旧版生产测试的工具实现)
- knowledge-client.service.ts: 新增 search()/getUserContext() 便捷方法

### 旧代码标记 @deprecated
- claude-agent.service.ts, claude-agent-v2.service.ts
- strategy-engine.service.ts, intent-classifier.ts, response-gate.ts

### 前端适配
- chatStore.ts: 新增 ActiveAgent/CompletedAgent/CoordinatorPhase 状态
- useChat.ts: 新增 WebSocket 事件处理
- ChatWindow.tsx: 集成 AgentStatusIndicator
- globals.css: 新增 agentPulse/agentSlideIn 动画

### 共享类型
- conversation.types.ts: 新增 AGENT_START/AGENT_COMPLETE/COORDINATOR_THINKING 事件

## 核心设计决策

1. **新旧结合**: Coordinator 的 10 个直接工具委托给旧版 ImmigrationToolsService
   (经过生产测试的 Google Search、汇率 API、新闻 API 等),6 个 Agent 调用工具
   走新的 Specialist Agent 系统
2. **递归 async generator**: agent-loop 支持流式输出 + 工具递归 + 成本/轮次控制
3. **并行 Agent 执行**: ToolExecutionQueue 根据 isConcurrencySafe 自动并行/串行
4. **Prompt 缓存**: 所有 Agent 的 system prompt 使用 cache_control: ephemeral
5. **速率限制重试**: 429/529 指数退避,最多 2 次
6. **向后兼容**: LegacyConversationContext 类型别名,StreamChunk 扩展不破坏现有结构

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-06 04:26:39 -08:00
hailin e1e9ba1a77 feat(multi-tenant): add super admin module and user profile pages
- Add SuperAdmin module for tenant management (CRUD, suspend/activate)
- Add tenant management REST API (/super-admin/tenants/*)
- Add user profile menu in ChatSidebar with dropdown
- Add ProfilePage and BindPhonePage for user account management
- Update init-db.sql with tenant_id columns for all 16 tables
- Add database seed script (scripts/seed.ts) with ts-node
- Integrate db:seed into deploy.sh rebuild command

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-26 06:41:11 -08:00
hailin 5ff53b8ba7 fix(chat): align input area elements vertically centered
- Change flex container from items-end to items-center
- Use top-1/2 -translate-y-1/2 for send button vertical centering
- Adjust paperclip button padding for consistent sizing

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-10 06:49:20 -08:00
hailin 3d120e1ce3 fix(chat): hide textarea scrollbar when content fits
- Set overflow-hidden by default on textarea
- Only show scrollbar when content exceeds max height (200px)
- Fix scrollbar appearing on empty input

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-10 06:44:59 -08:00
hailin 8a39505ee6 feat(chat): add paste and drag-drop file upload support
- Add clipboard paste handler for images and files (Ctrl+V / Cmd+V)
- Add drag-and-drop zone with visual feedback
- Update placeholder text to inform users about new features
- Improve file upload UX with drop overlay

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-10 06:22:59 -08:00
hailin d4925719fc feat(multimodal): add file upload and image support for chat
- Add MinIO object storage to docker-compose infrastructure
- Create file-service microservice for upload management with presigned URLs
- Add files table to database schema
- Update nginx and Kong for MinIO proxy routes
- Implement file upload UI in chat InputArea with drag-and-drop
- Add attachment preview in MessageBubble component
- Update conversation-service to handle multimodal messages
- Add Claude Vision API integration for image analysis

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-10 05:34:41 -08:00
hailin c914693f94 feat(web): add markdown rendering for AI responses 2026-01-10 01:33:00 -08:00
hailin 0cd667b5c8 fix(websocket): use singleton socket to prevent disconnection on re-render 2026-01-10 01:26:49 -08:00
hailin bd65a431aa fix(websocket): add debug logging for connection issues 2026-01-10 01:24:11 -08:00
hailin d073bd5a9d fix(websocket): configure Socket.IO path for nginx proxy 2026-01-10 01:12:58 -08:00
hailin f8fcf7c74b fix(web): integrate menu toggle into ChatWindow header, remove duplicate headers 2026-01-09 22:09:52 -08:00
hailin 4718d60bff fix(web): sidebar collapsed by default on all devices 2026-01-09 22:07:17 -08:00
hailin f12ca7a821 feat(web): add collapsible sidebar and delete conversation
Frontend:
- Add sidebarOpen state to chatStore with toggle functionality
- Make sidebar collapsible with smooth animation
- Add mobile-friendly drawer behavior with overlay
- Add toggle button for desktop view
- Implement delete conversation functionality with loading state

Backend:
- Add DELETE /conversations/:id endpoint
- Implement deleteConversation service method
- Delete messages before conversation (foreign key constraint)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-09 21:42:07 -08:00
hailin b82fdfe610 fix: 添加 border 颜色定义修复 Tailwind 构建错误
- 在 web-client tailwind.config.js 中添加 border 颜色
- 修复 'border-border' 类未定义导致的构建失败

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-09 07:06:32 -08:00
hailin a7add8ff90 Initial commit: iConsulting 香港移民咨询智能客服系统
项目架构:
- Monorepo (pnpm + Turborepo)
- 后端: NestJS 微服务 + Claude Agent SDK
- 前端: React + Vite + Ant Design

包含服务:
- conversation-service: 对话服务 (Claude AI)
- user-service: 用户认证服务
- payment-service: 支付服务 (支付宝/微信/Stripe)
- knowledge-service: 知识库服务 (RAG + Neo4j)
- evolution-service: 自我进化服务
- web-client: 用户前端
- admin-client: 管理后台

基础设施:
- PostgreSQL + Redis + Neo4j
- Kong API Gateway
- Nginx 反向代理
- Docker Compose 部署配置

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-09 00:01:12 -08:00