Compare commits
1 Commits
cce3e061a7
...
agent/rex/
| Author | SHA1 | Date | |
|---|---|---|---|
| f29eaa9685 |
@@ -1,33 +0,0 @@
|
|||||||
# 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
|
|
||||||
@@ -1,38 +0,0 @@
|
|||||||
# ============================================================
|
|
||||||
# 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,8 +56,7 @@
|
|||||||
],
|
],
|
||||||
"stylePreprocessorOptions": {
|
"stylePreprocessorOptions": {
|
||||||
"includePaths": [
|
"includePaths": [
|
||||||
"src",
|
"src"
|
||||||
"src/styles"
|
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -1,54 +0,0 @@
|
|||||||
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,13 +2,11 @@
|
|||||||
<!-- AgentCard — per spec Section 7.3 -->
|
<!-- AgentCard — per spec Section 7.3 -->
|
||||||
<!-- Integrates: Status Badge · Task Progress Bar · Quick‑Jump Button -->
|
<!-- Integrates: Status Badge · Task Progress Bar · Quick‑Jump Button -->
|
||||||
<!-- Left‑border accent matches status color. role="article" + aria‑labels. -->
|
<!-- Left‑border accent matches status color. role="article" + aria‑labels. -->
|
||||||
<!-- Enhanced: data-status attribute, elapsed time, design tokens. -->
|
|
||||||
<!-- ========================================================================== -->
|
<!-- ========================================================================== -->
|
||||||
<article
|
<article
|
||||||
class="agent-card"
|
class="agent-card"
|
||||||
role="article"
|
role="article"
|
||||||
[attr.data-status]="status"
|
[attr.aria-label]="displayName + ' — ' + statusLabel()"
|
||||||
[attr.aria-label]="(displayName || agentId) + ' — ' + statusLabel()"
|
|
||||||
[style.border-left-color]="statusBorderColor()"
|
[style.border-left-color]="statusBorderColor()"
|
||||||
(click)="cardClick.emit(sessionKey)"
|
(click)="cardClick.emit(sessionKey)"
|
||||||
appLongPress
|
appLongPress
|
||||||
@@ -34,20 +32,19 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- ── Body: current task ── -->
|
<!-- ── Body: current task ── -->
|
||||||
<div class="agent-card__body" *ngIf="task || isError()">
|
<div class="agent-card__body" *ngIf="task || status === 'error'">
|
||||||
<p
|
<p
|
||||||
class="agent-card__task"
|
class="agent-card__task"
|
||||||
[class.agent-card__task--error]="isError()"
|
[attr.aria-label]="'Current task: ' + (status === 'error' ? errorMessage : task)"
|
||||||
[attr.aria-label]="'Current task: ' + (isError() ? errorMessage || task : task)"
|
|
||||||
>
|
>
|
||||||
{{ isError() ? errorMessage || task : task }}
|
{{ status === 'error' ? errorMessage || task : task }}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- ── Task Progress Bar ── -->
|
<!-- ── Task Progress Bar ── -->
|
||||||
<div
|
<div
|
||||||
class="agent-card__progress"
|
class="agent-card__progress"
|
||||||
*ngIf="showProgress()"
|
*ngIf="progress > 0 && status !== 'error'"
|
||||||
[attr.aria-label]="'Task progress: ' + progress + '%'"
|
[attr.aria-label]="'Task progress: ' + progress + '%'"
|
||||||
>
|
>
|
||||||
<mat-progress-bar
|
<mat-progress-bar
|
||||||
@@ -58,16 +55,6 @@
|
|||||||
<span class="agent-card__progress-label text-mono">{{ progress }}%</span>
|
<span class="agent-card__progress-label text-mono">{{ progress }}%</span>
|
||||||
</div>
|
</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 ── -->
|
<!-- ── Footer: channel + last activity + quick‑jump ── -->
|
||||||
<div class="agent-card__footer">
|
<div class="agent-card__footer">
|
||||||
<div class="agent-card__meta">
|
<div class="agent-card__meta">
|
||||||
|
|||||||
@@ -2,18 +2,15 @@
|
|||||||
// AgentCard — M3 tactical dark styling
|
// AgentCard — M3 tactical dark styling
|
||||||
// Per spec Section 7.3: left‑border accent, status‑aware coloring,
|
// Per spec Section 7.3: left‑border accent, status‑aware coloring,
|
||||||
// responsive card layout with 320px min‑width.
|
// responsive card layout with 320px min‑width.
|
||||||
// Enhanced: data-status selectors, elapsed time, design token imports.
|
|
||||||
// ============================================================================
|
// ============================================================================
|
||||||
|
|
||||||
@use 'tokens' as tokens;
|
|
||||||
|
|
||||||
.agent-card {
|
.agent-card {
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
min-width: tokens.$cc-card-min-width;
|
min-width: var(--cc-card-min-width);
|
||||||
padding: tokens.$cc-card-padding;
|
padding: var(--cc-card-padding);
|
||||||
background-color: var(--cc-surface-container);
|
background-color: var(--cc-surface-container);
|
||||||
border-radius: tokens.$cc-card-border-radius;
|
border-radius: var(--cc-card-border-radius);
|
||||||
border-left: 4px solid var(--status-offline); // default; overridden by [style]
|
border-left: 4px solid var(--status-offline); // default; overridden by [style]
|
||||||
border-top: 1px solid var(--cc-outline);
|
border-top: 1px solid var(--cc-outline);
|
||||||
border-right: 1px solid var(--cc-outline);
|
border-right: 1px solid var(--cc-outline);
|
||||||
@@ -59,6 +56,11 @@
|
|||||||
letter-spacing: 0.02em;
|
letter-spacing: 0.02em;
|
||||||
text-transform: uppercase;
|
text-transform: uppercase;
|
||||||
color: var(--cc-on-surface);
|
color: var(--cc-on-surface);
|
||||||
|
|
||||||
|
// Per‑status background tints
|
||||||
|
.status-dot--active + & {
|
||||||
|
background-color: var(--status-active-bg);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
.agent-card__status-label {
|
.agent-card__status-label {
|
||||||
@@ -100,7 +102,8 @@
|
|||||||
color: var(--cc-on-surface);
|
color: var(--cc-on-surface);
|
||||||
line-height: 1.4;
|
line-height: 1.4;
|
||||||
|
|
||||||
&--error {
|
// Error messages get distinct styling
|
||||||
|
.agent-card--error & {
|
||||||
color: var(--status-error);
|
color: var(--status-error);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -114,7 +117,6 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.agent-card__progress-label {
|
.agent-card__progress-label {
|
||||||
font-family: var(--cc-font-mono);
|
|
||||||
font-size: 12px;
|
font-size: 12px;
|
||||||
font-weight: 500;
|
font-weight: 500;
|
||||||
color: var(--cc-on-surface-variant);
|
color: var(--cc-on-surface-variant);
|
||||||
@@ -136,23 +138,6 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── 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 ──
|
// ── Footer ──
|
||||||
.agent-card__footer {
|
.agent-card__footer {
|
||||||
display: flex;
|
display: flex;
|
||||||
@@ -176,6 +161,7 @@
|
|||||||
color: var(--cc-on-surface-variant);
|
color: var(--cc-on-surface-variant);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.agent-card__channel-icon,
|
||||||
.agent-card__channel .mat-icon {
|
.agent-card__channel .mat-icon {
|
||||||
font-size: 14px;
|
font-size: 14px;
|
||||||
width: 14px;
|
width: 14px;
|
||||||
@@ -191,6 +177,7 @@
|
|||||||
.agent-card__jump {
|
.agent-card__jump {
|
||||||
flex-shrink: 0;
|
flex-shrink: 0;
|
||||||
|
|
||||||
|
// Match M3 text button sizing
|
||||||
.mat-mdc-button {
|
.mat-mdc-button {
|
||||||
min-width: 36px;
|
min-width: 36px;
|
||||||
padding: 0 8px;
|
padding: 0 8px;
|
||||||
@@ -205,9 +192,11 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ── Status‑specific background tints for badge ──
|
// ── Status‑specific background tints for badge ──
|
||||||
// Using data-status attribute selectors for clean styling.
|
// We use the global status-dot classes from styles.scss and pair them
|
||||||
|
// with contextual background-color overrides here.
|
||||||
|
|
||||||
.agent-card[data-status="active"] .agent-card__badge {
|
.agent-card[data-status="active"] .agent-card__badge,
|
||||||
|
.agent-card .status-dot--active ~ .agent-card__badge {
|
||||||
background-color: var(--status-active-bg);
|
background-color: var(--status-active-bg);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -223,22 +212,8 @@
|
|||||||
background-color: var(--status-error-bg);
|
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 ──
|
// ── Responsive ──
|
||||||
@media (max-width: tokens.$cc-breakpoint-mobile) {
|
@media (max-width: 599px) {
|
||||||
.agent-card {
|
.agent-card {
|
||||||
min-width: unset;
|
min-width: unset;
|
||||||
padding: 16px;
|
padding: 16px;
|
||||||
|
|||||||
@@ -3,12 +3,8 @@ import {
|
|||||||
Component,
|
Component,
|
||||||
EventEmitter,
|
EventEmitter,
|
||||||
Input,
|
Input,
|
||||||
OnDestroy,
|
|
||||||
Output,
|
Output,
|
||||||
computed,
|
computed,
|
||||||
effect,
|
|
||||||
inject,
|
|
||||||
signal,
|
|
||||||
} from '@angular/core';
|
} from '@angular/core';
|
||||||
import { CommonModule } from '@angular/common';
|
import { CommonModule } from '@angular/common';
|
||||||
import { RouterModule } from '@angular/router';
|
import { RouterModule } from '@angular/router';
|
||||||
@@ -18,18 +14,12 @@ import { MatProgressBarModule } from '@angular/material/progress-bar';
|
|||||||
import { MatTooltipModule } from '@angular/material/tooltip';
|
import { MatTooltipModule } from '@angular/material/tooltip';
|
||||||
import { AgentStatus } from '../../../models/agent.model';
|
import { AgentStatus } from '../../../models/agent.model';
|
||||||
import { LongPressDirective } from '../../../directives/long-press.directive';
|
import { LongPressDirective } from '../../../directives/long-press.directive';
|
||||||
import {
|
|
||||||
STATUS_COLORS,
|
|
||||||
STATUS_LABELS,
|
|
||||||
CHANNEL_ICONS,
|
|
||||||
} from '../../../design/tokens';
|
|
||||||
|
|
||||||
// ============================================================================
|
// ============================================================================
|
||||||
// AgentCard Component
|
// AgentCard Component
|
||||||
// Per spec Section 7.3: Composes Agent Status Badge, Task Progress Bar,
|
// Per spec Section 7.3: Composes Agent Status Badge, Task Progress Bar,
|
||||||
// and Quick‑Jump Button into a card with left‑border status accent.
|
// and Quick‑Jump Button into a card with left‑border status accent.
|
||||||
// CUB-26: Emits cardClick and cardLongPress for drawer/modal integration.
|
// CUB-26: Emits cardClick and cardLongPress for drawer/modal integration.
|
||||||
// Enhanced with data-status attribute, elapsed time, and design tokens.
|
|
||||||
// ============================================================================
|
// ============================================================================
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
@@ -48,7 +38,7 @@ import {
|
|||||||
styleUrl: './agent-card.component.scss',
|
styleUrl: './agent-card.component.scss',
|
||||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||||
})
|
})
|
||||||
export class AgentCardComponent implements OnDestroy {
|
export class AgentCardComponent {
|
||||||
// --- Six required inputs per spec ---
|
// --- Six required inputs per spec ---
|
||||||
|
|
||||||
/** Agent status — drives badge color and left‑border accent */
|
/** Agent status — drives badge color and left‑border accent */
|
||||||
@@ -83,9 +73,6 @@ export class AgentCardComponent implements OnDestroy {
|
|||||||
/** Error message (shown only when status is 'error') */
|
/** Error message (shown only when status is 'error') */
|
||||||
@Input() errorMessage = '';
|
@Input() errorMessage = '';
|
||||||
|
|
||||||
/** Elapsed time string, e.g. "04m 12s" */
|
|
||||||
@Input() taskElapsed = '';
|
|
||||||
|
|
||||||
// --- CUB-26: Outputs for drawer/modal integration ---
|
// --- CUB-26: Outputs for drawer/modal integration ---
|
||||||
|
|
||||||
/** Emitted when the card is clicked — opens the session drawer. */
|
/** Emitted when the card is clicked — opens the session drawer. */
|
||||||
@@ -94,15 +81,7 @@ export class AgentCardComponent implements OnDestroy {
|
|||||||
/** Emitted when the card is long-pressed — bypasses drawer, opens session log directly. */
|
/** Emitted when the card is long-pressed — bypasses drawer, opens session log directly. */
|
||||||
@Output() readonly cardLongPress = new EventEmitter<string>();
|
@Output() readonly cardLongPress = new EventEmitter<string>();
|
||||||
|
|
||||||
// --- Internal state ---
|
// --- Computed values ---
|
||||||
|
|
||||||
/** 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 */
|
/** Map status → CSS custom property for the left‑border accent */
|
||||||
readonly statusBorderColor = computed(() => {
|
readonly statusBorderColor = computed(() => {
|
||||||
@@ -116,68 +95,46 @@ export class AgentCardComponent implements OnDestroy {
|
|||||||
return map[this.status] ?? 'var(--status-offline)';
|
return map[this.status] ?? 'var(--status-offline)';
|
||||||
});
|
});
|
||||||
|
|
||||||
/** Human‑readable status label (from design tokens) */
|
/** Human‑readable status label */
|
||||||
readonly statusLabel = computed(() => STATUS_LABELS[this.status] ?? this.status);
|
readonly statusLabel = computed(() => {
|
||||||
|
const labels: Record<AgentStatus, string> = {
|
||||||
|
active: 'Active',
|
||||||
|
idle: 'Idle',
|
||||||
|
thinking: 'Thinking…',
|
||||||
|
error: 'Error',
|
||||||
|
offline: 'Offline',
|
||||||
|
};
|
||||||
|
return labels[this.status] ?? this.status;
|
||||||
|
});
|
||||||
|
|
||||||
/** CSS class suffix for the status badge dot */
|
/** CSS class suffix for the status badge dot */
|
||||||
readonly statusDotClass = computed(() => `status-dot--${this.status}`);
|
readonly statusDotClass = computed(() => `status-dot--${this.status}`);
|
||||||
|
|
||||||
/** Material icon name for the channel (from design tokens) */
|
/** Material icon name for the channel */
|
||||||
readonly channelIcon = computed(() => CHANNEL_ICONS[this.channel] ?? 'chat');
|
readonly channelIcon = computed(() => {
|
||||||
|
const icons: Record<string, string> = {
|
||||||
/** Relative time string for lastActivity, refreshed every 30s */
|
telegram: 'telegram', // falls back to font icon if no SVG registered
|
||||||
readonly lastActivityLabel = computed(() => {
|
slack: 'chat',
|
||||||
// Read tick to create dependency that forces recomputation
|
discord: 'forum',
|
||||||
this._tick();
|
whatsapp: 'chat',
|
||||||
return this._relativeTime(this.lastActivity);
|
webchat: 'language',
|
||||||
|
email: 'email',
|
||||||
|
};
|
||||||
|
return icons[this.channel] ?? 'chat';
|
||||||
});
|
});
|
||||||
|
|
||||||
/** Quick‑jump route derived from sessionKey */
|
/** Relative time string for lastActivity */
|
||||||
readonly jumpRoute = computed(() => `/sessions/${this.sessionKey}`);
|
readonly lastActivityLabel = computed(() => {
|
||||||
|
if (!this.lastActivity) return '';
|
||||||
/** 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 now = Date.now();
|
||||||
const then = date.getTime();
|
const then = this.lastActivity.getTime();
|
||||||
const diffSec = Math.max(0, Math.floor((now - then) / 1000));
|
const diffSec = Math.max(0, Math.floor((now - then) / 1000));
|
||||||
if (diffSec < 60) return 'just now';
|
if (diffSec < 60) return 'just now';
|
||||||
if (diffSec < 3600) return `${Math.floor(diffSec / 60)}m ago`;
|
if (diffSec < 3600) return `${Math.floor(diffSec / 60)}m ago`;
|
||||||
if (diffSec < 86400) return `${Math.floor(diffSec / 3600)}h ago`;
|
if (diffSec < 86400) return `${Math.floor(diffSec / 3600)}h ago`;
|
||||||
return `${Math.floor(diffSec / 86400)}d ago`;
|
return `${Math.floor(diffSec / 86400)}d ago`;
|
||||||
}
|
});
|
||||||
|
|
||||||
private _startTimer(): void {
|
/** Quick‑jump route derived from sessionKey */
|
||||||
this._stopTimer();
|
readonly jumpRoute = computed(() => `/sessions/${this.sessionKey}`);
|
||||||
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;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
<!-- ============================================================================
|
||||||
|
Dashboard Summary Component Template
|
||||||
|
Displays total active agents, status breakdown, and system health.
|
||||||
|
============================================================================ -->
|
||||||
|
|
||||||
|
<section class="dashboard-summary" role="region" aria-label="Dashboard summary">
|
||||||
|
|
||||||
|
<!-- Total Agents -->
|
||||||
|
<div class="summary-total">
|
||||||
|
<span class="summary-total__count">{{ totalAgents() }}</span>
|
||||||
|
<span class="summary-total__label">Total Agents</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Status Breakdown -->
|
||||||
|
<div class="summary-breakdown" role="list" aria-label="Agent status breakdown">
|
||||||
|
@for (item of statusItems(); track item.status) {
|
||||||
|
<div class="status-item {{ statusClass(item.status) }}" role="listitem">
|
||||||
|
<span class="status-item__dot" [attr.aria-hidden]="true"></span>
|
||||||
|
<span class="status-item__label">{{ item.label }}</span>
|
||||||
|
<span class="status-item__count">{{ item.count }}</span>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- System Health Indicator -->
|
||||||
|
<div class="health-indicator {{ healthClass() }}" role="status" aria-label="System health: {{ healthLabel() }}">
|
||||||
|
<span class="health-indicator__dot" [attr.aria-hidden]="true"></span>
|
||||||
|
<span class="health-indicator__label">System</span>
|
||||||
|
<span class="health-indicator__value">{{ healthLabel() }}</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
</section>
|
||||||
@@ -0,0 +1,218 @@
|
|||||||
|
// ============================================================================
|
||||||
|
// Dashboard Summary Component Styles
|
||||||
|
// Uses design tokens from styles/_tokens.scss (CUB-21)
|
||||||
|
// ============================================================================
|
||||||
|
|
||||||
|
@use '../../../styles/tokens' as tokens;
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Host block
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
:host {
|
||||||
|
display: block;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Summary container
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
.dashboard-summary {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: tokens.$spacing-5;
|
||||||
|
padding: tokens.$spacing-6;
|
||||||
|
background-color: tokens.$color-surface-medium;
|
||||||
|
border-radius: tokens.$card-border-radius;
|
||||||
|
border: 1px solid tokens.$color-surface-lighter;
|
||||||
|
box-shadow: tokens.$shadow-level-1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Total agents
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
.summary-total {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: center;
|
||||||
|
gap: tokens.$spacing-1;
|
||||||
|
padding-bottom: tokens.$spacing-4;
|
||||||
|
border-bottom: 1px solid tokens.$color-surface-lighter;
|
||||||
|
|
||||||
|
&__count {
|
||||||
|
font-family: tokens.$font-family-brand;
|
||||||
|
font-size: tokens.$font-size-display-small;
|
||||||
|
font-weight: tokens.$font-weight-heavy;
|
||||||
|
line-height: tokens.$line-height-tight;
|
||||||
|
color: tokens.$color-on-surface;
|
||||||
|
letter-spacing: tokens.$letter-spacing-tight;
|
||||||
|
}
|
||||||
|
|
||||||
|
&__label {
|
||||||
|
font-family: tokens.$font-family-body;
|
||||||
|
font-size: tokens.$font-size-label-large;
|
||||||
|
font-weight: tokens.$font-weight-medium;
|
||||||
|
color: tokens.$color-on-surface-variant;
|
||||||
|
text-transform: uppercase;
|
||||||
|
letter-spacing: tokens.$letter-spacing-wide;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Status breakdown
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
.summary-breakdown {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(2, 1fr);
|
||||||
|
gap: tokens.$spacing-3;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Individual status item
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
.status-item {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: tokens.$spacing-2;
|
||||||
|
padding: tokens.$spacing-3 tokens.$spacing-4;
|
||||||
|
border-radius: tokens.$radius-md;
|
||||||
|
background-color: tokens.$color-surface-dark;
|
||||||
|
border: 1px solid tokens.$color-surface-lighter;
|
||||||
|
transition: background-color tokens.$duration-short tokens.$easing-standard;
|
||||||
|
|
||||||
|
&__dot {
|
||||||
|
width: tokens.$status-dot-size;
|
||||||
|
height: tokens.$status-dot-size;
|
||||||
|
border-radius: tokens.$radius-full;
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
&__label {
|
||||||
|
flex: 1;
|
||||||
|
font-family: tokens.$font-family-body;
|
||||||
|
font-size: tokens.$font-size-body-medium;
|
||||||
|
font-weight: tokens.$font-weight-medium;
|
||||||
|
color: tokens.$color-on-surface-variant;
|
||||||
|
}
|
||||||
|
|
||||||
|
&__count {
|
||||||
|
font-family: tokens.$font-family-mono;
|
||||||
|
font-size: tokens.$font-size-body-large;
|
||||||
|
font-weight: tokens.$font-weight-bold;
|
||||||
|
color: tokens.$color-on-surface;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Status-specific colors using the token map
|
||||||
|
&--active {
|
||||||
|
.status-item__dot {
|
||||||
|
background-color: tokens.$status-active;
|
||||||
|
animation: pulse-active tokens.$duration-standard tokens.$easing-standard infinite;
|
||||||
|
}
|
||||||
|
.status-item__count { color: tokens.$status-active; }
|
||||||
|
}
|
||||||
|
|
||||||
|
&--idle {
|
||||||
|
.status-item__dot {
|
||||||
|
background-color: tokens.$status-idle;
|
||||||
|
}
|
||||||
|
.status-item__count { color: tokens.$status-idle; }
|
||||||
|
}
|
||||||
|
|
||||||
|
&--thinking {
|
||||||
|
.status-item__dot {
|
||||||
|
background-color: tokens.$status-thinking;
|
||||||
|
animation: pulse-thinking 3s tokens.$easing-standard infinite;
|
||||||
|
}
|
||||||
|
.status-item__count { color: tokens.$status-thinking; }
|
||||||
|
}
|
||||||
|
|
||||||
|
&--error {
|
||||||
|
.status-item__dot {
|
||||||
|
background-color: tokens.$status-error;
|
||||||
|
animation: pulse-error tokens.$duration-fast tokens.$easing-standard infinite;
|
||||||
|
}
|
||||||
|
.status-item__count { color: tokens.$status-error; }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// System health indicator
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
.health-indicator {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: tokens.$spacing-2;
|
||||||
|
padding: tokens.$spacing-3 tokens.$spacing-4;
|
||||||
|
border-radius: tokens.$radius-md;
|
||||||
|
border: 1px solid tokens.$color-surface-lighter;
|
||||||
|
|
||||||
|
&__dot {
|
||||||
|
width: tokens.$status-dot-size;
|
||||||
|
height: tokens.$status-dot-size;
|
||||||
|
border-radius: tokens.$radius-full;
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
&__label {
|
||||||
|
font-family: tokens.$font-family-body;
|
||||||
|
font-size: tokens.$font-size-body-medium;
|
||||||
|
font-weight: tokens.$font-weight-medium;
|
||||||
|
color: tokens.$color-on-surface-variant;
|
||||||
|
}
|
||||||
|
|
||||||
|
&__value {
|
||||||
|
margin-left: auto;
|
||||||
|
font-family: tokens.$font-family-mono;
|
||||||
|
font-size: tokens.$font-size-body-medium;
|
||||||
|
font-weight: tokens.$font-weight-bold;
|
||||||
|
letter-spacing: tokens.$letter-spacing-mono;
|
||||||
|
}
|
||||||
|
|
||||||
|
&--healthy {
|
||||||
|
.health-indicator__dot {
|
||||||
|
background-color: tokens.$status-active;
|
||||||
|
animation: pulse-active tokens.$duration-standard tokens.$easing-standard infinite;
|
||||||
|
}
|
||||||
|
.health-indicator__value { color: tokens.$status-active; }
|
||||||
|
}
|
||||||
|
|
||||||
|
&--degraded {
|
||||||
|
.health-indicator__dot {
|
||||||
|
background-color: tokens.$status-error;
|
||||||
|
animation: pulse-error tokens.$duration-fast tokens.$easing-standard infinite;
|
||||||
|
}
|
||||||
|
.health-indicator__value { color: tokens.$status-error; }
|
||||||
|
}
|
||||||
|
|
||||||
|
&--unknown {
|
||||||
|
.health-indicator__dot {
|
||||||
|
background-color: tokens.$status-offline;
|
||||||
|
}
|
||||||
|
.health-indicator__value { color: tokens.$status-offline; }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Pulse animations (from the design system)
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
@keyframes pulse-active {
|
||||||
|
0%, 100% { opacity: 1; transform: scale(1); }
|
||||||
|
50% { opacity: 0.6; transform: scale(0.85); }
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes pulse-thinking {
|
||||||
|
0%, 100% { opacity: 1; transform: scale(1); }
|
||||||
|
50% { opacity: 0.5; transform: scale(0.9); }
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes pulse-error {
|
||||||
|
0%, 100% { opacity: 1; transform: scale(1); }
|
||||||
|
50% { opacity: 0.7; transform: scale(0.8); }
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Responsive: stack on compact screens
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
@media (max-width: tokens.$breakpoint-compact) {
|
||||||
|
.summary-breakdown {
|
||||||
|
grid-template-columns: 1fr;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,91 @@
|
|||||||
|
import { ChangeDetectionStrategy, Component, computed, inject } from '@angular/core';
|
||||||
|
import { AgentStatusService } from '../../services/agent-status.service';
|
||||||
|
import { AgentStatus } from '../../models/agent.model';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Dashboard Summary Component.
|
||||||
|
* Displays total active agents, status breakdown (Active, Idle, Thinking, Error),
|
||||||
|
* and a system health indicator.
|
||||||
|
*
|
||||||
|
* Binds to AgentStatusService.agents signal — no hardcoded values.
|
||||||
|
* Uses design tokens from CUB-21 (styles/_tokens.scss, app/design/tokens.ts).
|
||||||
|
*/
|
||||||
|
@Component({
|
||||||
|
selector: 'app-dashboard-summary',
|
||||||
|
standalone: true,
|
||||||
|
imports: [],
|
||||||
|
templateUrl: './dashboard-summary.component.html',
|
||||||
|
styleUrl: './dashboard-summary.component.scss',
|
||||||
|
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||||
|
})
|
||||||
|
export class DashboardSummaryComponent {
|
||||||
|
private readonly agentStatusService = inject(AgentStatusService);
|
||||||
|
|
||||||
|
/** All agents from the reactive signal */
|
||||||
|
readonly agents = this.agentStatusService.agents;
|
||||||
|
|
||||||
|
/** Total number of agents */
|
||||||
|
readonly totalAgents = computed(() => this.agents().length);
|
||||||
|
|
||||||
|
/** Count of agents per status */
|
||||||
|
readonly statusCounts = computed(() => {
|
||||||
|
const agents = this.agents();
|
||||||
|
const counts: Record<AgentStatus, number> = {
|
||||||
|
active: 0,
|
||||||
|
idle: 0,
|
||||||
|
thinking: 0,
|
||||||
|
error: 0,
|
||||||
|
offline: 0,
|
||||||
|
};
|
||||||
|
for (const agent of agents) {
|
||||||
|
counts[agent.status]++;
|
||||||
|
}
|
||||||
|
return counts;
|
||||||
|
});
|
||||||
|
|
||||||
|
/** Status items for template iteration */
|
||||||
|
readonly statusItems = computed(() => {
|
||||||
|
const counts = this.statusCounts();
|
||||||
|
const total = this.totalAgents();
|
||||||
|
return [
|
||||||
|
{ status: 'active' as AgentStatus, count: counts.active, label: 'Active' },
|
||||||
|
{ status: 'idle' as AgentStatus, count: counts.idle, label: 'Idle' },
|
||||||
|
{ status: 'thinking' as AgentStatus, count: counts.thinking, label: 'Thinking' },
|
||||||
|
{ status: 'error' as AgentStatus, count: counts.error, label: 'Error' },
|
||||||
|
] as const;
|
||||||
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* System health indicator:
|
||||||
|
* - 'healthy' → no errors, at least one active agent
|
||||||
|
* - 'degraded' → has errors OR no active agents but some agents exist
|
||||||
|
* - 'unknown' → no agents registered
|
||||||
|
*/
|
||||||
|
readonly systemHealth = computed((): 'healthy' | 'degraded' | 'unknown' => {
|
||||||
|
const agents = this.agents();
|
||||||
|
if (agents.length === 0) return 'unknown';
|
||||||
|
const counts = this.statusCounts();
|
||||||
|
if (counts.error > 0) return 'degraded';
|
||||||
|
if (counts.active > 0) return 'healthy';
|
||||||
|
return 'degraded';
|
||||||
|
});
|
||||||
|
|
||||||
|
readonly healthLabel = computed(() => {
|
||||||
|
const health = this.systemHealth();
|
||||||
|
switch (health) {
|
||||||
|
case 'healthy': return 'Healthy';
|
||||||
|
case 'degraded': return 'Degraded';
|
||||||
|
case 'unknown': return 'Unknown';
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
/** Get the CSS class for a given status */
|
||||||
|
statusClass(status: AgentStatus): string {
|
||||||
|
return `status-item--${status}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Get the CSS class for system health */
|
||||||
|
healthClass(): string {
|
||||||
|
return `health-indicator--${this.systemHealth()}`;
|
||||||
|
}
|
||||||
|
}
|
||||||
1
frontend/src/app/components/dashboard-summary/index.ts
Normal file
1
frontend/src/app/components/dashboard-summary/index.ts
Normal file
@@ -0,0 +1 @@
|
|||||||
|
export { DashboardSummaryComponent } from './dashboard-summary.component';
|
||||||
@@ -2,4 +2,5 @@ export * from './quick-jump-button/quick-jump-button.component';
|
|||||||
export { AgentStatusBadgeComponent } from './agent-status-badge/agent-status-badge.component';
|
export { AgentStatusBadgeComponent } from './agent-status-badge/agent-status-badge.component';
|
||||||
export { QuickJumpDrawerComponent } from './quick-jump-drawer/index';
|
export { QuickJumpDrawerComponent } from './quick-jump-drawer/index';
|
||||||
export { AgentSessionDrawerComponent } from './agent-session-drawer/index';
|
export { AgentSessionDrawerComponent } from './agent-session-drawer/index';
|
||||||
export type { SessionLogLine, SessionMessage } from './agent-session-drawer/index';
|
export type { SessionLogLine, SessionMessage } from './agent-session-drawer/index';
|
||||||
|
export { DashboardSummaryComponent } from './dashboard-summary/index';
|
||||||
@@ -94,92 +94,6 @@ export const CcStatusColors = {
|
|||||||
offline: { fg: '#64748b', bg: 'rgba(100, 116, 139, 0.12)', border: 'rgba(100, 116, 139, 0.40)' },
|
offline: { fg: '#64748b', bg: 'rgba(100, 116, 139, 0.12)', border: 'rgba(100, 116, 139, 0.40)' },
|
||||||
} as const;
|
} 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
|
// Typography
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
@@ -349,6 +263,9 @@ export const CcTokens = {
|
|||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
// CSS Custom Property Names
|
// 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 = {
|
export const CcCssProps = {
|
||||||
// Color
|
// Color
|
||||||
colorPrimary: '--cc-color-primary',
|
colorPrimary: '--cc-color-primary',
|
||||||
|
|||||||
@@ -12,7 +12,6 @@
|
|||||||
gap: 16px;
|
gap: 16px;
|
||||||
min-height: 400px;
|
min-height: 400px;
|
||||||
overflow-x: hidden;
|
overflow-x: hidden;
|
||||||
padding: var(--cc-section-padding);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.hub-page__title {
|
.hub-page__title {
|
||||||
|
|||||||
@@ -434,41 +434,4 @@ $min-body-font: 16px;
|
|||||||
@mixin touch-target($min-size: $min-touch-target) {
|
@mixin touch-target($min-size: $min-touch-target) {
|
||||||
min-width: $min-size;
|
min-width: $min-size;
|
||||||
min-height: $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;
|
|
||||||
@@ -1,88 +0,0 @@
|
|||||||
// 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/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)
|
|
||||||
|
|
||||||
// ── 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(h)
|
|
||||||
|
|
||||||
// ── 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)
|
|
||||||
}
|
|
||||||
|
|
||||||
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
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,21 +0,0 @@
|
|||||||
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
|
|
||||||
)
|
|
||||||
|
|
||||||
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/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/sys v0.29.0 // indirect
|
|
||||||
golang.org/x/text v0.21.0 // indirect
|
|
||||||
)
|
|
||||||
@@ -1,34 +0,0 @@
|
|||||||
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/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/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/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/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
|
||||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
|
||||||
@@ -1,45 +0,0 @@
|
|||||||
// 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
|
|
||||||
}
|
|
||||||
@@ -1,158 +0,0 @@
|
|||||||
// 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)
|
|
||||||
}
|
|
||||||
@@ -1,369 +0,0 @@
|
|||||||
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)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,106 +0,0 @@
|
|||||||
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
|
|
||||||
}
|
|
||||||
@@ -1,28 +0,0 @@
|
|||||||
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),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
@@ -1,28 +0,0 @@
|
|||||||
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),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
@@ -1,28 +0,0 @@
|
|||||||
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),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
@@ -1,165 +0,0 @@
|
|||||||
// 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"`
|
|
||||||
}
|
|
||||||
@@ -1,65 +0,0 @@
|
|||||||
// 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/handler"
|
|
||||||
"github.com/go-chi/chi/v5"
|
|
||||||
"github.com/go-chi/chi/v5/middleware"
|
|
||||||
"github.com/go-chi/cors"
|
|
||||||
)
|
|
||||||
|
|
||||||
// New creates a fully-configured chi router with all API routes mounted.
|
|
||||||
func New(h *handler.Handler) *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 — permissive for development ──────────────────────────────────
|
|
||||||
r.Use(cors.Handler(cors.Options{
|
|
||||||
AllowedOrigins: []string{"*"},
|
|
||||||
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 ───────────────────────────────────────────────────────
|
|
||||||
r.Get("/health", func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
w.Header().Set("Content-Type", "application/json")
|
|
||||||
w.Write([]byte(`{"status":"ok"}`))
|
|
||||||
})
|
|
||||||
|
|
||||||
// ── API v1 routes ──────────────────────────────────────────────────────
|
|
||||||
r.Route("/api", func(api chi.Router) {
|
|
||||||
// Agents CRUD
|
|
||||||
api.Route("/agents", func(agents chi.Router) {
|
|
||||||
agents.Get("/", h.ListAgents) // GET /api/agents
|
|
||||||
agents.Post("/", h.CreateAgent) // POST /api/agents
|
|
||||||
agents.Get("/{id}", h.GetAgent) // GET /api/agents/{id}
|
|
||||||
agents.Put("/{id}", h.UpdateAgent) // PUT /api/agents/{id}
|
|
||||||
agents.Delete("/{id}", h.DeleteAgent) // DELETE /api/agents/{id}
|
|
||||||
agents.Get("/{id}/history", h.AgentHistory) // GET /api/agents/{id}/history
|
|
||||||
})
|
|
||||||
|
|
||||||
// Sessions
|
|
||||||
api.Get("/sessions", h.ListSessions)
|
|
||||||
|
|
||||||
// Tasks
|
|
||||||
api.Get("/tasks", h.ListTasks)
|
|
||||||
|
|
||||||
// Projects
|
|
||||||
api.Get("/projects", h.ListProjects)
|
|
||||||
})
|
|
||||||
|
|
||||||
return r
|
|
||||||
}
|
|
||||||
@@ -1,177 +0,0 @@
|
|||||||
// 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)
|
|
||||||
}
|
|
||||||
@@ -1,67 +0,0 @@
|
|||||||
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)
|
|
||||||
}
|
|
||||||
@@ -1,80 +0,0 @@
|
|||||||
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)
|
|
||||||
}
|
|
||||||
@@ -1,64 +0,0 @@
|
|||||||
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