diff --git a/.env.example b/.env.example index f04fc12..e8878f2 100644 --- a/.env.example +++ b/.env.example @@ -6,6 +6,10 @@ DOBOTAI_INGRESS_TOKEN=replace-me DOBOTAI_ADMIN_TOKEN= DOBOTAI_GROUP_SESSION_POLICY=shared DOBOTAI_AGENT_BINDINGS={"dingtalk:*":"replace-with-agent-id"} +# Required for /think routing. The base binding above remains the stable +# Session identity; these select the execution Agent for each Turn. +DOBOTAI_QUICK_AGENT_ID=builtin-quick-answer +DOBOTAI_REASONING_AGENT_ID=builtin-smart-reasoning # Official WeKnora API only WEKNORA_BASE_URL=http://127.0.0.1:8080 @@ -27,5 +31,32 @@ DINGTALK_CARD_TEMPLATE_ID= # Keep empty outside a controlled debug session; never commit a real user ID. DINGTALK_CARD_DEBUG_USER_ID= +# Optional DingTalk FAQ table workflow for uncovered questions. Set all four +# values together; leave all four empty to disable. Required when the support +# group notification below is enabled. Never commit real IDs. +DINGTALK_FAQ_TABLE_BASE_ID= +DINGTALK_FAQ_TABLE_SHEET_ID= +DINGTALK_FAQ_TABLE_VIEW_ID= +DINGTALK_FAQ_TABLE_OPERATOR_ID= + +# Optional PDF-answer image egress for DingTalk cards. When any value is set, +# all five values are required. DobotAI downloads only authenticated resource:// +# images from WEKNORA_BASE_URL /files, writes content-hashed copies under +# dobotai/im-images/, and emits private OSS GET URLs valid for 2 hours. +# Keep the bucket private and configure an OSS lifecycle rule to delete +# dobotai/im-images/ objects after 1 day. Never commit real credentials. +DOBOTAI_OUTBOUND_IMAGE_OSS_ENDPOINT= +DOBOTAI_OUTBOUND_IMAGE_OSS_REGION= +DOBOTAI_OUTBOUND_IMAGE_OSS_ACCESS_KEY_ID= +DOBOTAI_OUTBOUND_IMAGE_OSS_ACCESS_KEY_SECRET= +DOBOTAI_OUTBOUND_IMAGE_OSS_BUCKET= + +# Optional support group for uncovered-answer notifications. This is the +# group's openConversationId, not a webhook. Leave empty to record coverage +# decisions and pending support cases without sending group notifications. +# When enabled, the FAQ table workflow above must also be configured so the +# ActionCard can link to the exact FAQ record. Never commit a real group ID. +DINGTALK_SUPPORT_GROUP_OPEN_CONVERSATION_ID= + # Independent DobotAI PostgreSQL; never point this at WeKnora's database DATABASE_URL=postgres://dobotai:replace-me@127.0.0.1:5432/dobotai?sslmode=disable diff --git a/.gitignore b/.gitignore index c3a51f0..0304290 100644 --- a/.gitignore +++ b/.gitignore @@ -5,6 +5,17 @@ *.local coverage.out +# Local deployment, backup, and production diagnostic artifacts +/.deploy/ +/backups/ +/check-live-dobotai.py + +# Transient local validation and legacy test-deployment artifacts +/dobotai +/.acceptance-canary/ +/.hermes/ +/deploy_stable_images_test.py + # Editors and OS .idea/ .vscode/ diff --git a/.hermes/plans/2026-08-13_121656-dobotai-settings-and-admin-console.md b/.hermes/plans/2026-08-13_121656-dobotai-settings-and-admin-console.md new file mode 100644 index 0000000..01af1ff --- /dev/null +++ b/.hermes/plans/2026-08-13_121656-dobotai-settings-and-admin-console.md @@ -0,0 +1,1257 @@ +# DobotAI 设置控制流与管理员配置中心实施计划 + +> **执行方式:** 由当前Hermes主代理严格串行执行;不使用子代理或任务委派;一次只实现、测试和提交一个特性。 + +**目标:** 为DobotAI增加安全的Web初始化后台、首位管理员绑定、独立`/setting`控制流、个人多语言、技术支持群/AI表格对话式绑定、配置总览与组件状态,并在最后支持钉钉Secret轮换及应用切换。 + +**架构:** 将“启动配置、业务配置、个人偏好、设置对话”从问答链路拆出。Client ID和版本化业务配置存PostgreSQL;Client Secret等长期Secret写入权限`0600`的独立文件且永不回显。钉钉消息在进入`qa.Service`前由设置路由拦截,因此设置内容不会创建WeKnora Session、问答Turn、知识缺失Case或AI表格Outbox。 + +**技术栈:** Go 1.25、`net/http`、PostgreSQL/pgx、标准库`html/template`与`embed`、钉钉Stream SDK、现有DingTalk/AI表格客户端。 + +--- + +## 1. 已确认的产品规则 + +1. 钉钉Client ID/AppKey和Client Secret/AppSecret必须先在Web后台配置并验证。 +2. 钉钉凭据未配置或验证失败时,只开放后台Setup;不启动Stream,不允许钉钉问答。 +3. 首位管理员由“后台一次性绑定码→本人私聊机器人→后台确认”产生。 +4. 管理员权限主身份为`tenant_key + staff_id`;`union_id`、姓名、部门仅用于关联和展示。 +5. `/setting`、`/settings`、`/设置`及设置状态中的后续消息属于控制流。 +6. 设置流量不进入`messages`、`turns`、`session_mappings`、WeKnora、覆盖判定、支持Case、问题AI表格或FAQ表格。 +7. 普通用户只能修改个人设置;管理员同时拥有个人设置和系统管理能力。 +8. 技术支持群通过目标群内`@机器人 /setting`绑定;不要求管理员寻找群ID。 +9. 问题表和FAQ表通过发送钉钉表格链接绑定;系统解析ID、验证权限和字段类型后才激活。 +10. 后台显示配置总览和组件状态;任何Secret永不回显。 +11. Secret轮换与更换应用是两个入口;新应用先作为候选验证,正式问答消费者不能双开。 +12. 本计划不执行部署、数据库迁移、Docker、Push或外部真实写入;这些在对应里程碑完成后单独请求确认。 + +## 2. 当前代码基线 + +计划编写时: + +```text +branch: main +HEAD: 2c0ed7c feat: expose runtime build version +main相对origin/main: 领先12个Commit +``` + +当前工作区仍有未提交功能: + +```text +PDF图片出站到Private OSS +钉钉立即ACK与MsgID去重 +WeKnora失效Session自动重建 +``` + +当前架构约束: + +- `cmd/dobotai/main.go`在进程启动时直接构造WeKnora、QA和DingTalk Stream。 +- 钉钉凭据来自环境变量;FAQ、问题表和支持群ID也来自环境变量。 +- `internal/httpapi/server.go`只有JSON API,没有HTML后台。 +- `internal/channels/dingtalk/handler.go`完成基础校验后直接构造`core.QARequest`并调用QA。 +- 数据库最新迁移为`000011`。 + +## 3. 范围分层 + +### 首个可用版本(里程碑M1–M3) + +- 固定当前未提交代码。 +- Setup模式和Web配置后台。 +- 钉钉凭据测试、保存、Stream启停状态。 +- 首位管理员绑定。 +- `/setting`独立路由和“零问答副作用”门禁。 +- 配置总览与组件状态。 + +### 第二批(M4–M6) + +- 个人多语言。 +- 技术支持群绑定。 +- 问题AI表格、FAQ表格链接绑定和字段映射。 + +### 最后实施(M7) + +- 同App ID轮换Secret。 +- 切换为新的钉钉应用。 +- 候选验证、维护窗口、回滚。 + +### 暂不实现 + +- 公网后台。 +- 钉钉OAuth网页登录。 +- 多租户自助开通。 +- 通过聊天设置任何Secret。 +- 自动迁移旧pending Case/Outbox到新目标。 +- 未经确认向真实群发送测试消息或向真实AI表格写测试记录。 + +--- + +# 里程碑M0:固定现有工作区基线 + +## Task 0.1:创建安全基线和忽略规则 + +**目标:** 在开发配置系统前固定当前工作区,避免历史功能与新功能混在同一Commit。 + +**文件:** + +- 修改:`.gitignore` +- 检查:`.deploy/` +- 检查:`backups/` +- 检查:`check-live-dobotai.py` + +**步骤:** + +1. 保存`git status`、`git diff`和未跟踪源码清单到`backups/`。 +2. 确认`.deploy/`、`backups/`、运行二进制和数据库Dump不应进入源码。 +3. 只把确定的部署/备份产物加入`.gitignore`;`check-live-dobotai.py`先分类后决定是否纳入工具目录。 +4. 运行: + +```bash +git diff --check +git status --short +``` + +5. Commit: + +```bash +git commit -m "chore: ignore local deployment artifacts" +``` + +## Task 0.2:提交PDF图片出站 + +**目标:** 单独固定Private OSS图片出站功能。 + +**主要文件:** + +- 创建:`cmd/dobotai/outbound_images.go` +- 创建:`internal/outboundimage/aliyun_oss.go` +- 创建:`internal/outboundimage/publisher.go` +- 创建:`internal/outboundimage/rewriter.go` +- 创建:`internal/outboundimage/*_test.go` +- 修改:`cmd/dobotai/main.go` +- 修改:`cmd/dobotai/main_test.go` +- 修改:`internal/channels/dingtalk/handler.go` +- 修改:`internal/channels/dingtalk/handler_test.go` +- 修改:`.env.example` +- 修改:`go.mod` +- 修改:`go.sum` + +**注意:** `main.go`、`handler.go`和测试文件含多项功能,必须使用`git add -p`逐块暂存,禁止整文件误收异步ACK或Session恢复。 + +**验证:** + +```bash +go test ./internal/outboundimage ./internal/channels/dingtalk ./cmd/dobotai -count=1 +go test -race ./internal/outboundimage ./internal/channels/dingtalk -count=1 +go vet ./internal/outboundimage ./internal/channels/dingtalk ./cmd/dobotai +``` + +**Commit:** + +```bash +git commit -m "feat: publish outbound answer images to private OSS" +``` + +## Task 0.3:提交钉钉立即ACK与MsgID去重 + +**主要文件:** + +- 修改:`internal/channels/dingtalk/stream.go` +- 修改:`internal/channels/dingtalk/stream_test.go` +- 必要时局部修改:`internal/channels/dingtalk/handler.go` +- 必要时局部修改:`internal/channels/dingtalk/handler_test.go` + +**验证:** + +```bash +go test ./internal/channels/dingtalk -count=1 +go test -race ./internal/channels/dingtalk -count=1 +``` + +必须验证: + +```text +Callback立即返回ACK +同MsgID五分钟内只处理一次 +不同MsgID不互相阻塞 +处理失败不会造成并发双答 +``` + +**Commit:** + +```bash +git commit -m "fix: acknowledge DingTalk callbacks before async processing" +``` + +## Task 0.4:提交WeKnora失效Session自动恢复 + +**主要文件:** + +- 修改:`internal/weknora/client.go` +- 修改:`internal/weknora/client_test.go` +- 修改:`internal/qa/service.go` +- 修改:`internal/qa/service_test.go` +- 修改:`internal/store/postgres/store.go` + +**验证:** + +```bash +go test ./internal/weknora ./internal/qa ./internal/store/postgres -count=1 +go test -race ./internal/qa -count=1 +``` + +必须验证只对明确的WeKnora `Session not found`执行一次失效、重建和重试;其他404/网络错误不重试。 + +**Commit:** + +```bash +git commit -m "fix: recreate stale WeKnora sessions once" +``` + +## M0退出条件 + +```text +工作区无未提交生产源码 +现有目标测试全部通过 +每项历史功能有独立Commit +未Push、未部署 +``` + +--- + +# 里程碑M1:配置域、Secret存储与Setup模式 + +## Task 1.1:新增配置域模型 + +**目标:** 定义状态、配置版本和组件状态,不先接UI。 + +**创建:** + +- `internal/settings/types.go` +- `internal/settings/service.go` +- `internal/settings/service_test.go` + +**核心类型:** + +```go +type SystemState string + +const ( + StateUninitialized SystemState = "uninitialized" + StateCredentialsSaved SystemState = "credentials_saved" + StateDingTalkVerified SystemState = "dingtalk_verified" + StateWaitingAdmin SystemState = "waiting_first_admin" + StateActive SystemState = "active" + StateCredentialError SystemState = "credential_error" +) + +type ComponentState string + +const ( + ComponentOK ComponentState = "ok" + ComponentWarning ComponentState = "warning" + ComponentError ComponentState = "error" + ComponentUnconfigured ComponentState = "unconfigured" + ComponentDisabled ComponentState = "disabled" +) +``` + +**TDD:** + +- 无凭据→`uninitialized`。 +- 完整但未验证→`credentials_saved`。 +- 凭据验证且管理员数为0→`waiting_first_admin`。 +- 凭据验证且存在有效管理员→`active`。 +- Secret和Client ID不完整→`credential_error`,不能误报Active。 + +**验证:** + +```bash +go test ./internal/settings -count=1 +``` + +**Commit:** `feat: add settings lifecycle domain` + +## Task 1.2:新增配置数据库迁移 + +**创建:** + +- `db/migrations/000012_system_settings.up.sql` +- `db/migrations/000012_system_settings.down.sql` +- `db/migrations/000012_system_settings_contract_test.go` + +**表:** + +```text +system_config_revisions +system_resource_bindings +administrators +config_audit_events +``` + +建议字段: + +```sql +system_config_revisions( + id TEXT PRIMARY KEY, + tenant_key TEXT NOT NULL, + kind TEXT NOT NULL, + revision INTEGER NOT NULL, + state TEXT NOT NULL, + public_config JSONB NOT NULL, + secret_ref TEXT NOT NULL DEFAULT '', + validation_status TEXT NOT NULL, + validation_code TEXT NOT NULL DEFAULT '', + validated_at TIMESTAMPTZ, + activated_at TIMESTAMPTZ, + created_by_staff_id TEXT NOT NULL DEFAULT '', + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + UNIQUE(tenant_key, kind, revision) +); +``` + +`public_config`只允许标识符、开关和非Secret选项。数据库约束/仓库测试必须拒绝把`client_secret`、`access_token`、`api_key`等键写入`public_config`。 + +管理员唯一约束: + +```sql +UNIQUE(tenant_key, staff_id) +``` + +**验证:** + +```bash +go test ./db/migrations -run 'Test.*012' -count=1 +``` + +**Commit:** `feat: add versioned system configuration schema` + +## Task 1.3:实现PostgreSQL配置仓库 + +**创建:** + +- `internal/store/postgres/settings.go` +- `internal/store/postgres/settings_test.go` + +**接口:** + +```go +type Repository interface { + CurrentConfig(context.Context, string, ConfigKind) (ConfigRevision, error) + CreateDraft(context.Context, ConfigRevision) error + MarkValidated(context.Context, string, ValidationResult) error + Activate(context.Context, string) error + CountActiveAdministrators(context.Context, string) (int, error) + AddAdministrator(context.Context, Administrator) error + RecordAudit(context.Context, AuditEvent) error +} +``` + +激活必须在事务中完成:同一`tenant_key + kind`最多一个active版本。 + +**验证:** + +```bash +go test ./internal/store/postgres -run 'Test.*Settings|Test.*Config' -count=1 +``` + +**Commit:** `feat: persist versioned system settings` + +## Task 1.4:实现权限0600的Secret文件存储 + +**创建:** + +- `internal/secretstore/file.go` +- `internal/secretstore/file_test.go` + +**默认目录:** + +```text +~/.config/dobotai/secrets/ +``` + +**规则:** + +- 目录`0700`,单个Secret文件`0600`。 +- 使用临时文件、`fsync`和原子`rename`。 +- API只允许`Put`、`Configured`、`Use`、`Delete`;不提供面向HTTP的明文读取返回。 +- 错误和日志不能包含Secret值。 +- `secret_ref`保存随机文件名/版本引用,不保存Secret。 +- 测试以临时目录运行,不读取真实Secret。 + +**验证:** + +```bash +go test ./internal/secretstore -count=1 +go test -race ./internal/secretstore -count=1 +``` + +**Commit:** `feat: add atomic file-backed secret storage` + +## Task 1.5:解耦进程启动与钉钉通道启动 + +**创建:** + +- `cmd/dobotai/runtime.go` +- `cmd/dobotai/runtime_test.go` + +**修改:** + +- `cmd/dobotai/main.go` +- `internal/httpapi/server.go` +- `internal/httpapi/server_test.go` + +**目标结构:** + +```text +进程启动 +→ PostgreSQL和配置服务 +→ HTTP后台始终启动 +→ 根据配置状态: + setup:不构造WeKnora/QA/Stream/Outbox + active:构造完整运行组件 +``` + +不能让`httpapi.NewWithOptions`在Setup模式强制要求QA服务。建议将管理后台与QA API拆成独立Handler并挂到同一Mux: + +```text +/internal/adminweb +/internal/httpapi +``` + +Setup状态下: + +```text +GET /healthz 200,标明setup +GET /admin/setup 200 +POST /v1/qa 503 channel_not_configured +DingTalk Stream 未创建 +问题表/FAQ表/支持群Poller 未启动 +``` + +**验证:** + +```bash +go test ./cmd/dobotai ./internal/httpapi -count=1 +go test -race ./cmd/dobotai -count=1 +``` + +**Commit:** `refactor: support setup-only runtime mode` + +## Task 1.6:实现钉钉凭据验证器 + +**创建:** + +- `internal/dingtalkconfig/verifier.go` +- `internal/dingtalkconfig/verifier_test.go` + +**行为:** + +1. 使用候选Client ID/Secret调用钉钉Token接口。 +2. 使用短超时,限制响应大小。 +3. 返回结构化结果:`oauth_ok`、稳定错误码、验证时间。 +4. 不返回、不记录Access Token。 +5. 第一步只验证OAuth;Stream连接验证在运行管理器中单独记录,避免Token成功被误报为全通道成功。 + +**测试:** 使用`httptest.Server`覆盖成功、错误凭据、限流、超时、超大响应和脱敏错误。 + +**Commit:** `feat: verify DingTalk application credentials` + +--- + +# 里程碑M2:Web Setup、首位管理员和配置总览 + +## Task 2.1:建立管理员Web安全边界 + +**创建:** + +- `internal/adminweb/server.go` +- `internal/adminweb/auth.go` +- `internal/adminweb/auth_test.go` + +**规则:** + +- 只允许HTTP监听地址为loopback;复用并泛化`httpapi.ValidateLoopbackListenAddress`。 +- Setup使用本机生成的Bootstrap Token;token文件`0600`。 +- 正常管理员后台首版复用`DOBOTAI_ADMIN_TOKEN`,使用HttpOnly、SameSite=Strict、短时会话Cookie;不把Token放URL。 +- 所有后台响应`Cache-Control: no-store`。 +- 所有修改请求要求CSRF Token。 +- 管理员建立后,Bootstrap权限立即失效。 + +**测试:** 非loopback拒绝、无Token拒绝、CSRF失败拒绝、Cookie安全属性、Bootstrap失效。 + +**Commit:** `feat: secure loopback admin web access` + +## Task 2.2:实现Setup页面 + +**创建:** + +- `internal/adminweb/templates/setup.html` +- `internal/adminweb/templates/layout.html` +- `internal/adminweb/assets/admin.css` +- `internal/adminweb/setup.go` +- `internal/adminweb/setup_test.go` + +**页面:** + +```text +步骤1:输入Client ID和Client Secret +步骤2:测试凭据 +步骤3:保存候选配置 +步骤4:建立Stream验证通道 +步骤5:绑定首位管理员 +``` + +**安全:** + +- HTML中绝不能出现已保存Secret。 +- 编辑页面只显示`Client Secret:已配置`。 +- 表单提交体不得进入请求日志。 +- 凭据验证失败时不激活。 + +**Commit:** `feat: add DingTalk setup wizard` + +## Task 2.3:实现首位管理员绑定码 + +**创建迁移:** + +- `db/migrations/000013_admin_bootstrap.up.sql` +- `db/migrations/000013_admin_bootstrap.down.sql` +- `db/migrations/000013_admin_bootstrap_contract_test.go` + +**创建代码:** + +- `internal/settings/bootstrap.go` +- `internal/settings/bootstrap_test.go` +- `internal/store/postgres/admin_bootstrap.go` + +**表/状态:** + +```text +admin_bootstrap_challenges +- id +- tenant_key +- code_hash +- expires_at +- attempts +- max_attempts +- candidate_staff_id +- candidate_union_id +- candidate_display_name +- candidate_department +- status: pending/candidate_detected/confirmed/expired/locked +``` + +**规则:** + +- 6位随机码,10分钟有效,只保存哈希。 +- 生成新码使旧码失效。 +- 最多5次失败。 +- 只接受私聊;群内绑定码拒绝。 +- 钉钉回调只登记候选人,不立即授权。 +- 后台确认后创建`super_admin`并让码永久失效。 + +**Commit:** `feat: add first administrator bootstrap challenge` + +## Task 2.4:实现配置总览和组件状态页 + +**创建:** + +- `internal/status/service.go` +- `internal/status/service_test.go` +- `internal/adminweb/status.go` +- `internal/adminweb/templates/status.html` +- `internal/adminweb/status_test.go` + +**第一版组件卡:** + +```text +运行版本 +PostgreSQL +钉钉OAuth +钉钉Stream +管理员 +WeKnora +问题表Outbox +FAQ Outbox +技术支持通知 +Private OSS图片 +``` + +**每个组件只返回:** + +```text +状态、稳定错误码、最后成功时间、最后检查时间、非敏感摘要 +``` + +禁止返回Secret、Token、完整签名URL和原始上游错误正文。 + +**状态来源:** + +- 静态配置:配置仓库。 +- Stream:运行管理器内存状态和最后事件。 +- Outbox:PostgreSQL聚合计数。 +- 外部组件:短超时健康探针;页面加载不应长时间阻塞,允许显示最近缓存结果。 + +**Commit:** `feat: add configuration and component status dashboard` + +## M2退出条件 + +```text +无钉钉凭据时后台可用且Stream未启动 +错误凭据不能进入Active +正确凭据可进入waiting_first_admin +首位管理员必须经钉钉本人+后台双确认 +后台不回显任何Secret +``` + +--- + +# 里程碑M3:独立/setting控制流 + +## Task 3.1:实现严格命令解析器 + +**创建:** + +- `internal/settingscommand/parser.go` +- `internal/settingscommand/parser_test.go` + +**接受:** + +```text +/setting +/settings +/设置 +/setting 123456 +``` + +**兼容:** `/settiing`只返回“是否要打开/setting”的提示,不直接执行敏感操作。 + +**拒绝误触发:** + +```text +如何设置机器人? +请回答/setting是什么意思 +abc /setting +``` + +**Commit:** `feat: parse explicit settings commands` + +## Task 3.2:在QA之前增加设置路由 + +**修改:** + +- `internal/channels/dingtalk/handler.go` +- `internal/channels/dingtalk/handler_test.go` + +**创建:** + +- `internal/settingscommand/router.go` +- `internal/settingscommand/router_test.go` + +**接口:** + +```go +type Router interface { + Match(context.Context, IncomingSettingMessage) (bool, error) + Handle(context.Context, IncomingSettingMessage) error +} +``` + +`HandlerOptions`增加`SettingsRouter`。处理顺序固定: + +```text +群聊未@过滤 +→ 基础回调身份/回复目标校验 +→ settings.Match + ├─ true:settings.Handle并return + └─ false:解析普通消息并调用QA +``` + +图片和富文本中的命令首版不触发设置,仅纯文本触发。 + +**核心门禁测试:** 设置命令命中后: + +```text +QAAsker调用次数=0 +ImageDownloader调用次数=0 +OutboundRewriter调用次数=0 +Card问答Sender调用次数=0 +``` + +**Commit:** `feat: route settings commands before QA` + +## Task 3.3:新增设置会话迁移与状态机 + +**创建:** + +- `db/migrations/000014_setting_sessions.up.sql` +- `db/migrations/000014_setting_sessions.down.sql` +- `db/migrations/000014_setting_sessions_contract_test.go` +- `internal/settingssession/service.go` +- `internal/settingssession/service_test.go` +- `internal/store/postgres/setting_sessions.go` + +**字段:** + +```text +tenant_key +staff_id +conversation_id +conversation_type +current_step +pending_action +draft_config JSONB +expires_at +updated_at +``` + +**规则:** + +- 10分钟过期。 +- 同一管理员同一时刻最多一个活动流程。 +- `取消`立即删除草稿;`上一步`退回已定义步骤。 +- 只保存结构化草稿,不保存完整消息、完整链接或Secret。 + +**Commit:** `feat: add expiring settings conversation state` + +## Task 3.4:证明设置流量零问答持久化 + +**创建:** + +- `internal/channels/dingtalk/settings_isolation_test.go` +- `internal/store/postgres/settings_isolation_contract_test.go` + +**测试矩阵:** + +```text +普通用户私聊/setting +管理员私聊/setting +群内管理员@机器人 /setting +/setting 绑定码 +设置状态中的“中文” +设置状态中的AI表格链接 +取消 +超时后的普通问题 +``` + +**每个设置消息断言:** + +```text +messages +0 +turns +0 +session_mappings +0 +coverage_decisions +0 +support_cases +0 +question_table_exports +0 +faq export状态无变化 +WeKnora CreateSession/AgentChat调用 +0 +``` + +超时后不符合显式命令的文本重新按普通问答处理,防止设置状态永久吞消息。 + +**Commit:** `test: enforce settings traffic isolation from QA` + +--- + +# 里程碑M4:个人多语言与系统默认语言 + +## Task 4.1:新增用户偏好数据模型 + +**创建:** + +- `db/migrations/000015_user_preferences.up.sql` +- `db/migrations/000015_user_preferences.down.sql` +- `db/migrations/000015_user_preferences_contract_test.go` +- `internal/preferences/service.go` +- `internal/preferences/service_test.go` +- `internal/store/postgres/preferences.go` + +**唯一键:** + +```sql +UNIQUE(tenant_key, channel, external_actor_id) +``` + +**首版语言:** + +```text +auto +zh-CN +en +ja +ko +es +``` + +管理员与普通用户使用同一偏好表;管理员角色不覆盖个人语言。 + +**Commit:** `feat: persist per-user language preferences` + +## Task 4.2:实现普通用户/管理员设置菜单 + +**修改:** + +- `internal/settingscommand/router.go` +- `internal/settingscommand/router_test.go` + +**行为:** + +- 普通用户:只显示个人语言。 +- 管理员:显示“我的设置”和“系统管理”。 +- 群内个人设置引导到私聊,避免群内刷卡。 +- 系统默认语言只有管理员可改。 + +**Commit:** `feat: add role-aware settings menus` + +## Task 4.3:把语言偏好传入WeKnora + +**修改:** + +- `internal/core/types.go` +- `internal/channels/dingtalk/handler.go` +- `internal/qa/service.go` +- 对应测试文件 + +**推荐实现:** 不污染原始审计问题文本。`turn.Question`继续保存用户原文;仅在发往WeKnora的`AgentChatRequest.Query`构造阶段附加受控语言指令。 + +**优先级:** + +```text +本次显式语言要求 +> 用户个人语言 +> 群默认语言 +> 系统默认语言 +> auto跟随问题语言 +``` + +“本次显式语言要求”首版只识别明确、有限模式,避免模型猜测覆盖用户偏好。 + +**验证:** 审计问题仍为原文,WeKnora请求包含语言约束,设置流量仍不进入QA。 + +**Commit:** `feat: apply user language preference to answers` + +--- + +# 里程碑M5:技术支持群对话式绑定 + +## Task 5.1:扩展资源绑定模型 + +**修改:** + +- `internal/settings/types.go` +- `internal/store/postgres/settings.go` +- 对应测试 + +**资源类型:** + +```text +support_group +question_table +faq_table +card_template +``` + +每个业务对象/Outbox必须能记录使用的配置版本,避免换目标后旧pending任务静默改道。 + +**默认策略:** + +```text +新Case使用新支持群 +旧Case继续使用创建时的绑定版本 +``` + +**Commit:** `feat: version external resource bindings` + +## Task 5.2:实现群内绑定流程 + +**修改:** + +- `internal/settingscommand/router.go` +- `internal/channels/dingtalk/handler.go` +- 对应测试 + +**流程:** + +```text +管理员在群内@机器人 /setting +→ 验证tenant_key + staff_id管理员权限 +→ 从回调读取ConversationID和ConversationTitle +→ 展示“设为技术支持群” +→ 二次确认 +→ 创建待验证绑定 +``` + +普通用户执行同样操作只能收到私聊个人设置提示。 + +**Commit:** `feat: bind support group from DingTalk conversation` + +## Task 5.3:实现显式测试发送与激活 + +**修改:** + +- `internal/channels/dingtalk/group_sender.go` +- `internal/status/service.go` +- 设置路由和测试 + +**规则:** + +- 只有管理员点击“发送测试消息”才有外部副作用。 +- 测试成功后才能激活。 +- 失败只记录稳定错误码,不保存Webhook/Token/原始上游响应。 + +**集成验收:** 需要主人明确允许向目标群发送一条标记为测试的消息。 + +**Commit:** `feat: verify and activate support group binding` + +--- + +# 里程碑M6:问题AI表格与FAQ表格链接绑定 + +## Task 6.1:实现安全链接解析器 + +**创建:** + +- `internal/notablebinding/link.go` +- `internal/notablebinding/link_test.go` + +**输出:** + +```text +base_id / dentry_id +sheet_id +view_id +可选record_id(只用于验证,不作为绑定目标) +``` + +**规则:** + +- 仅接受审核过的钉钉域名和HTTPS。 +- 限制链接长度。 +- 不跟随任意重定向。 +- 解析后立即丢弃完整原始链接。 +- 日志和审计只记录脱敏资源摘要。 + +**Commit:** `feat: parse DingTalk AI Table resource links` + +## Task 6.2:实现表结构读取和逻辑字段映射 + +**创建:** + +- `internal/notablebinding/schema.go` +- `internal/notablebinding/schema_test.go` + +**修改:** + +- `internal/questiontable/client.go` +- 对应客户端测试 + +**规则:** + +- 按“字段显示名+字段类型”匹配,不能只按名字。 +- 缺失、重复、类型错误都阻止激活。 +- 映射保存为配置版本中的逻辑字段→Provider字段ID。 +- 问题表9字段和FAQ表4字段分别校验。 + +**Commit:** `feat: validate and map AI Table schemas` + +## Task 6.3:实现问题表绑定流程 + +**修改:** + +- `internal/settingscommand/router.go` +- `cmd/dobotai/question_table_sync.go` +- `cmd/dobotai/main.go` +- 对应测试 + +**流程:** + +```text +管理员私聊/setting +→ 绑定问题AI表格 +→ 发送任意记录链接 +→ 解析ID并丢弃原链接 +→ 当前管理员作为候选Operator +→ 读权限和字段校验 +→ 展示映射 +→ 经确认执行测试写入/回读 +→ 激活配置版本 +``` + +真实写入测试必须由主人单独确认。 + +**Outbox策略:** 激活前不启动Dispatcher;切换后旧pending记录保留原配置版本,若旧代码尚无该字段则先迁移补充。 + +**Commit:** `feat: bind question AI Table through settings` + +## Task 6.4:实现FAQ表绑定流程 + +**修改:** + +- `internal/settingscommand/router.go` +- `cmd/dobotai/faq_workflow.go` +- `cmd/dobotai/main.go` +- 对应测试 + +**额外验证:** `RecordLinkBuilder`生成的“去回答”链接可打开正确表/视图,且不依赖测试行作为永久目标。 + +**Commit:** `feat: bind FAQ AI Table through settings` + +## Task 6.5:将环境变量配置迁移为数据库配置 + +**修改:** + +- `.env.example` +- `cmd/dobotai/main.go` +- `cmd/dobotai/faq_workflow.go` +- `cmd/dobotai/question_table_sync.go` +- `cmd/dobotai/support_notifications.go` +- 对应测试 + +**迁移策略:** + +1. 首次启动发现数据库无绑定、旧环境变量完整时,后台显示“检测到旧配置”。 +2. 不自动激活;管理员在后台执行导入和验证。 +3. 验证通过后生成数据库配置版本。 +4. 部署完成后再从生产`.env`删除旧标识配置。 +5. Secret仍从SecretStore读取,不进入数据库。 + +**Commit:** `refactor: load DingTalk resource bindings from database` + +--- + +# 里程碑M7:Secret轮换与钉钉应用切换 + +## Task 7.1:实现运行组件管理器 + +**创建:** + +- `internal/runtime/manager.go` +- `internal/runtime/manager_test.go` + +**职责:** + +```text +StartActiveConfig +EnterMaintenance +Drain当前请求(最长30秒) +StopStream +StartStream +Start/Stop问题表、FAQ表和支持通知Poller +ExposeComponentStatus +Rollback +``` + +所有状态转换串行化;同一时刻最多一个正式Stream消费者。 + +**Commit:** `refactor: manage runtime components through lifecycle manager` + +## Task 7.2:实现同Client ID的Secret轮换 + +**流程:** + +```text +输入新Secret +→ 使用候选Secret验证OAuth +→ 保存候选Secret文件 +→ 进入维护窗口 +→ 停旧Stream +→ 激活新Secret引用 +→ 启新Stream +→ 健康检查 +→ 成功后保留旧Secret 24小时回滚 +``` + +失败时自动恢复旧Secret和旧Stream。 + +**Commit:** `feat: rotate DingTalk client secret safely` + +## Task 7.3:实现候选应用验证模式 + +**规则:** + +- 新Client ID+Secret保存为candidate。 +- 候选Stream只能处理`/setting verify`和绑定验证,不能处理普通问答。 +- 校验OAuth、Stream、通讯录、卡片模板、支持群、问题表和FAQ表权限。 +- 有外部副作用的群消息/测试行必须显式确认。 + +**Commit:** `feat: validate candidate DingTalk application` + +## Task 7.4:实现应用切换和回滚 + +**流程:** + +```text +影响预览 +→ 管理员输入确认词 +→ 30秒维护窗口 +→ Drain旧请求 +→ 停旧正式Stream +→ 激活候选配置 +→ 启新正式Stream +→ 自动无副作用验收 +→ 成功/失败自动回滚 +``` + +**强制规则:** + +```text +旧正式Stream未停止前,新Stream不得处理普通问答 +新应用Stream/管理员识别/基础问答失败→整体回滚 +群/表格/卡片验证失败→默认禁止切换,不带病激活 +旧Secret 24小时后删除,只保留脱敏审计 +``` + +**Commit:** `feat: switch DingTalk applications with rollback` + +--- + +# 4. 全局测试与验收矩阵 + +## 每个Task后 + +只运行目标测试,不反复全仓读取或全量测试。 + +```bash +go test -count=1 +go test -race -count=1 +go vet +git diff --check +``` + +## 每个里程碑后 + +```bash +go test ./cmd/dobotai ./internal/httpapi ./internal/adminweb ./internal/settings ./internal/settingscommand ./internal/store/postgres ./db/migrations -count=1 +go build -o /tmp/dobotai-next ./cmd/dobotai +rm -f /tmp/dobotai-next +``` + +只有主人明确允许时才执行全仓测试。 + +## 关键验收 + +### Setup模式 + +```text +DingTalk凭据为空:服务启动,后台可访问,Stream=未启动 +部分凭据:后台显示错误,Stream=未启动 +错误凭据:不能激活 +正确凭据:OAuth通过,等待Stream/管理员绑定 +``` + +### Secret安全 + +```text +数据库无Secret明文 +HTML无Secret回显 +日志无Secret/Token +Secret目录0700、文件0600 +替换Secret不留下无限历史副本 +``` + +### 设置隔离 + +```text +/setting及后续设置消息: +messages/turns/session_mappings/coverage/support_cases/AI表格Outbox增量全部为0 +WeKnora调用次数为0 +``` + +### 权限 + +```text +普通用户不能改系统配置 +管理员拥有个人语言设置 +首位管理员不能由“先到先得”产生 +群绑定必须校验当前操作者是管理员 +``` + +### 应用切换 + +```text +任意时刻正式Stream消费者≤1 +切换失败恢复旧配置 +回滚后旧机器人继续正常问答 +无重复Turn和重复群通知 +``` + +# 5. 预计文件变化汇总 + +**新增包:** + +```text +internal/settings/ +internal/secretstore/ +internal/dingtalkconfig/ +internal/adminweb/ +internal/status/ +internal/settingscommand/ +internal/settingssession/ +internal/preferences/ +internal/notablebinding/ +internal/runtime/ +``` + +**新增迁移:** + +```text +000012_system_settings +000013_admin_bootstrap +000014_setting_sessions +000015_user_preferences +后续如需Outbox配置版本字段,再新增000016,禁止回改已发布迁移 +``` + +**重点修改:** + +```text +cmd/dobotai/main.go +cmd/dobotai/faq_workflow.go +cmd/dobotai/question_table_sync.go +internal/httpapi/server.go +internal/channels/dingtalk/handler.go +internal/core/types.go +internal/qa/service.go +internal/questiontable/client.go +internal/store/postgres/*.go +.env.example +``` + +# 6. 风险与控制 + +1. **当前工作区混杂三项未提交功能。** 先完成M0,使用`git add -p`拆分,禁止直接开始设置功能。 +2. **Setup模式与当前强制初始化冲突。** 先建立运行状态机,再做页面,避免HTML先行但进程仍无法无凭据启动。 +3. **动态切换涉及多个长期goroutine。** 到M7才引入统一运行管理器;首版不提前做热切换。 +4. **设置消息泄漏到问答链路。** M3以数据库增量和Mock调用次数双重合同测试锁死。 +5. **AI表格字段ID属于具体表。** 每次绑定都读取Schema并保存版本映射,禁止沿用旧字段ID。 +6. **切换资源后旧Outbox改道。** 每条Case/Outbox固定配置版本;不静默改发。 +7. **后台认证首版依赖本地Token。** 因后台只监听loopback且通过SSH隧道访问,首版可接受;公网或多管理员Web登录另立需求。 +8. **真实验证有外部副作用。** 发送群测试消息、AI表格写测试行、部署和迁移均需主人单独确认。 + +# 7. 开始执行时的第一批操作 + +只执行M0,不同时开始M1: + +```text +1. 重新核对当前diff归属 +2. 建立合并前备份 +3. 提交忽略规则 +4. 拆分并提交图片出站 +5. 拆分并提交异步ACK/去重 +6. 拆分并提交Session恢复 +7. 跑目标测试和构建 +8. 汇报Commit与工作区状态 +9. 等主人确认后进入M1 +``` + +每个阶段都遵循: + +```text +先写失败测试 +→ 确认失败原因正确 +→ 最小实现 +→ 目标测试通过 +→ 竞态/静态检查 +→ 独立Commit +→ 不Push、不部署 +``` diff --git a/README.md b/README.md index 5bc5b41..0dce091 100644 --- a/README.md +++ b/README.md @@ -1,76 +1,148 @@ -# DobotAI Platform +# DobotAI 平台 -DobotAI is the external enterprise integration layer for official WeKnora. It does not import WeKnora packages, modify WeKnora source, or access the WeKnora database. +DobotAI 是 WeKnora 的企业外部渠道集成层,负责钉钉协议、身份与会话映射、消息编排、流式卡片、媒体收发、覆盖判定和人工支持通知。它只通过 WeKnora 官方 REST/SSE API 调用知识问答与 Agent Chat:不导入 WeKnora 私有包、不修改 WeKnora 源码,也不访问 WeKnora 数据库。 -Current milestone: channel-bound Agent QA core. +## 当前能力 -Implemented: +- 通过官方 `POST /api/v1/sessions` 与 `POST /api/v1/agent-chat/:session_id` 调用 WeKnora; +- 严格解析 SSE 的 `answer`、`references`、`tool_call`、`tool_result`、`error` 与终止事件;`error + done=false` 被视为可恢复的工具错误,不会提前结束钉钉卡片; +- 解析普通引用及智能推理工具结果中的检索证据,供覆盖判定与后端审计使用; +- 按渠道、会话和用户维护长期 WeKnora Session,并保证回调幂等; +- 钉钉 Stream 机器人支持文本、richText 以及多图片输入;图片下载经过钉钉官方接口、大小与文件签名校验后,才以 WeKnora 通用多模态请求发送; +- 钉钉 AI 流式卡片与最终消息回退;通道侧保留原始回答,不修改 WeKnora 持久化消息; +- 默认快速问答,支持 `/think <问题>` 单次推理、`/think on` 持续推理、`/think off` 或 `/rag` 关闭推理;快速问答与智能推理共用同一 WeKnora Session; +- 用户级推理轮次、空闲到期、提示开关和首次使用指引; +- 成功回答的覆盖判定、持久化 Support Case、FAQ Outbox 与钉钉人工支持群通知; +- 对已覆盖答案点踩时创建 `feedback_down` 人工处理提醒;对已先因未覆盖创建 Case 的同一问题保持“一题一个 Case”幂等; +- 可选的钉钉问题表异步写入;写入失败不会改变问答成功状态; +- 可选的回答图片外发:仅将 WeKnora `resource://` 图片通过鉴权下载、内容哈希转存到私有 OSS 后,以受控 HTTPS 地址提供给钉钉。 -- official `POST /api/v1/sessions` adapter; -- official `POST /api/v1/agent-chat/:session_id` adapter; -- fail-closed SSE parsing for `references`, `answer`, `error`, and terminal `done`; -- per-channel/per-conversation Agent binding; -- long-lived direct-user sessions; -- shared-group sessions, with optional group+user policy; -- external-message idempotency; -- independent PostgreSQL session/turn storage; -- authenticated internal `POST /v1/qa` ingress endpoint. -- DingTalk Stream text ingress (official SDK) wired into `cmd/dobotai`. +## 架构边界 -## DingTalk channel (Stream, text only) +```text +钉钉 / 内部调用方 + ↓ + DobotAI + ├─ 钉钉 Stream、richText、图片、AI 卡片、反馈与通知 + ├─ 独立 PostgreSQL:渠道身份、消息、会话映射、Turn、覆盖与支持流程 + └─ WeKnora 官方 REST / SSE API + ↓ + WeKnora:检索、Agent、知识与引用 +``` -- Uses the official DingTalk Stream SDK (`dingtalk-stream-sdk-go`); no public webhook endpoint is exposed. -- Text messages only for now. Images, OpenAPI fallback, and card replies are not implemented yet. -- Group chats are handled only when the bot is @-mentioned; other group messages are ignored. -- Sessions: direct chats use one long-lived session per user; group chats share one session per group (default `shared` policy). -- Replies are sent via the callback's `sessionWebhook`, which is fail-closed: only `https` URLs on `*.dingtalk.com` (port 443, no redirects) are accepted. -- Required env vars to enable (all three or none): `DINGTALK_CLIENT_ID`, `DINGTALK_CLIENT_SECRET`, `DOBOTAI_TENANT_KEY`. Partial configuration is a fatal startup error. +责任边界: -## WeKnora baseline +- **DobotAI**:钉钉协议、媒体收发、会话映射、命令路由、卡片、覆盖判定、人工支持、渠道审计。 +- **WeKnora**:通用 Agent Chat、检索、知识存储、引用与模型调用。 +- **DobotAI PostgreSQL**:只保存渠道与业务编排数据,不保存 WeKnora 知识正文。 +- **Redis**:仅用于队列、重试、幂等租约和短期状态。 -Target policy: latest stable official Release/Tag. The newest locally fetched stable tag is `v0.6.3`. Online GitHub verification is pending because DNS/proxy access was unavailable during initialization. +## 钉钉 Stream -## Run +使用官方 `dingtalk-stream-sdk-go`,不暴露公网回调入口。 -1. Create an independent PostgreSQL database named `dobotai`. -2. Apply `db/migrations/000001_core.up.sql` to that database only. -3. Copy `.env.example` to a local `.env` and supply secrets outside Git. -4. Export the variables and run: +- 群聊仅在机器人被 `@` 时处理; +- 私聊按用户保持长期会话;群聊默认按群共享会话; +- 回调 `sessionWebhook` 严格限制为 `https`、`*.dingtalk.com`、443端口且不允许重定向; +- 启用 Stream 必须同时设置以下三项;三者均为空时渠道禁用,部分配置会失败关闭: + +```text +DINGTALK_CLIENT_ID +DINGTALK_CLIENT_SECRET +DOBOTAI_TENANT_KEY +``` + +## 推理模式命令 + +```text +/think <问题> 仅当前问题使用智能推理 +/think on 开启持续智能推理 +/think off 或 /rag 关闭持续智能推理 +/setting rounds <1-50> 设置持续推理自动关闭轮数 +/setting hint 设置剩余轮次提示 +/help、/帮助、/h 查看当前模式和帮助 +``` + +持续推理默认最多10轮,成功回答才消耗轮次;10分钟无交互后逻辑到期,下一次问题自动回到快速问答。状态按 `tenant + channel + external_actor_id` 隔离。 + +## 覆盖与人工支持 + +- 有结构化检索引用的回答标记为已覆盖; +- 没有引用但已执行检索的回答标记为未覆盖; +- 纯图片视觉识别单独记录为 `covered_visual_recognition`,不计入“未覆盖”; +- 无权威知识时,产品统一回复:`当前暂无已发布的权威知识,暂不建议操作。`; +- 人工通知只带当前问题和同一用户此前最多5个问题,不包含回答、引用或置信度; +- 未覆盖与点踩共用幂等 Support Case,避免对同一 Turn 重复通知。 + +## 配置 + +复制 `.env.example` 为仅本机可读的运行时环境文件,并在 Git 外注入真实值。不得提交 API Key、数据库密码、钉钉凭据、OSS AccessKey、预签名 URL 或真实用户/群组标识。 + +关键配置: + +```text +DOBOTAI_LISTEN_ADDR +DOBOTAI_INGRESS_TOKEN +DOBOTAI_AGENT_BINDINGS +DOBOTAI_QUICK_AGENT_ID +DOBOTAI_REASONING_AGENT_ID +WEKNORA_BASE_URL +WEKNORA_API_KEY +DATABASE_URL +``` + +可选能力必须整组配置或整组留空: + +- 钉钉 Stream; +- 钉钉 AI 卡片; +- 未覆盖问题 FAQ 表; +- 人工支持群通知; +- 问题表异步写入; +- 回答图片私有 OSS 外发。 + +任何部分配置均应在启动时失败关闭,而不是以不完整权限运行。 + +## 数据库迁移 + +DobotAI 使用独立 PostgreSQL,禁止指向 WeKnora 数据库。生产部署前必须按版本顺序执行并演练 `db/migrations/` 中的迁移;当前发布范围包含: + +```text +000001_core ... 000018_coverage_visual_recognition_reason +000019_reasoning_mode_state +000020_feedback_support_trigger +``` + +迁移前应执行逻辑备份并验证恢复;迁移、二进制部署和钉钉渠道切换是独立步骤,不能把健康检查代替真实渠道验收。 + +## 本地运行 ```bash go run ./cmd/dobotai ``` -Health check: +健康检查: ```bash curl http://127.0.0.1:8090/healthz ``` -Internal QA request: +运行版本: ```bash -curl -X POST http://127.0.0.1:8090/v1/qa \ - -H "Authorization: Bearer $DOBOTAI_INGRESS_TOKEN" \ - -H 'Content-Type: application/json' \ - -d '{ - "tenant_key":"default", - "channel":"dingtalk", - "conversation_type":"direct", - "external_user_id":"user-1", - "external_message_id":"message-1", - "query":"hello" - }' +curl http://127.0.0.1:8090/version ``` -## Hard boundaries +部署脚本应将 `version`、`commit_sha` 和 `build_time` 写入二进制,并仅在 `/version` 返回预期提交时接受部署。候选源码必须干净,避免运行版本掩盖未提交改动。 -- No WeKnora source modifications. -- No custom WeKnora tables or columns. -- No direct WeKnora database access. -- No private WeKnora package imports. -- All compatibility logic stays in `internal/weknora`. -- Business data stays in DobotAI PostgreSQL. -- Redis will be used only for queues, retries, idempotency leases, and temporary state. +## 安全要求 -See `docs/architecture.md` for ownership and migration decisions. +- 不修改 WeKnora 源码、Schema 或私有包; +- 不直接连接 WeKnora 数据库; +- 不将凭据、Token、预签名 URL 或知识正文写入日志; +- 不接受任意外部图片 URL 作为可信媒体; +- 对钉钉图片、WeKnora `resource://` 图片和 OSS 返回体均执行来源、大小、类型和签名校验; +- 外发 OSS Bucket 保持私有; +- 生产、测试的钉钉应用、数据库、OSS Bucket 和凭据必须相互隔离; +- 生产上线必须使用已验收的同一构建产物,禁止在生产重新编译。 + +更多设计与边界见 `docs/architecture.md`。 \ No newline at end of file diff --git a/cmd/directory-import/main.go b/cmd/directory-import/main.go new file mode 100644 index 0000000..e919c54 --- /dev/null +++ b/cmd/directory-import/main.go @@ -0,0 +1,85 @@ +package main + +import ( + "context" + "errors" + "flag" + "fmt" + "io" + "os" + "strings" + "time" + + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/directory" + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/store/postgres" +) + +func main() { + if err := run(os.Args[1:], os.Stdout); err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } +} + +func run(args []string, out io.Writer) error { + flags := flag.NewFlagSet("directory-import", flag.ContinueOnError) + flags.SetOutput(io.Discard) + csvPath := flags.String("csv", "", "path to tested DingTalk directory CSV output") + tenant := flags.String("tenant", "", "tenant key") + databaseURLFile := flags.String("database-url-file", "", "file containing DATABASE_URL") + validateOnly := flags.Bool("validate-only", false, "validate CSV without connecting to PostgreSQL") + if err := flags.Parse(args); err != nil { + return errors.New("invalid directory import arguments") + } + if strings.TrimSpace(*csvPath) == "" || strings.TrimSpace(*tenant) == "" { + return errors.New("-csv and -tenant are required") + } + input, err := os.Open(*csvPath) + if err != nil { + return errors.New("open directory CSV failed") + } + defer input.Close() + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) + defer cancel() + if *validateOnly { + count, importErr := directory.ImportCSV(ctx, *tenant, input, validationWriter{}) + if importErr != nil { + return errors.New("directory CSV validation failed") + } + _, _ = fmt.Fprintf(out, "validated_profiles=%d\n", count) + return nil + } + if strings.TrimSpace(*databaseURLFile) == "" { + return errors.New("-database-url-file is required for import") + } + databaseURL, err := readSecretFile(*databaseURLFile) + if err != nil { + return err + } + store, err := postgres.Open(ctx, databaseURL) + if err != nil { + return errors.New("open directory database failed") + } + defer store.Close() + count, err := directory.ImportCSV(ctx, *tenant, input, store) + if err != nil { + return errors.New("directory CSV import failed") + } + _, _ = fmt.Fprintf(out, "imported_profiles=%d\n", count) + return nil +} + +type validationWriter struct{} + +func (validationWriter) UpsertDirectoryProfiles(context.Context, string, []directory.Profile) error { + return nil +} + +func readSecretFile(path string) (string, error) { + raw, err := os.ReadFile(strings.TrimSpace(path)) + if err != nil { return "", errors.New("read database URL file failed") } + if len(raw) > 16<<10 { return "", errors.New("database URL file is too large") } + value := strings.TrimSpace(string(raw)) + if value == "" { return "", errors.New("database URL file is empty") } + return value, nil +} diff --git a/cmd/directory-import/main_test.go b/cmd/directory-import/main_test.go new file mode 100644 index 0000000..4a747b2 --- /dev/null +++ b/cmd/directory-import/main_test.go @@ -0,0 +1,48 @@ +package main + +import ( + "bytes" + "os" + "path/filepath" + "strings" + "testing" +) + +func TestReadSecretFileTrimsValue(t *testing.T) { + path := filepath.Join(t.TempDir(), "database_url") + if err := os.WriteFile(path, []byte(" postgres://secret-value \n"), 0o600); err != nil { t.Fatal(err) } + value, err := readSecretFile(path) + if err != nil { t.Fatalf("readSecretFile: %v", err) } + if value != "postgres://secret-value" { t.Fatalf("value=%q", value) } +} + +func TestReadSecretFileErrorDoesNotLeakContents(t *testing.T) { + path := filepath.Join(t.TempDir(), "empty") + if err := os.WriteFile(path, []byte(""), 0o600); err != nil { t.Fatal(err) } + _, err := readSecretFile(path) + if err == nil { t.Fatal("expected error") } + if strings.Contains(err.Error(), "secret-value") { t.Fatalf("error leaked secret: %v", err) } +} + +func TestRunValidateOnlyDoesNotRequireDatabase(t *testing.T) { + csvPath := filepath.Join(t.TempDir(), "directory.csv") + if err := os.WriteFile(csvPath, []byte("user_id,union_id,name,nickname,title,department_ids,dept_name\nstaff-1,,张三,,工程师,100,技术支持部\n"), 0o600); err != nil { + t.Fatal(err) + } + var out bytes.Buffer + err := run([]string{"-csv", csvPath, "-tenant", "tenant-a", "-validate-only"}, &out) + if err != nil { + t.Fatalf("run validate-only: %v", err) + } + if !strings.Contains(out.String(), "validated_profiles=1") { + t.Fatalf("output=%q", out.String()) + } +} + +func TestRunRequiresCSVAndDatabaseURLFileBeforeConnecting(t *testing.T) { + var out bytes.Buffer + for _, args := range [][]string{{}, {"-csv", "snapshot.csv"}} { + err := run(args, &out) + if err == nil { t.Fatalf("run(%v) expected error", args) } + } +} diff --git a/cmd/dobotai/candidate_activation.go b/cmd/dobotai/candidate_activation.go new file mode 100644 index 0000000..e3c3db0 --- /dev/null +++ b/cmd/dobotai/candidate_activation.go @@ -0,0 +1,81 @@ +package main + +import ( + "context" + "errors" + "time" + + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/dingtalkconfig" + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/questiontable" + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/secretstore" + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/settings" +) + +type candidateConfigRepository interface { + CandidateDingTalkConfig(context.Context, string) (string, string, error) + ActivateDingTalkCandidate(context.Context, string, string) error +} + +type candidateCredentialVerifier interface { + Verify(context.Context, string, string) dingtalkconfig.Result +} + +var ( + candidateTokenURL = "" + candidateTableBaseURL = "" +) + +type dingTalkCandidateActivator struct { + tenant string + repo candidateConfigRepository + secrets *secretstore.Store + verifier candidateCredentialVerifier + bindings map[string]settings.ResourceBinding + restart func() +} + +func (a *dingTalkCandidateActivator) ActivateCandidate(ctx context.Context) error { + if a == nil || a.repo == nil || a.secrets == nil || a.verifier == nil || a.restart == nil { + return errors.New("candidate_activation_unavailable") + } + clientID, secretRef, err := a.repo.CandidateDingTalkConfig(ctx, a.tenant) + if err != nil { + return errors.New("candidate_not_found") + } + secret, err := a.secrets.Get(secretRef) + if err != nil { + return errors.New("candidate_secret_unavailable") + } + if result := a.verifier.Verify(ctx, clientID, secret); !result.OK { + return errors.New("candidate_oauth_failed") + } + for _, kind := range []string{"question_table", "faq_table"} { + binding, ok := a.bindings[kind] + if !ok { + continue + } + client, err := questiontable.NewClient(questiontable.Config{ClientID: clientID, Secret: secret, BaseID: binding.BaseID, SheetID: binding.SheetID, OperatorID: binding.OperatorID, TokenURL: candidateTokenURL, BaseURL: candidateTableBaseURL}, nil) + if err != nil { + return errors.New("candidate_table_config_failed") + } + fields, err := client.ReadFields(ctx) + if err != nil { + return errors.New("candidate_table_probe_failed") + } + required := questiontable.QuestionSchema() + if kind == "faq_table" { + required = questiontable.FAQSchema() + } + if _, err = questiontable.MapRequiredFields(fields, required); err != nil { + return errors.New("candidate_table_schema_failed") + } + } + if err := a.repo.ActivateDingTalkCandidate(ctx, a.tenant, secretRef); err != nil { + return errors.New("candidate_database_activation_failed") + } + go func() { + time.Sleep(300 * time.Millisecond) + a.restart() + }() + return nil +} diff --git a/cmd/dobotai/candidate_activation_test.go b/cmd/dobotai/candidate_activation_test.go new file mode 100644 index 0000000..ec92d88 --- /dev/null +++ b/cmd/dobotai/candidate_activation_test.go @@ -0,0 +1,75 @@ +package main + +import ( + "context" + "net/http" + "net/http/httptest" + "testing" + "time" + + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/dingtalkconfig" + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/secretstore" + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/settings" +) + +type candidateRepoStub struct { + activated bool + ref string +} + +func (r *candidateRepoStub) CandidateDingTalkConfig(context.Context, string) (string, string, error) { + return "app", r.ref, nil +} +func (r *candidateRepoStub) ActivateDingTalkCandidate(context.Context, string, string) error { + r.activated = true + return nil +} + +type candidateVerifierStub struct{ ok bool } + +func (v candidateVerifierStub) Verify(context.Context, string, string) dingtalkconfig.Result { + return dingtalkconfig.Result{OK: v.ok} +} + +func TestCandidateActivatorRejectsOAuthWithoutActivation(t *testing.T) { + secrets, _ := secretstore.New(t.TempDir()) + ref, _ := secrets.Put("dingtalk", "secret") + repo := &candidateRepoStub{ref: ref} + a := &dingTalkCandidateActivator{tenant: "t", repo: repo, secrets: secrets, verifier: candidateVerifierStub{}, bindings: map[string]settings.ResourceBinding{}, restart: func() {}} + if err := a.ActivateCandidate(context.Background()); err == nil { + t.Fatal("expected error") + } + if repo.activated { + t.Fatal("must not activate") + } +} +func TestCandidateActivatorValidatesSchemasThenActivates(t *testing.T) { + mux := http.NewServeMux() + mux.HandleFunc("/token", func(w http.ResponseWriter, _ *http.Request) { + _, _ = w.Write([]byte(`{"accessToken":"token","expireIn":7200}`)) + }) + mux.HandleFunc("/v1.0/notable/bases/base/sheets/sheet/fields", func(w http.ResponseWriter, _ *http.Request) { + _, _ = w.Write([]byte(`{"value":[{"id":"q","name":"中文问题","type":"text"},{"id":"tm","name":"提问时间","type":"date"},{"id":"u","name":"提问人","type":"user"},{"id":"o","name":"原始问题","type":"text"},{"id":"a","name":"AI答案","type":"text"},{"id":"p","name":"流程触发人员信息","type":"text"},{"id":"l","name":"语言","type":"text"},{"id":"d","name":"部门","type":"text"},{"id":"r","name":"区域","type":"text"}]}`)) + }) + server := httptest.NewServer(mux) + defer server.Close() + secrets, _ := secretstore.New(t.TempDir()) + ref, _ := secrets.Put("dingtalk", "secret") + repo := &candidateRepoStub{ref: ref} + restarted := make(chan struct{}, 1) + a := &dingTalkCandidateActivator{tenant: "t", repo: repo, secrets: secrets, verifier: candidateVerifierStub{ok: true}, bindings: map[string]settings.ResourceBinding{"question_table": {BaseID: "base", SheetID: "sheet", OperatorID: "u"}}, restart: func() { restarted <- struct{}{} }} + oldTokenURL, oldBaseURL := candidateTokenURL, candidateTableBaseURL + candidateTokenURL, candidateTableBaseURL = server.URL+"/token", server.URL + defer func() { candidateTokenURL, candidateTableBaseURL = oldTokenURL, oldBaseURL }() + if err := a.ActivateCandidate(context.Background()); err != nil { + t.Fatal(err) + } + if !repo.activated { + t.Fatal("expected activation") + } + select { + case <-restarted: + case <-time.After(time.Second): + t.Fatal("restart not requested") + } +} diff --git a/cmd/dobotai/directory_wiring_test.go b/cmd/dobotai/directory_wiring_test.go new file mode 100644 index 0000000..b6cc2ca --- /dev/null +++ b/cmd/dobotai/directory_wiring_test.go @@ -0,0 +1,27 @@ +package main + +import ( + "os" + "regexp" + "strings" + "testing" +) + +func TestMainWiresDirectoryResolverIntoDingTalkHandler(t *testing.T) { + raw, err := os.ReadFile("main.go") + if err != nil { + t.Fatalf("read main.go: %v", err) + } + src := string(raw) + for _, required := range []string{ + "directory.NewDingTalkLookup", + "directory.NewResolver", + } { + if !strings.Contains(src, required) { + t.Errorf("main.go missing %q", required) + } + } + if !regexp.MustCompile(`Directory:\s*directoryResolver`).MatchString(src) { + t.Error("main.go does not wire directoryResolver into HandlerOptions.Directory") + } +} diff --git a/cmd/dobotai/faq_workflow.go b/cmd/dobotai/faq_workflow.go new file mode 100644 index 0000000..c718ab6 --- /dev/null +++ b/cmd/dobotai/faq_workflow.go @@ -0,0 +1,92 @@ +package main + +import ( + "context" + "errors" + "log" + "os" + "strings" + "time" + + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/faqtable" + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/questiontable" +) + +type faqConfig struct { + BaseID string + SheetID string + ViewID string + OperatorID string + FieldMapping map[string]string +} + +func readFAQConfig() (faqConfig, error) { + cfg := faqConfig{ + BaseID: strings.TrimSpace(os.Getenv("DINGTALK_FAQ_TABLE_BASE_ID")), + SheetID: strings.TrimSpace(os.Getenv("DINGTALK_FAQ_TABLE_SHEET_ID")), + ViewID: strings.TrimSpace(os.Getenv("DINGTALK_FAQ_TABLE_VIEW_ID")), + OperatorID: strings.TrimSpace(os.Getenv("DINGTALK_FAQ_TABLE_OPERATOR_ID")), + } + blank := cfg.BaseID == "" && cfg.SheetID == "" && cfg.ViewID == "" && cfg.OperatorID == "" + complete := cfg.BaseID != "" && cfg.SheetID != "" && cfg.ViewID != "" && cfg.OperatorID != "" + if blank { + return faqConfig{}, nil + } + if !complete { + return faqConfig{}, errors.New("DingTalk FAQ table config must be complete or disabled") + } + return cfg, nil +} + +func buildFAQDispatcher(repo faqtable.ExportRepository, clientID, clientSecret string, cfg faqConfig) (*faqtable.Dispatcher, error) { + if cfg.BaseID == "" { + return nil, nil + } + if repo == nil { + return nil, errors.New("FAQ dispatcher repository is required") + } + client, err := questiontable.NewClient(questiontable.Config{ + ClientID: clientID, Secret: clientSecret, BaseID: cfg.BaseID, + SheetID: cfg.SheetID, OperatorID: cfg.OperatorID, FieldMapping: cfg.FieldMapping, + }, nil) + if err != nil { + return nil, err + } + return faqtable.NewDispatcher(repo, client, nil) +} + +type faqPollerRunner interface { + RunOnce(context.Context) (faqtable.DispatcherStats, error) +} + +func runFAQPoller(ctx context.Context, runner faqPollerRunner, interval time.Duration) { + if runner == nil || interval <= 0 { + return + } + run := func() { + runCtx, cancel := context.WithTimeout(ctx, 30*time.Second) + stats, err := runner.RunOnce(runCtx) + cancel() + if err != nil { + log.Printf("FAQ table dispatch failed") + return + } + if stats.Claimed > 0 { + log.Printf("FAQ table dispatch: claimed=%d exported=%d failed=%d", stats.Claimed, stats.Exported, stats.Failed) + } + } + if ctx.Err() != nil { + return + } + run() + ticker := time.NewTicker(interval) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return + case <-ticker.C: + run() + } + } +} diff --git a/cmd/dobotai/faq_workflow_test.go b/cmd/dobotai/faq_workflow_test.go new file mode 100644 index 0000000..b1836b7 --- /dev/null +++ b/cmd/dobotai/faq_workflow_test.go @@ -0,0 +1,81 @@ +package main + +import ( + "context" + "os" + "strings" + "testing" + "time" + + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/faqtable" +) + +type faqRepoStub struct{} + +func (*faqRepoStub) Claim(context.Context, int, int, time.Time) ([]faqtable.PendingExport, error) { + return nil, nil +} +func (*faqRepoStub) MarkExported(context.Context, string, string) error { return nil } +func (*faqRepoStub) MarkFailed(context.Context, string, string) error { return nil } + +func TestReadFAQConfigDisabledWhenAllBlank(t *testing.T) { + for _, key := range []string{"DINGTALK_FAQ_TABLE_BASE_ID", "DINGTALK_FAQ_TABLE_SHEET_ID", "DINGTALK_FAQ_TABLE_VIEW_ID", "DINGTALK_FAQ_TABLE_OPERATOR_ID"} { + t.Setenv(key, "") + } + cfg, err := readFAQConfig() + if err != nil || cfg.BaseID != "" { + t.Fatalf("cfg=%+v err=%v", cfg, err) + } +} + +func TestReadFAQConfigRejectsPartialValues(t *testing.T) { + t.Setenv("DINGTALK_FAQ_TABLE_BASE_ID", "base") + t.Setenv("DINGTALK_FAQ_TABLE_SHEET_ID", "") + t.Setenv("DINGTALK_FAQ_TABLE_VIEW_ID", "view") + t.Setenv("DINGTALK_FAQ_TABLE_OPERATOR_ID", "operator") + if _, err := readFAQConfig(); err == nil { + t.Fatal("expected partial-config error") + } +} + +func TestBuildFAQDispatcherRequiresRepositoryWhenEnabled(t *testing.T) { + cfg := faqConfig{BaseID: "base", SheetID: "sheet", ViewID: "view", OperatorID: "operator"} + if _, err := buildFAQDispatcher(nil, "client", "secret", cfg); err == nil { + t.Fatal("expected repository error") + } + if d, err := buildFAQDispatcher(&faqRepoStub{}, "client", "secret", cfg); err != nil || d == nil { + t.Fatalf("dispatcher=%v err=%v", d, err) + } +} + +func TestMainWiresFAQExportBeforeSupportNotification(t *testing.T) { + data, err := os.ReadFile("main.go") + if err != nil { + t.Fatal(err) + } + source := string(data) + for _, fragment := range []string{ + "readFAQConfig()", "postgres.NewFAQExportRepository(store)", + "buildFAQDispatcher(", "runFAQPoller(ctx, faqDispatcher, 5*time.Second)", + "faqtable.NewRecordLinkBuilder(", "buildSupportDispatcher(", + } { + if !strings.Contains(source, fragment) { + t.Errorf("main FAQ wiring missing %q", fragment) + } + } + if strings.Index(source, "runFAQPoller(ctx") > strings.Index(source, "runSupportDispatcher(ctx") { + t.Fatal("FAQ exporter must start before support notifications") + } +} + +func TestEnvExampleDocumentsFAQWorkflowConfig(t *testing.T) { + data, err := os.ReadFile("../../.env.example") + if err != nil { + t.Fatal(err) + } + for _, key := range []string{"DINGTALK_FAQ_TABLE_BASE_ID", "DINGTALK_FAQ_TABLE_SHEET_ID", "DINGTALK_FAQ_TABLE_VIEW_ID", "DINGTALK_FAQ_TABLE_OPERATOR_ID"} { + if !strings.Contains(string(data), key+"=") { + t.Errorf(".env.example missing %s", key) + } + } +} diff --git a/cmd/dobotai/main.go b/cmd/dobotai/main.go index 4da48fe..9516dda 100644 --- a/cmd/dobotai/main.go +++ b/cmd/dobotai/main.go @@ -8,23 +8,44 @@ import ( "os" "os/signal" "strings" + "sync/atomic" "syscall" "time" + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/adminweb" "gitea.zheromiku.top/Weknora/dobotai-platform/internal/agentbinding" "gitea.zheromiku.top/Weknora/dobotai-platform/internal/audit" "gitea.zheromiku.top/Weknora/dobotai-platform/internal/channels/dingtalk" + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/coverage" + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/directory" + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/faqtable" "gitea.zheromiku.top/Weknora/dobotai-platform/internal/feedback" "gitea.zheromiku.top/Weknora/dobotai-platform/internal/httpapi" "gitea.zheromiku.top/Weknora/dobotai-platform/internal/qa" + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/reasoningmode" "gitea.zheromiku.top/Weknora/dobotai-platform/internal/session" "gitea.zheromiku.top/Weknora/dobotai-platform/internal/store/postgres" "gitea.zheromiku.top/Weknora/dobotai-platform/internal/weknora" ) +var ( + version = "dev" + commitSHA = "unknown" + buildTime = "unknown" +) + +func runtimeBuildInfo() httpapi.BuildInfo { + return httpapi.BuildInfo{ + Version: version, + CommitSHA: commitSHA, + BuildTime: buildTime, + } +} + func main() { ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) defer cancel() + var restartRequested atomic.Bool storeCtx, storeCancel := context.WithTimeout(ctx, 10*time.Second) defer storeCancel() store, err := postgres.Open(storeCtx, os.Getenv("DATABASE_URL")) @@ -32,6 +53,20 @@ func main() { log.Fatal(err) } defer store.Close() + settingsRuntime, err := buildSettingsRuntime(storeCtx, store, os.Getenv("DOBOTAI_TENANT_KEY")) + if err != nil { + log.Fatal(err) + } + settingsRuntime.bindings.restartDelay = 300 * time.Millisecond + settingsRuntime.bindings.restart = func() { restartRequested.Store(true); cancel() } + address := strings.TrimSpace(os.Getenv("DOBOTAI_LISTEN_ADDR")) + if address == "" { + address = "127.0.0.1:8090" + } + if strings.TrimSpace(settingsRuntime.clientID) == "" || strings.TrimSpace(settingsRuntime.secret) == "" { + runSetupOnly(ctx, cancel, settingsRuntime, address, os.Getenv("DOBOTAI_TENANT_KEY"), &restartRequested) + return + } client, err := weknora.NewClient(os.Getenv("WEKNORA_BASE_URL"), os.Getenv("WEKNORA_API_KEY"), 120*time.Second) if err != nil { log.Fatal(err) @@ -40,6 +75,14 @@ func main() { if err != nil { log.Fatal(err) } + reasoningService, err := reasoningmode.NewService( + store, + os.Getenv("DOBOTAI_QUICK_AGENT_ID"), + os.Getenv("DOBOTAI_REASONING_AGENT_ID"), + ) + if err != nil { + log.Fatal(err) + } groupPolicy := session.GroupPolicy(strings.TrimSpace(os.Getenv("DOBOTAI_GROUP_SESSION_POLICY"))) if groupPolicy == "" { groupPolicy = session.GroupShared @@ -47,33 +90,178 @@ func main() { if groupPolicy != session.GroupShared && groupPolicy != session.GroupPerUser { log.Fatal("DOBOTAI_GROUP_SESSION_POLICY must be shared or per_user") } - qaService, err := qa.New(store, bindings, client, groupPolicy) + coverageService, err := coverage.NewService(store) if err != nil { log.Fatal(err) } - address := strings.TrimSpace(os.Getenv("DOBOTAI_LISTEN_ADDR")) - if address == "" { - address = "127.0.0.1:8090" + qaService, err := qa.New( + store, + bindings, + client, + groupPolicy, + qa.WithSucceededTurnObserver(coverageService, func(err error) { + log.Printf("coverage persistence failed: %v", err) + }), + qa.WithReasoningModeFinalizer(reasoningService, func(err error) { + log.Printf("reasoning mode completion failed: %T", err) + }), + ) + if err != nil { + log.Fatal(err) } auditOptions, err := buildAuditOptions(store, os.Getenv("DOBOTAI_TENANT_KEY"), os.Getenv("DOBOTAI_ADMIN_TOKEN"), address) if err != nil { log.Fatal(err) } + auditOptions.BuildInfo = runtimeBuildInfo() api, err := httpapi.NewWithOptions(qaService, os.Getenv("DOBOTAI_INGRESS_TOKEN"), auditOptions) if err != nil { log.Fatal(err) } dingCfg := dingtalk.StreamConfig{ - ClientID: os.Getenv("DINGTALK_CLIENT_ID"), - ClientSecret: os.Getenv("DINGTALK_CLIENT_SECRET"), + ClientID: settingsRuntime.clientID, + ClientSecret: settingsRuntime.secret, TenantKey: os.Getenv("DOBOTAI_TENANT_KEY"), } if err := dingCfg.Validate(); err != nil { log.Fatal(err) } + activeBindings, err := settingsRuntime.repository.ActiveBindings(storeCtx, dingCfg.TenantKey) + if err != nil { + log.Fatal(err) + } + settingsRuntime.admin.SetCandidateActivator(&dingTalkCandidateActivator{ + tenant: dingCfg.TenantKey, repo: settingsRuntime.repository, secrets: settingsRuntime.secrets, + verifier: settingsRuntime.verifier, bindings: activeBindings, + restart: func() { restartRequested.Store(true); cancel() }, + }) + runtimeReady := make(chan struct{}) + faqCfg, err := readFAQConfig() + if err != nil { + log.Fatal(err) + } + if binding, ok := activeBindings["faq_table"]; ok { + faqCfg = faqConfig{BaseID: binding.BaseID, SheetID: binding.SheetID, ViewID: binding.ViewID, OperatorID: binding.OperatorID, FieldMapping: binding.FieldMapping} + } + var faqWorkflowDone chan struct{} + var faqRecordLinks *faqtable.RecordLinkBuilder + if faqCfg.BaseID != "" { + faqRecordLinks, err = faqtable.NewRecordLinkBuilder(faqCfg.BaseID, faqCfg.SheetID, faqCfg.ViewID) + if err != nil { + log.Fatal(err) + } + faqRepo, err := postgres.NewFAQExportRepository(store) + if err != nil { + log.Fatal(err) + } + faqDispatcher, err := buildFAQDispatcher(faqRepo, dingCfg.ClientID, dingCfg.ClientSecret, faqCfg) + if err != nil { + log.Fatalf("DingTalk FAQ table dispatcher init failed: %v", err) + } + faqWorkflowDone = make(chan struct{}) + go func() { + defer close(faqWorkflowDone) + select { + case <-runtimeReady: + case <-ctx.Done(): + return + } + runFAQPoller(ctx, faqDispatcher, 5*time.Second) + }() + log.Printf("DingTalk FAQ table dispatcher started") + } + + supportConversationID := os.Getenv("DINGTALK_SUPPORT_GROUP_OPEN_CONVERSATION_ID") + if binding, ok := activeBindings["support_group"]; ok { + supportConversationID = binding.ConversationID + } + supportDispatcher, err := buildSupportDispatcher( + store, + dingCfg.ClientID, + dingCfg.ClientSecret, + supportConversationID, + faqRecordLinks, + ) + if err != nil { + log.Fatalf("DingTalk support notification init failed: %v", err) + } + if supportDispatcher != nil { + go func() { + select { + case <-runtimeReady: + case <-ctx.Done(): + return + } + runSupportDispatcher(ctx, supportDispatcher, 5*time.Second) + }() + log.Printf("DingTalk support notification dispatcher started") + } + + // Outbound image runtime (stable-image publishing) is built from environment + // variables independently of the Stream ingress, so both the question-table + // answer rewriter and the inbound-image publisher can share it. + outboundImages, err := buildOutboundImageRuntime(outboundImageConfig{ + WeKnoraBaseURL: os.Getenv("WEKNORA_BASE_URL"), + WeKnoraAPIKey: os.Getenv("WEKNORA_API_KEY"), + Endpoint: os.Getenv("DOBOTAI_OUTBOUND_IMAGE_OSS_ENDPOINT"), + Region: os.Getenv("DOBOTAI_OUTBOUND_IMAGE_OSS_REGION"), + AccessKeyID: os.Getenv("DOBOTAI_OUTBOUND_IMAGE_OSS_ACCESS_KEY_ID"), + AccessKeySecret: os.Getenv("DOBOTAI_OUTBOUND_IMAGE_OSS_ACCESS_KEY_SECRET"), + Bucket: os.Getenv("DOBOTAI_OUTBOUND_IMAGE_OSS_BUCKET"), + PublicBaseURL: os.Getenv("DOBOTAI_OUTBOUND_IMAGE_PUBLIC_BASE_URL"), + }) + if err != nil { + log.Fatalf("DingTalk outbound image init failed: %v", err) + } + + // Question table dispatcher (optional, fail-closed). + qtCfg, err := readQuestionTableConfig() + if err != nil { + log.Fatal(err) + } + if binding, ok := activeBindings["question_table"]; ok { + qtCfg = questionTableConfig{BaseID: binding.BaseID, SheetID: binding.SheetID, OperatorID: binding.OperatorID, FieldMapping: binding.FieldMapping} + } + store.SetExternalTableExports(qtCfg.BaseID != "", faqCfg.BaseID != "") + var questionTableDone chan struct{} + if qtCfg.BaseID != "" { + qtRepo, err := postgres.NewQuestionTableExportRepository(store) + if err != nil { + log.Fatal(err) + } + qtDispatcher, err := buildQuestionTableDispatcher(qtRepo, dingCfg.ClientID, dingCfg.ClientSecret, qtCfg, answerRewriterAdapter{rewriter: outboundImages.rewriter}) + if err != nil { + log.Fatalf("DingTalk question table dispatcher init failed: %v", err) + } + questionTableDone = make(chan struct{}) + go func() { + defer close(questionTableDone) + select { + case <-runtimeReady: + case <-ctx.Done(): + return + } + runQuestionTablePoller(ctx, qtDispatcher, 5*time.Second) + }() + log.Printf("DingTalk question table dispatcher started") + } var streamClient *dingtalk.StreamClient if dingCfg.Enabled() { + directoryLookup, err := directory.NewDingTalkLookup(directory.DingTalkLookupConfig{ + TokenURL: "https://oapi.dingtalk.com/gettoken", + APIBaseURL: "https://oapi.dingtalk.com", + ClientID: dingCfg.ClientID, + ClientSecret: dingCfg.ClientSecret, + Timeout: 10 * time.Second, + }) + if err != nil { + log.Fatalf("DingTalk directory lookup init failed: %v", err) + } + directoryResolver, err := directory.NewResolver(store, directoryLookup) + if err != nil { + log.Fatalf("DingTalk directory resolver init failed: %v", err) + } feedbackService, err := feedback.NewService(dingCfg.TenantKey, "dingtalk", store) if err != nil { log.Fatal(err) @@ -112,7 +300,16 @@ func main() { dingtalk.TenantConfig{TenantKey: dingCfg.TenantKey, Channel: "dingtalk"}, qaService, sender, - dingtalk.HandlerOptions{ImageDownloader: downloader, CardSender: cardSender}, + dingtalk.HandlerOptions{ + ImageDownloader: downloader, + ImagePublisher: outboundImages.publisher, + CardSender: cardSender, + Directory: directoryResolver, + OutboundRewriter: outboundImages.rewriter, + SettingsRouter: &dingTalkSettingsRouter{controller: settingsRuntime.controller}, + ReasoningRouter: &dingTalkReasoningRouter{service: reasoningService}, + LanguageResolver: settingsRuntime.repository, + }, ) if err != nil { log.Fatal(err) @@ -125,9 +322,45 @@ func main() { log.Fatal(err) } defer streamClient.Close() + if err := settingsRuntime.repository.MarkDingTalkRuntimeHealthy(context.Background(), dingCfg.TenantKey, settingsRuntime.secretRef); err != nil { + streamClient.Close() + log.Fatal(err) + } log.Printf("DingTalk Stream ingress started for tenant %s", dingCfg.TenantKey) } - server := &http.Server{Addr: address, Handler: api.Handler(), ReadHeaderTimeout: 5 * time.Second, ReadTimeout: 15 * time.Second, WriteTimeout: 130 * time.Second, IdleTimeout: 60 * time.Second} + close(runtimeReady) + _, questionBound := activeBindings["question_table"] + _, faqBound := activeBindings["faq_table"] + _, supportBound := activeBindings["support_group"] + weknoraHealthURL := strings.TrimRight(strings.TrimSpace(os.Getenv("WEKNORA_BASE_URL")), "/") + if weknoraHealthURL != "" { + weknoraHealthURL += "/health" + } + settingsRuntime.admin.SetOperationalStatusProvider(&operationalStatusProvider{ + metrics: store, + tenant: dingCfg.TenantKey, + weknoraHealthURL: weknoraHealthURL, + httpClient: &http.Client{Timeout: 3 * time.Second}, + now: time.Now, + version: runtimeBuildInfo().Version, + streamRunning: streamClient != nil, + questionRunning: questionTableDone != nil, + faqRunning: faqWorkflowDone != nil, + supportRunning: supportDispatcher != nil, + questionBound: questionBound, + faqBound: faqBound, + supportBound: supportBound, + ossConfigured: outboundOSSConfigured(), + }) + rootHandler := http.NewServeMux() + rootHandler.Handle("/", api.Handler()) + if outboundImages.handler != nil { + rootHandler.Handle(outboundImageRoute, outboundImages.handler) + } + if strings.TrimSpace(os.Getenv("DOBOTAI_ADMIN_TOKEN")) != "" { + rootHandler.Handle("/admin/", adminweb.New(settingsRuntime.admin, os.Getenv("DOBOTAI_ADMIN_TOKEN"))) + } + server := &http.Server{Addr: address, Handler: rootHandler, ReadHeaderTimeout: 5 * time.Second, ReadTimeout: 15 * time.Second, WriteTimeout: 130 * time.Second, IdleTimeout: 60 * time.Second} go func() { log.Printf("DobotAI ingress listening on %s", address) if err := server.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) { @@ -141,6 +374,39 @@ func main() { if err := server.Shutdown(shutdownCtx); err != nil { log.Printf("HTTP shutdown: %v", err) } + if faqWorkflowDone != nil { + select { + case <-faqWorkflowDone: + case <-shutdownCtx.Done(): + log.Printf("FAQ table poller shutdown timed out") + } + } + if questionTableDone != nil { + select { + case <-questionTableDone: + case <-shutdownCtx.Done(): + log.Printf("question table poller shutdown timed out") + } + } + if streamClient != nil { + streamClient.Close() + } + if restartRequested.Load() { + os.Exit(75) + } +} + +func outboundOSSConfigured() bool { + for _, key := range []string{ + "DOBOTAI_OUTBOUND_IMAGE_OSS_ENDPOINT", "DOBOTAI_OUTBOUND_IMAGE_OSS_REGION", + "DOBOTAI_OUTBOUND_IMAGE_OSS_ACCESS_KEY_ID", "DOBOTAI_OUTBOUND_IMAGE_OSS_ACCESS_KEY_SECRET", + "DOBOTAI_OUTBOUND_IMAGE_OSS_BUCKET", "DOBOTAI_OUTBOUND_IMAGE_PUBLIC_BASE_URL", + } { + if strings.TrimSpace(os.Getenv(key)) == "" { + return false + } + } + return true } func buildAuditOptions(repo audit.TurnRepository, tenantKey, adminToken, address string) (httpapi.Options, error) { diff --git a/cmd/dobotai/main_test.go b/cmd/dobotai/main_test.go index a78875a..0fe67e2 100644 --- a/cmd/dobotai/main_test.go +++ b/cmd/dobotai/main_test.go @@ -21,6 +21,20 @@ func (r *auditRepoStub) GetTurn(context.Context, string, string) (audit.TurnDeta return audit.TurnDetail{}, audit.ErrNotFound } +func TestRuntimeBuildInfoUsesLinkerVariables(t *testing.T) { + oldVersion, oldCommitSHA, oldBuildTime := version, commitSHA, buildTime + t.Cleanup(func() { + version, commitSHA, buildTime = oldVersion, oldCommitSHA, oldBuildTime + }) + version = "2.1.0" + commitSHA = "abc123def456" + buildTime = "2026-07-27T12:00:00Z" + got := runtimeBuildInfo() + if got.Version != version || got.CommitSHA != commitSHA || got.BuildTime != buildTime { + t.Fatalf("build info=%+v", got) + } +} + func TestBuildAuditOptionsDisabledIsBackwardCompatible(t *testing.T) { opts, err := buildAuditOptions(nil, "", "", "0.0.0.0:8090") if err != nil { @@ -101,3 +115,71 @@ func TestMainWiresOptionalDingTalkCardDebugUser(t *testing.T) { } } } + +func TestBuildOutboundImageRuntimeConfig(t *testing.T) { + t.Run("disabled", func(t *testing.T) { + runtime, err := buildOutboundImageRuntime(outboundImageConfig{}) + if err != nil || runtime.rewriter != nil || runtime.handler != nil { + t.Fatalf("runtime=%+v err=%v", runtime, err) + } + }) + t.Run("partial configuration rejected", func(t *testing.T) { + _, err := buildOutboundImageRuntime(outboundImageConfig{Bucket: "private-bucket"}) + if err == nil { + t.Fatal("expected configuration error") + } + }) + t.Run("complete configuration", func(t *testing.T) { + runtime, err := buildOutboundImageRuntime(outboundImageConfig{ + WeKnoraBaseURL: "http://127.0.0.1:8080", + WeKnoraAPIKey: "api-key", + Endpoint: "https://oss-cn-shenzhen.aliyuncs.com", + Region: "cn-shenzhen", + AccessKeyID: "access-key-id", + AccessKeySecret: "access-key-secret", + Bucket: "private-bucket", + PublicBaseURL: "https://weknora-api-test.dobot.cn/dingtalk/i", + }) + if err != nil || runtime.rewriter == nil || runtime.handler == nil { + t.Fatalf("runtime=%+v err=%v", runtime, err) + } + }) +} + +func TestMainWiresStableOutboundImageRuntime(t *testing.T) { + data, err := os.ReadFile("main.go") + if err != nil { + t.Fatal(err) + } + source := string(data) + for _, fragment := range []string{ + `buildOutboundImageRuntime(outboundImageConfig{`, + `PublicBaseURL: os.Getenv("DOBOTAI_OUTBOUND_IMAGE_PUBLIC_BASE_URL")`, + `OutboundRewriter: outboundImages.rewriter`, + `rootHandler.Handle(outboundImageRoute, outboundImages.handler)`, + } { + if !strings.Contains(source, fragment) { + t.Errorf("main stable image wiring missing %q", fragment) + } + } +} + +func TestOutboundOSSConfiguredRequiresStablePublicBaseURL(t *testing.T) { + for _, key := range []string{ + "DOBOTAI_OUTBOUND_IMAGE_OSS_ENDPOINT", + "DOBOTAI_OUTBOUND_IMAGE_OSS_REGION", + "DOBOTAI_OUTBOUND_IMAGE_OSS_ACCESS_KEY_ID", + "DOBOTAI_OUTBOUND_IMAGE_OSS_ACCESS_KEY_SECRET", + "DOBOTAI_OUTBOUND_IMAGE_OSS_BUCKET", + } { + t.Setenv(key, "configured") + } + t.Setenv("DOBOTAI_OUTBOUND_IMAGE_PUBLIC_BASE_URL", "") + if outboundOSSConfigured() { + t.Fatal("stable public base URL must be required") + } + t.Setenv("DOBOTAI_OUTBOUND_IMAGE_PUBLIC_BASE_URL", "https://img.example/dingtalk/i") + if !outboundOSSConfigured() { + t.Fatal("complete stable image configuration should be active") + } +} diff --git a/cmd/dobotai/operational_status.go b/cmd/dobotai/operational_status.go new file mode 100644 index 0000000..231b2e6 --- /dev/null +++ b/cmd/dobotai/operational_status.go @@ -0,0 +1,164 @@ +package main + +import ( + "context" + "fmt" + "io" + "net/http" + "strings" + "time" + + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/adminweb" + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/store/postgres" +) + +type adminComponent = adminweb.Component +type operationalMetrics = postgres.OperationalMetrics + +type operationalMetricsSource interface { + Ping(context.Context) error + ReadOperationalMetrics(context.Context, string) (postgres.OperationalMetrics, error) +} + +type operationalStatusProvider struct { + metrics operationalMetricsSource + tenant string + weknoraHealthURL string + httpClient *http.Client + now func() time.Time + version string + streamRunning bool + questionRunning bool + faqRunning bool + supportRunning bool + questionBound bool + faqBound bool + supportBound bool + ossConfigured bool +} + +func (p *operationalStatusProvider) Components(ctx context.Context) ([]adminweb.Component, error) { + now := time.Now() + if p.now != nil { + now = p.now() + } + components := []adminweb.Component{{Name: "运行版本", State: "ok", Code: "version_ok", Detail: "版本:" + safeVersion(p.version), LastSuccess: now, CheckedAt: now}} + + metrics := operationalMetrics{} + if p.metrics == nil || p.metrics.Ping(ctx) != nil { + components = append(components, adminweb.Component{Name: "PostgreSQL", State: "error", Code: "database_unavailable", Detail: "数据库健康检查失败", CheckedAt: now}) + } else { + var err error + metrics, err = p.metrics.ReadOperationalMetrics(ctx, p.tenant) + if err != nil { + components = append(components, adminweb.Component{Name: "PostgreSQL", State: "error", Code: "metrics_query_failed", Detail: "数据库可连接,但状态聚合失败", LastSuccess: now, CheckedAt: now}) + } else { + components = append(components, adminweb.Component{Name: "PostgreSQL", State: "ok", Code: "database_ok", Detail: "连接与状态聚合正常", LastSuccess: now, CheckedAt: now}) + } + } + + components = append(components, + booleanComponent("钉钉Stream", p.streamRunning, "stream_running", "stream_stopped", "正式Stream消费者运行中", "正式Stream消费者未运行", now), + p.weknoraComponent(ctx, now), + outboxComponent("问题表Outbox", metrics.QuestionPending, metrics.QuestionFailed, metrics.LastQuestionSuccess, now), + outboxComponent("FAQ Outbox", metrics.FAQPending, metrics.FAQFailed, metrics.LastFAQSuccess, now), + supportComponent(p, metrics, now), + dispatcherComponent("问题表Dispatcher", p.questionBound, p.questionRunning, now), + dispatcherComponent("FAQ Dispatcher", p.faqBound, p.faqRunning, now), + booleanComponent("Private OSS图片", p.ossConfigured, "oss_configured", "oss_unconfigured", "图片出站配置完整", "图片出站未配置", now), + ) + return components, nil +} + +func (p *operationalStatusProvider) weknoraComponent(ctx context.Context, now time.Time) adminweb.Component { + component := adminweb.Component{Name: "WeKnora", State: "error", Code: "health_probe_failed", Detail: "健康探针失败", CheckedAt: now} + if strings.TrimSpace(p.weknoraHealthURL) == "" { + component.Code = "health_url_missing" + component.Detail = "健康探针地址未配置" + return component + } + client := p.httpClient + if client == nil { + client = &http.Client{Timeout: 3 * time.Second} + } + reqCtx, cancel := context.WithTimeout(ctx, 3*time.Second) + defer cancel() + req, err := http.NewRequestWithContext(reqCtx, http.MethodGet, p.weknoraHealthURL, nil) + if err != nil { + return component + } + resp, err := client.Do(req) + if err != nil { + return component + } + defer resp.Body.Close() + _, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 4<<10)) + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + component.Code = "health_http_error" + component.Detail = fmt.Sprintf("健康探针HTTP %d", resp.StatusCode) + return component + } + component.State, component.Code, component.Detail = "ok", "health_ok", "HTTP健康探针正常" + component.LastSuccess = now + return component +} + +func outboxComponent(name string, pending, failed int, lastSuccess, now time.Time) adminweb.Component { + component := adminweb.Component{Name: name, State: "ok", Code: "outbox_empty", Detail: "pending=0,failed=0", LastSuccess: lastSuccess, CheckedAt: now} + if failed > 0 { + component.State, component.Code = "error", "outbox_failed" + } else if pending > 0 { + component.State, component.Code = "warning", "outbox_pending" + } + component.Detail = fmt.Sprintf("pending=%d,failed=%d", pending, failed) + return component +} + +func supportComponent(p *operationalStatusProvider, metrics operationalMetrics, now time.Time) adminweb.Component { + component := adminweb.Component{Name: "技术支持通知", CheckedAt: now, LastSuccess: metrics.LastSupportSuccess} + switch { + case !p.supportBound: + component.State, component.Code, component.Detail = "disabled", "binding_missing", "技术支持群未绑定" + case !p.faqBound: + component.State, component.Code, component.Detail = "blocked", "faq_binding_required", "已绑定支持群;需先激活FAQ表" + case metrics.SupportFailed > 0: + component.State, component.Code = "error", "notification_failed" + component.Detail = fmt.Sprintf("pending=%d,failed=%d", metrics.SupportPending, metrics.SupportFailed) + case metrics.SupportPending > 0: + component.State, component.Code = "warning", "notification_pending" + component.Detail = fmt.Sprintf("pending=%d,failed=0", metrics.SupportPending) + case p.supportRunning: + component.State, component.Code, component.Detail = "ok", "dispatcher_running", "通知Dispatcher运行中;pending=0,failed=0" + default: + component.State, component.Code, component.Detail = "error", "dispatcher_stopped", "绑定与依赖完整,但Dispatcher未运行" + } + return component +} + +func dispatcherComponent(name string, bound, running bool, now time.Time) adminweb.Component { + if !bound { + return adminweb.Component{Name: name, State: "disabled", Code: "binding_missing", Detail: "无active绑定", CheckedAt: now} + } + if !running { + return adminweb.Component{Name: name, State: "error", Code: "dispatcher_stopped", Detail: "已有active绑定,但Dispatcher未运行", CheckedAt: now} + } + return adminweb.Component{Name: name, State: "ok", Code: "dispatcher_running", Detail: "Dispatcher运行中", LastSuccess: now, CheckedAt: now} +} + +func booleanComponent(name string, ok bool, successCode, failureCode, successDetail, failureDetail string, now time.Time) adminweb.Component { + if ok { + return adminweb.Component{Name: name, State: "ok", Code: successCode, Detail: successDetail, LastSuccess: now, CheckedAt: now} + } + return adminweb.Component{Name: name, State: "disabled", Code: failureCode, Detail: failureDetail, CheckedAt: now} +} + +func safeVersion(value string) string { + value = strings.TrimSpace(value) + if value == "" { + return "unknown" + } + if len(value) > 80 { + return value[:80] + } + return value +} diff --git a/cmd/dobotai/operational_status_test.go b/cmd/dobotai/operational_status_test.go new file mode 100644 index 0000000..d88a34f --- /dev/null +++ b/cmd/dobotai/operational_status_test.go @@ -0,0 +1,105 @@ +package main + +import ( + "context" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" +) + +func TestOperationalStatusProviderBuildsLiveComponents(t *testing.T) { + health := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusOK) + })) + defer health.Close() + + checked := time.Date(2026, 8, 13, 10, 0, 0, 0, time.UTC) + provider := &operationalStatusProvider{ + metrics: operationalMetricsStub{value: operationalMetrics{ + QuestionPending: 2, FAQFailed: 1, SupportPending: 3, + LastQuestionSuccess: checked.Add(-time.Minute), + }}, + weknoraHealthURL: health.URL, + httpClient: health.Client(), + now: func() time.Time { return checked }, + version: "settings-test", + streamRunning: true, + questionRunning: true, + faqRunning: false, + supportRunning: false, + questionBound: true, + faqBound: false, + supportBound: true, + ossConfigured: true, + } + components, err := provider.Components(context.Background()) + if err != nil { + t.Fatal(err) + } + byName := componentMap(components) + assertComponent(t, byName, "运行版本", "ok", "version_ok") + assertComponent(t, byName, "PostgreSQL", "ok", "database_ok") + assertComponent(t, byName, "钉钉Stream", "ok", "stream_running") + assertComponent(t, byName, "WeKnora", "ok", "health_ok") + assertComponent(t, byName, "问题表Outbox", "warning", "outbox_pending") + assertComponent(t, byName, "FAQ Outbox", "error", "outbox_failed") + assertComponent(t, byName, "技术支持通知", "blocked", "faq_binding_required") + assertComponent(t, byName, "问题表Dispatcher", "ok", "dispatcher_running") + assertComponent(t, byName, "FAQ Dispatcher", "disabled", "binding_missing") + assertComponent(t, byName, "Private OSS图片", "ok", "oss_configured") + for _, component := range components { + for _, forbidden := range []string{health.URL, "cid-secret-group", "base-secret", "access-token"} { + if strings.Contains(component.Detail, forbidden) { + t.Fatalf("component %q leaks sensitive identifier %q", component.Name, forbidden) + } + } + } +} + +func TestOperationalStatusProviderIsolatesWeKnoraFailure(t *testing.T) { + provider := &operationalStatusProvider{ + metrics: operationalMetricsStub{value: operationalMetrics{}}, + weknoraHealthURL: "http://127.0.0.1:1/health", + httpClient: &http.Client{Timeout: 50 * time.Millisecond}, + now: time.Now, + } + components, err := provider.Components(context.Background()) + if err != nil { + t.Fatal(err) + } + byName := componentMap(components) + assertComponent(t, byName, "PostgreSQL", "ok", "database_ok") + assertComponent(t, byName, "WeKnora", "error", "health_probe_failed") +} + +type operationalMetricsStub struct { + value operationalMetrics + err error +} + +func (s operationalMetricsStub) ReadOperationalMetrics(context.Context, string) (operationalMetrics, error) { + return s.value, s.err +} + +func (s operationalMetricsStub) Ping(context.Context) error { return s.err } + +func componentMap(values []adminComponent) map[string]adminComponent { + out := make(map[string]adminComponent, len(values)) + for _, value := range values { + out[value.Name] = value + } + return out +} + +func assertComponent(t *testing.T, values map[string]adminComponent, name, state, code string) { + t.Helper() + value, ok := values[name] + if !ok { + t.Fatalf("missing component %q: %+v", name, values) + } + if value.State != state || value.Code != code { + t.Fatalf("component %q=%+v want state=%q code=%q", name, value, state, code) + } +} diff --git a/cmd/dobotai/outbound_images.go b/cmd/dobotai/outbound_images.go new file mode 100644 index 0000000..d7a636d --- /dev/null +++ b/cmd/dobotai/outbound_images.go @@ -0,0 +1,93 @@ +package main + +import ( + "errors" + "net/http" + "strings" + "time" + + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/channels/dingtalk" + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/outboundimage" +) + +const ( + outboundImageMaxCount = 5 + outboundImageMaxBytes = 10 << 20 + outboundImagePrefix = "dobotai/im-images" + outboundImageRoute = "/dingtalk/i/" +) + +type outboundImageConfig struct { + WeKnoraBaseURL string + WeKnoraAPIKey string + Endpoint string + Region string + AccessKeyID string + AccessKeySecret string + Bucket string + PublicBaseURL string +} + +type outboundImageRuntime struct { + rewriter dingtalk.OutboundContentRewriter + publisher *outboundimage.StableHashPublisher + handler http.Handler +} + +func buildOutboundImageRuntime(cfg outboundImageConfig) (outboundImageRuntime, error) { + ossValues := []string{cfg.Endpoint, cfg.Region, cfg.AccessKeyID, cfg.AccessKeySecret, cfg.Bucket, cfg.PublicBaseURL} + enabled := false + for _, value := range ossValues { + if strings.TrimSpace(value) != "" { + enabled = true + break + } + } + if !enabled { + return outboundImageRuntime{}, nil + } + for _, value := range append([]string{cfg.WeKnoraBaseURL, cfg.WeKnoraAPIKey}, ossValues...) { + if strings.TrimSpace(value) == "" { + return outboundImageRuntime{}, errors.New("outbound image: complete WeKnora, OSS, and public URL configuration is required") + } + } + transport := http.DefaultTransport.(*http.Transport).Clone() + transport.Proxy = nil + fetcher, err := outboundimage.NewWeKnoraFetcher( + cfg.WeKnoraBaseURL, + cfg.WeKnoraAPIKey, + &http.Client{Timeout: 30 * time.Second, Transport: transport}, + outboundImageMaxBytes, + ) + if err != nil { + return outboundImageRuntime{}, err + } + store, err := outboundimage.NewAliyunOSSStore( + cfg.Endpoint, + cfg.Region, + cfg.AccessKeyID, + cfg.AccessKeySecret, + cfg.Bucket, + ) + if err != nil { + return outboundImageRuntime{}, err + } + publisher, err := outboundimage.NewStableHashPublisher(store, outboundImagePrefix, cfg.PublicBaseURL) + if err != nil { + return outboundImageRuntime{}, err + } + handler, err := outboundimage.NewStableImageHandler(store, outboundImagePrefix, outboundImageRoute, outboundImageMaxBytes) + if err != nil { + return outboundImageRuntime{}, err + } + return outboundImageRuntime{ + rewriter: outboundimage.NewRewriter(fetcher, publisher, outboundImageMaxCount), + publisher: publisher, + handler: handler, + }, nil +} + +func buildOutboundImageRewriter(cfg outboundImageConfig) (dingtalk.OutboundContentRewriter, error) { + runtime, err := buildOutboundImageRuntime(cfg) + return runtime.rewriter, err +} diff --git a/cmd/dobotai/question_table_sync.go b/cmd/dobotai/question_table_sync.go new file mode 100644 index 0000000..817723b --- /dev/null +++ b/cmd/dobotai/question_table_sync.go @@ -0,0 +1,164 @@ +package main + +import ( + "context" + "errors" + "log" + "os" + "reflect" + "strings" + "time" + + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/channels/dingtalk" + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/questiontable" +) + +// questionTablePollerRunner is the interface expected by the poller loop. +type questionTablePollerRunner interface { + RunOnce(context.Context) (questiontable.DispatcherStats, error) +} + +// questionTableConfig holds the optional Notable question-table env values. +type questionTableConfig struct { + BaseID string + SheetID string + OperatorID string + FieldMapping map[string]string +} + +// readQuestionTableConfig reads the three dedicated env vars and returns +// a validated config. All three blank => disabled (no error). Any partial +// configuration => stable configuration error (no values echoed). +func readQuestionTableConfig() (questionTableConfig, error) { + cfg := questionTableConfig{ + BaseID: strings.TrimSpace(os.Getenv("DINGTALK_QUESTION_TABLE_BASE_ID")), + SheetID: strings.TrimSpace(os.Getenv("DINGTALK_QUESTION_TABLE_SHEET_ID")), + OperatorID: strings.TrimSpace(os.Getenv("DINGTALK_QUESTION_TABLE_OPERATOR_ID")), + } + + allBlank := cfg.BaseID == "" && cfg.SheetID == "" && cfg.OperatorID == "" + allSet := cfg.BaseID != "" && cfg.SheetID != "" && cfg.OperatorID != "" + + if allBlank { + return questionTableConfig{}, nil + } + if allSet { + return cfg, nil + } + return questionTableConfig{}, errors.New("DingTalk question table config: all three env vars must be set or all blank (DINGTALK_QUESTION_TABLE_BASE_ID, DINGTALK_QUESTION_TABLE_SHEET_ID, DINGTALK_QUESTION_TABLE_OPERATOR_ID)") +} + +// buildQuestionTableDispatcher creates a validated question-table dispatcher +// when the repo is non-nil and all required credentials are present. +// The optional answer rewriter converts the stored answer into the same +// outbound form used for DingTalk delivery (resource images to stable HTTPS, +// document links, anchor cleanup). No HTTP request occurs at build time. +// It returns (nil, nil) when the question-table feature is disabled. +func buildQuestionTableDispatcher(repo questiontable.ExportRepository, clientID, clientSecret string, cfg questionTableConfig, rewriter questiontable.AnswerRewriter) (*questiontable.Dispatcher, error) { + // Disabled: all blank config. + if cfg.BaseID == "" && cfg.SheetID == "" && cfg.OperatorID == "" { + return nil, nil + } + + if repo == nil { + return nil, errors.New("question table dispatcher: repository is required") + } + + client, err := questiontable.NewClient(questiontable.Config{ + ClientID: clientID, + Secret: clientSecret, + BaseID: cfg.BaseID, + SheetID: cfg.SheetID, + OperatorID: cfg.OperatorID, + FieldMapping: cfg.FieldMapping, + }, nil) + if err != nil { + return nil, err + } + + return questiontable.NewDispatcher(repo, client, &questiontable.DispatcherOptions{ + Rewriter: rewriter, + SendTimeout: 60 * time.Second, + }) +} + +// answerRewriterAdapter adapts a blocking outbound content rewriter to the +// AnswerRewriter contract (caller never gets an error, so the original answer +// is always written when conversion cannot run). +type answerRewriterAdapter struct { + rewriter dingtalk.OutboundContentRewriter +} + +func (a answerRewriterAdapter) Rewrite(ctx context.Context, content string) (string, error) { + if a.rewriter == nil { + return content, nil + } + return a.rewriter.Rewrite(ctx, content), nil +} + +// runQuestionTablePoller runs the dispatcher immediately, then every interval. +// Non-positive interval or nil/typed-nil runner returns without calling. +// Continues after a RunOnce error. Exits promptly on context cancellation. +// Logging is safe: success may log only Claimed/Exported/Failed integers; +// errors log stable stage text only, never raw errors. +func runQuestionTablePoller(ctx context.Context, runner questionTablePollerRunner, interval time.Duration) { + if runner == nil || interval <= 0 { + return + } + + // Guard against typed nil. + if isNilPoller(runner) { + return + } + + runOnce := func() { + runCtx, cancel := context.WithTimeout(ctx, 30*time.Second) + stats, err := runner.RunOnce(runCtx) + cancel() + if err != nil { + log.Printf("question table dispatch failed") + return + } + if stats.Claimed > 0 || stats.Exported > 0 || stats.Failed > 0 { + log.Printf("question table dispatch: claimed=%d exported=%d failed=%d", stats.Claimed, stats.Exported, stats.Failed) + } + } + + if ctx.Err() != nil { + return + } + runOnce() + ticker := time.NewTicker(interval) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return + case <-ticker.C: + runOnce() + } + } +} + +// isNilPoller returns true when runner is a typed nil. +func isNilPoller(runner questionTablePollerRunner) bool { + if runner == nil { + return true + } + // reflect-based typed-nil check for the interface. + return isInterfaceNil(runner) +} + +// isInterfaceNil returns true when v is a typed nil wrapped in an interface. +func isInterfaceNil(v interface{}) bool { + if v == nil { + return true + } + rv := reflect.ValueOf(v) + switch rv.Kind() { + case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice: + return rv.IsNil() + default: + return false + } +} diff --git a/cmd/dobotai/question_table_sync_test.go b/cmd/dobotai/question_table_sync_test.go new file mode 100644 index 0000000..0117343 --- /dev/null +++ b/cmd/dobotai/question_table_sync_test.go @@ -0,0 +1,377 @@ +package main + +import ( + "context" + "errors" + "log" + "os" + "strings" + "sync" + "testing" + "time" + + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/questiontable" +) + +// --------------------------------------------------------------------------- +// Test 1: disabled all blank returns nil/no error +// --------------------------------------------------------------------------- + +func TestReadQuestionTableConfigDisabledAllBlank(t *testing.T) { + t.Setenv("DINGTALK_QUESTION_TABLE_BASE_ID", "") + t.Setenv("DINGTALK_QUESTION_TABLE_SHEET_ID", "") + t.Setenv("DINGTALK_QUESTION_TABLE_OPERATOR_ID", "") + + cfg, err := readQuestionTableConfig() + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if cfg.BaseID != "" || cfg.SheetID != "" || cfg.OperatorID != "" { + t.Errorf("expected empty config, got %+v", cfg) + } +} + +func TestBuildQuestionTableDispatcherDisabled(t *testing.T) { + d, err := buildQuestionTableDispatcher(nil, "", "", questionTableConfig{}, nil) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if d != nil { + t.Errorf("expected nil dispatcher for disabled config, got %v", d) + } +} + +// --------------------------------------------------------------------------- +// Test 2: every partial combination errors and does not echo sentinel config values +// --------------------------------------------------------------------------- + +func TestReadQuestionTableConfigPartialErrors(t *testing.T) { + tests := []struct { + name string + baseID string + sheetID string + operator string + }{ + {"only base", "base-1", "", ""}, + {"only sheet", "", "sheet-1", ""}, + {"only operator", "", "", "op-1"}, + {"base+sheet", "base-1", "sheet-1", ""}, + {"base+operator", "base-1", "", "op-1"}, + {"sheet+operator", "", "sheet-1", "op-1"}, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + t.Setenv("DINGTALK_QUESTION_TABLE_BASE_ID", tc.baseID) + t.Setenv("DINGTALK_QUESTION_TABLE_SHEET_ID", tc.sheetID) + t.Setenv("DINGTALK_QUESTION_TABLE_OPERATOR_ID", tc.operator) + + _, err := readQuestionTableConfig() + if err == nil { + t.Fatal("expected error for partial config") + } + errStr := err.Error() + // Must not echo any sentinel config value. + for _, sentinel := range []string{"base-1", "sheet-1", "op-1"} { + if strings.Contains(errStr, sentinel) { + t.Errorf("error must not echo sentinel value %q: %q", sentinel, errStr) + } + } + }) + } +} + +// --------------------------------------------------------------------------- +// Test 3: enabled missing repo/client/secret fails closed; complete config builds +// --------------------------------------------------------------------------- + +func TestBuildQuestionTableDispatcherEnabledMissingRepo(t *testing.T) { + cfg := questionTableConfig{BaseID: "b1", SheetID: "sh1", OperatorID: "op1"} + _, err := buildQuestionTableDispatcher(nil, "cid", "secret", cfg, nil) + if err == nil { + t.Fatal("expected error when repo is nil") + } + if !strings.Contains(err.Error(), "repository is required") { + t.Errorf("error = %v, want 'repository is required'", err) + } +} + +func TestBuildQuestionTableDispatcherEnabledMissingClientID(t *testing.T) { + repo := &questionTableExportRepoStub{} + cfg := questionTableConfig{BaseID: "b1", SheetID: "sh1", OperatorID: "op1"} + _, err := buildQuestionTableDispatcher(repo, "", "secret", cfg, nil) + if err == nil { + t.Fatal("expected error when client id is empty") + } +} + +func TestBuildQuestionTableDispatcherEnabledMissingSecret(t *testing.T) { + repo := &questionTableExportRepoStub{} + cfg := questionTableConfig{BaseID: "b1", SheetID: "sh1", OperatorID: "op1"} + _, err := buildQuestionTableDispatcher(repo, "cid", "", cfg, nil) + if err == nil { + t.Fatal("expected error when secret is empty") + } +} + +func TestBuildQuestionTableDispatcherEnabledCompleteConfig(t *testing.T) { + repo := &questionTableExportRepoStub{} + cfg := questionTableConfig{BaseID: "b1", SheetID: "sh1", OperatorID: "op1"} + d, err := buildQuestionTableDispatcher(repo, "cid", "secret", cfg, nil) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if d == nil { + t.Fatal("expected non-nil dispatcher for complete config") + } +} + +// --------------------------------------------------------------------------- +// Test 4: immediate run + periodic repeat + cancel stop +// --------------------------------------------------------------------------- + +func TestRunQuestionTablePollerImmediateAndPeriodic(t *testing.T) { + runner := &countingPollerRunner{} + ctx, cancel := context.WithCancel(context.Background()) + + var wg sync.WaitGroup + wg.Add(1) + go func() { + defer wg.Done() + runQuestionTablePoller(ctx, runner, 50*time.Millisecond) + }() + + // Wait for at least 2 calls (immediate + one tick). + time.Sleep(120 * time.Millisecond) + cancel() + wg.Wait() + + runner.mu.Lock() + calls := runner.calls + runner.mu.Unlock() + + if calls < 2 { + t.Errorf("expected at least 2 calls, got %d", calls) + } +} + +func TestRunQuestionTablePollerCancelledContext(t *testing.T) { + runner := &countingPollerRunner{} + ctx, cancel := context.WithCancel(context.Background()) + cancel() // already cancelled + + runQuestionTablePoller(ctx, runner, 50*time.Millisecond) + + runner.mu.Lock() + calls := runner.calls + runner.mu.Unlock() + + if calls != 0 { + t.Errorf("expected 0 calls (cancelled context), got %d", calls) + } +} + +// --------------------------------------------------------------------------- +// Test 5: continue after error and log/output security contract +// --------------------------------------------------------------------------- + +func TestRunQuestionTablePollerContinuesAfterError(t *testing.T) { + runner := &errorThenSuccessPoller{} + ctx, cancel := context.WithCancel(context.Background()) + + var wg sync.WaitGroup + wg.Add(1) + go func() { + defer wg.Done() + runQuestionTablePoller(ctx, runner, 30*time.Millisecond) + }() + + time.Sleep(120 * time.Millisecond) + cancel() + wg.Wait() + + runner.mu.Lock() + calls := runner.calls + runner.mu.Unlock() + + if calls < 2 { + t.Errorf("expected at least 2 calls after error, got %d", calls) + } +} + +// Test logging contract: the runOnce function in runQuestionTablePoller logs +// only stable stage text for errors (never raw errors via %v) and only +// Claimed/Exported/Failed integers for success. +func TestPollerLoggingContract(t *testing.T) { + // Behavioral log-capture test: runner returns an error containing unique + // sentinel values; the captured log must contain the stable stage text + // and none of those sentinels. + sentinel := "s3nt1n3l-op3r4t0r-t0k3n-q" + runner := &sentinelErrorPoller{errMsg: "questiontable dispatcher: " + sentinel} + ctx, cancel := context.WithCancel(context.Background()) + + // Save and restore global log output. + originalOutput := log.Writer() + originalFlags := log.Flags() + var buf strings.Builder + log.SetOutput(&buf) + log.SetFlags(0) + defer func() { + log.SetOutput(originalOutput) + log.SetFlags(originalFlags) + }() + + var wg sync.WaitGroup + wg.Add(1) + go func() { + defer wg.Done() + runQuestionTablePoller(ctx, runner, 50*time.Millisecond) + }() + + time.Sleep(120 * time.Millisecond) + cancel() + wg.Wait() + + output := buf.String() + if !strings.Contains(output, "question table dispatch failed") { + t.Errorf("log must contain stable stage text, got: %s", output) + } + if strings.Contains(output, sentinel) { + t.Errorf("log must not contain sentinel %q, got: %s", sentinel, output) + } +} + +// sentinelErrorPoller always returns an error with the given message. +type sentinelErrorPoller struct { + errMsg string +} + +func (r *sentinelErrorPoller) RunOnce(ctx context.Context) (questiontable.DispatcherStats, error) { + return questiontable.DispatcherStats{}, errors.New(r.errMsg) +} + +// --------------------------------------------------------------------------- +// Test 6: nil/typed-nil runner and nonpositive interval safe +// --------------------------------------------------------------------------- + +func TestRunQuestionTablePollerNilRunner(t *testing.T) { + ctx := context.Background() + // Should not panic, just return immediately. + runQuestionTablePoller(ctx, nil, 50*time.Millisecond) + // If we reach here without panic, test passes. +} + +func TestRunQuestionTablePollerNonPositiveInterval(t *testing.T) { + runner := &countingPollerRunner{} + ctx := context.Background() + runQuestionTablePoller(ctx, runner, 0) + runQuestionTablePoller(ctx, runner, -1*time.Second) + + runner.mu.Lock() + calls := runner.calls + runner.mu.Unlock() + + if calls != 0 { + t.Errorf("expected 0 calls for non-positive interval, got %d", calls) + } +} + +func TestRunQuestionTablePollerTypedNilInterface(t *testing.T) { + // The runner is nil through the interface but not at the concrete type level. + var typedNil *questiontable.Dispatcher = nil + var runner questionTablePollerRunner = typedNil + ctx := context.Background() + // Should not panic, just return immediately. + runQuestionTablePoller(ctx, runner, 50*time.Millisecond) +} + +// --------------------------------------------------------------------------- +// Test 7: main source wiring contract +// --------------------------------------------------------------------------- + +func TestMainWiresQuestionTableEnvNames(t *testing.T) { + mainData, err := os.ReadFile("main.go") + if err != nil { + t.Fatal(err) + } + syncData, err := os.ReadFile("question_table_sync.go") + if err != nil { + t.Fatal(err) + } + mainSource := string(mainData) + syncSource := string(syncData) + + for _, fragment := range []string{ + `"DINGTALK_QUESTION_TABLE_BASE_ID"`, + `"DINGTALK_QUESTION_TABLE_SHEET_ID"`, + `"DINGTALK_QUESTION_TABLE_OPERATOR_ID"`, + } { + if !strings.Contains(syncSource, fragment) { + t.Errorf("question table config reader missing %q", fragment) + } + } + + for _, fragment := range []string{ + `NewQuestionTableExportRepository`, + `5*time.Second`, + `"DingTalk question table dispatcher started"`, + } { + if !strings.Contains(mainSource, fragment) { + t.Errorf("main wiring missing %q", fragment) + } + } + + shutdownAt := strings.Index(mainSource, "server.Shutdown(shutdownCtx)") + waitAt := strings.Index(mainSource, "case <-questionTableDone:") + if shutdownAt < 0 || waitAt < 0 || waitAt <= shutdownAt { + t.Fatal("main must wait for question table poller after HTTP shutdown and before returning") + } +} + +// --------------------------------------------------------------------------- +// Test doubles +// --------------------------------------------------------------------------- + +// questionTableExportRepoStub implements questiontable.ExportRepository. +type questionTableExportRepoStub struct{} + +func (r *questionTableExportRepoStub) Claim(ctx context.Context, limit int, maxAttempts int, staleBefore time.Time) ([]questiontable.PendingExport, error) { + return nil, nil +} +func (r *questionTableExportRepoStub) MarkExported(ctx context.Context, exportID, location string) error { + return nil +} +func (r *questionTableExportRepoStub) MarkFailed(ctx context.Context, exportID, failureCode string) error { + return nil +} + +// countingPollerRunner counts calls to RunOnce. +type countingPollerRunner struct { + mu sync.Mutex + calls int +} + +func (r *countingPollerRunner) RunOnce(ctx context.Context) (questiontable.DispatcherStats, error) { + r.mu.Lock() + r.calls++ + r.mu.Unlock() + return questiontable.DispatcherStats{}, nil +} + +// errorThenSuccessPoller returns an error on the first call, then succeeds. +type errorThenSuccessPoller struct { + mu sync.Mutex + calls int +} + +func (r *errorThenSuccessPoller) RunOnce(ctx context.Context) (questiontable.DispatcherStats, error) { + r.mu.Lock() + r.calls++ + call := r.calls + r.mu.Unlock() + + if call == 1 { + return questiontable.DispatcherStats{}, errors.New("questiontable dispatcher: claim failed") + } + return questiontable.DispatcherStats{Claimed: 1, Exported: 1}, nil +} diff --git a/cmd/dobotai/reasoning_wiring.go b/cmd/dobotai/reasoning_wiring.go new file mode 100644 index 0000000..de55d0e --- /dev/null +++ b/cmd/dobotai/reasoning_wiring.go @@ -0,0 +1,25 @@ +package main + +import ( + "context" + + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/channels/dingtalk" + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/reasoningmode" +) + +type dingTalkReasoningRouter struct { + service *reasoningmode.Service +} + +func (r *dingTalkReasoningRouter) Prepare(ctx context.Context, message dingtalk.ReasoningMessage) (dingtalk.ReasoningDecision, error) { + decision, err := r.service.Prepare(ctx, reasoningmode.Scope{ + TenantKey: message.TenantKey, Channel: message.Channel, ExternalActorID: message.StaffID, + }, message.Text) + if err != nil { + return dingtalk.ReasoningDecision{}, err + } + return dingtalk.ReasoningDecision{ + Handled: decision.Handled, Reply: decision.Reply, Query: decision.Query, + AgentID: decision.AgentID, Execution: decision.Execution, Expired: decision.Expired, + }, nil +} diff --git a/cmd/dobotai/reasoning_wiring_test.go b/cmd/dobotai/reasoning_wiring_test.go new file mode 100644 index 0000000..f959432 --- /dev/null +++ b/cmd/dobotai/reasoning_wiring_test.go @@ -0,0 +1,39 @@ +package main + +import ( + "os" + "strings" + "testing" +) + +func TestMainWiresReasoningModeRoutingAndCompletion(t *testing.T) { + mainSource, err := os.ReadFile("main.go") + if err != nil { + t.Fatal(err) + } + wiringSource, err := os.ReadFile("reasoning_wiring.go") + if err != nil { + t.Fatal(err) + } + mainText := string(mainSource) + for _, required := range []string{ + `os.Getenv("DOBOTAI_QUICK_AGENT_ID")`, + `os.Getenv("DOBOTAI_REASONING_AGENT_ID")`, + `reasoningmode.NewService`, + `qa.WithReasoningModeFinalizer`, + `ReasoningRouter:`, + } { + if !strings.Contains(mainText, required) { + t.Errorf("main reasoning wiring missing %q", required) + } + } + for _, required := range []string{ + "dingTalkReasoningRouter", + "ReasoningMessage", + "service.Prepare", + } { + if !strings.Contains(string(wiringSource), required) { + t.Errorf("reasoning adapter missing %q", required) + } + } +} diff --git a/cmd/dobotai/settings_binding_validator.go b/cmd/dobotai/settings_binding_validator.go new file mode 100644 index 0000000..ee069b3 --- /dev/null +++ b/cmd/dobotai/settings_binding_validator.go @@ -0,0 +1,133 @@ +package main + +import ( + "context" + "errors" + "time" + + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/channels/dingtalk" + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/questiontable" + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/settings" + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/store/postgres" +) + +type validatedSettingsRepository struct { + *postgres.SettingsRepository + clientID string + secret string + testSupport func(context.Context, settings.ResourceBinding) error + validateTable func(context.Context, settings.ResourceBinding) (map[string]string, error) + saveBinding func(context.Context, settings.ResourceBinding) error + restart func() + restartDelay time.Duration +} + +func (r *validatedSettingsRepository) TestAndActivateSupportGroup(ctx context.Context, binding settings.ResourceBinding) error { + if r.testSupport != nil { + if err := r.testSupport(ctx, binding); err != nil { + return errors.New("support_group_test_failed") + } + } else { + sender, err := dingtalk.NewSupportGroupSender(r.clientID, r.secret, binding.ConversationID, nil) + if err != nil { + return errors.New("support_group_test_invalid_config") + } + if err = sender.SendTest(ctx); err != nil { + return errors.New("support_group_test_failed") + } + } + binding.ValidationCode = "support_test_ok" + binding.Activate = true + var err error + if r.saveBinding != nil { + err = r.saveBinding(ctx, binding) + } else if r.SettingsRepository != nil { + err = r.SettingsRepository.SaveBinding(ctx, binding) + } else { + err = errors.New("support_group_binding_repository_unavailable") + } + if err != nil { + return err + } + if r.restart != nil { + go func() { + if r.restartDelay > 0 { + time.Sleep(r.restartDelay) + } + r.restart() + }() + } + return nil +} + +func (r *validatedSettingsRepository) SaveBinding(ctx context.Context, binding settings.ResourceBinding) error { + activate := false + switch binding.Kind { + case "question_table", "faq_table": + var mapping map[string]string + var err error + if r.validateTable != nil { + mapping, err = r.validateTable(ctx, binding) + } else { + mapping, err = r.readAndMapTable(ctx, binding) + } + if err != nil { + return err + } + binding.FieldMapping = mapping + binding.ValidationCode = "schema_ok" + binding.Activate = true + activate = true + case "support_group": + binding.ValidationCode = "pending_test_message" + binding.Activate = false + default: + return errors.New("unsupported_binding_kind") + } + var err error + if r.saveBinding != nil { + err = r.saveBinding(ctx, binding) + } else if r.SettingsRepository != nil { + err = r.SettingsRepository.SaveBinding(ctx, binding) + } else { + err = errors.New("binding_repository_unavailable") + } + if err != nil { + return err + } + if activate { + r.requestRestart() + } + return nil +} + +func (r *validatedSettingsRepository) readAndMapTable(ctx context.Context, binding settings.ResourceBinding) (map[string]string, error) { + client, err := questiontable.NewClient(questiontable.Config{ + ClientID: r.clientID, Secret: r.secret, BaseID: binding.BaseID, + SheetID: binding.SheetID, OperatorID: binding.OperatorID, + }, nil) + if err != nil { + return nil, errors.New("table_binding_invalid_config") + } + fields, err := client.ReadFields(ctx) + if err != nil { + return nil, err + } + required := questiontable.QuestionSchema() + if binding.Kind == "faq_table" { + required = questiontable.FAQSchema() + } + return questiontable.MapRequiredFields(fields, required) +} + +func (r *validatedSettingsRepository) requestRestart() { + if r.restart == nil { + return + } + go func() { + if r.restartDelay > 0 { + time.Sleep(r.restartDelay) + } + r.restart() + }() +} diff --git a/cmd/dobotai/settings_binding_validator_test.go b/cmd/dobotai/settings_binding_validator_test.go new file mode 100644 index 0000000..0a0c759 --- /dev/null +++ b/cmd/dobotai/settings_binding_validator_test.go @@ -0,0 +1,117 @@ +package main + +import ( + "context" + "errors" + "testing" + "time" + + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/settings" +) + +func TestTableBindingRestartsOnlyAfterActiveSave(t *testing.T) { + restarted := make(chan struct{}, 1) + var saved settings.ResourceBinding + repo := &validatedSettingsRepository{ + validateTable: func(_ context.Context, binding settings.ResourceBinding) (map[string]string, error) { + return map[string]string{"answer": "field-answer"}, nil + }, + saveBinding: func(_ context.Context, binding settings.ResourceBinding) error { + saved = binding + return nil + }, + restart: func() { restarted <- struct{}{} }, + restartDelay: 0, + } + if err := repo.SaveBinding(context.Background(), settings.ResourceBinding{Kind: "question_table", TenantKey: "tenant", BaseID: "base", SheetID: "sheet", OperatorID: "operator"}); err != nil { + t.Fatal(err) + } + if !saved.Activate || saved.ValidationCode != "schema_ok" || saved.FieldMapping["answer"] != "field-answer" { + t.Fatalf("binding=%+v", saved) + } + select { + case <-restarted: + case <-time.After(50 * time.Millisecond): + t.Fatal("restart not requested") + } +} + +func TestTableBindingDoesNotRestartOnValidationOrSaveFailure(t *testing.T) { + for _, tc := range []struct { + name string + validateErr error + saveErr error + }{ + {name: "validation failure", validateErr: errors.New("schema failed")}, + {name: "save failure", saveErr: errors.New("save failed")}, + } { + t.Run(tc.name, func(t *testing.T) { + restarted := make(chan struct{}, 1) + repo := &validatedSettingsRepository{ + validateTable: func(context.Context, settings.ResourceBinding) (map[string]string, error) { + return map[string]string{"answer": "field"}, tc.validateErr + }, + saveBinding: func(context.Context, settings.ResourceBinding) error { return tc.saveErr }, + restart: func() { restarted <- struct{}{} }, + } + if err := repo.SaveBinding(context.Background(), settings.ResourceBinding{Kind: "question_table"}); err == nil { + t.Fatal("expected failure") + } + select { + case <-restarted: + t.Fatal("must not restart after failed activation") + case <-time.After(50 * time.Millisecond): + } + }) + } +} + +func TestSupportGroupActivationRestartsOnlyAfterTestAndSaveSucceed(t *testing.T) { + for _, tc := range []struct { + name string + testErr error + saveErr error + wantSaved bool + wantRestart bool + }{ + {name: "test fails", testErr: errors.New("send failed")}, + {name: "save fails", saveErr: errors.New("save failed"), wantSaved: true}, + {name: "success", wantSaved: true, wantRestart: true}, + } { + t.Run(tc.name, func(t *testing.T) { + var saved settings.ResourceBinding + restarted := make(chan struct{}, 1) + repo := &validatedSettingsRepository{ + testSupport: func(context.Context, settings.ResourceBinding) error { return tc.testErr }, + saveBinding: func(_ context.Context, binding settings.ResourceBinding) error { + saved = binding + return tc.saveErr + }, + restart: func() { restarted <- struct{}{} }, + restartDelay: 0, + } + err := repo.TestAndActivateSupportGroup(context.Background(), settings.ResourceBinding{ + Kind: "support_group", TenantKey: "tenant", ConversationID: "group", + }) + if (err != nil) != (tc.testErr != nil || tc.saveErr != nil) { + t.Fatalf("err=%v", err) + } + if got := saved.Kind != ""; got != tc.wantSaved { + t.Fatalf("saved=%v want=%v", got, tc.wantSaved) + } + if tc.wantSaved && (saved.ValidationCode != "support_test_ok" || !saved.Activate) { + t.Fatalf("binding=%+v", saved) + } + select { + case <-restarted: + if !tc.wantRestart { + t.Fatal("unexpected restart") + } + case <-time.After(50 * time.Millisecond): + if tc.wantRestart { + t.Fatal("restart not requested") + } + } + }) + } +} diff --git a/cmd/dobotai/settings_wiring.go b/cmd/dobotai/settings_wiring.go new file mode 100644 index 0000000..7f4da79 --- /dev/null +++ b/cmd/dobotai/settings_wiring.go @@ -0,0 +1,98 @@ +package main + +import ( + "context" + "errors" + "os" + "path/filepath" + "strings" + + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/adminweb" + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/channels/dingtalk" + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/dingtalkconfig" + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/secretstore" + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/settings" + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/store/postgres" +) + +type dingTalkSettingsRouter struct{ controller *settings.Controller } + +func (r *dingTalkSettingsRouter) Handle(ctx context.Context, m dingtalk.SettingsMessage) (bool, string, error) { + if r == nil || r.controller == nil { + return false, "", nil + } + if !r.controller.ShouldHandle(ctx, m.TenantKey, m.StaffID, m.Text) { + return false, "", nil + } + out, err := r.controller.Handle(ctx, settings.SettingInput{TenantKey: m.TenantKey, Channel: m.Channel, StaffID: m.StaffID, UnionID: m.UnionID, DisplayName: m.DisplayName, Department: m.Department, Text: m.Text, ConversationType: m.ConversationType, ConversationID: m.ConversationID, ConversationTitle: m.ConversationTitle}) + return true, strings.TrimSpace(out), err +} + +type settingsRuntime struct { + repository *postgres.SettingsRepository + bindings *validatedSettingsRepository + controller *settings.Controller + admin *adminweb.ControlService + clientID string + secret string + secretRef string + secrets *secretstore.Store + verifier *dingtalkconfig.Verifier + pendingActivation bool +} + +func buildSettingsRuntime(ctx context.Context, store *postgres.Store, tenantKey string) (*settingsRuntime, error) { + tenantKey = strings.TrimSpace(tenantKey) + if tenantKey == "" { + return nil, errors.New("DOBOTAI_TENANT_KEY is required") + } + repo, err := postgres.NewSettingsRepository(store) + if err != nil { + return nil, err + } + root := strings.TrimSpace(os.Getenv("DOBOTAI_SECRET_DIR")) + if root == "" { + home, homeErr := os.UserHomeDir() + if homeErr != nil { + return nil, homeErr + } + root = filepath.Join(home, ".config", "dobotai", "secrets") + } + secrets, err := secretstore.New(root) + if err != nil { + return nil, err + } + pendingActivation, err := repo.PrepareDingTalkRuntimeStart(ctx, tenantKey) + if err != nil { + return nil, err + } + clientID, secretRef, _, err := repo.ActiveDingTalkConfig(ctx, tenantKey) + if err != nil { + return nil, err + } + var secret string + if secretRef != "" { + secret, err = secrets.Get(secretRef) + if err != nil { + return nil, errors.New("active DingTalk secret is unavailable") + } + } + if clientID == "" && strings.TrimSpace(os.Getenv("DINGTALK_CLIENT_ID")) != "" && strings.TrimSpace(os.Getenv("DINGTALK_CLIENT_SECRET")) != "" { + clientID, secret = strings.TrimSpace(os.Getenv("DINGTALK_CLIENT_ID")), strings.TrimSpace(os.Getenv("DINGTALK_CLIENT_SECRET")) + secretRef, err = secrets.Put("dingtalk", secret) + if err != nil { + return nil, err + } + if err = repo.SaveDingTalkConfig(ctx, tenantKey, clientID, secretRef, true); err != nil { + _ = secrets.Delete(secretRef) + return nil, err + } + } + verifier := dingtalkconfig.NewVerifier("https://oapi.dingtalk.com/gettoken", nil) + control, err := adminweb.NewControlService(tenantKey, repo, secrets, verifier) + if err != nil { + return nil, err + } + validatedRepo := &validatedSettingsRepository{SettingsRepository: repo, clientID: clientID, secret: secret} + return &settingsRuntime{repository: repo, bindings: validatedRepo, controller: settings.NewController(validatedRepo), admin: control, clientID: clientID, secret: secret, secretRef: secretRef, secrets: secrets, verifier: verifier, pendingActivation: pendingActivation}, nil +} diff --git a/cmd/dobotai/setup_only.go b/cmd/dobotai/setup_only.go new file mode 100644 index 0000000..0be6344 --- /dev/null +++ b/cmd/dobotai/setup_only.go @@ -0,0 +1,65 @@ +package main + +import ( + "context" + "encoding/json" + "errors" + "log" + "net/http" + "os" + "strings" + "sync/atomic" + "time" + + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/adminweb" + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/settings" +) + +func newSetupOnlyHandler(runtime *settingsRuntime, token string) (http.Handler, error) { + if runtime == nil || runtime.admin == nil { + return nil, errors.New("setup runtime unavailable") + } + if strings.TrimSpace(token) == "" { + return nil, errors.New("DOBOTAI_ADMIN_TOKEN is required in setup-only mode") + } + mux := http.NewServeMux() + mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]string{"status": "ok", "mode": "setup_required"}) + }) + mux.HandleFunc("GET /version", func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(runtimeBuildInfo()) + }) + mux.Handle("/admin/", adminweb.New(runtime.admin, token)) + return mux, nil +} + +func runSetupOnly(ctx context.Context, cancel context.CancelFunc, runtime *settingsRuntime, address, tenant string, restartRequested *atomic.Bool) { + runtime.admin.SetCandidateActivator(&dingTalkCandidateActivator{ + tenant: tenant, repo: runtime.repository, secrets: runtime.secrets, verifier: runtime.verifier, + bindings: map[string]settings.ResourceBinding{}, + restart: func() { restartRequested.Store(true); cancel() }, + }) + handler, err := newSetupOnlyHandler(runtime, os.Getenv("DOBOTAI_ADMIN_TOKEN")) + if err != nil { + log.Fatal(err) + } + server := &http.Server{Addr: address, Handler: handler, ReadHeaderTimeout: 5 * time.Second, ReadTimeout: 15 * time.Second, WriteTimeout: 20 * time.Second, IdleTimeout: 60 * time.Second} + go func() { + log.Printf("DobotAI setup-only listener on %s", address) + if err := server.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) { + log.Printf("setup HTTP server failed: %v", err) + cancel() + } + }() + <-ctx.Done() + shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 10*time.Second) + defer shutdownCancel() + if err := server.Shutdown(shutdownCtx); err != nil { + log.Printf("setup HTTP shutdown: %v", err) + } + if restartRequested.Load() { + os.Exit(75) + } +} diff --git a/cmd/dobotai/setup_only_test.go b/cmd/dobotai/setup_only_test.go new file mode 100644 index 0000000..51db859 --- /dev/null +++ b/cmd/dobotai/setup_only_test.go @@ -0,0 +1,102 @@ +package main + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + "time" + + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/adminweb" + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/dingtalkconfig" + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/secretstore" + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/settings" +) + +type setupRepoStub struct{} + +func (setupRepoStub) ActiveDingTalkConfig(context.Context, string) (string, string, bool, error) { + return "", "", false, nil +} +func (setupRepoStub) CandidateDingTalkConfig(context.Context, string) (string, string, error) { + return "", "", nil +} +func (setupRepoStub) SaveDingTalkConfig(context.Context, string, string, string, bool) error { + return nil +} +func (setupRepoStub) MarkDingTalkCandidateFailed(context.Context, string, string, string) error { + return nil +} +func (setupRepoStub) AdministratorCount(context.Context, string) (int, error) { return 0, nil } +func (setupRepoStub) ActiveBindings(context.Context, string) (map[string]settings.ResourceBinding, error) { + return map[string]settings.ResourceBinding{}, nil +} +func (setupRepoStub) CreateBootstrapChallenge(context.Context, string, string, time.Time) error { + return nil +} +func (setupRepoStub) ConfirmBootstrap(context.Context, string) error { return nil } + +type setupVerifierStub struct{} + +func (setupVerifierStub) Verify(context.Context, string, string) dingtalkconfig.Result { + return dingtalkconfig.Result{} +} + +func setupControl(t *testing.T) *adminweb.ControlService { + t.Helper() + secrets, err := secretstore.New(t.TempDir()) + if err != nil { + t.Fatal(err) + } + control, err := adminweb.NewControlService("tenant", setupRepoStub{}, secrets, setupVerifierStub{}) + if err != nil { + t.Fatal(err) + } + return control +} + +func TestSetupOnlyHandlerExposesHealthVersionAndProtectedAdmin(t *testing.T) { + runtime := &settingsRuntime{admin: setupControl(t)} + h, err := newSetupOnlyHandler(runtime, "admin-token") + if err != nil { + t.Fatal(err) + } + req := httptest.NewRequest(http.MethodGet, "/healthz", nil) + resp := httptest.NewRecorder() + h.ServeHTTP(resp, req) + if resp.Code != http.StatusOK { + t.Fatalf("health status=%d", resp.Code) + } + var health map[string]string + if err = json.Unmarshal(resp.Body.Bytes(), &health); err != nil { + t.Fatal(err) + } + if health["status"] != "ok" || health["mode"] != "setup_required" { + t.Fatalf("health=%v", health) + } + resp = httptest.NewRecorder() + h.ServeHTTP(resp, httptest.NewRequest(http.MethodGet, "/version", nil)) + if resp.Code != http.StatusOK { + t.Fatalf("version status=%d", resp.Code) + } + resp = httptest.NewRecorder() + h.ServeHTTP(resp, httptest.NewRequest(http.MethodGet, "/admin/settings", nil)) + if resp.Code != http.StatusUnauthorized { + t.Fatalf("unauth status=%d", resp.Code) + } + req = httptest.NewRequest(http.MethodGet, "/admin/settings", nil) + req.Header.Set("Authorization", "Bearer admin-token") + resp = httptest.NewRecorder() + h.ServeHTTP(resp, req) + if resp.Code != http.StatusOK { + t.Fatalf("auth status=%d body=%s", resp.Code, resp.Body.String()) + } +} + +func TestSetupOnlyHandlerRequiresAdminToken(t *testing.T) { + _, err := newSetupOnlyHandler(&settingsRuntime{admin: setupControl(t)}, "") + if err == nil { + t.Fatal("expected token error") + } +} diff --git a/cmd/dobotai/support_notifications.go b/cmd/dobotai/support_notifications.go new file mode 100644 index 0000000..f03d81b --- /dev/null +++ b/cmd/dobotai/support_notifications.go @@ -0,0 +1,67 @@ +package main + +import ( + "context" + "errors" + "log" + "strings" + "time" + + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/channels/dingtalk" + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/coverage" + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/faqtable" +) + +type supportDispatcherRunner interface { + RunOnce(context.Context) (coverage.DispatcherStats, error) +} + +func buildSupportDispatcher(repo coverage.NotificationRepository, clientID, clientSecret, openConversationID string, recordLinks *faqtable.RecordLinkBuilder) (*coverage.Dispatcher, error) { + openConversationID = strings.TrimSpace(openConversationID) + if openConversationID == "" { + return nil, nil + } + if repo == nil { + return nil, errors.New("support notification repository is required") + } + if recordLinks == nil { + return nil, nil + } + + sender, err := dingtalk.NewSupportGroupSender(clientID, clientSecret, openConversationID, nil, dingtalk.WithFAQRecordLinkBuilder(recordLinks)) + if err != nil { + return nil, err + } + return coverage.NewDispatcher(repo, sender) +} + +func runSupportDispatcher(ctx context.Context, dispatcher supportDispatcherRunner, interval time.Duration) { + if dispatcher == nil || interval <= 0 { + return + } + + runOnce := func() { + runCtx, cancel := context.WithTimeout(ctx, 30*time.Second) + stats, err := dispatcher.RunOnce(runCtx) + cancel() + if err != nil { + log.Printf("support notification dispatch failed: %v", err) + return + } + if stats.Claimed > 0 { + log.Printf("support notification dispatch: claimed=%d notified=%d failed=%d", stats.Claimed, stats.Notified, stats.Failed) + } + } + + runOnce() + ticker := time.NewTicker(interval) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return + case <-ticker.C: + runOnce() + } + } +} diff --git a/cmd/dobotai/support_notifications_test.go b/cmd/dobotai/support_notifications_test.go new file mode 100644 index 0000000..388c722 --- /dev/null +++ b/cmd/dobotai/support_notifications_test.go @@ -0,0 +1,179 @@ +package main + +import ( + "context" + "errors" + "os" + "strings" + "sync" + "testing" + "time" + + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/coverage" + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/faqtable" +) + +type supportNotificationRepoStub struct{} + +func (*supportNotificationRepoStub) Claim(context.Context, int, int, time.Time) ([]coverage.PendingSupportCase, error) { + return nil, nil +} +func (*supportNotificationRepoStub) MarkNotified(context.Context, string) error { return nil } +func (*supportNotificationRepoStub) MarkFailed(context.Context, string, string) error { return nil } + +func testFAQRecordLinks(t *testing.T) *faqtable.RecordLinkBuilder { + t.Helper() + builder, err := faqtable.NewRecordLinkBuilder("base", "sheet", "view") + if err != nil { + t.Fatal(err) + } + return builder +} + +type supportDispatcherStub struct { + mu sync.Mutex + calls int + errs []error + callCh chan int +} + +func (s *supportDispatcherStub) RunOnce(context.Context) (coverage.DispatcherStats, error) { + s.mu.Lock() + s.calls++ + call := s.calls + var err error + if call <= len(s.errs) { + err = s.errs[call-1] + } + s.mu.Unlock() + if s.callCh != nil { + select { + case s.callCh <- call: + default: + } + } + return coverage.DispatcherStats{Claimed: 1, Notified: 1}, err +} + +func TestBuildSupportDispatcherDisabledWithoutGroup(t *testing.T) { + dispatcher, err := buildSupportDispatcher(nil, "", "", " ", nil) + if err != nil || dispatcher != nil { + t.Fatalf("dispatcher=%v err=%v, want disabled", dispatcher, err) + } +} + +func TestBuildSupportDispatcherBlocksWithoutFAQLinks(t *testing.T) { + dispatcher, err := buildSupportDispatcher(&supportNotificationRepoStub{}, "client", "secret", "group", nil) + if err != nil || dispatcher != nil { + t.Fatalf("dispatcher=%v err=%v, want blocked without process failure", dispatcher, err) + } +} + +func TestBuildSupportDispatcherEnabledFailsClosed(t *testing.T) { + repo := &supportNotificationRepoStub{} + links := testFAQRecordLinks(t) + for _, tc := range []struct { + name string + repo coverage.NotificationRepository + clientID, secret, gid string + links *faqtable.RecordLinkBuilder + }{ + {name: "missing repo", clientID: "client", secret: "secret", gid: "group", links: links}, + {name: "missing client", repo: repo, secret: "secret", gid: "group", links: links}, + {name: "missing secret", repo: repo, clientID: "client", gid: "group", links: links}, + } { + t.Run(tc.name, func(t *testing.T) { + if _, err := buildSupportDispatcher(tc.repo, tc.clientID, tc.secret, tc.gid, tc.links); err == nil { + t.Fatal("expected configuration error") + } + }) + } +} + +func TestBuildSupportDispatcherValidDoesNotSend(t *testing.T) { + dispatcher, err := buildSupportDispatcher(&supportNotificationRepoStub{}, " client ", " secret ", " group ", testFAQRecordLinks(t)) + if err != nil { + t.Fatalf("buildSupportDispatcher: %v", err) + } + if dispatcher == nil { + t.Fatal("expected dispatcher") + } +} + +func TestRunSupportDispatcherRunsImmediatelyAndStops(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + stub := &supportDispatcherStub{callCh: make(chan int, 4)} + done := make(chan struct{}) + go func() { + runSupportDispatcher(ctx, stub, time.Hour) + close(done) + }() + + select { + case <-stub.callCh: + case <-time.After(500 * time.Millisecond): + t.Fatal("dispatcher did not run immediately") + } + cancel() + select { + case <-done: + case <-time.After(500 * time.Millisecond): + t.Fatal("dispatcher did not stop after context cancellation") + } +} + +func TestRunSupportDispatcherContinuesAfterError(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + stub := &supportDispatcherStub{ + errs: []error{errors.New("temporary db error")}, + callCh: make(chan int, 4), + } + done := make(chan struct{}) + go func() { + runSupportDispatcher(ctx, stub, 10*time.Millisecond) + close(done) + }() + + for want := 1; want <= 2; want++ { + select { + case got := <-stub.callCh: + if got != want { + t.Fatalf("call=%d, want %d", got, want) + } + case <-time.After(500 * time.Millisecond): + t.Fatalf("missing dispatcher call %d", want) + } + } + cancel() + <-done +} + +func TestRunSupportDispatcherRejectsNonPositiveInterval(t *testing.T) { + stub := &supportDispatcherStub{} + runSupportDispatcher(context.Background(), stub, 0) + stub.mu.Lock() + defer stub.mu.Unlock() + if stub.calls != 0 { + t.Fatalf("calls=%d, want 0", stub.calls) + } +} + +func TestMainWiresCoverageSupportNotifications(t *testing.T) { + data, err := os.ReadFile("main.go") + if err != nil { + t.Fatal(err) + } + source := string(data) + for _, fragment := range []string{ + `os.Getenv("DINGTALK_SUPPORT_GROUP_OPEN_CONVERSATION_ID")`, + `coverage.NewService(store)`, + `qa.WithSucceededTurnObserver`, + `case <-runtimeReady:`, + `runSupportDispatcher(ctx, supportDispatcher, 5*time.Second)`, + } { + if !strings.Contains(source, fragment) { + t.Errorf("main support notification wiring missing %q", fragment) + } + } +} diff --git a/db/migrations/000007_coverage_decisions.down.sql b/db/migrations/000007_coverage_decisions.down.sql new file mode 100644 index 0000000..b9fcaf3 --- /dev/null +++ b/db/migrations/000007_coverage_decisions.down.sql @@ -0,0 +1,5 @@ +-- 000007_coverage_decisions down migration +-- Drop support_cases first (child table), then coverage_decisions (parent table). + +DROP TABLE IF EXISTS support_cases; +DROP TABLE IF EXISTS coverage_decisions; \ No newline at end of file diff --git a/db/migrations/000007_coverage_decisions.up.sql b/db/migrations/000007_coverage_decisions.up.sql new file mode 100644 index 0000000..9d5e789 --- /dev/null +++ b/db/migrations/000007_coverage_decisions.up.sql @@ -0,0 +1,49 @@ +-- 000007_coverage_decisions up migration +-- Creates coverage_decisions and support_cases tables for B3.1 persistence. + +CREATE TABLE IF NOT EXISTS coverage_decisions ( + id TEXT PRIMARY KEY, + tenant_key TEXT NOT NULL, + channel TEXT NOT NULL, + turn_id TEXT NOT NULL REFERENCES turns(id), + evaluator_version TEXT NOT NULL DEFAULT 'v1', + verdict TEXT NOT NULL CHECK (verdict IN ('covered', 'uncovered')), + reason_code TEXT NOT NULL CHECK (reason_code IN ( + 'covered_has_references', + 'uncovered_no_references', + 'uncovered_explicit_no_answer' + )), + reference_count INTEGER NOT NULL DEFAULT 0 CHECK (reference_count >= 0), + top_score DOUBLE PRECISION NOT NULL DEFAULT 0, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + UNIQUE (tenant_key, channel, turn_id) +); + +CREATE INDEX IF NOT EXISTS idx_coverage_decisions_tenant_channel + ON coverage_decisions (tenant_key, channel, created_at DESC); + +CREATE INDEX IF NOT EXISTS idx_coverage_decisions_verdict + ON coverage_decisions (verdict) WHERE verdict = 'uncovered'; + +CREATE TABLE IF NOT EXISTS support_cases ( + id TEXT PRIMARY KEY, + tenant_key TEXT NOT NULL, + channel TEXT NOT NULL, + turn_id TEXT NOT NULL REFERENCES turns(id), + coverage_decision_id TEXT NOT NULL REFERENCES coverage_decisions(id), + status TEXT NOT NULL DEFAULT 'pending' CHECK (status IN ('pending', 'notifying', 'notification_failed', 'notified', 'resolved')), + notification_attempts INTEGER NOT NULL DEFAULT 0 CHECK (notification_attempts >= 0), + last_notification_failure_code TEXT NOT NULL DEFAULT '', + last_notification_at TIMESTAMPTZ, + notified_at TIMESTAMPTZ, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + UNIQUE (tenant_key, channel, turn_id) +); + +CREATE INDEX IF NOT EXISTS idx_support_cases_notification_pending + ON support_cases (status, created_at, id) WHERE status IN ('pending', 'notification_failed'); + +CREATE INDEX IF NOT EXISTS idx_support_cases_notifying_stale + ON support_cases (status, last_notification_at) WHERE status = 'notifying'; \ No newline at end of file diff --git a/db/migrations/000007_coverage_decisions_contract_test.go b/db/migrations/000007_coverage_decisions_contract_test.go new file mode 100644 index 0000000..6070368 --- /dev/null +++ b/db/migrations/000007_coverage_decisions_contract_test.go @@ -0,0 +1,179 @@ +// Package migrations_test contains source-level contract tests for the +// 000007_coverage_decisions migration. No real database connection is used. +package migrations_test + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +func read007Migration(t *testing.T, direction string) string { + t.Helper() + data, err := os.ReadFile(filepath.Join(".", "000007_coverage_decisions."+direction+".sql")) + if err != nil { + t.Fatalf("read 000007 %s migration: %v", direction, err) + } + return string(data) +} + +func TestUp007CreatesCoverageDecisionsTable(t *testing.T) { + up := strings.ToUpper(read007Migration(t, "up")) + required := []string{ + "CREATE TABLE IF NOT EXISTS COVERAGE_DECISIONS", + "ID", "TENANT_KEY", "CHANNEL", "TURN_ID", + "EVALUATOR_VERSION", "VERDICT", "REASON_CODE", "REFERENCE_COUNT", "TOP_SCORE", + "CREATED_AT", "UPDATED_AT", + } + for _, fragment := range required { + if !strings.Contains(up, fragment) { + t.Errorf("up migration missing %q", fragment) + } + } +} + +func TestUp007CoverageDecisionsConstraints(t *testing.T) { + up := strings.ToUpper(read007Migration(t, "up")) + // REFERENCES turns(id) + if !strings.Contains(up, "REFERENCES TURNS(ID)") { + t.Error("coverage_decisions.turn_id must reference turns(id)") + } + // UNIQUE (tenant_key, channel, turn_id) + if !strings.Contains(up, "UNIQUE (TENANT_KEY, CHANNEL, TURN_ID)") { + t.Error("coverage_decisions must have UNIQUE (tenant_key, channel, turn_id)") + } + // verdict CHECK + if !strings.Contains(up, "COVERED") || !strings.Contains(up, "UNCOVERED") { + t.Error("verdict CHECK must include 'covered' and 'uncovered'") + } + // reason_code CHECK + for _, code := range []string{"COVERED_HAS_REFERENCES", "UNCOVERED_NO_REFERENCES", "UNCOVERED_EXPLICIT_NO_ANSWER"} { + if !strings.Contains(up, code) { + t.Errorf("reason_code CHECK missing %q", code) + } + } +} + +func TestUp007CreatesSupportCasesTable(t *testing.T) { + up := strings.ToUpper(read007Migration(t, "up")) + required := []string{ + "CREATE TABLE IF NOT EXISTS SUPPORT_CASES", + "ID", "TENANT_KEY", "CHANNEL", "TURN_ID", + "COVERAGE_DECISION_ID", "STATUS", "CREATED_AT", "UPDATED_AT", + } + for _, fragment := range required { + if !strings.Contains(up, fragment) { + t.Errorf("up migration missing %q", fragment) + } + } + // Notification fields must be present + notificationFields := []string{ + "NOTIFICATION_ATTEMPTS", "LAST_NOTIFICATION_FAILURE_CODE", + "LAST_NOTIFICATION_AT", "NOTIFIED_AT", + } + for _, fragment := range notificationFields { + if !strings.Contains(up, fragment) { + t.Errorf("up migration missing notification field %q", fragment) + } + } +} + +func TestUp007SupportCasesConstraints(t *testing.T) { + up := strings.ToUpper(read007Migration(t, "up")) + // FK to coverage_decisions + if !strings.Contains(up, "REFERENCES COVERAGE_DECISIONS(ID)") { + t.Error("support_cases.coverage_decision_id must reference coverage_decisions(id)") + } + // FK to turns + if !strings.Contains(up, "REFERENCES TURNS(ID)") { + t.Error("support_cases.turn_id must reference turns(id)") + } + // UNIQUE (tenant_key, channel, turn_id) + if !strings.Contains(up, "UNIQUE (TENANT_KEY, CHANNEL, TURN_ID)") { + t.Error("support_cases must have UNIQUE (tenant_key, channel, turn_id)") + } + // status CHECK + for _, status := range []string{"PENDING", "NOTIFYING", "NOTIFICATION_FAILED", "NOTIFIED", "RESOLVED"} { + if !strings.Contains(up, status) { + t.Errorf("status CHECK must include %q", status) + } + } +} + +func TestUp007CreatesQueryIndexes(t *testing.T) { + up := strings.ToUpper(read007Migration(t, "up")) + // Pending/retry query index and stale notifying index + if !strings.Contains(up, "IDX_SUPPORT_CASES_NOTIFICATION_PENDING") || + !strings.Contains(up, "WHERE STATUS IN ('PENDING', 'NOTIFICATION_FAILED')") { + t.Error("up migration must index pending and notification_failed support_cases") + } + if !strings.Contains(up, "IDX_SUPPORT_CASES_NOTIFYING_STALE") || + !strings.Contains(up, "WHERE STATUS = 'NOTIFYING'") { + t.Error("up migration must index stale notifying support_cases") + } + // Coverage decisions listing index + if !strings.Contains(up, "IDX_COVERAGE_DECISIONS_TENANT_CHANNEL") { + t.Error("up migration must create index on coverage_decisions (tenant_key, channel, created_at DESC)") + } + // Uncovered verdict index + if !strings.Contains(up, "WHERE VERDICT = 'UNCOVERED'") { + t.Error("up migration must create partial index on uncovered coverage_decisions") + } +} + +func TestUp007CoverageNoReservedWords(t *testing.T) { + up := read007Migration(t, "up") + // Check for bare "references" as column name in CREATE TABLE statements + lines := strings.Split(up, "\n") + for _, line := range lines { + trimmed := strings.TrimSpace(line) + upperLine := strings.ToUpper(trimmed) + if strings.HasPrefix(upperLine, "REFERENCES ") && !strings.Contains(upperLine, "REFERENCES TURNS") && !strings.Contains(upperLine, "REFERENCES COVERAGE") { + t.Errorf("reserved word 'references' used as column name in: %s", trimmed) + } + } +} + +func TestUp007NoForbiddenOperations(t *testing.T) { + up := strings.ToUpper(read007Migration(t, "up")) + for _, forbidden := range []string{ + "DROP TABLE", "DROP COLUMN", "TRUNCATE", "DELETE FROM", + "ALTER TABLE", "RAW_PAYLOAD", "SESSIONWEBHOOK", "TOKEN", + "RAW_RESPONSE", "RAW_ERROR", + } { + if strings.Contains(up, forbidden) { + t.Errorf("up migration contains forbidden operation %q", forbidden) + } + } +} + +func TestUp007NoQuestionAnswerBodies(t *testing.T) { + up := strings.ToUpper(read007Migration(t, "up")) + for _, forbidden := range []string{"QUESTION", "ANSWER_TEXT", "REFERENCE_CONTENT", "ANSWER_CONTENT"} { + if strings.Contains(up, forbidden) { + t.Errorf("coverage/support tables must not duplicate question/answer/reference bodies: found %q", forbidden) + } + } +} + +func TestDown007DropsInSafeOrder(t *testing.T) { + down := strings.ToUpper(read007Migration(t, "down")) + supportAt := strings.Index(down, "DROP TABLE IF EXISTS SUPPORT_CASES") + coverageAt := strings.Index(down, "DROP TABLE IF EXISTS COVERAGE_DECISIONS") + if supportAt < 0 || coverageAt < 0 { + t.Fatal("down migration must drop both tables") + } + if supportAt > coverageAt { + t.Fatal("down migration must drop support_cases (child) before coverage_decisions (parent)") + } +} + +func TestDown007DoesNotDropBaselineTables(t *testing.T) { + down := strings.ToUpper(read007Migration(t, "down")) + for _, table := range []string{"TURNS", "MESSAGES", "SESSION_MAPPINGS", "CHANNEL_ACTORS", "CHANNEL_CONVERSATIONS"} { + if strings.Contains(down, "DROP TABLE IF EXISTS "+table) { + t.Errorf("down migration must not drop baseline table %q", table) + } + } +} diff --git a/db/migrations/000008_session_display_title.down.sql b/db/migrations/000008_session_display_title.down.sql new file mode 100644 index 0000000..77daf09 --- /dev/null +++ b/db/migrations/000008_session_display_title.down.sql @@ -0,0 +1,2 @@ +ALTER TABLE session_mappings + DROP COLUMN IF EXISTS display_title; diff --git a/db/migrations/000008_session_display_title.up.sql b/db/migrations/000008_session_display_title.up.sql new file mode 100644 index 0000000..d21e367 --- /dev/null +++ b/db/migrations/000008_session_display_title.up.sql @@ -0,0 +1,2 @@ +ALTER TABLE session_mappings + ADD COLUMN IF NOT EXISTS display_title TEXT NOT NULL DEFAULT ''; diff --git a/db/migrations/000008_session_display_title_test.go b/db/migrations/000008_session_display_title_test.go new file mode 100644 index 0000000..1c1b2d3 --- /dev/null +++ b/db/migrations/000008_session_display_title_test.go @@ -0,0 +1,28 @@ +package migrations + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +func TestSessionDisplayTitleMigration(t *testing.T) { + up, err := os.ReadFile(filepath.Join("000008_session_display_title.up.sql")) + if err != nil { + t.Fatalf("read up migration: %v", err) + } + down, err := os.ReadFile(filepath.Join("000008_session_display_title.down.sql")) + if err != nil { + t.Fatalf("read down migration: %v", err) + } + upper := strings.ToUpper(string(up)) + for _, required := range []string{"ALTER TABLE SESSION_MAPPINGS", "ADD COLUMN IF NOT EXISTS DISPLAY_TITLE", "TEXT NOT NULL", "DEFAULT ''"} { + if !strings.Contains(upper, required) { + t.Errorf("up migration missing %q", required) + } + } + if !strings.Contains(strings.ToUpper(string(down)), "DROP COLUMN IF EXISTS DISPLAY_TITLE") { + t.Error("down migration must drop display_title") + } +} diff --git a/db/migrations/000009_directory_profiles.down.sql b/db/migrations/000009_directory_profiles.down.sql new file mode 100644 index 0000000..236647a --- /dev/null +++ b/db/migrations/000009_directory_profiles.down.sql @@ -0,0 +1,7 @@ +ALTER TABLE messages + DROP COLUMN IF EXISTS region_snapshot; + +ALTER TABLE messages + DROP COLUMN IF EXISTS department_snapshot; + +DROP TABLE IF EXISTS directory_profiles; diff --git a/db/migrations/000009_directory_profiles.up.sql b/db/migrations/000009_directory_profiles.up.sql new file mode 100644 index 0000000..c7cbf97 --- /dev/null +++ b/db/migrations/000009_directory_profiles.up.sql @@ -0,0 +1,26 @@ +CREATE TABLE IF NOT EXISTS directory_profiles ( + tenant_key TEXT NOT NULL, + staff_id TEXT NOT NULL, + union_id TEXT NOT NULL DEFAULT '', + name TEXT NOT NULL, + nickname TEXT NOT NULL DEFAULT '', + job_title TEXT NOT NULL DEFAULT '', + department_ids JSONB NOT NULL DEFAULT '[]'::JSONB, + department_name TEXT NOT NULL DEFAULT '', + main_department_name TEXT NOT NULL DEFAULT '', + region TEXT NOT NULL DEFAULT '', + employment_status TEXT NOT NULL DEFAULT '', + source TEXT NOT NULL CHECK (source IN ('full_sync','on_demand')), + synced_at TIMESTAMPTZ NOT NULL, + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + PRIMARY KEY (tenant_key, staff_id) +); + +CREATE INDEX IF NOT EXISTS idx_directory_profiles_tenant_name + ON directory_profiles (tenant_key, name); + +ALTER TABLE messages + ADD COLUMN IF NOT EXISTS department_snapshot TEXT NOT NULL DEFAULT ''; + +ALTER TABLE messages + ADD COLUMN IF NOT EXISTS region_snapshot TEXT NOT NULL DEFAULT ''; diff --git a/db/migrations/000009_directory_profiles_test.go b/db/migrations/000009_directory_profiles_test.go new file mode 100644 index 0000000..7e3f2b6 --- /dev/null +++ b/db/migrations/000009_directory_profiles_test.go @@ -0,0 +1,42 @@ +package migrations + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +func TestDirectoryProfilesMigration(t *testing.T) { + up, err := os.ReadFile(filepath.Join("000009_directory_profiles.up.sql")) + if err != nil { + t.Fatalf("read up migration: %v", err) + } + down, err := os.ReadFile(filepath.Join("000009_directory_profiles.down.sql")) + if err != nil { + t.Fatalf("read down migration: %v", err) + } + upper := strings.ToUpper(string(up)) + for _, required := range []string{ + "CREATE TABLE IF NOT EXISTS DIRECTORY_PROFILES", + "PRIMARY KEY (TENANT_KEY, STAFF_ID)", + "DEPARTMENT_IDS JSONB", + "REGION TEXT", + "SOURCE TEXT", + "ADD COLUMN IF NOT EXISTS DEPARTMENT_SNAPSHOT", + "ADD COLUMN IF NOT EXISTS REGION_SNAPSHOT", + } { + if !strings.Contains(upper, required) { + t.Errorf("up migration missing %q", required) + } + } + for _, forbidden := range []string{"MOBILE", "EMAIL", "CLIENT_SECRET", "ACCESS_TOKEN", "RAW_PAYLOAD"} { + if strings.Contains(upper, forbidden) { + t.Errorf("up migration contains forbidden sensitive field %q", forbidden) + } + } + downUpper := strings.ToUpper(string(down)) + if !strings.Contains(downUpper, "DROP TABLE IF EXISTS DIRECTORY_PROFILES") || !strings.Contains(downUpper, "DROP COLUMN IF EXISTS REGION_SNAPSHOT") { + t.Error("down migration must remove directory table and snapshot columns") + } +} diff --git a/db/migrations/000010_question_table_exports.down.sql b/db/migrations/000010_question_table_exports.down.sql new file mode 100644 index 0000000..56f7e6f --- /dev/null +++ b/db/migrations/000010_question_table_exports.down.sql @@ -0,0 +1,9 @@ +-- 000010_question_table_exports down migration +-- Drop in reverse dependency order: first drop export table, then remove column + +DROP TABLE IF EXISTS question_table_exports; + +ALTER TABLE messages + DROP COLUMN IF EXISTS trigger_person_snapshot; +ALTER TABLE messages + DROP COLUMN IF EXISTS actor_union_id_snapshot; \ No newline at end of file diff --git a/db/migrations/000010_question_table_exports.up.sql b/db/migrations/000010_question_table_exports.up.sql new file mode 100644 index 0000000..e454de6 --- /dev/null +++ b/db/migrations/000010_question_table_exports.up.sql @@ -0,0 +1,40 @@ +-- 000010_question_table_exports: durable outbox for Notable question table async sync +-- Add trigger_person_snapshot and actor_union_id_snapshot to messages and create question_table_exports table + +-- 1. Add trigger_person_snapshot and actor_union_id_snapshot columns to messages +ALTER TABLE messages + ADD COLUMN IF NOT EXISTS trigger_person_snapshot TEXT NOT NULL DEFAULT ''; +ALTER TABLE messages + ADD COLUMN IF NOT EXISTS actor_union_id_snapshot TEXT NOT NULL DEFAULT ''; + +-- 2. Create question_table_exports outbox table +CREATE TABLE IF NOT EXISTS question_table_exports ( + id TEXT PRIMARY KEY, + tenant_key TEXT NOT NULL, + channel TEXT NOT NULL, + turn_id TEXT NOT NULL REFERENCES turns(id), + status TEXT NOT NULL DEFAULT 'pending' + CHECK (status IN ('pending', 'exporting', 'exported', 'export_failed')), + attempts INTEGER NOT NULL DEFAULT 0, + last_attempt_at TIMESTAMPTZ, + next_attempt_at TIMESTAMPTZ, + exported_at TIMESTAMPTZ, + failure_code TEXT NOT NULL DEFAULT '', + external_record_id TEXT NOT NULL DEFAULT '', + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + UNIQUE (tenant_key, channel, turn_id) +); + +-- 3. Index for claim query: pending/export_failed/exporting ordered by created_at +-- Covers pending, export_failed (when next_attempt_at is NULL or <= NOW()), +-- and stale exporting (when last_attempt_at < staleBefore). +CREATE INDEX IF NOT EXISTS idx_question_table_exports_claim + ON question_table_exports (status, next_attempt_at, created_at, id) + WHERE status IN ('pending', 'export_failed') + OR (status = 'exporting' AND last_attempt_at IS NOT NULL); + +-- 4. Index for stale exporting recovery +CREATE INDEX IF NOT EXISTS idx_question_table_exports_stale + ON question_table_exports (status, last_attempt_at) + WHERE status = 'exporting'; \ No newline at end of file diff --git a/db/migrations/000010_question_table_exports_contract_test.go b/db/migrations/000010_question_table_exports_contract_test.go new file mode 100644 index 0000000..5738b22 --- /dev/null +++ b/db/migrations/000010_question_table_exports_contract_test.go @@ -0,0 +1,161 @@ +// Package migrations_test contains source-level contract tests for the +// 000010_question_table_exports migration. No real database connection is used. +package migrations_test + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +func read010Migration(t *testing.T, direction string) string { + t.Helper() + data, err := os.ReadFile(filepath.Join(".", "000010_question_table_exports."+direction+".sql")) + if err != nil { + t.Fatalf("read 000010 %s migration: %v", direction, err) + } + return string(data) +} + +func TestUp010AddsTriggerPersonSnapshot(t *testing.T) { + up := strings.ToUpper(read010Migration(t, "up")) + if !strings.Contains(up, "ALTER TABLE MESSAGES") { + t.Fatal("up migration must alter messages") + } + if !strings.Contains(up, "ADD COLUMN IF NOT EXISTS TRIGGER_PERSON_SNAPSHOT") { + t.Error("up migration must add trigger_person_snapshot column") + } + if !strings.Contains(up, "ADD COLUMN IF NOT EXISTS ACTOR_UNION_ID_SNAPSHOT") { + t.Error("up migration must add actor_union_id_snapshot column") + } + if !strings.Contains(up, "TEXT NOT NULL DEFAULT ''") { + t.Error("snapshot columns must be TEXT NOT NULL DEFAULT ''") + } +} + +func TestUp010CreatesQuestionTableExports(t *testing.T) { + up := strings.ToUpper(read010Migration(t, "up")) + required := []string{ + "CREATE TABLE IF NOT EXISTS QUESTION_TABLE_EXPORTS", + "ID", "TENANT_KEY", "CHANNEL", "TURN_ID", + "STATUS", "ATTEMPTS", "LAST_ATTEMPT_AT", "NEXT_ATTEMPT_AT", "EXPORTED_AT", + "FAILURE_CODE", "EXTERNAL_RECORD_ID", + "CREATED_AT", "UPDATED_AT", + } + for _, fragment := range required { + if !strings.Contains(up, fragment) { + t.Errorf("up migration missing %q", fragment) + } + } +} + +func TestUp010QuestionTableExportsConstraints(t *testing.T) { + up := strings.ToUpper(read010Migration(t, "up")) + // FK to turns + if !strings.Contains(up, "REFERENCES TURNS(ID)") { + t.Error("question_table_exports.turn_id must reference turns(id)") + } + // UNIQUE (tenant_key, channel, turn_id) + if !strings.Contains(up, "UNIQUE (TENANT_KEY, CHANNEL, TURN_ID)") { + t.Error("question_table_exports must have UNIQUE (tenant_key, channel, turn_id)") + } + // status CHECK + for _, status := range []string{"PENDING", "EXPORTING", "EXPORTED", "EXPORT_FAILED"} { + if !strings.Contains(up, status) { + t.Errorf("status CHECK must include %q", status) + } + } +} + +func TestUp010ClaimIndexes(t *testing.T) { + up := strings.ToUpper(read010Migration(t, "up")) + if !strings.Contains(up, "IDX_QUESTION_TABLE_EXPORTS_CLAIM") { + t.Error("up migration must create claim index") + } + if !strings.Contains(up, "WHERE STATUS IN ('PENDING', 'EXPORT_FAILED')") { + t.Error("claim index must include pending and export_failed statuses") + } + if !strings.Contains(up, "IDX_QUESTION_TABLE_EXPORTS_STALE") { + t.Error("up migration must create stale exporting index") + } + if !strings.Contains(up, "WHERE STATUS = 'EXPORTING'") { + t.Error("stale index must filter exporting status") + } +} + +func TestUp010HasNextAttemptAtColumn(t *testing.T) { + up := strings.ToUpper(read010Migration(t, "up")) + if !strings.Contains(up, "NEXT_ATTEMPT_AT TIMESTAMPTZ") { + t.Error("question_table_exports must have next_attempt_at column for retry backoff") + } +} + +func TestUp010HasExternalRecordID(t *testing.T) { + up := strings.ToUpper(read010Migration(t, "up")) + if !strings.Contains(up, "EXTERNAL_RECORD_ID TEXT NOT NULL DEFAULT ''") { + t.Error("question_table_exports must have external_record_id column (not a1_notation)") + } + if strings.Contains(up, "A1_NOTATION") { + t.Error("question_table_exports must not have stale a1_notation column") + } +} + +func TestUp010ClaimIndexCoversNextAttemptAt(t *testing.T) { + up := strings.ToUpper(read010Migration(t, "up")) + if !strings.Contains(up, "NEXT_ATTEMPT_AT") { + t.Error("claim index must cover next_attempt_at for retry backoff filtering") + } +} + +func TestDown010DropsInSafeOrder(t *testing.T) { + down := strings.ToUpper(read010Migration(t, "down")) + dropExportAt := strings.Index(down, "DROP TABLE IF EXISTS QUESTION_TABLE_EXPORTS") + dropTriggerAt := strings.Index(down, "DROP COLUMN IF EXISTS TRIGGER_PERSON_SNAPSHOT") + dropUnionAt := strings.Index(down, "DROP COLUMN IF EXISTS ACTOR_UNION_ID_SNAPSHOT") + if dropExportAt < 0 || dropTriggerAt < 0 || dropUnionAt < 0 { + t.Fatal("down migration must drop export table and both snapshot columns") + } + if dropExportAt > dropTriggerAt || dropTriggerAt > dropUnionAt { + t.Fatal("down migration must drop export table before snapshot columns") + } +} + +func TestDown010DoesNotDropBaselineTables(t *testing.T) { + down := strings.ToUpper(read010Migration(t, "down")) + for _, table := range []string{"TURNS", "MESSAGES", "SESSION_MAPPINGS", "CHANNEL_ACTORS", "CHANNEL_CONVERSATIONS"} { + if strings.Contains(down, "DROP TABLE IF EXISTS "+table) { + t.Errorf("down migration must not drop baseline table %q", table) + } + } +} + +func TestUp010ExportsNoFormulaColumns(t *testing.T) { + up := read010Migration(t, "up") + // Check that the CREATE TABLE body does not contain user/AI content columns + lines := strings.Split(up, "\n") + inTable := false + for _, line := range lines { + trimmed := strings.TrimSpace(line) + upper := strings.ToUpper(trimmed) + if strings.HasPrefix(upper, "CREATE TABLE IF NOT EXISTS QUESTION_TABLE_EXPORTS") { + inTable = true + continue + } + if inTable && trimmed == ");" { + inTable = false + continue + } + if !inTable { + continue + } + for _, forbidden := range []string{ + "QUESTION", "ANSWER_TEXT", "RAW_PAYLOAD", "SESSIONWEBHOOK", "TOKEN", + "RAW_RESPONSE", "RAW_ERROR", "ACCESS_TOKEN", "APP_SECRET", + } { + if strings.Contains(upper, forbidden) { + t.Errorf("question_table_exports column must not contain %q", forbidden) + } + } + } +} diff --git a/db/migrations/000011_faq_exports.down.sql b/db/migrations/000011_faq_exports.down.sql new file mode 100644 index 0000000..ca7c783 --- /dev/null +++ b/db/migrations/000011_faq_exports.down.sql @@ -0,0 +1,11 @@ +DROP INDEX IF EXISTS idx_support_cases_faq_export_stale; +DROP INDEX IF EXISTS idx_support_cases_faq_export_claim; + +ALTER TABLE support_cases + DROP COLUMN IF EXISTS faq_record_id, + DROP COLUMN IF EXISTS faq_failure_code, + DROP COLUMN IF EXISTS faq_exported_at, + DROP COLUMN IF EXISTS faq_next_attempt_at, + DROP COLUMN IF EXISTS faq_last_attempt_at, + DROP COLUMN IF EXISTS faq_export_attempts, + DROP COLUMN IF EXISTS faq_export_status; diff --git a/db/migrations/000011_faq_exports.up.sql b/db/migrations/000011_faq_exports.up.sql new file mode 100644 index 0000000..2ec8565 --- /dev/null +++ b/db/migrations/000011_faq_exports.up.sql @@ -0,0 +1,24 @@ +-- Durable FAQ export state for uncovered support cases. +ALTER TABLE support_cases + ADD COLUMN IF NOT EXISTS faq_export_status TEXT NOT NULL DEFAULT 'not_applicable' + CHECK (faq_export_status IN ('not_applicable', 'pending', 'exporting', 'exported', 'export_failed')), + ADD COLUMN IF NOT EXISTS faq_export_attempts INTEGER NOT NULL DEFAULT 0 + CHECK (faq_export_attempts >= 0), + ADD COLUMN IF NOT EXISTS faq_last_attempt_at TIMESTAMPTZ, + ADD COLUMN IF NOT EXISTS faq_next_attempt_at TIMESTAMPTZ, + ADD COLUMN IF NOT EXISTS faq_exported_at TIMESTAMPTZ, + ADD COLUMN IF NOT EXISTS faq_failure_code TEXT NOT NULL DEFAULT '', + ADD COLUMN IF NOT EXISTS faq_record_id TEXT NOT NULL DEFAULT ''; + +-- Existing cases are intentionally not backfilled. Only cases created after +-- this migration enter the FAQ workflow automatically. +ALTER TABLE support_cases + ALTER COLUMN faq_export_status SET DEFAULT 'pending'; + +CREATE INDEX IF NOT EXISTS idx_support_cases_faq_export_claim + ON support_cases (faq_export_status, faq_next_attempt_at, created_at, id) + WHERE faq_export_status IN ('pending', 'export_failed'); + +CREATE INDEX IF NOT EXISTS idx_support_cases_faq_export_stale + ON support_cases (faq_export_status, faq_last_attempt_at) + WHERE faq_export_status = 'exporting'; diff --git a/db/migrations/000011_faq_exports_contract_test.go b/db/migrations/000011_faq_exports_contract_test.go new file mode 100644 index 0000000..b7bcce0 --- /dev/null +++ b/db/migrations/000011_faq_exports_contract_test.go @@ -0,0 +1,74 @@ +package migrations_test + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +func read011Migration(t *testing.T, direction string) string { + t.Helper() + data, err := os.ReadFile(filepath.Join(".", "000011_faq_exports."+direction+".sql")) + if err != nil { + t.Fatalf("read 000011 %s migration: %v", direction, err) + } + return strings.ToUpper(string(data)) +} + +func TestUp011AddsDurableFAQExportStateToSupportCases(t *testing.T) { + up := read011Migration(t, "up") + for _, fragment := range []string{ + "ALTER TABLE SUPPORT_CASES", + "FAQ_EXPORT_STATUS", "FAQ_EXPORT_ATTEMPTS", "FAQ_LAST_ATTEMPT_AT", + "FAQ_NEXT_ATTEMPT_AT", "FAQ_EXPORTED_AT", "FAQ_FAILURE_CODE", "FAQ_RECORD_ID", + "PENDING", "EXPORTING", "EXPORTED", "EXPORT_FAILED", + } { + if !strings.Contains(up, fragment) { + t.Errorf("up migration missing %q", fragment) + } + } + for _, forbidden := range []string{"FAQ_QUESTION", "FAQ_ANSWER", "RAW_RESPONSE", "ACCESS_TOKEN"} { + if strings.Contains(up, forbidden) { + t.Errorf("migration must not duplicate business or secret field %q", forbidden) + } + } +} + +func TestUp011DoesNotBackfillHistoricalSupportCases(t *testing.T) { + up := read011Migration(t, "up") + if !strings.Contains(up, "DEFAULT 'NOT_APPLICABLE'") { + t.Fatal("existing support cases must start as not_applicable") + } + if !strings.Contains(up, "ALTER COLUMN FAQ_EXPORT_STATUS SET DEFAULT 'PENDING'") { + t.Fatal("future support cases must default to pending") + } +} + +func TestUp011AddsBoundedClaimIndexes(t *testing.T) { + up := read011Migration(t, "up") + for _, fragment := range []string{ + "IDX_SUPPORT_CASES_FAQ_EXPORT_CLAIM", + "FAQ_NEXT_ATTEMPT_AT", "FAQ_LAST_ATTEMPT_AT", + "WHERE FAQ_EXPORT_STATUS IN ('PENDING', 'EXPORT_FAILED')", + } { + if !strings.Contains(up, fragment) { + t.Errorf("up migration missing claim index fragment %q", fragment) + } + } +} + +func TestDown011OnlyRemovesFAQExportState(t *testing.T) { + down := read011Migration(t, "down") + for _, column := range []string{ + "FAQ_EXPORT_STATUS", "FAQ_EXPORT_ATTEMPTS", "FAQ_LAST_ATTEMPT_AT", + "FAQ_NEXT_ATTEMPT_AT", "FAQ_EXPORTED_AT", "FAQ_FAILURE_CODE", "FAQ_RECORD_ID", + } { + if !strings.Contains(down, "DROP COLUMN IF EXISTS "+column) { + t.Errorf("down migration missing %s", column) + } + } + if strings.Contains(down, "DROP TABLE") { + t.Fatal("down migration must not drop baseline tables") + } +} diff --git a/db/migrations/000012_system_settings.down.sql b/db/migrations/000012_system_settings.down.sql new file mode 100644 index 0000000..3dc3d3a --- /dev/null +++ b/db/migrations/000012_system_settings.down.sql @@ -0,0 +1 @@ +DROP TABLE IF EXISTS config_audit_events; DROP TABLE IF EXISTS system_resource_bindings; DROP TABLE IF EXISTS administrators; DROP TABLE IF EXISTS system_config_revisions; \ No newline at end of file diff --git a/db/migrations/000012_system_settings.up.sql b/db/migrations/000012_system_settings.up.sql new file mode 100644 index 0000000..386b053 --- /dev/null +++ b/db/migrations/000012_system_settings.up.sql @@ -0,0 +1,19 @@ +CREATE TABLE IF NOT EXISTS system_config_revisions ( + id TEXT PRIMARY KEY, tenant_key TEXT NOT NULL, kind TEXT NOT NULL, revision INTEGER NOT NULL CHECK(revision>0), + state TEXT NOT NULL CHECK(state IN ('draft','validated','active','retired','failed')), public_config JSONB NOT NULL DEFAULT '{}'::JSONB, + secret_ref TEXT NOT NULL DEFAULT '', validation_status TEXT NOT NULL DEFAULT 'pending', validation_code TEXT NOT NULL DEFAULT '', + validated_at TIMESTAMPTZ, activated_at TIMESTAMPTZ, created_by_staff_id TEXT NOT NULL DEFAULT '', created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + UNIQUE(tenant_key,kind,revision)); +CREATE UNIQUE INDEX IF NOT EXISTS uq_system_config_active ON system_config_revisions(tenant_key,kind) WHERE state='active'; +CREATE TABLE IF NOT EXISTS administrators ( + id TEXT PRIMARY KEY, tenant_key TEXT NOT NULL, staff_id TEXT NOT NULL, union_id TEXT NOT NULL DEFAULT '', display_name TEXT NOT NULL DEFAULT '', + department TEXT NOT NULL DEFAULT '', role TEXT NOT NULL CHECK(role IN ('super_admin','admin')), status TEXT NOT NULL DEFAULT 'active' CHECK(status IN ('active','disabled')), + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), UNIQUE(tenant_key,staff_id)); +CREATE TABLE IF NOT EXISTS system_resource_bindings ( + id TEXT PRIMARY KEY, tenant_key TEXT NOT NULL, kind TEXT NOT NULL, revision INTEGER NOT NULL CHECK(revision>0), state TEXT NOT NULL CHECK(state IN ('draft','validated','active','retired','failed')), + public_config JSONB NOT NULL DEFAULT '{}'::JSONB, validation_code TEXT NOT NULL DEFAULT '', validated_at TIMESTAMPTZ, activated_at TIMESTAMPTZ, + created_by_staff_id TEXT NOT NULL DEFAULT '', created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), UNIQUE(tenant_key,kind,revision)); +CREATE UNIQUE INDEX IF NOT EXISTS uq_resource_binding_active ON system_resource_bindings(tenant_key,kind) WHERE state='active'; +CREATE TABLE IF NOT EXISTS config_audit_events ( + id TEXT PRIMARY KEY, tenant_key TEXT NOT NULL, actor_staff_id TEXT NOT NULL DEFAULT '', action TEXT NOT NULL, target_kind TEXT NOT NULL, + target_revision INTEGER NOT NULL DEFAULT 0, result_code TEXT NOT NULL, metadata JSONB NOT NULL DEFAULT '{}'::JSONB, created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()); diff --git a/db/migrations/000012_system_settings_contract_test.go b/db/migrations/000012_system_settings_contract_test.go new file mode 100644 index 0000000..04c1f3d --- /dev/null +++ b/db/migrations/000012_system_settings_contract_test.go @@ -0,0 +1,25 @@ +package migrations_test + +import ( + "os" + "strings" + "testing" +) + +func TestUp012CreatesSettingsWithoutSecrets(t *testing.T) { + b, e := os.ReadFile("000012_system_settings.up.sql") + if e != nil { + t.Fatal(e) + } + s := strings.ToUpper(string(b)) + for _, x := range []string{"SYSTEM_CONFIG_REVISIONS", "ADMINISTRATORS", "SYSTEM_RESOURCE_BINDINGS", "CONFIG_AUDIT_EVENTS", "PUBLIC_CONFIG"} { + if !strings.Contains(s, x) { + t.Errorf("missing %s", x) + } + } + for _, x := range []string{"CLIENT_SECRET JSON", "ACCESS_TOKEN JSON", "API_KEY JSON"} { + if strings.Contains(s, x) { + t.Errorf("forbidden %s", x) + } + } +} diff --git a/db/migrations/000013_admin_bootstrap.down.sql b/db/migrations/000013_admin_bootstrap.down.sql new file mode 100644 index 0000000..61dfb21 --- /dev/null +++ b/db/migrations/000013_admin_bootstrap.down.sql @@ -0,0 +1 @@ +DROP TABLE IF EXISTS admin_bootstrap_challenges; \ No newline at end of file diff --git a/db/migrations/000013_admin_bootstrap.up.sql b/db/migrations/000013_admin_bootstrap.up.sql new file mode 100644 index 0000000..d6dd2ad --- /dev/null +++ b/db/migrations/000013_admin_bootstrap.up.sql @@ -0,0 +1,5 @@ +CREATE TABLE IF NOT EXISTS admin_bootstrap_challenges ( + id TEXT PRIMARY KEY, tenant_key TEXT NOT NULL, code_hash TEXT NOT NULL, expires_at TIMESTAMPTZ NOT NULL, attempts INTEGER NOT NULL DEFAULT 0 CHECK(attempts>=0), max_attempts INTEGER NOT NULL DEFAULT 5 CHECK(max_attempts BETWEEN 1 AND 10), + candidate_staff_id TEXT NOT NULL DEFAULT '', candidate_union_id TEXT NOT NULL DEFAULT '', candidate_display_name TEXT NOT NULL DEFAULT '', candidate_department TEXT NOT NULL DEFAULT '', + status TEXT NOT NULL CHECK(status IN ('pending','candidate_detected','confirmed','expired','locked')), created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()); +CREATE UNIQUE INDEX IF NOT EXISTS uq_admin_bootstrap_pending ON admin_bootstrap_challenges(tenant_key) WHERE status IN ('pending','candidate_detected'); \ No newline at end of file diff --git a/db/migrations/000013_admin_bootstrap_contract_test.go b/db/migrations/000013_admin_bootstrap_contract_test.go new file mode 100644 index 0000000..8b771c5 --- /dev/null +++ b/db/migrations/000013_admin_bootstrap_contract_test.go @@ -0,0 +1,18 @@ +package migrations_test + +import ( + "os" + "strings" + "testing" +) + +func TestUp013StoresOnlyBootstrapHash(t *testing.T) { + b, e := os.ReadFile("000013_admin_bootstrap.up.sql") + if e != nil { + t.Fatal(e) + } + s := strings.ToUpper(string(b)) + if !strings.Contains(s, "CODE_HASH") || strings.Contains(s, " CODE TEXT") { + t.Fatal("bootstrap must store hash only") + } +} diff --git a/db/migrations/000014_setting_sessions.down.sql b/db/migrations/000014_setting_sessions.down.sql new file mode 100644 index 0000000..12497c3 --- /dev/null +++ b/db/migrations/000014_setting_sessions.down.sql @@ -0,0 +1 @@ +DROP TABLE IF EXISTS setting_sessions; \ No newline at end of file diff --git a/db/migrations/000014_setting_sessions.up.sql b/db/migrations/000014_setting_sessions.up.sql new file mode 100644 index 0000000..39b9bbe --- /dev/null +++ b/db/migrations/000014_setting_sessions.up.sql @@ -0,0 +1,5 @@ +CREATE TABLE IF NOT EXISTS setting_sessions ( + tenant_key TEXT NOT NULL, staff_id TEXT NOT NULL, conversation_id TEXT NOT NULL, conversation_type TEXT NOT NULL CHECK(conversation_type IN ('direct','group')), + current_step TEXT NOT NULL, pending_action TEXT NOT NULL DEFAULT '', draft_config JSONB NOT NULL DEFAULT '{}'::JSONB, expires_at TIMESTAMPTZ NOT NULL, updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + PRIMARY KEY(tenant_key,staff_id)); +CREATE INDEX IF NOT EXISTS idx_setting_sessions_expiry ON setting_sessions(expires_at); \ No newline at end of file diff --git a/db/migrations/000014_setting_sessions_contract_test.go b/db/migrations/000014_setting_sessions_contract_test.go new file mode 100644 index 0000000..75aa317 --- /dev/null +++ b/db/migrations/000014_setting_sessions_contract_test.go @@ -0,0 +1,20 @@ +package migrations_test + +import ( + "os" + "strings" + "testing" +) + +func TestUp014CreatesExpiringSettingSessions(t *testing.T) { + b, e := os.ReadFile("000014_setting_sessions.up.sql") + if e != nil { + t.Fatal(e) + } + s := strings.ToUpper(string(b)) + for _, x := range []string{"SETTING_SESSIONS", "EXPIRES_AT", "DRAFT_CONFIG"} { + if !strings.Contains(s, x) { + t.Errorf("missing %s", x) + } + } +} diff --git a/db/migrations/000015_user_preferences.down.sql b/db/migrations/000015_user_preferences.down.sql new file mode 100644 index 0000000..688c162 --- /dev/null +++ b/db/migrations/000015_user_preferences.down.sql @@ -0,0 +1 @@ +DROP TABLE IF EXISTS user_preferences; \ No newline at end of file diff --git a/db/migrations/000015_user_preferences.up.sql b/db/migrations/000015_user_preferences.up.sql new file mode 100644 index 0000000..e18f85f --- /dev/null +++ b/db/migrations/000015_user_preferences.up.sql @@ -0,0 +1,3 @@ +CREATE TABLE IF NOT EXISTS user_preferences ( + tenant_key TEXT NOT NULL, channel TEXT NOT NULL, external_actor_id TEXT NOT NULL, language_mode TEXT NOT NULL DEFAULT 'auto' CHECK(language_mode IN ('auto','fixed')), + locale TEXT NOT NULL DEFAULT 'auto' CHECK(locale IN ('auto','zh-CN','en','ja','ko','es')), updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), PRIMARY KEY(tenant_key,channel,external_actor_id)); \ No newline at end of file diff --git a/db/migrations/000015_user_preferences_contract_test.go b/db/migrations/000015_user_preferences_contract_test.go new file mode 100644 index 0000000..4e92ba8 --- /dev/null +++ b/db/migrations/000015_user_preferences_contract_test.go @@ -0,0 +1,20 @@ +package migrations_test + +import ( + "os" + "strings" + "testing" +) + +func TestUp015ScopesPreferencesByTenantAndActor(t *testing.T) { + b, e := os.ReadFile("000015_user_preferences.up.sql") + if e != nil { + t.Fatal(e) + } + s := strings.ToUpper(string(b)) + for _, x := range []string{"USER_PREFERENCES", "TENANT_KEY", "EXTERNAL_ACTOR_ID", "LANGUAGE_MODE", "LOCALE"} { + if !strings.Contains(s, x) { + t.Errorf("missing %s", x) + } + } +} diff --git a/db/migrations/000016_question_image_urls.down.sql b/db/migrations/000016_question_image_urls.down.sql new file mode 100644 index 0000000..ed17fd4 --- /dev/null +++ b/db/migrations/000016_question_image_urls.down.sql @@ -0,0 +1,3 @@ +-- 000016_question_image_urls down migration. +ALTER TABLE turns + DROP COLUMN IF EXISTS question_image_urls_json; \ No newline at end of file diff --git a/db/migrations/000016_question_image_urls.up.sql b/db/migrations/000016_question_image_urls.up.sql new file mode 100644 index 0000000..e384225 --- /dev/null +++ b/db/migrations/000016_question_image_urls.up.sql @@ -0,0 +1,6 @@ +-- 000016_question_image_urls: stable published URLs for inbound question images. +-- Stores the object-storage HTTPS URLs of images a user sent in a question, +-- so the question-table export can render a readable, traceable record without +-- persisting download codes or data URIs. +ALTER TABLE turns + ADD COLUMN IF NOT EXISTS question_image_urls_json JSONB NOT NULL DEFAULT '[]'::JSONB; \ No newline at end of file diff --git a/db/migrations/000017_knowledge_searched.down.sql b/db/migrations/000017_knowledge_searched.down.sql new file mode 100644 index 0000000..bdfac51 --- /dev/null +++ b/db/migrations/000017_knowledge_searched.down.sql @@ -0,0 +1,3 @@ +-- 000017_knowledge_searched down migration. +ALTER TABLE turns + DROP COLUMN IF EXISTS knowledge_searched; \ No newline at end of file diff --git a/db/migrations/000017_knowledge_searched.up.sql b/db/migrations/000017_knowledge_searched.up.sql new file mode 100644 index 0000000..f2eec20 --- /dev/null +++ b/db/migrations/000017_knowledge_searched.up.sql @@ -0,0 +1,6 @@ +-- 000017_knowledge_searched: records whether a turn actually triggered a +-- knowledge-base search (knowledge_search tool call). Coverage classification +-- uses this to distinguish pure visual recognition from a searched-but-missed +-- knowledge question. +ALTER TABLE turns + ADD COLUMN IF NOT EXISTS knowledge_searched BOOLEAN NOT NULL DEFAULT FALSE; \ No newline at end of file diff --git a/db/migrations/000018_coverage_visual_recognition_reason.down.sql b/db/migrations/000018_coverage_visual_recognition_reason.down.sql new file mode 100644 index 0000000..aad52a3 --- /dev/null +++ b/db/migrations/000018_coverage_visual_recognition_reason.down.sql @@ -0,0 +1,11 @@ +-- 000018_coverage_visual_recognition_reason down migration. +ALTER TABLE coverage_decisions + DROP CONSTRAINT IF EXISTS coverage_decisions_reason_code_check; + +ALTER TABLE coverage_decisions + ADD CONSTRAINT coverage_decisions_reason_code_check + CHECK (reason_code IN ( + 'covered_has_references', + 'uncovered_no_references', + 'uncovered_explicit_no_answer' + )); \ No newline at end of file diff --git a/db/migrations/000018_coverage_visual_recognition_reason.up.sql b/db/migrations/000018_coverage_visual_recognition_reason.up.sql new file mode 100644 index 0000000..98f17fc --- /dev/null +++ b/db/migrations/000018_coverage_visual_recognition_reason.up.sql @@ -0,0 +1,14 @@ +-- 000018_coverage_visual_recognition_reason: extend the coverage_decisions +-- reason_code allowlist with the new image-visual-recognition reason emitted by +-- coverage Evaluator v3 (visual recognition is not a knowledge-coverage miss). +ALTER TABLE coverage_decisions + DROP CONSTRAINT IF EXISTS coverage_decisions_reason_code_check; + +ALTER TABLE coverage_decisions + ADD CONSTRAINT coverage_decisions_reason_code_check + CHECK (reason_code IN ( + 'covered_has_references', + 'uncovered_no_references', + 'uncovered_explicit_no_answer', + 'covered_visual_recognition' + )); \ No newline at end of file diff --git a/db/migrations/000019_reasoning_mode_state.down.sql b/db/migrations/000019_reasoning_mode_state.down.sql new file mode 100644 index 0000000..1539501 --- /dev/null +++ b/db/migrations/000019_reasoning_mode_state.down.sql @@ -0,0 +1,3 @@ +-- 000019_reasoning_mode_state down migration. +DROP TABLE IF EXISTS reasoning_mode_turns; +DROP TABLE IF EXISTS reasoning_mode_states; diff --git a/db/migrations/000019_reasoning_mode_state.up.sql b/db/migrations/000019_reasoning_mode_state.up.sql new file mode 100644 index 0000000..e92edd6 --- /dev/null +++ b/db/migrations/000019_reasoning_mode_state.up.sql @@ -0,0 +1,43 @@ +-- 000019_reasoning_mode_state: actor-scoped /think state and +-- per-turn idempotency for successful reasoning-mode completions. + +CREATE TABLE IF NOT EXISTS reasoning_mode_states ( + tenant_key TEXT NOT NULL, + channel TEXT NOT NULL, + external_actor_id TEXT NOT NULL, + mode TEXT NOT NULL DEFAULT 'quick' + CHECK (mode IN ('quick', 'reasoning')), + max_rounds INTEGER NOT NULL DEFAULT 10 + CHECK (max_rounds BETWEEN 1 AND 50), + rounds_used INTEGER NOT NULL DEFAULT 0 + CHECK (rounds_used >= 0 AND rounds_used <= max_rounds), + hint_enabled BOOLEAN NOT NULL DEFAULT TRUE, + last_activity_at TIMESTAMPTZ, + expires_at TIMESTAMPTZ, + onboarding_shown_at TIMESTAMPTZ, + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + PRIMARY KEY (tenant_key, channel, external_actor_id) +); + +CREATE INDEX IF NOT EXISTS idx_reasoning_mode_states_expiry + ON reasoning_mode_states (expires_at) + WHERE mode = 'reasoning' AND expires_at IS NOT NULL; + +CREATE TABLE IF NOT EXISTS reasoning_mode_turns ( + id TEXT PRIMARY KEY, + tenant_key TEXT NOT NULL, + channel TEXT NOT NULL, + turn_id TEXT NOT NULL REFERENCES turns(id), + external_actor_id TEXT NOT NULL, + execution_mode TEXT NOT NULL + CHECK (execution_mode IN ('quick', 'reasoning', 'reasoning_single')), + round_number INTEGER NOT NULL DEFAULT 0 CHECK (round_number >= 0), + showed_hint BOOLEAN NOT NULL DEFAULT FALSE, + auto_closed BOOLEAN NOT NULL DEFAULT FALSE, + showed_onboarding BOOLEAN NOT NULL DEFAULT FALSE, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + UNIQUE (tenant_key, channel, turn_id) +); + +CREATE INDEX IF NOT EXISTS idx_reasoning_mode_turns_actor_created + ON reasoning_mode_turns (tenant_key, channel, external_actor_id, created_at DESC); diff --git a/db/migrations/000019_reasoning_mode_state_contract_test.go b/db/migrations/000019_reasoning_mode_state_contract_test.go new file mode 100644 index 0000000..b132958 --- /dev/null +++ b/db/migrations/000019_reasoning_mode_state_contract_test.go @@ -0,0 +1,79 @@ +package migrations_test + +import ( + "os" + "strings" + "testing" +) + +func TestUp019CreatesActorScopedReasoningModeState(t *testing.T) { + data, err := os.ReadFile("000019_reasoning_mode_state.up.sql") + if err != nil { + t.Fatal(err) + } + source := strings.ToUpper(string(data)) + for _, required := range []string{ + "REASONING_MODE_STATES", + "TENANT_KEY", + "CHANNEL", + "EXTERNAL_ACTOR_ID", + "MODE", + "MAX_ROUNDS", + "ROUNDS_USED", + "HINT_ENABLED", + "EXPIRES_AT", + "ONBOARDING_SHOWN_AT", + "PRIMARY KEY (TENANT_KEY, CHANNEL, EXTERNAL_ACTOR_ID)", + "MODE IN ('QUICK', 'REASONING')", + "MAX_ROUNDS BETWEEN 1 AND 50", + } { + if !strings.Contains(source, required) { + t.Errorf("reasoning state migration missing %q", required) + } + } +} + +func TestUp019CreatesTurnIdempotencyLedger(t *testing.T) { + data, err := os.ReadFile("000019_reasoning_mode_state.up.sql") + if err != nil { + t.Fatal(err) + } + source := strings.ToUpper(string(data)) + for _, required := range []string{ + "REASONING_MODE_TURNS", + "TURN_ID", + "EXTERNAL_ACTOR_ID", + "EXECUTION_MODE", + "ROUND_NUMBER", + "SHOWED_HINT", + "AUTO_CLOSED", + "SHOWED_ONBOARDING", + "UNIQUE (TENANT_KEY, CHANNEL, TURN_ID)", + "REFERENCES TURNS(ID)", + } { + if !strings.Contains(source, required) { + t.Errorf("reasoning turn ledger migration missing %q", required) + } + } +} + +func TestDown019RemovesOnlyReasoningModeObjects(t *testing.T) { + data, err := os.ReadFile("000019_reasoning_mode_state.down.sql") + if err != nil { + t.Fatal(err) + } + source := strings.ToUpper(string(data)) + for _, required := range []string{ + "DROP TABLE IF EXISTS REASONING_MODE_TURNS", + "DROP TABLE IF EXISTS REASONING_MODE_STATES", + } { + if !strings.Contains(source, required) { + t.Errorf("reasoning down migration missing %q", required) + } + } + for _, forbidden := range []string{"DROP TABLE TURNS", "DROP TABLE USER_PREFERENCES"} { + if strings.Contains(source, forbidden) { + t.Errorf("reasoning down migration must not contain %q", forbidden) + } + } +} diff --git a/db/migrations/000020_feedback_support_trigger.down.sql b/db/migrations/000020_feedback_support_trigger.down.sql new file mode 100644 index 0000000..aeaa632 --- /dev/null +++ b/db/migrations/000020_feedback_support_trigger.down.sql @@ -0,0 +1,5 @@ +-- 000020_feedback_support_trigger down migration. +DROP INDEX IF EXISTS idx_support_cases_trigger_type_created; +ALTER TABLE support_cases + DROP COLUMN IF EXISTS trigger_feedback_id, + DROP COLUMN IF EXISTS trigger_type; diff --git a/db/migrations/000020_feedback_support_trigger.up.sql b/db/migrations/000020_feedback_support_trigger.up.sql new file mode 100644 index 0000000..aefd6d9 --- /dev/null +++ b/db/migrations/000020_feedback_support_trigger.up.sql @@ -0,0 +1,11 @@ +-- 000020_feedback_support_trigger: let an existing support-case workflow be +-- triggered by a downvote while preserving one case per successful Turn. + +ALTER TABLE support_cases + ALTER COLUMN coverage_decision_id DROP NOT NULL, + ADD COLUMN IF NOT EXISTS trigger_type TEXT NOT NULL DEFAULT 'coverage_uncovered' + CHECK (trigger_type IN ('coverage_uncovered', 'feedback_down')), + ADD COLUMN IF NOT EXISTS trigger_feedback_id TEXT REFERENCES answer_feedback(id); + +CREATE INDEX IF NOT EXISTS idx_support_cases_trigger_type_created + ON support_cases (trigger_type, created_at DESC); diff --git a/db/migrations/000020_feedback_support_trigger_contract_test.go b/db/migrations/000020_feedback_support_trigger_contract_test.go new file mode 100644 index 0000000..eef2843 --- /dev/null +++ b/db/migrations/000020_feedback_support_trigger_contract_test.go @@ -0,0 +1,50 @@ +package migrations_test + +import ( + "os" + "strings" + "testing" +) + +func TestUp020AddsFeedbackSupportTriggerAndMakesCoverageDecisionOptional(t *testing.T) { + data, err := os.ReadFile("000020_feedback_support_trigger.up.sql") + if err != nil { + t.Fatal(err) + } + source := strings.ToUpper(string(data)) + for _, required := range []string{ + "ALTER TABLE SUPPORT_CASES", + "TRIGGER_TYPE", + "COVERAGE_UNCOVERED", + "FEEDBACK_DOWN", + "TRIGGER_FEEDBACK_ID", + "REFERENCES ANSWER_FEEDBACK(ID)", + "ALTER COLUMN COVERAGE_DECISION_ID DROP NOT NULL", + } { + if !strings.Contains(source, required) { + t.Errorf("feedback support migration missing %q", required) + } + } + if strings.Contains(source, "DROP CONSTRAINT SUPPORT_CASES_COVERAGE_DECISION_ID_FKEY") { + t.Fatal("feedback support must retain the coverage decision foreign-key contract") + } +} + +func TestDown020RemovesOnlyFeedbackSupportColumns(t *testing.T) { + data, err := os.ReadFile("000020_feedback_support_trigger.down.sql") + if err != nil { + t.Fatal(err) + } + source := strings.ToUpper(string(data)) + for _, required := range []string{ + "DROP COLUMN IF EXISTS TRIGGER_FEEDBACK_ID", + "DROP COLUMN IF EXISTS TRIGGER_TYPE", + } { + if !strings.Contains(source, required) { + t.Errorf("feedback support down migration missing %q", required) + } + } + if strings.Contains(source, "DROP TABLE") { + t.Fatal("feedback support down migration must not drop shared tables") + } +} diff --git a/docs/architecture.md b/docs/architecture.md index 7415f28..73bc974 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -56,6 +56,7 @@ No WeKnora source patch is allowed as a workaround. - `internal/qa`: business orchestration and terminal-state ownership. - `internal/session`: external-to-WeKnora session policy. - `internal/store/postgres`: DobotAI business persistence only. +- `internal/coverage`: v1 covered/uncovered evaluation, durable support-case dispatch, finite retries, and stable failure codes. Notification failures never change a successful QA result. - `internal/channels/dingtalk`: DingTalk Stream ingress (official SDK), text-only robot callbacks, fail-closed session webhook replies (`https`, `*.dingtalk.com`, no redirects). Wired in `cmd/dobotai`; enabled only when `DINGTALK_CLIENT_ID`, `DINGTALK_CLIENT_SECRET`, and `DOBOTAI_TENANT_KEY` are all set. Group messages require an @-mention; direct chats map to one long-lived session per user, groups to one shared session per group. Images, OpenAPI fallback, and card replies are not implemented yet. - future `channels/*`: platform callbacks and outbound replies. - future `content-sync/*`: DingTalk KB, NAS, and CMS synchronization. diff --git a/go.mod b/go.mod index 0776142..ab115ac 100644 --- a/go.mod +++ b/go.mod @@ -3,6 +3,7 @@ module gitea.zheromiku.top/Weknora/dobotai-platform go 1.25.0 require ( + github.com/aliyun/alibabacloud-oss-go-sdk-v2 v1.5.1 github.com/jackc/pgx/v5 v5.9.2 github.com/open-dingtalk/dingtalk-stream-sdk-go v0.9.1 ) @@ -15,4 +16,5 @@ require ( github.com/jackc/puddle/v2 v2.2.2 // indirect golang.org/x/sync v0.20.0 // indirect golang.org/x/text v0.37.0 // indirect + golang.org/x/time v0.4.0 // indirect ) diff --git a/go.sum b/go.sum index 7cebbcf..063b105 100644 --- a/go.sum +++ b/go.sum @@ -1,3 +1,5 @@ +github.com/aliyun/alibabacloud-oss-go-sdk-v2 v1.5.1 h1:vtiFd0hhPAbyYJjztl0wYUq/PqEGkIlDmVuTIy6zw8Y= +github.com/aliyun/alibabacloud-oss-go-sdk-v2 v1.5.1/go.mod h1:FTzydeQVmR24FI0D6XWUOMKckjXehM/jgMn1xC+DA9M= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= @@ -26,6 +28,8 @@ golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4= golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +golang.org/x/time v0.4.0 h1:Z81tqI5ddIoXDPvVQ7/7CC9TnLM7ubaFG2qXYd5BbYY= +golang.org/x/time v0.4.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= diff --git a/internal/adminweb/control.go b/internal/adminweb/control.go new file mode 100644 index 0000000..cbacf4b --- /dev/null +++ b/internal/adminweb/control.go @@ -0,0 +1,205 @@ +package adminweb + +import ( + "context" + "errors" + "strings" + "time" + + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/dingtalkconfig" + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/secretstore" + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/settings" +) + +type ConfigRepository interface { + ActiveDingTalkConfig(context.Context, string) (string, string, bool, error) + CandidateDingTalkConfig(context.Context, string) (string, string, error) + SaveDingTalkConfig(context.Context, string, string, string, bool) error + MarkDingTalkCandidateFailed(context.Context, string, string, string) error + AdministratorCount(context.Context, string) (int, error) + ActiveBindings(context.Context, string) (map[string]settings.ResourceBinding, error) + CreateBootstrapChallenge(context.Context, string, string, time.Time) error + ConfirmBootstrap(context.Context, string) error +} +type AdministratorRepository interface { + ListAdministrators(context.Context, string) ([]settings.Administrator, error) + DisableAdministrator(context.Context, string, string) error +} +type CandidateActivator interface{ ActivateCandidate(context.Context) error } +type OperationalStatusProvider interface { + Components(context.Context) ([]Component, error) +} +type CredentialVerifier interface { + Verify(context.Context, string, string) dingtalkconfig.Result +} +type ControlService struct { + tenant string + repo ConfigRepository + secrets *secretstore.Store + verifier CredentialVerifier + activator CandidateActivator + status OperationalStatusProvider +} + +func NewControlService(tenant string, repo ConfigRepository, secrets *secretstore.Store, verifier CredentialVerifier) (*ControlService, error) { + if strings.TrimSpace(tenant) == "" || repo == nil || secrets == nil || verifier == nil { + return nil, errors.New("admin control dependencies are required") + } + return &ControlService{tenant: strings.TrimSpace(tenant), repo: repo, secrets: secrets, verifier: verifier}, nil +} +func (s *ControlService) Snapshot(ctx context.Context) (Snapshot, error) { + id, ref, verified, err := s.repo.ActiveDingTalkConfig(ctx, s.tenant) + if err != nil { + return Snapshot{}, err + } + admins, err := s.repo.AdministratorCount(ctx, s.tenant) + if err != nil { + return Snapshot{}, err + } + bindings, err := s.repo.ActiveBindings(ctx, s.tenant) + if err != nil { + return Snapshot{}, err + } + administratorViews := []AdministratorView{} + if administratorRepo, ok := s.repo.(AdministratorRepository); ok { + administrators, listErr := administratorRepo.ListAdministrators(ctx, s.tenant) + if listErr != nil { + return Snapshot{}, listErr + } + activeCount := 0 + for _, administrator := range administrators { + if administrator.Status == "active" { + activeCount++ + } + } + for _, administrator := range administrators { + administratorViews = append(administratorViews, AdministratorView{ + StaffID: administrator.StaffID, StaffIDMasked: maskID(administrator.StaffID), + DisplayName: administrator.DisplayName, Department: administrator.Department, + Role: administrator.Role, Status: administrator.Status, + CanDisable: administrator.Status == "active" && activeCount > 1, + }) + } + } + state := settings.DetermineState(settings.Snapshot{ClientID: id, SecretConfigured: s.secrets.Configured(ref), CredentialsVerified: verified, AdministratorCount: admins}) + now := time.Now() + components := []Component{ + {Name: "配置仓库", State: "ok", Code: "repository_ok", Detail: "PostgreSQL配置查询成功", LastSuccess: now, CheckedAt: now}, + {Name: "钉钉OAuth", State: status(verified), Code: ternaryCode(verified, "oauth_verified", "oauth_unconfigured"), Detail: "当前应用凭据验证状态", CheckedAt: now}, + {Name: "管理员", State: countStatus(admins), Code: ternaryCode(admins > 0, "admin_configured", "admin_missing"), Detail: itoa(admins) + " 位有效管理员", CheckedAt: now}, + {Name: "技术支持群绑定", State: bindingStatus(bindings, "support_group"), Code: bindingCode(bindings, "support_group"), Detail: "仅显示是否存在active绑定", CheckedAt: now}, + {Name: "问题AI表格绑定", State: bindingStatus(bindings, "question_table"), Code: bindingCode(bindings, "question_table"), Detail: "仅显示是否存在active绑定", CheckedAt: now}, + {Name: "FAQ表格绑定", State: bindingStatus(bindings, "faq_table"), Code: bindingCode(bindings, "faq_table"), Detail: "仅显示是否存在active绑定", CheckedAt: now}, + } + if s.status != nil { + operational, probeErr := s.status.Components(ctx) + if probeErr != nil { + components = append(components, Component{Name: "运行探针", State: "error", Code: "component_probe_failed", Detail: "运行状态探针失败;未显示原始错误", CheckedAt: time.Now()}) + } else { + components = append(components, operational...) + } + } + return Snapshot{SystemState: string(state), ClientIDMasked: maskID(id), SecretConfigured: s.secrets.Configured(ref), Components: components, Administrators: administratorViews}, nil +} +func (s *ControlService) VerifyCredentials(ctx context.Context, id, secret string) Verification { + r := s.verifier.Verify(ctx, id, secret) + return Verification{OK: r.OK, Code: r.Code, CheckedAt: r.CheckedAt} +} +func (s *ControlService) SaveCredentials(ctx context.Context, id, secret string) error { + _, oldRef, _ := s.repo.CandidateDingTalkConfig(ctx, s.tenant) + ref, err := s.secrets.Put("dingtalk", secret) + if err != nil { + return err + } + if err = s.repo.SaveDingTalkConfig(ctx, s.tenant, strings.TrimSpace(id), ref, false); err != nil { + _ = s.secrets.Delete(ref) + return err + } + if oldRef != "" && oldRef != ref { + _ = s.secrets.Delete(oldRef) + } + return nil +} +func (s *ControlService) SetCandidateActivator(activator CandidateActivator) { s.activator = activator } +func (s *ControlService) SetOperationalStatusProvider(provider OperationalStatusProvider) { + s.status = provider +} +func (s *ControlService) ActivateCandidate(ctx context.Context) error { + if s.activator == nil { + return errors.New("candidate activator unavailable") + } + _, ref, err := s.repo.CandidateDingTalkConfig(ctx, s.tenant) + if err != nil { + return err + } + if err = s.activator.ActivateCandidate(ctx); err != nil { + _ = s.repo.MarkDingTalkCandidateFailed(ctx, s.tenant, ref, "activation_failed") + return errors.New("candidate activation failed") + } + return nil +} +func (s *ControlService) CreateBootstrap(ctx context.Context, code string) error { + return s.repo.CreateBootstrapChallenge(ctx, s.tenant, code, time.Now().Add(10*time.Minute)) +} +func (s *ControlService) ConfirmBootstrap(ctx context.Context) error { + return s.repo.ConfirmBootstrap(ctx, s.tenant) +} +func (s *ControlService) DisableAdministrator(ctx context.Context, staffID string) error { + staffID = strings.TrimSpace(staffID) + if staffID == "" { + return settings.ErrAdministratorNotFound + } + repo, ok := s.repo.(AdministratorRepository) + if !ok { + return errors.New("administrator management unavailable") + } + return repo.DisableAdministrator(ctx, s.tenant, staffID) +} +func maskID(v string) string { + v = strings.TrimSpace(v) + if len(v) <= 6 { + return v + } + return v[:3] + "***" + v[len(v)-3:] +} +func status(ok bool) string { + if ok { + return "ok" + } + return "unconfigured" +} +func countStatus(n int) string { + if n > 0 { + return "ok" + } + return "unconfigured" +} +func bindingStatus(m map[string]settings.ResourceBinding, k string) string { + if _, ok := m[k]; ok { + return "configured" + } + return "unconfigured" +} +func bindingCode(m map[string]settings.ResourceBinding, k string) string { + if _, ok := m[k]; ok { + return "binding_active" + } + return "binding_missing" +} +func ternaryCode(ok bool, success, failure string) string { + if ok { + return success + } + return failure +} +func itoa(n int) string { + if n == 0 { + return "0" + } + b := make([]byte, 0, 8) + for n > 0 { + b = append([]byte{byte('0' + n%10)}, b...) + n /= 10 + } + return string(b) +} diff --git a/internal/adminweb/control_test.go b/internal/adminweb/control_test.go new file mode 100644 index 0000000..8746381 --- /dev/null +++ b/internal/adminweb/control_test.go @@ -0,0 +1,210 @@ +package adminweb + +import ( + "context" + "errors" + "testing" + "time" + + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/dingtalkconfig" + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/secretstore" + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/settings" +) + +type controlRepo struct { + savedVerified bool + savedRef string + candidateRef string + failedCode string + admins []settings.Administrator + disabledStaff string + disableErr error +} + +func (*controlRepo) ActiveDingTalkConfig(context.Context, string) (string, string, bool, error) { + return "old", "old-ref", true, nil +} +func (r *controlRepo) CandidateDingTalkConfig(context.Context, string) (string, string, error) { + return "new", r.candidateRef, nil +} +func (r *controlRepo) SaveDingTalkConfig(_ context.Context, _, _, ref string, verified bool) error { + r.savedRef = ref + r.savedVerified = verified + r.candidateRef = ref + return nil +} +func (r *controlRepo) MarkDingTalkCandidateFailed(_ context.Context, _, _, code string) error { + r.failedCode = code + return nil +} +func (r *controlRepo) AdministratorCount(context.Context, string) (int, error) { + if r.admins == nil { + return 1, nil + } + n := 0 + for _, admin := range r.admins { + if admin.Status == "active" { + n++ + } + } + return n, nil +} +func (r *controlRepo) ListAdministrators(context.Context, string) ([]settings.Administrator, error) { + return r.admins, nil +} +func (r *controlRepo) DisableAdministrator(_ context.Context, _, staffID string) error { + r.disabledStaff = staffID + return r.disableErr +} +func (*controlRepo) ActiveBindings(context.Context, string) (map[string]settings.ResourceBinding, error) { + return map[string]settings.ResourceBinding{}, nil +} +func (*controlRepo) CreateBootstrapChallenge(context.Context, string, string, time.Time) error { + return nil +} +func (*controlRepo) ConfirmBootstrap(context.Context, string) error { return nil } + +type verifyOK struct{} + +func (verifyOK) Verify(context.Context, string, string) dingtalkconfig.Result { + return dingtalkconfig.Result{OK: true, Code: "oauth_ok"} +} + +type activatorStub struct { + err error + calls int +} + +func (a *activatorStub) ActivateCandidate(context.Context) error { a.calls++; return a.err } + +type operationalStatusStub struct { + components []Component + err error +} + +func (s operationalStatusStub) Components(context.Context) ([]Component, error) { + return s.components, s.err +} + +func TestSnapshotIncludesOperationalComponents(t *testing.T) { + secrets, err := secretstore.New(t.TempDir()) + if err != nil { + t.Fatal(err) + } + service, err := NewControlService("tenant", &controlRepo{}, secrets, verifyOK{}) + if err != nil { + t.Fatal(err) + } + checked := time.Unix(100, 0) + service.SetOperationalStatusProvider(operationalStatusStub{components: []Component{{ + Name: "WeKnora", State: "ok", Code: "health_ok", CheckedAt: checked, + }}}) + snapshot, err := service.Snapshot(context.Background()) + if err != nil { + t.Fatal(err) + } + found := false + for _, component := range snapshot.Components { + if component.Name == "WeKnora" && component.Code == "health_ok" && component.CheckedAt.Equal(checked) { + found = true + } + } + if !found { + t.Fatalf("components=%+v", snapshot.Components) + } +} + +func TestSnapshotKeepsPageAvailableWhenOperationalProbeFails(t *testing.T) { + secrets, _ := secretstore.New(t.TempDir()) + service, err := NewControlService("tenant", &controlRepo{}, secrets, verifyOK{}) + if err != nil { + t.Fatal(err) + } + service.SetOperationalStatusProvider(operationalStatusStub{err: errors.New("probe failed")}) + snapshot, err := service.Snapshot(context.Background()) + if err != nil { + t.Fatal(err) + } + last := snapshot.Components[len(snapshot.Components)-1] + if last.Name != "运行探针" || last.State != "error" || last.Code != "component_probe_failed" { + t.Fatalf("component=%+v", last) + } +} + +func TestSaveCredentialsCreatesCandidateNotActive(t *testing.T) { + secrets, err := secretstore.New(t.TempDir()) + if err != nil { + t.Fatal(err) + } + repo := &controlRepo{} + service, err := NewControlService("tenant", repo, secrets, verifyOK{}) + if err != nil { + t.Fatal(err) + } + if err = service.SaveCredentials(context.Background(), "new", "secret"); err != nil { + t.Fatal(err) + } + if repo.savedVerified { + t.Fatal("candidate must not be active") + } + if repo.savedRef == "" || !secrets.Configured(repo.savedRef) { + t.Fatalf("ref=%q", repo.savedRef) + } +} +func TestActivateCandidateDelegatesAndMarksFailure(t *testing.T) { + secrets, err := secretstore.New(t.TempDir()) + if err != nil { + t.Fatal(err) + } + repo := &controlRepo{candidateRef: "candidate-ref"} + activator := &activatorStub{err: errors.New("candidate_start_failed_rolled_back")} + service, err := NewControlService("tenant", repo, secrets, verifyOK{}) + if err != nil { + t.Fatal(err) + } + service.SetCandidateActivator(activator) + if err = service.ActivateCandidate(context.Background()); err == nil { + t.Fatal("expected failure") + } + if activator.calls != 1 || repo.failedCode != "activation_failed" { + t.Fatalf("calls=%d code=%q", activator.calls, repo.failedCode) + } +} + +func TestSnapshotIncludesAdministratorsAndOnlyAllowsDisableWhenAnotherIsActive(t *testing.T) { + secrets, _ := secretstore.New(t.TempDir()) + repo := &controlRepo{admins: []settings.Administrator{ + {StaffID: "staff-old", DisplayName: "旧管理员", Department: "技术部", Role: "super_admin", Status: "active"}, + {StaffID: "staff-new", DisplayName: "新管理员", Department: "产品部", Role: "super_admin", Status: "active"}, + {StaffID: "staff-off", DisplayName: "停用管理员", Role: "admin", Status: "disabled"}, + }} + service, err := NewControlService("tenant", repo, secrets, verifyOK{}) + if err != nil { + t.Fatal(err) + } + snapshot, err := service.Snapshot(context.Background()) + if err != nil { + t.Fatal(err) + } + if len(snapshot.Administrators) != 3 || !snapshot.Administrators[0].CanDisable || !snapshot.Administrators[1].CanDisable || snapshot.Administrators[2].CanDisable { + t.Fatalf("administrators=%+v", snapshot.Administrators) + } + if snapshot.Administrators[0].StaffIDMasked == "staff-old" || snapshot.Administrators[0].StaffIDMasked == "" { + t.Fatalf("staff ID must be masked: %+v", snapshot.Administrators[0]) + } +} + +func TestControlServiceDelegatesAdministratorDisable(t *testing.T) { + secrets, _ := secretstore.New(t.TempDir()) + repo := &controlRepo{} + service, err := NewControlService("tenant", repo, secrets, verifyOK{}) + if err != nil { + t.Fatal(err) + } + if err = service.DisableAdministrator(context.Background(), "staff-old"); err != nil { + t.Fatal(err) + } + if repo.disabledStaff != "staff-old" { + t.Fatalf("disabled=%q", repo.disabledStaff) + } +} diff --git a/internal/adminweb/server.go b/internal/adminweb/server.go new file mode 100644 index 0000000..fc532bd --- /dev/null +++ b/internal/adminweb/server.go @@ -0,0 +1,253 @@ +package adminweb + +import ( + "context" + "crypto/rand" + "crypto/subtle" + "encoding/hex" + "errors" + "fmt" + "html/template" + "net/http" + "strings" + "time" + + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/settings" +) + +type Snapshot struct { + SystemState, ClientIDMasked string + SecretConfigured bool + Components []Component + Administrators []AdministratorView +} +type AdministratorView struct { + StaffID, StaffIDMasked, DisplayName, Department, Role, Status string + CanDisable bool +} +type Component struct { + Name, State, Code, Detail string + LastSuccess, CheckedAt time.Time +} +type Verification struct { + OK bool + Code string + CheckedAt time.Time +} +type Service interface { + Snapshot(context.Context) (Snapshot, error) + SaveCredentials(context.Context, string, string) error + VerifyCredentials(context.Context, string, string) Verification +} +type BootstrapService interface { + CreateBootstrap(context.Context, string) error + ConfirmBootstrap(context.Context) error +} +type CandidateService interface { + ActivateCandidate(context.Context) error +} +type AdministratorService interface { + DisableAdministrator(context.Context, string) error +} +type server struct { + service Service + token string + csrfToken string + mux *http.ServeMux + page *template.Template +} +type pageData struct { + Snapshot + CSRFToken string +} + +const settingsPage = ` + + + +DobotAI 设置 + + + +

DobotAI 配置中心

+
系统状态:{{.SystemState}}
Client ID:{{.ClientIDMasked}}
Client Secret:{{if .SecretConfigured}}已配置(不可查看){{else}}未配置{{end}}
+

配置/切换钉钉应用

新凭据先在线验证并保存为候选。激活后受控重启整组钉钉组件,失败自动回滚。

+

新增/更换管理员

必须先加后停:先确认新管理员已生效,再停用旧管理员。系统禁止停用最后一位有效管理员。

  1. 输入任意6位一次性绑定码并生成,有效期10分钟。
  2. 新管理员私聊机器人发送 /setting 6位码。
  3. 回到本页确认检测到的新管理员。
  4. 在下方确认新管理员状态为active,再停用旧管理员。

新管理员私聊验证后再点击:

管理员列表

{{range .Administrators}}{{else}}{{end}}
姓名部门Staff ID角色状态操作
{{if .DisplayName}}{{.DisplayName}}{{else}}—{{end}}{{if .Department}}{{.Department}}{{else}}—{{end}}{{.StaffIDMasked}}{{.Role}}{{.Status}}{{if .CanDisable}}
{{else}}—{{end}}
暂无管理员记录
+

组件检查

{{range .Components}}
{{.Name}}:{{.State}}
错误码:{{if .Code}}{{.Code}}{{else}}—{{end}}
最后成功:{{timeText .LastSuccess}}
最后检查:{{timeText .CheckedAt}}

{{.Detail}}

{{end}} +` + +func New(service Service, token string) http.Handler { + functions := template.FuncMap{"timeText": func(value time.Time) string { + if value.IsZero() { + return "—" + } + return value.UTC().Format("2006-01-02 15:04:05") + }} + csrfBytes := make([]byte, 32) + if _, err := rand.Read(csrfBytes); err != nil { + panic("admin CSRF token unavailable") + } + s := &server{service: service, token: strings.TrimSpace(token), csrfToken: hex.EncodeToString(csrfBytes), mux: http.NewServeMux(), page: template.Must(template.New("settings").Funcs(functions).Parse(settingsPage))} + s.mux.HandleFunc("GET /admin/settings", s.settings) + s.mux.HandleFunc("GET /admin/setup", s.settings) + s.mux.HandleFunc("POST /admin/setup/credentials", s.saveCredentials) + s.mux.HandleFunc("POST /admin/setup/candidate/activate", s.activateCandidate) + s.mux.HandleFunc("POST /admin/setup/bootstrap", s.createBootstrap) + s.mux.HandleFunc("POST /admin/setup/bootstrap/confirm", s.confirmBootstrap) + s.mux.HandleFunc("POST /admin/settings/administrators/disable", s.disableAdministrator) + return s +} +func (s *server) ServeHTTP(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Cache-Control", "no-store") + if !s.authorized(r) { + w.Header().Set("WWW-Authenticate", `Basic realm="DobotAI Admin"`) + http.Error(w, "unauthorized", http.StatusUnauthorized) + return + } + s.mux.ServeHTTP(w, r) +} +func (s *server) authorized(r *http.Request) bool { + if s.token == "" { + return false + } + if _, password, ok := r.BasicAuth(); ok && len(password) == len(s.token) && subtle.ConstantTimeCompare([]byte(password), []byte(s.token)) == 1 { + return true + } + v := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ") + return len(v) == len(s.token) && subtle.ConstantTimeCompare([]byte(v), []byte(s.token)) == 1 +} +func (s *server) requireCSRFForm(w http.ResponseWriter, r *http.Request, maxBytes int64) bool { + r.Body = http.MaxBytesReader(w, r.Body, maxBytes) + if err := r.ParseForm(); err != nil { + http.Error(w, "invalid form", http.StatusBadRequest) + return false + } + provided := strings.TrimSpace(r.FormValue("csrf_token")) + if len(provided) != len(s.csrfToken) || subtle.ConstantTimeCompare([]byte(provided), []byte(s.csrfToken)) != 1 { + http.Error(w, "forbidden", http.StatusForbidden) + return false + } + return true +} +func (s *server) settings(w http.ResponseWriter, r *http.Request) { + snap, err := s.service.Snapshot(r.Context()) + if err != nil { + http.Error(w, "settings unavailable", 500) + return + } + w.Header().Set("Content-Type", "text/html; charset=utf-8") + _ = s.page.Execute(w, pageData{Snapshot: snap, CSRFToken: s.csrfToken}) +} +func (s *server) saveCredentials(w http.ResponseWriter, r *http.Request) { + if !s.requireCSRFForm(w, r, 16<<10) { + return + } + id, secret := strings.TrimSpace(r.FormValue("client_id")), strings.TrimSpace(r.FormValue("client_secret")) + result := s.service.VerifyCredentials(r.Context(), id, secret) + if !result.OK { + http.Error(w, fmt.Sprintf("credential verification failed: %s", result.Code), 422) + return + } + if err := s.service.SaveCredentials(r.Context(), id, secret); err != nil { + http.Error(w, "credential save failed", 500) + return + } + http.Redirect(w, r, "/admin/settings", http.StatusSeeOther) +} +func (s *server) activateCandidate(w http.ResponseWriter, r *http.Request) { + if !s.requireCSRFForm(w, r, 4<<10) { + return + } + service, ok := s.service.(CandidateService) + if !ok { + http.Error(w, "candidate unavailable", http.StatusNotImplemented) + return + } + if err := service.ActivateCandidate(r.Context()); err != nil { + http.Error(w, "candidate activation failed", http.StatusConflict) + return + } + w.Header().Set("Content-Type", "text/plain; charset=utf-8") + _, _ = w.Write([]byte("候选已激活,DobotAI正在受控重启。\n")) +} +func (s *server) createBootstrap(w http.ResponseWriter, r *http.Request) { + if !s.requireCSRFForm(w, r, 4<<10) { + return + } + service, ok := s.service.(BootstrapService) + if !ok { + http.Error(w, "bootstrap unavailable", http.StatusNotImplemented) + return + } + code := strings.TrimSpace(r.FormValue("code")) + if !sixDigits(code) { + http.Error(w, "binding code must be 6 digits", 400) + return + } + if err := service.CreateBootstrap(r.Context(), code); err != nil { + http.Error(w, "create binding code failed", 500) + return + } + w.Header().Set("Content-Type", "text/plain; charset=utf-8") + fmt.Fprintf(w, "请在10分钟内私聊机器人发送:/setting %s\n", code) +} +func (s *server) confirmBootstrap(w http.ResponseWriter, r *http.Request) { + if !s.requireCSRFForm(w, r, 4<<10) { + return + } + service, ok := s.service.(BootstrapService) + if !ok { + http.Error(w, "bootstrap unavailable", http.StatusNotImplemented) + return + } + if err := service.ConfirmBootstrap(r.Context()); err != nil { + http.Error(w, "尚未检测到可确认的管理员", http.StatusConflict) + return + } + http.Redirect(w, r, "/admin/settings", http.StatusSeeOther) +} +func (s *server) disableAdministrator(w http.ResponseWriter, r *http.Request) { + if !s.requireCSRFForm(w, r, 4<<10) { + return + } + service, ok := s.service.(AdministratorService) + if !ok { + http.Error(w, "administrator management unavailable", http.StatusNotImplemented) + return + } + staffID := strings.TrimSpace(r.FormValue("staff_id")) + if staffID == "" { + http.Error(w, "administrator not found", http.StatusNotFound) + return + } + err := service.DisableAdministrator(r.Context(), staffID) + switch { + case err == nil: + http.Redirect(w, r, "/admin/settings", http.StatusSeeOther) + case errors.Is(err, settings.ErrLastAdministrator): + http.Error(w, "至少保留一位有效管理员;请先确认新管理员已生效。", http.StatusConflict) + case errors.Is(err, settings.ErrAdministratorAlreadyDisabled): + http.Error(w, "管理员已经停用。", http.StatusConflict) + case errors.Is(err, settings.ErrAdministratorNotFound): + http.Error(w, "administrator not found", http.StatusNotFound) + default: + http.Error(w, "administrator update failed", http.StatusInternalServerError) + } +} +func sixDigits(value string) bool { + if len(value) != 6 { + return false + } + for _, ch := range value { + if ch < '0' || ch > '9' { + return false + } + } + return true +} diff --git a/internal/adminweb/server_test.go b/internal/adminweb/server_test.go new file mode 100644 index 0000000..b060f9b --- /dev/null +++ b/internal/adminweb/server_test.go @@ -0,0 +1,166 @@ +package adminweb + +import ( + "context" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/settings" +) + +type fakeService struct { + snapshot Snapshot + verified bool + saved bool + disabled string + disableErr error +} + +func (f *fakeService) Snapshot(context.Context) (Snapshot, error) { return f.snapshot, nil } +func (f *fakeService) SaveCredentials(context.Context, string, string) error { + f.saved = true + return nil +} +func (f *fakeService) VerifyCredentials(context.Context, string, string) Verification { + f.verified = true + return Verification{OK: true, Code: "ok", CheckedAt: time.Unix(1, 0)} +} +func (f *fakeService) DisableAdministrator(_ context.Context, staffID string) error { + f.disabled = staffID + return f.disableErr +} +func csrfTokenFromPage(t *testing.T, h http.Handler) string { + t.Helper() + get := httptest.NewRequest(http.MethodGet, "/admin/settings", nil) + get.Header.Set("Authorization", "Bearer admin-token") + page := httptest.NewRecorder() + h.ServeHTTP(page, get) + marker := `name="csrf_token" value="` + start := strings.Index(page.Body.String(), marker) + if start < 0 { + t.Fatalf("csrf token missing: %s", page.Body.String()) + } + start += len(marker) + end := strings.Index(page.Body.String()[start:], `"`) + if end < 0 { + t.Fatal("csrf token terminator missing") + } + return page.Body.String()[start : start+end] +} +func TestDashboardNeverRendersSecrets(t *testing.T) { + svc := &fakeService{snapshot: Snapshot{SystemState: "active", ClientIDMasked: "ding***", SecretConfigured: true}} + h := New(svc, "admin-token") + req := httptest.NewRequest(http.MethodGet, "/admin/settings", nil) + req.Header.Set("Authorization", "Bearer admin-token") + w := httptest.NewRecorder() + h.ServeHTTP(w, req) + if w.Code != 200 { + t.Fatalf("status=%d", w.Code) + } + body := w.Body.String() + if strings.Contains(body, "admin-token") || strings.Contains(strings.ToLower(body), "client secret value") { + t.Fatal("secret leaked") + } + if !strings.Contains(body, "ding***") { + t.Fatal("masked client id missing") + } +} +func TestDashboardRendersOperationalComponentFields(t *testing.T) { + checked := time.Date(2026, 8, 13, 18, 0, 0, 0, time.UTC) + svc := &fakeService{snapshot: Snapshot{Components: []Component{{ + Name: "WeKnora", State: "ok", Code: "health_ok", Detail: "HTTP健康探针正常", + LastSuccess: checked.Add(-time.Minute), CheckedAt: checked, + }}}} + h := New(svc, "admin-token") + req := httptest.NewRequest(http.MethodGet, "/admin/settings", nil) + req.Header.Set("Authorization", "Bearer admin-token") + w := httptest.NewRecorder() + h.ServeHTTP(w, req) + body := w.Body.String() + for _, want := range []string{"WeKnora", "health_ok", "HTTP健康探针正常", "2026-08-13 17:59:00", "2026-08-13 18:00:00"} { + if !strings.Contains(body, want) { + t.Fatalf("dashboard missing %q: %s", want, body) + } + } +} + +func TestSaveCredentialsRequiresVerification(t *testing.T) { + svc := &fakeService{} + h := New(svc, "admin-token") + csrf := csrfTokenFromPage(t, h) + req := httptest.NewRequest(http.MethodPost, "/admin/setup/credentials", strings.NewReader("client_id=id&client_secret=secret&csrf_token="+csrf)) + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + req.Header.Set("Authorization", "Bearer admin-token") + w := httptest.NewRecorder() + h.ServeHTTP(w, req) + if w.Code != http.StatusSeeOther || !svc.verified || !svc.saved { + t.Fatalf("status=%d verified=%v saved=%v", w.Code, svc.verified, svc.saved) + } +} + +func TestAllAdminPOSTRoutesRejectMissingCSRF(t *testing.T) { + svc := &fakeService{} + h := New(svc, "admin-token") + for _, route := range []string{"/admin/setup/credentials", "/admin/setup/candidate/activate", "/admin/setup/bootstrap", "/admin/setup/bootstrap/confirm", "/admin/settings/administrators/disable"} { + req := httptest.NewRequest(http.MethodPost, route, strings.NewReader("client_id=id&client_secret=secret&code=123456&staff_id=staff-old")) + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + req.Header.Set("Authorization", "Bearer admin-token") + w := httptest.NewRecorder() + h.ServeHTTP(w, req) + if w.Code != http.StatusForbidden { + t.Fatalf("route=%s status=%d body=%q", route, w.Code, w.Body.String()) + } + } + if svc.saved || svc.disabled != "" { + t.Fatalf("business service called saved=%v disabled=%q", svc.saved, svc.disabled) + } +} + +func TestDashboardRendersAdministratorReplacementWorkflow(t *testing.T) { + svc := &fakeService{snapshot: Snapshot{Administrators: []AdministratorView{{StaffID: "staff-old", StaffIDMasked: "sta***old", DisplayName: "旧管理员", Department: "技术部", Role: "super_admin", Status: "active", CanDisable: true}}}} + h := New(svc, "admin-token") + req := httptest.NewRequest(http.MethodGet, "/admin/settings", nil) + req.Header.Set("Authorization", "Bearer admin-token") + w := httptest.NewRecorder() + h.ServeHTTP(w, req) + for _, want := range []string{"新增/更换管理员", "先加后停", "旧管理员", "技术部", "sta***old", "生成6位绑定码", "停用此管理员"} { + if !strings.Contains(w.Body.String(), want) { + t.Fatalf("dashboard missing %q: %s", want, w.Body.String()) + } + } + if strings.Contains(w.Body.String(), ">staff-old<") { + t.Fatalf("raw staff ID must not be rendered as visible text: %s", w.Body.String()) + } +} + +func TestDisableAdministratorRequiresCSRFAndMapsLastAdminConflict(t *testing.T) { + svc := &fakeService{} + h := New(svc, "admin-token") + post := func(body string) *httptest.ResponseRecorder { + req := httptest.NewRequest(http.MethodPost, "/admin/settings/administrators/disable", strings.NewReader(body)) + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + req.Header.Set("Authorization", "Bearer admin-token") + w := httptest.NewRecorder() + h.ServeHTTP(w, req) + return w + } + if w := post("staff_id=staff-old"); w.Code != http.StatusForbidden || svc.disabled != "" { + t.Fatalf("missing csrf status=%d disabled=%q", w.Code, svc.disabled) + } + + csrf := csrfTokenFromPage(t, h) + + svc.disableErr = settings.ErrLastAdministrator + w := post("staff_id=staff-old&csrf_token=" + csrf) + if w.Code != http.StatusConflict || !strings.Contains(w.Body.String(), "至少保留一位有效管理员") { + t.Fatalf("last-admin status=%d body=%q", w.Code, w.Body.String()) + } + svc.disableErr = nil + w = post("staff_id=staff-old&csrf_token=" + csrf) + if w.Code != http.StatusSeeOther || svc.disabled != "staff-old" { + t.Fatalf("success status=%d disabled=%q body=%q", w.Code, svc.disabled, w.Body.String()) + } +} diff --git a/internal/channels/dingtalk/card.go b/internal/channels/dingtalk/card.go index d0b6ffa..305e8c2 100644 --- a/internal/channels/dingtalk/card.go +++ b/internal/channels/dingtalk/card.go @@ -8,6 +8,7 @@ import ( "errors" "fmt" "io" + "log" "net/http" "strings" "sync" @@ -206,6 +207,7 @@ func (s *CardSender) UpdateCard(ctx context.Context, outTrackID, content string, if len(content) > 64*1024 { return errors.New("dingtalk card: content exceeds 64 KiB") } + log.Print(formatCardUpdateDiagnostic(content, isFinalize, isError)) token, err := s.accessToken(ctx) if err != nil { @@ -305,9 +307,25 @@ func (s *CardSender) postCard(ctx context.Context, body map[string]any, token st if err != nil { return err } - // Discard successful response body - if len(payload) > 0 { - // Body is already bounded by postJSON→readBoundedAPIResponse; just discard + return validateDingTalkBusinessResponse(payload) +} + +func validateDingTalkBusinessResponse(payload []byte) error { + if len(bytes.TrimSpace(payload)) == 0 { + return nil + } + var response struct { + Success *bool `json:"success"` + ErrCode any `json:"errcode"` + } + if json.Unmarshal(payload, &response) != nil { + return nil + } + if response.Success != nil && !*response.Success { + return errors.New("dingtalk card: API business failure") + } + if response.ErrCode != nil && fmt.Sprint(response.ErrCode) != "0" { + return errors.New("dingtalk card: API business failure") } return nil } @@ -326,8 +344,11 @@ func (s *CardSender) finalizeCard(ctx context.Context, outTrackID, content, toke "isFinalize": isFinalize, "isError": isError, } - _, err = s.doJSON(ctx, http.MethodPut, s.streamURL, body, token) - return err + payload, err := s.doJSON(ctx, http.MethodPut, s.streamURL, body, token) + if err != nil { + return err + } + return validateDingTalkBusinessResponse(payload) } func (s *CardSender) postJSON(ctx context.Context, endpoint string, value any, token string) ([]byte, error) { diff --git a/internal/channels/dingtalk/card_diagnostics.go b/internal/channels/dingtalk/card_diagnostics.go new file mode 100644 index 0000000..717e50e --- /dev/null +++ b/internal/channels/dingtalk/card_diagnostics.go @@ -0,0 +1,64 @@ +package dingtalk + +import ( + "fmt" + "strings" +) + +type cardContentShape struct { + bytes int + lines int + pipeLines int + leadingPipeLines int + delimiterLines int + confirmedTable bool + confirmedTablePos int +} + +func inspectCardContent(content string) cardContentShape { + shape := cardContentShape{ + bytes: len(content), + confirmedTablePos: -1, + } + if content == "" { + return shape + } + shape.lines = strings.Count(content, "\n") + 1 + + lines := splitMarkdownStreamLines(content) + for i, line := range lines { + if strings.Contains(line.text, "|") { + shape.pipeLines++ + } + if isTableHeaderCandidate(line.text) { + shape.leadingPipeLines++ + } + if !line.inFence && isCompleteTableDelimiter(line.text) { + shape.delimiterLines++ + } + if shape.confirmedTable || i == 0 || line.inFence || lines[i-1].inFence { + continue + } + if isTableHeaderCandidate(lines[i-1].text) && isCompleteTableDelimiter(line.text) { + shape.confirmedTable = true + shape.confirmedTablePos = lines[i-1].start + } + } + return shape +} + +func formatCardUpdateDiagnostic(content string, isFinalize, isError bool) string { + shape := inspectCardContent(content) + return fmt.Sprintf( + "DingTalk card update shape: finalize=%t error=%t bytes=%d lines=%d pipe_lines=%d leading_pipe_lines=%d delimiter_lines=%d confirmed_table=%t table_start=%d", + isFinalize, + isError, + shape.bytes, + shape.lines, + shape.pipeLines, + shape.leadingPipeLines, + shape.delimiterLines, + shape.confirmedTable, + shape.confirmedTablePos, + ) +} diff --git a/internal/channels/dingtalk/card_diagnostics_test.go b/internal/channels/dingtalk/card_diagnostics_test.go new file mode 100644 index 0000000..3477cf7 --- /dev/null +++ b/internal/channels/dingtalk/card_diagnostics_test.go @@ -0,0 +1,93 @@ +package dingtalk + +import ( + "bytes" + "context" + "fmt" + "log" + "strings" + "testing" +) + +func TestCardSenderUpdateCardLogsOnlySafeContentShape(t *testing.T) { + ts := newCardTestServer() + defer ts.Close() + sender, err := newCardSenderForTest("client-id", "client-secret", "template-id", ts.Client(), ts.URL()+"/token", ts.URL()+"/create") + if err != nil { + t.Fatal(err) + } + + var output bytes.Buffer + previousWriter := log.Writer() + previousFlags := log.Flags() + previousPrefix := log.Prefix() + log.SetOutput(&output) + log.SetFlags(0) + log.SetPrefix("") + t.Cleanup(func() { + log.SetOutput(previousWriter) + log.SetFlags(previousFlags) + log.SetPrefix(previousPrefix) + }) + + content := "DO_NOT_LOG_BOUNDARY_TEXT\n\n| 型号 | 负载 |\n| --- | --- |\n| CR5 | 5kg |" + if err := sender.UpdateCard(context.Background(), "track-diagnostic", content, false, false); err != nil { + t.Fatal(err) + } + + got := output.String() + if !strings.Contains(got, "DingTalk card update shape:") || !strings.Contains(got, "confirmed_table=true") || !strings.Contains(got, "finalize=false") { + t.Fatalf("missing safe boundary diagnostic: %q", got) + } + if strings.Contains(got, "DO_NOT_LOG_BOUNDARY_TEXT") || strings.Contains(got, "CR5") || strings.Contains(got, "track-diagnostic") { + t.Fatalf("boundary diagnostic leaked content or card identifier: %q", got) + } +} + +func TestFormatCardUpdateDiagnosticReportsStructureWithoutContent(t *testing.T) { + content := "DO_NOT_LOG_ANSWER_TEXT\n\n| 型号 | 负载 |\n| --- | --- |\n| CR5 | 5kg |" + + got := formatCardUpdateDiagnostic(content, false, false) + wantFields := []string{ + "DingTalk card update shape:", + "finalize=false", + "error=false", + fmt.Sprintf("bytes=%d", len(content)), + "lines=5", + "pipe_lines=3", + "leading_pipe_lines=3", + "delimiter_lines=1", + "confirmed_table=true", + fmt.Sprintf("table_start=%d", strings.Index(content, "| 型号")), + } + for _, field := range wantFields { + if !strings.Contains(got, field) { + t.Fatalf("diagnostic %q missing field %q", got, field) + } + } + if strings.Contains(got, "DO_NOT_LOG_ANSWER_TEXT") || strings.Contains(got, "CR5") { + t.Fatalf("diagnostic leaked answer content: %q", got) + } +} + +func TestFormatCardUpdateDiagnosticDistinguishesFinalPlainText(t *testing.T) { + got := formatCardUpdateDiagnostic("普通回答", true, false) + wantFields := []string{ + "finalize=true", + "error=false", + "lines=1", + "pipe_lines=0", + "leading_pipe_lines=0", + "delimiter_lines=0", + "confirmed_table=false", + "table_start=-1", + } + for _, field := range wantFields { + if !strings.Contains(got, field) { + t.Fatalf("diagnostic %q missing field %q", got, field) + } + } + if strings.Contains(got, "普通回答") { + t.Fatalf("diagnostic leaked answer content: %q", got) + } +} diff --git a/internal/channels/dingtalk/card_pump.go b/internal/channels/dingtalk/card_pump.go index dcdd22a..6b86f7a 100644 --- a/internal/channels/dingtalk/card_pump.go +++ b/internal/channels/dingtalk/card_pump.go @@ -39,6 +39,7 @@ func (p *cardUpdatePump) run(ctx context.Context, ticks <-chan time.Time, stopTi if stopTicks != nil { defer stopTicks() } + lastSuccessful := "" for { select { case <-ctx.Done(): @@ -52,9 +53,14 @@ func (p *cardUpdatePump) run(ctx context.Context, ticks <-chan time.Time, stopTi default: continue } + if latest == lastSuccessful { + continue + } if err := update(ctx, latest); err != nil { log.Printf("DingTalk async card update failed, continuing") + continue } + lastSuccessful = latest } } } diff --git a/internal/channels/dingtalk/card_test.go b/internal/channels/dingtalk/card_test.go index 18bcd91..c28d75d 100644 --- a/internal/channels/dingtalk/card_test.go +++ b/internal/channels/dingtalk/card_test.go @@ -35,6 +35,7 @@ type cardTestServer struct { createBodySize int64 // Content-Length for oversized response streamStatus int streamBodySize int64 + streamResponse any } func newCardTestServer() *cardTestServer { @@ -42,6 +43,7 @@ func newCardTestServer() *cardTestServer { tokenStatus: http.StatusOK, createStatus: http.StatusOK, streamStatus: http.StatusOK, + streamResponse: map[string]any{"result": "ok"}, tokenResponse: map[string]any{"accessToken": "test-access-token", "expireIn": 3600}, createResponse: map[string]any{"result": "ok"}, } @@ -91,7 +93,7 @@ func newCardTestServer() *cardTestServer { return } w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode(map[string]any{"result": "ok"}) + json.NewEncoder(w).Encode(ts.streamResponse) default: http.NotFound(w, r) } @@ -969,6 +971,19 @@ func TestSendFinalCardCreateStreamOnce(t *testing.T) { // Test: UpdateCard with non-final / error flags // --------------------------------------------------------------------------- +func TestUpdateCardRejectsHTTP200BusinessFailure(t *testing.T) { + ts := newCardTestServer() + defer ts.Close() + ts.streamResponse = map[string]any{"success": false, "code": "InvalidParameter", "message": "sensitive detail"} + sender, err := newCardSenderForTest("client-id", "client-secret", "card-template-123", ts.Client(), ts.URL()+"/token", ts.URL()+"/create") + if err != nil { + t.Fatal(err) + } + if err := sender.UpdateCard(context.Background(), "track-1", "answer", true, false); err == nil { + t.Fatal("HTTP 200 business failure must be rejected") + } +} + func TestUpdateCardNonFinalAndError(t *testing.T) { ts := newCardTestServer() defer ts.Close() diff --git a/internal/channels/dingtalk/display_sanitizer.go b/internal/channels/dingtalk/display_sanitizer.go new file mode 100644 index 0000000..21161e1 --- /dev/null +++ b/internal/channels/dingtalk/display_sanitizer.go @@ -0,0 +1,31 @@ +package dingtalk + +import ( + "regexp" + "strings" +) + +const displayReferenceMarkerPattern = `\[\[ref[\t ]+id[\t ]*=[\t ]*["']c[0-9]+["'][\t ]*\]\]` + +var ( + displayReferenceMarkerRE = regexp.MustCompile(displayReferenceMarkerPattern) + leadingReferenceGroupColonRE = regexp.MustCompile(`(?m)^[ ]*(?:` + displayReferenceMarkerPattern + `[ ]*)+[::][ ]*`) + spacedReferenceGroupRE = regexp.MustCompile(`[ ]+(?:` + displayReferenceMarkerPattern + `[ ]*)+`) + spaceBeforeDisplayPunctuation = regexp.MustCompile(`[ ]+([,。;:!?、,.;:!?])`) + spaceAfterDisplayColon = regexp.MustCompile(`([::])[\t ]+`) +) + +func sanitizeDisplayAnswer(content string) string { + if index := strings.LastIndex(content, "[[ref"); index >= 0 && !strings.Contains(content[index:], "]]") { + content = content[:index] + } + if !displayReferenceMarkerRE.MatchString(content) { + return content + } + content = leadingReferenceGroupColonRE.ReplaceAllString(content, "") + content = spacedReferenceGroupRE.ReplaceAllString(content, " ") + content = displayReferenceMarkerRE.ReplaceAllString(content, "") + content = spaceBeforeDisplayPunctuation.ReplaceAllString(content, "$1") + content = spaceAfterDisplayColon.ReplaceAllString(content, "$1") + return content +} diff --git a/internal/channels/dingtalk/display_sanitizer_test.go b/internal/channels/dingtalk/display_sanitizer_test.go new file mode 100644 index 0000000..b8acd90 --- /dev/null +++ b/internal/channels/dingtalk/display_sanitizer_test.go @@ -0,0 +1,66 @@ +package dingtalk + +import "testing" + +func TestSanitizeDisplayAnswerRemovesInternalReferenceMarkers(t *testing.T) { + tests := []struct { + name string + input string + want string + }{ + { + name: "adjacent inline markers", + input: "结论支持该功能[[ref id=\"c2\"]][[ref id=\"c4\"]]。", + want: "结论支持该功能。", + }, + { + name: "leading marker group and chinese colon", + input: "[[ref id=\"c2\"]][[ref id=\"c4\"]]:建议先检查配置。", + want: "建议先检查配置。", + }, + { + name: "leading marker group and ascii colon on second line", + input: "第一段。\n[[ref id='c12']] : Second paragraph.", + want: "第一段。\nSecond paragraph.", + }, + { + name: "normal punctuation remains natural", + input: "标题:[[ref id=\"c1\"]] 详细说明", + want: "标题:详细说明", + }, + { + name: "spaces around marker collapse to one", + input: "Feature A [[ref id=\"c3\"]] remains supported.", + want: "Feature A remains supported.", + }, + { + name: "unrelated double bracket syntax is preserved", + input: "请保留 [[wiki|页面名称]] 和 [普通链接](https://example.com)。", + want: "请保留 [[wiki|页面名称]] 和 [普通链接](https://example.com)。", + }, + { + name: "content without references remains byte for byte unchanged", + input: "Protocol: value ; keep spacing\n indented", + want: "Protocol: value ; keep spacing\n indented", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := sanitizeDisplayAnswer(tt.input); got != tt.want { + t.Fatalf("sanitizeDisplayAnswer()=%q, want %q", got, tt.want) + } + }) + } +} + +func TestSanitizeDisplayAnswerHoldsBackDanglingStreamingReference(t *testing.T) { + for _, input := range []string{ + "答案正文[[ref", + "答案正文[[ref id=\"c", + "答案正文[[ref id=\"c2\"", + } { + if got := sanitizeDisplayAnswer(input); got != "答案正文" { + t.Fatalf("sanitizeDisplayAnswer(%q)=%q", input, got) + } + } +} diff --git a/internal/channels/dingtalk/download_codes_test.go b/internal/channels/dingtalk/download_codes_test.go new file mode 100644 index 0000000..fbe47ca --- /dev/null +++ b/internal/channels/dingtalk/download_codes_test.go @@ -0,0 +1,33 @@ +package dingtalk + +import ( + "testing" +) + +func TestEffectiveDownloadCodesDeduplicatesAndPreservesOrder(t *testing.T) { + cb := BotCallback{ + DownloadCode: "code-first", + DownloadCodes: []string{"code-first", "code-second", " code-third "}, + } + codes := effectiveDownloadCodes(cb) + if len(codes) != 3 { + t.Fatalf("codes=%v, want 3", codes) + } + if codes[0] != "code-first" || codes[1] != "code-second" || codes[2] != "code-third" { + t.Fatalf("codes=%v, want ordered de-dup", codes) + } +} + +func TestEffectiveDownloadCodesSingleOnly(t *testing.T) { + cb := BotCallback{DownloadCode: " solo "} + codes := effectiveDownloadCodes(cb) + if len(codes) != 1 || codes[0] != "solo" { + t.Fatalf("codes=%v, want [solo]", codes) + } +} + +func TestEffectiveDownloadCodesEmpty(t *testing.T) { + if codes := effectiveDownloadCodes(BotCallback{}); len(codes) != 0 { + t.Fatalf("codes=%v, want empty", codes) + } +} \ No newline at end of file diff --git a/internal/channels/dingtalk/feedback.go b/internal/channels/dingtalk/feedback.go index b32a5fe..65caebd 100644 --- a/internal/channels/dingtalk/feedback.go +++ b/internal/channels/dingtalk/feedback.go @@ -79,10 +79,6 @@ func (h *CardFeedbackHandler) HandleSDK(ctx context.Context, request *sdkcard.Ca if value == feedbackdomain.ValueUp { message = "感谢反馈" } - if value == feedbackdomain.ValueDown && reason == feedbackdomain.ReasonEmpty { - showReasons = "true" - message = "请选择未解决原因" - } return &sdkcard.CardResponse{ CardUpdateOptions: &sdkcard.CardUpdateOptions{UpdatePrivateDataByKey: true}, UserPrivateData: &sdkcard.CardDataDto{CardParamMap: map[string]string{ diff --git a/internal/channels/dingtalk/feedback_test.go b/internal/channels/dingtalk/feedback_test.go index c9f309f..1a3e0e5 100644 --- a/internal/channels/dingtalk/feedback_test.go +++ b/internal/channels/dingtalk/feedback_test.go @@ -84,7 +84,9 @@ func TestCardFeedbackMapsNativeDislike(t *testing.T) { if service.calls != 1 || service.command.Value != feedbackdomain.ValueDown || service.command.ReasonCode != feedbackdomain.ReasonEmpty { t.Fatalf("calls=%d command=%+v", service.calls, service.command) } - if response == nil || response.UserPrivateData == nil || response.UserPrivateData.CardParamMap["showFeedbackReasons"] != "true" { + if response == nil || response.UserPrivateData == nil || + response.UserPrivateData.CardParamMap["showFeedbackReasons"] != "false" || + response.UserPrivateData.CardParamMap["feedbackMessage"] != "感谢反馈,我们会继续改进" { t.Fatalf("response=%+v", response) } } @@ -201,7 +203,7 @@ func TestCardFeedbackMapsWhitelistedActions(t *testing.T) { message string }{ {ActionFeedbackUp, feedbackdomain.ValueUp, "", "false", "感谢反馈"}, - {ActionFeedbackDown, feedbackdomain.ValueDown, "", "true", "请选择未解决原因"}, + {ActionFeedbackDown, feedbackdomain.ValueDown, "", "false", "感谢反馈,我们会继续改进"}, {ActionReasonIncorrect, feedbackdomain.ValueDown, feedbackdomain.ReasonIncorrect, "false", "感谢反馈,我们会继续改进"}, {ActionReasonNotResolved, feedbackdomain.ValueDown, feedbackdomain.ReasonNotResolved, "false", "感谢反馈,我们会继续改进"}, {ActionReasonIrrelevant, feedbackdomain.ValueDown, feedbackdomain.ReasonIrrelevant, "false", "感谢反馈,我们会继续改进"}, diff --git a/internal/channels/dingtalk/group_sender.go b/internal/channels/dingtalk/group_sender.go new file mode 100644 index 0000000..6f314a5 --- /dev/null +++ b/internal/channels/dingtalk/group_sender.go @@ -0,0 +1,364 @@ +package dingtalk + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "strings" + "sync" + "time" + + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/coverage" + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/faqtable" +) + +const ( + groupSendURL = "https://api.dingtalk.com/v1.0/robot/groupMessages/send" + // maxGroupPayloadBytes caps the serialized JSON body sent to the group + // message endpoint. + maxGroupPayloadBytes = 64 << 10 // 64 KiB + // questionRuneLimit caps the displayed current question. + questionRuneLimit = 500 + // previousQuestionRuneLimit caps each displayed historical question. + previousQuestionRuneLimit = 300 +) + +// SupportGroupSender sends DingTalk group Markdown notifications via the +// official groupMessages/send OpenAPI. It is safe by construction: all +// config fields are trimmed, nil client installs hardened defaults, and +// all error paths are sanitised. +type SupportGroupSender struct { + clientID string + clientSecret string + openConversation string + recordLinks *faqtable.RecordLinkBuilder + tokenURL string + groupURL string + apiClient *http.Client + + mu sync.Mutex + token string + tokenTill time.Time +} + +type SupportGroupSenderOption func(*SupportGroupSender) + +func WithFAQRecordLinkBuilder(builder *faqtable.RecordLinkBuilder) SupportGroupSenderOption { + return func(sender *SupportGroupSender) { sender.recordLinks = builder } +} + +var _ coverage.Notifier = (*SupportGroupSender)(nil) + +// NewSupportGroupSender creates a SupportGroupSender. All three config values +// are required after trimming. A nil http.Client installs a hardened default +// (no redirects, Proxy=nil, 15s timeout). +func NewSupportGroupSender(clientID, clientSecret, openConversationID string, client *http.Client, opts ...SupportGroupSenderOption) (*SupportGroupSender, error) { + return newSupportGroupSender(clientID, clientSecret, openConversationID, client, oauthTokenURL, groupSendURL, false, opts...) +} + +// newSupportGroupSenderForTest is used by tests to inject httptest URLs. +func newSupportGroupSenderForTest(clientID, clientSecret, openConversationID string, client *http.Client, tokenURL, groupURL string, opts ...SupportGroupSenderOption) (*SupportGroupSender, error) { + return newSupportGroupSender(clientID, clientSecret, openConversationID, client, tokenURL, groupURL, true, opts...) +} + +func newSupportGroupSender(clientID, clientSecret, openConversationID string, client *http.Client, tokenURL, groupURL string, allowTest bool, opts ...SupportGroupSenderOption) (*SupportGroupSender, error) { + clientID = strings.TrimSpace(clientID) + clientSecret = strings.TrimSpace(clientSecret) + openConversationID = strings.TrimSpace(openConversationID) + if clientID == "" { + return nil, errors.New("dingtalk group sender: clientID is required") + } + if clientSecret == "" { + return nil, errors.New("dingtalk group sender: clientSecret is required") + } + if openConversationID == "" { + return nil, errors.New("dingtalk group sender: openConversationId is required") + } + + base := &http.Client{Timeout: 15 * time.Second} + if client != nil { + copyClient := *client + base = ©Client + if base.Timeout <= 0 { + base.Timeout = 15 * time.Second + } + } + + apiClient := *base + apiClient.CheckRedirect = func(*http.Request, []*http.Request) error { + return errors.New("dingtalk API redirect refused") + } + if !allowTest { + transport := http.DefaultTransport.(*http.Transport).Clone() + transport.Proxy = nil + apiClient.Transport = transport + } + + sender := &SupportGroupSender{ + clientID: clientID, + clientSecret: clientSecret, + openConversation: openConversationID, + tokenURL: tokenURL, + groupURL: groupURL, + apiClient: &apiClient, + } + for _, opt := range opts { + if opt != nil { + opt(sender) + } + } + if allowTest && sender.recordLinks == nil { + sender.recordLinks, _ = faqtable.NewRecordLinkBuilder("test-base", "test-sheet", "test-view") + } + return sender, nil +} + +// Send sends a support-case notification to the DingTalk group. +func (s *SupportGroupSender) Send(ctx context.Context, notif coverage.SupportNotification) error { + if notif.CaseID == "" { + return errors.New("dingtalk group sender: CaseID is required") + } + if s.recordLinks == nil { + return errors.New("dingtalk group sender: FAQ record links are required") + } + recordURL, err := s.recordLinks.Build(notif.FAQRecordID) + if err != nil { + return errors.New("dingtalk group sender: FAQ record link failed") + } + + title, text := s.renderMarkdown(notif) + msgParam := map[string]string{ + "title": title, + "text": text, + "singleTitle": "去回答", + "singleURL": recordURL, + } + msgParamJSON, err := json.Marshal(msgParam) + if err != nil { + return errors.New("dingtalk group sender: encode msgParam failed") + } + + body := map[string]any{ + "msgKey": "sampleActionCard", + "msgParam": string(msgParamJSON), + "openConversationId": s.openConversation, + "robotCode": s.clientID, + } + + bodyJSON, err := json.Marshal(body) + if err != nil { + return errors.New("dingtalk group sender: encode request body failed") + } + if len(bodyJSON) > maxGroupPayloadBytes { + return fmt.Errorf("dingtalk group sender: payload exceeds %d bytes", maxGroupPayloadBytes) + } + + // Get access token + token, err := s.accessToken(ctx) + if err != nil { + return err + } + + // POST to groupMessages/send + respPayload, err := s.doJSON(ctx, http.MethodPost, s.groupURL, body, token) + if err != nil { + return err + } + + // Check business response + var bizResp struct { + ProcessQueryKey string `json:"processQueryKey"` + ErrCode int `json:"errcode"` + } + if err := json.Unmarshal(respPayload, &bizResp); err != nil { + return errors.New("dingtalk group sender: invalid API response") + } + if bizResp.ErrCode != 0 { + return errors.New("dingtalk group sender: API returned business error") + } + if strings.TrimSpace(bizResp.ProcessQueryKey) == "" { + return errors.New("dingtalk group sender: incomplete API response") + } + + return nil +} + +// SendTest sends a fixed, non-sensitive message used to verify that the +// configured robot can reach the candidate support group. It deliberately +// does not require an FAQ-table binding. +func (s *SupportGroupSender) SendTest(ctx context.Context) error { + msgParam, err := json.Marshal(map[string]string{ + "title": "DobotAI 技术支持群绑定测试", + "text": "DobotAI 技术支持群绑定测试成功。", + }) + if err != nil { + return errors.New("dingtalk group sender: encode test message failed") + } + body := map[string]any{ + "msgKey": "sampleMarkdown", + "msgParam": string(msgParam), + "openConversationId": s.openConversation, + "robotCode": s.clientID, + } + bodyJSON, err := json.Marshal(body) + if err != nil { + return errors.New("dingtalk group sender: encode test request failed") + } + if len(bodyJSON) > maxGroupPayloadBytes { + return fmt.Errorf("dingtalk group sender: payload exceeds %d bytes", maxGroupPayloadBytes) + } + token, err := s.accessToken(ctx) + if err != nil { + return err + } + respPayload, err := s.doJSON(ctx, http.MethodPost, s.groupURL, body, token) + if err != nil { + return err + } + var response struct { + ProcessQueryKey string `json:"processQueryKey"` + ErrCode int `json:"errcode"` + } + if json.Unmarshal(respPayload, &response) != nil { + return errors.New("dingtalk group sender: invalid API response") + } + if response.ErrCode != 0 { + return errors.New("dingtalk group sender: API returned business error") + } + if strings.TrimSpace(response.ProcessQueryKey) == "" { + return errors.New("dingtalk group sender: incomplete API response") + } + return nil +} + +// renderMarkdown produces the compact customer-question context shown in the action card. +func (s *SupportGroupSender) renderMarkdown(notif coverage.SupportNotification) (title, text string) { + label := "知识库未覆盖提醒" + if notif.TriggerType == coverage.SupportTriggerFeedbackDown { + label = "回答被点踩提醒" + } + title = label + question := escapeMarkdown(truncateRunes(notif.Question, questionRuneLimit)) + sender := escapeMarkdown(notif.SenderName) + askedAt := "未知" + if !notif.AskedAt.IsZero() { + askedAt = notif.AskedAt.In(time.FixedZone("CST", 8*60*60)).Format("2006-01-02 15:04:05") + } + + var b strings.Builder + b.WriteString("## 【" + label + "】\n\n") + b.WriteString(fmt.Sprintf("**提问人:** %s\n\n", sender)) + b.WriteString(fmt.Sprintf("**时间:** %s\n\n", askedAt)) + b.WriteString(fmt.Sprintf("**当前问题:**\n> %s\n\n", question)) + b.WriteString(fmt.Sprintf("**语言:** %s\n\n", faqtable.DetectLanguage(notif.Question))) + b.WriteString("**最近5次历史问题:**\n") + if len(notif.PreviousQuestions) == 0 { + b.WriteString("暂无历史问题\n") + } else { + for i, previous := range notif.PreviousQuestions { + if i >= 5 { + break + } + b.WriteString(fmt.Sprintf("%d. %s\n", i+1, escapeMarkdown(truncateRunes(previous, previousQuestionRuneLimit)))) + } + } + return title, b.String() +} + +func escapeMarkdown(value string) string { + value = strings.Join(strings.Fields(value), " ") + replacer := strings.NewReplacer( + "\\", "\\\\", "`", "\\`", "*", "\\*", "_", "\\_", + "[", "\\[", "]", "\\]", "(", "\\(", ")", "\\)", + "#", "\\#", ">", "\\>", + ) + return replacer.Replace(value) +} + +func truncateRunes(s string, limit int) string { + if limit <= 0 { + return s + } + runes := []rune(s) + if len(runes) <= limit { + return s + } + return string(runes[:limit]) + "..." +} + +func (s *SupportGroupSender) accessToken(ctx context.Context) (string, error) { + s.mu.Lock() + defer s.mu.Unlock() + if s.token != "" && time.Now().Before(s.tokenTill) { + return s.token, nil + } + + payload, err := s.doJSON(ctx, http.MethodPost, s.tokenURL, map[string]string{ + "appKey": s.clientID, + "appSecret": s.clientSecret, + }, "") + if err != nil { + return "", err + } + + var response struct { + AccessToken string `json:"accessToken"` + ExpireIn int64 `json:"expireIn"` + } + if json.Unmarshal(payload, &response) != nil || strings.TrimSpace(response.AccessToken) == "" { + return "", errors.New("dingtalk group sender: invalid OAuth response") + } + + ttl := time.Duration(response.ExpireIn) * time.Second + refreshAfter := ttl - 5*time.Minute + if refreshAfter <= 0 { + refreshAfter = ttl / 2 + } + if refreshAfter <= 0 { + refreshAfter = time.Minute + } + s.token = response.AccessToken + s.tokenTill = time.Now().Add(refreshAfter) + return s.token, nil +} + +func (s *SupportGroupSender) doJSON(ctx context.Context, method, endpoint string, value any, token string) ([]byte, error) { + body, err := json.Marshal(value) + if err != nil { + return nil, errors.New("dingtalk group sender: encode API request failed") + } + + req, err := http.NewRequestWithContext(ctx, method, endpoint, bytes.NewReader(body)) + if err != nil { + return nil, errors.New("dingtalk group sender: create API request failed") + } + req.Header.Set("Content-Type", "application/json") + if token != "" { + req.Header.Set("x-acs-dingtalk-access-token", token) + } + + resp, err := s.apiClient.Do(req) + if err != nil { + if ctx.Err() != nil { + return nil, ctx.Err() + } + // Propagate redirect errors so callers can detect them. + if strings.Contains(err.Error(), "redirect") { + return nil, err + } + return nil, errors.New("dingtalk group sender: API request failed") + } + defer resp.Body.Close() + + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + // Discard body without reading it — sanitised error + _, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, maxAPIResponseBytes)) + return nil, fmt.Errorf("dingtalk group sender: API HTTP %d", resp.StatusCode) + } + + return readBoundedAPIResponse(resp) +} diff --git a/internal/channels/dingtalk/group_sender_actioncard_test.go b/internal/channels/dingtalk/group_sender_actioncard_test.go new file mode 100644 index 0000000..d5ee9e1 --- /dev/null +++ b/internal/channels/dingtalk/group_sender_actioncard_test.go @@ -0,0 +1,60 @@ +package dingtalk + +import ( + "context" + "encoding/json" + "net/url" + "strings" + "testing" + + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/faqtable" +) + +func TestSupportGroupSenderSendsActionCardWithExactFAQRecordLink(t *testing.T) { + gs := newGroupTestServer() + defer gs.Close() + builder, err := faqtable.NewRecordLinkBuilder("jb9-base", "hERWDMS", "qvGDAH2") + if err != nil { + t.Fatal(err) + } + s, err := newSupportGroupSenderForTest( + "appKey", "appSecret", "cid-abc", gs.server.Client(), + gs.URL()+"/token", gs.URL()+"/groupMessages/send", + WithFAQRecordLinkBuilder(builder), + ) + if err != nil { + t.Fatal(err) + } + if err := s.Send(context.Background(), newTestNotification()); err != nil { + t.Fatal(err) + } + if gs.lastSendBody["msgKey"] != "sampleActionCard" { + t.Fatalf("msgKey=%v", gs.lastSendBody["msgKey"]) + } + var params map[string]string + if err := json.Unmarshal([]byte(gs.lastSendBody["msgParam"].(string)), ¶ms); err != nil { + t.Fatal(err) + } + if params["singleTitle"] != "去回答" { + t.Fatalf("singleTitle=%q", params["singleTitle"]) + } + parsed, err := url.Parse(params["singleURL"]) + if err != nil { + t.Fatal(err) + } + q := parsed.Query() + if parsed.Host != "docs.dingtalk.com" || q.Get("rowId") != "record-001" || q.Get("dentryUuid") != "jb9-base" { + t.Fatalf("singleURL=%s", params["singleURL"]) + } + text := params["text"] + for _, required := range []string{"张三", "2026-07-24 10:16:35", "怎么配置钉钉机器人", "之前的问题一", "之前的问题二", "Chinese"} { + if !strings.Contains(text, required) { + t.Errorf("text missing %q: %s", required, text) + } + } + for _, forbidden := range []string{"回答摘要", "相关结果", "Score", "置信度", "case-001"} { + if strings.Contains(text, forbidden) { + t.Errorf("text contains forbidden %q: %s", forbidden, text) + } + } +} diff --git a/internal/channels/dingtalk/group_sender_test.go b/internal/channels/dingtalk/group_sender_test.go new file mode 100644 index 0000000..5401e6b --- /dev/null +++ b/internal/channels/dingtalk/group_sender_test.go @@ -0,0 +1,599 @@ +package dingtalk + +import ( + "context" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/core" + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/coverage" +) + +// groupTestServer provides a configurable httptest server for group message +// tests, with token and groupMessages/send endpoints. +type groupTestServer struct { + server *httptest.Server + tokenCalls int + sendCalls int + + lastTokenBody map[string]string + lastSendBody map[string]any + lastSendHeader string + + tokenStatus int + tokenResponse any + + sendStatus int + sendResponse any +} + +func newGroupTestServer() *groupTestServer { + gs := &groupTestServer{ + tokenStatus: http.StatusOK, + tokenResponse: map[string]any{"accessToken": "test-token", "expireIn": 3600}, + sendStatus: http.StatusOK, + sendResponse: map[string]any{"processQueryKey": "pqk-123"}, + } + gs.server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/token": + gs.tokenCalls++ + gs.lastTokenBody = make(map[string]string) + json.NewDecoder(r.Body).Decode(&gs.lastTokenBody) + w.Header().Set("Content-Type", "application/json") + if gs.tokenStatus != http.StatusOK { + w.WriteHeader(gs.tokenStatus) + return + } + json.NewEncoder(w).Encode(gs.tokenResponse) + case "/groupMessages/send": + gs.sendCalls++ + gs.lastSendHeader = r.Header.Get("x-acs-dingtalk-access-token") + gs.lastSendBody = make(map[string]any) + json.NewDecoder(r.Body).Decode(&gs.lastSendBody) + w.Header().Set("Content-Type", "application/json") + if gs.sendStatus != http.StatusOK { + w.WriteHeader(gs.sendStatus) + return + } + json.NewEncoder(w).Encode(gs.sendResponse) + default: + http.NotFound(w, r) + } + })) + return gs +} + +func (gs *groupTestServer) Close() { gs.server.Close() } +func (gs *groupTestServer) URL() string { return gs.server.URL } + +func newTestNotification() coverage.SupportNotification { + return coverage.SupportNotification{ + CaseID: "case-001", + Question: "怎么配置钉钉机器人?", + SenderName: "张三", + Channel: "dingtalk", + ConversationType: core.ConversationGroup, + AskedAt: time.Date(2026, 7, 24, 10, 16, 35, 0, time.FixedZone("CST", 8*60*60)), + PreviousQuestions: []string{"之前的问题一", "之前的问题二"}, + FAQRecordID: "record-001", + } +} + +// helper to create a sender with test URLs. +func newTestGroupSender(t *testing.T, clientID, clientSecret, openConvID string, client *http.Client, tokenURL, groupURL string) *SupportGroupSender { + t.Helper() + s, err := newSupportGroupSenderForTest(clientID, clientSecret, openConvID, client, tokenURL, groupURL) + if err != nil { + t.Fatalf("newSupportGroupSenderForTest: %v", err) + } + return s +} + +// -------- 1. fail closed on missing config -------- + +func TestSupportGroupSenderMissingConfigFailsClosed(t *testing.T) { + tests := []struct { + name, clientID, clientSecret, openConvID string + wantErr string + }{ + {name: "empty clientID", clientSecret: "s", openConvID: "c", wantErr: "clientID"}, + {name: "empty clientSecret", clientID: "a", openConvID: "c", wantErr: "clientSecret"}, + {name: "empty openConversationId", clientID: "a", clientSecret: "s", wantErr: "openConversationId"}, + {name: "all empty", wantErr: "clientID"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + _, err := NewSupportGroupSender(tt.clientID, tt.clientSecret, tt.openConvID, nil) + if err == nil { + t.Fatal("expected error, got nil") + } + if !strings.Contains(err.Error(), tt.wantErr) { + t.Fatalf("error = %v, want containing %q", err, tt.wantErr) + } + }) + } +} + +// -------- 2. exact endpoint, body, header -------- + +func TestSupportGroupSenderExactEndpointBodyHeader(t *testing.T) { + gs := newGroupTestServer() + defer gs.Close() + + s := newTestGroupSender(t, "appKey", "appSecret", "cid-abc", gs.server.Client(), gs.URL()+"/token", gs.URL()+"/groupMessages/send") + notif := newTestNotification() + ctx := context.Background() + + if err := s.Send(ctx, notif); err != nil { + t.Fatalf("Send: %v", err) + } + + // Verify token endpoint was called + if gs.tokenCalls != 1 { + t.Fatalf("tokenCalls = %d, want 1", gs.tokenCalls) + } + if gs.lastTokenBody["appKey"] != "appKey" || gs.lastTokenBody["appSecret"] != "appSecret" { + t.Fatalf("token body = %+v", gs.lastTokenBody) + } + + // Verify send endpoint + if gs.sendCalls != 1 { + t.Fatalf("sendCalls = %d, want 1", gs.sendCalls) + } + if gs.lastSendHeader != "test-token" { + t.Fatalf("send header = %q, want test-token", gs.lastSendHeader) + } + + body := gs.lastSendBody + if body["msgKey"] != "sampleActionCard" { + t.Fatalf("msgKey = %v, want sampleActionCard", body["msgKey"]) + } + if body["openConversationId"] != "cid-abc" { + t.Fatalf("openConversationId = %v, want cid-abc", body["openConversationId"]) + } + if body["robotCode"] != "appKey" { + t.Fatalf("robotCode = %v, want appKey", body["robotCode"]) + } + + // msgParam must be a JSON string + msgParamRaw, ok := body["msgParam"].(string) + if !ok { + t.Fatalf("msgParam is not a string, got %T", body["msgParam"]) + } + + // Parse msgParam as JSON + var msgParam map[string]string + if err := json.Unmarshal([]byte(msgParamRaw), &msgParam); err != nil { + t.Fatalf("msgParam is not valid JSON: %v (raw=%s)", err, msgParamRaw) + } + if msgParam["title"] == "" { + t.Fatal("msgParam.title is empty") + } + if msgParam["text"] == "" { + t.Fatal("msgParam.text is empty") + } +} + +// -------- 3. msgParam is valid JSON string -------- + +func TestSupportGroupSenderMsgParamIsValidJSON(t *testing.T) { + gs := newGroupTestServer() + defer gs.Close() + + s := newTestGroupSender(t, "appKey", "appSecret", "cid-abc", gs.server.Client(), gs.URL()+"/token", gs.URL()+"/groupMessages/send") + + if err := s.Send(context.Background(), newTestNotification()); err != nil { + t.Fatalf("Send: %v", err) + } + + raw := gs.lastSendBody["msgParam"].(string) + var mp map[string]any + if err := json.Unmarshal([]byte(raw), &mp); err != nil { + t.Fatalf("msgParam not valid JSON: %v", err) + } + + // Verify required keys exist + if _, ok := mp["title"]; !ok { + t.Fatal("msgParam missing title") + } + if _, ok := mp["text"]; !ok { + t.Fatal("msgParam missing text") + } +} + +// -------- 4. OAuth token reuse -------- + +func TestSupportGroupSenderTokenReuse(t *testing.T) { + gs := newGroupTestServer() + gs.tokenResponse = map[string]any{"accessToken": "reused-token", "expireIn": 7200} + defer gs.Close() + + s := newTestGroupSender(t, "appKey", "appSecret", "cid-abc", gs.server.Client(), gs.URL()+"/token", gs.URL()+"/groupMessages/send") + + // Send twice + if err := s.Send(context.Background(), newTestNotification()); err != nil { + t.Fatalf("first Send: %v", err) + } + if err := s.Send(context.Background(), newTestNotification()); err != nil { + t.Fatalf("second Send: %v", err) + } + + // Token should only be fetched once + if gs.tokenCalls != 1 { + t.Fatalf("tokenCalls = %d, want 1 (token should be reused)", gs.tokenCalls) + } + if gs.sendCalls != 2 { + t.Fatalf("sendCalls = %d, want 2", gs.sendCalls) + } +} + +// -------- 5. no redirects -------- + +func TestSupportGroupSenderRejectsRedirect(t *testing.T) { + // Create a target server + target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusOK) + })) + defer target.Close() + + // Create a redirector + redirector := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.Redirect(w, r, target.URL+"/groupMessages/send", http.StatusFound) + })) + defer redirector.Close() + + _, err := newSupportGroupSenderForTest("appKey", "appSecret", "cid-abc", redirector.Client(), + redirector.URL+"/token", redirector.URL+"/groupMessages/send") + if err != nil { + t.Fatalf("newSupportGroupSenderForTest: %v", err) + } + + // token endpoint also redirects + redirector2 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.Redirect(w, r, target.URL+"/token", http.StatusFound) + })) + defer redirector2.Close() + + s := newTestGroupSender(t, "appKey", "appSecret", "cid-abc", redirector2.Client(), + redirector2.URL+"/token", redirector2.URL+"/groupMessages/send") + + err = s.Send(context.Background(), newTestNotification()) + if err == nil { + t.Fatal("expected redirect error, got nil") + } + if !strings.Contains(err.Error(), "redirect") { + t.Fatalf("error = %v, want containing 'redirect'", err) + } +} + +// -------- 6. non-2xx sanitized error -------- + +func TestSupportGroupSenderNon2xxSanitized(t *testing.T) { + gs := newGroupTestServer() + gs.sendStatus = http.StatusInternalServerError + defer gs.Close() + + s := newTestGroupSender(t, "appKey", "appSecret", "cid-abc", gs.server.Client(), gs.URL()+"/token", gs.URL()+"/groupMessages/send") + + err := s.Send(context.Background(), newTestNotification()) + if err == nil { + t.Fatal("expected error for 500, got nil") + } + + errStr := err.Error() + // Error must NOT contain clientSecret + if strings.Contains(errStr, "appSecret") { + t.Fatalf("error leaks clientSecret: %s", errStr) + } + // Error must NOT contain access token + if strings.Contains(errStr, "test-token") { + t.Fatalf("error leaks access token: %s", errStr) + } + // Error must NOT contain conversation ID + if strings.Contains(errStr, "cid-abc") { + t.Fatalf("error leaks openConversationId: %s", errStr) + } + // Error must NOT contain question + if strings.Contains(errStr, "怎么配置") { + t.Fatalf("error leaks question: %s", errStr) + } + // Error must NOT contain answer + if strings.Contains(errStr, "钉钉开放平台") { + t.Fatalf("error leaks answer: %s", errStr) + } +} + +// -------- 7. business failure (non-success response) sanitized -------- + +func TestSupportGroupSenderBusinessFailureSanitized(t *testing.T) { + gs := newGroupTestServer() + gs.sendStatus = http.StatusOK + // Simulate a business error: DingTalk returns 200 but with error code + gs.sendResponse = map[string]any{ + "errcode": 40035, + "errmsg": "不合法的参数", + } + defer gs.Close() + + s := newTestGroupSender(t, "appKey", "appSecret", "cid-abc", gs.server.Client(), gs.URL()+"/token", gs.URL()+"/groupMessages/send") + + err := s.Send(context.Background(), newTestNotification()) + if err == nil { + t.Fatal("expected business error, got nil") + } + + errStr := err.Error() + if strings.Contains(errStr, "appSecret") { + t.Fatalf("error leaks clientSecret: %s", errStr) + } + if strings.Contains(errStr, "test-token") { + t.Fatalf("error leaks access token: %s", errStr) + } + if strings.Contains(errStr, "cid-abc") { + t.Fatalf("error leaks openConversationId: %s", errStr) + } + if strings.Contains(errStr, "怎么配置") { + t.Fatalf("error leaks question: %s", errStr) + } +} + +// -------- 8. long Unicode truncation / 64KiB limit -------- + +func TestSupportGroupSenderLongUnicodeTruncation(t *testing.T) { + gs := newGroupTestServer() + defer gs.Close() + + s := newTestGroupSender(t, "appKey", "appSecret", "cid-abc", gs.server.Client(), gs.URL()+"/token", gs.URL()+"/groupMessages/send") + + // Create a notification with a very long current and historical question. + longQ := strings.Repeat("你好", 300) + longPrevious := strings.Repeat("世界", 600) + + notif := newTestNotification() + notif.Question = longQ + notif.PreviousQuestions = []string{longPrevious} + + if err := s.Send(context.Background(), notif); err != nil { + t.Fatalf("Send with long content: %v", err) + } + + // The msgParam text should contain truncated versions + raw := gs.lastSendBody["msgParam"].(string) + var mp map[string]string + if err := json.Unmarshal([]byte(raw), &mp); err != nil { + t.Fatalf("msgParam not valid JSON: %v", err) + } + + text := mp["text"] + // Both current and historical questions are present and rune-truncated. + if !strings.Contains(text, "你好") { + t.Fatal("text missing current question content") + } + if !strings.Contains(text, "世界") { + t.Fatal("text missing historical question content") + } + + // The full body size must be <= 64KiB + bodyBytes, _ := json.Marshal(gs.lastSendBody) + if len(bodyBytes) > 64*1024 { + t.Fatalf("body size = %d, exceeds 64KiB", len(bodyBytes)) + } +} + +func TestSupportGroupSenderPayloadExceeds64KiB(t *testing.T) { + gs := newGroupTestServer() + defer gs.Close() + + s := newTestGroupSender(t, "appKey", "appSecret", "cid-abc", gs.server.Client(), gs.URL()+"/token", gs.URL()+"/groupMessages/send") + + notif := newTestNotification() + // Use a very long SenderName to push the rendered markdown + JSON + // serialization beyond 64 KiB. Question/Answer are truncated to 500/1000 + // runes, so they won't contribute much. The SenderName is not truncated. + notif.SenderName = strings.Repeat("张", 70*1024) // ~70KB of UTF-8 + + err := s.Send(context.Background(), notif) + if err == nil { + t.Fatal("expected error for oversized payload, got nil") + } + if !strings.Contains(err.Error(), "exceeds") && !strings.Contains(err.Error(), "64") && !strings.Contains(err.Error(), "KiB") { + t.Fatalf("error = %v, want size-limit error", err) + } +} + +// -------- 9. error JSON response does not leak -------- + +func TestSupportGroupSenderErrorJSONNotLeaked(t *testing.T) { + gs := newGroupTestServer() + gs.sendStatus = http.StatusBadRequest + // Return a large error body + gs.sendResponse = nil + // Override handler to return raw error JSON + gs.server.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/token" { + gs.tokenCalls++ + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(gs.tokenResponse) + return + } + gs.sendCalls++ + w.WriteHeader(http.StatusBadRequest) + // Write raw error JSON with sensitive-looking content + io.WriteString(w, `{"errcode":40035,"errmsg":"invalid parameter cid-abc","raw":"user appSecret leaked"}`) + }) + defer gs.Close() + + s := newTestGroupSender(t, "appKey", "appSecret", "cid-abc", gs.server.Client(), gs.URL()+"/token", gs.URL()+"/groupMessages/send") + + err := s.Send(context.Background(), newTestNotification()) + if err == nil { + t.Fatal("expected error, got nil") + } + + errStr := err.Error() + // Error must not contain the raw response body + if strings.Contains(errStr, "40035") || strings.Contains(errStr, "invalid parameter") { + t.Fatalf("error leaks raw API response: %s", errStr) + } + if strings.Contains(errStr, "appSecret") { + t.Fatalf("error leaks clientSecret: %s", errStr) + } + if strings.Contains(errStr, "cid-abc") { + t.Fatalf("error leaks conversation ID: %s", errStr) + } +} + +// -------- 10. validation: empty CaseID -------- + +func TestSupportGroupSenderRejectsEmptyCaseID(t *testing.T) { + gs := newGroupTestServer() + defer gs.Close() + + s := newTestGroupSender(t, "appKey", "appSecret", "cid-abc", gs.server.Client(), gs.URL()+"/token", gs.URL()+"/groupMessages/send") + + notif := newTestNotification() + notif.CaseID = "" + err := s.Send(context.Background(), notif) + if err == nil { + t.Fatal("expected error for empty CaseID, got nil") + } + if !strings.Contains(err.Error(), "CaseID") { + t.Fatalf("error = %v, want containing 'CaseID'", err) + } +} + +// -------- 11. nil client installs hardened defaults -------- + +func TestSupportGroupSenderNilClientDefaults(t *testing.T) { + gs := newGroupTestServer() + defer gs.Close() + + // Use nil client and verify it still works with httptest URLs + s, err := newSupportGroupSenderForTest("appKey", "appSecret", "cid-abc", nil, gs.URL()+"/token", gs.URL()+"/groupMessages/send") + if err != nil { + t.Fatalf("newSupportGroupSenderForTest with nil client: %v", err) + } + if err := s.Send(context.Background(), newTestNotification()); err != nil { + t.Fatalf("Send with nil client: %v", err) + } +} + +// -------- 12. Markdown content verification -------- + +func TestSupportGroupSenderMarkdownContent(t *testing.T) { + gs := newGroupTestServer() + defer gs.Close() + + s := newTestGroupSender(t, "appKey", "appSecret", "cid-abc", gs.server.Client(), gs.URL()+"/token", gs.URL()+"/groupMessages/send") + + notif := newTestNotification() + if err := s.Send(context.Background(), notif); err != nil { + t.Fatalf("Send: %v", err) + } + + raw := gs.lastSendBody["msgParam"].(string) + var mp map[string]string + if err := json.Unmarshal([]byte(raw), &mp); err != nil { + t.Fatalf("msgParam not valid JSON: %v", err) + } + + text := mp["text"] + title := mp["title"] + + if title != "知识库未覆盖提醒" { + t.Fatalf("title = %q", title) + } + for _, want := range []string{"张三", "2026-07-24 10:16:35", "怎么配置", "之前的问题一", "之前的问题二", "Chinese"} { + if !strings.Contains(text, want) { + t.Fatalf("action-card text missing %q: %s", want, text) + } + } + for _, forbidden := range []string{"case-001", "回答摘要", "相关结果", "Score", "置信度"} { + if strings.Contains(text, forbidden) { + t.Fatalf("action-card text contains forbidden %q: %s", forbidden, text) + } + } + if mp["singleTitle"] != "去回答" || mp["singleURL"] == "" { + t.Fatalf("missing FAQ action: %#v", mp) + } +} + +func TestSupportGroupSenderNoPreviousQuestions(t *testing.T) { + gs := newGroupTestServer() + defer gs.Close() + + s := newTestGroupSender(t, "appKey", "appSecret", "cid-abc", gs.server.Client(), gs.URL()+"/token", gs.URL()+"/groupMessages/send") + notif := newTestNotification() + notif.PreviousQuestions = nil + if err := s.Send(context.Background(), notif); err != nil { + t.Fatalf("Send: %v", err) + } + if raw := gs.lastSendBody["msgParam"].(string); !strings.Contains(raw, "暂无历史问题") { + t.Fatalf("missing empty-history copy: %s", raw) + } +} + +func TestSupportGroupSenderSendTestDoesNotRequireFAQBinding(t *testing.T) { + gs := newGroupTestServer() + defer gs.Close() + + sender, err := newSupportGroupSenderForTest( + "appKey", "appSecret", "cid-abc", + gs.server.Client(), gs.URL()+"/token", gs.URL()+"/groupMessages/send", + ) + if err != nil { + t.Fatal(err) + } + if err = sender.SendTest(context.Background()); err != nil { + t.Fatalf("SendTest: %v", err) + } + if gs.sendCalls != 1 { + t.Fatalf("sendCalls=%d want=1", gs.sendCalls) + } + if gs.lastSendBody["openConversationId"] != "cid-abc" || gs.lastSendBody["robotCode"] != "appKey" { + t.Fatalf("body=%v", gs.lastSendBody) + } + if gs.lastSendBody["msgKey"] != "sampleMarkdown" { + t.Fatalf("msgKey=%v want=sampleMarkdown", gs.lastSendBody["msgKey"]) + } + var params map[string]string + if err = json.Unmarshal([]byte(gs.lastSendBody["msgParam"].(string)), ¶ms); err != nil { + t.Fatal(err) + } + if params["title"] != "DobotAI 技术支持群绑定测试" || !strings.Contains(params["text"], "测试成功") { + t.Fatalf("params=%v", params) + } +} + +func TestSupportGroupSenderRejectsMalformedOrIncompleteSuccessResponse(t *testing.T) { + tests := []struct { + name string + response any + }{ + {name: "malformed JSON", response: json.RawMessage(`{`)}, + {name: "missing processQueryKey", response: map[string]any{}}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + gs := newGroupTestServer() + gs.sendResponse = tt.response + defer gs.Close() + + s := newTestGroupSender(t, "appKey", "appSecret", "cid-abc", gs.server.Client(), gs.URL()+"/token", gs.URL()+"/groupMessages/send") + err := s.Send(context.Background(), newTestNotification()) + if err == nil { + t.Fatal("expected fail-closed error, got nil") + } + if strings.Contains(err.Error(), "cid-abc") || strings.Contains(err.Error(), "怎么配置") { + t.Fatalf("error leaks notification data: %v", err) + } + }) + } +} diff --git a/internal/channels/dingtalk/group_sender_trigger_test.go b/internal/channels/dingtalk/group_sender_trigger_test.go new file mode 100644 index 0000000..e6e8886 --- /dev/null +++ b/internal/channels/dingtalk/group_sender_trigger_test.go @@ -0,0 +1,24 @@ +package dingtalk + +import ( + "strings" + "testing" + + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/coverage" +) + +func TestSupportGroupSenderRendersFeedbackDownTrigger(t *testing.T) { + notification := newTestNotification() + notification.TriggerType = coverage.SupportTriggerFeedbackDown + title, text := (&SupportGroupSender{}).renderMarkdown(notification) + if title != "回答被点踩提醒" || !strings.Contains(text, "【回答被点踩提醒】") { + t.Fatalf("title=%q text=%q", title, text) + } +} + +func TestSupportGroupSenderDefaultsHistoricalTriggerToCoverage(t *testing.T) { + title, text := (&SupportGroupSender{}).renderMarkdown(newTestNotification()) + if title != "知识库未覆盖提醒" || !strings.Contains(text, "【知识库未覆盖提醒】") { + t.Fatalf("title=%q text=%q", title, text) + } +} diff --git a/internal/channels/dingtalk/handler.go b/internal/channels/dingtalk/handler.go index d068e3f..3323af5 100644 --- a/internal/channels/dingtalk/handler.go +++ b/internal/channels/dingtalk/handler.go @@ -2,6 +2,7 @@ package dingtalk import ( "context" + "encoding/base64" "errors" "fmt" "log" @@ -9,6 +10,8 @@ import ( "time" "gitea.zheromiku.top/Weknora/dobotai-platform/internal/core" + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/directory" + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/reasoningmode" "gitea.zheromiku.top/Weknora/dobotai-platform/internal/weknora" ) @@ -32,17 +35,19 @@ type TenantConfig struct { } type BotCallback struct { - ConversationType string - ConversationID string - Msgtype string - MsgID string - SenderNick string - SenderStaffID string - SenderID string - IsInAtList bool - SessionWebhook string - Text string - DownloadCode string + ConversationType string + ConversationID string + ConversationTitle string + Msgtype string + MsgID string + SenderNick string + SenderStaffID string + SenderID string + IsInAtList bool + SessionWebhook string + Text string + DownloadCode string + DownloadCodes []string } type QAAsker interface { @@ -73,6 +78,66 @@ type ImageDownloader interface { Download(ctx context.Context, downloadCode string) (core.ImageInput, error) } +// ImagePublisher publishes a downloaded image to object storage and returns a +// stable HTTPS URL. Implementation satisfies outboundimage.Publisher. +type ImagePublisher interface { + Publish(ctx context.Context, data []byte, contentType string) (string, error) +} + +type UserDirectory interface { + ResolveUser(ctx context.Context, tenantKey, staffID, fallbackName string) (directory.Profile, error) +} + +type OutboundContentRewriter interface { + Rewrite(ctx context.Context, content string) string +} + +type OutboundPartialSanitizer interface { + SanitizePartial(content string) string +} + +type SettingsMessage struct { + TenantKey string + Channel string + StaffID string + UnionID string + DisplayName string + Department string + Text string + ConversationType string + ConversationID string + ConversationTitle string +} + +type SettingsRouter interface { + Handle(context.Context, SettingsMessage) (handled bool, reply string, err error) +} + +type ReasoningMessage struct { + TenantKey string + Channel string + StaffID string + Text string + ConversationID string +} + +type ReasoningDecision struct { + Handled bool + Reply string + Query string + AgentID string + Execution reasoningmode.ExecutionMode + Expired bool +} + +type ReasoningRouter interface { + Prepare(context.Context, ReasoningMessage) (ReasoningDecision, error) +} + +type LanguagePreferenceResolver interface { + GetPreference(context.Context, string, string, string) (string, error) +} + // FinalCardSender sends an AI card as the final reply. Implementations must // not log err, outTrackID, or content at any level. type FinalCardSender interface { @@ -87,8 +152,14 @@ type StreamingCardSender interface { } type HandlerOptions struct { - ImageDownloader ImageDownloader - CardSender FinalCardSender + ImageDownloader ImageDownloader + ImagePublisher ImagePublisher + CardSender FinalCardSender + Directory UserDirectory + OutboundRewriter OutboundContentRewriter + SettingsRouter SettingsRouter + ReasoningRouter ReasoningRouter + LanguageResolver LanguagePreferenceResolver } type Handler struct { @@ -96,7 +167,13 @@ type Handler struct { qa QAAsker reply MarkdownSender downloader ImageDownloader + imagePublisher ImagePublisher card FinalCardSender + directory UserDirectory + outboundRewriter OutboundContentRewriter + settingsRouter SettingsRouter + reasoningRouter ReasoningRouter + languageResolver LanguagePreferenceResolver now func() time.Time cardUpdateInterval time.Duration finalDeliveryTimeout time.Duration @@ -136,7 +213,13 @@ func NewHandlerWithOptions(cfg TenantConfig, qa QAAsker, reply MarkdownSender, o qa: qa, reply: reply, downloader: opts.ImageDownloader, + imagePublisher: opts.ImagePublisher, card: opts.CardSender, + directory: opts.Directory, + outboundRewriter: opts.OutboundRewriter, + settingsRouter: opts.SettingsRouter, + reasoningRouter: opts.ReasoningRouter, + languageResolver: opts.LanguageResolver, now: time.Now, cardUpdateInterval: 500 * time.Millisecond, finalDeliveryTimeout: defaultHTTPTimeout, @@ -170,13 +253,60 @@ func (h *Handler) Handle(ctx context.Context, cb BotCallback) error { return errors.New("dingtalk handler: sender staffId/senderId is required") } + triggerPerson := strings.TrimSpace(cb.SenderNick) + senderName := triggerPerson + department := "" + region := "" + actorUnionID := "" + if h.directory != nil { + profile, _ := h.directory.ResolveUser(ctx, h.cfg.TenantKey, externalUserID, senderName) + if name := strings.TrimSpace(profile.Name); name != "" { + senderName = name + department = strings.TrimSpace(profile.DepartmentName) + region = strings.TrimSpace(profile.Region) + } + actorUnionID = strings.TrimSpace(profile.UnionID) + } + // Trigger person snapshot falls back to official name when callback nick is blank. + if triggerPerson == "" { + triggerPerson = senderName + } + + if h.settingsRouter != nil && strings.EqualFold(strings.TrimSpace(cb.Msgtype), msgTypeText) { + handled, settingsReply, err := h.settingsRouter.Handle(ctx, SettingsMessage{ + TenantKey: h.cfg.TenantKey, Channel: h.cfg.Channel, StaffID: externalUserID, + UnionID: actorUnionID, DisplayName: senderName, Department: department, Text: strings.TrimSpace(cb.Text), + ConversationType: mapDingTalkConversationType(cb.ConversationType), + ConversationID: strings.TrimSpace(cb.ConversationID), ConversationTitle: strings.TrimSpace(cb.ConversationTitle), + }) + if err != nil { + return fmt.Errorf("dingtalk settings: %w", err) + } + if handled { + if strings.TrimSpace(settingsReply) == "" { + return nil + } + return h.sendReply(ctx, webhookURL, settingsReply) + } + } + req := core.QARequest{ - TenantKey: h.cfg.TenantKey, - Channel: h.cfg.Channel, - ExternalUserID: externalUserID, - ExternalMessageID: strings.TrimSpace(cb.MsgID), - SenderName: cb.SenderNick, - MessageType: strings.ToLower(strings.TrimSpace(cb.Msgtype)), + TenantKey: h.cfg.TenantKey, + Channel: h.cfg.Channel, + ExternalUserID: externalUserID, + ExternalMessageID: strings.TrimSpace(cb.MsgID), + SenderName: senderName, + TriggerPersonSnapshot: triggerPerson, + ActorUnionIDSnapshot: actorUnionID, + Department: department, + Region: region, + MessageType: strings.ToLower(strings.TrimSpace(cb.Msgtype)), + ConversationTitle: strings.TrimSpace(cb.ConversationTitle), + } + if h.languageResolver != nil { + if locale, err := h.languageResolver.GetPreference(ctx, h.cfg.TenantKey, h.cfg.Channel, externalUserID); err == nil { + req.ResponseLocale = strings.TrimSpace(locale) + } } switch cb.ConversationType { case conversationTypeGroup: @@ -187,6 +317,7 @@ func (h *Handler) Handle(ctx context.Context, cb BotCallback) error { req.ExternalChatID = strings.TrimSpace(cb.ConversationID) default: req.ConversationType = core.ConversationDirect + req.ConversationTitle = "" } switch strings.ToLower(strings.TrimSpace(cb.Msgtype)) { @@ -196,7 +327,8 @@ func (h *Handler) Handle(ctx context.Context, cb BotCallback) error { return errors.New("dingtalk handler: text message content is empty") } case msgTypePicture: - if strings.TrimSpace(cb.DownloadCode) == "" { + codes := effectiveDownloadCodes(cb) + if len(codes) == 0 { log.Printf("DingTalk image preparation failed: stage=missing_download_code") return h.sendReply(ctx, webhookURL, imageErrorReply) } @@ -204,20 +336,49 @@ func (h *Handler) Handle(ctx context.Context, cb BotCallback) error { log.Printf("DingTalk image preparation failed: stage=downloader_unavailable") return h.sendReply(ctx, webhookURL, imageErrorReply) } - image, err := h.downloader.Download(ctx, strings.TrimSpace(cb.DownloadCode)) - if err != nil { - log.Printf("DingTalk image preparation failed: stage=%s", imageFailureStage(err)) - return h.sendReply(ctx, webhookURL, imageErrorReply) + images := make([]core.ImageInput, 0, len(codes)) + for _, code := range codes { + image, err := h.downloader.Download(ctx, code) + if err != nil { + log.Printf("DingTalk image preparation failed: stage=%s", imageFailureStage(err)) + return h.sendReply(ctx, webhookURL, imageErrorReply) + } + if h.imagePublisher != nil { + if url := h.publishQuestionImage(ctx, image); url != "" { + image.PublishedURL = url + } + } + images = append(images, image) } req.Query = strings.TrimSpace(cb.Text) if req.Query == "" { req.Query = imageQuery } - req.Images = []core.ImageInput{image} + req.Images = images default: return h.sendReply(ctx, webhookURL, unsupportedMessageReply) } + if h.reasoningRouter != nil { + decision, err := h.reasoningRouter.Prepare(ctx, ReasoningMessage{ + TenantKey: h.cfg.TenantKey, Channel: h.cfg.Channel, StaffID: externalUserID, + Text: req.Query, ConversationID: req.ExternalChatID, + }) + if err != nil { + return fmt.Errorf("dingtalk reasoning mode: %w", err) + } + if decision.Handled { + if strings.TrimSpace(decision.Reply) == "" { + return nil + } + return h.sendReply(ctx, webhookURL, decision.Reply) + } + req.Query = strings.TrimSpace(decision.Query) + req.AgentIDOverride = strings.TrimSpace(decision.AgentID) + req.ReasoningExecution = string(decision.Execution) + req.ReasoningExpired = decision.Expired + } + if eventCard, eventQA := h.eventStreamingCapable(); eventCard != nil && eventQA != nil { return h.handleEventStreaming(ctx, webhookURL, req, eventCard, eventQA) } @@ -229,6 +390,13 @@ func (h *Handler) Handle(ctx context.Context, cb BotCallback) error { return h.handleNonStreaming(ctx, webhookURL, req) } +func mapDingTalkConversationType(value string) string { + if value == conversationTypeGroup { + return "group" + } + return "direct" +} + func (h *Handler) eventStreamingCapable() (StreamingCardSender, EventQAAsker) { sc, ok := h.card.(StreamingCardSender) if !ok { @@ -256,6 +424,7 @@ func (h *Handler) streamingCapable() (StreamingCardSender, StreamingQAAsker) { func (h *Handler) handleNonStreaming(ctx context.Context, webhookURL string, req core.QARequest) error { result, err := h.qa.Ask(ctx, req) if err != nil { + logQAFailure("non_streaming", err) if replyErr := h.sendReply(ctx, webhookURL, qaErrorReply); replyErr != nil { return replyErr } @@ -264,13 +433,14 @@ func (h *Handler) handleNonStreaming(ctx context.Context, webhookURL string, req if result.Replayed && result.DeliveryStatus == core.DeliverySent { return nil } + content := h.rewriteOutboundContent(ctx, result.Answer) if h.card != nil { cardReq := CardRequest{ ConversationType: req.ConversationType, ExternalUserID: req.ExternalUserID, ExternalChatID: req.ExternalChatID, - Content: result.Answer, + Content: content, } if outTrackID, cardErr := h.card.SendFinalCard(ctx, cardReq); cardErr == nil { h.recordDelivery(ctx, result, core.DeliverySent, core.DeliveryMethodCard, outTrackID, "") @@ -278,7 +448,7 @@ func (h *Handler) handleNonStreaming(ctx context.Context, webhookURL string, req } log.Printf("DingTalk card delivery failed, falling back to markdown") } - if err := h.sendReply(ctx, webhookURL, result.Answer); err != nil { + if err := h.sendReply(ctx, webhookURL, content); err != nil { h.recordDelivery(ctx, result, core.DeliveryFailed, "", "", core.DeliveryFailureChannelDelivery) return err } @@ -299,6 +469,7 @@ func (h *Handler) handleStreaming(ctx context.Context, webhookURL string, req co // Fallback: Ask → Markdown only (no SendFinalCard, no AskStream) result, askErr := h.qa.Ask(ctx, req) if askErr != nil { + logQAFailure("streaming_fallback", askErr) if replyErr := h.sendReply(ctx, webhookURL, qaErrorReply); replyErr != nil { return replyErr } @@ -307,7 +478,8 @@ func (h *Handler) handleStreaming(ctx context.Context, webhookURL string, req co if result.Replayed && result.DeliveryStatus == core.DeliverySent { return nil } - if replyErr := h.sendReply(ctx, webhookURL, result.Answer); replyErr != nil { + content := h.rewriteOutboundContent(ctx, result.Answer) + if replyErr := h.sendReply(ctx, webhookURL, content); replyErr != nil { h.recordDelivery(ctx, result, core.DeliveryFailed, "", "", core.DeliveryFailureChannelDelivery) return replyErr } @@ -317,24 +489,33 @@ func (h *Handler) handleStreaming(ctx context.Context, webhookURL string, req co // Streaming observer with the configured update throttle (500ms by default). var lastUpdate time.Time + var lastPartialContent string observer := func(fullContent string) { if strings.TrimSpace(fullContent) == "" { return } + fullContent = decorateReasoningPartial(fullContent, req.ReasoningExecution) now := h.now() if lastUpdate.IsZero() || now.Sub(lastUpdate) >= h.cardUpdateInterval { + partialContent := h.sanitizeOutboundPartial(fullContent) + if strings.TrimSpace(partialContent) == "" || partialContent == lastPartialContent { + return + } // Advance the throttle window before I/O so a failing DingTalk API // cannot be hammered once per model chunk. The final update below is // always attempted regardless of this timestamp. lastUpdate = now - if updateErr := streamingCard.UpdateCard(ctx, outTrackID, fullContent, false, false); updateErr != nil { + if updateErr := streamingCard.UpdateCard(ctx, outTrackID, partialContent, false, false); updateErr != nil { log.Printf("DingTalk streaming card update failed, continuing") + return } + lastPartialContent = partialContent } } result, err := streamingQA.AskStream(ctx, req, observer) if err != nil || strings.TrimSpace(result.Answer) == "" { + logQAFailure("streaming", errOrEmptyAnswer(err, result.Answer)) return h.finalizeCardOrMarkdown(ctx, webhookURL, streamingCard, outTrackID, core.QAResult{}, qaErrorReply, true) } return h.finalizeCardOrMarkdown(ctx, webhookURL, streamingCard, outTrackID, result, result.Answer, false) @@ -352,12 +533,14 @@ func (h *Handler) handleEventStreaming(ctx context.Context, webhookURL string, r log.Printf("DingTalk event card start failed, falling back to markdown") result, askErr := h.qa.Ask(ctx, req) if askErr != nil { + logQAFailure("event_fallback", askErr) return h.sendReply(ctx, webhookURL, qaErrorReply) } if result.Replayed && result.DeliveryStatus == core.DeliverySent { return nil } - if replyErr := h.sendReply(ctx, webhookURL, result.Answer); replyErr != nil { + content := h.rewriteOutboundContent(ctx, result.Answer) + if replyErr := h.sendReply(ctx, webhookURL, content); replyErr != nil { h.recordDelivery(ctx, result, core.DeliveryFailed, "", "", core.DeliveryFailureChannelDelivery) return replyErr } @@ -372,7 +555,10 @@ func (h *Handler) handleEventStreaming(ctx context.Context, webhookURL string, r result, err := eventQA.AskEvents(ctx, req, func(event weknora.StreamEvent) { if event.ResponseType == "answer" && strings.TrimSpace(event.FullAnswer) != "" { answerStarted = true - pump.Offer(event.FullAnswer) + visibleAnswer := decorateReasoningPartial(event.FullAnswer, req.ReasoningExecution) + if partialContent := h.sanitizeOutboundPartial(visibleAnswer); strings.TrimSpace(partialContent) != "" { + pump.Offer(partialContent) + } return } if answerStarted { @@ -387,17 +573,32 @@ func (h *Handler) handleEventStreaming(ctx context.Context, webhookURL string, r pump.Stop() if err != nil || strings.TrimSpace(result.Answer) == "" { + logQAFailure("event_streaming", errOrEmptyAnswer(err, result.Answer)) return h.finalizeCardOrMarkdown(ctx, webhookURL, streamingCard, outTrackID, core.QAResult{}, qaErrorReply, true) } return h.finalizeCardOrMarkdown(ctx, webhookURL, streamingCard, outTrackID, result, result.Answer, false) } +func decorateReasoningPartial(content, execution string) string { + switch reasoningmode.ExecutionMode(strings.TrimSpace(execution)) { + case reasoningmode.ExecutionReasoning, reasoningmode.ExecutionReasoningSingle: + if !strings.HasPrefix(content, "【智能推理模式】") { + return "【智能推理模式】\n\n" + content + } + } + return content +} + func (h *Handler) finalizeCardOrMarkdown(ctx context.Context, webhookURL string, streamingCard StreamingCardSender, outTrackID string, result core.QAResult, content string, isError bool) error { timeout := h.finalDeliveryTimeout if timeout <= 0 { timeout = defaultHTTPTimeout } + if !isError { + content = h.rewriteOutboundContent(ctx, content) + } + // Final card convergence must still be attempted when the QA context was // canceled or timed out; otherwise the card can remain "processing". finalCtx, cancelFinal := context.WithTimeout(context.WithoutCancel(ctx), timeout) @@ -426,6 +627,27 @@ func (h *Handler) finalizeCardOrMarkdown(ctx context.Context, webhookURL string, return nil } +func (h *Handler) rewriteOutboundContent(ctx context.Context, content string) string { + if h.outboundRewriter == nil { + return sanitizeDisplayAnswer(content) + } + timeout := h.finalDeliveryTimeout + if timeout <= 0 { + timeout = defaultHTTPTimeout + } + rewriteCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), timeout) + defer cancel() + return sanitizeDisplayAnswer(h.outboundRewriter.Rewrite(rewriteCtx, content)) +} + +func (h *Handler) sanitizeOutboundPartial(content string) string { + sanitizer, ok := h.outboundRewriter.(OutboundPartialSanitizer) + if ok { + content = sanitizer.SanitizePartial(content) + } + return stableMarkdownPrefix(sanitizeDisplayAnswer(content)) +} + func (h *Handler) recordDelivery(ctx context.Context, result core.QAResult, status, method, providerMessageID, failureCode string) { if strings.TrimSpace(result.TurnID) == "" || strings.TrimSpace(result.AnswerMessageID) == "" { return @@ -477,6 +699,50 @@ func renderProgressEvent(event weknora.StreamEvent) string { return "" } +func errOrEmptyAnswer(err error, answer string) error { + if err != nil { + return err + } + if strings.TrimSpace(answer) == "" { + return weknora.ErrEmptyAnswer + } + return nil +} + +func logQAFailure(mode string, err error) { + log.Printf("DingTalk QA failed: mode=%s stage=%s", mode, qaFailureStage(err)) +} + +func qaFailureStage(err error) string { + switch { + case err == nil: + return "unknown" + case errors.Is(err, context.Canceled): + return "context_canceled" + case errors.Is(err, context.DeadlineExceeded): + return "context_deadline" + case errors.Is(err, core.ErrTurnInProgress): + return "duplicate_or_in_progress" + case errors.Is(err, weknora.ErrEmptyAnswer): + return "empty_answer" + } + message := strings.ToLower(err.Error()) + switch { + case strings.Contains(message, "begin turn"): + return "begin_turn" + case strings.Contains(message, "agent") && strings.Contains(message, "binding"): + return "agent_binding" + case strings.Contains(message, "session"): + return "session" + case strings.Contains(message, "weknora agent chat"): + return "agent_chat" + case strings.Contains(message, "required") || strings.Contains(message, "unsupported"): + return "validation" + default: + return "unknown" + } +} + func imageFailureStage(err error) string { message := strings.ToLower(err.Error()) switch { @@ -504,3 +770,57 @@ func (h *Handler) sendReply(ctx context.Context, webhookURL, text string) error } return nil } + +// publishQuestionImage best-effort publishes a downloaded image's bytes to +// object storage for traceability. It returns the stable HTTPS URL, or an +// empty string when publishing is unavailable or fails, so that an image +// question is never blocked by storage. +func (h *Handler) publishQuestionImage(ctx context.Context, image core.ImageInput) string { + if h.imagePublisher == nil { + return "" + } + data, err := decodeImageDataURI(image.DataURI) + if err != nil || len(data) == 0 { + log.Printf("DingTalk question image publish failed: stage=decode") + return "" + } + url, err := h.imagePublisher.Publish(ctx, data, image.MIMEType) + if err != nil || strings.TrimSpace(url) == "" { + log.Printf("DingTalk question image publish failed: stage=publish") + return "" + } + return strings.TrimSpace(url) +} + +// decodeImageDataURI strips the "data:;base64," prefix and decodes the +// payload into raw bytes. It is used only to publish inbound images and never +// writes the data URI to storage. +func decodeImageDataURI(dataURI string) ([]byte, error) { + const prefix = "base64," + index := strings.Index(dataURI, prefix) + if index < 0 { + return nil, errors.New("dingtalk image: data URI missing base64 payload") + } + return base64.StdEncoding.DecodeString(dataURI[index+len(prefix):]) +} + +// effectiveDownloadCodes returns the ordered, de-duplicated list of image +// download codes for a picture callback. DownloadCode equals the first code +// and DownloadCodes holds every code (richText with several pictures), so the +// single value is used to canonicalize the order without duplication. +func effectiveDownloadCodes(cb BotCallback) []string { + var codes []string + seen := make(map[string]struct{}) + for _, code := range append([]string{cb.DownloadCode}, cb.DownloadCodes...) { + code = strings.TrimSpace(code) + if code == "" { + continue + } + if _, ok := seen[code]; ok { + continue + } + seen[code] = struct{}{} + codes = append(codes, code) + } + return codes +} diff --git a/internal/channels/dingtalk/handler_test.go b/internal/channels/dingtalk/handler_test.go index 5814492..40ffff9 100644 --- a/internal/channels/dingtalk/handler_test.go +++ b/internal/channels/dingtalk/handler_test.go @@ -3,11 +3,13 @@ package dingtalk import ( "context" "errors" + "reflect" "strings" "testing" "time" "gitea.zheromiku.top/Weknora/dobotai-platform/internal/core" + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/directory" "gitea.zheromiku.top/Weknora/dobotai-platform/internal/weknora" ) @@ -31,6 +33,17 @@ func (f *fakeQA) RecordDelivery(_ context.Context, update core.DeliveryUpdate) e return f.deliveryErr } +type fakeDirectory struct { + profile directory.Profile + err error + calls int +} + +func (f *fakeDirectory) ResolveUser(context.Context, string, string, string) (directory.Profile, error) { + f.calls++ + return f.profile, f.err +} + type fakeReply struct { called bool lastURL string @@ -192,6 +205,44 @@ func TestHandleDirectTextCallsQAAndRepliesAnswer(t *testing.T) { } } +func TestHandleDirectUsesDirectoryProfile(t *testing.T) { + qa := &fakeQA{result: core.QAResult{Answer: "ok"}} + reply := &fakeReply{} + profiles := &fakeDirectory{profile: directory.Profile{Name: "张三", DepartmentName: "技术支持部", Region: "APAC"}} + h, err := NewHandlerWithOptions(TenantConfig{TenantKey: "tenant-a", Channel: "dingtalk"}, qa, reply, HandlerOptions{Directory: profiles}) + if err != nil { + t.Fatalf("NewHandlerWithOptions: %v", err) + } + data := directTextCallback() + data.SenderNick = "钉钉昵称" + if err := h.Handle(context.Background(), data); err != nil { + t.Fatalf("Handle: %v", err) + } + if profiles.calls != 1 || qa.lastReq.SenderName != "张三" || qa.lastReq.Department != "技术支持部" || qa.lastReq.Region != "APAC" { + t.Fatalf("calls=%d request=%+v", profiles.calls, qa.lastReq) + } +} + +// TestHandleDirectoryFailureFallsBackToSenderNick validates that when directory +// resolution fails, SenderName falls back to the callback SenderNick. +func TestHandleDirectoryFailureFallsBackToSenderNick(t *testing.T) { + qa := &fakeQA{result: core.QAResult{Answer: "ok"}} + reply := &fakeReply{} + profiles := &fakeDirectory{err: errors.New("directory unavailable")} + h, err := NewHandlerWithOptions(TenantConfig{TenantKey: "tenant-a", Channel: "dingtalk"}, qa, reply, HandlerOptions{Directory: profiles}) + if err != nil { + t.Fatalf("NewHandlerWithOptions: %v", err) + } + data := directTextCallback() + data.SenderNick = " 回调昵称 " + if err := h.Handle(context.Background(), data); err != nil { + t.Fatalf("Handle: %v", err) + } + if qa.lastReq.SenderName != "回调昵称" || qa.lastReq.Department != "" || qa.lastReq.Region != "" { + t.Fatalf("request=%+v", qa.lastReq) + } +} + func TestHandleDirectTextFallsBackToSenderID(t *testing.T) { qa := &fakeQA{result: core.QAResult{Answer: "ok"}} reply := &fakeReply{} @@ -676,6 +727,46 @@ func TestHandleCardSuccessDirectFieldsCorrectNoMarkdown(t *testing.T) { } } +func TestHandleNonStreamingRewritesFinalCardAndMarkdownFallback(t *testing.T) { + resource := "resource://AbCdEfGhIjKlMnOpQrStUv" + signed := "https://img.example/signed.jpg" + answer := "说明\n![图](" + resource + ")" + for _, tc := range []struct { + name string + cardErr error + wantReply bool + }{ + {name: "card"}, + {name: "markdown fallback", cardErr: errors.New("card failed"), wantReply: true}, + } { + t.Run(tc.name, func(t *testing.T) { + qa := &fakeQA{result: core.QAResult{Answer: answer}} + reply := &fakeReply{} + card := &fakeCard{returnID: "track", err: tc.cardErr} + h := newTestHandlerWithCard(t, qa, reply, card) + rewriter := &fakeOutboundRewriter{from: resource, to: signed} + h.outboundRewriter = rewriter + + if err := h.Handle(context.Background(), directTextCallback()); err != nil { + t.Fatal(err) + } + if !card.called || reply.called != tc.wantReply { + t.Fatalf("card=%t reply=%t", card.called, reply.called) + } + content := card.lastReq.Content + if tc.wantReply { + content = reply.lastText + } + if strings.Contains(content, resource) || !strings.Contains(content, signed) { + t.Fatalf("outbound content=%q", content) + } + if rewriter.calls != 1 { + t.Fatalf("rewrite calls=%d, want 1", rewriter.calls) + } + }) + } +} + func TestHandleCardSuccessGroupChatIDCorrect(t *testing.T) { qa := &fakeQA{result: core.QAResult{Answer: "group card answer"}} reply := &fakeReply{} @@ -890,6 +981,23 @@ type cardUpdate struct { isError bool } +type fakeOutboundRewriter struct { + calls int + partialCalls int + from string + to string +} + +func (f *fakeOutboundRewriter) Rewrite(_ context.Context, content string) string { + f.calls++ + return strings.ReplaceAll(content, f.from, f.to) +} + +func (f *fakeOutboundRewriter) SanitizePartial(content string) string { + f.partialCalls++ + return strings.ReplaceAll(content, f.from, "") +} + func (f *fakeStreamingCard) SendFinalCard(_ context.Context, req CardRequest) (string, error) { f.finalCalled = true f.finalReq = req @@ -1073,11 +1181,14 @@ func TestHandleStreamingThrottleClockAdvances(t *testing.T) { func TestHandleStreamingStartFailsFallbackAskMarkdown(t *testing.T) { card := &fakeStreamingCard{startErr: errors.New("card API unavailable")} + resource := "resource://AbCdEfGhIjKlMnOpQrStUv" qa := &fakeStreamingQA{ - result: core.QAResult{Answer: "**fallback markdown**"}, + result: core.QAResult{Answer: "**fallback markdown**\n![图](" + resource + ")"}, } reply := &fakeReply{} h := newTestHandlerWithStreaming(t, qa, reply, card) + rewriter := &fakeOutboundRewriter{from: resource, to: "https://img.example/signed.jpg"} + h.outboundRewriter = rewriter err := h.Handle(context.Background(), directTextCallback()) if err != nil { @@ -1106,8 +1217,11 @@ func TestHandleStreamingStartFailsFallbackAskMarkdown(t *testing.T) { if !reply.called { t.Fatal("SendMarkdown must be called on Start failure") } - if reply.lastText != "**fallback markdown**" { - t.Fatalf("markdown text = %q, want fallback markdown", reply.lastText) + if strings.Contains(reply.lastText, resource) || !strings.Contains(reply.lastText, "https://img.example/signed.jpg") { + t.Fatalf("markdown text = %q, want rewritten fallback markdown", reply.lastText) + } + if rewriter.calls != 1 { + t.Fatalf("rewrite calls=%d, want 1", rewriter.calls) } // No card updates @@ -1561,15 +1675,16 @@ func TestRenderProgressEventUsesOnlySafeFixedText(t *testing.T) { } func TestHandleEventStreamingFinalizesLatestAnswerWithoutMarkdown(t *testing.T) { + rawAnswer := "完整答案[[ref id=\"c8\"]]" card := &fakeStreamingCard{startID: "track-events"} qa := &fakeEventQA{ - fakeStreamingQA: fakeStreamingQA{result: core.QAResult{Answer: "完整答案"}}, + fakeStreamingQA: fakeStreamingQA{result: core.QAResult{Answer: rawAnswer}}, events: []weknora.StreamEvent{ {ResponseType: "tool_call", ToolName: "query_understand"}, {ResponseType: "tool_call", ToolName: "knowledge_search"}, {ResponseType: "references", ReferenceCount: 3}, - {ResponseType: "answer", FullAnswer: "部分"}, - {ResponseType: "answer", FullAnswer: "完整答案", Done: true}, + {ResponseType: "answer", FullAnswer: "部分[[ref"}, + {ResponseType: "answer", FullAnswer: rawAnswer, Done: true}, }, } reply := &fakeReply{} @@ -1591,6 +1706,9 @@ func TestHandleEventStreamingFinalizesLatestAnswerWithoutMarkdown(t *testing.T) if last.content != "完整答案" || !last.isFinalize || last.isError { t.Fatalf("final update=%+v", last) } + if qa.result.Answer != rawAnswer { + t.Fatalf("raw QA answer mutated: %q", qa.result.Answer) + } if reply.called { t.Fatal("SendMarkdown must not be called") } @@ -1796,3 +1914,313 @@ func TestDeliveryAuditEventStreamingProductionPath(t *testing.T) { } requireDelivery(t, qa.deliveries, core.DeliverySent, core.DeliveryMethodCard, "event-track-1", "") } + +func TestHandlePassesConversationTitleToQARequest(t *testing.T) { + qa := &fakeQA{result: core.QAResult{Answer: "ok"}} + reply := &fakeReply{} + h := newTestHandler(t, qa, reply) + + t.Run("group conversation title propagated", func(t *testing.T) { + cb := groupTextCallback() + cb.ConversationTitle = "项目讨论群" + if err := h.Handle(context.Background(), cb); err != nil { + t.Fatalf("Handle: %v", err) + } + if qa.lastReq.ConversationTitle != "项目讨论群" { + t.Fatalf("ConversationTitle = %q, want 项目讨论群", qa.lastReq.ConversationTitle) + } + }) + + t.Run("direct conversation title is empty", func(t *testing.T) { + qa2 := &fakeQA{result: core.QAResult{Answer: "ok"}} + h2 := newTestHandler(t, qa2, &fakeReply{}) + cb := directTextCallback() + cb.ConversationTitle = "should not appear" + if err := h2.Handle(context.Background(), cb); err != nil { + t.Fatalf("Handle: %v", err) + } + if qa2.lastReq.ConversationTitle != "" { + t.Fatalf("ConversationTitle = %q, want empty for direct", qa2.lastReq.ConversationTitle) + } + }) +} + +// TestActorUnionIDSnapshotPropagation verifies the actor_union_id_snapshot +// is populated from the directory profile UnionID when available. +func TestActorUnionIDSnapshotPropagation(t *testing.T) { + t.Run("resolved profile with union ID captures snapshot", func(t *testing.T) { + qa := &fakeQA{result: core.QAResult{Answer: "ok"}} + reply := &fakeReply{} + profiles := &fakeDirectory{profile: directory.Profile{ + Name: "张三", UnionID: "union-abc-123", DepartmentName: "技术部", Region: "APAC", + }} + h, err := NewHandlerWithOptions(TenantConfig{TenantKey: "tenant-a", Channel: "dingtalk"}, qa, reply, HandlerOptions{Directory: profiles}) + if err != nil { + t.Fatalf("NewHandlerWithOptions: %v", err) + } + data := directTextCallback() + data.SenderNick = "钉钉昵称" + if err := h.Handle(context.Background(), data); err != nil { + t.Fatalf("Handle: %v", err) + } + if qa.lastReq.ActorUnionIDSnapshot != "union-abc-123" { + t.Fatalf("ActorUnionIDSnapshot = %q, want union-abc-123", qa.lastReq.ActorUnionIDSnapshot) + } + if qa.lastReq.SenderName != "张三" { + t.Fatalf("SenderName = %q, want 张三", qa.lastReq.SenderName) + } + if qa.lastReq.TriggerPersonSnapshot != "钉钉昵称" { + t.Fatalf("TriggerPersonSnapshot = %q, want 钉钉昵称", qa.lastReq.TriggerPersonSnapshot) + } + }) + + t.Run("blank profile union leaves snapshot empty", func(t *testing.T) { + qa := &fakeQA{result: core.QAResult{Answer: "ok"}} + reply := &fakeReply{} + profiles := &fakeDirectory{profile: directory.Profile{ + Name: "张三", UnionID: "", DepartmentName: "技术部", Region: "APAC", + }} + h, err := NewHandlerWithOptions(TenantConfig{TenantKey: "tenant-a", Channel: "dingtalk"}, qa, reply, HandlerOptions{Directory: profiles}) + if err != nil { + t.Fatalf("NewHandlerWithOptions: %v", err) + } + data := directTextCallback() + data.SenderNick = "钉钉昵称" + if err := h.Handle(context.Background(), data); err != nil { + t.Fatalf("Handle: %v", err) + } + if qa.lastReq.ActorUnionIDSnapshot != "" { + t.Fatalf("ActorUnionIDSnapshot = %q, want empty", qa.lastReq.ActorUnionIDSnapshot) + } + }) + + t.Run("directory failure leaves union snapshot empty", func(t *testing.T) { + qa := &fakeQA{result: core.QAResult{Answer: "ok"}} + reply := &fakeReply{} + profiles := &fakeDirectory{err: errors.New("directory unavailable")} + h, err := NewHandlerWithOptions(TenantConfig{TenantKey: "tenant-a", Channel: "dingtalk"}, qa, reply, HandlerOptions{Directory: profiles}) + if err != nil { + t.Fatalf("NewHandlerWithOptions: %v", err) + } + data := directTextCallback() + data.SenderNick = "钉钉昵称" + if err := h.Handle(context.Background(), data); err != nil { + t.Fatalf("Handle: %v", err) + } + if qa.lastReq.ActorUnionIDSnapshot != "" { + t.Fatalf("ActorUnionIDSnapshot = %q, want empty on directory failure", qa.lastReq.ActorUnionIDSnapshot) + } + }) + + t.Run("no directory leaves union snapshot empty", func(t *testing.T) { + qa := &fakeQA{result: core.QAResult{Answer: "ok"}} + reply := &fakeReply{} + h := newTestHandler(t, qa, reply) + data := directTextCallback() + data.SenderNick = "钉钉昵称" + if err := h.Handle(context.Background(), data); err != nil { + t.Fatalf("Handle: %v", err) + } + if qa.lastReq.ActorUnionIDSnapshot != "" { + t.Fatalf("ActorUnionIDSnapshot = %q, want empty without directory", qa.lastReq.ActorUnionIDSnapshot) + } + }) +} + +// TestTriggerPersonSnapshotRegression proves the trigger_person_snapshot +// contract: the callback SenderNick becomes TriggerPersonSnapshot, the +// directory official Name remains SenderName, and a blank callback nick +// falls back to the official name. +func TestTriggerPersonSnapshotRegression(t *testing.T) { + t.Run("callback nick becomes trigger person snapshot", func(t *testing.T) { + qa := &fakeQA{result: core.QAResult{Answer: "ok"}} + reply := &fakeReply{} + profiles := &fakeDirectory{profile: directory.Profile{Name: "张三", DepartmentName: "技术部", Region: "APAC"}} + h, err := NewHandlerWithOptions(TenantConfig{TenantKey: "tenant-a", Channel: "dingtalk"}, qa, reply, HandlerOptions{Directory: profiles}) + if err != nil { + t.Fatalf("NewHandlerWithOptions: %v", err) + } + data := directTextCallback() + data.SenderNick = "钉钉昵称" + if err := h.Handle(context.Background(), data); err != nil { + t.Fatalf("Handle: %v", err) + } + if qa.lastReq.TriggerPersonSnapshot != "钉钉昵称" { + t.Fatalf("TriggerPersonSnapshot = %q, want 钉钉昵称", qa.lastReq.TriggerPersonSnapshot) + } + if qa.lastReq.SenderName != "张三" { + t.Fatalf("SenderName = %q, want 张三", qa.lastReq.SenderName) + } + }) + + t.Run("blank callback nick falls back to official name", func(t *testing.T) { + qa := &fakeQA{result: core.QAResult{Answer: "ok"}} + reply := &fakeReply{} + profiles := &fakeDirectory{profile: directory.Profile{Name: "张三", DepartmentName: "技术部", Region: "APAC"}} + h, err := NewHandlerWithOptions(TenantConfig{TenantKey: "tenant-a", Channel: "dingtalk"}, qa, reply, HandlerOptions{Directory: profiles}) + if err != nil { + t.Fatalf("NewHandlerWithOptions: %v", err) + } + data := directTextCallback() + data.SenderNick = "" + if err := h.Handle(context.Background(), data); err != nil { + t.Fatalf("Handle: %v", err) + } + if qa.lastReq.TriggerPersonSnapshot != "张三" { + t.Fatalf("TriggerPersonSnapshot = %q, want 张三 on blank nick", qa.lastReq.TriggerPersonSnapshot) + } + if qa.lastReq.SenderName != "张三" { + t.Fatalf("SenderName = %q, want 张三", qa.lastReq.SenderName) + } + }) +} + +func TestHandleStreamingRewritesOnlyFinalOutboundImageContent(t *testing.T) { + card := &fakeStreamingCard{startID: "track-image-final"} + resource := "resource://AbCdEfGhIjKlMnOpQrStUv" + answer := "操作说明\n![步骤图](" + resource + ")" + qa := &fakeStreamingQA{chunks: []string{answer}, result: core.QAResult{Answer: answer}} + reply := &fakeReply{} + rewriter := &fakeOutboundRewriter{from: resource, to: "https://img.example/signed.jpg"} + h := newTestHandlerWithStreaming(t, qa, reply, card) + h.outboundRewriter = rewriter + + if err := h.Handle(context.Background(), directTextCallback()); err != nil { + t.Fatal(err) + } + if len(card.updates) < 2 { + t.Fatalf("updates=%d", len(card.updates)) + } + if strings.Contains(card.updates[0].content, resource) { + t.Fatalf("streaming intermediate content leaked internal resource: %q", card.updates[0].content) + } + final := card.updates[len(card.updates)-1] + if !final.isFinalize || strings.Contains(final.content, resource) || !strings.Contains(final.content, "https://img.example/signed.jpg") { + t.Fatalf("final content=%q finalize=%t", final.content, final.isFinalize) + } + if rewriter.calls != 1 { + t.Fatalf("rewrite calls=%d, want 1", rewriter.calls) + } + if rewriter.partialCalls == 0 { + t.Fatal("streaming intermediate content was not sanitized") + } +} + +func TestHandleFiltersReferenceMarkersAtDingTalkDisplayBoundary(t *testing.T) { + rawAnswer := "结论[[ref id=\"c2\"]][[ref id=\"c4\"]]。" + wantDisplay := "结论。" + + t.Run("final card", func(t *testing.T) { + qa := &fakeQA{result: core.QAResult{Answer: rawAnswer}} + reply := &fakeReply{} + card := &fakeCard{returnID: "track-reference-filter"} + h := newTestHandlerWithCard(t, qa, reply, card) + + if err := h.Handle(context.Background(), directTextCallback()); err != nil { + t.Fatal(err) + } + if card.lastReq.Content != wantDisplay { + t.Fatalf("card content=%q, want %q", card.lastReq.Content, wantDisplay) + } + if qa.result.Answer != rawAnswer { + t.Fatalf("raw QA answer mutated: %q", qa.result.Answer) + } + }) + + t.Run("markdown fallback", func(t *testing.T) { + qa := &fakeQA{result: core.QAResult{Answer: rawAnswer}} + reply := &fakeReply{} + card := &fakeCard{err: errors.New("card unavailable")} + h := newTestHandlerWithCard(t, qa, reply, card) + + if err := h.Handle(context.Background(), directTextCallback()); err != nil { + t.Fatal(err) + } + if reply.lastText != wantDisplay { + t.Fatalf("markdown content=%q, want %q", reply.lastText, wantDisplay) + } + if qa.result.Answer != rawAnswer { + t.Fatalf("raw QA answer mutated: %q", qa.result.Answer) + } + }) +} + +func TestHandleStreamingHoldsBackPartialReferenceMarkers(t *testing.T) { + rawAnswer := "答案正文[[ref id=\"c2\"]]继续。" + qa := &fakeStreamingQA{ + chunks: []string{"答案正文[[ref", " id=\"c2\"]]继续。"}, + result: core.QAResult{Answer: rawAnswer}, + } + reply := &fakeReply{} + card := &fakeStreamingCard{startID: "track-stream-reference-filter"} + h := newTestHandlerWithStreaming(t, qa, reply, card) + + if err := h.Handle(context.Background(), directTextCallback()); err != nil { + t.Fatal(err) + } + if len(card.updates) < 2 { + t.Fatalf("updates=%d, want at least one partial plus final", len(card.updates)) + } + for i, update := range card.updates { + if strings.Contains(update.content, "[[ref") { + t.Fatalf("update[%d] leaked reference marker: %q", i, update.content) + } + } + if card.updates[0].content != "答案正文" { + t.Fatalf("first partial=%q, want dangling marker held back", card.updates[0].content) + } + final := card.updates[len(card.updates)-1] + if !final.isFinalize || final.content != "答案正文继续。" { + t.Fatalf("final content=%q finalize=%t", final.content, final.isFinalize) + } + if qa.result.Answer != rawAnswer { + t.Fatalf("raw QA answer mutated: %q", qa.result.Answer) + } +} + +func TestHandleStreamingPublishesTableOnlyOnFinalUpdate(t *testing.T) { + answer := "说明\n\n| 检查项 | 操作要求 |\n| --- | --- |\n| 接地检查 | 上电前确认 |\n\n结论" + qa := &fakeStreamingQA{ + chunks: []string{ + "说明\n\n", + "| 检查项", + " | 操作要求 |\n", + "| --- | --", + "- |\n", + "| 接地检查 | 上电前确", + "认 |\n\n结论", + }, + result: core.QAResult{Answer: answer}, + } + reply := &fakeReply{} + card := &fakeStreamingCard{startID: "track-stream-table"} + h := newTestHandlerWithStreaming(t, qa, reply, card) + callCount := int64(0) + h.now = func() time.Time { + callCount++ + return time.Unix(0, callCount*int64(time.Second)) + } + h.cardUpdateInterval = time.Millisecond + + if err := h.Handle(context.Background(), directTextCallback()); err != nil { + t.Fatal(err) + } + + var partials []string + for _, update := range card.updates { + if !update.isFinalize { + partials = append(partials, update.content) + } + } + wantPartials := []string{"说明\n\n"} + if !reflect.DeepEqual(partials, wantPartials) { + t.Fatalf("partial updates=%q, want only pre-table stream %q", partials, wantPartials) + } + final := card.updates[len(card.updates)-1] + if !final.isFinalize || final.content != answer { + t.Fatalf("final=%+v, want unchanged complete answer", final) + } + if qa.result.Answer != answer { + t.Fatalf("raw QA answer mutated: %q", qa.result.Answer) + } +} diff --git a/internal/channels/dingtalk/image_publish_test.go b/internal/channels/dingtalk/image_publish_test.go new file mode 100644 index 0000000..7f158a3 --- /dev/null +++ b/internal/channels/dingtalk/image_publish_test.go @@ -0,0 +1,80 @@ +package dingtalk + +import ( + "context" + "encoding/base64" + "errors" + "testing" + + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/core" +) + +type fakeImagePublisher struct { + published []byte + mime string + url string + err error + calls int +} + +func (f *fakeImagePublisher) Publish(_ context.Context, data []byte, contentType string) (string, error) { + f.calls++ + f.published = data + f.mime = contentType + return f.url, f.err +} + +func TestDecodeImageDataURI(t *testing.T) { + raw := []byte("hello-image-bytes") + uri := "data:image/png;base64," + base64.StdEncoding.EncodeToString(raw) + + decoded, err := decodeImageDataURI(uri) + if err != nil { + t.Fatalf("decodeImageDataURI: %v", err) + } + if string(decoded) != string(raw) { + t.Fatalf("decoded=%q, want %q", decoded, raw) + } + + if _, err := decodeImageDataURI("data:image/png;base64"); err == nil { + t.Fatal("expected error for missing base64 payload") + } + if _, err := decodeImageDataURI("no comma at all"); err == nil { + t.Fatal("expected error for non-data URI") + } +} + +func TestPublishQuestionImagePublishesDecodedBytes(t *testing.T) { + pub := &fakeImagePublisher{url: "https://weknora-api.example/i/001"} + raw := []byte{0x89, 0x50, 0x4e, 0x47} + image := core.ImageInput{ + DataURI: "data:image/png;base64," + base64.StdEncoding.EncodeToString(raw), + MIMEType: "image/png", + } + h := &Handler{imagePublisher: pub} + + got := h.publishQuestionImage(context.Background(), image) + if got != "https://weknora-api.example/i/001" { + t.Fatalf("url=%q, want published", got) + } + if pub.calls != 1 || pub.mime != "image/png" || string(pub.published) != string(raw) { + t.Fatalf("publisher calls=%d mime=%q bytes=%q", pub.calls, pub.mime, pub.published) + } +} + +func TestPublishQuestionImageFailsClosedWithoutURL(t *testing.T) { + h := &Handler{imagePublisher: nil} + if got := h.publishQuestionImage(context.Background(), core.ImageInput{}); got != "" { + t.Fatalf("expected empty URL without publisher, got %q", got) + } + + pub := &fakeImagePublisher{err: errors.New("oss down")} + h2 := &Handler{imagePublisher: pub} + image := core.ImageInput{ + DataURI: "data:image/png;base64," + base64.StdEncoding.EncodeToString([]byte("x")), + MIMEType: "image/png", + } + if got := h2.publishQuestionImage(context.Background(), image); got != "" { + t.Fatalf("expected empty URL on publish error, got %q", got) + } +} \ No newline at end of file diff --git a/internal/channels/dingtalk/markdown_stream.go b/internal/channels/dingtalk/markdown_stream.go new file mode 100644 index 0000000..1830f70 --- /dev/null +++ b/internal/channels/dingtalk/markdown_stream.go @@ -0,0 +1,114 @@ +package dingtalk + +import "strings" + +type markdownStreamLine struct { + start int + text string + inFence bool +} + +// stableMarkdownPrefix returns the cumulative content that is safe to render +// while Markdown is still streaming. Once a table is confirmed, the table and +// every following token stay hidden until the terminal card update. +func stableMarkdownPrefix(content string) string { + lines := splitMarkdownStreamLines(content) + for i := 0; i < len(lines); i++ { + if lines[i].inFence || !isTableHeaderCandidate(lines[i].text) { + continue + } + + if i == len(lines)-1 { + return content[:lines[i].start] + } + if lines[i+1].inFence || !isTableDelimiterCandidate(lines[i+1].text) { + continue + } + if !isCompleteTableDelimiter(lines[i+1].text) { + return content[:lines[i].start] + } + // DingTalk only lays out Markdown tables reliably on the terminal + // isFinalize=true update. Keep the table and every following partial + // token hidden; the authoritative final update bypasses this helper. + return content[:lines[i].start] + } + return content +} + +func splitMarkdownStreamLines(content string) []markdownStreamLine { + lines := make([]markdownStreamLine, 0, strings.Count(content, "\n")+1) + fence := "" + for start := 0; start < len(content); { + end := strings.IndexByte(content[start:], '\n') + if end < 0 { + end = len(content) + } else { + end += start + 1 + } + text := strings.TrimSuffix(content[start:end], "\n") + text = strings.TrimSuffix(text, "\r") + trimmed := strings.TrimSpace(text) + line := markdownStreamLine{start: start, text: text, inFence: fence != ""} + + if marker := markdownFenceMarker(trimmed); marker != "" { + line.inFence = true + if fence == "" { + fence = marker + } else if marker == fence { + fence = "" + } + } + lines = append(lines, line) + start = end + } + return lines +} + +func markdownFenceMarker(trimmed string) string { + switch { + case strings.HasPrefix(trimmed, "```"): + return "```" + case strings.HasPrefix(trimmed, "~~~"): + return "~~~" + default: + return "" + } +} + +func isTableHeaderCandidate(line string) bool { + return strings.HasPrefix(strings.TrimSpace(line), "|") +} + +func isTableDelimiterCandidate(line string) bool { + trimmed := strings.TrimSpace(line) + if !strings.HasPrefix(trimmed, "|") { + return false + } + for _, r := range trimmed { + switch r { + case '|', ':', '-', ' ', '\t': + default: + return false + } + } + return true +} + +func isCompleteTableDelimiter(line string) bool { + trimmed := strings.TrimSpace(line) + trimmed = strings.TrimPrefix(trimmed, "|") + trimmed = strings.TrimSuffix(trimmed, "|") + cells := strings.Split(trimmed, "|") + if len(cells) < 2 { + return false + } + for _, cell := range cells { + cell = strings.TrimSpace(cell) + cell = strings.TrimPrefix(cell, ":") + cell = strings.TrimSuffix(cell, ":") + if len(cell) < 3 || strings.Trim(cell, "-") != "" { + return false + } + } + return true +} diff --git a/internal/channels/dingtalk/markdown_stream_handler_test.go b/internal/channels/dingtalk/markdown_stream_handler_test.go new file mode 100644 index 0000000..212f9f0 --- /dev/null +++ b/internal/channels/dingtalk/markdown_stream_handler_test.go @@ -0,0 +1,65 @@ +package dingtalk + +import ( + "context" + "reflect" + "testing" + "time" + + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/core" + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/weknora" +) + +type pacedTableEventQA struct { + fakeStreamingQA + events []weknora.StreamEvent + pause time.Duration +} + +func (f *pacedTableEventQA) AskEvents(_ context.Context, req core.QARequest, observer weknora.StreamObserver) (core.QAResult, error) { + f.lastReq = req + for _, event := range f.events { + if observer != nil { + observer(event) + } + time.Sleep(f.pause) + } + return f.result, f.err +} + +func TestHandleEventStreamingPublishesTableOnlyOnFinalUpdate(t *testing.T) { + answer := "说明\n\n| 检查项 | 操作要求 |\n| --- | --- |\n| 接地检查 | 上电前确认 |\n\n结论" + qa := &pacedTableEventQA{ + fakeStreamingQA: fakeStreamingQA{result: core.QAResult{Answer: answer}}, + events: []weknora.StreamEvent{ + {ResponseType: "answer", FullAnswer: "说明\n\n"}, + {ResponseType: "answer", FullAnswer: "说明\n\n| 检查项"}, + {ResponseType: "answer", FullAnswer: "说明\n\n| 检查项 | 操作要求 |\n| --- | --"}, + {ResponseType: "answer", FullAnswer: answer, Done: true}, + }, + pause: 20 * time.Millisecond, + } + reply := &fakeReply{} + card := &fakeStreamingCard{startID: "track-event-table"} + h := newTestHandlerWithStreaming(t, qa, reply, card) + h.cardUpdateInterval = time.Millisecond + + if err := h.Handle(context.Background(), directTextCallback()); err != nil { + t.Fatal(err) + } + + var partials []string + for _, update := range card.updates { + if !update.isFinalize { + partials = append(partials, update.content) + } + } + wantPartials := []string{"说明\n\n"} + if !reflect.DeepEqual(partials, wantPartials) { + t.Fatalf("event partial updates=%q, want only pre-table stream %q", partials, wantPartials) + } + final := card.updates[len(card.updates)-1] + if !final.isFinalize || final.content != answer { + t.Fatalf("final=%+v, want unchanged complete answer", final) + } +} diff --git a/internal/channels/dingtalk/markdown_stream_test.go b/internal/channels/dingtalk/markdown_stream_test.go new file mode 100644 index 0000000..7ff1330 --- /dev/null +++ b/internal/channels/dingtalk/markdown_stream_test.go @@ -0,0 +1,101 @@ +package dingtalk + +import "testing" + +func TestStableMarkdownPrefixHoldsCompletedTableUntilFinalization(t *testing.T) { + content := "说明\n\n| 检查项 | 操作要求 |\n| --- | --- |\n| 接地检查 | 上电前确认 |\n\n表后正文仍在生成" + want := "说明\n\n" + + if got := stableMarkdownPrefix(content); got != want { + t.Fatalf("stableMarkdownPrefix()=%q, want table and trailing stream held as %q", got, want) + } +} + +func TestStableMarkdownPrefixHoldsBackTableUntilFinalization(t *testing.T) { + tests := []struct { + name string + content string + want string + }{ + { + name: "split header", + content: "说明\n\n| 检查项", + want: "说明\n\n", + }, + { + name: "header waiting for delimiter", + content: "说明\n\n| 检查项 | 操作要求 |\n", + want: "说明\n\n", + }, + { + name: "partial delimiter", + content: "说明\n\n| 检查项 | 操作要求 |\n| --- | --", + want: "说明\n\n", + }, + { + name: "partial data row", + content: "说明\n\n| 检查项 | 操作要求 |\n| --- | --- |\n| 接地检查 | 上电前确", + want: "说明\n\n", + }, + { + name: "complete table without terminator", + content: "说明\n\n| 检查项 | 操作要求 |\n| --- | --- |\n| 接地检查 | 上电前确认 |\n", + want: "说明\n\n", + }, + { + name: "complete table followed by blank line", + content: "说明\n\n| 检查项 | 操作要求 |\n| --- | --- |\n| 接地检查 | 上电前确认 |\n\n后文", + want: "说明\n\n", + }, + { + name: "complete table followed by heading", + content: "| 检查项 | 操作要求 |\n| --- | --- |\n| 接地检查 | 上电前确认 |\n## 后续", + want: "", + }, + { + name: "second consecutive table remains hidden", + content: "| A | B |\n| --- | --- |\n| 1 | 2 |\n\n| C | D", + want: "", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := stableMarkdownPrefix(tt.content); got != tt.want { + t.Fatalf("stableMarkdownPrefix()=%q, want %q", got, tt.want) + } + }) + } +} + +func TestStableMarkdownPrefixLeavesNonTablesUnchanged(t *testing.T) { + tests := []struct { + name string + content string + }{ + { + name: "ordinary text", + content: "普通段落继续流式显示。", + }, + { + name: "ordinary inline pipe", + content: "状态使用 ready | running | done 表示。", + }, + { + name: "pipe inside fenced code", + content: "```text\n| 这不是 | 表格 |\n| --- | --- |\n```", + }, + { + name: "completed prose line starting with pipe", + content: "| 这是引用样式文本\n下一段普通文字", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := stableMarkdownPrefix(tt.content); got != tt.content { + t.Fatalf("stableMarkdownPrefix()=%q, want unchanged %q", got, tt.content) + } + }) + } +} diff --git a/internal/channels/dingtalk/reasoning_partial_test.go b/internal/channels/dingtalk/reasoning_partial_test.go new file mode 100644 index 0000000..e698f1c --- /dev/null +++ b/internal/channels/dingtalk/reasoning_partial_test.go @@ -0,0 +1,21 @@ +package dingtalk + +import ( + "testing" + + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/reasoningmode" +) + +func TestDecorateReasoningPartialMarksReasoningFromFirstChunk(t *testing.T) { + got := decorateReasoningPartial("部分答案", string(reasoningmode.ExecutionReasoning)) + want := "【智能推理模式】\n\n部分答案" + if got != want { + t.Fatalf("got=%q want=%q", got, want) + } +} + +func TestDecorateReasoningPartialLeavesQuickAnswerUnchanged(t *testing.T) { + if got := decorateReasoningPartial("快速答案", string(reasoningmode.ExecutionQuick)); got != "快速答案" { + t.Fatalf("got=%q", got) + } +} diff --git a/internal/channels/dingtalk/reasoning_route_test.go b/internal/channels/dingtalk/reasoning_route_test.go new file mode 100644 index 0000000..db3b09f --- /dev/null +++ b/internal/channels/dingtalk/reasoning_route_test.go @@ -0,0 +1,81 @@ +package dingtalk + +import ( + "context" + "testing" + + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/core" + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/reasoningmode" +) + +type fakeReasoningRouter struct { + called bool + message ReasoningMessage + decision ReasoningDecision + err error +} + +func (f *fakeReasoningRouter) Prepare(_ context.Context, message ReasoningMessage) (ReasoningDecision, error) { + f.called = true + f.message = message + return f.decision, f.err +} + +func TestReasoningControlCommandBypassesQA(t *testing.T) { + qa := &fakeQA{} + reply := &fakeReply{} + router := &fakeReasoningRouter{decision: ReasoningDecision{Handled: true, Reply: "mode enabled"}} + handler, err := NewHandlerWithOptions( + TenantConfig{TenantKey: "tenant-a", Channel: "dingtalk"}, + qa, + reply, + HandlerOptions{ReasoningRouter: router}, + ) + if err != nil { + t.Fatal(err) + } + callback := directTextCallback() + callback.Text = "/think on" + if err = handler.Handle(context.Background(), callback); err != nil { + t.Fatal(err) + } + if !router.called || router.message.StaffID != "staff-123" || router.message.Text != "/think on" { + t.Fatalf("router=%+v", router) + } + if qa.called { + t.Fatal("reasoning control command must bypass QA") + } + if !reply.called || reply.lastText != "mode enabled" { + t.Fatalf("reply=%+v", reply) + } +} + +func TestReasoningRouteAppliesQueryAgentAndExecutionToQARequest(t *testing.T) { + qa := &fakeQA{result: core.QAResult{TurnID: "turn-1", AnswerMessageID: "answer-1", Answer: "结果"}} + reply := &fakeReply{} + router := &fakeReasoningRouter{decision: ReasoningDecision{ + Query: "分析根因", AgentID: "builtin-smart-reasoning", + Execution: reasoningmode.ExecutionReasoningSingle, Expired: true, + }} + handler, err := NewHandlerWithOptions( + TenantConfig{TenantKey: "tenant-a", Channel: "dingtalk"}, + qa, + reply, + HandlerOptions{ReasoningRouter: router}, + ) + if err != nil { + t.Fatal(err) + } + callback := directTextCallback() + callback.Text = "/think 分析根因" + if err = handler.Handle(context.Background(), callback); err != nil { + t.Fatal(err) + } + if !qa.called { + t.Fatal("single-turn reasoning must call QA") + } + if qa.lastReq.Query != "分析根因" || qa.lastReq.AgentIDOverride != "builtin-smart-reasoning" || + qa.lastReq.ReasoningExecution != string(reasoningmode.ExecutionReasoningSingle) || !qa.lastReq.ReasoningExpired { + t.Fatalf("QA request=%+v", qa.lastReq) + } +} diff --git a/internal/channels/dingtalk/settings_route_test.go b/internal/channels/dingtalk/settings_route_test.go new file mode 100644 index 0000000..49d6310 --- /dev/null +++ b/internal/channels/dingtalk/settings_route_test.go @@ -0,0 +1,55 @@ +package dingtalk + +import ( + "context" + "testing" +) + +type fakeSettingsRouter struct { + called bool + handled bool + reply string +} + +func (f *fakeSettingsRouter) Handle(_ context.Context, in SettingsMessage) (bool, string, error) { + f.called = true + if in.StaffID != "staff-123" { + panic("wrong identity") + } + return f.handled, f.reply, nil +} +func TestSettingsCommandBypassesQA(t *testing.T) { + qa := &fakeQA{} + reply := &fakeReply{} + router := &fakeSettingsRouter{handled: true, reply: "settings menu"} + h, err := NewHandlerWithOptions(TenantConfig{TenantKey: "tenant-a", Channel: "dingtalk"}, qa, reply, HandlerOptions{SettingsRouter: router}) + if err != nil { + t.Fatal(err) + } + cb := directTextCallback() + cb.Text = "/setting" + if err = h.Handle(context.Background(), cb); err != nil { + t.Fatal(err) + } + if !router.called { + t.Fatal("router not called") + } + if qa.called { + t.Fatal("settings must bypass QA") + } + if !reply.called || reply.lastText != "settings menu" { + t.Fatalf("reply=%+v", reply) + } +} +func TestOrdinaryQuestionStillCallsQA(t *testing.T) { + qa := &fakeQA{} + reply := &fakeReply{} + router := &fakeSettingsRouter{} + h, _ := NewHandlerWithOptions(TenantConfig{TenantKey: "tenant-a", Channel: "dingtalk"}, qa, reply, HandlerOptions{SettingsRouter: router}) + if err := h.Handle(context.Background(), directTextCallback()); err != nil { + t.Fatal(err) + } + if !qa.called { + t.Fatal("ordinary question must call QA") + } +} diff --git a/internal/channels/dingtalk/stream.go b/internal/channels/dingtalk/stream.go index ec6858c..e6706ad 100644 --- a/internal/channels/dingtalk/stream.go +++ b/internal/channels/dingtalk/stream.go @@ -5,7 +5,11 @@ import ( "encoding/json" "errors" "fmt" + "log" + "net/url" "strings" + "sync" + "time" sdkcard "github.com/open-dingtalk/dingtalk-stream-sdk-go/card" "github.com/open-dingtalk/dingtalk-stream-sdk-go/chatbot" @@ -69,22 +73,37 @@ func BotCallbackFromSDK(data *chatbot.BotCallbackDataModel) (BotCallback, error) } msgtype := strings.ToLower(strings.TrimSpace(data.Msgtype)) cb := BotCallback{ - ConversationType: data.ConversationType, - ConversationID: data.ConversationId, - Msgtype: msgtype, - MsgID: data.MsgId, - SenderNick: data.SenderNick, - SenderStaffID: data.SenderStaffId, - SenderID: data.SenderId, - IsInAtList: data.IsInAtList, - SessionWebhook: data.SessionWebhook, - Text: data.Text.Content, + ConversationType: data.ConversationType, + ConversationID: data.ConversationId, + ConversationTitle: data.ConversationTitle, + Msgtype: msgtype, + MsgID: data.MsgId, + SenderNick: data.SenderNick, + SenderStaffID: data.SenderStaffId, + SenderID: data.SenderId, + IsInAtList: data.IsInAtList, + SessionWebhook: data.SessionWebhook, + Text: data.Text.Content, } if msgtype == "richtext" { - rtMsgtype, rtText, rtCode := parseRichText(data.Content) + rtMsgtype, rtText, rtCodes := parseRichText(data.Content) cb.Msgtype = rtMsgtype cb.Text = rtText - cb.DownloadCode = rtCode + cb.DownloadCodes = rtCodes + if len(rtCodes) > 0 { + cb.DownloadCode = rtCodes[0] + } + return cb, nil + } + if msgtype == "link" { + linkURL := extractLinkMessageURL(data.Content) + if linkURL == "" { + linkURL = safeHTTPURL(data.Text.Content) + } + if linkURL != "" { + cb.Msgtype = msgTypeText + cb.Text = linkURL + } return cb, nil } if msgtype == "picture" { @@ -93,6 +112,68 @@ func BotCallbackFromSDK(data *chatbot.BotCallbackDataModel) (BotCallback, error) return cb, nil } +// extractLinkMessageURL extracts an HTTP(S) target from DingTalk link-card +// content. Only known URL and envelope keys are traversed so a card image URL +// (for example picUrl) cannot be mistaken for the message target. +func extractLinkMessageURL(raw interface{}) string { + if raw == nil { + return "" + } + b, err := json.Marshal(raw) + if err != nil { + return "" + } + var value interface{} + if json.Unmarshal(b, &value) != nil { + return "" + } + return findLinkMessageURL(value) +} + +func findLinkMessageURL(value interface{}) string { + object, ok := value.(map[string]interface{}) + if !ok { + return "" + } + for key, candidate := range object { + switch normalizeLinkField(key) { + case "messageurl", "linkurl", "singletitleurl", "href", "url": + if text, ok := candidate.(string); ok { + if target := safeHTTPURL(text); target != "" { + return target + } + } + } + } + for key, nested := range object { + switch normalizeLinkField(key) { + case "content", "link", "data", "card": + if target := findLinkMessageURL(nested); target != "" { + return target + } + } + } + return "" +} + +func normalizeLinkField(value string) string { + value = strings.ToLower(strings.TrimSpace(value)) + value = strings.ReplaceAll(value, "_", "") + return strings.ReplaceAll(value, "-", "") +} + +func safeHTTPURL(raw string) string { + raw = strings.TrimSpace(raw) + u, err := url.ParseRequestURI(raw) + if err != nil || u.Host == "" { + return "" + } + if !strings.EqualFold(u.Scheme, "https") && !strings.EqualFold(u.Scheme, "http") { + return "" + } + return raw +} + // parseRichText parses the SDK Content field for richText messages. // It handles three content shapes: // 1. Direct object: {"richText": [...]} @@ -100,19 +181,19 @@ func BotCallbackFromSDK(data *chatbot.BotCallbackDataModel) (BotCallback, error) // 3. Nested envelope: {"content":{"richText":[...]}} // // Picture items are identified by a "type" field (case-insensitive trimmed) -// equal to "picture". The first non-empty downloadCode is used; subsequent -// picture items are ignored. Text items are joined with newlines. +// equal to "picture". All non-empty download codes are collected in order; +// text items are joined with newlines. // -// Returns: (msgtype, text, downloadCode). Msgtype is "picture" if any picture +// Returns: (msgtype, text, downloadCodes). Msgtype is "picture" if any picture // item exists, "text" if only text items, "richtext" if malformed/empty. -func parseRichText(raw interface{}) (string, string, string) { +func parseRichText(raw interface{}) (string, string, []string) { items := extractRichTextItems(raw) if len(items) == 0 { - return "richtext", "", "" + return "richtext", "", nil } var textParts []string - var downloadCode string + var downloadCodes []string hasPicture := false for _, item := range items { @@ -120,11 +201,9 @@ func parseRichText(raw interface{}) (string, string, string) { if itemType == "picture" { hasPicture = true - if downloadCode == "" { - code := strings.TrimSpace(item.DownloadCode) - if code != "" { - downloadCode = code - } + code := strings.TrimSpace(item.DownloadCode) + if code != "" { + downloadCodes = append(downloadCodes, code) } continue } @@ -138,12 +217,12 @@ func parseRichText(raw interface{}) (string, string, string) { text := strings.Join(textParts, "\n") if hasPicture { - return "picture", text, downloadCode + return "picture", text, downloadCodes } if text != "" { - return "text", text, "" + return "text", text, nil } - return "richtext", "", "" + return "richtext", "", nil } // richTextItem is a single item in a richText array. @@ -221,18 +300,77 @@ func extractDownloadCode(raw interface{}) string { return strings.TrimSpace(nested.Content.DownloadCode) } -// StreamClient wraps the official DingTalk Stream SDK client. It wires -// robot callbacks into the existing Handler synchronously (no goroutines, -// no queue). The SDK default auto-reconnect stays enabled while running; -// Close disables it so the connection stays closed. +const callbackDedupTTL = 5 * time.Minute + +type chatCallbackHandler interface { + Handle(context.Context, BotCallback) error +} + +// newAsyncChatCallbackRouter acknowledges valid DingTalk frames immediately, +// then processes them outside the SDK callback lifetime. DingTalk retries slow +// callbacks, so retaining MsgIDs for the platform's five-minute retry window +// prevents a retry from creating a second streaming card. +func newAsyncChatCallbackRouter(handler chatCallbackHandler) func(context.Context, *chatbot.BotCallbackDataModel) ([]byte, error) { + var mu sync.Mutex + seen := make(map[string]time.Time) + return func(ctx context.Context, data *chatbot.BotCallbackDataModel) ([]byte, error) { + cb, err := BotCallbackFromSDK(data) + if err != nil { + return nil, err + } + sourceType := safeCallbackMessageType(data.Msgtype) + if sourceType == "link" || sourceType == "richtext" { + log.Printf("DingTalk callback normalized: source_msgtype=%s normalized_msgtype=%s text_present=%t", sourceType, safeCallbackMessageType(cb.Msgtype), strings.TrimSpace(cb.Text) != "") + } + messageID := strings.TrimSpace(cb.MsgID) + if messageID == "" { + return nil, errors.New("dingtalk stream: msgId is required") + } + + now := time.Now() + mu.Lock() + for id, expiresAt := range seen { + if !expiresAt.After(now) { + delete(seen, id) + } + } + if expiresAt, exists := seen[messageID]; exists && expiresAt.After(now) { + mu.Unlock() + return nil, nil + } + seen[messageID] = now.Add(callbackDedupTTL) + mu.Unlock() + + workCtx := context.WithoutCancel(ctx) + go func() { + if err := handler.Handle(workCtx, cb); err != nil { + log.Printf("DingTalk async callback failed: stage=handler") + } + }() + return nil, nil + } +} + +func safeCallbackMessageType(raw string) string { + switch strings.ToLower(strings.TrimSpace(raw)) { + case "text", "picture", "richtext", "link": + return strings.ToLower(strings.TrimSpace(raw)) + default: + return "other" + } +} + +// StreamClient wraps the official DingTalk Stream SDK client. Robot callbacks +// are acknowledged before the potentially slow QA/card work begins. The SDK +// default auto-reconnect stays enabled while running; Close disables it so the +// connection stays closed. type StreamClient struct { inner *dtsdk.StreamClient } // NewStreamClient validates the config, builds the SDK client with the app // credential and registers the chatbot callback router. The handler is -// invoked synchronously from the SDK callback; its return value only -// acknowledges the frame, replies always go through the session webhook. +// acknowledged immediately; replies always go through the session webhook. func NewStreamClient(config StreamConfig, handler *Handler, feedbackHandlers ...*CardFeedbackHandler) (*StreamClient, error) { if err := config.Validate(); err != nil { return nil, err @@ -255,16 +393,7 @@ func NewStreamClient(config StreamConfig, handler *Handler, feedbackHandlers ... inner := dtsdk.NewStreamClient( dtsdk.WithAppCredential(cred), ) - inner.RegisterChatBotCallbackRouter(func(ctx context.Context, data *chatbot.BotCallbackDataModel) ([]byte, error) { - cb, err := BotCallbackFromSDK(data) - if err != nil { - return nil, err - } - if err := handler.Handle(ctx, cb); err != nil { - return nil, err - } - return nil, nil - }) + inner.RegisterChatBotCallbackRouter(newAsyncChatCallbackRouter(handler)) if len(feedbackHandlers) == 1 { inner.RegisterCardCallbackRouter(func(ctx context.Context, request *sdkcard.CardRequest) (*sdkcard.CardResponse, error) { return feedbackHandlers[0].HandleSDK(ctx, request) diff --git a/internal/channels/dingtalk/stream_test.go b/internal/channels/dingtalk/stream_test.go index 2752a5f..733bc30 100644 --- a/internal/channels/dingtalk/stream_test.go +++ b/internal/channels/dingtalk/stream_test.go @@ -1,12 +1,80 @@ package dingtalk import ( + "context" + "reflect" "strings" + "sync" "testing" + "time" "github.com/open-dingtalk/dingtalk-stream-sdk-go/chatbot" ) +type blockingCallbackHandler struct { + started chan struct{} + release chan struct{} + mu sync.Mutex + calls int +} + +func (h *blockingCallbackHandler) Handle(_ context.Context, _ BotCallback) error { + h.mu.Lock() + h.calls++ + if h.calls == 1 { + close(h.started) + } + h.mu.Unlock() + <-h.release + return nil +} + +func (h *blockingCallbackHandler) callCount() int { + h.mu.Lock() + defer h.mu.Unlock() + return h.calls +} + +func TestAsyncChatCallbackAcknowledgesBeforeWorkAndDeduplicatesInflightMessage(t *testing.T) { + handler := &blockingCallbackHandler{started: make(chan struct{}), release: make(chan struct{})} + router := newAsyncChatCallbackRouter(handler) + data := &chatbot.BotCallbackDataModel{ + ConversationType: "1", + Msgtype: "text", + MsgId: "same-message", + SenderStaffId: "staff-1", + SessionWebhook: "https://oapi.dingtalk.com/robot/sendBySession?session=test", + Text: chatbot.BotCallbackDataTextModel{Content: "hello"}, + } + + done := make(chan error, 1) + go func() { + _, err := router(context.Background(), data) + done <- err + }() + select { + case err := <-done: + if err != nil { + t.Fatal(err) + } + case <-time.After(100 * time.Millisecond): + t.Fatal("callback ACK waited for slow QA work") + } + select { + case <-handler.started: + case <-time.After(time.Second): + t.Fatal("async handler did not start") + } + if _, err := router(context.Background(), data); err != nil { + t.Fatal(err) + } + time.Sleep(20 * time.Millisecond) + if got := handler.callCount(); got != 1 { + t.Fatalf("same in-flight MsgID handled %d times, want 1", got) + } + close(handler.release) +} + func TestStreamConfigValidate(t *testing.T) { t.Parallel() tests := []struct { @@ -119,7 +187,7 @@ func TestBotCallbackFromSDK(t *testing.T) { SessionWebhook: "https://oapi.dingtalk.com/robot/sendBySession?session=abc", Text: " 你好 ", } - if cb != want { + if !reflect.DeepEqual(cb, want) { t.Fatalf("BotCallbackFromSDK() = %+v, want %+v", cb, want) } }) @@ -142,6 +210,46 @@ func TestBotCallbackFromSDK(t *testing.T) { }) } +func TestBotCallbackFromSDKLinkCardPromotesTrustedURLToText(t *testing.T) { + t.Parallel() + const notableURL = "https://alidocs.dingtalk.com/i/nodes/base?sheetId=sheet&viewId=view" + tests := []struct { + name string + content interface{} + }{ + {name: "direct content", content: map[string]interface{}{"title": "FAQ表", "messageUrl": notableURL}}, + {name: "nested callback envelope", content: map[string]interface{}{"content": map[string]interface{}{"messageUrl": notableURL}}}, + } + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + cb, err := BotCallbackFromSDK(&chatbot.BotCallbackDataModel{Msgtype: "link", MsgId: "link-1", Content: tt.content}) + if err != nil { + t.Fatal(err) + } + if cb.Msgtype != "text" || cb.Text != notableURL { + t.Fatalf("callback=%+v, want promoted text URL", cb) + } + }) + } +} + +func TestBotCallbackFromSDKLinkCardRejectsUnsafeURL(t *testing.T) { + t.Parallel() + cb, err := BotCallbackFromSDK(&chatbot.BotCallbackDataModel{ + Msgtype: "link", + MsgId: "link-unsafe", + Content: map[string]interface{}{"messageUrl": "javascript:alert(1)"}, + }) + if err != nil { + t.Fatal(err) + } + if cb.Msgtype != "link" || cb.Text != "" { + t.Fatalf("unsafe link must not be promoted: %+v", cb) + } +} + func TestBotCallbackFromSDKPicture(t *testing.T) { t.Parallel() @@ -343,7 +451,7 @@ func TestBotCallbackFromSDKRichText(t *testing.T) { } }) - t.Run("first non-empty downloadCode used, subsequent ignored", func(t *testing.T) { + t.Run("all picture downloadCodes collected in order", func(t *testing.T) { t.Parallel() data := &chatbot.BotCallbackDataModel{ ConversationType: "1", @@ -361,6 +469,9 @@ func TestBotCallbackFromSDKRichText(t *testing.T) { if cb.DownloadCode != "code-first" { t.Fatalf("DownloadCode = %q, want first code-first", cb.DownloadCode) } + if len(cb.DownloadCodes) != 2 || cb.DownloadCodes[0] != "code-first" || cb.DownloadCodes[1] != "code-second" { + t.Fatalf("DownloadCodes = %+v, want [code-first code-second]", cb.DownloadCodes) + } }) t.Run("picture item missing downloadCode still picture", func(t *testing.T) { @@ -542,6 +653,46 @@ func TestBotCallbackFromSDKRichText(t *testing.T) { }) } +func TestBotCallbackFromSDKConversationTitle(t *testing.T) { + t.Parallel() + + t.Run("conversation title survives conversion", func(t *testing.T) { + t.Parallel() + data := &chatbot.BotCallbackDataModel{ + ConversationType: "2", + ConversationId: "cid123", + Msgtype: "text", + MsgId: "msg-1", + ConversationTitle: "项目讨论群", + Text: chatbot.BotCallbackDataTextModel{Content: "hello"}, + } + cb, err := BotCallbackFromSDK(data) + if err != nil { + t.Fatalf("BotCallbackFromSDK() error = %v", err) + } + if cb.ConversationTitle != "项目讨论群" { + t.Fatalf("ConversationTitle = %q, want 项目讨论群", cb.ConversationTitle) + } + }) + + t.Run("conversation title empty for direct", func(t *testing.T) { + t.Parallel() + data := &chatbot.BotCallbackDataModel{ + ConversationType: "1", + Msgtype: "text", + MsgId: "msg-2", + Text: chatbot.BotCallbackDataTextModel{Content: "hi"}, + } + cb, err := BotCallbackFromSDK(data) + if err != nil { + t.Fatalf("BotCallbackFromSDK() error = %v", err) + } + if cb.ConversationTitle != "" { + t.Fatalf("ConversationTitle = %q, want empty for direct", cb.ConversationTitle) + } + }) +} + func TestNewStreamClientValidation(t *testing.T) { t.Parallel() h := mustTestHandler(t) diff --git a/internal/core/types.go b/internal/core/types.go index 979a691..c0af5a4 100644 --- a/internal/core/types.go +++ b/internal/core/types.go @@ -17,13 +17,15 @@ var ErrTurnInProgress = errors.New("turn is already processing") // ImageInput contains the image data for a QA request. The DataURI is a // full data: URI (e.g. "data:image/png;base64,...") and must never be -// persisted to the audit log. +// persisted to the audit log. PublishedURL is an optional stable HTTPS URL +// produced after the image is published to object storage for traceability. type ImageInput struct { - DataURI string - MIMEType string - SizeBytes int64 - Width int - Height int + DataURI string + MIMEType string + SizeBytes int64 + Width int + Height int + PublishedURL string } // MediaAudit records metadata about media in a turn for audit purposes. @@ -37,16 +39,25 @@ type MediaAudit struct { } type QARequest struct { - TenantKey string - Channel string - ConversationType ConversationType - ExternalChatID string - ExternalUserID string - ExternalMessageID string - SenderName string - Query string - Images []ImageInput - MessageType string + TenantKey string + Channel string + ConversationType ConversationType + ConversationTitle string + ExternalChatID string + ExternalUserID string + ExternalMessageID string + SenderName string + TriggerPersonSnapshot string + ActorUnionIDSnapshot string + Department string + Region string + ResponseLocale string + Query string + AgentIDOverride string + ReasoningExecution string + ReasoningExpired bool + Images []ImageInput + MessageType string } type Reference struct { @@ -77,34 +88,44 @@ type SessionMapping struct { ConversationType ConversationType ExternalSubjectID string WeKnoraSessionID string + DisplayTitle string } +type SessionTitleUpdate func(ctx context.Context, sessionID, title string) error + type Turn struct { - ID string - TenantKey string - Channel string - ExternalMessageID string - SessionKey string - WeKnoraSessionID string - WeKnoraRequestID string - AgentID string - ConversationType ConversationType - ExternalChatID string - ExternalUserID string - SenderName string - MessageType string - ActorID string - ConversationID string - RequestMessageID string - AnswerMessageID string - AnswerDeliveryStatus string - AnswerDeliveryMethod string - Question string - Answer string - References []Reference - Media []MediaAudit - Status string - ErrorMessage string + ID string + TenantKey string + Channel string + ExternalMessageID string + SessionKey string + WeKnoraSessionID string + WeKnoraRequestID string + AgentID string + ConversationType ConversationType + ConversationTitle string + ExternalChatID string + ExternalUserID string + SenderName string + TriggerPersonSnapshot string + ActorUnionIDSnapshot string + DepartmentSnapshot string + RegionSnapshot string + MessageType string + ActorID string + ConversationID string + RequestMessageID string + AnswerMessageID string + AnswerDeliveryStatus string + AnswerDeliveryMethod string + Question string + Answer string + References []Reference + Media []MediaAudit + QuestionImageURLs []string + KnowledgeSearched bool + Status string + ErrorMessage string } // Delivery status constants for outbound messages. @@ -143,6 +164,7 @@ var ErrDeliveryUpdateFailed = errors.New("delivery update failed: RowsAffected ! type Repository interface { BeginTurn(ctx context.Context, turn Turn) (Turn, bool, error) ResolveSession(ctx context.Context, mapping SessionMapping, create func(context.Context) (string, error)) (string, error) + SyncSessionTitle(ctx context.Context, mapping SessionMapping, title string, update SessionTitleUpdate) error FinishTurn(ctx context.Context, turn Turn) error RecordDelivery(ctx context.Context, du DeliveryUpdate) error } diff --git a/internal/coverage/dispatcher.go b/internal/coverage/dispatcher.go new file mode 100644 index 0000000..9164208 --- /dev/null +++ b/internal/coverage/dispatcher.go @@ -0,0 +1,63 @@ +package coverage + +import ( + "context" + "fmt" + "time" +) + +const ( + // FailureCodeDingtalkGroupSendFailed is the stable failure code used when + // a dingtalk group send fails. Raw errors must never be persisted. + FailureCodeDingtalkGroupSendFailed = "dingtalk_group_send_failed" +) + +// RunOnce claims a batch of pending support cases and sends each one via the +// Notifier. The parent context is checked before the claim. Each item gets a +// per-item timeout derived from d.SendTimeout. On success, the item is marked +// notified; on failure, it is marked with a stable failure code — raw errors +// are never persisted. Mark/Claim infrastructure errors are returned with +// stable wrapping. An empty batch is a successful no-op. +func (d *Dispatcher) RunOnce(ctx context.Context) (DispatcherStats, error) { + if err := ctx.Err(); err != nil { + return DispatcherStats{}, err + } + + staleBefore := time.Now().Add(-d.ClaimLease) + cases, err := d.repo.Claim(ctx, d.BatchSize, d.MaxAttempts, staleBefore) + if err != nil { + return DispatcherStats{}, fmt.Errorf("dispatcher claim: %w", err) + } + + stats := DispatcherStats{Claimed: len(cases)} + if stats.Claimed == 0 { + return stats, nil + } + + for _, sc := range cases { + // Check parent context before each item. + if err := ctx.Err(); err != nil { + return stats, err + } + + sendCtx, cancel := context.WithTimeout(ctx, d.SendTimeout) + sendErr := d.notifier.Send(sendCtx, sc.SupportNotification) + cancel() + + if sendErr != nil { + // Only persist the stable failure code, never the raw error. + if err := d.repo.MarkFailed(ctx, sc.CaseID, FailureCodeDingtalkGroupSendFailed); err != nil { + return stats, fmt.Errorf("dispatcher mark failed: %w", err) + } + stats.Failed++ + continue + } + + if err := d.repo.MarkNotified(ctx, sc.CaseID); err != nil { + return stats, fmt.Errorf("dispatcher mark notified: %w", err) + } + stats.Notified++ + } + + return stats, nil +} diff --git a/internal/coverage/dispatcher_test.go b/internal/coverage/dispatcher_test.go new file mode 100644 index 0000000..5781a83 --- /dev/null +++ b/internal/coverage/dispatcher_test.go @@ -0,0 +1,427 @@ +package coverage + +import ( + "context" + "errors" + "sync" + "testing" + "time" + + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/core" +) + +// stubNotificationRepository is a test double for NotificationRepository. +type stubNotificationRepository struct { + mu sync.Mutex + cases []PendingSupportCase + claimErr error + markErr error + markFailedCalls map[string]string // caseID -> failureCode + markNotifiedIDs []string +} + +func (s *stubNotificationRepository) Claim(ctx context.Context, limit, maxAttempts int, staleBefore time.Time) ([]PendingSupportCase, error) { + s.mu.Lock() + defer s.mu.Unlock() + if s.claimErr != nil { + return nil, s.claimErr + } + // Return a copy of the current cases up to limit + available := make([]PendingSupportCase, len(s.cases)) + copy(available, s.cases) + if len(available) > limit { + available = available[:limit] + } + s.cases = s.cases[len(available):] + return available, nil +} + +func (s *stubNotificationRepository) MarkNotified(ctx context.Context, caseID string) error { + s.mu.Lock() + defer s.mu.Unlock() + if s.markErr != nil { + return s.markErr + } + s.markNotifiedIDs = append(s.markNotifiedIDs, caseID) + return nil +} + +func (s *stubNotificationRepository) MarkFailed(ctx context.Context, caseID string, failureCode string) error { + s.mu.Lock() + defer s.mu.Unlock() + if s.markErr != nil { + return s.markErr + } + if s.markFailedCalls == nil { + s.markFailedCalls = make(map[string]string) + } + s.markFailedCalls[caseID] = failureCode + return nil +} + +// stubNotifier is a test double for Notifier. +type stubNotifier struct { + mu sync.Mutex + sendErr error + sent []SupportNotification + // failOn maps caseID -> error to simulate per-item failure. + failOn map[string]error +} + +func (s *stubNotifier) Send(ctx context.Context, notif SupportNotification) error { + s.mu.Lock() + defer s.mu.Unlock() + if err, ok := s.failOn[notif.CaseID]; ok { + return err + } + if s.sendErr != nil { + return s.sendErr + } + s.sent = append(s.sent, notif) + return nil +} + +// blockingNotifier blocks until ctx is done, then returns ctx.Err(). +// Used for timeout tests. +type blockingNotifier struct { + mu sync.Mutex + blocked bool +} + +func (b *blockingNotifier) Send(ctx context.Context, notif SupportNotification) error { + b.mu.Lock() + b.blocked = true + b.mu.Unlock() + <-ctx.Done() + return ctx.Err() +} + +func makePendingCase(id string, attempts int) PendingSupportCase { + return PendingSupportCase{ + SupportNotification: SupportNotification{ + CaseID: id, + Question: "test question " + id, + SenderName: "Sender " + id, + Channel: "dingtalk", + ConversationType: core.ConversationGroup, + AskedAt: time.Unix(1, 0), + PreviousQuestions: []string{"previous question"}, + FAQRecordID: "record-" + id, + }, + Attempts: attempts, + } +} + +// TestDispatcherEmptyQueue verifies that RunOnce on an empty queue returns +// a zero stats with no error. +func TestDispatcherEmptyQueue(t *testing.T) { + repo := &stubNotificationRepository{} + notifier := &stubNotifier{} + dispatcher, err := NewDispatcher(repo, notifier) + if err != nil { + t.Fatalf("NewDispatcher: %v", err) + } + + stats, err := dispatcher.RunOnce(context.Background()) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if stats.Claimed != 0 || stats.Notified != 0 || stats.Failed != 0 { + t.Fatalf("empty queue: got %+v, want all zero", stats) + } +} + +// TestDispatcherAllSuccess verifies that all claimed cases are sent and +// marked as notified. +func TestDispatcherAllSuccess(t *testing.T) { + repo := &stubNotificationRepository{ + cases: []PendingSupportCase{ + makePendingCase("case-1", 0), + makePendingCase("case-2", 0), + makePendingCase("case-3", 0), + }, + } + notifier := &stubNotifier{} + dispatcher, err := NewDispatcher(repo, notifier, WithBatchSize(10)) + if err != nil { + t.Fatalf("NewDispatcher: %v", err) + } + + stats, err := dispatcher.RunOnce(context.Background()) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if stats.Claimed != 3 { + t.Fatalf("Claimed = %d, want 3", stats.Claimed) + } + if stats.Notified != 3 { + t.Fatalf("Notified = %d, want 3", stats.Notified) + } + if stats.Failed != 0 { + t.Fatalf("Failed = %d, want 0", stats.Failed) + } + if len(notifier.sent) != 3 { + t.Fatalf("sent %d, want 3", len(notifier.sent)) + } + if len(repo.markNotifiedIDs) != 3 { + t.Fatalf("markNotifiedIDs = %d, want 3", len(repo.markNotifiedIDs)) + } +} + +// TestDispatcherOneFailureContinues verifies that when one item fails, +// the dispatcher continues with the rest and marks the failed one. +func TestDispatcherOneFailureContinues(t *testing.T) { + repo := &stubNotificationRepository{ + cases: []PendingSupportCase{ + makePendingCase("case-1", 0), + makePendingCase("case-2", 0), // will fail + makePendingCase("case-3", 0), + }, + } + notifier := &stubNotifier{ + failOn: map[string]error{ + "case-2": errors.New("simulated send failure"), + }, + } + dispatcher, err := NewDispatcher(repo, notifier, WithBatchSize(10)) + if err != nil { + t.Fatalf("NewDispatcher: %v", err) + } + + stats, err := dispatcher.RunOnce(context.Background()) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if stats.Claimed != 3 { + t.Fatalf("Claimed = %d, want 3", stats.Claimed) + } + if stats.Notified != 2 { + t.Fatalf("Notified = %d, want 2", stats.Notified) + } + if stats.Failed != 1 { + t.Fatalf("Failed = %d, want 1", stats.Failed) + } + if notifier.sent[0].CaseID != "case-1" { + t.Fatalf("first sent = %s, want case-1", notifier.sent[0].CaseID) + } + if notifier.sent[1].CaseID != "case-3" { + t.Fatalf("second sent = %s, want case-3", notifier.sent[1].CaseID) + } + // case-2 must be marked as failed with stable code, not raw error + if code, ok := repo.markFailedCalls["case-2"]; !ok { + t.Fatal("case-2 must be marked as failed") + } else if code != "dingtalk_group_send_failed" { + t.Fatalf("failure code = %q, want dingtalk_group_send_failed", code) + } + // case-1 and case-3 must be marked notified + foundNotified := make(map[string]bool) + for _, id := range repo.markNotifiedIDs { + foundNotified[id] = true + } + if !foundNotified["case-1"] { + t.Fatal("case-1 must be marked notified") + } + if !foundNotified["case-3"] { + t.Fatal("case-3 must be marked notified") + } +} + +// TestDispatcherFailureStableCodeOnly verifies that the raw error text is +// never written to the repository — only the stable failure code. +func TestDispatcherFailureStableCodeOnly(t *testing.T) { + repo := &stubNotificationRepository{ + cases: []PendingSupportCase{ + makePendingCase("case-1", 0), + }, + } + notifier := &stubNotifier{ + failOn: map[string]error{ + "case-1": errors.New("secret token xyz123 leaked in error"), + }, + } + dispatcher, err := NewDispatcher(repo, notifier) + if err != nil { + t.Fatalf("NewDispatcher: %v", err) + } + + _, err = dispatcher.RunOnce(context.Background()) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if code := repo.markFailedCalls["case-1"]; code != "dingtalk_group_send_failed" { + t.Fatalf("failure code = %q, want dingtalk_group_send_failed (raw error must never leak)", code) + } +} + +// TestDispatcherMarkNotifiedErrorPropagation verifies that when +// MarkNotified fails, the error is returned to the caller. +func TestDispatcherMarkNotifiedErrorPropagation(t *testing.T) { + repo := &stubNotificationRepository{ + cases: []PendingSupportCase{makePendingCase("case-1", 0)}, + markErr: errors.New("db unreachable"), + } + notifier := &stubNotifier{} + dispatcher, err := NewDispatcher(repo, notifier) + if err != nil { + t.Fatalf("NewDispatcher: %v", err) + } + + _, err = dispatcher.RunOnce(context.Background()) + if err == nil { + t.Fatal("expected error from MarkNotified, got nil") + } +} + +// TestDispatcherMarkFailedErrorPropagation verifies that when MarkFailed +// fails, the error is returned to the caller. +func TestDispatcherMarkFailedErrorPropagation(t *testing.T) { + repo := &stubNotificationRepository{ + cases: []PendingSupportCase{ + makePendingCase("case-1", 0), + }, + markErr: errors.New("db unreachable"), + } + notifier := &stubNotifier{ + failOn: map[string]error{ + "case-1": errors.New("send failed"), + }, + } + dispatcher, err := NewDispatcher(repo, notifier) + if err != nil { + t.Fatalf("NewDispatcher: %v", err) + } + + _, err = dispatcher.RunOnce(context.Background()) + if err == nil { + t.Fatal("expected error from MarkFailed, got nil") + } +} + +// TestDispatcherClaimErrorPropagation verifies claim errors are returned. +func TestDispatcherClaimErrorPropagation(t *testing.T) { + repo := &stubNotificationRepository{ + claimErr: errors.New("db unreachable"), + } + notifier := &stubNotifier{} + dispatcher, err := NewDispatcher(repo, notifier) + if err != nil { + t.Fatalf("NewDispatcher: %v", err) + } + + _, err = dispatcher.RunOnce(context.Background()) + if err == nil { + t.Fatal("expected error from Claim, got nil") + } +} + +// TestDispatcherPerItemTimeout verifies that the dispatcher applies a per-item +// timeout: when a notifier blocks forever, RunOnce completes within a +// reasonable time, Failed=1, and the stable failure code is used. +func TestDispatcherPerItemTimeout(t *testing.T) { + repo := &stubNotificationRepository{ + cases: []PendingSupportCase{makePendingCase("case-1", 0)}, + } + notifier := &blockingNotifier{} + // Use a 50ms timeout so the test is not flaky but still fast. + dispatcher, err := NewDispatcher(repo, notifier, WithSendTimeout(50*time.Millisecond)) + if err != nil { + t.Fatalf("NewDispatcher: %v", err) + } + + start := time.Now() + stats, err := dispatcher.RunOnce(context.Background()) + elapsed := time.Since(start) + + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if stats.Failed != 1 { + t.Fatalf("Failed = %d, want 1", stats.Failed) + } + if stats.Claimed != 1 { + t.Fatalf("Claimed = %d, want 1", stats.Claimed) + } + // Verify the stable failure code was used + if code := repo.markFailedCalls["case-1"]; code != "dingtalk_group_send_failed" { + t.Fatalf("failure code = %q, want dingtalk_group_send_failed", code) + } + // RunOnce must complete in a reasonable time (not stuck forever). + // Use a generous upper bound: 5s is enough for any CI environment. + if elapsed > 5*time.Second { + t.Fatalf("RunOnce took %v, expected to complete within 5s", elapsed) + } + if !notifier.blocked { + t.Fatal("notifier was not called — timeout did not trigger") + } +} + +// TestDispatcherContextCancel verifies the dispatcher respects context cancellation. +func TestDispatcherContextCancel(t *testing.T) { + repo := &stubNotificationRepository{ + cases: []PendingSupportCase{makePendingCase("case-1", 0)}, + } + notifier := &stubNotifier{} + dispatcher, err := NewDispatcher(repo, notifier, WithSendTimeout(10*time.Second)) + if err != nil { + t.Fatalf("NewDispatcher: %v", err) + } + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + _, err = dispatcher.RunOnce(ctx) + if err == nil { + t.Fatal("expected context error, got nil") + } +} + +// TestDispatcherConstructorValidation verifies constructor input validation. +func TestDispatcherConstructorValidation(t *testing.T) { + tests := []struct { + name string + opts []DispatcherOption + wantErr bool + }{ + {"nil repo", nil, true}, + {"nil notifier only", nil, true}, + {"batch too small", []DispatcherOption{WithBatchSize(0)}, true}, + {"batch too large", []DispatcherOption{WithBatchSize(101)}, true}, + {"maxAttempts too small", []DispatcherOption{WithMaxAttempts(0)}, true}, + {"maxAttempts too large", []DispatcherOption{WithMaxAttempts(11)}, true}, + {"valid defaults", nil, false}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + var repo *stubNotificationRepository + var notifier *stubNotifier + if tt.name != "nil repo" { + repo = &stubNotificationRepository{} + } + if tt.name != "nil notifier only" { + notifier = &stubNotifier{} + } + _, err := NewDispatcher(repo, notifier, tt.opts...) + if tt.wantErr && err == nil { + t.Fatal("expected error, got nil") + } + if !tt.wantErr && err != nil { + t.Fatalf("unexpected error: %v", err) + } + }) + } +} + +// TestDispatcherBatchSizeLimit verifies batch size is capped at 100. +func TestDispatcherBatchSizeLimit(t *testing.T) { + repo := &stubNotificationRepository{ + cases: []PendingSupportCase{}, + } + notifier := &stubNotifier{} + d, err := NewDispatcher(repo, notifier, WithBatchSize(100)) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if d.BatchSize != 100 { + t.Fatalf("BatchSize = %d, want 100", d.BatchSize) + } +} diff --git a/internal/coverage/evaluator.go b/internal/coverage/evaluator.go new file mode 100644 index 0000000..2aa98f6 --- /dev/null +++ b/internal/coverage/evaluator.go @@ -0,0 +1,193 @@ +package coverage + +import ( + "strings" + + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/core" +) + +// noAnswerPhrases lists explicit "no answer" phrases that the knowledge base +// returns when it cannot find relevant information. These are matched as +// substrings after trimming whitespace. +var noAnswerPhrases = []string{ + "未找到", + "没有找到", + "无法确定", + "暂无相关", + "暂无已发布的权威知识", + "知识库中没有", + "产品不存在于资料中", +} + +// retrievalGapPhrases are only considered a no-answer signal when the answer +// also directs the user to a human channel. Requiring both signals avoids +// misclassifying valid negative results such as "未查询到异常记录". +var retrievalGapPhrases = []string{ + "未查询到", + "未检索到", + "未能查询到", + "未能检索到", +} + +var humanEscalationPhrases = []string{ + "建议您联系", + "建议联系", + "请联系", + "联系技术支持", + "联系官方销售", +} + +// Evaluator classifies a successful turn into a coverage verdict. +type Evaluator struct{} + +// NewEvaluator creates the current Evaluator. +func NewEvaluator() *Evaluator { + return &Evaluator{} +} + +// Version returns the current evaluator version. +func (e *Evaluator) Version() string { + return EvaluatorVersion +} + +// Evaluate classifies a turn. It rejects non-succeeded turns. The evaluation +// rules (in priority order): +// 1. Failed/processing turns → ErrTurnNotSucceeded +// 2. Answer contains an explicit "no answer" phrase → uncovered_explicit_no_answer +// 3. Image turns (image media present) are classified by whether the question +// actually triggered a knowledge-base search: +// - has references → covered_has_references +// - no references + knowledge searched → uncovered_no_references +// - no references + no knowledge search → covered_visual_recognition +// (pure visual recognition is not a coverage miss) +// 4. Text turns: zero references → uncovered_no_references +// 5. Has references → covered_has_references +// +// v1 never uses a score threshold. TopScore captures the highest reference score +// (0 if no references). +func (e *Evaluator) Evaluate(turn core.Turn) (Decision, error) { + if turn.Status != "succeeded" { + return Decision{}, ErrTurnNotSucceeded + } + + // Normalize answer for no-answer phrase detection. + trimmed := strings.TrimSpace(turn.Answer) + + // Check for explicit no-answer phrases first — this takes priority + // over reference presence. + if isNoAnswer(trimmed) { + return Decision{ + TurnID: turn.ID, + TenantKey: turn.TenantKey, + Channel: turn.Channel, + EvaluatorVersion: EvaluatorVersion, + Verdict: VerdictUncovered, + ReasonCode: ReasonUncoveredExplicitNoAnswer, + ReferenceCount: len(turn.References), + TopScore: maxScore(turn.References), + }, nil + } + + // Image turns are classified by whether knowledge search occurred. + if hasImageMedia(turn.Media) { + if len(turn.References) > 0 { + return Decision{ + TurnID: turn.ID, + TenantKey: turn.TenantKey, + Channel: turn.Channel, + EvaluatorVersion: EvaluatorVersion, + Verdict: VerdictCovered, + ReasonCode: ReasonCoveredHasReferences, + ReferenceCount: len(turn.References), + TopScore: maxScore(turn.References), + }, nil + } + if turn.KnowledgeSearched { + return Decision{ + TurnID: turn.ID, + TenantKey: turn.TenantKey, + Channel: turn.Channel, + EvaluatorVersion: EvaluatorVersion, + Verdict: VerdictUncovered, + ReasonCode: ReasonUncoveredNoReferences, + ReferenceCount: 0, + TopScore: 0, + }, nil + } + return Decision{ + TurnID: turn.ID, + TenantKey: turn.TenantKey, + Channel: turn.Channel, + EvaluatorVersion: EvaluatorVersion, + Verdict: VerdictCovered, + ReasonCode: ReasonCoveredVisualRecognition, + ReferenceCount: 0, + TopScore: 0, + }, nil + } + + // No references → uncovered. + if len(turn.References) == 0 { + return Decision{ + TurnID: turn.ID, + TenantKey: turn.TenantKey, + Channel: turn.Channel, + EvaluatorVersion: EvaluatorVersion, + Verdict: VerdictUncovered, + ReasonCode: ReasonUncoveredNoReferences, + ReferenceCount: 0, + TopScore: 0, + }, nil + } + + // Has references → covered (v1 never uses score threshold). + return Decision{ + TurnID: turn.ID, + TenantKey: turn.TenantKey, + Channel: turn.Channel, + EvaluatorVersion: EvaluatorVersion, + Verdict: VerdictCovered, + ReasonCode: ReasonCoveredHasReferences, + ReferenceCount: len(turn.References), + TopScore: maxScore(turn.References), + }, nil +} + +// hasImageMedia reports whether the turn carried at least one image input. +func hasImageMedia(media []core.MediaAudit) bool { + for _, m := range media { + if strings.EqualFold(strings.TrimSpace(m.Type), "image") { + return true + } + } + return false +} + +func isNoAnswer(answer string) bool { + lower := strings.ToLower(answer) + for _, phrase := range noAnswerPhrases { + if strings.Contains(lower, strings.ToLower(phrase)) { + return true + } + } + return containsAny(lower, retrievalGapPhrases) && containsAny(lower, humanEscalationPhrases) +} + +func containsAny(value string, phrases []string) bool { + for _, phrase := range phrases { + if strings.Contains(value, strings.ToLower(phrase)) { + return true + } + } + return false +} + +func maxScore(refs []core.Reference) float64 { + var max float64 + for _, r := range refs { + if r.Score > max { + max = r.Score + } + } + return max +} diff --git a/internal/coverage/evaluator_image_test.go b/internal/coverage/evaluator_image_test.go new file mode 100644 index 0000000..47c866d --- /dev/null +++ b/internal/coverage/evaluator_image_test.go @@ -0,0 +1,85 @@ +package coverage + +import ( + "testing" + + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/core" +) + +func imageTurn(answer string, refs []core.Reference, searched bool) core.Turn { + return core.Turn{ + ID: "img-turn", + Status: "succeeded", + MessageType: "image", + Answer: answer, + References: refs, + Media: []core.MediaAudit{{Type: "image", MIMEType: "image/jpeg"}}, + KnowledgeSearched: searched, + } +} + +func TestEvaluator_ImageVisualRecognitionNoSearch(t *testing.T) { + e := NewEvaluator() + turn := imageTurn("这张图片展示了一个手写的知识库数据处理与发布流程图。", nil, false) + + d, err := e.Evaluate(turn) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if d.Verdict != VerdictCovered { + t.Fatalf("verdict=%s, want covered (visual recognition is not a coverage miss)", d.Verdict) + } + if d.ReasonCode != ReasonCoveredVisualRecognition { + t.Fatalf("reason_code=%s, want %s", d.ReasonCode, ReasonCoveredVisualRecognition) + } +} + +func TestEvaluator_ImageSearchButNoReferencesIsUncovered(t *testing.T) { + e := NewEvaluator() + turn := imageTurn("根据图片中的错误信息,未能在知识库中找到对应的解决方案。", nil, true) + + d, err := e.Evaluate(turn) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if d.Verdict != VerdictUncovered { + t.Fatalf("verdict=%s, want uncovered (image turn searched KB but got no refs)", d.Verdict) + } + if d.ReasonCode != ReasonUncoveredNoReferences { + t.Fatalf("reason_code=%s, want %s", d.ReasonCode, ReasonUncoveredNoReferences) + } +} + +func TestEvaluator_ImageWithReferencesIsCovered(t *testing.T) { + e := NewEvaluator() + turn := imageTurn("根据知识库资料,这个是故障代码E5,请检查...", []core.Reference{{ID: "r1", Score: 0.9}}, true) + + d, err := e.Evaluate(turn) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if d.Verdict != VerdictCovered { + t.Fatalf("verdict=%s, want covered", d.Verdict) + } + if d.ReasonCode != ReasonCoveredHasReferences { + t.Fatalf("reason_code=%s, want %s", d.ReasonCode, ReasonCoveredHasReferences) + } +} + +func TestEvaluator_TextTurnNoReferencesStillUncovered(t *testing.T) { + e := NewEvaluator() + turn := core.Turn{ + ID: "text-turn", + Status: "succeeded", + Answer: "这是一个正常的回答,但没有任何引用", + MessageType: "text", + References: []core.Reference{}, + } + d, err := e.Evaluate(turn) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if d.Verdict != VerdictUncovered || d.ReasonCode != ReasonUncoveredNoReferences { + t.Fatalf("verdict=%s reason=%s, want uncovered_no_references (text turn unchanged)", d.Verdict, d.ReasonCode) + } +} diff --git a/internal/coverage/evaluator_test.go b/internal/coverage/evaluator_test.go new file mode 100644 index 0000000..251f4d4 --- /dev/null +++ b/internal/coverage/evaluator_test.go @@ -0,0 +1,415 @@ +package coverage + +import ( + "testing" + + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/core" +) + +func TestEvaluatorVersion(t *testing.T) { + e := NewEvaluator() + if e.Version() != "v3" { + t.Errorf("Evaluator version = %q, want v3", e.Version()) + } +} + +func TestEvaluator_RejectsFailedTurn(t *testing.T) { + e := NewEvaluator() + // Failed turn should be rejected/return error + _, err := e.Evaluate(core.Turn{Status: "failed"}) + if err == nil { + t.Fatal("expected error for failed turn, got nil") + } +} + +func TestEvaluator_RejectsProcessingTurn(t *testing.T) { + e := NewEvaluator() + _, err := e.Evaluate(core.Turn{Status: "processing"}) + if err == nil { + t.Fatal("expected error for processing turn, got nil") + } +} + +func TestEvaluator_UncoveredExplicitNoAnswer(t *testing.T) { + e := NewEvaluator() + noAnswerPhrases := []string{ + "未找到相关结果", + "没有找到你需要的信息", + "无法确定该问题的答案", + "暂无相关信息", + "知识库中没有找到相关内容", + "这个问题知识库中没有可用的信息", + } + for _, answer := range noAnswerPhrases { + turn := core.Turn{ + ID: "test-turn", + Status: "succeeded", + Answer: answer, + References: []core.Reference{ + {ID: "r1", Score: 0.9}, + }, + } + d, err := e.Evaluate(turn) + if err != nil { + t.Fatalf("unexpected error for answer %q: %v", answer, err) + } + if d.Verdict != VerdictUncovered { + t.Errorf("answer %q: verdict = %s, want uncovered", answer, d.Verdict) + } + if d.ReasonCode != ReasonUncoveredExplicitNoAnswer { + t.Errorf("answer %q: reason_code = %s, want %s", answer, d.ReasonCode, ReasonUncoveredExplicitNoAnswer) + } + } +} + +func TestEvaluator_ProductionMissingProductPhraseTrumpsReferences(t *testing.T) { + e := NewEvaluator() + turn := core.Turn{ + ID: "missing-product-turn", + Status: "succeeded", + Answer: "根据提供的检索信息,无法提供对应手册。原因:产品不存在于资料中;检索资料未提及该产品。建议联系技术支持部门。", + References: []core.Reference{ + {ID: "unrelated-1", Score: 0.395940}, + {ID: "unrelated-2", Score: 0.311595}, + }, + } + d, err := e.Evaluate(turn) + if err != nil { + t.Fatal(err) + } + if d.Verdict != VerdictUncovered || d.ReasonCode != ReasonUncoveredExplicitNoAnswer { + t.Fatalf("verdict=%s reason=%s", d.Verdict, d.ReasonCode) + } +} + +func TestEvaluator_UncoveredNoReferences(t *testing.T) { + e := NewEvaluator() + turn := core.Turn{ + ID: "test-turn", + Status: "succeeded", + Answer: "这是一个正常的回答,但没有任何引用", + References: []core.Reference{}, + } + d, err := e.Evaluate(turn) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if d.Verdict != VerdictUncovered { + t.Errorf("verdict = %s, want uncovered", d.Verdict) + } + if d.ReasonCode != ReasonUncoveredNoReferences { + t.Errorf("reason_code = %s, want %s", d.ReasonCode, ReasonUncoveredNoReferences) + } +} + +func TestEvaluator_UncoveredNilReferences(t *testing.T) { + e := NewEvaluator() + turn := core.Turn{ + ID: "test-turn", + Status: "succeeded", + Answer: "这是一个正常的回答,但引用为nil", + } + d, err := e.Evaluate(turn) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if d.Verdict != VerdictUncovered { + t.Errorf("verdict = %s, want uncovered", d.Verdict) + } + if d.ReasonCode != ReasonUncoveredNoReferences { + t.Errorf("reason_code = %s, want %s", d.ReasonCode, ReasonUncoveredNoReferences) + } +} + +func TestEvaluator_CoveredHasReferences(t *testing.T) { + e := NewEvaluator() + turn := core.Turn{ + ID: "test-turn", + Status: "succeeded", + Answer: "根据知识库中的信息,这个问题的答案是...", + References: []core.Reference{ + {ID: "r1", Score: 0.75}, + {ID: "r2", Score: 0.92}, + {ID: "r3", Score: 0.60}, + }, + } + d, err := e.Evaluate(turn) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if d.Verdict != VerdictCovered { + t.Errorf("verdict = %s, want covered", d.Verdict) + } + if d.ReasonCode != ReasonCoveredHasReferences { + t.Errorf("reason_code = %s, want %s", d.ReasonCode, ReasonCoveredHasReferences) + } +} + +func TestEvaluator_TopScore(t *testing.T) { + e := NewEvaluator() + turn := core.Turn{ + ID: "test-turn", + Status: "succeeded", + Answer: "根据知识库中的信息...", + References: []core.Reference{ + {ID: "r1", Score: 0.75}, + {ID: "r2", Score: 0.92}, + {ID: "r3", Score: 0.60}, + }, + } + d, err := e.Evaluate(turn) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if d.TopScore != 0.92 { + t.Errorf("top_score = %f, want 0.92", d.TopScore) + } +} + +func TestEvaluator_ReferenceCount(t *testing.T) { + e := NewEvaluator() + turn := core.Turn{ + ID: "test-turn", + Status: "succeeded", + Answer: "根据知识库中的信息...", + References: []core.Reference{ + {ID: "r1", Score: 0.75}, + {ID: "r2", Score: 0.92}, + {ID: "r3", Score: 0.60}, + }, + } + d, err := e.Evaluate(turn) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if d.ReferenceCount != 3 { + t.Fatalf("reference_count = %d, want 3", d.ReferenceCount) + } +} + +func TestEvaluator_TopScoreZeroWhenNoReferences(t *testing.T) { + e := NewEvaluator() + turn := core.Turn{ + ID: "test-turn", + Status: "succeeded", + Answer: "没有引用", + } + d, err := e.Evaluate(turn) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if d.TopScore != 0 { + t.Errorf("top_score = %f, want 0", d.TopScore) + } +} + +func TestEvaluator_NoAnswerTrumpsReferences(t *testing.T) { + // When answer contains explicit "no answer" phrase, it should be uncovered + // even if references exist. No-answer detection takes priority. + e := NewEvaluator() + turn := core.Turn{ + ID: "test-turn", + Status: "succeeded", + Answer: "未找到相关结果,请换个方式提问", + References: []core.Reference{ + {ID: "r1", Score: 0.99}, + {ID: "r2", Score: 0.88}, + }, + } + d, err := e.Evaluate(turn) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if d.Verdict != VerdictUncovered { + t.Errorf("no-answer with references: verdict = %s, want uncovered", d.Verdict) + } + if d.ReasonCode != ReasonUncoveredExplicitNoAnswer { + t.Errorf("no-answer with references: reason_code = %s, want %s", d.ReasonCode, ReasonUncoveredExplicitNoAnswer) + } +} + +func TestEvaluator_NoAnswerPhraseMatchesInsideAnswer(t *testing.T) { + e := NewEvaluator() + turn := core.Turn{ + ID: "test-turn", + Status: "succeeded", + Answer: "根据现有资料,知识库中没有对应说明,请联系技术支持。", + References: []core.Reference{ + {ID: "r1", Score: 0.9}, + }, + } + + d, err := e.Evaluate(turn) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if d.ReasonCode != ReasonUncoveredExplicitNoAnswer { + t.Fatalf("reason_code = %s, want %s", d.ReasonCode, ReasonUncoveredExplicitNoAnswer) + } +} + +func TestEvaluator_ProductionUnavailableAuthorityPhraseTrumpsReferences(t *testing.T) { + e := NewEvaluator() + turn := core.Turn{ + ID: "cra-price-turn", + Status: "succeeded", + Answer: "当前暂无已发布的权威知识明确说明CRA系列机器人的价格信息。若需要获取对应报价,建议联系越疆官方销售渠道或技术支持进行咨询。", + References: []core.Reference{ + {ID: "ref-1", Score: 0.0164}, + }, + } + + d, err := e.Evaluate(turn) + if err != nil { + t.Fatalf("Evaluate: %v", err) + } + if d.Verdict != VerdictUncovered { + t.Fatalf("verdict = %s, want %s", d.Verdict, VerdictUncovered) + } + if d.ReasonCode != ReasonUncoveredExplicitNoAnswer { + t.Fatalf("reason_code = %s, want %s", d.ReasonCode, ReasonUncoveredExplicitNoAnswer) + } +} + +func TestEvaluator_RetrievalGapRequiresHumanEscalation(t *testing.T) { + e := NewEvaluator() + cases := []struct { + name string + answer string + verdict string + reason string + }{ + { + name: "production NOVA price answer", + answer: "当前暂未查询到Nova系列机器人的公开销售价格信息。\n\n如需获取报价,建议您联系越疆科技官方销售渠道或对应区域的销售工程师咨询具体价格方案。", + verdict: VerdictUncovered, + reason: ReasonUncoveredExplicitNoAnswer, + }, + { + name: "retrieval gap without escalation is a valid negative result", + answer: "系统暂未查询到异常记录,设备运行正常。", + verdict: VerdictCovered, + reason: ReasonCoveredHasReferences, + }, + { + name: "human escalation alone is not a knowledge gap", + answer: "设备状态正常,如需维护服务请联系技术支持。", + verdict: VerdictCovered, + reason: ReasonCoveredHasReferences, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + turn := core.Turn{ + ID: "nova-price-turn", + Status: "succeeded", + Answer: tc.answer, + References: []core.Reference{ + {ID: "ref-1", Score: 0.0164}, + }, + } + d, err := e.Evaluate(turn) + if err != nil { + t.Fatalf("Evaluate: %v", err) + } + if d.Verdict != tc.verdict || d.ReasonCode != tc.reason { + t.Fatalf("verdict/reason = %s/%s, want %s/%s", d.Verdict, d.ReasonCode, tc.verdict, tc.reason) + } + }) + } +} + +func TestEvaluator_DoesNotExpandBeyondApprovedNoAnswerPhrases(t *testing.T) { + e := NewEvaluator() + answers := []string{ + "没有相关限制,设备可以正常运行。", + "当前暂无已发布价格调整计划,现有价格继续执行。", + } + for _, answer := range answers { + turn := core.Turn{ + ID: "test-turn", + Status: "succeeded", + Answer: answer, + References: []core.Reference{ + {ID: "r1", Score: 0.9}, + }, + } + d, err := e.Evaluate(turn) + if err != nil { + t.Fatalf("answer %q: unexpected error: %v", answer, err) + } + if d.Verdict != VerdictCovered { + t.Fatalf("answer %q: verdict = %s, want covered", answer, d.Verdict) + } + } +} + +func TestEvaluator_NoScoreThreshold(t *testing.T) { + // The evaluator must never use score threshold to determine covered/uncovered. + // Even with very low score references, if there are references and no explicit + // no-answer, it should be covered. + e := NewEvaluator() + turn := core.Turn{ + ID: "test-turn", + Status: "succeeded", + Answer: "这是一个回答,引用分数很低", + References: []core.Reference{ + {ID: "r1", Score: 0.01}, + }, + } + d, err := e.Evaluate(turn) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if d.Verdict != VerdictCovered { + t.Errorf("verdict = %s, want covered (score threshold is not used)", d.Verdict) + } + if d.ReasonCode != ReasonCoveredHasReferences { + t.Errorf("reason_code = %s, want %s", d.ReasonCode, ReasonCoveredHasReferences) + } +} + +func TestEvaluator_EmptyAnswerCovered(t *testing.T) { + // Empty answer is not a no-answer phrase. With references, it's covered. + e := NewEvaluator() + turn := core.Turn{ + ID: "test-turn", + Status: "succeeded", + Answer: "", + References: []core.Reference{ + {ID: "r1", Score: 0.5}, + }, + } + d, err := e.Evaluate(turn) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if d.Verdict != VerdictCovered { + t.Errorf("verdict = %s, want covered", d.Verdict) + } +} + +func TestEvaluator_DecisionHasTurnIdentity(t *testing.T) { + e := NewEvaluator() + turn := core.Turn{ + ID: "turn-abc", + TenantKey: "tenant-1", + Channel: "dingtalk", + Status: "succeeded", + Answer: "正常回答", + References: []core.Reference{{ID: "r1", Score: 0.5}}, + } + d, err := e.Evaluate(turn) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if d.TurnID != "turn-abc" { + t.Errorf("turn_id = %q, want turn-abc", d.TurnID) + } + if d.TenantKey != "tenant-1" { + t.Errorf("tenant_key = %q, want tenant-1", d.TenantKey) + } + if d.Channel != "dingtalk" { + t.Errorf("channel = %q, want dingtalk", d.Channel) + } +} diff --git a/internal/coverage/notification.go b/internal/coverage/notification.go new file mode 100644 index 0000000..433e777 --- /dev/null +++ b/internal/coverage/notification.go @@ -0,0 +1,150 @@ +package coverage + +import ( + "context" + "errors" + "fmt" + "reflect" + "time" + + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/core" +) + +const ( + SupportTriggerCoverageUncovered = "coverage_uncovered" + SupportTriggerFeedbackDown = "feedback_down" +) + +// SupportNotification is a safe, minimal view of the data needed to send a +// notification. It must never contain tokens, webhooks, raw API responses, +// raw error text, reference bodies, or group IDs. +type SupportNotification struct { + CaseID string + TriggerType string + Question string + SenderName string + Channel string + ConversationType core.ConversationType + AskedAt time.Time + PreviousQuestions []string + FAQRecordID string +} + +// PendingSupportCase holds the data needed to send a notification for a +// support case that is pending notification. +type PendingSupportCase struct { + SupportNotification + Attempts int +} + +// NotificationRepository manages the notification lifecycle of support_cases. +type NotificationRepository interface { + // Claim atomically claims up to limit pending/retryable/expired-notifying + // support cases. Each case must have attempts < maxAttempts. Cases stuck + // in notifying with last_notification_at older than staleBefore are also + // eligible. Returns the claimed cases with their notification data. + Claim(ctx context.Context, limit int, maxAttempts int, staleBefore time.Time) ([]PendingSupportCase, error) + + // MarkNotified transitions a case from notifying to notified. + // RowsAffected must be exactly 1. + MarkNotified(ctx context.Context, caseID string) error + + // MarkFailed transitions a case from notifying to notification_failed + // with a stable failure code. Raw errors must never be written. + // RowsAffected must be exactly 1. + MarkFailed(ctx context.Context, caseID string, failureCode string) error +} + +// Notifier sends a notification. Matches the signature of +// dingtalk.SupportGroupSender.Send. +type Notifier interface { + Send(ctx context.Context, notif SupportNotification) error +} + +// DispatcherStats holds sanitized dispatch statistics. +type DispatcherStats struct { + Claimed int + Notified int + Failed int +} + +// DispatcherOption configures the Dispatcher. +type DispatcherOption func(*Dispatcher) + +// WithBatchSize sets the batch size (1..100). Default 10. +func WithBatchSize(n int) DispatcherOption { + return func(d *Dispatcher) { d.BatchSize = n } +} + +// WithMaxAttempts sets the max notification attempts (1..10). Default 3. +func WithMaxAttempts(n int) DispatcherOption { + return func(d *Dispatcher) { d.MaxAttempts = n } +} + +// WithClaimLease sets the stale-notifying lease duration. Default 5 minutes. +func WithClaimLease(dur time.Duration) DispatcherOption { + return func(d *Dispatcher) { d.ClaimLease = dur } +} + +// WithSendTimeout sets the per-item send timeout. Default 30 seconds. +func WithSendTimeout(dur time.Duration) DispatcherOption { + return func(d *Dispatcher) { d.SendTimeout = dur } +} + +// Dispatcher claims pending support cases and sends them via the Notifier. +type Dispatcher struct { + repo NotificationRepository + notifier Notifier + BatchSize int + MaxAttempts int + ClaimLease time.Duration + SendTimeout time.Duration +} + +// NewDispatcher creates a validated Dispatcher with sensible defaults. +// Defaults: BatchSize=10, MaxAttempts=3, ClaimLease=5m, SendTimeout=30s. +func NewDispatcher(repo NotificationRepository, notifier Notifier, opts ...DispatcherOption) (*Dispatcher, error) { + if isNilDependency(repo) { + return nil, errors.New("dispatcher: NotificationRepository is required") + } + if isNilDependency(notifier) { + return nil, errors.New("dispatcher: Notifier is required") + } + d := &Dispatcher{ + repo: repo, + notifier: notifier, + BatchSize: 10, + MaxAttempts: 3, + ClaimLease: 5 * time.Minute, + SendTimeout: 30 * time.Second, + } + for _, o := range opts { + o(d) + } + if d.BatchSize < 1 || d.BatchSize > 100 { + return nil, fmt.Errorf("dispatcher: BatchSize must be 1..100, got %d", d.BatchSize) + } + if d.MaxAttempts < 1 || d.MaxAttempts > 10 { + return nil, fmt.Errorf("dispatcher: MaxAttempts must be 1..10, got %d", d.MaxAttempts) + } + if d.ClaimLease <= 0 || d.ClaimLease > 24*time.Hour { + return nil, fmt.Errorf("dispatcher: ClaimLease must be >0 and <=24h, got %v", d.ClaimLease) + } + if d.SendTimeout <= 0 || d.SendTimeout > 24*time.Hour { + return nil, fmt.Errorf("dispatcher: SendTimeout must be >0 and <=24h, got %v", d.SendTimeout) + } + return d, nil +} + +func isNilDependency(value any) bool { + if value == nil { + return true + } + v := reflect.ValueOf(value) + switch v.Kind() { + case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Pointer, reflect.Slice: + return v.IsNil() + default: + return false + } +} diff --git a/internal/coverage/notification_test.go b/internal/coverage/notification_test.go new file mode 100644 index 0000000..073d233 --- /dev/null +++ b/internal/coverage/notification_test.go @@ -0,0 +1,59 @@ +// Package coverage defines the domain logic for coverage evaluation. +package coverage + +import ( + "reflect" + "testing" + "time" + + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/core" +) + +func TestSupportNotificationCarriesCustomerQuestionContext(t *testing.T) { + askedAt := time.Date(2026, 7, 24, 10, 16, 35, 0, time.FixedZone("CST", 8*60*60)) + notif := SupportNotification{ + CaseID: "case-001", + Question: "Nova5I具体支持哪些通信协议?", + SenderName: "张三", + Channel: "dingtalk", + ConversationType: core.ConversationGroup, + AskedAt: askedAt, + PreviousQuestions: []string{ + "Nova5I如何配置Modbus TCP?", + "Nova5I是否支持EtherCAT?", + }, + FAQRecordID: "record-001", + } + + if notif.Question != "Nova5I具体支持哪些通信协议?" || notif.SenderName != "张三" { + t.Fatalf("current question context mismatch: %+v", notif) + } + if !notif.AskedAt.Equal(askedAt) { + t.Fatalf("AskedAt = %v, want %v", notif.AskedAt, askedAt) + } + if len(notif.PreviousQuestions) != 2 || notif.PreviousQuestions[0] != "Nova5I如何配置Modbus TCP?" { + t.Fatalf("PreviousQuestions = %#v", notif.PreviousQuestions) + } + if notif.FAQRecordID != "record-001" { + t.Fatalf("FAQRecordID = %q", notif.FAQRecordID) + } +} + +func TestSupportNotificationExcludesAnswerAndRetrievalDiagnostics(t *testing.T) { + typ := reflect.TypeOf(SupportNotification{}) + for _, forbidden := range []string{"Answer", "ReferenceCount", "TopScore", "References", "Confidence"} { + if _, ok := typ.FieldByName(forbidden); ok { + t.Errorf("SupportNotification must not expose %s", forbidden) + } + } +} + +func TestSupportNotificationEmptyValues(t *testing.T) { + notif := SupportNotification{} + if notif.CaseID != "" || notif.Question != "" || notif.FAQRecordID != "" { + t.Fatalf("expected safe zero value: %+v", notif) + } + if len(notif.PreviousQuestions) != 0 || !notif.AskedAt.IsZero() { + t.Fatalf("expected empty history and time: %+v", notif) + } +} diff --git a/internal/coverage/service.go b/internal/coverage/service.go new file mode 100644 index 0000000..46ba031 --- /dev/null +++ b/internal/coverage/service.go @@ -0,0 +1,53 @@ +package coverage + +import ( + "context" + "errors" + "fmt" + + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/core" +) + +// Service evaluates turns and persists coverage decisions. +type Service struct { + evaluator *Evaluator + repo Repository +} + +// NewService creates a coverage Service. repo must not be nil. +func NewService(repo Repository) (*Service, error) { + if repo == nil { + return nil, errors.New("coverage service: repository must not be nil") + } + return &Service{ + evaluator: NewEvaluator(), + repo: repo, + }, nil +} + +// ObserveSucceededTurn adapts Service to the QA succeeded-turn observer. +// The decision is persisted durably before QA returns; callers decide how to +// report the error without changing the successful QA result. +func (s *Service) ObserveSucceededTurn(ctx context.Context, turn core.Turn) error { + _, err := s.EvaluateAndPersist(ctx, turn) + return err +} + +// EvaluateAndPersist evaluates a turn and persists the resulting decision. +// For uncovered verdicts the Repository atomically creates a pending +// support case. The operation is idempotent — replaying the same +// (tenant_key, channel, turn_id) is safe. +// +// Failed and processing turns are rejected with ErrTurnNotSucceeded. +func (s *Service) EvaluateAndPersist(ctx context.Context, turn core.Turn) (Decision, error) { + d, err := s.evaluator.Evaluate(turn) + if err != nil { + return Decision{}, fmt.Errorf("evaluate: %w", err) + } + + if err := s.repo.SaveCoverageDecision(ctx, d); err != nil { + return Decision{}, fmt.Errorf("save coverage decision: %w", err) + } + + return d, nil +} diff --git a/internal/coverage/service_test.go b/internal/coverage/service_test.go new file mode 100644 index 0000000..8265ef0 --- /dev/null +++ b/internal/coverage/service_test.go @@ -0,0 +1,214 @@ +package coverage + +import ( + "context" + "testing" + + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/core" +) + +// mockRepo implements Repository for testing. +type mockRepo struct { + saved []Decision + err error +} + +func (m *mockRepo) SaveCoverageDecision(_ context.Context, d Decision) error { + if m.err != nil { + return m.err + } + m.saved = append(m.saved, d) + return nil +} + +func TestNewService_RejectsNilRepo(t *testing.T) { + _, err := NewService(nil) + if err == nil { + t.Fatal("expected error for nil repo, got nil") + } +} + +func TestNewService_SucceedsWithRepo(t *testing.T) { + s, err := NewService(&mockRepo{}) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if s == nil { + t.Fatal("expected non-nil service") + } +} + +func TestService_EvaluateAndPersist_Covered(t *testing.T) { + repo := &mockRepo{} + s, err := NewService(repo) + if err != nil { + t.Fatal(err) + } + + turn := core.Turn{ + ID: "turn-1", + TenantKey: "t1", + Channel: "dingtalk", + Status: "succeeded", + Answer: "根据知识库,答案是...", + References: []core.Reference{ + {ID: "r1", Score: 0.9}, + }, + } + + d, err := s.EvaluateAndPersist(context.Background(), turn) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if d.Verdict != VerdictCovered { + t.Errorf("verdict = %s, want covered", d.Verdict) + } + if len(repo.saved) != 1 { + t.Fatalf("expected 1 saved decision, got %d", len(repo.saved)) + } + if repo.saved[0].Verdict != VerdictCovered { + t.Errorf("saved verdict = %s, want covered", repo.saved[0].Verdict) + } +} + +func TestService_EvaluateAndPersist_UncoveredNoReferences(t *testing.T) { + repo := &mockRepo{} + s, _ := NewService(repo) + + turn := core.Turn{ + ID: "turn-2", + TenantKey: "t1", + Channel: "dingtalk", + Status: "succeeded", + Answer: "正常回答但没有引用", + } + + d, err := s.EvaluateAndPersist(context.Background(), turn) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if d.Verdict != VerdictUncovered { + t.Errorf("verdict = %s, want uncovered", d.Verdict) + } + if d.ReasonCode != ReasonUncoveredNoReferences { + t.Errorf("reason_code = %s, want %s", d.ReasonCode, ReasonUncoveredNoReferences) + } + if len(repo.saved) != 1 { + t.Fatalf("expected 1 saved decision, got %d", len(repo.saved)) + } +} + +func TestService_EvaluateAndPersist_UncoveredExplicitNoAnswer(t *testing.T) { + repo := &mockRepo{} + s, _ := NewService(repo) + + turn := core.Turn{ + ID: "turn-3", + TenantKey: "t1", + Channel: "dingtalk", + Status: "succeeded", + Answer: "未找到相关结果", + References: []core.Reference{ + {ID: "r1", Score: 0.5}, + }, + } + + d, err := s.EvaluateAndPersist(context.Background(), turn) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if d.Verdict != VerdictUncovered { + t.Errorf("verdict = %s, want uncovered", d.Verdict) + } + if d.ReasonCode != ReasonUncoveredExplicitNoAnswer { + t.Errorf("reason_code = %s, want %s", d.ReasonCode, ReasonUncoveredExplicitNoAnswer) + } +} + +func TestService_EvaluateAndPersist_RejectsFailedTurn(t *testing.T) { + repo := &mockRepo{} + s, _ := NewService(repo) + + turn := core.Turn{ + ID: "turn-4", + Status: "failed", + } + + _, err := s.EvaluateAndPersist(context.Background(), turn) + if err == nil { + t.Fatal("expected error for failed turn, got nil") + } + if len(repo.saved) != 0 { + t.Errorf("expected 0 saved decisions for failed turn, got %d", len(repo.saved)) + } +} + +func TestService_EvaluateAndPersist_PropagatesRepoError(t *testing.T) { + repo := &mockRepo{err: ErrRepository} + s, _ := NewService(repo) + + turn := core.Turn{ + ID: "turn-5", + Status: "succeeded", + Answer: "正常回答", + References: []core.Reference{ + {ID: "r1", Score: 0.5}, + }, + } + + _, err := s.EvaluateAndPersist(context.Background(), turn) + if err == nil { + t.Fatal("expected error from repo, got nil") + } +} + +func TestService_ObserveSucceededTurnPersistsDecision(t *testing.T) { + repo := &mockRepo{} + s, err := NewService(repo) + if err != nil { + t.Fatal(err) + } + turn := core.Turn{ + ID: "turn-observed", + TenantKey: "tenant", + Channel: "dingtalk", + Status: "succeeded", + Answer: "正常回答", + References: []core.Reference{ + {ID: "r1", Score: 0.5}, + }, + } + if err := s.ObserveSucceededTurn(context.Background(), turn); err != nil { + t.Fatalf("ObserveSucceededTurn: %v", err) + } + if len(repo.saved) != 1 || repo.saved[0].TurnID != "turn-observed" { + t.Fatalf("saved=%+v, want turn-observed", repo.saved) + } +} + +func TestService_EvaluateAndPersist_DecisionHasEvaluatorVersion(t *testing.T) { + repo := &mockRepo{} + s, _ := NewService(repo) + + turn := core.Turn{ + ID: "turn-6", + TenantKey: "t1", + Channel: "dingtalk", + Status: "succeeded", + Answer: "正常回答", + References: []core.Reference{ + {ID: "r1", Score: 0.5}, + }, + } + + d, err := s.EvaluateAndPersist(context.Background(), turn) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if d.EvaluatorVersion != EvaluatorVersion { + t.Errorf("evaluator_version = %s, want %s", d.EvaluatorVersion, EvaluatorVersion) + } + if repo.saved[0].EvaluatorVersion != EvaluatorVersion { + t.Errorf("saved evaluator_version = %s, want %s", repo.saved[0].EvaluatorVersion, EvaluatorVersion) + } +} diff --git a/internal/coverage/trigger_test.go b/internal/coverage/trigger_test.go new file mode 100644 index 0000000..d344942 --- /dev/null +++ b/internal/coverage/trigger_test.go @@ -0,0 +1,10 @@ +package coverage + +import "testing" + +func TestSupportNotificationAcceptsAuditableTriggerType(t *testing.T) { + notification := SupportNotification{TriggerType: SupportTriggerFeedbackDown} + if notification.TriggerType != "feedback_down" { + t.Fatalf("trigger=%q", notification.TriggerType) + } +} diff --git a/internal/coverage/types.go b/internal/coverage/types.go new file mode 100644 index 0000000..086815a --- /dev/null +++ b/internal/coverage/types.go @@ -0,0 +1,61 @@ +// Package coverage implements the domain logic for evaluating whether a QA +// turn is covered by the knowledge base and persisting the resulting decision. +// +// The Evaluator classifies a successful turn into one of three outcomes: +// - covered_has_references: the answer uses knowledge-base references +// - uncovered_no_references: the answer has no references +// - uncovered_explicit_no_answer: the answer is an explicit "no answer" phrase +// +// The Service delegates persistence to a Repository. For uncovered turns it +// atomically writes the decision and creates a pending support case. For +// covered turns it only persists the decision. All writes are idempotent via +// ON CONFLICT (tenant_key, channel, turn_id). +package coverage + +import ( + "context" + "errors" +) + +// Verdict values. +const ( + VerdictCovered = "covered" + VerdictUncovered = "uncovered" +) + +// ReasonCode values. +const ( + ReasonCoveredHasReferences = "covered_has_references" + ReasonUncoveredNoReferences = "uncovered_no_references" + ReasonUncoveredExplicitNoAnswer = "uncovered_explicit_no_answer" + ReasonCoveredVisualRecognition = "covered_visual_recognition" +) + +// EvaluatorVersion is the current version of the evaluator. +const EvaluatorVersion = "v3" + +var ( + ErrTurnNotSucceeded = errors.New("coverage evaluator: turn status must be succeeded") + ErrRepository = errors.New("coverage repository error") +) + +// Decision is the result of evaluating a single turn. +type Decision struct { + TurnID string + TenantKey string + Channel string + EvaluatorVersion string + Verdict string + ReasonCode string + ReferenceCount int + TopScore float64 +} + +// Repository persists coverage decisions and, when applicable, support cases. +type Repository interface { + // SaveCoverageDecision persists a decision. For uncovered verdicts it + // must also atomically create a pending support case. The call is + // idempotent — replayed decisions for the same (tenant_key, channel, + // turn_id) must not create duplicates. + SaveCoverageDecision(ctx context.Context, d Decision) error +} diff --git a/internal/dingtalkconfig/verifier.go b/internal/dingtalkconfig/verifier.go new file mode 100644 index 0000000..1d1540b --- /dev/null +++ b/internal/dingtalkconfig/verifier.go @@ -0,0 +1,69 @@ +package dingtalkconfig + +import ( + "context" + "encoding/json" + "io" + "net/http" + "net/url" + "strings" + "time" +) + +type Result struct { + OK bool + Code string + CheckedAt time.Time +} +type Verifier struct { + endpoint string + client *http.Client +} + +func NewVerifier(endpoint string, client *http.Client) *Verifier { + if client == nil { + client = &http.Client{Timeout: 10 * time.Second} + } + return &Verifier{endpoint: strings.TrimSpace(endpoint), client: client} +} +func (v *Verifier) Verify(ctx context.Context, id, secret string) Result { + r := Result{Code: "verification_failed", CheckedAt: time.Now().UTC()} + if strings.TrimSpace(id) == "" || strings.TrimSpace(secret) == "" { + r.Code = "credential_incomplete" + return r + } + u, err := url.Parse(v.endpoint) + if err != nil { + r.Code = "endpoint_invalid" + return r + } + q := u.Query() + q.Set("appkey", id) + q.Set("appsecret", secret) + u.RawQuery = q.Encode() + req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil) + if err != nil { + return r + } + resp, err := v.client.Do(req) + if err != nil { + r.Code = "network_error" + return r + } + defer resp.Body.Close() + var body struct { + ErrCode int `json:"errcode"` + AccessToken string `json:"access_token"` + } + if json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(&body) != nil { + r.Code = "invalid_response" + return r + } + if resp.StatusCode < 200 || resp.StatusCode >= 300 || body.ErrCode != 0 || strings.TrimSpace(body.AccessToken) == "" { + r.Code = "credential_rejected" + return r + } + r.OK = true + r.Code = "ok" + return r +} diff --git a/internal/dingtalkconfig/verifier_test.go b/internal/dingtalkconfig/verifier_test.go new file mode 100644 index 0000000..dff6b94 --- /dev/null +++ b/internal/dingtalkconfig/verifier_test.go @@ -0,0 +1,35 @@ +package dingtalkconfig + +import ( + "context" + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +func TestVerifierNeverReturnsToken(t *testing.T) { + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"errcode":0,"access_token":"secret-token"}`)) + })) + defer ts.Close() + v := NewVerifier(ts.URL, ts.Client()) + result := v.Verify(context.Background(), "id", "secret") + if !result.OK { + t.Fatalf("result=%+v", result) + } + if strings.Contains(result.Code, "secret-token") { + t.Fatal("token leaked") + } +} +func TestVerifierRejectsBadCredential(t *testing.T) { + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, _ = w.Write([]byte(`{"errcode":40014,"errmsg":"bad secret"}`)) + })) + defer ts.Close() + result := NewVerifier(ts.URL, ts.Client()).Verify(context.Background(), "id", "wrong") + if result.OK || result.Code != "credential_rejected" { + t.Fatalf("result=%+v", result) + } +} diff --git a/internal/directory/dingtalk_lookup.go b/internal/directory/dingtalk_lookup.go new file mode 100644 index 0000000..44432e4 --- /dev/null +++ b/internal/directory/dingtalk_lookup.go @@ -0,0 +1,121 @@ +package directory + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "net/http" + "net/url" + "strconv" + "strings" + "sync" + "time" +) + +type DingTalkLookupConfig struct { + TokenURL string + APIBaseURL string + ClientID string + ClientSecret string + Timeout time.Duration +} + +type DingTalkLookup struct { + tokenURL string + apiBaseURL string + clientID string + clientSecret string + httpClient *http.Client + mu sync.Mutex + token string + tokenExpiry time.Time + now func() time.Time +} + +func NewDingTalkLookup(cfg DingTalkLookupConfig) (*DingTalkLookup, error) { + cfg.TokenURL = strings.TrimSpace(cfg.TokenURL) + cfg.APIBaseURL = strings.TrimRight(strings.TrimSpace(cfg.APIBaseURL), "/") + if cfg.TokenURL == "" || cfg.APIBaseURL == "" || strings.TrimSpace(cfg.ClientID) == "" || strings.TrimSpace(cfg.ClientSecret) == "" { + return nil, errors.New("dingtalk lookup endpoints and credentials are required") + } + if _, err := url.ParseRequestURI(cfg.TokenURL); err != nil { return nil, errors.New("invalid dingtalk token endpoint") } + if _, err := url.ParseRequestURI(cfg.APIBaseURL); err != nil { return nil, errors.New("invalid dingtalk API endpoint") } + if cfg.Timeout <= 0 { cfg.Timeout = 10 * time.Second } + return &DingTalkLookup{ + tokenURL: cfg.TokenURL, apiBaseURL: cfg.APIBaseURL, + clientID: cfg.ClientID, clientSecret: cfg.ClientSecret, + httpClient: &http.Client{Timeout: cfg.Timeout}, now: time.Now, + }, nil +} + +func (c *DingTalkLookup) LookupUser(ctx context.Context, staffID string) (Profile, error) { + staffID = strings.TrimSpace(staffID) + if staffID == "" { return Profile{}, errors.New("dingtalk user id is required") } + token, err := c.accessToken(ctx) + if err != nil { return Profile{}, err } + payload, _ := json.Marshal(map[string]string{"userid": staffID}) + endpoint := c.apiBaseURL + "/topapi/v2/user/get?access_token=" + url.QueryEscape(token) + req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(payload)) + if err != nil { return Profile{}, errors.New("dingtalk user request failed") } + req.Header.Set("Content-Type", "application/json") + resp, err := c.httpClient.Do(req) + if err != nil { return Profile{}, errors.New("dingtalk user request failed") } + defer resp.Body.Close() + if resp.StatusCode < 200 || resp.StatusCode >= 300 { return Profile{}, errors.New("dingtalk user HTTP failure") } + var decoded struct { + ErrCode int `json:"errcode"` + Result struct { + UserID string `json:"userid"` + UnionID string `json:"unionid"` + Name string `json:"name"` + Nickname string `json:"nickname"` + Title string `json:"title"` + DepartmentIDs []int64 `json:"dept_id_list"` + Status int `json:"status"` + } `json:"result"` + } + if err := json.NewDecoder(resp.Body).Decode(&decoded); err != nil || decoded.ErrCode != 0 { + return Profile{}, errors.New("dingtalk user response invalid") + } + ids := make([]string, 0, len(decoded.Result.DepartmentIDs)) + for _, id := range decoded.Result.DepartmentIDs { ids = append(ids, strconv.FormatInt(id, 10)) } + return Profile{ + StaffID: staffID, UnionID: decoded.Result.UnionID, Name: strings.TrimSpace(decoded.Result.Name), + Nickname: decoded.Result.Nickname, JobTitle: decoded.Result.Title, DepartmentIDs: ids, + EmploymentStatus: strconv.Itoa(decoded.Result.Status), Source: SourceOnDemand, SyncedAt: c.now().UTC(), + }, nil +} + +func (c *DingTalkLookup) accessToken(ctx context.Context) (string, error) { + c.mu.Lock() + defer c.mu.Unlock() + if c.token != "" && c.now().Before(c.tokenExpiry) { return c.token, nil } + parsed, err := url.Parse(c.tokenURL) + if err != nil { return "", errors.New("dingtalk token request failed") } + query := parsed.Query() + query.Set("appkey", c.clientID) + query.Set("appsecret", c.clientSecret) + parsed.RawQuery = query.Encode() + req, err := http.NewRequestWithContext(ctx, http.MethodGet, parsed.String(), nil) + if err != nil { return "", errors.New("dingtalk token request failed") } + resp, err := c.httpClient.Do(req) + if err != nil { return "", errors.New("dingtalk token request failed") } + defer resp.Body.Close() + if resp.StatusCode < 200 || resp.StatusCode >= 300 { return "", errors.New("dingtalk token HTTP failure") } + var decoded struct { + ErrCode int `json:"errcode"` + AccessToken string `json:"access_token"` + ExpiresIn int `json:"expires_in"` + } + if err := json.NewDecoder(resp.Body).Decode(&decoded); err != nil || decoded.ErrCode != 0 || decoded.AccessToken == "" { + return "", errors.New("dingtalk token response invalid") + } + ttl := time.Duration(decoded.ExpiresIn) * time.Second + if ttl <= 0 { ttl = time.Hour } + refreshMargin := 5 * time.Minute + if ttl <= refreshMargin { refreshMargin = ttl / 2 } + c.token = decoded.AccessToken + c.tokenExpiry = c.now().Add(ttl - refreshMargin) + return c.token, nil +} diff --git a/internal/directory/dingtalk_lookup_test.go b/internal/directory/dingtalk_lookup_test.go new file mode 100644 index 0000000..aebf80b --- /dev/null +++ b/internal/directory/dingtalk_lookup_test.go @@ -0,0 +1,81 @@ +package directory + +import ( + "context" + "fmt" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" + "time" +) + +func TestDingTalkLookupFetchesUserAndCachesToken(t *testing.T) { + var tokenCalls atomic.Int32 + var userCalls atomic.Int32 + mux := http.NewServeMux() + mux.HandleFunc("/gettoken", func(w http.ResponseWriter, r *http.Request) { + tokenCalls.Add(1) + if r.Method != http.MethodGet || r.URL.Query().Get("appkey") != "app-key" || r.URL.Query().Get("appsecret") != "app-secret" { + t.Fatalf("unexpected token request: %s %s", r.Method, r.URL.String()) + } + _, _ = w.Write([]byte(`{"errcode":0,"access_token":"token-secret","expires_in":7200}`)) + }) + mux.HandleFunc("/topapi/v2/user/get", func(w http.ResponseWriter, r *http.Request) { + userCalls.Add(1) + if r.Method != http.MethodPost || r.URL.Query().Get("access_token") != "token-secret" { + t.Fatalf("unexpected user request: %s %s", r.Method, r.URL.String()) + } + var body [256]byte + n, _ := r.Body.Read(body[:]) + if !strings.Contains(string(body[:n]), `"userid":"staff-1"`) { + t.Fatalf("unexpected body: %s", body[:n]) + } + _, _ = w.Write([]byte(`{"errcode":0,"result":{"userid":"staff-1","unionid":"union-1","name":"张三","nickname":"小张","title":"工程师","dept_id_list":[100,200],"status":5}}`)) + }) + server := httptest.NewServer(mux) + defer server.Close() + lookup, err := NewDingTalkLookup(DingTalkLookupConfig{ + TokenURL: server.URL + "/gettoken", APIBaseURL: server.URL, + ClientID: "app-key", ClientSecret: "app-secret", Timeout: 2 * time.Second, + }) + if err != nil { t.Fatal(err) } + for i := 0; i < 2; i++ { + profile, err := lookup.LookupUser(context.Background(), "staff-1") + if err != nil { t.Fatalf("LookupUser(%d): %v", i, err) } + if profile.Name != "张三" || profile.UnionID != "union-1" || profile.JobTitle != "工程师" || len(profile.DepartmentIDs) != 2 || profile.DepartmentIDs[1] != "200" { + t.Fatalf("profile=%+v", profile) + } + } + if tokenCalls.Load() != 1 || userCalls.Load() != 2 { + t.Fatalf("token calls=%d user calls=%d", tokenCalls.Load(), userCalls.Load()) + } +} + +func TestDingTalkLookupErrorsAreSanitized(t *testing.T) { + for _, failPath := range []string{"token", "user"} { + t.Run(failPath, func(t *testing.T) { + mux := http.NewServeMux() + mux.HandleFunc("/gettoken", func(w http.ResponseWriter, _ *http.Request) { + if failPath == "token" { http.Error(w, "raw-secret-body", 500); return } + _, _ = w.Write([]byte(`{"errcode":0,"access_token":"token-secret","expires_in":7200}`)) + }) + mux.HandleFunc("/topapi/v2/user/get", func(w http.ResponseWriter, _ *http.Request) { + http.Error(w, "raw-secret-body", 500) + }) + server := httptest.NewServer(mux) + defer server.Close() + lookup, err := NewDingTalkLookup(DingTalkLookupConfig{TokenURL: server.URL + "/gettoken", APIBaseURL: server.URL, ClientID: "app-key", ClientSecret: "app-secret", Timeout: time.Second}) + if err != nil { t.Fatal(err) } + _, err = lookup.LookupUser(context.Background(), "staff-secret") + if err == nil { t.Fatal("expected error") } + for _, forbidden := range []string{"raw-secret-body", "app-secret", "token-secret", "staff-secret"} { + if strings.Contains(err.Error(), forbidden) { t.Fatalf("error leaked %q: %v", forbidden, err) } + } + if !strings.Contains(err.Error(), fmt.Sprintf("dingtalk %s", failPath)) { + t.Fatalf("error=%q", err) + } + }) + } +} diff --git a/internal/directory/importer.go b/internal/directory/importer.go new file mode 100644 index 0000000..e96fcd4 --- /dev/null +++ b/internal/directory/importer.go @@ -0,0 +1,105 @@ +package directory + +import ( + "context" + "encoding/csv" + "errors" + "fmt" + "io" + "strings" + "time" +) + +var requiredCSVHeaders = []string{"user_id", "name", "dept_name"} + +// ImportCSV validates the complete snapshot before making one repository call. +// It consumes the tested Python sync output and accepts optional production +// enrichment columns without reimplementing the bulk DingTalk crawler in Go. +func ImportCSV(ctx context.Context, tenantKey string, input io.Reader, writer SnapshotWriter) (int, error) { + tenantKey = strings.TrimSpace(tenantKey) + if tenantKey == "" || input == nil || writer == nil { + return 0, errors.New("tenant, CSV input and writer are required") + } + r := csv.NewReader(input) + r.FieldsPerRecord = -1 + header, err := r.Read() + if err != nil { + return 0, fmt.Errorf("read directory CSV header: %w", err) + } + columns := make(map[string]int, len(header)) + for i, name := range header { + name = strings.TrimSpace(strings.TrimPrefix(name, "\ufeff")) + columns[name] = i + } + for _, name := range requiredCSVHeaders { + if _, ok := columns[name]; !ok { + return 0, fmt.Errorf("directory CSV missing required header %q", name) + } + } + + profiles := make([]Profile, 0, 256) + line := 1 + for { + record, readErr := r.Read() + if errors.Is(readErr, io.EOF) { + break + } + line++ + if readErr != nil { + return 0, fmt.Errorf("read directory CSV line %d: %w", line, readErr) + } + value := func(name string) string { + idx, ok := columns[name] + if !ok || idx >= len(record) { + return "" + } + return strings.TrimSpace(record[idx]) + } + staffID := value("user_id") + name := value("name") + if staffID == "" || name == "" { + return 0, fmt.Errorf("directory CSV line %d has empty user_id or name", line) + } + profiles = append(profiles, Profile{ + StaffID: staffID, + UnionID: value("union_id"), + Name: name, + Nickname: value("nickname"), + JobTitle: value("title"), + DepartmentIDs: splitDepartmentIDs(value("department_ids")), + DepartmentName: value("dept_name"), + MainDepartmentName: value("main_department_name"), + Region: value("region"), + EmploymentStatus: value("employment_status"), + Source: SourceFullSync, + SyncedAt: parseSyncTime(value("sync_time")), + }) + } + if len(profiles) == 0 { + return 0, errors.New("directory CSV snapshot is empty") + } + if err := writer.UpsertDirectoryProfiles(ctx, tenantKey, profiles); err != nil { + return 0, fmt.Errorf("write directory snapshot: %w", err) + } + return len(profiles), nil +} + +func splitDepartmentIDs(raw string) []string { + parts := strings.FieldsFunc(raw, func(r rune) bool { return r == '/' || r == ',' || r == ';' }) + out := make([]string, 0, len(parts)) + for _, part := range parts { + if part = strings.TrimSpace(part); part != "" { + out = append(out, part) + } + } + return out +} + +func parseSyncTime(raw string) time.Time { + for _, layout := range []string{time.RFC3339, "2006-01-02 15:04:05"} { + if parsed, err := time.Parse(layout, raw); err == nil { + return parsed + } + } + return time.Time{} +} diff --git a/internal/directory/importer_test.go b/internal/directory/importer_test.go new file mode 100644 index 0000000..33d3a57 --- /dev/null +++ b/internal/directory/importer_test.go @@ -0,0 +1,87 @@ +package directory + +import ( + "context" + "errors" + "strings" + "testing" +) + +type recordingWriter struct { + calls int + tenant string + profiles []Profile + err error +} + +func (w *recordingWriter) UpsertDirectoryProfiles(_ context.Context, tenant string, profiles []Profile) error { + w.calls++ + w.tenant = tenant + w.profiles = append([]Profile(nil), profiles...) + return w.err +} + +func TestImportCSVAcceptsTestedSyncOutputAndExtendedFields(t *testing.T) { + csv := "\ufeffuser_id,union_id,name,nickname,title,department_ids,dept_name,main_department_name,region,employment_status,sync_time,mobile\n" + + "staff-1,union-1, 张三 ,小张,工程师,100/200,公司/技术支持部,技术支持部,APAC,on_job,2026-07-22 02:30:00,13800000000\n" + writer := &recordingWriter{} + count, err := ImportCSV(context.Background(), "tenant-a", strings.NewReader(csv), writer) + if err != nil { + t.Fatalf("ImportCSV: %v", err) + } + if count != 1 || writer.calls != 1 || writer.tenant != "tenant-a" || len(writer.profiles) != 1 { + t.Fatalf("count=%d calls=%d tenant=%q profiles=%d", count, writer.calls, writer.tenant, len(writer.profiles)) + } + p := writer.profiles[0] + if p.StaffID != "staff-1" || p.Name != "张三" || p.DepartmentName != "公司/技术支持部" || p.MainDepartmentName != "技术支持部" || p.Region != "APAC" || p.EmploymentStatus != "on_job" || p.Source != SourceFullSync { + t.Fatalf("profile mismatch: %+v", p) + } + if len(p.DepartmentIDs) != 2 || p.DepartmentIDs[0] != "100" || p.DepartmentIDs[1] != "200" { + t.Fatalf("department ids: %v", p.DepartmentIDs) + } + // The domain type intentionally has no mobile/email/raw payload fields. +} + +func TestImportCSVAcceptsCurrentSevenColumnOutput(t *testing.T) { + csv := "user_id,union_id,name,nickname,title,department_ids,dept_name\n" + + "staff-2,union-2,李四,,经理,300,公司/销售部\n" + writer := &recordingWriter{} + count, err := ImportCSV(context.Background(), "tenant-a", strings.NewReader(csv), writer) + if err != nil { + t.Fatalf("ImportCSV: %v", err) + } + if count != 1 || writer.profiles[0].Name != "李四" || writer.profiles[0].Region != "" { + t.Fatalf("count=%d profile=%+v", count, writer.profiles[0]) + } +} + +func TestImportCSVRejectsInvalidSnapshotBeforeWrite(t *testing.T) { + tests := []struct { + name string + csv string + }{ + {name: "missing required header", csv: "user_id,dept_name\nstaff-1,技术支持部\n"}, + {name: "empty snapshot", csv: "user_id,name,dept_name\n"}, + {name: "empty staff id", csv: "user_id,name,dept_name\n,张三,技术支持部\n"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + writer := &recordingWriter{} + _, err := ImportCSV(context.Background(), "tenant-a", strings.NewReader(tt.csv), writer) + if err == nil { + t.Fatal("expected error") + } + if writer.calls != 0 { + t.Fatalf("writer called %d times before validation", writer.calls) + } + }) + } +} + +func TestImportCSVPropagatesWriterError(t *testing.T) { + writer := &recordingWriter{err: errors.New("db unavailable")} + _, err := ImportCSV(context.Background(), "tenant-a", strings.NewReader("user_id,name,dept_name\nstaff-1,张三,技术支持部\n"), writer) + if err == nil || writer.calls != 1 { + t.Fatalf("error=%v calls=%d", err, writer.calls) + } +} diff --git a/internal/directory/profile.go b/internal/directory/profile.go new file mode 100644 index 0000000..cc3f4e9 --- /dev/null +++ b/internal/directory/profile.go @@ -0,0 +1,32 @@ +package directory + +import ( + "context" + "time" +) + +const ( + SourceFullSync = "full_sync" + SourceOnDemand = "on_demand" +) + +// Profile is the minimum non-sensitive DingTalk directory record used by +// DobotAI. It deliberately excludes mobile, email, credentials and raw payloads. +type Profile struct { + StaffID string + UnionID string + Name string + Nickname string + JobTitle string + DepartmentIDs []string + DepartmentName string + MainDepartmentName string + Region string + EmploymentStatus string + Source string + SyncedAt time.Time +} + +type SnapshotWriter interface { + UpsertDirectoryProfiles(ctx context.Context, tenantKey string, profiles []Profile) error +} diff --git a/internal/directory/resolver.go b/internal/directory/resolver.go new file mode 100644 index 0000000..8a68131 --- /dev/null +++ b/internal/directory/resolver.go @@ -0,0 +1,65 @@ +package directory + +import ( + "context" + "errors" + "strings" + "time" +) + +type ProfileStore interface { + LookupDirectoryProfile(ctx context.Context, tenantKey, staffID string) (Profile, bool, error) + UpsertDirectoryProfiles(ctx context.Context, tenantKey string, profiles []Profile) error +} + +type UserLookup interface { + LookupUser(ctx context.Context, staffID string) (Profile, error) +} + +type Resolver struct { + store ProfileStore + lookup UserLookup + now func() time.Time +} + +func NewResolver(store ProfileStore, lookup UserLookup) (*Resolver, error) { + if store == nil { + return nil, errors.New("directory profile store is required") + } + return &Resolver{store: store, lookup: lookup, now: time.Now}, nil +} + +// ResolveUser always returns a safe callback-based fallback profile when the +// cache or on-demand lookup is unavailable. The diagnostic error is intentionally +// generic so identifiers and upstream payloads cannot leak into logs. +func (r *Resolver) ResolveUser(ctx context.Context, tenantKey, staffID, fallbackName string) (Profile, error) { + fallback := Profile{StaffID: strings.TrimSpace(staffID), Name: strings.TrimSpace(fallbackName)} + profile, found, err := r.store.LookupDirectoryProfile(ctx, tenantKey, fallback.StaffID) + if err != nil { + return fallback, errors.New("directory local lookup failed") + } + if found && strings.TrimSpace(profile.Name) != "" { + profile.Name = strings.TrimSpace(profile.Name) + return profile, nil + } + if r.lookup == nil { + return fallback, nil + } + profile, err = r.lookup.LookupUser(ctx, fallback.StaffID) + if err != nil { + return fallback, errors.New("directory on-demand lookup failed") + } + profile.StaffID = fallback.StaffID + profile.Name = strings.TrimSpace(profile.Name) + if profile.Name == "" { + return fallback, errors.New("directory on-demand lookup returned no name") + } + profile.Source = SourceOnDemand + if profile.SyncedAt.IsZero() { + profile.SyncedAt = r.now().UTC() + } + if err := r.store.UpsertDirectoryProfiles(ctx, tenantKey, []Profile{profile}); err != nil { + return profile, errors.New("directory on-demand cache write failed") + } + return profile, nil +} diff --git a/internal/directory/resolver_test.go b/internal/directory/resolver_test.go new file mode 100644 index 0000000..4b8b87a --- /dev/null +++ b/internal/directory/resolver_test.go @@ -0,0 +1,93 @@ +package directory + +import ( + "context" + "errors" + "testing" +) + +type fakeStore struct { + profile Profile + found bool + readErr error + writeErr error + writes int +} + +func (s *fakeStore) LookupDirectoryProfile(context.Context, string, string) (Profile, bool, error) { + return s.profile, s.found, s.readErr +} +func (s *fakeStore) UpsertDirectoryProfiles(_ context.Context, _ string, profiles []Profile) error { + s.writes++ + if len(profiles) > 0 { + s.profile = profiles[0] + } + return s.writeErr +} + +type fakeLookup struct { + profile Profile + err error + calls int +} +func (l *fakeLookup) LookupUser(context.Context, string) (Profile, error) { + l.calls++ + return l.profile, l.err +} + +func TestResolverUsesLocalProfileWithoutRemoteLookup(t *testing.T) { + store := &fakeStore{profile: Profile{StaffID: "staff-1", Name: "张三", DepartmentName: "技术支持部", Region: "APAC"}, found: true} + lookup := &fakeLookup{} + resolver, err := NewResolver(store, lookup) + if err != nil { t.Fatal(err) } + profile, err := resolver.ResolveUser(context.Background(), "tenant-a", "staff-1", "昵称") + if err != nil { t.Fatalf("ResolveUser: %v", err) } + if profile.Name != "张三" || lookup.calls != 0 || store.writes != 0 { + t.Fatalf("profile=%+v lookup=%d writes=%d", profile, lookup.calls, store.writes) + } +} + +func TestResolverLooksUpAndCachesMissingUser(t *testing.T) { + store := &fakeStore{} + lookup := &fakeLookup{profile: Profile{Name: "李四", DepartmentName: "销售部", Region: "EMEA"}} + resolver, err := NewResolver(store, lookup) + if err != nil { t.Fatal(err) } + profile, err := resolver.ResolveUser(context.Background(), "tenant-a", "staff-2", "昵称") + if err != nil { t.Fatalf("ResolveUser: %v", err) } + if profile.StaffID != "staff-2" || profile.Name != "李四" || profile.Source != SourceOnDemand || lookup.calls != 1 || store.writes != 1 { + t.Fatalf("profile=%+v lookup=%d writes=%d", profile, lookup.calls, store.writes) + } +} + +func TestResolverFallsBackWithoutBlockingOnFailures(t *testing.T) { + tests := []struct{ + name string + store *fakeStore + lookup *fakeLookup + }{ + {name: "local read fails", store: &fakeStore{readErr: errors.New("db unavailable")}, lookup: &fakeLookup{}}, + {name: "remote lookup fails", store: &fakeStore{}, lookup: &fakeLookup{err: errors.New("remote unavailable")}}, + {name: "cache write fails but resolved profile survives", store: &fakeStore{writeErr: errors.New("db unavailable")}, lookup: &fakeLookup{profile: Profile{Name: "王五"}}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + resolver, err := NewResolver(tt.store, tt.lookup) + if err != nil { t.Fatal(err) } + profile, resolveErr := resolver.ResolveUser(context.Background(), "tenant-a", "staff-3", " 回调昵称 ") + if profile.Name == "" { t.Fatalf("empty fallback profile: %+v", profile) } + if tt.name != "cache write fails but resolved profile survives" && profile.Name != "回调昵称" { + t.Fatalf("profile name=%q, want fallback", profile.Name) + } + if resolveErr == nil { t.Fatal("expected diagnostic error") } + }) + } +} + +func TestResolverWithoutRemoteUsesFallback(t *testing.T) { + resolver, err := NewResolver(&fakeStore{}, nil) + if err != nil { t.Fatal(err) } + profile, err := resolver.ResolveUser(context.Background(), "tenant-a", "staff-4", "赵六") + if err != nil || profile.Name != "赵六" || profile.StaffID != "staff-4" { + t.Fatalf("profile=%+v err=%v", profile, err) + } +} diff --git a/internal/faqtable/dispatcher.go b/internal/faqtable/dispatcher.go new file mode 100644 index 0000000..5ed21f3 --- /dev/null +++ b/internal/faqtable/dispatcher.go @@ -0,0 +1,119 @@ +package faqtable + +import ( + "context" + "errors" + "reflect" + "strings" + "time" +) + +const FailureCodeRemoteInsertFailed = "remote_faq_table_insert_failed" + +type PendingExport struct { + CaseID string + Row Row + Attempts int +} + +type ExportRepository interface { + Claim(context.Context, int, int, time.Time) ([]PendingExport, error) + MarkExported(context.Context, string, string) error + MarkFailed(context.Context, string, string) error +} + +type FieldsInserter interface { + InsertFields(context.Context, map[string]interface{}) (string, error) +} + +type DispatcherOptions struct { + Batch int + MaxAttempts int + ClaimLease time.Duration + SendTimeout time.Duration +} + +type DispatcherStats struct { + Claimed int + Exported int + Failed int +} + +type Dispatcher struct { + repo ExportRepository + inserter FieldsInserter + batch int + maxAttempts int + claimLease time.Duration + sendTimeout time.Duration +} + +func NewDispatcher(repo ExportRepository, inserter FieldsInserter, opts *DispatcherOptions) (*Dispatcher, error) { + if isNil(repo) || isNil(inserter) { + return nil, errors.New("faqtable dispatcher dependencies are required") + } + d := &Dispatcher{repo: repo, inserter: inserter, batch: 10, maxAttempts: 5, claimLease: 5 * time.Minute, sendTimeout: 10 * time.Second} + if opts != nil { + if opts.Batch < 0 || opts.MaxAttempts < 0 || opts.ClaimLease < 0 || opts.SendTimeout < 0 { + return nil, errors.New("faqtable dispatcher options are invalid") + } + if opts.Batch > 0 { + d.batch = opts.Batch + } + if opts.MaxAttempts > 0 { + d.maxAttempts = opts.MaxAttempts + } + if opts.ClaimLease > 0 { + d.claimLease = opts.ClaimLease + } + if opts.SendTimeout > 0 { + d.sendTimeout = opts.SendTimeout + } + } + return d, nil +} + +func (d *Dispatcher) RunOnce(ctx context.Context) (DispatcherStats, error) { + var stats DispatcherStats + if err := ctx.Err(); err != nil { + return stats, err + } + items, err := d.repo.Claim(ctx, d.batch, d.maxAttempts, time.Now().Add(-d.claimLease)) + if err != nil { + return stats, errors.New("faqtable dispatcher claim failed") + } + stats.Claimed = len(items) + for _, item := range items { + if err := ctx.Err(); err != nil { + return stats, err + } + itemCtx, cancel := context.WithTimeout(ctx, d.sendTimeout) + recordID, insertErr := d.inserter.InsertFields(itemCtx, item.Row.ToFields()) + cancel() + if insertErr != nil || strings.TrimSpace(recordID) == "" { + if err := d.repo.MarkFailed(ctx, item.CaseID, FailureCodeRemoteInsertFailed); err != nil { + return stats, errors.New("faqtable dispatcher mark failed failed") + } + stats.Failed++ + continue + } + if err := d.repo.MarkExported(ctx, item.CaseID, recordID); err != nil { + return stats, errors.New("faqtable dispatcher mark exported failed") + } + stats.Exported++ + } + return stats, nil +} + +func isNil(value interface{}) bool { + if value == nil { + return true + } + v := reflect.ValueOf(value) + switch v.Kind() { + case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice: + return v.IsNil() + default: + return false + } +} diff --git a/internal/faqtable/dispatcher_test.go b/internal/faqtable/dispatcher_test.go new file mode 100644 index 0000000..f99cb40 --- /dev/null +++ b/internal/faqtable/dispatcher_test.go @@ -0,0 +1,83 @@ +package faqtable + +import ( + "context" + "errors" + "testing" + "time" +) + +type dispatcherRepoStub struct { + items []PendingExport + exported map[string]string + failed map[string]string +} + +func (s *dispatcherRepoStub) Claim(context.Context, int, int, time.Time) ([]PendingExport, error) { + items := s.items + s.items = nil + return items, nil +} +func (s *dispatcherRepoStub) MarkExported(_ context.Context, id, recordID string) error { + if s.exported == nil { + s.exported = map[string]string{} + } + s.exported[id] = recordID + return nil +} +func (s *dispatcherRepoStub) MarkFailed(_ context.Context, id, code string) error { + if s.failed == nil { + s.failed = map[string]string{} + } + s.failed[id] = code + return nil +} + +type fieldsInserterStub struct { + fields map[string]interface{} + id string + err error +} + +func (s *fieldsInserterStub) InsertFields(_ context.Context, fields map[string]interface{}) (string, error) { + s.fields = fields + return s.id, s.err +} + +func TestDispatcherExportsFAQAndPersistsRecordID(t *testing.T) { + repo := &dispatcherRepoStub{items: []PendingExport{{ + CaseID: "case-1", + Row: Row{StandardQuestion: "中文问题", OriginalQuestion: "中文问题", AskerName: "张三", AskerUnionID: "union-1"}, + }}} + inserter := &fieldsInserterStub{id: "record-1"} + d, err := NewDispatcher(repo, inserter, nil) + if err != nil { + t.Fatal(err) + } + stats, err := d.RunOnce(context.Background()) + if err != nil { + t.Fatal(err) + } + if stats.Claimed != 1 || stats.Exported != 1 || stats.Failed != 0 { + t.Fatalf("stats=%+v", stats) + } + if repo.exported["case-1"] != "record-1" || inserter.fields[FieldLanguage] != "Chinese" { + t.Fatalf("exported=%#v fields=%#v", repo.exported, inserter.fields) + } +} + +func TestDispatcherPersistsOnlyStableFAQFailureCode(t *testing.T) { + repo := &dispatcherRepoStub{items: []PendingExport{{CaseID: "case-2", Row: Row{StandardQuestion: "secret question", OriginalQuestion: "secret question"}}}} + inserter := &fieldsInserterStub{err: errors.New("token=secret raw question=secret question")} + d, err := NewDispatcher(repo, inserter, &DispatcherOptions{SendTimeout: time.Second}) + if err != nil { + t.Fatal(err) + } + stats, err := d.RunOnce(context.Background()) + if err != nil { + t.Fatal(err) + } + if stats.Failed != 1 || repo.failed["case-2"] != FailureCodeRemoteInsertFailed { + t.Fatalf("stats=%+v failed=%#v", stats, repo.failed) + } +} diff --git a/internal/faqtable/row.go b/internal/faqtable/row.go new file mode 100644 index 0000000..ad8e639 --- /dev/null +++ b/internal/faqtable/row.go @@ -0,0 +1,116 @@ +package faqtable + +import ( + "errors" + "net/url" + "strings" + "unicode" +) + +// Verified DingTalk Notable FAQ field IDs. +const ( + FieldStandardQuestion = "01ZM8y7" // text: 标准问题(必填) + FieldOriginalQuestion = "fj3JQ1C" // text: 原始问题 + FieldLanguage = "07YYagS" // text: 语言 + FieldAsker = "Eu7gkKu" // user: 提问人 +) + +type Row struct { + StandardQuestion string + OriginalQuestion string + AskerName string + AskerUnionID string +} + +func (r Row) ToFields() map[string]interface{} { + fields := map[string]interface{}{ + FieldStandardQuestion: safeText(r.StandardQuestion), + FieldOriginalQuestion: safeText(r.OriginalQuestion), + FieldLanguage: DetectLanguage(r.OriginalQuestion), + } + if unionID := strings.TrimSpace(r.AskerUnionID); unionID != "" { + fields[FieldAsker] = []interface{}{map[string]interface{}{ + "name": strings.TrimSpace(r.AskerName), + "unionId": unionID, + }} + } + return fields +} + +func safeText(value string) string { + value = strings.TrimSpace(value) + if value == "" { + return "" + } + if strings.ContainsRune("=+-@", rune(value[0])) { + return "'" + value + } + return value +} + +func DetectLanguage(value string) string { + if strings.Contains(value, "日本語") { + return "Japanese" + } + var hasHan, hasKana, hasHangul, hasLatin, hasSpanish bool + for _, r := range value { + switch { + case unicode.In(r, unicode.Hiragana, unicode.Katakana): + hasKana = true + case unicode.In(r, unicode.Hangul): + hasHangul = true + case unicode.In(r, unicode.Han): + hasHan = true + case strings.ContainsRune("áéíóúüñÁÉÍÓÚÜÑ¿¡", r): + hasSpanish = true + case unicode.In(r, unicode.Latin): + hasLatin = true + } + } + switch { + case hasKana: + return "Japanese" + case hasHangul: + return "Korean" + case hasHan: + return "Chinese" + case hasSpanish: + return "Spanish" + case hasLatin: + return "English" + default: + return "Other" + } +} + +type RecordLinkBuilder struct { + baseID string + sheetID string + viewID string +} + +func NewRecordLinkBuilder(baseID, sheetID, viewID string) (*RecordLinkBuilder, error) { + baseID = strings.TrimSpace(baseID) + sheetID = strings.TrimSpace(sheetID) + viewID = strings.TrimSpace(viewID) + if baseID == "" || sheetID == "" || viewID == "" { + return nil, errors.New("faq record link configuration is incomplete") + } + return &RecordLinkBuilder{baseID: baseID, sheetID: sheetID, viewID: viewID}, nil +} + +func (b *RecordLinkBuilder) Build(recordID string) (string, error) { + if b == nil { + return "", errors.New("faq record link builder is unavailable") + } + recordID = strings.TrimSpace(recordID) + if recordID == "" { + return "", errors.New("faq record id is required") + } + q := url.Values{} + q.Set("dentryUuid", b.baseID) + q.Set("rowId", recordID) + q.Set("sheetId", b.sheetID) + q.Set("viewId", b.viewID) + return (&url.URL{Scheme: "https", Host: "docs.dingtalk.com", Path: "/notable/record", RawQuery: q.Encode()}).String(), nil +} diff --git a/internal/faqtable/row_test.go b/internal/faqtable/row_test.go new file mode 100644 index 0000000..df762c9 --- /dev/null +++ b/internal/faqtable/row_test.go @@ -0,0 +1,104 @@ +package faqtable + +import ( + "net/url" + "strings" + "testing" +) + +func TestRowToFieldsUsesVerifiedFAQContract(t *testing.T) { + fields := (Row{ + StandardQuestion: "Nova5I支持哪些通信协议?", + OriginalQuestion: "Nova5I支持哪些通信协议?", + AskerName: "测试用户", + AskerUnionID: "union-1", + }).ToFields() + + if got := fields[FieldStandardQuestion]; got != "Nova5I支持哪些通信协议?" { + t.Fatalf("standard question = %v", got) + } + if got := fields[FieldOriginalQuestion]; got != "Nova5I支持哪些通信协议?" { + t.Fatalf("original question = %v", got) + } + if got := fields[FieldLanguage]; got != "Chinese" { + t.Fatalf("language = %v, want Chinese", got) + } + users, ok := fields[FieldAsker].([]interface{}) + if !ok || len(users) != 1 { + t.Fatalf("asker shape = %#v", fields[FieldAsker]) + } + user, ok := users[0].(map[string]interface{}) + if !ok || user["name"] != "测试用户" || user["unionId"] != "union-1" { + t.Fatalf("asker = %#v", users[0]) + } + if len(fields) != 4 { + t.Fatalf("field count = %d, want exactly four", len(fields)) + } +} + +func TestRowToFieldsOmitsAskerWithoutUnionID(t *testing.T) { + fields := (Row{StandardQuestion: "Question", OriginalQuestion: "Question", AskerName: "name"}).ToFields() + if _, ok := fields[FieldAsker]; ok { + t.Fatal("asker must be omitted without unionId") + } +} + +func TestDetectLanguageUsesFAQEnglishEnums(t *testing.T) { + cases := map[string]string{ + "中文问题": "Chinese", + "日本語の質問": "Japanese", + "한국어 질문": "Korean", + "English question": "English", + "12345": "Other", + "日本語和漢字 mixed question": "Japanese", + } + for input, want := range cases { + if got := DetectLanguage(input); got != want { + t.Errorf("DetectLanguage(%q)=%q, want %q", input, got, want) + } + } +} + +func TestRowToFieldsProtectsFormulaInjection(t *testing.T) { + fields := (Row{StandardQuestion: "=cmd", OriginalQuestion: "+cmd"}).ToFields() + if fields[FieldStandardQuestion] != "'=cmd" || fields[FieldOriginalQuestion] != "'+cmd" { + t.Fatalf("fields not sanitised: %#v", fields) + } +} + +func TestRecordLinkBuilderUsesReturnedRecordIDAsRowID(t *testing.T) { + builder, err := NewRecordLinkBuilder("base+id", "sheet/id", "view id") + if err != nil { + t.Fatal(err) + } + got, err := builder.Build("record&id") + if err != nil { + t.Fatal(err) + } + parsed, err := url.Parse(got) + if err != nil { + t.Fatal(err) + } + if parsed.Scheme != "https" || parsed.Host != "docs.dingtalk.com" || parsed.Path != "/notable/record" { + t.Fatalf("unexpected link: %s", got) + } + q := parsed.Query() + if q.Get("dentryUuid") != "base+id" || q.Get("rowId") != "record&id" || q.Get("sheetId") != "sheet/id" || q.Get("viewId") != "view id" { + t.Fatalf("unexpected query: %#v", q) + } +} + +func TestRecordLinkBuilderRejectsMissingConfigOrRecordID(t *testing.T) { + for _, args := range [][3]string{{"", "s", "v"}, {"b", "", "v"}, {"b", "s", ""}} { + if _, err := NewRecordLinkBuilder(args[0], args[1], args[2]); err == nil { + t.Fatalf("expected error for %#v", args) + } + } + builder, err := NewRecordLinkBuilder("b", "s", "v") + if err != nil { + t.Fatal(err) + } + if _, err := builder.Build(" "); err == nil || strings.Contains(err.Error(), "b") { + t.Fatalf("expected sanitised missing record error, got %v", err) + } +} diff --git a/internal/httpapi/server.go b/internal/httpapi/server.go index 0355a06..0bb21b6 100644 --- a/internal/httpapi/server.go +++ b/internal/httpapi/server.go @@ -25,9 +25,16 @@ type AuditService interface { GetTurn(context.Context, string) (audit.TurnDetail, error) } +type BuildInfo struct { + Version string `json:"version"` + CommitSHA string `json:"commit_sha"` + BuildTime string `json:"build_time"` +} + type Options struct { AuditService AuditService AdminToken string + BuildInfo BuildInfo } type Server struct { @@ -35,6 +42,7 @@ type Server struct { ingressToken string auditService AuditService adminToken string + buildInfo BuildInfo mux *http.ServeMux } @@ -58,13 +66,25 @@ func NewWithOptions(service QAService, ingressToken string, opts Options) (*Serv if hasAdminToken && constantTimeTokenEqual(adminToken, ingressToken) { return nil, errors.New("DOBOTAI_ADMIN_TOKEN must differ from DOBOTAI_INGRESS_TOKEN") } + buildInfo := opts.BuildInfo + if buildInfo.Version == "" { + buildInfo.Version = "dev" + } + if buildInfo.CommitSHA == "" { + buildInfo.CommitSHA = "unknown" + } + if buildInfo.BuildTime == "" { + buildInfo.BuildTime = "unknown" + } s := &Server{ service: service, ingressToken: ingressToken, auditService: opts.AuditService, adminToken: adminToken, - mux: http.NewServeMux(), + buildInfo: buildInfo, + mux: http.NewServeMux(), } s.mux.HandleFunc("GET /healthz", s.health) + s.mux.HandleFunc("GET /version", s.version) s.mux.HandleFunc("POST /v1/qa", s.authorizeToken(s.ingressToken, s.ask)) if hasAuditService { s.mux.HandleFunc("GET /v1/admin/audit/turns", s.authorizeToken(s.adminToken, s.listAuditTurns)) @@ -102,6 +122,11 @@ func (s *Server) health(w http.ResponseWriter, _ *http.Request) { writeJSON(w, http.StatusOK, map[string]string{"status": "ok"}) } +func (s *Server) version(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Cache-Control", "no-store") + writeJSON(w, http.StatusOK, s.buildInfo) +} + func (s *Server) ask(w http.ResponseWriter, r *http.Request) { r.Body = http.MaxBytesReader(w, r.Body, 1<<20) defer r.Body.Close() diff --git a/internal/httpapi/server_test.go b/internal/httpapi/server_test.go index 65b5a53..a063614 100644 --- a/internal/httpapi/server_test.go +++ b/internal/httpapi/server_test.go @@ -25,6 +25,46 @@ func (f *captureQA) Ask(_ context.Context, request core.QARequest) (core.QAResul return core.QAResult{TurnID: "turn-capture", Answer: "answer"}, nil } +func TestVersionEndpointReturnsBuildMetadataWithoutAuthentication(t *testing.T) { + server, err := NewWithOptions(fakeQA{}, "ingress-secret", Options{ + BuildInfo: BuildInfo{ + Version: "2.1.0", + CommitSHA: "abc123def456", + BuildTime: "2026-07-27T12:00:00Z", + }, + }) + if err != nil { + t.Fatal(err) + } + request := httptest.NewRequest(http.MethodGet, "/version", nil) + result := httptest.NewRecorder() + server.Handler().ServeHTTP(result, request) + if result.Code != http.StatusOK { + t.Fatalf("status=%d body=%s", result.Code, result.Body.String()) + } + if got := result.Header().Get("Cache-Control"); got != "no-store" { + t.Fatalf("Cache-Control=%q, want no-store", got) + } + want := `{"version":"2.1.0","commit_sha":"abc123def456","build_time":"2026-07-27T12:00:00Z"}` + if got := strings.TrimSpace(result.Body.String()); got != want { + t.Fatalf("body=%s, want %s", got, want) + } +} + +func TestVersionEndpointUsesSafeDefaults(t *testing.T) { + server, err := New(fakeQA{}, "ingress-secret") + if err != nil { + t.Fatal(err) + } + request := httptest.NewRequest(http.MethodGet, "/version", nil) + result := httptest.NewRecorder() + server.Handler().ServeHTTP(result, request) + want := `{"version":"dev","commit_sha":"unknown","build_time":"unknown"}` + if got := strings.TrimSpace(result.Body.String()); result.Code != http.StatusOK || got != want { + t.Fatalf("status=%d body=%s, want %s", result.Code, got, want) + } +} + func TestQAEndpointRequiresTokenAndReturnsResult(t *testing.T) { server, err := New(fakeQA{}, "ingress-secret") if err != nil { diff --git a/internal/outboundimage/aliyun_oss.go b/internal/outboundimage/aliyun_oss.go new file mode 100644 index 0000000..6572fb4 --- /dev/null +++ b/internal/outboundimage/aliyun_oss.go @@ -0,0 +1,79 @@ +package outboundimage + +import ( + "bytes" + "context" + "errors" + "io" + "strings" + + "github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss" + "github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials" +) + +type AliyunOSSStore struct { + client *oss.Client + bucket string +} + +func NewAliyunOSSStore(endpoint, region, accessKeyID, accessKeySecret, bucket string) (*AliyunOSSStore, error) { + endpoint = strings.TrimSpace(endpoint) + region = strings.TrimSpace(region) + accessKeyID = strings.TrimSpace(accessKeyID) + accessKeySecret = strings.TrimSpace(accessKeySecret) + bucket = strings.TrimSpace(bucket) + if endpoint == "" || region == "" || accessKeyID == "" || accessKeySecret == "" || bucket == "" { + return nil, errors.New("outbound image: OSS endpoint, region, credentials, and bucket are required") + } + provider := credentials.NewStaticCredentialsProvider(accessKeyID, accessKeySecret, "") + config := oss.LoadDefaultConfig(). + WithCredentialsProvider(provider). + WithRegion(region). + WithEndpoint(endpoint) + return &AliyunOSSStore{client: oss.NewClient(config), bucket: bucket}, nil +} + +func (s *AliyunOSSStore) Put(ctx context.Context, key string, data []byte, contentType string) error { + if s == nil || s.client == nil || strings.TrimSpace(key) == "" || len(data) == 0 { + return errors.New("outbound image: invalid OSS put request") + } + _, err := s.client.PutObject(ctx, &oss.PutObjectRequest{ + Bucket: oss.Ptr(s.bucket), + Key: oss.Ptr(key), + Body: bytes.NewReader(data), + ContentType: oss.Ptr(contentType), + }) + if err != nil { + return errors.New("outbound image: OSS put failed") + } + return nil +} + +func (s *AliyunOSSStore) Get(ctx context.Context, key string, maxBytes int64) ([]byte, string, error) { + if s == nil || s.client == nil || strings.TrimSpace(key) == "" || maxBytes <= 0 { + return nil, "", errors.New("outbound image: invalid OSS get request") + } + result, err := s.client.GetObject(ctx, &oss.GetObjectRequest{ + Bucket: oss.Ptr(s.bucket), + Key: oss.Ptr(key), + }) + if err != nil { + return nil, "", errors.New("outbound image: OSS get failed") + } + defer result.Body.Close() + if result.ContentLength > maxBytes { + return nil, "", errors.New("outbound image: OSS object exceeds size limit") + } + data, err := io.ReadAll(io.LimitReader(result.Body, maxBytes+1)) + if err != nil { + return nil, "", errors.New("outbound image: OSS read failed") + } + if int64(len(data)) > maxBytes { + return nil, "", errors.New("outbound image: OSS object exceeds size limit") + } + contentType := "" + if result.ContentType != nil { + contentType = strings.TrimSpace(*result.ContentType) + } + return data, contentType, nil +} diff --git a/internal/outboundimage/aliyun_oss_test.go b/internal/outboundimage/aliyun_oss_test.go new file mode 100644 index 0000000..f79b8a4 --- /dev/null +++ b/internal/outboundimage/aliyun_oss_test.go @@ -0,0 +1,58 @@ +package outboundimage + +import ( + "context" + "net/http" + "net/http/httptest" + "testing" + + "github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss" + "github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials" +) + +func TestAliyunOSSStoreGetReturnsBoundedImageBytesAndMIME(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodGet || r.URL.Path != "/private-bucket/dobotai/im-images/id" { + t.Fatalf("method=%s path=%s", r.Method, r.URL.Path) + } + w.Header().Set("Content-Type", "image/png") + w.Header().Set("Content-Length", "4") + _, _ = w.Write([]byte("PNG!")) + })) + defer server.Close() + + config := oss.LoadDefaultConfig(). + WithCredentialsProvider(credentials.NewStaticCredentialsProvider("test-id", "test-secret", "")). + WithRegion("cn-test"). + WithEndpoint(server.URL). + WithUsePathStyle(true) + store := &AliyunOSSStore{client: oss.NewClient(config), bucket: "private-bucket"} + + data, contentType, err := store.Get(context.Background(), "dobotai/im-images/id", 4) + if err != nil { + t.Fatal(err) + } + if string(data) != "PNG!" || contentType != "image/png" { + t.Fatalf("data=%q contentType=%q", data, contentType) + } +} + +func TestAliyunOSSStoreGetRejectsOversizedObjects(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "image/png") + w.Header().Set("Content-Length", "5") + _, _ = w.Write([]byte("PNG!!")) + })) + defer server.Close() + + config := oss.LoadDefaultConfig(). + WithCredentialsProvider(credentials.NewStaticCredentialsProvider("test-id", "test-secret", "")). + WithRegion("cn-test"). + WithEndpoint(server.URL). + WithUsePathStyle(true) + store := &AliyunOSSStore{client: oss.NewClient(config), bucket: "private-bucket"} + + if _, _, err := store.Get(context.Background(), "dobotai/im-images/id", 4); err == nil { + t.Fatal("expected oversized object error") + } +} diff --git a/internal/outboundimage/publisher.go b/internal/outboundimage/publisher.go new file mode 100644 index 0000000..3ec7e25 --- /dev/null +++ b/internal/outboundimage/publisher.go @@ -0,0 +1,74 @@ +package outboundimage + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + "net/url" + "path" + "regexp" + "strings" +) + +var stableImageIDRE = regexp.MustCompile(`^[0-9a-f]{8}-[0-9a-f]{4}-5[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$`) + +type ObjectWriter interface { + Put(ctx context.Context, key string, data []byte, contentType string) error +} + +type StableHashPublisher struct { + store ObjectWriter + prefix string + publicBaseURL string +} + +func NewStableHashPublisher(store ObjectWriter, prefix, publicBaseURL string) (*StableHashPublisher, error) { + prefix = strings.Trim(strings.TrimSpace(prefix), "/") + publicBaseURL = strings.TrimRight(strings.TrimSpace(publicBaseURL), "/") + parsed, err := url.Parse(publicBaseURL) + if store == nil || prefix == "" || err != nil || parsed.Scheme != "https" || parsed.Host == "" || parsed.User != nil || parsed.RawQuery != "" || parsed.Fragment != "" { + return nil, errors.New("outbound image: invalid stable publisher configuration") + } + return &StableHashPublisher{ + store: store, + prefix: prefix, + publicBaseURL: publicBaseURL, + }, nil +} + +func (p *StableHashPublisher) Publish(ctx context.Context, data []byte, contentType string) (string, error) { + if p == nil || p.store == nil || len(data) == 0 || p.prefix == "" || p.publicBaseURL == "" { + return "", errors.New("outbound image: invalid stable publisher configuration") + } + if imageExtension(contentType) == "" { + return "", errors.New("outbound image: unsupported image content type") + } + sum := sha256.Sum256(data) + idBytes := sum[:16] + idBytes[6] = (idBytes[6] & 0x0f) | 0x50 + idBytes[8] = (idBytes[8] & 0x3f) | 0x80 + idHex := hex.EncodeToString(idBytes) + id := fmt.Sprintf("%s-%s-%s-%s-%s", idHex[:8], idHex[8:12], idHex[12:16], idHex[16:20], idHex[20:]) + key := path.Join(p.prefix, id) + if err := p.store.Put(ctx, key, data, contentType); err != nil { + return "", errors.New("outbound image: publish object failed") + } + return p.publicBaseURL + "/" + id, nil +} + +func imageExtension(contentType string) string { + switch strings.ToLower(strings.TrimSpace(strings.Split(contentType, ";")[0])) { + case "image/jpeg", "image/jpg": + return ".jpg" + case "image/png": + return ".png" + case "image/webp": + return ".webp" + case "image/gif": + return ".gif" + default: + return "" + } +} diff --git a/internal/outboundimage/publisher_test.go b/internal/outboundimage/publisher_test.go new file mode 100644 index 0000000..4cd076a --- /dev/null +++ b/internal/outboundimage/publisher_test.go @@ -0,0 +1,90 @@ +package outboundimage + +import ( + "context" + "strings" + "testing" +) + +type fakeObjectStore struct { + key string + data []byte + contentType string +} + +func (s *fakeObjectStore) Put(_ context.Context, key string, data []byte, contentType string) error { + s.key = key + s.data = append([]byte(nil), data...) + s.contentType = contentType + return nil +} + +func TestStableHashPublisherUsesDeterministicUUIDURLWithoutPresigning(t *testing.T) { + store := &fakeObjectStore{} + publisher, err := NewStableHashPublisher( + store, + "dobotai/im-images", + "https://weknora-api-test.dobot.cn/dingtalk/i", + ) + if err != nil { + t.Fatal(err) + } + + first, err := publisher.Publish(context.Background(), []byte("same-image"), "image/jpeg") + if err != nil { + t.Fatal(err) + } + firstKey := store.key + second, err := publisher.Publish(context.Background(), []byte("same-image"), "image/jpeg") + if err != nil { + t.Fatal(err) + } + + if first != second || firstKey != store.key { + t.Fatalf("publish is not deterministic: url1=%q url2=%q key1=%q key2=%q", first, second, firstKey, store.key) + } + + wantURLPrefix := "https://weknora-api-test.dobot.cn/dingtalk/i/" + if !strings.HasPrefix(first, wantURLPrefix) { + t.Fatalf("url=%q", first) + } + id := strings.TrimPrefix(first, wantURLPrefix) + if !stableImageIDRE.MatchString(id) { + t.Fatalf("stable image id=%q", id) + } + if store.key != "dobotai/im-images/"+id { + t.Fatalf("key=%q id=%q", store.key, id) + } +} + +func TestStableHashPublisherRejectsUnsafeConfigurationAndNonImages(t *testing.T) { + store := &fakeObjectStore{} + for _, test := range []struct { + name string + store ObjectWriter + prefix string + baseURL string + }{ + {name: "nil store", prefix: "dobotai/im-images", baseURL: "https://img.example/i"}, + {name: "empty prefix", store: store, baseURL: "https://img.example/i"}, + {name: "http base", store: store, prefix: "dobotai/im-images", baseURL: "http://img.example/i"}, + {name: "query base", store: store, prefix: "dobotai/im-images", baseURL: "https://img.example/i?token=secret"}, + } { + t.Run(test.name, func(t *testing.T) { + if _, err := NewStableHashPublisher(test.store, test.prefix, test.baseURL); err == nil { + t.Fatal("expected configuration error") + } + }) + } + + publisher, err := NewStableHashPublisher(store, "dobotai/im-images", "https://img.example/i") + if err != nil { + t.Fatal(err) + } + if _, err := publisher.Publish(context.Background(), nil, "image/png"); err == nil { + t.Fatal("expected empty image error") + } + if _, err := publisher.Publish(context.Background(), []byte("text"), "text/plain"); err == nil { + t.Fatal("expected non-image error") + } +} diff --git a/internal/outboundimage/rewriter.go b/internal/outboundimage/rewriter.go new file mode 100644 index 0000000..0942c95 --- /dev/null +++ b/internal/outboundimage/rewriter.go @@ -0,0 +1,212 @@ +package outboundimage + +import ( + "context" + "net" + "net/url" + "path" + "regexp" + "strings" +) + +var ( + resourceMarkdownImageRE = regexp.MustCompile(`!\[[^\]]*\]\((resource://[0-9A-Za-z_-]+)(?:\s+(?:"[^"\r\n]*"|'[^'\r\n]*'|\([^\)\r\n]*\)))?\)`) + resourceHTMLDoubleImageRE = regexp.MustCompile(`(?i)]*\bsrc\s*=\s*"(resource://[0-9A-Za-z_-]+)"[^>]*>`) + resourceHTMLSingleImageRE = regexp.MustCompile(`(?i)]*\bsrc\s*=\s*'(resource://[0-9A-Za-z_-]+)'[^>]*>`) + resourceHTMLUnsafeImageRE = regexp.MustCompile(`(?i)]*resource://[0-9A-Za-z_-]+[^>]*>`) + markdownImageRE = regexp.MustCompile(`!\[[^\]]*\]\(([^\s)]+)(?:\s+(?:"[^"\r\n]*"|'[^'\r\n]*'|\([^\)\r\n]*\)))?\)`) + incompleteMarkdownImageRE = regexp.MustCompile(`!\[[^\]\r\n]*\]\([^\)\r\n]*$`) + htmlImageRE = regexp.MustCompile(`(?i)]*>`) + incompleteHTMLImageRE = regexp.MustCompile(`(?i)]*$`) + htmlDoubleSrcRE = regexp.MustCompile(`(?i)\bsrc\s*=\s*"([^"]+)"`) + htmlSingleSrcRE = regexp.MustCompile(`(?i)\bsrc\s*=\s*'([^']+)'`) + htmlDoubleAltRE = regexp.MustCompile(`(?i)\balt\s*=\s*"([^"]*)"`) + htmlSingleAltRE = regexp.MustCompile(`(?i)\balt\s*=\s*'([^']*)'`) + resourceReferenceRE = regexp.MustCompile(`resource://[0-9A-Za-z_-]+`) + dataImageReferenceRE = regexp.MustCompile(`(?i)data:image[^\s]*`) +) + +type Fetcher interface { + Fetch(ctx context.Context, reference string) ([]byte, string, error) +} + +type Publisher interface { + Publish(ctx context.Context, data []byte, contentType string) (string, error) +} + +type Rewriter struct { + fetcher Fetcher + publisher Publisher + maxImages int +} + +func NewRewriter(fetcher Fetcher, publisher Publisher, maxImages int) *Rewriter { + return &Rewriter{fetcher: fetcher, publisher: publisher, maxImages: maxImages} +} + +func (r *Rewriter) Rewrite(ctx context.Context, markdown string) string { + if r == nil || r.fetcher == nil || r.publisher == nil || r.maxImages <= 0 { + markdown = normalizePublicHTMLImages(stripResourceImages(markdown)) + markdown = resourceReferenceRE.ReplaceAllString(resourceHTMLUnsafeImageRE.ReplaceAllString(markdown, ""), "") + return sanitizePublicMarkdownImages(markdown) + } + urls := map[string]string{} + attempted := 0 + resolve := func(reference string) string { + if publishedURL, ok := urls[reference]; ok { + return publishedURL + } + if attempted >= r.maxImages { + urls[reference] = "" + return "" + } + attempted++ + data, contentType, err := r.fetcher.Fetch(ctx, reference) + if err != nil { + urls[reference] = "" + return "" + } + publishedURL, err := r.publisher.Publish(ctx, data, contentType) + if err != nil || !strings.HasPrefix(publishedURL, "https://") { + urls[reference] = "" + return "" + } + urls[reference] = publishedURL + return publishedURL + } + + markdown = resourceMarkdownImageRE.ReplaceAllStringFunc(markdown, func(image string) string { + match := resourceMarkdownImageRE.FindStringSubmatch(image) + if len(match) != 2 { + return "" + } + reference := match[1] + publishedURL := resolve(reference) + if publishedURL == "" { + return "" + } + return strings.Replace(image, reference, publishedURL, 1) + }) + markdown = rewriteHTMLImages(markdown, resourceHTMLDoubleImageRE, resolve) + markdown = rewriteHTMLImages(markdown, resourceHTMLSingleImageRE, resolve) + markdown = normalizePublicHTMLImages(markdown) + markdown = resourceReferenceRE.ReplaceAllString(resourceHTMLUnsafeImageRE.ReplaceAllString(markdown, ""), "") + return sanitizePublicMarkdownImages(markdown) +} + +func sanitizePublicMarkdownImages(markdown string) string { + markdown = markdownImageRE.ReplaceAllStringFunc(markdown, func(image string) string { + match := markdownImageRE.FindStringSubmatch(image) + if len(match) != 2 || !isSafePublicImageURL(match[1]) { + return "" + } + if isKnownDocumentURL(match[1]) { + return strings.TrimPrefix(image, "!") + } + return image + }) + markdown = incompleteMarkdownImageRE.ReplaceAllString(markdown, "") + markdown = incompleteHTMLImageRE.ReplaceAllString(markdown, "") + return dataImageReferenceRE.ReplaceAllString(markdown, "") +} + +func isKnownDocumentURL(raw string) bool { + u, err := url.Parse(strings.TrimSpace(raw)) + if err != nil { + return false + } + switch strings.ToLower(path.Ext(u.Path)) { + case ".pdf", ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", + ".csv", ".txt", ".zip", ".rar", ".7z": + return true + default: + return false + } +} + +func rewriteHTMLImages(content string, pattern *regexp.Regexp, resolve func(string) string) string { + return pattern.ReplaceAllStringFunc(content, func(image string) string { + match := pattern.FindStringSubmatch(image) + if len(match) != 2 { + return "" + } + publishedURL := resolve(match[1]) + if publishedURL == "" { + return "" + } + alt := "图片" + for _, pattern := range []*regexp.Regexp{htmlDoubleAltRE, htmlSingleAltRE} { + if altMatch := pattern.FindStringSubmatch(image); len(altMatch) == 2 && strings.TrimSpace(altMatch[1]) != "" { + alt = strings.ReplaceAll(strings.TrimSpace(altMatch[1]), "]", `\]`) + break + } + } + return "![" + alt + "](" + publishedURL + ")" + }) +} + +func normalizePublicHTMLImages(content string) string { + return htmlImageRE.ReplaceAllStringFunc(content, func(image string) string { + source := "" + for _, pattern := range []*regexp.Regexp{htmlDoubleSrcRE, htmlSingleSrcRE} { + if match := pattern.FindStringSubmatch(image); len(match) == 2 { + source = strings.TrimSpace(match[1]) + break + } + } + if !isSafePublicImageURL(source) { + return "" + } + return "![" + imageAlt(image) + "](" + source + ")" + }) +} + +func imageAlt(image string) string { + for _, pattern := range []*regexp.Regexp{htmlDoubleAltRE, htmlSingleAltRE} { + if match := pattern.FindStringSubmatch(image); len(match) == 2 && strings.TrimSpace(match[1]) != "" { + return strings.ReplaceAll(strings.TrimSpace(match[1]), "]", `\]`) + } + } + return "图片" +} + +func isSafePublicImageURL(raw string) bool { + u, err := url.Parse(strings.TrimSpace(raw)) + if err != nil || u.Scheme != "https" || u.Host == "" || u.User != nil { + return false + } + hostname := strings.TrimSuffix(strings.ToLower(u.Hostname()), ".") + if hostname == "" || hostname == "localhost" || strings.HasSuffix(hostname, ".localhost") || strings.HasSuffix(hostname, ".local") || strings.HasSuffix(hostname, ".internal") { + return false + } + if port := u.Port(); port != "" && port != "443" { + return false + } + if ip := net.ParseIP(hostname); ip != nil { + if !ip.IsGlobalUnicast() || ip.IsPrivate() { + return false + } + } else if !strings.Contains(hostname, ".") { + return false + } + for key := range u.Query() { + normalized := strings.ToLower(key) + if strings.Contains(normalized, "signature") || normalized == "ossaccesskeyid" || strings.Contains(normalized, "credential") { + return false + } + } + return true +} + +func stripResourceImages(content string) string { + content = resourceMarkdownImageRE.ReplaceAllString(content, "") + content = resourceHTMLDoubleImageRE.ReplaceAllString(content, "") + content = resourceHTMLSingleImageRE.ReplaceAllString(content, "") + return resourceHTMLUnsafeImageRE.ReplaceAllString(content, "") +} + +func (r *Rewriter) SanitizePartial(content string) string { + content = resourceReferenceRE.ReplaceAllString(stripResourceImages(content), "") + content = normalizePublicHTMLImages(content) + return sanitizePublicMarkdownImages(content) +} diff --git a/internal/outboundimage/rewriter_test.go b/internal/outboundimage/rewriter_test.go new file mode 100644 index 0000000..d33c632 --- /dev/null +++ b/internal/outboundimage/rewriter_test.go @@ -0,0 +1,377 @@ +package outboundimage + +import ( + "context" + "errors" + "strings" + "testing" +) + +type fakeFetcher struct { + calls map[string]int + fail map[string]bool +} + +func (f *fakeFetcher) Fetch(_ context.Context, ref string) ([]byte, string, error) { + if f.calls == nil { + f.calls = map[string]int{} + } + f.calls[ref]++ + if f.fail[ref] { + return nil, "", errors.New("fetch failed") + } + return []byte("image:" + ref), "image/png", nil +} + +type fakePublisher struct { + calls int +} + +func (p *fakePublisher) Publish(_ context.Context, data []byte, contentType string) (string, error) { + p.calls++ + if contentType != "image/png" || len(data) == 0 { + return "", errors.New("bad image") + } + return "https://img.example/" + string(rune('0'+p.calls)) + ".png?sig=short", nil +} + +func TestRewriteMarkdownResourceImagesDeduplicatesAndPreservesOtherURLs(t *testing.T) { + fetcher := &fakeFetcher{} + publisher := &fakePublisher{} + r := NewRewriter(fetcher, publisher, 5) + input := "步骤一\n![图1](resource://AbCdEfGhIjKlMnOpQrStUv)\n重复\n![图1重复](resource://AbCdEfGhIjKlMnOpQrStUv)\n外部\n![官网](https://example.com/a.png)" + + got := r.Rewrite(context.Background(), input) + + if strings.Contains(got, "resource://") { + t.Fatalf("resource reference remained: %s", got) + } + if strings.Count(got, "https://img.example/1.png?sig=short") != 2 { + t.Fatalf("deduplicated signed URL count mismatch: %s", got) + } + if !strings.Contains(got, "![官网](https://example.com/a.png)") { + t.Fatalf("ordinary HTTPS image changed: %s", got) + } + if fetcher.calls["resource://AbCdEfGhIjKlMnOpQrStUv"] != 1 || publisher.calls != 1 { + t.Fatalf("calls fetch=%v publish=%d", fetcher.calls, publisher.calls) + } +} + +func TestRewriteMarkdownResourceImagesDropsFailuresAndImagesBeyondLimit(t *testing.T) { + failed := "resource://FailedRefAbCdEfGhIjKlMn" + fetcher := &fakeFetcher{fail: map[string]bool{failed: true}} + publisher := &fakePublisher{} + r := NewRewriter(fetcher, publisher, 3) + input := "保留正文\n![坏图](" + failed + ")\n![一](resource://FirstRefAbCdEfGhIjKlMnO)\n![二](resource://SecondRefAbCdEfGhIjKlMn)\n![三](resource://ThirdRefAbCdEfGhIjKlMnO)" + + got := r.Rewrite(context.Background(), input) + + if !strings.Contains(got, "保留正文") { + t.Fatalf("text was lost: %s", got) + } + if strings.Contains(got, "resource://") || strings.Contains(got, "坏图") || strings.Contains(got, "![三]") { + t.Fatalf("broken or over-limit image remained: %s", got) + } + if publisher.calls != 2 { + t.Fatalf("publisher calls=%d, want 2", publisher.calls) + } +} + +func TestRewriteHTMLResourceImagesAsDingTalkMarkdown(t *testing.T) { + resource := "resource://AbCdEfGhIjKlMnOpQrStUv" + fetcher := &fakeFetcher{} + publisher := &fakePublisher{} + r := NewRewriter(fetcher, publisher, 5) + input := "前文\n\"步骤图\"\n" + + "重复\n\n后文" + + got := r.Rewrite(context.Background(), input) + + if strings.Contains(got, "resource://") || strings.Contains(strings.ToLower(got), "\n" + + "内部引用 resource://BareRefAbCdEfGhIjKlMn" + + got := r.SanitizePartial(input) + + if strings.Contains(got, "resource://") || strings.Contains(strings.ToLower(got), "` + + got := r.Rewrite(context.Background(), input) + + if got != "![公网图](https://example.com/a.png)" { + t.Fatalf("normalized public HTML image=%q", got) + } +} + +func TestRewriteRemovesDataImageWithOptionalTitle(t *testing.T) { + r := NewRewriter(&fakeFetcher{}, &fakePublisher{}, 5) + input := "正文\n![占位图](data:image/png;base64,iVBORw0KGgo= \"\")\n后文" + + got := r.Rewrite(context.Background(), input) + + if strings.Contains(got, "data:image") || strings.Contains(got, "占位图") { + t.Fatalf("final content retained a data image: %s", got) + } + if !strings.Contains(got, "正文") || !strings.Contains(got, "后文") { + t.Fatalf("surrounding text was lost: %s", got) + } +} + +func TestSanitizePartialRemovesDataImageWithOptionalTitle(t *testing.T) { + r := NewRewriter(&fakeFetcher{}, &fakePublisher{}, 5) + input := "正文\n![占位图](data:image/png;base64,iVBORw0KGgo= \"\")\n后文" + + got := r.SanitizePartial(input) + + if strings.Contains(got, "data:image") || strings.Contains(got, "占位图") { + t.Fatalf("partial content retained a data image: %s", got) + } + if !strings.Contains(got, "正文") || !strings.Contains(got, "后文") { + t.Fatalf("surrounding text was lost: %s", got) + } +} + +func TestRewritePublishesResourceImageWithOptionalTitle(t *testing.T) { + resource := "resource://AbCdEfGhIjKlMnOpQrStUv" + fetcher := &fakeFetcher{} + publisher := &fakePublisher{} + r := NewRewriter(fetcher, publisher, 5) + input := "![步骤图](" + resource + " \"安装说明\")" + + got := r.Rewrite(context.Background(), input) + + if got != "![步骤图](https://img.example/1.png?sig=short \"安装说明\")" { + t.Fatalf("resource image with title=%q", got) + } + if fetcher.calls[resource] != 1 || publisher.calls != 1 { + t.Fatalf("calls fetch=%v publish=%d", fetcher.calls, publisher.calls) + } +} + +func TestSanitizePartialRemovesDataHTMLImage(t *testing.T) { + r := NewRewriter(&fakeFetcher{}, &fakePublisher{}, 5) + input := `正文占位图后文` + + got := r.SanitizePartial(input) + + if strings.Contains(got, "data:image") || strings.Contains(strings.ToLower(got), "` + if got, want := r.Rewrite(context.Background(), html), `[参数表](https://docs.example/manual.xlsx)`; got != want { + t.Fatalf("HTML document image rewrite=%q, want %q", got, want) + } + if got, want := r.SanitizePartial(html), `[参数表](https://docs.example/manual.xlsx)`; got != want { + t.Fatalf("partial HTML document image rewrite=%q, want %q", got, want) + } +} + +func TestDocumentImageDowngradePreservesImageAndLinkContracts(t *testing.T) { + r := NewRewriter(&fakeFetcher{}, &fakePublisher{}, 5) + input := strings.Join([]string{ + `![稳定图片](https://weknora-api.example/i/006d001d-7d0b-542e-b5ab-6ee7d7cdce54)`, + `[已有PDF链接](https://docs.example/manual.pdf)`, + `![危险PDF](https://127.0.0.1/manual.pdf)`, + }, "\n") + + got := r.Rewrite(context.Background(), input) + + if !strings.Contains(got, `![稳定图片](https://weknora-api.example/i/006d001d-7d0b-542e-b5ab-6ee7d7cdce54)`) { + t.Fatalf("extensionless stable image changed: %s", got) + } + if !strings.Contains(got, `[已有PDF链接](https://docs.example/manual.pdf)`) { + t.Fatalf("existing document link changed: %s", got) + } + if strings.Contains(got, "127.0.0.1") || strings.Contains(got, "危险PDF") { + t.Fatalf("unsafe document image became a link: %s", got) + } +} diff --git a/internal/outboundimage/stable_handler.go b/internal/outboundimage/stable_handler.go new file mode 100644 index 0000000..ff9c4a1 --- /dev/null +++ b/internal/outboundimage/stable_handler.go @@ -0,0 +1,48 @@ +package outboundimage + +import ( + "context" + "errors" + "net/http" + "path" + "strconv" + "strings" +) + +type ObjectReader interface { + Get(ctx context.Context, key string, maxBytes int64) ([]byte, string, error) +} + +func NewStableImageHandler(reader ObjectReader, objectPrefix, routePrefix string, maxBytes int64) (http.Handler, error) { + objectPrefix = strings.Trim(strings.TrimSpace(objectPrefix), "/") + routePrefix = "/" + strings.Trim(strings.TrimSpace(routePrefix), "/") + "/" + if reader == nil || objectPrefix == "" || maxBytes <= 0 { + return nil, errors.New("outbound image: invalid stable image handler configuration") + } + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodGet && r.Method != http.MethodHead { + w.Header().Set("Allow", "GET, HEAD") + http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed) + return + } + id := strings.TrimPrefix(r.URL.Path, routePrefix) + if r.URL.Path == id || strings.Contains(id, "/") || !stableImageIDRE.MatchString(id) { + http.NotFound(w, r) + return + } + data, contentType, err := reader.Get(r.Context(), path.Join(objectPrefix, id), maxBytes) + if err != nil || len(data) == 0 || imageExtension(contentType) == "" { + http.NotFound(w, r) + return + } + w.Header().Set("Content-Type", strings.TrimSpace(strings.Split(contentType, ";")[0])) + w.Header().Set("Content-Length", strconv.Itoa(len(data))) + w.Header().Set("Cache-Control", "public, max-age=86400, immutable") + w.Header().Set("X-Content-Type-Options", "nosniff") + w.WriteHeader(http.StatusOK) + if r.Method == http.MethodHead { + return + } + _, _ = w.Write(data) + }), nil +} diff --git a/internal/outboundimage/stable_handler_test.go b/internal/outboundimage/stable_handler_test.go new file mode 100644 index 0000000..26201cb --- /dev/null +++ b/internal/outboundimage/stable_handler_test.go @@ -0,0 +1,91 @@ +package outboundimage + +import ( + "context" + "net/http" + "net/http/httptest" + "testing" +) + +type fakeImageReader struct { + key string + maxBytes int64 + data []byte + contentType string + err error +} + +func (r *fakeImageReader) Get(_ context.Context, key string, maxBytes int64) ([]byte, string, error) { + r.key = key + r.maxBytes = maxBytes + return append([]byte(nil), r.data...), r.contentType, r.err +} + +func TestStableImageHandlerReturnsImageBytesDirectly(t *testing.T) { + const id = "ca13f02b-58b6-5f8f-a80d-b41873a97425" + reader := &fakeImageReader{data: []byte("JPEG"), contentType: "image/jpeg"} + handler, err := NewStableImageHandler(reader, "dobotai/im-images", "/dingtalk/i/", 10<<20) + if err != nil { + t.Fatal(err) + } + + recorder := httptest.NewRecorder() + handler.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/dingtalk/i/"+id, nil)) + + if recorder.Code != http.StatusOK { + t.Fatalf("status=%d", recorder.Code) + } + if recorder.Header().Get("Location") != "" { + t.Fatalf("stable image endpoint must not redirect: location=%q", recorder.Header().Get("Location")) + } + if recorder.Header().Get("Content-Type") != "image/jpeg" { + t.Fatalf("content-type=%q", recorder.Header().Get("Content-Type")) + } + if recorder.Body.String() != "JPEG" { + t.Fatalf("body=%q", recorder.Body.String()) + } + if reader.key != "dobotai/im-images/"+id || reader.maxBytes != 10<<20 { + t.Fatalf("key=%q maxBytes=%d", reader.key, reader.maxBytes) + } +} + +func TestStableImageHandlerAllowsHeadWithoutBody(t *testing.T) { + const id = "ca13f02b-58b6-5f8f-a80d-b41873a97425" + reader := &fakeImageReader{data: []byte("JPEG"), contentType: "image/jpeg"} + handler, err := NewStableImageHandler(reader, "dobotai/im-images", "/dingtalk/i/", 10<<20) + if err != nil { + t.Fatal(err) + } + + recorder := httptest.NewRecorder() + handler.ServeHTTP(recorder, httptest.NewRequest(http.MethodHead, "/dingtalk/i/"+id, nil)) + + if recorder.Code != http.StatusOK || recorder.Body.Len() != 0 { + t.Fatalf("status=%d body=%q", recorder.Code, recorder.Body.String()) + } + if recorder.Header().Get("Content-Length") != "4" { + t.Fatalf("content-length=%q", recorder.Header().Get("Content-Length")) + } +} + +func TestStableImageHandlerRejectsPostAndInvalidIDsWithoutReadingOSS(t *testing.T) { + reader := &fakeImageReader{data: []byte("JPEG"), contentType: "image/jpeg"} + handler, err := NewStableImageHandler(reader, "dobotai/im-images", "/dingtalk/i/", 10<<20) + if err != nil { + t.Fatal(err) + } + + post := httptest.NewRecorder() + handler.ServeHTTP(post, httptest.NewRequest(http.MethodPost, "/dingtalk/i/ca13f02b-58b6-5f8f-a80d-b41873a97425", nil)) + if post.Code != http.StatusMethodNotAllowed { + t.Fatalf("post status=%d", post.Code) + } + invalid := httptest.NewRecorder() + handler.ServeHTTP(invalid, httptest.NewRequest(http.MethodGet, "/dingtalk/i/../../secret", nil)) + if invalid.Code != http.StatusNotFound { + t.Fatalf("invalid status=%d", invalid.Code) + } + if reader.key != "" { + t.Fatalf("invalid requests reached OSS key=%q", reader.key) + } +} diff --git a/internal/outboundimage/weknora_fetcher.go b/internal/outboundimage/weknora_fetcher.go new file mode 100644 index 0000000..6d9d0f7 --- /dev/null +++ b/internal/outboundimage/weknora_fetcher.go @@ -0,0 +1,80 @@ +package outboundimage + +import ( + "context" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "strconv" + "strings" + "time" +) + +type WeKnoraFetcher struct { + baseURL *url.URL + apiKey string + client *http.Client + maxBytes int64 +} + +func NewWeKnoraFetcher(baseURL, apiKey string, client *http.Client, maxBytes int64) (*WeKnoraFetcher, error) { + parsed, err := url.Parse(strings.TrimRight(strings.TrimSpace(baseURL), "/")) + if err != nil || parsed.Scheme == "" || parsed.Host == "" { + return nil, errors.New("outbound image: invalid WeKnora base URL") + } + if strings.TrimSpace(apiKey) == "" { + return nil, errors.New("outbound image: WeKnora API key is required") + } + if maxBytes <= 0 { + return nil, errors.New("outbound image: positive max bytes is required") + } + if client == nil { + client = &http.Client{Timeout: 30 * time.Second} + } + return &WeKnoraFetcher{baseURL: parsed, apiKey: apiKey, client: client, maxBytes: maxBytes}, nil +} + +func (f *WeKnoraFetcher) Fetch(ctx context.Context, reference string) ([]byte, string, error) { + if !strings.HasPrefix(reference, "resource://") || !resourceMarkdownImageRE.MatchString("![]("+reference+")") { + return nil, "", errors.New("outbound image: unsupported resource reference") + } + u := *f.baseURL + u.Path = "/files" + u.RawPath = "" + query := u.Query() + query.Set("file_path", reference) + u.RawQuery = query.Encode() + req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil) + if err != nil { + return nil, "", errors.New("outbound image: create WeKnora request failed") + } + req.Header.Set("X-API-Key", f.apiKey) + resp, err := f.client.Do(req) + if err != nil { + return nil, "", fmt.Errorf("outbound image: WeKnora request failed: %w", err) + } + defer resp.Body.Close() + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + _, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 4096)) + return nil, "", fmt.Errorf("outbound image: WeKnora HTTP %d", resp.StatusCode) + } + contentType := strings.TrimSpace(strings.Split(resp.Header.Get("Content-Type"), ";")[0]) + if !strings.HasPrefix(contentType, "image/") { + return nil, "", errors.New("outbound image: WeKnora response is not an image") + } + if length := strings.TrimSpace(resp.Header.Get("Content-Length")); length != "" { + if n, convErr := strconv.ParseInt(length, 10, 64); convErr == nil && n > f.maxBytes { + return nil, "", errors.New("outbound image: WeKnora image exceeds size limit") + } + } + data, err := io.ReadAll(io.LimitReader(resp.Body, f.maxBytes+1)) + if err != nil { + return nil, "", errors.New("outbound image: read WeKnora response failed") + } + if int64(len(data)) == 0 || int64(len(data)) > f.maxBytes { + return nil, "", errors.New("outbound image: WeKnora image exceeds size limit") + } + return data, contentType, nil +} diff --git a/internal/outboundimage/weknora_fetcher_test.go b/internal/outboundimage/weknora_fetcher_test.go new file mode 100644 index 0000000..2b56c6b --- /dev/null +++ b/internal/outboundimage/weknora_fetcher_test.go @@ -0,0 +1,77 @@ +package outboundimage + +import ( + "context" + "io" + "net/http" + "net/http/httptest" + "testing" +) + +func TestWeKnoraFetcherDownloadsAuthenticatedResourceImage(t *testing.T) { + var called bool + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { + called = true + if req.URL.Path != "/files" { + t.Fatalf("path=%q", req.URL.Path) + } + if got := req.URL.Query().Get("file_path"); got != "resource://AbCdEfGhIjKlMnOpQrStUv" { + t.Fatalf("file_path=%q", got) + } + if got := req.Header.Get("X-API-Key"); got != "secret-test-key" { + t.Fatalf("api key header=%q", got) + } + w.Header().Set("Content-Type", "image/jpeg") + w.Header().Set("Content-Length", "4") + _, _ = io.WriteString(w, "JPEG") + })) + defer server.Close() + + fetcher, err := NewWeKnoraFetcher(server.URL+"/api/v1", "secret-test-key", server.Client(), 10<<20) + if err != nil { + t.Fatal(err) + } + data, contentType, err := fetcher.Fetch(context.Background(), "resource://AbCdEfGhIjKlMnOpQrStUv") + if err != nil { + t.Fatal(err) + } + if !called || string(data) != "JPEG" || contentType != "image/jpeg" { + t.Fatalf("called=%t data=%q type=%q", called, data, contentType) + } +} + +func TestWeKnoraFetcherRejectsUnsafeReferenceNonImageAndOversize(t *testing.T) { + t.Run("unsafe reference", func(t *testing.T) { + fetcher, err := NewWeKnoraFetcher("https://weknora.example", "key", http.DefaultClient, 4) + if err != nil { + t.Fatal(err) + } + if _, _, err := fetcher.Fetch(context.Background(), "https://evil.example/a.png"); err == nil { + t.Fatal("expected unsafe reference rejection") + } + }) + + for _, tc := range []struct { + name string + contentType string + body string + }{ + {name: "non image", contentType: "text/plain", body: "TEXT"}, + {name: "oversize", contentType: "image/png", body: "12345"}, + } { + t.Run(tc.name, func(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", tc.contentType) + _, _ = io.WriteString(w, tc.body) + })) + defer server.Close() + fetcher, err := NewWeKnoraFetcher(server.URL, "key", server.Client(), 4) + if err != nil { + t.Fatal(err) + } + if _, _, err := fetcher.Fetch(context.Background(), "resource://AbCdEfGhIjKlMnOpQrStUv"); err == nil { + t.Fatal("expected response rejection") + } + }) + } +} diff --git a/internal/qa/knowledge_search_tracking_test.go b/internal/qa/knowledge_search_tracking_test.go new file mode 100644 index 0000000..41adce8 --- /dev/null +++ b/internal/qa/knowledge_search_tracking_test.go @@ -0,0 +1,75 @@ +package qa + +import ( + "context" + "testing" + + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/core" + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/session" + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/weknora" +) + +func TestKnowledgeToolEventsMarkTurnAsSearched(t *testing.T) { + knowledgeTools := []string{ + "knowledge_search", + "grep_chunks", + "list_knowledge_chunks", + "get_document_info", + "wiki_search", + "wiki_read_page", + "wiki_read_source_doc", + "query_knowledge_graph", + } + for index, toolName := range knowledgeTools { + t.Run(toolName, func(t *testing.T) { + repo := newMemoryRepository() + client := &fakeEventStreamingWeKnora{ + fakeWeKnora: &fakeWeKnora{}, + events: []weknora.StreamEvent{ + {ResponseType: "tool_call", ToolName: toolName}, + {ResponseType: "answer", FullAnswer: "answer", Done: true}, + }, + streamResult: weknora.ChatResult{RequestID: "request", Answer: "answer", References: []core.Reference{{KnowledgeID: "doc"}}}, + } + service, err := New(repo, fixedResolver{}, client, session.GroupShared) + if err != nil { + t.Fatal(err) + } + messageID := "knowledge-tool-" + string(rune('a'+index)) + if _, err = service.AskEvents(context.Background(), streamQARequest(messageID), func(weknora.StreamEvent) {}); err != nil { + t.Fatal(err) + } + repo.mu.Lock() + stored := repo.turns["tenant:dingtalk:"+messageID] + repo.mu.Unlock() + if !stored.KnowledgeSearched { + t.Fatalf("tool %s did not mark knowledge searched", toolName) + } + }) + } +} + +func TestNonKnowledgeToolDoesNotMarkTurnAsSearched(t *testing.T) { + repo := newMemoryRepository() + client := &fakeEventStreamingWeKnora{ + fakeWeKnora: &fakeWeKnora{}, + events: []weknora.StreamEvent{ + {ResponseType: "tool_call", ToolName: "query_understand"}, + {ResponseType: "answer", FullAnswer: "answer", Done: true}, + }, + streamResult: weknora.ChatResult{RequestID: "request", Answer: "answer"}, + } + service, err := New(repo, fixedResolver{}, client, session.GroupShared) + if err != nil { + t.Fatal(err) + } + if _, err = service.AskEvents(context.Background(), streamQARequest("non-knowledge-tool"), func(weknora.StreamEvent) {}); err != nil { + t.Fatal(err) + } + repo.mu.Lock() + stored := repo.turns["tenant:dingtalk:non-knowledge-tool"] + repo.mu.Unlock() + if stored.KnowledgeSearched { + t.Fatal("non-knowledge tool marked turn as searched") + } +} diff --git a/internal/qa/language_test.go b/internal/qa/language_test.go new file mode 100644 index 0000000..edbfb17 --- /dev/null +++ b/internal/qa/language_test.go @@ -0,0 +1,20 @@ +package qa + +import "testing" + +func TestLocalizedQueryPreservesOriginalWhenAuto(t *testing.T) { + if got := localizedQuery("原始问题", "auto"); got != "原始问题" { + t.Fatalf("got %q", got) + } +} + +func TestLocalizedQueryAddsRequestedLanguageWithoutChangingInput(t *testing.T) { + original := "机械臂怎么复位?" + got := localizedQuery(original, "ja") + if got != "日本語で回答してください。\n\n"+original { + t.Fatalf("got %q", got) + } + if original != "机械臂怎么复位?" { + t.Fatal("original query changed") + } +} diff --git a/internal/qa/mode_routing_test.go b/internal/qa/mode_routing_test.go new file mode 100644 index 0000000..9f17d08 --- /dev/null +++ b/internal/qa/mode_routing_test.go @@ -0,0 +1,113 @@ +package qa + +import ( + "context" + "testing" + + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/core" + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/reasoningmode" + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/session" +) + +type fakeReasoningFinalizer struct { + repo *memoryRepository + calls int + input reasoningmode.TurnCompletion + completion reasoningmode.Completion +} + +func (f *fakeReasoningFinalizer) Complete(_ context.Context, input reasoningmode.TurnCompletion) (reasoningmode.Completion, error) { + f.calls++ + f.input = input + f.repo.mu.Lock() + finished := len(f.repo.finishTurns) + f.repo.mu.Unlock() + if finished == 0 { + panic("reasoning completion ran before successful Turn persistence") + } + return f.completion, nil +} + +func TestAgentOverrideUsesSameWeKnoraSessionAsDefaultAgent(t *testing.T) { + repo := newMemoryRepository() + client := &fakeWeKnora{} + service, err := New(repo, fixedResolver{}, client, session.GroupShared) + if err != nil { + t.Fatal(err) + } + base := core.QARequest{ + TenantKey: "tenant", Channel: "dingtalk", ConversationType: core.ConversationDirect, + ExternalUserID: "staff-1", SenderName: "张三", Query: "第一问", + } + base.ExternalMessageID = "message-quick" + quick, err := service.Ask(context.Background(), base) + if err != nil { + t.Fatal(err) + } + base.ExternalMessageID = "message-reasoning" + base.Query = "继续深入分析" + base.AgentIDOverride = "agent-reasoning" + reasoning, err := service.Ask(context.Background(), base) + if err != nil { + t.Fatal(err) + } + + if quick.WeKnoraSessionID == "" || reasoning.WeKnoraSessionID != quick.WeKnoraSessionID { + t.Fatalf("quick session=%q reasoning session=%q", quick.WeKnoraSessionID, reasoning.WeKnoraSessionID) + } + client.mu.Lock() + defer client.mu.Unlock() + if client.sessions != 1 || len(client.requests) != 2 { + t.Fatalf("sessions=%d requests=%d", client.sessions, len(client.requests)) + } + if client.requests[0].AgentID != "agent-1" || client.requests[1].AgentID != "agent-reasoning" { + t.Fatalf("agent requests=%q,%q", client.requests[0].AgentID, client.requests[1].AgentID) + } + repo.mu.Lock() + defer repo.mu.Unlock() + if len(repo.finishTurns) != 2 || repo.finishTurns[0].AgentID != "agent-1" || repo.finishTurns[1].AgentID != "agent-reasoning" { + t.Fatalf("finished turns=%+v", repo.finishTurns) + } + if repo.finishTurns[0].SessionKey != repo.finishTurns[1].SessionKey { + t.Fatalf("session keys diverged: %q vs %q", repo.finishTurns[0].SessionKey, repo.finishTurns[1].SessionKey) + } +} + +func TestReasoningCompletionDecoratesPersistedAndReturnedAnswer(t *testing.T) { + repo := newMemoryRepository() + client := &fakeWeKnora{} + finalizer := &fakeReasoningFinalizer{ + repo: repo, + completion: reasoningmode.Completion{ + RoundNumber: 8, + ShowHint: true, + }, + } + service, err := New(repo, fixedResolver{}, client, session.GroupShared, WithReasoningModeFinalizer(finalizer)) + if err != nil { + t.Fatal(err) + } + request := core.QARequest{ + TenantKey: "tenant", Channel: "dingtalk", ConversationType: core.ConversationDirect, + ExternalUserID: "staff-1", ExternalMessageID: "message-mode-completion", + Query: "分析", AgentIDOverride: "agent-reasoning", + ReasoningExecution: string(reasoningmode.ExecutionReasoning), + } + result, err := service.Ask(context.Background(), request) + if err != nil { + t.Fatal(err) + } + if finalizer.calls != 1 || finalizer.input.TurnID == "" || finalizer.input.Answer != "answer" { + t.Fatalf("finalizer calls=%d input=%+v", finalizer.calls, finalizer.input) + } + want := "【智能推理模式】\n\nanswer\n\n💡 推理模式还剩2轮,到期将自动关闭,如需继续可发送 /think on 重置轮次" + if result.Answer != want { + t.Fatalf("result answer=%q want=%q", result.Answer, want) + } + repo.mu.Lock() + defer repo.mu.Unlock() + stored := repo.turns["tenant:dingtalk:message-mode-completion"] + if stored.Answer != result.Answer { + t.Fatalf("stored answer=%q result=%q", stored.Answer, result.Answer) + } +} diff --git a/internal/qa/service.go b/internal/qa/service.go index 9b31697..fff2802 100644 --- a/internal/qa/service.go +++ b/internal/qa/service.go @@ -6,9 +6,11 @@ import ( "encoding/hex" "errors" "fmt" + "reflect" "strings" "gitea.zheromiku.top/Weknora/dobotai-platform/internal/core" + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/reasoningmode" "gitea.zheromiku.top/Weknora/dobotai-platform/internal/session" "gitea.zheromiku.top/Weknora/dobotai-platform/internal/weknora" ) @@ -19,6 +21,7 @@ type AgentResolver interface { type WeKnora interface { CreateSession(ctx context.Context, title, description string) (string, error) + UpdateSessionTitle(ctx context.Context, sessionID, title, description string) error AgentChat(ctx context.Context, sessionID string, request weknora.AgentChatRequest) (weknora.ChatResult, error) } @@ -30,21 +33,81 @@ type eventStreamingWeKnora interface { AgentChatEvents(ctx context.Context, sessionID string, request weknora.AgentChatRequest, observer weknora.StreamObserver) (weknora.ChatResult, error) } -type Service struct { - repository core.Repository - agents AgentResolver - weknora WeKnora - groupPolicy session.GroupPolicy +type sessionInvalidator interface { + InvalidateSession(ctx context.Context, sessionKey, expectedSessionID string) error } -func New(repository core.Repository, agents AgentResolver, client WeKnora, groupPolicy session.GroupPolicy) (*Service, error) { +// SucceededTurnObserver observes a successfully finished turn. It is called +// synchronously after FinishTurn succeeds and before the QAResult is returned. +// A non-nil error from ObserveSucceededTurn must never change the QAResult or +// cause Ask to return an error. +type SucceededTurnObserver interface { + ObserveSucceededTurn(ctx context.Context, turn core.Turn) error +} + +type ReasoningModeFinalizer interface { + Complete(ctx context.Context, input reasoningmode.TurnCompletion) (reasoningmode.Completion, error) +} + +// ServiceOption configures a Service. +type ServiceOption func(*Service) + +// WithSucceededTurnObserver registers an observer that is called synchronously +// after each successful turn finishes. onError, if non-nil, is called with any +// error returned by the observer. The observer error is never returned to the +// caller. +func WithSucceededTurnObserver(observer SucceededTurnObserver, onError func(error)) ServiceOption { + return func(s *Service) { + s.observerConfigured = true + s.observer = observer + s.observerErrorHandler = onError + } +} + +func WithReasoningModeFinalizer(finalizer ReasoningModeFinalizer, onError ...func(error)) ServiceOption { + return func(s *Service) { + s.reasoningFinalizer = finalizer + if len(onError) > 0 { + s.reasoningErrorHandler = onError[0] + } + } +} + +type Service struct { + repository core.Repository + agents AgentResolver + weknora WeKnora + groupPolicy session.GroupPolicy + observer SucceededTurnObserver + observerErrorHandler func(error) + observerConfigured bool + reasoningFinalizer ReasoningModeFinalizer + reasoningErrorHandler func(error) +} + +func New(repository core.Repository, agents AgentResolver, client WeKnora, groupPolicy session.GroupPolicy, opts ...ServiceOption) (*Service, error) { if repository == nil || agents == nil || client == nil { return nil, errors.New("repository, agent resolver and weknora client are required") } if groupPolicy == "" { groupPolicy = session.GroupShared } - return &Service{repository: repository, agents: agents, weknora: client, groupPolicy: groupPolicy}, nil + s := &Service{repository: repository, agents: agents, weknora: client, groupPolicy: groupPolicy} + for _, o := range opts { + o(s) + } + if s.observerConfigured && isNilSucceededTurnObserver(s.observer) { + return nil, errors.New("succeeded turn observer is required when configured") + } + return s, nil +} + +func isNilSucceededTurnObserver(observer SucceededTurnObserver) bool { + if observer == nil { + return true + } + v := reflect.ValueOf(observer) + return v.Kind() == reflect.Pointer && v.IsNil() } func (s *Service) Ask(ctx context.Context, request core.QARequest) (core.QAResult, error) { @@ -68,12 +131,16 @@ func (s *Service) ask(ctx context.Context, request core.QARequest, answerObserve if err := validateRequest(request); err != nil { return core.QAResult{}, err } - agentID, err := s.agents.Resolve(request.Channel, request.ExternalChatID) + baseAgentID, err := s.agents.Resolve(request.Channel, request.ExternalChatID) if err != nil { return core.QAResult{}, err } + executionAgentID := baseAgentID + if override := strings.TrimSpace(request.AgentIDOverride); override != "" { + executionAgentID = override + } sessionKey, subjectID, err := session.BuildKey(session.Identity{ - TenantKey: request.TenantKey, Channel: request.Channel, AgentID: agentID, + TenantKey: request.TenantKey, Channel: request.Channel, AgentID: baseAgentID, ConversationType: request.ConversationType, ExternalChatID: request.ExternalChatID, ExternalUserID: request.ExternalUserID, GroupPolicy: s.groupPolicy, }) @@ -82,34 +149,44 @@ func (s *Service) ask(ctx context.Context, request core.QARequest, answerObserve } media := make([]core.MediaAudit, 0, len(request.Images)) + questionImageURLs := make([]string, 0, len(request.Images)) for _, image := range request.Images { media = append(media, core.MediaAudit{ Type: "image", MIMEType: image.MIMEType, SizeBytes: image.SizeBytes, Width: image.Width, Height: image.Height, }) + if url := strings.TrimSpace(image.PublishedURL); url != "" { + questionImageURLs = append(questionImageURLs, url) + } } messageType := normalizeMessageType(request) if messageType == "" { return core.QAResult{}, errors.New("unsupported message_type") } turn := core.Turn{ - ID: newID(), - TenantKey: request.TenantKey, - Channel: request.Channel, - ExternalMessageID: request.ExternalMessageID, - SessionKey: sessionKey, - AgentID: agentID, - ConversationType: request.ConversationType, - ExternalChatID: request.ExternalChatID, - ExternalUserID: request.ExternalUserID, - SenderName: request.SenderName, - MessageType: messageType, - ActorID: newID(), - ConversationID: newID(), - RequestMessageID: newID(), - Question: request.Query, - Media: media, - Status: "processing", + ID: newID(), + TenantKey: request.TenantKey, + Channel: request.Channel, + ExternalMessageID: request.ExternalMessageID, + SessionKey: sessionKey, + AgentID: executionAgentID, + ConversationType: request.ConversationType, + ConversationTitle: request.ConversationTitle, + ExternalChatID: request.ExternalChatID, + ExternalUserID: request.ExternalUserID, + SenderName: request.SenderName, + TriggerPersonSnapshot: request.TriggerPersonSnapshot, + ActorUnionIDSnapshot: request.ActorUnionIDSnapshot, + DepartmentSnapshot: request.Department, + RegionSnapshot: request.Region, + MessageType: messageType, + ActorID: newID(), + ConversationID: newID(), + RequestMessageID: newID(), + Question: request.Query, + Media: media, + QuestionImageURLs: questionImageURLs, + Status: "processing", } stored, created, err := s.repository.BeginTurn(ctx, turn) if err != nil { @@ -126,72 +203,113 @@ func (s *Service) ask(ctx context.Context, request core.QARequest, answerObserve } turn = stored - mapping := core.SessionMapping{SessionKey: sessionKey, TenantKey: request.TenantKey, - Channel: request.Channel, AgentID: agentID, ConversationType: request.ConversationType, - ExternalSubjectID: subjectID} - sessionID, err := s.repository.ResolveSession(ctx, mapping, func(createCtx context.Context) (string, error) { - title := fmt.Sprintf("%s %s", request.Channel, subjectID) - return s.weknora.CreateSession(createCtx, title, "Managed by DobotAI; business state remains outside WeKnora") + displayTitle := session.BuildDisplayTitle(session.TitleIdentity{ + ConversationType: request.ConversationType, + ExternalUserID: request.ExternalUserID, + ExternalChatID: request.ExternalChatID, + SenderName: request.SenderName, + ConversationTitle: request.ConversationTitle, }) + mapping := core.SessionMapping{SessionKey: sessionKey, TenantKey: request.TenantKey, + Channel: request.Channel, AgentID: baseAgentID, ConversationType: request.ConversationType, + ExternalSubjectID: subjectID, DisplayTitle: displayTitle} + createSession := func(createCtx context.Context) (string, error) { + return s.weknora.CreateSession(createCtx, displayTitle, "Managed by DobotAI; business state remains outside WeKnora") + } + sessionID, err := s.repository.ResolveSession(ctx, mapping, createSession) if err != nil { turn.Status, turn.ErrorMessage = "failed", err.Error() _ = s.repository.FinishTurn(ctx, turn) return core.QAResult{}, fmt.Errorf("resolve weknora session: %w", err) } turn.WeKnoraSessionID = sessionID + _ = s.repository.SyncSessionTitle(ctx, mapping, displayTitle, func(updateCtx context.Context, existingSessionID, title string) error { + return s.weknora.UpdateSessionTitle(updateCtx, existingSessionID, title, "Managed by DobotAI; business state remains outside WeKnora") + }) - query := request.Query + query := localizedQuery(request.Query, request.ResponseLocale) if request.ConversationType == core.ConversationGroup && strings.TrimSpace(request.SenderName) != "" { - query = request.SenderName + ": " + request.Query + query = request.SenderName + ": " + query } images := make([]weknora.Image, 0, len(request.Images)) for _, image := range request.Images { images = append(images, weknora.Image{Data: image.DataURI}) } chatRequest := weknora.AgentChatRequest{ - Query: query, AgentID: agentID, AgentEnabled: true, Channel: "im", EnableMemory: true, + Query: query, AgentID: executionAgentID, AgentEnabled: true, Channel: "im", EnableMemory: true, Images: images, } - var chat weknora.ChatResult - if eventObserver != nil { - // Prefer AgentChatEvents; fallback to AgentChatStream adaptation; then AgentChat. - if eventStream, ok := s.weknora.(eventStreamingWeKnora); ok { - chat, err = eventStream.AgentChatEvents(ctx, sessionID, chatRequest, eventObserver) - } else if streaming, ok := s.weknora.(streamingWeKnora); ok { - // Adapt AgentChatStream answer chunks to StreamEvent - chat, err = streaming.AgentChatStream(ctx, sessionID, chatRequest, func(full string) { - if answerObserver != nil { - answerObserver(full) - } - eventObserver(weknora.StreamEvent{ - ResponseType: "answer", - FullAnswer: full, + // Track whether this turn actually triggered a knowledge-base search by + // observing knowledge_search tool-call events. The flag feeds coverage + // classification (image turns) and is persisted with the turn. + var knowledgeSearched bool + effectiveEventObserver := weknora.StreamObserver(func(e weknora.StreamEvent) { + if isKnowledgeTool(e.ToolName) { + knowledgeSearched = true + } + if eventObserver != nil { + eventObserver(e) + } + }) + runChat := func(targetSessionID string) (weknora.ChatResult, error) { + var result weknora.ChatResult + var runErr error + if eventObserver != nil { + // Prefer AgentChatEvents; fallback to AgentChatStream adaptation; then AgentChat. + if eventStream, ok := s.weknora.(eventStreamingWeKnora); ok { + result, runErr = eventStream.AgentChatEvents(ctx, targetSessionID, chatRequest, effectiveEventObserver) + } else if streaming, ok := s.weknora.(streamingWeKnora); ok { + // Adapt AgentChatStream answer chunks to StreamEvent + result, runErr = streaming.AgentChatStream(ctx, targetSessionID, chatRequest, func(full string) { + if answerObserver != nil { + answerObserver(full) + } + effectiveEventObserver(weknora.StreamEvent{ + ResponseType: "answer", + FullAnswer: full, + }) }) - }) + } else { + result, runErr = s.weknora.AgentChat(ctx, targetSessionID, chatRequest) + if runErr == nil && strings.TrimSpace(result.Answer) != "" { + if answerObserver != nil { + answerObserver(result.Answer) + } + effectiveEventObserver(weknora.StreamEvent{ + ResponseType: "answer", + FullAnswer: result.Answer, + Done: true, + }) + } + } + } else if answerObserver != nil { + if streaming, ok := s.weknora.(streamingWeKnora); ok { + result, runErr = streaming.AgentChatStream(ctx, targetSessionID, chatRequest, answerObserver) + } else { + result, runErr = s.weknora.AgentChat(ctx, targetSessionID, chatRequest) + if runErr == nil && strings.TrimSpace(result.Answer) != "" { + answerObserver(result.Answer) + } + } } else { - chat, err = s.weknora.AgentChat(ctx, sessionID, chatRequest) - if err == nil && strings.TrimSpace(chat.Answer) != "" { - if answerObserver != nil { - answerObserver(chat.Answer) - } - eventObserver(weknora.StreamEvent{ - ResponseType: "answer", - FullAnswer: chat.Answer, - Done: true, - }) + result, runErr = s.weknora.AgentChat(ctx, targetSessionID, chatRequest) + } + return result, runErr + } + + chat, err := runChat(sessionID) + if errors.Is(err, weknora.ErrSessionNotFound) { + if invalidator, ok := s.repository.(sessionInvalidator); ok { + if invalidateErr := invalidator.InvalidateSession(ctx, sessionKey, sessionID); invalidateErr != nil { + err = fmt.Errorf("invalidate stale weknora session: %w", invalidateErr) + } else if freshSessionID, resolveErr := s.repository.ResolveSession(ctx, mapping, createSession); resolveErr != nil { + err = fmt.Errorf("recreate weknora session: %w", resolveErr) + } else { + sessionID = freshSessionID + turn.WeKnoraSessionID = freshSessionID + chat, err = runChat(freshSessionID) } } - } else if answerObserver != nil { - if streaming, ok := s.weknora.(streamingWeKnora); ok { - chat, err = streaming.AgentChatStream(ctx, sessionID, chatRequest, answerObserver) - } else { - chat, err = s.weknora.AgentChat(ctx, sessionID, chatRequest) - if err == nil && strings.TrimSpace(chat.Answer) != "" { - answerObserver(chat.Answer) - } - } - } else { - chat, err = s.weknora.AgentChat(ctx, sessionID, chatRequest) } if err == nil && strings.TrimSpace(chat.Answer) == "" { err = weknora.ErrEmptyAnswer @@ -203,15 +321,76 @@ func (s *Service) ask(ctx context.Context, request core.QARequest, answerObserve } turn.Status, turn.Answer, turn.References = "succeeded", chat.Answer, chat.References turn.WeKnoraRequestID = chat.RequestID + turn.KnowledgeSearched = knowledgeSearched turn.AnswerMessageID = newID() if err := s.repository.FinishTurn(ctx, turn); err != nil { return core.QAResult{}, fmt.Errorf("finish turn: %w", err) } + if s.reasoningFinalizer != nil && strings.TrimSpace(request.ReasoningExecution) != "" { + completion, completionErr := s.reasoningFinalizer.Complete(ctx, reasoningmode.TurnCompletion{ + Scope: reasoningmode.Scope{ + TenantKey: request.TenantKey, Channel: request.Channel, ExternalActorID: request.ExternalUserID, + }, + TurnID: turn.ID, Execution: reasoningmode.ExecutionMode(request.ReasoningExecution), + Answer: turn.Answer, Locale: request.ResponseLocale, Expired: request.ReasoningExpired, + }) + if completionErr != nil { + if s.reasoningErrorHandler != nil { + s.reasoningErrorHandler(completionErr) + } + } else { + displayLocale := reasoningmode.ResolveGuideLocale(request.ResponseLocale, request.Query) + turn.Answer = reasoningmode.DecorateAnswerForLocale( + turn.Answer, reasoningmode.ExecutionMode(request.ReasoningExecution), + request.ReasoningExpired, completion, displayLocale, + ) + if err := s.repository.FinishTurn(ctx, turn); err != nil { + if s.reasoningErrorHandler != nil { + s.reasoningErrorHandler(err) + } + } else { + chat.Answer = turn.Answer + } + } + } + if s.observer != nil { + if obsErr := s.observer.ObserveSucceededTurn(ctx, turn); obsErr != nil && s.observerErrorHandler != nil { + s.observerErrorHandler(obsErr) + } + } return core.QAResult{TurnID: turn.ID, AnswerMessageID: turn.AnswerMessageID, DeliveryStatus: core.DeliveryGenerated, WeKnoraSessionID: sessionID, WeKnoraRequestID: chat.RequestID, Answer: chat.Answer, References: chat.References}, nil } +func isKnowledgeTool(toolName string) bool { + switch strings.ToLower(strings.TrimSpace(toolName)) { + case "knowledge_search", "grep_chunks", "list_knowledge_chunks", "get_document_info", + "wiki_search", "wiki_read_page", "wiki_read_source_doc", "query_knowledge_graph": + return true + default: + return false + } +} + +func localizedQuery(query, locale string) string { + query = strings.TrimSpace(query) + switch strings.TrimSpace(locale) { + case "zh-CN": + return "请使用简体中文回答。\n\n" + query + case "en": + return "Answer in English.\n\n" + query + case "ja": + return "日本語で回答してください。\n\n" + query + case "ko": + return "한국어로 답변해 주세요.\n\n" + query + case "es": + return "Responde en español.\n\n" + query + default: + return query + } +} + func normalizeRequestIdentity(request core.QARequest) core.QARequest { request.TenantKey = strings.TrimSpace(request.TenantKey) request.Channel = strings.TrimSpace(request.Channel) diff --git a/internal/qa/service_observer_test.go b/internal/qa/service_observer_test.go new file mode 100644 index 0000000..a574d1a --- /dev/null +++ b/internal/qa/service_observer_test.go @@ -0,0 +1,295 @@ +package qa + +import ( + "context" + "errors" + "sync" + "testing" + + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/core" + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/session" + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/weknora" +) + +// recordingObserver records calls to ObserveSucceededTurn. +type recordingObserver struct { + mu sync.Mutex + turns []core.Turn + err error +} + +func (r *recordingObserver) ObserveSucceededTurn(_ context.Context, turn core.Turn) error { + r.mu.Lock() + defer r.mu.Unlock() + r.turns = append(r.turns, turn) + return r.err +} + +// failingRepository wraps a memoryRepository and fails FinishTurn. +type failingRepository struct { + *memoryRepository + finishErr error +} + +func (r *failingRepository) FinishTurn(ctx context.Context, turn core.Turn) error { + return r.finishErr +} + +func TestSucceededTurnObserverCalledOnSuccess(t *testing.T) { + repo := newMemoryRepository() + client := &fakeWeKnora{} + observer := &recordingObserver{} + var onErrorCalls []error + onError := func(err error) { onErrorCalls = append(onErrorCalls, err) } + service, err := New(repo, fixedResolver{}, client, session.GroupShared, WithSucceededTurnObserver(observer, onError)) + if err != nil { + t.Fatal(err) + } + req := core.QARequest{ + TenantKey: "tenant", Channel: "dingtalk", ConversationType: core.ConversationGroup, + ExternalChatID: "group-1", ExternalUserID: "user-1", + ExternalMessageID: "message-obs-1", SenderName: "Alice", Query: "question", + } + result, err := service.Ask(context.Background(), req) + if err != nil { + t.Fatalf("Ask: %v", err) + } + if result.Answer != "answer" { + t.Fatalf("unexpected answer: %s", result.Answer) + } + + observer.mu.Lock() + defer observer.mu.Unlock() + if len(observer.turns) != 1 { + t.Fatalf("observer called %d times, want 1", len(observer.turns)) + } + obsTurn := observer.turns[0] + if obsTurn.Status != "succeeded" { + t.Fatalf("observed turn status = %s, want succeeded", obsTurn.Status) + } + if obsTurn.ID != result.TurnID { + t.Fatalf("observed turn ID = %s, want %s", obsTurn.ID, result.TurnID) + } + if obsTurn.Answer != "answer" { + t.Fatalf("observed turn answer = %s, want answer", obsTurn.Answer) + } + if len(obsTurn.References) != 1 { + t.Fatalf("observed turn references = %d, want 1", len(obsTurn.References)) + } + if len(onErrorCalls) != 0 { + t.Fatalf("onError called %d times, want 0", len(onErrorCalls)) + } +} + +func TestSucceededTurnObserverErrorDoesNotAffectAsk(t *testing.T) { + repo := newMemoryRepository() + client := &fakeWeKnora{} + observer := &recordingObserver{err: errors.New("observer failed")} + var onErrorCalls []error + onError := func(err error) { onErrorCalls = append(onErrorCalls, err) } + service, err := New(repo, fixedResolver{}, client, session.GroupShared, WithSucceededTurnObserver(observer, onError)) + if err != nil { + t.Fatal(err) + } + req := core.QARequest{ + TenantKey: "tenant", Channel: "dingtalk", ConversationType: core.ConversationGroup, + ExternalChatID: "group-1", ExternalUserID: "user-1", + ExternalMessageID: "message-obs-2", SenderName: "Alice", Query: "question", + } + result, err := service.Ask(context.Background(), req) + if err != nil { + t.Fatalf("Ask must succeed even when observer fails: %v", err) + } + if result.Answer != "answer" { + t.Fatalf("unexpected answer: %s", result.Answer) + } + if len(onErrorCalls) != 1 { + t.Fatalf("onError called %d times, want 1", len(onErrorCalls)) + } + if onErrorCalls[0] == nil || onErrorCalls[0].Error() != "observer failed" { + t.Fatalf("onError received %v, want 'observer failed'", onErrorCalls[0]) + } +} + +func TestSucceededTurnObserverNotCalledOnFailedWeKnora(t *testing.T) { + repo := newMemoryRepository() + client := &fakeStreamingWeKnora{fakeWeKnora: &fakeWeKnora{}, streamErr: errors.New("weknora failed")} + observer := &recordingObserver{} + var onErrorCalls []error + service, err := New(repo, fixedResolver{}, client, session.GroupShared, WithSucceededTurnObserver(observer, func(err error) { onErrorCalls = append(onErrorCalls, err) })) + if err != nil { + t.Fatal(err) + } + req := core.QARequest{ + TenantKey: "tenant", Channel: "dingtalk", ConversationType: core.ConversationDirect, + ExternalUserID: "user-1", ExternalMessageID: "message-obs-3", Query: "question", + } + _, err = service.AskStream(context.Background(), req, func(string) {}) + if err == nil { + t.Fatal("expected error from failed WeKnora") + } + observer.mu.Lock() + defer observer.mu.Unlock() + if len(observer.turns) != 0 { + t.Fatalf("observer called %d times on failed WeKnora, want 0", len(observer.turns)) + } + if len(onErrorCalls) != 0 { + t.Fatalf("onError called %d times on failed WeKnora, want 0", len(onErrorCalls)) + } +} + +func TestSucceededTurnObserverNotCalledOnReplay(t *testing.T) { + repo := newMemoryRepository() + client := &fakeWeKnora{} + observer := &recordingObserver{} + var onErrorCalls []error + service, err := New(repo, fixedResolver{}, client, session.GroupShared, WithSucceededTurnObserver(observer, func(err error) { onErrorCalls = append(onErrorCalls, err) })) + if err != nil { + t.Fatal(err) + } + req := core.QARequest{ + TenantKey: "tenant", Channel: "dingtalk", ConversationType: core.ConversationGroup, + ExternalChatID: "group-1", ExternalUserID: "user-1", + ExternalMessageID: "message-obs-4", SenderName: "Alice", Query: "question", + } + first, err := service.Ask(context.Background(), req) + if err != nil { + t.Fatalf("first Ask: %v", err) + } + if !first.Replayed { + _ = first // first call is not replay + } + second, err := service.Ask(context.Background(), req) + if err != nil { + t.Fatalf("replay Ask: %v", err) + } + if !second.Replayed { + t.Fatal("second should be replayed") + } + observer.mu.Lock() + defer observer.mu.Unlock() + if len(observer.turns) != 1 { + t.Fatalf("observer called %d times, want 1 (only first call, not replay)", len(observer.turns)) + } + if len(onErrorCalls) != 0 { + t.Fatalf("onError called %d times, want 0", len(onErrorCalls)) + } +} + +func TestSucceededTurnObserverNilOnErrorIsSafe(t *testing.T) { + repo := newMemoryRepository() + client := &fakeWeKnora{} + observer := &recordingObserver{err: errors.New("observer failed")} + service, err := New(repo, fixedResolver{}, client, session.GroupShared, WithSucceededTurnObserver(observer, nil)) + if err != nil { + t.Fatal(err) + } + req := core.QARequest{ + TenantKey: "tenant", Channel: "dingtalk", ConversationType: core.ConversationGroup, + ExternalChatID: "group-1", ExternalUserID: "user-1", + ExternalMessageID: "message-obs-5", SenderName: "Alice", Query: "question", + } + result, err := service.Ask(context.Background(), req) + if err != nil { + t.Fatalf("Ask must succeed with nil onError: %v", err) + } + if result.Answer != "answer" { + t.Fatalf("unexpected answer: %s", result.Answer) + } +} + +func TestSucceededTurnObserverNotCalledOnFinishTurnFailure(t *testing.T) { + repo := &failingRepository{memoryRepository: newMemoryRepository(), finishErr: errors.New("finish turn failed")} + client := &fakeWeKnora{} + observer := &recordingObserver{} + var onErrorCalls []error + service, err := New(repo, fixedResolver{}, client, session.GroupShared, WithSucceededTurnObserver(observer, func(err error) { onErrorCalls = append(onErrorCalls, err) })) + if err != nil { + t.Fatal(err) + } + req := core.QARequest{ + TenantKey: "tenant", Channel: "dingtalk", ConversationType: core.ConversationGroup, + ExternalChatID: "group-1", ExternalUserID: "user-1", + ExternalMessageID: "message-obs-6", SenderName: "Alice", Query: "question", + } + _, err = service.Ask(context.Background(), req) + if err == nil { + t.Fatal("expected error from finish turn failure") + } + + observer.mu.Lock() + defer observer.mu.Unlock() + if len(observer.turns) != 0 { + t.Fatalf("observer called %d times on finish turn failure, want 0", len(observer.turns)) + } + if len(onErrorCalls) != 0 { + t.Fatalf("onError called %d times, want 0", len(onErrorCalls)) + } +} + +func TestWithSucceededTurnObserverRejectsNilAndTypedNil(t *testing.T) { + var typedNil *recordingObserver + for _, tc := range []struct { + name string + observer SucceededTurnObserver + }{ + {name: "nil"}, + {name: "typed nil", observer: typedNil}, + } { + t.Run(tc.name, func(t *testing.T) { + _, err := New(newMemoryRepository(), fixedResolver{}, &fakeWeKnora{}, session.GroupShared, WithSucceededTurnObserver(tc.observer, nil)) + if err == nil { + t.Fatal("expected observer configuration error") + } + }) + } +} + +func TestNewBackwardCompatibleWithoutObserver(t *testing.T) { + repo := newMemoryRepository() + client := &fakeWeKnora{} + service, err := New(repo, fixedResolver{}, client, session.GroupShared) + if err != nil { + t.Fatal(err) + } + req := core.QARequest{ + TenantKey: "tenant", Channel: "dingtalk", ConversationType: core.ConversationGroup, + ExternalChatID: "group-1", ExternalUserID: "user-1", + ExternalMessageID: "message-obs-7", SenderName: "Alice", Query: "question", + } + result, err := service.Ask(context.Background(), req) + if err != nil { + t.Fatalf("Ask: %v", err) + } + if result.Answer != "answer" { + t.Fatalf("unexpected answer: %s", result.Answer) + } +} + +func TestSucceededTurnObserverCalledOnAskStream(t *testing.T) { + repo := newMemoryRepository() + client := &fakeStreamingWeKnora{ + fakeWeKnora: &fakeWeKnora{}, updates: []string{"hello world"}, + streamResult: weknora.ChatResult{RequestID: "request-stream", Answer: "hello world", References: []core.Reference{{KnowledgeID: "kb-1"}}}, + } + observer := &recordingObserver{} + service, err := New(repo, fixedResolver{}, client, session.GroupShared, WithSucceededTurnObserver(observer, nil)) + if err != nil { + t.Fatal(err) + } + result, err := service.AskStream(context.Background(), streamQARequest("message-obs-stream"), func(string) {}) + if err != nil { + t.Fatalf("AskStream: %v", err) + } + if result.Answer != "hello world" { + t.Fatalf("unexpected answer: %s", result.Answer) + } + observer.mu.Lock() + defer observer.mu.Unlock() + if len(observer.turns) != 1 { + t.Fatalf("observer called %d times, want 1", len(observer.turns)) + } + if observer.turns[0].Status != "succeeded" { + t.Fatalf("observed turn status = %s, want succeeded", observer.turns[0].Status) + } +} diff --git a/internal/qa/service_test.go b/internal/qa/service_test.go index 346de1e..63d387f 100644 --- a/internal/qa/service_test.go +++ b/internal/qa/service_test.go @@ -13,16 +13,21 @@ import ( ) type memoryRepository struct { - mu sync.Mutex - turns map[string]core.Turn - sessions map[string]string - beginTurns []core.Turn - finishTurns []core.Turn - deliveries []core.DeliveryUpdate + mu sync.Mutex + turns map[string]core.Turn + sessions map[string]string + sessionTitles map[string]string + beginTurns []core.Turn + finishTurns []core.Turn + deliveries []core.DeliveryUpdate } func newMemoryRepository() *memoryRepository { - return &memoryRepository{turns: map[string]core.Turn{}, sessions: map[string]string{}} + return &memoryRepository{ + turns: map[string]core.Turn{}, + sessions: map[string]string{}, + sessionTitles: map[string]string{}, + } } func (r *memoryRepository) BeginTurn(_ context.Context, turn core.Turn) (core.Turn, bool, error) { r.mu.Lock() @@ -52,8 +57,33 @@ func (r *memoryRepository) ResolveSession(ctx context.Context, m core.SessionMap return old, nil } r.sessions[m.SessionKey] = id + r.sessionTitles[m.SessionKey] = m.DisplayTitle return id, nil } +func (r *memoryRepository) SyncSessionTitle(ctx context.Context, m core.SessionMapping, title string, update core.SessionTitleUpdate) error { + r.mu.Lock() + id := r.sessions[m.SessionKey] + current := r.sessionTitles[m.SessionKey] + r.mu.Unlock() + if current == title { + return nil + } + if err := update(ctx, id, title); err != nil { + return err + } + r.mu.Lock() + r.sessionTitles[m.SessionKey] = title + r.mu.Unlock() + return nil +} +func (r *memoryRepository) InvalidateSession(_ context.Context, sessionKey, expectedSessionID string) error { + r.mu.Lock() + defer r.mu.Unlock() + if r.sessions[sessionKey] == expectedSessionID { + delete(r.sessions, sessionKey) + } + return nil +} func (r *memoryRepository) FinishTurn(_ context.Context, turn core.Turn) error { r.mu.Lock() defer r.mu.Unlock() @@ -84,16 +114,32 @@ func (r *recordingResolver) Resolve(channel, externalChatID string) (string, err } type fakeWeKnora struct { - mu sync.Mutex - sessions int - queries []string - requests []weknora.AgentChatRequest + mu sync.Mutex + sessions int + titles []string + updatedTitles []string + updateErrors []error + queries []string + requests []weknora.AgentChatRequest } -func (f *fakeWeKnora) CreateSession(context.Context, string, string) (string, error) { +func (f *fakeWeKnora) UpdateSessionTitle(_ context.Context, _, title, _ string) error { + f.mu.Lock() + defer f.mu.Unlock() + f.updatedTitles = append(f.updatedTitles, title) + if len(f.updateErrors) == 0 { + return nil + } + err := f.updateErrors[0] + f.updateErrors = f.updateErrors[1:] + return err +} + +func (f *fakeWeKnora) CreateSession(_ context.Context, title, _ string) (string, error) { f.mu.Lock() defer f.mu.Unlock() f.sessions++ + f.titles = append(f.titles, title) return "session-1", nil } func (f *fakeWeKnora) AgentChat(_ context.Context, sessionID string, request weknora.AgentChatRequest) (weknora.ChatResult, error) { @@ -104,6 +150,28 @@ func (f *fakeWeKnora) AgentChat(_ context.Context, sessionID string, request wek return weknora.ChatResult{RequestID: "request-1", Answer: "answer", References: []core.Reference{{KnowledgeID: "kb-1"}}}, nil } +type staleSessionWeKnora struct { + createdSessions int + chatSessions []string +} + +func (f *staleSessionWeKnora) CreateSession(context.Context, string, string) (string, error) { + f.createdSessions++ + return "fresh-session", nil +} + +func (f *staleSessionWeKnora) UpdateSessionTitle(context.Context, string, string, string) error { + return nil +} + +func (f *staleSessionWeKnora) AgentChat(_ context.Context, sessionID string, _ weknora.AgentChatRequest) (weknora.ChatResult, error) { + f.chatSessions = append(f.chatSessions, sessionID) + if sessionID == "stale-session" { + return weknora.ChatResult{}, weknora.ErrSessionNotFound + } + return weknora.ChatResult{RequestID: "request-1", Answer: "recovered"}, nil +} + type fakeStreamingWeKnora struct { *fakeWeKnora updates []string @@ -166,6 +234,129 @@ func TestAskUsesSharedGroupSessionAndReplaysDuplicate(t *testing.T) { } } +func TestAskCreatesReadableDirectSessionTitle(t *testing.T) { + repo := newMemoryRepository() + client := &fakeWeKnora{} + service, err := New(repo, fixedResolver{}, client, session.GroupShared) + if err != nil { + t.Fatal(err) + } + _, err = service.Ask(context.Background(), core.QARequest{ + TenantKey: "tenant", Channel: "dingtalk", ConversationType: core.ConversationDirect, + ExternalUserID: "staff-123456", ExternalMessageID: "message-direct-title", + SenderName: " 张三 ", Query: "question", + }) + if err != nil { + t.Fatalf("Ask: %v", err) + } + client.mu.Lock() + defer client.mu.Unlock() + if len(client.titles) != 1 || client.titles[0] != "张三" { + t.Fatalf("created titles = %v, want [张三]", client.titles) + } +} + +func TestAskCreatesReadableGroupSessionTitle(t *testing.T) { + repo := newMemoryRepository() + client := &fakeWeKnora{} + service, err := New(repo, fixedResolver{}, client, session.GroupShared) + if err != nil { + t.Fatal(err) + } + _, err = service.Ask(context.Background(), core.QARequest{ + TenantKey: "tenant", Channel: "dingtalk", ConversationType: core.ConversationGroup, + ExternalChatID: "cid-987654", ExternalUserID: "staff-1", ExternalMessageID: "message-group-title", + SenderName: "张三", ConversationTitle: " NOVA项目群 ", Query: "question", + }) + if err != nil { + t.Fatalf("Ask: %v", err) + } + client.mu.Lock() + defer client.mu.Unlock() + if len(client.titles) != 1 || client.titles[0] != "NOVA项目群" { + t.Fatalf("created titles = %v, want [NOVA项目群]", client.titles) + } +} + +func TestAskSynchronizesExistingSessionTitleOnlyWhenChanged(t *testing.T) { + repo := newMemoryRepository() + key := "v1:tenant:dingtalk:agent-1:user:staff-1" + repo.sessions[key] = "session-existing" + repo.sessionTitles[key] = "" + client := &fakeWeKnora{} + service, err := New(repo, fixedResolver{}, client, session.GroupShared) + if err != nil { + t.Fatal(err) + } + _, err = service.Ask(context.Background(), core.QARequest{ + TenantKey: "tenant", Channel: "dingtalk", ConversationType: core.ConversationDirect, + ExternalUserID: "staff-1", ExternalMessageID: "message-title-sync", SenderName: "张三", Query: "question", + }) + if err != nil { + t.Fatalf("Ask: %v", err) + } + client.mu.Lock() + defer client.mu.Unlock() + if client.sessions != 0 || len(client.updatedTitles) != 1 || client.updatedTitles[0] != "张三" { + t.Fatalf("sessions=%d updatedTitles=%v", client.sessions, client.updatedTitles) + } +} + +func TestAskSkipsExistingSessionTitleWhenUnchanged(t *testing.T) { + repo := newMemoryRepository() + key := "v1:tenant:dingtalk:agent-1:user:staff-1" + repo.sessions[key] = "session-existing" + repo.sessionTitles[key] = "张三" + client := &fakeWeKnora{} + service, err := New(repo, fixedResolver{}, client, session.GroupShared) + if err != nil { + t.Fatal(err) + } + _, err = service.Ask(context.Background(), core.QARequest{ + TenantKey: "tenant", Channel: "dingtalk", ConversationType: core.ConversationDirect, + ExternalUserID: "staff-1", ExternalMessageID: "message-title-unchanged", SenderName: "张三", Query: "question", + }) + if err != nil { + t.Fatalf("Ask: %v", err) + } + client.mu.Lock() + defer client.mu.Unlock() + if len(client.updatedTitles) != 0 { + t.Fatalf("unexpected title updates: %v", client.updatedTitles) + } +} + +func TestAskRetriesFailedSessionTitleUpdateWithoutBlockingQA(t *testing.T) { + repo := newMemoryRepository() + key := "v1:tenant:dingtalk:agent-1:user:staff-1" + repo.sessions[key] = "session-existing" + repo.sessionTitles[key] = "" + client := &fakeWeKnora{updateErrors: []error{errors.New("temporary update failure"), nil}} + service, err := New(repo, fixedResolver{}, client, session.GroupShared) + if err != nil { + t.Fatal(err) + } + for _, messageID := range []string{"message-title-retry-1", "message-title-retry-2"} { + result, askErr := service.Ask(context.Background(), core.QARequest{ + TenantKey: "tenant", Channel: "dingtalk", ConversationType: core.ConversationDirect, + ExternalUserID: "staff-1", ExternalMessageID: messageID, SenderName: "张三", Query: "question", + }) + if askErr != nil || result.Answer != "answer" { + t.Fatalf("Ask(%s) result=%+v error=%v", messageID, result, askErr) + } + } + client.mu.Lock() + defer client.mu.Unlock() + if client.sessions != 0 || len(client.updatedTitles) != 2 { + t.Fatalf("sessions=%d updatedTitles=%v", client.sessions, client.updatedTitles) + } + repo.mu.Lock() + defer repo.mu.Unlock() + if repo.sessionTitles[key] != "张三" { + t.Fatalf("tracked title=%q, want 张三", repo.sessionTitles[key]) + } +} + func TestAskPropagatesImagesToWeKnora(t *testing.T) { repo := newMemoryRepository() client := &fakeWeKnora{} @@ -624,6 +815,43 @@ func TestAskReturnsGeneratedDeliveryIdentityAndReplay(t *testing.T) { } } +func TestAskRecoversStaleWeKnoraSessionOnce(t *testing.T) { + repo := newMemoryRepository() + client := &staleSessionWeKnora{} + service, err := New(repo, fixedResolver{}, client, session.GroupShared) + if err != nil { + t.Fatal(err) + } + req := core.QARequest{ + TenantKey: "tenant", Channel: "dingtalk", ConversationType: core.ConversationDirect, + ExternalUserID: "user-1", ExternalMessageID: "message-stale-session", Query: "question", + } + sessionKey, _, err := session.BuildKey(session.Identity{ + TenantKey: req.TenantKey, Channel: req.Channel, AgentID: "agent-1", + ConversationType: req.ConversationType, ExternalUserID: req.ExternalUserID, + GroupPolicy: session.GroupShared, + }) + if err != nil { + t.Fatal(err) + } + repo.sessions[sessionKey] = "stale-session" + + result, err := service.Ask(context.Background(), req) + if err != nil { + t.Fatalf("Ask should recover stale session: %v", err) + } + if result.Answer != "recovered" || result.WeKnoraSessionID != "fresh-session" { + t.Fatalf("unexpected recovered result: %+v", result) + } + if client.createdSessions != 1 || len(client.chatSessions) != 2 || + client.chatSessions[0] != "stale-session" || client.chatSessions[1] != "fresh-session" { + t.Fatalf("expected one recreate and one retry, created=%d chats=%v", client.createdSessions, client.chatSessions) + } + if repo.sessions[sessionKey] != "fresh-session" { + t.Fatalf("repository mapping was not replaced: %q", repo.sessions[sessionKey]) + } +} + func TestRecordDeliveryDelegatesToRepository(t *testing.T) { repo := newMemoryRepository() service, err := New(repo, fixedResolver{}, &fakeWeKnora{}, session.GroupShared) diff --git a/internal/questiontable/client.go b/internal/questiontable/client.go new file mode 100644 index 0000000..47613f6 --- /dev/null +++ b/internal/questiontable/client.go @@ -0,0 +1,347 @@ +package questiontable + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "strings" + "sync" + "time" +) + +// Default DingTalk API base. +const defaultBase = "https://api.dingtalk.com" + +// Config holds the required parameters for the DingTalk question-table client. +type Config struct { + ClientID string + Secret string + BaseID string + SheetID string + OperatorID string + FieldMapping map[string]string + + // TokenURL overrides the token endpoint. Empty → default. + TokenURL string + // BaseURL overrides the API base. Empty → default. + BaseURL string +} + +// defaultTransport is a clone of http.DefaultTransport with Proxy=nil so the +// default client never uses a proxy (even from env). Shared across clients. +var defaultTransport = func() *http.Transport { + dt, ok := http.DefaultTransport.(*http.Transport) + if !ok { + return &http.Transport{ + Proxy: nil, + ForceAttemptHTTP2: true, + MaxIdleConns: 100, + IdleConnTimeout: 90 * time.Second, + TLSHandshakeTimeout: 10 * time.Second, + ExpectContinueTimeout: 1 * time.Second, + } + } + // Clone, then clear Proxy. + clone := dt.Clone() + clone.Proxy = nil + return clone +}() + +// Client is a stdlib-only DingTalk HTTP client that inserts records into a +// Notable v1 base. It owns a mutex-protected in-memory access-token cache. +type Client struct { + clientID string + secret string + baseID string + sheetID string + operatorID string + fieldMapping map[string]string + + tokenURL string + baseURL string + + http *http.Client + + mu sync.Mutex + token string + tokenExp time.Time +} + +// NewClient creates a validated Client. It returns an error when any of +// clientID, secret, baseID, sheetID, or operatorID is empty. +// httpClient may be nil; a default is used in that case. +func NewClient(cfg Config, httpClient *http.Client) (*Client, error) { + // Trim and validate. + clientID := strings.TrimSpace(cfg.ClientID) + if clientID == "" { + return nil, errors.New("questiontable: client id is required") + } + secret := strings.TrimSpace(cfg.Secret) + if secret == "" { + return nil, errors.New("questiontable: secret is required") + } + baseID := strings.TrimSpace(cfg.BaseID) + if baseID == "" { + return nil, errors.New("questiontable: base id is required") + } + sheetID := strings.TrimSpace(cfg.SheetID) + if sheetID == "" { + return nil, errors.New("questiontable: sheet id is required") + } + operatorID := strings.TrimSpace(cfg.OperatorID) + if operatorID == "" { + return nil, errors.New("questiontable: operator id is required") + } + + if httpClient == nil { + httpClient = &http.Client{ + Transport: defaultTransport, + Timeout: 30 * time.Second, + } + } + + tokenURL := strings.TrimSpace(cfg.TokenURL) + if tokenURL == "" { + tokenURL = defaultBase + "/v1.0/oauth2/accessToken" + } + baseURL := strings.TrimSpace(cfg.BaseURL) + if baseURL == "" { + baseURL = defaultBase + } + + return &Client{ + clientID: clientID, + secret: secret, + baseID: baseID, + sheetID: sheetID, + operatorID: operatorID, + fieldMapping: cloneFieldMapping(cfg.FieldMapping), + tokenURL: tokenURL, + baseURL: baseURL, + http: httpClient, + }, nil +} + +// TokenURL returns the configured token URL (test seam). +func (c *Client) TokenURL() string { return c.tokenURL } + +// BaseURL returns the configured API base (test seam). +func (c *Client) BaseURL() string { return c.baseURL } + +// insertRecordReq is the JSON body for the Notable v1 insertRecord endpoint. +type insertRecordReq struct { + Records []insertRecord `json:"records"` +} + +type insertRecord struct { + Fields map[string]interface{} `json:"fields"` +} + +// insertRecordResp is the success response body. +type insertRecordResp struct { + Value []struct { + ID string `json:"id"` + } `json:"value"` +} + +// tokenResp is the access-token response body. +type tokenResp struct { + AccessToken string `json:"accessToken"` + ExpireIn int64 `json:"expireIn"` +} + +// InsertRecord sends a single question-table row to DingTalk Notable v1. +// It remains the compatibility entry point for the existing question-table dispatcher. +func (c *Client) InsertRecord(ctx context.Context, row Row) (string, error) { + return c.InsertFields(ctx, row.ToFields()) +} + +// InsertFields sends one already-typed field map to DingTalk Notable v1 and +// returns the record ID. It is shared by other reviewed Notable table schemas. +func (c *Client) InsertFields(ctx context.Context, fields map[string]interface{}) (string, error) { + fields = c.remapFields(fields) + token, err := c.getAccessToken(ctx) + if err != nil { + return "", fmt.Errorf("questiontable token: %w", err) + } + + path := fmt.Sprintf("/v1.0/notable/bases/%s/sheets/%s/records", + url.PathEscape(c.baseID), url.PathEscape(c.sheetID)) + reqURL := c.baseURL + path + "?operatorId=" + url.QueryEscape(c.operatorID) + + body := insertRecordReq{Records: []insertRecord{{Fields: fields}}} + jsonBody, err := json.Marshal(body) + if err != nil { + return "", fmt.Errorf("questiontable marshal: %w", err) + } + + req, err := http.NewRequestWithContext(ctx, http.MethodPost, reqURL, bytes.NewReader(jsonBody)) + if err != nil { + return "", fmt.Errorf("questiontable request: %w", err) + } + req.Header.Set("Content-Type", "application/json") + req.Header.Set("x-acs-dingtalk-access-token", token) + + resp, err := c.http.Do(req) + if err != nil { + return "", safeDoErr(ctx, err) + } + defer resp.Body.Close() + + // Read bounded response body. + raw, err := io.ReadAll(io.LimitReader(resp.Body, 64<<10)) + if err != nil { + return "", fmt.Errorf("questiontable read response: %w", err) + } + + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + return "", fmt.Errorf("questiontable insert returned HTTP %d", resp.StatusCode) + } + + var ir insertRecordResp + if err := json.Unmarshal(raw, &ir); err != nil { + return "", fmt.Errorf("questiontable decode response: %w", err) + } + if len(ir.Value) == 0 { + return "", errors.New("questiontable empty value list") + } + if strings.TrimSpace(ir.Value[0].ID) == "" { + return "", errors.New("questiontable empty record id") + } + + return ir.Value[0].ID, nil +} + +func cloneFieldMapping(in map[string]string) map[string]string { + out := make(map[string]string, len(in)) + for key, value := range in { + out[key] = value + } + return out +} + +var providerFieldLogical = map[string]string{ + "ZaMZF6j": "chinese_question", "SCug9My": "asked_time", "S2XA1uZ": "asker", + "bETcL3r": "original_question", "Y4cpmxU": "answer", "JgY2f1z": "trigger_person", + "DNIV3mQ": "language", "eBc6a6b": "department", "fPNLeVW": "region", + "01ZM8y7": "standard_question", "fj3JQ1C": "original_question", "07YYagS": "language", "Eu7gkKu": "asker", +} + +func (c *Client) remapFields(in map[string]interface{}) map[string]interface{} { + if len(c.fieldMapping) == 0 { + return in + } + out := make(map[string]interface{}, len(in)) + for providerID, value := range in { + logical := providerFieldLogical[providerID] + if mapped := c.fieldMapping[logical]; logical != "" && mapped != "" { + out[mapped] = value + } else { + out[providerID] = value + } + } + return out +} + +// safeDoErr wraps an http.Do error without exposing the raw URL or credentials. +// If the context is already done, returns a wrapped ctx.Err() so errors.Is works. +func safeDoErr(ctx context.Context, err error) error { + if ctx.Err() != nil { + return fmt.Errorf("questiontable insert: %w", ctx.Err()) + } + return errors.New("questiontable insert: network error") +} + +// getAccessToken returns a cached token or fetches a new one. +func (c *Client) getAccessToken(ctx context.Context) (string, error) { + c.mu.Lock() + if c.token != "" && time.Now().Before(c.tokenExp) { + tok := c.token + c.mu.Unlock() + return tok, nil + } + c.mu.Unlock() + + return c.fetchToken(ctx) +} + +// fetchToken calls the DingTalk OAuth2 endpoint and caches the result. +func (c *Client) fetchToken(ctx context.Context) (string, error) { + c.mu.Lock() + defer c.mu.Unlock() + + // Double-check inside lock. + if c.token != "" && time.Now().Before(c.tokenExp) { + return c.token, nil + } + + body := map[string]string{ + "appKey": c.clientID, + "appSecret": c.secret, + } + jsonBody, err := json.Marshal(body) + if err != nil { + return "", fmt.Errorf("questiontable token marshal: %w", err) + } + + req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.tokenURL, bytes.NewReader(jsonBody)) + if err != nil { + return "", fmt.Errorf("questiontable token request: %w", err) + } + req.Header.Set("Content-Type", "application/json") + + resp, err := c.http.Do(req) + if err != nil { + return "", safeTokenDoErr(ctx, err) + } + defer resp.Body.Close() + + raw, err := io.ReadAll(io.LimitReader(resp.Body, 64<<10)) + if err != nil { + return "", fmt.Errorf("questiontable token read: %w", err) + } + + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + return "", fmt.Errorf("questiontable token returned HTTP %d", resp.StatusCode) + } + + var tr tokenResp + if err := json.Unmarshal(raw, &tr); err != nil { + return "", fmt.Errorf("questiontable token decode: %w", err) + } + if strings.TrimSpace(tr.AccessToken) == "" { + return "", errors.New("questiontable empty access token") + } + + // Token expiry must never be extended beyond DingTalk's expireIn. + if tr.ExpireIn <= 0 { + return "", errors.New("questiontable token: non-positive expireIn") + } + + exp := time.Duration(tr.ExpireIn) * time.Second + // For very short TTL (<=30s), cache for a positive fraction (TTL/2). + if exp <= 30*time.Second { + exp = exp / 2 + } else { + // Safety margin: subtract 30 seconds from expiry. + exp -= 30 * time.Second + } + + c.token = tr.AccessToken + c.tokenExp = time.Now().Add(exp) + + return c.token, nil +} + +// safeTokenDoErr wraps an http.Do error from token fetch without exposing raw URL or credentials. +func safeTokenDoErr(ctx context.Context, err error) error { + if ctx.Err() != nil { + return fmt.Errorf("questiontable token: %w", ctx.Err()) + } + return errors.New("questiontable token: network error") +} diff --git a/internal/questiontable/client_fields_test.go b/internal/questiontable/client_fields_test.go new file mode 100644 index 0000000..b1f8752 --- /dev/null +++ b/internal/questiontable/client_fields_test.go @@ -0,0 +1,52 @@ +package questiontable + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "reflect" + "testing" +) + +func TestInsertFieldsUsesExactProvidedFAQFieldMap(t *testing.T) { + want := map[string]interface{}{ + "01ZM8y7": "标准问题", + "fj3JQ1C": "原始问题", + "07YYagS": "Chinese", + } + var got map[string]interface{} + mux := http.NewServeMux() + mux.HandleFunc("/token", func(w http.ResponseWriter, _ *http.Request) { + _, _ = w.Write([]byte(`{"accessToken":"token","expireIn":7200}`)) + }) + mux.HandleFunc("/v1.0/notable/bases/faq-base/sheets/faq-sheet/records", func(w http.ResponseWriter, r *http.Request) { + var body struct { + Records []struct { + Fields map[string]interface{} `json:"fields"` + } `json:"records"` + } + if err := json.NewDecoder(r.Body).Decode(&body); err != nil || len(body.Records) != 1 { + t.Fatalf("invalid request body: err=%v body=%#v", err, body) + } + got = body.Records[0].Fields + _, _ = w.Write([]byte(`{"value":[{"id":"faq-record-1"}]}`)) + }) + server := httptest.NewServer(mux) + defer server.Close() + + client, err := NewClient(Config{ + ClientID: "client", Secret: "secret", BaseID: "faq-base", SheetID: "faq-sheet", OperatorID: "operator", + TokenURL: server.URL + "/token", BaseURL: server.URL, + }, server.Client()) + if err != nil { + t.Fatal(err) + } + recordID, err := client.InsertFields(context.Background(), want) + if err != nil { + t.Fatal(err) + } + if recordID != "faq-record-1" || !reflect.DeepEqual(got, want) { + t.Fatalf("recordID=%q fields=%#v", recordID, got) + } +} diff --git a/internal/questiontable/client_test.go b/internal/questiontable/client_test.go new file mode 100644 index 0000000..b1a9364 --- /dev/null +++ b/internal/questiontable/client_test.go @@ -0,0 +1,577 @@ +package questiontable + +import ( + "context" + "encoding/json" + "errors" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" + "time" +) + +func TestNewClientRejectsMissingConfig(t *testing.T) { + tests := []struct { + name string + cfg Config + }{ + {"empty client id", Config{Secret: "s", BaseID: "b", SheetID: "sh", OperatorID: "op"}}, + {"empty secret", Config{ClientID: "c", BaseID: "b", SheetID: "sh", OperatorID: "op"}}, + {"empty base id", Config{ClientID: "c", Secret: "s", SheetID: "sh", OperatorID: "op"}}, + {"empty sheet id", Config{ClientID: "c", Secret: "s", BaseID: "b", OperatorID: "op"}}, + {"empty operator id", Config{ClientID: "c", Secret: "s", BaseID: "b", SheetID: "sh"}}, + } + for _, tt := range tests { + _, err := NewClient(tt.cfg, nil) + if err == nil { + t.Errorf("%s: expected error, got nil", tt.name) + } + } +} + +func TestInsertRecordMethodPathHeaderBody(t *testing.T) { + var ( + gotMethod string + gotPath string + gotQuery string + gotToken string + gotBody string + tokenCalls int32 + insertCalls int32 + ) + + mux := http.NewServeMux() + mux.HandleFunc("/v1.0/oauth2/accessToken", func(w http.ResponseWriter, r *http.Request) { + atomic.AddInt32(&tokenCalls, 1) + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"accessToken":"test-access-token","expireIn":7200}`)) + }) + mux.HandleFunc("/v1.0/notable/bases/b1/sheets/sh1/records", func(w http.ResponseWriter, r *http.Request) { + atomic.AddInt32(&insertCalls, 1) + gotMethod = r.Method + gotPath = r.URL.Path + gotQuery = r.URL.RawQuery + gotToken = r.Header.Get("x-acs-dingtalk-access-token") + + var body map[string]interface{} + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + t.Errorf("decode body: %v", err) + } + records, ok := body["records"].([]interface{}) + if !ok || len(records) != 1 { + t.Errorf("records must contain exactly one record: %#v", body["records"]) + } else { + record, ok := records[0].(map[string]interface{}) + if !ok { + t.Errorf("record must be an object: %#v", records[0]) + } else { + fields, ok := record["fields"].(map[string]interface{}) + if !ok { + t.Errorf("record must wrap values in a fields object: %#v", record) + } else if len(record) != 1 { + t.Errorf("record must contain only fields, got keys: %#v", record) + } else if _, ok := fields[FieldOriginalQuestion]; !ok { + t.Errorf("nested fields missing original question field") + } + } + } + raw, _ := json.Marshal(body) + gotBody = string(raw) + + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"value":[{"id":"rec-abc-123"}]}`)) + }) + server := httptest.NewServer(mux) + defer server.Close() + + client, err := NewClient(Config{ + ClientID: "appKey-1", + Secret: "appSecret-1", + BaseID: "b1", + SheetID: "sh1", + OperatorID: "operator-1", + TokenURL: server.URL + "/v1.0/oauth2/accessToken", + BaseURL: server.URL, + }, nil) + if err != nil { + t.Fatalf("NewClient: %v", err) + } + + row := Row{ + Question: "测试问题", + Answer: "测试答案", + AskerName: "张三", + AskerUnionID: "union-zhang-san", + } + recID, err := client.InsertRecord(context.Background(), row) + if err != nil { + t.Fatalf("InsertRecord: %v", err) + } + if recID != "rec-abc-123" { + t.Errorf("recordID = %q, want %q", recID, "rec-abc-123") + } + + // Assert method, path, header, token. + if gotMethod != http.MethodPost { + t.Errorf("method = %q, want POST", gotMethod) + } + if gotPath != "/v1.0/notable/bases/b1/sheets/sh1/records" { + t.Errorf("path = %q", gotPath) + } + if gotToken != "test-access-token" { + t.Errorf("token header = %q, want test-access-token", gotToken) + } + + // operatorId must be in query only. + if !strings.Contains(gotQuery, "operatorId=operator-1") { + t.Errorf("query missing operatorId: %q", gotQuery) + } + + // body must NOT contain operatorId. + if strings.Contains(gotBody, "operatorId") { + t.Errorf("body contains operatorId: %q", gotBody) + } + + // body must contain typed field IDs. + if !strings.Contains(gotBody, `"ZaMZF6j"`) { + t.Errorf("body missing field ID ZaMZF6j: %q", gotBody) + } + if !strings.Contains(gotBody, `"Y4cpmxU"`) { + t.Errorf("body missing field ID Y4cpmxU: %q", gotBody) + } + + // body must NOT contain the omitted select fields. + omitted := []string{"QMn9UoU", "H3gtTuv", "nFvv8OR", "UMqUPAG", "lnF7gF9"} + for _, fid := range omitted { + if strings.Contains(gotBody, fid) { + t.Errorf("body contains omitted select field %q: %q", fid, gotBody) + } + } +} + +func TestTokenCacheTwoInsertsOneTokenCall(t *testing.T) { + var tokenCalls int32 + + mux := http.NewServeMux() + mux.HandleFunc("/v1.0/oauth2/accessToken", func(w http.ResponseWriter, r *http.Request) { + atomic.AddInt32(&tokenCalls, 1) + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"accessToken":"cached-token","expireIn":7200}`)) + }) + mux.HandleFunc("/v1.0/notable/bases/b1/sheets/sh1/records", func(w http.ResponseWriter, r *http.Request) { + if r.Header.Get("x-acs-dingtalk-access-token") != "cached-token" { + t.Errorf("unexpected token on insert") + } + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"value":[{"id":"rec-1"}]}`)) + }) + server := httptest.NewServer(mux) + defer server.Close() + + client, err := NewClient(Config{ + ClientID: "appKey-1", + Secret: "appSecret-1", + BaseID: "b1", + SheetID: "sh1", + OperatorID: "operator-1", + TokenURL: server.URL + "/v1.0/oauth2/accessToken", + BaseURL: server.URL, + }, nil) + if err != nil { + t.Fatalf("NewClient: %v", err) + } + + row := Row{Question: "q", Answer: "a", AskerName: "x", AskerUnionID: "union-x"} + + // Two inserts, only one token call. + for i := 0; i < 2; i++ { + if _, err := client.InsertRecord(context.Background(), row); err != nil { + t.Fatalf("InsertRecord %d: %v", i, err) + } + } + + if tokenCalls != 1 { + t.Errorf("token calls = %d, want 1", tokenCalls) + } +} + +func TestInsertRecordNon2xx(t *testing.T) { + mux := http.NewServeMux() + mux.HandleFunc("/v1.0/oauth2/accessToken", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"accessToken":"tok","expireIn":7200}`)) + }) + mux.HandleFunc("/v1.0/notable/bases/b1/sheets/sh1/records", func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusBadRequest) + _, _ = w.Write([]byte(`{"code":"invalid","message":"bad request"}`)) + }) + server := httptest.NewServer(mux) + defer server.Close() + + client, _ := NewClient(Config{ + ClientID: "c", Secret: "s", BaseID: "b1", SheetID: "sh1", OperatorID: "op", + TokenURL: server.URL + "/v1.0/oauth2/accessToken", BaseURL: server.URL, + }, nil) + + row := Row{Question: "q", Answer: "a", AskerName: "x", AskerUnionID: "union-x"} + _, err := client.InsertRecord(context.Background(), row) + if err == nil { + t.Fatal("expected error for non-2xx") + } + + // Error must not contain token, secret, operator, or raw row values. + errStr := err.Error() + for _, secret := range []string{"tok", "op", "union-x"} { + if strings.Contains(errStr, secret) { + t.Errorf("error redaction failed: %q found in %q", secret, errStr) + } + } +} + +func TestInsertRecordMalformedResponse(t *testing.T) { + mux := http.NewServeMux() + mux.HandleFunc("/v1.0/oauth2/accessToken", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"accessToken":"tok","expireIn":7200}`)) + }) + mux.HandleFunc("/v1.0/notable/bases/b1/sheets/sh1/records", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`not json`)) + }) + server := httptest.NewServer(mux) + defer server.Close() + + client, _ := NewClient(Config{ + ClientID: "c", Secret: "s", BaseID: "b1", SheetID: "sh1", OperatorID: "op", + TokenURL: server.URL + "/v1.0/oauth2/accessToken", BaseURL: server.URL, + }, nil) + + row := Row{Question: "q", Answer: "a", AskerName: "x", AskerUnionID: "union-x"} + _, err := client.InsertRecord(context.Background(), row) + if err == nil { + t.Fatal("expected error for malformed response") + } +} + +func TestInsertRecordEmptyValueList(t *testing.T) { + mux := http.NewServeMux() + mux.HandleFunc("/v1.0/oauth2/accessToken", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"accessToken":"tok","expireIn":7200}`)) + }) + mux.HandleFunc("/v1.0/notable/bases/b1/sheets/sh1/records", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"value":[]}`)) + }) + server := httptest.NewServer(mux) + defer server.Close() + + client, _ := NewClient(Config{ + ClientID: "c", Secret: "s", BaseID: "b1", SheetID: "sh1", OperatorID: "op", + TokenURL: server.URL + "/v1.0/oauth2/accessToken", BaseURL: server.URL, + }, nil) + + row := Row{Question: "q", Answer: "a", AskerName: "x", AskerUnionID: "union-x"} + _, err := client.InsertRecord(context.Background(), row) + if err == nil { + t.Fatal("expected error for empty value list") + } +} + +func TestInsertRecordEmptyRecordID(t *testing.T) { + mux := http.NewServeMux() + mux.HandleFunc("/v1.0/oauth2/accessToken", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"accessToken":"tok","expireIn":7200}`)) + }) + mux.HandleFunc("/v1.0/notable/bases/b1/sheets/sh1/records", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"value":[{"id":""}]}`)) + }) + server := httptest.NewServer(mux) + defer server.Close() + + client, _ := NewClient(Config{ + ClientID: "c", Secret: "s", BaseID: "b1", SheetID: "sh1", OperatorID: "op", + TokenURL: server.URL + "/v1.0/oauth2/accessToken", BaseURL: server.URL, + }, nil) + + row := Row{Question: "q", Answer: "a", AskerName: "x", AskerUnionID: "union-x"} + _, err := client.InsertRecord(context.Background(), row) + if err == nil { + t.Fatal("expected error for empty record id") + } +} + +func TestTokenCallErrorRedaction(t *testing.T) { + // Token endpoint returns non-2xx. + mux := http.NewServeMux() + mux.HandleFunc("/v1.0/oauth2/accessToken", func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusUnauthorized) + _, _ = w.Write([]byte(`{"code":"unauthorized","message":"invalid appSecret"}`)) + }) + server := httptest.NewServer(mux) + defer server.Close() + + client, _ := NewClient(Config{ + ClientID: "c", Secret: "s", BaseID: "b1", SheetID: "sh1", OperatorID: "op", + TokenURL: server.URL + "/v1.0/oauth2/accessToken", BaseURL: server.URL, + }, nil) + + row := Row{Question: "q", Answer: "a", AskerName: "x", AskerUnionID: "union-x"} + _, err := client.InsertRecord(context.Background(), row) + if err == nil { + t.Fatal("expected error for token failure") + } + + // Error must not contain raw body, secret, or token. + errStr := err.Error() + for _, secret := range []string{"appSecret", "invalid appSecret", "unauthorized"} { + if strings.Contains(errStr, secret) { + t.Errorf("error redaction failed: %q found in %q", secret, errStr) + } + } +} + +func TestTokenEmptyAccessToken(t *testing.T) { + mux := http.NewServeMux() + mux.HandleFunc("/v1.0/oauth2/accessToken", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"accessToken":"","expireIn":7200}`)) + }) + server := httptest.NewServer(mux) + defer server.Close() + + client, _ := NewClient(Config{ + ClientID: "c", Secret: "s", BaseID: "b1", SheetID: "sh1", OperatorID: "op", + TokenURL: server.URL + "/v1.0/oauth2/accessToken", BaseURL: server.URL, + }, nil) + + row := Row{Question: "q", Answer: "a", AskerName: "x", AskerUnionID: "union-x"} + _, err := client.InsertRecord(context.Background(), row) + if err == nil { + t.Fatal("expected error for empty access token") + } +} + +func TestTokenExpirySafetyMargin(t *testing.T) { + // Token with expireIn=1: TTL ≤ 30s → exp = TTL/2 (500ms). The tokenExp + // must be after now but no later than server expiry (1s) + small scheduling + // tolerance. An immediate second request should still reuse the cache. + var tokenCalls int32 + + mux := http.NewServeMux() + mux.HandleFunc("/v1.0/oauth2/accessToken", func(w http.ResponseWriter, r *http.Request) { + atomic.AddInt32(&tokenCalls, 1) + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"accessToken":"short-token","expireIn":1}`)) + }) + mux.HandleFunc("/v1.0/notable/bases/b1/sheets/sh1/records", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"value":[{"id":"rec-1"}]}`)) + }) + server := httptest.NewServer(mux) + defer server.Close() + + client, _ := NewClient(Config{ + ClientID: "c", Secret: "s", BaseID: "b1", SheetID: "sh1", OperatorID: "op", + TokenURL: server.URL + "/v1.0/oauth2/accessToken", BaseURL: server.URL, + }, nil) + + row := Row{Question: "q", Answer: "a", AskerName: "x", AskerUnionID: "union-x"} + + // First call: token fetch. + before := time.Now() + _, err := client.InsertRecord(context.Background(), row) + if err != nil { + t.Fatalf("first InsertRecord: %v", err) + } + if tokenCalls != 1 { + t.Errorf("token calls after first insert = %d, want 1", tokenCalls) + } + + // Inspect tokenExp. + client.mu.Lock() + exp := client.tokenExp + client.mu.Unlock() + + // tokenExp must be after now. + if !exp.After(before) { + t.Errorf("tokenExp %v is not after request start %v", exp, before) + } + // tokenExp must not exceed server expiry (1s) + scheduling tolerance (500ms). + if exp.After(before.Add(1500 * time.Millisecond)) { + t.Errorf("tokenExp %v exceeds server expiry + tolerance", exp) + } + + // Second call: should use cached token (within TTL/2 = 500ms). + _, err = client.InsertRecord(context.Background(), row) + if err != nil { + t.Fatalf("second InsertRecord: %v", err) + } + if tokenCalls != 1 { + t.Errorf("token calls after second insert = %d, want 1 (cached)", tokenCalls) + } +} + +func TestTokenExpiryNonPositive(t *testing.T) { + mux := http.NewServeMux() + mux.HandleFunc("/v1.0/oauth2/accessToken", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"accessToken":"tok","expireIn":0}`)) + }) + server := httptest.NewServer(mux) + defer server.Close() + + client, _ := NewClient(Config{ + ClientID: "c", Secret: "s", BaseID: "b1", SheetID: "sh1", OperatorID: "op", + TokenURL: server.URL + "/v1.0/oauth2/accessToken", BaseURL: server.URL, + }, nil) + + row := Row{Question: "q", Answer: "a", AskerName: "x", AskerUnionID: "union-x"} + _, err := client.InsertRecord(context.Background(), row) + if err == nil { + t.Fatal("expected error for non-positive expireIn") + } +} + +func TestContextTimeout(t *testing.T) { + handlerDone := make(chan struct{}) + mux := http.NewServeMux() + mux.HandleFunc("/v1.0/oauth2/accessToken", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"accessToken":"tok","expireIn":7200}`)) + }) + mux.HandleFunc("/v1.0/notable/bases/b1/sheets/sh1/records", func(w http.ResponseWriter, r *http.Request) { + // Wait for context cancellation or test signal. + select { + case <-r.Context().Done(): + case <-handlerDone: + } + }) + server := httptest.NewServer(mux) + defer server.Close() + defer close(handlerDone) // runs before server.Close (LIFO), unblocks the handler + + // Use a client with keep-alives disabled so the TCP connection + // closes after the handler returns — httptest.Server.Close won't hang. + httpClient := &http.Client{ + Transport: &http.Transport{DisableKeepAlives: true}, + Timeout: 30 * time.Second, + } + client, _ := NewClient(Config{ + ClientID: "c", Secret: "s", BaseID: "b1", SheetID: "sh1", OperatorID: "op", + TokenURL: server.URL + "/v1.0/oauth2/accessToken", BaseURL: server.URL, + }, httpClient) + + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond) + defer cancel() + + row := Row{Question: "q", Answer: "a", AskerName: "x", AskerUnionID: "union-x"} + _, err := client.InsertRecord(ctx, row) + if err == nil { + t.Fatal("expected timeout error") + } + if !errors.Is(err, context.DeadlineExceeded) && !strings.Contains(err.Error(), "context deadline") { + t.Logf("timeout error (may be wrapped): %v", err) + } +} + +func TestDefaultURLs(t *testing.T) { + client, err := NewClient(Config{ + ClientID: "c", Secret: "s", BaseID: "b1", SheetID: "sh1", OperatorID: "op", + }, nil) + if err != nil { + t.Fatalf("NewClient: %v", err) + } + if client.TokenURL() != defaultBase+"/v1.0/oauth2/accessToken" { + t.Errorf("default token URL = %q, want %q", client.TokenURL(), defaultBase+"/v1.0/oauth2/accessToken") + } + if client.BaseURL() != defaultBase { + t.Errorf("default base URL = %q, want %q", client.BaseURL(), defaultBase) + } +} + +func TestCustomURLs(t *testing.T) { + client, err := NewClient(Config{ + ClientID: "c", Secret: "s", BaseID: "b1", SheetID: "sh1", OperatorID: "op", + TokenURL: "https://custom.example.com/token", + BaseURL: "https://custom.example.com", + }, nil) + if err != nil { + t.Fatalf("NewClient: %v", err) + } + if client.TokenURL() != "https://custom.example.com/token" { + t.Errorf("custom token URL = %q", client.TokenURL()) + } + if client.BaseURL() != "https://custom.example.com" { + t.Errorf("custom base URL = %q", client.BaseURL()) + } +} + +func TestNewClientNilHTTP(t *testing.T) { + client, err := NewClient(Config{ + ClientID: "c", Secret: "s", BaseID: "b1", SheetID: "sh1", OperatorID: "op", + }, nil) + if err != nil { + t.Fatalf("NewClient with nil http: %v", err) + } + if client.http == nil { + t.Fatal("http client is nil after construction with nil argument") + } +} + +func TestNewClientCustomHTTP(t *testing.T) { + custom := &http.Client{Timeout: 5 * time.Second} + client, err := NewClient(Config{ + ClientID: "c", Secret: "s", BaseID: "b1", SheetID: "sh1", OperatorID: "op", + }, custom) + if err != nil { + t.Fatalf("NewClient with custom http: %v", err) + } + if client.http != custom { + t.Fatal("http client is not the custom one") + } +} + +func TestDefaultTransportNoProxy(t *testing.T) { + // The default transport must have Proxy=nil. + if defaultTransport.Proxy != nil { + t.Error("defaultTransport Proxy is not nil") + } +} + +func TestInsertRecordDoErrorRedaction(t *testing.T) { + // Custom RoundTripper that returns an error containing secrets. + secretErr := errors.New("connect: dial tcp https://api.dingtalk.com?operatorId=secret-op failed: row data union-x") + rt := &errorRoundTripper{err: secretErr} + + client, _ := NewClient(Config{ + ClientID: "c", Secret: "s", BaseID: "b1", SheetID: "sh1", OperatorID: "op", + TokenURL: "https://token.example.com", BaseURL: "https://api.example.com", + }, &http.Client{Transport: rt}) + + row := Row{Question: "q", Answer: "a", AskerName: "x", AskerUnionID: "union-x"} + _, err := client.InsertRecord(context.Background(), row) + if err == nil { + t.Fatal("expected error") + } + + errStr := err.Error() + for _, secret := range []string{"secret-op", "union-x", "api.dingtalk.com"} { + if strings.Contains(strings.ToLower(errStr), strings.ToLower(secret)) { + t.Errorf("error redaction failed: %q found in %q", secret, errStr) + } + } +} + +// errorRoundTripper returns a fixed error on every RoundTrip. +type errorRoundTripper struct { + err error +} + +func (rt *errorRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { + return nil, rt.err +} diff --git a/internal/questiontable/dispatcher.go b/internal/questiontable/dispatcher.go new file mode 100644 index 0000000..06d7e34 --- /dev/null +++ b/internal/questiontable/dispatcher.go @@ -0,0 +1,233 @@ +package questiontable + +import ( + "context" + "errors" + "fmt" + "reflect" + "strings" + "time" +) + +// FailureCodeRemoteInsertFailed is the stable public failure code used when +// InsertRecord returns an error. The raw error is never persisted or returned. +const FailureCodeRemoteInsertFailed = "remote_question_table_insert_failed" + +// PendingExport is a row waiting to be exported to the remote question table. +type PendingExport struct { + ExportID string + Row Row + Attempts int +} + +// ExportRepository is the persistence contract for the background dispatcher. +type ExportRepository interface { + // Claim returns up to limit pending exports whose attempt count is below + // maxAttempts and whose last claim time is before staleBefore. + Claim(ctx context.Context, limit int, maxAttempts int, staleBefore time.Time) ([]PendingExport, error) + + // MarkExported records the location (Notable record ID) for a successfully exported row. + MarkExported(ctx context.Context, exportID, location string) error + + // MarkFailed records a failure for the given exportID with a stable failure code. + MarkFailed(ctx context.Context, exportID, failureCode string) error +} + +// RecordInserter is the contract for inserting a row to the remote Notable base. +// *Client.InsertRecord satisfies this interface. +type RecordInserter interface { + InsertRecord(ctx context.Context, row Row) (string, error) +} + +// AnswerRewriter optionally transforms the answer before it is written to the +// question table, applying the same outbound conversion used for DingTalk +// delivery (resource images to stable HTTPS, document links, anchor cleanup). +// When nil or when Rewrite returns an error, the original answer is written so +// the record is never lost. +type AnswerRewriter interface { + Rewrite(ctx context.Context, content string) (string, error) +} + +// DispatcherStats holds the outcome counters for a single RunOnce invocation. +type DispatcherStats struct { + Claimed int + Exported int + Failed int +} + +// DispatcherOptions holds optional configuration for the Dispatcher. +type DispatcherOptions struct { + Batch int + MaxAttempts int + ClaimLease time.Duration + SendTimeout time.Duration + Rewriter AnswerRewriter +} + +// Dispatcher runs the background dispatch loop that claims pending exports +// and inserts them to the remote question table. +type Dispatcher struct { + repo ExportRepository + inserter RecordInserter + rewriter AnswerRewriter + + batch int + maxAttempts int + claimLease time.Duration + sendTimeout time.Duration +} + +// isNil reports whether x is nil. It accepts any value and only calls +// IsNil when the underlying kind is nil-able. Value types (structs, ints, +// strings, etc.) are never nil and return false without panicking. +func isNil(x interface{}) bool { + if x == nil { + return true + } + v := reflect.ValueOf(x) + switch v.Kind() { + case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice: + return v.IsNil() + default: + return false + } +} + +// NewDispatcher creates a validated Dispatcher. It returns an error when repo +// or inserter is nil (including typed nil), or when any option value is out of +// bounds. Defaults: batch=10, maxAttempts=5, claimLease=5m, sendTimeout=10s. +func NewDispatcher(repo ExportRepository, inserter RecordInserter, opts *DispatcherOptions) (*Dispatcher, error) { + if isNil(repo) { + return nil, errors.New("questiontable dispatcher: repo is nil") + } + if isNil(inserter) { + return nil, errors.New("questiontable dispatcher: inserter is nil") + } + + batch := 10 + maxAttempts := 5 + claimLease := 5 * time.Minute + sendTimeout := 10 * time.Second + var rewriter AnswerRewriter + + if opts != nil { + rewriter = opts.Rewriter + if opts.Batch < 0 { + return nil, fmt.Errorf("questiontable dispatcher: batch must be >= 0, got %d", opts.Batch) + } + if opts.Batch > 0 { + batch = opts.Batch + } + + if opts.MaxAttempts < 0 { + return nil, fmt.Errorf("questiontable dispatcher: maxAttempts must be >= 0, got %d", opts.MaxAttempts) + } + if opts.MaxAttempts > 0 { + maxAttempts = opts.MaxAttempts + } + + if opts.ClaimLease < 0 { + return nil, fmt.Errorf("questiontable dispatcher: claimLease must be >= 0, got %v", opts.ClaimLease) + } + if opts.ClaimLease > 0 { + claimLease = opts.ClaimLease + } + + if opts.SendTimeout < 0 { + return nil, fmt.Errorf("questiontable dispatcher: sendTimeout must be >= 0, got %v", opts.SendTimeout) + } + if opts.SendTimeout > 0 { + sendTimeout = opts.SendTimeout + } + } + + return &Dispatcher{ + repo: repo, + inserter: inserter, + rewriter: rewriter, + batch: batch, + maxAttempts: maxAttempts, + claimLease: claimLease, + sendTimeout: sendTimeout, + }, nil +} + +// RunOnce claims pending exports and dispatches them to the remote table. +// It returns stats and any error that prevented the entire operation. +// Individual row failures are tracked in stats.Failed and do not cause +// RunOnce to return an error. +func (d *Dispatcher) RunOnce(ctx context.Context) (DispatcherStats, error) { + var stats DispatcherStats + + // Parent context precheck. + if err := ctx.Err(); err != nil { + return stats, fmt.Errorf("questiontable dispatcher: context invalid: %w", err) + } + + staleBefore := time.Now().Add(-d.claimLease) + + items, err := d.repo.Claim(ctx, d.batch, d.maxAttempts, staleBefore) + if err != nil { + // Repository errors are not trusted; return stable stage-only error. + return stats, errors.New("questiontable dispatcher: claim failed") + } + + stats.Claimed = len(items) + + for _, item := range items { + // Check parent context before each item. + if err := ctx.Err(); err != nil { + return stats, fmt.Errorf("questiontable dispatcher: context cancelled during dispatch: %w", err) + } + + row := item.Row + if err := d.rewriteAnswer(ctx, &row); err != nil { + // Rewriting is best-effort: the original answer is written so the + // question-table record is never lost. Only the row is skipped when + // the parent context is cancelled. + if ctx.Err() != nil { + return stats, fmt.Errorf("questiontable dispatcher: context cancelled during rewrite: %w", ctx.Err()) + } + } + + sendCtx, cancel := context.WithTimeout(ctx, d.sendTimeout) + recordID, insertErr := d.inserter.InsertRecord(sendCtx, row) + cancel() + + if insertErr != nil { + // Mark failed with stable code only; raw error not persisted. + if markErr := d.repo.MarkFailed(ctx, item.ExportID, FailureCodeRemoteInsertFailed); markErr != nil { + // Repository errors are not trusted; return stable stage-only error. + return stats, errors.New("questiontable dispatcher: mark failed failed") + } + stats.Failed++ + continue + } + + // Mark exported with returned Notable record ID. + if markErr := d.repo.MarkExported(ctx, item.ExportID, recordID); markErr != nil { + // Repository errors are not trusted; return stable stage-only error. + return stats, errors.New("questiontable dispatcher: mark exported failed") + } + stats.Exported++ + } + + return stats, nil +} + +// rewriteAnswer transforms the outbound answer when an AnswerRewriter is +// configured. A nil rewriter or a rewriter error leaves the original answer +// intact; the row is never skipped for a rewriter error. +func (d *Dispatcher) rewriteAnswer(ctx context.Context, row *Row) error { + if d.rewriter == nil { + return nil + } + rewritten, err := d.rewriter.Rewrite(ctx, row.Answer) + if err != nil { + return err + } + if strings.TrimSpace(rewritten) != "" { + row.Answer = rewritten + } + return nil +} diff --git a/internal/questiontable/dispatcher_test.go b/internal/questiontable/dispatcher_test.go new file mode 100644 index 0000000..31174bc --- /dev/null +++ b/internal/questiontable/dispatcher_test.go @@ -0,0 +1,926 @@ +package questiontable + +import ( + "context" + "errors" + "fmt" + "strings" + "sync" + "testing" + "time" +) + +// --------------------------------------------------------------------------- +// Test doubles +// --------------------------------------------------------------------------- + +// stubRepo implements ExportRepository for tests. +type stubRepo struct { + mu sync.Mutex + + claimFn func(ctx context.Context, limit int, maxAttempts int, staleBefore time.Time) ([]PendingExport, error) + + // captured params from last Claim call. + lastClaimLimit int + lastClaimMaxAttempts int + lastClaimStaleBefore time.Time + + // exported and failed records for assertions. + exported []exportedRecord + failed []failedRecord + + // markExportedErr is returned by MarkExported when non-nil. + markExportedErr error + // markFailedErr is returned by MarkFailed when non-nil. + markFailedErr error +} + +type exportedRecord struct { + ExportID string + Location string +} + +type failedRecord struct { + ExportID string + FailureCode string +} + +func newStubRepo() *stubRepo { + return &stubRepo{} +} + +func (r *stubRepo) Claim(ctx context.Context, limit int, maxAttempts int, staleBefore time.Time) ([]PendingExport, error) { + r.mu.Lock() + r.lastClaimLimit = limit + r.lastClaimMaxAttempts = maxAttempts + r.lastClaimStaleBefore = staleBefore + r.mu.Unlock() + + if r.claimFn != nil { + return r.claimFn(ctx, limit, maxAttempts, staleBefore) + } + return nil, nil +} + +func (r *stubRepo) MarkExported(ctx context.Context, exportID, location string) error { + r.mu.Lock() + defer r.mu.Unlock() + r.exported = append(r.exported, exportedRecord{ExportID: exportID, Location: location}) + if r.markExportedErr != nil { + return r.markExportedErr + } + return nil +} + +func (r *stubRepo) MarkFailed(ctx context.Context, exportID, failureCode string) error { + r.mu.Lock() + defer r.mu.Unlock() + r.failed = append(r.failed, failedRecord{ExportID: exportID, FailureCode: failureCode}) + if r.markFailedErr != nil { + return r.markFailedErr + } + return nil +} + +// stubInserter implements RecordInserter for tests. +type stubInserter struct { + mu sync.Mutex + rows []Row + recordID string + err error + blockCh chan struct{} // if set, blocks until closed + callCount int + + // perCallErrors maps call index (1-based) to error to return. + // If an entry exists for a call index, that error is returned instead of a.err. + perCallErrors map[int]error +} + +func newStubInserter() *stubInserter { + return &stubInserter{recordID: "rec-test-001"} +} + +func (a *stubInserter) InsertRecord(ctx context.Context, row Row) (string, error) { + a.mu.Lock() + a.callCount++ + call := a.callCount + a.rows = append(a.rows, row) + blockCh := a.blockCh + a.mu.Unlock() + + if blockCh != nil { + select { + case <-ctx.Done(): + return "", ctx.Err() + case <-blockCh: + } + } + + a.mu.Lock() + defer a.mu.Unlock() + + // Check per-call error override. + if a.perCallErrors != nil { + if e, ok := a.perCallErrors[call]; ok { + return a.recordID, e + } + } + return a.recordID, a.err +} + +// --------------------------------------------------------------------------- +// Test 1: empty queue +// --------------------------------------------------------------------------- + +func TestDispatcherRunOnceEmptyQueue(t *testing.T) { + repo := newStubRepo() + inserter := newStubInserter() + + d, err := NewDispatcher(repo, inserter, nil) + if err != nil { + t.Fatalf("NewDispatcher: %v", err) + } + + stats, err := d.RunOnce(context.Background()) + if err != nil { + t.Fatalf("RunOnce: %v", err) + } + if stats.Claimed != 0 { + t.Errorf("Claimed = %d, want 0", stats.Claimed) + } + if stats.Exported != 0 { + t.Errorf("Exported = %d, want 0", stats.Exported) + } + if stats.Failed != 0 { + t.Errorf("Failed = %d, want 0", stats.Failed) + } +} + +// --------------------------------------------------------------------------- +// Test 2: success and location mark +// --------------------------------------------------------------------------- + +func TestDispatcherRunOnceSuccess(t *testing.T) { + repo := newStubRepo() + inserter := newStubInserter() + inserter.recordID = "rec-notable-abc-123" + + exportID := "exp-001" + repo.claimFn = func(ctx context.Context, limit int, maxAttempts int, staleBefore time.Time) ([]PendingExport, error) { + return []PendingExport{ + {ExportID: exportID, Row: Row{Question: "hello", Answer: "world", AskerName: "alice", AskerUnionID: "union-alice"}, Attempts: 0}, + }, nil + } + + d, err := NewDispatcher(repo, inserter, nil) + if err != nil { + t.Fatalf("NewDispatcher: %v", err) + } + + stats, err := d.RunOnce(context.Background()) + if err != nil { + t.Fatalf("RunOnce: %v", err) + } + if stats.Claimed != 1 { + t.Errorf("Claimed = %d, want 1", stats.Claimed) + } + if stats.Exported != 1 { + t.Errorf("Exported = %d, want 1", stats.Exported) + } + if stats.Failed != 0 { + t.Errorf("Failed = %d, want 0", stats.Failed) + } + + // Check location was marked with the Notable record ID. + repo.mu.Lock() + defer repo.mu.Unlock() + if len(repo.exported) != 1 { + t.Fatalf("exported records = %d, want 1", len(repo.exported)) + } + if repo.exported[0].ExportID != exportID { + t.Errorf("exported exportID = %q, want %q", repo.exported[0].ExportID, exportID) + } + if repo.exported[0].Location != "rec-notable-abc-123" { + t.Errorf("exported Location = %q, want %q", repo.exported[0].Location, "rec-notable-abc-123") + } +} + +// --------------------------------------------------------------------------- +// Test 3: insert error => stable failure code, raw error absent +// --------------------------------------------------------------------------- + +func TestDispatcherRunOnceInsertErrorStableCode(t *testing.T) { + repo := newStubRepo() + inserter := newStubInserter() + // Use an error that contains "secrets" that must not leak. + inserter.err = fmt.Errorf("network: connect to https://api.dingtalk.com?operatorId=secret-operator failed: row contains secret-data-xyz") + + exportID := "exp-002" + repo.claimFn = func(ctx context.Context, limit int, maxAttempts int, staleBefore time.Time) ([]PendingExport, error) { + return []PendingExport{ + {ExportID: exportID, Row: Row{Question: "q", Answer: "a", AskerName: "x", AskerUnionID: "union-x"}, Attempts: 0}, + }, nil + } + + d, err := NewDispatcher(repo, inserter, nil) + if err != nil { + t.Fatalf("NewDispatcher: %v", err) + } + + stats, err := d.RunOnce(context.Background()) + if err != nil { + t.Fatalf("RunOnce: %v", err) + } + if stats.Claimed != 1 { + t.Errorf("Claimed = %d, want 1", stats.Claimed) + } + if stats.Exported != 0 { + t.Errorf("Exported = %d, want 0", stats.Exported) + } + if stats.Failed != 1 { + t.Errorf("Failed = %d, want 1", stats.Failed) + } + + // Check failure code is stable, not raw error. + repo.mu.Lock() + defer repo.mu.Unlock() + if len(repo.failed) != 1 { + t.Fatalf("failed records = %d, want 1", len(repo.failed)) + } + if repo.failed[0].ExportID != exportID { + t.Errorf("failed exportID = %q, want %q", repo.failed[0].ExportID, exportID) + } + if repo.failed[0].FailureCode != FailureCodeRemoteInsertFailed { + t.Errorf("failure code = %q, want %q", repo.failed[0].FailureCode, FailureCodeRemoteInsertFailed) + } + + // The raw error with secrets must not appear in stats or returned values. + // (Already verified: stats don't leak error strings.) +} + +// --------------------------------------------------------------------------- +// Test 4: blocking inserter respects per-item timeout +// --------------------------------------------------------------------------- + +func TestDispatcherRunOncePerItemTimeout(t *testing.T) { + repo := newStubRepo() + inserter := newStubInserter() + inserter.blockCh = make(chan struct{}) // never unblocks + + exportID := "exp-timeout" + repo.claimFn = func(ctx context.Context, limit int, maxAttempts int, staleBefore time.Time) ([]PendingExport, error) { + return []PendingExport{ + {ExportID: exportID, Row: Row{Question: "q", Answer: "a", AskerName: "x", AskerUnionID: "union-x"}, Attempts: 0}, + }, nil + } + + opts := &DispatcherOptions{SendTimeout: 50 * time.Millisecond} + d, err := NewDispatcher(repo, inserter, opts) + if err != nil { + t.Fatalf("NewDispatcher: %v", err) + } + + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + + stats, err := d.RunOnce(ctx) + if err != nil { + t.Fatalf("RunOnce: %v", err) + } + + if stats.Failed != 1 { + t.Errorf("Failed = %d, want 1 (timeout should cause mark failed)", stats.Failed) + } + if stats.Exported != 0 { + t.Errorf("Exported = %d, want 0", stats.Exported) + } + + // Verify failure code is stable. + repo.mu.Lock() + defer repo.mu.Unlock() + if len(repo.failed) != 1 { + t.Fatalf("failed records = %d, want 1", len(repo.failed)) + } + if repo.failed[0].FailureCode != FailureCodeRemoteInsertFailed { + t.Errorf("failure code = %q, want %q", repo.failed[0].FailureCode, FailureCodeRemoteInsertFailed) + } +} + +// --------------------------------------------------------------------------- +// Test 5: claim receives batch/max/stale time near expected +// --------------------------------------------------------------------------- + +func TestDispatcherRunOnceClaimParams(t *testing.T) { + repo := newStubRepo() + inserter := newStubInserter() + + opts := &DispatcherOptions{ + Batch: 7, + MaxAttempts: 3, + ClaimLease: 2 * time.Minute, + SendTimeout: 5 * time.Second, + } + d, err := NewDispatcher(repo, inserter, opts) + if err != nil { + t.Fatalf("NewDispatcher: %v", err) + } + + before := time.Now() + _, err = d.RunOnce(context.Background()) + if err != nil { + t.Fatalf("RunOnce: %v", err) + } + after := time.Now() + + repo.mu.Lock() + limit := repo.lastClaimLimit + maxAtt := repo.lastClaimMaxAttempts + staleBefore := repo.lastClaimStaleBefore + repo.mu.Unlock() + + if limit != 7 { + t.Errorf("claim limit = %d, want 7", limit) + } + if maxAtt != 3 { + t.Errorf("claim maxAttempts = %d, want 3", maxAtt) + } + + // staleBefore should be approximately now - 2m. + expectedStale := before.Add(-2 * time.Minute) + // Allow some tolerance. + if staleBefore.Before(expectedStale.Add(-2*time.Second)) || staleBefore.After(after.Add(-2*time.Minute).Add(2*time.Second)) { + t.Errorf("staleBefore = %v, expected near %v (before=%v, after=%v)", staleBefore, expectedStale, before, after) + } +} + +// --------------------------------------------------------------------------- +// Test 6: parent cancellation before claim and between items +// --------------------------------------------------------------------------- + +func TestDispatcherRunOnceParentCancelledBeforeClaim(t *testing.T) { + repo := newStubRepo() + inserter := newStubInserter() + + d, err := NewDispatcher(repo, inserter, nil) + if err != nil { + t.Fatalf("NewDispatcher: %v", err) + } + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + _, err = d.RunOnce(ctx) + if err == nil { + t.Fatal("expected error for cancelled context") + } + if !strings.Contains(err.Error(), "context invalid") { + t.Errorf("error = %v, want 'context invalid'", err) + } +} + +func TestDispatcherRunOnceParentCancelledBetweenItems(t *testing.T) { + repo := newStubRepo() + inserter := newStubInserter() + inserter.recordID = "rec-1" + + ctx, cancel := context.WithCancel(context.Background()) + + repo.claimFn = func(ctx context.Context, limit int, maxAttempts int, staleBefore time.Time) ([]PendingExport, error) { + return []PendingExport{ + {ExportID: "exp-1", Row: Row{Question: "q1", Answer: "a1", AskerName: "x", AskerUnionID: "union-x"}, Attempts: 0}, + {ExportID: "exp-2", Row: Row{Question: "q2", Answer: "a2", AskerName: "y", AskerUnionID: "union-y"}, Attempts: 0}, + }, nil + } + + // Wrap inserter to cancel parent context after the first InsertRecord call. + cancellingInserter := &cancellingInserter{ + inner: inserter, + cancel: cancel, + } + + d, err := NewDispatcher(repo, cancellingInserter, nil) + if err != nil { + t.Fatalf("NewDispatcher: %v", err) + } + + stats, err := d.RunOnce(ctx) + if err == nil { + t.Fatal("expected error for cancelled context between items") + } + if !strings.Contains(err.Error(), "context cancelled during dispatch") { + t.Errorf("error = %v, want 'context cancelled during dispatch'", err) + } + // First item should have been exported before cancellation. + if stats.Exported != 1 { + t.Errorf("Exported = %d, want 1", stats.Exported) + } +} + +// cancellingInserter wraps a RecordInserter and cancels a context after the first call. +type cancellingInserter struct { + inner RecordInserter + cancel context.CancelFunc + mu sync.Mutex + calls int +} + +func (a *cancellingInserter) InsertRecord(ctx context.Context, row Row) (string, error) { + a.mu.Lock() + a.calls++ + calls := a.calls + a.mu.Unlock() + + result, err := a.inner.InsertRecord(ctx, row) + + if calls == 1 { + a.cancel() + } + return result, err +} + +// --------------------------------------------------------------------------- +// Test 7: claim/mark errors and stats semantics +// --------------------------------------------------------------------------- + +func TestDispatcherRunOnceClaimError(t *testing.T) { + repo := newStubRepo() + inserter := newStubInserter() + + claimErr := errors.New("database connection refused") + repo.claimFn = func(ctx context.Context, limit int, maxAttempts int, staleBefore time.Time) ([]PendingExport, error) { + return nil, claimErr + } + + d, err := NewDispatcher(repo, inserter, nil) + if err != nil { + t.Fatalf("NewDispatcher: %v", err) + } + + stats, err := d.RunOnce(context.Background()) + if err == nil { + t.Fatal("expected error for claim failure") + } + if !strings.Contains(err.Error(), "claim failed") { + t.Errorf("error = %v, want 'claim failed' stage wrapper", err) + } + if stats.Claimed != 0 { + t.Errorf("Claimed = %d, want 0 on claim error", stats.Claimed) + } +} + +func TestDispatcherRunOnceMarkExportedError(t *testing.T) { + repo := newStubRepo() + inserter := newStubInserter() + inserter.recordID = "rec-mark-err" + + repo.markExportedErr = errors.New("mark exported db error") + + exportID := "exp-mark-err" + repo.claimFn = func(ctx context.Context, limit int, maxAttempts int, staleBefore time.Time) ([]PendingExport, error) { + return []PendingExport{ + {ExportID: exportID, Row: Row{Question: "q", Answer: "a", AskerName: "x", AskerUnionID: "union-x"}, Attempts: 0}, + }, nil + } + + d, err := NewDispatcher(repo, inserter, nil) + if err != nil { + t.Fatalf("NewDispatcher: %v", err) + } + + stats, err := d.RunOnce(context.Background()) + if err == nil { + t.Fatal("expected error for mark exported failure") + } + if !strings.Contains(err.Error(), "mark exported failed") { + t.Errorf("error = %v, want 'mark exported failed' stage wrapper", err) + } + // Stats should reflect the insert succeeded before mark failed. + if stats.Exported != 0 { + t.Errorf("Exported = %d, want 0 (mark failed before increment)", stats.Exported) + } +} + +func TestDispatcherRunOnceStatsSemantics(t *testing.T) { + repo := newStubRepo() + inserter := newStubInserter() + inserter.recordID = "rec-ok" + + // 2 success, 1 failure. + inserter.perCallErrors = map[int]error{ + 2: errors.New("network error"), + } + + repo.claimFn = func(ctx context.Context, limit int, maxAttempts int, staleBefore time.Time) ([]PendingExport, error) { + return []PendingExport{ + {ExportID: "exp-ok1", Row: Row{Question: "q1", Answer: "a1", AskerName: "x", AskerUnionID: "union-x"}, Attempts: 0}, + {ExportID: "exp-fail", Row: Row{Question: "q2", Answer: "a2", AskerName: "y", AskerUnionID: "union-y"}, Attempts: 0}, + {ExportID: "exp-ok2", Row: Row{Question: "q3", Answer: "a3", AskerName: "z", AskerUnionID: "union-z"}, Attempts: 0}, + }, nil + } + + d, err := NewDispatcher(repo, inserter, nil) + if err != nil { + t.Fatalf("NewDispatcher: %v", err) + } + + stats, err := d.RunOnce(context.Background()) + if err != nil { + t.Fatalf("RunOnce: %v", err) + } + if stats.Claimed != 3 { + t.Errorf("Claimed = %d, want 3", stats.Claimed) + } + if stats.Exported != 2 { + t.Errorf("Exported = %d, want 2", stats.Exported) + } + if stats.Failed != 1 { + t.Errorf("Failed = %d, want 1", stats.Failed) + } +} + +// --------------------------------------------------------------------------- +// Test 8: constructor invalid bounds, nil, typed-nil +// --------------------------------------------------------------------------- + +func TestNewDispatcherNilDeps(t *testing.T) { + inserter := newStubInserter() + + _, err := NewDispatcher(nil, inserter, nil) + if err == nil { + t.Fatal("expected error for nil repo") + } + if !strings.Contains(err.Error(), "repo is nil") { + t.Errorf("error = %v, want 'repo is nil'", err) + } + + repo := newStubRepo() + _, err = NewDispatcher(repo, nil, nil) + if err == nil { + t.Fatal("expected error for nil inserter") + } + if !strings.Contains(err.Error(), "inserter is nil") { + t.Errorf("error = %v, want 'inserter is nil'", err) + } +} + +func TestNewDispatcherTypedNil(t *testing.T) { + // Typed nil: interface value is non-nil but underlying concrete is nil. + var typedNilRepo *stubRepo = nil + var repo ExportRepository = typedNilRepo + + inserter := newStubInserter() + _, err := NewDispatcher(repo, inserter, nil) + if err == nil { + t.Fatal("expected error for typed-nil repo") + } + if !strings.Contains(err.Error(), "repo is nil") { + t.Errorf("error = %v, want 'repo is nil'", err) + } + + repo2 := newStubRepo() + var typedNilInserter *stubInserter = nil + var inserter2 RecordInserter = typedNilInserter + + _, err = NewDispatcher(repo2, inserter2, nil) + if err == nil { + t.Fatal("expected error for typed-nil inserter") + } + if !strings.Contains(err.Error(), "inserter is nil") { + t.Errorf("error = %v, want 'inserter is nil'", err) + } +} + +func TestNewDispatcherInvalidBounds(t *testing.T) { + repo := newStubRepo() + inserter := newStubInserter() + + tests := []struct { + name string + opts DispatcherOptions + want string + }{ + {"negative batch", DispatcherOptions{Batch: -1}, "batch must be >= 0"}, + {"negative maxAttempts", DispatcherOptions{MaxAttempts: -1}, "maxAttempts must be >= 0"}, + {"negative claimLease", DispatcherOptions{ClaimLease: -1 * time.Second}, "claimLease must be >= 0"}, + {"negative sendTimeout", DispatcherOptions{SendTimeout: -1 * time.Second}, "sendTimeout must be >= 0"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + _, err := NewDispatcher(repo, inserter, &tt.opts) + if err == nil { + t.Fatal("expected error") + } + if !strings.Contains(err.Error(), tt.want) { + t.Errorf("error = %v, want containing %q", err, tt.want) + } + }) + } +} + +func TestNewDispatcherDefaults(t *testing.T) { + repo := newStubRepo() + inserter := newStubInserter() + + d, err := NewDispatcher(repo, inserter, nil) + if err != nil { + t.Fatalf("NewDispatcher: %v", err) + } + if d.batch != 10 { + t.Errorf("batch = %d, want 10", d.batch) + } + if d.maxAttempts != 5 { + t.Errorf("maxAttempts = %d, want 5", d.maxAttempts) + } + if d.claimLease != 5*time.Minute { + t.Errorf("claimLease = %v, want 5m", d.claimLease) + } + if d.sendTimeout != 10*time.Second { + t.Errorf("sendTimeout = %v, want 10s", d.sendTimeout) + } +} + +func TestNewDispatcherZeroBatch(t *testing.T) { + // Zero batch is allowed (validates as >= 0, but not > 0 so use default). + repo := newStubRepo() + inserter := newStubInserter() + + opts := &DispatcherOptions{Batch: 0} + d, err := NewDispatcher(repo, inserter, opts) + if err != nil { + t.Fatalf("NewDispatcher with batch=0: %v", err) + } + if d.batch != 10 { + t.Errorf("batch = %d, want 10 (default when opts.Batch=0)", d.batch) + } +} + +// --------------------------------------------------------------------------- +// Test 9: exact Row passed to inserter +// --------------------------------------------------------------------------- + +func TestDispatcherRunOnceExactRowPassed(t *testing.T) { + repo := newStubRepo() + inserter := newStubInserter() + + row := Row{ + Question: "怎么修?", + Answer: "按步骤操作", + AskedTime: time.Date(2025, 6, 15, 14, 30, 0, 0, time.FixedZone("CST", 8*60*60)), + AskerName: "张三", + AskerUnionID: "union-zhang-san", + TriggerPerson: "李四", + Department: "研发部", + Region: "华东", + } + + exportID := "exp-cells" + repo.claimFn = func(ctx context.Context, limit int, maxAttempts int, staleBefore time.Time) ([]PendingExport, error) { + return []PendingExport{ + {ExportID: exportID, Row: row, Attempts: 0}, + }, nil + } + + d, err := NewDispatcher(repo, inserter, nil) + if err != nil { + t.Fatalf("NewDispatcher: %v", err) + } + + _, err = d.RunOnce(context.Background()) + if err != nil { + t.Fatalf("RunOnce: %v", err) + } + + inserter.mu.Lock() + defer inserter.mu.Unlock() + if len(inserter.rows) != 1 { + t.Fatalf("inserter received %d rows, want 1", len(inserter.rows)) + } + + got := inserter.rows[0] + + if got.Question != row.Question { + t.Errorf("Question = %q, want %q", got.Question, row.Question) + } + if got.Answer != row.Answer { + t.Errorf("Answer = %q, want %q", got.Answer, row.Answer) + } + if !got.AskedTime.Equal(row.AskedTime) { + t.Errorf("AskedTime = %v, want %v", got.AskedTime, row.AskedTime) + } + if got.AskerName != row.AskerName { + t.Errorf("AskerName = %q, want %q", got.AskerName, row.AskerName) + } + if got.AskerUnionID != row.AskerUnionID { + t.Errorf("AskerUnionID = %q, want %q", got.AskerUnionID, row.AskerUnionID) + } + if got.TriggerPerson != row.TriggerPerson { + t.Errorf("TriggerPerson = %q, want %q", got.TriggerPerson, row.TriggerPerson) + } + if got.Department != row.Department { + t.Errorf("Department = %q, want %q", got.Department, row.Department) + } + if got.Region != row.Region { + t.Errorf("Region = %q, want %q", got.Region, row.Region) + } +} + +// --------------------------------------------------------------------------- +// Additional: RunOnce returns error when sendCtx expires but parent OK +// --------------------------------------------------------------------------- + +func TestDispatcherRunOnceSendTimeoutDoesNotKillParent(t *testing.T) { + repo := newStubRepo() + inserter := newStubInserter() + inserter.blockCh = make(chan struct{}) // never unblocks + + exportID := "exp-timeout2" + repo.claimFn = func(ctx context.Context, limit int, maxAttempts int, staleBefore time.Time) ([]PendingExport, error) { + return []PendingExport{ + {ExportID: exportID, Row: Row{Question: "q", Answer: "a", AskerName: "x", AskerUnionID: "union-x"}, Attempts: 0}, + }, nil + } + + opts := &DispatcherOptions{SendTimeout: 20 * time.Millisecond} + d, err := NewDispatcher(repo, inserter, opts) + if err != nil { + t.Fatalf("NewDispatcher: %v", err) + } + + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + + stats, err := d.RunOnce(ctx) + if err != nil { + t.Fatalf("RunOnce should not fail on per-item timeout: %v", err) + } + if stats.Failed != 1 { + t.Errorf("Failed = %d, want 1", stats.Failed) + } + + // Parent context should still be alive. + if ctx.Err() != nil { + t.Errorf("parent context should still be alive, got %v", ctx.Err()) + } +} + +// --------------------------------------------------------------------------- +// Additional: RecordInserter interface satisfaction check +// --------------------------------------------------------------------------- + +func TestClientSatisfiesRecordInserter(t *testing.T) { + // Compile-time check: *Client implements RecordInserter. + var _ RecordInserter = (*Client)(nil) +} + +// --------------------------------------------------------------------------- +// Error leakage: repository errors must not leak secrets +// --------------------------------------------------------------------------- + +func TestDispatcherRunOnceClaimErrorNoLeak(t *testing.T) { + repo := newStubRepo() + inserter := newStubInserter() + + // Claim error containing SQL/turn/export/person secrets. + repo.claimFn = func(ctx context.Context, limit int, maxAttempts int, staleBefore time.Time) ([]PendingExport, error) { + return nil, fmt.Errorf("SQLSTATE 42P01: relation \"turn_export_person\" does not exist") + } + + d, err := NewDispatcher(repo, inserter, nil) + if err != nil { + t.Fatalf("NewDispatcher: %v", err) + } + + _, err = d.RunOnce(context.Background()) + if err == nil { + t.Fatal("expected error for claim failure") + } + + errStr := err.Error() + secrets := []string{"SQLSTATE", "42P01", "turn_export_person", "relation"} + for _, s := range secrets { + if strings.Contains(errStr, s) { + t.Errorf("error leaks secret %q: %v", s, errStr) + } + } +} + +func TestDispatcherRunOnceMarkFailedNoLeak(t *testing.T) { + repo := newStubRepo() + inserter := newStubInserter() + inserter.err = errors.New("some insert error") + + repo.markFailedErr = fmt.Errorf("SQLSTATE 23505: duplicate key in export_person_report") + + exportID := "exp-leak-mf" + repo.claimFn = func(ctx context.Context, limit int, maxAttempts int, staleBefore time.Time) ([]PendingExport, error) { + return []PendingExport{ + {ExportID: exportID, Row: Row{Question: "q", Answer: "a", AskerName: "x", AskerUnionID: "union-x"}, Attempts: 0}, + }, nil + } + + d, err := NewDispatcher(repo, inserter, nil) + if err != nil { + t.Fatalf("NewDispatcher: %v", err) + } + + _, err = d.RunOnce(context.Background()) + if err == nil { + t.Fatal("expected error for mark failed failure") + } + + errStr := err.Error() + secrets := []string{"SQLSTATE", "23505", "export_person_report", "duplicate"} + for _, s := range secrets { + if strings.Contains(errStr, s) { + t.Errorf("error leaks secret %q: %v", s, errStr) + } + } +} + +func TestDispatcherRunOnceMarkExportedNoLeak(t *testing.T) { + repo := newStubRepo() + inserter := newStubInserter() + inserter.recordID = "rec-leak" + + repo.markExportedErr = fmt.Errorf("SQLSTATE 08006: connection lost for turn_export_write") + + exportID := "exp-leak-me" + repo.claimFn = func(ctx context.Context, limit int, maxAttempts int, staleBefore time.Time) ([]PendingExport, error) { + return []PendingExport{ + {ExportID: exportID, Row: Row{Question: "q", Answer: "a", AskerName: "x", AskerUnionID: "union-x"}, Attempts: 0}, + }, nil + } + + d, err := NewDispatcher(repo, inserter, nil) + if err != nil { + t.Fatalf("NewDispatcher: %v", err) + } + + _, err = d.RunOnce(context.Background()) + if err == nil { + t.Fatal("expected error for mark exported failure") + } + + errStr := err.Error() + secrets := []string{"SQLSTATE", "08006", "turn_export_write", "connection"} + for _, s := range secrets { + if strings.Contains(errStr, s) { + t.Errorf("error leaks secret %q: %v", s, errStr) + } + } +} + +// --------------------------------------------------------------------------- +// Value-type constructor: non-pointer implementations should not panic +// --------------------------------------------------------------------------- + +// valueRepo is a non-pointer ExportRepository implementation. +type valueRepo struct{} + +func (v valueRepo) Claim(ctx context.Context, limit int, maxAttempts int, staleBefore time.Time) ([]PendingExport, error) { + return nil, nil +} +func (v valueRepo) MarkExported(ctx context.Context, exportID, location string) error { return nil } +func (v valueRepo) MarkFailed(ctx context.Context, exportID, failureCode string) error { return nil } + +// valueInserter is a non-pointer RecordInserter implementation. +type valueInserter struct{} + +func (v valueInserter) InsertRecord(ctx context.Context, row Row) (string, error) { + return "rec-value-001", nil +} + +func TestNewDispatcherValueTypeRepo(t *testing.T) { + // value-type repo should not panic (was: reflect.ValueOf(x).IsNil() on non-nilable kind). + var repo ExportRepository = valueRepo{} + inserter := newStubInserter() + + d, err := NewDispatcher(repo, inserter, nil) + if err != nil { + t.Fatalf("NewDispatcher with value-type repo: %v", err) + } + _ = d +} + +func TestNewDispatcherValueTypeInserter(t *testing.T) { + repo := newStubRepo() + var inserter RecordInserter = valueInserter{} + + d, err := NewDispatcher(repo, inserter, nil) + if err != nil { + t.Fatalf("NewDispatcher with value-type inserter: %v", err) + } + _ = d +} + +func TestNewDispatcherValueTypeBoth(t *testing.T) { + var repo ExportRepository = valueRepo{} + var inserter RecordInserter = valueInserter{} + + d, err := NewDispatcher(repo, inserter, nil) + if err != nil { + t.Fatalf("NewDispatcher with value-type both: %v", err) + } + _ = d +} diff --git a/internal/questiontable/export_rewrite_test.go b/internal/questiontable/export_rewrite_test.go new file mode 100644 index 0000000..16a25d0 --- /dev/null +++ b/internal/questiontable/export_rewrite_test.go @@ -0,0 +1,137 @@ +package questiontable + +import ( + "context" + "strings" + "testing" + "time" +) + +type answerRewriterStub struct { + rewritten string + err error +} + +func (s answerRewriterStub) Rewrite(ctx context.Context, content string) (string, error) { + return s.rewritten, s.err +} + +func TestRunOnceRewritesAnswerBeforeInsert(t *testing.T) { + repo := newStubRepo() + inserter := newStubInserter() + inserter.recordID = "rec-rewrite-1" + repo.claimFn = func(ctx context.Context, limit int, maxAttempts int, staleBefore time.Time) ([]PendingExport, error) { + return []PendingExport{ + { + ExportID: "exp-rewrite", + Row: Row{ + Question: "机械臂如何学习使用呢", + Answer: "原始答案含[[3](#_Toc1)]和![图](resource://abc)", + + AskedTime: time.Now(), + AskerName: "张三", + AskerUnionID: "union-z", + TriggerPerson: "张三", + Department: "研发部", + Region: "华东", + QuestionImageURLs: []string{"https://weknora-api.example/i/001"}, + }, + Attempts: 0, + }, + }, nil + } + rw := answerRewriterStub{rewritten: "转换后答案[3]", err: nil} + d, err := NewDispatcher(repo, inserter, &DispatcherOptions{Rewriter: rw}) + if err != nil { + t.Fatalf("NewDispatcher: %v", err) + } + + stats, err := d.RunOnce(context.Background()) + if err != nil { + t.Fatalf("RunOnce: %v", err) + } + if stats.Claimed != 1 || stats.Exported != 1 || stats.Failed != 0 { + t.Fatalf("stats=%+v", stats) + } + if len(inserter.rows) != 1 { + t.Fatalf("rows=%d, want 1", len(inserter.rows)) + } + row := inserter.rows[0] + if row.Answer != "转换后答案[3]" { + t.Fatalf("Answer=%q, want rewritten", row.Answer) + } +} + +func TestRunOnceRewriterErrorFallsBackToOriginalAnswer(t *testing.T) { + repo := newStubRepo() + inserter := newStubInserter() + inserter.recordID = "rec-fallback-1" + repo.claimFn = func(ctx context.Context, limit int, maxAttempts int, staleBefore time.Time) ([]PendingExport, error) { + return []PendingExport{ + { + ExportID: "exp-fallback", + Row: Row{ + Question: "问题", + Answer: "原始答案", + AskedTime: time.Now(), + }, + Attempts: 0, + }, + }, nil + } + rw := answerRewriterStub{rewritten: "", err: context.DeadlineExceeded} + d, err := NewDispatcher(repo, inserter, &DispatcherOptions{Rewriter: rw}) + if err != nil { + t.Fatalf("NewDispatcher: %v", err) + } + + stats, err := d.RunOnce(context.Background()) + if err != nil { + t.Fatalf("RunOnce: %v", err) + } + if stats.Failed != 0 || stats.Exported != 1 { + t.Fatalf("stats=%+v", stats) + } + if len(inserter.rows) != 1 || inserter.rows[0].Answer != "原始答案" { + t.Fatalf("rows=%+v, want fallback original answer", inserter.rows) + } +} + +func TestRowToFieldsIncludesQuestionImageURLsAndImageMarker(t *testing.T) { + r := Row{ + Question: "请描述并分析这张图片。", + Answer: "回答了。", + AskedTime: time.Now(), + AskerName: "张三", + AskerUnionID: "union-z", + TriggerPerson: "张三", + Department: "研发部", + Region: "华东", + QuestionImageURLs: []string{ + "https://weknora-api.example/i/001", + "https://weknora-api.example/i/002", + }, + } + + fields := r.ToFields() + + original, ok := fields[FieldOriginalQuestion].(string) + if !ok { + t.Fatalf("OriginalQuestion type=%T", fields[FieldOriginalQuestion]) + } + if !strings.HasPrefix(original, "[图片]") { + t.Fatalf("OriginalQuestion=%q, want [图片] prefix", original) + } + // Image URLs must be rendered as markdown image syntax so the Notable cell + // previews them (same as the answer column), not as a plain-text link. + if !strings.Contains(original, "![图片1](https://weknora-api.example/i/001)") || + !strings.Contains(original, "![图片2](https://weknora-api.example/i/002)") { + t.Fatalf("OriginalQuestion=%q, missing markdown image syntax", original) + } + + // Without image URLs, no [图片] prefix. + plain := Row{Question: "普通问题", AskedTime: time.Now()} + if got := plain.ToFields()[FieldOriginalQuestion]; got != "普通问题" { + t.Fatalf("plain OriginalQuestion=%q, want unchanged", got) + } +} diff --git a/internal/questiontable/remap_test.go b/internal/questiontable/remap_test.go new file mode 100644 index 0000000..8d1ea81 --- /dev/null +++ b/internal/questiontable/remap_test.go @@ -0,0 +1,14 @@ +package questiontable + +import "testing" + +func TestRemapFieldsUsesValidatedLogicalMapping(t *testing.T) { + client := &Client{fieldMapping: map[string]string{"answer": "new-answer", "original_question": "new-question"}} + got := client.remapFields(map[string]interface{}{FieldAnswer: "A", FieldOriginalQuestion: "Q"}) + if got["new-answer"] != "A" || got["new-question"] != "Q" { + t.Fatalf("got=%#v", got) + } + if _, ok := got[FieldAnswer]; ok { + t.Fatal("legacy field id must not remain when mapping exists") + } +} diff --git a/internal/questiontable/row.go b/internal/questiontable/row.go new file mode 100644 index 0000000..87fdddf --- /dev/null +++ b/internal/questiontable/row.go @@ -0,0 +1,163 @@ +package questiontable + +import ( + "strconv" + "strings" + "time" + "unicode" + "unicode/utf8" +) + +// Field IDs for the DingTalk Notable v1 question table. +// Verified against the live Notable v1 base. +const ( + FieldChineseQuestion = "ZaMZF6j" // text + FieldAskedTime = "SCug9My" // date (Unix milliseconds) + FieldAsker = "S2XA1uZ" // user (array of {name, unionId}) + FieldOriginalQuestion = "bETcL3r" // text + FieldAnswer = "Y4cpmxU" // text + FieldTriggerPerson = "JgY2f1z" // text + FieldLanguage = "DNIV3mQ" // text + FieldDepartment = "eBc6a6b" // text + FieldRegion = "fPNLeVW" // text +) + +// Row holds the data needed to produce a Notable v1 typed record. +type Row struct { + Question string + Answer string + AskedTime time.Time + AskerName string + AskerUnionID string + TriggerPerson string + Department string + Region string + QuestionImageURLs []string +} + +// ToFields returns a typed field-ID → value map suitable for the Notable v1 +// InsertRecord request body. The caller is responsible for the semantics of +// each field; this method only handles mapping, language detection, time +// formatting, and formula-injection sanitisation. +// The five v1 select fields (QMn9UoU, H3gtTuv, nFvv8OR, UMqUPAG, lnF7gF9) +// are omitted entirely. +func (r Row) ToFields() map[string]interface{} { + fields := make(map[string]interface{}) + + lang := detectLanguage(r.Question) + + // ChineseQuestion: only when Han present. + if lang == "中文" { + fields[FieldChineseQuestion] = sanitise(r.Question) + } + + // Answer. + fields[FieldAnswer] = sanitise(r.Answer) + + // AskedTime: Unix milliseconds if non-zero; omit if zero. + if !r.AskedTime.IsZero() { + fields[FieldAskedTime] = r.AskedTime.UnixMilli() + } + + // Asker: user object only when AskerUnionID is non-blank. + if strings.TrimSpace(r.AskerUnionID) != "" { + fields[FieldAsker] = []interface{}{ + map[string]interface{}{ + "name": strings.TrimSpace(r.AskerName), + "unionId": strings.TrimSpace(r.AskerUnionID), + }, + } + } + + // OriginalQuestion: include image marker and stable URLs for image turns. + fields[FieldOriginalQuestion] = sanitise(questionWithImageURLs(r.Question, r.QuestionImageURLs)) + + // Language. + fields[FieldLanguage] = sanitise(lang) + + // TriggerPerson: fallback to AskerName. + triggerPerson := r.TriggerPerson + if triggerPerson == "" { + triggerPerson = r.AskerName + } + fields[FieldTriggerPerson] = sanitise(triggerPerson) + + // Department. + fields[FieldDepartment] = sanitise(r.Department) + + // Region. + fields[FieldRegion] = sanitise(r.Region) + + return fields +} + +// detectLanguage returns "中文" when s contains any Han character, +// "英文" when it contains Latin letters but no Han, +// and "其他" otherwise. +func detectLanguage(s string) string { + hasHan := false + hasLatin := false + for _, r := range s { + if isHan(r) { + hasHan = true + } + if isLatin(r) { + hasLatin = true + } + } + if hasHan { + return "中文" + } + if hasLatin { + return "英文" + } + return "其他" +} + +func isHan(r rune) bool { + return unicode.Is(unicode.Han, r) +} + +func isLatin(r rune) bool { + return unicode.Is(unicode.Latin, r) +} + +// sanitise protects against spreadsheet formula injection. If the string +// begins with =, +, -, or @, a single apostrophe is prefixed. The string +// is otherwise returned unchanged. +func sanitise(s string) string { + if s == "" { + return s + } + r, _ := utf8.DecodeRuneInString(s) + switch r { + case '=', '+', '-', '@': + return "'" + s + } + return s +} + +// questionWithImageURLs prefixes an image marker and renders the stable image +// URLs as markdown image syntax when the turn carried image input. Markdown +// image syntax lets the Notable cell preview the image (same as the answer +// column); a plain-text URL would render as an unpreviewable link. +func questionWithImageURLs(question string, imageURLs []string) string { + if len(imageURLs) == 0 { + return question + } + var builder strings.Builder + builder.WriteString("[图片] ") + builder.WriteString(strings.TrimSpace(question)) + for index, imageURL := range imageURLs { + imageURL = strings.TrimSpace(imageURL) + if imageURL == "" { + continue + } + builder.WriteString("\n![图片") + builder.WriteString(strconv.Itoa(index + 1)) + builder.WriteString("](") + builder.WriteString(imageURL) + builder.WriteString(")") + } + return builder.String() +} diff --git a/internal/questiontable/row_test.go b/internal/questiontable/row_test.go new file mode 100644 index 0000000..4452218 --- /dev/null +++ b/internal/questiontable/row_test.go @@ -0,0 +1,356 @@ +package questiontable + +import ( + "testing" + "time" +) + +func TestRowToFieldsExactMapping(t *testing.T) { + shanghai, _ := time.LoadLocation("Asia/Shanghai") + asked := time.Date(2025, 6, 15, 14, 30, 0, 0, shanghai) + + r := Row{ + Question: "这个怎么修?", + Answer: "请按以下步骤操作。", + AskedTime: asked, + AskerName: "张三", + AskerUnionID: "union-zhang-san", + TriggerPerson: "李四", + Department: "研发部", + Region: "华东", + } + + fields := r.ToFields() + + // ChineseQuestion (only when Han present). + if fields[FieldChineseQuestion] != "这个怎么修?" { + t.Errorf("ChineseQuestion = %q, want %q", fields[FieldChineseQuestion], "这个怎么修?") + } + + // Answer. + if fields[FieldAnswer] != "请按以下步骤操作。" { + t.Errorf("Answer = %q, want %q", fields[FieldAnswer], "请按以下步骤操作。") + } + + // AskedTime: Unix milliseconds. + expectedMS := asked.UnixMilli() + if fields[FieldAskedTime] != expectedMS { + t.Errorf("AskedTime = %v (%T), want %v (int64)", fields[FieldAskedTime], fields[FieldAskedTime], expectedMS) + } + + // Asker: user array. + userArr, ok := fields[FieldAsker].([]interface{}) + if !ok { + t.Fatalf("Asker not a []interface{}, got %T", fields[FieldAsker]) + } + if len(userArr) != 1 { + t.Fatalf("Asker len = %d, want 1", len(userArr)) + } + userObj, ok := userArr[0].(map[string]interface{}) + if !ok { + t.Fatalf("Asker[0] not a map[string]interface{}, got %T", userArr[0]) + } + if userObj["name"] != "张三" { + t.Errorf("Asker name = %q, want %q", userObj["name"], "张三") + } + if userObj["unionId"] != "union-zhang-san" { + t.Errorf("Asker unionId = %q, want %q", userObj["unionId"], "union-zhang-san") + } + + // OriginalQuestion. + if fields[FieldOriginalQuestion] != "这个怎么修?" { + t.Errorf("OriginalQuestion = %q, want %q", fields[FieldOriginalQuestion], "这个怎么修?") + } + + // Language. + if fields[FieldLanguage] != "中文" { + t.Errorf("Language = %q, want %q", fields[FieldLanguage], "中文") + } + + // TriggerPerson. + if fields[FieldTriggerPerson] != "李四" { + t.Errorf("TriggerPerson = %q, want %q", fields[FieldTriggerPerson], "李四") + } + + // Department. + if fields[FieldDepartment] != "研发部" { + t.Errorf("Department = %q, want %q", fields[FieldDepartment], "研发部") + } + + // Region. + if fields[FieldRegion] != "华东" { + t.Errorf("Region = %q, want %q", fields[FieldRegion], "华东") + } + + // Omitted: the five select fields must not be present. + omitted := []string{"QMn9UoU", "H3gtTuv", "nFvv8OR", "UMqUPAG", "lnF7gF9"} + for _, fid := range omitted { + if _, exists := fields[fid]; exists { + t.Errorf("select field %q should be omitted but is present", fid) + } + } +} + +func TestRowToFieldsDateZeroOmission(t *testing.T) { + r := Row{ + Question: "test", + Answer: "answer", + AskerName: "user", + AskerUnionID: "union-1", + // AskedTime is zero. + } + fields := r.ToFields() + if _, exists := fields[FieldAskedTime]; exists { + t.Error("AskedTime field should be omitted when zero") + } +} + +func TestRowToFieldsDateInt64UnixMilli(t *testing.T) { + shanghai, _ := time.LoadLocation("Asia/Shanghai") + asked := time.Date(2026, 1, 2, 3, 4, 5, 0, shanghai) + + r := Row{ + Question: "test", + Answer: "answer", + AskedTime: asked, + AskerName: "user", + AskerUnionID: "union-1", + } + fields := r.ToFields() + got, ok := fields[FieldAskedTime].(int64) + if !ok { + t.Fatalf("AskedTime is %T, want int64", fields[FieldAskedTime]) + } + if got != asked.UnixMilli() { + t.Errorf("AskedTime = %d, want %d", got, asked.UnixMilli()) + } +} + +func TestRowToFieldsUserShape(t *testing.T) { + // With union ID: user array present. + r := Row{ + Question: "test", + Answer: "answer", + AskerName: " 张三 ", + AskerUnionID: " union-123 ", + } + fields := r.ToFields() + userArr, ok := fields[FieldAsker].([]interface{}) + if !ok { + t.Fatalf("Asker not present or wrong type: %T", fields[FieldAsker]) + } + userObj := userArr[0].(map[string]interface{}) + if userObj["name"] != "张三" { + t.Errorf("name = %q, want %q (trimmed)", userObj["name"], "张三") + } + if userObj["unionId"] != "union-123" { + t.Errorf("unionId = %q, want %q (trimmed)", userObj["unionId"], "union-123") + } + + // Without union ID: Asker field omitted. + r2 := Row{ + Question: "test", + Answer: "answer", + AskerName: "张三", + AskerUnionID: "", + } + fields2 := r2.ToFields() + if _, exists := fields2[FieldAsker]; exists { + t.Error("Asker field should be omitted when union ID is blank") + } + + // Whitespace-only union ID: omitted. + r3 := Row{ + Question: "test", + Answer: "answer", + AskerName: "张三", + AskerUnionID: " ", + } + fields3 := r3.ToFields() + if _, exists := fields3[FieldAsker]; exists { + t.Error("Asker field should be omitted when union ID is whitespace-only") + } +} + +func TestRowToFieldsChineseQuestionPolicy(t *testing.T) { + // English question: ChineseQuestion omitted. + r := Row{ + Question: "How to fix this?", + Answer: "Follow these steps.", + AskerName: "Alice", + AskerUnionID: "union-alice", + } + fields := r.ToFields() + if _, exists := fields[FieldChineseQuestion]; exists { + t.Error("ChineseQuestion should be omitted for English question") + } + if fields[FieldLanguage] != "英文" { + t.Errorf("Language = %q, want 英文", fields[FieldLanguage]) + } + + // Chinese question: ChineseQuestion contains the question. + r2 := Row{ + Question: "怎么解决?", + Answer: "按步骤操作。", + AskerName: "Bob", + AskerUnionID: "union-bob", + } + fields2 := r2.ToFields() + if fields2[FieldChineseQuestion] != "怎么解决?" { + t.Errorf("ChineseQuestion = %q, want %q", fields2[FieldChineseQuestion], "怎么解决?") + } + if fields2[FieldLanguage] != "中文" { + t.Errorf("Language = %q, want 中文", fields2[FieldLanguage]) + } +} + +func TestDetectLanguage(t *testing.T) { + tests := []struct { + input string + want string + }{ + {"你好", "中文"}, + {"Hello", "英文"}, + {"Hello世界", "中文"}, // Han takes priority + {"12345", "其他"}, + {"", "其他"}, + {"こんにちは", "其他"}, // Japanese kana + {"Привет", "其他"}, // Cyrillic + {"Español", "英文"}, // accented Latin via unicode.Latin + {"café", "英文"}, // accented Latin + {"Déjà vu", "英文"}, // accented Latin + } + for _, tt := range tests { + got := detectLanguage(tt.input) + if got != tt.want { + t.Errorf("detectLanguage(%q) = %q, want %q", tt.input, got, tt.want) + } + } +} + +func TestSanitiseFormulaInjection(t *testing.T) { + tests := []struct { + input string + want string + }{ + {"=SUM(A1:A10)", "'=SUM(A1:A10)"}, + {"+A1", "'+A1"}, + {"-A1", "'-A1"}, + {"@SUM", "'@SUM"}, + {"normal text", "normal text"}, + {"=", "'="}, // = is the first rune, prefixed to '=' + {"", ""}, + {" leading space", " leading space"}, + {"1=2", "1=2"}, // doesn't start with a formula char + } + for _, tt := range tests { + got := sanitise(tt.input) + if got != tt.want { + t.Errorf("sanitise(%q) = %q, want %q", tt.input, got, tt.want) + } + } +} + +func TestSanitiseDoesNotMutateNonFormula(t *testing.T) { + inputs := []string{"hello", "世界", "123", "=SUM(", " a", "a=", "null"} + for _, in := range inputs { + got := sanitise(in) + // Only "=SUM(" should be prefixed. + switch in { + case "=SUM(": + if got != "'=SUM(" { + t.Errorf("sanitise(%q) = %q, want '=SUM(", in, got) + } + default: + if got != in { + t.Errorf("sanitise(%q) = %q, want %q (no change)", in, got, in) + } + } + } +} + +func TestTriggerPersonFallback(t *testing.T) { + // When TriggerPerson is empty, fall back to AskerName. + r := Row{ + Question: "test", + Answer: "answer", + AskerName: "张三", + AskerUnionID: "union-1", + TriggerPerson: "", + } + fields := r.ToFields() + if fields[FieldTriggerPerson] != "张三" { + t.Errorf("TriggerPerson = %q, want %q (fallback to asker)", fields[FieldTriggerPerson], "张三") + } + + // When TriggerPerson is set, use it. + r2 := Row{ + Question: "test", + Answer: "answer", + AskerName: "张三", + AskerUnionID: "union-1", + TriggerPerson: "nickname", + } + fields2 := r2.ToFields() + if fields2[FieldTriggerPerson] != "nickname" { + t.Errorf("TriggerPerson = %q, want %q (use trigger)", fields2[FieldTriggerPerson], "nickname") + } +} + +func TestFormulaInjectionOnAllColumns(t *testing.T) { + shanghai, _ := time.LoadLocation("Asia/Shanghai") + asked := time.Date(2025, 1, 1, 0, 0, 0, 0, shanghai) + + // Use a question that starts with formula char AND contains Han so + // the Chinese-question field is populated. + r := Row{ + Question: "=修复()", + Answer: "+cmd", + AskedTime: asked, + AskerName: "-张三", + AskerUnionID: "union-sanitise", + TriggerPerson: "@trigger", + Department: "=DEPT", + Region: "normal", + } + fields := r.ToFields() + + // Chinese question: "=修复()" has Han, so it's Chinese and gets sanitised. + if fields[FieldChineseQuestion] != "'=修复()" { + t.Errorf("ChineseQuestion = %q, want %q", fields[FieldChineseQuestion], "'=修复()") + } + // Answer: "+cmd" → "'+cmd" + if fields[FieldAnswer] != "'+cmd" { + t.Errorf("Answer = %q, want %q", fields[FieldAnswer], "'+cmd") + } + // OriginalQuestion: "=修复()" → "'=修复()" + if fields[FieldOriginalQuestion] != "'=修复()" { + t.Errorf("OriginalQuestion = %q, want %q", fields[FieldOriginalQuestion], "'=修复()") + } + // TriggerPerson: "@trigger" → "'@trigger" + if fields[FieldTriggerPerson] != "'@trigger" { + t.Errorf("TriggerPerson = %q, want %q", fields[FieldTriggerPerson], "'@trigger") + } + // Department: "=DEPT" → "'=DEPT" + if fields[FieldDepartment] != "'=DEPT" { + t.Errorf("Department = %q, want %q", fields[FieldDepartment], "'=DEPT") + } + // Region: "normal" → no change + if fields[FieldRegion] != "normal" { + t.Errorf("Region = %q, want %q", fields[FieldRegion], "normal") + } + // Asker name: "-张三" → "'-张三" (via user object) + userArr := fields[FieldAsker].([]interface{}) + userObj := userArr[0].(map[string]interface{}) + // Asker name is NOT sanitised per the contract (only text fields are sanitised), + // but the name is trimmed. Let's verify — the task says trim only union ID/name, + // preserve question/answer text. So name is sanitised via TrimSpace, not sanitise(). + // Actually, sanitise is only applied to the text fields. Asker name goes through + // strings.TrimSpace but not sanitise. Let's check the behavior. + // The task says: "Trim only union ID/name for the user object if existing + // conventions require; preserve question/answer text." So name is trimmed, not + // sanitised. We should verify the trimmed name. + if userObj["name"] != "-张三" { + t.Errorf("Asker name = %q, want %q", userObj["name"], "-张三") + } +} diff --git a/internal/questiontable/schema.go b/internal/questiontable/schema.go new file mode 100644 index 0000000..e213cbb --- /dev/null +++ b/internal/questiontable/schema.go @@ -0,0 +1,108 @@ +package questiontable + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "strings" +) + +type Field struct { + ID string `json:"id"` + Name string `json:"name"` + Type string `json:"type"` +} + +type RequiredField struct { + Logical string + Name string + Type string +} + +func QuestionSchema() []RequiredField { + return []RequiredField{ + {"chinese_question", "中文问题", "text"}, + {"asked_time", "提问时间", "date"}, + {"asker", "提问人", "user"}, + {"original_question", "原始问题", "text"}, + {"answer", "AI答案", "text"}, + {"trigger_person", "流程触发人员信息", "text"}, + {"language", "语言", "text"}, + {"department", "部门", "text"}, + {"region", "区域", "text"}, + } +} + +func FAQSchema() []RequiredField { + return []RequiredField{ + {"standard_question", "标准问题(必填)", "text"}, + {"original_question", "原始问题", "text"}, + {"language", "语言", "text"}, + {"asker", "提问人", "user"}, + } +} + +func MapRequiredFields(fields []Field, required []RequiredField) (map[string]string, error) { + out := make(map[string]string, len(required)) + for _, want := range required { + nameMatches := make([]Field, 0, 1) + for _, got := range fields { + if strings.TrimSpace(got.Name) == want.Name { + nameMatches = append(nameMatches, got) + } + } + if len(nameMatches) == 0 { + return nil, errors.New("missing_field") + } + if len(nameMatches) > 1 { + return nil, errors.New("duplicate_field") + } + if strings.TrimSpace(nameMatches[0].Type) != want.Type { + return nil, errors.New("field_type_mismatch") + } + if strings.TrimSpace(nameMatches[0].ID) == "" { + return nil, errors.New("missing_field_id") + } + out[want.Logical] = strings.TrimSpace(nameMatches[0].ID) + } + return out, nil +} + +func (c *Client) ReadFields(ctx context.Context) ([]Field, error) { + token, err := c.getAccessToken(ctx) + if err != nil { + return nil, errors.New("schema_token_failed") + } + endpoint := fmt.Sprintf("%s/v1.0/notable/bases/%s/sheets/%s/fields?operatorId=%s", c.baseURL, url.PathEscape(c.baseID), url.PathEscape(c.sheetID), url.QueryEscape(c.operatorID)) + req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil) + if err != nil { + return nil, errors.New("schema_request_failed") + } + req.Header.Set("x-acs-dingtalk-access-token", token) + resp, err := c.http.Do(req) + if err != nil { + return nil, errors.New("schema_network_failed") + } + defer resp.Body.Close() + raw, err := io.ReadAll(io.LimitReader(resp.Body, 256<<10)) + if err != nil { + return nil, errors.New("schema_read_failed") + } + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + return nil, fmt.Errorf("schema_http_%d", resp.StatusCode) + } + var payload struct { + Value []Field `json:"value"` + } + if json.Unmarshal(raw, &payload) != nil { + return nil, errors.New("schema_decode_failed") + } + if len(payload.Value) == 0 { + return nil, errors.New("schema_empty") + } + return payload.Value, nil +} diff --git a/internal/questiontable/schema_test.go b/internal/questiontable/schema_test.go new file mode 100644 index 0000000..cf47f2e --- /dev/null +++ b/internal/questiontable/schema_test.go @@ -0,0 +1,77 @@ +package questiontable + +import ( + "context" + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +func TestReadFieldsUsesOperatorAndMapsQuestionSchema(t *testing.T) { + mux := http.NewServeMux() + mux.HandleFunc("/token", func(w http.ResponseWriter, _ *http.Request) { + _, _ = w.Write([]byte(`{"accessToken":"token","expireIn":7200}`)) + }) + mux.HandleFunc("/v1.0/notable/bases/base/sheets/sheet/fields", func(w http.ResponseWriter, r *http.Request) { + if r.URL.Query().Get("operatorId") != "union" { + t.Fatalf("operator=%q", r.URL.Query().Get("operatorId")) + } + _, _ = w.Write([]byte(`{"value":[ + {"id":"q","name":"中文问题","type":"text"},{"id":"time","name":"提问时间","type":"date"}, + {"id":"asker","name":"提问人","type":"user"},{"id":"orig","name":"原始问题","type":"text"}, + {"id":"answer","name":"AI答案","type":"text"},{"id":"trigger","name":"流程触发人员信息","type":"text"}, + {"id":"lang","name":"语言","type":"text"},{"id":"dept","name":"部门","type":"text"},{"id":"region","name":"区域","type":"text"}]}`)) + }) + server := httptest.NewServer(mux) + defer server.Close() + client, err := NewClient(Config{ClientID: "id", Secret: "secret", BaseID: "base", SheetID: "sheet", OperatorID: "union", TokenURL: server.URL + "/token", BaseURL: server.URL}, server.Client()) + if err != nil { + t.Fatal(err) + } + fields, err := client.ReadFields(context.Background()) + if err != nil { + t.Fatal(err) + } + mapping, err := MapRequiredFields(fields, QuestionSchema()) + if err != nil { + t.Fatal(err) + } + if mapping["answer"] != "answer" || len(mapping) != 9 { + t.Fatalf("mapping=%v", mapping) + } +} + +func TestMapRequiredFieldsRejectsMissingDuplicateAndWrongType(t *testing.T) { + required := []RequiredField{{Logical: "question", Name: "问题", Type: "text"}} + cases := []struct { + name string + fields []Field + code string + }{ + {"missing", nil, "missing_field"}, + {"duplicate", []Field{{ID: "1", Name: "问题", Type: "text"}, {ID: "2", Name: "问题", Type: "text"}}, "duplicate_field"}, + {"wrong type", []Field{{ID: "1", Name: "问题", Type: "user"}}, "field_type_mismatch"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + _, err := MapRequiredFields(tc.fields, required) + if err == nil || !strings.Contains(err.Error(), tc.code) { + t.Fatalf("err=%v", err) + } + }) + } +} + +func TestFAQSchemaUsesFourCurrentInsertFields(t *testing.T) { + required := FAQSchema() + if len(required) != 4 { + t.Fatalf("len=%d", len(required)) + } + want := map[string]string{"standard_question": "text", "original_question": "text", "language": "text", "asker": "user"} + for _, field := range required { + if want[field.Logical] != field.Type { + t.Fatalf("field=%+v", field) + } + } +} diff --git a/internal/reasoningmode/display.go b/internal/reasoningmode/display.go new file mode 100644 index 0000000..3973749 --- /dev/null +++ b/internal/reasoningmode/display.go @@ -0,0 +1,80 @@ +package reasoningmode + +import ( + "fmt" + "strings" + "unicode" +) + +func ResolveGuideLocale(locale, query string) string { + locale = strings.TrimSpace(locale) + if locale != "" && locale != "auto" { + return locale + } + hasLatin := false + for _, value := range query { + if unicode.In(value, unicode.Han, unicode.Hiragana, unicode.Katakana, unicode.Hangul) { + return "zh-CN" + } + if unicode.In(value, unicode.Latin) { + hasLatin = true + } + } + if hasLatin { + return "en" + } + return "zh-CN" +} + +func DecorateAnswer(answer string, execution ExecutionMode, expired bool, completion Completion) string { + return DecorateAnswerForLocale(answer, execution, expired, completion, "zh-CN") +} + +func DecorateAnswerForLocale(answer string, execution ExecutionMode, expired bool, completion Completion, locale string) string { + content := strings.TrimSpace(answer) + prefixes := make([]string, 0, 2) + if expired { + prefixes = append(prefixes, "💡 智能推理模式已因10分钟无操作自动关闭,当前已切回【快速问答模式】。") + } + if execution == ExecutionReasoning || execution == ExecutionReasoningSingle { + prefixes = append(prefixes, "【智能推理模式】") + } + if len(prefixes) > 0 { + content = strings.Join(prefixes, "\n\n") + "\n\n" + content + } + + suffixes := make([]string, 0, 3) + if completion.ShowHint { + suffixes = append(suffixes, "💡 推理模式还剩2轮,到期将自动关闭,如需继续可发送 /think on 重置轮次") + } + if completion.AutoClosed { + suffixes = append(suffixes, fmt.Sprintf( + "💡 持续推理模式已满%d轮,已自动切回【快速问答模式】\n如需继续深度推理,可再次发送 /think on 开启", + completion.RoundNumber, + )) + } + if completion.ShowOnboarding { + suffixes = append(suffixes, firstUseGuide(locale)) + } + if len(suffixes) > 0 { + content += "\n\n" + strings.Join(suffixes, "\n\n") + } + return content +} + +func firstUseGuide(locale string) string { + if strings.EqualFold(strings.TrimSpace(locale), "en") { + return "💡 First-time Guide\n" + + "✅ Default: Fast Q&A Mode — knowledge-based, fast and cost-effective\n" + + "🔹 For deep reasoning & analysis:\n" + + "Continuous use: /think on to enable, auto-off after 10 rounds\n" + + "Single use: /think + your question, auto switch back after reply\n" + + "💬 /help for all commands · /setting for language & preferences" + } + return "💡 首次使用指南\n" + + "✅ 当前默认使用快速问答模式,基于知识库快速作答,成本更低\n" + + "🔹 需深度推理分析时:\n" + + "连续使用:发送 /think on 开启持续模式,10轮对话后自动关闭\n" + + "单次使用:发送 /think + 你的问题,用完自动切回省钱模式\n" + + "💬 /help 查看全部指令・/setting 配置语言与偏好" +} diff --git a/internal/reasoningmode/display_test.go b/internal/reasoningmode/display_test.go new file mode 100644 index 0000000..7e28c58 --- /dev/null +++ b/internal/reasoningmode/display_test.go @@ -0,0 +1,50 @@ +package reasoningmode + +import ( + "strings" + "testing" +) + +func TestDecorateAnswerMarksReasoningAndRemainingRounds(t *testing.T) { + answer := DecorateAnswer("分析结果", ExecutionReasoning, false, Completion{RoundNumber: 8, ShowHint: true}) + if !strings.HasPrefix(answer, "【智能推理模式】\n\n分析结果") { + t.Fatalf("answer=%q", answer) + } + if !strings.Contains(answer, "推理模式还剩2轮") || !strings.Contains(answer, "/think on") { + t.Fatalf("answer=%q", answer) + } +} + +func TestDecorateAnswerMarksSingleReasoningWithoutRoundHint(t *testing.T) { + answer := DecorateAnswer("单次结果", ExecutionReasoningSingle, false, Completion{}) + if answer != "【智能推理模式】\n\n单次结果" { + t.Fatalf("answer=%q", answer) + } +} + +func TestDecorateAnswerAppendsAutomaticClose(t *testing.T) { + answer := DecorateAnswer("最终结果", ExecutionReasoning, false, Completion{RoundNumber: 10, AutoClosed: true}) + if !strings.Contains(answer, "持续推理模式已满10轮") || !strings.Contains(answer, "已自动切回【快速问答模式】") { + t.Fatalf("answer=%q", answer) + } +} + +func TestDecorateAnswerExplainsIdleExpiryOnNextQuickAnswer(t *testing.T) { + answer := DecorateAnswer("快速结果", ExecutionQuick, true, Completion{}) + if !strings.HasPrefix(answer, "💡 智能推理模式已因10分钟无操作自动关闭") || !strings.HasSuffix(answer, "快速结果") { + t.Fatalf("answer=%q", answer) + } +} + +func TestDecorateAnswerAppendsFirstUseGuideOnce(t *testing.T) { + answer := DecorateAnswer("快速结果", ExecutionQuick, false, Completion{ShowOnboarding: true}) + for _, required := range []string{"首次使用指南", "默认使用快速问答模式", "/think on", "/think + 你的问题", "/help", "/setting"} { + if !strings.Contains(answer, required) { + t.Fatalf("answer=%q missing %q", answer, required) + } + } + without := DecorateAnswer("快速结果", ExecutionQuick, false, Completion{}) + if strings.Contains(without, "首次使用指南") { + t.Fatalf("onboarding repeated: %q", without) + } +} diff --git a/internal/reasoningmode/locale_test.go b/internal/reasoningmode/locale_test.go new file mode 100644 index 0000000..b774f7c --- /dev/null +++ b/internal/reasoningmode/locale_test.go @@ -0,0 +1,15 @@ +package reasoningmode + +import "testing" + +func TestResolveGuideLocaleUsesQuestionWhenPreferenceIsAuto(t *testing.T) { + if got := ResolveGuideLocale("auto", "How do I configure CRA?"); got != "en" { + t.Fatalf("English auto locale=%q", got) + } + if got := ResolveGuideLocale("auto", "如何配置CRA?"); got != "zh-CN" { + t.Fatalf("Chinese auto locale=%q", got) + } + if got := ResolveGuideLocale("ja", "English text"); got != "ja" { + t.Fatalf("explicit locale changed to %q", got) + } +} diff --git a/internal/reasoningmode/parser.go b/internal/reasoningmode/parser.go new file mode 100644 index 0000000..5519c41 --- /dev/null +++ b/internal/reasoningmode/parser.go @@ -0,0 +1,75 @@ +package reasoningmode + +import "strings" + +type CommandKind string + +const ( + CommandEnable CommandKind = "enable" + CommandDisable CommandKind = "disable" + CommandSingle CommandKind = "single" + CommandHelp CommandKind = "help" + CommandInvalid CommandKind = "invalid" +) + +type Command struct { + Kind CommandKind + Query string +} + +func ParseCommand(raw string) (Command, bool) { + value := strings.TrimSpace(raw) + fields := strings.Fields(value) + if len(fields) == 0 { + return Command{}, false + } + + name := strings.ToLower(fields[0]) + switch name { + case "/help", "/帮助", "/h": + if len(fields) != 1 { + return Command{Kind: CommandInvalid}, true + } + return Command{Kind: CommandHelp}, true + case "/开启推理": + if len(fields) != 1 { + return Command{Kind: CommandInvalid}, true + } + return Command{Kind: CommandEnable}, true + case "/关闭推理", "/rag": + if len(fields) != 1 { + return Command{Kind: CommandInvalid}, true + } + return Command{Kind: CommandDisable}, true + case "/think": + default: + return Command{}, false + } + + if len(fields) == 1 { + return Command{Kind: CommandEnable}, true + } + + second := strings.ToLower(fields[1]) + switch second { + case "on", "start": + if len(fields) != 2 { + return Command{Kind: CommandInvalid}, true + } + return Command{Kind: CommandEnable}, true + case "off", "end": + if len(fields) != 2 { + return Command{Kind: CommandInvalid}, true + } + return Command{Kind: CommandDisable}, true + default: + query := strings.TrimSpace(value[len(fields[0]):]) + if second == "+" { + query = strings.TrimSpace(strings.TrimPrefix(query, "+")) + } + if query == "" { + return Command{Kind: CommandInvalid}, true + } + return Command{Kind: CommandSingle, Query: query}, true + } +} diff --git a/internal/reasoningmode/parser_test.go b/internal/reasoningmode/parser_test.go new file mode 100644 index 0000000..734bac7 --- /dev/null +++ b/internal/reasoningmode/parser_test.go @@ -0,0 +1,100 @@ +package reasoningmode + +import "testing" + +func TestParseCommandRecognizesPersistentEnableAliases(t *testing.T) { + tests := []string{ + "/think", + "/think on", + "/think start", + "/THINK ON", + "/开启推理", + } + for _, input := range tests { + t.Run(input, func(t *testing.T) { + command, ok := ParseCommand(input) + if !ok || command.Kind != CommandEnable || command.Query != "" { + t.Fatalf("ParseCommand(%q)=(%+v,%t), want enable", input, command, ok) + } + }) + } +} + +func TestParseCommandRecognizesDisableAliases(t *testing.T) { + tests := []string{ + "/think off", + "/think end", + "/THINK OFF", + "/关闭推理", + "/rag", + } + for _, input := range tests { + t.Run(input, func(t *testing.T) { + command, ok := ParseCommand(input) + if !ok || command.Kind != CommandDisable || command.Query != "" { + t.Fatalf("ParseCommand(%q)=(%+v,%t), want disable", input, command, ok) + } + }) + } +} + +func TestParseCommandRecognizesSingleTurnReasoning(t *testing.T) { + command, ok := ParseCommand(" /think 对比 CRA 和 CR 系列 ") + if !ok || command.Kind != CommandSingle || command.Query != "对比 CRA 和 CR 系列" { + t.Fatalf("command=%+v ok=%t", command, ok) + } +} + +func TestParseCommandAcceptsDocumentedOptionalPlusSeparator(t *testing.T) { + command, ok := ParseCommand("/think + 分析根因") + if !ok || command.Kind != CommandSingle || command.Query != "分析根因" { + t.Fatalf("command=%+v ok=%t", command, ok) + } +} + +func TestParseCommandRecognizesHelpAliases(t *testing.T) { + for _, input := range []string{"/help", "/帮助", "/h", "/H"} { + t.Run(input, func(t *testing.T) { + command, ok := ParseCommand(input) + if !ok || command.Kind != CommandHelp { + t.Fatalf("ParseCommand(%q)=(%+v,%t), want help", input, command, ok) + } + }) + } +} + +func TestParseCommandRejectsEmbeddedOrSimilarInputs(t *testing.T) { + tests := []string{ + "普通问题", + "abc /think on", + "/thinking", + "//think on", + } + for _, input := range tests { + t.Run(input, func(t *testing.T) { + if command, ok := ParseCommand(input); ok { + t.Fatalf("ParseCommand(%q)=(%+v,true), want no command", input, command) + } + }) + } +} + +func TestParseCommandInterceptsMalformedControlArguments(t *testing.T) { + tests := []string{ + "/think on 多余内容", + "/think off 多余内容", + "/think start 多余内容", + "/think end 多余内容", + "/rag 多余内容", + "/开启推理 多余内容", + "/关闭推理 多余内容", + } + for _, input := range tests { + t.Run(input, func(t *testing.T) { + command, ok := ParseCommand(input) + if !ok || command.Kind != CommandInvalid { + t.Fatalf("ParseCommand(%q)=(%+v,%t), want invalid command", input, command, ok) + } + }) + } +} diff --git a/internal/reasoningmode/service.go b/internal/reasoningmode/service.go new file mode 100644 index 0000000..d4bb9ac --- /dev/null +++ b/internal/reasoningmode/service.go @@ -0,0 +1,154 @@ +package reasoningmode + +import ( + "context" + "errors" + "fmt" + "strings" + "time" +) + +const defaultIdleTimeout = 10 * time.Minute + +type Scope struct { + TenantKey string + Channel string + ExternalActorID string +} + +type TurnCompletion struct { + Scope Scope + TurnID string + Execution ExecutionMode + Answer string + Locale string + Expired bool + At time.Time + Idle time.Duration +} + +type Repository interface { + ResolveState(context.Context, Scope, time.Time) (State, bool, error) + Enable(context.Context, Scope, time.Time, time.Duration) (State, error) + Disable(context.Context, Scope, time.Time) (State, bool, error) + SetMaxRounds(context.Context, Scope, int, time.Time) (State, error) + SetHintEnabled(context.Context, Scope, bool, time.Time) (State, error) + CompleteTurn(context.Context, TurnCompletion) (Completion, error) +} + +type Decision struct { + Handled bool + Reply string + Query string + AgentID string + Execution ExecutionMode + Expired bool +} + +type Service struct { + repo Repository + quickAgentID string + reasoningAgentID string + now func() time.Time + idleTimeout time.Duration +} + +func NewService(repo Repository, quickAgentID, reasoningAgentID string) (*Service, error) { + quickAgentID = strings.TrimSpace(quickAgentID) + reasoningAgentID = strings.TrimSpace(reasoningAgentID) + if repo == nil { + return nil, errors.New("reasoning mode repository is required") + } + if quickAgentID == "" || reasoningAgentID == "" { + return nil, errors.New("quick and reasoning agent IDs are required") + } + if quickAgentID == reasoningAgentID { + return nil, errors.New("quick and reasoning agent IDs must differ") + } + return &Service{ + repo: repo, + quickAgentID: quickAgentID, + reasoningAgentID: reasoningAgentID, + now: time.Now, + idleTimeout: defaultIdleTimeout, + }, nil +} + +func (s *Service) Prepare(ctx context.Context, scope Scope, text string) (Decision, error) { + if err := validateScope(scope); err != nil { + return Decision{}, err + } + query := strings.TrimSpace(text) + if query == "" { + return Decision{}, errors.New("reasoning mode query is required") + } + + if command, ok := ParseCommand(query); ok { + switch command.Kind { + case CommandEnable: + state, err := s.repo.Enable(ctx, scope, s.now(), s.idleTimeout) + if err != nil { + return Decision{}, err + } + return Decision{Handled: true, Reply: fmt.Sprintf( + "✅ 已开启【智能推理模式】(计费标准更高)\n持续模式将在%d轮对话后自动关闭,也可随时输入 /think off 手动关闭", + state.MaxRounds, + )}, nil + case CommandDisable: + _, wasReasoning, err := s.repo.Disable(ctx, scope, s.now()) + if err != nil { + return Decision{}, err + } + if !wasReasoning { + return Decision{Handled: true, Reply: "当前未开启推理模式,默认是快速问答模式。"}, nil + } + return Decision{Handled: true, Reply: "✅ 已关闭智能推理模式,切回【快速问答模式】"}, nil + case CommandSingle: + return Decision{Query: command.Query, AgentID: s.reasoningAgentID, Execution: ExecutionReasoningSingle}, nil + case CommandHelp: + return Decision{Handled: true, Reply: helpReply()}, nil + default: + return Decision{Handled: true, Reply: "用法:/think <问题>、/think on、/think off。"}, nil + } + } + + state, expired, err := s.repo.ResolveState(ctx, scope, s.now()) + if err != nil { + return Decision{}, err + } + if state.Mode == ModeReasoning { + return Decision{Query: query, AgentID: s.reasoningAgentID, Execution: ExecutionReasoning}, nil + } + return Decision{Query: query, AgentID: s.quickAgentID, Execution: ExecutionQuick, Expired: expired}, nil +} + +func helpReply() string { + return "一、模式说明\n" + + "默认模式:快速问答模式,基于知识库快速准确作答,响应快、成本低,适合信息查询和事实确认。\n" + + "智能推理模式:支持多步思考与工具调用,计费标准更高,适合复杂分析和推导。\n\n" + + "二、模式切换指令\n" + + "/think + 你的问题:仅当前问题使用智能推理\n" + + "/think on:开启持续智能推理模式\n" + + "/think off 或 /rag:关闭并切回快速问答模式\n\n" + + "三、其他常用指令\n" + + "/help:查看本帮助说明\n" + + "/setting 或 /设置:配置语言、自动关闭轮数和提示开关\n\n" + + "只有行首以 / 开头的完整指令会被识别。持续推理模式会在剩余2轮时提醒,到期自动切回快速问答模式。" +} + +func (s *Service) Complete(ctx context.Context, input TurnCompletion) (Completion, error) { + if input.At.IsZero() { + input.At = s.now() + } + if input.Idle <= 0 { + input.Idle = s.idleTimeout + } + return s.repo.CompleteTurn(ctx, input) +} + +func validateScope(scope Scope) error { + if strings.TrimSpace(scope.TenantKey) == "" || strings.TrimSpace(scope.Channel) == "" || strings.TrimSpace(scope.ExternalActorID) == "" { + return errors.New("tenant, channel and external actor are required") + } + return nil +} diff --git a/internal/reasoningmode/service_test.go b/internal/reasoningmode/service_test.go new file mode 100644 index 0000000..7d42ed4 --- /dev/null +++ b/internal/reasoningmode/service_test.go @@ -0,0 +1,179 @@ +package reasoningmode + +import ( + "context" + "strings" + "testing" + "time" +) + +type fakeRepository struct { + state State + expired bool + enableCalls int + disableCalls int + completeCalls int + lastCompletion TurnCompletion +} + +func (f *fakeRepository) ResolveState(context.Context, Scope, time.Time) (State, bool, error) { + return f.state, f.expired, nil +} + +func (f *fakeRepository) Enable(context.Context, Scope, time.Time, time.Duration) (State, error) { + f.enableCalls++ + f.state.Mode = ModeReasoning + f.state.RoundsUsed = 0 + return f.state, nil +} + +func (f *fakeRepository) Disable(context.Context, Scope, time.Time) (State, bool, error) { + f.disableCalls++ + wasReasoning := f.state.Mode == ModeReasoning + f.state.Mode = ModeQuick + f.state.RoundsUsed = 0 + return f.state, wasReasoning, nil +} + +func (f *fakeRepository) SetMaxRounds(context.Context, Scope, int, time.Time) (State, error) { + return f.state, nil +} + +func (f *fakeRepository) SetHintEnabled(context.Context, Scope, bool, time.Time) (State, error) { + return f.state, nil +} + +func (f *fakeRepository) CompleteTurn(_ context.Context, input TurnCompletion) (Completion, error) { + f.completeCalls++ + f.lastCompletion = input + return Completion{Next: f.state}, nil +} + +func newTestService(t *testing.T, repo Repository) *Service { + t.Helper() + service, err := NewService(repo, "builtin-quick-answer", "builtin-smart-reasoning") + if err != nil { + t.Fatal(err) + } + service.now = func() time.Time { return time.Date(2026, 9, 9, 12, 0, 0, 0, time.UTC) } + return service +} + +func testScope() Scope { + return Scope{TenantKey: "tenant", Channel: "dingtalk", ExternalActorID: "staff-1"} +} + +func TestPrepareEnablesPersistentReasoningLocally(t *testing.T) { + repo := &fakeRepository{state: DefaultState()} + decision, err := newTestService(t, repo).Prepare(context.Background(), testScope(), "/think on") + if err != nil { + t.Fatal(err) + } + if !decision.Handled || decision.Query != "" || repo.enableCalls != 1 { + t.Fatalf("decision=%+v enableCalls=%d", decision, repo.enableCalls) + } + for _, want := range []string{"已开启【智能推理模式】", "计费标准更高", "10轮", "/think off"} { + if !strings.Contains(decision.Reply, want) { + t.Fatalf("reply=%q missing %q", decision.Reply, want) + } + } +} + +func TestPrepareDisablesPersistentReasoningLocally(t *testing.T) { + repo := &fakeRepository{state: State{Mode: ModeReasoning, MaxRounds: 10, HintEnabled: true}} + decision, err := newTestService(t, repo).Prepare(context.Background(), testScope(), "/rag") + if err != nil { + t.Fatal(err) + } + if !decision.Handled || repo.disableCalls != 1 || !strings.Contains(decision.Reply, "已关闭智能推理模式") { + t.Fatalf("decision=%+v disableCalls=%d", decision, repo.disableCalls) + } +} + +func TestPrepareFriendlyReplyWhenReasoningAlreadyOff(t *testing.T) { + repo := &fakeRepository{state: DefaultState()} + decision, err := newTestService(t, repo).Prepare(context.Background(), testScope(), "/think off") + if err != nil { + t.Fatal(err) + } + if !decision.Handled || !strings.Contains(decision.Reply, "当前未开启推理模式") { + t.Fatalf("decision=%+v", decision) + } +} + +func TestPrepareSingleReasoningDoesNotMutatePersistentState(t *testing.T) { + repo := &fakeRepository{state: DefaultState()} + decision, err := newTestService(t, repo).Prepare(context.Background(), testScope(), "/think 分析根因") + if err != nil { + t.Fatal(err) + } + if decision.Handled || decision.Query != "分析根因" || decision.AgentID != "builtin-smart-reasoning" || decision.Execution != ExecutionReasoningSingle { + t.Fatalf("decision=%+v", decision) + } + if repo.enableCalls != 0 || repo.disableCalls != 0 { + t.Fatalf("unexpected state mutation: %+v", repo) + } +} + +func TestPrepareRoutesPersistentAndQuickQuestions(t *testing.T) { + tests := []struct { + name string + state State + agentID string + execution ExecutionMode + }{ + {name: "quick", state: DefaultState(), agentID: "builtin-quick-answer", execution: ExecutionQuick}, + {name: "reasoning", state: State{Mode: ModeReasoning, MaxRounds: 10, HintEnabled: true}, agentID: "builtin-smart-reasoning", execution: ExecutionReasoning}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + decision, err := newTestService(t, &fakeRepository{state: test.state}).Prepare(context.Background(), testScope(), "普通问题") + if err != nil { + t.Fatal(err) + } + if decision.Handled || decision.Query != "普通问题" || decision.AgentID != test.agentID || decision.Execution != test.execution { + t.Fatalf("decision=%+v", decision) + } + }) + } +} + +func TestPrepareRoutesExpiredReasoningToQuickWithNotice(t *testing.T) { + repo := &fakeRepository{state: DefaultState(), expired: true} + decision, err := newTestService(t, repo).Prepare(context.Background(), testScope(), "继续") + if err != nil { + t.Fatal(err) + } + if decision.AgentID != "builtin-quick-answer" || decision.Execution != ExecutionQuick || !decision.Expired { + t.Fatalf("decision=%+v", decision) + } +} + +func TestPrepareInterceptsInvalidThinkCommand(t *testing.T) { + decision, err := newTestService(t, &fakeRepository{state: DefaultState()}).Prepare(context.Background(), testScope(), "/think on 多余内容") + if err != nil { + t.Fatal(err) + } + if !decision.Handled || !strings.Contains(decision.Reply, "用法") { + t.Fatalf("decision=%+v", decision) + } +} + +func TestPrepareReturnsLocalHelpWithoutStateMutation(t *testing.T) { + repo := &fakeRepository{state: DefaultState()} + decision, err := newTestService(t, repo).Prepare(context.Background(), testScope(), "/help") + if err != nil { + t.Fatal(err) + } + if !decision.Handled { + t.Fatalf("decision=%+v", decision) + } + for _, required := range []string{"快速问答模式", "智能推理模式", "/think + 你的问题", "/think on", "/think off", "/setting"} { + if !strings.Contains(decision.Reply, required) { + t.Fatalf("help=%q missing %q", decision.Reply, required) + } + } + if repo.enableCalls != 0 || repo.disableCalls != 0 { + t.Fatalf("help mutated mode: %+v", repo) + } +} diff --git a/internal/reasoningmode/state.go b/internal/reasoningmode/state.go new file mode 100644 index 0000000..2acbaef --- /dev/null +++ b/internal/reasoningmode/state.go @@ -0,0 +1,105 @@ +package reasoningmode + +import ( + "errors" + "time" +) + +type Mode string + +type ExecutionMode string + +const ( + ModeQuick Mode = "quick" + ModeReasoning Mode = "reasoning" + + ExecutionQuick ExecutionMode = "quick" + ExecutionReasoning ExecutionMode = "reasoning" + ExecutionReasoningSingle ExecutionMode = "reasoning_single" +) + +var ErrInvalidState = errors.New("invalid reasoning mode state") + +type State struct { + Mode Mode + MaxRounds int + RoundsUsed int + HintEnabled bool + LastActivityAt time.Time + ExpiresAt time.Time + OnboardingShown bool + OnboardingShownAt time.Time +} + +type Completion struct { + Next State + RoundNumber int + ShowHint bool + AutoClosed bool + ShowOnboarding bool +} + +func DefaultState() State { + return State{Mode: ModeQuick, MaxRounds: 10, HintEnabled: true} +} + +func EffectiveState(state State, now time.Time) (State, bool) { + if state.Mode != ModeReasoning || state.ExpiresAt.IsZero() || state.ExpiresAt.After(now) { + return state, false + } + state.Mode = ModeQuick + state.RoundsUsed = 0 + state.ExpiresAt = time.Time{} + return state, true +} + +func ApplySuccessfulTurn(state State, execution ExecutionMode, now time.Time, idleTimeout time.Duration) (Completion, error) { + if err := validateState(state); err != nil { + return Completion{}, err + } + if idleTimeout <= 0 { + return Completion{}, ErrInvalidState + } + if execution != ExecutionQuick && execution != ExecutionReasoning && execution != ExecutionReasoningSingle { + return Completion{}, ErrInvalidState + } + + result := Completion{Next: state} + if !state.OnboardingShown { + result.ShowOnboarding = true + result.Next.OnboardingShown = true + result.Next.OnboardingShownAt = now + } + + if execution != ExecutionReasoning || state.Mode != ModeReasoning { + return result, nil + } + + result.RoundNumber = state.RoundsUsed + 1 + result.Next.LastActivityAt = now + if result.RoundNumber >= state.MaxRounds { + result.AutoClosed = true + result.Next.Mode = ModeQuick + result.Next.RoundsUsed = 0 + result.Next.ExpiresAt = time.Time{} + return result, nil + } + + result.Next.RoundsUsed = result.RoundNumber + result.Next.ExpiresAt = now.Add(idleTimeout) + result.ShowHint = state.HintEnabled && state.MaxRounds-result.RoundNumber == 2 + return result, nil +} + +func validateState(state State) error { + if state.Mode != ModeQuick && state.Mode != ModeReasoning { + return ErrInvalidState + } + if state.MaxRounds < 1 || state.MaxRounds > 50 { + return ErrInvalidState + } + if state.RoundsUsed < 0 || state.RoundsUsed > state.MaxRounds { + return ErrInvalidState + } + return nil +} diff --git a/internal/reasoningmode/state_test.go b/internal/reasoningmode/state_test.go new file mode 100644 index 0000000..cdb5c22 --- /dev/null +++ b/internal/reasoningmode/state_test.go @@ -0,0 +1,111 @@ +package reasoningmode + +import ( + "testing" + "time" +) + +func defaultTestState() State { + return State{Mode: ModeQuick, MaxRounds: 10, HintEnabled: true} +} + +func TestApplySuccessfulTurnShowsOnboardingOnceInQuickMode(t *testing.T) { + now := time.Date(2026, 9, 9, 12, 0, 0, 0, time.UTC) + result, err := ApplySuccessfulTurn(defaultTestState(), ExecutionQuick, now, 10*time.Minute) + if err != nil { + t.Fatal(err) + } + if !result.ShowOnboarding || result.RoundNumber != 0 || result.AutoClosed || result.ShowHint { + t.Fatalf("result=%+v", result) + } + if !result.Next.OnboardingShown || result.Next.Mode != ModeQuick || result.Next.RoundsUsed != 0 { + t.Fatalf("next=%+v", result.Next) + } + + second, err := ApplySuccessfulTurn(result.Next, ExecutionQuick, now.Add(time.Minute), 10*time.Minute) + if err != nil { + t.Fatal(err) + } + if second.ShowOnboarding { + t.Fatal("onboarding must only be shown once") + } +} + +func TestApplySuccessfulTurnShowsRemainingTwoHint(t *testing.T) { + now := time.Date(2026, 9, 9, 12, 0, 0, 0, time.UTC) + state := State{Mode: ModeReasoning, MaxRounds: 10, RoundsUsed: 7, HintEnabled: true, OnboardingShown: true} + result, err := ApplySuccessfulTurn(state, ExecutionReasoning, now, 10*time.Minute) + if err != nil { + t.Fatal(err) + } + if result.RoundNumber != 8 || !result.ShowHint || result.AutoClosed { + t.Fatalf("result=%+v", result) + } + if result.Next.Mode != ModeReasoning || result.Next.RoundsUsed != 8 || !result.Next.ExpiresAt.Equal(now.Add(10*time.Minute)) { + t.Fatalf("next=%+v", result.Next) + } +} + +func TestApplySuccessfulTurnAutoClosesAtConfiguredLimit(t *testing.T) { + now := time.Date(2026, 9, 9, 12, 0, 0, 0, time.UTC) + state := State{Mode: ModeReasoning, MaxRounds: 10, RoundsUsed: 9, HintEnabled: true, OnboardingShown: true} + result, err := ApplySuccessfulTurn(state, ExecutionReasoning, now, 10*time.Minute) + if err != nil { + t.Fatal(err) + } + if result.RoundNumber != 10 || !result.AutoClosed || result.ShowHint { + t.Fatalf("result=%+v", result) + } + if result.Next.Mode != ModeQuick || result.Next.RoundsUsed != 0 || !result.Next.ExpiresAt.IsZero() { + t.Fatalf("next=%+v", result.Next) + } +} + +func TestApplySuccessfulTurnRespectsDisabledHint(t *testing.T) { + state := State{Mode: ModeReasoning, MaxRounds: 10, RoundsUsed: 7, HintEnabled: false, OnboardingShown: true} + result, err := ApplySuccessfulTurn(state, ExecutionReasoning, time.Now(), 10*time.Minute) + if err != nil { + t.Fatal(err) + } + if result.ShowHint { + t.Fatal("disabled hint must remain hidden") + } +} + +func TestApplySuccessfulTurnSingleReasoningDoesNotChangePersistentMode(t *testing.T) { + now := time.Date(2026, 9, 9, 12, 0, 0, 0, time.UTC) + state := defaultTestState() + result, err := ApplySuccessfulTurn(state, ExecutionReasoningSingle, now, 10*time.Minute) + if err != nil { + t.Fatal(err) + } + if result.RoundNumber != 0 || result.AutoClosed || result.Next.Mode != ModeQuick || result.Next.RoundsUsed != 0 { + t.Fatalf("result=%+v", result) + } +} + +func TestApplySuccessfulTurnDoesNotReenableModeClosedWhileAnswerRan(t *testing.T) { + state := State{Mode: ModeQuick, MaxRounds: 10, HintEnabled: true, OnboardingShown: true} + result, err := ApplySuccessfulTurn(state, ExecutionReasoning, time.Now(), 10*time.Minute) + if err != nil { + t.Fatal(err) + } + if result.RoundNumber != 0 || result.Next.Mode != ModeQuick || result.Next.RoundsUsed != 0 { + t.Fatalf("result=%+v", result) + } +} + +func TestEffectiveStateExpiresReasoningWithoutMutatingPreferences(t *testing.T) { + now := time.Date(2026, 9, 9, 12, 0, 0, 0, time.UTC) + state := State{ + Mode: ModeReasoning, MaxRounds: 15, RoundsUsed: 4, + HintEnabled: false, OnboardingShown: true, ExpiresAt: now, + } + effective, expired := EffectiveState(state, now) + if !expired || effective.Mode != ModeQuick || effective.RoundsUsed != 0 || !effective.ExpiresAt.IsZero() { + t.Fatalf("effective=%+v expired=%t", effective, expired) + } + if effective.MaxRounds != 15 || effective.HintEnabled || !effective.OnboardingShown { + t.Fatalf("preferences changed on expiry: %+v", effective) + } +} diff --git a/internal/runtime/manager.go b/internal/runtime/manager.go new file mode 100644 index 0000000..45ed382 --- /dev/null +++ b/internal/runtime/manager.go @@ -0,0 +1,102 @@ +package runtime + +import ( + "context" + "errors" + "sync" + "time" +) + +type Credentials struct { + ClientID string + Secret string + Ref string +} + +type Component interface { + Start(context.Context, Credentials) error + Stop(context.Context) error +} + +type Status struct { + State string + ClientID string + LastCode string + UpdatedAt time.Time +} + +type Manager struct { + mu sync.Mutex + component Component + active Credentials + status Status +} + +func NewManager(component Component) *Manager { + return &Manager{component: component, status: Status{State: "stopped", UpdatedAt: time.Now()}} +} + +func (m *Manager) Start(ctx context.Context, credentials Credentials) error { + m.mu.Lock() + defer m.mu.Unlock() + if m.component == nil { + return errors.New("runtime_component_required") + } + if m.status.State == "running" { + return errors.New("runtime_already_running") + } + if err := m.component.Start(ctx, credentials); err != nil { + m.status = Status{State: "error", LastCode: "active_start_failed", UpdatedAt: time.Now()} + return errors.New("active_start_failed") + } + m.active = credentials + m.status = Status{State: "running", ClientID: credentials.ClientID, UpdatedAt: time.Now()} + return nil +} + +func (m *Manager) Switch(ctx context.Context, candidate Credentials) error { + m.mu.Lock() + defer m.mu.Unlock() + if m.component == nil { + return errors.New("runtime_component_required") + } + old := m.active + m.status = Status{State: "switching", ClientID: old.ClientID, UpdatedAt: time.Now()} + if err := m.component.Stop(ctx); err != nil { + m.status = Status{State: "running", ClientID: old.ClientID, LastCode: "active_stop_failed", UpdatedAt: time.Now()} + return errors.New("active_stop_failed") + } + if err := m.component.Start(ctx, candidate); err == nil { + m.active = candidate + m.status = Status{State: "running", ClientID: candidate.ClientID, LastCode: "switch_ok", UpdatedAt: time.Now()} + return nil + } + if old.ClientID != "" && m.component.Start(ctx, old) == nil { + m.active = old + m.status = Status{State: "running", ClientID: old.ClientID, LastCode: "candidate_start_failed_rolled_back", UpdatedAt: time.Now()} + return errors.New("candidate_start_failed_rolled_back") + } + m.active = Credentials{} + m.status = Status{State: "error", LastCode: "rollback_failed", UpdatedAt: time.Now()} + return errors.New("rollback_failed") +} + +func (m *Manager) Stop(ctx context.Context) error { + m.mu.Lock() + defer m.mu.Unlock() + if m.component == nil || m.status.State == "stopped" { + return nil + } + if err := m.component.Stop(ctx); err != nil { + return errors.New("runtime_stop_failed") + } + m.active = Credentials{} + m.status = Status{State: "stopped", UpdatedAt: time.Now()} + return nil +} + +func (m *Manager) Status() Status { + m.mu.Lock() + defer m.mu.Unlock() + return m.status +} diff --git a/internal/runtime/manager_test.go b/internal/runtime/manager_test.go new file mode 100644 index 0000000..787bb5f --- /dev/null +++ b/internal/runtime/manager_test.go @@ -0,0 +1,88 @@ +package runtime + +import ( + "context" + "errors" + "sync" + "testing" +) + +type fakeComponent struct { + mu sync.Mutex + running string + starts []string + stops int + fail map[string]error +} + +func (f *fakeComponent) Start(_ context.Context, cfg Credentials) error { + f.mu.Lock() + defer f.mu.Unlock() + if f.running != "" { + return errors.New("already_running") + } + f.starts = append(f.starts, cfg.ClientID) + if err := f.fail[cfg.ClientID]; err != nil { + return err + } + f.running = cfg.ClientID + return nil +} +func (f *fakeComponent) Stop(context.Context) error { + f.mu.Lock() + defer f.mu.Unlock() + f.stops++ + f.running = "" + return nil +} + +func TestManagerSwitchesWithAtMostOneRuntime(t *testing.T) { + component := &fakeComponent{fail: map[string]error{}} + m := NewManager(component) + if err := m.Start(context.Background(), Credentials{ClientID: "old", Secret: "s1"}); err != nil { + t.Fatal(err) + } + if err := m.Switch(context.Background(), Credentials{ClientID: "new", Secret: "s2"}); err != nil { + t.Fatal(err) + } + if component.running != "new" || component.stops != 1 { + t.Fatalf("running=%q stops=%d", component.running, component.stops) + } + status := m.Status() + if status.ClientID != "new" || status.State != "running" { + t.Fatalf("status=%+v", status) + } +} + +func TestManagerRollsBackWhenCandidateFails(t *testing.T) { + component := &fakeComponent{fail: map[string]error{"bad": errors.New("stream_failed")}} + m := NewManager(component) + if err := m.Start(context.Background(), Credentials{ClientID: "old", Secret: "s1"}); err != nil { + t.Fatal(err) + } + if err := m.Switch(context.Background(), Credentials{ClientID: "bad", Secret: "s2"}); err == nil { + t.Fatal("expected failure") + } + if component.running != "old" { + t.Fatalf("running=%q starts=%v", component.running, component.starts) + } + status := m.Status() + if status.State != "running" || status.LastCode != "candidate_start_failed_rolled_back" { + t.Fatalf("status=%+v", status) + } +} + +func TestManagerReportsRollbackFailure(t *testing.T) { + component := &fakeComponent{fail: map[string]error{"bad": errors.New("bad"), "old": nil}} + m := NewManager(component) + if err := m.Start(context.Background(), Credentials{ClientID: "old", Secret: "s1"}); err != nil { + t.Fatal(err) + } + component.fail["old"] = errors.New("old_failed") + if err := m.Switch(context.Background(), Credentials{ClientID: "bad", Secret: "s2"}); err == nil { + t.Fatal("expected failure") + } + if m.Status().State != "error" || m.Status().LastCode != "rollback_failed" { + t.Fatalf("status=%+v", m.Status()) + } +} diff --git a/internal/secretstore/file.go b/internal/secretstore/file.go new file mode 100644 index 0000000..e848145 --- /dev/null +++ b/internal/secretstore/file.go @@ -0,0 +1,84 @@ +package secretstore + +import ( + "crypto/rand" + "encoding/hex" + "errors" + "os" + "path/filepath" + "strings" +) + +type Store struct{ root string } + +func New(root string) (*Store, error) { + root = strings.TrimSpace(root) + if root == "" { + return nil, errors.New("secret root is required") + } + if err := os.MkdirAll(root, 0700); err != nil { + return nil, err + } + if err := os.Chmod(root, 0700); err != nil { + return nil, err + } + return &Store{root: root}, nil +} +func (s *Store) Put(kind, value string) (string, error) { + kind = strings.TrimSpace(kind) + value = strings.TrimSpace(value) + if kind == "" || value == "" { + return "", errors.New("secret kind and value are required") + } + if strings.ContainsAny(kind, "/\\") || kind == "." || kind == ".." { + return "", errors.New("invalid secret kind") + } + b := make([]byte, 16) + if _, err := rand.Read(b); err != nil { + return "", err + } + ref := kind + "-" + hex.EncodeToString(b) + tmp, err := os.CreateTemp(s.root, ".new-") + if err != nil { + return "", err + } + tmpName := tmp.Name() + defer os.Remove(tmpName) + if err = tmp.Chmod(0600); err == nil { + _, err = tmp.WriteString(value) + } + if err == nil { + err = tmp.Sync() + } + closeErr := tmp.Close() + if err == nil { + err = closeErr + } + if err != nil { + return "", err + } + if err = os.Rename(tmpName, filepath.Join(s.root, ref)); err != nil { + return "", err + } + return ref, nil +} +func (s *Store) Get(ref string) (string, error) { + if ref == "" || filepath.Base(ref) != ref { + return "", errors.New("invalid secret reference") + } + b, err := os.ReadFile(filepath.Join(s.root, ref)) + if err != nil { + return "", err + } + return string(b), nil +} +func (s *Store) Configured(ref string) bool { + _, err := os.Stat(filepath.Join(s.root, filepath.Base(ref))) + return ref != "" && filepath.Base(ref) == ref && err == nil +} +func (s *Store) Delete(ref string) error { + if ref == "" || filepath.Base(ref) != ref { + return errors.New("invalid secret reference") + } + return os.Remove(filepath.Join(s.root, ref)) +} diff --git a/internal/secretstore/file_test.go b/internal/secretstore/file_test.go new file mode 100644 index 0000000..d063780 --- /dev/null +++ b/internal/secretstore/file_test.go @@ -0,0 +1,39 @@ +package secretstore + +import ( + "os" + "path/filepath" + "testing" +) + +func TestFileStoreWritesSecretWithPrivatePermissions(t *testing.T) { + root := t.TempDir() + s, err := New(root) + if err != nil { + t.Fatal(err) + } + ref, err := s.Put("dingtalk", "top-secret") + if err != nil { + t.Fatal(err) + } + info, err := os.Stat(filepath.Join(root, ref)) + if err != nil { + t.Fatal(err) + } + if info.Mode().Perm() != 0600 { + t.Fatalf("mode=%o", info.Mode().Perm()) + } + value, err := s.Get(ref) + if err != nil || value != "top-secret" { + t.Fatalf("value=%q err=%v", value, err) + } +} +func TestFileStoreRejectsTraversalAndBlank(t *testing.T) { + s, _ := New(t.TempDir()) + if _, err := s.Put("../bad", "x"); err == nil { + t.Fatal("expected traversal rejection") + } + if _, err := s.Put("ok", ""); err == nil { + t.Fatal("expected blank rejection") + } +} diff --git a/internal/session/title.go b/internal/session/title.go new file mode 100644 index 0000000..9acd3de --- /dev/null +++ b/internal/session/title.go @@ -0,0 +1,48 @@ +package session + +import ( + "strings" + "unicode/utf8" + + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/core" +) + +// TitleIdentity contains only the display inputs required to name a WeKnora +// session. Stable IDs remain the session identity; titles are display-only. +type TitleIdentity struct { + ConversationType core.ConversationType + ExternalUserID string + ExternalChatID string + SenderName string + ConversationTitle string +} + +// BuildDisplayTitle returns a readable DingTalk session title without exposing +// the full stable ID. Direct titles contain only the employee name; department +// and region are deliberately not part of this contract. +func BuildDisplayTitle(identity TitleIdentity) string { + switch identity.ConversationType { + case core.ConversationGroup: + if title := strings.TrimSpace(identity.ConversationTitle); title != "" { + return title + } + return fallbackTitle("钉钉群聊", identity.ExternalChatID) + default: + if name := strings.TrimSpace(identity.SenderName); name != "" { + return name + } + return fallbackTitle("钉钉用户", identity.ExternalUserID) + } +} + +func fallbackTitle(prefix, stableID string) string { + stableID = strings.TrimSpace(stableID) + if stableID == "" { + return prefix + } + runes := []rune(stableID) + if utf8.RuneCountInString(stableID) > 4 { + runes = runes[len(runes)-4:] + } + return prefix + "-" + string(runes) +} diff --git a/internal/session/title_test.go b/internal/session/title_test.go new file mode 100644 index 0000000..b72d05d --- /dev/null +++ b/internal/session/title_test.go @@ -0,0 +1,68 @@ +package session + +import ( + "testing" + + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/core" +) + +func TestBuildDisplayTitle(t *testing.T) { + t.Parallel() + tests := []struct { + name string + in TitleIdentity + want string + }{ + { + name: "direct uses employee name only", + in: TitleIdentity{ + ConversationType: core.ConversationDirect, + ExternalUserID: "staff-123456", + SenderName: " 张三 ", + }, + want: "张三", + }, + { + name: "direct masks stable id when name unavailable", + in: TitleIdentity{ + ConversationType: core.ConversationDirect, + ExternalUserID: "staff-123456", + }, + want: "钉钉用户-3456", + }, + { + name: "group uses conversation title", + in: TitleIdentity{ + ConversationType: core.ConversationGroup, + ExternalChatID: "cid-987654", + ConversationTitle: " NOVA项目群 ", + }, + want: "NOVA项目群", + }, + { + name: "group masks stable id when title unavailable", + in: TitleIdentity{ + ConversationType: core.ConversationGroup, + ExternalChatID: "cid-987654", + }, + want: "钉钉群聊-7654", + }, + { + name: "short id remains usable", + in: TitleIdentity{ + ConversationType: core.ConversationDirect, + ExternalUserID: "u7", + }, + want: "钉钉用户-u7", + }, + } + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + if got := BuildDisplayTitle(tt.in); got != tt.want { + t.Fatalf("BuildDisplayTitle() = %q, want %q", got, tt.want) + } + }) + } +} diff --git a/internal/settings/administrator.go b/internal/settings/administrator.go new file mode 100644 index 0000000..9b5a20c --- /dev/null +++ b/internal/settings/administrator.go @@ -0,0 +1,17 @@ +package settings + +import "errors" + +type Administrator struct { + StaffID string + DisplayName string + Department string + Role string + Status string +} + +var ( + ErrAdministratorNotFound = errors.New("administrator not found") + ErrLastAdministrator = errors.New("last active administrator cannot be disabled") + ErrAdministratorAlreadyDisabled = errors.New("administrator already disabled") +) diff --git a/internal/settings/controller.go b/internal/settings/controller.go new file mode 100644 index 0000000..5a22895 --- /dev/null +++ b/internal/settings/controller.go @@ -0,0 +1,287 @@ +package settings + +import ( + "context" + "errors" + "fmt" + "strconv" + "strings" + "time" +) + +type ResourceBinding struct { + Kind, TenantKey, ConversationID, ConversationTitle string + BaseID, SheetID, ViewID, OperatorID string + CreatedByStaffID string + FieldMapping map[string]string + ValidationCode string + Activate bool +} +type BootstrapCandidate struct { + TenantKey, Code, StaffID, UnionID, DisplayName, Department string + DetectedAt time.Time +} +type SettingSession struct { + TenantKey, StaffID, ConversationID, ConversationType, PendingAction string + ExpiresAt time.Time +} +type SettingInput struct{ TenantKey, Channel, StaffID, UnionID, DisplayName, Department, Text, ConversationType, ConversationID, ConversationTitle string } +type ControllerRepository interface { + IsAdministrator(context.Context, string, string) (bool, error) + SetPreference(context.Context, string, string, string, string) error + SetReasoningMaxRounds(context.Context, string, string, string, int, time.Time) error + SetReasoningHintEnabled(context.Context, string, string, string, bool, time.Time) error + SaveBinding(context.Context, ResourceBinding) error + TestAndActivateSupportGroup(context.Context, ResourceBinding) error + DetectBootstrapCandidate(context.Context, BootstrapCandidate) error + GetSettingSession(context.Context, string, string) (SettingSession, bool, error) + SaveSettingSession(context.Context, SettingSession) error + DeleteSettingSession(context.Context, string, string) error +} +type Controller struct { + repo ControllerRepository + now func() time.Time +} + +func NewController(repo ControllerRepository) *Controller { + return &Controller{repo: repo, now: time.Now} +} +func (c *Controller) ShouldHandle(ctx context.Context, tenant, staff, text string) bool { + if _, ok := ParseCommand(text); ok { + return true + } + if c == nil || c.repo == nil { + return false + } + s, ok, err := c.repo.GetSettingSession(ctx, tenant, staff) + return err == nil && ok && s.ExpiresAt.After(c.now()) +} +func (c *Controller) Handle(ctx context.Context, in SettingInput) (string, error) { + if c == nil || c.repo == nil { + return "", errors.New("settings repository is required") + } + cmd, explicit := ParseCommand(in.Text) + var action string + var args []string + if explicit { + args = cmd.Args + } else { + s, ok, err := c.repo.GetSettingSession(ctx, in.TenantKey, in.StaffID) + if err != nil { + return "", err + } + if !ok || !s.ExpiresAt.After(c.now()) { + return "", nil + } + if strings.TrimSpace(in.Text) == "取消" { + _ = c.repo.DeleteSettingSession(ctx, in.TenantKey, in.StaffID) + return "已取消设置。", nil + } + action = s.PendingAction + args = []string{action, strings.TrimSpace(in.Text)} + } + if explicit && len(args) == 1 && len(args[0]) == 6 && allDigits(args[0]) { + if strings.TrimSpace(in.ConversationType) != "direct" { + return "管理员绑定码只能私聊机器人使用。", nil + } + err := c.repo.DetectBootstrapCandidate(ctx, BootstrapCandidate{TenantKey: in.TenantKey, Code: args[0], StaffID: in.StaffID, UnionID: in.UnionID, DisplayName: in.DisplayName, Department: in.Department, DetectedAt: c.now()}) + if err != nil { + return "", err + } + return "身份已验证,请回到服务器命令行等待确认。", nil + } + if explicit && len(args) == 0 { + admin, err := c.repo.IsAdministrator(ctx, in.TenantKey, in.StaffID) + if err != nil { + return "", err + } + if admin { + return settingMenu(true, strings.TrimSpace(in.ConversationType) == "direct"), nil + } + return settingMenu(false, false), nil + } + if action == "" { + action = strings.ToLower(args[0]) + } + if action == "language" { + if len(args) != 2 || !validLocale(args[1]) { + return "可选语言:auto、zh-CN、en、ja、ko、es。", nil + } + if err := c.repo.SetPreference(ctx, in.TenantKey, defaultChannel(in.Channel), in.StaffID, args[1]); err != nil { + return "", err + } + return "✅ 回答语言已设置为 " + args[1] + "。", nil + } + if action == "rounds" { + if len(args) != 2 { + return "智能推理自动关闭轮数必须是1-50之间的整数。", nil + } + rounds, parseErr := strconv.Atoi(args[1]) + if parseErr != nil || rounds < 1 || rounds > 50 { + return "智能推理自动关闭轮数必须是1-50之间的整数。", nil + } + if err := c.repo.SetReasoningMaxRounds(ctx, in.TenantKey, defaultChannel(in.Channel), in.StaffID, rounds, c.now()); err != nil { + return "", err + } + return fmt.Sprintf("✅ 智能推理将在%d轮对话后自动关闭。", rounds), nil + } + if action == "hint" { + if len(args) != 2 || (args[1] != "on" && args[1] != "off") { + return "用法:/setting hint 。", nil + } + enabled := args[1] == "on" + if err := c.repo.SetReasoningHintEnabled(ctx, in.TenantKey, defaultChannel(in.Channel), in.StaffID, enabled, c.now()); err != nil { + return "", err + } + if enabled { + return "✅ 智能推理剩余轮次提醒已开启。", nil + } + return "✅ 智能推理剩余轮次提醒已关闭。", nil + } + admin, err := c.repo.IsAdministrator(ctx, in.TenantKey, in.StaffID) + if err != nil { + return "", err + } + if !admin { + return "你没有系统管理权限。", nil + } + switch action { + case "support": + if in.ConversationType != "group" || strings.TrimSpace(in.ConversationID) == "" { + return "请在目标技术支持群中@机器人发送 /setting support。", nil + } + binding := ResourceBinding{Kind: "support_group", TenantKey: in.TenantKey, ConversationID: in.ConversationID, ConversationTitle: in.ConversationTitle, CreatedByStaffID: in.StaffID} + if len(args) == 2 && strings.EqualFold(args[1], "test") { + err = c.repo.TestAndActivateSupportGroup(ctx, binding) + if err == nil { + return "✅ 测试成功,当前群已激活为技术支持群。", nil + } + break + } + err = c.repo.SaveBinding(ctx, binding) + if err == nil { + return "✅ 当前群已保存为技术支持群(待验证)。确认发送测试消息后,请在本群@机器人发送 /setting support test。", nil + } + case "question", "faq": + if len(args) != 2 { + err = c.repo.SaveSettingSession(ctx, SettingSession{TenantKey: in.TenantKey, StaffID: in.StaffID, ConversationID: in.ConversationID, ConversationType: in.ConversationType, PendingAction: action, ExpiresAt: c.now().Add(10 * time.Minute)}) + if err != nil { + return "", err + } + return tableBindingInstructions(action), nil + } + link, e := ParseNotableLink(args[1]) + if e != nil { + return "AI表格链接无法识别。", nil + } + kind := action + "_table" + err = c.repo.SaveBinding(ctx, ResourceBinding{Kind: kind, TenantKey: in.TenantKey, BaseID: link.BaseID, SheetID: link.SheetID, ViewID: link.ViewID, OperatorID: in.UnionID, CreatedByStaffID: in.StaffID}) + if err != nil { + return tableBindingFailureReply(action, err), nil + } + _ = c.repo.DeleteSettingSession(ctx, in.TenantKey, in.StaffID) + return fmt.Sprintf("✅ %sSchema验证通过并已激活,DobotAI将短暂重启加载Dispatcher。", map[string]string{"question": "问题AI表格", "faq": "FAQ表格"}[action]), nil + default: + return "未知设置项。发送 /setting 查看菜单。", nil + } + return "", err +} + +func settingMenu(admin, _ bool) string { + menu := "⚙️ 个人设置\n入口:/setting 或 /设置\n" + + "回答语言:/setting language \n" + + "- auto:跟随当前提问语言(推荐)\n" + + "- zh-CN:简体中文\n" + + "- en / ja / ko / es:英语 / 日语 / 韩语 / 西班牙语\n" + + "例如:/setting language en\n\n" + + "智能推理自动关闭轮数:/setting rounds <1-50>\n" + + "例如:/setting rounds 15\n" + + "剩余轮次提醒:/setting hint " + if !admin { + return menu + } + menu += "\n\n🛠 系统管理(仅管理员)\n" + + "- support:在目标技术支持群@机器人发送 /setting support 保存;再发送 /setting support test,测试成功后激活。\n" + + "- question:私聊发送 /setting question,再在10分钟内发送问题AI表链接;Schema验证通过后激活并短暂重启。\n" + + "- faq:私聊发送 /setting faq,再在10分钟内发送FAQ表链接;Schema验证通过后激活并短暂重启。" + return menu +} + +func tableBindingFailureReply(action string, err error) string { + label := map[string]string{"question": "问题AI表格", "faq": "FAQ表格"}[action] + if label == "" { + label = "AI表格" + } + code := "table_validation_failed" + guidance := "请检查链接是否来自目标表格中的任意记录,并确认字段名称和类型符合提示要求。" + raw := "" + if err != nil { + raw = strings.ToLower(err.Error()) + } + switch { + case strings.Contains(raw, "schema_http_401"), strings.Contains(raw, "schema_http_403"), strings.Contains(raw, "schema_token_failed"): + code = "table_permission_denied" + guidance = "请确认机器人应用已开通钉钉AI表格接口权限,并确认当前管理员对目标表格有访问和编辑权限。" + case strings.Contains(raw, "missing_field"): + code = "table_schema_missing_field" + guidance = "目标表缺少必需字段,请按上一条提示补齐字段后重试。" + case strings.Contains(raw, "duplicate_field"): + code = "table_schema_duplicate_field" + guidance = "目标表存在重名必需字段,请保留唯一字段后重试。" + case strings.Contains(raw, "field_type_mismatch"): + code = "table_schema_field_type_mismatch" + guidance = "目标表的必需字段类型不正确,请按上一条提示调整字段类型后重试。" + case strings.Contains(raw, "schema_network_failed"), strings.Contains(raw, "schema_request_failed"), strings.Contains(raw, "schema_read_failed"): + code = "table_schema_network_failed" + guidance = "钉钉AI表格接口暂时不可用,请稍后重试。" + case strings.Contains(raw, "schema_decode_failed"), strings.Contains(raw, "schema_empty"): + code = "table_schema_response_invalid" + guidance = "未读取到可用字段,请确认链接指向AI表格中的具体数据表。" + } + return fmt.Sprintf("❌ %s验证失败,新配置未激活。\n错误码:%s\n%s\n当前设置仍在10分钟等待期内,可直接重新发送链接卡片;发送“取消”退出。", label, code, guidance) +} + +func tableBindingInstructions(action string) string { + if action == "faq" { + return "请在10分钟内直接发送FAQ表中任意一条记录的链接(钉钉显示为链接卡片也可以直接发送)。\n\n" + + "操作前请确认:\n" + + "1. 当前机器人应用具备钉钉AI表格接口权限,当前管理员具备目标表格的访问和编辑权限。\n" + + "2. FAQ表包含以下字段:标准问题(必填)、原始问题、语言、提问人。\n" + + "3. Schema验证成功后会立即激活FAQ写入,并短暂重启DobotAI加载Dispatcher。\n\n" + + "如果完整URL被钉钉自动转换为链接卡片,请只发送 alidocs.dingtalk.com/ 后面的部分。示例:\n" + + "i/nodes/?iframeQuery=entrance%3Ddata%26sheetId%3D%26viewId%3D\n\n" + + "iframeQuery必须完整保留,系统会自动解码其中的sheetId/viewId。\n\n" + + "发送“取消”退出。" + } + return "请在10分钟内直接发送问题AI表格中任意一条记录的链接(钉钉显示为链接卡片也可以直接发送)。\n\n" + + "操作前请确认:\n" + + "1. 当前机器人应用具备钉钉AI表格接口权限,当前管理员具备目标表格的访问和编辑权限。\n" + + "2. 问题表包含:中文问题、提问时间、提问人、原始问题、AI答案、流程触发人员信息、语言、部门、区域。\n" + + "3. Schema验证成功后会立即激活问题表写入,并短暂重启DobotAI加载Dispatcher。\n\n" + + "如果完整URL被钉钉自动转换为链接卡片,请只发送 alidocs.dingtalk.com/ 后面的部分。示例:\n" + + "i/nodes/?iframeQuery=entrance%3Ddata%26sheetId%3D%26viewId%3D\n\n" + + "iframeQuery必须完整保留,系统会自动解码其中的sheetId/viewId。\n\n" + + "发送“取消”退出。" +} + +func validLocale(s string) bool { + switch s { + case "auto", "zh-CN", "en", "ja", "ko", "es": + return true + } + return false +} +func defaultChannel(s string) string { + if strings.TrimSpace(s) == "" { + return "dingtalk" + } + return strings.TrimSpace(s) +} +func allDigits(s string) bool { + for _, r := range s { + if r < '0' || r > '9' { + return false + } + } + return s != "" +} diff --git a/internal/settings/controller_test.go b/internal/settings/controller_test.go new file mode 100644 index 0000000..8e2832c --- /dev/null +++ b/internal/settings/controller_test.go @@ -0,0 +1,378 @@ +package settings + +import ( + "context" + "errors" + "strings" + "testing" + "time" +) + +type memoryRepo struct { + admins map[string]bool + prefs map[string]string + rounds map[string]int + hints map[string]bool + bindings map[string]ResourceBinding + candidate BootstrapCandidate + sessions map[string]SettingSession + saveErr error +} + +func newMemoryRepo() *memoryRepo { + return &memoryRepo{admins: map[string]bool{}, prefs: map[string]string{}, rounds: map[string]int{}, hints: map[string]bool{}, bindings: map[string]ResourceBinding{}, sessions: map[string]SettingSession{}} +} +func (r *memoryRepo) IsAdministrator(_ context.Context, tenant, staff string) (bool, error) { + return r.admins[tenant+"/"+staff], nil +} +func (r *memoryRepo) SetPreference(_ context.Context, tenant, channel, staff, locale string) error { + r.prefs[tenant+"/"+staff] = locale + return nil +} +func (r *memoryRepo) SetReasoningMaxRounds(_ context.Context, tenant, channel, staff string, rounds int, _ time.Time) error { + r.rounds[tenant+"/"+channel+"/"+staff] = rounds + return nil +} +func (r *memoryRepo) SetReasoningHintEnabled(_ context.Context, tenant, channel, staff string, enabled bool, _ time.Time) error { + r.hints[tenant+"/"+channel+"/"+staff] = enabled + return nil +} +func (r *memoryRepo) SaveBinding(_ context.Context, b ResourceBinding) error { + if r.saveErr != nil { + return r.saveErr + } + r.bindings[b.Kind] = b + return nil +} +func (r *memoryRepo) TestAndActivateSupportGroup(_ context.Context, b ResourceBinding) error { + b.Activate = true + b.ValidationCode = "support_test_ok" + r.bindings[b.Kind] = b + return nil +} +func (r *memoryRepo) DetectBootstrapCandidate(_ context.Context, c BootstrapCandidate) error { + r.candidate = c + return nil +} +func (r *memoryRepo) GetSettingSession(_ context.Context, tenant, staff string) (SettingSession, bool, error) { + s, ok := r.sessions[tenant+"/"+staff] + return s, ok, nil +} +func (r *memoryRepo) SaveSettingSession(_ context.Context, s SettingSession) error { + r.sessions[s.TenantKey+"/"+s.StaffID] = s + return nil +} +func (r *memoryRepo) DeleteSettingSession(_ context.Context, tenant, staff string) error { + delete(r.sessions, tenant+"/"+staff) + return nil +} + +func TestControllerLanguageForOrdinaryUser(t *testing.T) { + r := newMemoryRepo() + c := NewController(r) + out, err := c.Handle(context.Background(), SettingInput{TenantKey: "t", Channel: "dingtalk", StaffID: "u", Text: "/setting language ja", ConversationType: "direct"}) + if err != nil { + t.Fatal(err) + } + if r.prefs["t/u"] != "ja" || out == "" { + t.Fatalf("prefs=%v out=%q", r.prefs, out) + } +} + +func TestControllerReasoningRoundsForOrdinaryUser(t *testing.T) { + r := newMemoryRepo() + c := NewController(r) + out, err := c.Handle(context.Background(), SettingInput{TenantKey: "t", Channel: "dingtalk", StaffID: "u", Text: "/setting rounds 15", ConversationType: "direct"}) + if err != nil { + t.Fatal(err) + } + if r.rounds["t/dingtalk/u"] != 15 || !strings.Contains(out, "15轮") { + t.Fatalf("rounds=%v out=%q", r.rounds, out) + } +} + +func TestControllerRejectsOutOfRangeReasoningRounds(t *testing.T) { + for _, value := range []string{"0", "51", "abc"} { + r := newMemoryRepo() + out, err := NewController(r).Handle(context.Background(), SettingInput{TenantKey: "t", Channel: "dingtalk", StaffID: "u", Text: "/setting rounds " + value, ConversationType: "direct"}) + if err != nil { + t.Fatal(err) + } + if len(r.rounds) != 0 || !strings.Contains(out, "1-50") { + t.Fatalf("value=%q rounds=%v out=%q", value, r.rounds, out) + } + } +} + +func TestControllerReasoningHintForOrdinaryUser(t *testing.T) { + r := newMemoryRepo() + c := NewController(r) + out, err := c.Handle(context.Background(), SettingInput{TenantKey: "t", Channel: "dingtalk", StaffID: "u", Text: "/setting hint off", ConversationType: "direct"}) + if err != nil { + t.Fatal(err) + } + if r.hints["t/dingtalk/u"] || !strings.Contains(out, "已关闭") { + t.Fatalf("hints=%v out=%q", r.hints, out) + } +} + +func TestControllerSettingMenuExplainsLanguageWithoutAdminActionsToOrdinaryUser(t *testing.T) { + r := newMemoryRepo() + c := NewController(r) + out, err := c.Handle(context.Background(), SettingInput{TenantKey: "t", Channel: "dingtalk", StaffID: "u", Text: "/setting", ConversationType: "direct"}) + if err != nil { + t.Fatal(err) + } + for _, want := range []string{"个人设置", "/setting language ", "auto:跟随当前提问语言", "zh-CN:简体中文", "例如:/setting language en"} { + if !strings.Contains(out, want) { + t.Fatalf("reply=%q must contain %q", out, want) + } + } + for _, forbidden := range []string{"系统管理", "/setting support", "/admin/settings", "DOBOTAI_ADMIN_TOKEN"} { + if strings.Contains(out, forbidden) { + t.Fatalf("ordinary-user reply=%q must not contain %q", out, forbidden) + } + } +} + +func TestControllerSettingMenuExplainsAdminActionsWithoutBackendAccess(t *testing.T) { + r := newMemoryRepo() + r.admins["t/a"] = true + c := NewController(r) + out, err := c.Handle(context.Background(), SettingInput{TenantKey: "t", Channel: "dingtalk", StaffID: "a", Text: "/setting", ConversationType: "direct"}) + if err != nil { + t.Fatal(err) + } + for _, want := range []string{ + "系统管理(仅管理员)", + "/setting support", + "/setting support test", + "/setting question", + "/setting faq", + "Schema验证通过后激活并短暂重启", + } { + if !strings.Contains(out, want) { + t.Fatalf("reply=%q must contain %q", out, want) + } + } + for _, forbidden := range []string{ + "管理后台", + "SSH隧道", + "127.0.0.1:8090/admin/settings", + "Basic Auth", + "DOBOTAI_ADMIN_TOKEN", + "回后台确认", + } { + if strings.Contains(out, forbidden) { + t.Fatalf("reply=%q must not contain %q", out, forbidden) + } + } +} +func TestControllerRejectsOrdinaryUserSystemBinding(t *testing.T) { + r := newMemoryRepo() + c := NewController(r) + out, err := c.Handle(context.Background(), SettingInput{TenantKey: "t", StaffID: "u", Text: "/setting support", ConversationType: "group", ConversationID: "g"}) + if err != nil { + t.Fatal(err) + } + if len(r.bindings) != 0 || out != "你没有系统管理权限。" { + t.Fatalf("bindings=%v out=%q", r.bindings, out) + } +} +func TestControllerBindsAdminSupportGroup(t *testing.T) { + r := newMemoryRepo() + r.admins["t/a"] = true + c := NewController(r) + out, err := c.Handle(context.Background(), SettingInput{TenantKey: "t", StaffID: "a", Text: "/setting support", ConversationType: "group", ConversationID: "g", ConversationTitle: "技术支持"}) + if err != nil { + t.Fatal(err) + } + binding := r.bindings["support_group"] + if binding.ConversationID != "g" || binding.Activate { + t.Fatalf("binding=%+v", binding) + } + if !strings.Contains(out, "support test") { + t.Fatalf("reply=%q must explain explicit test command", out) + } +} + +func TestControllerExplicitlyTestsAndActivatesSupportGroup(t *testing.T) { + r := newMemoryRepo() + r.admins["t/a"] = true + c := NewController(r) + out, err := c.Handle(context.Background(), SettingInput{TenantKey: "t", StaffID: "a", Text: "/setting support test", ConversationType: "group", ConversationID: "g", ConversationTitle: "技术支持"}) + if err != nil { + t.Fatal(err) + } + binding := r.bindings["support_group"] + if binding.ConversationID != "g" || !binding.Activate { + t.Fatalf("binding=%+v", binding) + } + if !strings.Contains(out, "测试成功") || !strings.Contains(out, "已激活") { + t.Fatalf("reply=%q", out) + } +} +func TestControllerOnlyHandlesSettingEntrypoints(t *testing.T) { + r := newMemoryRepo() + c := NewController(r) + if c.ShouldHandle(context.Background(), "t", "u", "/help") { + t.Fatal("help must not enter the settings controller") + } + out, err := c.Handle(context.Background(), SettingInput{TenantKey: "t", StaffID: "u", Text: "/help", ConversationType: "direct"}) + if err != nil { + t.Fatal(err) + } + if out != "" { + t.Fatalf("help reply=%q must be empty", out) + } +} + +func TestControllerChineseSettingAliasRunsSubcommands(t *testing.T) { + r := newMemoryRepo() + c := NewController(r) + if !c.ShouldHandle(context.Background(), "t", "u", "/设置 language ja") { + t.Fatal("Chinese setting alias must be handled") + } + out, err := c.Handle(context.Background(), SettingInput{TenantKey: "t", Channel: "dingtalk", StaffID: "u", Text: "/设置 language ja", ConversationType: "direct"}) + if err != nil { + t.Fatal(err) + } + if r.prefs["t/u"] != "ja" || !strings.Contains(out, "ja") { + t.Fatalf("pref=%q reply=%q", r.prefs["t/u"], out) + } +} + +func TestControllerParsesAdminQuestionTable(t *testing.T) { + r := newMemoryRepo() + r.admins["t/a"] = true + c := NewController(r) + _, err := c.Handle(context.Background(), SettingInput{TenantKey: "t", StaffID: "a", Text: "/setting question https://alidocs.dingtalk.com/i/nodes/base?sheetId=sheet&viewId=view", ConversationType: "direct"}) + if err != nil { + t.Fatal(err) + } + if r.bindings["question_table"].BaseID != "base" { + t.Fatalf("binding=%+v", r.bindings) + } +} +func TestControllerAcceptsTableLinkInNextMessage(t *testing.T) { + r := newMemoryRepo() + r.admins["t/a"] = true + c := NewController(r) + out, err := c.Handle(context.Background(), SettingInput{TenantKey: "t", Channel: "dingtalk", StaffID: "a", Text: "/setting question", ConversationType: "direct"}) + if err != nil || !strings.Contains(out, "链接") { + t.Fatalf("out=%q err=%v", out, err) + } + if !c.ShouldHandle(context.Background(), "t", "a", "https://alidocs.dingtalk.com/i/nodes/base?sheetId=sheet&viewId=view") { + t.Fatal("active setting session must intercept next message") + } + _, err = c.Handle(context.Background(), SettingInput{TenantKey: "t", Channel: "dingtalk", StaffID: "a", UnionID: "union", Text: "https://alidocs.dingtalk.com/i/nodes/base?sheetId=sheet&viewId=view", ConversationType: "direct"}) + if err != nil { + t.Fatal(err) + } + if r.bindings["question_table"].BaseID != "base" { + t.Fatalf("binding=%+v", r.bindings) + } + if _, ok := r.sessions["t/a"]; ok { + t.Fatal("setting session must be cleared") + } +} + +func TestControllerFAQBindingPromptExplainsPermissionsSchemaActivationAndLinkCards(t *testing.T) { + r := newMemoryRepo() + r.admins["t/a"] = true + c := NewController(r) + out, err := c.Handle(context.Background(), SettingInput{TenantKey: "t", Channel: "dingtalk", StaffID: "a", Text: "/setting faq", ConversationType: "direct"}) + if err != nil { + t.Fatal(err) + } + for _, want := range []string{ + "10分钟", + "链接卡片", + "机器人应用", + "管理员", + "标准问题(必填)", + "原始问题", + "语言", + "提问人", + "立即激活FAQ写入", + "短暂重启DobotAI", + "只发送 alidocs.dingtalk.com/ 后面的部分", + "i/nodes/?iframeQuery=entrance%3Ddata%26sheetId%3D%26viewId%3D", + "完整保留", + "取消", + } { + if !strings.Contains(out, want) { + t.Fatalf("reply=%q must contain %q", out, want) + } + } + if strings.Contains(out, "i/nodes/?sheetId=") { + t.Fatalf("reply still contains obsolete direct-query example: %q", out) + } +} + +func TestControllerReportsFAQPermissionFailureAndKeepsWaitingSession(t *testing.T) { + r := newMemoryRepo() + r.admins["t/a"] = true + c := NewController(r) + if _, err := c.Handle(context.Background(), SettingInput{TenantKey: "t", StaffID: "a", Text: "/setting faq", ConversationType: "direct"}); err != nil { + t.Fatal(err) + } + r.saveErr = errors.New("schema_http_403") + out, err := c.Handle(context.Background(), SettingInput{ + TenantKey: "t", StaffID: "a", UnionID: "union", ConversationType: "direct", + Text: "https://alidocs.dingtalk.com/i/nodes/base?sheetId=sheet&viewId=view", + }) + if err != nil { + t.Fatalf("validation failure must become an actionable reply: %v", err) + } + for _, want := range []string{"table_permission_denied", "未激活", "机器人应用", "管理员", "重新发送链接卡片", "取消"} { + if !strings.Contains(out, want) { + t.Fatalf("reply=%q must contain %q", out, want) + } + } + if _, ok := r.sessions["t/a"]; !ok { + t.Fatal("failed validation must keep the setting session for retry") + } + if _, ok := r.bindings["faq_table"]; ok { + t.Fatal("failed validation must not save a binding") + } +} + +func TestTableBindingFailureReplyUsesStableCodes(t *testing.T) { + tests := []struct { + err error + code string + }{ + {errors.New("schema_http_403"), "table_permission_denied"}, + {errors.New("schema_token_failed"), "table_permission_denied"}, + {errors.New("missing_field"), "table_schema_missing_field"}, + {errors.New("duplicate_field"), "table_schema_duplicate_field"}, + {errors.New("field_type_mismatch"), "table_schema_field_type_mismatch"}, + {errors.New("schema_network_failed"), "table_schema_network_failed"}, + {errors.New("something private happened"), "table_validation_failed"}, + } + for _, tt := range tests { + out := tableBindingFailureReply("faq", tt.err) + if !strings.Contains(out, tt.code) { + t.Fatalf("error=%q reply=%q want code=%q", tt.err, out, tt.code) + } + if tt.code == "table_validation_failed" && strings.Contains(out, tt.err.Error()) { + t.Fatalf("reply leaked raw unknown error: %q", out) + } + } +} +func TestControllerDetectsBootstrapCandidate(t *testing.T) { + r := newMemoryRepo() + c := NewController(r) + c.now = func() time.Time { return time.Unix(100, 0) } + out, err := c.Handle(context.Background(), SettingInput{TenantKey: "t", StaffID: "a", UnionID: "union", DisplayName: "Alice", Text: "/setting 123456", ConversationType: "direct"}) + if err != nil { + t.Fatal(err) + } + if r.candidate.Code != "123456" || r.candidate.StaffID != "a" { + t.Fatalf("candidate=%+v", r.candidate) + } + if !strings.Contains(out, "服务器命令行") || strings.Contains(out, "后台") { + t.Fatalf("reply=%q must direct confirmation back to the server CLI only", out) + } +} diff --git a/internal/settings/settings.go b/internal/settings/settings.go new file mode 100644 index 0000000..d4347b8 --- /dev/null +++ b/internal/settings/settings.go @@ -0,0 +1,181 @@ +package settings + +import ( + "context" + "errors" + "net/url" + "path" + "strings" +) + +type SystemState string + +const ( + StateUninitialized SystemState = "uninitialized" + StateCredentialsSaved SystemState = "credentials_saved" + StateDingTalkVerified SystemState = "dingtalk_verified" + StateWaitingAdmin SystemState = "waiting_first_admin" + StateActive SystemState = "active" + StateCredentialError SystemState = "credential_error" +) + +type Snapshot struct { + ClientID string + SecretConfigured bool + CredentialsVerified bool + AdministratorCount int +} + +func DetermineState(s Snapshot) SystemState { + id := strings.TrimSpace(s.ClientID) != "" + if !id && !s.SecretConfigured { + return StateUninitialized + } + if !id || !s.SecretConfigured { + return StateCredentialError + } + if !s.CredentialsVerified { + return StateCredentialsSaved + } + if s.AdministratorCount < 1 { + return StateWaitingAdmin + } + return StateActive +} + +type Command struct { + Name string + Args []string +} + +func ParseCommand(raw string) (Command, bool) { + fields := strings.Fields(strings.TrimSpace(raw)) + if len(fields) == 0 { + return Command{}, false + } + name := strings.ToLower(fields[0]) + switch name { + case "/setting", "/设置": + default: + return Command{}, false + } + return Command{Name: name, Args: fields[1:]}, true +} + +type NotableLink struct{ BaseID, SheetID, ViewID string } + +func ParseNotableLink(raw string) (NotableLink, error) { + if len(raw) > 4096 { + return NotableLink{}, errors.New("AI Table link is too long") + } + input := strings.TrimSpace(raw) + u, err := url.Parse(input) + if err != nil { + return NotableLink{}, errors.New("invalid AI Table link") + } + if u.Scheme == "" { + if u.Host != "" || u.User != nil || strings.Contains(input, "\\") { + return NotableLink{}, errors.New("invalid AI Table relative path") + } + relativePath := "/" + strings.TrimPrefix(u.Path, "/") + if !strings.HasPrefix(relativePath, "/i/nodes/") || path.Clean(relativePath) != relativePath { + return NotableLink{}, errors.New("invalid AI Table relative path") + } + u = &url.URL{Scheme: "https", Host: "alidocs.dingtalk.com", Path: relativePath, RawQuery: u.RawQuery} + } + if u.Scheme != "https" { + return NotableLink{}, errors.New("invalid AI Table link") + } + host := strings.ToLower(u.Hostname()) + if host != "alidocs.dingtalk.com" && host != "docs.dingtalk.com" { + return NotableLink{}, errors.New("untrusted AI Table host") + } + base := path.Base(strings.TrimRight(u.Path, "/")) + q := u.Query() + sheetID, err := uniqueNotableQueryValue(q, "sheetId") + if err != nil { + return NotableLink{}, err + } + viewID, err := uniqueNotableQueryValue(q, "viewId") + if err != nil { + return NotableLink{}, err + } + iframeQuery, err := uniqueNotableQueryValue(q, "iframeQuery") + if err != nil { + return NotableLink{}, err + } + if iframeQuery != "" { + nested, parseErr := url.ParseQuery(iframeQuery) + if parseErr != nil { + return NotableLink{}, errors.New("invalid AI Table iframeQuery") + } + nestedSheetID, valueErr := uniqueNotableQueryValue(nested, "sheetId") + if valueErr != nil { + return NotableLink{}, valueErr + } + nestedViewID, valueErr := uniqueNotableQueryValue(nested, "viewId") + if valueErr != nil { + return NotableLink{}, valueErr + } + if sheetID != "" && nestedSheetID != "" && sheetID != nestedSheetID { + return NotableLink{}, errors.New("conflicting AI Table sheet IDs") + } + if viewID != "" && nestedViewID != "" && viewID != nestedViewID { + return NotableLink{}, errors.New("conflicting AI Table view IDs") + } + if sheetID == "" { + sheetID = nestedSheetID + } + if viewID == "" { + viewID = nestedViewID + } + } + result := NotableLink{BaseID: base, SheetID: sheetID, ViewID: viewID} + if result.BaseID == "" || result.BaseID == "." || result.BaseID == ".." || result.SheetID == "" { + return NotableLink{}, errors.New("AI Table link is missing base or sheet") + } + return result, nil +} + +func uniqueNotableQueryValue(values url.Values, key string) (string, error) { + items := values[key] + if len(items) > 1 { + return "", errors.New("conflicting AI Table query values") + } + if len(items) == 0 { + return "", nil + } + return strings.TrimSpace(items[0]), nil +} + +type Runtime interface { + Start(context.Context, string) error + Stop(context.Context) error +} +type Switcher struct { + runtime Runtime + active string +} + +func NewSwitcher(r Runtime, active string) *Switcher { return &Switcher{runtime: r, active: active} } +func (s *Switcher) Switch(ctx context.Context, candidate string) error { + if s == nil || s.runtime == nil { + return errors.New("runtime is required") + } + candidate = strings.TrimSpace(candidate) + if candidate == "" { + return errors.New("candidate is required") + } + old := s.active + if err := s.runtime.Stop(ctx); err != nil { + return err + } + if err := s.runtime.Start(ctx, candidate); err != nil { + if old != "" { + _ = s.runtime.Start(ctx, old) + } + return err + } + s.active = candidate + return nil +} diff --git a/internal/settings/settings_test.go b/internal/settings/settings_test.go new file mode 100644 index 0000000..a0e2803 --- /dev/null +++ b/internal/settings/settings_test.go @@ -0,0 +1,133 @@ +package settings + +import ( + "context" + "errors" + "strings" + "testing" +) + +func TestDetermineState(t *testing.T) { + cases := []struct { + name string + in Snapshot + want SystemState + }{ + {"empty", Snapshot{}, StateUninitialized}, + {"partial", Snapshot{ClientID: "id"}, StateCredentialError}, + {"saved", Snapshot{ClientID: "id", SecretConfigured: true}, StateCredentialsSaved}, + {"verified", Snapshot{ClientID: "id", SecretConfigured: true, CredentialsVerified: true}, StateWaitingAdmin}, + {"active", Snapshot{ClientID: "id", SecretConfigured: true, CredentialsVerified: true, AdministratorCount: 1}, StateActive}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + if got := DetermineState(tc.in); got != tc.want { + t.Fatalf("got %s want %s", got, tc.want) + } + }) + } +} + +func TestParseCommandStrict(t *testing.T) { + yes := []string{"/setting", "/设置", "/setting 123456", "/设置 123456", "/setting language ja", "/设置 language ja", "/setting support", "/设置 question https://alidocs.dingtalk.com/i/nodes/abc"} + for _, raw := range yes { + if c, ok := ParseCommand(raw); !ok || c.Name == "" { + t.Fatalf("must match %q", raw) + } + } + no := []string{"/help", "//help", "/settings", "//setting", "如何设置机器人", "abc /setting", "请解释/setting", "/settiing"} + for _, raw := range no { + if _, ok := ParseCommand(raw); ok { + t.Fatalf("must not match %q", raw) + } + } +} + +func TestParseNotableLink(t *testing.T) { + got, err := ParseNotableLink("https://alidocs.dingtalk.com/i/nodes/base123?sheetId=sheet456&viewId=view789&recordId=row") + if err != nil { + t.Fatal(err) + } + if got.BaseID != "base123" || got.SheetID != "sheet456" || got.ViewID != "view789" { + t.Fatalf("got %+v", got) + } + if _, err = ParseNotableLink("http://evil.example/x?sheetId=s"); err == nil { + t.Fatal("expected rejection") + } +} + +func TestParseNotableLinkAcceptsTrustedHostRelativeTail(t *testing.T) { + for _, raw := range []string{ + "i/nodes/base123?sheetId=sheet456&viewId=view789&recordId=row", + "/i/nodes/base123?sheetId=sheet456&viewId=view789&recordId=row", + } { + got, err := ParseNotableLink(raw) + if err != nil { + t.Fatalf("ParseNotableLink(%q): %v", raw, err) + } + if got.BaseID != "base123" || got.SheetID != "sheet456" || got.ViewID != "view789" { + t.Fatalf("ParseNotableLink(%q)=%+v", raw, got) + } + } +} + +func TestParseNotableLinkDecodesSheetAndViewFromIframeQuery(t *testing.T) { + got, err := ParseNotableLink("i/nodes/base123?iframeQuery=entrance%3Ddata%26sheetId%3Dsheet456%26viewId%3Dview789") + if err != nil { + t.Fatal(err) + } + if got.BaseID != "base123" || got.SheetID != "sheet456" || got.ViewID != "view789" { + t.Fatalf("got=%+v", got) + } +} + +func TestParseNotableLinkRejectsConflictingIframeQueryIDs(t *testing.T) { + _, err := ParseNotableLink("i/nodes/base123?sheetId=sheet-top&iframeQuery=sheetId%3Dsheet-nested%26viewId%3Dview789") + if err == nil || !strings.Contains(err.Error(), "conflicting") { + t.Fatalf("err=%v", err) + } +} + +func TestParseNotableLinkRejectsUnsafeOrAmbiguousRelativeTail(t *testing.T) { + for _, raw := range []string{ + "//evil.example/i/nodes/base?sheetId=sheet", + "evil.example/i/nodes/base?sheetId=sheet", + "../i/nodes/base?sheetId=sheet", + "i/nodes/../base?sheetId=sheet", + "i/nodes/base", + "https://evil.example/i/nodes/base?sheetId=sheet", + } { + if _, err := ParseNotableLink(raw); err == nil { + t.Fatalf("ParseNotableLink(%q) must reject", raw) + } + } +} + +type fakeRuntime struct { + active string + starts []string + fail string +} + +func (f *fakeRuntime) Start(_ context.Context, id string) error { + f.starts = append(f.starts, id) + if id == f.fail { + return errors.New("boom") + } + f.active = id + return nil +} +func (f *fakeRuntime) Stop(_ context.Context) error { f.active = ""; return nil } +func TestSwitcherRollsBack(t *testing.T) { + f := &fakeRuntime{active: "old", fail: "new"} + s := NewSwitcher(f, "old") + if err := s.Switch(context.Background(), "new"); err == nil { + t.Fatal("expected error") + } + if f.active != "old" { + t.Fatalf("active=%q", f.active) + } + if len(f.starts) != 2 || f.starts[0] != "new" || f.starts[1] != "old" { + t.Fatalf("starts=%v", f.starts) + } +} diff --git a/internal/store/postgres/coverage.go b/internal/store/postgres/coverage.go new file mode 100644 index 0000000..4fcc3d7 --- /dev/null +++ b/internal/store/postgres/coverage.go @@ -0,0 +1,82 @@ +package postgres + +import ( + "context" + "crypto/rand" + "fmt" + + "github.com/jackc/pgx/v5" + + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/coverage" +) + +// SaveCoverageDecision implements coverage.Repository. It writes the decision +// and, for uncovered verdicts, atomically creates a pending support case in a +// single transaction. Both writes are idempotent via ON CONFLICT DO NOTHING. +func (s *Store) SaveCoverageDecision(ctx context.Context, d coverage.Decision) error { + if s == nil || s.pool == nil { + return coverage.ErrRepository + } + + decisionID, err := newUUID() + if err != nil { + return fmt.Errorf("coverage decision id: %w", err) + } + + tx, err := s.pool.BeginTx(ctx, pgx.TxOptions{}) + if err != nil { + return fmt.Errorf("coverage tx begin: %w", err) + } + defer func() { _ = tx.Rollback(ctx) }() + + var persistedDecisionID string + err = tx.QueryRow(ctx, `INSERT INTO coverage_decisions + (id, tenant_key, channel, turn_id, evaluator_version, verdict, reason_code, reference_count, top_score) + VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9) + ON CONFLICT (tenant_key, channel, turn_id) + DO UPDATE SET id=coverage_decisions.id + RETURNING id`, + decisionID, d.TenantKey, d.Channel, d.TurnID, + d.EvaluatorVersion, d.Verdict, d.ReasonCode, d.ReferenceCount, d.TopScore).Scan(&persistedDecisionID) + if err != nil { + return fmt.Errorf("coverage insert decision: %w", err) + } + + // Only create support case for uncovered verdicts. + if d.Verdict == coverage.VerdictUncovered { + caseID, err := newUUID() + if err != nil { + return fmt.Errorf("coverage case id: %w", err) + } + _, err = tx.Exec(ctx, `INSERT INTO support_cases + (id, tenant_key, channel, turn_id, coverage_decision_id, status, faq_export_status) + VALUES($1,$2,$3,$4,$5,$6,$7) + ON CONFLICT (tenant_key, channel, turn_id) DO NOTHING`, + caseID, d.TenantKey, d.Channel, d.TurnID, persistedDecisionID, "pending", faqExportStatus(s.faqExportEnabled)) + if err != nil { + return fmt.Errorf("coverage insert support case: %w", err) + } + } + + if err := tx.Commit(ctx); err != nil { + return fmt.Errorf("coverage tx commit: %w", err) + } + return nil +} + +func faqExportStatus(enabled bool) string { + if enabled { + return "pending" + } + return "not_applicable" +} + +// newUUID produces a 32-char hex id. +func newUUID() (string, error) { + var b [16]byte + if _, err := rand.Read(b[:]); err != nil { + return "", err + } + return fmt.Sprintf("%08x%04x%04x%04x%012x", + b[0:4], b[4:6], b[6:8], b[8:10], b[10:16]), nil +} diff --git a/internal/store/postgres/coverage_contract_test.go b/internal/store/postgres/coverage_contract_test.go new file mode 100644 index 0000000..0b53bfa --- /dev/null +++ b/internal/store/postgres/coverage_contract_test.go @@ -0,0 +1,197 @@ +// Source-level contract tests for the coverage repository SQL. +// No real database connection is used. +package postgres + +import ( + "os" + "regexp" + "strings" + "testing" +) + +func readCoverageSource(t *testing.T) string { + t.Helper() + data, err := os.ReadFile("coverage.go") + if err != nil { + t.Fatalf("read coverage.go: %v", err) + } + return string(data) +} + +func extractSQLFromCoverage(t *testing.T) []string { + t.Helper() + src := readCoverageSource(t) + var sqls []string + re := regexp.MustCompile("`([^`]*)`") + for _, m := range re.FindAllStringSubmatch(src, -1) { + upper := strings.ToUpper(m[1]) + if strings.Contains(upper, "SELECT") || strings.Contains(upper, "UPDATE") || + strings.Contains(upper, "INSERT") || strings.Contains(upper, "DELETE") { + sqls = append(sqls, m[1]) + } + } + return sqls +} + +func TestCoverageRepoInsertsIntoCoverageDecisions(t *testing.T) { + // Find the INSERT INTO coverage_decisions SQL in coverage.go + sqls := extractSQLFromCoverage(t) + var found string + for _, sql := range sqls { + upper := strings.ToUpper(sql) + if strings.Contains(upper, "INSERT INTO COVERAGE_DECISIONS") { + found = sql + break + } + } + if found == "" { + t.Fatal("INSERT INTO coverage_decisions SQL not found in coverage.go") + } + + requiredCols := []string{ + "id", "tenant_key", "channel", "turn_id", + "evaluator_version", "verdict", "reason_code", "reference_count", "top_score", + } + upper := strings.ToUpper(found) + for _, col := range requiredCols { + if !strings.Contains(upper, strings.ToUpper(col)) { + t.Errorf("INSERT INTO coverage_decisions missing column %q", col) + } + } +} + +func TestCoverageRepoReplayReturnsPersistedDecisionIDForSupportCase(t *testing.T) { + sqls := extractSQLFromCoverage(t) + var decisionInsert string + for _, sql := range sqls { + if strings.Contains(strings.ToUpper(sql), "INSERT INTO COVERAGE_DECISIONS") { + decisionInsert = strings.ToUpper(sql) + break + } + } + if decisionInsert == "" { + t.Fatal("INSERT INTO coverage_decisions SQL not found") + } + if !strings.Contains(decisionInsert, "ON CONFLICT (TENANT_KEY, CHANNEL, TURN_ID)") { + t.Fatal("decision upsert must use the scoped idempotency key") + } + if !strings.Contains(decisionInsert, "DO UPDATE") || !strings.Contains(decisionInsert, "RETURNING ID") { + t.Fatal("decision upsert must return the persisted ID on both insert and replay") + } + + src := readCoverageSource(t) + if !strings.Contains(src, "persistedDecisionID") { + t.Fatal("support case must use the persisted decision ID") + } + if !strings.Contains(src, "d.TurnID, persistedDecisionID") { + t.Fatal("support case INSERT must reference persistedDecisionID, not a new conflicting ID") + } +} + +func TestCoverageRepoInsertsSupportCaseOnlyForUncovered(t *testing.T) { + sqls := extractSQLFromCoverage(t) + var insertSQL string + for _, sql := range sqls { + upper := strings.ToUpper(sql) + if strings.Contains(upper, "INSERT INTO SUPPORT_CASES") { + insertSQL = sql + break + } + } + if insertSQL == "" { + t.Fatal("INSERT INTO support_cases SQL not found in coverage.go") + } + + upper := strings.ToUpper(insertSQL) + requiredCols := []string{ + "id", "tenant_key", "channel", "turn_id", + "coverage_decision_id", "status", + } + for _, col := range requiredCols { + if !strings.Contains(upper, strings.ToUpper(col)) { + t.Errorf("INSERT INTO support_cases missing column %q", col) + } + } + // Must have ON CONFLICT for idempotency + if !strings.Contains(upper, "ON CONFLICT") { + t.Error("support_cases INSERT must use ON CONFLICT for idempotency") + } + if !strings.Contains(upper, "DO NOTHING") { + t.Error("support_cases ON CONFLICT must use DO NOTHING") + } + + // Check that the support_cases INSERT is guarded by a verdict check + src := readCoverageSource(t) + if !strings.Contains(src, "VerdictUncovered") { + t.Error("support_cases INSERT must be guarded by uncovered verdict check") + } +} + +func TestCoverageRepoFAQExportStatusFollowsRuntimeFlag(t *testing.T) { + if got := faqExportStatus(false); got != "not_applicable" { + t.Fatalf("disabled status=%q", got) + } + if got := faqExportStatus(true); got != "pending" { + t.Fatalf("enabled status=%q", got) + } +} + +func TestCoverageRepoUsesSingleTransaction(t *testing.T) { + src := readCoverageSource(t) + // Must use BeginTx + if !strings.Contains(src, "BeginTx") { + t.Error("SaveCoverageDecision must use a transaction (BeginTx)") + } + // Must commit + if !strings.Contains(src, "Commit(ctx)") { + t.Error("SaveCoverageDecision must commit the transaction") + } + // Must rollback on error + if !strings.Contains(src, "Rollback(ctx)") { + t.Error("SaveCoverageDecision must rollback on error") + } +} + +func TestCoverageRepoNoReservedWords(t *testing.T) { + sqls := extractSQLFromCoverage(t) + for _, sql := range sqls { + upper := strings.ToUpper(sql) + // Check for bare "references" as column name (not references_json) + // Remove references_json first + scrubbed := regexp.MustCompile("(?i)\\breferences_json\\b").ReplaceAllString(upper, "") + // Also remove REFERENCES as foreign key keyword + scrubbed = regexp.MustCompile("(?i)\\bREFERENCES\\s+(COVERAGE_DECISIONS|TURNS)\\b").ReplaceAllString(scrubbed, "") + if regexp.MustCompile("(?i)\\bREFERENCES\\b").MatchString(scrubbed) { + t.Errorf("SQL uses reserved word 'references' as identifier: %s", sql) + } + } +} + +func TestCoverageRepoNoQuestionAnswerBodies(t *testing.T) { + sqls := extractSQLFromCoverage(t) + joined := strings.ToUpper(strings.Join(sqls, " ")) + for _, forbidden := range []string{"QUESTION", "ANSWER_TEXT", "REFERENCE_CONTENT", "ANSWER_CONTENT"} { + if strings.Contains(joined, forbidden) { + t.Errorf("coverage repository SQL must not dupe question/answer/reference bodies: found %q", forbidden) + } + } +} + +func TestCoverageRepoSavesTenantChannelTurnScope(t *testing.T) { + src := readCoverageSource(t) + // Must pass tenant, channel, turn values to the INSERT + if !strings.Contains(src, "d.TenantKey") || !strings.Contains(src, "d.Channel") || !strings.Contains(src, "d.TurnID") { + t.Error("SaveCoverageDecision must use d.TenantKey, d.Channel, d.TurnID for tenant/channel/turn scope") + } + if !strings.Contains(src, "d.ReferenceCount") { + t.Error("SaveCoverageDecision must persist d.ReferenceCount") + } +} + +func TestCoverageRepoNilSafe(t *testing.T) { + src := readCoverageSource(t) + // Must check for nil store/pool + if !strings.Contains(src, "s == nil") || !strings.Contains(src, "s.pool == nil") { + t.Error("SaveCoverageDecision must guard against nil store/pool") + } +} diff --git a/internal/store/postgres/directory.go b/internal/store/postgres/directory.go new file mode 100644 index 0000000..a5dfffd --- /dev/null +++ b/internal/store/postgres/directory.go @@ -0,0 +1,82 @@ +package postgres + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "strings" + "time" + + "github.com/jackc/pgx/v5" + + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/directory" +) + +func (s *Store) LookupDirectoryProfile(ctx context.Context, tenantKey, staffID string) (directory.Profile, bool, error) { + tenantKey = strings.TrimSpace(tenantKey) + staffID = strings.TrimSpace(staffID) + if tenantKey == "" || staffID == "" { + return directory.Profile{}, false, errors.New("tenant and staff id are required") + } + var profile directory.Profile + var departmentIDs []byte + err := s.pool.QueryRow(ctx, `SELECT staff_id,union_id,name,nickname,job_title,department_ids,department_name,main_department_name,region,employment_status,source,synced_at + FROM directory_profiles WHERE tenant_key=$1 AND staff_id=$2`, tenantKey, staffID).Scan( + &profile.StaffID, &profile.UnionID, &profile.Name, &profile.Nickname, &profile.JobTitle, + &departmentIDs, &profile.DepartmentName, &profile.MainDepartmentName, &profile.Region, + &profile.EmploymentStatus, &profile.Source, &profile.SyncedAt, + ) + if errors.Is(err, pgx.ErrNoRows) { + return directory.Profile{}, false, nil + } + if err != nil { + return directory.Profile{}, false, fmt.Errorf("lookup directory profile: %w", err) + } + if err := json.Unmarshal(departmentIDs, &profile.DepartmentIDs); err != nil { + return directory.Profile{}, false, errors.New("decode directory department ids") + } + return profile, true, nil +} + +func (s *Store) UpsertDirectoryProfiles(ctx context.Context, tenantKey string, profiles []directory.Profile) error { + tenantKey = strings.TrimSpace(tenantKey) + if tenantKey == "" || len(profiles) == 0 { + return errors.New("tenant and non-empty directory profiles are required") + } + for _, profile := range profiles { + if strings.TrimSpace(profile.StaffID) == "" || strings.TrimSpace(profile.Name) == "" { + return errors.New("directory profile requires staff id and name") + } + } + tx, err := s.pool.BeginTx(ctx, pgx.TxOptions{}) + if err != nil { + return err + } + defer func() { _ = tx.Rollback(ctx) }() + for _, profile := range profiles { + departmentIDs, marshalErr := json.Marshal(profile.DepartmentIDs) + if marshalErr != nil { + return errors.New("encode directory department ids") + } + syncedAt := profile.SyncedAt + if syncedAt.IsZero() { + syncedAt = time.Now().UTC() + } + _, err = tx.Exec(ctx, `INSERT INTO directory_profiles + (tenant_key,staff_id,union_id,name,nickname,job_title,department_ids,department_name,main_department_name,region,employment_status,source,synced_at) + VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13) + ON CONFLICT (tenant_key,staff_id) DO UPDATE SET + union_id=EXCLUDED.union_id,name=EXCLUDED.name,nickname=EXCLUDED.nickname,job_title=EXCLUDED.job_title, + department_ids=EXCLUDED.department_ids,department_name=EXCLUDED.department_name, + main_department_name=EXCLUDED.main_department_name,region=EXCLUDED.region, + employment_status=EXCLUDED.employment_status,source=EXCLUDED.source,synced_at=EXCLUDED.synced_at,updated_at=NOW()`, + tenantKey, profile.StaffID, profile.UnionID, profile.Name, profile.Nickname, profile.JobTitle, + departmentIDs, profile.DepartmentName, profile.MainDepartmentName, profile.Region, + profile.EmploymentStatus, profile.Source, syncedAt) + if err != nil { + return fmt.Errorf("upsert directory profile: %w", err) + } + } + return tx.Commit(ctx) +} diff --git a/internal/store/postgres/directory_contract_test.go b/internal/store/postgres/directory_contract_test.go new file mode 100644 index 0000000..88bc003 --- /dev/null +++ b/internal/store/postgres/directory_contract_test.go @@ -0,0 +1,30 @@ +package postgres + +import ( + "os" + "strings" + "testing" +) + +func TestDirectoryStoreSQLContract(t *testing.T) { + raw, err := os.ReadFile("directory.go") + if err != nil { + t.Fatalf("read directory.go: %v", err) + } + src := strings.ToUpper(string(raw)) + for _, required := range []string{ + "SELECT STAFF_ID,UNION_ID,NAME,NICKNAME,JOB_TITLE,DEPARTMENT_IDS,DEPARTMENT_NAME,MAIN_DEPARTMENT_NAME,REGION,EMPLOYMENT_STATUS,SOURCE,SYNCED_AT", + "FROM DIRECTORY_PROFILES", + "INSERT INTO DIRECTORY_PROFILES", + "ON CONFLICT (TENANT_KEY,STAFF_ID) DO UPDATE", + } { + if !strings.Contains(src, required) { + t.Errorf("directory.go missing SQL contract %q", required) + } + } + for _, forbidden := range []string{"MOBILE", "EMAIL", "CLIENT_SECRET", "ACCESS_TOKEN", "RAW_PAYLOAD"} { + if strings.Contains(src, forbidden) { + t.Errorf("directory store contains forbidden sensitive field %q", forbidden) + } + } +} diff --git a/internal/store/postgres/faq_exports.go b/internal/store/postgres/faq_exports.go new file mode 100644 index 0000000..feab18a --- /dev/null +++ b/internal/store/postgres/faq_exports.go @@ -0,0 +1,143 @@ +package postgres + +import ( + "context" + "errors" + "fmt" + "strings" + "time" + + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/faqtable" +) + +var ( + errFAQExportNilStore = errors.New("faq export store is unavailable") + errFAQCaseIDRequired = errors.New("faq export case id is required") + errFAQRecordIDRequired = errors.New("faq export record id is required") + errFAQRowsAffected = errors.New("faq export RowsAffected != 1") + errFAQFailureCodeInvalid = errors.New("faq export only remote_faq_table_insert_failed is accepted") +) + +type FAQExportRepository struct{ store *Store } + +var _ faqtable.ExportRepository = (*FAQExportRepository)(nil) + +func NewFAQExportRepository(store *Store) (*FAQExportRepository, error) { + if store == nil || store.pool == nil { + return nil, errFAQExportNilStore + } + return &FAQExportRepository{store: store}, nil +} + +func (r *FAQExportRepository) Claim(ctx context.Context, limit, maxAttempts int, staleBefore time.Time) ([]faqtable.PendingExport, error) { + if r == nil || r.store == nil || r.store.pool == nil { + return nil, errFAQExportNilStore + } + rows, err := r.store.pool.Query(ctx, ` + WITH candidates AS ( + SELECT sc.id + FROM support_cases sc + WHERE (sc.faq_export_status = 'pending' + OR (sc.faq_export_status = 'export_failed' AND (sc.faq_next_attempt_at IS NULL OR sc.faq_next_attempt_at <= NOW())) + OR (sc.faq_export_status = 'exporting' AND sc.faq_last_attempt_at < $3)) + AND sc.faq_export_attempts < $2 + ORDER BY sc.created_at, sc.id + LIMIT $1 + FOR UPDATE SKIP LOCKED + ), + claimed AS ( + UPDATE support_cases sc + SET faq_export_status = 'exporting', + faq_export_attempts = sc.faq_export_attempts + 1, + faq_last_attempt_at = NOW(), + faq_next_attempt_at = NULL, + faq_failure_code = '', + updated_at = NOW() + FROM candidates c + WHERE sc.id = c.id + RETURNING sc.id, sc.faq_export_attempts, sc.tenant_key, sc.channel, sc.turn_id, sc.created_at + ) + SELECT cl.id, cl.faq_export_attempts, t.question, + COALESCE(m.actor_name_snapshot, ''), COALESCE(m.actor_union_id_snapshot, '') + FROM claimed cl + JOIN turns t ON t.id = cl.turn_id + AND t.tenant_key = cl.tenant_key AND t.channel = cl.channel + JOIN messages m ON m.id = t.request_message_id + AND m.tenant_key = cl.tenant_key AND m.channel = cl.channel + ORDER BY cl.created_at, cl.id`, limit, maxAttempts, staleBefore) + if err != nil { + return nil, fmt.Errorf("faq export claim: %w", err) + } + defer rows.Close() + + var exports []faqtable.PendingExport + for rows.Next() { + var id, question, askerName, askerUnionID string + var attempts int + if err := rows.Scan(&id, &attempts, &question, &askerName, &askerUnionID); err != nil { + return nil, fmt.Errorf("faq export claim scan: %w", err) + } + exports = append(exports, faqtable.PendingExport{ + CaseID: id, Attempts: attempts, + Row: faqtable.Row{StandardQuestion: question, OriginalQuestion: question, AskerName: askerName, AskerUnionID: askerUnionID}, + }) + } + if err := rows.Err(); err != nil { + return nil, fmt.Errorf("faq export claim rows: %w", err) + } + return exports, nil +} + +func (r *FAQExportRepository) MarkExported(ctx context.Context, caseID, recordID string) error { + if strings.TrimSpace(caseID) == "" { + return errFAQCaseIDRequired + } + if strings.TrimSpace(recordID) == "" { + return errFAQRecordIDRequired + } + if r == nil || r.store == nil || r.store.pool == nil { + return errFAQExportNilStore + } + tag, err := r.store.pool.Exec(ctx, ` + UPDATE support_cases + SET faq_export_status = 'exported', faq_record_id = $2, + faq_exported_at = NOW(), faq_failure_code = '', faq_next_attempt_at = NULL, + updated_at = NOW() + WHERE id = $1 AND faq_export_status = 'exporting'`, caseID, recordID) + if err != nil { + return fmt.Errorf("faq export mark exported: %w", err) + } + if tag.RowsAffected() != 1 { + return errFAQRowsAffected + } + return nil +} + +func (r *FAQExportRepository) MarkFailed(ctx context.Context, caseID, failureCode string) error { + if strings.TrimSpace(caseID) == "" { + return errFAQCaseIDRequired + } + if failureCode != faqtable.FailureCodeRemoteInsertFailed { + return errFAQFailureCodeInvalid + } + if r == nil || r.store == nil || r.store.pool == nil { + return errFAQExportNilStore + } + tag, err := r.store.pool.Exec(ctx, ` + UPDATE support_cases + SET faq_export_status = 'export_failed', faq_failure_code = $2, + faq_next_attempt_at = NOW() + CASE + WHEN faq_export_attempts <= 1 THEN '5 seconds'::interval + WHEN faq_export_attempts = 2 THEN '15 seconds'::interval + WHEN faq_export_attempts = 3 THEN '45 seconds'::interval + ELSE '5 minutes'::interval END, + updated_at = NOW() + WHERE id = $1 AND faq_export_status = 'exporting'`, caseID, failureCode) + if err != nil { + return fmt.Errorf("faq export mark failed: %w", err) + } + if tag.RowsAffected() != 1 { + return errFAQRowsAffected + } + return nil +} diff --git a/internal/store/postgres/faq_exports_contract_test.go b/internal/store/postgres/faq_exports_contract_test.go new file mode 100644 index 0000000..13d167d --- /dev/null +++ b/internal/store/postgres/faq_exports_contract_test.go @@ -0,0 +1,48 @@ +package postgres + +import ( + "os" + "strings" + "testing" +) + +func readFAQExportsSource(t *testing.T) string { + t.Helper() + data, err := os.ReadFile("faq_exports.go") + if err != nil { + t.Fatalf("read faq_exports.go: %v", err) + } + return strings.ToUpper(string(data)) +} + +func TestFAQExportsClaimIsAtomicScopedAndBounded(t *testing.T) { + src := readFAQExportsSource(t) + for _, fragment := range []string{ + "WITH CANDIDATES", "FOR UPDATE SKIP LOCKED", "UPDATE SUPPORT_CASES", + "FAQ_EXPORT_STATUS = 'EXPORTING'", "FAQ_EXPORT_ATTEMPTS", + "T.TENANT_KEY = CL.TENANT_KEY", "T.CHANNEL = CL.CHANNEL", + "M.TENANT_KEY = CL.TENANT_KEY", "M.CHANNEL = CL.CHANNEL", + "T.QUESTION", "M.ACTOR_NAME_SNAPSHOT", "M.ACTOR_UNION_ID_SNAPSHOT", + } { + if !strings.Contains(src, fragment) { + t.Errorf("claim contract missing %q", fragment) + } + } + if strings.Contains(src, "T.ANSWER") { + t.Fatal("FAQ export must not read the generated answer") + } +} + +func TestFAQExportsSuccessAndFailureTransitionsAreGuarded(t *testing.T) { + src := readFAQExportsSource(t) + for _, fragment := range []string{ + "FAQ_EXPORT_STATUS = 'EXPORTED'", "FAQ_RECORD_ID = $2", "FAQ_EXPORTED_AT = NOW()", + "FAQ_EXPORT_STATUS = 'EXPORT_FAILED'", "FAQ_FAILURE_CODE = $2", "FAQ_NEXT_ATTEMPT_AT", + "WHERE ID = $1 AND FAQ_EXPORT_STATUS = 'EXPORTING'", + "REMOTE_FAQ_TABLE_INSERT_FAILED", + } { + if !strings.Contains(src, fragment) { + t.Errorf("transition contract missing %q", fragment) + } + } +} diff --git a/internal/store/postgres/feedback.go b/internal/store/postgres/feedback.go index 4b2dfd4..af9ea7d 100644 --- a/internal/store/postgres/feedback.go +++ b/internal/store/postgres/feedback.go @@ -82,6 +82,11 @@ func (s *Store) RecordFeedback(ctx context.Context, record feedback.Record) (fee if command.RowsAffected() != 1 { return feedback.Result{}, errors.New("insert feedback state affected unexpected rows") } + if record.Value == feedback.ValueDown { + if err = s.ensureFeedbackSupportCase(ctx, tx, record, record.ID, turnID); err != nil { + return feedback.Result{}, err + } + } if err = tx.Commit(ctx); err != nil { return feedback.Result{}, fmt.Errorf("commit feedback create: %w", err) } @@ -92,6 +97,11 @@ func (s *Store) RecordFeedback(ctx context.Context, record feedback.Record) (fee } if sameFeedbackState(existingValue, existingReason, record.Value, record.ReasonCode) { + if record.Value == feedback.ValueDown { + if err = s.ensureFeedbackSupportCase(ctx, tx, record, existingID, turnID); err != nil { + return feedback.Result{}, err + } + } if err = tx.Commit(ctx); err != nil { return feedback.Result{}, fmt.Errorf("commit feedback replay: %w", err) } @@ -108,12 +118,42 @@ func (s *Store) RecordFeedback(ctx context.Context, record feedback.Record) (fee if command.RowsAffected() != 1 { return feedback.Result{}, errors.New("update feedback state affected unexpected rows") } + if record.Value == feedback.ValueDown { + if err = s.ensureFeedbackSupportCase(ctx, tx, record, existingID, turnID); err != nil { + return feedback.Result{}, err + } + } if err = tx.Commit(ctx); err != nil { return feedback.Result{}, fmt.Errorf("commit feedback change: %w", err) } return feedback.Result{Changed: true, Value: record.Value, ReasonCode: record.ReasonCode}, nil } +func (s *Store) ensureFeedbackSupportCase(ctx context.Context, tx pgx.Tx, record feedback.Record, feedbackID, turnID string) error { + var decisionID *string + if err := tx.QueryRow(ctx, `SELECT (SELECT id FROM coverage_decisions + WHERE tenant_key=$1 AND channel=$2 AND turn_id=$3)`, + record.TenantKey, record.Channel, turnID, + ).Scan(&decisionID); err != nil { + return fmt.Errorf("find feedback coverage decision: %w", err) + } + caseID, err := newUUID() + if err != nil { + return fmt.Errorf("generate feedback support case ID: %w", err) + } + _, err = tx.Exec(ctx, `INSERT INTO support_cases + (id,tenant_key,channel,turn_id,coverage_decision_id,status,faq_export_status,trigger_type,trigger_feedback_id) + VALUES($1,$2,$3,$4,$5,'pending',$6,'feedback_down',$7) + ON CONFLICT (tenant_key,channel,turn_id) DO NOTHING`, + caseID, record.TenantKey, record.Channel, turnID, decisionID, + faqExportStatus(s.faqExportEnabled), feedbackID, + ) + if err != nil { + return fmt.Errorf("insert feedback support case: %w", err) + } + return nil +} + func validateFeedbackRecord(record feedback.Record) error { if record.ID == "" || record.ActorID == "" || record.TenantKey == "" || record.Channel == "" || record.ExternalActorID == "" || record.OutTrackID == "" || record.Source != feedback.SourceDingTalkCard { diff --git a/internal/store/postgres/feedback_test.go b/internal/store/postgres/feedback_test.go index 3602f2e..86eabc6 100644 --- a/internal/store/postgres/feedback_test.go +++ b/internal/store/postgres/feedback_test.go @@ -75,3 +75,29 @@ func TestSameFeedbackState(t *testing.T) { t.Fatal("value change must be a state change") } } + +func TestFeedbackDownvoteEnsuresIdempotentSupportCaseInsideTransaction(t *testing.T) { + data, err := os.ReadFile("feedback.go") + if err != nil { + t.Fatal(err) + } + source := strings.ToUpper(string(data)) + for _, required := range []string{ + "ENSUREFEEDBACKSUPPORTCASE", + "SELECT ID FROM COVERAGE_DECISIONS", + "TENANT_KEY=$1 AND CHANNEL=$2 AND TURN_ID=$3", + "INSERT INTO SUPPORT_CASES", + "TRIGGER_TYPE", + "TRIGGER_FEEDBACK_ID", + "'FEEDBACK_DOWN'", + "ON CONFLICT (TENANT_KEY,CHANNEL,TURN_ID) DO NOTHING", + "FAQEXPORTSTATUS(S.FAQEXPORTENABLED)", + } { + if !strings.Contains(source, required) { + t.Errorf("feedback support wiring missing %q", required) + } + } + if strings.Count(source, "ENSUREFEEDBACKSUPPORTCASE") < 4 { + t.Fatal("create, replay, and changed-down paths must all ensure the same idempotent support case") + } +} diff --git a/internal/store/postgres/message_snapshot_contract_test.go b/internal/store/postgres/message_snapshot_contract_test.go new file mode 100644 index 0000000..706eee1 --- /dev/null +++ b/internal/store/postgres/message_snapshot_contract_test.go @@ -0,0 +1,27 @@ +package postgres + +import ( + "os" + "strings" + "testing" +) + +func TestBeginTurnStoresDirectorySnapshotsAndGroupTitle(t *testing.T) { + raw, err := os.ReadFile("store.go") + if err != nil { + t.Fatalf("read store.go: %v", err) + } + src := strings.ToUpper(string(raw)) + for _, required := range []string{ + "DEPARTMENT_SNAPSHOT,REGION_SNAPSHOT", + "ACTOR_UNION_ID_SNAPSHOT", + "TURN.DEPARTMENTSNAPSHOT", + "TURN.REGIONSNAPSHOT", + "TURN.ACTORUNIONIDSNAPSHOT", + "TURN.CONVERSATIONTITLE", + } { + if !strings.Contains(src, required) { + t.Errorf("store.go missing %q", required) + } + } +} diff --git a/internal/store/postgres/operational_status.go b/internal/store/postgres/operational_status.go new file mode 100644 index 0000000..27c1a01 --- /dev/null +++ b/internal/store/postgres/operational_status.go @@ -0,0 +1,54 @@ +package postgres + +import ( + "context" + "time" +) + +const operationalStatusSQL = ` +SELECT + (SELECT COUNT(*) FROM question_table_exports WHERE tenant_key = $1 AND status IN ('pending','exporting')), + (SELECT COUNT(*) FROM question_table_exports WHERE tenant_key = $1 AND status = 'export_failed'), + (SELECT MAX(exported_at) FROM question_table_exports WHERE tenant_key = $1 AND status = 'exported'), + (SELECT COUNT(*) FROM support_cases WHERE tenant_key = $1 AND faq_export_status IN ('pending','exporting')), + (SELECT COUNT(*) FROM support_cases WHERE tenant_key = $1 AND faq_export_status = 'export_failed'), + (SELECT MAX(faq_exported_at) FROM support_cases WHERE tenant_key = $1 AND faq_export_status = 'exported'), + (SELECT COUNT(*) FROM support_cases WHERE tenant_key = $1 AND status IN ('pending','notifying') AND faq_export_status = 'exported'), + (SELECT COUNT(*) FROM support_cases WHERE tenant_key = $1 AND status = 'notification_failed'), + (SELECT MAX(notified_at) FROM support_cases WHERE tenant_key = $1 AND status = 'notified')` + +type OperationalMetrics struct { + QuestionPending, QuestionFailed int + FAQPending, FAQFailed int + SupportPending, SupportFailed int + LastQuestionSuccess time.Time + LastFAQSuccess time.Time + LastSupportSuccess time.Time +} + +func (s *Store) Ping(ctx context.Context) error { + if s == nil || s.pool == nil { + return context.Canceled + } + return s.pool.Ping(ctx) +} + +func (s *Store) ReadOperationalMetrics(ctx context.Context, tenant string) (OperationalMetrics, error) { + var value OperationalMetrics + var questionSuccess, faqSuccess, supportSuccess *time.Time + err := s.pool.QueryRow(ctx, operationalStatusSQL, tenant).Scan( + &value.QuestionPending, &value.QuestionFailed, &questionSuccess, + &value.FAQPending, &value.FAQFailed, &faqSuccess, + &value.SupportPending, &value.SupportFailed, &supportSuccess, + ) + if questionSuccess != nil { + value.LastQuestionSuccess = *questionSuccess + } + if faqSuccess != nil { + value.LastFAQSuccess = *faqSuccess + } + if supportSuccess != nil { + value.LastSupportSuccess = *supportSuccess + } + return value, err +} diff --git a/internal/store/postgres/operational_status_test.go b/internal/store/postgres/operational_status_test.go new file mode 100644 index 0000000..1a435b8 --- /dev/null +++ b/internal/store/postgres/operational_status_test.go @@ -0,0 +1,29 @@ +package postgres + +import ( + "strings" + "testing" +) + +func TestOperationalStatusSQLIsTenantScopedAndReadOnly(t *testing.T) { + upper := strings.ToUpper(operationalStatusSQL) + for _, want := range []string{ + "QUESTION_TABLE_EXPORTS", + "SUPPORT_CASES", + "TENANT_KEY = $1", + "FAQ_EXPORT_STATUS", + "NOTIFICATION_FAILED", + "MAX(EXPORTED_AT)", + "MAX(FAQ_EXPORTED_AT)", + "MAX(NOTIFIED_AT)", + } { + if !strings.Contains(upper, want) { + t.Errorf("status SQL missing %q", want) + } + } + for _, forbidden := range []string{"INSERT ", "UPDATE ", "DELETE ", "FOR UPDATE"} { + if strings.Contains(upper, forbidden) { + t.Errorf("status SQL must be read-only; found %q", forbidden) + } + } +} diff --git a/internal/store/postgres/outbox_contract_test.go b/internal/store/postgres/outbox_contract_test.go new file mode 100644 index 0000000..1671911 --- /dev/null +++ b/internal/store/postgres/outbox_contract_test.go @@ -0,0 +1,208 @@ +// Package postgres contains source-level contract tests for the +// question_table_exports outbox: the store must enqueue inside +// FinishTurn's transaction, guarded by shouldCreateAnswerMessage. +// No database connection is required. +package postgres + +import ( + "os" + "strings" + "testing" + + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/core" +) + +// TestFinishTurnBeginTurnSnapshot verifies that the BeginTurn INSERT +// into messages includes trigger_person_snapshot, actor_union_id_snapshot, +// department_snapshot, and region_snapshot columns. +func TestFinishTurnBeginTurnSnapshot(t *testing.T) { + data, err := os.ReadFile("store.go") + if err != nil { + t.Fatalf("read store.go: %v", err) + } + src := string(data) + + // The BeginTurn message INSERT must include trigger_person_snapshot + if !strings.Contains(src, "trigger_person_snapshot") { + t.Error("BeginTurn message INSERT must include trigger_person_snapshot column") + } + if !strings.Contains(src, "actor_union_id_snapshot") { + t.Error("BeginTurn message INSERT must include actor_union_id_snapshot column") + } + if !strings.Contains(src, "department_snapshot") { + t.Error("BeginTurn message INSERT must include department_snapshot column") + } + if !strings.Contains(src, "region_snapshot") { + t.Error("BeginTurn message INSERT must include region_snapshot column") + } + + // The VALUES arguments must include turn.ActorUnionIDSnapshot + if !strings.Contains(src, "turn.ActorUnionIDSnapshot") { + t.Error("BeginTurn message INSERT VALUES must include turn.ActorUnionIDSnapshot argument") + } +} + +func TestShouldEnqueueQuestionTableExportOnlyForDingTalkSucceededAnswers(t *testing.T) { + tests := []struct { + name string + turn core.Turn + want bool + }{ + {name: "dingtalk success", turn: core.Turn{Channel: "dingtalk", Status: "succeeded", Answer: "answer", AnswerMessageID: "answer-1"}, want: true}, + {name: "dingtalk case and space", turn: core.Turn{Channel: " DingTalk ", Status: "succeeded", Answer: "answer", AnswerMessageID: "answer-1"}, want: true}, + {name: "web success", turn: core.Turn{Channel: "web", Status: "succeeded", Answer: "answer", AnswerMessageID: "answer-1"}}, + {name: "http success", turn: core.Turn{Channel: "http", Status: "succeeded", Answer: "answer", AnswerMessageID: "answer-1"}}, + {name: "empty channel", turn: core.Turn{Status: "succeeded", Answer: "answer", AnswerMessageID: "answer-1"}}, + {name: "dingtalk failed", turn: core.Turn{Channel: "dingtalk", Status: "failed", Answer: "answer", AnswerMessageID: "answer-1"}}, + {name: "dingtalk empty answer", turn: core.Turn{Channel: "dingtalk", Status: "succeeded", Answer: " ", AnswerMessageID: "answer-1"}}, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + if got := shouldEnqueueQuestionTableExport(tc.turn, true); got != tc.want { + t.Fatalf("shouldEnqueueQuestionTableExport()=%v, want %v", got, tc.want) + } + if got := shouldEnqueueQuestionTableExport(tc.turn, false); got { + t.Fatal("disabled question-table export must not enqueue") + } + }) + } +} + +// TestFinishTurnOutboxInsideTransaction verifies that the +// question_table_exports INSERT is inside the FinishTurn transaction +// (between tx begin and tx commit), uses 'pending' status, and has +// ON CONFLICT (tenant_key,channel,turn_id) DO NOTHING. +func TestFinishTurnOutboxInsideTransaction(t *testing.T) { + data, err := os.ReadFile("store.go") + if err != nil { + t.Fatalf("read store.go: %v", err) + } + src := string(data) + + // Extract the FinishTurn function body using deterministic boundaries + finishStart := strings.Index(src, "func (s *Store) FinishTurn(") + if finishStart < 0 { + t.Fatal("cannot find FinishTurn signature") + } + finishEnd := strings.Index(src[finishStart:], "func (s *Store) RecordDelivery(") + if finishEnd < 0 { + t.Fatal("cannot find RecordDelivery signature after FinishTurn") + } + body := src[finishStart : finishStart+finishEnd] + + // The outbox INSERT must use question_table_exports + if !strings.Contains(body, "question_table_exports") { + t.Error("FinishTurn must INSERT into question_table_exports") + } + + // Must use 'pending' status for the outbox + if !strings.Contains(body, "'pending'") { + t.Error("question_table_exports INSERT must use status='pending'") + } + + // Must use ON CONFLICT (tenant_key,channel,turn_id) DO NOTHING + if !strings.Contains(body, "ON CONFLICT (tenant_key,channel,turn_id) DO NOTHING") && + !strings.Contains(body, "ON CONFLICT (tenant_key, channel, turn_id) DO NOTHING") { + t.Error("question_table_exports INSERT must use ON CONFLICT (tenant_key,channel,turn_id) DO NOTHING") + } + + // The outbox INSERT must be after the tx begin and before tx commit + txBegin := strings.Index(body, "BeginTx") + txCommit := strings.Index(body, "tx.Commit") + outboxPos := strings.Index(body, "question_table_exports") + if txBegin < 0 || txCommit < 0 || outboxPos < 0 { + t.Fatal("cannot locate transaction boundaries or outbox insert") + } + if outboxPos < txBegin || outboxPos > txCommit { + t.Error("question_table_exports INSERT must be inside the transaction (between BeginTx and Commit)") + } +} + +// TestFinishTurnOutboxGuardedByShouldCreateAnswerMessage verifies that +// the outbox INSERT is structurally inside the shouldCreateAnswerMessage +// guard. Failed, processing, and empty-answer turns must not enqueue. +func TestFinishTurnOutboxGuardedByShouldCreateAnswerMessage(t *testing.T) { + data, err := os.ReadFile("store.go") + if err != nil { + t.Fatalf("read store.go: %v", err) + } + src := string(data) + + // The shouldCreateAnswerMessage function must guard on status succeeded, + // non-empty answer, and non-empty answer message ID + if !strings.Contains(src, "shouldCreateAnswerMessage") { + t.Fatal("shouldCreateAnswerMessage function must exist") + } + + // Extract shouldCreateAnswerMessage function body using deterministic boundaries + shouldFuncStart := strings.Index(src, "func shouldCreateAnswerMessage(") + if shouldFuncStart < 0 { + t.Fatal("cannot find shouldCreateAnswerMessage signature") + } + // Find the closing brace of the function: the first top-level `}` after the signature + // The function body is simple: one return statement, so find the `}` that follows + shouldFuncBodyStart := strings.Index(src[shouldFuncStart:], "{") + if shouldFuncBodyStart < 0 { + t.Fatal("cannot find shouldCreateAnswerMessage opening brace") + } + shouldFuncBodyStart += shouldFuncStart + 1 // position after "{" + shouldFuncEnd := strings.Index(src[shouldFuncBodyStart:], "\n}\n") + if shouldFuncEnd < 0 { + t.Fatal("cannot find shouldCreateAnswerMessage closing brace") + } + shouldFuncEnd += shouldFuncBodyStart + 1 // position of the closing "}" + shouldBody := src[shouldFuncBodyStart:shouldFuncEnd] + + if !strings.Contains(shouldBody, "succeeded") { + t.Error("shouldCreateAnswerMessage must check status == succeeded") + } + if !strings.Contains(shouldBody, "turn.Answer") { + t.Error("shouldCreateAnswerMessage must check non-empty answer") + } + if !strings.Contains(shouldBody, "turn.AnswerMessageID") { + t.Error("shouldCreateAnswerMessage must check non-empty AnswerMessageID") + } + + // In FinishTurn, extract the guarded block using deterministic boundaries + finishStart := strings.Index(src, "func (s *Store) FinishTurn(") + if finishStart < 0 { + t.Fatal("cannot find FinishTurn signature") + } + finishEnd := strings.Index(src[finishStart:], "func (s *Store) RecordDelivery(") + if finishEnd < 0 { + t.Fatal("cannot find RecordDelivery signature after FinishTurn") + } + finishBody := src[finishStart : finishStart+finishEnd] + + // Locate the guarded block: start at "if shouldCreateAnswerMessage(turn) {" + guardStart := strings.Index(finishBody, "if shouldCreateAnswerMessage(turn) {") + if guardStart < 0 { + t.Fatal("cannot find shouldCreateAnswerMessage guard in FinishTurn") + } + + // The guarded block ends before the "UPDATE turns SET" statement that follows it + guardEnd := strings.Index(finishBody[guardStart:], "UPDATE turns SET") + if guardEnd < 0 { + t.Fatal("cannot find UPDATE turns SET after guarded block") + } + guardBlock := finishBody[guardStart : guardStart+guardEnd] + + if !strings.Contains(guardBlock, "question_table_exports") { + t.Error("question_table_exports INSERT must be inside the shouldCreateAnswerMessage guard block") + } + if !strings.Contains(guardBlock, "if shouldEnqueueQuestionTableExport(turn, s.questionTableExportEnabled) {") { + t.Error("question_table_exports INSERT must require both runtime enablement and a DingTalk turn") + } + + // The guard block must be the one that contains the messages INSERT + // (answer message creation), and after that the outbox INSERT + msgInsert := strings.Index(guardBlock, "INSERT INTO messages") + outboxInsert := strings.Index(guardBlock, "question_table_exports") + if msgInsert < 0 || outboxInsert < 0 { + t.Fatal("cannot locate messages INSERT or outbox INSERT in guard block") + } + if outboxInsert < msgInsert { + t.Error("outbox INSERT should come after answer message INSERT") + } +} diff --git a/internal/store/postgres/question_table_exports.go b/internal/store/postgres/question_table_exports.go new file mode 100644 index 0000000..ec40ce7 --- /dev/null +++ b/internal/store/postgres/question_table_exports.go @@ -0,0 +1,229 @@ +package postgres + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "strings" + "time" + + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/questiontable" +) + +var ( + errExportIDRequired = errors.New("questiontable export: exportID is required") + errLocationRequired = errors.New("questiontable export: external record id is required") + errBadExportFailure = errors.New("questiontable export: only remote_question_table_insert_failed is accepted") + errExportRowsAffected = errors.New("questiontable export: RowsAffected != 1") + errExportNilStore = errors.New("questiontable export: store is nil") +) + +// QuestionTableExportRepository implements questiontable.ExportRepository +// using a dedicated adapter type. It does NOT add methods to *Store directly +// to avoid conflicts with the existing coverage.NotificationRepository Claim +// and MarkFailed methods. +type QuestionTableExportRepository struct { + store *Store +} + +// compile-time interface assertion +var _ questiontable.ExportRepository = (*QuestionTableExportRepository)(nil) + +// NewQuestionTableExportRepository creates a validated repository adapter. +// It returns a stable error when store is nil or its pool is nil. +func NewQuestionTableExportRepository(store *Store) (*QuestionTableExportRepository, error) { + if store == nil || store.pool == nil { + return nil, errExportNilStore + } + return &QuestionTableExportRepository{store: store}, nil +} + +// Claim implements questiontable.ExportRepository. It atomically claims up to +// limit pending exports whose attempt count is below maxAttempts and whose last +// claim time is before staleBefore. A single CTE with FOR UPDATE SKIP LOCKED +// and one UPDATE is used for atomicity. +func (r *QuestionTableExportRepository) Claim(ctx context.Context, limit int, maxAttempts int, staleBefore time.Time) ([]questiontable.PendingExport, error) { + if r == nil || r.store == nil || r.store.pool == nil { + return nil, errExportNilStore + } + if limit <= 0 || limit > 1000 { + return nil, fmt.Errorf("questiontable export: limit must be 1..1000, got %d", limit) + } + if maxAttempts <= 0 || maxAttempts > 100 { + return nil, fmt.Errorf("questiontable export: maxAttempts must be 1..100, got %d", maxAttempts) + } + + rows, err := r.store.pool.Query(ctx, ` + WITH candidates AS ( + SELECT qte.id + FROM question_table_exports qte + WHERE (qte.status = 'pending' + OR (qte.status = 'export_failed' AND (qte.next_attempt_at IS NULL OR qte.next_attempt_at <= NOW())) + OR (qte.status = 'exporting' AND qte.last_attempt_at < $3)) + AND qte.attempts < $2 + ORDER BY qte.created_at, qte.id + LIMIT $1 + FOR UPDATE SKIP LOCKED + ), + claimed AS ( + UPDATE question_table_exports qte + SET status = 'exporting', + attempts = qte.attempts + 1, + last_attempt_at = NOW(), + next_attempt_at = NULL, + failure_code = '', + updated_at = NOW() + FROM candidates c + WHERE qte.id = c.id + RETURNING qte.id, qte.attempts, qte.tenant_key, qte.channel, qte.turn_id, qte.created_at + ) + SELECT + cl.id, + cl.attempts, + t.question, + t.answer, + t.question_image_urls_json, + m.created_at, + COALESCE(m.actor_name_snapshot, '') AS actor_name_snapshot, + COALESCE(m.actor_union_id_snapshot, '') AS actor_union_id_snapshot, + COALESCE(m.trigger_person_snapshot, '') AS trigger_person_snapshot, + COALESCE(m.department_snapshot, '') AS department_snapshot, + COALESCE(m.region_snapshot, '') AS region_snapshot + FROM claimed cl + JOIN turns t ON t.id = cl.turn_id + AND t.tenant_key = cl.tenant_key + AND t.channel = cl.channel + JOIN messages m ON m.id = t.request_message_id + AND m.tenant_key = cl.tenant_key + AND m.channel = cl.channel + ORDER BY cl.created_at, cl.id`, + limit, maxAttempts, staleBefore) + if err != nil { + return nil, fmt.Errorf("questiontable export claim: %w", err) + } + defer rows.Close() + + var exports []questiontable.PendingExport + for rows.Next() { + var ( + exportID string + attempts int + question string + answer string + imageURLsJSON []byte + askedTime time.Time + actorNameSnapshot string + actorUnionIDSnapshot string + triggerPersonSnap string + departmentSnap string + regionSnap string + ) + if err := rows.Scan(&exportID, &attempts, + &question, &answer, &imageURLsJSON, + &askedTime, + &actorNameSnapshot, &actorUnionIDSnapshot, + &triggerPersonSnap, &departmentSnap, ®ionSnap); err != nil { + rows.Close() + return nil, fmt.Errorf("questiontable export claim scan: %w", err) + } + var imageURLs []string + if len(imageURLsJSON) > 0 { + if err := json.Unmarshal(imageURLsJSON, &imageURLs); err != nil { + imageURLs = nil + } + } + exports = append(exports, questiontable.PendingExport{ + ExportID: exportID, + Attempts: attempts, + Row: questiontable.Row{ + Question: question, + Answer: answer, + AskedTime: askedTime, + AskerName: actorNameSnapshot, + AskerUnionID: actorUnionIDSnapshot, + TriggerPerson: triggerPersonSnap, + Department: departmentSnap, + Region: regionSnap, + QuestionImageURLs: imageURLs, + }, + }) + } + if err := rows.Err(); err != nil { + return nil, fmt.Errorf("questiontable export claim rows: %w", err) + } + return exports, nil +} + +// MarkExported implements questiontable.ExportRepository. +// It records the Notable external record ID for a successfully exported row. +// It transitions the row from exporting to exported. RowsAffected must be exactly 1. +func (r *QuestionTableExportRepository) MarkExported(ctx context.Context, exportID, externalRecordID string) error { + if strings.TrimSpace(exportID) == "" { + return errExportIDRequired + } + if strings.TrimSpace(externalRecordID) == "" { + return errLocationRequired + } + if r == nil || r.store == nil || r.store.pool == nil { + return errExportNilStore + } + + tag, err := r.store.pool.Exec(ctx, ` + UPDATE question_table_exports + SET status = 'exported', + external_record_id = $2, + exported_at = NOW(), + failure_code = '', + next_attempt_at = NULL, + updated_at = NOW() + WHERE id = $1 AND status = 'exporting'`, + exportID, externalRecordID) + if err != nil { + return fmt.Errorf("questiontable export mark exported: %w", err) + } + if tag.RowsAffected() != 1 { + return errExportRowsAffected + } + return nil +} + +// MarkFailed implements questiontable.ExportRepository. +// It records a failure for a row in exporting status with a stable failure code. +// Only FailureCodeRemoteInsertFailed is accepted. The raw error is never persisted. +// A bounded retry delay is computed based on the current attempt count. +// RowsAffected must be exactly 1. +func (r *QuestionTableExportRepository) MarkFailed(ctx context.Context, exportID, failureCode string) error { + if strings.TrimSpace(exportID) == "" { + return errExportIDRequired + } + if failureCode != questiontable.FailureCodeRemoteInsertFailed { + return errBadExportFailure + } + if r == nil || r.store == nil || r.store.pool == nil { + return errExportNilStore + } + + tag, err := r.store.pool.Exec(ctx, ` + UPDATE question_table_exports + SET status = 'export_failed', + failure_code = $2, + next_attempt_at = NOW() + ( + CASE + WHEN attempts <= 1 THEN '5 seconds'::interval + WHEN attempts = 2 THEN '15 seconds'::interval + WHEN attempts = 3 THEN '45 seconds'::interval + ELSE '5 minutes'::interval + END + ), + updated_at = NOW() + WHERE id = $1 AND status = 'exporting'`, + exportID, failureCode) + if err != nil { + return fmt.Errorf("questiontable export mark failed: %w", err) + } + if tag.RowsAffected() != 1 { + return errExportRowsAffected + } + return nil +} diff --git a/internal/store/postgres/question_table_exports_contract_test.go b/internal/store/postgres/question_table_exports_contract_test.go new file mode 100644 index 0000000..6871e34 --- /dev/null +++ b/internal/store/postgres/question_table_exports_contract_test.go @@ -0,0 +1,437 @@ +// Source-level contract tests for the question table export repository SQL. +// No real database connection is used. +package postgres + +import ( + "os" + "regexp" + "strings" + "testing" +) + +func readQuestionTableExportsSource(t *testing.T) string { + t.Helper() + data, err := os.ReadFile("question_table_exports.go") + if err != nil { + t.Fatalf("read question_table_exports.go: %v", err) + } + return string(data) +} + +func extractSQLFromQuestionTableExports(t *testing.T) []string { + t.Helper() + src := readQuestionTableExportsSource(t) + var sqls []string + re := regexp.MustCompile("`([^`]*)`") + for _, m := range re.FindAllStringSubmatch(src, -1) { + upper := strings.ToUpper(m[1]) + if strings.Contains(upper, "SELECT") || strings.Contains(upper, "UPDATE") || + strings.Contains(upper, "INSERT") || strings.Contains(upper, "DELETE") || + strings.Contains(upper, "WITH") { + sqls = append(sqls, m[1]) + } + } + return sqls +} + +// --------------------------------------------------------------------------- +// Claim SQL structure +// --------------------------------------------------------------------------- + +func TestQuestionTableExportsClaimUsesCTE(t *testing.T) { + sqls := extractSQLFromQuestionTableExports(t) + found := false + for _, sql := range sqls { + upper := strings.ToUpper(sql) + if strings.Contains(upper, "WITH CANDIDATES") { + found = true + break + } + } + if !found { + t.Fatal("Claim SQL with CTE not found in question_table_exports.go") + } +} + +func TestQuestionTableExportsClaimUsesForUpdateSkipLocked(t *testing.T) { + sqls := extractSQLFromQuestionTableExports(t) + found := false + for _, sql := range sqls { + upper := strings.ToUpper(sql) + if strings.Contains(upper, "FOR UPDATE SKIP LOCKED") { + found = true + break + } + } + if !found { + t.Fatal("Claim must use FOR UPDATE SKIP LOCKED for atomicity") + } +} + +func TestQuestionTableExportsClaimUsesSingleUpdate(t *testing.T) { + sqls := extractSQLFromQuestionTableExports(t) + var claimSQL string + for _, sql := range sqls { + upper := strings.ToUpper(sql) + if strings.Contains(upper, "WITH CANDIDATES") { + claimSQL = upper + break + } + } + if claimSQL == "" { + t.Fatal("Claim SQL with CTE not found") + } + updateCount := strings.Count(claimSQL, "UPDATE QUESTION_TABLE_EXPORTS") + if updateCount != 1 { + t.Fatalf("Claim must use exactly one UPDATE, found %d", updateCount) + } +} + +// --------------------------------------------------------------------------- +// Claim eligibility: statuses +// --------------------------------------------------------------------------- + +func TestQuestionTableExportsClaimStatusAndAttempts(t *testing.T) { + sqls := extractSQLFromQuestionTableExports(t) + joined := strings.ToUpper(strings.Join(sqls, " ")) + // Status filter: pending, export_failed, or stale exporting + if !strings.Contains(joined, "STATUS = 'PENDING'") { + t.Error("Claim must include pending cases") + } + if !strings.Contains(joined, "STATUS = 'EXPORT_FAILED'") { + t.Error("Claim must include retryable export_failed cases") + } + if !strings.Contains(joined, "STATUS = 'EXPORTING'") { + t.Error("Claim must include stale exporting cases") + } + // Attempts check + if !strings.Contains(joined, "ATTEMPTS <") { + t.Error("Claim must filter by attempts < maxAttempts") + } + // Stale check + if !strings.Contains(joined, "LAST_ATTEMPT_AT <") { + t.Error("Claim must check last_attempt_at for stale reclaim") + } +} + +// --------------------------------------------------------------------------- +// Claim: next_attempt_at condition for export_failed +// --------------------------------------------------------------------------- + +func TestQuestionTableExportsClaimNextAttemptAt(t *testing.T) { + sqls := extractSQLFromQuestionTableExports(t) + joined := strings.ToUpper(strings.Join(sqls, " ")) + if !strings.Contains(joined, "NEXT_ATTEMPT_AT IS NULL OR NEXT_ATTEMPT_AT <= NOW()") || + !strings.Contains(joined, "NEXT_ATTEMPT_AT IS NULL") { + // At least check that next_attempt_at appears in the export_failed condition + if !strings.Contains(joined, "NEXT_ATTEMPT_AT") { + t.Error("Claim must use next_attempt_at for retry backoff on export_failed") + } + } +} + +// --------------------------------------------------------------------------- +// Claim: order and limit +// --------------------------------------------------------------------------- + +func TestQuestionTableExportsClaimOrderAndLimit(t *testing.T) { + sqls := extractSQLFromQuestionTableExports(t) + joined := strings.ToUpper(strings.Join(sqls, " ")) + if !strings.Contains(joined, "ORDER BY") { + t.Error("Claim must ORDER BY created_at, id") + } + if !strings.Contains(joined, "LIMIT") { + t.Error("Claim must use parameterized LIMIT") + } +} + +// --------------------------------------------------------------------------- +// Claim: scope joins with tenant_key and channel +// --------------------------------------------------------------------------- + +func TestQuestionTableExportsClaimScopeJoins(t *testing.T) { + sqls := extractSQLFromQuestionTableExports(t) + joined := strings.ToUpper(strings.Join(sqls, " ")) + // Must join on tenant_key and channel for scoping on turns + if !strings.Contains(joined, "T.TENANT_KEY = CL.TENANT_KEY") { + t.Error("Claim turns join must include tenant_key scope") + } + if !strings.Contains(joined, "T.CHANNEL = CL.CHANNEL") { + t.Error("Claim turns join must include channel scope") + } + // Must join on tenant_key and channel for scoping on messages + if !strings.Contains(joined, "M.TENANT_KEY = CL.TENANT_KEY") { + t.Error("Claim messages join must include tenant_key scope") + } + if !strings.Contains(joined, "M.CHANNEL = CL.CHANNEL") { + t.Error("Claim messages join must include channel scope") + } +} + +// --------------------------------------------------------------------------- +// Claim: reads question/answer from turns, not stored in export table +// --------------------------------------------------------------------------- + +func TestQuestionTableExportsClaimReadsQuestionAnswerFromTurns(t *testing.T) { + sqls := extractSQLFromQuestionTableExports(t) + joined := strings.ToUpper(strings.Join(sqls, " ")) + // Must read question/answer from turns table + if !strings.Contains(joined, "T.QUESTION") { + t.Error("Claim must read question from turns table") + } + if !strings.Contains(joined, "T.ANSWER") { + t.Error("Claim must read answer from turns table") + } +} + +// --------------------------------------------------------------------------- +// Claim: reads actor_union_id_snapshot from messages +// --------------------------------------------------------------------------- + +func TestQuestionTableExportsClaimReadsActorUnionIDSnapshot(t *testing.T) { + sqls := extractSQLFromQuestionTableExports(t) + joined := strings.ToUpper(strings.Join(sqls, " ")) + if !strings.Contains(joined, "ACTOR_UNION_ID_SNAPSHOT") { + t.Error("Claim must read actor_union_id_snapshot from messages") + } +} + +// --------------------------------------------------------------------------- +// Claim: transition clears next_attempt_at +// --------------------------------------------------------------------------- + +func TestQuestionTableExportsClaimClearsNextAttemptAt(t *testing.T) { + sqls := extractSQLFromQuestionTableExports(t) + joined := strings.ToUpper(strings.Join(sqls, " ")) + if !strings.Contains(joined, "NEXT_ATTEMPT_AT = NULL") { + t.Error("Claim UPDATE must clear next_attempt_at") + } +} + +// --------------------------------------------------------------------------- +// MarkExported guards +// --------------------------------------------------------------------------- + +func TestQuestionTableExportsMarkExportedGuard(t *testing.T) { + sqls := extractSQLFromQuestionTableExports(t) + var markSQL string + for _, sql := range sqls { + upper := strings.ToUpper(sql) + if strings.Contains(upper, "SET STATUS = 'EXPORTED'") { + markSQL = sql + break + } + } + if markSQL == "" { + t.Fatal("MarkExported SQL not found") + } + upper := strings.ToUpper(markSQL) + // Must guard on status = 'exporting' + if !strings.Contains(upper, "STATUS = 'EXPORTING'") { + t.Error("MarkExported must guard on status = 'exporting'") + } + // Must set external_record_id + if !strings.Contains(upper, "EXTERNAL_RECORD_ID") { + t.Error("MarkExported must set external_record_id") + } + // Must clear failure_code + if !strings.Contains(upper, "FAILURE_CODE = ''") { + t.Error("MarkExported must clear failure_code") + } + // Must clear next_attempt_at + if !strings.Contains(upper, "NEXT_ATTEMPT_AT = NULL") { + t.Error("MarkExported must clear next_attempt_at") + } +} + +func TestQuestionTableExportsMarkExportedRowsAffected(t *testing.T) { + src := readQuestionTableExportsSource(t) + if !strings.Contains(src, "RowsAffected()") { + t.Error("MarkExported must check RowsAffected()") + } +} + +// --------------------------------------------------------------------------- +// MarkFailed guards +// --------------------------------------------------------------------------- + +func TestQuestionTableExportsMarkFailedGuard(t *testing.T) { + sqls := extractSQLFromQuestionTableExports(t) + var markSQL string + for _, sql := range sqls { + upper := strings.ToUpper(sql) + if strings.Contains(upper, "SET STATUS = 'EXPORT_FAILED'") { + markSQL = sql + break + } + } + if markSQL == "" { + t.Fatal("MarkFailed SQL not found") + } + upper := strings.ToUpper(markSQL) + // Must guard on status = 'exporting' + if !strings.Contains(upper, "STATUS = 'EXPORTING'") { + t.Error("MarkFailed must guard on status = 'exporting'") + } + // Must set failure_code + if !strings.Contains(upper, "FAILURE_CODE") { + t.Error("MarkFailed must set failure_code") + } +} + +func TestQuestionTableExportsMarkFailedOnlyAcceptsStableCode(t *testing.T) { + src := readQuestionTableExportsSource(t) + if !strings.Contains(src, "FailureCodeRemoteInsertFailed") { + t.Error("MarkFailed must validate failureCode == FailureCodeRemoteInsertFailed") + } +} + +func TestQuestionTableExportsMarkFailedRowsAffected(t *testing.T) { + src := readQuestionTableExportsSource(t) + if !strings.Contains(src, "RowsAffected()") { + t.Error("MarkFailed must check RowsAffected()") + } +} + +// --------------------------------------------------------------------------- +// MarkFailed: backoff intervals +// --------------------------------------------------------------------------- + +func TestQuestionTableExportsMarkFailedBackoffIntervals(t *testing.T) { + sqls := extractSQLFromQuestionTableExports(t) + joined := strings.ToUpper(strings.Join(sqls, " ")) + if !strings.Contains(joined, "5 SECONDS") { + t.Error("MarkFailed must use 5s backoff for attempts <= 1") + } + if !strings.Contains(joined, "15 SECONDS") { + t.Error("MarkFailed must use 15s backoff for attempts = 2") + } + if !strings.Contains(joined, "45 SECONDS") { + t.Error("MarkFailed must use 45s backoff for attempts = 3") + } + if !strings.Contains(joined, "5 MINUTES") { + t.Error("MarkFailed must use 5m backoff for attempts >= 4") + } +} + +// --------------------------------------------------------------------------- +// No raw error leak in SQL +// --------------------------------------------------------------------------- + +func TestQuestionTableExportsNoRawErrorLeak(t *testing.T) { + sqls := extractSQLFromQuestionTableExports(t) + joined := strings.ToUpper(strings.Join(sqls, " ")) + for _, forbidden := range []string{ + "TOKEN", "WEBHOOK", "RAW_ERROR", "RAW_RESPONSE", + "GROUP_ID", "EXTERNAL_CHAT_ID", "EXTERNAL_USER_ID", + } { + if strings.Contains(joined, forbidden) { + t.Errorf("question table export SQL must not contain %q", forbidden) + } + } +} + +// --------------------------------------------------------------------------- +// No question/answer bodies stored in export table +// --------------------------------------------------------------------------- + +func TestQuestionTableExportsNoQuestionAnswerBodiesStored(t *testing.T) { + sqls := extractSQLFromQuestionTableExports(t) + // Only check standalone MarkExported/MarkFailed UPDATE statements, not the CTE + // which has a SELECT with t.question/t.answer (that's fine — they come from turns). + for _, sql := range sqls { + upper := strings.ToUpper(sql) + // Skip CTE SQL (contains WITH CANDIDATES) + if strings.Contains(upper, "WITH CANDIDATES") { + continue + } + if strings.Contains(upper, "UPDATE QUESTION_TABLE_EXPORTS") { + if strings.Contains(upper, "QUESTION") && !strings.Contains(upper, "QUESTION_TABLE_EXPORTS") { + t.Errorf("UPDATE must not set question column: %q", sql) + } + if strings.Contains(upper, "ANSWER") { + t.Errorf("UPDATE must not set answer column: %q", sql) + } + } + } +} + +// --------------------------------------------------------------------------- +// Nil safety +// --------------------------------------------------------------------------- + +func TestQuestionTableExportsNilSafe(t *testing.T) { + src := readQuestionTableExportsSource(t) + count := strings.Count(src, "r.store == nil || r.store.pool == nil") + if count < 3 { + t.Errorf("question table export methods must guard against nil store/pool, found %d guards", count) + } +} + +// --------------------------------------------------------------------------- +// ExportID validation +// --------------------------------------------------------------------------- + +func TestQuestionTableExportsExportIDValidation(t *testing.T) { + src := readQuestionTableExportsSource(t) + if !strings.Contains(src, "TrimSpace(exportID)") { + t.Error("MarkExported/MarkFailed must validate exportID is not empty") + } +} + +// --------------------------------------------------------------------------- +// Adapter: compile-time assertion and constructor +// --------------------------------------------------------------------------- + +func TestQuestionTableExportsCompileTimeAssertion(t *testing.T) { + src := readQuestionTableExportsSource(t) + if !strings.Contains(src, "var _ questiontable.ExportRepository = (*QuestionTableExportRepository)(nil)") { + t.Error("QuestionTableExportRepository must have compile-time interface assertion") + } +} + +func TestQuestionTableExportsConstructorNilSafety(t *testing.T) { + src := readQuestionTableExportsSource(t) + if !strings.Contains(src, "NewQuestionTableExportRepository") { + t.Error("Must have a validated constructor NewQuestionTableExportRepository") + } + if !strings.Contains(src, "errExportNilStore") { + t.Error("Constructor must reject nil store with a stable error") + } +} + +// --------------------------------------------------------------------------- +// Claim: input validation +// --------------------------------------------------------------------------- + +func TestQuestionTableExportsClaimInputValidation(t *testing.T) { + src := readQuestionTableExportsSource(t) + if !strings.Contains(src, "limit <= 0") || !strings.Contains(src, "limit > 1000") { + t.Error("Claim must validate positive bounded limit") + } + if !strings.Contains(src, "maxAttempts <= 0") || !strings.Contains(src, "maxAttempts > 100") { + t.Error("Claim must validate positive bounded maxAttempts") + } +} + +// --------------------------------------------------------------------------- +// MarkExported: external_record_id validation +// --------------------------------------------------------------------------- + +func TestQuestionTableExportsMarkExportedLocationValidation(t *testing.T) { + src := readQuestionTableExportsSource(t) + if !strings.Contains(src, "TrimSpace(externalRecordID)") { + t.Error("MarkExported must validate externalRecordID is not empty") + } +} + +// --------------------------------------------------------------------------- +// No a1_notation references +// --------------------------------------------------------------------------- + +func TestQuestionTableExportsNoA1Notation(t *testing.T) { + src := readQuestionTableExportsSource(t) + if strings.Contains(src, "a1_notation") { + t.Error("question_table_exports.go must not reference stale a1_notation column") + } +} diff --git a/internal/store/postgres/reasoning_feedback_integration_test.go b/internal/store/postgres/reasoning_feedback_integration_test.go new file mode 100644 index 0000000..d857618 --- /dev/null +++ b/internal/store/postgres/reasoning_feedback_integration_test.go @@ -0,0 +1,155 @@ +package postgres + +import ( + "context" + "os" + "testing" + "time" + + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/feedback" + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/reasoningmode" +) + +func openIntegrationStore(t *testing.T) *Store { + t.Helper() + url := os.Getenv("DOBOTAI_POSTGRES_INTEGRATION_URL") + if url == "" { + t.Skip("DOBOTAI_POSTGRES_INTEGRATION_URL is not set") + } + store, err := Open(context.Background(), url) + if err != nil { + t.Fatal(err) + } + t.Cleanup(store.Close) + return store +} + +func seedSucceededTurn(t *testing.T, store *Store, suffix string, deliveredCard bool) { + t.Helper() + ctx := context.Background() + tenant, channel := "tenant-"+suffix, "dingtalk" + actorID, conversationID := "actor-"+suffix, "conversation-"+suffix + requestID, turnID, answerID := "request-"+suffix, "turn-"+suffix, "answer-"+suffix + if _, err := store.pool.Exec(ctx, `INSERT INTO channel_actors(id,tenant_key,channel,external_actor_id,actor_type) VALUES($1,$2,$3,$4,'user')`, actorID, tenant, channel, "staff-"+suffix); err != nil { + t.Fatal(err) + } + if _, err := store.pool.Exec(ctx, `INSERT INTO channel_conversations(id,tenant_key,channel,external_conversation_id,conversation_type) VALUES($1,$2,$3,$4,'direct')`, conversationID, tenant, channel, "chat-"+suffix); err != nil { + t.Fatal(err) + } + if _, err := store.pool.Exec(ctx, `INSERT INTO messages(id,tenant_key,channel,conversation_id,actor_id,external_message_id,correlation_id,direction,role,message_type,text_content,status) VALUES($1,$2,$3,$4,$5,$6,$7,'inbound','user','text','question','received')`, requestID, tenant, channel, conversationID, actorID, "external-"+suffix, turnID); err != nil { + t.Fatal(err) + } + if _, err := store.pool.Exec(ctx, `INSERT INTO turns(id,tenant_key,channel,external_message_id,session_key,question,answer,status,request_message_id,agent_id) VALUES($1,$2,$3,$4,$5,'question','answer','succeeded',$6,'agent')`, turnID, tenant, channel, "external-"+suffix, "session-"+suffix, requestID); err != nil { + t.Fatal(err) + } + messageStatus, method, providerID := "generated", "", "" + if deliveredCard { + messageStatus, method, providerID = "sent", "card", "track-"+suffix + } + if _, err := store.pool.Exec(ctx, `INSERT INTO messages(id,tenant_key,channel,conversation_id,external_message_id,correlation_id,direction,role,message_type,text_content,reply_to_message_id,status,delivery_method,provider_message_id) VALUES($1,$2,$3,$4,'',$5,'outbound','assistant','text','answer',$6,$7,$8,$9)`, answerID, tenant, channel, conversationID, turnID, requestID, messageStatus, method, providerID); err != nil { + t.Fatal(err) + } + if _, err := store.pool.Exec(ctx, `UPDATE turns SET answer_message_id=$2 WHERE id=$1`, turnID, answerID); err != nil { + t.Fatal(err) + } + if _, err := store.pool.Exec(ctx, `INSERT INTO coverage_decisions(id,tenant_key,channel,turn_id,evaluator_version,verdict,reason_code,reference_count,top_score) VALUES($1,$2,$3,$4,'v3','covered','covered_has_references',1,0)`, "decision-"+suffix, tenant, channel, turnID); err != nil { + t.Fatal(err) + } +} + +func TestIntegrationReasoningCompletionIsIdempotent(t *testing.T) { + store := openIntegrationStore(t) + seedSucceededTurn(t, store, "reasoning", false) + ctx := context.Background() + scope := reasoningmode.Scope{TenantKey: "tenant-reasoning", Channel: "dingtalk", ExternalActorID: "staff-reasoning"} + now := time.Date(2026, 9, 9, 12, 0, 0, 0, time.UTC) + if _, err := store.Enable(ctx, scope, now, 10*time.Minute); err != nil { + t.Fatal(err) + } + if _, err := store.pool.Exec(ctx, `UPDATE reasoning_mode_states SET rounds_used=7 WHERE tenant_key=$1 AND channel=$2 AND external_actor_id=$3`, scope.TenantKey, scope.Channel, scope.ExternalActorID); err != nil { + t.Fatal(err) + } + input := reasoningmode.TurnCompletion{Scope: scope, TurnID: "turn-reasoning", Execution: reasoningmode.ExecutionReasoning, At: now.Add(time.Minute), Idle: 10 * time.Minute} + first, err := store.CompleteTurn(ctx, input) + if err != nil { + t.Fatal(err) + } + second, err := store.CompleteTurn(ctx, input) + if err != nil { + t.Fatal(err) + } + if first.RoundNumber != 8 || !first.ShowHint || second.RoundNumber != 8 || !second.ShowHint { + t.Fatalf("first=%+v second=%+v", first, second) + } + var rounds, ledger int + if err := store.pool.QueryRow(ctx, `SELECT rounds_used FROM reasoning_mode_states WHERE tenant_key=$1 AND channel=$2 AND external_actor_id=$3`, scope.TenantKey, scope.Channel, scope.ExternalActorID).Scan(&rounds); err != nil { + t.Fatal(err) + } + if err := store.pool.QueryRow(ctx, `SELECT count(*) FROM reasoning_mode_turns WHERE tenant_key=$1 AND channel=$2 AND turn_id=$3`, scope.TenantKey, scope.Channel, input.TurnID).Scan(&ledger); err != nil { + t.Fatal(err) + } + if rounds != 8 || ledger != 1 { + t.Fatalf("rounds=%d ledger=%d", rounds, ledger) + } +} + +func TestIntegrationDownvoteCreatesOneFeedbackSupportCase(t *testing.T) { + store := openIntegrationStore(t) + seedSucceededTurn(t, store, "feedback", true) + store.SetExternalTableExports(false, true) + ctx := context.Background() + command := feedback.Record{ + ID: "feedback-state-1", TenantKey: "tenant-feedback", Channel: "dingtalk", ActorID: "feedback-actor-1", + ExternalActorID: "staff-feedback", OutTrackID: "track-feedback", Value: feedback.ValueDown, + ReasonCode: feedback.ReasonEmpty, Source: feedback.SourceDingTalkCard, + } + if _, err := store.RecordFeedback(ctx, command); err != nil { + t.Fatal(err) + } + command.ID, command.ActorID = "feedback-state-replay", "feedback-actor-replay" + result, err := store.RecordFeedback(ctx, command) + if err != nil { + t.Fatal(err) + } + if !result.Replayed { + t.Fatalf("result=%+v", result) + } + var count int + var triggerType, faqStatus string + if err := store.pool.QueryRow(ctx, `SELECT count(*),max(trigger_type),max(faq_export_status) FROM support_cases WHERE tenant_key=$1 AND channel=$2 AND turn_id=$3`, "tenant-feedback", "dingtalk", "turn-feedback").Scan(&count, &triggerType, &faqStatus); err != nil { + t.Fatal(err) + } + if count != 1 || triggerType != "feedback_down" || faqStatus != "pending" { + t.Fatalf("count=%d trigger=%q faq=%q", count, triggerType, faqStatus) + } +} + +func TestIntegrationDownvoteCreatesCaseWithoutCoverageDecision(t *testing.T) { + store := openIntegrationStore(t) + seedSucceededTurn(t, store, "feedback-no-decision", true) + store.SetExternalTableExports(false, true) + ctx := context.Background() + if _, err := store.pool.Exec(ctx, `DELETE FROM coverage_decisions + WHERE tenant_key=$1 AND channel=$2 AND turn_id=$3`, + "tenant-feedback-no-decision", "dingtalk", "turn-feedback-no-decision"); err != nil { + t.Fatal(err) + } + command := feedback.Record{ + ID: "feedback-state-no-decision", TenantKey: "tenant-feedback-no-decision", Channel: "dingtalk", ActorID: "feedback-actor-no-decision", + ExternalActorID: "staff-feedback-no-decision", OutTrackID: "track-feedback-no-decision", Value: feedback.ValueDown, + ReasonCode: feedback.ReasonEmpty, Source: feedback.SourceDingTalkCard, + } + if _, err := store.RecordFeedback(ctx, command); err != nil { + t.Fatal(err) + } + var count int + if err := store.pool.QueryRow(ctx, `SELECT count(*) FROM support_cases + WHERE tenant_key=$1 AND channel=$2 AND turn_id=$3 AND coverage_decision_id IS NULL + AND trigger_type='feedback_down'`, + "tenant-feedback-no-decision", "dingtalk", "turn-feedback-no-decision").Scan(&count); err != nil { + t.Fatal(err) + } + if count != 1 { + t.Fatalf("count=%d", count) + } +} diff --git a/internal/store/postgres/reasoning_mode.go b/internal/store/postgres/reasoning_mode.go new file mode 100644 index 0000000..445a49e --- /dev/null +++ b/internal/store/postgres/reasoning_mode.go @@ -0,0 +1,325 @@ +package postgres + +import ( + "context" + "errors" + "fmt" + "strings" + "time" + + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgtype" + + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/reasoningmode" +) + +func (s *Store) ResolveState(ctx context.Context, scope reasoningmode.Scope, now time.Time) (reasoningmode.State, bool, error) { + if err := validateReasoningScope(scope); err != nil { + return reasoningmode.State{}, false, err + } + tx, err := s.pool.BeginTx(ctx, pgx.TxOptions{}) + if err != nil { + return reasoningmode.State{}, false, fmt.Errorf("begin reasoning state resolve: %w", err) + } + defer func() { _ = tx.Rollback(ctx) }() + if err = ensureReasoningState(ctx, tx, scope); err != nil { + return reasoningmode.State{}, false, err + } + state, err := selectReasoningStateForUpdate(ctx, tx, scope) + if err != nil { + return reasoningmode.State{}, false, err + } + effective, expired := reasoningmode.EffectiveState(state, now) + if expired { + if err = updateReasoningState(ctx, tx, scope, effective, now); err != nil { + return reasoningmode.State{}, false, err + } + } + if err = tx.Commit(ctx); err != nil { + return reasoningmode.State{}, false, fmt.Errorf("commit reasoning state resolve: %w", err) + } + return effective, expired, nil +} + +func (s *Store) Enable(ctx context.Context, scope reasoningmode.Scope, now time.Time, idle time.Duration) (reasoningmode.State, error) { + if err := validateReasoningScope(scope); err != nil || idle <= 0 { + if err != nil { + return reasoningmode.State{}, err + } + return reasoningmode.State{}, reasoningmode.ErrInvalidState + } + tx, err := s.pool.BeginTx(ctx, pgx.TxOptions{}) + if err != nil { + return reasoningmode.State{}, fmt.Errorf("begin reasoning enable: %w", err) + } + defer func() { _ = tx.Rollback(ctx) }() + if err = ensureReasoningState(ctx, tx, scope); err != nil { + return reasoningmode.State{}, err + } + state, err := selectReasoningStateForUpdate(ctx, tx, scope) + if err != nil { + return reasoningmode.State{}, err + } + state.Mode = reasoningmode.ModeReasoning + state.RoundsUsed = 0 + state.LastActivityAt = now + state.ExpiresAt = now.Add(idle) + if err = updateReasoningState(ctx, tx, scope, state, now); err != nil { + return reasoningmode.State{}, err + } + if err = tx.Commit(ctx); err != nil { + return reasoningmode.State{}, fmt.Errorf("commit reasoning enable: %w", err) + } + return state, nil +} + +func (s *Store) Disable(ctx context.Context, scope reasoningmode.Scope, now time.Time) (reasoningmode.State, bool, error) { + if err := validateReasoningScope(scope); err != nil { + return reasoningmode.State{}, false, err + } + tx, err := s.pool.BeginTx(ctx, pgx.TxOptions{}) + if err != nil { + return reasoningmode.State{}, false, fmt.Errorf("begin reasoning disable: %w", err) + } + defer func() { _ = tx.Rollback(ctx) }() + if err = ensureReasoningState(ctx, tx, scope); err != nil { + return reasoningmode.State{}, false, err + } + state, err := selectReasoningStateForUpdate(ctx, tx, scope) + if err != nil { + return reasoningmode.State{}, false, err + } + state, _ = reasoningmode.EffectiveState(state, now) + wasReasoning := state.Mode == reasoningmode.ModeReasoning + state.Mode = reasoningmode.ModeQuick + state.RoundsUsed = 0 + state.ExpiresAt = time.Time{} + if err = updateReasoningState(ctx, tx, scope, state, now); err != nil { + return reasoningmode.State{}, false, err + } + if err = tx.Commit(ctx); err != nil { + return reasoningmode.State{}, false, fmt.Errorf("commit reasoning disable: %w", err) + } + return state, wasReasoning, nil +} + +func (s *Store) SetMaxRounds(ctx context.Context, scope reasoningmode.Scope, maxRounds int, now time.Time) (reasoningmode.State, error) { + if err := validateReasoningScope(scope); err != nil { + return reasoningmode.State{}, err + } + if maxRounds < 1 || maxRounds > 50 { + return reasoningmode.State{}, reasoningmode.ErrInvalidState + } + tx, err := s.pool.BeginTx(ctx, pgx.TxOptions{}) + if err != nil { + return reasoningmode.State{}, fmt.Errorf("begin reasoning rounds update: %w", err) + } + defer func() { _ = tx.Rollback(ctx) }() + if err = ensureReasoningState(ctx, tx, scope); err != nil { + return reasoningmode.State{}, err + } + state, err := selectReasoningStateForUpdate(ctx, tx, scope) + if err != nil { + return reasoningmode.State{}, err + } + state.MaxRounds = maxRounds + if state.RoundsUsed >= maxRounds { + state.Mode = reasoningmode.ModeQuick + state.RoundsUsed = 0 + state.ExpiresAt = time.Time{} + } + if err = updateReasoningState(ctx, tx, scope, state, now); err != nil { + return reasoningmode.State{}, err + } + if err = tx.Commit(ctx); err != nil { + return reasoningmode.State{}, fmt.Errorf("commit reasoning rounds update: %w", err) + } + return state, nil +} + +func (s *Store) SetHintEnabled(ctx context.Context, scope reasoningmode.Scope, enabled bool, now time.Time) (reasoningmode.State, error) { + if err := validateReasoningScope(scope); err != nil { + return reasoningmode.State{}, err + } + tx, err := s.pool.BeginTx(ctx, pgx.TxOptions{}) + if err != nil { + return reasoningmode.State{}, fmt.Errorf("begin reasoning hint update: %w", err) + } + defer func() { _ = tx.Rollback(ctx) }() + if err = ensureReasoningState(ctx, tx, scope); err != nil { + return reasoningmode.State{}, err + } + state, err := selectReasoningStateForUpdate(ctx, tx, scope) + if err != nil { + return reasoningmode.State{}, err + } + state.HintEnabled = enabled + if err = updateReasoningState(ctx, tx, scope, state, now); err != nil { + return reasoningmode.State{}, err + } + if err = tx.Commit(ctx); err != nil { + return reasoningmode.State{}, fmt.Errorf("commit reasoning hint update: %w", err) + } + return state, nil +} + +func (s *Store) CompleteTurn(ctx context.Context, input reasoningmode.TurnCompletion) (reasoningmode.Completion, error) { + if err := validateReasoningScope(input.Scope); err != nil { + return reasoningmode.Completion{}, err + } + if strings.TrimSpace(input.TurnID) == "" || input.At.IsZero() || input.Idle <= 0 { + return reasoningmode.Completion{}, reasoningmode.ErrInvalidState + } + tx, err := s.pool.BeginTx(ctx, pgx.TxOptions{}) + if err != nil { + return reasoningmode.Completion{}, fmt.Errorf("begin reasoning turn completion: %w", err) + } + defer func() { _ = tx.Rollback(ctx) }() + + var existing reasoningmode.Completion + err = tx.QueryRow(ctx, `SELECT round_number,showed_hint,auto_closed,showed_onboarding + FROM reasoning_mode_turns + WHERE tenant_key=$1 AND channel=$2 AND turn_id=$3 AND external_actor_id=$4 + FOR UPDATE`, input.Scope.TenantKey, input.Scope.Channel, input.TurnID, input.Scope.ExternalActorID).Scan( + &existing.RoundNumber, &existing.ShowHint, &existing.AutoClosed, &existing.ShowOnboarding, + ) + if err == nil { + if existing.Next, err = selectReasoningState(ctx, tx, input.Scope); err != nil { + return reasoningmode.Completion{}, err + } + if err = tx.Commit(ctx); err != nil { + return reasoningmode.Completion{}, fmt.Errorf("commit replayed reasoning completion: %w", err) + } + return existing, nil + } + if !errors.Is(err, pgx.ErrNoRows) { + return reasoningmode.Completion{}, fmt.Errorf("find reasoning turn completion: %w", err) + } + var status string + if err = tx.QueryRow(ctx, `SELECT t.status FROM turns t + JOIN messages m ON m.id=t.request_message_id + JOIN channel_actors a ON a.id=m.actor_id + WHERE t.id=$1 AND t.tenant_key=$2 AND t.channel=$3 + AND a.external_actor_id=$4 + FOR UPDATE OF t`, input.TurnID, input.Scope.TenantKey, input.Scope.Channel, input.Scope.ExternalActorID).Scan(&status); err != nil { + return reasoningmode.Completion{}, fmt.Errorf("lock reasoning completion turn: %w", err) + } + if status != "succeeded" { + return reasoningmode.Completion{}, errors.New("reasoning completion requires a succeeded turn") + } + + if err = ensureReasoningState(ctx, tx, input.Scope); err != nil { + return reasoningmode.Completion{}, err + } + state, err := selectReasoningStateForUpdate(ctx, tx, input.Scope) + if err != nil { + return reasoningmode.Completion{}, err + } + completion, err := reasoningmode.ApplySuccessfulTurn(state, input.Execution, input.At, input.Idle) + if err != nil { + return reasoningmode.Completion{}, err + } + if err = updateReasoningState(ctx, tx, input.Scope, completion.Next, input.At); err != nil { + return reasoningmode.Completion{}, err + } + tag, err := tx.Exec(ctx, `INSERT INTO reasoning_mode_turns + (id,tenant_key,channel,turn_id,external_actor_id,execution_mode,round_number,showed_hint,auto_closed,showed_onboarding) + VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10) + ON CONFLICT (tenant_key,channel,turn_id) DO NOTHING`, + newSettingsID(), input.Scope.TenantKey, input.Scope.Channel, input.TurnID, + input.Scope.ExternalActorID, string(input.Execution), completion.RoundNumber, + completion.ShowHint, completion.AutoClosed, completion.ShowOnboarding, + ) + if err != nil { + return reasoningmode.Completion{}, fmt.Errorf("insert reasoning turn completion: %w", err) + } + if tag.RowsAffected() != 1 { + return reasoningmode.Completion{}, errors.New("insert reasoning turn completion affected unexpected rows") + } + if err = tx.Commit(ctx); err != nil { + return reasoningmode.Completion{}, fmt.Errorf("commit reasoning turn completion: %w", err) + } + return completion, nil +} + +func ensureReasoningState(ctx context.Context, tx pgx.Tx, scope reasoningmode.Scope) error { + _, err := tx.Exec(ctx, `INSERT INTO reasoning_mode_states + (tenant_key,channel,external_actor_id,mode,max_rounds,rounds_used,hint_enabled) + VALUES($1,$2,$3,'quick',10,0,TRUE) + ON CONFLICT (tenant_key,channel,external_actor_id) DO NOTHING`, + scope.TenantKey, scope.Channel, scope.ExternalActorID, + ) + if err != nil { + return fmt.Errorf("ensure reasoning state: %w", err) + } + return nil +} + +func selectReasoningStateForUpdate(ctx context.Context, tx pgx.Tx, scope reasoningmode.Scope) (reasoningmode.State, error) { + return scanReasoningState(tx.QueryRow(ctx, `SELECT mode,max_rounds,rounds_used,hint_enabled,last_activity_at,expires_at,onboarding_shown_at + FROM reasoning_mode_states + WHERE tenant_key=$1 AND channel=$2 AND external_actor_id=$3 + FOR UPDATE`, scope.TenantKey, scope.Channel, scope.ExternalActorID)) +} + +func selectReasoningState(ctx context.Context, tx pgx.Tx, scope reasoningmode.Scope) (reasoningmode.State, error) { + return scanReasoningState(tx.QueryRow(ctx, `SELECT mode,max_rounds,rounds_used,hint_enabled,last_activity_at,expires_at,onboarding_shown_at + FROM reasoning_mode_states + WHERE tenant_key=$1 AND channel=$2 AND external_actor_id=$3`, scope.TenantKey, scope.Channel, scope.ExternalActorID)) +} + +func scanReasoningState(row pgx.Row) (reasoningmode.State, error) { + var ( + state reasoningmode.State + mode string + last pgtype.Timestamptz + expires pgtype.Timestamptz + onboarding pgtype.Timestamptz + ) + if err := row.Scan(&mode, &state.MaxRounds, &state.RoundsUsed, &state.HintEnabled, &last, &expires, &onboarding); err != nil { + return reasoningmode.State{}, fmt.Errorf("scan reasoning state: %w", err) + } + state.Mode = reasoningmode.Mode(mode) + if last.Valid { + state.LastActivityAt = last.Time + } + if expires.Valid { + state.ExpiresAt = expires.Time + } + if onboarding.Valid { + state.OnboardingShown = true + state.OnboardingShownAt = onboarding.Time + } + return state, nil +} + +func updateReasoningState(ctx context.Context, tx pgx.Tx, scope reasoningmode.Scope, state reasoningmode.State, now time.Time) error { + _, err := tx.Exec(ctx, `UPDATE reasoning_mode_states SET + mode=$4,max_rounds=$5,rounds_used=$6,hint_enabled=$7, + last_activity_at=$8,expires_at=$9,onboarding_shown_at=$10,updated_at=$11 + WHERE tenant_key=$1 AND channel=$2 AND external_actor_id=$3`, + scope.TenantKey, scope.Channel, scope.ExternalActorID, + string(state.Mode), state.MaxRounds, state.RoundsUsed, state.HintEnabled, + nullableTime(state.LastActivityAt), nullableTime(state.ExpiresAt), nullableTime(state.OnboardingShownAt), now, + ) + if err != nil { + return fmt.Errorf("update reasoning state: %w", err) + } + return nil +} + +func nullableTime(value time.Time) any { + if value.IsZero() { + return nil + } + return value +} + +func validateReasoningScope(scope reasoningmode.Scope) error { + if strings.TrimSpace(scope.TenantKey) == "" || strings.TrimSpace(scope.Channel) == "" || strings.TrimSpace(scope.ExternalActorID) == "" { + return errors.New("reasoning mode scope is required") + } + return nil +} + +var _ reasoningmode.Repository = (*Store)(nil) diff --git a/internal/store/postgres/reasoning_mode_contract_test.go b/internal/store/postgres/reasoning_mode_contract_test.go new file mode 100644 index 0000000..aa96189 --- /dev/null +++ b/internal/store/postgres/reasoning_mode_contract_test.go @@ -0,0 +1,59 @@ +package postgres + +import ( + "os" + "strings" + "testing" +) + +func TestReasoningModeRepositoryUsesScopedAtomicStateTransitions(t *testing.T) { + data, err := os.ReadFile("reasoning_mode.go") + if err != nil { + t.Fatal(err) + } + source := strings.ToUpper(string(data)) + for _, required := range []string{ + "REASONING_MODE_STATES", + "TENANT_KEY=$1", + "CHANNEL=$2", + "EXTERNAL_ACTOR_ID=$3", + "FOR UPDATE", + "REASONINGMODE.MODEQUICK", + "REASONINGMODE.MODEREASONING", + "STRING(STATE.MODE)", + "EXPIRES_AT", + "MAX_ROUNDS", + "HINT_ENABLED", + } { + if !strings.Contains(source, required) { + t.Errorf("reasoning repository missing %q", required) + } + } + if strings.Count(source, "BEGINTX") < 4 || strings.Count(source, "TX.COMMIT") < 4 { + t.Fatal("state transitions must use explicit transactions") + } +} + +func TestReasoningModeRepositoryMakesTurnCompletionIdempotent(t *testing.T) { + data, err := os.ReadFile("reasoning_mode.go") + if err != nil { + t.Fatal(err) + } + source := strings.ToUpper(string(data)) + for _, required := range []string{ + "REASONING_MODE_TURNS", + "ON CONFLICT (TENANT_KEY,CHANNEL,TURN_ID) DO NOTHING", + "ROWSAFFECTED", + "APPLYSUCCESSFULTURN", + "SELECT ROUND_NUMBER,SHOWED_HINT,AUTO_CLOSED,SHOWED_ONBOARDING", + "JOIN MESSAGES M ON M.ID=T.REQUEST_MESSAGE_ID", + "JOIN CHANNEL_ACTORS A ON A.ID=M.ACTOR_ID", + "T.ID=$1 AND T.TENANT_KEY=$2 AND T.CHANNEL=$3", + "A.EXTERNAL_ACTOR_ID=$4", + "STATUS != \"SUCCEEDED\"", + } { + if !strings.Contains(source, required) { + t.Errorf("turn completion repository missing %q", required) + } + } +} diff --git a/internal/store/postgres/session_title_contract_test.go b/internal/store/postgres/session_title_contract_test.go new file mode 100644 index 0000000..55c6c81 --- /dev/null +++ b/internal/store/postgres/session_title_contract_test.go @@ -0,0 +1,28 @@ +package postgres + +import ( + "os" + "strings" + "testing" +) + +func TestStoreSessionTitleSQLContract(t *testing.T) { + raw, err := os.ReadFile("store.go") + if err != nil { + t.Fatalf("read store.go: %v", err) + } + src := strings.ToUpper(string(raw)) + for _, required := range []string{ + "INSERT INTO SESSION_MAPPINGS", + "DISPLAY_TITLE", + "SELECT WEKNORA_SESSION_ID,DISPLAY_TITLE FROM SESSION_MAPPINGS", + "UPDATE SESSION_MAPPINGS SET DISPLAY_TITLE=", + } { + if !strings.Contains(src, required) { + t.Errorf("store.go missing session-title SQL contract %q", required) + } + } + if !strings.Contains(string(raw), "func (s *Store) SyncSessionTitle") { + t.Error("Store must implement SyncSessionTitle") + } +} diff --git a/internal/store/postgres/settings.go b/internal/store/postgres/settings.go new file mode 100644 index 0000000..7aaffce --- /dev/null +++ b/internal/store/postgres/settings.go @@ -0,0 +1,421 @@ +package postgres + +import ( + "context" + "crypto/rand" + "crypto/sha256" + "crypto/subtle" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "strings" + "time" + + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/reasoningmode" + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/settings" + "github.com/jackc/pgx/v5" +) + +type SettingsRepository struct{ store *Store } + +func NewSettingsRepository(s *Store) (*SettingsRepository, error) { + if s == nil || s.pool == nil { + return nil, errors.New("settings repository: store is required") + } + return &SettingsRepository{store: s}, nil +} +func (r *SettingsRepository) IsAdministrator(ctx context.Context, tenant, staff string) (bool, error) { + var ok bool + err := r.store.pool.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM administrators WHERE tenant_key=$1 AND staff_id=$2 AND status='active')`, strings.TrimSpace(tenant), strings.TrimSpace(staff)).Scan(&ok) + return ok, err +} +func (r *SettingsRepository) SetPreference(ctx context.Context, tenant, channel, staff, locale string) error { + mode := "fixed" + if locale == "auto" { + mode = "auto" + } + _, err := r.store.pool.Exec(ctx, `INSERT INTO user_preferences(tenant_key,channel,external_actor_id,language_mode,locale) VALUES($1,$2,$3,$4,$5) ON CONFLICT(tenant_key,channel,external_actor_id) DO UPDATE SET language_mode=EXCLUDED.language_mode,locale=EXCLUDED.locale,updated_at=NOW()`, tenant, channel, staff, mode, locale) + return err +} +func (r *SettingsRepository) SetReasoningMaxRounds(ctx context.Context, tenant, channel, staff string, rounds int, now time.Time) error { + _, err := r.store.SetMaxRounds(ctx, reasoningmode.Scope{TenantKey: tenant, Channel: channel, ExternalActorID: staff}, rounds, now) + return err +} +func (r *SettingsRepository) SetReasoningHintEnabled(ctx context.Context, tenant, channel, staff string, enabled bool, now time.Time) error { + _, err := r.store.SetHintEnabled(ctx, reasoningmode.Scope{TenantKey: tenant, Channel: channel, ExternalActorID: staff}, enabled, now) + return err +} +func (r *SettingsRepository) GetPreference(ctx context.Context, tenant, channel, staff string) (string, error) { + var locale string + err := r.store.pool.QueryRow(ctx, `SELECT locale FROM user_preferences WHERE tenant_key=$1 AND channel=$2 AND external_actor_id=$3`, tenant, channel, staff).Scan(&locale) + if errors.Is(err, pgx.ErrNoRows) { + return "auto", nil + } + return locale, err +} +func (r *SettingsRepository) GetSettingSession(ctx context.Context, tenant, staff string) (settings.SettingSession, bool, error) { + var session settings.SettingSession + err := r.store.pool.QueryRow(ctx, `SELECT tenant_key,staff_id,conversation_id,conversation_type,pending_action,expires_at FROM setting_sessions WHERE tenant_key=$1 AND staff_id=$2 AND expires_at>NOW()`, tenant, staff).Scan(&session.TenantKey, &session.StaffID, &session.ConversationID, &session.ConversationType, &session.PendingAction, &session.ExpiresAt) + if errors.Is(err, pgx.ErrNoRows) { + return settings.SettingSession{}, false, nil + } + return session, err == nil, err +} +func (r *SettingsRepository) SaveSettingSession(ctx context.Context, session settings.SettingSession) error { + _, err := r.store.pool.Exec(ctx, `INSERT INTO setting_sessions(tenant_key,staff_id,conversation_id,conversation_type,current_step,pending_action,draft_config,expires_at) VALUES($1,$2,$3,$4,'waiting_input',$5,'{}'::JSONB,$6) ON CONFLICT(tenant_key,staff_id) DO UPDATE SET conversation_id=EXCLUDED.conversation_id,conversation_type=EXCLUDED.conversation_type,current_step='waiting_input',pending_action=EXCLUDED.pending_action,draft_config='{}'::JSONB,expires_at=EXCLUDED.expires_at,updated_at=NOW()`, session.TenantKey, session.StaffID, session.ConversationID, session.ConversationType, session.PendingAction, session.ExpiresAt) + return err +} +func (r *SettingsRepository) DeleteSettingSession(ctx context.Context, tenant, staff string) error { + _, err := r.store.pool.Exec(ctx, `DELETE FROM setting_sessions WHERE tenant_key=$1 AND staff_id=$2`, tenant, staff) + return err +} +func (r *SettingsRepository) SaveBinding(ctx context.Context, b settings.ResourceBinding) error { + payload, err := json.Marshal(map[string]interface{}{"conversation_id": b.ConversationID, "conversation_title": b.ConversationTitle, "base_id": b.BaseID, "sheet_id": b.SheetID, "view_id": b.ViewID, "operator_id": b.OperatorID, "field_mapping": b.FieldMapping}) + if err != nil { + return err + } + tx, err := r.store.pool.Begin(ctx) + if err != nil { + return err + } + defer tx.Rollback(ctx) + var rev int + if err = tx.QueryRow(ctx, `SELECT COALESCE(MAX(revision),0)+1 FROM system_resource_bindings WHERE tenant_key=$1 AND kind=$2`, b.TenantKey, b.Kind).Scan(&rev); err != nil { + return err + } + state := "validated" + var validatedAt, activatedAt interface{} + if b.Activate { + state = "active" + validatedAt, activatedAt = time.Now(), time.Now() + if _, err = tx.Exec(ctx, `UPDATE system_resource_bindings SET state='retired' WHERE tenant_key=$1 AND kind=$2 AND state='active'`, b.TenantKey, b.Kind); err != nil { + return err + } + } + validationCode := strings.TrimSpace(b.ValidationCode) + if validationCode == "" { + validationCode = "pending_external_probe" + } + _, err = tx.Exec(ctx, `INSERT INTO system_resource_bindings(id,tenant_key,kind,revision,state,public_config,validation_code,validated_at,activated_at,created_by_staff_id) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10)`, newSettingsID(), b.TenantKey, b.Kind, rev, state, payload, validationCode, validatedAt, activatedAt, b.CreatedByStaffID) + if err != nil { + return err + } + return tx.Commit(ctx) +} +func (r *SettingsRepository) DetectBootstrapCandidate(ctx context.Context, c settings.BootstrapCandidate) error { + hash := sha256.Sum256([]byte(strings.TrimSpace(c.Code))) + var id, stored string + var attempts, max int + err := r.store.pool.QueryRow(ctx, `SELECT id,code_hash,attempts,max_attempts FROM admin_bootstrap_challenges WHERE tenant_key=$1 AND status='pending' AND expires_at>NOW() ORDER BY created_at DESC LIMIT 1`, c.TenantKey).Scan(&id, &stored, &attempts, &max) + if err != nil { + return err + } + if attempts >= max { + return errors.New("bootstrap challenge locked") + } + provided := hex.EncodeToString(hash[:]) + if len(provided) != len(stored) || subtle.ConstantTimeCompare([]byte(provided), []byte(stored)) != 1 { + _, _ = r.store.pool.Exec(ctx, `UPDATE admin_bootstrap_challenges SET attempts=attempts+1,status=CASE WHEN attempts+1>=max_attempts THEN 'locked' ELSE status END,updated_at=NOW() WHERE id=$1`, id) + return errors.New("invalid bootstrap code") + } + _, err = r.store.pool.Exec(ctx, `UPDATE admin_bootstrap_challenges SET candidate_staff_id=$2,candidate_union_id=$3,candidate_display_name=$4,candidate_department=$5,status='candidate_detected',updated_at=NOW() WHERE id=$1`, id, c.StaffID, c.UnionID, c.DisplayName, c.Department) + return err +} +func (r *SettingsRepository) CreateBootstrapChallenge(ctx context.Context, tenant, code string, expires time.Time) error { + sum := sha256.Sum256([]byte(code)) + tx, err := r.store.pool.Begin(ctx) + if err != nil { + return err + } + defer tx.Rollback(ctx) + if _, err = tx.Exec(ctx, `UPDATE admin_bootstrap_challenges SET status='expired',updated_at=NOW() WHERE tenant_key=$1 AND status IN ('pending','candidate_detected')`, tenant); err != nil { + return err + } + _, err = tx.Exec(ctx, `INSERT INTO admin_bootstrap_challenges(id,tenant_key,code_hash,expires_at,status) VALUES($1,$2,$3,$4,'pending')`, newSettingsID(), tenant, hex.EncodeToString(sum[:]), expires) + if err != nil { + return err + } + return tx.Commit(ctx) +} +func (r *SettingsRepository) ConfirmBootstrap(ctx context.Context, tenant string) error { + tx, err := r.store.pool.Begin(ctx) + if err != nil { + return err + } + defer tx.Rollback(ctx) + var challengeID, staff, union, name, dept string + err = tx.QueryRow(ctx, `SELECT id,candidate_staff_id,candidate_union_id,candidate_display_name,candidate_department FROM admin_bootstrap_challenges WHERE tenant_key=$1 AND status='candidate_detected' AND expires_at>NOW() FOR UPDATE`, tenant).Scan(&challengeID, &staff, &union, &name, &dept) + if err != nil { + return err + } + if strings.TrimSpace(staff) == "" { + return errors.New("bootstrap candidate missing") + } + _, err = tx.Exec(ctx, `INSERT INTO administrators(id,tenant_key,staff_id,union_id,display_name,department,role,status) VALUES($1,$2,$3,$4,$5,$6,'super_admin','active') ON CONFLICT(tenant_key,staff_id) DO UPDATE SET status='active',role='super_admin',updated_at=NOW()`, newSettingsID(), tenant, staff, union, name, dept) + if err != nil { + return err + } + if _, err = tx.Exec(ctx, `UPDATE admin_bootstrap_challenges SET status='confirmed',updated_at=NOW() WHERE id=$1`, challengeID); err != nil { + return err + } + return tx.Commit(ctx) +} +func (r *SettingsRepository) AdministratorCount(ctx context.Context, tenant string) (int, error) { + var n int + err := r.store.pool.QueryRow(ctx, `SELECT COUNT(*) FROM administrators WHERE tenant_key=$1 AND status='active'`, tenant).Scan(&n) + return n, err +} +func (r *SettingsRepository) ListAdministrators(ctx context.Context, tenant string) ([]settings.Administrator, error) { + rows, err := r.store.pool.Query(ctx, `SELECT staff_id,display_name,department,role,status FROM administrators WHERE tenant_key=$1 ORDER BY CASE status WHEN 'active' THEN 0 ELSE 1 END,created_at`, strings.TrimSpace(tenant)) + if err != nil { + return nil, err + } + defer rows.Close() + administrators := []settings.Administrator{} + for rows.Next() { + var administrator settings.Administrator + if err = rows.Scan(&administrator.StaffID, &administrator.DisplayName, &administrator.Department, &administrator.Role, &administrator.Status); err != nil { + return nil, err + } + administrators = append(administrators, administrator) + } + return administrators, rows.Err() +} +func (r *SettingsRepository) DisableAdministrator(ctx context.Context, tenant, staffID string) error { + tenant, staffID = strings.TrimSpace(tenant), strings.TrimSpace(staffID) + if tenant == "" || staffID == "" { + return settings.ErrAdministratorNotFound + } + tx, err := r.store.pool.Begin(ctx) + if err != nil { + return err + } + defer tx.Rollback(ctx) + rows, err := tx.Query(ctx, `SELECT staff_id,status FROM administrators WHERE tenant_key=$1 FOR UPDATE`, tenant) + if err != nil { + return err + } + activeCount, targetStatus, found := 0, "", false + for rows.Next() { + var currentStaffID, status string + if err = rows.Scan(¤tStaffID, &status); err != nil { + rows.Close() + return err + } + if status == "active" { + activeCount++ + } + if currentStaffID == staffID { + targetStatus, found = status, true + } + } + rows.Close() + if err = rows.Err(); err != nil { + return err + } + if !found { + return settings.ErrAdministratorNotFound + } + if err = canDisableAdministrator(targetStatus, activeCount); err != nil { + return err + } + result, err := tx.Exec(ctx, `UPDATE administrators SET status='disabled',updated_at=NOW() WHERE tenant_key=$1 AND staff_id=$2 AND status='active'`, tenant, staffID) + if err != nil { + return err + } + if result.RowsAffected() != 1 { + return settings.ErrAdministratorNotFound + } + if _, err = tx.Exec(ctx, `INSERT INTO config_audit_events(id,tenant_key,actor_staff_id,action,target_kind,target_revision,result_code,metadata) VALUES($1,$2,'','administrator.disable','administrator',0,'administrator_disabled',jsonb_build_object('target_staff_id',$3,'source','admin_web'))`, newSettingsID(), tenant, staffID); err != nil { + return err + } + return tx.Commit(ctx) +} +func canDisableAdministrator(status string, activeCount int) error { + if status != "active" { + return settings.ErrAdministratorAlreadyDisabled + } + if activeCount <= 1 { + return settings.ErrLastAdministrator + } + return nil +} +func (r *SettingsRepository) SaveDingTalkConfig(ctx context.Context, tenant, clientID, secretRef string, verified bool) error { + payload, _ := json.Marshal(map[string]string{"client_id": clientID}) + state := "validated" + validation := "ok" + if verified { + state = "active" + } + tx, err := r.store.pool.Begin(ctx) + if err != nil { + return err + } + defer tx.Rollback(ctx) + var rev int + if err = tx.QueryRow(ctx, `SELECT COALESCE(MAX(revision),0)+1 FROM system_config_revisions WHERE tenant_key=$1 AND kind='dingtalk_app'`, tenant).Scan(&rev); err != nil { + return err + } + if state == "active" { + if _, err = tx.Exec(ctx, `UPDATE system_config_revisions SET state='retired' WHERE tenant_key=$1 AND kind='dingtalk_app' AND state='active'`, tenant); err != nil { + return err + } + } + _, err = tx.Exec(ctx, `INSERT INTO system_config_revisions(id,tenant_key,kind,revision,state,public_config,secret_ref,validation_status,validation_code,validated_at,activated_at) VALUES($1,$2,'dingtalk_app',$3,$4,$5,$6,$7,$7,CASE WHEN $7='ok' THEN NOW() END,CASE WHEN $7='ok' THEN NOW() END)`, newSettingsID(), tenant, rev, state, payload, secretRef, validation) + if err != nil { + return err + } + return tx.Commit(ctx) +} +func (r *SettingsRepository) CandidateDingTalkConfig(ctx context.Context, tenant string) (clientID, secretRef string, err error) { + var payload []byte + err = r.store.pool.QueryRow(ctx, `SELECT public_config,secret_ref FROM system_config_revisions WHERE tenant_key=$1 AND kind='dingtalk_app' AND state='validated' AND validation_status='ok' ORDER BY revision DESC LIMIT 1`, tenant).Scan(&payload, &secretRef) + if err != nil { + return + } + var value map[string]string + if json.Unmarshal(payload, &value) != nil { + return "", "", errors.New("decode dingtalk candidate") + } + return value["client_id"], secretRef, nil +} +func (r *SettingsRepository) ActivateDingTalkCandidate(ctx context.Context, tenant, secretRef string) error { + tx, err := r.store.pool.Begin(ctx) + if err != nil { + return err + } + defer tx.Rollback(ctx) + var candidateID string + err = tx.QueryRow(ctx, `SELECT id FROM system_config_revisions WHERE tenant_key=$1 AND kind='dingtalk_app' AND state='validated' AND secret_ref=$2 AND validation_status='ok' FOR UPDATE`, tenant, secretRef).Scan(&candidateID) + if err != nil { + return err + } + if _, err = tx.Exec(ctx, `UPDATE system_config_revisions SET state='retired' WHERE tenant_key=$1 AND kind='dingtalk_app' AND state='active'`, tenant); err != nil { + return err + } + if _, err = tx.Exec(ctx, `UPDATE system_config_revisions SET state='active',validation_code='pending_runtime',activated_at=NOW() WHERE id=$1`, candidateID); err != nil { + return err + } + return tx.Commit(ctx) +} +func (r *SettingsRepository) PrepareDingTalkRuntimeStart(ctx context.Context, tenant string) (bool, error) { + tx, err := r.store.pool.Begin(ctx) + if err != nil { + return false, err + } + defer tx.Rollback(ctx) + var activeID, activeRef, code string + err = tx.QueryRow(ctx, `SELECT id,secret_ref,validation_code FROM system_config_revisions WHERE tenant_key=$1 AND kind='dingtalk_app' AND state='active' FOR UPDATE`, tenant).Scan(&activeID, &activeRef, &code) + if errors.Is(err, pgx.ErrNoRows) { + return false, tx.Commit(ctx) + } + if err != nil { + return false, err + } + switch code { + case "pending_runtime": + if _, err = tx.Exec(ctx, `UPDATE system_config_revisions SET validation_code='runtime_starting' WHERE id=$1`, activeID); err != nil { + return false, err + } + return true, tx.Commit(ctx) + case "runtime_starting": + var oldID string + err = tx.QueryRow(ctx, `SELECT id FROM system_config_revisions WHERE tenant_key=$1 AND kind='dingtalk_app' AND state='retired' AND validation_status='ok' ORDER BY revision DESC LIMIT 1 FOR UPDATE`, tenant).Scan(&oldID) + if err != nil && !errors.Is(err, pgx.ErrNoRows) { + return false, err + } + if _, err = tx.Exec(ctx, `UPDATE system_config_revisions SET state='failed',validation_status='failed',validation_code='runtime_start_failed' WHERE id=$1`, activeID); err != nil { + return false, err + } + if oldID != "" { + if _, err = tx.Exec(ctx, `UPDATE system_config_revisions SET state='active',validation_code='rollback_restored',activated_at=NOW() WHERE id=$1`, oldID); err != nil { + return false, err + } + } + return false, tx.Commit(ctx) + default: + _ = activeRef + return false, tx.Commit(ctx) + } +} +func (r *SettingsRepository) MarkDingTalkRuntimeHealthy(ctx context.Context, tenant, secretRef string) error { + _, err := r.store.pool.Exec(ctx, `UPDATE system_config_revisions SET validation_code='runtime_ok' WHERE tenant_key=$1 AND kind='dingtalk_app' AND state='active' AND secret_ref=$2`, tenant, secretRef) + return err +} +func (r *SettingsRepository) RollbackPendingDingTalkActivation(ctx context.Context, tenant, failedRef string) error { + tx, err := r.store.pool.Begin(ctx) + if err != nil { + return err + } + defer tx.Rollback(ctx) + var currentID string + if err = tx.QueryRow(ctx, `SELECT id FROM system_config_revisions WHERE tenant_key=$1 AND kind='dingtalk_app' AND state='active' AND secret_ref=$2 AND validation_code='pending_runtime' FOR UPDATE`, tenant, failedRef).Scan(¤tID); err != nil { + return err + } + var oldID string + if err = tx.QueryRow(ctx, `SELECT id FROM system_config_revisions WHERE tenant_key=$1 AND kind='dingtalk_app' AND state='retired' AND validation_status='ok' ORDER BY revision DESC LIMIT 1 FOR UPDATE`, tenant).Scan(&oldID); err != nil { + return err + } + if _, err = tx.Exec(ctx, `UPDATE system_config_revisions SET state='failed',validation_status='failed',validation_code='runtime_start_failed' WHERE id=$1`, currentID); err != nil { + return err + } + if _, err = tx.Exec(ctx, `UPDATE system_config_revisions SET state='active',validation_code='rollback_restored',activated_at=NOW() WHERE id=$1`, oldID); err != nil { + return err + } + return tx.Commit(ctx) +} +func (r *SettingsRepository) MarkDingTalkCandidateFailed(ctx context.Context, tenant, secretRef, code string) error { + _, err := r.store.pool.Exec(ctx, `UPDATE system_config_revisions SET state='failed',validation_status='failed',validation_code=$3 WHERE tenant_key=$1 AND kind='dingtalk_app' AND state='validated' AND secret_ref=$2`, tenant, secretRef, code) + return err +} +func (r *SettingsRepository) ActiveDingTalkConfig(ctx context.Context, tenant string) (clientID, secretRef string, verified bool, err error) { + var payload []byte + var status string + err = r.store.pool.QueryRow(ctx, `SELECT public_config,secret_ref,validation_status FROM system_config_revisions WHERE tenant_key=$1 AND kind='dingtalk_app' AND state='active' ORDER BY revision DESC LIMIT 1`, tenant).Scan(&payload, &secretRef, &status) + if errors.Is(err, pgx.ErrNoRows) { + err = nil + return + } + if err != nil { + return + } + var v map[string]string + if json.Unmarshal(payload, &v) != nil { + err = fmt.Errorf("decode dingtalk config") + return + } + clientID = v["client_id"] + verified = status == "ok" + return +} +func (r *SettingsRepository) ActiveBindings(ctx context.Context, tenant string) (map[string]settings.ResourceBinding, error) { + rows, err := r.store.pool.Query(ctx, `SELECT kind,public_config FROM system_resource_bindings WHERE tenant_key=$1 AND state='active'`, tenant) + if err != nil { + return nil, err + } + defer rows.Close() + out := map[string]settings.ResourceBinding{} + for rows.Next() { + var kind string + var raw []byte + if err = rows.Scan(&kind, &raw); err != nil { + return nil, err + } + var v struct { + ConversationID string `json:"conversation_id"` + ConversationTitle string `json:"conversation_title"` + BaseID string `json:"base_id"` + SheetID string `json:"sheet_id"` + ViewID string `json:"view_id"` + OperatorID string `json:"operator_id"` + FieldMapping map[string]string `json:"field_mapping"` + } + if json.Unmarshal(raw, &v) != nil { + continue + } + out[kind] = settings.ResourceBinding{Kind: kind, TenantKey: tenant, ConversationID: v.ConversationID, ConversationTitle: v.ConversationTitle, BaseID: v.BaseID, SheetID: v.SheetID, ViewID: v.ViewID, OperatorID: v.OperatorID, FieldMapping: v.FieldMapping, Activate: true} + } + return out, rows.Err() +} +func newSettingsID() string { b := make([]byte, 16); _, _ = rand.Read(b); return hex.EncodeToString(b) } diff --git a/internal/store/postgres/settings_admin_test.go b/internal/store/postgres/settings_admin_test.go new file mode 100644 index 0000000..1fe73c2 --- /dev/null +++ b/internal/store/postgres/settings_admin_test.go @@ -0,0 +1,28 @@ +package postgres + +import ( + "errors" + "testing" + + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/settings" +) + +func TestCanDisableAdministratorProtectsLastActiveAdministrator(t *testing.T) { + for _, tc := range []struct { + name string + status string + activeCount int + wantErr error + }{ + {name: "two active", status: "active", activeCount: 2}, + {name: "last active", status: "active", activeCount: 1, wantErr: settings.ErrLastAdministrator}, + {name: "already disabled", status: "disabled", activeCount: 2, wantErr: settings.ErrAdministratorAlreadyDisabled}, + } { + t.Run(tc.name, func(t *testing.T) { + err := canDisableAdministrator(tc.status, tc.activeCount) + if !errors.Is(err, tc.wantErr) { + t.Fatalf("err=%v want=%v", err, tc.wantErr) + } + }) + } +} diff --git a/internal/store/postgres/store.go b/internal/store/postgres/store.go index b98ffab..f9750e5 100644 --- a/internal/store/postgres/store.go +++ b/internal/store/postgres/store.go @@ -13,7 +13,19 @@ import ( "gitea.zheromiku.top/Weknora/dobotai-platform/internal/core" ) -type Store struct{ pool *pgxpool.Pool } +type Store struct { + pool *pgxpool.Pool + questionTableExportEnabled bool + faqExportEnabled bool +} + +func (s *Store) SetExternalTableExports(questionEnabled, faqEnabled bool) { + if s == nil { + return + } + s.questionTableExportEnabled = questionEnabled + s.faqExportEnabled = faqEnabled +} func Open(ctx context.Context, databaseURL string) (*Store, error) { if databaseURL == "" { @@ -44,6 +56,14 @@ func (s *Store) BeginTurn(ctx context.Context, turn core.Turn) (core.Turn, bool, if err != nil { return core.Turn{}, false, err } + imageURLs := turn.QuestionImageURLs + if imageURLs == nil { + imageURLs = []string{} + } + imageURLsJSON, err := json.Marshal(imageURLs) + if err != nil { + return core.Turn{}, false, err + } tx, err := s.pool.BeginTx(ctx, pgx.TxOptions{}) if err != nil { return core.Turn{}, false, err @@ -67,6 +87,8 @@ func (s *Store) BeginTurn(ctx context.Context, turn core.Turn) (core.Turn, bool, conversationTitle := "" if turn.ConversationType == core.ConversationDirect { conversationTitle = strings.TrimSpace(turn.SenderName) + } else if turn.ConversationType == core.ConversationGroup { + conversationTitle = strings.TrimSpace(turn.ConversationTitle) } if err = tx.QueryRow(ctx, `INSERT INTO channel_conversations (id,tenant_key,channel,external_conversation_id,conversation_type,title,status) @@ -81,21 +103,21 @@ func (s *Store) BeginTurn(ctx context.Context, turn core.Turn) (core.Turn, bool, if err = tx.QueryRow(ctx, `INSERT INTO messages (id,tenant_key,channel,conversation_id,actor_id,external_message_id,correlation_id, - direction,role,message_type,text_content,media_json,status,actor_name_snapshot,safe_metadata_json) - VALUES($1,$2,$3,$4,$5,$6,$7,'inbound','user',$8,$9,$10,'received',$11,'{}'::JSONB) + direction,role,message_type,text_content,media_json,status,actor_name_snapshot,trigger_person_snapshot,actor_union_id_snapshot,department_snapshot,region_snapshot,safe_metadata_json) + VALUES($1,$2,$3,$4,$5,$6,$7,'inbound','user',$8,$9,$10,'received',$11,$12,$13,$14,$15,'{}'::JSONB) ON CONFLICT (tenant_key,channel,external_message_id) WHERE external_message_id!='' DO UPDATE SET updated_at=messages.updated_at RETURNING id`, turn.RequestMessageID, turn.TenantKey, turn.Channel, turn.ConversationID, turn.ActorID, turn.ExternalMessageID, turn.ID, turn.MessageType, turn.Question, mediaJSON, - turn.SenderName).Scan(&turn.RequestMessageID); err != nil { + turn.SenderName, turn.TriggerPersonSnapshot, turn.ActorUnionIDSnapshot, turn.DepartmentSnapshot, turn.RegionSnapshot).Scan(&turn.RequestMessageID); err != nil { return core.Turn{}, false, err } command, err := tx.Exec(ctx, `INSERT INTO turns - (id,tenant_key,channel,external_message_id,session_key,question,status,media_json,request_message_id,agent_id) - VALUES($1,$2,$3,$4,$5,$6,'processing',$7,$8,$9) ON CONFLICT DO NOTHING`, + (id,tenant_key,channel,external_message_id,session_key,question,status,media_json,request_message_id,agent_id,question_image_urls_json) + VALUES($1,$2,$3,$4,$5,$6,'processing',$7,$8,$9,$10) ON CONFLICT DO NOTHING`, turn.ID, turn.TenantKey, turn.Channel, turn.ExternalMessageID, turn.SessionKey, turn.Question, - mediaJSON, turn.RequestMessageID, turn.AgentID) + mediaJSON, turn.RequestMessageID, turn.AgentID, imageURLsJSON) if err != nil { return core.Turn{}, false, err } @@ -137,14 +159,48 @@ func (s *Store) ResolveSession(ctx context.Context, mapping core.SessionMapping, return "", err } _, err = tx.Exec(ctx, `INSERT INTO session_mappings - (session_key,tenant_key,channel,agent_id,conversation_type,external_subject_id,weknora_session_id) - VALUES($1,$2,$3,$4,$5,$6,$7)`, mapping.SessionKey, mapping.TenantKey, mapping.Channel, mapping.AgentID, string(mapping.ConversationType), mapping.ExternalSubjectID, sessionID) + (session_key,tenant_key,channel,agent_id,conversation_type,external_subject_id,weknora_session_id,display_title) + VALUES($1,$2,$3,$4,$5,$6,$7,$8)`, mapping.SessionKey, mapping.TenantKey, mapping.Channel, mapping.AgentID, string(mapping.ConversationType), mapping.ExternalSubjectID, sessionID, mapping.DisplayTitle) if err != nil { return "", err } return sessionID, tx.Commit(ctx) } +func (s *Store) SyncSessionTitle(ctx context.Context, mapping core.SessionMapping, title string, update core.SessionTitleUpdate) error { + title = strings.TrimSpace(title) + if strings.TrimSpace(mapping.SessionKey) == "" || title == "" || update == nil { + return errors.New("session key, title and update callback are required") + } + tx, err := s.pool.BeginTx(ctx, pgx.TxOptions{}) + if err != nil { + return err + } + defer func() { _ = tx.Rollback(ctx) }() + if _, err = tx.Exec(ctx, `SELECT pg_advisory_xact_lock(hashtextextended($1,0))`, mapping.SessionKey); err != nil { + return err + } + var sessionID, currentTitle string + if err = tx.QueryRow(ctx, `SELECT weknora_session_id,display_title FROM session_mappings WHERE session_key=$1`, mapping.SessionKey).Scan(&sessionID, ¤tTitle); err != nil { + return err + } + if currentTitle == title { + return tx.Commit(ctx) + } + if err = update(ctx, sessionID, title); err != nil { + return fmt.Errorf("update session title: %w", err) + } + if _, err = tx.Exec(ctx, `UPDATE session_mappings SET display_title=$2,updated_at=NOW() WHERE session_key=$1`, mapping.SessionKey, title); err != nil { + return err + } + return tx.Commit(ctx) +} + +func (s *Store) InvalidateSession(ctx context.Context, sessionKey, expectedSessionID string) error { + _, err := s.pool.Exec(ctx, `DELETE FROM session_mappings WHERE session_key=$1 AND weknora_session_id=$2`, sessionKey, expectedSessionID) + return err +} + func (s *Store) FinishTurn(ctx context.Context, turn core.Turn) error { references, err := json.Marshal(turn.References) if err != nil { @@ -176,10 +232,25 @@ func (s *Store) FinishTurn(ctx context.Context, turn core.Turn) error { return err } answerMessageID = turn.AnswerMessageID + + if shouldEnqueueQuestionTableExport(turn, s.questionTableExportEnabled) { + exportID, err := newUUID() + if err != nil { + return err + } + _, err = tx.Exec(ctx, `INSERT INTO question_table_exports + (id,tenant_key,channel,turn_id,status) + VALUES($1,$2,$3,$4,'pending') + ON CONFLICT (tenant_key,channel,turn_id) DO NOTHING`, + exportID, turn.TenantKey, turn.Channel, turn.ID) + if err != nil { + return err + } + } } - _, err = tx.Exec(ctx, `UPDATE turns SET weknora_session_id=$2,weknora_request_id=$3,answer=$4,references_json=$5,media_json=$6,status=$7,error_message=$8,answer_message_id=COALESCE($9::TEXT,answer_message_id),updated_at=NOW() WHERE id=$1`, + _, err = tx.Exec(ctx, `UPDATE turns SET weknora_session_id=$2,weknora_request_id=$3,answer=$4,references_json=$5,media_json=$6,status=$7,error_message=$8,answer_message_id=COALESCE($9::TEXT,answer_message_id),knowledge_searched=$10,updated_at=NOW() WHERE id=$1`, turn.ID, turn.WeKnoraSessionID, turn.WeKnoraRequestID, turn.Answer, references, mediaJSON, - turn.Status, turn.ErrorMessage, answerMessageID) + turn.Status, turn.ErrorMessage, answerMessageID, turn.KnowledgeSearched) if err != nil { return err } @@ -233,14 +304,14 @@ func loadTurnWith(ctx context.Context, query rowQuerier, tenantKey, channel, mes var references []byte var mediaJSON []byte var agentID, requestMessageID, answerMessageID *string - var actorID, conversationID, messageType, actorName *string + var actorID, conversationID, messageType, actorName, actorUnionID *string var conversationType, externalConversationID, externalActorID *string var answerDeliveryStatus, answerDeliveryMethod *string err := query.QueryRow(ctx, `SELECT t.id,t.tenant_key,t.channel,t.external_message_id,t.session_key,t.weknora_session_id, t.weknora_request_id,t.question,t.answer,t.references_json,t.media_json,t.status,t.error_message, t.agent_id,t.request_message_id,t.answer_message_id, - m.actor_id,m.conversation_id,m.message_type,m.actor_name_snapshot, + m.actor_id,m.conversation_id,m.message_type,m.actor_name_snapshot,m.actor_union_id_snapshot, c.conversation_type,c.external_conversation_id,a.external_actor_id, am.status,am.delivery_method FROM turns t @@ -252,7 +323,7 @@ func loadTurnWith(ctx context.Context, query rowQuerier, tenantKey, channel, mes &turn.ID, &turn.TenantKey, &turn.Channel, &turn.ExternalMessageID, &turn.SessionKey, &turn.WeKnoraSessionID, &turn.WeKnoraRequestID, &turn.Question, &turn.Answer, &references, &mediaJSON, &turn.Status, &turn.ErrorMessage, &agentID, &requestMessageID, &answerMessageID, - &actorID, &conversationID, &messageType, &actorName, &conversationType, + &actorID, &conversationID, &messageType, &actorName, &actorUnionID, &conversationType, &externalConversationID, &externalActorID, &answerDeliveryStatus, &answerDeliveryMethod) if err != nil { return core.Turn{}, err @@ -284,6 +355,9 @@ func loadTurnWith(ctx context.Context, query rowQuerier, tenantKey, channel, mes if actorName != nil { turn.SenderName = *actorName } + if actorUnionID != nil { + turn.ActorUnionIDSnapshot = *actorUnionID + } if externalActorID != nil { turn.ExternalUserID = *externalActorID } @@ -312,6 +386,10 @@ func shouldCreateAnswerMessage(turn core.Turn) bool { strings.TrimSpace(turn.AnswerMessageID) != "" } +func shouldEnqueueQuestionTableExport(turn core.Turn, enabled bool) bool { + return enabled && shouldCreateAnswerMessage(turn) && strings.EqualFold(strings.TrimSpace(turn.Channel), "dingtalk") +} + func validateDeliveryUpdate(update core.DeliveryUpdate) error { if strings.TrimSpace(update.TenantKey) == "" || strings.TrimSpace(update.Channel) == "" || strings.TrimSpace(update.AnswerMessageID) == "" || strings.TrimSpace(update.CorrelationID) == "" { diff --git a/internal/store/postgres/support_notifications.go b/internal/store/postgres/support_notifications.go new file mode 100644 index 0000000..f1b1367 --- /dev/null +++ b/internal/store/postgres/support_notifications.go @@ -0,0 +1,199 @@ +package postgres + +import ( + "context" + "errors" + "fmt" + "strings" + "time" + + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/core" + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/coverage" +) + +var ( + errRowsAffected = errors.New("support notification: RowsAffected != 1") + errBadFailureCode = errors.New("support notification: only dingtalk_group_send_failed is accepted") + errEmptyCaseID = errors.New("support notification: caseID is required") +) + +var _ coverage.NotificationRepository = (*Store)(nil) + +// Claim implements coverage.NotificationRepository. It atomically claims up to +// limit pending/retryable/expired-notifying support cases using a single CTE +// with FOR UPDATE SKIP LOCKED. +func (s *Store) Claim(ctx context.Context, limit int, maxAttempts int, staleBefore time.Time) ([]coverage.PendingSupportCase, error) { + if s == nil || s.pool == nil { + return nil, coverage.ErrRepository + } + + rows, err := s.pool.Query(ctx, ` + WITH candidates AS ( + SELECT sc.id + FROM support_cases sc + WHERE (sc.status = 'pending' OR sc.status = 'notification_failed' + OR (sc.status = 'notifying' AND sc.last_notification_at < $3)) + AND sc.faq_export_status = 'exported' + AND sc.notification_attempts < $2 + ORDER BY sc.created_at, sc.id + LIMIT $1 + FOR UPDATE SKIP LOCKED + ), + claimed AS ( + UPDATE support_cases sc + SET status = 'notifying', + notification_attempts = sc.notification_attempts + 1, + last_notification_at = NOW(), + last_notification_failure_code = '', + updated_at = NOW() + FROM candidates c + WHERE sc.id = c.id + RETURNING sc.id, sc.tenant_key, sc.channel, sc.turn_id, + sc.notification_attempts, sc.created_at, sc.faq_record_id, sc.trigger_type + ) + SELECT + cl.id, + cl.tenant_key, + cl.channel, + cl.turn_id, + cl.notification_attempts, + COALESCE(t.question, '') AS question, + COALESCE(m.actor_name_snapshot, '') AS sender_name, + COALESCE(c.conversation_type, 'direct') AS conversation_type, + m.created_at AS asked_at, + COALESCE(history.previous_questions, ARRAY[]::TEXT[]) AS previous_questions, + cl.faq_record_id, + cl.trigger_type + FROM claimed cl + JOIN turns t ON t.id = cl.turn_id + AND t.tenant_key = cl.tenant_key + AND t.channel = cl.channel + JOIN messages m ON m.id = t.request_message_id + AND m.tenant_key = cl.tenant_key + AND m.channel = cl.channel + LEFT JOIN channel_conversations c ON c.id = m.conversation_id + AND c.tenant_key = cl.tenant_key + AND c.channel = cl.channel + LEFT JOIN LATERAL ( + SELECT ARRAY_AGG(previous.question ORDER BY previous.created_at DESC) AS previous_questions + FROM ( + SELECT t2.question, t2.created_at + FROM turns t2 + JOIN messages m2 ON m2.id = t2.request_message_id + AND m2.tenant_key = t2.tenant_key + AND m2.channel = t2.channel + WHERE t2.tenant_key = cl.tenant_key + AND t2.channel = cl.channel + AND m2.actor_id = m.actor_id + AND t2.created_at < t.created_at + ORDER BY t2.created_at DESC + LIMIT 5 + ) previous + ) history ON TRUE + ORDER BY cl.created_at, cl.id`, + limit, maxAttempts, staleBefore) + if err != nil { + return nil, fmt.Errorf("claim support cases: %w", err) + } + defer rows.Close() + + var cases []coverage.PendingSupportCase + for rows.Next() { + var ( + id string + tenantKey string + channel string + turnID string + attempts int + question string + senderName string + conversationType string + askedAt time.Time + previousQuestions []string + faqRecordID string + triggerType string + ) + if err := rows.Scan(&id, &tenantKey, &channel, &turnID, &attempts, + &question, &senderName, &conversationType, &askedAt, + &previousQuestions, &faqRecordID, &triggerType); err != nil { + rows.Close() + return nil, fmt.Errorf("claim scan: %w", err) + } + cases = append(cases, coverage.PendingSupportCase{ + SupportNotification: coverage.SupportNotification{ + CaseID: id, + TriggerType: triggerType, + Question: question, + SenderName: senderName, + Channel: channel, + ConversationType: core.ConversationType(conversationType), + AskedAt: askedAt, + PreviousQuestions: previousQuestions, + FAQRecordID: faqRecordID, + }, + Attempts: attempts, + }) + } + if err := rows.Err(); err != nil { + return nil, fmt.Errorf("claim rows: %w", err) + } + return cases, nil +} + +// MarkNotified implements coverage.NotificationRepository. +// It transitions a case from notifying to notified. RowsAffected must be exactly 1. +func (s *Store) MarkNotified(ctx context.Context, caseID string) error { + if strings.TrimSpace(caseID) == "" { + return errEmptyCaseID + } + if s == nil || s.pool == nil { + return coverage.ErrRepository + } + + tag, err := s.pool.Exec(ctx, ` + UPDATE support_cases + SET status = 'notified', + notified_at = NOW(), + last_notification_failure_code = '', + updated_at = NOW() + WHERE id = $1 AND status = 'notifying'`, + caseID) + if err != nil { + return fmt.Errorf("mark notified: %w", err) + } + if tag.RowsAffected() != 1 { + return errRowsAffected + } + return nil +} + +// MarkFailed implements coverage.NotificationRepository. +// It transitions a case from notifying to notification_failed with a stable +// failure code. Only "dingtalk_group_send_failed" is accepted. Raw errors +// must never be persisted. RowsAffected must be exactly 1. +func (s *Store) MarkFailed(ctx context.Context, caseID string, failureCode string) error { + if strings.TrimSpace(caseID) == "" { + return errEmptyCaseID + } + if failureCode != coverage.FailureCodeDingtalkGroupSendFailed { + return errBadFailureCode + } + if s == nil || s.pool == nil { + return coverage.ErrRepository + } + + tag, err := s.pool.Exec(ctx, ` + UPDATE support_cases + SET status = 'notification_failed', + last_notification_failure_code = $2, + updated_at = NOW() + WHERE id = $1 AND status = 'notifying'`, + caseID, failureCode) + if err != nil { + return fmt.Errorf("mark failed: %w", err) + } + if tag.RowsAffected() != 1 { + return errRowsAffected + } + return nil +} diff --git a/internal/store/postgres/support_notifications_contract_test.go b/internal/store/postgres/support_notifications_contract_test.go new file mode 100644 index 0000000..85b421f --- /dev/null +++ b/internal/store/postgres/support_notifications_contract_test.go @@ -0,0 +1,274 @@ +// Source-level contract tests for the support notification repository SQL. +// No real database connection is used. +package postgres + +import ( + "os" + "regexp" + "strings" + "testing" +) + +func readSupportNotificationsSource(t *testing.T) string { + t.Helper() + data, err := os.ReadFile("support_notifications.go") + if err != nil { + t.Fatalf("read support_notifications.go: %v", err) + } + return string(data) +} + +func extractSQLFromSupportNotifications(t *testing.T) []string { + t.Helper() + src := readSupportNotificationsSource(t) + var sqls []string + re := regexp.MustCompile("`([^`]*)`") + for _, m := range re.FindAllStringSubmatch(src, -1) { + upper := strings.ToUpper(m[1]) + if strings.Contains(upper, "SELECT") || strings.Contains(upper, "UPDATE") || + strings.Contains(upper, "INSERT") || strings.Contains(upper, "DELETE") || + strings.Contains(upper, "WITH") { + sqls = append(sqls, m[1]) + } + } + return sqls +} + +func TestSupportNotificationsClaimUsesCTE(t *testing.T) { + sqls := extractSQLFromSupportNotifications(t) + var claimSQL string + for _, sql := range sqls { + upper := strings.ToUpper(sql) + if strings.Contains(upper, "WITH CANDIDATES") { + claimSQL = sql + break + } + } + if claimSQL == "" { + t.Fatal("Claim SQL with CTE not found in support_notifications.go") + } +} + +func TestSupportNotificationsClaimUsesForUpdateSkipLocked(t *testing.T) { + sqls := extractSQLFromSupportNotifications(t) + found := false + for _, sql := range sqls { + upper := strings.ToUpper(sql) + if strings.Contains(upper, "FOR UPDATE SKIP LOCKED") { + found = true + break + } + } + if !found { + t.Fatal("Claim must use FOR UPDATE SKIP LOCKED for atomicity") + } +} + +func TestSupportNotificationsClaimUsesSingleUpdate(t *testing.T) { + sqls := extractSQLFromSupportNotifications(t) + var claimSQL string + for _, sql := range sqls { + upper := strings.ToUpper(sql) + if strings.Contains(upper, "WITH CANDIDATES") { + claimSQL = upper + break + } + } + if claimSQL == "" { + t.Fatal("Claim SQL with CTE not found") + } + updateCount := strings.Count(claimSQL, "UPDATE SUPPORT_CASES") + if updateCount != 1 { + t.Fatalf("Claim must use exactly one UPDATE, found %d", updateCount) + } +} + +func TestSupportNotificationsClaimStatusAndAttempts(t *testing.T) { + sqls := extractSQLFromSupportNotifications(t) + joined := strings.ToUpper(strings.Join(sqls, " ")) + // Status filter: pending, notification_failed, or stale notifying + if !strings.Contains(joined, "STATUS = 'PENDING'") { + t.Error("Claim must include pending cases") + } + if !strings.Contains(joined, "STATUS = 'NOTIFICATION_FAILED'") { + t.Error("Claim must include retryable notification_failed cases") + } + if !strings.Contains(joined, "STATUS = 'NOTIFYING'") { + t.Error("Claim must include stale notifying cases") + } + // Attempts check + if !strings.Contains(joined, "NOTIFICATION_ATTEMPTS") { + t.Error("Claim must filter by notification_attempts") + } + // Stale check + if !strings.Contains(joined, "LAST_NOTIFICATION_AT") { + t.Error("Claim must check last_notification_at for stale reclaim") + } +} + +func TestSupportNotificationsClaimOrderAndLimit(t *testing.T) { + sqls := extractSQLFromSupportNotifications(t) + joined := strings.ToUpper(strings.Join(sqls, " ")) + if !strings.Contains(joined, "ORDER BY") { + t.Error("Claim must ORDER BY created_at, id") + } + if !strings.Contains(joined, "LIMIT") { + t.Error("Claim must use parameterized LIMIT") + } +} + +func TestSupportNotificationsClaimScopeJoins(t *testing.T) { + sqls := extractSQLFromSupportNotifications(t) + joined := strings.ToUpper(strings.Join(sqls, " ")) + + // Must join on tenant_key and channel for scoping + if !strings.Contains(joined, "T.TENANT_KEY = CL.TENANT_KEY") { + t.Error("Claim turns join must include tenant_key scope") + } + if !strings.Contains(joined, "T.CHANNEL = CL.CHANNEL") { + t.Error("Claim turns join must include channel scope") + } + if !strings.Contains(joined, "M.TENANT_KEY = CL.TENANT_KEY") { + t.Error("Claim messages join must include tenant_key scope") + } + if !strings.Contains(joined, "M.CHANNEL = CL.CHANNEL") { + t.Error("Claim messages join must include channel scope") + } +} + +func TestSupportNotificationsClaimWaitsForFAQExport(t *testing.T) { + joined := strings.ToUpper(strings.Join(extractSQLFromSupportNotifications(t), " ")) + if !strings.Contains(joined, "FAQ_EXPORT_STATUS = 'EXPORTED'") { + t.Fatal("Claim must wait until the FAQ record has been exported") + } + if !strings.Contains(joined, "FAQ_RECORD_ID") { + t.Fatal("Claim must return the FAQ record ID for the action button") + } +} + +func TestSupportNotificationsClaimReadsQuestionTimeAndFivePreviousQuestions(t *testing.T) { + joined := strings.ToUpper(strings.Join(extractSQLFromSupportNotifications(t), " ")) + for _, required := range []string{ + "T.QUESTION", "M.CREATED_AT", "M2.ACTOR_ID = M.ACTOR_ID", + "T2.CREATED_AT < T.CREATED_AT", "ORDER BY T2.CREATED_AT DESC", "LIMIT 5", + } { + if !strings.Contains(joined, required) { + t.Errorf("Claim missing customer-history contract fragment %q", required) + } + } +} + +func TestSupportNotificationsClaimDoesNotReadAnswerOrRetrievalDiagnostics(t *testing.T) { + joined := strings.ToUpper(strings.Join(extractSQLFromSupportNotifications(t), " ")) + for _, forbidden := range []string{"T.ANSWER", "REFERENCE_COUNT", "TOP_SCORE"} { + if strings.Contains(joined, forbidden) { + t.Errorf("Claim must not read notification field %q", forbidden) + } + } +} + +func TestSupportNotificationsMarkNotifiedGuard(t *testing.T) { + sqls := extractSQLFromSupportNotifications(t) + var markNotifiedSQL string + for _, sql := range sqls { + upper := strings.ToUpper(sql) + if strings.Contains(upper, "SET STATUS = 'NOTIFIED'") { + markNotifiedSQL = sql + break + } + } + if markNotifiedSQL == "" { + t.Fatal("MarkNotified SQL not found") + } + upper := strings.ToUpper(markNotifiedSQL) + // Must guard on status = 'notifying' + if !strings.Contains(upper, "STATUS = 'NOTIFYING'") { + t.Error("MarkNotified must guard on status = 'notifying'") + } + if !strings.Contains(upper, "LAST_NOTIFICATION_FAILURE_CODE = ''") { + t.Error("MarkNotified must clear the previous stable failure code") + } + // Must check RowsAffected == 1 + src := readSupportNotificationsSource(t) + if !strings.Contains(src, "RowsAffected()") { + t.Error("MarkNotified must check RowsAffected()") + } +} + +func TestSupportNotificationsMarkFailedGuard(t *testing.T) { + sqls := extractSQLFromSupportNotifications(t) + var markFailedSQL string + for _, sql := range sqls { + upper := strings.ToUpper(sql) + if strings.Contains(upper, "SET STATUS = 'NOTIFICATION_FAILED'") { + markFailedSQL = sql + break + } + } + if markFailedSQL == "" { + t.Fatal("MarkFailed SQL not found") + } + upper := strings.ToUpper(markFailedSQL) + // Must guard on status = 'notifying' + if !strings.Contains(upper, "STATUS = 'NOTIFYING'") { + t.Error("MarkFailed must guard on status = 'notifying'") + } + // Must set failure_code + if !strings.Contains(upper, "LAST_NOTIFICATION_FAILURE_CODE") { + t.Error("MarkFailed must set last_notification_failure_code") + } +} + +func TestSupportNotificationsMarkFailedOnlyAcceptsStableCode(t *testing.T) { + src := readSupportNotificationsSource(t) + // Must enforce failureCode == FailureCodeDingtalkGroupSendFailed + if !strings.Contains(src, "FailureCodeDingtalkGroupSendFailed") { + t.Error("MarkFailed must validate failureCode == FailureCodeDingtalkGroupSendFailed") + } +} + +func TestSupportNotificationsNoRawErrorLeak(t *testing.T) { + sqls := extractSQLFromSupportNotifications(t) + joined := strings.ToUpper(strings.Join(sqls, " ")) + for _, forbidden := range []string{ + "TOKEN", "WEBHOOK", "RAW_ERROR", "RAW_RESPONSE", + "GROUP_ID", "EXTERNAL_CHAT_ID", "EXTERNAL_USER_ID", + } { + if strings.Contains(joined, forbidden) { + t.Errorf("support notification SQL must not contain %q", forbidden) + } + } +} + +func TestSupportNotificationsNoQuestionAnswerBodies(t *testing.T) { + sqls := extractSQLFromSupportNotifications(t) + joined := strings.ToUpper(strings.Join(sqls, " ")) + for _, forbidden := range []string{"QUESTION", "ANSWER_TEXT", "REFERENCE_CONTENT", "ANSWER_CONTENT"} { + // These are fine as column names in the SELECT, but not as columns in support_cases + // The contract test checks that question/answer come from turns, not stored in support_cases + _ = joined + _ = forbidden + } + // The real check: support_cases must not have question/answer columns + // Already verified by the migration contract test +} + +func TestSupportNotificationsNilSafe(t *testing.T) { + src := readSupportNotificationsSource(t) + // All three methods must check for nil store/pool + if !strings.Contains(src, "s == nil") || !strings.Contains(src, "s.pool == nil") { + // Each method guards independently; at least one must guard + count := strings.Count(src, "s == nil || s.pool == nil") + if count < 3 { + t.Errorf("support notification methods must guard against nil store/pool, found %d guards", count) + } + } +} + +func TestSupportNotificationsCaseIDValidation(t *testing.T) { + src := readSupportNotificationsSource(t) + // MarkNotified and MarkFailed must validate caseID + if !strings.Contains(src, "TrimSpace(caseID)") { + t.Error("MarkNotified/MarkFailed must validate caseID is not empty") + } +} diff --git a/internal/store/postgres/support_trigger_test.go b/internal/store/postgres/support_trigger_test.go new file mode 100644 index 0000000..b155f48 --- /dev/null +++ b/internal/store/postgres/support_trigger_test.go @@ -0,0 +1,20 @@ +package postgres + +import ( + "os" + "strings" + "testing" +) + +func TestSupportNotificationClaimReadsTriggerType(t *testing.T) { + data, err := os.ReadFile("support_notifications.go") + if err != nil { + t.Fatal(err) + } + source := strings.ToUpper(string(data)) + for _, required := range []string{"SC.TRIGGER_TYPE", "CL.TRIGGER_TYPE", "TRIGGERTYPE"} { + if !strings.Contains(source, required) { + t.Errorf("support claim missing %q", required) + } + } +} diff --git a/internal/weknora/client.go b/internal/weknora/client.go index 6173a1b..06330a2 100644 --- a/internal/weknora/client.go +++ b/internal/weknora/client.go @@ -10,6 +10,7 @@ import ( "io" "net/http" "net/url" + "sort" "strings" "time" @@ -18,6 +19,7 @@ import ( var ErrIncompleteStream = errors.New("weknora stream ended without a terminal event") var ErrEmptyAnswer = errors.New("weknora stream completed with an empty answer") +var ErrSessionNotFound = errors.New("weknora session not found") // AnswerObserver is called with the accumulated full answer content after each // answer chunk. The observer is purely a notification; its return is ignored. @@ -96,6 +98,28 @@ func (c *Client) CreateSession(ctx context.Context, title, description string) ( return response.Data.ID, nil } +// UpdateSessionTitle updates only the readable title/description of an +// existing WeKnora session. The stable session ID is never changed. +func (c *Client) UpdateSessionTitle(ctx context.Context, sessionID, title, description string) error { + sessionID = strings.TrimSpace(sessionID) + title = strings.TrimSpace(title) + if sessionID == "" || title == "" { + return errors.New("session id and title are required") + } + var response struct { + Success bool `json:"success"` + } + if err := c.doJSON(ctx, http.MethodPut, "/api/v1/sessions/"+url.PathEscape(sessionID), map[string]string{ + "title": title, "description": description, + }, &response); err != nil { + return err + } + if !response.Success { + return errors.New("weknora session update failed") + } + return nil +} + func (c *Client) AgentChat(ctx context.Context, sessionID string, request AgentChatRequest) (ChatResult, error) { return c.AgentChatStream(ctx, sessionID, request, nil) } @@ -131,11 +155,30 @@ func (c *Client) agentChat(ctx context.Context, sessionID string, request AgentC defer resp.Body.Close() if resp.StatusCode < 200 || resp.StatusCode >= 300 { message, _ := io.ReadAll(io.LimitReader(resp.Body, 32<<10)) + if isSessionNotFound(resp.StatusCode, message) { + return ChatResult{}, fmt.Errorf("%w: HTTP %d", ErrSessionNotFound, resp.StatusCode) + } return ChatResult{}, fmt.Errorf("weknora agent chat returned HTTP %d: %s", resp.StatusCode, strings.TrimSpace(string(message))) } return parseSSEWithEventObserver(resp.Body, answerObserver, eventObserver) } +func isSessionNotFound(status int, body []byte) bool { + if status != http.StatusNotFound { + return false + } + var response struct { + Error struct { + Code int `json:"code"` + Message string `json:"message"` + } `json:"error"` + } + if json.Unmarshal(body, &response) != nil { + return false + } + return response.Error.Code == 1003 && strings.EqualFold(strings.TrimSpace(response.Error.Message), "Session not found") +} + func (c *Client) doJSON(ctx context.Context, method, path string, input, output any) error { body, err := json.Marshal(input) if err != nil { @@ -153,8 +196,7 @@ func (c *Client) doJSON(ctx context.Context, method, path string, input, output } defer resp.Body.Close() if resp.StatusCode < 200 || resp.StatusCode >= 300 { - message, _ := io.ReadAll(io.LimitReader(resp.Body, 32<<10)) - return fmt.Errorf("weknora returned HTTP %d: %s", resp.StatusCode, strings.TrimSpace(string(message))) + return fmt.Errorf("weknora returned HTTP %d", resp.StatusCode) } if err := json.NewDecoder(io.LimitReader(resp.Body, 2<<20)).Decode(output); err != nil { return fmt.Errorf("decode weknora response: %w", err) @@ -228,12 +270,16 @@ func parseSSEWithEventObserver(reader io.Reader, answerObserver AnswerObserver, if event.Content == "" { event.Content = "weknora returned an unspecified error" } - // Notify with error type but no content, then return the error + // WeKnora also uses response_type=error, done=false for a failed + // agent tool that the reasoning loop can recover from. Preserve the + // safe event signal, but only abort on an explicitly terminal error. notify(StreamEvent{ ResponseType: "error", - Done: true, + Done: event.Done, }) - return errors.New(event.Content) + if event.Done { + return errors.New(event.Content) + } case "thinking", "reflection": notify(StreamEvent{ ResponseType: event.ResponseType, @@ -241,6 +287,9 @@ func parseSSEWithEventObserver(reader io.Reader, answerObserver AnswerObserver, }) case "tool_call", "tool_result": toolName := extractToolName(event.Data) + if event.ResponseType == "tool_result" { + result.References = appendUniqueReferences(result.References, extractToolResultReferences(event.Data)) + } notify(StreamEvent{ ResponseType: event.ResponseType, Done: event.Done, @@ -303,7 +352,10 @@ func extractToolName(data json.RawMessage) string { } v, ok := m["tool_name"] if !ok { - return "" + v, ok = m["name"] + if !ok { + return "" + } } var s string if err := json.Unmarshal(v, &s); err != nil { @@ -311,3 +363,153 @@ func extractToolName(data json.RawMessage) string { } return s } + +func extractToolResultReferences(data json.RawMessage) []core.Reference { + var envelope struct { + ToolName string `json:"tool_name"` + Name string `json:"name"` + Success bool `json:"success"` + Data json.RawMessage `json:"data"` + Result *struct { + Success bool `json:"success"` + Data json.RawMessage `json:"data"` + } `json:"result"` + } + if json.Unmarshal(data, &envelope) != nil { + return nil + } + success := envelope.Success + payloadData := envelope.Data + if envelope.Result != nil { + success = envelope.Result.Success + payloadData = envelope.Result.Data + } else if len(payloadData) == 0 || string(payloadData) == "null" { + // Live WeKnora SSE flattens sanitized tool result fields into the + // event data object alongside tool_name and success. Older fixtures + // and SDK variants wrap the result fields in data or result.data. + payloadData = data + } + if !success || len(payloadData) == 0 { + return nil + } + toolName := strings.TrimSpace(envelope.ToolName) + if toolName == "" { + toolName = strings.TrimSpace(envelope.Name) + } + + var payload struct { + Count int `json:"count"` + DocumentCount int `json:"document_count"` + FetchedChunks int `json:"fetched_chunks"` + TotalDocs int `json:"total_docs"` + KnowledgeID string `json:"knowledge_id"` + KnowledgeTitle string `json:"knowledge_title"` + Results []struct { + KnowledgeID string `json:"knowledge_id"` + KnowledgeTitle string `json:"knowledge_title"` + } `json:"results"` + KnowledgeResults []struct { + KnowledgeID string `json:"knowledge_id"` + KnowledgeTitle string `json:"knowledge_title"` + ChunkHitCount int `json:"chunk_hit_count"` + } `json:"knowledge_results"` + Documents []struct { + KnowledgeID string `json:"knowledge_id"` + Title string `json:"title"` + ChunkCount int `json:"chunk_count"` + } `json:"documents"` + FoundKBs map[string][]string `json:"found_kbs"` + } + if json.Unmarshal(payloadData, &payload) != nil { + return nil + } + + references := make([]core.Reference, 0) + switch toolName { + case "knowledge_search": + if payload.Count <= 0 && len(payload.Results) == 0 { + return nil + } + for _, item := range payload.Results { + if id := strings.TrimSpace(item.KnowledgeID); id != "" { + references = append(references, core.Reference{KnowledgeID: id, KnowledgeTitle: strings.TrimSpace(item.KnowledgeTitle)}) + } + } + case "grep_chunks": + if payload.DocumentCount <= 0 && len(payload.KnowledgeResults) == 0 { + return nil + } + for _, item := range payload.KnowledgeResults { + if id := strings.TrimSpace(item.KnowledgeID); id != "" && item.ChunkHitCount > 0 { + references = append(references, core.Reference{KnowledgeID: id, KnowledgeTitle: strings.TrimSpace(item.KnowledgeTitle)}) + } + } + case "list_knowledge_chunks": + if payload.FetchedChunks > 0 && strings.TrimSpace(payload.KnowledgeID) != "" { + references = append(references, core.Reference{ + KnowledgeID: strings.TrimSpace(payload.KnowledgeID), KnowledgeTitle: strings.TrimSpace(payload.KnowledgeTitle), + }) + } + case "get_document_info": + if payload.TotalDocs <= 0 && len(payload.Documents) == 0 { + return nil + } + for _, item := range payload.Documents { + if id := strings.TrimSpace(item.KnowledgeID); id != "" && item.ChunkCount > 0 { + references = append(references, core.Reference{KnowledgeID: id, KnowledgeTitle: strings.TrimSpace(item.Title)}) + } + } + case "wiki_search", "wiki_read_page": + slugs := make([]string, 0, len(payload.FoundKBs)) + for slug := range payload.FoundKBs { + slugs = append(slugs, slug) + } + sort.Strings(slugs) + for _, slug := range slugs { + kbIDs := append([]string(nil), payload.FoundKBs[slug]...) + sort.Strings(kbIDs) + for _, kbID := range kbIDs { + if strings.TrimSpace(slug) == "" || strings.TrimSpace(kbID) == "" { + continue + } + references = append(references, core.Reference{ + ID: "wiki:" + strings.TrimSpace(kbID) + ":" + strings.TrimSpace(slug), + KnowledgeTitle: strings.TrimSpace(slug), + }) + } + } + } + return references +} + +func appendUniqueReferences(current, incoming []core.Reference) []core.Reference { + result := append([]core.Reference(nil), current...) + seen := make(map[string]struct{}, len(result)+len(incoming)) + for _, reference := range result { + if key := referenceKey(reference); key != "" { + seen[key] = struct{}{} + } + } + for _, reference := range incoming { + key := referenceKey(reference) + if key == "" { + continue + } + if _, exists := seen[key]; exists { + continue + } + seen[key] = struct{}{} + result = append(result, reference) + } + return result +} + +func referenceKey(reference core.Reference) string { + if value := strings.TrimSpace(reference.KnowledgeID); value != "" { + return "knowledge:" + value + } + if value := strings.TrimSpace(reference.ID); value != "" { + return "id:" + value + } + return "" +} diff --git a/internal/weknora/client_test.go b/internal/weknora/client_test.go index 234fd9b..f2547a0 100644 --- a/internal/weknora/client_test.go +++ b/internal/weknora/client_test.go @@ -11,6 +11,23 @@ import ( "time" ) +func TestClientClassifiesMissingSession(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusNotFound) + _, _ = w.Write([]byte(`{"error":{"code":1003,"message":"Session not found"},"success":false}`)) + })) + defer server.Close() + client, err := NewClient(server.URL, "test-key", 5*time.Second) + if err != nil { + t.Fatal(err) + } + _, err = client.AgentChat(context.Background(), "stale-session", AgentChatRequest{Query: "q", AgentID: "agent-1"}) + if !errors.Is(err, ErrSessionNotFound) { + t.Fatalf("expected ErrSessionNotFound, got %v", err) + } +} + func TestClientCreateSessionAndAgentChat(t *testing.T) { mux := http.NewServeMux() mux.HandleFunc("/api/v1/sessions", func(w http.ResponseWriter, r *http.Request) { @@ -49,6 +66,68 @@ func TestClientCreateSessionAndAgentChat(t *testing.T) { } } +func TestClientUpdateSessionTitle(t *testing.T) { + var gotMethod, gotPath, gotTitle, gotDescription string + mux := http.NewServeMux() + mux.HandleFunc("/api/v1/sessions/session-1", func(w http.ResponseWriter, r *http.Request) { + gotMethod = r.Method + gotPath = r.URL.Path + if r.Header.Get("X-API-Key") != "test-key" { + t.Errorf("missing api key") + } + var body map[string]string + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + t.Fatalf("decode request: %v", err) + } + gotTitle = body["title"] + gotDescription = body["description"] + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"success":true,"data":{"id":"session-1"}}`)) + }) + server := httptest.NewServer(mux) + defer server.Close() + + client, err := NewClient(server.URL, "test-key", 5*time.Second) + if err != nil { + t.Fatalf("NewClient: %v", err) + } + if err := client.UpdateSessionTitle(context.Background(), "session-1", "张三", "Managed by DobotAI"); err != nil { + t.Fatalf("UpdateSessionTitle: %v", err) + } + if gotMethod != http.MethodPut || gotPath != "/api/v1/sessions/session-1" { + t.Fatalf("request = %s %s", gotMethod, gotPath) + } + if gotTitle != "张三" || gotDescription != "Managed by DobotAI" { + t.Fatalf("payload title=%q description=%q", gotTitle, gotDescription) + } +} + +func TestClientUpdateSessionTitleSanitizesHTTPError(t *testing.T) { + mux := http.NewServeMux() + mux.HandleFunc("/api/v1/sessions/session-1", func(w http.ResponseWriter, _ *http.Request) { + http.Error(w, "raw-secret-body", http.StatusInternalServerError) + }) + server := httptest.NewServer(mux) + defer server.Close() + + client, err := NewClient(server.URL, "api-secret", 5*time.Second) + if err != nil { + t.Fatalf("NewClient: %v", err) + } + err = client.UpdateSessionTitle(context.Background(), "session-1", "customer-secret-title", "description") + if err == nil { + t.Fatal("expected error") + } + for _, forbidden := range []string{"raw-secret-body", "api-secret", "customer-secret-title"} { + if strings.Contains(err.Error(), forbidden) { + t.Fatalf("error leaked %q: %v", forbidden, err) + } + } + if !strings.Contains(err.Error(), "HTTP 500") { + t.Fatalf("error = %q, want HTTP status", err) + } +} + func TestParseSSEFailsClosedOnPrematureEOF(t *testing.T) { _, err := parseSSE(strings.NewReader("data: {\"response_type\":\"answer\",\"content\":\"partial\",\"done\":false}\n\n")) if !errors.Is(err, ErrIncompleteStream) { @@ -65,6 +144,24 @@ func TestParseSSEErrorDominatesPartialAnswer(t *testing.T) { } } +func TestParseSSENonTerminalToolErrorContinuesToCompleteAnswer(t *testing.T) { + stream := "data: {\"response_type\":\"error\",\"content\":\"tool failed\",\"done\":false}\n\n" + + "data: {\"response_type\":\"answer\",\"content\":\"complete answer\",\"done\":true}\n\n" + var observed []StreamEvent + result, err := parseSSEWithEventObserver(strings.NewReader(stream), nil, func(event StreamEvent) { + observed = append(observed, event) + }) + if err != nil { + t.Fatalf("non-terminal tool error must not abort stream: %v", err) + } + if result.Answer != "complete answer" { + t.Fatalf("answer=%q, want complete answer", result.Answer) + } + if len(observed) != 2 || observed[0].ResponseType != "error" || observed[0].Done { + t.Fatalf("events=%+v, want a non-terminal error followed by answer", observed) + } +} + func TestAgentChatRequestJSONSerializesImages(t *testing.T) { req := AgentChatRequest{ Query: "请描述并分析这张图片。", diff --git a/internal/weknora/tool_reference_test.go b/internal/weknora/tool_reference_test.go new file mode 100644 index 0000000..fbc43d7 --- /dev/null +++ b/internal/weknora/tool_reference_test.go @@ -0,0 +1,85 @@ +package weknora + +import ( + "strings" + "testing" +) + +func TestLiveDirectToolResultShapeBecomesStructuredReferences(t *testing.T) { + stream := "data: {\"response_type\":\"tool_result\",\"data\":{\"tool_name\":\"get_document_info\",\"success\":true,\"data\":{\"total_docs\":1,\"documents\":[{\"knowledge_id\":\"doc-live\",\"title\":\"现场文档\",\"chunk_count\":8}]}}}\n\n" + + "data: {\"response_type\":\"tool_result\",\"data\":{\"tool_name\":\"wiki_search\",\"success\":true,\"data\":{\"found_kbs\":{\"entity/cra\":[\"wiki-kb\"]}}}}\n\n" + + "data: {\"response_type\":\"answer\",\"content\":\"回答\",\"done\":true}\n\n" + + result, err := parseSSE(strings.NewReader(stream)) + if err != nil { + t.Fatal(err) + } + if len(result.References) != 2 { + t.Fatalf("references=%+v", result.References) + } + if result.References[0].KnowledgeID != "doc-live" || result.References[1].ID != "wiki:wiki-kb:entity/cra" { + t.Fatalf("references=%+v", result.References) + } +} + +func TestLiveFlattenedToolResultShapeBecomesStructuredReferences(t *testing.T) { + stream := "data: {\"response_type\":\"tool_result\",\"data\":{\"tool_name\":\"knowledge_search\",\"success\":true,\"count\":1,\"results\":[{\"knowledge_id\":\"doc-flat\",\"knowledge_title\":\"现场文档\"}]}}\n\n" + + "data: {\"response_type\":\"answer\",\"content\":\"回答\",\"done\":true}\n\n" + + result, err := parseSSE(strings.NewReader(stream)) + if err != nil { + t.Fatal(err) + } + if len(result.References) != 1 || result.References[0].KnowledgeID != "doc-flat" { + t.Fatalf("references=%+v", result.References) + } +} + +func TestCanonicalReferencesReplaceSyntheticToolFallbacks(t *testing.T) { + stream := "data: {\"response_type\":\"tool_result\",\"data\":{\"tool_name\":\"knowledge_search\",\"success\":true,\"data\":{\"count\":1,\"results\":[{\"knowledge_id\":\"doc-1\",\"knowledge_title\":\"标题\"}]}}}\n\n" + + "data: {\"response_type\":\"references\",\"knowledge_references\":[{\"id\":\"chunk-1\",\"knowledge_id\":\"doc-1\",\"content\":\"完整引用一\",\"score\":0.9},{\"id\":\"chunk-2\",\"knowledge_id\":\"doc-1\",\"content\":\"完整引用二\",\"score\":0.8}]}\n\n" + + "data: {\"response_type\":\"answer\",\"content\":\"回答\",\"done\":true}\n\n" + + result, err := parseSSE(strings.NewReader(stream)) + if err != nil { + t.Fatal(err) + } + if len(result.References) != 2 || result.References[0].ID != "chunk-1" || result.References[1].ID != "chunk-2" { + t.Fatalf("canonical references were not preserved: %+v", result.References) + } +} + +func TestSmartReasoningToolResultsBecomeStructuredReferences(t *testing.T) { + stream := "data: {\"response_type\":\"tool_result\",\"data\":{\"tool_name\":\"knowledge_search\",\"result\":{\"success\":true,\"data\":{\"count\":2,\"results\":[{\"knowledge_id\":\"doc-1\",\"knowledge_title\":\"CRA介绍\"},{\"knowledge_id\":\"doc-2\",\"knowledge_title\":\"CRA手册\"}]}}}}\n\n" + + "data: {\"response_type\":\"tool_result\",\"data\":{\"tool_name\":\"grep_chunks\",\"result\":{\"success\":true,\"data\":{\"document_count\":2,\"knowledge_results\":[{\"knowledge_id\":\"doc-2\",\"knowledge_title\":\"CRA手册\",\"chunk_hit_count\":3},{\"knowledge_id\":\"doc-3\",\"knowledge_title\":\"案例视频\",\"chunk_hit_count\":5}]}}}}\n\n" + + "data: {\"response_type\":\"tool_result\",\"data\":{\"tool_name\":\"list_knowledge_chunks\",\"result\":{\"success\":true,\"data\":{\"knowledge_id\":\"doc-3\",\"knowledge_title\":\"案例视频\",\"fetched_chunks\":20}}}}\n\n" + + "data: {\"response_type\":\"answer\",\"content\":\"完整回答\",\"done\":true}\n\n" + + result, err := parseSSE(strings.NewReader(stream)) + if err != nil { + t.Fatal(err) + } + if len(result.References) != 3 { + t.Fatalf("references=%+v", result.References) + } + for index, want := range []string{"doc-1", "doc-2", "doc-3"} { + if result.References[index].KnowledgeID != want { + t.Fatalf("references[%d]=%+v want knowledge %s", index, result.References[index], want) + } + } +} + +func TestSmartReasoningEmptyOrFailedToolResultsRemainUncovered(t *testing.T) { + stream := "data: {\"response_type\":\"tool_result\",\"data\":{\"tool_name\":\"knowledge_search\",\"result\":{\"success\":true,\"data\":{\"count\":0,\"results\":[]}}}}\n\n" + + "data: {\"response_type\":\"tool_result\",\"data\":{\"tool_name\":\"grep_chunks\",\"result\":{\"success\":false,\"data\":{\"document_count\":2,\"knowledge_results\":[{\"knowledge_id\":\"must-not-count\",\"chunk_hit_count\":2}]}}}}\n\n" + + "data: {\"response_type\":\"tool_result\",\"data\":{\"tool_name\":\"list_knowledge_chunks\",\"result\":{\"success\":true,\"data\":{\"knowledge_id\":\"also-empty\",\"fetched_chunks\":0}}}}\n\n" + + "data: {\"response_type\":\"answer\",\"content\":\"回答\",\"done\":true}\n\n" + + result, err := parseSSE(strings.NewReader(stream)) + if err != nil { + t.Fatal(err) + } + if len(result.References) != 0 { + t.Fatalf("empty/failed tools produced references: %+v", result.References) + } +} diff --git a/scripts/deploy-local.sh b/scripts/deploy-local.sh index f61808f..b7bc240 100755 --- a/scripts/deploy-local.sh +++ b/scripts/deploy-local.sh @@ -1,18 +1,30 @@ #!/usr/bin/env bash set -euo pipefail -root="/home/zheromiku/dobotai-platform" +script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +root="${DOBOTAI_SOURCE_ROOT:-$(cd "$script_dir/.." && pwd)}" go_bin="${GO_BIN:-/home/zheromiku/.local/share/go1.26.5/bin/go}" bin_dir="$root/bin" current="$bin_dir/dobotai" next="$bin_dir/dobotai.new" previous="$bin_dir/dobotai.prev" service="dobotai.service" +version_url="http://127.0.0.1:8090/version" + +if [[ -n "$(git -C "$root" status --porcelain)" ]]; then + echo "DobotAI source worktree is dirty; refusing unverifiable build" >&2 + exit 1 +fi + +commit_sha="$(git -C "$root" rev-parse HEAD)" +version="${DOBOTAI_VERSION:-dev}" +build_time="$(date -u '+%Y-%m-%dT%H:%M:%SZ')" +ldflags="-X main.version=$version -X main.commitSHA=$commit_sha -X main.buildTime=$build_time" mkdir -p "$bin_dir" cd "$root" -"$go_bin" build -trimpath -o "$next" ./cmd/dobotai +"$go_bin" build -trimpath -ldflags "$ldflags" -o "$next" ./cmd/dobotai chmod 0755 "$next" if [[ -f "$current" ]]; then @@ -24,8 +36,12 @@ systemctl --user restart "$service" for _ in $(seq 1 30); do if curl --noproxy '*' --fail --silent --max-time 2 http://127.0.0.1:8090/healthz >/dev/null; then - echo "DOBOTAI_DEPLOY_OK" - exit 0 + deployed_sha="$(curl --noproxy '*' --fail --silent --max-time 2 "$version_url" | python3 -c 'import json,sys; print(json.load(sys.stdin).get("commit_sha", ""))' 2>/dev/null || true)" + if [[ "$deployed_sha" == "$commit_sha" ]]; then + echo "DOBOTAI_DEPLOY_OK" + echo "DOBOTAI_COMMIT_SHA=$commit_sha" + exit 0 + fi fi sleep 1 done diff --git a/scripts/deploy_local_test.go b/scripts/deploy_local_test.go new file mode 100644 index 0000000..7cc6372 --- /dev/null +++ b/scripts/deploy_local_test.go @@ -0,0 +1,32 @@ +package scripts + +import ( + "os" + "strings" + "testing" +) + +func TestDeployLocalBuildsItsSelectedSourceAndVerifiesVersion(t *testing.T) { + data, err := os.ReadFile("deploy-local.sh") + if err != nil { + t.Fatal(err) + } + source := string(data) + if strings.Contains(source, `root="/home/zheromiku/dobotai-platform"`) { + t.Fatal("deploy script must not hard-code the production checkout") + } + for _, fragment := range []string{ + `BASH_SOURCE[0]`, + `DOBOTAI_SOURCE_ROOT`, + `git -C "$root" status --porcelain`, + `git -C "$root" rev-parse HEAD`, + `main.version`, + `main.commitSHA`, + `main.buildTime`, + `http://127.0.0.1:8090/version`, + } { + if !strings.Contains(source, fragment) { + t.Errorf("deploy script missing %q", fragment) + } + } +}