Compare commits
4 Commits
agent/rex/
...
agent/dex/
| Author | SHA1 | Date | |
|---|---|---|---|
| c906cd46ad | |||
| cce3e061a7 | |||
| ab19a7ccde | |||
| 745994182f |
33
frontend/.dockerignore
Normal file
33
frontend/.dockerignore
Normal file
@@ -0,0 +1,33 @@
|
||||
# Dependencies
|
||||
node_modules/
|
||||
npm-debug.log*
|
||||
yarn-error.log
|
||||
|
||||
# Build output (rebuilt in container)
|
||||
dist/
|
||||
out-tsc/
|
||||
|
||||
# Angular cache
|
||||
.angular/cache/
|
||||
|
||||
# IDE
|
||||
.idea/
|
||||
.vscode/
|
||||
*.sublime-workspace
|
||||
|
||||
# OS files
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
|
||||
# Git
|
||||
.git/
|
||||
.gitignore
|
||||
|
||||
# Docker
|
||||
Dockerfile
|
||||
.dockerignore
|
||||
|
||||
# Misc
|
||||
coverage/
|
||||
tmp/
|
||||
*.log
|
||||
38
frontend/Dockerfile
Normal file
38
frontend/Dockerfile
Normal file
@@ -0,0 +1,38 @@
|
||||
# ============================================================
|
||||
# Control Center Frontend — Multi-stage Docker Build
|
||||
# Angular 21 + nginx for static serving + API proxy
|
||||
# ============================================================
|
||||
|
||||
# --- Build Stage ---
|
||||
FROM node:22-slim AS builder
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Install dependencies first (layer caching)
|
||||
COPY package.json package-lock.json ./
|
||||
RUN npm ci
|
||||
|
||||
# Copy source and build production bundle
|
||||
COPY . .
|
||||
RUN npm run build
|
||||
|
||||
# --- Runtime Stage ---
|
||||
FROM nginx:1.27-alpine AS runtime
|
||||
|
||||
# Remove default nginx config
|
||||
RUN rm /etc/nginx/conf.d/default.conf
|
||||
|
||||
# Copy custom nginx config
|
||||
COPY nginx.conf /etc/nginx/conf.d/default.conf
|
||||
|
||||
# Copy built Angular app from builder stage
|
||||
COPY --from=builder /app/dist/frontend/browser /usr/share/nginx/html
|
||||
|
||||
# Expose HTTP port
|
||||
EXPOSE 80
|
||||
|
||||
# Health check — confirm nginx is serving
|
||||
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
|
||||
CMD wget -qO- http://localhost/ || exit 1
|
||||
|
||||
CMD ["nginx", "-g", "daemon off;"]
|
||||
@@ -56,7 +56,8 @@
|
||||
],
|
||||
"stylePreprocessorOptions": {
|
||||
"includePaths": [
|
||||
"src"
|
||||
"src",
|
||||
"src/styles"
|
||||
]
|
||||
}
|
||||
},
|
||||
|
||||
54
frontend/nginx.conf
Normal file
54
frontend/nginx.conf
Normal file
@@ -0,0 +1,54 @@
|
||||
server {
|
||||
listen 80;
|
||||
server_name _;
|
||||
|
||||
root /usr/share/nginx/html;
|
||||
index index.html;
|
||||
|
||||
# Gzip compression
|
||||
gzip on;
|
||||
gzip_vary on;
|
||||
gzip_proxied any;
|
||||
gzip_comp_level 6;
|
||||
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript image/svg+xml;
|
||||
|
||||
# Cache static assets (Angular uses content hashes)
|
||||
location /assets/ {
|
||||
expires 1y;
|
||||
add_header Cache-Control "public, immutable";
|
||||
}
|
||||
|
||||
# Cache hashed JS/CSS bundles
|
||||
location ~* \.(js|css)$ {
|
||||
expires 1y;
|
||||
add_header Cache-Control "public, immutable";
|
||||
}
|
||||
|
||||
# Proxy API requests to backend
|
||||
location /api/ {
|
||||
proxy_pass http://backend:8080/api/;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
# Proxy SignalR WebSocket connections to backend
|
||||
location /hubs/ {
|
||||
proxy_pass http://backend:8080/hubs/;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection "upgrade";
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_read_timeout 86400;
|
||||
}
|
||||
|
||||
# Angular SPA — all other routes fall back to index.html
|
||||
location / {
|
||||
try_files $uri $uri/ /index.html;
|
||||
}
|
||||
}
|
||||
@@ -2,11 +2,13 @@
|
||||
<!-- AgentCard — per spec Section 7.3 -->
|
||||
<!-- Integrates: Status Badge · Task Progress Bar · Quick‑Jump Button -->
|
||||
<!-- Left‑border accent matches status color. role="article" + aria‑labels. -->
|
||||
<!-- Enhanced: data-status attribute, elapsed time, design tokens. -->
|
||||
<!-- ========================================================================== -->
|
||||
<article
|
||||
class="agent-card"
|
||||
role="article"
|
||||
[attr.aria-label]="displayName + ' — ' + statusLabel()"
|
||||
[attr.data-status]="status"
|
||||
[attr.aria-label]="(displayName || agentId) + ' — ' + statusLabel()"
|
||||
[style.border-left-color]="statusBorderColor()"
|
||||
(click)="cardClick.emit(sessionKey)"
|
||||
appLongPress
|
||||
@@ -32,19 +34,20 @@
|
||||
</div>
|
||||
|
||||
<!-- ── Body: current task ── -->
|
||||
<div class="agent-card__body" *ngIf="task || status === 'error'">
|
||||
<div class="agent-card__body" *ngIf="task || isError()">
|
||||
<p
|
||||
class="agent-card__task"
|
||||
[attr.aria-label]="'Current task: ' + (status === 'error' ? errorMessage : task)"
|
||||
[class.agent-card__task--error]="isError()"
|
||||
[attr.aria-label]="'Current task: ' + (isError() ? errorMessage || task : task)"
|
||||
>
|
||||
{{ status === 'error' ? errorMessage || task : task }}
|
||||
{{ isError() ? errorMessage || task : task }}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<!-- ── Task Progress Bar ── -->
|
||||
<div
|
||||
class="agent-card__progress"
|
||||
*ngIf="progress > 0 && status !== 'error'"
|
||||
*ngIf="showProgress()"
|
||||
[attr.aria-label]="'Task progress: ' + progress + '%'"
|
||||
>
|
||||
<mat-progress-bar
|
||||
@@ -55,6 +58,16 @@
|
||||
<span class="agent-card__progress-label text-mono">{{ progress }}%</span>
|
||||
</div>
|
||||
|
||||
<!-- ── Elapsed Time ── -->
|
||||
<div
|
||||
class="agent-card__elapsed"
|
||||
*ngIf="taskElapsed && isActiveLike()"
|
||||
[attr.aria-label]="'Elapsed: ' + taskElapsed"
|
||||
>
|
||||
<mat-icon aria-hidden="true" class="agent-card__elapsed-icon">schedule</mat-icon>
|
||||
<span class="text-mono">{{ taskElapsed }}</span>
|
||||
</div>
|
||||
|
||||
<!-- ── Footer: channel + last activity + quick‑jump ── -->
|
||||
<div class="agent-card__footer">
|
||||
<div class="agent-card__meta">
|
||||
|
||||
@@ -2,15 +2,18 @@
|
||||
// AgentCard — M3 tactical dark styling
|
||||
// Per spec Section 7.3: left‑border accent, status‑aware coloring,
|
||||
// responsive card layout with 320px min‑width.
|
||||
// Enhanced: data-status selectors, elapsed time, design token imports.
|
||||
// ============================================================================
|
||||
|
||||
@use 'tokens' as tokens;
|
||||
|
||||
.agent-card {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-width: var(--cc-card-min-width);
|
||||
padding: var(--cc-card-padding);
|
||||
min-width: tokens.$cc-card-min-width;
|
||||
padding: tokens.$cc-card-padding;
|
||||
background-color: var(--cc-surface-container);
|
||||
border-radius: var(--cc-card-border-radius);
|
||||
border-radius: tokens.$cc-card-border-radius;
|
||||
border-left: 4px solid var(--status-offline); // default; overridden by [style]
|
||||
border-top: 1px solid var(--cc-outline);
|
||||
border-right: 1px solid var(--cc-outline);
|
||||
@@ -56,11 +59,6 @@
|
||||
letter-spacing: 0.02em;
|
||||
text-transform: uppercase;
|
||||
color: var(--cc-on-surface);
|
||||
|
||||
// Per‑status background tints
|
||||
.status-dot--active + & {
|
||||
background-color: var(--status-active-bg);
|
||||
}
|
||||
}
|
||||
|
||||
.agent-card__status-label {
|
||||
@@ -102,8 +100,7 @@
|
||||
color: var(--cc-on-surface);
|
||||
line-height: 1.4;
|
||||
|
||||
// Error messages get distinct styling
|
||||
.agent-card--error & {
|
||||
&--error {
|
||||
color: var(--status-error);
|
||||
}
|
||||
}
|
||||
@@ -117,6 +114,7 @@
|
||||
}
|
||||
|
||||
.agent-card__progress-label {
|
||||
font-family: var(--cc-font-mono);
|
||||
font-size: 12px;
|
||||
font-weight: 500;
|
||||
color: var(--cc-on-surface-variant);
|
||||
@@ -138,6 +136,23 @@
|
||||
}
|
||||
}
|
||||
|
||||
// ── Elapsed Time ──
|
||||
.agent-card__elapsed {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
font-size: 12px;
|
||||
color: var(--cc-on-surface-variant);
|
||||
padding: 2px 0;
|
||||
}
|
||||
|
||||
.agent-card__elapsed-icon {
|
||||
font-size: 14px;
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
color: var(--status-thinking);
|
||||
}
|
||||
|
||||
// ── Footer ──
|
||||
.agent-card__footer {
|
||||
display: flex;
|
||||
@@ -161,7 +176,6 @@
|
||||
color: var(--cc-on-surface-variant);
|
||||
}
|
||||
|
||||
.agent-card__channel-icon,
|
||||
.agent-card__channel .mat-icon {
|
||||
font-size: 14px;
|
||||
width: 14px;
|
||||
@@ -177,7 +191,6 @@
|
||||
.agent-card__jump {
|
||||
flex-shrink: 0;
|
||||
|
||||
// Match M3 text button sizing
|
||||
.mat-mdc-button {
|
||||
min-width: 36px;
|
||||
padding: 0 8px;
|
||||
@@ -192,11 +205,9 @@
|
||||
}
|
||||
|
||||
// ── Status‑specific background tints for badge ──
|
||||
// We use the global status-dot classes from styles.scss and pair them
|
||||
// with contextual background-color overrides here.
|
||||
// Using data-status attribute selectors for clean styling.
|
||||
|
||||
.agent-card[data-status="active"] .agent-card__badge,
|
||||
.agent-card .status-dot--active ~ .agent-card__badge {
|
||||
.agent-card[data-status="active"] .agent-card__badge {
|
||||
background-color: var(--status-active-bg);
|
||||
}
|
||||
|
||||
@@ -212,8 +223,22 @@
|
||||
background-color: var(--status-error-bg);
|
||||
}
|
||||
|
||||
.agent-card[data-status="offline"] .agent-card__badge {
|
||||
background-color: var(--cc-surface-container-high);
|
||||
}
|
||||
|
||||
// ── Active‑like pulse on card border ──
|
||||
.agent-card[data-status="active"],
|
||||
.agent-card[data-status="thinking"] {
|
||||
border-left-width: 4px;
|
||||
}
|
||||
|
||||
.agent-card[data-status="error"] {
|
||||
border-left-color: var(--status-error);
|
||||
}
|
||||
|
||||
// ── Responsive ──
|
||||
@media (max-width: 599px) {
|
||||
@media (max-width: tokens.$cc-breakpoint-mobile) {
|
||||
.agent-card {
|
||||
min-width: unset;
|
||||
padding: 16px;
|
||||
|
||||
@@ -3,8 +3,12 @@ import {
|
||||
Component,
|
||||
EventEmitter,
|
||||
Input,
|
||||
OnDestroy,
|
||||
Output,
|
||||
computed,
|
||||
effect,
|
||||
inject,
|
||||
signal,
|
||||
} from '@angular/core';
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { RouterModule } from '@angular/router';
|
||||
@@ -14,12 +18,18 @@ import { MatProgressBarModule } from '@angular/material/progress-bar';
|
||||
import { MatTooltipModule } from '@angular/material/tooltip';
|
||||
import { AgentStatus } from '../../../models/agent.model';
|
||||
import { LongPressDirective } from '../../../directives/long-press.directive';
|
||||
import {
|
||||
STATUS_COLORS,
|
||||
STATUS_LABELS,
|
||||
CHANNEL_ICONS,
|
||||
} from '../../../design/tokens';
|
||||
|
||||
// ============================================================================
|
||||
// AgentCard Component
|
||||
// Per spec Section 7.3: Composes Agent Status Badge, Task Progress Bar,
|
||||
// and Quick‑Jump Button into a card with left‑border status accent.
|
||||
// CUB-26: Emits cardClick and cardLongPress for drawer/modal integration.
|
||||
// Enhanced with data-status attribute, elapsed time, and design tokens.
|
||||
// ============================================================================
|
||||
|
||||
@Component({
|
||||
@@ -38,7 +48,7 @@ import { LongPressDirective } from '../../../directives/long-press.directive';
|
||||
styleUrl: './agent-card.component.scss',
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
})
|
||||
export class AgentCardComponent {
|
||||
export class AgentCardComponent implements OnDestroy {
|
||||
// --- Six required inputs per spec ---
|
||||
|
||||
/** Agent status — drives badge color and left‑border accent */
|
||||
@@ -73,6 +83,9 @@ export class AgentCardComponent {
|
||||
/** Error message (shown only when status is 'error') */
|
||||
@Input() errorMessage = '';
|
||||
|
||||
/** Elapsed time string, e.g. "04m 12s" */
|
||||
@Input() taskElapsed = '';
|
||||
|
||||
// --- CUB-26: Outputs for drawer/modal integration ---
|
||||
|
||||
/** Emitted when the card is clicked — opens the session drawer. */
|
||||
@@ -81,7 +94,15 @@ export class AgentCardComponent {
|
||||
/** Emitted when the card is long-pressed — bypasses drawer, opens session log directly. */
|
||||
@Output() readonly cardLongPress = new EventEmitter<string>();
|
||||
|
||||
// --- Computed values ---
|
||||
// --- Internal state ---
|
||||
|
||||
/** Timer for refreshing relative-time label */
|
||||
private _timer: ReturnType<typeof setInterval> | null = null;
|
||||
|
||||
/** Internal signal to trigger relative-time recomputation */
|
||||
private readonly _tick = signal(0);
|
||||
|
||||
// --- Computed values using design tokens ---
|
||||
|
||||
/** Map status → CSS custom property for the left‑border accent */
|
||||
readonly statusBorderColor = computed(() => {
|
||||
@@ -95,46 +116,68 @@ export class AgentCardComponent {
|
||||
return map[this.status] ?? 'var(--status-offline)';
|
||||
});
|
||||
|
||||
/** Human‑readable status label */
|
||||
readonly statusLabel = computed(() => {
|
||||
const labels: Record<AgentStatus, string> = {
|
||||
active: 'Active',
|
||||
idle: 'Idle',
|
||||
thinking: 'Thinking…',
|
||||
error: 'Error',
|
||||
offline: 'Offline',
|
||||
};
|
||||
return labels[this.status] ?? this.status;
|
||||
});
|
||||
/** Human‑readable status label (from design tokens) */
|
||||
readonly statusLabel = computed(() => STATUS_LABELS[this.status] ?? this.status);
|
||||
|
||||
/** CSS class suffix for the status badge dot */
|
||||
readonly statusDotClass = computed(() => `status-dot--${this.status}`);
|
||||
|
||||
/** Material icon name for the channel */
|
||||
readonly channelIcon = computed(() => {
|
||||
const icons: Record<string, string> = {
|
||||
telegram: 'telegram', // falls back to font icon if no SVG registered
|
||||
slack: 'chat',
|
||||
discord: 'forum',
|
||||
whatsapp: 'chat',
|
||||
webchat: 'language',
|
||||
email: 'email',
|
||||
};
|
||||
return icons[this.channel] ?? 'chat';
|
||||
/** Material icon name for the channel (from design tokens) */
|
||||
readonly channelIcon = computed(() => CHANNEL_ICONS[this.channel] ?? 'chat');
|
||||
|
||||
/** Relative time string for lastActivity, refreshed every 30s */
|
||||
readonly lastActivityLabel = computed(() => {
|
||||
// Read tick to create dependency that forces recomputation
|
||||
this._tick();
|
||||
return this._relativeTime(this.lastActivity);
|
||||
});
|
||||
|
||||
/** Relative time string for lastActivity */
|
||||
readonly lastActivityLabel = computed(() => {
|
||||
if (!this.lastActivity) return '';
|
||||
/** Quick‑jump route derived from sessionKey */
|
||||
readonly jumpRoute = computed(() => `/sessions/${this.sessionKey}`);
|
||||
|
||||
/** Whether progress bar should show */
|
||||
readonly showProgress = computed(() => this.progress > 0 && this.status !== 'error');
|
||||
|
||||
/** Whether error state is active */
|
||||
readonly isError = computed(() => this.status === 'error');
|
||||
|
||||
/** Whether card is in an active-like state (active or thinking) */
|
||||
readonly isActiveLike = computed(() => this.status === 'active' || this.status === 'thinking');
|
||||
|
||||
constructor() {
|
||||
// Start the relative-time refresh timer
|
||||
this._startTimer();
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this._stopTimer();
|
||||
}
|
||||
|
||||
// --- Private helpers ---
|
||||
|
||||
private _relativeTime(date: Date | null | undefined): string {
|
||||
if (!date) return '';
|
||||
const now = Date.now();
|
||||
const then = this.lastActivity.getTime();
|
||||
const then = date.getTime();
|
||||
const diffSec = Math.max(0, Math.floor((now - then) / 1000));
|
||||
if (diffSec < 60) return 'just now';
|
||||
if (diffSec < 3600) return `${Math.floor(diffSec / 60)}m ago`;
|
||||
if (diffSec < 86400) return `${Math.floor(diffSec / 3600)}h ago`;
|
||||
return `${Math.floor(diffSec / 86400)}d ago`;
|
||||
});
|
||||
}
|
||||
|
||||
/** Quick‑jump route derived from sessionKey */
|
||||
readonly jumpRoute = computed(() => `/sessions/${this.sessionKey}`);
|
||||
private _startTimer(): void {
|
||||
this._stopTimer();
|
||||
this._timer = setInterval(() => {
|
||||
// Increment tick to force lastActivityLabel recomputation
|
||||
this._tick.update(v => v + 1);
|
||||
}, 30_000);
|
||||
}
|
||||
|
||||
private _stopTimer(): void {
|
||||
if (this._timer) {
|
||||
clearInterval(this._timer);
|
||||
this._timer = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -94,6 +94,92 @@ export const CcStatusColors = {
|
||||
offline: { fg: '#64748b', bg: 'rgba(100, 116, 139, 0.12)', border: 'rgba(100, 116, 139, 0.40)' },
|
||||
} as const;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Convenience exports for component usage (CUB-20)
|
||||
// ---------------------------------------------------------------------------
|
||||
/** Status colors — maps AgentStatus to hex values */
|
||||
export const STATUS_COLORS: Record<string, string> = {
|
||||
active: '#38BDF8',
|
||||
idle: '#2DD4BF',
|
||||
thinking: '#A78BFA',
|
||||
error: '#F87171',
|
||||
offline: '#64748B',
|
||||
};
|
||||
|
||||
/** Status background tints (12% opacity) */
|
||||
export const STATUS_BG_COLORS: Record<string, string> = {
|
||||
active: 'rgba(56, 189, 248, 0.12)',
|
||||
idle: 'rgba(45, 212, 191, 0.12)',
|
||||
thinking: 'rgba(167, 139, 250, 0.12)',
|
||||
error: 'rgba(248, 113, 113, 0.12)',
|
||||
offline: 'rgba(100, 116, 139, 0.12)',
|
||||
};
|
||||
|
||||
/** Surface overrides (CUB-20 convenience) */
|
||||
export const SURFACE = {
|
||||
background: '#0D0F12',
|
||||
surface: '#13161A',
|
||||
container: '#1C2027',
|
||||
containerHigh: '#252B33',
|
||||
onSurface: '#E2E8F0',
|
||||
onSurfaceVariant: '#8A9BB0',
|
||||
outline: '#2D3748',
|
||||
} as const;
|
||||
|
||||
/** Tactical Dark Mode color palette (CUB-20 convenience) */
|
||||
export const COLORS = {
|
||||
surface: '#0F172A',
|
||||
surfaceLight: '#1E293B',
|
||||
primary: '#38BDF8',
|
||||
secondary: '#2DD4BF',
|
||||
accent: '#A78BFA',
|
||||
danger: '#F87171',
|
||||
textPrimary: '#FFFFFF',
|
||||
textSecondary: '#94A3B8',
|
||||
border: '#334155',
|
||||
} as const;
|
||||
|
||||
/** Layout constants (CUB-20 convenience) */
|
||||
export const LAYOUT = {
|
||||
navRailCollapsedWidth: 72,
|
||||
navRailExpandedWidth: 256,
|
||||
headerHeight: 64,
|
||||
bottomNavHeight: 80,
|
||||
cardBorderRadius: 16,
|
||||
cardMinWidth: 320,
|
||||
cardGap: 16,
|
||||
cardPadding: 20,
|
||||
sectionPadding: 24,
|
||||
spacingUnit: 8,
|
||||
} as const;
|
||||
|
||||
/** Breakpoints (px) (CUB-20 convenience) */
|
||||
export const BREAKPOINTS = {
|
||||
mobile: 599,
|
||||
tablet: 1023,
|
||||
desktop: 1024,
|
||||
} as const;
|
||||
|
||||
/** Channel icon mapping (CUB-20) */
|
||||
export const CHANNEL_ICONS: Record<string, string> = {
|
||||
telegram: 'telegram',
|
||||
slack: 'chat',
|
||||
discord: 'forum',
|
||||
whatsapp: 'chat',
|
||||
webchat: 'language',
|
||||
email: 'email',
|
||||
mqtt: 'sensors',
|
||||
};
|
||||
|
||||
/** Human-readable status labels (CUB-20) */
|
||||
export const STATUS_LABELS: Record<string, string> = {
|
||||
active: 'Active',
|
||||
idle: 'Idle',
|
||||
thinking: 'Thinking…',
|
||||
error: 'Error',
|
||||
offline: 'Offline',
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Typography
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -263,9 +349,6 @@ export const CcTokens = {
|
||||
// ---------------------------------------------------------------------------
|
||||
// CSS Custom Property Names
|
||||
// ---------------------------------------------------------------------------
|
||||
// Use these constants when setting styles programmatically via Renderer2
|
||||
// or ElementRef.style, e.g.: el.style.setProperty(CcCssProps.colorPrimary, '#fff')
|
||||
// ---------------------------------------------------------------------------
|
||||
export const CcCssProps = {
|
||||
// Color
|
||||
colorPrimary: '--cc-color-primary',
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
gap: 16px;
|
||||
min-height: 400px;
|
||||
overflow-x: hidden;
|
||||
padding: var(--cc-section-padding);
|
||||
}
|
||||
|
||||
.hub-page__title {
|
||||
|
||||
@@ -434,4 +434,41 @@ $min-body-font: 16px;
|
||||
@mixin touch-target($min-size: $min-touch-target) {
|
||||
min-width: $min-size;
|
||||
min-height: $min-size;
|
||||
}
|
||||
}
|
||||
// ============================================================================
|
||||
// CUB-20 / CUB-27 CONVENIENCE ALIASES
|
||||
// ============================================================================
|
||||
// Short aliases used by agent-card, hub-page, and other components.
|
||||
// These map to the canonical M3 tokens above.
|
||||
|
||||
$cc-background: $color-surface-darkest;
|
||||
$cc-surface: $color-surface-dark;
|
||||
$cc-surface-container: $color-surface-medium;
|
||||
$cc-surface-container-high: $color-surface-light;
|
||||
$cc-on-surface: $color-on-surface;
|
||||
$cc-on-surface-variant: $color-on-surface-variant;
|
||||
$cc-outline: $color-surface-lighter;
|
||||
|
||||
$cc-font-mono: $font-family-mono;
|
||||
$cc-font-family: $font-family-brand;
|
||||
|
||||
$cc-nav-rail-collapsed-width: $nav-rail-collapsed-width;
|
||||
$cc-nav-rail-expanded-width: $nav-rail-expanded-width;
|
||||
$cc-header-height: $header-height;
|
||||
$cc-bottom-nav-height: $bottom-nav-height;
|
||||
$cc-card-border-radius: $card-border-radius;
|
||||
$cc-card-min-width: $card-min-width;
|
||||
$cc-card-gap: $spacing-card-gap;
|
||||
$cc-card-padding: $spacing-card-pad;
|
||||
$cc-section-padding: $spacing-section;
|
||||
$cc-spacing-unit: $spacing-unit;
|
||||
|
||||
$cc-breakpoint-mobile: $breakpoint-compact;
|
||||
$cc-breakpoint-tablet: $breakpoint-medium;
|
||||
$cc-breakpoint-desktop: $breakpoint-expanded;
|
||||
|
||||
$cc-surface-darkest: $color-surface-darkest;
|
||||
$cc-surface-dark: $color-surface-dark;
|
||||
$cc-surface-medium: $color-surface-medium;
|
||||
$cc-surface-light: $color-surface-light;
|
||||
$cc-surface-lighter: $color-surface-lighter;
|
||||
|
||||
35
go-backend/.dockerignore
Normal file
35
go-backend/.dockerignore
Normal file
@@ -0,0 +1,35 @@
|
||||
# Ignore local build artifacts and version-control files
|
||||
*.exe
|
||||
*.dll
|
||||
*.so
|
||||
*.dylib
|
||||
*.test
|
||||
*.out
|
||||
bin/
|
||||
dist/
|
||||
|
||||
# Version control
|
||||
.git
|
||||
.gitignore
|
||||
|
||||
# IDE / editor
|
||||
.idea
|
||||
.vscode
|
||||
*.swp
|
||||
*.swo
|
||||
*~
|
||||
|
||||
# OS
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
|
||||
# Dependency cache (already fetched in Dockerfile)
|
||||
vendor/
|
||||
|
||||
# Documentation
|
||||
README.md
|
||||
*.md
|
||||
|
||||
# CI / CD
|
||||
.github/
|
||||
.gitea/
|
||||
35
go-backend/Dockerfile
Normal file
35
go-backend/Dockerfile
Normal file
@@ -0,0 +1,35 @@
|
||||
# Build stage
|
||||
FROM golang:1.23-alpine AS builder
|
||||
WORKDIR /app
|
||||
|
||||
# Install build dependencies
|
||||
RUN apk add --no-cache git ca-certificates
|
||||
|
||||
# Copy dependency files first for better layer caching
|
||||
COPY go.mod go.sum ./
|
||||
RUN go mod download
|
||||
|
||||
# Copy source code
|
||||
COPY . .
|
||||
|
||||
# Build the binary
|
||||
RUN CGO_ENABLED=0 GOOS=linux go build -ldflags="-w -s" -o /bin/server ./cmd/server
|
||||
|
||||
# ── Final stage ─────────────────────────────────────────────────────────
|
||||
FROM alpine:latest
|
||||
WORKDIR /app
|
||||
|
||||
# Install ca-certificates for HTTPS outbound calls
|
||||
RUN apk --no-cache add ca-certificates
|
||||
|
||||
# Copy binary from builder
|
||||
COPY --from=builder /bin/server /app/server
|
||||
|
||||
# Expose the default port (overridden by PORT env var)
|
||||
EXPOSE 8080
|
||||
|
||||
# Run as non-root
|
||||
RUN adduser -D -s /bin/sh appuser
|
||||
USER appuser
|
||||
|
||||
ENTRYPOINT ["/app/server"]
|
||||
107
go-backend/cmd/server/main.go
Normal file
107
go-backend/cmd/server/main.go
Normal file
@@ -0,0 +1,107 @@
|
||||
// Command server starts the Control Center Go backend API server.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"code.cubecraftcreations.com/CubeCraft-Creations/Control-Center/go-backend/internal/config"
|
||||
"code.cubecraftcreations.com/CubeCraft-Creations/Control-Center/go-backend/internal/db"
|
||||
"code.cubecraftcreations.com/CubeCraft-Creations/Control-Center/go-backend/internal/handler"
|
||||
"code.cubecraftcreations.com/CubeCraft-Creations/Control-Center/go-backend/internal/router"
|
||||
"code.cubecraftcreations.com/CubeCraft-Creations/Control-Center/go-backend/internal/store"
|
||||
)
|
||||
|
||||
func main() {
|
||||
// ── Configuration ──────────────────────────────────────────────────────
|
||||
cfg := config.Load()
|
||||
|
||||
// ── Logging ────────────────────────────────────────────────────────────
|
||||
logger := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
|
||||
Level: parseLogLevel(cfg.LogLevel),
|
||||
}))
|
||||
slog.SetDefault(logger)
|
||||
|
||||
// ── Database (optional until CUB-120 schema is ready) ──────────────────
|
||||
var pool *db.Pool
|
||||
if cfg.DatabaseURL != "" {
|
||||
var err error
|
||||
pool, err = db.New(cfg.DatabaseURL)
|
||||
if err != nil {
|
||||
slog.Warn("database connection failed; running without DB", "error", err)
|
||||
}
|
||||
}
|
||||
|
||||
// ── Stores (in-memory for now; PostgreSQL after CUB-120) ────────────────
|
||||
agentStore := store.NewAgentStore()
|
||||
sessionStore := store.NewSessionStore()
|
||||
taskStore := store.NewTaskStore()
|
||||
projectStore := store.NewProjectStore()
|
||||
|
||||
// ── HTTP handler ───────────────────────────────────────────────────────
|
||||
h := handler.NewHandler(agentStore, sessionStore, taskStore, projectStore)
|
||||
|
||||
// ── Router ─────────────────────────────────────────────────────────────
|
||||
r := router.New(&router.Dependencies{
|
||||
Handler: h,
|
||||
DB: pool,
|
||||
CORSOrigin: cfg.CORSOrigin,
|
||||
})
|
||||
|
||||
// ── Server ─────────────────────────────────────────────────────────────
|
||||
srv := &http.Server{
|
||||
Addr: fmt.Sprintf(":%d", cfg.Port),
|
||||
Handler: r,
|
||||
ReadTimeout: 10 * time.Second,
|
||||
WriteTimeout: 15 * time.Second,
|
||||
IdleTimeout: 60 * time.Second,
|
||||
}
|
||||
|
||||
// Graceful shutdown
|
||||
quit := make(chan os.Signal, 1)
|
||||
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
|
||||
|
||||
go func() {
|
||||
slog.Info("server starting", "port", cfg.Port, "env", cfg.Environment)
|
||||
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
||||
slog.Error("server failed", "error", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}()
|
||||
|
||||
<-quit
|
||||
slog.Info("shutting down server...")
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
||||
defer cancel()
|
||||
|
||||
if err := srv.Shutdown(ctx); err != nil {
|
||||
slog.Error("server forced to shutdown", "error", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
if pool != nil {
|
||||
pool.Close()
|
||||
}
|
||||
|
||||
slog.Info("server exited cleanly")
|
||||
}
|
||||
|
||||
func parseLogLevel(level string) slog.Level {
|
||||
switch level {
|
||||
case "debug":
|
||||
return slog.LevelDebug
|
||||
case "warn":
|
||||
return slog.LevelWarn
|
||||
case "error":
|
||||
return slog.LevelError
|
||||
default:
|
||||
return slog.LevelInfo
|
||||
}
|
||||
}
|
||||
26
go-backend/go.mod
Normal file
26
go-backend/go.mod
Normal file
@@ -0,0 +1,26 @@
|
||||
module code.cubecraftcreations.com/CubeCraft-Creations/Control-Center/go-backend
|
||||
|
||||
go 1.23
|
||||
|
||||
require (
|
||||
github.com/go-chi/chi/v5 v5.2.0
|
||||
github.com/go-chi/cors v1.2.1
|
||||
github.com/go-playground/validator/v10 v10.24.0
|
||||
github.com/google/uuid v1.6.0
|
||||
github.com/jackc/pgx/v5 v5.7.2
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/gabriel-vasile/mimetype v1.4.8 // indirect
|
||||
github.com/go-playground/locales v0.14.1 // indirect
|
||||
github.com/go-playground/universal-translator v0.18.1 // indirect
|
||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
||||
github.com/jackc/puddle/v2 v2.2.2 // indirect
|
||||
github.com/leodido/go-urn v1.4.0 // indirect
|
||||
golang.org/x/crypto v0.32.0 // indirect
|
||||
golang.org/x/net v0.34.0 // indirect
|
||||
golang.org/x/sync v0.10.0 // indirect
|
||||
golang.org/x/sys v0.29.0 // indirect
|
||||
golang.org/x/text v0.21.0 // indirect
|
||||
)
|
||||
50
go-backend/go.sum
Normal file
50
go-backend/go.sum
Normal file
@@ -0,0 +1,50 @@
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/gabriel-vasile/mimetype v1.4.8 h1:FfZ3gj38NjllZIeJAmMhr+qKL8Wu+nOoI3GqacKw1NM=
|
||||
github.com/gabriel-vasile/mimetype v1.4.8/go.mod h1:ByKUIKGjh1ODkGM1asKUbQZOLGrPjydw3hYPU2YU9t8=
|
||||
github.com/go-chi/chi/v5 v5.2.0 h1:Aj1EtB0qR2Rdo2dG4O94RIU35w2lvQSj6BRA4+qwFL0=
|
||||
github.com/go-chi/chi/v5 v5.2.0/go.mod h1:DslCQbL2OYiznFReuXYUmQ2hGd1aDpCnlMNITLSKoi8=
|
||||
github.com/go-chi/cors v1.2.1 h1:xEC8UT3Rlp2QuWNEr4Fs/c2EAGVKBwy/1vHx3bppil4=
|
||||
github.com/go-chi/cors v1.2.1/go.mod h1:sSbTewc+6wYHBBCW7ytsFSn836hqM7JxpglAy2Vzc58=
|
||||
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
|
||||
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
|
||||
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
|
||||
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
|
||||
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
|
||||
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
|
||||
github.com/go-playground/validator/v10 v10.24.0 h1:KHQckvo8G6hlWnrPX4NJJ+aBfWNAE/HH+qdL2cBpCmg=
|
||||
github.com/go-playground/validator/v10 v10.24.0/go.mod h1:GGzBIJMuE98Ic/kJsBXbz1x/7cByt++cQ+YOuDM5wus=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
|
||||
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
|
||||
github.com/jackc/pgx/v5 v5.7.2 h1:mLoDLV6sonKlvjIEsV56SkWNCnuNv531l94GaIzO+XI=
|
||||
github.com/jackc/pgx/v5 v5.7.2/go.mod h1:ncY89UGWxg82EykZUwSpUKEfccBGGYq1xjrOpsbsfGQ=
|
||||
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
|
||||
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
||||
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
|
||||
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
|
||||
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
|
||||
golang.org/x/crypto v0.32.0 h1:euUpcYgM8WcP71gNpTqQCn6rC2t6ULUPiOzfWaXVVfc=
|
||||
golang.org/x/crypto v0.32.0/go.mod h1:ZnnJkOaASj8g0AjIduWNlq2NRxL0PlBrbKVyZ6V/Ugc=
|
||||
golang.org/x/net v0.34.0 h1:Mb7Mrk043xzHgnRM88suvJFwzVrRfHEHJEl5/71CKw0=
|
||||
golang.org/x/net v0.34.0/go.mod h1:di0qlW3YNM5oh6GqDGQr92MyTozJPmybPK4Ev/Gm31k=
|
||||
golang.org/x/sync v0.10.0 h1:3NQrjDixjgGwUOCaF8w2+VYHv0Ve/vGYSbdkTa98gmQ=
|
||||
golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
||||
golang.org/x/sys v0.29.0 h1:TPYlXGxvx1MGTn2GiZDhnjPA9wZzZeGKHHmKhHYvgaU=
|
||||
golang.org/x/sys v0.29.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/text v0.21.0 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo=
|
||||
golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
45
go-backend/internal/config/config.go
Normal file
45
go-backend/internal/config/config.go
Normal file
@@ -0,0 +1,45 @@
|
||||
// Package config provides application configuration loaded from environment
|
||||
// variables with sensible defaults for local development.
|
||||
package config
|
||||
|
||||
import (
|
||||
"os"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
// Config holds all application configuration.
|
||||
type Config struct {
|
||||
Port int
|
||||
DatabaseURL string
|
||||
CORSOrigin string
|
||||
LogLevel string
|
||||
Environment string
|
||||
}
|
||||
|
||||
// Load reads configuration from environment variables, applying defaults where
|
||||
// values are not set. All secrets come from the environment — nothing is hardcoded.
|
||||
func Load() *Config {
|
||||
return &Config{
|
||||
Port: getEnvInt("PORT", 8080),
|
||||
DatabaseURL: getEnv("DATABASE_URL", "postgres://controlcenter:controlcenter@localhost:5432/controlcenter?sslmode=disable"),
|
||||
CORSOrigin: getEnv("CORS_ORIGIN", "*"),
|
||||
LogLevel: getEnv("LOG_LEVEL", "info"),
|
||||
Environment: getEnv("ENVIRONMENT", "development"),
|
||||
}
|
||||
}
|
||||
|
||||
func getEnv(key, fallback string) string {
|
||||
if v := os.Getenv(key); v != "" {
|
||||
return v
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
|
||||
func getEnvInt(key string, fallback int) int {
|
||||
if v := os.Getenv(key); v != "" {
|
||||
if i, err := strconv.Atoi(v); err == nil {
|
||||
return i
|
||||
}
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
62
go-backend/internal/db/db.go
Normal file
62
go-backend/internal/db/db.go
Normal file
@@ -0,0 +1,62 @@
|
||||
// Package db provides PostgreSQL connection management using pgx.
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
// Pool wraps a pgx connection pool with lifecycle helpers.
|
||||
type Pool struct {
|
||||
*pgxpool.Pool
|
||||
}
|
||||
|
||||
// New creates a connection pool from a PostgreSQL DSN.
|
||||
func New(dsn string) (*Pool, error) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
cfg, err := pgxpool.ParseConfig(dsn)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse pgx config: %w", err)
|
||||
}
|
||||
|
||||
// Sensible defaults
|
||||
cfg.MaxConns = 20
|
||||
cfg.MinConns = 2
|
||||
cfg.MaxConnLifetime = 30 * time.Minute
|
||||
cfg.MaxConnIdleTime = 10 * time.Minute
|
||||
cfg.HealthCheckPeriod = 5 * time.Second
|
||||
|
||||
pool, err := pgxpool.NewWithConfig(ctx, cfg)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create pgx pool: %w", err)
|
||||
}
|
||||
|
||||
if err := pool.Ping(ctx); err != nil {
|
||||
pool.Close()
|
||||
return nil, fmt.Errorf("ping database: %w", err)
|
||||
}
|
||||
|
||||
slog.Info("database connected", "pool", cfg.ConnConfig.Database)
|
||||
return &Pool{Pool: pool}, nil
|
||||
}
|
||||
|
||||
// Close shuts down the pool gracefully.
|
||||
func (p *Pool) Close() {
|
||||
if p.Pool != nil {
|
||||
p.Pool.Close()
|
||||
slog.Info("database pool closed")
|
||||
}
|
||||
}
|
||||
|
||||
// Health returns nil if the database is reachable.
|
||||
func (p *Pool) Health(ctx context.Context) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
|
||||
defer cancel()
|
||||
return p.Ping(ctx)
|
||||
}
|
||||
158
go-backend/internal/handler/agent.go
Normal file
158
go-backend/internal/handler/agent.go
Normal file
@@ -0,0 +1,158 @@
|
||||
// Package handler contains HTTP handlers for the Control Center API.
|
||||
// Each handler is a method on a Handler struct that receives its
|
||||
// dependencies (stores) through dependency injection.
|
||||
package handler
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"code.cubecraftcreations.com/CubeCraft-Creations/Control-Center/go-backend/internal/models"
|
||||
"code.cubecraftcreations.com/CubeCraft-Creations/Control-Center/go-backend/internal/store"
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/go-playground/validator/v10"
|
||||
)
|
||||
|
||||
// Handler groups all route handlers and their dependencies.
|
||||
type Handler struct {
|
||||
AgentStore *store.AgentStore
|
||||
SessionStore *store.SessionStore
|
||||
TaskStore *store.TaskStore
|
||||
ProjectStore *store.ProjectStore
|
||||
validate *validator.Validate
|
||||
}
|
||||
|
||||
// NewHandler returns a fully wired Handler.
|
||||
func NewHandler(
|
||||
as *store.AgentStore,
|
||||
ss *store.SessionStore,
|
||||
ts *store.TaskStore,
|
||||
ps *store.ProjectStore,
|
||||
) *Handler {
|
||||
v := validator.New()
|
||||
v.RegisterValidation("agentStatus", validateAgentStatus)
|
||||
return &Handler{
|
||||
AgentStore: as,
|
||||
SessionStore: ss,
|
||||
TaskStore: ts,
|
||||
ProjectStore: ps,
|
||||
validate: v,
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Agent Handlers ────────────────────────────────────────────────────────────
|
||||
|
||||
// ListAgents handles GET /api/agents.
|
||||
func (h *Handler) ListAgents(w http.ResponseWriter, r *http.Request) {
|
||||
statusFilter := models.AgentStatus(r.URL.Query().Get("status"))
|
||||
allAgents := h.AgentStore.List(statusFilter)
|
||||
|
||||
page, pageSize := parsePagination(r)
|
||||
start, end := paginateSlice(len(allAgents), page, pageSize)
|
||||
|
||||
pageSlice := allAgents[start:end]
|
||||
writeJSON(w, http.StatusOK, models.PaginatedResponse{
|
||||
Data: pageSlice,
|
||||
TotalCount: h.AgentStore.Count(),
|
||||
Page: page,
|
||||
PageSize: pageSize,
|
||||
HasMore: end < len(allAgents),
|
||||
})
|
||||
}
|
||||
|
||||
// GetAgent handles GET /api/agents/{id}.
|
||||
func (h *Handler) GetAgent(w http.ResponseWriter, r *http.Request) {
|
||||
id := chi.URLParam(r, "id")
|
||||
agent, ok := h.AgentStore.Get(id)
|
||||
if !ok {
|
||||
writeJSON(w, http.StatusNotFound, models.ErrorResponse{Error: "agent not found"})
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, agent)
|
||||
}
|
||||
|
||||
// CreateAgent handles POST /api/agents.
|
||||
func (h *Handler) CreateAgent(w http.ResponseWriter, r *http.Request) {
|
||||
var req models.CreateAgentRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
writeJSON(w, http.StatusBadRequest, models.ErrorResponse{Error: "invalid request body"})
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.validate.Struct(req); err != nil {
|
||||
writeJSON(w, http.StatusUnprocessableEntity, models.ErrorResponse{
|
||||
Error: "validation failed",
|
||||
Details: validationErrors(err),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
agent := models.AgentCardData{
|
||||
ID: req.ID,
|
||||
DisplayName: req.DisplayName,
|
||||
Role: req.Role,
|
||||
Status: req.Status,
|
||||
CurrentTask: req.CurrentTask,
|
||||
SessionKey: req.SessionKey,
|
||||
Channel: req.Channel,
|
||||
LastActivity: time.Now().UTC().Format(time.RFC3339),
|
||||
}
|
||||
|
||||
if ok := h.AgentStore.Create(agent); !ok {
|
||||
writeJSON(w, http.StatusConflict, models.ErrorResponse{Error: "agent with this ID already exists"})
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, agent)
|
||||
}
|
||||
|
||||
// UpdateAgent handles PUT /api/agents/{id}.
|
||||
func (h *Handler) UpdateAgent(w http.ResponseWriter, r *http.Request) {
|
||||
id := chi.URLParam(r, "id")
|
||||
|
||||
var req models.UpdateAgentRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
writeJSON(w, http.StatusBadRequest, models.ErrorResponse{Error: "invalid request body"})
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.validate.Struct(req); err != nil {
|
||||
writeJSON(w, http.StatusUnprocessableEntity, models.ErrorResponse{
|
||||
Error: "validation failed",
|
||||
Details: validationErrors(err),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
agent, ok := h.AgentStore.Update(id, req)
|
||||
if !ok {
|
||||
writeJSON(w, http.StatusNotFound, models.ErrorResponse{Error: "agent not found"})
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, agent)
|
||||
}
|
||||
|
||||
// DeleteAgent handles DELETE /api/agents/{id}.
|
||||
func (h *Handler) DeleteAgent(w http.ResponseWriter, r *http.Request) {
|
||||
id := chi.URLParam(r, "id")
|
||||
if ok := h.AgentStore.Delete(id); !ok {
|
||||
writeJSON(w, http.StatusNotFound, models.ErrorResponse{Error: "agent not found"})
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// AgentHistory handles GET /api/agents/{id}/history.
|
||||
func (h *Handler) AgentHistory(w http.ResponseWriter, r *http.Request) {
|
||||
id := chi.URLParam(r, "id")
|
||||
if _, ok := h.AgentStore.Get(id); !ok {
|
||||
writeJSON(w, http.StatusNotFound, models.ErrorResponse{Error: "agent not found"})
|
||||
return
|
||||
}
|
||||
|
||||
history := h.AgentStore.History(id)
|
||||
if history == nil {
|
||||
history = []models.AgentStatusHistoryEntry{}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, history)
|
||||
}
|
||||
369
go-backend/internal/handler/handler_test.go
Normal file
369
go-backend/internal/handler/handler_test.go
Normal file
@@ -0,0 +1,369 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"code.cubecraftcreations.com/CubeCraft-Creations/Control-Center/go-backend/internal/models"
|
||||
"code.cubecraftcreations.com/CubeCraft-Creations/Control-Center/go-backend/internal/store"
|
||||
"github.com/go-chi/chi/v5"
|
||||
)
|
||||
|
||||
// testHandler creates a Handler wired to fresh in-memory stores for testing.
|
||||
func testHandler(t *testing.T) *Handler {
|
||||
t.Helper()
|
||||
return NewHandler(
|
||||
store.NewAgentStore(),
|
||||
store.NewSessionStore(),
|
||||
store.NewTaskStore(),
|
||||
store.NewProjectStore(),
|
||||
)
|
||||
}
|
||||
|
||||
// serveChi creates a chi.Mux with the standard routes registered, then
|
||||
// serves a request against it. Returns the recorded response.
|
||||
func serveChi(h *Handler, method, path, body string) *httptest.ResponseRecorder {
|
||||
w := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(method, path, strings.NewReader(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
r := chi.NewRouter()
|
||||
r.Route("/api", func(api chi.Router) {
|
||||
api.Route("/agents", func(agents chi.Router) {
|
||||
agents.Get("/", h.ListAgents)
|
||||
agents.Post("/", h.CreateAgent)
|
||||
agents.Get("/{id}", h.GetAgent)
|
||||
agents.Put("/{id}", h.UpdateAgent)
|
||||
agents.Delete("/{id}", h.DeleteAgent)
|
||||
agents.Get("/{id}/history", h.AgentHistory)
|
||||
})
|
||||
api.Get("/sessions", h.ListSessions)
|
||||
api.Get("/tasks", h.ListTasks)
|
||||
api.Get("/projects", h.ListProjects)
|
||||
})
|
||||
r.ServeHTTP(w, req)
|
||||
return w
|
||||
}
|
||||
|
||||
func parseBody(t *testing.T, w *httptest.ResponseRecorder) map[string]any {
|
||||
t.Helper()
|
||||
var body map[string]any
|
||||
if err := json.NewDecoder(w.Result().Body).Decode(&body); err != nil {
|
||||
t.Fatalf("failed to decode body: %v", err)
|
||||
}
|
||||
return body
|
||||
}
|
||||
|
||||
func parseAgent(t *testing.T, w *httptest.ResponseRecorder) models.AgentCardData {
|
||||
t.Helper()
|
||||
var a models.AgentCardData
|
||||
if err := json.NewDecoder(w.Result().Body).Decode(&a); err != nil {
|
||||
t.Fatalf("failed to decode agent: %v", err)
|
||||
}
|
||||
return a
|
||||
}
|
||||
|
||||
func parsePaginated(t *testing.T, w *httptest.ResponseRecorder) models.PaginatedResponse {
|
||||
t.Helper()
|
||||
var pr models.PaginatedResponse
|
||||
if err := json.NewDecoder(w.Result().Body).Decode(&pr); err != nil {
|
||||
t.Fatalf("failed to decode paginated response: %v", err)
|
||||
}
|
||||
return pr
|
||||
}
|
||||
|
||||
// ─── Agent Tests ───────────────────────────────────────────────────────────────
|
||||
|
||||
func TestCreateAgent_Success(t *testing.T) {
|
||||
h := testHandler(t)
|
||||
w := serveChi(h, "POST", "/api/agents", `{
|
||||
"id": "dex",
|
||||
"displayName": "Dex",
|
||||
"role": "Backend Dev",
|
||||
"status": "idle",
|
||||
"sessionKey": "sess-1",
|
||||
"channel": "discord"
|
||||
}`)
|
||||
|
||||
if w.Code != http.StatusCreated {
|
||||
t.Fatalf("expected 201, got %d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
|
||||
a := parseAgent(t, w)
|
||||
if a.ID != "dex" {
|
||||
t.Errorf("expected id=dax, got %s", a.ID)
|
||||
}
|
||||
if a.Status != models.AgentStatusIdle {
|
||||
t.Errorf("expected status=idle, got %s", a.Status)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateAgent_Duplicate(t *testing.T) {
|
||||
h := testHandler(t)
|
||||
serveChi(h, "POST", "/api/agents", `{"id":"otto","displayName":"Otto","role":"Orchestrator","status":"active","sessionKey":"s1","channel":"discord"}`)
|
||||
w := serveChi(h, "POST", "/api/agents", `{"id":"otto","displayName":"Otto","role":"Orchestrator","status":"active","sessionKey":"s2","channel":"discord"}`)
|
||||
|
||||
if w.Code != http.StatusConflict {
|
||||
t.Fatalf("expected 409, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateAgent_Validation(t *testing.T) {
|
||||
h := testHandler(t)
|
||||
// Missing displayName
|
||||
w := serveChi(h, "POST", "/api/agents", `{"id":"dex","status":"idle","sessionKey":"s1","channel":"discord"}`)
|
||||
if w.Code != http.StatusUnprocessableEntity {
|
||||
t.Fatalf("expected 422, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateAgent_InvalidStatus(t *testing.T) {
|
||||
h := testHandler(t)
|
||||
w := serveChi(h, "POST", "/api/agents", `{"id":"dex","displayName":"Dex","role":"Dev","status":"flying","sessionKey":"s1","channel":"discord"}`)
|
||||
if w.Code != http.StatusUnprocessableEntity {
|
||||
t.Fatalf("expected 422 for invalid status, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetAgent_NotFound(t *testing.T) {
|
||||
h := testHandler(t)
|
||||
w := serveChi(h, "GET", "/api/agents/nonexistent", "")
|
||||
if w.Code != http.StatusNotFound {
|
||||
t.Fatalf("expected 404, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetAgent_Success(t *testing.T) {
|
||||
h := testHandler(t)
|
||||
serveChi(h, "POST", "/api/agents", `{"id":"pip","displayName":"Pip","role":"Edge Dev","status":"idle","sessionKey":"s1","channel":"discord"}`)
|
||||
w := serveChi(h, "GET", "/api/agents/pip", "")
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("expected 200, got %d", w.Code)
|
||||
}
|
||||
a := parseAgent(t, w)
|
||||
if a.DisplayName != "Pip" {
|
||||
t.Errorf("expected Pip, got %s", a.DisplayName)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListAgents(t *testing.T) {
|
||||
h := testHandler(t)
|
||||
serveChi(h, "POST", "/api/agents", `{"id":"a1","displayName":"Alpha","role":"Tester","status":"idle","sessionKey":"s1","channel":"discord"}`)
|
||||
serveChi(h, "POST", "/api/agents", `{"id":"a2","displayName":"Beta","role":"Tester","status":"active","sessionKey":"s2","channel":"discord"}`)
|
||||
|
||||
w := serveChi(h, "GET", "/api/agents", "")
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("expected 200, got %d", w.Code)
|
||||
}
|
||||
|
||||
pr := parsePaginated(t, w)
|
||||
if pr.TotalCount != 2 {
|
||||
t.Errorf("expected totalCount=2, got %d", pr.TotalCount)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListAgents_FilterByStatus(t *testing.T) {
|
||||
h := testHandler(t)
|
||||
serveChi(h, "POST", "/api/agents", `{"id":"a1","displayName":"Alpha","role":"Tester","status":"idle","sessionKey":"s1","channel":"discord"}`)
|
||||
serveChi(h, "POST", "/api/agents", `{"id":"a2","displayName":"Beta","role":"Tester","status":"active","sessionKey":"s2","channel":"discord"}`)
|
||||
|
||||
w := serveChi(h, "GET", "/api/agents?status=active", "")
|
||||
pr := parsePaginated(t, w)
|
||||
if pr.TotalCount != 2 {
|
||||
t.Errorf("expected totalCount=2 (unfiltered), got %d", pr.TotalCount)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdateAgent(t *testing.T) {
|
||||
h := testHandler(t)
|
||||
serveChi(h, "POST", "/api/agents", `{"id":"hex","displayName":"Hex","role":"DB Specialist","status":"idle","sessionKey":"s1","channel":"discord"}`)
|
||||
|
||||
w := serveChi(h, "PUT", "/api/agents/hex", `{"status":"thinking","currentTask":"schema review"}`)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
|
||||
a := parseAgent(t, w)
|
||||
if a.Status != models.AgentStatusThinking {
|
||||
t.Errorf("expected status=thinking, got %s", a.Status)
|
||||
}
|
||||
if a.CurrentTask == nil || *a.CurrentTask != "schema review" {
|
||||
t.Errorf("expected currentTask=schema review")
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdateAgent_NotFound(t *testing.T) {
|
||||
h := testHandler(t)
|
||||
w := serveChi(h, "PUT", "/api/agents/nope", `{"status":"idle"}`)
|
||||
if w.Code != http.StatusNotFound {
|
||||
t.Fatalf("expected 404, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeleteAgent(t *testing.T) {
|
||||
h := testHandler(t)
|
||||
serveChi(h, "POST", "/api/agents", `{"id":"temp","displayName":"Temp","role":"Temp","status":"idle","sessionKey":"s1","channel":"discord"}`)
|
||||
|
||||
w := serveChi(h, "DELETE", "/api/agents/temp", "")
|
||||
if w.Code != http.StatusNoContent {
|
||||
t.Fatalf("expected 204, got %d", w.Code)
|
||||
}
|
||||
|
||||
// Verify gone
|
||||
w2 := serveChi(h, "GET", "/api/agents/temp", "")
|
||||
if w2.Code != http.StatusNotFound {
|
||||
t.Fatalf("expected 404 after delete, got %d", w2.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAgentHistory(t *testing.T) {
|
||||
h := testHandler(t)
|
||||
serveChi(h, "POST", "/api/agents", `{"id":"nano","displayName":"Nano","role":"Firmware","status":"idle","sessionKey":"s1","channel":"discord"}`)
|
||||
serveChi(h, "PUT", "/api/agents/nano", `{"status":"thinking","currentTask":"mqtt payload"}`)
|
||||
|
||||
w := serveChi(h, "GET", "/api/agents/nano/history", "")
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("expected 200, got %d", w.Code)
|
||||
}
|
||||
|
||||
var entries []models.AgentStatusHistoryEntry
|
||||
json.NewDecoder(w.Result().Body).Decode(&entries)
|
||||
if len(entries) < 2 {
|
||||
t.Errorf("expected at least 2 history entries, got %d", len(entries))
|
||||
}
|
||||
// Newest first — first entry should be "thinking"
|
||||
if entries[0].Status != models.AgentStatusThinking {
|
||||
t.Errorf("expected newest entry status=thinking, got %s", entries[0].Status)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAgentHistory_NotFound(t *testing.T) {
|
||||
h := testHandler(t)
|
||||
w := serveChi(h, "GET", "/api/agents/ghost/history", "")
|
||||
if w.Code != http.StatusNotFound {
|
||||
t.Fatalf("expected 404, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Session Tests ─────────────────────────────────────────────────────────════
|
||||
|
||||
func TestListSessions_Empty(t *testing.T) {
|
||||
h := testHandler(t)
|
||||
w := serveChi(h, "GET", "/api/sessions", "")
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("expected 200, got %d", w.Code)
|
||||
}
|
||||
pr := parsePaginated(t, w)
|
||||
if pr.TotalCount != 0 {
|
||||
t.Errorf("expected 0 sessions, got %d", pr.TotalCount)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListSessions_WithData(t *testing.T) {
|
||||
h := testHandler(t)
|
||||
h.SessionStore.Create(models.Session{
|
||||
SessionKey: "sess-1",
|
||||
AgentID: "dex",
|
||||
Channel: "discord",
|
||||
Status: "running",
|
||||
Model: "deepseek-v4",
|
||||
})
|
||||
h.SessionStore.Create(models.Session{
|
||||
SessionKey: "sess-2",
|
||||
AgentID: "otto",
|
||||
Channel: "discord",
|
||||
Status: "done",
|
||||
Model: "deepseek-v4",
|
||||
})
|
||||
|
||||
w := serveChi(h, "GET", "/api/sessions", "")
|
||||
pr := parsePaginated(t, w)
|
||||
if pr.TotalCount != 2 {
|
||||
t.Errorf("expected totalCount=2, got %d", pr.TotalCount)
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Task Tests ────────────────────────────────────────────────────────────────
|
||||
|
||||
func TestListTasks_Empty(t *testing.T) {
|
||||
h := testHandler(t)
|
||||
w := serveChi(h, "GET", "/api/tasks", "")
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("expected 200, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListTasks_WithData(t *testing.T) {
|
||||
h := testHandler(t)
|
||||
h.TaskStore.Create(models.Task{
|
||||
AgentID: "dex",
|
||||
Title: "Implement CRUD API",
|
||||
Status: models.TaskStatusRunning,
|
||||
})
|
||||
|
||||
w := serveChi(h, "GET", "/api/tasks", "")
|
||||
pr := parsePaginated(t, w)
|
||||
if pr.TotalCount != 1 {
|
||||
t.Errorf("expected totalCount=1, got %d", pr.TotalCount)
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Project Tests ─────────────────────────────────────────────────────────────
|
||||
|
||||
func TestListProjects_Empty(t *testing.T) {
|
||||
h := testHandler(t)
|
||||
w := serveChi(h, "GET", "/api/projects", "")
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("expected 200, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListProjects_WithData(t *testing.T) {
|
||||
h := testHandler(t)
|
||||
h.ProjectStore.Create(models.Project{
|
||||
Name: "Extrudex",
|
||||
Description: "Filament inventory system",
|
||||
Status: models.ProjectStatusActive,
|
||||
})
|
||||
|
||||
w := serveChi(h, "GET", "/api/projects", "")
|
||||
pr := parsePaginated(t, w)
|
||||
if pr.TotalCount != 1 {
|
||||
t.Errorf("expected totalCount=1, got %d", pr.TotalCount)
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Pagination Tests ─────────────────────────────────────────────────────────
|
||||
|
||||
func TestPagination_PageOutOfRange(t *testing.T) {
|
||||
h := testHandler(t)
|
||||
serveChi(h, "POST", "/api/agents", `{"id":"a1","displayName":"A1","role":"T","status":"idle","sessionKey":"s1","channel":"discord"}`)
|
||||
|
||||
w := serveChi(h, "GET", "/api/agents?page=99", "")
|
||||
pr := parsePaginated(t, w)
|
||||
if len(pr.Data.([]any)) != 0 {
|
||||
t.Errorf("expected empty page, got %d items", len(pr.Data.([]any)))
|
||||
}
|
||||
// HasMore=false because we're past all data — nothing more to fetch.
|
||||
if pr.HasMore {
|
||||
t.Error("expected HasMore=false when page is beyond data")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPagination_PageSize(t *testing.T) {
|
||||
h := testHandler(t)
|
||||
for i := range 5 {
|
||||
id := string(rune('a' + i))
|
||||
serveChi(h, "POST", "/api/agents", `{"id":"`+string(id)+`","displayName":"`+string(id)+`","role":"T","status":"idle","sessionKey":"s1","channel":"discord"}`)
|
||||
}
|
||||
|
||||
w := serveChi(h, "GET", "/api/agents?pageSize=2&page=2", "")
|
||||
pr := parsePaginated(t, w)
|
||||
if pr.PageSize != 2 {
|
||||
t.Errorf("expected pageSize=2, got %d", pr.PageSize)
|
||||
}
|
||||
}
|
||||
106
go-backend/internal/handler/helpers.go
Normal file
106
go-backend/internal/handler/helpers.go
Normal file
@@ -0,0 +1,106 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/go-playground/validator/v10"
|
||||
)
|
||||
|
||||
// ─── Pagination ────────────────────────────────────────────────────────────────
|
||||
|
||||
const (
|
||||
defaultPage = 1
|
||||
defaultPageSize = 20
|
||||
maxPageSize = 100
|
||||
)
|
||||
|
||||
// parsePagination extracts page and pageSize query params from the request.
|
||||
func parsePagination(r *http.Request) (page, pageSize int) {
|
||||
page = defaultPage
|
||||
pageSize = defaultPageSize
|
||||
|
||||
if p := r.URL.Query().Get("page"); p != "" {
|
||||
if n, err := strconv.Atoi(p); err == nil && n > 0 {
|
||||
page = n
|
||||
}
|
||||
}
|
||||
if ps := r.URL.Query().Get("pageSize"); ps != "" {
|
||||
if n, err := strconv.Atoi(ps); err == nil && n > 0 {
|
||||
if n > maxPageSize {
|
||||
n = maxPageSize
|
||||
}
|
||||
pageSize = n
|
||||
}
|
||||
}
|
||||
return page, pageSize
|
||||
}
|
||||
|
||||
// paginateSlice computes the start and end indexes for a page of `total` items.
|
||||
// Bounds are clamped to [0, total].
|
||||
func paginateSlice(total, page, pageSize int) (start, end int) {
|
||||
start = (page - 1) * pageSize
|
||||
if start > total {
|
||||
start = total
|
||||
}
|
||||
end = start + pageSize
|
||||
if end > total {
|
||||
end = total
|
||||
}
|
||||
return start, end
|
||||
}
|
||||
|
||||
// ─── JSON Helpers ─────────────────────────────────────────────────────────────
|
||||
|
||||
// writeJSON marshals v as JSON and writes it to w with the given status code.
|
||||
func writeJSON(w http.ResponseWriter, status int, v any) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
if v == nil {
|
||||
return
|
||||
}
|
||||
if err := json.NewEncoder(w).Encode(v); err != nil {
|
||||
http.Error(w, `{"error":"internal encoding error"}`, http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Validation ───────────────────────────────────────────────────────────────
|
||||
|
||||
// validationErrors converts a validator.ValidationErrors into a string map
|
||||
// suitable for the ErrorResponse details field.
|
||||
func validationErrors(err error) map[string]string {
|
||||
details := make(map[string]string)
|
||||
if verrs, ok := err.(validator.ValidationErrors); ok {
|
||||
for _, fe := range verrs {
|
||||
field := strings.ToLower(fe.Field())
|
||||
details[field] = fieldError(fe)
|
||||
}
|
||||
}
|
||||
return details
|
||||
}
|
||||
|
||||
func fieldError(fe validator.FieldError) string {
|
||||
switch fe.Tag() {
|
||||
case "required":
|
||||
return "this field is required"
|
||||
case "min":
|
||||
return fmt.Sprintf("must be at least %s characters", fe.Param())
|
||||
case "max":
|
||||
return fmt.Sprintf("must be at most %s characters", fe.Param())
|
||||
default:
|
||||
return fmt.Sprintf("failed validation: %s", fe.Tag())
|
||||
}
|
||||
}
|
||||
|
||||
// validateAgentStatus is a custom validator for AgentStatus values.
|
||||
func validateAgentStatus(fl validator.FieldLevel) bool {
|
||||
if status, ok := fl.Field().Interface().(interface {
|
||||
IsValid() bool
|
||||
}); ok {
|
||||
return status.IsValid()
|
||||
}
|
||||
return false
|
||||
}
|
||||
28
go-backend/internal/handler/project.go
Normal file
28
go-backend/internal/handler/project.go
Normal file
@@ -0,0 +1,28 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"code.cubecraftcreations.com/CubeCraft-Creations/Control-Center/go-backend/internal/models"
|
||||
)
|
||||
|
||||
// ─── Project Handlers ──────────────────────────────────────────────────────────
|
||||
|
||||
// ListProjects handles GET /api/projects.
|
||||
func (h *Handler) ListProjects(w http.ResponseWriter, r *http.Request) {
|
||||
projects := h.ProjectStore.List()
|
||||
if projects == nil {
|
||||
projects = []models.Project{}
|
||||
}
|
||||
|
||||
page, pageSize := parsePagination(r)
|
||||
start, end := paginateSlice(len(projects), page, pageSize)
|
||||
|
||||
writeJSON(w, http.StatusOK, models.PaginatedResponse{
|
||||
Data: projects[start:end],
|
||||
TotalCount: h.ProjectStore.Count(),
|
||||
Page: page,
|
||||
PageSize: pageSize,
|
||||
HasMore: end < len(projects),
|
||||
})
|
||||
}
|
||||
28
go-backend/internal/handler/session.go
Normal file
28
go-backend/internal/handler/session.go
Normal file
@@ -0,0 +1,28 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"code.cubecraftcreations.com/CubeCraft-Creations/Control-Center/go-backend/internal/models"
|
||||
)
|
||||
|
||||
// ─── Session Handlers ──────────────────────────────────────────────────────────
|
||||
|
||||
// ListSessions handles GET /api/sessions.
|
||||
func (h *Handler) ListSessions(w http.ResponseWriter, r *http.Request) {
|
||||
sessions := h.SessionStore.ListActive()
|
||||
if sessions == nil {
|
||||
sessions = []models.Session{}
|
||||
}
|
||||
|
||||
page, pageSize := parsePagination(r)
|
||||
start, end := paginateSlice(len(sessions), page, pageSize)
|
||||
|
||||
writeJSON(w, http.StatusOK, models.PaginatedResponse{
|
||||
Data: sessions[start:end],
|
||||
TotalCount: h.SessionStore.Count(),
|
||||
Page: page,
|
||||
PageSize: pageSize,
|
||||
HasMore: end < len(sessions),
|
||||
})
|
||||
}
|
||||
28
go-backend/internal/handler/task.go
Normal file
28
go-backend/internal/handler/task.go
Normal file
@@ -0,0 +1,28 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"code.cubecraftcreations.com/CubeCraft-Creations/Control-Center/go-backend/internal/models"
|
||||
)
|
||||
|
||||
// ─── Task Handlers ─────────────────────────────────────────────────────────────
|
||||
|
||||
// ListTasks handles GET /api/tasks.
|
||||
func (h *Handler) ListTasks(w http.ResponseWriter, r *http.Request) {
|
||||
tasks := h.TaskStore.ListRecent()
|
||||
if tasks == nil {
|
||||
tasks = []models.Task{}
|
||||
}
|
||||
|
||||
page, pageSize := parsePagination(r)
|
||||
start, end := paginateSlice(len(tasks), page, pageSize)
|
||||
|
||||
writeJSON(w, http.StatusOK, models.PaginatedResponse{
|
||||
Data: tasks[start:end],
|
||||
TotalCount: h.TaskStore.Count(),
|
||||
Page: page,
|
||||
PageSize: pageSize,
|
||||
HasMore: end < len(tasks),
|
||||
})
|
||||
}
|
||||
165
go-backend/internal/models/models.go
Normal file
165
go-backend/internal/models/models.go
Normal file
@@ -0,0 +1,165 @@
|
||||
// Package models defines the domain types and API contracts for the
|
||||
// Control Center Go backend. These types map to the existing TypeScript
|
||||
// AgentCardData interface and extend it with persistence-focused types
|
||||
// for the new session, task, and project entities.
|
||||
//
|
||||
// All JSON field names use camelCase to match the existing frontend
|
||||
// contract established by the .NET backend.
|
||||
package models
|
||||
|
||||
import "time"
|
||||
|
||||
// ─── Agent Status ──────────────────────────────────────────────────────────────
|
||||
|
||||
// AgentStatus represents an agent's operational status.
|
||||
// Maps to the frontend status values: active, idle, thinking, error.
|
||||
type AgentStatus string
|
||||
|
||||
const (
|
||||
AgentStatusActive AgentStatus = "active"
|
||||
AgentStatusIdle AgentStatus = "idle"
|
||||
AgentStatusThinking AgentStatus = "thinking"
|
||||
AgentStatusError AgentStatus = "error"
|
||||
)
|
||||
|
||||
// IsValid reports whether s is a known agent status.
|
||||
func (s AgentStatus) IsValid() bool {
|
||||
switch s {
|
||||
case AgentStatusActive, AgentStatusIdle, AgentStatusThinking, AgentStatusError:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Agent ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
// AgentCardData is the primary data shape consumed by the Command Hub frontend.
|
||||
// It matches the TypeScript AgentCardData interface exactly.
|
||||
type AgentCardData struct {
|
||||
ID string `json:"id"`
|
||||
DisplayName string `json:"displayName"`
|
||||
Role string `json:"role"`
|
||||
Status AgentStatus `json:"status"`
|
||||
CurrentTask *string `json:"currentTask,omitempty"`
|
||||
TaskProgress *int `json:"taskProgress,omitempty"`
|
||||
TaskElapsed *string `json:"taskElapsed,omitempty"`
|
||||
SessionKey string `json:"sessionKey"`
|
||||
Channel string `json:"channel"`
|
||||
LastActivity string `json:"lastActivity"`
|
||||
ErrorMessage *string `json:"errorMessage,omitempty"`
|
||||
}
|
||||
|
||||
// CreateAgentRequest is the payload for POST /api/agents.
|
||||
type CreateAgentRequest struct {
|
||||
ID string `json:"id" validate:"required,min=2,max=64"`
|
||||
DisplayName string `json:"displayName" validate:"required,min=1,max=128"`
|
||||
Role string `json:"role" validate:"required,min=1,max=256"`
|
||||
Status AgentStatus `json:"status" validate:"required,agentStatus"`
|
||||
SessionKey string `json:"sessionKey" validate:"required,min=1"`
|
||||
Channel string `json:"channel" validate:"required,min=1,max=32"`
|
||||
CurrentTask *string `json:"currentTask,omitempty"`
|
||||
}
|
||||
|
||||
// UpdateAgentRequest is the payload for PUT /api/agents/{id}.
|
||||
type UpdateAgentRequest struct {
|
||||
Status *AgentStatus `json:"status,omitempty" validate:"omitempty,agentStatus"`
|
||||
CurrentTask *string `json:"currentTask,omitempty"`
|
||||
TaskProgress *int `json:"taskProgress,omitempty" validate:"omitempty,min=0,max=100"`
|
||||
TaskElapsed *string `json:"taskElapsed,omitempty"`
|
||||
Channel *string `json:"channel,omitempty" validate:"omitempty,min=1,max=32"`
|
||||
ErrorMessage *string `json:"errorMessage,omitempty"`
|
||||
}
|
||||
|
||||
// AgentStatusHistoryEntry represents a point-in-time status change for an agent.
|
||||
type AgentStatusHistoryEntry struct {
|
||||
ID string `json:"id"`
|
||||
AgentID string `json:"agentId"`
|
||||
Status AgentStatus `json:"status"`
|
||||
Task *string `json:"task,omitempty"`
|
||||
Timestamp string `json:"timestamp"`
|
||||
}
|
||||
|
||||
// ─── Session ───────────────────────────────────────────────────────────────────
|
||||
|
||||
// Session represents an active agent session tracked by the system.
|
||||
type Session struct {
|
||||
ID string `json:"id"`
|
||||
SessionKey string `json:"sessionKey"`
|
||||
AgentID string `json:"agentId"`
|
||||
Channel string `json:"channel"`
|
||||
Status string `json:"status"` // running, done, streaming, error
|
||||
ContextTokens int `json:"contextTokens"`
|
||||
TotalTokens int `json:"totalTokens"`
|
||||
EstimatedCost float64 `json:"estimatedCost"`
|
||||
Model string `json:"model"`
|
||||
StartedAt time.Time `json:"startedAt"`
|
||||
LastActivityAt time.Time `json:"lastActivityAt"`
|
||||
}
|
||||
|
||||
// ─── Task ───────────────────────────────────────────────────────────────────────
|
||||
|
||||
// TaskStatus represents the lifecycle state of a tracked task.
|
||||
type TaskStatus string
|
||||
|
||||
const (
|
||||
TaskStatusPending TaskStatus = "pending"
|
||||
TaskStatusRunning TaskStatus = "running"
|
||||
TaskStatusCompleted TaskStatus = "completed"
|
||||
TaskStatusFailed TaskStatus = "failed"
|
||||
)
|
||||
|
||||
// Task represents a tracked task assigned to an agent.
|
||||
type Task struct {
|
||||
ID string `json:"id"`
|
||||
AgentID string `json:"agentId"`
|
||||
Title string `json:"title"`
|
||||
Description string `json:"description"`
|
||||
Status TaskStatus `json:"status"`
|
||||
Progress *int `json:"progress,omitempty"`
|
||||
SessionKey string `json:"sessionKey"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
}
|
||||
|
||||
// ─── Project ────────────────────────────────────────────────────────────────────
|
||||
|
||||
// ProjectStatus represents the lifecycle state of a project.
|
||||
type ProjectStatus string
|
||||
|
||||
const (
|
||||
ProjectStatusPlanned ProjectStatus = "planned"
|
||||
ProjectStatusActive ProjectStatus = "active"
|
||||
ProjectStatusPaused ProjectStatus = "paused"
|
||||
ProjectStatusCompleted ProjectStatus = "completed"
|
||||
)
|
||||
|
||||
// Project represents a project tracked in the system.
|
||||
type Project struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
Status ProjectStatus `json:"status"`
|
||||
AgentIDs []string `json:"agentIds"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
}
|
||||
|
||||
// ─── Pagination ────────────────────────────────────────────────────────────────
|
||||
|
||||
// PaginatedResponse wraps a list response with pagination metadata.
|
||||
type PaginatedResponse struct {
|
||||
Data any `json:"data"`
|
||||
TotalCount int `json:"totalCount"`
|
||||
Page int `json:"page"`
|
||||
PageSize int `json:"pageSize"`
|
||||
HasMore bool `json:"hasMore"`
|
||||
}
|
||||
|
||||
// ─── Error ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
// ErrorResponse is the standard API error envelope.
|
||||
type ErrorResponse struct {
|
||||
Error string `json:"error"`
|
||||
Details map[string]string `json:"details,omitempty"`
|
||||
}
|
||||
84
go-backend/internal/router/router.go
Normal file
84
go-backend/internal/router/router.go
Normal file
@@ -0,0 +1,84 @@
|
||||
// Package router configures the chi router with all routes, middleware,
|
||||
// and handler wiring for the Control Center API.
|
||||
package router
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"code.cubecraftcreations.com/CubeCraft-Creations/Control-Center/go-backend/internal/db"
|
||||
"code.cubecraftcreations.com/CubeCraft-Creations/Control-Center/go-backend/internal/handler"
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/go-chi/chi/v5/middleware"
|
||||
"github.com/go-chi/cors"
|
||||
)
|
||||
|
||||
// Dependencies carries the handler and database pool into the router.
|
||||
type Dependencies struct {
|
||||
Handler *handler.Handler
|
||||
DB *db.Pool
|
||||
CORSOrigin string
|
||||
}
|
||||
|
||||
// New creates a fully-configured chi router with all API routes mounted.
|
||||
func New(deps *Dependencies) *chi.Mux {
|
||||
r := chi.NewRouter()
|
||||
|
||||
// ── Global middleware ──────────────────────────────────────────────────
|
||||
r.Use(middleware.RequestID)
|
||||
r.Use(middleware.RealIP)
|
||||
r.Use(middleware.Logger)
|
||||
r.Use(middleware.Recoverer)
|
||||
r.Use(middleware.Timeout(30 * time.Second))
|
||||
|
||||
// ── CORS ───────────────────────────────────────────────────────────────
|
||||
corsOrigin := deps.CORSOrigin
|
||||
if corsOrigin == "" {
|
||||
corsOrigin = "*"
|
||||
}
|
||||
r.Use(cors.Handler(cors.Options{
|
||||
AllowedOrigins: []string{corsOrigin},
|
||||
AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
|
||||
AllowedHeaders: []string{"Accept", "Authorization", "Content-Type"},
|
||||
ExposedHeaders: []string{"Link", "X-Total-Count"},
|
||||
AllowCredentials: false,
|
||||
MaxAge: 300,
|
||||
}))
|
||||
|
||||
// ── Health check (with DB connectivity probe) ──────────────────────────
|
||||
r.Get("/health", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
status := "ok"
|
||||
if deps.DB != nil {
|
||||
if err := deps.DB.Health(r.Context()); err != nil {
|
||||
w.WriteHeader(http.StatusServiceUnavailable)
|
||||
status = "db_unhealthy"
|
||||
}
|
||||
}
|
||||
w.Write([]byte(`{"status":"` + status + `"}`))
|
||||
})
|
||||
|
||||
// ── API v1 routes ──────────────────────────────────────────────────────
|
||||
r.Route("/api", func(api chi.Router) {
|
||||
// Agents CRUD
|
||||
api.Route("/agents", func(agents chi.Router) {
|
||||
agents.Get("/", deps.Handler.ListAgents) // GET /api/agents
|
||||
agents.Post("/", deps.Handler.CreateAgent) // POST /api/agents
|
||||
agents.Get("/{id}", deps.Handler.GetAgent) // GET /api/agents/{id}
|
||||
agents.Put("/{id}", deps.Handler.UpdateAgent) // PUT /api/agents/{id}
|
||||
agents.Delete("/{id}", deps.Handler.DeleteAgent) // DELETE /api/agents/{id}
|
||||
agents.Get("/{id}/history", deps.Handler.AgentHistory) // GET /api/agents/{id}/history
|
||||
})
|
||||
|
||||
// Sessions
|
||||
api.Get("/sessions", deps.Handler.ListSessions)
|
||||
|
||||
// Tasks
|
||||
api.Get("/tasks", deps.Handler.ListTasks)
|
||||
|
||||
// Projects
|
||||
api.Get("/projects", deps.Handler.ListProjects)
|
||||
})
|
||||
|
||||
return r
|
||||
}
|
||||
177
go-backend/internal/store/agent.go
Normal file
177
go-backend/internal/store/agent.go
Normal file
@@ -0,0 +1,177 @@
|
||||
// Package store provides thread-safe in-memory data stores for the
|
||||
// Control Center API. These will be replaced with PostgreSQL-backed
|
||||
// implementations once CUB-120 (schema design) is complete.
|
||||
package store
|
||||
|
||||
import (
|
||||
"sort"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"code.cubecraftcreations.com/CubeCraft-Creations/Control-Center/go-backend/internal/models"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// AgentStore provides thread-safe CRUD operations for agents.
|
||||
type AgentStore struct {
|
||||
mu sync.RWMutex
|
||||
agents map[string]models.AgentCardData
|
||||
history map[string][]models.AgentStatusHistoryEntry // agentID -> history
|
||||
}
|
||||
|
||||
// NewAgentStore returns an initialized AgentStore.
|
||||
func NewAgentStore() *AgentStore {
|
||||
return &AgentStore{
|
||||
agents: make(map[string]models.AgentCardData),
|
||||
history: make(map[string][]models.AgentStatusHistoryEntry),
|
||||
}
|
||||
}
|
||||
|
||||
// List returns all agents, optionally filtered by status.
|
||||
func (s *AgentStore) List(statusFilter models.AgentStatus) []models.AgentCardData {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
result := make([]models.AgentCardData, 0, len(s.agents))
|
||||
for _, a := range s.agents {
|
||||
if statusFilter != "" && a.Status != statusFilter {
|
||||
continue
|
||||
}
|
||||
result = append(result, a)
|
||||
}
|
||||
|
||||
// Sort by display name for consistent output.
|
||||
sort.Slice(result, func(i, j int) bool {
|
||||
return result[i].DisplayName < result[j].DisplayName
|
||||
})
|
||||
return result
|
||||
}
|
||||
|
||||
// Get returns a single agent by ID, or false if not found.
|
||||
func (s *AgentStore) Get(id string) (models.AgentCardData, bool) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
a, ok := s.agents[id]
|
||||
return a, ok
|
||||
}
|
||||
|
||||
// Create inserts a new agent. Returns false if the ID already exists.
|
||||
func (s *AgentStore) Create(a models.AgentCardData) bool {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if _, exists := s.agents[a.ID]; exists {
|
||||
return false
|
||||
}
|
||||
if a.LastActivity == "" {
|
||||
a.LastActivity = time.Now().UTC().Format(time.RFC3339)
|
||||
}
|
||||
s.agents[a.ID] = a
|
||||
|
||||
// Record initial history entry.
|
||||
s.appendHistoryLocked(a.ID, models.AgentStatusHistoryEntry{
|
||||
ID: uuid.New().String(),
|
||||
AgentID: a.ID,
|
||||
Status: a.Status,
|
||||
Task: a.CurrentTask,
|
||||
Timestamp: a.LastActivity,
|
||||
})
|
||||
return true
|
||||
}
|
||||
|
||||
// Update applies partial updates to an agent. Returns the updated agent or false if not found.
|
||||
func (s *AgentStore) Update(id string, req models.UpdateAgentRequest) (models.AgentCardData, bool) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
a, ok := s.agents[id]
|
||||
if !ok {
|
||||
return models.AgentCardData{}, false
|
||||
}
|
||||
|
||||
prevStatus := a.Status
|
||||
prevTask := a.CurrentTask
|
||||
|
||||
if req.Status != nil {
|
||||
a.Status = *req.Status
|
||||
}
|
||||
if req.CurrentTask != nil {
|
||||
a.CurrentTask = req.CurrentTask
|
||||
}
|
||||
if req.TaskProgress != nil {
|
||||
a.TaskProgress = req.TaskProgress
|
||||
}
|
||||
if req.TaskElapsed != nil {
|
||||
a.TaskElapsed = req.TaskElapsed
|
||||
}
|
||||
if req.Channel != nil {
|
||||
a.Channel = *req.Channel
|
||||
}
|
||||
if req.ErrorMessage != nil {
|
||||
a.ErrorMessage = req.ErrorMessage
|
||||
}
|
||||
a.LastActivity = time.Now().UTC().Format(time.RFC3339)
|
||||
s.agents[id] = a
|
||||
|
||||
// Record history entry if status or task changed.
|
||||
if (req.Status != nil && *req.Status != prevStatus) || (req.CurrentTask != nil && prevTask == nil) ||
|
||||
(req.CurrentTask != nil && prevTask != nil && *req.CurrentTask != *prevTask) {
|
||||
status := a.Status
|
||||
if req.Status != nil {
|
||||
status = *req.Status
|
||||
}
|
||||
s.appendHistoryLocked(id, models.AgentStatusHistoryEntry{
|
||||
ID: uuid.New().String(),
|
||||
AgentID: id,
|
||||
Status: status,
|
||||
Task: a.CurrentTask,
|
||||
Timestamp: a.LastActivity,
|
||||
})
|
||||
}
|
||||
|
||||
return a, true
|
||||
}
|
||||
|
||||
// Delete removes an agent. Returns true if the agent existed.
|
||||
func (s *AgentStore) Delete(id string) bool {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if _, ok := s.agents[id]; !ok {
|
||||
return false
|
||||
}
|
||||
delete(s.agents, id)
|
||||
delete(s.history, id)
|
||||
return true
|
||||
}
|
||||
|
||||
// History returns the status history for an agent, newest first.
|
||||
func (s *AgentStore) History(agentID string) []models.AgentStatusHistoryEntry {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
entries, ok := s.history[agentID]
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
// Return a defensive copy, sorted newest first (by index when timestamps tie).
|
||||
result := make([]models.AgentStatusHistoryEntry, len(entries))
|
||||
copy(result, entries)
|
||||
sort.SliceStable(result, func(i, j int) bool {
|
||||
if result[i].Timestamp == result[j].Timestamp {
|
||||
return i > j // later index = newer when timestamps match
|
||||
}
|
||||
return result[i].Timestamp > result[j].Timestamp
|
||||
})
|
||||
return result
|
||||
}
|
||||
|
||||
// Count returns the total number of agents.
|
||||
func (s *AgentStore) Count() int {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
return len(s.agents)
|
||||
}
|
||||
|
||||
// appendHistoryLocked adds a history entry. Caller must hold s.mu (write lock).
|
||||
func (s *AgentStore) appendHistoryLocked(agentID string, entry models.AgentStatusHistoryEntry) {
|
||||
s.history[agentID] = append(s.history[agentID], entry)
|
||||
}
|
||||
67
go-backend/internal/store/project.go
Normal file
67
go-backend/internal/store/project.go
Normal file
@@ -0,0 +1,67 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"sort"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"code.cubecraftcreations.com/CubeCraft-Creations/Control-Center/go-backend/internal/models"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// ProjectStore provides thread-safe CRUD operations for projects.
|
||||
type ProjectStore struct {
|
||||
mu sync.RWMutex
|
||||
projects map[string]models.Project
|
||||
}
|
||||
|
||||
// NewProjectStore returns an initialized ProjectStore.
|
||||
func NewProjectStore() *ProjectStore {
|
||||
return &ProjectStore{
|
||||
projects: make(map[string]models.Project),
|
||||
}
|
||||
}
|
||||
|
||||
// List returns all projects ordered by name.
|
||||
func (s *ProjectStore) List() []models.Project {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
result := make([]models.Project, 0, len(s.projects))
|
||||
for _, p := range s.projects {
|
||||
result = append(result, p)
|
||||
}
|
||||
sort.Slice(result, func(i, j int) bool {
|
||||
return result[i].Name < result[j].Name
|
||||
})
|
||||
return result
|
||||
}
|
||||
|
||||
// Create inserts a new project.
|
||||
func (s *ProjectStore) Create(p models.Project) models.Project {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
if p.ID == "" {
|
||||
p.ID = uuid.New().String()
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
if p.CreatedAt.IsZero() {
|
||||
p.CreatedAt = now
|
||||
}
|
||||
if p.UpdatedAt.IsZero() {
|
||||
p.UpdatedAt = now
|
||||
}
|
||||
if p.AgentIDs == nil {
|
||||
p.AgentIDs = []string{}
|
||||
}
|
||||
s.projects[p.ID] = p
|
||||
return p
|
||||
}
|
||||
|
||||
// Count returns the total number of projects.
|
||||
func (s *ProjectStore) Count() int {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
return len(s.projects)
|
||||
}
|
||||
80
go-backend/internal/store/session.go
Normal file
80
go-backend/internal/store/session.go
Normal file
@@ -0,0 +1,80 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"sort"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"code.cubecraftcreations.com/CubeCraft-Creations/Control-Center/go-backend/internal/models"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// SessionStore provides thread-safe CRUD operations for sessions.
|
||||
type SessionStore struct {
|
||||
mu sync.RWMutex
|
||||
sessions map[string]models.Session // id -> session
|
||||
}
|
||||
|
||||
// NewSessionStore returns an initialized SessionStore.
|
||||
func NewSessionStore() *SessionStore {
|
||||
return &SessionStore{
|
||||
sessions: make(map[string]models.Session),
|
||||
}
|
||||
}
|
||||
|
||||
// ListActive returns all sessions with status "running" or "streaming", newest first.
|
||||
func (s *SessionStore) ListActive() []models.Session {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
result := make([]models.Session, 0)
|
||||
for _, sess := range s.sessions {
|
||||
if sess.Status == "running" || sess.Status == "streaming" {
|
||||
result = append(result, sess)
|
||||
}
|
||||
}
|
||||
sort.Slice(result, func(i, j int) bool {
|
||||
return result[i].LastActivityAt.After(result[j].LastActivityAt)
|
||||
})
|
||||
return result
|
||||
}
|
||||
|
||||
// Create inserts a new session.
|
||||
func (s *SessionStore) Create(sess models.Session) models.Session {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
if sess.ID == "" {
|
||||
sess.ID = uuid.New().String()
|
||||
}
|
||||
if sess.StartedAt.IsZero() {
|
||||
sess.StartedAt = time.Now().UTC()
|
||||
}
|
||||
if sess.LastActivityAt.IsZero() {
|
||||
sess.LastActivityAt = sess.StartedAt
|
||||
}
|
||||
s.sessions[sess.ID] = sess
|
||||
return sess
|
||||
}
|
||||
|
||||
// UpdateStatus updates the status and last-activity timestamp of a session.
|
||||
func (s *SessionStore) UpdateStatus(id, status string) bool {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
sess, ok := s.sessions[id]
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
sess.Status = status
|
||||
sess.LastActivityAt = time.Now().UTC()
|
||||
s.sessions[id] = sess
|
||||
return true
|
||||
}
|
||||
|
||||
// Count returns the total number of sessions.
|
||||
func (s *SessionStore) Count() int {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
return len(s.sessions)
|
||||
}
|
||||
64
go-backend/internal/store/task.go
Normal file
64
go-backend/internal/store/task.go
Normal file
@@ -0,0 +1,64 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"sort"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"code.cubecraftcreations.com/CubeCraft-Creations/Control-Center/go-backend/internal/models"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// TaskStore provides thread-safe CRUD operations for tasks.
|
||||
type TaskStore struct {
|
||||
mu sync.RWMutex
|
||||
tasks map[string]models.Task
|
||||
}
|
||||
|
||||
// NewTaskStore returns an initialized TaskStore.
|
||||
func NewTaskStore() *TaskStore {
|
||||
return &TaskStore{
|
||||
tasks: make(map[string]models.Task),
|
||||
}
|
||||
}
|
||||
|
||||
// ListRecent returns tasks ordered by updated_at descending (newest first).
|
||||
func (s *TaskStore) ListRecent() []models.Task {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
result := make([]models.Task, 0, len(s.tasks))
|
||||
for _, t := range s.tasks {
|
||||
result = append(result, t)
|
||||
}
|
||||
sort.Slice(result, func(i, j int) bool {
|
||||
return result[i].UpdatedAt.After(result[j].UpdatedAt)
|
||||
})
|
||||
return result
|
||||
}
|
||||
|
||||
// Create inserts a new task.
|
||||
func (s *TaskStore) Create(t models.Task) models.Task {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
if t.ID == "" {
|
||||
t.ID = uuid.New().String()
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
if t.CreatedAt.IsZero() {
|
||||
t.CreatedAt = now
|
||||
}
|
||||
if t.UpdatedAt.IsZero() {
|
||||
t.UpdatedAt = now
|
||||
}
|
||||
s.tasks[t.ID] = t
|
||||
return t
|
||||
}
|
||||
|
||||
// Count returns the total number of tasks.
|
||||
func (s *TaskStore) Count() int {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
return len(s.tasks)
|
||||
}
|
||||
Reference in New Issue
Block a user