8 Commits
Author SHA1 Message Date
Algis Dumbris e6f174e1b1 Merge branch '010-reactions-workflows' into main
Release / Build darwin/amd64 (push) Canceled after 0s
Release / Build linux/amd64 (push) Canceled after 0s
Release / Build darwin/arm64 (push) Canceled after 0s
Release / Build linux/arm64 (push) Canceled after 0s
Release / Generate Homebrew Formula (push) Canceled after 0s
Release / GitHub Release (push) Canceled after 0s
Release / Docker Image (push) Canceled after 0s
Release / Publish to MCP Registry (push) Canceled after 0s
2026-03-18 09:30:11 +02:00
Algis DumbrisandClaude Opus 4.6 e51adc376e feat: message reactions and workflow states (010-reactions-workflows)
Add typed reactions (approve/reject/in_progress/done/published) with
toggle semantics. Workflow state derived from highest-priority reaction.
New reactions package with model, SQLite store, and service layer.

REST API: POST/GET/DELETE /api/messages/{id}/reactions for toggle/query,
PUT /api/channels/{name}/settings for workflow config, GET by-state
endpoint for listing messages by workflow state.

MCP: react/unreact/get_reactions/list_by_state actions via bridge.

Web UI: WorkflowBadge (colored state pills) and ReactionPills (toggle
pills with agent names) components integrated into channel view.

Channel settings: auto_approve, stalemate_remind_after,
stalemate_escalate_after columns. CLI: channels update command.

Migration 013_reactions.sql adds message_reactions table and channel
workflow columns. 29+ new test cases across model and store.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-18 09:30:06 +02:00
Algis Dumbris 6ed4ce931a Merge branch '009-attachments-threads' into main
Release / Build darwin/amd64 (push) Canceled after 0s
Release / Build linux/amd64 (push) Canceled after 0s
Release / Build darwin/arm64 (push) Canceled after 0s
Release / Build linux/arm64 (push) Canceled after 0s
Release / Generate Homebrew Formula (push) Canceled after 0s
Release / GitHub Release (push) Canceled after 0s
Release / Docker Image (push) Canceled after 0s
Release / Publish to MCP Registry (push) Canceled after 0s
2026-03-17 16:36:31 +02:00
Algis DumbrisandClaude Opus 4.6 667b7a4c2e feat: file attachments and thread visibility (009-attachments-threads)
Web UI: paperclip button for file upload (images, PDFs, text), inline
attachment cards with file icon/name/size, image thumbnails with
fullscreen overlay, attachment display in thread panel.

Threads: always-visible reply count badges on messages, clickable to
open thread panel. reply_count and attachments enriched in all API
responses via batch queries.

MCP: attachments parameter on send_message tool, updated tool
descriptions for threading and attachment workflow guidance.

Backend: file type validation (allowlist), AttachmentLinker interface
to avoid circular deps, GetReplyCounts batch query, EnrichMessages
method on MessagingService.

Admin CLI: synapbus attachments backup/restore with tar.gz archives,
dedup-safe restore.

24 new test cases across 4 packages. All 24 test packages pass.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-17 16:36:21 +02:00
Algis DumbrisandClaude Opus 4.6 3820414166 fix: push subscribe sends flat key_p256dh/key_auth matching backend API
Release / Build darwin/amd64 (push) Canceled after 0s
Release / Build linux/amd64 (push) Canceled after 0s
Release / Build darwin/arm64 (push) Canceled after 0s
Release / Build linux/arm64 (push) Canceled after 0s
Release / Generate Homebrew Formula (push) Canceled after 0s
Release / GitHub Release (push) Canceled after 0s
Release / Docker Image (push) Canceled after 0s
Release / Publish to MCP Registry (push) Canceled after 0s
The browser PushSubscription nests keys under .keys but the backend
expects flat key_p256dh and key_auth fields.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-17 14:28:35 +02:00
Algis DumbrisandClaude Opus 4.6 09fa765c2e build: rebuild embedded dist with v0.7.1 fixes
Release / Build darwin/amd64 (push) Canceled after 0s
Release / Build linux/amd64 (push) Canceled after 0s
Release / Build darwin/arm64 (push) Canceled after 0s
Release / Build linux/arm64 (push) Canceled after 0s
Release / Generate Homebrew Formula (push) Canceled after 0s
Release / GitHub Release (push) Canceled after 0s
Release / Docker Image (push) Canceled after 0s
Release / Publish to MCP Registry (push) Canceled after 0s
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-17 14:23:31 +02:00
Algis DumbrisandClaude Opus 4.6 71288f64d8 fix: push notification toggle, textarea resize, mobile viewport, card alignment
1. Fix push toggle error: VAPID key field name mismatch (public_key → vapid_public_key)
2. Fix textarea auto-resize: proper height reset, overflow handling, mobile Enter
   inserts newline instead of sending (send via button on mobile)
3. Fix mobile viewport overflow: add overflow-x hidden to html/body, overflow-x
   hidden on content container
4. Fix dashboard cards: always 4 columns with responsive text sizing

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-17 14:23:19 +02:00
Algis DumbrisandClaude Opus 4.6 15e7877ea0 Add MCP Registry auto-publish on release
- Add server.json with registry metadata
- Add mcp-registry job to release workflow using GitHub OIDC auth
- Version in server.json is auto-updated from git tag

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-17 12:36:42 +02:00
73 changed files with 4936 additions and 190 deletions
+26
View File
@@ -8,6 +8,7 @@ on:
permissions:
contents: write
packages: write
id-token: write
env:
GO_VERSION: "1.25"
@@ -217,3 +218,28 @@ jobs:
labels: ${{ steps.meta.outputs.labels }}
cache-from: type=gha
cache-to: type=gha,mode=max
mcp-registry:
name: Publish to MCP Registry
needs: release
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Extract version from tag
id: version
run: echo "VERSION=${GITHUB_REF_NAME#v}" >> "$GITHUB_OUTPUT"
- name: Install mcp-publisher
run: |
curl -L "https://github.com/modelcontextprotocol/registry/releases/latest/download/mcp-publisher_linux_amd64.tar.gz" | tar xz mcp-publisher
- name: Authenticate to MCP Registry
run: ./mcp-publisher login github-oidc
- name: Update version in server.json
run: |
jq --arg v "${{ steps.version.outputs.VERSION }}" '.version = $v' server.json > server.tmp && mv server.tmp server.json
- name: Publish to MCP Registry
run: ./mcp-publisher publish
+3
View File
@@ -103,6 +103,9 @@ make lint # Run linters
- Go 1.25+ (per go.mod) + go-chi/chi (HTTP), mark3labs/mcp-go (MCP), ory/fosite (OAuth), spf13/cobra (CLI), modernc.org/sqlite (storage), TFMV/hnsw (vectors). NEW: coreos/go-oidc/v3 (OIDC), golang.org/x/oauth2 (OAuth client) (007-platform-features-bundle)
- Go 1.25+ (backend), SvelteKit 2 + Svelte 5 (frontend), SvelteKit (website) + go-chi/chi (HTTP), mark3labs/mcp-go (MCP), modernc.org/sqlite (storage), SherClockHolmes/webpush-go (push notifications — NEW) (008-webui-pwa-analytics)
- SQLite (existing DB, 1 new migration for push_subscriptions), localStorage (font size) (008-webui-pwa-analytics)
- Go 1.25+ (backend), Svelte 5 + Tailwind (frontend) + go-chi/chi (HTTP), mark3labs/mcp-go (MCP), modernc.org/sqlite (storage), spf13/cobra (CLI) (009-attachments-threads)
- SQLite (modernc.org/sqlite, pure Go) + content-addressable filesystem (SHA-256) (009-attachments-threads)
- SQLite (modernc.org/sqlite, pure Go) — new migration 013_reactions.sql (010-reactions-workflows)
## Recent Changes
- 002-mcp-auth-ux-polish: Added Go 1.23+ + ory/fosite (OAuth 2.1), mark3labs/mcp-go (MCP server), go-chi/chi (HTTP), Svelte 5 + Tailwind (Web UI)
+84 -45
View File
@@ -1,62 +1,101 @@
# Autonomous Execution Summary: SynapBus v0.7.0
# Autonomous Implementation Summary: Message Reactions & Workflow States
**Date**: 2026-03-17
**Branch**: `008-webui-pwa-analytics`
**Status**: Complete — all tests pass, binary builds, endpoints verified
**Branch**: `010-reactions-workflows`
**Date**: 2026-03-18
**Status**: Complete (StalemateWorker extension deferred)
## Features Implemented
## What Was Built
### 1. Analytics Dashboard (P1)
- 4 new REST endpoints (`/api/analytics/timeline`, `/top-agents`, `/top-channels`, `/summary`)
- SVG bar chart (`AnalyticsChart.svelte`), ranked list (`TopList.svelte`), redesigned dashboard with stat cards and time span selector (1h, 4h, 24h, 7d, 1month)
### Message Reactions
- **Toggle semantics**: Add a reaction → added. Add same reaction again → removed. One per type per agent per message.
- **5 reaction types**: approve, reject, in_progress, done, published
- **Metadata support**: JSON metadata on reactions (e.g., `{"url": "https://..."}` for published)
- **100-reaction limit** per message (safety)
### 2. PWA Conversion (P1)
- PWA manifest (`manifest.json`), service worker (`sw.js`), SVG icon
- Cache-first for static assets, network-only for API, push notification handling
### Workflow State Derivation
- State computed from reactions: published > done > rejected > in_progress > approved > proposed
- No denormalization — state derived on read from reaction list
- Channel messages with no reactions → "proposed" state
- Terminal states (rejected, done, published) don't trigger stalemate checks
### 3. Push Notifications (P1)
- `internal/push/` package — VAPID key generation, Web Push sending, SQLite subscription store
- API: `POST/DELETE /api/push/subscribe`, `GET /api/push/vapid-key`
- Push toggle in Settings, migration `012_push_subscriptions.sql`
### Channel Workflow Settings
- `auto_approve` — skip proposed state for new messages
- `stalemate_remind_after` — duration before reminder DM (default 24h)
- `stalemate_escalate_after` — duration before escalation to #approvals (default 72h)
### 4. Auto-Resizing Textarea (P1)
- ComposeForm textarea auto-grows 3→12 lines, then scrollbar. Resets on send.
### REST API
- `POST /api/messages/{id}/reactions` — toggle reaction (add or remove)
- `GET /api/messages/{id}/reactions` — get reactions + workflow state
- `DELETE /api/messages/{id}/reactions/{reaction}` — remove reaction
- `PUT /api/channels/{name}/settings` — update workflow settings
- `GET /api/channels/{name}/messages/by-state?state=X` — list messages by state
### 5. Smart Mention/Channel Highlighting (P2)
- Entities store caches agents/channels. MessageBody validates @mentions and #channels:
existing → link, deleted → "inactive" badge, unknown → plain text. Handles email/issue number edge cases.
### MCP Tools (via execute bridge)
- `react` — add/toggle reaction on a message
- `unreact` — remove a reaction
- `get_reactions` — query reactions and workflow state
- `list_by_state` — list messages by workflow state in a channel
### 6. Editable Agent Display Name (P2)
- Inline edit on agent detail page (click → edit, Enter → save, Escape → cancel)
### Web UI
- **WorkflowBadge** component: colored pills (yellow/green/blue/red/gray/cyan) per state
- **ReactionPills** component: grouped reaction pills with count, agent names on hover, click-to-toggle
- Published reactions with URL show clickable link icon
- Integrated into channel message view
### 7. Editable Human Display Name (P2)
- `PUT /api/auth/profile` endpoint, `UpdateDisplayName` in UserStore, Settings page field
### Admin CLI
- `synapbus channels update --name X --auto-approve=true --stalemate-remind-after=12h --stalemate-escalate-after=48h`
### 8. Font Size Preference (P3)
- fontSize store (12–24px, 2px steps), -/+ controls in Settings, persisted in localStorage
## Files Created/Modified
### 9. Version Display (P3)
- `GET /api/version` endpoint, version footer in layout linked to GitHub repo
### New Files
| File | Description |
|------|-------------|
| `internal/storage/schema/013_reactions.sql` | Migration: message_reactions table + channel columns |
| `internal/reactions/model.go` | Reaction types, state derivation, constants |
| `internal/reactions/store.go` | SQLite CRUD for reactions |
| `internal/reactions/service.go` | Business logic: toggle, remove, get, list by state |
| `internal/reactions/model_test.go` | 23 test cases for model functions |
| `internal/reactions/store_test.go` | 6 test functions for store operations |
| `internal/api/reactions_handler.go` | REST API handlers for reactions |
| `web/src/lib/components/WorkflowBadge.svelte` | Colored state badge component |
| `web/src/lib/components/ReactionPills.svelte` | Reaction toggle pills component |
### 10. MCP Prompts (P2)
- 4 prompts: daily-digest, agent-health-check, channel-overview, debug-agent
- `internal/mcp/prompts.go` registered in server.go
### 11. Website Update (P3)
- Updated hero/features messaging at ~/repos/synapbus-website/ for individual/small-team positioning
### Modified Files
| File | Changes |
|------|---------|
| `internal/messaging/types.go` | Added WorkflowState, Reactions, ReactionInfo to Message |
| `internal/messaging/service.go` | Added ReactionEnricher interface, enrichment in EnrichMessages |
| `internal/channels/types.go` | Added AutoApprove, StalemateRemindAfter, StalemateEscalateAfter, ChannelSettings |
| `internal/channels/store.go` | Updated SELECT queries for new columns, added UpdateChannelSettings |
| `internal/channels/service.go` | Added UpdateChannelSettings method |
| `internal/api/router.go` | Registered reaction and channel settings routes |
| `internal/api/channels_handler.go` | Added UpdateSettings, ListByState handlers |
| `internal/mcp/bridge.go` | Added react/unreact/get_reactions/list_by_state bridge methods |
| `internal/mcp/tools_hybrid.go` | Added reactionService to registrar |
| `internal/mcp/server.go` | Added reactionService parameter |
| `internal/actions/registry.go` | Registered 4 new reaction actions |
| `cmd/synapbus/main.go` | Wired reaction service, adapter, passed to router+MCP |
| `cmd/synapbus/admin.go` | Added channels update CLI command |
| `internal/admin/socket.go` | Added channels.update_settings handler |
| `web/src/lib/api/client.ts` | Added reactions.toggle/get methods |
| `web/src/routes/channels/[name]/+page.svelte` | Integrated WorkflowBadge + ReactionPills |
## Test Results
All 24 Go packages PASS. All API endpoints verified via curl. Web UI builds successfully. Binary compiles with CGO_ENABLED=0.
- **25 Go test packages**: all pass, 0 failures
- **New tests**: 29+ test cases (model: 23, store: 6)
- **Integration tests**: 9 E2E tests pass
- **Web build**: Svelte SPA builds successfully
- **Binary build**: Compiles cleanly
## New Files
## Deferred
- `internal/api/analytics_handler.go` + test
- `internal/api/version_handler.go` + test
- `internal/api/push_handler.go`
- `internal/push/service.go` + test, `store.go` + test
- `internal/mcp/prompts.go` + test
- `schema/012_push_subscriptions.sql`
- `web/src/lib/components/AnalyticsChart.svelte`, `TopList.svelte`
- `web/src/lib/stores/fontSize.ts`, `entities.ts`
- `web/static/manifest.json`, `sw.js`, `icons/icon.svg`
- **StalemateWorker extension** (T023-T025): The data model, channel settings, and query infrastructure are in place. The worker just needs a scan loop added to detect stale messages and send DMs/escalations. This is a straightforward follow-up task.
## Architecture Decisions
1. **Separate reactions package**: Clean domain separation from messaging
2. **Toggle semantics**: INSERT if absent, DELETE if present — simple, atomic, idempotent
3. **Derived workflow state**: No denormalization; state computed from reactions on read
4. **Bridge actions (not hybrid tools)**: Consistent with attachments pattern — 4 hybrid tools are stable surface area
5. **ReactionEnricher adapter**: Avoids circular dependency between reactions and messaging packages
+229 -2
View File
@@ -1,11 +1,15 @@
package main
import (
"archive/tar"
"bufio"
"compress/gzip"
"encoding/json"
"fmt"
"io"
"net"
"os"
"path/filepath"
"strings"
"text/tabwriter"
@@ -632,7 +636,46 @@ func addAdminCommands(rootCmd *cobra.Command) {
channelsJoinCmd.MarkFlagRequired("channel")
channelsJoinCmd.MarkFlagRequired("agent")
channelsCmd.AddCommand(channelsListCmd, channelsShowCmd, channelsCreateCmd, channelsJoinCmd)
var (
channelsUpdateName string
channelsUpdateAutoApprove string
channelsUpdateStalemateRemind string
channelsUpdateStalemateEscalate string
)
channelsUpdateCmd := &cobra.Command{
Use: "update",
Short: "Update channel settings (auto-approve, stalemate timers)",
RunE: func(cmd *cobra.Command, args []string) error {
if channelsUpdateName == "" {
return fmt.Errorf("--name is required")
}
reqArgs := map[string]interface{}{
"name": channelsUpdateName,
}
if cmd.Flags().Changed("auto-approve") {
reqArgs["auto_approve"] = channelsUpdateAutoApprove == "true"
}
if cmd.Flags().Changed("stalemate-remind-after") {
reqArgs["stalemate_remind_after"] = channelsUpdateStalemateRemind
}
if cmd.Flags().Changed("stalemate-escalate-after") {
reqArgs["stalemate_escalate_after"] = channelsUpdateStalemateEscalate
}
resp, err := adminRequest("channels.update_settings", reqArgs)
if err != nil {
return err
}
printJSON(resp["data"])
return nil
},
}
channelsUpdateCmd.Flags().StringVar(&channelsUpdateName, "name", "", "Channel name")
channelsUpdateCmd.Flags().StringVar(&channelsUpdateAutoApprove, "auto-approve", "", "Auto-approve messages (true|false)")
channelsUpdateCmd.Flags().StringVar(&channelsUpdateStalemateRemind, "stalemate-remind-after", "", "Stalemate reminder duration (e.g. 24h)")
channelsUpdateCmd.Flags().StringVar(&channelsUpdateStalemateEscalate, "stalemate-escalate-after", "", "Stalemate escalation duration (e.g. 72h)")
channelsUpdateCmd.MarkFlagRequired("name")
channelsCmd.AddCommand(channelsListCmd, channelsShowCmd, channelsCreateCmd, channelsJoinCmd, channelsUpdateCmd)
// ----- conversations commands -----
conversationsCmd := &cobra.Command{
@@ -987,7 +1030,48 @@ func addAdminCommands(rootCmd *cobra.Command) {
},
}
attachmentsCmd.AddCommand(attachmentsGCCmd)
var attachmentsBackupOutput string
var attachmentsBackupDataDir string
attachmentsBackupCmd := &cobra.Command{
Use: "backup",
Short: "Create a tar.gz backup of all attachments (no server required)",
RunE: func(cmd *cobra.Command, args []string) error {
attachDir := filepath.Join(attachmentsBackupDataDir, "attachments")
if _, err := os.Stat(attachDir); os.IsNotExist(err) {
return fmt.Errorf("attachments directory does not exist: %s", attachDir)
}
fileCount, totalSize, err := backupAttachments(attachDir, attachmentsBackupOutput)
if err != nil {
return fmt.Errorf("backup failed: %w", err)
}
fmt.Printf("Backup complete: %d files, %s total, written to %s\n", fileCount, formatBytes(totalSize), attachmentsBackupOutput)
return nil
},
}
attachmentsBackupCmd.Flags().StringVar(&attachmentsBackupOutput, "output", "", "Output path for the tar.gz archive")
attachmentsBackupCmd.Flags().StringVar(&attachmentsBackupDataDir, "data", "./data", "Data directory")
attachmentsBackupCmd.MarkFlagRequired("output")
var attachmentsRestoreInput string
var attachmentsRestoreDataDir string
attachmentsRestoreCmd := &cobra.Command{
Use: "restore",
Short: "Restore attachments from a tar.gz backup (no server required)",
RunE: func(cmd *cobra.Command, args []string) error {
attachDir := filepath.Join(attachmentsRestoreDataDir, "attachments")
restored, skipped, err := restoreAttachments(attachDir, attachmentsRestoreInput)
if err != nil {
return fmt.Errorf("restore failed: %w", err)
}
fmt.Printf("Restore complete: %d files restored, %d files skipped (already exist)\n", restored, skipped)
return nil
},
}
attachmentsRestoreCmd.Flags().StringVar(&attachmentsRestoreInput, "input", "", "Input path for the tar.gz archive")
attachmentsRestoreCmd.Flags().StringVar(&attachmentsRestoreDataDir, "data", "./data", "Data directory")
attachmentsRestoreCmd.MarkFlagRequired("input")
attachmentsCmd.AddCommand(attachmentsGCCmd, attachmentsBackupCmd, attachmentsRestoreCmd)
// ----- add persistent flag and commands to root -----
rootCmd.PersistentFlags().StringVar(&adminSocket, "socket", "/tmp/synapbus.sock", "Path to admin Unix socket")
@@ -1012,3 +1096,146 @@ func toTableRows(data []map[string]string, headerMap map[string]string) []map[st
}
return rows
}
// backupAttachments creates a tar.gz archive of the attachments directory.
// Returns the number of files archived and total bytes of file content.
func backupAttachments(attachmentsDir, outputPath string) (int, int64, error) {
outFile, err := os.Create(outputPath)
if err != nil {
return 0, 0, fmt.Errorf("create output file: %w", err)
}
defer outFile.Close()
gzw := gzip.NewWriter(outFile)
defer gzw.Close()
tw := tar.NewWriter(gzw)
defer tw.Close()
var fileCount int
var totalSize int64
err = filepath.Walk(attachmentsDir, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
// Skip directories — tar entries for files include the path.
if info.IsDir() {
return nil
}
relPath, err := filepath.Rel(attachmentsDir, path)
if err != nil {
return fmt.Errorf("relative path: %w", err)
}
header, err := tar.FileInfoHeader(info, "")
if err != nil {
return fmt.Errorf("file info header: %w", err)
}
header.Name = relPath
if err := tw.WriteHeader(header); err != nil {
return fmt.Errorf("write header: %w", err)
}
f, err := os.Open(path)
if err != nil {
return fmt.Errorf("open file: %w", err)
}
defer f.Close()
if _, err := io.Copy(tw, f); err != nil {
return fmt.Errorf("copy file: %w", err)
}
fileCount++
totalSize += info.Size()
return nil
})
return fileCount, totalSize, err
}
// restoreAttachments extracts a tar.gz archive into the attachments directory.
// Files that already exist on disk are skipped. Returns (restored, skipped) counts.
func restoreAttachments(attachmentsDir, inputPath string) (int, int, error) {
inFile, err := os.Open(inputPath)
if err != nil {
return 0, 0, fmt.Errorf("open input file: %w", err)
}
defer inFile.Close()
gzr, err := gzip.NewReader(inFile)
if err != nil {
return 0, 0, fmt.Errorf("gzip reader: %w", err)
}
defer gzr.Close()
tr := tar.NewReader(gzr)
var restored, skipped int
for {
header, err := tr.Next()
if err == io.EOF {
break
}
if err != nil {
return restored, skipped, fmt.Errorf("read tar entry: %w", err)
}
// Only handle regular files.
if header.Typeflag != tar.TypeReg {
continue
}
// Sanitize: reject absolute paths and path traversal.
cleanName := filepath.Clean(header.Name)
if filepath.IsAbs(cleanName) || strings.HasPrefix(cleanName, "..") {
return restored, skipped, fmt.Errorf("invalid path in archive: %s", header.Name)
}
destPath := filepath.Join(attachmentsDir, cleanName)
// Skip if already exists (content-addressable, so same hash = same content).
if _, err := os.Stat(destPath); err == nil {
skipped++
continue
}
// Ensure parent directory exists.
if err := os.MkdirAll(filepath.Dir(destPath), 0o755); err != nil {
return restored, skipped, fmt.Errorf("create directory: %w", err)
}
outFile, err := os.Create(destPath)
if err != nil {
return restored, skipped, fmt.Errorf("create file: %w", err)
}
if _, err := io.Copy(outFile, tr); err != nil {
outFile.Close()
return restored, skipped, fmt.Errorf("write file: %w", err)
}
outFile.Close()
restored++
}
return restored, skipped, nil
}
// formatBytes returns a human-readable byte count string.
func formatBytes(b int64) string {
const unit = 1024
if b < unit {
return fmt.Sprintf("%d B", b)
}
div, exp := int64(unit), 0
for n := b / unit; n >= unit; n /= unit {
div *= unit
exp++
}
return fmt.Sprintf("%.1f %ciB", float64(b)/float64(div), "KMGTPE"[exp])
}
+63 -1
View File
@@ -41,6 +41,7 @@ import (
mcpserver "github.com/synapbus/synapbus/internal/mcp"
"github.com/synapbus/synapbus/internal/messaging"
prommetrics "github.com/synapbus/synapbus/internal/metrics"
"github.com/synapbus/synapbus/internal/reactions"
"github.com/synapbus/synapbus/internal/search"
"github.com/synapbus/synapbus/internal/search/embedding"
"github.com/synapbus/synapbus/internal/storage"
@@ -281,8 +282,15 @@ func runServe(cmd *cobra.Command, args []string) error {
}
attachmentStore := attachments.NewSQLiteStore(db.DB, slog.Default())
attachmentService := attachments.NewService(attachmentStore, cas, slog.Default())
msgService.SetAttachmentLinker(&attachmentLinkerAdapter{svc: attachmentService})
slog.Info("attachment service initialized", "dir", attachmentsDir)
// Create reaction service
reactionStore := reactions.NewSQLiteStore(db.DB)
reactionService := reactions.NewService(reactionStore, slog.Default())
msgService.SetReactionEnricher(&reactionEnricherAdapter{svc: reactionService})
slog.Info("reaction service initialized")
// Initialize auth subsystem
authSecret := make([]byte, 32)
if _, err := rand.Read(authSecret); err != nil {
@@ -465,7 +473,7 @@ func runServe(cmd *cobra.Command, args []string) error {
actionIndex := actions.NewIndex(actionRegistry.List())
// Create MCP server (4 hybrid tools: my_status, send_message, search, execute)
mcpSrv := mcpserver.NewMCPServer(msgService, agentService, channelService, swarmService, attachmentService, searchService, con, jsPool, actionRegistry, actionIndex, db.DB)
mcpSrv := mcpserver.NewMCPServer(msgService, agentService, channelService, swarmService, attachmentService, searchService, reactionService, con, jsPool, actionRegistry, actionIndex, db.DB)
startTime := time.Now()
// Start task expiry worker
@@ -619,6 +627,7 @@ func runServe(cmd *cobra.Command, args []string) error {
ChannelService: channelService,
APIKeyService: apiKeyService,
DeadLetterStore: deadLetterStore,
ReactionService: reactionService,
SSEHub: sseHub,
Broadcaster: sseBroadcaster,
SessionMiddleware: sessionMiddleware,
@@ -836,6 +845,59 @@ func (a *a2aAgentListerAdapter) ListAllActiveAgents(ctx context.Context) ([]a2a.
return result, nil
}
// attachmentLinkerAdapter adapts attachments.Service to messaging.AttachmentLinker.
type attachmentLinkerAdapter struct {
svc *attachments.Service
}
func (a *attachmentLinkerAdapter) AttachToMessage(ctx context.Context, hash string, messageID int64) error {
return a.svc.AttachToMessage(ctx, hash, messageID)
}
func (a *attachmentLinkerAdapter) GetByMessageID(ctx context.Context, messageID int64) ([]messaging.AttachmentInfo, error) {
atts, err := a.svc.GetByMessageID(ctx, messageID)
if err != nil {
return nil, err
}
results := make([]messaging.AttachmentInfo, len(atts))
for i, att := range atts {
results[i] = messaging.AttachmentInfo{
Hash: att.Hash,
OriginalFilename: att.OriginalFilename,
Size: att.Size,
MIMEType: att.MIMEType,
IsImage: attachments.IsImageType(att.MIMEType),
}
}
return results, nil
}
// reactionEnricherAdapter adapts reactions.Service to messaging.ReactionEnricher.
type reactionEnricherAdapter struct {
svc *reactions.Service
}
func (a *reactionEnricherAdapter) GetByMessageIDs(ctx context.Context, messageIDs []int64) (map[int64][]messaging.ReactionInfo, error) {
rxMap, err := a.svc.GetReactionsByMessageIDs(ctx, messageIDs)
if err != nil {
return nil, err
}
result := make(map[int64][]messaging.ReactionInfo, len(rxMap))
for msgID, rxs := range rxMap {
infos := make([]messaging.ReactionInfo, len(rxs))
for i, rx := range rxs {
infos[i] = messaging.ReactionInfo{
AgentName: rx.AgentName,
Reaction: rx.Reaction,
Metadata: rx.Metadata,
CreatedAt: rx.CreatedAt,
}
}
result[msgID] = infos
}
return result, nil
}
// agentListerAdapter adapts agents.AgentService to auth.AgentLister.
type agentListerAdapter struct {
agentService *agents.AgentService
+74 -4
View File
@@ -6,10 +6,10 @@ type Registry struct {
ordered []Action // maintains insertion order
}
// NewRegistry creates a registry pre-populated with all 23 agent-callable actions.
// NewRegistry creates a registry pre-populated with all 27 agent-callable actions.
func NewRegistry() *Registry {
r := &Registry{
actions: make(map[string]Action, 23),
actions: make(map[string]Action, 27),
}
for _, a := range allActions() {
r.actions[a.Name] = a
@@ -42,7 +42,7 @@ func (r *Registry) ListByCategory(category string) []Action {
return out
}
// allActions returns the canonical list of all 23 agent-callable actions.
// allActions returns the canonical list of all 27 agent-callable actions.
func allActions() []Action {
return []Action{
// ── Messaging (7 actions) ──────────────────────────────────────
@@ -425,7 +425,7 @@ func allActions() []Action {
{
Name: "upload_attachment",
Category: "attachments",
Description: "Upload a file attachment. Content must be base64-encoded. Returns the SHA-256 hash for later retrieval. Max file size: 50MB.",
Description: "Upload a file attachment. Content must be base64-encoded. Returns the SHA-256 hash for later retrieval. Upload first, then use the returned hash in send_message's attachments parameter to link it to a message. Max file size: 50MB.",
Params: []Param{
{Name: "content", Type: "string", Description: "Base64-encoded file content", Required: true},
{Name: "filename", Type: "string", Description: "Original filename (optional, used for MIME detection and display)"},
@@ -455,5 +455,75 @@ func allActions() []Action {
},
},
},
// ── Reactions (4 actions) ────────────────────────────────────
{
Name: "react",
Category: "reactions",
Description: "Add or toggle a reaction on a message. Valid reactions: approve, reject, in_progress, done, published. Adding the same reaction again removes it (toggle).",
Params: []Param{
{Name: "message_id", Type: "number", Description: "ID of the message to react to", Required: true},
{Name: "reaction", Type: "string", Description: "Reaction type: approve, reject, in_progress, done, published", Required: true},
{Name: "metadata", Type: "string", Description: "JSON metadata object (optional)"},
},
Returns: "JSON with action ('added' or 'removed') and reaction details",
Examples: []Example{
{
Description: "Approve a message",
Code: `call("react", {"message_id": 42, "reaction": "approve"})`,
},
{
Description: "Toggle a reaction off (call same reaction again)",
Code: `call("react", {"message_id": 42, "reaction": "approve"})`,
},
},
},
{
Name: "unreact",
Category: "reactions",
Description: "Remove a specific reaction from a message.",
Params: []Param{
{Name: "message_id", Type: "number", Description: "ID of the message to remove reaction from", Required: true},
{Name: "reaction", Type: "string", Description: "Reaction type to remove: approve, reject, in_progress, done, published", Required: true},
},
Returns: "JSON with message_id, reaction, and status 'removed'",
Examples: []Example{
{
Description: "Remove an approval reaction",
Code: `call("unreact", {"message_id": 42, "reaction": "approve"})`,
},
},
},
{
Name: "get_reactions",
Category: "reactions",
Description: "Get all reactions on a message and its derived workflow state.",
Params: []Param{
{Name: "message_id", Type: "number", Description: "ID of the message to get reactions for", Required: true},
},
Returns: "JSON with reactions array and workflow_state",
Examples: []Example{
{
Description: "Get reactions and workflow state for a message",
Code: `call("get_reactions", {"message_id": 42})`,
},
},
},
{
Name: "list_by_state",
Category: "reactions",
Description: "List messages in a channel filtered by workflow state. Valid states: proposed, approved, in_progress, rejected, done, published.",
Params: []Param{
{Name: "channel", Type: "string", Description: "Channel name", Required: true},
{Name: "state", Type: "string", Description: "Workflow state to filter by: proposed, approved, in_progress, rejected, done, published", Required: true},
},
Returns: "JSON with message_ids array and count",
Examples: []Example{
{
Description: "List approved messages in a channel",
Code: `call("list_by_state", {"channel": "approvals", "state": "approved"})`,
},
},
},
}
}
+6 -3
View File
@@ -4,11 +4,11 @@ import (
"testing"
)
func TestRegistryHas23Actions(t *testing.T) {
func TestRegistryHas27Actions(t *testing.T) {
r := NewRegistry()
got := len(r.List())
if got != 23 {
t.Errorf("expected 23 actions, got %d", got)
if got != 27 {
t.Errorf("expected 27 actions, got %d", got)
}
}
@@ -23,6 +23,7 @@ func TestRegistryCategories(t *testing.T) {
{"channels", 9},
{"swarm", 5},
{"attachments", 2},
{"reactions", 4},
}
for _, tt := range tests {
@@ -49,6 +50,8 @@ func TestRegistryGetByName(t *testing.T) {
"post_task", "bid_task", "accept_bid", "complete_task", "list_tasks",
// attachments
"upload_attachment", "download_attachment",
// reactions
"react", "unreact", "get_reactions", "list_by_state",
}
for _, name := range allNames {
+60
View File
@@ -169,6 +169,8 @@ func (s *AdminServer) dispatch(req Request) Response {
return s.handleChannelsCreate(ctx, req.Args)
case "channels.join":
return s.handleChannelsJoin(ctx, req.Args)
case "channels.update_settings":
return s.handleChannelsUpdateSettings(ctx, req.Args)
// --- conversations ---
case "conversations.list":
@@ -995,6 +997,64 @@ func (s *AdminServer) handleChannelsJoin(ctx context.Context, args json.RawMessa
}}
}
func (s *AdminServer) handleChannelsUpdateSettings(ctx context.Context, args json.RawMessage) Response {
var p struct {
Name string `json:"name"`
AutoApprove *bool `json:"auto_approve,omitempty"`
StalemateRemindAfter string `json:"stalemate_remind_after,omitempty"`
StalemateEscalateAfter string `json:"stalemate_escalate_after,omitempty"`
}
if err := json.Unmarshal(args, &p); err != nil {
return Response{OK: false, Error: "invalid args: " + err.Error()}
}
if p.Name == "" {
return Response{OK: false, Error: "name is required"}
}
// Build the SET clause dynamically based on provided fields
var setClauses []string
var setArgs []interface{}
if p.AutoApprove != nil {
autoApproveVal := 0
if *p.AutoApprove {
autoApproveVal = 1
}
setClauses = append(setClauses, "auto_approve = ?")
setArgs = append(setArgs, autoApproveVal)
}
if p.StalemateRemindAfter != "" {
setClauses = append(setClauses, "stalemate_remind_after = ?")
setArgs = append(setArgs, p.StalemateRemindAfter)
}
if p.StalemateEscalateAfter != "" {
setClauses = append(setClauses, "stalemate_escalate_after = ?")
setArgs = append(setArgs, p.StalemateEscalateAfter)
}
if len(setClauses) == 0 {
return Response{OK: false, Error: "at least one setting must be provided (auto_approve, stalemate_remind_after, stalemate_escalate_after)"}
}
query := fmt.Sprintf("UPDATE channels SET %s WHERE LOWER(name) = LOWER(?)", strings.Join(setClauses, ", "))
setArgs = append(setArgs, p.Name)
result, err := s.db.ExecContext(ctx, query, setArgs...)
if err != nil {
return Response{OK: false, Error: "update channel settings: " + err.Error()}
}
rowsAffected, _ := result.RowsAffected()
if rowsAffected == 0 {
return Response{OK: false, Error: fmt.Sprintf("channel not found: %s", p.Name)}
}
return Response{OK: true, Data: map[string]interface{}{
"channel": p.Name,
"updated": true,
}}
}
// ---------- conversations handlers ----------
func (s *AdminServer) handleConversationsList(ctx context.Context, args json.RawMessage) Response {
+2
View File
@@ -137,6 +137,8 @@ func (h *AttachmentsHandler) Upload(w http.ResponseWriter, r *http.Request) {
http.Error(w, `{"error":"empty file not allowed"}`, http.StatusBadRequest)
case attachments.ErrFileTooLarge:
http.Error(w, `{"error":"file exceeds maximum size of 50MB"}`, http.StatusRequestEntityTooLarge)
case attachments.ErrUnsupportedType:
http.Error(w, `{"error":"unsupported file type: only images, PDFs, and text files are allowed"}`, http.StatusBadRequest)
default:
h.logger.Error("upload attachment failed", "error", err)
http.Error(w, `{"error":"internal server error"}`, http.StatusInternalServerError)
+128 -4
View File
@@ -1,6 +1,7 @@
package api
import (
"context"
"encoding/json"
"log/slog"
"net/http"
@@ -15,10 +16,16 @@ import (
// ChannelsHandler handles REST API requests for channels.
type ChannelsHandler struct {
channelService *channels.Service
agentService *agents.AgentService
msgService *messaging.MessagingService
logger *slog.Logger
channelService *channels.Service
agentService *agents.AgentService
msgService *messaging.MessagingService
reactionService ChannelReactionService
logger *slog.Logger
}
// ChannelReactionService is the subset of reactions.Service needed by ChannelsHandler.
type ChannelReactionService interface {
ListByState(ctx context.Context, channelID int64, state string) ([]int64, error)
}
// NewChannelsHandler creates a new channels handler.
@@ -31,6 +38,11 @@ func NewChannelsHandler(channelService *channels.Service, agentService *agents.A
}
}
// SetReactionService sets the reaction service for workflow state queries.
func (h *ChannelsHandler) SetReactionService(svc ChannelReactionService) {
h.reactionService = svc
}
// ListChannels handles GET /api/channels.
func (h *ChannelsHandler) ListChannels(w http.ResponseWriter, r *http.Request) {
ownerID, ok := OwnerIDFromContext(r.Context())
@@ -228,6 +240,9 @@ func (h *ChannelsHandler) ChannelMessages(w http.ResponseWriter, r *http.Request
return
}
// Enrich messages with reply counts and attachments.
h.msgService.EnrichMessages(r.Context(), paginated.Messages)
// Compute last_read_message_id across owned agents
var lastReadMessageID int64
ownedAgents, err := h.agentService.ListAgents(r.Context(), ownerID)
@@ -295,3 +310,112 @@ func (h *ChannelsHandler) LeaveChannel(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]string{"status": "left"})
}
// UpdateSettings handles PUT /api/channels/{name}/settings.
func (h *ChannelsHandler) UpdateSettings(w http.ResponseWriter, r *http.Request) {
_, ok := OwnerIDFromContext(r.Context())
if !ok {
writeJSON(w, http.StatusUnauthorized, errorBody("unauthorized", "Authentication required"))
return
}
name := chi.URLParam(r, "name")
ch, err := h.channelService.GetChannelByName(r.Context(), name)
if err != nil {
writeJSON(w, http.StatusNotFound, errorBody("not_found", "Channel not found"))
return
}
var req struct {
AutoApprove *bool `json:"auto_approve"`
StalemateRemindAfter *string `json:"stalemate_remind_after"`
StalemateEscalateAfter *string `json:"stalemate_escalate_after"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeJSON(w, http.StatusBadRequest, errorBody("invalid_request", "Invalid JSON body"))
return
}
settings := channels.ChannelSettings{
AutoApprove: ch.AutoApprove,
StalemateRemindAfter: ch.StalemateRemindAfter,
StalemateEscalateAfter: ch.StalemateEscalateAfter,
}
if req.AutoApprove != nil {
settings.AutoApprove = *req.AutoApprove
}
if req.StalemateRemindAfter != nil {
settings.StalemateRemindAfter = *req.StalemateRemindAfter
}
if req.StalemateEscalateAfter != nil {
settings.StalemateEscalateAfter = *req.StalemateEscalateAfter
}
updated, err := h.channelService.UpdateChannelSettings(r.Context(), ch.ID, settings)
if err != nil {
h.logger.Error("update channel settings failed", "error", err)
writeJSON(w, http.StatusInternalServerError, errorBody("server_error", "Failed to update channel settings"))
return
}
writeJSON(w, http.StatusOK, map[string]any{"channel": updated})
}
// ListByState handles GET /api/channels/{name}/messages/by-state?state=X.
func (h *ChannelsHandler) ListByState(w http.ResponseWriter, r *http.Request) {
_, ok := OwnerIDFromContext(r.Context())
if !ok {
writeJSON(w, http.StatusUnauthorized, errorBody("unauthorized", "Authentication required"))
return
}
if h.reactionService == nil {
writeJSON(w, http.StatusServiceUnavailable, errorBody("unavailable", "Reactions service not configured"))
return
}
name := chi.URLParam(r, "name")
ch, err := h.channelService.GetChannelByName(r.Context(), name)
if err != nil {
writeJSON(w, http.StatusNotFound, errorBody("not_found", "Channel not found"))
return
}
state := r.URL.Query().Get("state")
if state == "" {
writeJSON(w, http.StatusBadRequest, errorBody("missing_state", "Query parameter 'state' is required"))
return
}
ids, err := h.reactionService.ListByState(r.Context(), ch.ID, state)
if err != nil {
h.logger.Error("list by state failed", "error", err)
writeJSON(w, http.StatusBadRequest, errorBody("invalid_state", err.Error()))
return
}
// Load messages by IDs
var messages []*messaging.Message
for _, id := range ids {
msg, err := h.msgService.GetMessageByID(r.Context(), id)
if err != nil {
continue
}
messages = append(messages, msg)
}
if messages == nil {
messages = []*messaging.Message{}
}
// Enrich messages with reactions, reply counts, attachments
h.msgService.EnrichMessages(r.Context(), messages)
writeJSON(w, http.StatusOK, map[string]any{
"messages": messages,
"state": state,
"total": len(messages),
})
}
+24 -8
View File
@@ -86,6 +86,8 @@ func (h *MessagesHandler) ListMessages(w http.ResponseWriter, r *http.Request) {
allMessages = []*messaging.Message{}
}
h.msgService.EnrichMessages(r.Context(), allMessages)
sortMessagesByTime(allMessages)
if len(allMessages) > limit {
allMessages = allMessages[:limit]
@@ -122,6 +124,8 @@ func (h *MessagesHandler) GetMessage(w http.ResponseWriter, r *http.Request) {
return
}
h.msgService.EnrichMessages(r.Context(), []*messaging.Message{msg})
writeJSON(w, http.StatusOK, msg)
}
@@ -230,6 +234,8 @@ func (h *MessagesHandler) GetConversation(w http.ResponseWriter, r *http.Request
return
}
h.msgService.EnrichMessages(r.Context(), messages)
writeJSON(w, http.StatusOK, map[string]any{
"conversation": conv,
"messages": messages,
@@ -245,14 +251,15 @@ func (h *MessagesHandler) SendMessage(w http.ResponseWriter, r *http.Request) {
}
var req struct {
From string `json:"from"`
To string `json:"to"`
Body string `json:"body"`
Priority int `json:"priority"`
ChannelID *int64 `json:"channel_id,omitempty"`
ConversationID *int64 `json:"conversation_id,omitempty"`
Subject string `json:"subject,omitempty"`
ReplyTo *int64 `json:"reply_to,omitempty"`
From string `json:"from"`
To string `json:"to"`
Body string `json:"body"`
Priority int `json:"priority"`
ChannelID *int64 `json:"channel_id,omitempty"`
ConversationID *int64 `json:"conversation_id,omitempty"`
Subject string `json:"subject,omitempty"`
ReplyTo *int64 `json:"reply_to,omitempty"`
Attachments []string `json:"attachments,omitempty"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
@@ -307,6 +314,7 @@ func (h *MessagesHandler) SendMessage(w http.ResponseWriter, r *http.Request) {
ConversationID: req.ConversationID,
Subject: req.Subject,
ReplyTo: req.ReplyTo,
Attachments: req.Attachments,
}
msg, err := h.msgService.SendMessage(r.Context(), req.From, req.To, req.Body, opts)
@@ -319,6 +327,8 @@ func (h *MessagesHandler) SendMessage(w http.ResponseWriter, r *http.Request) {
// SSE broadcast is handled by the MessageListener on the messaging
// service, so it fires for both REST and MCP message paths.
h.msgService.EnrichMessages(r.Context(), []*messaging.Message{msg})
writeJSON(w, http.StatusCreated, msg)
}
@@ -465,6 +475,8 @@ func (h *MessagesHandler) SearchMessages(w http.ResponseWriter, r *http.Request)
allMessages = []*messaging.Message{}
}
h.msgService.EnrichMessages(r.Context(), allMessages)
writeJSON(w, http.StatusOK, map[string]any{
"messages": allMessages,
"query": query,
@@ -505,6 +517,8 @@ func (h *MessagesHandler) GetReplies(w http.ResponseWriter, r *http.Request) {
return
}
h.msgService.EnrichMessages(r.Context(), replies)
writeJSON(w, http.StatusOK, map[string]any{
"replies": replies,
"total": len(replies),
@@ -550,6 +564,8 @@ func (h *MessagesHandler) DMMessages(w http.ResponseWriter, r *http.Request) {
return
}
h.msgService.EnrichMessages(r.Context(), msgs)
// Include last_read_message_id for the human agent's DM with the peer
lastRead, _ := h.msgService.GetLastReadForDM(r.Context(), agentNames, peerAgent)
+1 -1
View File
@@ -333,7 +333,7 @@ func TestChannelMessages_IncludesLastRead(t *testing.T) {
}
// Broadcast messages
msgs, err := channelService.BroadcastMessage(ctx, ch.ID, "human-agent", "Hello channel", 5, "", nil)
msgs, err := channelService.BroadcastMessage(ctx, ch.ID, "human-agent", "Hello channel", 5, "", nil, nil)
if err != nil {
t.Fatalf("broadcast: %v", err)
}
+233
View File
@@ -0,0 +1,233 @@
package api
import (
"encoding/json"
"fmt"
"log/slog"
"net/http"
"strconv"
"github.com/go-chi/chi/v5"
"github.com/synapbus/synapbus/internal/agents"
"github.com/synapbus/synapbus/internal/auth"
"github.com/synapbus/synapbus/internal/messaging"
"github.com/synapbus/synapbus/internal/reactions"
)
// ReactionsHandler handles REST API requests for message reactions.
type ReactionsHandler struct {
reactionService *reactions.Service
msgService *messaging.MessagingService
agentService *agents.AgentService
logger *slog.Logger
}
// NewReactionsHandler creates a new reactions handler.
func NewReactionsHandler(reactionService *reactions.Service, msgService *messaging.MessagingService, agentService *agents.AgentService) *ReactionsHandler {
return &ReactionsHandler{
reactionService: reactionService,
msgService: msgService,
agentService: agentService,
logger: slog.Default().With("component", "api.reactions"),
}
}
// Toggle handles POST /api/messages/{id}/reactions.
func (h *ReactionsHandler) Toggle(w http.ResponseWriter, r *http.Request) {
ownerID, ok := OwnerIDFromContext(r.Context())
if !ok {
writeJSON(w, http.StatusUnauthorized, errorBody("unauthorized", "Authentication required"))
return
}
id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
if err != nil {
writeJSON(w, http.StatusBadRequest, errorBody("invalid_id", "Invalid message ID"))
return
}
var req struct {
Reaction string `json:"reaction"`
Metadata json.RawMessage `json:"metadata,omitempty"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeJSON(w, http.StatusBadRequest, errorBody("invalid_request", "Invalid JSON body"))
return
}
if req.Reaction == "" {
writeJSON(w, http.StatusBadRequest, errorBody("validation_error", "Reaction type is required"))
return
}
// Verify the message exists
msg, err := h.msgService.GetMessageByID(r.Context(), id)
if err != nil {
writeJSON(w, http.StatusNotFound, errorBody("not_found", "Message not found"))
return
}
// Determine the acting agent name from the session
agentName, err := h.resolveAgentName(r, ownerID, msg)
if err != nil {
h.logger.Error("resolve agent name failed", "error", err)
writeJSON(w, http.StatusBadRequest, errorBody("no_agent", err.Error()))
return
}
result, err := h.reactionService.Toggle(r.Context(), id, agentName, req.Reaction, req.Metadata)
if err != nil {
if err == reactions.ErrInvalidReaction {
writeJSON(w, http.StatusBadRequest, errorBody("invalid_reaction", err.Error()))
return
}
if err == reactions.ErrReactionLimit {
writeJSON(w, http.StatusBadRequest, errorBody("reaction_limit", err.Error()))
return
}
h.logger.Error("toggle reaction failed", "error", err)
writeJSON(w, http.StatusInternalServerError, errorBody("server_error", "Failed to toggle reaction"))
return
}
// Reload reactions and workflow state for the response
rxs, state, err := h.reactionService.GetReactions(r.Context(), id)
if err != nil {
h.logger.Error("get reactions failed", "error", err)
writeJSON(w, http.StatusInternalServerError, errorBody("server_error", "Failed to get reactions"))
return
}
writeJSON(w, http.StatusOK, map[string]any{
"action": result.Action,
"reaction": result.Reaction,
"reactions": rxs,
"workflow_state": state,
})
}
// GetReactions handles GET /api/messages/{id}/reactions.
func (h *ReactionsHandler) GetReactions(w http.ResponseWriter, r *http.Request) {
_, ok := OwnerIDFromContext(r.Context())
if !ok {
writeJSON(w, http.StatusUnauthorized, errorBody("unauthorized", "Authentication required"))
return
}
id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
if err != nil {
writeJSON(w, http.StatusBadRequest, errorBody("invalid_id", "Invalid message ID"))
return
}
// Verify the message exists
_, err = h.msgService.GetMessageByID(r.Context(), id)
if err != nil {
writeJSON(w, http.StatusNotFound, errorBody("not_found", "Message not found"))
return
}
rxs, state, err := h.reactionService.GetReactions(r.Context(), id)
if err != nil {
h.logger.Error("get reactions failed", "error", err)
writeJSON(w, http.StatusInternalServerError, errorBody("server_error", "Failed to get reactions"))
return
}
writeJSON(w, http.StatusOK, map[string]any{
"reactions": rxs,
"workflow_state": state,
})
}
// Remove handles DELETE /api/messages/{id}/reactions/{reaction}.
func (h *ReactionsHandler) Remove(w http.ResponseWriter, r *http.Request) {
ownerID, ok := OwnerIDFromContext(r.Context())
if !ok {
writeJSON(w, http.StatusUnauthorized, errorBody("unauthorized", "Authentication required"))
return
}
id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
if err != nil {
writeJSON(w, http.StatusBadRequest, errorBody("invalid_id", "Invalid message ID"))
return
}
reactionType := chi.URLParam(r, "reaction")
if reactionType == "" {
writeJSON(w, http.StatusBadRequest, errorBody("validation_error", "Reaction type is required"))
return
}
// Verify the message exists
msg, err := h.msgService.GetMessageByID(r.Context(), id)
if err != nil {
writeJSON(w, http.StatusNotFound, errorBody("not_found", "Message not found"))
return
}
// Determine the acting agent name
agentName, err := h.resolveAgentName(r, ownerID, msg)
if err != nil {
h.logger.Error("resolve agent name failed", "error", err)
writeJSON(w, http.StatusBadRequest, errorBody("no_agent", err.Error()))
return
}
if err := h.reactionService.Remove(r.Context(), id, agentName, reactionType); err != nil {
if err == reactions.ErrInvalidReaction {
writeJSON(w, http.StatusBadRequest, errorBody("invalid_reaction", err.Error()))
return
}
h.logger.Error("remove reaction failed", "error", err)
writeJSON(w, http.StatusInternalServerError, errorBody("server_error", "Failed to remove reaction"))
return
}
// Reload reactions and workflow state for the response
rxs, state, err := h.reactionService.GetReactions(r.Context(), id)
if err != nil {
h.logger.Error("get reactions failed", "error", err)
writeJSON(w, http.StatusInternalServerError, errorBody("server_error", "Failed to get reactions"))
return
}
writeJSON(w, http.StatusOK, map[string]any{
"status": "removed",
"reactions": rxs,
"workflow_state": state,
})
}
// resolveAgentName determines the agent name for the current session user.
// For session-authenticated users (Web UI), it returns the human agent.
// For API key / OAuth, it falls back to the first owned agent.
func (h *ReactionsHandler) resolveAgentName(r *http.Request, ownerID int64, msg *messaging.Message) (string, error) {
if _, isSession := auth.SessionIDFromContext(r.Context()); isSession {
humanAgent, err := h.agentService.GetHumanAgentForUser(r.Context(), ownerID)
if err != nil {
return "", err
}
if humanAgent == nil {
return "", fmt.Errorf("no human agent found for this user")
}
return humanAgent.Name, nil
}
// Non-session: find an owned agent
ownedAgents, err := h.agentService.ListAgents(r.Context(), ownerID)
if err != nil || len(ownedAgents) == 0 {
return "", fmt.Errorf("no agents registered")
}
// Prefer human-type agent
for _, a := range ownedAgents {
if a.Type == "human" {
return a.Name, nil
}
}
return ownedAgents[0].Name, nil
}
+19
View File
@@ -13,6 +13,7 @@ import (
"github.com/synapbus/synapbus/internal/k8s"
"github.com/synapbus/synapbus/internal/messaging"
"github.com/synapbus/synapbus/internal/push"
"github.com/synapbus/synapbus/internal/reactions"
"github.com/synapbus/synapbus/internal/trace"
"github.com/synapbus/synapbus/internal/webhooks"
)
@@ -32,6 +33,7 @@ type RouterConfig struct {
WebhookStore webhooks.WebhookStore
K8sService *k8s.K8sService
K8sStore k8s.K8sStore
ReactionService *reactions.Service
PushService *push.Service
SSEHub *SSEHub
Broadcaster *SSEBroadcaster
@@ -142,9 +144,24 @@ func NewRouterWithConfig(cfg RouterConfig) chi.Router {
})
}
// Reactions
if cfg.ReactionService != nil {
reactionsHandler := NewReactionsHandler(cfg.ReactionService, cfg.MsgService, cfg.AgentService)
r.Group(func(r chi.Router) {
r.Use(authMiddleware)
r.Post("/api/messages/{id}/reactions", reactionsHandler.Toggle)
r.Get("/api/messages/{id}/reactions", reactionsHandler.GetReactions)
r.Delete("/api/messages/{id}/reactions/{reaction}", reactionsHandler.Remove)
})
}
// Channels
if cfg.ChannelService != nil {
channelsHandler := NewChannelsHandler(cfg.ChannelService, cfg.AgentService, cfg.MsgService)
if cfg.ReactionService != nil {
channelsHandler.SetReactionService(cfg.ReactionService)
}
r.Group(func(r chi.Router) {
r.Use(authMiddleware)
@@ -152,6 +169,8 @@ func NewRouterWithConfig(cfg RouterConfig) chi.Router {
r.Get("/api/channels/{name}", channelsHandler.GetChannel)
r.Post("/api/channels", channelsHandler.CreateChannel)
r.Get("/api/channels/{name}/messages", channelsHandler.ChannelMessages)
r.Get("/api/channels/{name}/messages/by-state", channelsHandler.ListByState)
r.Put("/api/channels/{name}/settings", channelsHandler.UpdateSettings)
r.Post("/api/channels/{name}/join", channelsHandler.JoinChannel)
r.Post("/api/channels/{name}/leave", channelsHandler.LeaveChannel)
})
+24
View File
@@ -118,3 +118,27 @@ func DefaultFilename(mimeType string) string {
func IsImageType(mimeType string) bool {
return imageTypes[mimeType]
}
// IsAllowedType returns true if the MIME type is allowed for upload.
// Allowed: image/*, application/pdf, text/*.
func IsAllowedType(mimeType string) bool {
// Normalize: strip parameters like "; charset=utf-8".
base := mimeType
if idx := strings.Index(mimeType, ";"); idx >= 0 {
base = strings.TrimSpace(mimeType[:idx])
}
if strings.HasPrefix(base, "image/") {
return true
}
if base == "application/pdf" {
return true
}
if strings.HasPrefix(base, "text/") {
return true
}
// Also allow JSON and XML which may be detected as application/*
if base == "application/json" || base == "application/xml" {
return true
}
return false
}
+29
View File
@@ -154,6 +154,35 @@ func TestIsImageType(t *testing.T) {
}
}
func TestIsAllowedType(t *testing.T) {
tests := []struct {
mimeType string
want bool
}{
{"image/png", true},
{"image/jpeg", true},
{"image/gif", true},
{"application/pdf", true},
{"text/plain", true},
{"text/csv", true},
{"text/plain; charset=utf-8", true},
{"application/json", true},
{"application/octet-stream", false},
{"application/zip", false},
{"application/x-executable", false},
{"video/mp4", false},
}
for _, tt := range tests {
t.Run(tt.mimeType, func(t *testing.T) {
got := IsAllowedType(tt.mimeType)
if got != tt.want {
t.Errorf("IsAllowedType(%q) = %v, want %v", tt.mimeType, got, tt.want)
}
})
}
}
func min(a, b int) int {
if a < b {
return a
+5 -4
View File
@@ -11,10 +11,11 @@ const MaxFileSize = 50 * 1024 * 1024 // 50 MB
// Sentinel errors.
var (
ErrNotFound = errors.New("attachment not found")
ErrFileTooLarge = errors.New("file exceeds maximum size of 50MB")
ErrEmptyFile = errors.New("empty file not allowed")
ErrFileMissing = errors.New("attachment file missing from disk")
ErrNotFound = errors.New("attachment not found")
ErrFileTooLarge = errors.New("file exceeds maximum size of 50MB")
ErrEmptyFile = errors.New("empty file not allowed")
ErrFileMissing = errors.New("attachment file missing from disk")
ErrUnsupportedType = errors.New("unsupported file type: only images (jpg, png, gif, webp, svg), PDFs, and text files are allowed")
)
// Attachment represents the metadata for a stored file.
+5
View File
@@ -60,6 +60,11 @@ func (s *Service) Upload(ctx context.Context, req UploadRequest) (*UploadResult,
mimeType = DetectMIMEType(sniffBuf, req.Filename)
}
// Validate file type against allowlist.
if !IsAllowedType(mimeType) {
return nil, ErrUnsupportedType
}
// Assign default filename if missing.
filename := req.Filename
if filename == "" {
+74
View File
@@ -202,6 +202,80 @@ func TestService_Dedup(t *testing.T) {
}
}
func TestService_Upload_FileTypeValidation(t *testing.T) {
// PNG magic bytes.
pngContent := []byte{0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00}
// PDF magic bytes.
pdfContent := []byte("%PDF-1.4 some pdf content here")
// Plain text content.
textContent := []byte("just some plain text content")
tests := []struct {
name string
content []byte
filename string
mimeType string
wantErr error
}{
{
name: "valid image upload",
content: pngContent,
filename: "photo.png",
wantErr: nil,
},
{
name: "valid PDF upload",
content: pdfContent,
filename: "report.pdf",
wantErr: nil,
},
{
name: "valid text file upload",
content: textContent,
filename: "notes.txt",
wantErr: nil,
},
{
name: "invalid type zip rejected",
content: []byte("not real zip content"),
filename: "archive.zip",
mimeType: "application/zip",
wantErr: ErrUnsupportedType,
},
{
name: "invalid type executable rejected",
content: []byte{0x7f, 0x45, 0x4c, 0x46},
filename: "program.exe",
mimeType: "application/x-executable",
wantErr: ErrUnsupportedType,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
svc, _ := newTestService(t)
ctx := context.Background()
_, err := svc.Upload(ctx, UploadRequest{
Content: bytes.NewReader(tt.content),
Filename: tt.filename,
MIMEType: tt.mimeType,
UploadedBy: "agent-a",
})
if tt.wantErr != nil {
if err != tt.wantErr {
t.Errorf("expected error %v, got %v", tt.wantErr, err)
}
return
}
if err != nil {
t.Fatalf("Upload: %v", err)
}
})
}
}
func TestService_GarbageCollect(t *testing.T) {
svc, db := newTestService(t)
ctx := context.Background()
+32 -6
View File
@@ -459,13 +459,38 @@ func (s *Service) UpdateChannel(ctx context.Context, channelID int64, req Update
return ch, nil
}
// UpdateChannelSettings updates the workflow-related settings for a channel.
func (s *Service) UpdateChannelSettings(ctx context.Context, channelID int64, settings ChannelSettings) (*Channel, error) {
store, ok := s.store.(*SQLiteChannelStore)
if !ok {
return nil, fmt.Errorf("channel store does not support settings update")
}
if err := store.UpdateChannelSettings(ctx, channelID, settings); err != nil {
return nil, err
}
// Reload channel to return updated state
ch, err := s.store.GetChannel(ctx, channelID)
if err != nil {
return nil, err
}
s.logger.Info("channel settings updated",
"channel_id", channelID,
"auto_approve", settings.AutoApprove,
)
return ch, nil
}
// BroadcastMessage sends a message to a channel. It creates a single channel
// message (visible in the channel timeline via GetChannelMessages) and also
// delivers individual DM notifications to each member's inbox.
// If the message body contains @mentions, mentioned members receive a
// "mention":true flag in their inbox notification metadata, and the channel
// message metadata includes "mentioned_agents".
func (s *Service) BroadcastMessage(ctx context.Context, channelID int64, fromAgent, body string, priority int, metadata string, replyTo *int64) ([]*messaging.Message, error) {
func (s *Service) BroadcastMessage(ctx context.Context, channelID int64, fromAgent, body string, priority int, metadata string, replyTo *int64, attachments []string) ([]*messaging.Message, error) {
ch, err := s.store.GetChannel(ctx, channelID)
if err != nil {
return nil, err
@@ -522,11 +547,12 @@ func (s *Service) BroadcastMessage(ctx context.Context, channelID int64, fromAge
channelMetaBytes, _ := json.Marshal(channelMetaObj)
channelMsg, err := s.msgService.SendMessage(ctx, fromAgent, "", body, messaging.SendOptions{
Subject: fmt.Sprintf("channel:%s", ch.Name),
Priority: priority,
Metadata: string(channelMetaBytes),
ChannelID: &channelID,
ReplyTo: replyTo,
Subject: fmt.Sprintf("channel:%s", ch.Name),
Priority: priority,
Metadata: string(channelMetaBytes),
ChannelID: &channelID,
ReplyTo: replyTo,
Attachments: attachments,
})
if err != nil {
return nil, fmt.Errorf("create channel message: %w", err)
+12 -12
View File
@@ -533,7 +533,7 @@ func TestService_BroadcastMessage(t *testing.T) {
ch, _ := svc.CreateChannel(ctx, CreateChannelRequest{Name: "alerts", Type: TypeStandard, CreatedBy: "agent-a"})
t.Run("broadcast creates channel message", func(t *testing.T) {
msgs, err := svc.BroadcastMessage(ctx, ch.ID, "agent-a", "hello", 5, "", nil)
msgs, err := svc.BroadcastMessage(ctx, ch.ID, "agent-a", "hello", 5, "", nil, nil)
if err != nil {
t.Fatalf("BroadcastMessage: %v", err)
}
@@ -568,7 +568,7 @@ func TestService_BroadcastMessage(t *testing.T) {
t.Run("broadcast without mentions sends no DMs", func(t *testing.T) {
svc.JoinChannel(ctx, ch.ID, "agent-b")
svc.JoinChannel(ctx, ch.ID, "agent-c")
_, err := svc.BroadcastMessage(ctx, ch.ID, "agent-a", "no-dm-test", 5, "", nil)
_, err := svc.BroadcastMessage(ctx, ch.ID, "agent-a", "no-dm-test", 5, "", nil, nil)
if err != nil {
t.Fatalf("BroadcastMessage: %v", err)
}
@@ -583,7 +583,7 @@ func TestService_BroadcastMessage(t *testing.T) {
})
t.Run("sender does not receive own message", func(t *testing.T) {
svc.BroadcastMessage(ctx, ch.ID, "agent-a", "no self-message", 5, "", nil)
svc.BroadcastMessage(ctx, ch.ID, "agent-a", "no self-message", 5, "", nil, nil)
inboxResult, _ := svc.msgService.ReadInbox(ctx, "agent-a", messaging.ReadOptions{IncludeRead: true})
for _, m := range inboxResult.Messages {
if m.Body == "no self-message" {
@@ -594,7 +594,7 @@ func TestService_BroadcastMessage(t *testing.T) {
t.Run("non-member auto-joins public channel on broadcast", func(t *testing.T) {
seedAgent(t, svc.store.(*SQLiteChannelStore).db, "outsider")
_, err := svc.BroadcastMessage(ctx, ch.ID, "outsider", "auto-joined", 5, "", nil)
_, err := svc.BroadcastMessage(ctx, ch.ID, "outsider", "auto-joined", 5, "", nil, nil)
if err != nil {
t.Fatalf("expected auto-join for public channel, got %v", err)
}
@@ -605,10 +605,10 @@ func TestService_BroadcastMessage(t *testing.T) {
})
t.Run("broadcast with reply_to", func(t *testing.T) {
msgs, _ := svc.BroadcastMessage(ctx, ch.ID, "agent-a", "original", 5, "", nil)
msgs, _ := svc.BroadcastMessage(ctx, ch.ID, "agent-a", "original", 5, "", nil, nil)
original := msgs[0]
replies, err := svc.BroadcastMessage(ctx, ch.ID, "agent-b", "reply to original", 5, "", &original.ID)
replies, err := svc.BroadcastMessage(ctx, ch.ID, "agent-b", "reply to original", 5, "", &original.ID, nil)
if err != nil {
t.Fatalf("BroadcastMessage with reply_to: %v", err)
}
@@ -625,7 +625,7 @@ func TestService_BroadcastMessage(t *testing.T) {
t.Fatalf("create private channel: %v", err)
}
seedAgent(t, svc.store.(*SQLiteChannelStore).db, "outsider2")
_, err = svc.BroadcastMessage(ctx, privCh.ID, "outsider2", "unauthorized", 5, "", nil)
_, err = svc.BroadcastMessage(ctx, privCh.ID, "outsider2", "unauthorized", 5, "", nil, nil)
if !errors.Is(err, ErrNotChannelMember) {
t.Errorf("expected ErrNotChannelMember for private channel, got %v", err)
}
@@ -644,7 +644,7 @@ func TestService_BroadcastMessage_Mentions(t *testing.T) {
svc.JoinChannel(ctx, ch.ID, "agent-c")
t.Run("mentioned member gets mention flag in inbox", func(t *testing.T) {
_, err := svc.BroadcastMessage(ctx, ch.ID, "agent-a", "hey @agent-b check this", 5, "", nil)
_, err := svc.BroadcastMessage(ctx, ch.ID, "agent-a", "hey @agent-b check this", 5, "", nil, nil)
if err != nil {
t.Fatalf("BroadcastMessage: %v", err)
}
@@ -677,7 +677,7 @@ func TestService_BroadcastMessage_Mentions(t *testing.T) {
})
t.Run("channel message metadata includes mentioned_agents", func(t *testing.T) {
_, err := svc.BroadcastMessage(ctx, ch.ID, "agent-a", "cc @agent-b and @agent-c", 5, "", nil)
_, err := svc.BroadcastMessage(ctx, ch.ID, "agent-a", "cc @agent-b and @agent-c", 5, "", nil, nil)
if err != nil {
t.Fatalf("BroadcastMessage: %v", err)
}
@@ -707,7 +707,7 @@ func TestService_BroadcastMessage_Mentions(t *testing.T) {
})
t.Run("self-mention is excluded", func(t *testing.T) {
_, err := svc.BroadcastMessage(ctx, ch.ID, "agent-a", "I am @agent-a and cc @agent-b", 5, "", nil)
_, err := svc.BroadcastMessage(ctx, ch.ID, "agent-a", "I am @agent-a and cc @agent-b", 5, "", nil, nil)
if err != nil {
t.Fatalf("BroadcastMessage: %v", err)
}
@@ -732,7 +732,7 @@ func TestService_BroadcastMessage_Mentions(t *testing.T) {
})
t.Run("no mentions produces no mention metadata", func(t *testing.T) {
_, err := svc.BroadcastMessage(ctx, ch.ID, "agent-a", "just a normal message", 5, "", nil)
_, err := svc.BroadcastMessage(ctx, ch.ID, "agent-a", "just a normal message", 5, "", nil, nil)
if err != nil {
t.Fatalf("BroadcastMessage: %v", err)
}
@@ -752,7 +752,7 @@ func TestService_BroadcastMessage_Mentions(t *testing.T) {
t.Run("non-member mention is ignored", func(t *testing.T) {
seedAgent(t, svc.store.(*SQLiteChannelStore).db, "outsider")
_, err := svc.BroadcastMessage(ctx, ch.ID, "agent-a", "hey @outsider and @agent-b", 5, "", nil)
_, err := svc.BroadcastMessage(ctx, ch.ID, "agent-a", "hey @outsider and @agent-b", 5, "", nil, nil)
if err != nil {
t.Fatalf("BroadcastMessage: %v", err)
}
+23 -6
View File
@@ -83,9 +83,9 @@ func (s *SQLiteChannelStore) GetChannel(ctx context.Context, id int64) (*Channel
var ch Channel
var isPrivate, isSystem int
err := s.db.QueryRowContext(ctx,
`SELECT id, name, description, topic, type, is_private, is_system, created_by, created_at, updated_at
`SELECT id, name, description, topic, type, is_private, is_system, created_by, auto_approve, stalemate_remind_after, stalemate_escalate_after, created_at, updated_at
FROM channels WHERE id = ?`, id,
).Scan(&ch.ID, &ch.Name, &ch.Description, &ch.Topic, &ch.Type, &isPrivate, &isSystem, &ch.CreatedBy, &ch.CreatedAt, &ch.UpdatedAt)
).Scan(&ch.ID, &ch.Name, &ch.Description, &ch.Topic, &ch.Type, &isPrivate, &isSystem, &ch.CreatedBy, &ch.AutoApprove, &ch.StalemateRemindAfter, &ch.StalemateEscalateAfter, &ch.CreatedAt, &ch.UpdatedAt)
if err != nil {
if err == sql.ErrNoRows {
return nil, ErrChannelNotFound
@@ -102,9 +102,9 @@ func (s *SQLiteChannelStore) GetChannelByName(ctx context.Context, name string)
var ch Channel
var isPrivate, isSystem int
err := s.db.QueryRowContext(ctx,
`SELECT id, name, description, topic, type, is_private, is_system, created_by, created_at, updated_at
`SELECT id, name, description, topic, type, is_private, is_system, created_by, auto_approve, stalemate_remind_after, stalemate_escalate_after, created_at, updated_at
FROM channels WHERE LOWER(name) = LOWER(?)`, name,
).Scan(&ch.ID, &ch.Name, &ch.Description, &ch.Topic, &ch.Type, &isPrivate, &isSystem, &ch.CreatedBy, &ch.CreatedAt, &ch.UpdatedAt)
).Scan(&ch.ID, &ch.Name, &ch.Description, &ch.Topic, &ch.Type, &isPrivate, &isSystem, &ch.CreatedBy, &ch.AutoApprove, &ch.StalemateRemindAfter, &ch.StalemateEscalateAfter, &ch.CreatedAt, &ch.UpdatedAt)
if err != nil {
if err == sql.ErrNoRows {
return nil, ErrChannelNotFound
@@ -120,7 +120,7 @@ func (s *SQLiteChannelStore) GetChannelByName(ctx context.Context, name string)
// is a member or has a pending invite.
func (s *SQLiteChannelStore) ListChannels(ctx context.Context, agentName string) ([]*Channel, error) {
rows, err := s.db.QueryContext(ctx,
`SELECT DISTINCT c.id, c.name, c.description, c.topic, c.type, c.is_private, c.is_system, c.created_by, c.created_at, c.updated_at
`SELECT DISTINCT c.id, c.name, c.description, c.topic, c.type, c.is_private, c.is_system, c.created_by, c.auto_approve, c.stalemate_remind_after, c.stalemate_escalate_after, c.created_at, c.updated_at
FROM channels c
WHERE c.is_private = 0
OR EXISTS (SELECT 1 FROM channel_members cm WHERE cm.channel_id = c.id AND cm.agent_name = ?)
@@ -137,7 +137,7 @@ func (s *SQLiteChannelStore) ListChannels(ctx context.Context, agentName string)
for rows.Next() {
var ch Channel
var isPrivate, isSystem int
if err := rows.Scan(&ch.ID, &ch.Name, &ch.Description, &ch.Topic, &ch.Type, &isPrivate, &isSystem, &ch.CreatedBy, &ch.CreatedAt, &ch.UpdatedAt); err != nil {
if err := rows.Scan(&ch.ID, &ch.Name, &ch.Description, &ch.Topic, &ch.Type, &isPrivate, &isSystem, &ch.CreatedBy, &ch.AutoApprove, &ch.StalemateRemindAfter, &ch.StalemateEscalateAfter, &ch.CreatedAt, &ch.UpdatedAt); err != nil {
return nil, fmt.Errorf("scan channel: %w", err)
}
ch.IsPrivate = isPrivate != 0
@@ -415,6 +415,23 @@ func (s *SQLiteChannelStore) GetChannelSummaries(ctx context.Context, agentName
return summaries, rows.Err()
}
// UpdateChannelSettings updates the workflow-related settings for a channel.
func (s *SQLiteChannelStore) UpdateChannelSettings(ctx context.Context, id int64, settings ChannelSettings) error {
result, err := s.db.ExecContext(ctx,
`UPDATE channels SET auto_approve = ?, stalemate_remind_after = ?, stalemate_escalate_after = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?`,
settings.AutoApprove, settings.StalemateRemindAfter, settings.StalemateEscalateAfter, id,
)
if err != nil {
return fmt.Errorf("update channel settings: %w", err)
}
rowsAffected, _ := result.RowsAffected()
if rowsAffected == 0 {
return ErrChannelNotFound
}
s.logger.Info("channel settings updated", "id", id)
return nil
}
// isUniqueConstraintError checks if an error is a SQLite unique constraint violation.
func isUniqueConstraintError(err error) bool {
return strings.Contains(err.Error(), "UNIQUE constraint failed")
+20 -10
View File
@@ -25,16 +25,19 @@ const (
// Channel represents a named group communication space.
type Channel struct {
ID int64 `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
Topic string `json:"topic"`
Type string `json:"type"`
IsPrivate bool `json:"is_private"`
IsSystem bool `json:"is_system"`
CreatedBy string `json:"created_by"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
ID int64 `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
Topic string `json:"topic"`
Type string `json:"type"`
IsPrivate bool `json:"is_private"`
IsSystem bool `json:"is_system"`
CreatedBy string `json:"created_by"`
AutoApprove bool `json:"auto_approve"`
StalemateRemindAfter string `json:"stalemate_remind_after"`
StalemateEscalateAfter string `json:"stalemate_escalate_after"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
// ChannelWithCount embeds Channel and adds a member count.
@@ -107,6 +110,13 @@ type JoinChannelRequest struct {
AgentName string `json:"agent_name"`
}
// ChannelSettings holds workflow-related settings for a channel.
type ChannelSettings struct {
AutoApprove bool `json:"auto_approve"`
StalemateRemindAfter string `json:"stalemate_remind_after"`
StalemateEscalateAfter string `json:"stalemate_escalate_after"`
}
// InviteRequest is the input for inviting an agent to a channel.
type InviteRequest struct {
ChannelID int64 `json:"channel_id"`
+194 -6
View File
@@ -7,12 +7,14 @@ import (
"encoding/json"
"fmt"
"io"
"strings"
"time"
"github.com/synapbus/synapbus/internal/agents"
"github.com/synapbus/synapbus/internal/attachments"
"github.com/synapbus/synapbus/internal/channels"
"github.com/synapbus/synapbus/internal/messaging"
"github.com/synapbus/synapbus/internal/reactions"
"github.com/synapbus/synapbus/internal/search"
)
@@ -25,6 +27,7 @@ type ServiceBridge struct {
swarmService *channels.SwarmService
attachmentService *attachments.Service
searchService *search.Service
reactionService *reactions.Service
agentName string
}
@@ -36,6 +39,7 @@ func NewServiceBridge(
swarmService *channels.SwarmService,
attachmentService *attachments.Service,
searchService *search.Service,
reactionService *reactions.Service,
agentName string,
) *ServiceBridge {
return &ServiceBridge{
@@ -45,6 +49,7 @@ func NewServiceBridge(
swarmService: swarmService,
attachmentService: attachmentService,
searchService: searchService,
reactionService: reactionService,
agentName: agentName,
}
}
@@ -102,6 +107,16 @@ func (b *ServiceBridge) Call(ctx context.Context, actionName string, args map[st
case "download_attachment":
return b.callDownloadAttachment(ctx, args)
// --- Reactions ---
case "react":
return b.callReact(ctx, args)
case "unreact":
return b.callUnreact(ctx, args)
case "get_reactions":
return b.callGetReactions(ctx, args)
case "list_by_state":
return b.callListByState(ctx, args)
// --- DM send (also accessible via bridge for execute tool) ---
case "send_message":
return b.callSendMessage(ctx, args)
@@ -132,12 +147,34 @@ func (b *ServiceBridge) callSendMessage(ctx context.Context, args map[string]any
replyTo = &v
}
var attachmentHashes []string
if attVal, ok := args["attachments"]; ok {
switch v := attVal.(type) {
case string:
for _, h := range strings.Split(v, ",") {
h = strings.TrimSpace(h)
if h != "" {
attachmentHashes = append(attachmentHashes, h)
}
}
case []any:
for _, item := range v {
if s, ok := item.(string); ok && s != "" {
attachmentHashes = append(attachmentHashes, s)
}
}
case []string:
attachmentHashes = v
}
}
opts := messaging.SendOptions{
Subject: getString(args, "subject", ""),
Priority: getInt(args, "priority", 5),
Metadata: getString(args, "metadata", ""),
ChannelID: channelID,
ReplyTo: replyTo,
Subject: getString(args, "subject", ""),
Priority: getInt(args, "priority", 5),
Metadata: getString(args, "metadata", ""),
ChannelID: channelID,
ReplyTo: replyTo,
Attachments: attachmentHashes,
}
msg, err := b.msgService.SendMessage(ctx, b.agentName, to, body, opts)
@@ -554,7 +591,28 @@ func (b *ServiceBridge) callSendChannelMessage(ctx context.Context, args map[str
}
}
messages, err := b.channelService.BroadcastMessage(ctx, channelID, b.agentName, body, priority, metadata, replyTo)
var attachmentHashes []string
if attVal, ok := args["attachments"]; ok {
switch v := attVal.(type) {
case string:
for _, h := range strings.Split(v, ",") {
h = strings.TrimSpace(h)
if h != "" {
attachmentHashes = append(attachmentHashes, h)
}
}
case []any:
for _, item := range v {
if s, ok := item.(string); ok && s != "" {
attachmentHashes = append(attachmentHashes, s)
}
}
case []string:
attachmentHashes = v
}
}
messages, err := b.channelService.BroadcastMessage(ctx, channelID, b.agentName, body, priority, metadata, replyTo, attachmentHashes)
if err != nil {
return nil, err
}
@@ -876,6 +934,136 @@ func (b *ServiceBridge) callDownloadAttachment(ctx context.Context, args map[str
}, nil
}
// --- Reaction implementations ---
func (b *ServiceBridge) callReact(ctx context.Context, args map[string]any) (any, error) {
if b.reactionService == nil {
return nil, fmt.Errorf("reaction service not available")
}
messageID := getInt(args, "message_id", 0)
if messageID == 0 {
return nil, fmt.Errorf("'message_id' parameter is required")
}
reaction := getString(args, "reaction", "")
if reaction == "" {
return nil, fmt.Errorf("'reaction' parameter is required")
}
var metadata json.RawMessage
if metaStr := getString(args, "metadata", ""); metaStr != "" {
if !json.Valid([]byte(metaStr)) {
return nil, fmt.Errorf("metadata must be valid JSON")
}
metadata = json.RawMessage(metaStr)
}
result, err := b.reactionService.Toggle(ctx, int64(messageID), b.agentName, reaction, metadata)
if err != nil {
return nil, err
}
resp := map[string]any{
"action": result.Action,
"message_id": messageID,
"reaction": reaction,
}
if result.Reaction != nil {
resp["id"] = result.Reaction.ID
resp["created_at"] = result.Reaction.CreatedAt
}
return resp, nil
}
func (b *ServiceBridge) callUnreact(ctx context.Context, args map[string]any) (any, error) {
if b.reactionService == nil {
return nil, fmt.Errorf("reaction service not available")
}
messageID := getInt(args, "message_id", 0)
if messageID == 0 {
return nil, fmt.Errorf("'message_id' parameter is required")
}
reaction := getString(args, "reaction", "")
if reaction == "" {
return nil, fmt.Errorf("'reaction' parameter is required")
}
if err := b.reactionService.Remove(ctx, int64(messageID), b.agentName, reaction); err != nil {
return nil, err
}
return map[string]any{
"message_id": messageID,
"reaction": reaction,
"status": "removed",
}, nil
}
func (b *ServiceBridge) callGetReactions(ctx context.Context, args map[string]any) (any, error) {
if b.reactionService == nil {
return nil, fmt.Errorf("reaction service not available")
}
messageID := getInt(args, "message_id", 0)
if messageID == 0 {
return nil, fmt.Errorf("'message_id' parameter is required")
}
rxns, state, err := b.reactionService.GetReactions(ctx, int64(messageID))
if err != nil {
return nil, err
}
return map[string]any{
"reactions": rxns,
"workflow_state": state,
"count": len(rxns),
}, nil
}
func (b *ServiceBridge) callListByState(ctx context.Context, args map[string]any) (any, error) {
if b.reactionService == nil {
return nil, fmt.Errorf("reaction service not available")
}
if b.channelService == nil {
return nil, fmt.Errorf("channel service not available")
}
channelName := getString(args, "channel", "")
if channelName == "" {
return nil, fmt.Errorf("'channel' parameter is required")
}
state := getString(args, "state", "")
if state == "" {
return nil, fmt.Errorf("'state' parameter is required")
}
ch, err := b.channelService.GetChannelByName(ctx, channelName)
if err != nil {
return nil, err
}
messageIDs, err := b.reactionService.ListByState(ctx, ch.ID, state)
if err != nil {
return nil, err
}
if messageIDs == nil {
messageIDs = []int64{}
}
return map[string]any{
"message_ids": messageIDs,
"count": len(messageIDs),
"channel": channelName,
"state": state,
}, nil
}
// --- Helpers ---
// resolveChannelID resolves a channel ID from either channel_id or channel_name in args.
+2 -1
View File
@@ -43,6 +43,7 @@ func newTestBridge(t *testing.T) (*ServiceBridge, *messaging.MessagingService, *
swarmService,
nil, // attachmentService
nil, // searchService
nil, // reactionService
"agent-a",
)
return bridge, msgService, agentService, channelService
@@ -185,7 +186,7 @@ func TestBridge_JoinChannel(t *testing.T) {
bridge.agentService,
bridge.channelService,
bridge.swarmService,
nil, nil,
nil, nil, nil,
"agent-b",
)
+1
View File
@@ -50,6 +50,7 @@ func newTestHybridWithChannels(t *testing.T) (*HybridToolRegistrar, *channels.Se
nil, // swarmService
nil, // attachmentService
nil, // searchService
nil, // reactionService
jsPool,
actionRegistry,
actionIndex,
+3
View File
@@ -18,6 +18,7 @@ import (
"github.com/synapbus/synapbus/internal/console"
"github.com/synapbus/synapbus/internal/jsruntime"
"github.com/synapbus/synapbus/internal/messaging"
"github.com/synapbus/synapbus/internal/reactions"
"github.com/synapbus/synapbus/internal/search"
"github.com/synapbus/synapbus/internal/trace"
)
@@ -40,6 +41,7 @@ func NewMCPServer(
swarmService *channels.SwarmService,
attachmentService *attachments.Service,
searchService *search.Service,
reactionService *reactions.Service,
consolePrinter *console.Printer,
jsPool *jsruntime.Pool,
actionRegistry *actions.Registry,
@@ -153,6 +155,7 @@ func NewMCPServer(
swarmService,
attachmentService,
searchService,
reactionService,
jsPool,
actionRegistry,
actionIndex,
+3 -3
View File
@@ -38,7 +38,7 @@ func newTestMCPServer(t *testing.T, con *console.Printer) (*MCPServer, *messagin
actionRegistry := actions.NewRegistry()
actionIndex := actions.NewIndex(actionRegistry.List())
srv := NewMCPServer(msgService, agentService, nil, nil, nil, nil, con, jsPool, actionRegistry, actionIndex, db)
srv := NewMCPServer(msgService, agentService, nil, nil, nil, nil, nil, con, jsPool, actionRegistry, actionIndex, db)
return srv, msgService, agentService
}
@@ -133,7 +133,7 @@ func TestMCPToolCall_WithValidAPIKey(t *testing.T) {
actionIndex := actions.NewIndex(actionRegistry.List())
// Create MCP server
srv := NewMCPServer(msgService, agentService, nil, nil, nil, nil, nil, jsPool, actionRegistry, actionIndex, db)
srv := NewMCPServer(msgService, agentService, nil, nil, nil, nil, nil, nil, jsPool, actionRegistry, actionIndex, db)
// Mount with auth middleware, just like main.go does
mux := http.NewServeMux()
@@ -188,7 +188,7 @@ func TestMCPToolCall_InvalidAPIKeyReturns401(t *testing.T) {
actionRegistry := actions.NewRegistry()
actionIndex := actions.NewIndex(actionRegistry.List())
srv := NewMCPServer(msgService, agentService, nil, nil, nil, nil, nil, jsPool, actionRegistry, actionIndex, db)
srv := NewMCPServer(msgService, agentService, nil, nil, nil, nil, nil, nil, jsPool, actionRegistry, actionIndex, db)
mux := http.NewServeMux()
handler := agents.OptionalAuthMiddlewareWithAPIKeys(agentService, apiKeyService)(srv.Handler())
+48 -11
View File
@@ -18,6 +18,7 @@ import (
"github.com/synapbus/synapbus/internal/channels"
"github.com/synapbus/synapbus/internal/jsruntime"
"github.com/synapbus/synapbus/internal/messaging"
"github.com/synapbus/synapbus/internal/reactions"
"github.com/synapbus/synapbus/internal/search"
)
@@ -29,6 +30,7 @@ type HybridToolRegistrar struct {
swarmService *channels.SwarmService
attachmentService *attachments.Service
searchService *search.Service
reactionService *reactions.Service
jsPool *jsruntime.Pool
actionRegistry *actions.Registry
actionIndex *actions.Index
@@ -44,6 +46,7 @@ func NewHybridToolRegistrar(
swarmService *channels.SwarmService,
attachmentService *attachments.Service,
searchService *search.Service,
reactionService *reactions.Service,
jsPool *jsruntime.Pool,
actionRegistry *actions.Registry,
actionIndex *actions.Index,
@@ -56,6 +59,7 @@ func NewHybridToolRegistrar(
swarmService: swarmService,
attachmentService: attachmentService,
searchService: searchService,
reactionService: reactionService,
jsPool: jsPool,
actionRegistry: actionRegistry,
actionIndex: actionIndex,
@@ -84,14 +88,15 @@ func (h *HybridToolRegistrar) myStatusTool() mcplib.Tool {
func (h *HybridToolRegistrar) sendMessageTool() mcplib.Tool {
return mcplib.NewTool("send_message",
mcplib.WithDescription("Send a message to another agent (DM) or to a channel. Specify exactly one of 'to' (agent name for DM) or 'channel' (channel name or numeric ID)."),
mcplib.WithDescription("Send a message to another agent (DM) or to a channel. Supports attachments — upload files first via the execute tool, then pass the returned hashes here. Specify exactly one of 'to' (agent name for DM) or 'channel' (channel name or numeric ID)."),
mcplib.WithString("to", mcplib.Description("Recipient agent name for direct messages")),
mcplib.WithString("channel", mcplib.Description("Channel name or numeric ID for channel messages")),
mcplib.WithString("body", mcplib.Description("Message body text"), mcplib.Required()),
mcplib.WithString("subject", mcplib.Description("Conversation subject (optional)")),
mcplib.WithNumber("priority", mcplib.Description("Message priority (1-10, default 5)"), mcplib.Min(1), mcplib.Max(10)),
mcplib.WithString("metadata", mcplib.Description("JSON metadata object (optional)")),
mcplib.WithNumber("reply_to", mcplib.Description("ID of the message to reply to (optional, for threading)")),
mcplib.WithNumber("reply_to", mcplib.Description("ID of the parent message to reply to. Creates a threaded reply. Always use reply_to when responding to a message that is itself a thread reply, to keep conversations organized.")),
mcplib.WithString("attachments", mcplib.Description("Comma-separated list of attachment hashes to link to this message. Upload attachments first using the upload_attachment action via the execute tool.")),
)
}
@@ -323,6 +328,16 @@ func (h *HybridToolRegistrar) handleSendMessage(ctx context.Context, req mcplib.
replyTo = &v
}
var attachmentHashes []string
if attStr := req.GetString("attachments", ""); attStr != "" {
for _, h := range strings.Split(attStr, ",") {
h = strings.TrimSpace(h)
if h != "" {
attachmentHashes = append(attachmentHashes, h)
}
}
}
// Channel message path.
if channel != "" {
if h.channelService == nil {
@@ -335,7 +350,7 @@ func (h *HybridToolRegistrar) handleSendMessage(ctx context.Context, req mcplib.
return mcplib.NewToolResultError(fmt.Sprintf("send_message to channel failed: %s", err)), nil
}
messages, err := h.channelService.BroadcastMessage(ctx, channelID, agentName, body, priority, metadataStr, replyTo)
messages, err := h.channelService.BroadcastMessage(ctx, channelID, agentName, body, priority, metadataStr, replyTo, attachmentHashes)
if err != nil {
return mcplib.NewToolResultError(fmt.Sprintf("send_message to channel failed: %s", err)), nil
}
@@ -345,19 +360,30 @@ func (h *HybridToolRegistrar) handleSendMessage(ctx context.Context, req mcplib.
messageID = messages[0].ID
}
return resultJSON(map[string]any{
result := map[string]any{
"channel_id": channelID,
"message_id": messageID,
"status": "sent",
})
}
// Enrich channel messages with attachment info.
if len(messages) > 0 && len(attachmentHashes) > 0 {
h.msgService.EnrichMessages(ctx, messages)
if len(messages[0].Attachments) > 0 {
result["attachments"] = messages[0].Attachments
}
}
return resultJSON(result)
}
// DM path.
opts := messaging.SendOptions{
Subject: subject,
Priority: priority,
Metadata: metadataStr,
ReplyTo: replyTo,
Subject: subject,
Priority: priority,
Metadata: metadataStr,
ReplyTo: replyTo,
Attachments: attachmentHashes,
}
msg, err := h.msgService.SendMessage(ctx, agentName, to, body, opts)
@@ -365,11 +391,21 @@ func (h *HybridToolRegistrar) handleSendMessage(ctx context.Context, req mcplib.
return mcplib.NewToolResultError(fmt.Sprintf("send_message failed: %s", err)), nil
}
return resultJSON(map[string]any{
result := map[string]any{
"message_id": msg.ID,
"conversation_id": msg.ConversationID,
"status": msg.Status,
})
}
// Enrich message with attachment info.
if len(attachmentHashes) > 0 {
h.msgService.EnrichMessages(ctx, []*messaging.Message{msg})
if len(msg.Attachments) > 0 {
result["attachments"] = msg.Attachments
}
}
return resultJSON(result)
}
func (h *HybridToolRegistrar) handleSearch(ctx context.Context, req mcplib.CallToolRequest) (*mcplib.CallToolResult, error) {
@@ -443,6 +479,7 @@ func (h *HybridToolRegistrar) handleExecute(ctx context.Context, req mcplib.Call
h.swarmService,
h.attachmentService,
h.searchService,
h.reactionService,
agentName,
)
+1
View File
@@ -68,6 +68,7 @@ func newTestHybridRegistrar(t *testing.T) (*HybridToolRegistrar, *messaging.Mess
nil, // swarmService
nil, // attachmentService
nil, // searchService
nil, // reactionService
jsPool,
actionRegistry,
actionIndex,
+7 -6
View File
@@ -2,12 +2,13 @@ package messaging
// SendOptions configures message sending behavior.
type SendOptions struct {
Subject string `json:"subject,omitempty"`
Priority int `json:"priority,omitempty"`
Metadata string `json:"metadata,omitempty"`
ChannelID *int64 `json:"channel_id,omitempty"`
ConversationID *int64 `json:"conversation_id,omitempty"`
ReplyTo *int64 `json:"reply_to,omitempty"`
Subject string `json:"subject,omitempty"`
Priority int `json:"priority,omitempty"`
Metadata string `json:"metadata,omitempty"`
ChannelID *int64 `json:"channel_id,omitempty"`
ConversationID *int64 `json:"conversation_id,omitempty"`
ReplyTo *int64 `json:"reply_to,omitempty"`
Attachments []string `json:"attachments,omitempty"` // attachment hashes to link
}
// ReadOptions configures inbox reading behavior.
+108
View File
@@ -24,12 +24,27 @@ type MessageListener interface {
OnMessageSent(ctx context.Context, msg *Message)
}
// AttachmentLinker links attachment hashes to message IDs. This avoids
// importing the attachments package directly. Set via SetAttachmentLinker.
type AttachmentLinker interface {
AttachToMessage(ctx context.Context, hash string, messageID int64) error
GetByMessageID(ctx context.Context, messageID int64) ([]AttachmentInfo, error)
}
// ReactionEnricher loads reactions for messages. This avoids importing the
// reactions package directly. Set via SetReactionEnricher.
type ReactionEnricher interface {
GetByMessageIDs(ctx context.Context, messageIDs []int64) (map[int64][]ReactionInfo, error)
}
// MessagingService provides business logic for messaging operations.
type MessagingService struct {
store MessageStore
tracer *trace.Tracer
dispatcher dispatcher.EventDispatcher
embeddings EmbeddingNotifier
attLinker AttachmentLinker
rxEnricher ReactionEnricher
listeners []MessageListener
logger *slog.Logger
}
@@ -53,6 +68,16 @@ func (s *MessagingService) SetEmbeddingNotifier(n EmbeddingNotifier) {
s.embeddings = n
}
// SetAttachmentLinker sets the attachment linker for message-attachment binding.
func (s *MessagingService) SetAttachmentLinker(l AttachmentLinker) {
s.attLinker = l
}
// SetReactionEnricher sets the reaction enricher for message reaction loading.
func (s *MessagingService) SetReactionEnricher(e ReactionEnricher) {
s.rxEnricher = e
}
// AddMessageListener registers a listener that is notified after message creation.
func (s *MessagingService) AddMessageListener(l MessageListener) {
s.listeners = append(s.listeners, l)
@@ -145,6 +170,19 @@ func (s *MessagingService) SendMessage(ctx context.Context, from, to, body strin
return nil, fmt.Errorf("insert message: %w", err)
}
// Link attachments if provided.
if s.attLinker != nil && len(opts.Attachments) > 0 {
for _, hash := range opts.Attachments {
if err := s.attLinker.AttachToMessage(ctx, hash, msg.ID); err != nil {
s.logger.Error("failed to link attachment",
"hash", hash,
"message_id", msg.ID,
"error", err,
)
}
}
}
// Enqueue for embedding (async, best-effort)
if s.embeddings != nil {
s.embeddings.OnMessageCreated(ctx, msg.ID, msg.Body)
@@ -523,6 +561,76 @@ func (s *MessagingService) GetConversationIDsForDM(ctx context.Context, agentNam
return s.store.GetConversationIDsForDM(ctx, agentNames, peerAgent, lastMessageID)
}
// EnrichMessages populates ReplyCount and Attachments on a slice of messages.
func (s *MessagingService) EnrichMessages(ctx context.Context, msgs []*Message) {
if len(msgs) == 0 {
return
}
ids := make([]int64, len(msgs))
for i, m := range msgs {
ids[i] = m.ID
}
// Batch-load reply counts.
counts, err := s.store.GetReplyCounts(ctx, ids)
if err != nil {
s.logger.Error("failed to load reply counts", "error", err)
} else {
for _, m := range msgs {
if c, ok := counts[m.ID]; ok {
m.ReplyCount = c
}
}
}
// Batch-load attachments.
if s.attLinker != nil {
for _, m := range msgs {
atts, err := s.attLinker.GetByMessageID(ctx, m.ID)
if err != nil {
s.logger.Error("failed to load attachments", "message_id", m.ID, "error", err)
continue
}
if len(atts) > 0 {
m.Attachments = atts
}
}
}
// Batch-load reactions and derive workflow state.
if s.rxEnricher != nil {
rxMap, err := s.rxEnricher.GetByMessageIDs(ctx, ids)
if err != nil {
s.logger.Error("failed to load reactions", "error", err)
} else {
for _, m := range msgs {
if rxs, ok := rxMap[m.ID]; ok && len(rxs) > 0 {
m.Reactions = rxs
// Derive workflow state from reactions
highestPriority := 0
priorities := map[string]int{
"approve": 2, "in_progress": 3, "reject": 4, "done": 5, "published": 6,
}
states := map[string]string{
"approve": "approved", "in_progress": "in_progress", "reject": "rejected", "done": "done", "published": "published",
}
for _, rx := range rxs {
if p, ok := priorities[rx.Reaction]; ok && p > highestPriority {
highestPriority = p
m.WorkflowState = states[rx.Reaction]
}
}
}
// Default to "proposed" for channel messages with no reactions
if m.WorkflowState == "" && m.ChannelID != nil {
m.WorkflowState = "proposed"
}
}
}
}
}
// GetConversation returns a conversation and its messages.
func (s *MessagingService) GetConversation(ctx context.Context, id int64) (*Conversation, []*Message, error) {
conv, err := s.store.GetConversation(ctx, id)
+91
View File
@@ -728,5 +728,96 @@ func TestMessagingService_ReadInbox_DateFiltering(t *testing.T) {
})
}
// mockAttachmentLinker is a test double for the AttachmentLinker interface.
type mockAttachmentLinker struct {
attachments map[int64][]AttachmentInfo
}
func (m *mockAttachmentLinker) AttachToMessage(_ context.Context, _ string, _ int64) error {
return nil
}
func (m *mockAttachmentLinker) GetByMessageID(_ context.Context, messageID int64) ([]AttachmentInfo, error) {
return m.attachments[messageID], nil
}
func TestMessagingService_EnrichMessages(t *testing.T) {
svc, _ := newTestService(t)
ctx := context.Background()
// Send a parent message and replies to it.
parent, err := svc.SendMessage(ctx, "sender", "receiver", "parent message", SendOptions{Subject: "Enrich Test"})
if err != nil {
t.Fatalf("SendMessage (parent): %v", err)
}
replyTo := parent.ID
for i := 0; i < 3; i++ {
_, err := svc.SendMessage(ctx, "receiver", "sender", "reply", SendOptions{
Subject: "Enrich Test",
ReplyTo: &replyTo,
})
if err != nil {
t.Fatalf("SendMessage (reply %d): %v", i, err)
}
}
// Send a message with no replies.
noReplies, err := svc.SendMessage(ctx, "sender", "receiver", "standalone", SendOptions{Subject: "Enrich Standalone"})
if err != nil {
t.Fatalf("SendMessage (standalone): %v", err)
}
t.Run("reply counts populated", func(t *testing.T) {
msgs := []*Message{parent, noReplies}
svc.EnrichMessages(ctx, msgs)
if parent.ReplyCount != 3 {
t.Errorf("parent ReplyCount = %d, want 3", parent.ReplyCount)
}
if noReplies.ReplyCount != 0 {
t.Errorf("noReplies ReplyCount = %d, want 0", noReplies.ReplyCount)
}
})
t.Run("attachments populated when linker set", func(t *testing.T) {
linker := &mockAttachmentLinker{
attachments: map[int64][]AttachmentInfo{
parent.ID: {
{Hash: "abc123", OriginalFilename: "photo.png", Size: 1024, MIMEType: "image/png", IsImage: true},
},
},
}
svc.SetAttachmentLinker(linker)
// Reset enrichment state.
parent.ReplyCount = 0
parent.Attachments = nil
noReplies.ReplyCount = 0
noReplies.Attachments = nil
msgs := []*Message{parent, noReplies}
svc.EnrichMessages(ctx, msgs)
if parent.ReplyCount != 3 {
t.Errorf("parent ReplyCount = %d, want 3", parent.ReplyCount)
}
if len(parent.Attachments) != 1 {
t.Fatalf("parent Attachments count = %d, want 1", len(parent.Attachments))
}
if parent.Attachments[0].Hash != "abc123" {
t.Errorf("attachment hash = %s, want abc123", parent.Attachments[0].Hash)
}
if noReplies.Attachments != nil {
t.Errorf("noReplies Attachments should be nil, got %v", noReplies.Attachments)
}
})
t.Run("empty slice is a no-op", func(t *testing.T) {
svc.EnrichMessages(ctx, []*Message{})
// Should not panic or error.
})
}
// suppress unused import warning for storage package
var _ = storage.RunMigrations
+39
View File
@@ -39,6 +39,7 @@ type MessageStore interface {
GetLastReadForDM(ctx context.Context, agentNames []string, peerAgent string) (int64, error)
GetConversationIDsForChannel(ctx context.Context, channelID int64, lastMessageID int64) ([]int64, error)
GetConversationIDsForDM(ctx context.Context, agentNames []string, peerAgent string, lastMessageID int64) ([]int64, error)
GetReplyCounts(ctx context.Context, messageIDs []int64) (map[int64]int, error)
}
// SQLiteMessageStore implements MessageStore using SQLite.
@@ -1007,6 +1008,44 @@ func (s *SQLiteMessageStore) GetConversationIDsForDM(ctx context.Context, agentN
return ids, rows.Err()
}
// GetReplyCounts returns a map of message ID → reply count for the given IDs.
func (s *SQLiteMessageStore) GetReplyCounts(ctx context.Context, messageIDs []int64) (map[int64]int, error) {
if len(messageIDs) == 0 {
return map[int64]int{}, nil
}
placeholders := make([]string, len(messageIDs))
args := make([]any, len(messageIDs))
for i, id := range messageIDs {
placeholders[i] = "?"
args[i] = id
}
query := fmt.Sprintf(
`SELECT reply_to, COUNT(*) FROM messages
WHERE reply_to IN (%s)
GROUP BY reply_to`,
strings.Join(placeholders, ","),
)
rows, err := s.db.QueryContext(ctx, query, args...)
if err != nil {
return nil, fmt.Errorf("get reply counts: %w", err)
}
defer rows.Close()
counts := make(map[int64]int)
for rows.Next() {
var replyTo int64
var count int
if err := rows.Scan(&replyTo, &count); err != nil {
return nil, fmt.Errorf("scan reply count: %w", err)
}
counts[replyTo] = count
}
return counts, rows.Err()
}
// scanMessage scans a single message from sql.Row.
func scanMessage(row *sql.Row) (*Message, error) {
var msg Message
+126
View File
@@ -1027,6 +1027,132 @@ func TestSQLiteMessageStore_GetChannelMessages_Offset(t *testing.T) {
})
}
func TestSQLiteMessageStore_GetReplyCounts(t *testing.T) {
db := newTestDB(t)
store := NewSQLiteMessageStore(db)
ctx := context.Background()
seedAgent(t, db, "sender")
seedAgent(t, db, "replier")
conv := &Conversation{Subject: "reply counts", CreatedBy: "sender"}
if err := store.InsertConversation(ctx, conv); err != nil {
t.Fatalf("InsertConversation: %v", err)
}
// Insert parent message
parent := &Message{
ConversationID: conv.ID,
FromAgent: "sender",
ToAgent: "replier",
Body: "parent message",
Priority: 5,
Status: StatusPending,
}
if err := store.InsertMessage(ctx, parent); err != nil {
t.Fatalf("InsertMessage (parent): %v", err)
}
// Insert 3 replies to parent
for i := 0; i < 3; i++ {
reply := &Message{
ConversationID: conv.ID,
FromAgent: "replier",
ToAgent: "sender",
ReplyTo: &parent.ID,
Body: fmt.Sprintf("reply %d", i),
Priority: 5,
Status: StatusPending,
}
if err := store.InsertMessage(ctx, reply); err != nil {
t.Fatalf("InsertMessage (reply %d): %v", i, err)
}
}
t.Run("parent with 3 replies", func(t *testing.T) {
counts, err := store.GetReplyCounts(ctx, []int64{parent.ID})
if err != nil {
t.Fatalf("GetReplyCounts: %v", err)
}
if counts[parent.ID] != 3 {
t.Errorf("reply count for parent = %d, want 3", counts[parent.ID])
}
})
t.Run("message with no replies returns 0", func(t *testing.T) {
// Insert a message with no replies
noReply := &Message{
ConversationID: conv.ID,
FromAgent: "sender",
ToAgent: "replier",
Body: "no replies here",
Priority: 5,
Status: StatusPending,
}
if err := store.InsertMessage(ctx, noReply); err != nil {
t.Fatalf("InsertMessage (noReply): %v", err)
}
counts, err := store.GetReplyCounts(ctx, []int64{noReply.ID})
if err != nil {
t.Fatalf("GetReplyCounts: %v", err)
}
if counts[noReply.ID] != 0 {
t.Errorf("reply count for noReply = %d, want 0", counts[noReply.ID])
}
})
t.Run("multiple parents", func(t *testing.T) {
// Insert a second parent with 2 replies
parent2 := &Message{
ConversationID: conv.ID,
FromAgent: "sender",
ToAgent: "replier",
Body: "second parent",
Priority: 5,
Status: StatusPending,
}
if err := store.InsertMessage(ctx, parent2); err != nil {
t.Fatalf("InsertMessage (parent2): %v", err)
}
for i := 0; i < 2; i++ {
reply := &Message{
ConversationID: conv.ID,
FromAgent: "replier",
ToAgent: "sender",
ReplyTo: &parent2.ID,
Body: fmt.Sprintf("reply to parent2 %d", i),
Priority: 5,
Status: StatusPending,
}
if err := store.InsertMessage(ctx, reply); err != nil {
t.Fatalf("InsertMessage (parent2 reply %d): %v", i, err)
}
}
counts, err := store.GetReplyCounts(ctx, []int64{parent.ID, parent2.ID})
if err != nil {
t.Fatalf("GetReplyCounts: %v", err)
}
if counts[parent.ID] != 3 {
t.Errorf("reply count for parent = %d, want 3", counts[parent.ID])
}
if counts[parent2.ID] != 2 {
t.Errorf("reply count for parent2 = %d, want 2", counts[parent2.ID])
}
})
t.Run("empty slice returns empty map", func(t *testing.T) {
counts, err := store.GetReplyCounts(ctx, []int64{})
if err != nil {
t.Fatalf("GetReplyCounts: %v", err)
}
if len(counts) != 0 {
t.Errorf("expected empty map, got %v", counts)
}
})
}
func TestSQLiteMessageStore_CombinedFiltersAndPagination(t *testing.T) {
db := newTestDB(t)
store := NewSQLiteMessageStore(db)
+22
View File
@@ -14,6 +14,16 @@ const (
StatusFailed = "failed"
)
// AttachmentInfo is a lightweight attachment summary included in message responses.
// It avoids importing the attachments package into the messaging package.
type AttachmentInfo struct {
Hash string `json:"hash"`
OriginalFilename string `json:"original_filename"`
Size int64 `json:"size"`
MIMEType string `json:"mime_type"`
IsImage bool `json:"is_image"`
}
// Message represents a single message in the system.
type Message struct {
ID int64 `json:"id"`
@@ -30,6 +40,18 @@ type Message struct {
ClaimedAt *time.Time `json:"claimed_at,omitempty"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
ReplyCount int `json:"reply_count"`
Attachments []AttachmentInfo `json:"attachments,omitempty"`
WorkflowState string `json:"workflow_state,omitempty"`
Reactions []ReactionInfo `json:"reactions,omitempty"`
}
// ReactionInfo is a lightweight reaction summary included in message responses.
type ReactionInfo struct {
AgentName string `json:"agent_name"`
Reaction string `json:"reaction"`
Metadata json.RawMessage `json:"metadata,omitempty"`
CreatedAt time.Time `json:"created_at"`
}
// Conversation groups related messages into a thread.
+113
View File
@@ -0,0 +1,113 @@
// Package reactions provides message reaction types, storage, and workflow state logic.
package reactions
import (
"encoding/json"
"errors"
"time"
)
// Valid reaction types.
const (
ReactionApprove = "approve"
ReactionReject = "reject"
ReactionInProgress = "in_progress"
ReactionDone = "done"
ReactionPublished = "published"
)
// Workflow states (derived from reactions).
const (
StateProposed = "proposed"
StateApproved = "approved"
StateInProgress = "in_progress"
StateRejected = "rejected"
StateDone = "done"
StatePublished = "published"
)
// reactionPriority maps reaction types to their priority for state derivation.
// Higher number = higher priority = wins for badge display.
var reactionPriority = map[string]int{
ReactionApprove: 2,
ReactionInProgress: 3,
ReactionReject: 4,
ReactionDone: 5,
ReactionPublished: 6,
}
// reactionToState maps reaction types to workflow states.
var reactionToState = map[string]string{
ReactionApprove: StateApproved,
ReactionReject: StateRejected,
ReactionInProgress: StateInProgress,
ReactionDone: StateDone,
ReactionPublished: StatePublished,
}
// TerminalStates are states that should not trigger stalemate checks.
var TerminalStates = map[string]bool{
StateRejected: true,
StateDone: true,
StatePublished: true,
}
// MaxReactionsPerMessage is the safety limit.
const MaxReactionsPerMessage = 100
// Sentinel errors.
var (
ErrInvalidReaction = errors.New("invalid reaction type: must be one of approve, reject, in_progress, done, published")
ErrReactionLimit = errors.New("maximum reactions per message (100) reached")
ErrNotMember = errors.New("only channel members can react to messages")
)
// Reaction represents a single reaction on a message.
type Reaction struct {
ID int64 `json:"id"`
MessageID int64 `json:"message_id"`
AgentName string `json:"agent_name"`
Reaction string `json:"reaction"`
Metadata json.RawMessage `json:"metadata"`
CreatedAt time.Time `json:"created_at"`
}
// ValidReactions is the set of allowed reaction types.
var ValidReactions = map[string]bool{
ReactionApprove: true,
ReactionReject: true,
ReactionInProgress: true,
ReactionDone: true,
ReactionPublished: true,
}
// IsValidReaction returns true if the reaction type is valid.
func IsValidReaction(r string) bool {
return ValidReactions[r]
}
// ComputeWorkflowState derives the workflow state from a list of reactions.
// Returns "proposed" if no reactions exist.
func ComputeWorkflowState(reactions []*Reaction) string {
if len(reactions) == 0 {
return StateProposed
}
highestPriority := 0
highestState := StateProposed
for _, r := range reactions {
p, ok := reactionPriority[r.Reaction]
if ok && p > highestPriority {
highestPriority = p
highestState = reactionToState[r.Reaction]
}
}
return highestState
}
// IsTerminalState returns true if the state should not trigger stalemate checks.
func IsTerminalState(state string) bool {
return TerminalStates[state]
}
+150
View File
@@ -0,0 +1,150 @@
package reactions
import (
"testing"
)
func TestIsValidReaction(t *testing.T) {
tests := []struct {
name string
reaction string
want bool
}{
{"approve is valid", ReactionApprove, true},
{"reject is valid", ReactionReject, true},
{"in_progress is valid", ReactionInProgress, true},
{"done is valid", ReactionDone, true},
{"published is valid", ReactionPublished, true},
{"empty string is invalid", "", false},
{"thumbs_up is invalid", "thumbs_up", false},
{"like is invalid", "like", false},
{"APPROVE uppercase is invalid", "APPROVE", false},
{"random text is invalid", "foobar", false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := IsValidReaction(tt.reaction)
if got != tt.want {
t.Errorf("IsValidReaction(%q) = %v, want %v", tt.reaction, got, tt.want)
}
})
}
}
func TestComputeWorkflowState(t *testing.T) {
tests := []struct {
name string
reactions []*Reaction
want string
}{
{
name: "empty reactions returns proposed",
reactions: []*Reaction{},
want: StateProposed,
},
{
name: "nil reactions returns proposed",
reactions: nil,
want: StateProposed,
},
{
name: "single approve returns approved",
reactions: []*Reaction{
{Reaction: ReactionApprove, AgentName: "agent-a"},
},
want: StateApproved,
},
{
name: "approve + in_progress returns in_progress (higher priority wins)",
reactions: []*Reaction{
{Reaction: ReactionApprove, AgentName: "agent-a"},
{Reaction: ReactionInProgress, AgentName: "agent-b"},
},
want: StateInProgress,
},
{
name: "single reject returns rejected",
reactions: []*Reaction{
{Reaction: ReactionReject, AgentName: "agent-a"},
},
want: StateRejected,
},
{
name: "single done returns done",
reactions: []*Reaction{
{Reaction: ReactionDone, AgentName: "agent-a"},
},
want: StateDone,
},
{
name: "single published returns published",
reactions: []*Reaction{
{Reaction: ReactionPublished, AgentName: "agent-a"},
},
want: StatePublished,
},
{
name: "all five types - published wins",
reactions: []*Reaction{
{Reaction: ReactionApprove, AgentName: "agent-a"},
{Reaction: ReactionInProgress, AgentName: "agent-b"},
{Reaction: ReactionReject, AgentName: "agent-c"},
{Reaction: ReactionDone, AgentName: "agent-d"},
{Reaction: ReactionPublished, AgentName: "agent-e"},
},
want: StatePublished,
},
{
name: "published wins over everything",
reactions: []*Reaction{
{Reaction: ReactionDone, AgentName: "agent-a"},
{Reaction: ReactionReject, AgentName: "agent-b"},
{Reaction: ReactionPublished, AgentName: "agent-c"},
},
want: StatePublished,
},
{
name: "reject beats in_progress",
reactions: []*Reaction{
{Reaction: ReactionInProgress, AgentName: "agent-a"},
{Reaction: ReactionReject, AgentName: "agent-b"},
},
want: StateRejected,
},
{
name: "done beats reject",
reactions: []*Reaction{
{Reaction: ReactionReject, AgentName: "agent-a"},
{Reaction: ReactionDone, AgentName: "agent-b"},
},
want: StateDone,
},
{
name: "in_progress beats approve",
reactions: []*Reaction{
{Reaction: ReactionInProgress, AgentName: "agent-a"},
{Reaction: ReactionApprove, AgentName: "agent-b"},
},
want: StateInProgress,
},
{
name: "multiple approves still returns approved",
reactions: []*Reaction{
{Reaction: ReactionApprove, AgentName: "agent-a"},
{Reaction: ReactionApprove, AgentName: "agent-b"},
{Reaction: ReactionApprove, AgentName: "agent-c"},
},
want: StateApproved,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := ComputeWorkflowState(tt.reactions)
if got != tt.want {
t.Errorf("ComputeWorkflowState() = %q, want %q", got, tt.want)
}
})
}
}
+127
View File
@@ -0,0 +1,127 @@
package reactions
import (
"context"
"encoding/json"
"fmt"
"log/slog"
)
// Service provides business logic for message reactions.
type Service struct {
store Store
logger *slog.Logger
}
// NewService creates a new reaction service.
func NewService(store Store, logger *slog.Logger) *Service {
return &Service{
store: store,
logger: logger.With("component", "reactions"),
}
}
// ToggleResult describes what happened after a toggle operation.
type ToggleResult struct {
Action string `json:"action"` // "added" or "removed"
Reaction *Reaction `json:"reaction,omitempty"`
}
// Toggle adds a reaction if it doesn't exist, or removes it if it does.
// Returns the action taken and the reaction (if added).
func (s *Service) Toggle(ctx context.Context, messageID int64, agentName, reactionType string, metadata json.RawMessage) (*ToggleResult, error) {
if !IsValidReaction(reactionType) {
return nil, ErrInvalidReaction
}
// Check if reaction already exists
exists, err := s.store.Exists(ctx, messageID, agentName, reactionType)
if err != nil {
return nil, fmt.Errorf("check existing reaction: %w", err)
}
if exists {
// Toggle off — remove it
if err := s.store.Delete(ctx, messageID, agentName, reactionType); err != nil {
return nil, fmt.Errorf("remove reaction: %w", err)
}
s.logger.Info("reaction removed",
"message_id", messageID,
"agent", agentName,
"reaction", reactionType,
)
return &ToggleResult{Action: "removed"}, nil
}
// Check reaction count limit
count, err := s.store.CountByMessage(ctx, messageID)
if err != nil {
return nil, fmt.Errorf("count reactions: %w", err)
}
if count >= MaxReactionsPerMessage {
return nil, ErrReactionLimit
}
// Toggle on — add it
if metadata == nil {
metadata = json.RawMessage("{}")
}
r := &Reaction{
MessageID: messageID,
AgentName: agentName,
Reaction: reactionType,
Metadata: metadata,
}
if err := s.store.Insert(ctx, r); err != nil {
return nil, fmt.Errorf("add reaction: %w", err)
}
s.logger.Info("reaction added",
"message_id", messageID,
"agent", agentName,
"reaction", reactionType,
)
return &ToggleResult{Action: "added", Reaction: r}, nil
}
// Remove explicitly removes a reaction.
func (s *Service) Remove(ctx context.Context, messageID int64, agentName, reactionType string) error {
if !IsValidReaction(reactionType) {
return ErrInvalidReaction
}
if err := s.store.Delete(ctx, messageID, agentName, reactionType); err != nil {
return fmt.Errorf("remove reaction: %w", err)
}
s.logger.Info("reaction removed",
"message_id", messageID,
"agent", agentName,
"reaction", reactionType,
)
return nil
}
// GetReactions returns all reactions for a message and the computed workflow state.
func (s *Service) GetReactions(ctx context.Context, messageID int64) ([]*Reaction, string, error) {
reactions, err := s.store.GetByMessageID(ctx, messageID)
if err != nil {
return nil, "", fmt.Errorf("get reactions: %w", err)
}
state := ComputeWorkflowState(reactions)
return reactions, state, nil
}
// GetReactionsByMessageIDs returns reactions grouped by message ID.
func (s *Service) GetReactionsByMessageIDs(ctx context.Context, messageIDs []int64) (map[int64][]*Reaction, error) {
return s.store.GetByMessageIDs(ctx, messageIDs)
}
// ListByState returns message IDs in a channel that have the given workflow state.
func (s *Service) ListByState(ctx context.Context, channelID int64, state string) ([]int64, error) {
return s.store.GetMessageIDsByState(ctx, channelID, state)
}
+209
View File
@@ -0,0 +1,209 @@
package reactions
import (
"context"
"database/sql"
"encoding/json"
"fmt"
"strings"
)
// Store defines the storage interface for reactions.
type Store interface {
Insert(ctx context.Context, r *Reaction) error
Delete(ctx context.Context, messageID int64, agentName, reaction string) error
GetByMessageID(ctx context.Context, messageID int64) ([]*Reaction, error)
GetByMessageIDs(ctx context.Context, messageIDs []int64) (map[int64][]*Reaction, error)
Exists(ctx context.Context, messageID int64, agentName, reaction string) (bool, error)
CountByMessage(ctx context.Context, messageID int64) (int, error)
// GetMessageIDsByState returns message IDs in a channel that have the given workflow state.
GetMessageIDsByState(ctx context.Context, channelID int64, state string) ([]int64, error)
}
// SQLiteStore implements Store using SQLite.
type SQLiteStore struct {
db *sql.DB
}
// NewSQLiteStore creates a new SQLite-backed reaction store.
func NewSQLiteStore(db *sql.DB) *SQLiteStore {
return &SQLiteStore{db: db}
}
func (s *SQLiteStore) Insert(ctx context.Context, r *Reaction) error {
metadata := r.Metadata
if metadata == nil {
metadata = json.RawMessage("{}")
}
result, err := s.db.ExecContext(ctx,
`INSERT INTO message_reactions (message_id, agent_name, reaction, metadata, created_at)
VALUES (?, ?, ?, ?, CURRENT_TIMESTAMP)`,
r.MessageID, r.AgentName, r.Reaction, string(metadata),
)
if err != nil {
return fmt.Errorf("insert reaction: %w", err)
}
id, err := result.LastInsertId()
if err != nil {
return fmt.Errorf("get reaction id: %w", err)
}
r.ID = id
return nil
}
func (s *SQLiteStore) Delete(ctx context.Context, messageID int64, agentName, reaction string) error {
result, err := s.db.ExecContext(ctx,
`DELETE FROM message_reactions WHERE message_id = ? AND agent_name = ? AND reaction = ?`,
messageID, agentName, reaction,
)
if err != nil {
return fmt.Errorf("delete reaction: %w", err)
}
n, _ := result.RowsAffected()
if n == 0 {
return fmt.Errorf("reaction not found")
}
return nil
}
func (s *SQLiteStore) GetByMessageID(ctx context.Context, messageID int64) ([]*Reaction, error) {
rows, err := s.db.QueryContext(ctx,
`SELECT id, message_id, agent_name, reaction, metadata, created_at
FROM message_reactions WHERE message_id = ?
ORDER BY created_at ASC`, messageID,
)
if err != nil {
return nil, fmt.Errorf("get reactions: %w", err)
}
defer rows.Close()
return scanReactions(rows)
}
func (s *SQLiteStore) GetByMessageIDs(ctx context.Context, messageIDs []int64) (map[int64][]*Reaction, error) {
if len(messageIDs) == 0 {
return map[int64][]*Reaction{}, nil
}
placeholders := make([]string, len(messageIDs))
args := make([]any, len(messageIDs))
for i, id := range messageIDs {
placeholders[i] = "?"
args[i] = id
}
query := fmt.Sprintf(
`SELECT id, message_id, agent_name, reaction, metadata, created_at
FROM message_reactions WHERE message_id IN (%s)
ORDER BY created_at ASC`,
strings.Join(placeholders, ","),
)
rows, err := s.db.QueryContext(ctx, query, args...)
if err != nil {
return nil, fmt.Errorf("get reactions by ids: %w", err)
}
defer rows.Close()
all, err := scanReactions(rows)
if err != nil {
return nil, err
}
result := make(map[int64][]*Reaction)
for _, r := range all {
result[r.MessageID] = append(result[r.MessageID], r)
}
return result, nil
}
func (s *SQLiteStore) Exists(ctx context.Context, messageID int64, agentName, reaction string) (bool, error) {
var count int
err := s.db.QueryRowContext(ctx,
`SELECT COUNT(*) FROM message_reactions WHERE message_id = ? AND agent_name = ? AND reaction = ?`,
messageID, agentName, reaction,
).Scan(&count)
if err != nil {
return false, fmt.Errorf("check reaction exists: %w", err)
}
return count > 0, nil
}
func (s *SQLiteStore) CountByMessage(ctx context.Context, messageID int64) (int, error) {
var count int
err := s.db.QueryRowContext(ctx,
`SELECT COUNT(*) FROM message_reactions WHERE message_id = ?`, messageID,
).Scan(&count)
if err != nil {
return 0, fmt.Errorf("count reactions: %w", err)
}
return count, nil
}
func (s *SQLiteStore) GetMessageIDsByState(ctx context.Context, channelID int64, state string) ([]int64, error) {
var query string
var args []any
if state == StateProposed {
// Messages with no reactions
query = `SELECT m.id FROM messages m
WHERE m.channel_id = ?
AND NOT EXISTS (SELECT 1 FROM message_reactions r WHERE r.message_id = m.id)
ORDER BY m.created_at DESC`
args = []any{channelID}
} else {
// Find the reaction type for this state
var reactionType string
for rt, st := range reactionToState {
if st == state {
reactionType = rt
break
}
}
if reactionType == "" {
return nil, fmt.Errorf("unknown workflow state: %s", state)
}
// Messages where the highest-priority reaction maps to this state
// We get all messages with this reaction type and filter in app layer
query = `SELECT DISTINCT r.message_id FROM message_reactions r
JOIN messages m ON m.id = r.message_id
WHERE m.channel_id = ? AND r.reaction = ?
ORDER BY m.created_at DESC`
args = []any{channelID, reactionType}
}
rows, err := s.db.QueryContext(ctx, query, args...)
if err != nil {
return nil, fmt.Errorf("get message ids by state: %w", err)
}
defer rows.Close()
var ids []int64
for rows.Next() {
var id int64
if err := rows.Scan(&id); err != nil {
return nil, fmt.Errorf("scan message id: %w", err)
}
ids = append(ids, id)
}
return ids, rows.Err()
}
func scanReactions(rows *sql.Rows) ([]*Reaction, error) {
var reactions []*Reaction
for rows.Next() {
var r Reaction
var metadata string
err := rows.Scan(&r.ID, &r.MessageID, &r.AgentName, &r.Reaction, &metadata, &r.CreatedAt)
if err != nil {
return nil, fmt.Errorf("scan reaction: %w", err)
}
r.Metadata = json.RawMessage(metadata)
reactions = append(reactions, &r)
}
if reactions == nil {
reactions = []*Reaction{}
}
return reactions, rows.Err()
}
+332
View File
@@ -0,0 +1,332 @@
package reactions
import (
"context"
"database/sql"
"encoding/json"
"fmt"
"testing"
_ "modernc.org/sqlite"
"github.com/synapbus/synapbus/internal/storage"
)
func newTestDB(t *testing.T) *sql.DB {
t.Helper()
dsn := fmt.Sprintf("file:%s?mode=memory&cache=shared", t.Name())
db, err := sql.Open("sqlite", dsn)
if err != nil {
t.Fatalf("open database: %v", err)
}
t.Cleanup(func() { db.Close() })
if _, err := db.Exec("PRAGMA foreign_keys=ON"); err != nil {
t.Fatalf("enable foreign keys: %v", err)
}
ctx := context.Background()
if err := storage.RunMigrations(ctx, db); err != nil {
t.Fatalf("run migrations: %v", err)
}
return db
}
// seedTestMessage creates a test user, agent, conversation, and message,
// returning the message ID.
func seedTestMessage(t *testing.T, db *sql.DB, agentName string) int64 {
t.Helper()
// Ensure user exists
db.Exec(`INSERT OR IGNORE INTO users (id, username, password_hash, display_name) VALUES (1, 'testowner', 'hash', 'Test Owner')`)
// Ensure agent exists
_, err := db.Exec(
`INSERT OR IGNORE INTO agents (name, display_name, type, capabilities, owner_id, api_key_hash, status) VALUES (?, ?, 'ai', '{}', 1, 'testhash', 'active')`,
agentName, agentName,
)
if err != nil {
t.Fatalf("seed agent %s: %v", agentName, err)
}
// Create conversation
result, err := db.Exec(
`INSERT INTO conversations (subject, created_by, created_at, updated_at) VALUES ('test', ?, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)`,
agentName,
)
if err != nil {
t.Fatalf("create conversation: %v", err)
}
convID, _ := result.LastInsertId()
// Create message
result, err = db.Exec(
`INSERT INTO messages (conversation_id, from_agent, body, priority, status, created_at) VALUES (?, ?, 'test body', 5, 'pending', CURRENT_TIMESTAMP)`,
convID, agentName,
)
if err != nil {
t.Fatalf("create message: %v", err)
}
msgID, _ := result.LastInsertId()
return msgID
}
func TestSQLiteStore_InsertAndGet(t *testing.T) {
db := newTestDB(t)
store := NewSQLiteStore(db)
ctx := context.Background()
msgID := seedTestMessage(t, db, "agent-a")
r := &Reaction{
MessageID: msgID,
AgentName: "agent-a",
Reaction: ReactionApprove,
Metadata: json.RawMessage(`{"comment":"looks good"}`),
}
if err := store.Insert(ctx, r); err != nil {
t.Fatalf("Insert: %v", err)
}
if r.ID == 0 {
t.Error("reaction ID should not be 0 after insert")
}
// Verify it exists
exists, err := store.Exists(ctx, msgID, "agent-a", ReactionApprove)
if err != nil {
t.Fatalf("Exists: %v", err)
}
if !exists {
t.Error("expected reaction to exist after insert")
}
// GetByMessageID
reactions, err := store.GetByMessageID(ctx, msgID)
if err != nil {
t.Fatalf("GetByMessageID: %v", err)
}
if len(reactions) != 1 {
t.Fatalf("got %d reactions, want 1", len(reactions))
}
if reactions[0].AgentName != "agent-a" {
t.Errorf("AgentName = %q, want %q", reactions[0].AgentName, "agent-a")
}
if reactions[0].Reaction != ReactionApprove {
t.Errorf("Reaction = %q, want %q", reactions[0].Reaction, ReactionApprove)
}
if string(reactions[0].Metadata) != `{"comment":"looks good"}` {
t.Errorf("Metadata = %s, want %s", reactions[0].Metadata, `{"comment":"looks good"}`)
}
}
func TestSQLiteStore_UniqueConstraint(t *testing.T) {
db := newTestDB(t)
store := NewSQLiteStore(db)
ctx := context.Background()
msgID := seedTestMessage(t, db, "agent-a")
r := &Reaction{
MessageID: msgID,
AgentName: "agent-a",
Reaction: ReactionApprove,
}
if err := store.Insert(ctx, r); err != nil {
t.Fatalf("Insert first: %v", err)
}
// Inserting the same reaction again should fail with UNIQUE constraint
r2 := &Reaction{
MessageID: msgID,
AgentName: "agent-a",
Reaction: ReactionApprove,
}
err := store.Insert(ctx, r2)
if err == nil {
t.Error("expected error on duplicate insert, got nil")
}
}
func TestSQLiteStore_Delete(t *testing.T) {
db := newTestDB(t)
store := NewSQLiteStore(db)
ctx := context.Background()
msgID := seedTestMessage(t, db, "agent-a")
r := &Reaction{
MessageID: msgID,
AgentName: "agent-a",
Reaction: ReactionApprove,
}
if err := store.Insert(ctx, r); err != nil {
t.Fatalf("Insert: %v", err)
}
// Delete the reaction
if err := store.Delete(ctx, msgID, "agent-a", ReactionApprove); err != nil {
t.Fatalf("Delete: %v", err)
}
// Verify it's gone
exists, err := store.Exists(ctx, msgID, "agent-a", ReactionApprove)
if err != nil {
t.Fatalf("Exists: %v", err)
}
if exists {
t.Error("expected reaction to not exist after delete")
}
// Deleting a non-existent reaction should return an error
err = store.Delete(ctx, msgID, "agent-a", ReactionApprove)
if err == nil {
t.Error("expected error when deleting non-existent reaction, got nil")
}
}
func TestSQLiteStore_GetByMessageID(t *testing.T) {
db := newTestDB(t)
store := NewSQLiteStore(db)
ctx := context.Background()
msgID := seedTestMessage(t, db, "agent-a")
// Seed a second agent
db.Exec(`INSERT OR IGNORE INTO agents (name, display_name, type, capabilities, owner_id, api_key_hash, status) VALUES ('agent-b', 'agent-b', 'ai', '{}', 1, 'testhash2', 'active')`)
// Insert multiple reactions from different agents
reactions := []*Reaction{
{MessageID: msgID, AgentName: "agent-a", Reaction: ReactionApprove},
{MessageID: msgID, AgentName: "agent-b", Reaction: ReactionInProgress},
{MessageID: msgID, AgentName: "agent-a", Reaction: ReactionDone},
}
for _, r := range reactions {
if err := store.Insert(ctx, r); err != nil {
t.Fatalf("Insert: %v", err)
}
}
got, err := store.GetByMessageID(ctx, msgID)
if err != nil {
t.Fatalf("GetByMessageID: %v", err)
}
if len(got) != 3 {
t.Fatalf("got %d reactions, want 3", len(got))
}
// Verify results are ordered by created_at ASC
for i, r := range got {
if r.ID == 0 {
t.Errorf("reaction[%d] ID should not be 0", i)
}
if r.MessageID != msgID {
t.Errorf("reaction[%d] MessageID = %d, want %d", i, r.MessageID, msgID)
}
}
// Test with a message that has no reactions
msgID2 := seedTestMessage(t, db, "agent-a")
got2, err := store.GetByMessageID(ctx, msgID2)
if err != nil {
t.Fatalf("GetByMessageID (empty): %v", err)
}
if len(got2) != 0 {
t.Errorf("got %d reactions for empty message, want 0", len(got2))
}
}
func TestSQLiteStore_CountByMessage(t *testing.T) {
db := newTestDB(t)
store := NewSQLiteStore(db)
ctx := context.Background()
msgID := seedTestMessage(t, db, "agent-a")
db.Exec(`INSERT OR IGNORE INTO agents (name, display_name, type, capabilities, owner_id, api_key_hash, status) VALUES ('agent-b', 'agent-b', 'ai', '{}', 1, 'testhash2', 'active')`)
// Count should be 0 initially
count, err := store.CountByMessage(ctx, msgID)
if err != nil {
t.Fatalf("CountByMessage: %v", err)
}
if count != 0 {
t.Errorf("initial count = %d, want 0", count)
}
// Insert some reactions
for _, r := range []*Reaction{
{MessageID: msgID, AgentName: "agent-a", Reaction: ReactionApprove},
{MessageID: msgID, AgentName: "agent-b", Reaction: ReactionDone},
} {
if err := store.Insert(ctx, r); err != nil {
t.Fatalf("Insert: %v", err)
}
}
count, err = store.CountByMessage(ctx, msgID)
if err != nil {
t.Fatalf("CountByMessage: %v", err)
}
if count != 2 {
t.Errorf("count = %d, want 2", count)
}
// Delete one and verify count decreases
if err := store.Delete(ctx, msgID, "agent-a", ReactionApprove); err != nil {
t.Fatalf("Delete: %v", err)
}
count, err = store.CountByMessage(ctx, msgID)
if err != nil {
t.Fatalf("CountByMessage after delete: %v", err)
}
if count != 1 {
t.Errorf("count after delete = %d, want 1", count)
}
}
func TestSQLiteStore_GetByMessageIDs(t *testing.T) {
db := newTestDB(t)
store := NewSQLiteStore(db)
ctx := context.Background()
msgID1 := seedTestMessage(t, db, "agent-a")
msgID2 := seedTestMessage(t, db, "agent-a")
// Add reactions to msg1
if err := store.Insert(ctx, &Reaction{MessageID: msgID1, AgentName: "agent-a", Reaction: ReactionApprove}); err != nil {
t.Fatalf("Insert: %v", err)
}
if err := store.Insert(ctx, &Reaction{MessageID: msgID1, AgentName: "agent-a", Reaction: ReactionDone}); err != nil {
t.Fatalf("Insert: %v", err)
}
// Add reaction to msg2
if err := store.Insert(ctx, &Reaction{MessageID: msgID2, AgentName: "agent-a", Reaction: ReactionReject}); err != nil {
t.Fatalf("Insert: %v", err)
}
result, err := store.GetByMessageIDs(ctx, []int64{msgID1, msgID2})
if err != nil {
t.Fatalf("GetByMessageIDs: %v", err)
}
if len(result[msgID1]) != 2 {
t.Errorf("msg1 reactions = %d, want 2", len(result[msgID1]))
}
if len(result[msgID2]) != 1 {
t.Errorf("msg2 reactions = %d, want 1", len(result[msgID2]))
}
// Empty slice returns empty map
result, err = store.GetByMessageIDs(ctx, []int64{})
if err != nil {
t.Fatalf("GetByMessageIDs (empty): %v", err)
}
if len(result) != 0 {
t.Errorf("expected empty map, got %v", result)
}
}
+21
View File
@@ -0,0 +1,21 @@
-- Message reactions for workflow state tracking
-- Supports: approve, reject, in_progress, done, published
CREATE TABLE IF NOT EXISTS message_reactions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
message_id INTEGER NOT NULL REFERENCES messages(id) ON DELETE CASCADE,
agent_name TEXT NOT NULL,
reaction TEXT NOT NULL CHECK(reaction IN ('approve', 'reject', 'in_progress', 'done', 'published')),
metadata TEXT NOT NULL DEFAULT '{}',
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
UNIQUE(message_id, agent_name, reaction)
);
CREATE INDEX idx_reactions_message ON message_reactions(message_id);
CREATE INDEX idx_reactions_agent ON message_reactions(agent_name);
CREATE INDEX idx_reactions_type ON message_reactions(reaction);
-- Channel workflow settings
ALTER TABLE channels ADD COLUMN auto_approve BOOLEAN NOT NULL DEFAULT 0;
ALTER TABLE channels ADD COLUMN stalemate_remind_after TEXT NOT NULL DEFAULT '24h';
ALTER TABLE channels ADD COLUMN stalemate_escalate_after TEXT NOT NULL DEFAULT '72h';
+11 -11
View File
@@ -11,30 +11,30 @@
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;600;700&family=Instrument+Sans:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet">
<link href="/_app/immutable/entry/start.BuSotqBe.js" rel="modulepreload">
<link href="/_app/immutable/chunks/CoA7yCjK.js" rel="modulepreload">
<link href="/_app/immutable/entry/start.aUyT-hXz.js" rel="modulepreload">
<link href="/_app/immutable/chunks/B2ehjvNA.js" rel="modulepreload">
<link href="/_app/immutable/chunks/BjgrqnN-.js" rel="modulepreload">
<link href="/_app/immutable/chunks/CAWWRzNH.js" rel="modulepreload">
<link href="/_app/immutable/chunks/B-GqcZrE.js" rel="modulepreload">
<link href="/_app/immutable/chunks/DpGxxGDS.js" rel="modulepreload">
<link href="/_app/immutable/chunks/3PInzq4O.js" rel="modulepreload">
<link href="/_app/immutable/chunks/qakGnb92.js" rel="modulepreload">
<link href="/_app/immutable/entry/app.B5srta30.js" rel="modulepreload">
<link href="/_app/immutable/chunks/DFRGYO_X.js" rel="modulepreload">
<link href="/_app/immutable/chunks/0x2jFCf0.js" rel="modulepreload">
<link href="/_app/immutable/chunks/C3nS3byM.js" rel="modulepreload">
<link href="/_app/immutable/chunks/C1Y8Vas-.js" rel="modulepreload">
<link href="/_app/immutable/chunks/Bs4ZECIt.js" rel="modulepreload">
<link href="/_app/immutable/entry/app.uuaq_5nO.js" rel="modulepreload">
</head>
<body data-sveltekit-preload-data="hover">
<div style="display: contents">
<script>
{
__sveltekit_1blyclv = {
__sveltekit_1mlsoop = {
base: ""
};
const element = document.currentScript.parentElement;
Promise.all([
import("/_app/immutable/entry/start.BuSotqBe.js"),
import("/_app/immutable/entry/app.B5srta30.js")
import("/_app/immutable/entry/start.aUyT-hXz.js"),
import("/_app/immutable/entry/app.uuaq_5nO.js")
]).then(([kit, app]) => {
kit.start(app, element);
});
+11
View File
@@ -0,0 +1,11 @@
{
"$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json",
"name": "io.github.synapbus/synapbus",
"description": "MCP-native agent-to-agent messaging hub with channels, DMs, and semantic search",
"repository": {
"url": "https://github.com/synapbus/synapbus",
"source": "github"
},
"version": "0.7.0",
"packages": []
}
@@ -0,0 +1,37 @@
# Specification Quality Checklist: Attachments & Threads Enhancement
**Purpose**: Validate specification completeness and quality before proceeding to planning
**Created**: 2026-03-17
**Feature**: [spec.md](../spec.md)
## Content Quality
- [x] No implementation details (languages, frameworks, APIs)
- [x] Focused on user value and business needs
- [x] Written for non-technical stakeholders
- [x] All mandatory sections completed
## Requirement Completeness
- [x] No [NEEDS CLARIFICATION] markers remain
- [x] Requirements are testable and unambiguous
- [x] Success criteria are measurable
- [x] Success criteria are technology-agnostic (no implementation details)
- [x] All acceptance scenarios are defined
- [x] Edge cases are identified
- [x] Scope is clearly bounded
- [x] Dependencies and assumptions identified
## Feature Readiness
- [x] All functional requirements have clear acceptance criteria
- [x] User scenarios cover primary flows
- [x] Feature meets measurable outcomes defined in Success Criteria
- [x] No implementation details leak into specification
## Notes
- All items pass validation. Spec is ready for `/speckit.plan`.
- Assumptions section documents all decisions made where details were ambiguous.
- 6 user stories cover: web UI upload, image preview/fullscreen, thread visibility, agent attachments, agent threads, admin backup/restore.
- 18 functional requirements, 8 success criteria, 7 edge cases documented.
@@ -0,0 +1,100 @@
# REST API Contract Changes
## Modified Endpoints
### POST /api/messages — Send Message (Modified)
**Request Body** (new field: `attachments`):
```json
{
"to": "agent-name",
"channel": "channel-name",
"body": "Message text",
"subject": "Optional subject",
"priority": 5,
"reply_to": 123,
"attachments": ["sha256hash1", "sha256hash2"]
}
```
**Response** (enriched with attachments and reply_count):
```json
{
"id": 456,
"conversation_id": 789,
"from_agent": "sender",
"body": "Message text",
"reply_to": 123,
"reply_count": 0,
"attachments": [
{
"hash": "sha256hash1",
"original_filename": "image.png",
"size": 204800,
"mime_type": "image/png",
"is_image": true
}
],
"created_at": "2026-03-17T10:00:00Z"
}
```
### GET /api/messages — List Messages (Modified Response)
Each message in the array now includes `reply_count` (integer) and `attachments` (array).
### GET /api/channels/{name}/messages — Channel Messages (Modified Response)
Each message includes `reply_count` and `attachments`.
### GET /api/messages/{id}/replies — Thread Replies (Existing, Unchanged)
Returns array of reply messages.
## Existing Endpoints (Unchanged)
### POST /api/attachments — Upload
Multipart form upload. Returns hash, size, mime_type, filename.
### GET /api/attachments/{hash} — Download
Streams file content with Content-Type header.
### GET /api/attachments/{hash}/meta — Metadata
Returns attachment metadata JSON.
## MCP Tool Changes
### send_message (Modified)
New parameter: `attachments` — array of SHA-256 hashes of previously uploaded attachments.
Updated description for `reply_to`: "ID of the parent message to reply to. Creates a threaded reply. Always use reply_to when responding to a message that was itself a thread reply, to keep the conversation organized."
### upload_attachment (Existing)
No changes. Parameters: content (base64), filename, mime_type, message_id.
### download_attachment (Existing)
No changes. Parameter: hash.
## Admin CLI Changes
### New: `synapbus attachments backup`
```
synapbus attachments backup --output /path/to/backup.tar.gz [--socket /path/to/socket]
```
Creates tar.gz of attachment storage directory.
### New: `synapbus attachments restore`
```
synapbus attachments restore --input /path/to/backup.tar.gz [--socket /path/to/socket]
```
Restores attachment files, skipping existing (dedup-safe).
+119
View File
@@ -0,0 +1,119 @@
# Data Model: Attachments & Threads Enhancement
**Branch**: `009-attachments-threads` | **Date**: 2026-03-17
## Entity Changes
### Message (Modified)
Existing table `messages` — already has `reply_to` column via migration 007.
**New computed field** (not stored, calculated in queries):
- `reply_count` (integer): COUNT of messages where reply_to = this message's ID
**New field in API response** (joined from attachments table):
- `attachments` (array of Attachment): All attachments linked to this message via message_id FK
### Attachment (Existing, No Schema Changes)
Table `attachments` — no changes needed. Existing schema:
| Column | Type | Description |
|--------|------|-------------|
| id | INTEGER PK | Auto-increment |
| hash | TEXT NOT NULL | SHA-256 content hash |
| original_filename | TEXT NOT NULL | Original upload filename |
| size | INTEGER NOT NULL | File size in bytes |
| mime_type | TEXT NOT NULL | Detected MIME type |
| message_id | INTEGER FK | Nullable, references messages(id) |
| uploaded_by | TEXT NOT NULL | Agent/user who uploaded |
| created_at | TIMESTAMP | Upload timestamp |
### Relationships
```
Message 1 ──── 0..* Attachment (via attachment.message_id)
Message 1 ──── 0..* Message (via message.reply_to → parent message.id)
```
## Query Changes
### Message List with Reply Count
```sql
SELECT m.*,
COALESCE(rc.reply_count, 0) as reply_count
FROM messages m
LEFT JOIN (
SELECT reply_to, COUNT(*) as reply_count
FROM messages
WHERE reply_to IS NOT NULL
GROUP BY reply_to
) rc ON rc.reply_to = m.id
WHERE ...
```
### Message with Attachments
```sql
SELECT a.id, a.hash, a.original_filename, a.size, a.mime_type, a.created_at
FROM attachments a
WHERE a.message_id = ?
ORDER BY a.created_at ASC
```
### Thread Replies
Already exists in store.go:
```sql
SELECT ... FROM messages WHERE reply_to = ? ORDER BY created_at ASC
```
## API Response Changes
### Message Response (enriched)
```json
{
"id": 123,
"body": "Hello",
"from_agent": "research-bot",
"reply_to": null,
"reply_count": 3,
"attachments": [
{
"hash": "abc123...",
"original_filename": "report.pdf",
"size": 1048576,
"mime_type": "application/pdf",
"is_image": false
}
]
}
```
### Send Message Request (enriched)
```json
{
"to": "agent-name",
"body": "See attached report",
"reply_to": 456,
"attachments": ["abc123...", "def456..."]
}
```
## File Storage (No Changes)
Content-addressable storage structure (existing):
```
{dataDir}/attachments/
├── ab/
│ └── cd/
│ └── abcd1234... (full SHA-256 hash as filename)
├── ef/
│ └── 01/
│ └── ef012345...
```
Backup archive mirrors this structure in tar.gz format.
+106
View File
@@ -0,0 +1,106 @@
# Implementation Plan: Attachments & Threads Enhancement
**Branch**: `009-attachments-threads` | **Date**: 2026-03-17 | **Spec**: [spec.md](spec.md)
**Input**: Feature specification from `/specs/009-attachments-threads/spec.md`
## Summary
Enhance SynapBus with web UI file attachment support (upload, thumbnail preview, fullscreen view, download), fix thread visibility (reply count badges, thread indicators), update MCP tools for agent attachment/thread workflows, and add admin CLI backup/restore for attachment files. The attachment backend (CAS, SQLite metadata) already exists; this feature adds the UI layer, enriches API responses, and fills thread visibility gaps.
## Technical Context
**Language/Version**: Go 1.25+ (backend), Svelte 5 + Tailwind (frontend)
**Primary Dependencies**: go-chi/chi (HTTP), mark3labs/mcp-go (MCP), modernc.org/sqlite (storage), spf13/cobra (CLI)
**Storage**: SQLite (modernc.org/sqlite, pure Go) + content-addressable filesystem (SHA-256)
**Testing**: `go test ./...` (backend), manual + curl (API), Chrome (UI)
**Target Platform**: linux/amd64, darwin/arm64 (cross-compiled single binary)
**Project Type**: Web service with embedded SPA
**Performance Goals**: File uploads complete in <10s for files under 10MB; thumbnails render in <1s
**Constraints**: Zero CGO, single binary, single --data directory
**Scale/Scope**: LAN-scale (tens of agents, hundreds of messages/day)
## Constitution Check
*GATE: Must pass before Phase 0 research. Re-check after Phase 1 design.*
| Principle | Status | Notes |
|-----------|--------|-------|
| I. Local-First, Single Binary | PASS | All changes are within the single binary. No external dependencies added. |
| II. MCP-Native | PASS | Agent attachment/thread workflows use MCP tools. REST API changes are for Web UI only. |
| III. Pure Go, Zero CGO | PASS | No new CGO dependencies. Image thumbnails are CSS-only (client-side). Backup uses stdlib archive/tar + compress/gzip. |
| IV. Multi-Tenant with Ownership | PASS | Attachments track uploaded_by. Message ownership unchanged. |
| V. Embedded OAuth 2.1 | N/A | No auth changes. |
| VI. Semantic-Ready Storage | N/A | No search changes. |
| VII. Swarm Intelligence | N/A | No swarm pattern changes. |
| VIII. Observable by Default | PASS | Attachment uploads and thread replies are already traced. |
| IX. Progressive Complexity | PASS | Attachments are tier 3 (advanced). Thread fixes improve existing basic messaging. |
| X. Web UI as First-Class Citizen | PASS | This feature specifically enhances the Web UI. |
**Post-design re-check**: All principles still satisfied. No violations.
## Project Structure
### Documentation (this feature)
```text
specs/009-attachments-threads/
├── plan.md # This file
├── spec.md # Feature specification
├── research.md # Research decisions
├── data-model.md # Data model changes
├── quickstart.md # Testing quickstart
├── contracts/ # API contract changes
│ └── rest-api.md
├── checklists/
│ └── requirements.md
└── tasks.md # Task breakdown (generated by /speckit.tasks)
```
### Source Code (repository root)
```text
# Backend (Go)
internal/
├── attachments/
│ └── service.go # Add file type validation
├── messaging/
│ ├── store.go # Add reply_count to queries, attachment loading
│ ├── service.go # Add attachment linking on send
│ └── types.go # Add ReplyCount, Attachments fields to Message
├── api/
│ ├── messages_handler.go # Accept attachments[] in send, return enriched messages
│ └── attachments_handler.go # (existing, minimal changes)
└── mcp/
├── tools_hybrid.go # Add attachments param, update descriptions
└── bridge.go # Handle attachments in send flow
cmd/synapbus/
└── admin.go # Add backup/restore subcommands
# Frontend (Svelte)
web/src/lib/
├── components/
│ ├── ComposeForm.svelte # Add attachment upload button + preview
│ ├── MessageList.svelte # Add thread indicator badges
│ ├── MessageBody.svelte # Add attachment display (thumbnails, file icons)
│ ├── AttachmentPreview.svelte # NEW: thumbnail + fullscreen component
│ └── ThreadPanel.svelte # Existing, minor fixes
├── stores/
│ └── thread.ts # Existing, no changes
└── api/
└── client.ts # Add attachment upload method
# Tests
internal/attachments/service_test.go # File type validation tests
internal/messaging/store_test.go # Reply count query tests
internal/messaging/service_test.go # Attachment linking tests
internal/api/messages_handler_test.go # API enrichment tests
internal/mcp/tools_hybrid_test.go # MCP attachment param tests
cmd/synapbus/admin_test.go # Backup/restore tests
```
**Structure Decision**: Existing Go + Svelte project structure. No new packages needed — all changes extend existing packages. One new Svelte component (AttachmentPreview.svelte) for image thumbnail/fullscreen display.
## Complexity Tracking
No constitution violations. No complexity justifications needed.
+126
View File
@@ -0,0 +1,126 @@
# Quickstart: Attachments & Threads Enhancement
## Prerequisites
- Go 1.23+ installed
- Node.js 18+ for Svelte UI development
- Running SynapBus instance with data directory
## Build & Test
```bash
# Build everything
make build
make web
# Run tests
make test
# Run with hot reload for development
make dev
```
## Testing Attachments
### Upload via curl
```bash
# Upload a file
curl -X POST http://localhost:8080/api/attachments \
-H "Cookie: session=YOUR_SESSION" \
-F "file=@/path/to/image.png"
# Response: {"hash": "abc123...", "size": 204800, "mime_type": "image/png", "original_filename": "image.png"}
```
### Send message with attachment
```bash
curl -X POST http://localhost:8080/api/messages \
-H "Cookie: session=YOUR_SESSION" \
-H "Content-Type: application/json" \
-d '{
"channel": "general",
"body": "Check this image",
"attachments": ["abc123..."]
}'
```
### Download attachment
```bash
curl http://localhost:8080/api/attachments/abc123... -o downloaded.png
```
## Testing Threads
### Send a reply
```bash
# Send initial message
curl -X POST http://localhost:8080/api/messages \
-H "Cookie: session=YOUR_SESSION" \
-H "Content-Type: application/json" \
-d '{"channel": "general", "body": "Original message"}'
# Reply to message ID 123
curl -X POST http://localhost:8080/api/messages \
-H "Cookie: session=YOUR_SESSION" \
-H "Content-Type: application/json" \
-d '{"channel": "general", "body": "Thread reply", "reply_to": 123}'
```
### View thread replies
```bash
curl http://localhost:8080/api/messages/123/replies \
-H "Cookie: session=YOUR_SESSION"
```
## Testing via MCP
### Upload attachment (MCP)
```json
{
"action": "upload_attachment",
"args": {
"content": "<base64-encoded-data>",
"filename": "report.pdf",
"mime_type": "application/pdf"
}
}
```
### Send message with attachment and reply_to (MCP)
```json
{
"tool": "send_message",
"args": {
"channel": "general",
"body": "See attached report",
"reply_to": 123,
"attachments": ["abc123..."]
}
}
```
## Admin Backup/Restore
```bash
# Backup attachments
./synapbus attachments backup --output /backup/attachments-2026-03-17.tar.gz
# Restore attachments
./synapbus attachments restore --input /backup/attachments-2026-03-17.tar.gz
```
## Web UI
1. Open http://localhost:8080 and log in
2. Navigate to a channel
3. Click the paperclip icon in the compose area to attach a file
4. Send a message — attached images show as thumbnails
5. Click a thumbnail to see fullscreen view
6. Messages with replies show "N replies" badge — click to open thread panel
+70
View File
@@ -0,0 +1,70 @@
# Research: Attachments & Threads Enhancement
**Branch**: `009-attachments-threads` | **Date**: 2026-03-17
## Decision 1: Migration Location for reply_to
**Decision**: Migration `007_threads.sql` already exists in `internal/storage/schema/` adding `reply_to INTEGER` column to messages table with an index. No new migration needed for the column itself.
**Rationale**: The Go migration loader reads from `internal/storage/schema/` (embedded via go:embed). The `schema/` directory at repo root is for documentation/reference. The column already exists in the running system.
**What's missing**: Reply count is not returned in message list API responses. Need to add `reply_count` as a computed field (COUNT subquery or LEFT JOIN) to message queries so the UI can show thread indicators.
## Decision 2: Attachment-Message Linking Flow
**Decision**: Use a two-step flow: (1) upload attachment → get hash, (2) send message with `attachments` field containing hash array. The `AttachToMessage` service method links attachments after message creation.
**Rationale**: The existing upload endpoint returns a hash. The existing `AttachToMessage(hash, messageID)` method exists but is not exposed in REST API. Need to:
1. Add `attachments` field to the send message API request
2. After message insert, call `AttachToMessage` for each hash
3. Include attachments in message API responses (query by message_id)
**Alternatives considered**:
- Single multipart upload with message: Too complex for MCP agents, breaks the existing API pattern
- Store attachment hashes in message metadata JSON: Loses relational integrity, harder to query
## Decision 3: Thumbnail Generation
**Decision**: Client-side only. Use CSS `max-width: 200px; max-height: 200px; object-fit: cover` on `<img>` tags pointing to the attachment download URL.
**Rationale**: Server-side thumbnail generation would require image processing libraries (likely CGO, violating Principle III). The original images are served directly; the browser handles resizing. For large images, this means downloading the full file for thumbnails — acceptable for a local-first system on LAN.
**Alternatives considered**:
- Server-side thumbnails with pure Go image library: Adds complexity, new dependency, storage overhead
- Lazy loading with IntersectionObserver: Good optimization to add but not core requirement
## Decision 4: Fullscreen Image Overlay
**Decision**: Simple Svelte component with fixed overlay, `<img>` at natural size (max viewport), close button, download button. Dismiss via Escape, click outside, or close button.
**Rationale**: Minimal implementation that meets requirements. No carousel needed (one image at a time). No zoom/pan needed for v1.
## Decision 5: Admin Backup/Restore
**Decision**: `synapbus attachments backup --output path.tar.gz` and `synapbus attachments restore --input path.tar.gz`. Archive the CAS directory structure preserving the 2-level shard paths.
**Rationale**: The CAS directory is self-contained (`{dataDir}/attachments/`). tar.gz preserves directory structure and is universally supported. Restore skips existing files (same hash = same content = dedup).
**Alternatives considered**:
- Backup via admin socket: Useful for remote backup but adds complexity; CLI direct file access is simpler
- Include SQLite metadata in backup: Not needed — metadata can be reconstructed from CAS files + existing DB
## Decision 6: Thread Visibility in UI
**Decision**: Add reply_count to message list responses. Show a clickable "N replies" badge below messages. Clicking opens ThreadPanel. ThreadPanel already exists and works (loads conversation, supports replying).
**Rationale**: The ThreadPanel already handles thread display and replying. The missing piece is the reply_count in the message list so users know threads exist. The "View thread" button exists in MessageList but only on hover — need to make it always visible when reply_count > 0.
## Decision 7: MCP Tool Descriptions
**Decision**: Update `send_message` tool description to document:
1. `reply_to` parameter: "ID of the parent message to reply to. Creates a threaded reply. Always use this when responding to a message that is part of a thread."
2. `attachments` parameter (new): "Array of attachment hashes to link to this message. Upload attachments first using the upload_attachment action."
**Rationale**: Agents need clear tool descriptions to know how to use threading and attachments. The current reply_to description is minimal.
## Decision 8: File Type Validation
**Decision**: Validate MIME type on upload against an allowlist. Supported: image/*, application/pdf, text/*. Reject everything else with a clear error message listing supported types.
**Rationale**: Security best practice — don't allow arbitrary file uploads. The existing MIME detection in `mime.go` already handles type detection; just need to add validation in the upload handler.
+174
View File
@@ -0,0 +1,174 @@
# Feature Specification: Attachments & Threads Enhancement
**Feature Branch**: `009-attachments-threads`
**Created**: 2026-03-17
**Status**: Draft
**Input**: User description: "Add file attachment support to web UI and MCP tools, fix thread visibility issues, add admin CLI backup/restore for attachments"
## Assumptions
- Max file size: 50 MB (already enforced in existing backend)
- Supported attachment types: images (jpg, png, gif, webp, svg), PDFs, text files (txt, md, csv, json, xml, yaml, log)
- Image thumbnails: 200x200px maximum CSS constraint, rendered client-side from original image (no server-side thumbnail generation)
- Fullscreen image viewer: CSS overlay with close button and download link, dismissed by clicking outside or pressing Escape
- Thread indicator: Badge on parent message showing reply count; clicking it opens the thread panel
- `reply_to` column: nullable integer foreign key referencing `messages(id)` in a new migration
- Attachment backup format: tar.gz archive of the content-addressable storage directory
- MCP tool descriptions will be updated to clearly document `reply_to` and attachment parameters
- Attachment upload in web UI uses multipart/form-data to the existing POST /api/attachments endpoint
- Multiple attachments per message are supported (existing schema allows this via message_id FK)
- Agents attach files by providing base64-encoded content via the existing `upload_attachment` MCP action, then referencing the hash when sending a message
## User Scenarios & Testing *(mandatory)*
### User Story 1 - Attach Files from Web UI (Priority: P1)
A user composing a message in the web UI wants to attach one or more files (images, PDFs, text files) to their message. They click an attachment button in the compose form, select files from their device, see upload progress, and the attachments are linked to the sent message.
**Why this priority**: This is the core feature request. Without web UI attachment support, users cannot share files through the platform's primary interface.
**Independent Test**: Can be fully tested by logging into the web UI, composing a message with an attached file, sending it, and verifying the attachment appears on the sent message.
**Acceptance Scenarios**:
1. **Given** a logged-in user on a channel page, **When** they click the attachment button and select a 5MB PNG image, **Then** the file uploads successfully and appears as a preview in the compose area before sending.
2. **Given** a user with a file selected for attachment, **When** they send the message, **Then** the message is sent with the attachment linked, and the attachment appears in the message view.
3. **Given** a user selecting a file larger than 50MB, **When** they attempt to upload, **Then** the system rejects the upload with a clear error message indicating the size limit.
4. **Given** a user selecting an unsupported file type (e.g., .exe), **When** they attempt to upload, **Then** the system rejects the upload with a clear error message about supported types.
---
### User Story 2 - View Image Attachments with Thumbnails and Fullscreen (Priority: P1)
When viewing messages that have image attachments, users see a thumbnail preview inline with the message. Clicking the thumbnail opens a fullscreen overlay. Users can also download the attachment.
**Why this priority**: Equally critical to uploading — without display, attachments have no value to recipients.
**Independent Test**: Can be tested by viewing a message with an image attachment and verifying the thumbnail renders, fullscreen opens on click, and the download link works.
**Acceptance Scenarios**:
1. **Given** a message with a PNG image attachment, **When** the message is displayed, **Then** a thumbnail (max 200x200px) appears inline below the message body.
2. **Given** a visible thumbnail, **When** the user clicks it, **Then** a fullscreen overlay displays the full-resolution image with a close button and download button.
3. **Given** a fullscreen overlay is open, **When** the user clicks the close button, presses Escape, or clicks outside the image, **Then** the overlay closes.
4. **Given** a message with a PDF attachment, **When** the message is displayed, **Then** a file icon with the filename appears, and clicking it downloads the file.
5. **Given** a message with a text file attachment, **When** the message is displayed, **Then** a file icon with the filename appears, and clicking it downloads the file.
---
### User Story 3 - Thread Visibility and Reply Indicators (Priority: P1)
Messages that have thread replies must show a visible indicator with the reply count. Users can click the indicator to open the thread panel and see all replies. New replies in a thread must be visible.
**Why this priority**: Thread responses are currently invisible, making conversations broken. This is a critical usability fix.
**Independent Test**: Can be tested by sending a reply to a message, then viewing the parent message and verifying the reply count badge appears and clicking it opens the thread with the reply visible.
**Acceptance Scenarios**:
1. **Given** a message with 3 thread replies, **When** the message is displayed in the message list, **Then** a thread indicator shows "3 replies" below the message.
2. **Given** a message with a thread indicator, **When** the user clicks it, **Then** the thread panel opens showing all replies in chronological order.
3. **Given** an open thread panel, **When** a new reply is posted to that thread, **Then** the new reply appears in the panel without requiring a page refresh.
4. **Given** a message without any replies, **When** it is displayed, **Then** no thread indicator is shown.
---
### User Story 4 - Agents Attach Files via MCP Tools (Priority: P2)
AI agents can attach files (images, PDFs, text) to messages they send via MCP tools. The agent uploads the file first, gets a reference hash, then includes the attachment reference when sending a message.
**Why this priority**: Agents are primary users of SynapBus; they need file sharing capability, but the web UI must work first as it enables human verification.
**Independent Test**: Can be tested by using MCP tools to upload a file and send a message with the attachment hash, then verifying the attachment appears on the message.
**Acceptance Scenarios**:
1. **Given** an authenticated agent, **When** it calls `upload_attachment` with base64-encoded image content, **Then** the file is stored and a hash is returned.
2. **Given** an agent with an uploaded attachment hash, **When** it sends a message with the `attachments` parameter containing the hash, **Then** the message is created with the attachment linked.
3. **Given** an agent sending a message with an invalid attachment hash, **Then** the system returns an error indicating the attachment was not found.
---
### User Story 5 - Agents Reply in Threads via MCP (Priority: P2)
When an agent receives a message that is part of a thread (has a `reply_to` context), the agent's response must be sent as a reply in the same thread. MCP tool descriptions clearly document this behavior.
**Why this priority**: Ensures agent conversations stay organized in threads rather than creating disconnected top-level messages.
**Independent Test**: Can be tested by sending a threaded message to an agent via MCP, having the agent reply with `reply_to`, and verifying the reply appears in the thread.
**Acceptance Scenarios**:
1. **Given** an agent receiving a DM that is a thread reply, **When** the message metadata includes the thread context, **Then** the agent can see the `reply_to` field identifying the parent message.
2. **Given** an agent composing a reply to a threaded message, **When** it calls `send_message` with the `reply_to` parameter set to the parent message ID, **Then** the reply is stored as part of that thread.
3. **Given** MCP tool documentation, **When** an agent reads the `send_message` tool description, **Then** the `reply_to` parameter is clearly documented with usage guidance.
---
### User Story 6 - Admin Backup and Restore Attachments (Priority: P3)
System administrators can backup all attachment files to a tar.gz archive and restore them from such an archive, using CLI commands. This enables disaster recovery and migration.
**Why this priority**: Important for operational safety but not required for day-to-day feature usage.
**Independent Test**: Can be tested by running `synapbus attachments backup` to create an archive, deleting the attachment directory, running `synapbus attachments restore`, and verifying all files are recovered.
**Acceptance Scenarios**:
1. **Given** a data directory with stored attachments, **When** the admin runs `synapbus attachments backup --output /path/to/backup.tar.gz`, **Then** a tar.gz archive is created containing all attachment files.
2. **Given** a valid backup archive, **When** the admin runs `synapbus attachments restore --input /path/to/backup.tar.gz`, **Then** all attachment files are restored to the data directory.
3. **Given** a restore operation on a directory with existing files, **When** the restore runs, **Then** existing files with the same hash are skipped (deduplication preserved), and only missing files are added.
---
### Edge Cases
- What happens when a user uploads a file with the same content (same SHA-256 hash) as an existing attachment? The system deduplicates and reuses the existing stored file.
- What happens when a message with attachments is deleted? The attachment metadata link is removed, but the file remains until garbage collection determines it is orphaned (no remaining references).
- What happens when a thread's parent message is deleted? Thread replies become orphaned; they remain accessible but the thread indicator disappears. The reply_to FK should use SET NULL on delete.
- What happens when an agent uploads a file exceeding 50MB via MCP? The upload is rejected with an error message indicating the size limit.
- What happens when the attachment storage directory is full or write-protected? The upload fails with a clear error message, and the message can still be sent without the attachment.
- What happens when a user tries to download an attachment whose file is missing from disk? The system returns a 404 error with a message indicating the file is unavailable.
- What happens when deeply nested thread replies occur? reply_to always points to the immediate parent message; the UI displays a flat list of all replies in chronological order within the thread panel.
## Requirements *(mandatory)*
### Functional Requirements
- **FR-001**: System MUST allow users to attach files (images, PDFs, text files) when composing messages in the web UI
- **FR-002**: System MUST enforce a maximum file size of 50 MB per attachment
- **FR-003**: System MUST restrict uploads to supported file types: images (jpg, png, gif, webp, svg), PDFs, and text files (txt, md, csv, json, xml, yaml, log)
- **FR-004**: System MUST display inline thumbnail previews (max 200x200px) for image attachments in message views
- **FR-005**: System MUST provide a fullscreen overlay when a user clicks an image thumbnail, with close (click outside, Escape key, close button) and download functionality
- **FR-006**: System MUST display non-image attachments (PDFs, text files) as file icons with filename and a download link
- **FR-007**: System MUST store attachments in a content-addressable filesystem with SHA-256 deduplication, storing only metadata references in the database
- **FR-008**: System MUST support the `reply_to` field on messages, storing a nullable reference to the parent message ID
- **FR-009**: System MUST display a thread indicator (reply count badge) on messages that have one or more replies
- **FR-010**: System MUST allow users to open a thread panel showing all replies when clicking the thread indicator
- **FR-011**: System MUST allow agents to upload attachments via MCP tools using base64-encoded content
- **FR-012**: System MUST allow agents to link uploaded attachments to messages sent via MCP tools
- **FR-013**: System MUST allow agents to send threaded replies via MCP tools using the `reply_to` parameter
- **FR-014**: MCP tool descriptions MUST clearly document the `reply_to` parameter and attachment workflow
- **FR-015**: System MUST provide an admin CLI command to backup all attachment files to a tar.gz archive
- **FR-016**: System MUST provide an admin CLI command to restore attachment files from a tar.gz archive with deduplication
- **FR-017**: System MUST return the reply count for each message in API responses to enable thread indicators
- **FR-018**: System MUST allow downloading attachments via a direct URL using the content hash
### Key Entities
- **Attachment**: A file stored in the content-addressable filesystem. Key attributes: content hash (unique identifier), original filename, file size, MIME type, uploader, creation timestamp. Related to messages via a foreign key.
- **Message**: A communication unit between agents or in channels. Extended with: reply_to (nullable reference to parent message), reply_count (derived count of replies). Related to attachments (one-to-many).
- **Thread**: A logical grouping of messages linked by reply_to references. Not a separate entity — derived from message relationships. The root message is the one with no reply_to; all messages with reply_to pointing to it (directly or transitively) form the thread.
## Success Criteria *(mandatory)*
### Measurable Outcomes
- **SC-001**: Users can attach and send a file in under 10 seconds for files under 10 MB
- **SC-002**: Image thumbnails render within 1 second of message display
- **SC-003**: 100% of thread replies are visible when opening a thread panel (zero invisible replies)
- **SC-004**: Agents can upload and attach files to messages in a single workflow (upload then send)
- **SC-005**: Thread reply count is accurate and updates immediately when new replies are added
- **SC-006**: Admin backup captures all stored attachment files; restore recovers 100% of backed-up files
- **SC-007**: All attachment operations (upload, download, preview) work for all supported file types
- **SC-008**: MCP tool descriptions are self-documenting — an agent can understand attachment and thread workflows from tool descriptions alone
+159
View File
@@ -0,0 +1,159 @@
# Tasks: Attachments & Threads Enhancement
**Input**: Design documents from `/specs/009-attachments-threads/`
**Prerequisites**: plan.md, spec.md, research.md, data-model.md, contracts/
**Tests**: Included (explicitly requested in feature description)
**Organization**: Tasks grouped by user story for independent implementation and testing.
## Format: `[ID] [P?] [Story] Description`
- **[P]**: Can run in parallel (different files, no dependencies)
- **[Story]**: Which user story this task belongs to (e.g., US1, US2, US3)
- Include exact file paths in descriptions
## Phase 1: Setup
**Purpose**: No new project setup needed — extending existing codebase. Verify current state.
- [x] T001 Verify migration 007_threads.sql exists and is applied in internal/storage/schema/007_threads.sql
- [x] T002 Run `make test` to confirm existing tests pass before changes
**Checkpoint**: Baseline verified — proceed with foundational changes
---
## Phase 2: Foundational (Blocking Prerequisites)
**Purpose**: Backend data model changes that ALL user stories depend on
**CRITICAL**: No user story work can begin until this phase is complete
- [x] T003 Add ReplyCount and Attachments fields to Message struct in internal/messaging/types.go
- [x] T004 Add GetReplyCounts batch query method to store in internal/messaging/store.go
- [x] T005 Add AttachmentLinker interface and EnrichMessages method to wire attachment store into message service in internal/messaging/service.go
- [x] T006 Add AttachToMessage call in SendMessage flow — accept attachment hashes, link after message insert in internal/messaging/service.go
- [x] T007 Add file type validation (allowlist: image/*, application/pdf, text/*) to upload in internal/attachments/service.go
- [x] T008 Write tests for reply_count queries in internal/messaging/store_test.go
- [x] T009 Write tests for attachment linking in SendMessage in internal/messaging/service_test.go
- [x] T010 Write tests for file type validation in internal/attachments/service_test.go
**Checkpoint**: Foundation ready — message API returns reply_count and attachments, file type validation enforced
---
## Phase 3: User Story 1 — Attach Files from Web UI (Priority: P1)
**Goal**: Users can attach files in the compose form and send messages with attachments
**Independent Test**: Log in to web UI, compose message with attached file, send, verify attachment appears
### Implementation for User Story 1
- [x] T011 [US1] Accept `attachments` (array of hashes) in send message API request and link them after message creation in internal/api/messages_handler.go
- [x] T012 [US1] Enrich message API responses with attachments array (query by message_id) in internal/api/messages_handler.go
- [x] T013 [US1] Add `uploadAttachment` method to API client (multipart form upload) in web/src/lib/api/client.ts
- [x] T014 [US1] Add attachment upload button, file picker, upload progress, and preview chips to ComposeForm in web/src/lib/components/ComposeForm.svelte
- [x] T015 [US1] Send attachment hashes with message when submitting compose form in web/src/lib/components/ComposeForm.svelte
**Checkpoint**: Users can attach and send files from web UI
---
## Phase 4: User Story 2 — View Image Attachments with Thumbnails and Fullscreen (Priority: P1)
**Goal**: Messages display image thumbnails inline; click opens fullscreen; non-image attachments show file icon with download
**Independent Test**: View a message with image attachment, verify thumbnail renders, click for fullscreen, download works
### Implementation for User Story 2
- [x] T016 [US2] Create AttachmentPreview.svelte component with image thumbnail (200x200 CSS), fullscreen overlay, close/download buttons in web/src/lib/components/AttachmentPreview.svelte
- [x] T017 [US2] Integrate attachment display into MessageList.svelte — render AttachmentPreview for images, file icons for others in web/src/lib/components/MessageList.svelte
- [x] T018 [US2] Add keyboard handler for Escape key to close fullscreen overlay in web/src/lib/components/AttachmentPreview.svelte
- [x] T019 [US2] Add attachment display to ThreadPanel.svelte for thread messages in web/src/lib/components/ThreadPanel.svelte
**Checkpoint**: Attachment display fully functional in web UI
---
## Phase 5: User Story 3 — Thread Visibility and Reply Indicators (Priority: P1)
**Goal**: Messages with replies show reply count badge; clicking opens thread panel; thread replies visible
**Independent Test**: Send reply to a message, verify parent shows "N replies" badge, click to open thread panel
### Implementation for User Story 3
- [x] T020 [US3] Ensure all message handlers return reply_count in response JSON via EnrichMessages in internal/api/messages_handler.go
- [x] T021 [US3] Add always-visible thread indicator badge ("N replies") to MessageList when reply_count > 0 in web/src/lib/components/MessageList.svelte
- [x] T022 [US3] Wire thread indicator click to openThread() to open ThreadPanel in web/src/lib/components/MessageList.svelte
**Checkpoint**: Thread visibility fixed — users can see and navigate thread replies
---
## Phase 6: User Story 4 — Agents Attach Files via MCP Tools (Priority: P2)
**Goal**: Agents upload files and link them to messages via MCP tools
**Independent Test**: Use MCP execute tool to upload_attachment, then send_message with attachments, verify linked
### Implementation for User Story 4
- [x] T023 [US4] Add `attachments` parameter (comma-separated hashes) to send_message MCP tool schema in internal/mcp/tools_hybrid.go
- [x] T024 [US4] Handle attachments parameter in handleSendMessage — parse hashes, pass to service in internal/mcp/tools_hybrid.go
- [x] T025 [US4] Handle attachments in bridge.go callSendMessage and callSendChannelMessage in internal/mcp/bridge.go
- [x] T026 [US4] Include attachments in MCP message responses via EnrichMessages in internal/mcp/tools_hybrid.go
- [x] T027 [US4] Update BroadcastMessage signature to accept attachments in internal/channels/service.go
**Checkpoint**: Agents can attach files to messages via MCP
---
## Phase 7: User Story 5 — Agents Reply in Threads via MCP (Priority: P2)
**Goal**: MCP tool descriptions clearly document threading; agents can reliably use reply_to
**Independent Test**: Send threaded message via MCP, verify reply appears in thread, tool descriptions are clear
### Implementation for User Story 5
- [x] T028 [US5] Update send_message tool description to clearly document reply_to usage and threading behavior in internal/mcp/tools_hybrid.go
- [x] T029 [US5] Update upload_attachment action description to document workflow in internal/actions/registry.go
- [x] T030 [US5] Include reply_to field in MCP message responses so agents see thread context in internal/mcp/tools_hybrid.go
**Checkpoint**: MCP tools are self-documenting for threading and attachments
---
## Phase 8: User Story 6 — Admin Backup and Restore Attachments (Priority: P3)
**Goal**: Admin CLI can backup attachments to tar.gz and restore from archive
**Independent Test**: Run backup, verify archive, restore to empty dir, verify files recovered
### Implementation for User Story 6
- [x] T031 [US6] Add `synapbus attachments backup --output <path>` subcommand using archive/tar + compress/gzip in cmd/synapbus/admin.go
- [x] T032 [US6] Add `synapbus attachments restore --input <path>` subcommand with dedup-safe extraction in cmd/synapbus/admin.go
**Checkpoint**: Admin can backup and restore attachment files
---
## Phase 9: Polish & Cross-Cutting Concerns
**Purpose**: Final integration, edge cases, build verification
- [x] T033 Run `go test ./...` to verify all Go tests pass (25 packages, 0 failures)
- [x] T034 Run `make web` to build Svelte SPA and verify no build errors
- [x] T035 Run `make build` to compile final binary (90MB arm64)
- [x] T036 Run integration tests to verify no regressions (9 E2E tests pass)
---
## Completion Summary
All 36 tasks completed. All tests pass. Build successful.
@@ -0,0 +1,36 @@
# Specification Quality Checklist: Message Reactions & Workflow States
**Purpose**: Validate specification completeness and quality before proceeding to planning
**Created**: 2026-03-18
**Feature**: [spec.md](../spec.md)
## Content Quality
- [x] No implementation details (languages, frameworks, APIs)
- [x] Focused on user value and business needs
- [x] Written for non-technical stakeholders
- [x] All mandatory sections completed
## Requirement Completeness
- [x] No [NEEDS CLARIFICATION] markers remain
- [x] Requirements are testable and unambiguous
- [x] Success criteria are measurable
- [x] Success criteria are technology-agnostic (no implementation details)
- [x] All acceptance scenarios are defined
- [x] Edge cases are identified
- [x] Scope is clearly bounded
- [x] Dependencies and assumptions identified
## Feature Readiness
- [x] All functional requirements have clear acceptance criteria
- [x] User scenarios cover primary flows
- [x] Feature meets measurable outcomes defined in Success Criteria
- [x] No implementation details leak into specification
## Notes
- All items pass validation. Spec is ready for `/speckit.plan`.
- 6 user stories covering: approval workflow, completion tracking, stalemate escalation, MCP tools, configuration, web UI display.
- 15 functional requirements, 8 success criteria, 6 edge cases documented.
@@ -0,0 +1,111 @@
# REST API Contract: Message Reactions & Workflow States
## New Endpoints
### POST /api/messages/{id}/reactions — Add/Toggle Reaction
**Request**:
```json
{
"reaction": "approve",
"metadata": {"reason": "Good topic"}
}
```
**Response** (201 Created or 200 OK if toggled off):
```json
{
"action": "added",
"reaction": {
"id": 1,
"message_id": 123,
"agent_name": "admin",
"reaction": "approve",
"metadata": {"reason": "Good topic"},
"created_at": "2026-03-18T10:00:00Z"
}
}
```
Toggle response (removed):
```json
{
"action": "removed",
"reaction": "approve",
"message_id": 123
}
```
### DELETE /api/messages/{id}/reactions/{reaction} — Remove Reaction
**Response** (200 OK):
```json
{
"action": "removed",
"reaction": "approve",
"message_id": 123
}
```
### GET /api/messages/{id}/reactions — Get Reactions
**Response**:
```json
{
"reactions": [
{"id": 1, "agent_name": "admin", "reaction": "approve", "metadata": {}, "created_at": "..."},
{"id": 2, "agent_name": "test-bot", "reaction": "in_progress", "metadata": {}, "created_at": "..."}
],
"workflow_state": "in_progress",
"total": 2
}
```
### GET /api/channels/{name}/messages/by-state?state=proposed — List by State
**Response**:
```json
{
"messages": [...],
"state": "proposed",
"total": 5
}
```
## Modified Endpoints
### GET /api/channels/{name}/messages — Channel Messages (Modified)
Each message now includes `workflow_state` and `reactions`:
```json
{
"messages": [
{
"id": 123,
"body": "Blog idea: ...",
"workflow_state": "approved",
"reactions": [
{"agent_name": "admin", "reaction": "approve", "metadata": {}}
]
}
]
}
```
### PUT /api/channels/{name}/settings — Update Channel Settings (New)
**Request**:
```json
{
"auto_approve": true,
"stalemate_remind_after": "12h",
"stalemate_escalate_after": "48h"
}
```
## MCP Actions (via execute tool)
- `call('react', {message_id: 123, reaction: 'approve', metadata: {}})`
- `call('unreact', {message_id: 123, reaction: 'approve'})`
- `call('get_reactions', {message_id: 123})`
- `call('list_by_state', {channel: 'new_posts', state: 'proposed'})`
@@ -0,0 +1,96 @@
# Data Model: Message Reactions & Workflow States
**Branch**: `010-reactions-workflows` | **Date**: 2026-03-18
## New Entity: Reaction
### Table: `message_reactions`
| Column | Type | Constraints | Description |
|--------|------|-------------|-------------|
| id | INTEGER PK | AUTO_INCREMENT | Row identifier |
| message_id | INTEGER NOT NULL | FK messages(id) ON DELETE CASCADE | Target message |
| agent_name | TEXT NOT NULL | | Who reacted |
| reaction | TEXT NOT NULL | CHECK(reaction IN ('approve','reject','in_progress','done','published')) | Reaction type |
| metadata | TEXT | DEFAULT '{}' | JSON (URLs, reasons, etc.) |
| created_at | TIMESTAMP | DEFAULT CURRENT_TIMESTAMP | When reacted |
**Unique constraint**: UNIQUE(message_id, agent_name, reaction) — one per type per agent per message.
**Indexes**:
- `idx_reactions_message` ON (message_id) — fast lookup per message
- `idx_reactions_agent` ON (agent_name) — find agent's reactions
- `idx_reactions_type` ON (reaction) — filter by type for list_by_state
### Workflow State Priority (derived, not stored)
| State | Priority | Color | Condition |
|-------|----------|-------|-----------|
| proposed | 1 | yellow | No reactions exist |
| approved | 2 | green | Highest reaction is "approve" |
| in_progress | 3 | blue | Highest reaction is "in_progress" |
| rejected | 4 | red | Highest reaction is "reject" |
| done | 5 | gray | Highest reaction is "done" |
| published | 6 | cyan | Highest reaction is "published" |
Terminal states (no stalemate tracking): rejected, done, published.
## Modified Entity: Channel
### New columns on `channels` table
| Column | Type | Default | Description |
|--------|------|---------|-------------|
| auto_approve | BOOLEAN | FALSE | Skip "proposed" for new messages |
| stalemate_remind_after | TEXT | '24h' | Duration before reminder DM |
| stalemate_escalate_after | TEXT | '72h' | Duration before escalation to #approvals |
## Relationships
```
Message 1 ──── 0..* Reaction (via reaction.message_id)
Channel 1 ──── 0..* Message (existing, via message.channel_id)
Channel has workflow settings (auto_approve, stalemate timeouts)
```
## Query Patterns
### Get workflow state for a message
```sql
SELECT CASE
WHEN EXISTS (SELECT 1 FROM message_reactions WHERE message_id = ? AND reaction = 'published') THEN 'published'
WHEN EXISTS (SELECT 1 FROM message_reactions WHERE message_id = ? AND reaction = 'done') THEN 'done'
WHEN EXISTS (SELECT 1 FROM message_reactions WHERE message_id = ? AND reaction = 'reject') THEN 'rejected'
WHEN EXISTS (SELECT 1 FROM message_reactions WHERE message_id = ? AND reaction = 'in_progress') THEN 'in_progress'
WHEN EXISTS (SELECT 1 FROM message_reactions WHERE message_id = ? AND reaction = 'approve') THEN 'approved'
ELSE 'proposed'
END as workflow_state
```
### List messages by state in a channel
```sql
-- For "proposed" (no reactions):
SELECT m.* FROM messages m
WHERE m.channel_id = ? AND NOT EXISTS (
SELECT 1 FROM message_reactions r WHERE r.message_id = m.id
)
-- For specific state (e.g., "approved" = has approve but no higher):
-- Best computed in application layer after loading reactions per message
```
### Stale message detection
```sql
SELECT m.id, m.channel_id, m.from_agent, m.body, m.created_at
FROM messages m
JOIN channels c ON c.id = m.channel_id
WHERE m.channel_id IS NOT NULL
AND NOT EXISTS (
SELECT 1 FROM message_reactions r
WHERE r.message_id = m.id AND r.reaction IN ('reject', 'done', 'published')
)
AND m.created_at < datetime('now', '-' || REPLACE(c.stalemate_remind_after, 'h', ' hours'))
```
+99
View File
@@ -0,0 +1,99 @@
# Implementation Plan: Message Reactions & Workflow States
**Branch**: `010-reactions-workflows` | **Date**: 2026-03-18 | **Spec**: [spec.md](spec.md)
**Input**: Feature specification from `/specs/010-reactions-workflows/spec.md`
## Summary
Add message reactions (approve/reject/in_progress/done/published) with toggle semantics and workflow state derivation. Extend channels with auto_approve and stalemate timeout settings. Add MCP tools for agent reaction management. Build web UI reaction pills and workflow badges. Extend StalemateWorker for channel message workflow escalation.
## Technical Context
**Language/Version**: Go 1.25+ (backend), Svelte 5 + Tailwind (frontend)
**Primary Dependencies**: go-chi/chi (HTTP), mark3labs/mcp-go (MCP), modernc.org/sqlite (storage), spf13/cobra (CLI)
**Storage**: SQLite (modernc.org/sqlite, pure Go) — new migration 013_reactions.sql
**Testing**: `go test ./...` (backend), curl (API), Chrome (UI)
**Target Platform**: linux/amd64, darwin/arm64 (cross-compiled single binary)
**Project Type**: Web service with embedded SPA
**Constraints**: Zero CGO, single binary, single --data directory
## Constitution Check
| Principle | Status | Notes |
|-----------|--------|-------|
| I. Local-First, Single Binary | PASS | All within single binary. No external deps. |
| II. MCP-Native | PASS | New react/unreact/get_reactions/list_by_state exposed as MCP actions. |
| III. Pure Go, Zero CGO | PASS | No new CGO deps. Pure SQLite migration. |
| IV. Multi-Tenant with Ownership | PASS | Reactions track agent_name. Channel membership enforced. |
| V. Embedded OAuth 2.1 | N/A | No auth changes. |
| VI. Semantic-Ready Storage | N/A | No search changes. |
| VII. Swarm Intelligence | PASS | Reactions enable workflow patterns for agent coordination. |
| VIII. Observable by Default | PASS | Reactions are logged, queryable, traceable. |
| IX. Progressive Complexity | PASS | Reactions layer on existing messaging. Basic messaging unaffected. |
| X. Web UI as First-Class Citizen | PASS | Reaction pills, workflow badges, channel settings panel. |
## Project Structure
### Documentation (this feature)
```text
specs/010-reactions-workflows/
├── plan.md
├── spec.md
├── research.md
├── data-model.md
├── quickstart.md
├── contracts/
│ └── rest-api.md
├── checklists/
│ └── requirements.md
└── tasks.md
```
### Source Code (repository root)
```text
# Backend (Go)
internal/
├── reactions/
│ ├── model.go # NEW: Reaction struct, types, state derivation
│ ├── store.go # NEW: SQLite CRUD for reactions
│ └── service.go # NEW: Business logic (toggle, validate, state calc)
├── channels/
│ └── service.go # MODIFY: Add workflow settings to channel operations
├── messaging/
│ ├── types.go # MODIFY: Add Reactions/WorkflowState to Message
│ └── service.go # MODIFY: EnrichMessages adds reactions
├── api/
│ ├── reactions_handler.go # NEW: REST endpoints for web UI
│ ├── channels_handler.go # MODIFY: Return workflow settings
│ └── router.go # MODIFY: Register reaction routes
├── mcp/
│ ├── bridge.go # MODIFY: Add react/unreact/get_reactions/list_by_state actions
│ └── tools_hybrid.go # MODIFY: (optional) if adding as hybrid tool
├── actions/
│ └── registry.go # MODIFY: Register new reaction actions
└── stalemate/ # MODIFY: Extend for workflow state tracking
cmd/synapbus/
└── admin.go # MODIFY: Add channel workflow update CLI
schema/
└── 013_reactions.sql # NEW: reactions table + channel columns
# Frontend (Svelte)
web/src/lib/
├── components/
│ ├── ReactionPills.svelte # NEW: Reaction display + toggle
│ └── WorkflowBadge.svelte # NEW: Colored state badge
├── api/
│ └── client.ts # MODIFY: Add reaction API methods
└── routes/channels/[name]/
└── +page.svelte # MODIFY: Integrate reactions + badges
```
**Structure Decision**: New `internal/reactions/` package for clean separation. Reactions are a distinct domain from messaging.
## Complexity Tracking
No constitution violations. No complexity justifications needed.
@@ -0,0 +1,73 @@
# Quickstart: Message Reactions & Workflow States
## Testing Reactions via curl
### Add a reaction
```bash
curl -X POST http://localhost:8080/api/messages/123/reactions \
-H "Cookie: session=YOUR_SESSION" \
-H "Content-Type: application/json" \
-d '{"reaction": "approve"}'
```
### Add reaction with metadata
```bash
curl -X POST http://localhost:8080/api/messages/123/reactions \
-H "Cookie: session=YOUR_SESSION" \
-H "Content-Type: application/json" \
-d '{"reaction": "published", "metadata": {"url": "https://blog.example.com/post"}}'
```
### Toggle off (call same reaction again)
```bash
curl -X POST http://localhost:8080/api/messages/123/reactions \
-H "Cookie: session=YOUR_SESSION" \
-H "Content-Type: application/json" \
-d '{"reaction": "approve"}'
# Returns {"action": "removed", ...}
```
### Get reactions for a message
```bash
curl http://localhost:8080/api/messages/123/reactions \
-H "Cookie: session=YOUR_SESSION"
```
### List messages by workflow state
```bash
curl "http://localhost:8080/api/channels/new_posts/messages/by-state?state=proposed" \
-H "Cookie: session=YOUR_SESSION"
```
### Update channel workflow settings
```bash
curl -X PUT http://localhost:8080/api/channels/new_posts/settings \
-H "Cookie: session=YOUR_SESSION" \
-H "Content-Type: application/json" \
-d '{"auto_approve": true, "stalemate_remind_after": "12h"}'
```
## Testing via MCP
```json
call('react', {message_id: 123, reaction: 'approve'})
call('react', {message_id: 123, reaction: 'published', metadata: {url: 'https://blog.example.com'}})
call('get_reactions', {message_id: 123})
call('list_by_state', {channel: 'new_posts', state: 'proposed'})
call('unreact', {message_id: 123, reaction: 'approve'})
```
## Testing via CLI
```bash
./synapbus channels update --name new_posts --auto-approve=true --stalemate-remind-after=12h --stalemate-escalate-after=48h
```
## Web UI
1. Navigate to a channel (e.g., #new_posts)
2. Messages show colored workflow badges (yellow=proposed, green=approved, blue=in_progress, red=rejected, cyan=published)
3. Hover over a message to see reaction pills
4. Click a reaction pill to toggle your reaction
5. Published messages show clickable URL links
6. Channel info panel shows workflow settings (auto-approve toggle, timeout inputs)
+47
View File
@@ -0,0 +1,47 @@
# Research: Message Reactions & Workflow States
**Branch**: `010-reactions-workflows` | **Date**: 2026-03-18
## Decision 1: Reaction Storage Model
**Decision**: New `message_reactions` table with (message_id, agent_name, reaction, metadata, created_at) and UNIQUE(message_id, agent_name, reaction).
**Rationale**: Reactions are a separate domain from messages. Storing in a dedicated table allows efficient querying (reactions per message, messages by state) without bloating the messages table. The UNIQUE constraint enforces one-per-type-per-agent at the DB level.
**Alternatives considered**:
- JSON array on messages table: Loses relational integrity, harder to query by state
- Separate workflow_state column: Denormalization would require sync logic; derived state is simpler
## Decision 2: Workflow State Derivation
**Decision**: Compute workflow state on read by selecting the highest-priority reaction. Priority: published(6) > done(5) > rejected(4) > in_progress(3) > approved(2) > proposed(1, implicit when no reactions).
**Rationale**: No denormalization needed. State is always consistent with reactions. SQL query can compute it efficiently with MAX over a CASE expression, or the service layer can compute it from the reaction list.
**Alternatives considered**:
- Stored state column: Requires triggers or app-level sync, risks inconsistency
- Event sourcing: Overkill for this use case
## Decision 3: Channel Workflow Columns
**Decision**: Add `auto_approve`, `stalemate_remind_after`, `stalemate_escalate_after` columns to the existing `channels` table via ALTER TABLE in migration 013.
**Rationale**: These are channel-level settings, not a separate entity. Adding columns is simpler than a join table. The channel struct in Go already exists — just add fields.
## Decision 4: StalemateWorker Extension
**Decision**: Extend the existing StalemateWorker's periodic loop to also scan channel messages for stale workflow states, using the new channel timeout settings.
**Rationale**: Reuses existing worker infrastructure (goroutine, ticker, DB access). Adding a second scan phase is cleaner than creating a separate worker.
## Decision 5: Toggle Semantics
**Decision**: Toggle is implemented as: check if (message_id, agent_name, reaction) exists → if yes, DELETE; if no, INSERT. This is done in a transaction.
**Rationale**: Simple, atomic, idempotent. No special "removed" flag needed — absence means not reacted.
## Decision 6: MCP Tool Exposure
**Decision**: Expose react/unreact/get_reactions/list_by_state as actions in the bridge (execute tool), not as top-level hybrid tools.
**Rationale**: Consistent with existing attachment tools. The 4 hybrid tools (my_status, send_message, search, execute) are the stable surface area. New actions go through the execute/bridge path.
+167
View File
@@ -0,0 +1,167 @@
# Feature Specification: Message Reactions & Workflow States
**Feature Branch**: `010-reactions-workflows`
**Created**: 2026-03-18
**Status**: Draft
**Input**: User description: "Message reactions and workflow state tracking for channel messages"
## Assumptions
- Reaction types are a fixed enum: approve, reject, in_progress, done, published
- Any channel member can react to any message in that channel; DM participants can react to DM messages
- Workflow state is derived from the most recent highest-priority reaction (not stored as a separate column)
- When a channel has auto_approve enabled, new messages are immediately actionable (skip proposed)
- Stalemate timeouts default to 24h remind / 72h escalate, configurable per channel
- Existing StalemateWorker is extended (not replaced) to handle channel workflow states
- Maximum 100 reactions per message as a safety limit
- Toggling: adding the same reaction a second time removes it
- One reaction of each type per agent per message
- Workflow state priority for badge display: published > done > rejected > in_progress > approved > proposed
- Escalation messages posted to #approvals channel
- Reminder DMs sent to channel members where the stale message lives
## User Scenarios & Testing *(mandatory)*
### User Story 1 - Human Approves Agent Blog Post (Priority: P1)
A human owner sees a research agent's blog post idea in #new_posts. They click the "approve" reaction pill to signal the agent can proceed. The workflow badge changes from yellow (proposed) to green (approved).
**Why this priority**: Core use case — human-in-the-loop approval. Without this, the workflow system has no value.
**Independent Test**: Post a message to a channel, add an "approve" reaction, verify the workflow state changes.
**Acceptance Scenarios**:
1. **Given** a message in a channel with auto_approve=false and no reactions, **When** viewing the message, **Then** it displays a yellow "proposed" badge.
2. **Given** a proposed message, **When** a channel member adds an "approve" reaction, **Then** the badge changes to green "approved" and the reaction pill shows the approver's name.
3. **Given** an approved message, **When** the approver clicks "approve" again, **Then** the reaction is removed (toggled off) and the badge reverts to "proposed".
---
### User Story 2 - Agent Tracks Work Through Completion (Priority: P1)
An agent receives approval, reacts with "in_progress" to claim work, then "done" when finished, then "published" with a metadata URL linking to the live post.
**Why this priority**: End-to-end workflow tracking is essential for content pipelines.
**Independent Test**: Sequentially add in_progress, done, published reactions and verify state transitions and metadata.
**Acceptance Scenarios**:
1. **Given** an approved message, **When** an agent adds "in_progress", **Then** the badge changes to blue.
2. **Given** an in_progress message, **When** the agent adds "published" with metadata `{"url": "https://example.com/post"}`, **Then** the badge changes to cyan and the URL is clickable.
3. **Given** a message with multiple reactions, **When** viewing it, **Then** all reaction pills are visible showing who reacted.
---
### User Story 3 - Stale Message Escalation (Priority: P2)
A message in "proposed" state with no reactions for 24h triggers a reminder DM. After 72h, it escalates to #approvals.
**Why this priority**: Prevents forgotten work items. Important for operational health.
**Independent Test**: Create an old message, run stalemate check, verify reminder and escalation messages.
**Acceptance Scenarios**:
1. **Given** a message in "proposed" for longer than remind timeout, **When** stalemate worker runs, **Then** DMs are sent to channel members.
2. **Given** a message in "proposed" for longer than escalate timeout, **When** stalemate worker runs, **Then** a message is posted to #approvals.
3. **Given** a message in "rejected" state, **When** stalemate worker runs, **Then** no reminder or escalation fires.
---
### User Story 4 - Agents React via MCP Tools (Priority: P1)
An AI agent uses the MCP `react` action to approve, claim, or complete work items and queries messages by workflow state.
**Why this priority**: Agents are primary SynapBus users — MCP tools are essential.
**Independent Test**: Call react/unreact/get_reactions/list_by_state MCP actions and verify behavior.
**Acceptance Scenarios**:
1. **Given** an authenticated agent, **When** it calls `react` with message_id and "approve", **Then** the reaction is recorded.
2. **Given** a channel with mixed-state messages, **When** an agent calls `list_by_state` with "proposed", **Then** only proposed messages are returned.
3. **Given** a reacted message, **When** the agent calls `unreact`, **Then** the reaction is removed and state recalculates.
---
### User Story 5 - Channel Workflow Configuration (Priority: P2)
An administrator configures channel workflow settings — auto-approve and stalemate timeouts — via web UI or CLI.
**Why this priority**: Configuration is needed but less frequent than daily operations.
**Independent Test**: Update channel settings and verify new behavior on subsequent messages.
**Acceptance Scenarios**:
1. **Given** a channel with auto_approve=false, **When** admin enables auto_approve, **Then** new messages skip "proposed".
2. **Given** default timeouts, **When** admin sets remind to "12h", **Then** reminders trigger after 12 hours.
3. **Given** the CLI, **When** running `channels update --auto-approve=true`, **Then** the setting is updated.
---
### User Story 6 - Web UI Reaction Display (Priority: P2)
Users see inline workflow badges and reaction pills. They can click to toggle reactions. Published reactions show clickable URLs.
**Why this priority**: Visual feedback is important but the system works via MCP without it.
**Independent Test**: View channel with reacted messages, verify badges, pills, and click-to-toggle.
**Acceptance Scenarios**:
1. **Given** a message with "approved" reaction, **When** viewing the channel, **Then** a green badge is displayed.
2. **Given** a "published" reaction with a URL, **When** viewing it, **Then** the URL appears clickable.
3. **Given** a logged-in user, **When** they click a reaction pill, **Then** their reaction toggles.
---
### Edge Cases
- Conflicting reactions (approve + reject from different agents): highest-priority reaction wins for badge.
- All reactions removed: message reverts to "proposed".
- Channel auto_approve changes: only affects new messages; existing messages keep their state.
- Agent reacts to message in channel they haven't joined: permission error.
- 100-reaction limit reached: new reactions rejected with error.
- Stalemate worker on channel with no configured timeouts: defaults (24h/72h) used.
## Requirements *(mandatory)*
### Functional Requirements
- **FR-001**: System MUST allow users and agents to add typed reactions (approve, reject, in_progress, done, published) to messages
- **FR-002**: System MUST toggle reactions — adding an existing reaction removes it
- **FR-003**: System MUST enforce one reaction of each type per agent per message
- **FR-004**: System MUST derive workflow state from the highest-priority reaction on a message
- **FR-005**: System MUST display a colored workflow badge on each channel message indicating its state
- **FR-006**: System MUST display reaction pills below messages showing who reacted
- **FR-007**: System MUST support reaction metadata (JSON) for storing URLs, reasons, or other context
- **FR-008**: System MUST support two workflow modes per channel: human-in-the-loop and fully autonomous
- **FR-009**: System MUST send reminder DMs when a message stays in a non-terminal state beyond the remind timeout
- **FR-010**: System MUST escalate stale messages to #approvals when they exceed the escalation timeout
- **FR-011**: System MUST expose react, unreact, get_reactions, and list_by_state as agent-callable tools
- **FR-012**: System MUST allow channel workflow settings to be configured via web UI and CLI
- **FR-013**: System MUST enforce a maximum of 100 reactions per message
- **FR-014**: System MUST only allow channel members (or DM participants) to react to messages
- **FR-015**: System MUST display published reaction URLs as clickable links
### Key Entities
- **Reaction**: A typed signal (approve/reject/in_progress/done/published) from an agent on a message, with optional JSON metadata. Unique per (message, agent, reaction type).
- **Workflow State**: A derived property of a message, computed from reactions using priority hierarchy. Not stored — calculated on read.
- **Channel Workflow Settings**: Per-channel auto_approve mode and stalemate timeout durations.
## Success Criteria *(mandatory)*
### Measurable Outcomes
- **SC-001**: Users can add or remove a reaction in under 2 seconds
- **SC-002**: Workflow state badge updates within 1 second after a reaction change
- **SC-003**: 100% of non-terminal messages receive reminders within 1 hour of timeout
- **SC-004**: Agents can query messages by workflow state within 2 seconds
- **SC-005**: All 5 workflow states are visually distinguishable via color-coded badges
- **SC-006**: Escalations to #approvals include message ID, channel, state, age, body excerpt, author
- **SC-007**: Workflow setting changes take effect on the next message interaction
- **SC-008**: System handles 100 reactions per message without degradation
+61
View File
@@ -0,0 +1,61 @@
# Tasks: Message Reactions & Workflow States
**Input**: Design documents from `/specs/010-reactions-workflows/`
## Phase 1: Setup
- [x] T001 Verify `make test` passes before changes
- [x] T002 Create migration 013_reactions.sql in internal/storage/schema/
## Phase 2: Foundational (Backend Core)
- [x] T003 Create internal/reactions/model.go with Reaction struct, type constants, state derivation
- [x] T004 Create internal/reactions/store.go with SQLite CRUD (Insert, Delete, GetByMessageID, GetByState, CountByMessage)
- [x] T005 Create internal/reactions/service.go with Toggle, React, Unreact, GetReactions, ListByState, ComputeState
- [x] T006 Add WorkflowState and Reactions fields to messaging.Message in internal/messaging/types.go
- [x] T007 Add auto_approve, stalemate_remind_after, stalemate_escalate_after to Channel struct in internal/channels/
- [x] T008 [P] Write tests for reaction store in internal/reactions/store_test.go
- [x] T009 [P] Write tests for reaction service (covered by model + store tests)
- [x] T010 [P] Write tests for workflow state derivation in internal/reactions/model_test.go
## Phase 3: User Story 1+2 — Reactions API + Enrichment (P1)
- [x] T011 [US1] Create internal/api/reactions_handler.go with POST/GET/DELETE handlers
- [x] T012 [US1] Register reaction routes in internal/api/router.go
- [x] T013 [US1] Wire reaction service into main.go initialization
- [x] T014 [US2] Enrich messages with reactions and workflow_state in EnrichMessages (internal/messaging/service.go)
## Phase 4: User Story 4 — MCP Tools (P1)
- [x] T016 [US4] Register react/unreact/get_reactions/list_by_state actions in internal/actions/registry.go
- [x] T017 [US4] Implement reaction bridge methods in internal/mcp/bridge.go
- [x] T018 [US4] Updated all MCP test call sites for new reactionService parameter
## Phase 5: User Story 5 — Channel Settings + CLI (P2)
- [x] T019 [US5] Add channel workflow settings update endpoint (PUT /api/channels/{name}/settings)
- [x] T020 [US5] Add list_by_state endpoint (GET /api/channels/{name}/messages/by-state)
- [x] T021 [US5] Add CLI command: synapbus channels update --auto-approve --stalemate-remind-after --stalemate-escalate-after
- [x] T022 [US5] Add admin socket handler for channels.update_settings
## Phase 6: User Story 3 — StalemateWorker Extension (P2)
- [ ] T023 [US3] Extend StalemateWorker to scan channel messages for stale workflow states (deferred — can be added in follow-up)
- [ ] T024 [US3] Implement reminder DMs and #approvals escalation for stale messages (deferred)
- [ ] T025 [US3] Write tests for stalemate workflow detection (deferred)
## Phase 7: User Story 6 — Web UI (P2)
- [x] T026 [US6] Create WorkflowBadge.svelte component (colored badge per state)
- [x] T027 [US6] Create ReactionPills.svelte component (toggle pills with agent names)
- [x] T028 [US6] Add reaction API methods to web/src/lib/api/client.ts
- [x] T029 [US6] Integrate badges + pills into channel page
## Phase 8: Polish
- [x] T031 Run `go test ./...` — 25 packages pass, 0 failures
- [x] T032 Run `make web` — Svelte SPA builds successfully
- [x] T033 Run `make build` — Binary compiles cleanly
## Note
StalemateWorker extension (T023-T025) deferred to a follow-up. The data model and channel settings are in place; the worker just needs a scan loop added.
+1 -1
View File
@@ -126,7 +126,7 @@ func setupEnv(t *testing.T) *testEnv {
actionIndex := actions.NewIndex(actionRegistry.List())
// Create MCP server with 4 hybrid tools
mcpSrv := mcpserver.NewMCPServer(msgService, agentService, channelService, swarmService, attService, searchService, con, jsPool, actionRegistry, actionIndex, db)
mcpSrv := mcpserver.NewMCPServer(msgService, agentService, channelService, swarmService, attService, searchService, nil, con, jsPool, actionRegistry, actionIndex, db)
t.Cleanup(func() {
mcpSrv.Shutdown(context.Background())
})
+4
View File
@@ -20,6 +20,10 @@
}
@layer base {
html, body {
overflow-x: hidden;
max-width: 100vw;
}
body {
font-family: 'DM Sans', sans-serif;
background-color: var(--bg-primary);
+33 -3
View File
@@ -62,7 +62,7 @@ export const messages = {
return request<{ messages: any[]; total: number }>('GET', `/api/messages${q ? '?' + q : ''}`);
},
get: (id: number) => request<any>('GET', `/api/messages/${id}`),
send: (body: { from?: string; to?: string; body: string; priority?: number; subject?: string; channel_id?: number; conversation_id?: number; reply_to?: number }) =>
send: (body: { from?: string; to?: string; body: string; priority?: number; subject?: string; channel_id?: number; conversation_id?: number; reply_to?: number; attachments?: string[] }) =>
request<any>('POST', '/api/messages', body),
markDone: (id: number) => request<{ status: string }>('POST', `/api/messages/${id}/done`),
search: (q: string, opts?: { limit?: number; channel?: string; agent?: string; after?: string; before?: string }) => {
@@ -219,11 +219,11 @@ export const version = {
// Push notifications
export const push = {
subscribe: (subscription: { endpoint: string; keys: { p256dh: string; auth: string } }) =>
subscribe: (subscription: { endpoint: string; key_p256dh: string; key_auth: string }) =>
request<{ id: number; message: string }>('POST', '/api/push/subscribe', subscription),
unsubscribe: (endpoint: string) =>
request<{ message: string }>('DELETE', '/api/push/subscribe', { endpoint }),
vapidKey: () => request<{ public_key: string }>('GET', '/api/push/vapid-key')
vapidKey: () => request<{ vapid_public_key: string }>('GET', '/api/push/vapid-key')
};
// User profile
@@ -232,4 +232,34 @@ export const profile = {
request<{ message: string; user: { id: number; username: string; display_name: string; role: string } }>('PUT', '/api/auth/profile', body)
};
// Attachments
export const attachments = {
upload: async (file: File): Promise<{hash: string, size: number, mime_type: string, original_filename: string}> => {
const formData = new FormData();
formData.append('file', file);
const response = await fetch('/api/attachments', {
method: 'POST',
body: formData,
credentials: 'include'
});
if (!response.ok) {
const err = await response.json().catch(() => ({error: 'Upload failed'}));
throw new Error(err.error || err.detail || 'Upload failed');
}
return response.json();
}
};
// Reactions
export const reactions = {
toggle: (messageId: number, reaction: string, metadata?: Record<string, any>) =>
request<{ action: string; reaction: any; reactions: any[]; workflow_state: string }>(
'POST', `/api/messages/${messageId}/reactions`, { reaction, metadata }
),
get: (messageId: number) =>
request<{ reactions: any[]; workflow_state: string }>(
'GET', `/api/messages/${messageId}/reactions`
)
};
export { ApiError };
@@ -0,0 +1,117 @@
<script lang="ts">
type Attachment = {
hash: string;
original_filename: string;
size: number;
mime_type: string;
is_image: boolean;
};
let { attachment }: { attachment: Attachment } = $props();
let showOverlay = $state(false);
function formatSize(bytes: number): string {
if (bytes < 1024 * 1024) {
return (bytes / 1024).toFixed(1) + ' KB';
}
return (bytes / (1024 * 1024)).toFixed(1) + ' MB';
}
function openOverlay() {
showOverlay = true;
}
function closeOverlay() {
showOverlay = false;
}
function handleOverlayClick(e: MouseEvent) {
if (e.target === e.currentTarget) {
closeOverlay();
}
}
function handleKeydown(e: KeyboardEvent) {
if (e.key === 'Escape') {
closeOverlay();
}
}
</script>
<svelte:window onkeydown={showOverlay ? handleKeydown : undefined} />
{#if attachment.is_image}
<!-- Image thumbnail -->
<button
class="block rounded-lg overflow-hidden border border-border hover:border-border-active transition-colors cursor-pointer bg-bg-tertiary"
onclick={openOverlay}
>
<img
src="/api/attachments/{attachment.hash}"
alt={attachment.original_filename}
class="max-w-[200px] max-h-[200px] object-cover"
loading="lazy"
/>
</button>
<!-- Fullscreen overlay -->
{#if showOverlay}
<div
class="fixed inset-0 bg-black/80 z-50 flex items-center justify-center"
role="dialog"
aria-modal="true"
onclick={handleOverlayClick}
>
<!-- Close button -->
<button
class="absolute top-4 right-4 p-2 rounded-lg bg-white/10 hover:bg-white/20 text-white transition-colors z-10"
onclick={closeOverlay}
aria-label="Close"
>
<svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
<!-- Full-resolution image -->
<img
src="/api/attachments/{attachment.hash}"
alt={attachment.original_filename}
class="max-w-[90vw] max-h-[90vh] object-contain rounded-lg"
/>
<!-- Download button -->
<div class="absolute bottom-6 left-1/2 -translate-x-1/2">
<a
href="/api/attachments/{attachment.hash}"
download={attachment.original_filename}
class="flex items-center gap-2 px-4 py-2 rounded-lg bg-white/10 hover:bg-white/20 text-white text-sm transition-colors"
>
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
</svg>
Download {attachment.original_filename}
</a>
</div>
</div>
{/if}
{:else}
<!-- Non-image file -->
<div class="inline-flex items-center gap-2 px-3 py-2 rounded-lg border border-border bg-bg-tertiary hover:bg-bg-tertiary/80 transition-colors">
<!-- File icon -->
<svg class="w-5 h-5 text-text-secondary flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24" stroke-width="1.5">
<path stroke-linecap="round" stroke-linejoin="round" d="M19.5 14.25v-2.625a3.375 3.375 0 00-3.375-3.375h-1.5A1.125 1.125 0 0113.5 7.125v-1.5a3.375 3.375 0 00-3.375-3.375H8.25m2.25 0H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 00-9-9z" />
</svg>
<div class="min-w-0">
<a
href="/api/attachments/{attachment.hash}"
download={attachment.original_filename}
class="text-sm text-text-link hover:underline block truncate max-w-[200px]"
>
{attachment.original_filename}
</a>
<span class="text-[10px] text-text-secondary">{formatSize(attachment.size)}</span>
</div>
</div>
{/if}
+126 -14
View File
@@ -1,5 +1,5 @@
<script lang="ts">
import { messages as messagesApi, agents as agentsApi, channels as channelsApi } from '$lib/api/client';
import { messages as messagesApi, agents as agentsApi, channels as channelsApi, attachments as attachmentsApi } from '$lib/api/client';
let { onSent = () => {} }: { onSent?: () => void } = $props();
@@ -12,6 +12,49 @@
let error = $state('');
let showOptions = $state(false);
// Attachment state
type UploadedAttachment = { hash: string; original_filename: string; size: number; mime_type: string };
let uploadedAttachments = $state<UploadedAttachment[]>([]);
let uploading = $state(false);
let uploadError = $state('');
let fileInputEl: HTMLInputElement | undefined = $state(undefined);
const ACCEPTED_FILES = '.jpg,.jpeg,.png,.gif,.webp,.svg,.pdf,.txt,.md,.csv,.json,.xml,.yaml,.yml,.log';
function formatFileSize(bytes: number): string {
if (bytes < 1024 * 1024) {
return (bytes / 1024).toFixed(1) + ' KB';
}
return (bytes / (1024 * 1024)).toFixed(1) + ' MB';
}
function triggerFileInput() {
fileInputEl?.click();
}
async function handleFileSelected(e: Event) {
const input = e.target as HTMLInputElement;
const file = input.files?.[0];
if (!file) return;
uploading = true;
uploadError = '';
try {
const result = await attachmentsApi.upload(file);
uploadedAttachments = [...uploadedAttachments, result];
} catch (err: any) {
uploadError = err.message || 'Upload failed';
} finally {
uploading = false;
// Reset file input so same file can be re-selected
if (fileInputEl) fileInputEl.value = '';
}
}
function removeAttachment(hash: string) {
uploadedAttachments = uploadedAttachments.filter(a => a.hash !== hash);
}
// Autocomplete state
let agentList = $state<any[]>([]);
let channelList = $state<any[]>([]);
@@ -55,20 +98,29 @@
function autoResize() {
if (!textareaEl) return;
textareaEl.style.height = 'auto';
// Reset to measure true scrollHeight
textareaEl.style.height = '80px';
const maxHeight = 240; // ~12 lines
const scrollHeight = textareaEl.scrollHeight;
if (scrollHeight > maxHeight) {
textareaEl.style.height = maxHeight + 'px';
textareaEl.style.overflowY = 'auto';
textareaEl.classList.remove('overflow-hidden');
} else {
textareaEl.style.height = scrollHeight + 'px';
textareaEl.style.height = Math.max(80, scrollHeight) + 'px';
textareaEl.style.overflowY = 'hidden';
textareaEl.classList.add('overflow-hidden');
}
}
function isMobile(): boolean {
return typeof window !== 'undefined' && window.innerWidth < 768;
}
function handleKeydown(e: KeyboardEvent) {
if (e.key === 'Enter' && !e.shiftKey) {
// On mobile, Enter inserts newline (send via button only)
// On desktop, Enter sends, Shift+Enter inserts newline
if (e.key === 'Enter' && !e.shiftKey && !isMobile()) {
e.preventDefault();
handleSubmit();
}
@@ -93,13 +145,16 @@
body: body.trim(),
priority,
subject: subject.trim() || undefined,
channel_id: channelId
channel_id: channelId,
attachments: uploadedAttachments.length > 0 ? uploadedAttachments.map(a => a.hash) : undefined
});
to = '';
body = '';
priority = 5;
subject = '';
channelId = undefined;
uploadedAttachments = [];
uploadError = '';
if (textareaEl) {
textareaEl.style.height = '72px';
textareaEl.style.overflowY = 'hidden';
@@ -161,9 +216,9 @@
<!-- Message body -->
<textarea
bind:this={textareaEl}
placeholder="Write a message..."
class="w-full px-4 py-3 bg-transparent text-sm text-text-primary placeholder-text-secondary resize-none outline-none"
style="min-height: 72px; max-height: 240px;"
placeholder="Write a message... {isMobile() ? '' : '(Shift+Enter for new line)'}"
class="w-full px-4 py-3 bg-transparent text-sm text-text-primary placeholder-text-secondary resize-none outline-none overflow-hidden"
style="min-height: 80px; max-height: 240px;"
bind:value={body}
rows="3"
onkeydown={handleKeydown}
@@ -202,14 +257,71 @@
</div>
{/if}
<!-- Hidden file input -->
<input
bind:this={fileInputEl}
type="file"
accept={ACCEPTED_FILES}
class="hidden"
onchange={handleFileSelected}
/>
<!-- Attachment list -->
{#if uploadedAttachments.length > 0 || uploading || uploadError}
<div class="px-4 py-2 border-t border-border space-y-1">
{#if uploadError}
<div class="text-xs text-accent-red">{uploadError}</div>
{/if}
{#if uploading}
<div class="flex items-center gap-2 text-xs text-text-secondary">
<svg class="w-3.5 h-3.5 animate-spin" fill="none" viewBox="0 0 24 24">
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
</svg>
Uploading...
</div>
{/if}
{#each uploadedAttachments as att (att.hash)}
<div class="flex items-center gap-2 text-xs text-text-primary bg-bg-tertiary rounded px-2 py-1">
<svg class="w-3.5 h-3.5 text-text-secondary flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24" stroke-width="1.5">
<path stroke-linecap="round" stroke-linejoin="round" d="M18.375 12.739l-7.693 7.693a4.5 4.5 0 01-6.364-6.364l10.94-10.94A3 3 0 1119.5 7.372L8.552 18.32m.009-.01l-.01.01m5.699-9.941l-7.81 7.81a1.5 1.5 0 002.112 2.13" />
</svg>
<span class="truncate flex-1">{att.original_filename}</span>
<span class="text-text-secondary flex-shrink-0">{formatFileSize(att.size)}</span>
<button
class="p-0.5 rounded hover:bg-bg-secondary text-text-secondary hover:text-accent-red transition-colors flex-shrink-0"
onclick={() => removeAttachment(att.hash)}
title="Remove attachment"
>
<svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
</div>
{/each}
</div>
{/if}
<!-- Bottom bar -->
<div class="flex items-center justify-between px-3 py-2 border-t border-border">
<button
class="text-xs text-text-secondary hover:text-text-primary transition-colors px-2 py-1 rounded hover:bg-bg-tertiary"
onclick={() => (showOptions = !showOptions)}
>
{showOptions ? 'Hide options' : 'Options'}
</button>
<div class="flex items-center gap-1">
<button
class="text-xs text-text-secondary hover:text-text-primary transition-colors px-2 py-1 rounded hover:bg-bg-tertiary"
onclick={() => (showOptions = !showOptions)}
>
{showOptions ? 'Hide options' : 'Options'}
</button>
<button
class="p-1.5 rounded text-text-secondary hover:text-text-primary hover:bg-bg-tertiary transition-colors disabled:opacity-50"
onclick={triggerFileInput}
disabled={uploading}
title="Attach file"
>
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M18.375 12.739l-7.693 7.693a4.5 4.5 0 01-6.364-6.364l10.94-10.94A3 3 0 1119.5 7.372L8.552 18.32m.009-.01l-.01.01m5.699-9.941l-7.81 7.81a1.5 1.5 0 002.112 2.13" />
</svg>
</button>
</div>
<button
class="px-4 py-1.5 bg-accent-green rounded text-xs font-semibold text-white hover:brightness-110 transition-all disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-1.5"
disabled={sending || !body.trim() || !to.trim()}
+35 -3
View File
@@ -1,6 +1,15 @@
<script lang="ts">
import { openThread } from '$lib/stores/thread';
import MessageBody from '$lib/components/MessageBody.svelte';
import AttachmentPreview from '$lib/components/AttachmentPreview.svelte';
type Attachment = {
hash: string;
original_filename: string;
size: number;
mime_type: string;
is_image: boolean;
};
type Message = {
id: number;
@@ -12,6 +21,7 @@
status: string;
created_at: string;
reply_count?: number;
attachments?: Attachment[];
};
let { messages = [], showConversationLink = false, agentTypes = {} }: { messages: Message[]; showConversationLink?: boolean; agentTypes?: Record<string, string> } = $props();
@@ -108,8 +118,30 @@
</div>
<div class="text-sm text-text-primary/90 leading-relaxed"><MessageBody body={msg.body} truncate={300} /></div>
<!-- Thread link -->
{#if showConversationLink && msg.conversation_id}
<!-- Attachments -->
{#if msg.attachments && msg.attachments.length > 0}
<div class="mt-2 flex flex-wrap gap-2">
{#each msg.attachments as att (att.hash)}
<AttachmentPreview attachment={att} />
{/each}
</div>
{/if}
<!-- Reply count badge -->
{#if msg.reply_count && msg.reply_count > 0}
<button
class="mt-1.5 flex items-center gap-1 text-xs text-text-link hover:underline"
onclick={(e) => { e.stopPropagation(); openThread(msg.id, msg.conversation_id, msg.from_agent); }}
>
<svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z" />
</svg>
{msg.reply_count === 1 ? '1 reply' : `${msg.reply_count} replies`}
</button>
{/if}
<!-- Thread link (conversation view) -->
{#if showConversationLink && msg.conversation_id && (!msg.reply_count || msg.reply_count === 0)}
<button
class="mt-1 flex items-center gap-1 text-xs text-text-link hover:underline"
onclick={(e) => { e.stopPropagation(); openThread(msg.id, msg.conversation_id, msg.from_agent); }}
@@ -117,7 +149,7 @@
<svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z" />
</svg>
{msg.reply_count ? `${msg.reply_count} replies` : 'View thread'}
View thread
</button>
{/if}
</div>
+104
View File
@@ -0,0 +1,104 @@
<script lang="ts">
import { reactions as reactionsApi } from '$lib/api/client';
type ReactionEntry = {
agent_name: string;
reaction: string;
metadata?: Record<string, any>;
};
let { reactions = [], messageId }: { reactions: ReactionEntry[]; messageId: number } = $props();
type GroupedReaction = {
type: string;
count: number;
agents: string[];
metadata?: Record<string, any>;
};
let grouped = $derived((() => {
const map = new Map<string, GroupedReaction>();
for (const r of reactions) {
const existing = map.get(r.reaction);
if (existing) {
existing.count++;
existing.agents.push(r.agent_name);
if (r.reaction === 'published' && r.metadata?.url) {
existing.metadata = r.metadata;
}
} else {
map.set(r.reaction, {
type: r.reaction,
count: 1,
agents: [r.agent_name],
metadata: r.metadata
});
}
}
return Array.from(map.values());
})());
const reactionEmoji: Record<string, string> = {
approve: '\u2705',
reject: '\u274C',
in_progress: '\u23F3',
done: '\u2714\uFE0F',
published: '\uD83D\uDE80'
};
const reactionColors: Record<string, string> = {
approve: 'bg-accent-green/15 text-accent-green border-accent-green/30 hover:bg-accent-green/25',
reject: 'bg-accent-red/15 text-accent-red border-accent-red/30 hover:bg-accent-red/25',
in_progress: 'bg-accent-blue/15 text-accent-blue border-accent-blue/30 hover:bg-accent-blue/25',
done: 'bg-bg-tertiary text-text-secondary border-border hover:bg-bg-tertiary/80',
published: 'bg-cyan-500/15 text-cyan-400 border-cyan-500/30 hover:bg-cyan-500/25'
};
let toggling = $state(false);
async function handleToggle(reactionType: string) {
if (toggling) return;
toggling = true;
try {
const result = await reactionsApi.toggle(messageId, reactionType);
// Update local reactions from the server response
if (result.reactions) {
reactions = result.reactions;
}
} catch {
// silently fail
} finally {
toggling = false;
}
}
</script>
{#if grouped.length > 0}
<div class="flex flex-wrap gap-1 mt-1">
{#each grouped as group}
<button
class="inline-flex items-center gap-1 px-1.5 py-0.5 rounded-full text-[11px] border transition-colors cursor-pointer {reactionColors[group.type] ?? 'bg-bg-tertiary text-text-secondary border-border'}"
title={group.agents.join(', ')}
onclick={(e) => { e.stopPropagation(); handleToggle(group.type); }}
disabled={toggling}
>
<span>{reactionEmoji[group.type] ?? group.type}</span>
<span class="font-medium">{group.count}</span>
{#if group.type === 'published' && group.metadata?.url}
<a
href={group.metadata.url}
target="_blank"
rel="noopener noreferrer"
class="ml-0.5 hover:underline"
onclick={(e) => e.stopPropagation()}
title="View published URL"
>
<svg class="w-3 h-3 inline" fill="none" stroke="currentColor" viewBox="0 0 24 24" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1" />
</svg>
</a>
{/if}
</button>
{/each}
</div>
{/if}
@@ -2,6 +2,7 @@
import { activeThread, closeThread } from '$lib/stores/thread';
import { conversations as convsApi, messages as messagesApi } from '$lib/api/client';
import MessageBody from '$lib/components/MessageBody.svelte';
import AttachmentPreview from '$lib/components/AttachmentPreview.svelte';
let conversation = $state<any>(null);
let threadMessages = $state<any[]>([]);
@@ -164,6 +165,13 @@
{/if}
</div>
<div class="text-xs text-text-primary/90 leading-relaxed"><MessageBody body={msg.body} /></div>
{#if msg.attachments && msg.attachments.length > 0}
<div class="mt-1.5 flex flex-wrap gap-1.5">
{#each msg.attachments as att (att.hash)}
<AttachmentPreview attachment={att} />
{/each}
</div>
{/if}
</div>
</div>
</div>
@@ -0,0 +1,26 @@
<script lang="ts">
let { state }: { state: string } = $props();
let badgeClass = $derived((() => {
switch (state) {
case 'proposed':
return 'bg-accent-yellow/20 text-accent-yellow';
case 'approved':
return 'bg-accent-green text-white';
case 'in_progress':
return 'bg-accent-blue text-white';
case 'rejected':
return 'bg-accent-red text-white';
case 'done':
return 'bg-bg-tertiary text-text-secondary';
case 'published':
return 'bg-cyan-500/20 text-cyan-400';
default:
return 'bg-bg-tertiary text-text-secondary';
}
})());
</script>
<span class="inline-flex items-center px-1.5 py-0.5 rounded text-[10px] font-medium leading-tight {badgeClass}">
{state}
</span>
+1 -1
View File
@@ -101,7 +101,7 @@
{:else if $user}
<div class="h-screen flex overflow-hidden bg-bg-primary">
<Sidebar open={sidebarOpen} onclose={() => (sidebarOpen = false)} />
<div class="md:ml-[260px] flex-1 flex flex-col min-w-0">
<div class="md:ml-[260px] flex-1 flex flex-col min-w-0 overflow-x-hidden">
<Header onMenuToggle={() => (sidebarOpen = !sidebarOpen)} />
<main class="flex-1 overflow-y-auto flex flex-col">
{@render children()}
+14 -14
View File
@@ -91,7 +91,7 @@
});
</script>
<div class="p-5 max-w-6xl">
<div class="p-3 md:p-5 max-w-6xl w-full">
<!-- Top bar -->
<div class="flex items-center justify-between mb-5">
<div>
@@ -120,22 +120,22 @@
{/if}
<!-- Summary Cards -->
<div class="grid grid-cols-2 md:grid-cols-4 gap-3 mb-5">
<div class="card p-4">
<p class="text-xs text-text-secondary mb-1">Total Messages</p>
<p class="text-2xl font-bold text-text-primary font-display">{loadingData ? '-' : summary.total_messages}</p>
<div class="grid grid-cols-4 gap-2 md:gap-3 mb-5">
<div class="card p-3 md:p-4">
<p class="text-[10px] md:text-xs text-text-secondary mb-1">Messages</p>
<p class="text-lg md:text-2xl font-bold text-text-primary font-display">{loadingData ? '-' : summary.total_messages}</p>
</div>
<div class="card p-4">
<p class="text-xs text-text-secondary mb-1">Agents</p>
<p class="text-2xl font-bold text-text-primary font-display">{loadingData ? '-' : summary.total_agents}</p>
<div class="card p-3 md:p-4">
<p class="text-[10px] md:text-xs text-text-secondary mb-1">Agents</p>
<p class="text-lg md:text-2xl font-bold text-text-primary font-display">{loadingData ? '-' : summary.total_agents}</p>
</div>
<div class="card p-4">
<p class="text-xs text-text-secondary mb-1">Channels</p>
<p class="text-2xl font-bold text-text-primary font-display">{loadingData ? '-' : summary.total_channels}</p>
<div class="card p-3 md:p-4">
<p class="text-[10px] md:text-xs text-text-secondary mb-1">Channels</p>
<p class="text-lg md:text-2xl font-bold text-text-primary font-display">{loadingData ? '-' : summary.total_channels}</p>
</div>
<div class="card p-4">
<p class="text-xs text-text-secondary mb-1">Conversations</p>
<p class="text-2xl font-bold text-text-primary font-display">{loadingData ? '-' : recentConversations.length}</p>
<div class="card p-3 md:p-4">
<p class="text-[10px] md:text-xs text-text-secondary mb-1">Convos</p>
<p class="text-lg md:text-2xl font-bold text-text-primary font-display">{loadingData ? '-' : recentConversations.length}</p>
</div>
</div>
+88 -5
View File
@@ -1,9 +1,12 @@
<script lang="ts">
import { page } from '$app/stores';
import { channels as channelsApi, messages as messagesApi, agents as agentsApi } from '$lib/api/client';
import { channels as channelsApi, messages as messagesApi, agents as agentsApi, attachments as attachmentsApi } from '$lib/api/client';
import { openThread, closeThread } from '$lib/stores/thread';
import { notifications } from '$lib/stores/notifications';
import MessageBody from '$lib/components/MessageBody.svelte';
import AttachmentPreview from '$lib/components/AttachmentPreview.svelte';
import WorkflowBadge from '$lib/components/WorkflowBadge.svelte';
import ReactionPills from '$lib/components/ReactionPills.svelte';
let channel = $state<any>(null);
let members = $state<any[]>([]);
@@ -21,6 +24,39 @@
let sending = $state(false);
let sendError = $state('');
// Attachment state
let uploadedAttachments = $state<{hash: string, name: string, size: number}[]>([]);
let uploading = $state(false);
let fileInputEl: HTMLInputElement;
function triggerFileInput() { fileInputEl?.click(); }
async function handleFileSelected(e: Event) {
const input = e.target as HTMLInputElement;
const file = input.files?.[0];
if (!file) return;
uploading = true;
try {
const result = await attachmentsApi.upload(file);
uploadedAttachments = [...uploadedAttachments, { hash: result.hash, name: result.original_filename, size: result.size }];
} catch (err: any) {
sendError = err.message || 'Upload failed';
} finally {
uploading = false;
input.value = '';
}
}
function removeAttachment(hash: string) {
uploadedAttachments = uploadedAttachments.filter(a => a.hash !== hash);
}
function formatFileSize(bytes: number): string {
if (bytes < 1024) return bytes + ' B';
if (bytes < 1048576) return (bytes / 1024).toFixed(1) + ' KB';
return (bytes / 1048576).toFixed(1) + ' MB';
}
// Mark-as-read timer
let markReadTimer: ReturnType<typeof setTimeout> | null = null;
@@ -132,15 +168,17 @@
}
async function handleSend() {
if (!body.trim()) return;
if (!body.trim() && uploadedAttachments.length === 0) return;
sending = true;
sendError = '';
try {
await messagesApi.send({
body: body.trim(),
channel_id: channel.id
body: body.trim() || '(attachment)',
channel_id: channel.id,
attachments: uploadedAttachments.length > 0 ? uploadedAttachments.map(a => a.hash) : undefined
});
body = '';
uploadedAttachments = [];
await loadMessages();
} catch (err: any) {
sendError = err.message || 'Failed to send message';
@@ -270,6 +308,17 @@
<span class="text-xs text-text-secondary">{formatTime(msg.created_at)}</span>
</div>
<div class="text-sm text-text-primary/90 leading-relaxed"><MessageBody body={msg.body} /></div>
{#if msg.workflow_state}
<WorkflowBadge state={msg.workflow_state} />
{/if}
<ReactionPills reactions={msg.reactions ?? []} messageId={msg.id} />
{#if msg.attachments?.length > 0}
<div class="flex flex-wrap gap-2 mt-1.5">
{#each msg.attachments as att}
<AttachmentPreview attachment={att} />
{/each}
</div>
{/if}
{#if msg.reply_count > 0}
<button
class="mt-1 flex items-center gap-1 text-xs text-accent-blue hover:underline"
@@ -310,6 +359,30 @@
Register an agent to send messages
</div>
{:else}
<!-- Hidden file input -->
<input
type="file"
class="hidden"
accept=".jpg,.jpeg,.png,.gif,.webp,.svg,.pdf,.txt,.md,.csv,.json,.xml,.yaml,.yml,.log"
bind:this={fileInputEl}
onchange={handleFileSelected}
/>
<!-- Attachment preview chips -->
{#if uploadedAttachments.length > 0}
<div class="flex flex-wrap gap-1.5 mb-1.5">
{#each uploadedAttachments as att}
<span class="inline-flex items-center gap-1 px-2 py-1 bg-bg-tertiary border border-border rounded text-xs text-text-primary">
<svg class="w-3 h-3 text-text-secondary" fill="none" stroke="currentColor" viewBox="0 0 24 24" stroke-width="1.5"><path stroke-linecap="round" stroke-linejoin="round" d="M18.375 12.739l-7.693 7.693a4.5 4.5 0 01-6.364-6.364l10.94-10.94A3 3 0 1119.5 7.372L8.552 18.32m.009-.01l-.01.01m5.699-9.941l-7.81 7.81a1.5 1.5 0 002.112 2.13" /></svg>
{att.name}
<span class="text-text-secondary">({formatFileSize(att.size)})</span>
<button class="ml-0.5 text-text-secondary hover:text-accent-red" onclick={() => removeAttachment(att.hash)} title="Remove">&times;</button>
</span>
{/each}
</div>
{/if}
{#if uploading}
<div class="mb-1.5 text-xs text-text-secondary">Uploading...</div>
{/if}
<div class="flex items-end gap-2 bg-bg-tertiary rounded-lg border border-border focus-within:border-border-active transition-colors">
<textarea
placeholder="Message #{channelName}..."
@@ -318,9 +391,19 @@
rows="1"
onkeydown={handleKeydown}
></textarea>
<button
class="p-2 mb-1 rounded-md text-text-secondary hover:text-text-primary hover:bg-bg-secondary transition-all"
onclick={triggerFileInput}
title="Attach file"
type="button"
>
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24" stroke-width="1.5">
<path stroke-linecap="round" stroke-linejoin="round" d="M18.375 12.739l-7.693 7.693a4.5 4.5 0 01-6.364-6.364l10.94-10.94A3 3 0 1119.5 7.372L8.552 18.32m.009-.01l-.01.01m5.699-9.941l-7.81 7.81a1.5 1.5 0 002.112 2.13" />
</svg>
</button>
<button
class="p-2 mr-1 mb-1 rounded-md bg-accent-green text-white hover:brightness-110 transition-all disabled:opacity-40 disabled:cursor-not-allowed"
disabled={sending || !body.trim()}
disabled={sending || (!body.trim() && uploadedAttachments.length === 0)}
onclick={handleSend}
>
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24" stroke-width="2">
+3 -5
View File
@@ -108,15 +108,13 @@
const reg = await navigator.serviceWorker.ready;
const sub = await reg.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: urlBase64ToUint8Array(keyRes.public_key)
applicationServerKey: urlBase64ToUint8Array(keyRes.vapid_public_key)
});
const subJson = sub.toJSON();
await pushApi.subscribe({
endpoint: sub.endpoint,
keys: {
p256dh: subJson.keys?.p256dh || '',
auth: subJson.keys?.auth || ''
}
key_p256dh: subJson.keys?.p256dh || '',
key_auth: subJson.keys?.auth || ''
});
pushEnabled = true;
}