Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
Merge remote-tracking branch 'origin/main' into feature/multi-agent-backend
yushen0b7de540524b
diff --cc CLAUDE.mdindex 840b5f7009,f30da4fd04..312d6832f9--- a/CLAUDE.md+++ b/CLAUDE.md@@@ -14,52 -14,61 +14,102 @@@ Multica is an AI-native task managemen**Polyglot monorepo** — Go backend + TypeScript frontend.-- `server/` — Go backend (Chi + sqlc + gorilla/websocket)+- `server/` — Go backend (Chi router, sqlc for DB, gorilla/websocket for real-time)- `apps/web/` — Next.js 16 frontend (App Router)-- `packages/` — Shared TypeScript packages (ui, types, sdk, utils)+- `packages/` — Shared TypeScript packages (ui, types, sdk, store, hooks, utils)-### 2.1 Web App Structure (`apps/web/`)++### Web App Structure (`apps/web/`)++ The frontend uses a **feature-based architecture** with three layers:++ ```+ apps/web/+ ├── app/ # Routing layer (thin shells — import from features/)+ ├── features/ # Business logic, organized by domain+ ├── shared/ # Cross-feature utilities (api client)+ ```++ **`app/`** — Next.js App Router pages. Route files should be thin: import and re-export from `features/`. Layout components and route-specific glue (redirects, auth guards) live here. Shared layout components (e.g. `app-sidebar`) stay in `app/(dashboard)/_components/`.++ **`features/`** — Domain modules, each with its own components, hooks, stores, and config:++ | Feature | Purpose | Exports |+ |---|---|---|+ | `features/auth/` | Authentication state | `useAuthStore`, `AuthInitializer` |+ | `features/workspace/` | Workspace, members, agents | `useWorkspaceStore`, `useActorName` |+ | `features/issues/` | Issue components and config | Icons, pickers, status/priority config |+ | `features/realtime/` | WebSocket connection | `WSProvider`, `useWSEvent` |++ **`shared/`** — Code used across multiple features. Currently only `api.ts` (SDK singleton).+-### 2.2 State Management++### State Management++ - **Zustand** for global client state (`features/auth/store.ts`, `features/workspace/store.ts`).+ - **React Context** only for connection lifecycle (`WSProvider` in `features/realtime/`).+ - **Local `useState`** for component-scoped UI state (forms, modals, filters).+ - Do not use React Context for data that can be a zustand store.++ **Store conventions:**+ - One store per feature domain. Import via `useAuthStore(selector)` or `useWorkspaceStore(selector)`.+ - Stores must not call `useRouter` or any React hooks — keep navigation in components.+ - Cross-store reads use `useOtherStore.getState()` inside actions (not hooks).+ - Dependency direction: `workspace` → `auth`, `realtime` → `auth`, `issues` → `workspace`. Never reverse.+-### 2.3 Import Aliases++### Import Aliases++ Use `@/` alias (maps to `apps/web/`):+ ```typescript+ import { api } from "@/shared/api";+ import { useAuthStore } from "@/features/auth";+ import { useWorkspaceStore } from "@/features/workspace";+ import { useWSEvent } from "@/features/realtime";+ import { StatusIcon } from "@/features/issues/components";+ ```++ Within a feature, use relative imports. Between features or to shared, use `@/`.+-## 3. Core Workflow Commands+### Data Flow++```+Browser → ApiClient (SDK) → REST API (Chi handlers) → sqlc queries → PostgreSQL+Browser ← WSClient (SDK) ← WebSocket ← Hub.Broadcast() ← Handlers/TaskService+```++### Backend Structure (`server/`)++- **Entry points** (`cmd/`): `server` (HTTP API), `daemon` (local agent runtime), `migrate`, `seed`+- **Handlers** (`internal/handler/`): One file per domain (issue, comment, agent, auth, daemon, etc.). Each handler holds `Queries`, `DB`, `Hub`, and `TaskService`.+- **Real-time** (`internal/realtime/`): Hub manages WebSocket clients. Server broadcasts events; inbound WS message routing is still TODO.+- **Auth** (`internal/auth/` + `internal/middleware/`): JWT (HS256). Middleware sets `X-User-ID` and `X-User-Email` headers. Login creates user on-the-fly if not found.+- **Task lifecycle** (`internal/service/task.go`): Orchestrates agent work — enqueue → claim → start → complete/fail. Syncs issue status automatically and broadcasts WS events at each transition.+- **Database**: sqlc generates Go code from SQL in `pkg/db/queries/` → `pkg/db/generated/`. Migrations in `migrations/`.+- **Routes** (`cmd/server/router.go`): Public routes (auth, health, ws) + protected routes (require JWT) + daemon routes (unauthenticated, separate auth model).++### Frontend Structure (`apps/web/`)++- **App Router layout groups**: `(auth)/` for login, `(dashboard)/` for protected routes+- **Auth context** (`lib/auth-context.tsx`): Global provider for user, workspace, members, agents. Hydrates from localStorage. Provides actor lookup helpers (`getMemberName`, `getAgentName`, `getActorName`).+- **WebSocket context** (`lib/ws-context.tsx`): Wraps `WSClient` from SDK. `useWSEvent()` hook auto-subscribes/unsubscribes.+- **API client** (`lib/api.ts`): Singleton `ApiClient` from `@multica/sdk`, initialized from localStorage.+- **State**: Zustand stores (`@multica/store`) for issues, agents, inbox. WebSocket events keep stores in sync without re-fetching.++### Key Packages++- **`@multica/sdk`**: `ApiClient` (REST) and `WSClient` (WebSocket) classes. All backend communication goes through here.+- **`@multica/types`**: Shared domain types + WebSocket event types (issue:created/updated/deleted, task:*, agent:status, comment:*, inbox:new, daemon:*).+- **`@multica/store`**: Zustand stores — simple arrays with add/update/remove. No persistence; memory only.+- **`@multica/ui`**: shadcn/ui component library with Radix primitives, Tailwind CSS 4, Shiki syntax highlighting for markdown.+- **`@multica/hooks`**: `useRealtime()` (WS → store sync), `useIssues()`, `useAgents()`, `useInbox()` (fetch + cache).++### Multi-tenancy++All queries filter by `workspace_id`. Membership checks gate access. `X-Workspace-ID` header routes requests to the correct workspace.++### Agent Assignees++Assignees are polymorphic — can be a member or an agent. `assignee_type` + `assignee_id` on issues. Agents render with distinct styling (purple background, robot icon).++## Commands```bash# One-click setup & run@@@ -83,30 -92,12 +133,30 @@@ make sqlc # Regenerate sqlmake migrate-up # Run database migrationsmake migrate-down # Rollback migrations+# Run a single Go test+cd server && go test ./internal/handler/ -run TestName++# Run a single TS test+pnpm --filter @multica/web exec vitest run src/path/to/file.test.ts++# Run a single E2E test (requires backend + frontend running)+pnpm exec playwright test e2e/tests/specific-test.spec.ts+# Infrastructure- docker compose up -d # Start PostgreSQL- docker compose down # Stop PostgreSQL+ make db-up # Start shared PostgreSQL+ make db-down # Stop shared PostgreSQL```-## 4. Coding Rules+### Worktree Support++For isolated feature testing with a separate database:+```bash+make worktree-env # Generate .env.worktree with unique DB/ports+make setup-worktree # Setup using .env.worktree+make start-worktree # Start using .env.worktree+```++## Coding Rules- TypeScript strict mode is enabled; keep types explicit.- Go code follows standard Go conventions (gofmt, go vet).@@@ -117,19 -108,23 +167,23 @@@- Treat compatibility code as a maintenance cost, not a default safety mechanism. Avoid "just in case" branches that make the codebase harder to reason about.- Avoid broad refactors unless required by the task.-## 5. UI/UX Rules+## UI/UX Rules- Prefer `packages/ui` shadcn components over custom implementations.- - Do not introduce extra state (useState, context, reducers) unless explicitly required by the design.+ - **shadcn official components** → `packages/ui/src/components/ui/` — keep this directory clean; install missing components via `npx shadcn add`, do not mix in business code.+ - **Shared business components & utils** → `packages/ui/src/components/common/` — reusable project-level UI components (e.g. ActorAvatar) and shared utilities live here.+ - **Feature-specific components** → `features/<domain>/components/` — issue icons, pickers, and other domain-bound UI live inside their feature module, not in `packages/ui`.+ - Use shadcn design tokens for styling (e.g. `bg-primary`, `text-muted-foreground`, `text-destructive`). Avoid hardcoded color values (e.g. `text-red-500`, `bg-gray-100`).+ - Do not introduce extra state (useState, context, reducers) unless explicitly required by the design. Prefer zustand stores for shared state over React Context.- Pay close attention to **overflow** (truncate long text, scrollable containers), **alignment**, and **spacing** consistency.- When unsure about interaction or state design, ask — the user will provide direction.-## 6. Testing Rules+## Testing Rules- **TypeScript**: Vitest. Mock external/third-party dependencies only.- - **Go**: Standard `go test`. Use testcontainers or test database for DB tests.+ - **Go**: Standard `go test`. Tests should create their own fixture data in a test database.-## 7. Commit Rules+## Commit Rules- Use atomic commits grouped by logical intent.- Conventional format:diff --cc Makefileindex 929ba7c77f,f9deb94db5..07d3213b6d--- a/Makefile+++ b/Makefile@@@ -1,4 -1,4 +1,4 @@@- .PHONY: dev daemon cli build test migrate-up migrate-down sqlc seed clean setup start stop check worktree-env setup-main start-main stop-main check-main setup-worktree start-worktree stop-worktree check-worktree-.PHONY: dev daemon build test migrate-up migrate-down sqlc clean setup start stop check worktree-env setup-main start-main stop-main check-main setup-worktree start-worktree stop-worktree check-worktree db-up db-down++.PHONY: dev daemon cli build test migrate-up migrate-down sqlc seed clean setup start stop check worktree-env setup-main start-main stop-main check-main setup-worktree start-worktree stop-worktree check-worktree db-up db-downMAIN_ENV_FILE ?= .envWORKTREE_ENV_FILE ?= .env.worktree@@@ -123,9 -119,11 +125,11 @@@ COMMIT ?= $(shell git rev-parse --shorbuild:cd server && go build -o bin/server ./cmd/server- cd server && go build -o bin/daemon ./cmd/daemon+ cd server && go build -ldflags "-X main.version=$(VERSION) -X main.commit=$(COMMIT)" -o bin/multica-cli ./cmd/multicatest:+ $(REQUIRE_ENV)+ @bash scripts/ensure-postgres.sh "$(ENV_FILE)"cd server && go test ./...# Databasediff --cc apps/web/app/(dashboard)/settings/page.tsxindex da0c267856,ea117c7b25..27ecc0646e--- a/apps/web/app/(dashboard)/settings/page.tsx+++ b/apps/web/app/(dashboard)/settings/page.tsx@@@ -333,23 -339,10 +342,23 @@@ export default function SettingsPage()placeholder="What does this workspace focus on?"/></div>+ <div>- <label className="text-xs font-medium text-muted-foreground">++ <Label className="text-xs text-muted-foreground">+ Context- </label>++ </Label>+ <textarea+ value={context}+ onChange={(e) => setContext(e.target.value)}+ rows={4}+ disabled={!canManageWorkspace}+ className="mt-1 w-full rounded-md border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring resize-none"+ placeholder="Background information and context for AI agents working in this workspace"+ />+ </div><div>- <label className="text-xs font-medium text-muted-foreground">+ <Label className="text-xs text-muted-foreground">Slug- </label>+ </Label><div className="mt-1 rounded-md border bg-muted/50 px-3 py-2 text-sm text-muted-foreground">{workspace.slug}</div>diff --cc server/internal/daemon/client.goindex 98a654fb45,0000000000..07b5aef2d6mode 100644,000000..100644--- a/server/internal/daemon/client.go+++ b/server/internal/daemon/client.go@@@ -1,157 -1,0 +1,182 @@@+package daemon++import (+ "bytes"+ "context"+ "encoding/json"++ "errors"+ "fmt"+ "io"+ "net/http"+ "net/url"+ "strings"+ "time"+)+++// requestError is returned by postJSON/getJSON when the server responds with an error status.++type requestError struct {++ Method string++ Path string++ StatusCode int++ Body string++}++++func (e *requestError) Error() string {++ return fmt.Sprintf("%s %s returned %d: %s", e.Method, e.Path, e.StatusCode, e.Body)++}++++// isWorkspaceNotFoundError returns true if the error is a 404 with "workspace not found" body.++func isWorkspaceNotFoundError(err error) bool {++ var reqErr *requestError++ if !errors.As(err, &reqErr) {++ return false++ }++ if reqErr.StatusCode != http.StatusNotFound {++ return false++ }++ return strings.Contains(strings.ToLower(reqErr.Body), "workspace not found")++}+++// Client handles HTTP communication with the Multica server daemon API.+type Client struct {+ baseURL string+ client *http.Client+}++// NewClient creates a new daemon API client.+func NewClient(baseURL string) *Client {+ return &Client{+ baseURL: baseURL,+ client: &http.Client{Timeout: 30 * time.Second},+ }+}++func (c *Client) ClaimTask(ctx context.Context, runtimeID string) (*Task, error) {+ var resp struct {+ Task *Task `json:"task"`+ }+ if err := c.postJSON(ctx, fmt.Sprintf("/api/daemon/runtimes/%s/tasks/claim", runtimeID), map[string]any{}, &resp); err != nil {+ return nil, err+ }+ return resp.Task, nil+}++func (c *Client) CreatePairingSession(ctx context.Context, req map[string]string) (PairingSession, error) {+ var resp PairingSession+ if err := c.postJSON(ctx, "/api/daemon/pairing-sessions", req, &resp); err != nil {+ return PairingSession{}, err+ }+ return resp, nil+}++func (c *Client) GetPairingSession(ctx context.Context, token string) (PairingSession, error) {+ var resp PairingSession+ if err := c.getJSON(ctx, fmt.Sprintf("/api/daemon/pairing-sessions/%s", url.PathEscape(token)), &resp); err != nil {+ return PairingSession{}, err+ }+ return resp, nil+}++func (c *Client) ClaimPairingSession(ctx context.Context, token string) (PairingSession, error) {+ var resp PairingSession+ if err := c.postJSON(ctx, fmt.Sprintf("/api/daemon/pairing-sessions/%s/claim", url.PathEscape(token)), map[string]any{}, &resp); err != nil {+ return PairingSession{}, err+ }+ return resp, nil+}++func (c *Client) StartTask(ctx context.Context, taskID string) error {+ return c.postJSON(ctx, fmt.Sprintf("/api/daemon/tasks/%s/start", taskID), map[string]any{}, nil)+}++func (c *Client) ReportProgress(ctx context.Context, taskID, summary string, step, total int) error {+ return c.postJSON(ctx, fmt.Sprintf("/api/daemon/tasks/%s/progress", taskID), map[string]any{+ "summary": summary,+ "step": step,+ "total": total,+ }, nil)+}++func (c *Client) CompleteTask(ctx context.Context, taskID, output string) error {+ return c.postJSON(ctx, fmt.Sprintf("/api/daemon/tasks/%s/complete", taskID), map[string]any{+ "output": output,+ }, nil)+}++func (c *Client) FailTask(ctx context.Context, taskID, errMsg string) error {+ return c.postJSON(ctx, fmt.Sprintf("/api/daemon/tasks/%s/fail", taskID), map[string]any{+ "error": errMsg,+ }, nil)+}++func (c *Client) SendHeartbeat(ctx context.Context, runtimeID string) error {+ return c.postJSON(ctx, "/api/daemon/heartbeat", map[string]string{+ "runtime_id": runtimeID,+ }, nil)+}++func (c *Client) Register(ctx context.Context, req map[string]any) ([]Runtime, error) {+ var resp struct {+ Runtimes []Runtime `json:"runtimes"`+ }+ if err := c.postJSON(ctx, "/api/daemon/register", req, &resp); err != nil {+ return nil, err+ }+ return resp.Runtimes, nil+}++func (c *Client) postJSON(ctx context.Context, path string, reqBody any, respBody any) error {+ var body io.Reader+ if reqBody != nil {+ data, err := json.Marshal(reqBody)+ if err != nil {+ return err+ }+ body = bytes.NewReader(data)+ }++ req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.baseURL+path, body)+ if err != nil {+ return err+ }+ req.Header.Set("Content-Type", "application/json")++ resp, err := c.client.Do(req)+ if err != nil {+ return err+ }+ defer resp.Body.Close()++ if resp.StatusCode >= 400 {+ data, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))- return fmt.Errorf("%s %s returned %d: %s", http.MethodPost, path, resp.StatusCode, strings.TrimSpace(string(data)))++ return &requestError{Method: http.MethodPost, Path: path, StatusCode: resp.StatusCode, Body: strings.TrimSpace(string(data))}+ }+ if respBody == nil {+ io.Copy(io.Discard, resp.Body)+ return nil+ }+ return json.NewDecoder(resp.Body).Decode(respBody)+}++func (c *Client) getJSON(ctx context.Context, path string, respBody any) error {+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.baseURL+path, nil)+ if err != nil {+ return err+ }++ resp, err := c.client.Do(req)+ if err != nil {+ return err+ }+ defer resp.Body.Close()++ if resp.StatusCode >= 400 {+ data, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))- return fmt.Errorf("%s %s returned %d: %s", http.MethodGet, path, resp.StatusCode, strings.TrimSpace(string(data)))++ return &requestError{Method: http.MethodGet, Path: path, StatusCode: resp.StatusCode, Body: strings.TrimSpace(string(data))}+ }+ if respBody == nil {+ io.Copy(io.Discard, resp.Body)+ return nil+ }+ return json.NewDecoder(resp.Body).Decode(respBody)+}diff --cc server/internal/daemon/daemon_test.goindex bca2b9764a,8ef47f140a..7888a5b125--- a/server/internal/daemon/daemon_test.go+++ b/server/internal/daemon/daemon_test.go@@@ -1,6 -1,7 +1,7 @@@-package main+package daemonimport (+ "net/http""os""path/filepath""strings"