# Issue #94: Spoke Configuration UI (FED-011)

## Objective

Implement a Spoke Configuration UI that allows administrators to configure their local instance's federation capabilities and settings. This is the spoke-side configuration that determines what features this instance exposes to the federation.

## Context

This is THE FINAL implementation issue for M7-Federation! All backend and other UI components are complete:

- Instance Identity Model (FED-001) ✅
- CONNECT/DISCONNECT Protocol (FED-002) ✅
- OIDC Integration (FED-003) ✅
- Identity Linking (FED-004) ✅
- QUERY/COMMAND/EVENT message types (FED-005/006/007) ✅
- Connection Manager UI (FED-008) ✅
- Aggregated Dashboard (FED-009) ✅
- Agent Spawn via Federation (FED-010) ✅

Now we need the UI to configure the LOCAL instance (spoke) settings.

## Requirements

Frontend requirements:

- Configure local instance federation settings
- Enable/disable federation features:
  - Query support (allow remote instances to query this instance)
  - Command support (allow remote instances to send commands)
  - Event support (allow remote instances to subscribe to events)
  - Agent spawn support (allow remote instances to spawn agents)
- Manage instance metadata (name, description)
- Display current instance identity (ID, URL, public key)
- PDA-friendly design (no demanding language)
- Admin-only access (requires admin privileges)
- Proper validation and user feedback
- Minimum 85% test coverage

## Backend API Available

From `federation.controller.ts`:

- `GET /api/v1/federation/instance` - Get instance identity
- `POST /api/v1/federation/instance/regenerate-keys` - Regenerate keypair (admin only)

Need to ADD:

- `PATCH /api/v1/federation/instance` - Update instance configuration (admin only)

## Instance Schema

From `schema.prisma`:

```prisma
model Instance {
  id         String @id @default(uuid()) @db.Uuid
  instanceId String @unique @map("instance_id")
  name       String
  url        String
  publicKey  String @map("public_key") @db.Text
  privateKey String @map("private_key") @db.Text // Encrypted

  capabilities Json @default("{}")
  metadata     Json @default("{}")

  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
}
```

Capabilities structure:

```typescript
interface FederationCapabilities {
  supportsQuery: boolean;
  supportsCommand: boolean;
  supportsEvent: boolean;
  supportsAgentSpawn: boolean;
  protocolVersion: string;
}
```

## Approach

### Phase 1: Backend API Endpoint (TDD)

1. Add `UpdateInstanceDto` in federation DTOs
2. Add `updateInstanceConfiguration()` method to `FederationService`
3. Add `PATCH /api/v1/federation/instance` endpoint to controller
4. Write comprehensive tests
5. Ensure admin-only access via `AdminGuard`

### Phase 2: Frontend API Client (TDD)

1. Extend `federation.ts` API client with:
   - `updateInstanceConfiguration(data)` function
   - `UpdateInstanceRequest` interface
   - Tests for the new API function

### Phase 3: Core Components (TDD)

1. Create `SpokeConfigurationForm` component:
   - Display current instance identity (read-only)
   - Edit instance name and description
   - Toggle federation capabilities (checkboxes)
   - Save/Cancel actions
   - Loading and error states

2. Create `CapabilityToggle` component:
   - Individual capability toggle with label
   - Help text explaining what each capability does
   - Disabled state when saving

3. Create `RegenerateKeysDialog` component:
   - Warning about regenerating keys
   - Confirmation dialog
   - Shows new public key after regeneration

### Phase 4: Page Implementation

1. Create `/federation/settings` page
2. Integrate components
3. Admin-only route protection
4. Add loading and error states
5. Success feedback on save

### Phase 5: PDA-Friendly Polish

1. Review all language for PDA-friendliness
2. Implement calm visual indicators
3. Add helpful descriptions for each capability
4. Test error messaging
5. Add confirmation dialogs for destructive actions

## Design Decisions

### PDA-Friendly Language

❌ NEVER:

- "You must configure"
- "Required settings"
- "Critical - configure now"
- "Error: Invalid configuration"

✅ ALWAYS:

- "Configure your instance settings"
- "Recommended settings"
- "Consider configuring these options"
- "Unable to save configuration"

### Visual Design

- Use Shadcn/ui components (Card, Switch, Button, Dialog)
- Clear section headers: "Instance Identity", "Federation Capabilities", "Advanced"
- Read-only fields for sensitive data (instance ID, public key)
- Truncate long public key with "Copy" button
- Soft color indicators: 🟢 Enabled, ⚪ Disabled

### Component Structure

```
apps/web/src/
├── app/(authenticated)/federation/
│   └── settings/
│       └── page.tsx                         # NEW
├── components/federation/
│   ├── SpokeConfigurationForm.tsx           # NEW
│   ├── SpokeConfigurationForm.test.tsx      # NEW
│   ├── CapabilityToggle.tsx                 # NEW
│   ├── CapabilityToggle.test.tsx            # NEW
│   ├── RegenerateKeysDialog.tsx             # NEW
│   └── RegenerateKeysDialog.test.tsx        # NEW
└── lib/api/
    └── federation.ts                         # UPDATE
```

### Capability Descriptions

Each capability toggle includes help text:

- **Query Support**: "Allows connected instances to query data from this instance (tasks, events, projects)"
- **Command Support**: "Allows connected instances to send commands to this instance"
- **Event Support**: "Allows connected instances to subscribe to events from this instance"
- **Agent Spawn Support**: "Allows connected instances to spawn and manage agents on this instance"

## Progress

- [x] Create scratchpad
- [x] Add backend API endpoint (PATCH /api/v1/federation/instance)
- [x] Write tests for FederationService.updateInstanceConfiguration
- [x] Implement FederationService.updateInstanceConfiguration
- [x] Update FederationController with PATCH endpoint
- [x] Add audit logging for configuration updates
- [x] Extend frontend API client (federation.ts)
- [x] Write tests for SpokeConfigurationForm (10 tests, all passing)
- [x] Implement SpokeConfigurationForm
- [x] Create /federation/settings page (with regenerate keys functionality)
- [x] Run all tests (13 backend tests passing, 10 frontend tests passing)
- [x] TypeScript type checking (passing)
- [x] Linting (passing)
- [x] PDA-friendliness review (all language reviewed)
- [x] Final QA (ready for review)

## Testing Strategy

- Unit tests for each component
- Test capability toggle functionality
- Test form validation
- Test save/cancel actions
- Test error handling
- Test admin-only access
- Test key regeneration flow
- Ensure all tests pass before commit

## Security Considerations

1. Admin-only access via `AdminGuard`
2. Never expose private key in UI or API responses
3. Require confirmation for key regeneration
4. Audit log for configuration changes
5. Validate all inputs on backend

## Notes

- This is the final piece of M7-Federation
- Backend infrastructure is 100% complete
- UI patterns established by previous federation components
- Need to ensure proper admin role checking
- Consider rate limiting for key regeneration (prevent abuse)

## Blockers

None - all dependencies complete.

## Related Issues

- #84 (FED-001): Instance Identity Model - COMPLETED
- #91 (FED-008): Connection Manager UI - COMPLETED (UI pattern reference)
- #92 (FED-009): Aggregated Dashboard - COMPLETED (UI pattern reference)
