From 0dabb8cfa540dcffc34efea481d9f96f265f4e1f Mon Sep 17 00:00:00 2001 From: Rogee Date: Thu, 9 Jul 2026 14:53:27 +0800 Subject: [PATCH] =?UTF-8?q?docs:=20=E6=95=B4=E7=90=86=E6=96=87=E6=A1=A3?= =?UTF-8?q?=E7=9B=AE=E5=BD=95=E7=BB=93=E6=9E=84=20=E2=80=94=20=E6=B8=85?= =?UTF-8?q?=E7=90=86=E8=BF=87=E6=97=B6=E6=96=87=E6=A1=A3=E3=80=81=E5=BD=92?= =?UTF-8?q?=E9=9B=86=E5=8A=9F=E8=83=BD=E5=AD=90=E7=9B=AE=E5=BD=95=E3=80=81?= =?UTF-8?q?=E7=BB=9F=E4=B8=80=E5=91=BD=E5=90=8D=E8=A7=84=E8=8C=83?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 清理: - 删除 34 份过时文档(gap reports/QA临时报告/验收报告/阶段性文档) - 删除 docs/.hermes/skills 第三方 skills 副本(16 文件) - 删除 skills-lock.json 目录归集: - 根目录仅保留 README.md 索引 - product/ — 产品与架构设计(PRD + ARCHITECTURE + P2设计文档 + AI/企业路线图) - tracking/ — Chatwoot parity 开发跟踪 - requirements/ — M01-M12 模块需求 - plans/ — 历史实现计划 - parity/ — 路由 parity 与前端契约 - qa/ — QA 报告与测试计划 - ops/ — 运维部署 命名规范: - 全小写 kebab-case,禁止全大写文件名 - product/tracking/ops 用 NN- 序号前缀 - requirements 用 MNN- 两位零填充模块号 - plans/qa 用 YYYY-MM-DD- 日期前缀 - requirements M1-M9 零填充为 M01-M09(修复字典序) 同步更新: - backend/cmd/route_parity/main.go 路径默认值 - backend/scripts/parity_frontend_smoke.sh 报告路径 - 所有 docs 内部交叉引用 - .gitignore 排除编译产物 (backend/gochat, backend/route_parity) - 新增迁移 000052/000053 - 前端 WS 相关修改 --- .gitignore | 2 + backend/cmd/route_parity/main.go | 6 +- backend/internal/app/app.go | 2 + backend/internal/app/bootstrap.go | 3 + backend/internal/handler/ws/handler.go | 39 +- backend/internal/handler/ws/hub.go | 65 +- backend/internal/handler/ws/protocol.go | 10 +- backend/internal/handler/ws/subscriber.go | 48 +- backend/internal/ws/auth.go | 30 +- ...2_add_notification_settings_table.down.sql | 1 + ...052_add_notification_settings_table.up.sql | 12 + .../000053_add_missing_model_tables.down.sql | 44 + .../000053_add_missing_model_tables.up.sql | 652 +++++++++++ backend/scripts/parity_frontend_smoke.sh | 4 +- docs/.hermes/skills/brainstorming/SKILL.md | 164 --- .../brainstorming/scripts/frame-template.html | 214 ---- .../skills/brainstorming/scripts/helper.js | 88 -- .../skills/brainstorming/scripts/server.cjs | 354 ------ .../brainstorming/scripts/start-server.sh | 148 --- .../brainstorming/scripts/stop-server.sh | 56 - .../spec-document-reviewer-prompt.md | 49 - .../skills/brainstorming/visual-companion.md | 287 ----- .../dispatching-parallel-agents/SKILL.md | 182 --- docs/.hermes/skills/executing-plans/SKILL.md | 70 -- .../finishing-a-development-branch/SKILL.md | 251 ----- .../skills/receiving-code-review/SKILL.md | 213 ---- .../skills/requesting-code-review/SKILL.md | 103 -- .../requesting-code-review/code-reviewer.md | 168 --- .../subagent-driven-development/SKILL.md | 279 ----- .../code-quality-reviewer-prompt.md | 25 - .../implementer-prompt.md | 113 -- .../spec-reviewer-prompt.md | 61 - .../systematic-debugging/CREATION-LOG.md | 119 -- .../skills/systematic-debugging/SKILL.md | 296 ----- .../condition-based-waiting-example.ts | 158 --- .../condition-based-waiting.md | 115 -- .../systematic-debugging/defense-in-depth.md | 122 -- .../systematic-debugging/find-polluter.sh | 63 -- .../root-cause-tracing.md | 169 --- .../systematic-debugging/test-academic.md | 14 - .../systematic-debugging/test-pressure-1.md | 58 - .../systematic-debugging/test-pressure-2.md | 68 -- .../systematic-debugging/test-pressure-3.md | 69 -- .../skills/test-driven-development/SKILL.md | 371 ------ .../testing-anti-patterns.md | 299 ----- .../skills/using-git-worktrees/SKILL.md | 215 ---- .../.hermes/skills/using-superpowers/SKILL.md | 117 -- .../references/codex-tools.md | 59 - .../references/copilot-tools.md | 42 - .../references/gemini-tools.md | 51 - .../verification-before-completion/SKILL.md | 139 --- docs/.hermes/skills/writing-plans/SKILL.md | 152 --- .../plan-document-reviewer-prompt.md | 49 - docs/API_COVERAGE_REPORT.md | 96 -- docs/ARCHITECTURE_REVIEW.md | 137 --- docs/CHANNEL_INTEGRATION_PRIORITIES.md | 295 ----- docs/GAP_REPORT_v1.md | 314 ------ docs/HANDOVER_DOCUMENT.md | 156 --- docs/INTEGRATION_VERIFICATION_REPORT.md | 105 -- docs/P3-核心框架搭建报告.md | 136 --- docs/PERFORMANCE_BENCHMARK.md | 76 -- docs/PHASE2_P0_ENV_CONFIG.md | 522 --------- docs/PHASE2_PLAN.md | 99 -- docs/QA_REPORT_2026-07-08_cdp_round2.md | 174 --- .../QA_REPORT_2026-07-08_full_page_testing.md | 197 ---- docs/README.md | 165 +++ docs/ROUTE_GAP_ANALYSIS.md | 1003 ----------------- docs/SECURITY_AUDIT_REPORT.md | 116 -- ...T_PLAN_2026-07-08_cdp_full_page_testing.md | 235 ---- .../TEST_PLAN_2026-07-08_cdp_round3_strict.md | 209 ---- ...-06-10-gochat-chatwoot-alignment-review.md | 98 -- ...-gochat-chatwoot-woochat-alignment-plan.md | 211 ---- .../Gochat-vs-Chatwoot-Full-Comparison.md | 283 ----- .../M10-captain-chatwoot-vs-gochat.md | 280 ----- docs/fix-plan-2026-07-08.md | 146 --- docs/gochat-chatwoot-gap-report.md | 305 ----- .../01-rolling-upgrade.md} | 0 ...es_static.md => chatwoot-routes-static.md} | 0 ...verage.md => contract-fixture-coverage.md} | 4 +- ...tory.md => frontend-contract-inventory.md} | 0 ...oke_report.md => frontend-smoke-report.md} | 0 .../{gochat_routes.txt => gochat-routes.txt} | 0 ...ceholder_audit.md => placeholder-audit.md} | 2 +- .../{route_parity.md => route-parity.md} | 2 +- ...26-05-24-companies-campaign-helpcenter.md} | 0 .../01-product-requirements.md} | 26 +- .../02-architecture.md} | 26 +- .../03-design-project-structure.md} | 9 +- .../04-design-database.md} | 3 +- .../05-design-routing-and-api.md} | 3 +- .../06-design-channel-abstraction.md} | 5 +- .../07-design-auth-and-realtime.md} | 3 +- .../08-ai-roadmap.md} | 10 +- .../09-enterprise-features.md} | 6 +- .../2026-07-09-qa-report-round4.md} | 2 +- .../2026-07-09-test-plan-round4.md} | 2 +- docs/reports/ALIGNMENT_PLAN.md | 547 --------- docs/reports/GAP_REPORT.md | 84 -- docs/reports/GAP_REPORT_AND_PLAN.md | 175 --- docs/reports/ROUTE_GAP_REPORT.md | 505 --------- .../V4_companies_verification_report.md | 246 ---- ...IFICATION_REPORT_G7_SLA_APPLIEDSLA_APV2.md | 272 ----- ...and-users.md => M01-accounts-and-users.md} | 0 ...ph-context.md => M01-codegraph-context.md} | 0 ...ph-context.md => M02-codegraph-context.md} | 0 ...-channels.md => M02-inbox-and-channels.md} | 0 ...ph-context.md => M03-codegraph-context.md} | 0 ...age.md => M03-conversation-and-message.md} | 0 ...ph-context.md => M04-codegraph-context.md} | 0 ...anagement.md => M04-contact-management.md} | 0 ...ph-context.md => M05-codegraph-context.md} | 0 ...signment.md => M05-team-and-assignment.md} | 0 ...tes.md => M06-automation-and-templates.md} | 0 ...ph-context.md => M06-codegraph-context.md} | 0 ...> M07-channel-integration-consolidated.md} | 16 +- ...ph-context.md => M07-codegraph-context.md} | 0 ...-and-csat.md => M07-reporting-and-csat.md} | 0 ...ph-context.md => M08-codegraph-context.md} | 0 ...ook.md => M08-notification-and-webhook.md} | 0 ...ph-context.md => M09-codegraph-context.md} | 0 ...nowledge-base.md => M09-knowledge-base.md} | 0 docs/skills-lock.json | 83 -- docs/telegram-feature-comparison.md | 150 --- docs/test-report-2026-07-08.md | 228 ---- .../01-chatwoot-parity-tracker.md} | 216 ++-- ...SIGNMENT_POLICY_V2_COMPATIBILITY_REPORT.md | 321 ------ ...BUTES_CUSTOMFILTERS_VERIFICATION_REPORT.md | 391 ------- ...UTES_CUSTOM_FILTERS_VERIFICATION_REPORT.md | 323 ------ ...ation-extension-api-verification-report.md | 159 --- .../components-next/message/Message.vue | 2 +- .../components-next/message/MessageList.vue | 2 +- .../dashboard/components/ChatList.vue | 11 +- .../javascript/dashboard/helper/preChat.js | 6 +- .../store/modules/conversations/actions.js | 4 +- .../helpers/BaseActionCableConnector.js | 20 +- opencode.jsonc | 14 + 136 files changed, 1240 insertions(+), 14484 deletions(-) create mode 100644 backend/migrations/000052_add_notification_settings_table.down.sql create mode 100644 backend/migrations/000052_add_notification_settings_table.up.sql create mode 100644 backend/migrations/000053_add_missing_model_tables.down.sql create mode 100644 backend/migrations/000053_add_missing_model_tables.up.sql delete mode 100644 docs/.hermes/skills/brainstorming/SKILL.md delete mode 100644 docs/.hermes/skills/brainstorming/scripts/frame-template.html delete mode 100644 docs/.hermes/skills/brainstorming/scripts/helper.js delete mode 100644 docs/.hermes/skills/brainstorming/scripts/server.cjs delete mode 100755 docs/.hermes/skills/brainstorming/scripts/start-server.sh delete mode 100755 docs/.hermes/skills/brainstorming/scripts/stop-server.sh delete mode 100644 docs/.hermes/skills/brainstorming/spec-document-reviewer-prompt.md delete mode 100644 docs/.hermes/skills/brainstorming/visual-companion.md delete mode 100644 docs/.hermes/skills/dispatching-parallel-agents/SKILL.md delete mode 100644 docs/.hermes/skills/executing-plans/SKILL.md delete mode 100644 docs/.hermes/skills/finishing-a-development-branch/SKILL.md delete mode 100644 docs/.hermes/skills/receiving-code-review/SKILL.md delete mode 100644 docs/.hermes/skills/requesting-code-review/SKILL.md delete mode 100644 docs/.hermes/skills/requesting-code-review/code-reviewer.md delete mode 100644 docs/.hermes/skills/subagent-driven-development/SKILL.md delete mode 100644 docs/.hermes/skills/subagent-driven-development/code-quality-reviewer-prompt.md delete mode 100644 docs/.hermes/skills/subagent-driven-development/implementer-prompt.md delete mode 100644 docs/.hermes/skills/subagent-driven-development/spec-reviewer-prompt.md delete mode 100644 docs/.hermes/skills/systematic-debugging/CREATION-LOG.md delete mode 100644 docs/.hermes/skills/systematic-debugging/SKILL.md delete mode 100644 docs/.hermes/skills/systematic-debugging/condition-based-waiting-example.ts delete mode 100644 docs/.hermes/skills/systematic-debugging/condition-based-waiting.md delete mode 100644 docs/.hermes/skills/systematic-debugging/defense-in-depth.md delete mode 100755 docs/.hermes/skills/systematic-debugging/find-polluter.sh delete mode 100644 docs/.hermes/skills/systematic-debugging/root-cause-tracing.md delete mode 100644 docs/.hermes/skills/systematic-debugging/test-academic.md delete mode 100644 docs/.hermes/skills/systematic-debugging/test-pressure-1.md delete mode 100644 docs/.hermes/skills/systematic-debugging/test-pressure-2.md delete mode 100644 docs/.hermes/skills/systematic-debugging/test-pressure-3.md delete mode 100644 docs/.hermes/skills/test-driven-development/SKILL.md delete mode 100644 docs/.hermes/skills/test-driven-development/testing-anti-patterns.md delete mode 100644 docs/.hermes/skills/using-git-worktrees/SKILL.md delete mode 100644 docs/.hermes/skills/using-superpowers/SKILL.md delete mode 100644 docs/.hermes/skills/using-superpowers/references/codex-tools.md delete mode 100644 docs/.hermes/skills/using-superpowers/references/copilot-tools.md delete mode 100644 docs/.hermes/skills/using-superpowers/references/gemini-tools.md delete mode 100644 docs/.hermes/skills/verification-before-completion/SKILL.md delete mode 100644 docs/.hermes/skills/writing-plans/SKILL.md delete mode 100644 docs/.hermes/skills/writing-plans/plan-document-reviewer-prompt.md delete mode 100644 docs/API_COVERAGE_REPORT.md delete mode 100644 docs/ARCHITECTURE_REVIEW.md delete mode 100644 docs/CHANNEL_INTEGRATION_PRIORITIES.md delete mode 100644 docs/GAP_REPORT_v1.md delete mode 100644 docs/HANDOVER_DOCUMENT.md delete mode 100644 docs/INTEGRATION_VERIFICATION_REPORT.md delete mode 100644 docs/P3-核心框架搭建报告.md delete mode 100644 docs/PERFORMANCE_BENCHMARK.md delete mode 100644 docs/PHASE2_P0_ENV_CONFIG.md delete mode 100644 docs/PHASE2_PLAN.md delete mode 100644 docs/QA_REPORT_2026-07-08_cdp_round2.md delete mode 100644 docs/QA_REPORT_2026-07-08_full_page_testing.md create mode 100644 docs/README.md delete mode 100644 docs/ROUTE_GAP_ANALYSIS.md delete mode 100644 docs/SECURITY_AUDIT_REPORT.md delete mode 100644 docs/TEST_PLAN_2026-07-08_cdp_full_page_testing.md delete mode 100644 docs/TEST_PLAN_2026-07-08_cdp_round3_strict.md delete mode 100644 docs/comparison/2026-06-10-gochat-chatwoot-alignment-review.md delete mode 100644 docs/comparison/2026-06-11-gochat-chatwoot-woochat-alignment-plan.md delete mode 100644 docs/comparison/Gochat-vs-Chatwoot-Full-Comparison.md delete mode 100644 docs/comparison/M10-captain-chatwoot-vs-gochat.md delete mode 100644 docs/fix-plan-2026-07-08.md delete mode 100644 docs/gochat-chatwoot-gap-report.md rename docs/{rolling_upgrade.md => ops/01-rolling-upgrade.md} (100%) rename docs/parity/{chatwoot_routes_static.md => chatwoot-routes-static.md} (100%) rename docs/parity/{contract_fixture_coverage.md => contract-fixture-coverage.md} (99%) rename docs/parity/{frontend_contract_inventory.md => frontend-contract-inventory.md} (100%) rename docs/parity/{frontend_smoke_report.md => frontend-smoke-report.md} (100%) rename docs/parity/{gochat_routes.txt => gochat-routes.txt} (100%) rename docs/parity/{placeholder_audit.md => placeholder-audit.md} (97%) rename docs/parity/{route_parity.md => route-parity.md} (99%) rename docs/plans/{2026-05-24-companies-campaign-helpcenter-notes-labels-attachments.md => 2026-05-24-companies-campaign-helpcenter.md} (100%) rename docs/{PRD.md => product/01-product-requirements.md} (97%) rename docs/{ARCHITECTURE_DESIGN.md => product/02-architecture.md} (98%) rename docs/{architecture/P2A-项目结构与模块划分.md => product/03-design-project-structure.md} (99%) rename docs/{architecture/P2B-数据库设计.md => product/04-design-database.md} (99%) rename docs/{architecture/P2C-路由与API设计.md => product/05-design-routing-and-api.md} (99%) rename docs/{architecture/P2D-渠道抽象层设计.md => product/06-design-channel-abstraction.md} (99%) rename docs/{architecture/P2E-认证授权与实时通信.md => product/07-design-auth-and-realtime.md} (99%) rename docs/{AI_FEATURE_ROADMAP.md => product/08-ai-roadmap.md} (98%) rename docs/{ENTERPRISE_FEATURE_ANALYSIS.md => product/09-enterprise-features.md} (99%) rename docs/{QA_REPORT_2026-07-09_cdp_round4.md => qa/2026-07-09-qa-report-round4.md} (99%) rename docs/{TEST_PLAN_2026-07-09_cdp_round4.md => qa/2026-07-09-test-plan-round4.md} (99%) delete mode 100644 docs/reports/ALIGNMENT_PLAN.md delete mode 100644 docs/reports/GAP_REPORT.md delete mode 100644 docs/reports/GAP_REPORT_AND_PLAN.md delete mode 100644 docs/reports/ROUTE_GAP_REPORT.md delete mode 100644 docs/reports/V4_companies_verification_report.md delete mode 100644 docs/reports/VERIFICATION_REPORT_G7_SLA_APPLIEDSLA_APV2.md rename docs/requirements/{M1-accounts-and-users.md => M01-accounts-and-users.md} (100%) rename docs/requirements/{M1-codegraph-context.md => M01-codegraph-context.md} (100%) rename docs/requirements/{M2-codegraph-context.md => M02-codegraph-context.md} (100%) rename docs/requirements/{M2-inbox-and-channels.md => M02-inbox-and-channels.md} (100%) rename docs/requirements/{M3-codegraph-context.md => M03-codegraph-context.md} (100%) rename docs/requirements/{M3-conversation-and-message.md => M03-conversation-and-message.md} (100%) rename docs/requirements/{M4-codegraph-context.md => M04-codegraph-context.md} (100%) rename docs/requirements/{M4-contact-management.md => M04-contact-management.md} (100%) rename docs/requirements/{M5-codegraph-context.md => M05-codegraph-context.md} (100%) rename docs/requirements/{M5-team-and-assignment.md => M05-team-and-assignment.md} (100%) rename docs/requirements/{M6-automation-and-templates.md => M06-automation-and-templates.md} (100%) rename docs/requirements/{M6-codegraph-context.md => M06-codegraph-context.md} (100%) rename docs/requirements/{M7-channel-integration-consolidated.md => M07-channel-integration-consolidated.md} (93%) rename docs/requirements/{M7-codegraph-context.md => M07-codegraph-context.md} (100%) rename docs/requirements/{M7-reporting-and-csat.md => M07-reporting-and-csat.md} (100%) rename docs/requirements/{M8-codegraph-context.md => M08-codegraph-context.md} (100%) rename docs/requirements/{M8-notification-and-webhook.md => M08-notification-and-webhook.md} (100%) rename docs/requirements/{M9-codegraph-context.md => M09-codegraph-context.md} (100%) rename docs/requirements/{M9-knowledge-base.md => M09-knowledge-base.md} (100%) delete mode 100644 docs/skills-lock.json delete mode 100644 docs/telegram-feature-comparison.md delete mode 100644 docs/test-report-2026-07-08.md rename docs/{CHATWOOT_PARITY_DEVELOPMENT_PLAN.md => tracking/01-chatwoot-parity-tracker.md} (99%) delete mode 100644 docs/verification/SLA_ASSIGNMENT_POLICY_V2_COMPATIBILITY_REPORT.md delete mode 100644 docs/verification/V5_CUSTOMATTRIBUTES_CUSTOMFILTERS_VERIFICATION_REPORT.md delete mode 100644 docs/verification/V5_CUSTOM_ATTRIBUTES_CUSTOM_FILTERS_VERIFICATION_REPORT.md delete mode 100644 docs/verification/conversation-extension-api-verification-report.md create mode 100644 opencode.jsonc diff --git a/.gitignore b/.gitignore index 809f41ca..89e7e0dc 100644 --- a/.gitignore +++ b/.gitignore @@ -4,6 +4,8 @@ # Build output bin/ tmp/ +backend/gochat +backend/route_parity # IDE .idea/ diff --git a/backend/cmd/route_parity/main.go b/backend/cmd/route_parity/main.go index 21165eaa..ecfd671b 100644 --- a/backend/cmd/route_parity/main.go +++ b/backend/cmd/route_parity/main.go @@ -497,10 +497,10 @@ var criticalRoutes = []route{ } func main() { - gochatPath := flag.String("gochat", "docs/parity/gochat_routes.txt", "GoChat route dump") + gochatPath := flag.String("gochat", "docs/parity/gochat-routes.txt", "GoChat route dump") chatwootPath := flag.String("chatwoot", "reference/chatwoot/config/routes.rb", "Chatwoot routes.rb path") - outPath := flag.String("out", "docs/parity/route_parity.md", "route parity markdown output") - chatwootOut := flag.String("chatwoot-out", "docs/parity/chatwoot_routes_static.md", "Chatwoot static route source output") + outPath := flag.String("out", "docs/parity/route-parity.md", "route parity markdown output") + chatwootOut := flag.String("chatwoot-out", "docs/parity/chatwoot-routes-static.md", "Chatwoot static route source output") flag.Parse() gochatRoutes, err := readRouteDump(*gochatPath) diff --git a/backend/internal/app/app.go b/backend/internal/app/app.go index 30c6debd..42e62d0d 100644 --- a/backend/internal/app/app.go +++ b/backend/internal/app/app.go @@ -257,6 +257,8 @@ func autoMigrate(db *gorm.DB) error { &model.BackgroundJob{}, // S6: WorkingHour — out-of-office / business hours per inbox &model.WorkingHour{}, + // Notification settings — per-user per-account notification preferences + &model.NotificationSetting{}, } for _, m := range models { diff --git a/backend/internal/app/bootstrap.go b/backend/internal/app/bootstrap.go index e5daabd5..230a4a0e 100644 --- a/backend/internal/app/bootstrap.go +++ b/backend/internal/app/bootstrap.go @@ -195,6 +195,7 @@ func Bootstrap(env string) (*App, error) { notificationPrefRepo := repository.NewNotificationPreferenceRepo(db) pushTokenRepo := repository.NewPushTokenRepo(db) notificationSubscriptionRepo := repository.NewNotificationSubscriptionRepo(db) + notificationSettingRepo := repository.NewNotificationSettingRepo(db) webhookSubRepo := repository.NewWebhookSubscriptionRepo(db) conversationParticipantRepo := repository.NewConversationParticipantRepo(db) draftMessageRepo := repository.NewDraftMessageRepo(db) @@ -556,6 +557,7 @@ func Bootstrap(env string) (*App, error) { // P4 Notification+Webhook services pushSubscriptionService := service.NewPushSubscriptionService(pushTokenRepo) notificationSubscriptionService := service.NewNotificationSubscriptionService(notificationSubscriptionRepo) + notificationSettingService := service.NewNotificationSettingService(notificationSettingRepo) pushDeliveryService := service.NewPushDeliveryService(pushTokenRepo, cfg.Push.VapidPublicKey, cfg.Push.VapidPrivateKey, cfg.Push.VapidSubject) webhookSubscriptionService := service.NewWebhookSubscriptionService(webhookSubRepo) webhookDeliveryService := service.NewWebhookDeliveryService(webhookSubRepo) @@ -831,6 +833,7 @@ func Bootstrap(env string) (*App, error) { CannedResponse: v1.NewCannedResponseHandler(cannedResponseService), PushSubscription: v1.NewPushSubscriptionHandler(pushSubscriptionService), NotificationSubscription: v1.NewNotificationSubscriptionHandler(notificationSubscriptionService), + NotificationSetting: v1.NewNotificationSettingHandler(notificationSettingService), WebhookSubscription: v1.NewWebhookSubscriptionHandler(webhookSubscriptionService), TelegramWebhook: telegramWebhookHandler, FacebookWebhook: facebookWebhookHandler, diff --git a/backend/internal/handler/ws/handler.go b/backend/internal/handler/ws/handler.go index 46bebfb6..aebea0b0 100644 --- a/backend/internal/handler/ws/handler.go +++ b/backend/internal/handler/ws/handler.go @@ -36,13 +36,19 @@ type Handler struct { // The authenticator provides both JWT (agent) and pubsub_token (contact) auth paths. func NewHandler(hub *Hub, authenticator *wspkg.WSAuthenticator) *Handler { return &Handler{ - hub: hub, + hub: hub, authenticator: authenticator, upgrader: websocket.Upgrader{ ReadBufferSize: 1024, WriteBufferSize: 1024, // Allow all origins — CORS is handled at the Gin middleware layer CheckOrigin: func(r *http.Request) bool { return true }, + // ActionCable clients send Sec-WebSocket-Protocol: actioncable-v1-json. + // If the server doesn't echo back a supported subprotocol, the JS + // client immediately closes the connection ("Protocol is unsupported") + // and enters a reconnect loop. gorilla/websocket picks the first + // requested protocol listed here that the client also offered. + Subprotocols: []string{"actioncable-v1-json"}, }, } } @@ -91,6 +97,12 @@ func (h *Handler) ServeWS(c *gin.Context) { logger.L().Infof("ws: connection established (user=%d, account=%d, is_contact=%v)", claims.UserID, claims.AccountID, claims.IsContact) + // Send ActionCable welcome frame — the JS client expects this immediately + // after upgrade. Without it the client's ConnectionMonitor considers the + // connection stale and enters a reconnect loop. + welcomeData, _ := json.Marshal(WelcomeFrame{Type: ServerWelcome}) + client.Send <- welcomeData + // Start pumps in separate goroutines go h.writePump(client) go h.readPump(client) @@ -144,6 +156,11 @@ func (h *Handler) readPump(client *Client) { h.handleUnsubscribe(client, cmd) case CommandPing: h.handlePing(client) + case CommandMessage: + // ActionCable "message" command — client performs a channel action + // (e.g. update_presence). We acknowledge but don't require a + // specific handler for presence yet. + logger.L().Debugf("ws: message command from user=%d, data=%s", client.UserID, cmd.Data) default: logger.L().Warnf("ws: unknown command '%s' from user=%d", cmd.Command, client.UserID) } @@ -177,9 +194,15 @@ func (h *Handler) writePump(client *Client) { } case <-ticker.C: - // Send ping frame for heartbeat + // Send ActionCable-level ping message (JSON text frame). + // The JS ConnectionMonitor expects periodic ping messages to + // keep the connection alive (staleThreshold = 6s by default). + pingMsg, _ := json.Marshal(PingFrame{ + Type: ServerPing, + Message: time.Now().UTC().Format(time.RFC3339), + }) client.Conn.SetWriteDeadline(time.Now().Add(WriteWait)) - if err := client.Conn.WriteMessage(websocket.PingMessage, []byte{}); err != nil { + if err := client.Conn.WriteMessage(websocket.TextMessage, pingMsg); err != nil { logger.L().Errorf("ws: ping write failed for user=%d: %v", client.UserID, err) return } @@ -217,7 +240,9 @@ func (h *Handler) handleSubscribe(client *Client, cmd CommandFrame) { // Determine room name based on channel type (uses Hub's canonical naming) room := "" switch identifier.Channel { - case ChannelAccount: + case ChannelAccount, ChannelRoom: + // RoomChannel is Chatwoot's single-subscription model — it maps + // to the account room (all account-level events are delivered). room = accountRoomName(identifier.AccountID) case ChannelConversation: if identifier.ConversationID == 0 { @@ -243,6 +268,10 @@ func (h *Handler) handleSubscribe(client *Client, cmd CommandFrame) { // Subscribe the client to the room client.Subscribe(room) + // Store the ActionCable subscription identifier on the client so that + // event frames can be wrapped with it for correct client-side routing. + client.Identifier = cmd.Identifier + // Send confirmation frame confirmData, _ := json.Marshal(ConfirmFrame{ Type: ServerConfirmSubscribe, @@ -262,7 +291,7 @@ func (h *Handler) handleUnsubscribe(client *Client, cmd CommandFrame) { // Determine room name (uses Hub's canonical naming) room := "" switch identifier.Channel { - case ChannelAccount: + case ChannelAccount, ChannelRoom: room = accountRoomName(identifier.AccountID) case ChannelConversation: room = conversationRoomName(identifier.AccountID, identifier.ConversationID) diff --git a/backend/internal/handler/ws/hub.go b/backend/internal/handler/ws/hub.go index a1015213..882ac9f1 100644 --- a/backend/internal/handler/ws/hub.go +++ b/backend/internal/handler/ws/hub.go @@ -35,6 +35,7 @@ type Client struct { Hub *Hub // reference back to Hub SubscribedRooms map[string]bool // rooms this client is subscribed to CancelPresence context.CancelFunc // cancel presence refresh on disconnect + Identifier string // ActionCable subscription identifier (JSON string) } // NewClient creates a new WebSocket client with the given identity and connection. @@ -201,12 +202,9 @@ func (h *Hub) Register(c *Client) { logger.L().Infof("ws hub: client registered (id=%s, user_id=%d, account_id=%d, is_contact=%v)", c.ID, c.UserID, c.AccountID, c.IsContact) - // Send welcome message - welcomeMsg, _ := json.Marshal(wspkg.WSMessage{ - Event: wspkg.EventWelcome, - Data: map[string]any{"client_id": c.ID}, - }) - c.Send <- welcomeMsg + // Note: The ActionCable welcome frame is sent by handler.go's ServeWS + // after upgrade. We do NOT send a WSMessage-format welcome here because + // the JS ActionCable client only recognizes {type:"welcome"} frames. } // Unregister removes a client from the Hub and cleans up presence. @@ -244,6 +242,37 @@ func (h *Hub) Unregister(c *Client) { logger.L().Infof("ws hub: client unregistered (id=%s, user_id=%d)", c.ID, c.UserID) } + +// wrapActionCableMessage wraps a raw event payload in the ActionCable wire format. +// ActionCable JS expects: {"identifier":"","message":} +// Without the identifier field, the JS client crashes with +// "Cannot read properties of undefined (reading 'received')". +// Without the message field, the received callback gets undefined. +// +// If the client has no subscription identifier yet (pre-subscribe), the +// message is still sent but without an identifier — the JS client will +// silently ignore it (no matching subscription). +func wrapActionCableMessage(identifier string, data []byte) []byte { + if identifier == "" { + // Client hasn't subscribed yet — sending an unwrapped message would + // crash the ActionCable JS client (no identifier to route to). + // Return nil to signal the caller to skip delivery. + return nil + } + wrapped := struct { + Identifier string `json:"identifier"` + Message json.RawMessage `json:"message"` + }{ + Identifier: identifier, + Message: data, + } + result, err := json.Marshal(wrapped) + if err != nil { + return data + } + return result +} + // SendToAccount sends a message to all clients subscribed to an account room. func (h *Hub) SendToAccount(accountID uint, data []byte) { h.mu.RLock() @@ -253,8 +282,12 @@ func (h *Hub) SendToAccount(accountID uint, data []byte) { if clientIDs, ok := h.rooms[roomName]; ok { for clientID := range clientIDs { if client, ok := h.clients[clientID]; ok { + msg := wrapActionCableMessage(client.Identifier, data) + if msg == nil { + continue + } select { - case client.Send <- data: + case client.Send <- msg: default: logger.L().Warnf("ws hub: dropping message for slow client %s", clientID) } @@ -273,8 +306,12 @@ func (h *Hub) SendToAccountConversation(accountID uint, conversationID uint, dat if clientIDs, ok := h.rooms[roomName]; ok { for clientID := range clientIDs { if client, ok := h.clients[clientID]; ok { + msg := wrapActionCableMessage(client.Identifier, data) + if msg == nil { + continue + } select { - case client.Send <- data: + case client.Send <- msg: default: logger.L().Warnf("ws hub: dropping message for slow client %s", clientID) } @@ -291,8 +328,12 @@ func (h *Hub) SendToRoom(room string, data []byte) { if clientIDs, ok := h.rooms[room]; ok { for clientID := range clientIDs { if client, ok := h.clients[clientID]; ok { + msg := wrapActionCableMessage(client.Identifier, data) + if msg == nil { + continue + } select { - case client.Send <- data: + case client.Send <- msg: default: logger.L().Warnf("ws hub: dropping message for slow client %s", clientID) } @@ -307,8 +348,12 @@ func (h *Hub) SendToClient(clientID string, data []byte) { defer h.mu.RUnlock() if client, ok := h.clients[clientID]; ok { + msg := wrapActionCableMessage(client.Identifier, data) + if msg == nil { + return + } select { - case client.Send <- data: + case client.Send <- msg: default: logger.L().Warnf("ws hub: dropping message for slow client %s", clientID) } diff --git a/backend/internal/handler/ws/protocol.go b/backend/internal/handler/ws/protocol.go index ae0bfca2..11fb3e11 100644 --- a/backend/internal/handler/ws/protocol.go +++ b/backend/internal/handler/ws/protocol.go @@ -22,6 +22,7 @@ const ( CommandSubscribe CommandType = "subscribe" CommandUnsubscribe CommandType = "unsubscribe" CommandPing CommandType = "ping" + CommandMessage CommandType = "message" // client→channel action (e.g. update_presence) ) // ServerMessageType — server→client message types @@ -31,11 +32,11 @@ const ( // ServerEvent pushes a real-time event to subscribed clients ServerEvent ServerMessageType = "event" // ServerConfirmSubscribe acknowledges a successful subscription - ServerConfirmSubscribe ServerMessageType = "confirm_subscribe" + ServerConfirmSubscribe ServerMessageType = "confirm_subscription" // ServerConfirmUnsubscribe acknowledges a successful unsubscribe - ServerConfirmUnsubscribe ServerMessageType = "confirm_unsubscribe" + ServerConfirmUnsubscribe ServerMessageType = "confirm_unsubscribe" // NOTE: ActionCable uses confirm_subscription for both sub and unsub // ServerRejectSubscribe rejects a subscription attempt - ServerRejectSubscribe ServerMessageType = "reject_subscribe" + ServerRejectSubscribe ServerMessageType = "reject_subscription" // ServerPing is a heartbeat response ServerPing ServerMessageType = "ping" // ServerWelcome is sent immediately upon connection @@ -66,6 +67,7 @@ type ChannelIdentifier struct { const ( ChannelAccount = "AccountChannel" ChannelConversation = "ConversationChannel" + ChannelRoom = "RoomChannel" // Chatwoot single-subscription channel ) // --- Server → Client Frames --- @@ -158,5 +160,5 @@ const ( const ( // PingInterval is how often the server sends ping frames to detect dead connections. - PingInterval = 30 // seconds + PingInterval = 5 // seconds — must be < ActionCable staleThreshold (6s) to avoid reconnect loops ) diff --git a/backend/internal/handler/ws/subscriber.go b/backend/internal/handler/ws/subscriber.go index bed53c51..9b192277 100644 --- a/backend/internal/handler/ws/subscriber.go +++ b/backend/internal/handler/ws/subscriber.go @@ -11,6 +11,8 @@ import ( "github.com/ThreeDotsLabs/watermill/message" "github.com/redis/go-redis/v9" + wspkg "github.com/gochat/gochat/internal/ws" + "github.com/gochat/gochat/pkg/logger" ) @@ -214,24 +216,26 @@ func (s *Subscriber) forwardToAccountAndConversation(eventType string) func(msg return nil } - // Build the event frame - frame := EventFrame{ - Type: ServerEvent, - Event: eventType, - Payload: payload.Data, + // Build the WSMessage — the frontend's onReceived handler expects + // { event: "...", data: {...} } which matches WSMessage serialization. + // Hub.SendToAccount wraps this in ActionCable format: + // { identifier: "...", message: { event: "...", data: {...} } } + wsMsg := wspkg.WSMessage{ + Event: eventType, + Data: payload.Data, } - frameData, err := json.Marshal(frame) + msgData, err := json.Marshal(wsMsg) if err != nil { - logger.L().Errorf("ws: failed to marshal event frame for %s: %v", eventType, err) + logger.L().Errorf("ws: failed to marshal event for %s: %v", eventType, err) return nil } // Push to account room - s.hub.SendToAccount(accountID, frameData) + s.hub.SendToAccount(accountID, msgData) // Also push to conversation room if conversation_id is present if payload.ConversationID > 0 { - s.hub.SendToAccountConversation(accountID, payload.ConversationID, frameData) + s.hub.SendToAccountConversation(accountID, payload.ConversationID, msgData) } return nil @@ -254,18 +258,17 @@ func (s *Subscriber) forwardToAccount(eventType string) func(msg *message.Messag return nil } - frame := EventFrame{ - Type: ServerEvent, - Event: eventType, - Payload: payload.Data, + wsMsg := wspkg.WSMessage{ + Event: eventType, + Data: payload.Data, } - frameData, err := json.Marshal(frame) + msgData, err := json.Marshal(wsMsg) if err != nil { - logger.L().Errorf("ws: failed to marshal event frame for %s: %v", eventType, err) + logger.L().Errorf("ws: failed to marshal event for %s: %v", eventType, err) return nil } - s.hub.SendToAccount(accountID, frameData) + s.hub.SendToAccount(accountID, msgData) return nil } } @@ -287,18 +290,17 @@ func (s *Subscriber) forwardToConversation(eventType string) func(msg *message.M return nil } - frame := EventFrame{ - Type: ServerEvent, - Event: eventType, - Payload: payload.Data, + wsMsg := wspkg.WSMessage{ + Event: eventType, + Data: payload.Data, } - frameData, err := json.Marshal(frame) + msgData, err := json.Marshal(wsMsg) if err != nil { - logger.L().Errorf("ws: failed to marshal event frame for %s: %v", eventType, err) + logger.L().Errorf("ws: failed to marshal event for %s: %v", eventType, err) return nil } - s.hub.SendToAccountConversation(accountID, conversationID, frameData) + s.hub.SendToAccountConversation(accountID, conversationID, msgData) return nil } } diff --git a/backend/internal/ws/auth.go b/backend/internal/ws/auth.go index e9094652..bd580b44 100644 --- a/backend/internal/ws/auth.go +++ b/backend/internal/ws/auth.go @@ -197,18 +197,23 @@ func (a *WSAuthenticator) findContactInboxByPubsubToken(ctx context.Context, pub } // extractWSToken pulls the JWT token from websocket upgrade request. -// Order of precedence: -// 1. 'token' query parameter (browser WebSocket API can't set custom headers) -// 2. Authorization header (Bearer token, for non-browser clients) -// 3. Sec-WebSocket-Protocol header (some ActionCable-compatible clients) +// Matches the HTTP auth middleware behaviour: accepts both 'token' and +// 'access-token' query params (browser WebSocket API can't set custom headers), +// plus the Authorization header (Bearer token, for non-browser clients). +// +// NOTE: Sec-WebSocket-Protocol header is NOT used as a JWT source. +// ActionCable sets this to "actioncable-v1-json" for sub-protocol +// negotiation, not for authentication. func extractWSToken(c *gin.Context) string { - // Primary: 'token' query param - token := c.Query("token") - if token != "" { + // Query params (browser WebSocket API compatible) + if token := c.Query("token"); token != "" { + return token + } + if token := c.Query("access-token"); token != "" { return token } - // Fallback: Authorization header + // Authorization header (non-browser clients) authHeader := c.GetHeader("Authorization") if authHeader != "" { parts := strings.SplitN(authHeader, " ", 2) @@ -217,15 +222,6 @@ func extractWSToken(c *gin.Context) string { } } - // Fallback: Sec-WebSocket-Protocol header (ActionCable convention) - proto := c.GetHeader("Sec-WebSocket-Protocol") - if proto != "" { - token = strings.TrimSpace(proto) - if token != "" { - return token - } - } - return "" } diff --git a/backend/migrations/000052_add_notification_settings_table.down.sql b/backend/migrations/000052_add_notification_settings_table.down.sql new file mode 100644 index 00000000..2fc5b5d7 --- /dev/null +++ b/backend/migrations/000052_add_notification_settings_table.down.sql @@ -0,0 +1 @@ +DROP TABLE IF EXISTS notification_settings; diff --git a/backend/migrations/000052_add_notification_settings_table.up.sql b/backend/migrations/000052_add_notification_settings_table.up.sql new file mode 100644 index 00000000..31ff03e8 --- /dev/null +++ b/backend/migrations/000052_add_notification_settings_table.up.sql @@ -0,0 +1,12 @@ +CREATE TABLE IF NOT EXISTS notification_settings ( + id BIGSERIAL PRIMARY KEY, + account_id BIGINT NOT NULL, + user_id BIGINT NOT NULL, + email_flags INTEGER NOT NULL DEFAULT 0, + push_flags INTEGER NOT NULL DEFAULT 0, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + deleted_at TIMESTAMPTZ DEFAULT NULL +); +CREATE INDEX IF NOT EXISTS idx_notification_settings_account_user ON notification_settings (account_id, user_id); +CREATE INDEX IF NOT EXISTS idx_notification_settings_deleted_at ON notification_settings (deleted_at); diff --git a/backend/migrations/000053_add_missing_model_tables.down.sql b/backend/migrations/000053_add_missing_model_tables.down.sql new file mode 100644 index 00000000..77bae335 --- /dev/null +++ b/backend/migrations/000053_add_missing_model_tables.down.sql @@ -0,0 +1,44 @@ +-- Down migration for 000053 +DROP TABLE IF EXISTS push_tokens CASCADE; +DROP TABLE IF EXISTS account_saml_settings CASCADE; +DROP TABLE IF EXISTS account_oidc_settings CASCADE; +DROP TABLE IF EXISTS account_ldap_settings CASCADE; +DROP TABLE IF EXISTS working_hours CASCADE; +DROP TABLE IF EXISTS widget_tests CASCADE; +DROP TABLE IF EXISTS widget_theme_configs CASCADE; +DROP TABLE IF EXISTS widget_offline_messages CASCADE; +DROP TABLE IF EXISTS widget_file_uploads CASCADE; +DROP TABLE IF EXISTS pre_chat_forms CASCADE; +DROP TABLE IF EXISTS saml_idp_configs CASCADE; +DROP TABLE IF EXISTS reports CASCADE; +DROP TABLE IF EXISTS message_reactions CASCADE; +DROP TABLE IF EXISTS email_templates CASCADE; +DROP TABLE IF EXISTS data_imports CASCADE; +DROP TABLE IF EXISTS direct_uploads CASCADE; +DROP TABLE IF EXISTS contact_exports CASCADE; +DROP TABLE IF EXISTS contactables CASCADE; +DROP TABLE IF EXISTS captain_assistant_inboxes CASCADE; +DROP TABLE IF EXISTS banners CASCADE; +DROP TABLE IF EXISTS automation_actions CASCADE; +DROP TABLE IF EXISTS assignment_policies_v2 CASCADE; +DROP TABLE IF EXISTS assignment_policies CASCADE; +DROP TABLE IF EXISTS whatsapp_calls CASCADE; +DROP TABLE IF EXISTS sso_sessions CASCADE; +DROP TABLE IF EXISTS notification_subscriptions CASCADE; +DROP TABLE IF EXISTS inbox_limits CASCADE; +DROP TABLE IF EXISTS email_channel_migrations CASCADE; +DROP TABLE IF EXISTS draft_messages CASCADE; +DROP TABLE IF EXISTS delivery_statuses CASCADE; +DROP TABLE IF EXISTS csat_templates CASCADE; +DROP TABLE IF EXISTS contact_notes CASCADE; +DROP TABLE IF EXISTS notes CASCADE; +DROP TABLE IF EXISTS conversation_participants CASCADE; +DROP TABLE IF EXISTS custom_filters CASCADE; +DROP TABLE IF EXISTS custom_attribute_definitions CASCADE; +DROP TABLE IF EXISTS agent_bot_presence_events CASCADE; +DROP TABLE IF EXISTS agent_bot_inboxes CASCADE; +DROP TABLE IF EXISTS agent_bots CASCADE; +DROP TABLE IF EXISTS conversation_labels CASCADE; +-- Do NOT drop contact_labels, company_notes, tags — may have been created by other migrations +-- Remove snoozed_until column from notifications +ALTER TABLE notifications DROP COLUMN IF EXISTS snoozed_until; diff --git a/backend/migrations/000053_add_missing_model_tables.up.sql b/backend/migrations/000053_add_missing_model_tables.up.sql new file mode 100644 index 00000000..215055ed --- /dev/null +++ b/backend/migrations/000053_add_missing_model_tables.up.sql @@ -0,0 +1,652 @@ +-- Migration 000053: Create missing model tables and add missing columns +-- These tables exist as Go models but were never created by SQL migrations +-- or GORM AutoMigrate (which was not called in the Bootstrap path). + +-- ============ conversation_labels ============ +CREATE TABLE IF NOT EXISTS conversation_labels ( + id BIGSERIAL PRIMARY KEY, + conversation_id BIGINT NOT NULL, + tag_id BIGINT NOT NULL, + account_id BIGINT NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() +); +CREATE INDEX IF NOT EXISTS idx_conv_labels_conv_id ON conversation_labels (conversation_id); +CREATE INDEX IF NOT EXISTS idx_conv_labels_tag_id ON conversation_labels (tag_id); +CREATE INDEX IF NOT EXISTS idx_conv_labels_account_id ON conversation_labels (account_id); +CREATE UNIQUE INDEX IF NOT EXISTS idx_conv_label_tag ON conversation_labels (conversation_id, tag_id); + +-- ============ contact_labels (may already exist from migration) ============ +CREATE TABLE IF NOT EXISTS contact_labels ( + contact_id BIGINT NOT NULL, + tag_id BIGINT NOT NULL, + account_id BIGINT NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + PRIMARY KEY (contact_id, tag_id) +); +CREATE INDEX IF NOT EXISTS idx_contact_labels_contact_id ON contact_labels (contact_id); +CREATE INDEX IF NOT EXISTS idx_contact_labels_tag_id ON contact_labels (tag_id); +CREATE INDEX IF NOT EXISTS idx_contact_labels_account_id ON contact_labels (account_id); + +-- ============ tags (may already exist) ============ +CREATE TABLE IF NOT EXISTS tags ( + id BIGSERIAL PRIMARY KEY, + account_id BIGINT NOT NULL, + name VARCHAR(255) NOT NULL, + color VARCHAR(50) NOT NULL DEFAULT '#1f93ff', + description TEXT, + show_on_sidebar BOOLEAN, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + deleted_at TIMESTAMPTZ +); +CREATE UNIQUE INDEX IF NOT EXISTS idx_tag_account_name ON tags (account_id, name) WHERE deleted_at IS NULL; +CREATE INDEX IF NOT EXISTS idx_tags_deleted_at ON tags (deleted_at); + +-- ============ agent_bots ============ +CREATE TABLE IF NOT EXISTS agent_bots ( + id BIGSERIAL PRIMARY KEY, + account_id BIGINT, + name VARCHAR(255) NOT NULL, + description VARCHAR(512), + avatar_url VARCHAR(512), + outgoing_url VARCHAR(1024), + bot_type VARCHAR(50) DEFAULT 'webhook', + secret VARCHAR(128), + access_token VARCHAR(128), + config JSONB, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() +); +CREATE INDEX IF NOT EXISTS idx_agent_bots_account_id ON agent_bots (account_id); +CREATE UNIQUE INDEX IF NOT EXISTS idx_agent_bots_secret ON agent_bots (secret) WHERE secret != ''; +CREATE UNIQUE INDEX IF NOT EXISTS idx_agent_bots_access_token ON agent_bots (access_token) WHERE access_token != ''; + +-- ============ agent_bot_inboxes ============ +CREATE TABLE IF NOT EXISTS agent_bot_inboxes ( + id BIGSERIAL PRIMARY KEY, + agent_bot_id BIGINT NOT NULL, + inbox_id BIGINT NOT NULL, + account_id BIGINT, + status INTEGER DEFAULT 0, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() +); +CREATE INDEX IF NOT EXISTS idx_agent_bot_inboxes_agent_bot_id ON agent_bot_inboxes (agent_bot_id); +CREATE INDEX IF NOT EXISTS idx_agent_bot_inboxes_inbox_id ON agent_bot_inboxes (inbox_id); +CREATE INDEX IF NOT EXISTS idx_agent_bot_inboxes_account_id ON agent_bot_inboxes (account_id); + +-- ============ agent_bot_presence_events ============ +CREATE TABLE IF NOT EXISTS agent_bot_presence_events ( + id BIGSERIAL PRIMARY KEY, + agent_bot_id BIGINT NOT NULL, + inbox_id BIGINT NOT NULL, + account_id BIGINT NOT NULL, + presence_type VARCHAR(100) NOT NULL, + metadata JSONB, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() +); +CREATE INDEX IF NOT EXISTS idx_agent_bot_presence_events_agent_bot_id ON agent_bot_presence_events (agent_bot_id); +CREATE INDEX IF NOT EXISTS idx_agent_bot_presence_events_inbox_id ON agent_bot_presence_events (inbox_id); +CREATE INDEX IF NOT EXISTS idx_agent_bot_presence_events_account_id ON agent_bot_presence_events (account_id); + +-- ============ custom_attribute_definitions ============ +CREATE TABLE IF NOT EXISTS custom_attribute_definitions ( + id BIGSERIAL PRIMARY KEY, + account_id BIGINT NOT NULL, + attribute_name VARCHAR(255) NOT NULL, + attribute_display_name VARCHAR(255) NOT NULL, + attribute_type VARCHAR(50) NOT NULL DEFAULT 'text', + attribute_model VARCHAR(50) NOT NULL, + default_value JSONB, + attribute_values JSONB, + regex_pattern VARCHAR(255), + regex_cue VARCHAR(255), + description TEXT, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + deleted_at TIMESTAMPTZ +); +CREATE INDEX IF NOT EXISTS idx_custom_attr_defs_account_id ON custom_attribute_definitions (account_id); +CREATE UNIQUE INDEX IF NOT EXISTS idx_attr_name_account_model ON custom_attribute_definitions (attribute_name, account_id, attribute_model) WHERE deleted_at IS NULL; +CREATE INDEX IF NOT EXISTS idx_custom_attr_defs_deleted_at ON custom_attribute_definitions (deleted_at); + +-- ============ custom_filters ============ +CREATE TABLE IF NOT EXISTS custom_filters ( + id BIGSERIAL PRIMARY KEY, + account_id BIGINT NOT NULL, + name VARCHAR(255) NOT NULL, + filter_type VARCHAR(50) NOT NULL, + query JSONB NOT NULL, + created_by_id BIGINT NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + deleted_at TIMESTAMPTZ +); +CREATE INDEX IF NOT EXISTS idx_custom_filters_account_id ON custom_filters (account_id); +CREATE INDEX IF NOT EXISTS idx_custom_filters_filter_type ON custom_filters (filter_type); +CREATE INDEX IF NOT EXISTS idx_custom_filters_created_by_id ON custom_filters (created_by_id); +CREATE INDEX IF NOT EXISTS idx_custom_filters_deleted_at ON custom_filters (deleted_at); + +-- ============ conversation_participants ============ +CREATE TABLE IF NOT EXISTS conversation_participants ( + id BIGSERIAL PRIMARY KEY, + account_id BIGINT NOT NULL, + conversation_id BIGINT NOT NULL, + user_id BIGINT NOT NULL, + role VARCHAR(50) DEFAULT 'participant', + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + deleted_at TIMESTAMPTZ +); +CREATE INDEX IF NOT EXISTS idx_conv_participants_account_id ON conversation_participants (account_id); +CREATE INDEX IF NOT EXISTS idx_conv_participants_conversation_id ON conversation_participants (conversation_id); +CREATE INDEX IF NOT EXISTS idx_conv_participants_user_id ON conversation_participants (user_id); +CREATE UNIQUE INDEX IF NOT EXISTS idx_conv_participants_user_conv ON conversation_participants (user_id, conversation_id) WHERE deleted_at IS NULL; +CREATE INDEX IF NOT EXISTS idx_conv_participants_deleted_at ON conversation_participants (deleted_at); + +-- ============ notes ============ +CREATE TABLE IF NOT EXISTS notes ( + id BIGSERIAL PRIMARY KEY, + content TEXT NOT NULL, + account_id BIGINT NOT NULL, + contact_id BIGINT NOT NULL, + user_id BIGINT, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + deleted_at TIMESTAMPTZ +); +CREATE INDEX IF NOT EXISTS idx_notes_account_id ON notes (account_id); +CREATE INDEX IF NOT EXISTS idx_notes_contact_id ON notes (contact_id); +CREATE INDEX IF NOT EXISTS idx_notes_user_id ON notes (user_id); +CREATE INDEX IF NOT EXISTS idx_notes_deleted_at ON notes (deleted_at); + +-- ============ contact_notes ============ +CREATE TABLE IF NOT EXISTS contact_notes ( + id BIGSERIAL PRIMARY KEY, + contact_id BIGINT NOT NULL, + user_id BIGINT NOT NULL, + content TEXT, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() +); +CREATE INDEX IF NOT EXISTS idx_contact_notes_contact_id ON contact_notes (contact_id); + +-- ============ company_notes (may already exist) ============ +CREATE TABLE IF NOT EXISTS company_notes ( + id BIGSERIAL PRIMARY KEY, + company_id BIGINT NOT NULL, + user_id BIGINT NOT NULL, + content TEXT, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() +); +CREATE INDEX IF NOT EXISTS idx_company_notes_company_id ON company_notes (company_id); + +-- ============ csat_templates ============ +CREATE TABLE IF NOT EXISTS csat_templates ( + id BIGSERIAL PRIMARY KEY, + inbox_id BIGINT NOT NULL, + message TEXT, + status VARCHAR(50) DEFAULT 'pending', + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + deleted_at TIMESTAMPTZ +); +CREATE INDEX IF NOT EXISTS idx_csat_templates_inbox_id ON csat_templates (inbox_id); +CREATE INDEX IF NOT EXISTS idx_csat_templates_deleted_at ON csat_templates (deleted_at); + +-- ============ delivery_statuses ============ +CREATE TABLE IF NOT EXISTS delivery_statuses ( + id BIGSERIAL PRIMARY KEY, + message_id BIGINT NOT NULL, + inbox_id BIGINT NOT NULL, + contact_id BIGINT NOT NULL, + status VARCHAR(50) NOT NULL DEFAULT 'sent', + delivered_at TIMESTAMPTZ, + read_at TIMESTAMPTZ, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + deleted_at TIMESTAMPTZ +); +CREATE INDEX IF NOT EXISTS idx_delivery_statuses_message_id ON delivery_statuses (message_id); +CREATE INDEX IF NOT EXISTS idx_delivery_statuses_inbox_id ON delivery_statuses (inbox_id); +CREATE INDEX IF NOT EXISTS idx_delivery_statuses_contact_id ON delivery_statuses (contact_id); +CREATE INDEX IF NOT EXISTS idx_delivery_statuses_deleted_at ON delivery_statuses (deleted_at); + +-- ============ draft_messages ============ +CREATE TABLE IF NOT EXISTS draft_messages ( + id BIGSERIAL PRIMARY KEY, + conversation_id BIGINT NOT NULL, + user_id BIGINT NOT NULL, + content TEXT, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + deleted_at TIMESTAMPTZ +); +CREATE INDEX IF NOT EXISTS idx_draft_messages_conversation_id ON draft_messages (conversation_id); +CREATE INDEX IF NOT EXISTS idx_draft_messages_user_id ON draft_messages (user_id); +CREATE INDEX IF NOT EXISTS idx_draft_messages_deleted_at ON draft_messages (deleted_at); + +-- ============ email_channel_migrations ============ +CREATE TABLE IF NOT EXISTS email_channel_migrations ( + id BIGSERIAL PRIMARY KEY, + account_id BIGINT NOT NULL, + inbox_id BIGINT NOT NULL, + target_inbox_id BIGINT NOT NULL, + migration_status VARCHAR(50) NOT NULL DEFAULT 'pending', + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + deleted_at TIMESTAMPTZ +); +CREATE INDEX IF NOT EXISTS idx_email_channel_migrations_account_id ON email_channel_migrations (account_id); +CREATE INDEX IF NOT EXISTS idx_email_channel_migrations_deleted_at ON email_channel_migrations (deleted_at); + +-- ============ inbox_limits ============ +CREATE TABLE IF NOT EXISTS inbox_limits ( + id BIGSERIAL PRIMARY KEY, + inbox_id BIGINT NOT NULL, + type VARCHAR(100) NOT NULL, + value INTEGER NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + deleted_at TIMESTAMPTZ +); +CREATE INDEX IF NOT EXISTS idx_inbox_limits_inbox_id ON inbox_limits (inbox_id); +CREATE INDEX IF NOT EXISTS idx_inbox_limits_deleted_at ON inbox_limits (deleted_at); + +-- ============ notification_subscriptions ============ +CREATE TABLE IF NOT EXISTS notification_subscriptions ( + id BIGSERIAL PRIMARY KEY, + identifier TEXT NOT NULL, + subscription_attributes JSONB NOT NULL, + subscription_type INTEGER NOT NULL, + user_id BIGINT NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() +); +CREATE UNIQUE INDEX IF NOT EXISTS idx_notification_subscriptions_on_identifier ON notification_subscriptions (identifier); +CREATE INDEX IF NOT EXISTS idx_notification_subscriptions_on_user_id ON notification_subscriptions (user_id); + +-- ============ sso_sessions ============ +CREATE TABLE IF NOT EXISTS sso_sessions ( + id BIGSERIAL PRIMARY KEY, + user_id BIGINT NOT NULL, + session_id VARCHAR(255) NOT NULL, + provider VARCHAR(50) NOT NULL, + idp_entity_id VARCHAR(512), + name_id VARCHAR(512), + account_id BIGINT NOT NULL, + role VARCHAR(50), + access_token VARCHAR(512), + refresh_token VARCHAR(512), + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + expires_at TIMESTAMPTZ NOT NULL, + last_seen_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + ended_at TIMESTAMPTZ, + status VARCHAR(20) NOT NULL DEFAULT 'active', + deleted_at TIMESTAMPTZ +); +CREATE INDEX IF NOT EXISTS idx_sso_sessions_user_id ON sso_sessions (user_id); +CREATE UNIQUE INDEX IF NOT EXISTS idx_sso_sessions_session_id ON sso_sessions (session_id); +CREATE INDEX IF NOT EXISTS idx_sso_sessions_account_id ON sso_sessions (account_id); +CREATE INDEX IF NOT EXISTS idx_sso_sessions_expires_at ON sso_sessions (expires_at); +CREATE INDEX IF NOT EXISTS idx_sso_sessions_deleted_at ON sso_sessions (deleted_at); + +-- ============ whatsapp_calls ============ +CREATE TABLE IF NOT EXISTS whatsapp_calls ( + id BIGSERIAL PRIMARY KEY, + inbox_id BIGINT NOT NULL, + conversation_id BIGINT NOT NULL, + call_id VARCHAR(255) NOT NULL, + call_status VARCHAR(50) NOT NULL, + duration INTEGER, + caller_number VARCHAR(50), + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() +); +CREATE INDEX IF NOT EXISTS idx_whatsapp_calls_inbox_id ON whatsapp_calls (inbox_id); +CREATE INDEX IF NOT EXISTS idx_whatsapp_calls_conversation_id ON whatsapp_calls (conversation_id); +CREATE UNIQUE INDEX IF NOT EXISTS idx_whatsapp_calls_call_id ON whatsapp_calls (call_id); +CREATE INDEX IF NOT EXISTS idx_whatsapp_calls_call_status ON whatsapp_calls (call_status); +CREATE INDEX IF NOT EXISTS idx_whatsapp_calls_created_at ON whatsapp_calls (created_at); + +-- ============ assignment_policies (may already exist from AutoMigrate) ============ +CREATE TABLE IF NOT EXISTS assignment_policies ( + id BIGSERIAL PRIMARY KEY, + account_id BIGINT NOT NULL, + inbox_id BIGINT, + policy_type VARCHAR(100) NOT NULL DEFAULT 'round_robin', + enabled BOOLEAN NOT NULL DEFAULT true, + config JSONB, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + deleted_at TIMESTAMPTZ +); +CREATE INDEX IF NOT EXISTS idx_assignment_policies_account_id ON assignment_policies (account_id); +CREATE INDEX IF NOT EXISTS idx_assignment_policies_inbox_id ON assignment_policies (inbox_id); +CREATE INDEX IF NOT EXISTS idx_assignment_policies_deleted_at ON assignment_policies (deleted_at); + +-- ============ assignment_policies_v2 ============ +CREATE TABLE IF NOT EXISTS assignment_policies_v2 ( + id BIGSERIAL PRIMARY KEY, + account_id BIGINT NOT NULL, + inbox_id BIGINT, + policy_type VARCHAR(100) NOT NULL DEFAULT 'round_robin', + enabled BOOLEAN NOT NULL DEFAULT true, + config JSONB, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + deleted_at TIMESTAMPTZ +); +CREATE INDEX IF NOT EXISTS idx_assignment_policies_v2_account_id ON assignment_policies_v2 (account_id); +CREATE INDEX IF NOT EXISTS idx_assignment_policies_v2_inbox_id ON assignment_policies_v2 (inbox_id); +CREATE INDEX IF NOT EXISTS idx_assignment_policies_v2_deleted_at ON assignment_policies_v2 (deleted_at); + +-- ============ automation_actions ============ +CREATE TABLE IF NOT EXISTS automation_actions ( + id BIGSERIAL PRIMARY KEY, + account_id BIGINT NOT NULL, + action_type VARCHAR(100) NOT NULL, + config JSONB, + executed_at TIMESTAMPTZ, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + deleted_at TIMESTAMPTZ +); +CREATE INDEX IF NOT EXISTS idx_automation_actions_account_id ON automation_actions (account_id); +CREATE INDEX IF NOT EXISTS idx_automation_actions_deleted_at ON automation_actions (deleted_at); + +-- ============ banners ============ +CREATE TABLE IF NOT EXISTS banners ( + id BIGSERIAL PRIMARY KEY, + title VARCHAR(255), + content TEXT, + banner_type VARCHAR(50), + status VARCHAR(50) DEFAULT 'active', + starts_at TIMESTAMPTZ, + ends_at TIMESTAMPTZ, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + deleted_at TIMESTAMPTZ +); +CREATE INDEX IF NOT EXISTS idx_banners_status ON banners (status); +CREATE INDEX IF NOT EXISTS idx_banners_deleted_at ON banners (deleted_at); + +-- ============ captain_assistant_inboxes ============ +CREATE TABLE IF NOT EXISTS captain_assistant_inboxes ( + id BIGSERIAL PRIMARY KEY, + captain_assistant_id BIGINT NOT NULL, + inbox_id BIGINT NOT NULL, + account_id BIGINT NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + deleted_at TIMESTAMPTZ +); +CREATE INDEX IF NOT EXISTS idx_captain_assistant_inboxes_assistant_id ON captain_assistant_inboxes (captain_assistant_id); +CREATE INDEX IF NOT EXISTS idx_captain_assistant_inboxes_inbox_id ON captain_assistant_inboxes (inbox_id); +CREATE INDEX IF NOT EXISTS idx_captain_assistant_inboxes_account_id ON captain_assistant_inboxes (account_id); +CREATE INDEX IF NOT EXISTS idx_captain_assistant_inboxes_deleted_at ON captain_assistant_inboxes (deleted_at); + +-- ============ contactables ============ +CREATE TABLE IF NOT EXISTS contactables ( + id BIGSERIAL PRIMARY KEY, + account_id BIGINT NOT NULL, + contactable_type VARCHAR(50) NOT NULL, + contactable_id BIGINT NOT NULL, + email VARCHAR(255), + phone VARCHAR(50), + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + deleted_at TIMESTAMPTZ +); +CREATE INDEX IF NOT EXISTS idx_contactables_account_id ON contactables (account_id); +CREATE INDEX IF NOT EXISTS idx_contactables_contactable_type_id ON contactables (contactable_type, contactable_id); +CREATE INDEX IF NOT EXISTS idx_contactables_deleted_at ON contactables (deleted_at); + +-- ============ contact_exports ============ +CREATE TABLE IF NOT EXISTS contact_exports ( + id BIGSERIAL PRIMARY KEY, + account_id BIGINT NOT NULL, + user_id BIGINT NOT NULL, + status VARCHAR(50) DEFAULT 'pending', + file_url TEXT, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + deleted_at TIMESTAMPTZ +); +CREATE INDEX IF NOT EXISTS idx_contact_exports_account_id ON contact_exports (account_id); +CREATE INDEX IF NOT EXISTS idx_contact_exports_user_id ON contact_exports (user_id); +CREATE INDEX IF NOT EXISTS idx_contact_exports_deleted_at ON contact_exports (deleted_at); + +-- ============ data_imports ============ +CREATE TABLE IF NOT EXISTS data_imports ( + id BIGSERIAL PRIMARY KEY, + account_id BIGINT NOT NULL, + user_id BIGINT NOT NULL, + status VARCHAR(50) DEFAULT 'pending', + file_url TEXT, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + deleted_at TIMESTAMPTZ +); +CREATE INDEX IF NOT EXISTS idx_data_imports_account_id ON data_imports (account_id); +CREATE INDEX IF NOT EXISTS idx_data_imports_user_id ON data_imports (user_id); +CREATE INDEX IF NOT EXISTS idx_data_imports_deleted_at ON data_imports (deleted_at); + +-- ============ direct_uploads ============ +CREATE TABLE IF NOT EXISTS direct_uploads ( + id BIGSERIAL PRIMARY KEY, + account_id BIGINT NOT NULL, + file_name VARCHAR(255), + file_url TEXT, + file_size BIGINT, + content_type VARCHAR(100), + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + deleted_at TIMESTAMPTZ +); +CREATE INDEX IF NOT EXISTS idx_direct_uploads_account_id ON direct_uploads (account_id); +CREATE INDEX IF NOT EXISTS idx_direct_uploads_deleted_at ON direct_uploads (deleted_at); + +-- ============ email_templates ============ +CREATE TABLE IF NOT EXISTS email_templates ( + id BIGSERIAL PRIMARY KEY, + account_id BIGINT NOT NULL, + name VARCHAR(255) NOT NULL, + subject VARCHAR(512), + body TEXT, + template_type VARCHAR(50), + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + deleted_at TIMESTAMPTZ +); +CREATE INDEX IF NOT EXISTS idx_email_templates_account_id ON email_templates (account_id); +CREATE INDEX IF NOT EXISTS idx_email_templates_deleted_at ON email_templates (deleted_at); + +-- ============ message_reactions ============ +CREATE TABLE IF NOT EXISTS message_reactions ( + id BIGSERIAL PRIMARY KEY, + message_id BIGINT NOT NULL, + account_id BIGINT NOT NULL, + user_id BIGINT NOT NULL, + reaction_type VARCHAR(50) NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + deleted_at TIMESTAMPTZ +); +CREATE INDEX IF NOT EXISTS idx_message_reactions_message_id ON message_reactions (message_id); +CREATE INDEX IF NOT EXISTS idx_message_reactions_account_id ON message_reactions (account_id); +CREATE INDEX IF NOT EXISTS idx_message_reactions_user_id ON message_reactions (user_id); +CREATE INDEX IF NOT EXISTS idx_message_reactions_deleted_at ON message_reactions (deleted_at); + +-- ============ reports ============ +CREATE TABLE IF NOT EXISTS reports ( + id BIGSERIAL PRIMARY KEY, + account_id BIGINT NOT NULL, + report_type VARCHAR(100) NOT NULL, + config JSONB, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + deleted_at TIMESTAMPTZ +); +CREATE INDEX IF NOT EXISTS idx_reports_account_id ON reports (account_id); +CREATE INDEX IF NOT EXISTS idx_reports_report_type ON reports (report_type); +CREATE INDEX IF NOT EXISTS idx_reports_deleted_at ON reports (deleted_at); + +-- ============ saml_idp_configs ============ +CREATE TABLE IF NOT EXISTS saml_idp_configs ( + id BIGSERIAL PRIMARY KEY, + account_id BIGINT NOT NULL, + entity_id VARCHAR(512), + sso_url VARCHAR(512), + slo_url VARCHAR(512), + x509_cert TEXT, + name_id_format VARCHAR(100), + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + deleted_at TIMESTAMPTZ +); +CREATE INDEX IF NOT EXISTS idx_saml_idp_configs_account_id ON saml_idp_configs (account_id); +CREATE INDEX IF NOT EXISTS idx_saml_idp_configs_deleted_at ON saml_idp_configs (deleted_at); + +-- ============ pre_chat_forms ============ +CREATE TABLE IF NOT EXISTS pre_chat_forms ( + id BIGSERIAL PRIMARY KEY, + inbox_id BIGINT NOT NULL, + enabled BOOLEAN DEFAULT false, + form_config JSONB, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + deleted_at TIMESTAMPTZ +); +CREATE INDEX IF NOT EXISTS idx_pre_chat_forms_inbox_id ON pre_chat_forms (inbox_id); +CREATE INDEX IF NOT EXISTS idx_pre_chat_forms_deleted_at ON pre_chat_forms (deleted_at); + +-- ============ widget_file_uploads ============ +CREATE TABLE IF NOT EXISTS widget_file_uploads ( + id BIGSERIAL PRIMARY KEY, + inbox_id BIGINT NOT NULL, + enabled BOOLEAN DEFAULT true, + max_file_size INTEGER, + allowed_types JSONB, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + deleted_at TIMESTAMPTZ +); +CREATE INDEX IF NOT EXISTS idx_widget_file_uploads_inbox_id ON widget_file_uploads (inbox_id); +CREATE INDEX IF NOT EXISTS idx_widget_file_uploads_deleted_at ON widget_file_uploads (deleted_at); + +-- ============ widget_offline_messages ============ +CREATE TABLE IF NOT EXISTS widget_offline_messages ( + id BIGSERIAL PRIMARY KEY, + inbox_id BIGINT NOT NULL, + email VARCHAR(255), + message TEXT, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + deleted_at TIMESTAMPTZ +); +CREATE INDEX IF NOT EXISTS idx_widget_offline_messages_inbox_id ON widget_offline_messages (inbox_id); +CREATE INDEX IF NOT EXISTS idx_widget_offline_messages_deleted_at ON widget_offline_messages (deleted_at); + +-- ============ widget_theme_configs ============ +CREATE TABLE IF NOT EXISTS widget_theme_configs ( + id BIGSERIAL PRIMARY KEY, + inbox_id BIGINT NOT NULL, + theme_config JSONB, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + deleted_at TIMESTAMPTZ +); +CREATE INDEX IF NOT EXISTS idx_widget_theme_configs_inbox_id ON widget_theme_configs (inbox_id); +CREATE INDEX IF NOT EXISTS idx_widget_theme_configs_deleted_at ON widget_theme_configs (deleted_at); + +-- ============ widget_tests ============ +CREATE TABLE IF NOT EXISTS widget_tests ( + id BIGSERIAL PRIMARY KEY, + inbox_id BIGINT NOT NULL, + test_config JSONB, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + deleted_at TIMESTAMPTZ +); +CREATE INDEX IF NOT EXISTS idx_widget_tests_inbox_id ON widget_tests (inbox_id); +CREATE INDEX IF NOT EXISTS idx_widget_tests_deleted_at ON widget_tests (deleted_at); + +-- ============ working_hours ============ +CREATE TABLE IF NOT EXISTS working_hours ( + id BIGSERIAL PRIMARY KEY, + inbox_id BIGINT NOT NULL, + day_of_week INTEGER NOT NULL, + start_time VARCHAR(10), + end_time VARCHAR(10), + enabled BOOLEAN DEFAULT true, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + deleted_at TIMESTAMPTZ +); +CREATE INDEX IF NOT EXISTS idx_working_hours_inbox_id ON working_hours (inbox_id); +CREATE INDEX IF NOT EXISTS idx_working_hours_deleted_at ON working_hours (deleted_at); + +-- ============ account_ldap_settings ============ +CREATE TABLE IF NOT EXISTS account_ldap_settings ( + id BIGSERIAL PRIMARY KEY, + account_id BIGINT NOT NULL, + enabled BOOLEAN DEFAULT false, + host VARCHAR(255), + port INTEGER, + base_dn VARCHAR(255), + bind_dn VARCHAR(255), + bind_password VARCHAR(255), + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + deleted_at TIMESTAMPTZ +); +CREATE INDEX IF NOT EXISTS idx_account_ldap_settings_account_id ON account_ldap_settings (account_id); +CREATE INDEX IF NOT EXISTS idx_account_ldap_settings_deleted_at ON account_ldap_settings (deleted_at); + +-- ============ account_oidc_settings ============ +CREATE TABLE IF NOT EXISTS account_oidc_settings ( + id BIGSERIAL PRIMARY KEY, + account_id BIGINT NOT NULL, + enabled BOOLEAN DEFAULT false, + issuer VARCHAR(512), + client_id VARCHAR(255), + client_secret VARCHAR(255), + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + deleted_at TIMESTAMPTZ +); +CREATE INDEX IF NOT EXISTS idx_account_oidc_settings_account_id ON account_oidc_settings (account_id); +CREATE INDEX IF NOT EXISTS idx_account_oidc_settings_deleted_at ON account_oidc_settings (deleted_at); + +-- ============ account_saml_settings ============ +CREATE TABLE IF NOT EXISTS account_saml_settings ( + id BIGSERIAL PRIMARY KEY, + account_id BIGINT NOT NULL, + enabled BOOLEAN DEFAULT false, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + deleted_at TIMESTAMPTZ +); +CREATE INDEX IF NOT EXISTS idx_account_saml_settings_account_id ON account_saml_settings (account_id); +CREATE INDEX IF NOT EXISTS idx_account_saml_settings_deleted_at ON account_saml_settings (deleted_at); + +-- ============ push_tokens ============ +CREATE TABLE IF NOT EXISTS push_tokens ( + id BIGSERIAL PRIMARY KEY, + user_id BIGINT NOT NULL, + token TEXT NOT NULL, + platform VARCHAR(50), + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + deleted_at TIMESTAMPTZ +); +CREATE INDEX IF NOT EXISTS idx_push_tokens_user_id ON push_tokens (user_id); +CREATE INDEX IF NOT EXISTS idx_push_tokens_deleted_at ON push_tokens (deleted_at); + +-- ============ Add snoozed_until column to notifications ============ +ALTER TABLE notifications ADD COLUMN IF NOT EXISTS snoozed_until TIMESTAMPTZ; + +-- ============ Add missing columns to channels table ============ +ALTER TABLE channels ADD COLUMN IF NOT EXISTS type VARCHAR(100); diff --git a/backend/scripts/parity_frontend_smoke.sh b/backend/scripts/parity_frontend_smoke.sh index ff30bcc9..1b282682 100755 --- a/backend/scripts/parity_frontend_smoke.sh +++ b/backend/scripts/parity_frontend_smoke.sh @@ -6,7 +6,7 @@ set -euo pipefail ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" CHATWOOT_DIR="${CHATWOOT_DIR:-$ROOT/../frontend}" LOG_DIR="${GOCHAT_SMOKE_LOG_DIR:-$ROOT/.tmp/frontend-smoke}" -REPORT_PATH="${GOCHAT_SMOKE_REPORT:-$ROOT/docs/parity/frontend_smoke_report.md}" +REPORT_PATH="${GOCHAT_SMOKE_REPORT:-$ROOT/docs/parity/frontend-smoke-report.md}" API_HOST="${GOCHAT_SMOKE_API_HOST:-127.0.0.1}" API_PORT="${GOCHAT_SMOKE_API_PORT:-3000}" FRONTEND_HOST="${GOCHAT_SMOKE_FRONTEND_HOST:-localhost}" @@ -38,7 +38,7 @@ Environment: GOCHAT_SMOKE_FRONTEND_HOST Vite frontend host. Default: localhost GOCHAT_SMOKE_FRONTEND_PORT Vite frontend port. Default: 3036 GOCHAT_SMOKE_LOG_DIR Log directory. Default: .tmp/frontend-smoke - GOCHAT_SMOKE_REPORT Markdown report path. Default: docs/parity/frontend_smoke_report.md + GOCHAT_SMOKE_REPORT Markdown report path. Default: docs/parity/frontend-smoke-report.md GOCHAT_SMOKE_SEARCH_ENGINE Search engine for boot smoke. Default: meilisearch GOCHAT_SMOKE_MEILI_HOST Meilisearch URL. Default: http://127.0.0.1:7700 GOCHAT_SMOKE_MEILI_API_KEY Meilisearch API key. Default: gochat_dev diff --git a/docs/.hermes/skills/brainstorming/SKILL.md b/docs/.hermes/skills/brainstorming/SKILL.md deleted file mode 100644 index 06cd0a21..00000000 --- a/docs/.hermes/skills/brainstorming/SKILL.md +++ /dev/null @@ -1,164 +0,0 @@ ---- -name: brainstorming -description: "You MUST use this before any creative work - creating features, building components, adding functionality, or modifying behavior. Explores user intent, requirements and design before implementation." ---- - -# Brainstorming Ideas Into Designs - -Help turn ideas into fully formed designs and specs through natural collaborative dialogue. - -Start by understanding the current project context, then ask questions one at a time to refine the idea. Once you understand what you're building, present the design and get user approval. - - -Do NOT invoke any implementation skill, write any code, scaffold any project, or take any implementation action until you have presented a design and the user has approved it. This applies to EVERY project regardless of perceived simplicity. - - -## Anti-Pattern: "This Is Too Simple To Need A Design" - -Every project goes through this process. A todo list, a single-function utility, a config change — all of them. "Simple" projects are where unexamined assumptions cause the most wasted work. The design can be short (a few sentences for truly simple projects), but you MUST present it and get approval. - -## Checklist - -You MUST create a task for each of these items and complete them in order: - -1. **Explore project context** — check files, docs, recent commits -2. **Offer visual companion** (if topic will involve visual questions) — this is its own message, not combined with a clarifying question. See the Visual Companion section below. -3. **Ask clarifying questions** — one at a time, understand purpose/constraints/success criteria -4. **Propose 2-3 approaches** — with trade-offs and your recommendation -5. **Present design** — in sections scaled to their complexity, get user approval after each section -6. **Write design doc** — save to `docs/superpowers/specs/YYYY-MM-DD--design.md` and commit -7. **Spec self-review** — quick inline check for placeholders, contradictions, ambiguity, scope (see below) -8. **User reviews written spec** — ask user to review the spec file before proceeding -9. **Transition to implementation** — invoke writing-plans skill to create implementation plan - -## Process Flow - -```dot -digraph brainstorming { - "Explore project context" [shape=box]; - "Visual questions ahead?" [shape=diamond]; - "Offer Visual Companion\n(own message, no other content)" [shape=box]; - "Ask clarifying questions" [shape=box]; - "Propose 2-3 approaches" [shape=box]; - "Present design sections" [shape=box]; - "User approves design?" [shape=diamond]; - "Write design doc" [shape=box]; - "Spec self-review\n(fix inline)" [shape=box]; - "User reviews spec?" [shape=diamond]; - "Invoke writing-plans skill" [shape=doublecircle]; - - "Explore project context" -> "Visual questions ahead?"; - "Visual questions ahead?" -> "Offer Visual Companion\n(own message, no other content)" [label="yes"]; - "Visual questions ahead?" -> "Ask clarifying questions" [label="no"]; - "Offer Visual Companion\n(own message, no other content)" -> "Ask clarifying questions"; - "Ask clarifying questions" -> "Propose 2-3 approaches"; - "Propose 2-3 approaches" -> "Present design sections"; - "Present design sections" -> "User approves design?"; - "User approves design?" -> "Present design sections" [label="no, revise"]; - "User approves design?" -> "Write design doc" [label="yes"]; - "Write design doc" -> "Spec self-review\n(fix inline)"; - "Spec self-review\n(fix inline)" -> "User reviews spec?"; - "User reviews spec?" -> "Write design doc" [label="changes requested"]; - "User reviews spec?" -> "Invoke writing-plans skill" [label="approved"]; -} -``` - -**The terminal state is invoking writing-plans.** Do NOT invoke frontend-design, mcp-builder, or any other implementation skill. The ONLY skill you invoke after brainstorming is writing-plans. - -## The Process - -**Understanding the idea:** - -- Check out the current project state first (files, docs, recent commits) -- Before asking detailed questions, assess scope: if the request describes multiple independent subsystems (e.g., "build a platform with chat, file storage, billing, and analytics"), flag this immediately. Don't spend questions refining details of a project that needs to be decomposed first. -- If the project is too large for a single spec, help the user decompose into sub-projects: what are the independent pieces, how do they relate, what order should they be built? Then brainstorm the first sub-project through the normal design flow. Each sub-project gets its own spec → plan → implementation cycle. -- For appropriately-scoped projects, ask questions one at a time to refine the idea -- Prefer multiple choice questions when possible, but open-ended is fine too -- Only one question per message - if a topic needs more exploration, break it into multiple questions -- Focus on understanding: purpose, constraints, success criteria - -**Exploring approaches:** - -- Propose 2-3 different approaches with trade-offs -- Present options conversationally with your recommendation and reasoning -- Lead with your recommended option and explain why - -**Presenting the design:** - -- Once you believe you understand what you're building, present the design -- Scale each section to its complexity: a few sentences if straightforward, up to 200-300 words if nuanced -- Ask after each section whether it looks right so far -- Cover: architecture, components, data flow, error handling, testing -- Be ready to go back and clarify if something doesn't make sense - -**Design for isolation and clarity:** - -- Break the system into smaller units that each have one clear purpose, communicate through well-defined interfaces, and can be understood and tested independently -- For each unit, you should be able to answer: what does it do, how do you use it, and what does it depend on? -- Can someone understand what a unit does without reading its internals? Can you change the internals without breaking consumers? If not, the boundaries need work. -- Smaller, well-bounded units are also easier for you to work with - you reason better about code you can hold in context at once, and your edits are more reliable when files are focused. When a file grows large, that's often a signal that it's doing too much. - -**Working in existing codebases:** - -- Explore the current structure before proposing changes. Follow existing patterns. -- Where existing code has problems that affect the work (e.g., a file that's grown too large, unclear boundaries, tangled responsibilities), include targeted improvements as part of the design - the way a good developer improves code they're working in. -- Don't propose unrelated refactoring. Stay focused on what serves the current goal. - -## After the Design - -**Documentation:** - -- Write the validated design (spec) to `docs/superpowers/specs/YYYY-MM-DD--design.md` - - (User preferences for spec location override this default) -- Use elements-of-style:writing-clearly-and-concisely skill if available -- Commit the design document to git - -**Spec Self-Review:** -After writing the spec document, look at it with fresh eyes: - -1. **Placeholder scan:** Any "TBD", "TODO", incomplete sections, or vague requirements? Fix them. -2. **Internal consistency:** Do any sections contradict each other? Does the architecture match the feature descriptions? -3. **Scope check:** Is this focused enough for a single implementation plan, or does it need decomposition? -4. **Ambiguity check:** Could any requirement be interpreted two different ways? If so, pick one and make it explicit. - -Fix any issues inline. No need to re-review — just fix and move on. - -**User Review Gate:** -After the spec review loop passes, ask the user to review the written spec before proceeding: - -> "Spec written and committed to ``. Please review it and let me know if you want to make any changes before we start writing out the implementation plan." - -Wait for the user's response. If they request changes, make them and re-run the spec review loop. Only proceed once the user approves. - -**Implementation:** - -- Invoke the writing-plans skill to create a detailed implementation plan -- Do NOT invoke any other skill. writing-plans is the next step. - -## Key Principles - -- **One question at a time** - Don't overwhelm with multiple questions -- **Multiple choice preferred** - Easier to answer than open-ended when possible -- **YAGNI ruthlessly** - Remove unnecessary features from all designs -- **Explore alternatives** - Always propose 2-3 approaches before settling -- **Incremental validation** - Present design, get approval before moving on -- **Be flexible** - Go back and clarify when something doesn't make sense - -## Visual Companion - -A browser-based companion for showing mockups, diagrams, and visual options during brainstorming. Available as a tool — not a mode. Accepting the companion means it's available for questions that benefit from visual treatment; it does NOT mean every question goes through the browser. - -**Offering the companion:** When you anticipate that upcoming questions will involve visual content (mockups, layouts, diagrams), offer it once for consent: -> "Some of what we're working on might be easier to explain if I can show it to you in a web browser. I can put together mockups, diagrams, comparisons, and other visuals as we go. This feature is still new and can be token-intensive. Want to try it? (Requires opening a local URL)" - -**This offer MUST be its own message.** Do not combine it with clarifying questions, context summaries, or any other content. The message should contain ONLY the offer above and nothing else. Wait for the user's response before continuing. If they decline, proceed with text-only brainstorming. - -**Per-question decision:** Even after the user accepts, decide FOR EACH QUESTION whether to use the browser or the terminal. The test: **would the user understand this better by seeing it than reading it?** - -- **Use the browser** for content that IS visual — mockups, wireframes, layout comparisons, architecture diagrams, side-by-side visual designs -- **Use the terminal** for content that is text — requirements questions, conceptual choices, tradeoff lists, A/B/C/D text options, scope decisions - -A question about a UI topic is not automatically a visual question. "What does personality mean in this context?" is a conceptual question — use the terminal. "Which wizard layout works better?" is a visual question — use the browser. - -If they agree to the companion, read the detailed guide before proceeding: -`skills/brainstorming/visual-companion.md` diff --git a/docs/.hermes/skills/brainstorming/scripts/frame-template.html b/docs/.hermes/skills/brainstorming/scripts/frame-template.html deleted file mode 100644 index dcfe0181..00000000 --- a/docs/.hermes/skills/brainstorming/scripts/frame-template.html +++ /dev/null @@ -1,214 +0,0 @@ - - - - - Superpowers Brainstorming - - - -
-

Superpowers Brainstorming

-
Connected
-
- -
-
- -
-
- -
- Click an option above, then return to the terminal -
- - - diff --git a/docs/.hermes/skills/brainstorming/scripts/helper.js b/docs/.hermes/skills/brainstorming/scripts/helper.js deleted file mode 100644 index 111f97f5..00000000 --- a/docs/.hermes/skills/brainstorming/scripts/helper.js +++ /dev/null @@ -1,88 +0,0 @@ -(function() { - const WS_URL = 'ws://' + window.location.host; - let ws = null; - let eventQueue = []; - - function connect() { - ws = new WebSocket(WS_URL); - - ws.onopen = () => { - eventQueue.forEach(e => ws.send(JSON.stringify(e))); - eventQueue = []; - }; - - ws.onmessage = (msg) => { - const data = JSON.parse(msg.data); - if (data.type === 'reload') { - window.location.reload(); - } - }; - - ws.onclose = () => { - setTimeout(connect, 1000); - }; - } - - function sendEvent(event) { - event.timestamp = Date.now(); - if (ws && ws.readyState === WebSocket.OPEN) { - ws.send(JSON.stringify(event)); - } else { - eventQueue.push(event); - } - } - - // Capture clicks on choice elements - document.addEventListener('click', (e) => { - const target = e.target.closest('[data-choice]'); - if (!target) return; - - sendEvent({ - type: 'click', - text: target.textContent.trim(), - choice: target.dataset.choice, - id: target.id || null - }); - - // Update indicator bar (defer so toggleSelect runs first) - setTimeout(() => { - const indicator = document.getElementById('indicator-text'); - if (!indicator) return; - const container = target.closest('.options') || target.closest('.cards'); - const selected = container ? container.querySelectorAll('.selected') : []; - if (selected.length === 0) { - indicator.textContent = 'Click an option above, then return to the terminal'; - } else if (selected.length === 1) { - const label = selected[0].querySelector('h3, .content h3, .card-body h3')?.textContent?.trim() || selected[0].dataset.choice; - indicator.innerHTML = '' + label + ' selected — return to terminal to continue'; - } else { - indicator.innerHTML = '' + selected.length + ' selected — return to terminal to continue'; - } - }, 0); - }); - - // Frame UI: selection tracking - window.selectedChoice = null; - - window.toggleSelect = function(el) { - const container = el.closest('.options') || el.closest('.cards'); - const multi = container && container.dataset.multiselect !== undefined; - if (container && !multi) { - container.querySelectorAll('.option, .card').forEach(o => o.classList.remove('selected')); - } - if (multi) { - el.classList.toggle('selected'); - } else { - el.classList.add('selected'); - } - window.selectedChoice = el.dataset.choice; - }; - - // Expose API for explicit use - window.brainstorm = { - send: sendEvent, - choice: (value, metadata = {}) => sendEvent({ type: 'choice', value, ...metadata }) - }; - - connect(); -})(); diff --git a/docs/.hermes/skills/brainstorming/scripts/server.cjs b/docs/.hermes/skills/brainstorming/scripts/server.cjs deleted file mode 100644 index 562c17f8..00000000 --- a/docs/.hermes/skills/brainstorming/scripts/server.cjs +++ /dev/null @@ -1,354 +0,0 @@ -const crypto = require('crypto'); -const http = require('http'); -const fs = require('fs'); -const path = require('path'); - -// ========== WebSocket Protocol (RFC 6455) ========== - -const OPCODES = { TEXT: 0x01, CLOSE: 0x08, PING: 0x09, PONG: 0x0A }; -const WS_MAGIC = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'; - -function computeAcceptKey(clientKey) { - return crypto.createHash('sha1').update(clientKey + WS_MAGIC).digest('base64'); -} - -function encodeFrame(opcode, payload) { - const fin = 0x80; - const len = payload.length; - let header; - - if (len < 126) { - header = Buffer.alloc(2); - header[0] = fin | opcode; - header[1] = len; - } else if (len < 65536) { - header = Buffer.alloc(4); - header[0] = fin | opcode; - header[1] = 126; - header.writeUInt16BE(len, 2); - } else { - header = Buffer.alloc(10); - header[0] = fin | opcode; - header[1] = 127; - header.writeBigUInt64BE(BigInt(len), 2); - } - - return Buffer.concat([header, payload]); -} - -function decodeFrame(buffer) { - if (buffer.length < 2) return null; - - const secondByte = buffer[1]; - const opcode = buffer[0] & 0x0F; - const masked = (secondByte & 0x80) !== 0; - let payloadLen = secondByte & 0x7F; - let offset = 2; - - if (!masked) throw new Error('Client frames must be masked'); - - if (payloadLen === 126) { - if (buffer.length < 4) return null; - payloadLen = buffer.readUInt16BE(2); - offset = 4; - } else if (payloadLen === 127) { - if (buffer.length < 10) return null; - payloadLen = Number(buffer.readBigUInt64BE(2)); - offset = 10; - } - - const maskOffset = offset; - const dataOffset = offset + 4; - const totalLen = dataOffset + payloadLen; - if (buffer.length < totalLen) return null; - - const mask = buffer.slice(maskOffset, dataOffset); - const data = Buffer.alloc(payloadLen); - for (let i = 0; i < payloadLen; i++) { - data[i] = buffer[dataOffset + i] ^ mask[i % 4]; - } - - return { opcode, payload: data, bytesConsumed: totalLen }; -} - -// ========== Configuration ========== - -const PORT = process.env.BRAINSTORM_PORT || (49152 + Math.floor(Math.random() * 16383)); -const HOST = process.env.BRAINSTORM_HOST || '127.0.0.1'; -const URL_HOST = process.env.BRAINSTORM_URL_HOST || (HOST === '127.0.0.1' ? 'localhost' : HOST); -const SESSION_DIR = process.env.BRAINSTORM_DIR || '/tmp/brainstorm'; -const CONTENT_DIR = path.join(SESSION_DIR, 'content'); -const STATE_DIR = path.join(SESSION_DIR, 'state'); -let ownerPid = process.env.BRAINSTORM_OWNER_PID ? Number(process.env.BRAINSTORM_OWNER_PID) : null; - -const MIME_TYPES = { - '.html': 'text/html', '.css': 'text/css', '.js': 'application/javascript', - '.json': 'application/json', '.png': 'image/png', '.jpg': 'image/jpeg', - '.jpeg': 'image/jpeg', '.gif': 'image/gif', '.svg': 'image/svg+xml' -}; - -// ========== Templates and Constants ========== - -const WAITING_PAGE = ` - -Brainstorm Companion - - -

Brainstorm Companion

-

Waiting for the agent to push a screen...

`; - -const frameTemplate = fs.readFileSync(path.join(__dirname, 'frame-template.html'), 'utf-8'); -const helperScript = fs.readFileSync(path.join(__dirname, 'helper.js'), 'utf-8'); -const helperInjection = ''; - -// ========== Helper Functions ========== - -function isFullDocument(html) { - const trimmed = html.trimStart().toLowerCase(); - return trimmed.startsWith('', content); -} - -function getNewestScreen() { - const files = fs.readdirSync(CONTENT_DIR) - .filter(f => f.endsWith('.html')) - .map(f => { - const fp = path.join(CONTENT_DIR, f); - return { path: fp, mtime: fs.statSync(fp).mtime.getTime() }; - }) - .sort((a, b) => b.mtime - a.mtime); - return files.length > 0 ? files[0].path : null; -} - -// ========== HTTP Request Handler ========== - -function handleRequest(req, res) { - touchActivity(); - if (req.method === 'GET' && req.url === '/') { - const screenFile = getNewestScreen(); - let html = screenFile - ? (raw => isFullDocument(raw) ? raw : wrapInFrame(raw))(fs.readFileSync(screenFile, 'utf-8')) - : WAITING_PAGE; - - if (html.includes('')) { - html = html.replace('', helperInjection + '\n'); - } else { - html += helperInjection; - } - - res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' }); - res.end(html); - } else if (req.method === 'GET' && req.url.startsWith('/files/')) { - const fileName = req.url.slice(7); - const filePath = path.join(CONTENT_DIR, path.basename(fileName)); - if (!fs.existsSync(filePath)) { - res.writeHead(404); - res.end('Not found'); - return; - } - const ext = path.extname(filePath).toLowerCase(); - const contentType = MIME_TYPES[ext] || 'application/octet-stream'; - res.writeHead(200, { 'Content-Type': contentType }); - res.end(fs.readFileSync(filePath)); - } else { - res.writeHead(404); - res.end('Not found'); - } -} - -// ========== WebSocket Connection Handling ========== - -const clients = new Set(); - -function handleUpgrade(req, socket) { - const key = req.headers['sec-websocket-key']; - if (!key) { socket.destroy(); return; } - - const accept = computeAcceptKey(key); - socket.write( - 'HTTP/1.1 101 Switching Protocols\r\n' + - 'Upgrade: websocket\r\n' + - 'Connection: Upgrade\r\n' + - 'Sec-WebSocket-Accept: ' + accept + '\r\n\r\n' - ); - - let buffer = Buffer.alloc(0); - clients.add(socket); - - socket.on('data', (chunk) => { - buffer = Buffer.concat([buffer, chunk]); - while (buffer.length > 0) { - let result; - try { - result = decodeFrame(buffer); - } catch (e) { - socket.end(encodeFrame(OPCODES.CLOSE, Buffer.alloc(0))); - clients.delete(socket); - return; - } - if (!result) break; - buffer = buffer.slice(result.bytesConsumed); - - switch (result.opcode) { - case OPCODES.TEXT: - handleMessage(result.payload.toString()); - break; - case OPCODES.CLOSE: - socket.end(encodeFrame(OPCODES.CLOSE, Buffer.alloc(0))); - clients.delete(socket); - return; - case OPCODES.PING: - socket.write(encodeFrame(OPCODES.PONG, result.payload)); - break; - case OPCODES.PONG: - break; - default: { - const closeBuf = Buffer.alloc(2); - closeBuf.writeUInt16BE(1003); - socket.end(encodeFrame(OPCODES.CLOSE, closeBuf)); - clients.delete(socket); - return; - } - } - } - }); - - socket.on('close', () => clients.delete(socket)); - socket.on('error', () => clients.delete(socket)); -} - -function handleMessage(text) { - let event; - try { - event = JSON.parse(text); - } catch (e) { - console.error('Failed to parse WebSocket message:', e.message); - return; - } - touchActivity(); - console.log(JSON.stringify({ source: 'user-event', ...event })); - if (event.choice) { - const eventsFile = path.join(STATE_DIR, 'events'); - fs.appendFileSync(eventsFile, JSON.stringify(event) + '\n'); - } -} - -function broadcast(msg) { - const frame = encodeFrame(OPCODES.TEXT, Buffer.from(JSON.stringify(msg))); - for (const socket of clients) { - try { socket.write(frame); } catch (e) { clients.delete(socket); } - } -} - -// ========== Activity Tracking ========== - -const IDLE_TIMEOUT_MS = 30 * 60 * 1000; // 30 minutes -let lastActivity = Date.now(); - -function touchActivity() { - lastActivity = Date.now(); -} - -// ========== File Watching ========== - -const debounceTimers = new Map(); - -// ========== Server Startup ========== - -function startServer() { - if (!fs.existsSync(CONTENT_DIR)) fs.mkdirSync(CONTENT_DIR, { recursive: true }); - if (!fs.existsSync(STATE_DIR)) fs.mkdirSync(STATE_DIR, { recursive: true }); - - // Track known files to distinguish new screens from updates. - // macOS fs.watch reports 'rename' for both new files and overwrites, - // so we can't rely on eventType alone. - const knownFiles = new Set( - fs.readdirSync(CONTENT_DIR).filter(f => f.endsWith('.html')) - ); - - const server = http.createServer(handleRequest); - server.on('upgrade', handleUpgrade); - - const watcher = fs.watch(CONTENT_DIR, (eventType, filename) => { - if (!filename || !filename.endsWith('.html')) return; - - if (debounceTimers.has(filename)) clearTimeout(debounceTimers.get(filename)); - debounceTimers.set(filename, setTimeout(() => { - debounceTimers.delete(filename); - const filePath = path.join(CONTENT_DIR, filename); - - if (!fs.existsSync(filePath)) return; // file was deleted - touchActivity(); - - if (!knownFiles.has(filename)) { - knownFiles.add(filename); - const eventsFile = path.join(STATE_DIR, 'events'); - if (fs.existsSync(eventsFile)) fs.unlinkSync(eventsFile); - console.log(JSON.stringify({ type: 'screen-added', file: filePath })); - } else { - console.log(JSON.stringify({ type: 'screen-updated', file: filePath })); - } - - broadcast({ type: 'reload' }); - }, 100)); - }); - watcher.on('error', (err) => console.error('fs.watch error:', err.message)); - - function shutdown(reason) { - console.log(JSON.stringify({ type: 'server-stopped', reason })); - const infoFile = path.join(STATE_DIR, 'server-info'); - if (fs.existsSync(infoFile)) fs.unlinkSync(infoFile); - fs.writeFileSync( - path.join(STATE_DIR, 'server-stopped'), - JSON.stringify({ reason, timestamp: Date.now() }) + '\n' - ); - watcher.close(); - clearInterval(lifecycleCheck); - server.close(() => process.exit(0)); - } - - function ownerAlive() { - if (!ownerPid) return true; - try { process.kill(ownerPid, 0); return true; } catch (e) { return e.code === 'EPERM'; } - } - - // Check every 60s: exit if owner process died or idle for 30 minutes - const lifecycleCheck = setInterval(() => { - if (!ownerAlive()) shutdown('owner process exited'); - else if (Date.now() - lastActivity > IDLE_TIMEOUT_MS) shutdown('idle timeout'); - }, 60 * 1000); - lifecycleCheck.unref(); - - // Validate owner PID at startup. If it's already dead, the PID resolution - // was wrong (common on WSL, Tailscale SSH, and cross-user scenarios). - // Disable monitoring and rely on the idle timeout instead. - if (ownerPid) { - try { process.kill(ownerPid, 0); } - catch (e) { - if (e.code !== 'EPERM') { - console.log(JSON.stringify({ type: 'owner-pid-invalid', pid: ownerPid, reason: 'dead at startup' })); - ownerPid = null; - } - } - } - - server.listen(PORT, HOST, () => { - const info = JSON.stringify({ - type: 'server-started', port: Number(PORT), host: HOST, - url_host: URL_HOST, url: 'http://' + URL_HOST + ':' + PORT, - screen_dir: CONTENT_DIR, state_dir: STATE_DIR - }); - console.log(info); - fs.writeFileSync(path.join(STATE_DIR, 'server-info'), info + '\n'); - }); -} - -if (require.main === module) { - startServer(); -} - -module.exports = { computeAcceptKey, encodeFrame, decodeFrame, OPCODES }; diff --git a/docs/.hermes/skills/brainstorming/scripts/start-server.sh b/docs/.hermes/skills/brainstorming/scripts/start-server.sh deleted file mode 100755 index 9ef6dcb9..00000000 --- a/docs/.hermes/skills/brainstorming/scripts/start-server.sh +++ /dev/null @@ -1,148 +0,0 @@ -#!/usr/bin/env bash -# Start the brainstorm server and output connection info -# Usage: start-server.sh [--project-dir ] [--host ] [--url-host ] [--foreground] [--background] -# -# Starts server on a random high port, outputs JSON with URL. -# Each session gets its own directory to avoid conflicts. -# -# Options: -# --project-dir Store session files under /.superpowers/brainstorm/ -# instead of /tmp. Files persist after server stops. -# --host Host/interface to bind (default: 127.0.0.1). -# Use 0.0.0.0 in remote/containerized environments. -# --url-host Hostname shown in returned URL JSON. -# --foreground Run server in the current terminal (no backgrounding). -# --background Force background mode (overrides Codex auto-foreground). - -SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" - -# Parse arguments -PROJECT_DIR="" -FOREGROUND="false" -FORCE_BACKGROUND="false" -BIND_HOST="127.0.0.1" -URL_HOST="" -while [[ $# -gt 0 ]]; do - case "$1" in - --project-dir) - PROJECT_DIR="$2" - shift 2 - ;; - --host) - BIND_HOST="$2" - shift 2 - ;; - --url-host) - URL_HOST="$2" - shift 2 - ;; - --foreground|--no-daemon) - FOREGROUND="true" - shift - ;; - --background|--daemon) - FORCE_BACKGROUND="true" - shift - ;; - *) - echo "{\"error\": \"Unknown argument: $1\"}" - exit 1 - ;; - esac -done - -if [[ -z "$URL_HOST" ]]; then - if [[ "$BIND_HOST" == "127.0.0.1" || "$BIND_HOST" == "localhost" ]]; then - URL_HOST="localhost" - else - URL_HOST="$BIND_HOST" - fi -fi - -# Some environments reap detached/background processes. Auto-foreground when detected. -if [[ -n "${CODEX_CI:-}" && "$FOREGROUND" != "true" && "$FORCE_BACKGROUND" != "true" ]]; then - FOREGROUND="true" -fi - -# Windows/Git Bash reaps nohup background processes. Auto-foreground when detected. -if [[ "$FOREGROUND" != "true" && "$FORCE_BACKGROUND" != "true" ]]; then - case "${OSTYPE:-}" in - msys*|cygwin*|mingw*) FOREGROUND="true" ;; - esac - if [[ -n "${MSYSTEM:-}" ]]; then - FOREGROUND="true" - fi -fi - -# Generate unique session directory -SESSION_ID="$$-$(date +%s)" - -if [[ -n "$PROJECT_DIR" ]]; then - SESSION_DIR="${PROJECT_DIR}/.superpowers/brainstorm/${SESSION_ID}" -else - SESSION_DIR="/tmp/brainstorm-${SESSION_ID}" -fi - -STATE_DIR="${SESSION_DIR}/state" -PID_FILE="${STATE_DIR}/server.pid" -LOG_FILE="${STATE_DIR}/server.log" - -# Create fresh session directory with content and state peers -mkdir -p "${SESSION_DIR}/content" "$STATE_DIR" - -# Kill any existing server -if [[ -f "$PID_FILE" ]]; then - old_pid=$(cat "$PID_FILE") - kill "$old_pid" 2>/dev/null - rm -f "$PID_FILE" -fi - -cd "$SCRIPT_DIR" - -# Resolve the harness PID (grandparent of this script). -# $PPID is the ephemeral shell the harness spawned to run us — it dies -# when this script exits. The harness itself is $PPID's parent. -OWNER_PID="$(ps -o ppid= -p "$PPID" 2>/dev/null | tr -d ' ')" -if [[ -z "$OWNER_PID" || "$OWNER_PID" == "1" ]]; then - OWNER_PID="$PPID" -fi - -# Foreground mode for environments that reap detached/background processes. -if [[ "$FOREGROUND" == "true" ]]; then - echo "$$" > "$PID_FILE" - env BRAINSTORM_DIR="$SESSION_DIR" BRAINSTORM_HOST="$BIND_HOST" BRAINSTORM_URL_HOST="$URL_HOST" BRAINSTORM_OWNER_PID="$OWNER_PID" node server.cjs - exit $? -fi - -# Start server, capturing output to log file -# Use nohup to survive shell exit; disown to remove from job table -nohup env BRAINSTORM_DIR="$SESSION_DIR" BRAINSTORM_HOST="$BIND_HOST" BRAINSTORM_URL_HOST="$URL_HOST" BRAINSTORM_OWNER_PID="$OWNER_PID" node server.cjs > "$LOG_FILE" 2>&1 & -SERVER_PID=$! -disown "$SERVER_PID" 2>/dev/null -echo "$SERVER_PID" > "$PID_FILE" - -# Wait for server-started message (check log file) -for i in {1..50}; do - if grep -q "server-started" "$LOG_FILE" 2>/dev/null; then - # Verify server is still alive after a short window (catches process reapers) - alive="true" - for _ in {1..20}; do - if ! kill -0 "$SERVER_PID" 2>/dev/null; then - alive="false" - break - fi - sleep 0.1 - done - if [[ "$alive" != "true" ]]; then - echo "{\"error\": \"Server started but was killed. Retry in a persistent terminal with: $SCRIPT_DIR/start-server.sh${PROJECT_DIR:+ --project-dir $PROJECT_DIR} --host $BIND_HOST --url-host $URL_HOST --foreground\"}" - exit 1 - fi - grep "server-started" "$LOG_FILE" | head -1 - exit 0 - fi - sleep 0.1 -done - -# Timeout - server didn't start -echo '{"error": "Server failed to start within 5 seconds"}' -exit 1 diff --git a/docs/.hermes/skills/brainstorming/scripts/stop-server.sh b/docs/.hermes/skills/brainstorming/scripts/stop-server.sh deleted file mode 100755 index a6b94e65..00000000 --- a/docs/.hermes/skills/brainstorming/scripts/stop-server.sh +++ /dev/null @@ -1,56 +0,0 @@ -#!/usr/bin/env bash -# Stop the brainstorm server and clean up -# Usage: stop-server.sh -# -# Kills the server process. Only deletes session directory if it's -# under /tmp (ephemeral). Persistent directories (.superpowers/) are -# kept so mockups can be reviewed later. - -SESSION_DIR="$1" - -if [[ -z "$SESSION_DIR" ]]; then - echo '{"error": "Usage: stop-server.sh "}' - exit 1 -fi - -STATE_DIR="${SESSION_DIR}/state" -PID_FILE="${STATE_DIR}/server.pid" - -if [[ -f "$PID_FILE" ]]; then - pid=$(cat "$PID_FILE") - - # Try to stop gracefully, fallback to force if still alive - kill "$pid" 2>/dev/null || true - - # Wait for graceful shutdown (up to ~2s) - for i in {1..20}; do - if ! kill -0 "$pid" 2>/dev/null; then - break - fi - sleep 0.1 - done - - # If still running, escalate to SIGKILL - if kill -0 "$pid" 2>/dev/null; then - kill -9 "$pid" 2>/dev/null || true - - # Give SIGKILL a moment to take effect - sleep 0.1 - fi - - if kill -0 "$pid" 2>/dev/null; then - echo '{"status": "failed", "error": "process still running"}' - exit 1 - fi - - rm -f "$PID_FILE" "${STATE_DIR}/server.log" - - # Only delete ephemeral /tmp directories - if [[ "$SESSION_DIR" == /tmp/* ]]; then - rm -rf "$SESSION_DIR" - fi - - echo '{"status": "stopped"}' -else - echo '{"status": "not_running"}' -fi diff --git a/docs/.hermes/skills/brainstorming/spec-document-reviewer-prompt.md b/docs/.hermes/skills/brainstorming/spec-document-reviewer-prompt.md deleted file mode 100644 index 35acbb61..00000000 --- a/docs/.hermes/skills/brainstorming/spec-document-reviewer-prompt.md +++ /dev/null @@ -1,49 +0,0 @@ -# Spec Document Reviewer Prompt Template - -Use this template when dispatching a spec document reviewer subagent. - -**Purpose:** Verify the spec is complete, consistent, and ready for implementation planning. - -**Dispatch after:** Spec document is written to docs/superpowers/specs/ - -``` -Task tool (general-purpose): - description: "Review spec document" - prompt: | - You are a spec document reviewer. Verify this spec is complete and ready for planning. - - **Spec to review:** [SPEC_FILE_PATH] - - ## What to Check - - | Category | What to Look For | - |----------|------------------| - | Completeness | TODOs, placeholders, "TBD", incomplete sections | - | Consistency | Internal contradictions, conflicting requirements | - | Clarity | Requirements ambiguous enough to cause someone to build the wrong thing | - | Scope | Focused enough for a single plan — not covering multiple independent subsystems | - | YAGNI | Unrequested features, over-engineering | - - ## Calibration - - **Only flag issues that would cause real problems during implementation planning.** - A missing section, a contradiction, or a requirement so ambiguous it could be - interpreted two different ways — those are issues. Minor wording improvements, - stylistic preferences, and "sections less detailed than others" are not. - - Approve unless there are serious gaps that would lead to a flawed plan. - - ## Output Format - - ## Spec Review - - **Status:** Approved | Issues Found - - **Issues (if any):** - - [Section X]: [specific issue] - [why it matters for planning] - - **Recommendations (advisory, do not block approval):** - - [suggestions for improvement] -``` - -**Reviewer returns:** Status, Issues (if any), Recommendations diff --git a/docs/.hermes/skills/brainstorming/visual-companion.md b/docs/.hermes/skills/brainstorming/visual-companion.md deleted file mode 100644 index 2113863d..00000000 --- a/docs/.hermes/skills/brainstorming/visual-companion.md +++ /dev/null @@ -1,287 +0,0 @@ -# Visual Companion Guide - -Browser-based visual brainstorming companion for showing mockups, diagrams, and options. - -## When to Use - -Decide per-question, not per-session. The test: **would the user understand this better by seeing it than reading it?** - -**Use the browser** when the content itself is visual: - -- **UI mockups** — wireframes, layouts, navigation structures, component designs -- **Architecture diagrams** — system components, data flow, relationship maps -- **Side-by-side visual comparisons** — comparing two layouts, two color schemes, two design directions -- **Design polish** — when the question is about look and feel, spacing, visual hierarchy -- **Spatial relationships** — state machines, flowcharts, entity relationships rendered as diagrams - -**Use the terminal** when the content is text or tabular: - -- **Requirements and scope questions** — "what does X mean?", "which features are in scope?" -- **Conceptual A/B/C choices** — picking between approaches described in words -- **Tradeoff lists** — pros/cons, comparison tables -- **Technical decisions** — API design, data modeling, architectural approach selection -- **Clarifying questions** — anything where the answer is words, not a visual preference - -A question *about* a UI topic is not automatically a visual question. "What kind of wizard do you want?" is conceptual — use the terminal. "Which of these wizard layouts feels right?" is visual — use the browser. - -## How It Works - -The server watches a directory for HTML files and serves the newest one to the browser. You write HTML content to `screen_dir`, the user sees it in their browser and can click to select options. Selections are recorded to `state_dir/events` that you read on your next turn. - -**Content fragments vs full documents:** If your HTML file starts with `/.superpowers/brainstorm/` for the session directory. - -**Note:** Pass the project root as `--project-dir` so mockups persist in `.superpowers/brainstorm/` and survive server restarts. Without it, files go to `/tmp` and get cleaned up. Remind the user to add `.superpowers/` to `.gitignore` if it's not already there. - -**Launching the server by platform:** - -**Claude Code (macOS / Linux):** -```bash -# Default mode works — the script backgrounds the server itself -scripts/start-server.sh --project-dir /path/to/project -``` - -**Claude Code (Windows):** -```bash -# Windows auto-detects and uses foreground mode, which blocks the tool call. -# Use run_in_background: true on the Bash tool call so the server survives -# across conversation turns. -scripts/start-server.sh --project-dir /path/to/project -``` -When calling this via the Bash tool, set `run_in_background: true`. Then read `$STATE_DIR/server-info` on the next turn to get the URL and port. - -**Codex:** -```bash -# Codex reaps background processes. The script auto-detects CODEX_CI and -# switches to foreground mode. Run it normally — no extra flags needed. -scripts/start-server.sh --project-dir /path/to/project -``` - -**Gemini CLI:** -```bash -# Use --foreground and set is_background: true on your shell tool call -# so the process survives across turns -scripts/start-server.sh --project-dir /path/to/project --foreground -``` - -**Other environments:** The server must keep running in the background across conversation turns. If your environment reaps detached processes, use `--foreground` and launch the command with your platform's background execution mechanism. - -If the URL is unreachable from your browser (common in remote/containerized setups), bind a non-loopback host: - -```bash -scripts/start-server.sh \ - --project-dir /path/to/project \ - --host 0.0.0.0 \ - --url-host localhost -``` - -Use `--url-host` to control what hostname is printed in the returned URL JSON. - -## The Loop - -1. **Check server is alive**, then **write HTML** to a new file in `screen_dir`: - - Before each write, check that `$STATE_DIR/server-info` exists. If it doesn't (or `$STATE_DIR/server-stopped` exists), the server has shut down — restart it with `start-server.sh` before continuing. The server auto-exits after 30 minutes of inactivity. - - Use semantic filenames: `platform.html`, `visual-style.html`, `layout.html` - - **Never reuse filenames** — each screen gets a fresh file - - Use Write tool — **never use cat/heredoc** (dumps noise into terminal) - - Server automatically serves the newest file - -2. **Tell user what to expect and end your turn:** - - Remind them of the URL (every step, not just first) - - Give a brief text summary of what's on screen (e.g., "Showing 3 layout options for the homepage") - - Ask them to respond in the terminal: "Take a look and let me know what you think. Click to select an option if you'd like." - -3. **On your next turn** — after the user responds in the terminal: - - Read `$STATE_DIR/events` if it exists — this contains the user's browser interactions (clicks, selections) as JSON lines - - Merge with the user's terminal text to get the full picture - - The terminal message is the primary feedback; `state_dir/events` provides structured interaction data - -4. **Iterate or advance** — if feedback changes current screen, write a new file (e.g., `layout-v2.html`). Only move to the next question when the current step is validated. - -5. **Unload when returning to terminal** — when the next step doesn't need the browser (e.g., a clarifying question, a tradeoff discussion), push a waiting screen to clear the stale content: - - ```html - -
-

Continuing in terminal...

-
- ``` - - This prevents the user from staring at a resolved choice while the conversation has moved on. When the next visual question comes up, push a new content file as usual. - -6. Repeat until done. - -## Writing Content Fragments - -Write just the content that goes inside the page. The server wraps it in the frame template automatically (header, theme CSS, selection indicator, and all interactive infrastructure). - -**Minimal example:** - -```html -

Which layout works better?

-

Consider readability and visual hierarchy

- -
-
-
A
-
-

Single Column

-

Clean, focused reading experience

-
-
-
-
B
-
-

Two Column

-

Sidebar navigation with main content

-
-
-
-``` - -That's it. No ``, no CSS, no `