Compare commits

3 Commits

Author SHA1 Message Date
amadzarak f046db7fc2 OPC # 0009: Gitea and OPC Build Webhooks
controlplane/build ✔ Build succeeded.
2026-04-26 16:54:54 -04:00
amadzarak 66ef611761 OPC # 0006: Build monitor grid, CI SolutionBuild rows, by-sha endpoint, dashboard SHA badge 2026-04-26 16:47:40 -04:00
amadzarak c7da1eb017 OPC # 0006: OPC Git Trunk-Based management 2026-04-26 16:31:57 -04:00
8 changed files with 620 additions and 335 deletions
+106 -30
View File
@@ -19,13 +19,19 @@ public static class GitEndpoints
// All responses include a repoKey field so the caller knows which repo each commit came from.
// GET /api/git/log?grep=...&limit=25&page=1&repo=all
// page is 1-based. Each repo contributes up to limit*page commits before merge-sort+skip/take.
// branch filters to commits reachable from the named local branch; requires a specific repo (not "all").
// Each result includes a branches[] array listing local branches that contain that commit.
private static IResult GetLog(
IConfiguration config,
string? grep = null,
int limit = 25,
int page = 1,
string repo = "all")
string? grep = null,
int limit = 25,
int page = 1,
string repo = "all",
string? branch = null)
{
if (!string.IsNullOrWhiteSpace(branch) && repo == "all")
return Results.BadRequest("'branch' filter requires a specific 'repo' parameter.");
var repos = repo == "all"
? ResolveAllRepos(config)
: ResolveNamedRepo(config, repo) is { } p
@@ -43,16 +49,30 @@ public static class GitEndpoints
using var r = new Repository(repoPath);
var tips = r.Branches
.Where(b => b.Tip != null)
.Select(b => (GitObject)b.Tip)
.ToList();
var filter = new CommitFilter
CommitFilter filter;
if (!string.IsNullOrWhiteSpace(branch))
{
SortBy = CommitSortStrategies.Topological | CommitSortStrategies.Time,
IncludeReachableFrom = tips.Count > 0 ? tips : (object)r.Head,
};
var branchRef = r.Branches[branch];
if (branchRef?.Tip is null)
return Results.BadRequest($"Branch '{branch}' not found in repo '{repoKey}'.");
filter = new CommitFilter
{
SortBy = CommitSortStrategies.Topological | CommitSortStrategies.Time,
IncludeReachableFrom = branchRef.Tip,
};
}
else
{
var tips = r.Branches
.Where(b => b.Tip != null)
.Select(b => (GitObject)b.Tip)
.ToList();
filter = new CommitFilter
{
SortBy = CommitSortStrategies.Topological | CommitSortStrategies.Time,
IncludeReachableFrom = tips.Count > 0 ? tips : (object)r.Head,
};
}
IEnumerable<Commit> query = r.Commits.QueryBy(filter);
@@ -63,22 +83,42 @@ public static class GitEndpoints
bucket.Add((c.Author.When, repoKey, ToGitCommit(r, c)));
}
var commits = bucket
var pageEntries = bucket
.OrderByDescending(x => x.When)
.Skip((page - 1) * limit)
.Take(limit)
.Select(x => new
{
repoKey = x.RepoKey,
hash = x.Commit.Hash,
shortHash = x.Commit.ShortHash,
author = x.Commit.Author,
date = x.Commit.Date,
subject = x.Commit.Subject,
files = x.Commit.Files,
})
.ToList();
// Annotate each commit with the local branches whose tip is a descendant of that commit.
var branchMap = new Dictionary<string, List<string>>(StringComparer.Ordinal);
foreach (var grp in pageEntries.GroupBy(x => x.RepoKey))
{
if (!repos.TryGetValue(grp.Key, out var rPath) || !Directory.Exists(rPath)) continue;
using var annotRepo = new Repository(rPath);
var localBranches = annotRepo.Branches.Where(b => !b.IsRemote && b.Tip != null).ToList();
foreach (var (_, _, c) in grp)
{
var target = annotRepo.Lookup<Commit>(c.Hash);
if (target is null) { branchMap[c.Hash] = []; continue; }
branchMap[c.Hash] = localBranches
.Where(b => annotRepo.ObjectDatabase.FindMergeBase(b.Tip, target)?.Sha == target.Sha)
.Select(b => b.FriendlyName)
.ToList();
}
}
var commits = pageEntries.Select(x => new
{
repoKey = x.RepoKey,
hash = x.Commit.Hash,
shortHash = x.Commit.ShortHash,
author = x.Commit.Author,
date = x.Commit.Date,
subject = x.Commit.Subject,
files = x.Commit.Files,
branches = branchMap.TryGetValue(x.Commit.Hash, out var br) ? (IReadOnlyList<string>)br : Array.Empty<string>(),
}).ToList();
return Results.Ok(commits);
}
@@ -127,18 +167,55 @@ public static class GitEndpoints
return Results.NotFound();
}
// GET /api/git/branches
private static IResult GetBranches(IConfiguration config)
// GET /api/git/branches?repo=all
// repo defaults to "default" (single configured repo). Pass "all" to get branches from all
// registered repos. Each result includes repoKey so the caller can group branches by repo.
private static IResult GetBranches(IConfiguration config, string repo = "default")
{
var repoPath = ResolveRepo(config);
if (repo == "all")
{
var allRepos = ResolveAllRepos(config);
if (allRepos.Count == 0)
return Results.Problem("Could not locate any git repositories.");
var allBranches = new List<object>();
foreach (var (repoKey, rPath) in allRepos)
{
if (!Directory.Exists(rPath)) continue;
using var gitRepo = new Repository(rPath);
allBranches.AddRange(gitRepo.Branches
.Where(b => !b.IsRemote && b.Tip != null)
.OrderBy(b => b.FriendlyName)
.Select(b => (object)new
{
repoKey,
name = b.FriendlyName,
hash = b.Tip.Sha,
shortHash = b.Tip.Sha[..7],
subject = b.Tip.MessageShort,
author = b.Tip.Author.Name,
date = b.Tip.Author.When.ToString("yyyy-MM-dd HH:mm:ss zzz"),
isHead = b.IsCurrentRepositoryHead,
}));
}
return Results.Ok(allBranches);
}
var repoPath = repo == "default"
? ResolveRepo(config)
: ResolveNamedRepo(config, repo) ?? ResolveRepo(config);
if (repoPath is null)
return Results.Problem("Could not locate a git repository.");
using var repo = new Repository(repoPath);
var branches = repo.Branches
var repoLabel = repo == "default" ? "default" : repo;
using var singleRepo = new Repository(repoPath);
var branches = singleRepo.Branches
.Where(b => !b.IsRemote && b.Tip != null)
.OrderBy(b => b.FriendlyName)
.Select(b => new
{
repoKey = repoLabel,
name = b.FriendlyName,
hash = b.Tip.Sha,
shortHash = b.Tip.Sha[..7],
@@ -147,7 +224,6 @@ public static class GitEndpoints
date = b.Tip.Author.When.ToString("yyyy-MM-dd HH:mm:ss zzz"),
isHead = b.IsCurrentRepositoryHead,
})
.OrderBy(b => b.name)
.ToList();
return Results.Ok(branches);
@@ -1,4 +1,5 @@
using ControlPlane.Api.Services;
using ControlPlane.Core.Models;
using ControlPlane.Core.Services;
using System.Text.Json;
@@ -16,6 +17,7 @@ public static class ProjectBuildEndpoints
var group = app.MapGroup("/api/builds").WithTags("Builds");
group.MapGet("/projects", GetProjects);
group.MapGet("/history", GetHistory);
group.MapGet("/by-sha", GetBySha);
group.MapPost("/{projectName}", TriggerProjectBuild);
return app;
}
@@ -27,6 +29,31 @@ public static class ProjectBuildEndpoints
private static async Task<IResult> GetHistory(BuildHistoryService history) =>
Results.Ok(await history.GetBuildsAsync());
/// <summary>
/// Returns the latest SolutionBuild record for the given commit SHA, or null if none exists.
/// Used by the OPC CommitsTab to render per-commit CI status dots.
/// </summary>
private static async Task<IResult> GetBySha(string sha, BuildHistoryService history)
{
if (string.IsNullOrWhiteSpace(sha))
return Results.BadRequest("sha is required");
var builds = await history.GetBuildsByShaAsync(sha);
var latest = builds
.Where(b => b.Kind == BuildKind.SolutionBuild)
.MaxBy(b => b.StartedAt);
return Results.Ok(latest is null ? null : new
{
latest.Id,
latest.Status,
latest.StartedAt,
latest.FinishedAt,
latest.DurationMs,
latest.CommitSha,
});
}
/// <summary>
/// Triggers a build for a named project and streams SSE output.
/// projectName must match one of the names returned by GET /api/builds/projects.
+23
View File
@@ -30,6 +30,29 @@ export async function getBuildHistory(): Promise<BuildRecord[]> {
return res.json();
}
export interface ShaBuildResult {
id: string;
status: 'Running' | 'Succeeded' | 'Failed';
startedAt: string;
finishedAt?: string;
durationMs?: number;
commitSha?: string;
}
/** Returns the latest SolutionBuild for a given SHA, or null if none exists. */
export async function getBuildBySha(sha: string): Promise<ShaBuildResult | null> {
const res = await fetch(`${BASE_URL}/api/builds/by-sha?sha=${encodeURIComponent(sha)}`);
if (!res.ok) throw new Error(`getBuildBySha failed: ${res.statusText}`);
return res.json();
}
/** Batch-fetches SolutionBuild status for multiple SHAs. Returns a map of sha -> result|null. */
export async function getBuildsByShas(shas: string[]): Promise<Map<string, ShaBuildResult | null>> {
const unique = [...new Set(shas.filter(Boolean))];
const entries = await Promise.all(unique.map(async (sha) => [sha, await getBuildBySha(sha)] as const));
return new Map(entries);
}
export function triggerProjectBuild(
projectName: string,
onLine: (line: string) => void,
+22 -4
View File
@@ -121,6 +121,7 @@ export interface LinkedCommit {
date: string;
subject: string;
files: string[];
branches: string[];
}
export async function getLinkedCommits(opcNumber: string): Promise<LinkedCommit[]> {
@@ -208,18 +209,35 @@ export async function getBranchCoverageForRepo(repoKey: string, hashes: string[]
// Reuses LinkedCommit shape — repoKey identifies which repo each commit came from.
export async function getChangesets(
page = 1,
limit = 25,
repo = 'all',
page = 1,
limit = 25,
repo = 'all',
grep?: string,
branch?: string,
): Promise<LinkedCommit[]> {
const params = new URLSearchParams({ page: String(page), limit: String(limit), repo });
if (grep) params.set('grep', grep);
if (grep) params.set('grep', grep);
if (branch) params.set('branch', branch);
const res = await fetch(`${BASE_URL}/api/git/log?${params}`);
if (!res.ok) throw new Error(`Failed to load changesets: ${res.statusText}`);
return res.json();
}
// ── Local git branches (from LibGit2 repos) ───────────────────────────────────
export interface RepoBranchInfo {
repoKey: string;
name: string;
hash: string;
isHead: boolean;
}
export async function getBranches(repo = 'all'): Promise<RepoBranchInfo[]> {
const res = await fetch(`${BASE_URL}/api/git/branches?repo=${encodeURIComponent(repo)}`);
if (!res.ok) throw new Error(`Failed to load branches: ${res.statusText}`);
return res.json();
}
// ── Commit detail (full diff) ─────────────────────────────────────────────────
export interface CommitFile {
+47
View File
@@ -1292,3 +1292,50 @@ body {
min-width: 60px;
text-align: center;
}
.cs-page-with-tree {
display: flex;
gap: 1.5rem;
align-items: flex-start;
}
.cs-branch-tree {
width: 200px;
flex-shrink: 0;
position: sticky;
top: 1rem;
border: 1px solid #dce0e6;
border-radius: 8px;
overflow: hidden;
padding: 0.25rem 0;
max-height: calc(100vh - 8rem);
overflow-y: auto;
}
.cs-branch-tree .bp6-tree-node-content {
font-size: 0.82rem;
height: 28px;
}
.cs-branch-tree .bp6-tree-node-content:hover {
background: #f6f7f9;
}
.cs-branch-tree .bp6-tree-node.bp6-tree-node-selected > .bp6-tree-node-content {
background: #e8f0fb;
color: #215db0;
}
.cs-content-area {
flex: 1;
min-width: 0;
}
.cs-branch-badge {
font-size: 0.67rem;
letter-spacing: 0.01em;
white-space: nowrap;
margin-left: 0.5rem;
opacity: 0.85;
vertical-align: middle;
}
@@ -1,13 +1,18 @@
import { useEffect, useRef, useState } from 'react';
import { useEffect, useRef, useState } from 'react';
import {
Button, Callout, Intent, Tag, Spinner, NonIdealState,
Collapse, HTMLTable,
AnchorButton, Button, Callout, Collapse, HTMLTable, Intent, NonIdealState, Spinner, Tag,
} from '@blueprintjs/core';
import { getProjects, getBuildHistory, type ProjectDefinition, type BuildRecord } from '../api/buildApi';
import { getGitLog, type GitCommit } from '../api/gitApi';
const BASE_URL = import.meta.env.VITE_API_URL ?? '';
const KIND_LABEL: Record<string, string> = {
DotnetProject: '.NET',
NpmProject: 'npm',
DockerImage: 'Docker',
SolutionBuild: 'CI',
};
const KIND_INTENT: Record<string, Intent> = {
DotnetProject: Intent.PRIMARY,
NpmProject: Intent.WARNING,
@@ -21,90 +26,31 @@ const STATUS_INTENT: Record<string, Intent> = {
Running: Intent.PRIMARY,
};
// ── Git history panel ─────────────────────────────────────────────────────────
function GitHistoryPanel({ relativePath }: { relativePath: string }) {
const [commits, setCommits] = useState<GitCommit[]>([]);
const [loading, setLoading] = useState(false);
const [open, setOpen] = useState(false);
const [fetched, setFetched] = useState(false);
const [error, setError] = useState<string | null>(null);
const toggle = async () => {
if (!open && !fetched) {
setLoading(true);
setError(null);
try {
const data = await getGitLog(relativePath, 10);
setCommits(data);
setFetched(true);
} catch (e) {
setError(e instanceof Error ? e.message : 'Failed to load git history');
} finally {
setLoading(false);
}
}
setOpen((o) => !o);
};
// ── Inline log viewer ─────────────────────────────────────────────────────────
function LogRow({ lines }: { lines: string[] }) {
const ref = useRef<HTMLDivElement>(null);
useEffect(() => { if (ref.current) ref.current.scrollTop = ref.current.scrollHeight; }, [lines]);
return (
<div style={{ marginTop: '0.5rem' }}>
<Button
minimal small
icon="git-branch"
text={open ? 'Hide history' : 'Git history'}
onClick={toggle}
loading={loading}
/>
<Collapse isOpen={open && !loading}>
{error && <Callout intent={Intent.DANGER} compact style={{ marginTop: '0.25rem' }}>{error}</Callout>}
{commits.length === 0 && !error && (
<p style={{ fontSize: '0.75rem', color: '#8f99a8', marginTop: '0.5rem' }}>No commits found for this path.</p>
)}
{commits.length > 0 && (
<HTMLTable className="bp6-html-table-condensed bp6-html-table-striped" style={{ width: '100%', marginTop: '0.5rem', fontSize: '0.72rem' }}>
<thead>
<tr>
<th style={{ width: 60 }}>Commit</th>
<th>Message</th>
<th>Author</th>
<th style={{ width: 140 }}>Date</th>
<th style={{ width: 40, textAlign: 'right' }}>Files</th>
</tr>
</thead>
<tbody>
{commits.map((c) => (
<tr key={c.hash}>
<td>
<code style={{ fontSize: '0.7rem', color: '#4a90d9' }}>{c.shortHash}</code>
</td>
<td style={{ maxWidth: 320, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
{c.subject}
</td>
<td style={{ color: '#738091' }}>{c.author}</td>
<td style={{ color: '#738091' }}>
{new Date(c.date).toLocaleString(undefined, { dateStyle: 'short', timeStyle: 'short' })}
</td>
<td style={{ textAlign: 'right', color: '#8f99a8' }}>
<span title={c.files.join('\n')}>{c.files.length}</span>
</td>
</tr>
))}
</tbody>
</HTMLTable>
)}
</Collapse>
</div>
<tr>
<td colSpan={7} style={{ padding: 0 }}>
<div ref={ref} style={{
fontFamily: 'monospace', fontSize: '0.7rem',
background: '#111', color: '#d4d4d4',
padding: '0.5rem 0.75rem', maxHeight: 200, overflowY: 'auto',
whiteSpace: 'pre-wrap', wordBreak: 'break-all',
}}>
{lines.map((l, i) => <div key={i}>{l}</div>)}
</div>
</td>
</tr>
);
}
// ── Per-project card ──────────────────────────────────────────────────────────
// ── Manual project row ────────────────────────────────────────────────────────
function ProjectCard({
project,
lastBuild,
onBuilt,
function ProjectRow({
project, lastBuild, onBuilt,
}: {
project: ProjectDefinition;
lastBuild: BuildRecord | undefined;
@@ -114,29 +60,18 @@ function ProjectCard({
const [logs, setLogs] = useState<string[]>([]);
const [open, setOpen] = useState(false);
const [error, setError] = useState<string | null>(null);
const logRef = useRef<HTMLDivElement>(null);
useEffect(() => {
if (logRef.current) logRef.current.scrollTop = logRef.current.scrollHeight;
}, [logs]);
const handleBuild = async () => {
setBuilding(true);
setOpen(true);
setLogs([]);
setError(null);
try {
const res = await fetch(
`${BASE_URL}/api/builds/${encodeURIComponent(project.name)}`,
{ method: 'POST' }
);
const res = await fetch(`${BASE_URL}/api/builds/${encodeURIComponent(project.name)}`, { method: 'POST' });
if (!res.ok || !res.body) throw new Error(res.statusText);
const reader = res.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
while (true) {
const { done, value } = await reader.read();
if (done) break;
@@ -149,8 +84,7 @@ function ProjectCard({
try {
const msg = JSON.parse(dataLine);
if (msg.done) onBuilt();
else if (typeof msg.line === 'string')
setLogs((p) => [...p.slice(-1000), msg.line]);
else if (typeof msg.line === 'string') setLogs((p) => [...p.slice(-1000), msg.line]);
} catch { /* ignore */ }
}
}
@@ -162,70 +96,86 @@ function ProjectCard({
};
const statusIntent = lastBuild ? STATUS_INTENT[lastBuild.status] : Intent.NONE;
const statusLabel = lastBuild?.status ?? 'Never built';
const lastRun = lastBuild ? new Date(lastBuild.startedAt).toLocaleString() : '';
const duration = lastBuild?.durationMs != null
? `${(lastBuild.durationMs / 1000).toFixed(1)}s` : null;
const duration = lastBuild?.durationMs != null ? `${(lastBuild.durationMs / 1000).toFixed(1)}s` : '—';
const lastRun = lastBuild ? new Date(lastBuild.startedAt).toLocaleString() : '—';
return (
<div className="job-card">
<div className="job-card-header">
<div>
<strong>{project.name}</strong>
<span className="job-card-subdomain" style={{ fontFamily: 'monospace', fontSize: '0.72rem' }}>
{project.relativePath}
</span>
</div>
<div style={{ display: 'flex', gap: '0.4rem', alignItems: 'center' }}>
<Tag intent={KIND_INTENT[project.kind] ?? Intent.NONE} minimal round>{project.kind}</Tag>
<Tag intent={statusIntent} round>{statusLabel}</Tag>
{duration && <Tag minimal round>{duration}</Tag>}
</div>
</div>
<div style={{ display: 'flex', gap: '0.5rem', alignItems: 'center', padding: '0.5rem 0 0.25rem' }}>
<Button
icon="play"
small
intent={Intent.PRIMARY}
loading={building}
onClick={handleBuild}
text="Build"
/>
<span style={{ fontSize: '0.75rem', color: '#999' }}>Last run: {lastRun}</span>
{logs.length > 0 && (
<Button minimal small
icon={open ? 'chevron-up' : 'chevron-down'}
onClick={() => setOpen((o) => !o)}
text={open ? 'Hide log' : 'Show log'}
/>
)}
</div>
{error && <Callout intent={Intent.DANGER} compact style={{ marginTop: '0.25rem' }}>{error}</Callout>}
{open && logs.length > 0 && (
<div
ref={logRef}
style={{
fontFamily: 'monospace', fontSize: '0.7rem',
background: '#111', color: '#d4d4d4',
padding: '0.5rem 0.75rem', borderRadius: 4,
height: 200, overflowY: 'auto',
whiteSpace: 'pre-wrap', wordBreak: 'break-all',
marginTop: '0.5rem',
}}
>
{logs.map((l, i) => <div key={i}>{l}</div>)}
</div>
<>
<tr>
<td>
<span style={{ fontWeight: 600 }}>{project.name}</span>
<br />
<code style={{ fontSize: '0.68rem', color: '#8f99a8' }}>{project.relativePath}</code>
</td>
<td><Tag intent={KIND_INTENT[project.kind] ?? Intent.NONE} minimal round>{KIND_LABEL[project.kind] ?? project.kind}</Tag></td>
<td><Tag minimal round style={{ color: '#8f99a8' }}>manual</Tag></td>
<td><Tag intent={statusIntent} minimal round>{lastBuild?.status ?? 'Never'}</Tag></td>
<td style={{ color: '#8f99a8', fontSize: '0.8rem' }}>{lastRun}</td>
<td style={{ color: '#8f99a8', fontSize: '0.8rem', textAlign: 'right' }}>{duration}</td>
<td style={{ textAlign: 'right' }}>
<Button icon="play" small intent={Intent.PRIMARY} loading={building} onClick={handleBuild} text="Build" />
{logs.length > 0 && (
<Button minimal small icon={open ? 'chevron-up' : 'chevron-down'} onClick={() => setOpen((o) => !o)} style={{ marginLeft: 4 }} />
)}
</td>
</tr>
{error && (
<tr><td colSpan={7}><Callout intent={Intent.DANGER} compact>{error}</Callout></td></tr>
)}
<GitHistoryPanel relativePath={project.relativePath} />
</div>
<Collapse isOpen={open && logs.length > 0} keepChildrenMounted>
<LogRow lines={logs} />
</Collapse>
</>
);
}
// ── Page ──────────────────────────────────────────────────────────────────────
// ── CI (SolutionBuild) row ───────────────────────────────────────────────────
function CiRow({ build, giteaBase }: { build: BuildRecord; giteaBase: string }) {
const [open, setOpen] = useState(false);
const repo = build.target.replace(/\.slnx?$/, ''); // "ControlPlane.slnx" → "ControlPlane"
const shortSha = build.commitSha?.slice(0, 7);
const shaUrl = build.commitSha
? `${giteaBase}/ClarityStack/${repo === 'ControlPlane' ? 'OPC' : repo}/commit/${build.commitSha}`
: null;
const duration = build.durationMs != null ? `${(build.durationMs / 1000).toFixed(1)}s` : '—';
const lastRun = new Date(build.startedAt).toLocaleString();
return (
<>
<tr>
<td>
<span style={{ fontWeight: 600 }}>{repo}</span>
<br />
<code style={{ fontSize: '0.68rem', color: '#8f99a8' }}>{build.target}</code>
</td>
<td><Tag intent={Intent.SUCCESS} minimal round>CI</Tag></td>
<td>
{shortSha && shaUrl ? (
<AnchorButton href={shaUrl} target="_blank" rel="noopener noreferrer" minimal small
style={{ fontFamily: 'monospace', fontSize: '0.72rem', padding: '0 4px' }}>
{shortSha}
</AnchorButton>
) : <span style={{ color: '#8f99a8', fontSize: '0.8rem' }}>â</span>}
</td>
<td><Tag intent={STATUS_INTENT[build.status] ?? Intent.NONE} minimal round>{build.status}</Tag></td>
<td style={{ color: '#8f99a8', fontSize: '0.8rem' }}>{lastRun}</td>
<td style={{ color: '#8f99a8', fontSize: '0.8rem', textAlign: 'right' }}>{duration}</td>
<td style={{ textAlign: 'right' }}>
{build.log.length > 0 && (
<Button minimal small icon={open ? 'chevron-up' : 'chevron-down'} onClick={() => setOpen((o) => !o)} text={open ? 'Hide' : 'Log'} />
)}
</td>
</tr>
<Collapse isOpen={open} keepChildrenMounted>
<LogRow lines={build.log} />
</Collapse>
</>
);
}
// ── Page ──────────────────────────────────────────────────────────────────────
export default function BuildMonitorPage() {
const [projects, setProjects] = useState<ProjectDefinition[]>([]);
@@ -233,6 +183,8 @@ export default function BuildMonitorPage() {
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const giteaBase = (import.meta.env.VITE_GITEA_URL as string | undefined) ?? 'https://opc.clarity.test';
const load = async () => {
setLoading(true);
setError(null);
@@ -247,9 +199,20 @@ export default function BuildMonitorPage() {
}
};
useEffect(() => { (async () => { await load(); })(); }, []);
useEffect(() => { load(); }, []);
// Find latest build per project — match exactly by relativePath (= build target)
// Latest SolutionBuild per solution target (one CI row per repo)
const ciBuilds = Object.values(
history
.filter((b) => b.kind === 'SolutionBuild')
.reduce<Record<string, BuildRecord>>((acc, b) => {
if (!acc[b.target] || new Date(b.startedAt) > new Date(acc[b.target].startedAt))
acc[b.target] = b;
return acc;
}, {})
);
// Latest manual build per project path
const lastBuildFor = (project: ProjectDefinition): BuildRecord | undefined =>
history.find((b) => b.target === project.relativePath);
@@ -258,44 +221,42 @@ export default function BuildMonitorPage() {
<div className="page-header">
<div>
<h1>Build Monitor</h1>
<p>Trigger and track builds for every project in the solution.</p>
</div>
<div style={{ display: 'flex', gap: '0.5rem', alignItems: 'center' }}>
<Button icon="refresh" minimal onClick={load} loading={loading} title="Refresh" />
<Button
icon="play"
text="Build All"
intent={Intent.WARNING}
disabled={loading || projects.length === 0}
onClick={async () => {
for (const p of projects) {
await fetch(`${BASE_URL}/api/builds/${encodeURIComponent(p.name)}`, { method: 'POST' });
}
load();
}}
/>
<p>CI gate builds (webhook-triggered) and manual per-project builds.</p>
</div>
<Button icon="refresh" minimal onClick={load} loading={loading} title="Refresh" />
</div>
{error && (
<Callout intent={Intent.DANGER} title="Failed to load projects" style={{ marginBottom: '1rem' }}>
{error}
</Callout>
<Callout intent={Intent.DANGER} title="Failed to load" style={{ marginBottom: '1rem' }}>{error}</Callout>
)}
{loading && <NonIdealState icon={<Spinner />} title="Loading projects..." />}
{loading && <NonIdealState icon={<Spinner />} title="Loading..." />}
{!loading && !error && (
<div className="job-list">
{projects.map((p) => (
<ProjectCard
key={p.name}
project={p}
lastBuild={lastBuildFor(p)}
onBuilt={load}
/>
))}
</div>
<HTMLTable className="bp6-html-table-condensed bp6-html-table-striped" style={{ width: '100%' }}>
<thead>
<tr>
<th>Name</th>
<th>Kind</th>
<th>Commit / Trigger</th>
<th>Status</th>
<th>Last Run</th>
<th style={{ textAlign: 'right' }}>Duration</th>
<th style={{ textAlign: 'right' }}>Actions</th>
</tr>
</thead>
<tbody>
{ciBuilds.map((b) => (
<CiRow key={`ci-${b.target}`} build={b} giteaBase={giteaBase} />
))}
{projects.map((p) => (
<ProjectRow key={p.name} project={p} lastBuild={lastBuildFor(p)} onBuilt={load} />
))}
{ciBuilds.length === 0 && projects.length === 0 && (
<tr><td colSpan={7} style={{ textAlign: 'center', color: '#8f99a8', padding: '2rem' }}>No builds yet.</td></tr>
)}
</tbody>
</HTMLTable>
)}
</>
);
+239 -115
View File
@@ -1,7 +1,8 @@
import { useState, useEffect, useCallback } from 'react';
import { Button, HTMLSelect, InputGroup, Intent, NonIdealState, Spinner, Tag, Tooltip } from '@blueprintjs/core';
import { useState, useEffect, useCallback, useMemo } from 'react';
import { Button, HTMLSelect, InputGroup, Intent, NonIdealState, Spinner, Tag, Tooltip, Tree } from '@blueprintjs/core';
import type { TreeNodeInfo } from '@blueprintjs/core';
import { GitCommitDrawer } from '../components/GitCommitDrawer';
import { getChangesets } from '../api/opcApi';
import { getChangesets, getBranches } from '../api/opcApi';
import type { LinkedCommit } from '../api/opcApi';
const PAGE_SIZE = 25;
@@ -19,23 +20,62 @@ const REPO_INTENT: Record<string, Intent> = {
Gateway: Intent.SUCCESS,
};
export default function ChangesetsPage() {
const [commits, setCommits] = useState<LinkedCommit[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [page, setPage] = useState(1);
const [hasMore, setHasMore] = useState(false);
const [repoFilter, setRepoFilter] = useState('all');
const [grepFilter, setGrepFilter] = useState('');
const [grepInput, setGrepInput] = useState('');
const [viewingHash, setViewingHash] = useState<string | null>(null);
const REPO_COLOR: Record<string, string> = {
Clarity: '#215db0',
OPC: '#935610',
Gateway: '#1c6e42',
};
const load = useCallback(async (p: number, repo: string, grep: string) => {
const SDLC_ORDER = ['develop', 'staging', 'uat', 'main'] as const;
function getBranchLabel(branches: string[]): string | null {
if (branches.length === 0) return null;
const sdlc = branches.filter(b => (SDLC_ORDER as readonly string[]).includes(b));
if (sdlc.length === 0) return branches[0];
const highest = sdlc.reduce((a, b) =>
SDLC_ORDER.indexOf(b as typeof SDLC_ORDER[number]) > SDLC_ORDER.indexOf(a as typeof SDLC_ORDER[number]) ? b : a,
);
const idx = SDLC_ORDER.indexOf(highest as typeof SDLC_ORDER[number]);
if (idx > 0) {
const prev = SDLC_ORDER[idx - 1];
if (branches.includes(prev)) return `${prev}${highest}`;
}
return highest;
}
export default function ChangesetsPage() {
const [commits, setCommits] = useState<LinkedCommit[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [page, setPage] = useState(1);
const [hasMore, setHasMore] = useState(false);
const [repoFilter, setRepoFilter] = useState('all');
const [grepFilter, setGrepFilter] = useState('');
const [grepInput, setGrepInput] = useState('');
const [viewingHash, setViewingHash] = useState<string | null>(null);
const [branchMap, setBranchMap] = useState<Record<string, string[]>>({});
const [selectedBranch, setSelectedBranch] = useState<{ repoKey: string; branch: string } | null>(null);
const [expandedRepos, setExpandedRepos] = useState<Set<string>>(new Set());
// Load branches for the tree once on mount
useEffect(() => {
getBranches('all')
.then(data => {
const map: Record<string, string[]> = {};
for (const b of data) {
if (!map[b.repoKey]) map[b.repoKey] = [];
map[b.repoKey].push(b.name);
}
setBranchMap(map);
})
.catch(() => { /* branch tree is non-critical */ });
}, []);
const load = useCallback(async (p: number, repo: string, grep: string, branch?: string) => {
setLoading(true);
setError(null);
try {
// Fetch one extra to detect whether there's a next page
const rows = await getChangesets(p, PAGE_SIZE + 1, repo, grep || undefined);
const rows = await getChangesets(p, PAGE_SIZE + 1, repo, grep || undefined, branch);
setHasMore(rows.length > PAGE_SIZE);
setCommits(rows.slice(0, PAGE_SIZE));
} catch (e) {
@@ -47,25 +87,77 @@ export default function ChangesetsPage() {
}, []);
useEffect(() => {
load(page, repoFilter, grepFilter);
}, [load, page, repoFilter, grepFilter]);
const effectiveRepo = selectedBranch ? selectedBranch.repoKey : repoFilter;
const effectiveBranch = selectedBranch?.branch;
load(page, effectiveRepo, grepFilter, effectiveBranch);
}, [load, page, repoFilter, grepFilter, selectedBranch]);
const applySearch = () => {
setPage(1);
setGrepFilter(grepInput);
};
const clearSearch = () => {
setGrepInput('');
setGrepFilter('');
setPage(1);
};
const applySearch = () => { setPage(1); setGrepFilter(grepInput); };
const clearSearch = () => { setGrepInput(''); setGrepFilter(''); setPage(1); };
const handleRepoChange = (repo: string) => {
setPage(1);
setSelectedBranch(null);
setRepoFilter(repo);
};
const treeNodes = useMemo((): TreeNodeInfo[] => [
{
id: 'all',
label: 'All Branches',
icon: 'git-branch',
isSelected: selectedBranch === null,
},
...Object.keys(branchMap).map(repoKey => ({
id: `repo|${repoKey}`,
label: <span style={{ color: REPO_COLOR[repoKey] ?? 'inherit', fontWeight: 500 }}>{repoKey}</span>,
icon: (expandedRepos.has(repoKey) ? 'folder-open' : 'folder-close') as TreeNodeInfo['icon'],
isExpanded: expandedRepos.has(repoKey),
isSelected: false,
childNodes: branchMap[repoKey].map(name => ({
id: `branch|${repoKey}|${name}`,
label: name,
icon: 'git-commit' as TreeNodeInfo['icon'],
isSelected: selectedBranch?.repoKey === repoKey && selectedBranch?.branch === name,
})),
})),
], [branchMap, expandedRepos, selectedBranch]);
const handleNodeClick = (node: TreeNodeInfo) => {
const id = String(node.id);
if (id === 'all') {
setPage(1);
setSelectedBranch(null);
} else if (id.startsWith('branch|')) {
const [, repoKey, ...rest] = id.split('|');
setPage(1);
setSelectedBranch({ repoKey, branch: rest.join('|') });
} else if (id.startsWith('repo|')) {
const repoKey = id.slice(5);
setExpandedRepos(s => {
const next = new Set(s);
next.has(repoKey) ? next.delete(repoKey) : next.add(repoKey);
return next;
});
}
};
const handleNodeExpand = (node: TreeNodeInfo) => {
const id = String(node.id);
if (id.startsWith('repo|')) setExpandedRepos(s => new Set([...s, id.slice(5)]));
};
const handleNodeCollapse = (node: TreeNodeInfo) => {
const id = String(node.id);
if (id.startsWith('repo|')) setExpandedRepos(s => { const n = new Set(s); n.delete(id.slice(5)); return n; });
};
const doRefresh = () => {
const effectiveRepo = selectedBranch ? selectedBranch.repoKey : repoFilter;
const effectiveBranch = selectedBranch?.branch;
load(page, effectiveRepo, grepFilter, effectiveBranch);
};
return (
<div>
<div className="page-header">
@@ -73,100 +165,132 @@ export default function ChangesetsPage() {
<h1>Changesets</h1>
<p>Chronological commit timeline across all three repos.</p>
</div>
<Button icon="refresh" minimal onClick={() => load(page, repoFilter, grepFilter)} />
<Button icon="refresh" minimal onClick={doRefresh} />
</div>
{/* Filter bar */}
<div className="opc-filter-bar">
<HTMLSelect
value={repoFilter}
onChange={e => handleRepoChange(e.target.value)}
options={REPO_OPTIONS}
/>
<InputGroup
leftIcon="search"
placeholder="Filter commits by text or OPC number…"
value={grepInput}
onChange={e => setGrepInput(e.target.value)}
onKeyDown={e => { if (e.key === 'Enter') applySearch(); }}
style={{ width: 320 }}
rightElement={
<Button minimal icon="arrow-right" intent={Intent.PRIMARY}
disabled={!grepInput.trim()} onClick={applySearch} />
}
/>
{grepFilter && (
<Button minimal small icon="cross" text="Clear" onClick={clearSearch} />
)}
<span className="opc-count-badge">{loading ? '…' : `${commits.length} shown`}</span>
</div>
<div className="cs-page-with-tree">
{/* Branch tree */}
<div className="cs-branch-tree">
<Tree
contents={treeNodes}
onNodeClick={handleNodeClick}
onNodeExpand={handleNodeExpand}
onNodeCollapse={handleNodeCollapse}
/>
</div>
{/* Content */}
{loading ? (
<NonIdealState icon={<Spinner />} title="Loading changesets…" />
) : error ? (
<NonIdealState icon="warning-sign" title="Could not load commits"
description={error} intent={Intent.DANGER} />
) : commits.length === 0 ? (
<NonIdealState icon="git-commit" title="No commits found"
description="Try changing the repo filter or clearing the search." />
) : (
<div className="cs-timeline">
{commits.map(c => (
<div
key={`${c.repoKey}-${c.hash}`}
className="cs-row"
onClick={() => setViewingHash(c.hash)}
>
<div className="cs-row-left">
<Tag
intent={REPO_INTENT[c.repoKey] ?? Intent.NONE}
minimal round
className="cs-repo-badge"
>
{c.repoKey || '?'}
</Tag>
</div>
{/* Main content */}
<div className="cs-content-area">
{/* Filter bar */}
<div className="opc-filter-bar">
<HTMLSelect
value={repoFilter}
onChange={e => handleRepoChange(e.target.value)}
options={REPO_OPTIONS}
disabled={!!selectedBranch}
/>
<InputGroup
leftIcon="search"
placeholder="Filter commits by text or OPC number…"
value={grepInput}
onChange={e => setGrepInput(e.target.value)}
onKeyDown={e => { if (e.key === 'Enter') applySearch(); }}
style={{ width: 320 }}
rightElement={
<Button minimal icon="arrow-right" intent={Intent.PRIMARY}
disabled={!grepInput.trim()} onClick={applySearch} />
}
/>
{grepFilter && (
<Button minimal small icon="cross" text="Clear" onClick={clearSearch} />
)}
{selectedBranch && (
<Tag
minimal
intent={REPO_INTENT[selectedBranch.repoKey] ?? Intent.NONE}
icon="git-branch"
onRemove={() => { setPage(1); setSelectedBranch(null); }}
>
{selectedBranch.repoKey} / {selectedBranch.branch}
</Tag>
)}
<span className="opc-count-badge">{loading ? '…' : `${commits.length} shown`}</span>
</div>
<div className="cs-row-body">
<div className="cs-row-top">
<Tooltip content="View diff" placement="top">
<code className="opc-commit-hash">{c.shortHash}</code>
</Tooltip>
<span className="cs-subject">{c.subject}</span>
</div>
<div className="cs-row-meta">
{c.author} · {c.date}
{c.files.length > 0 && (
<span className="cs-file-count"> · {c.files.length} file{c.files.length !== 1 ? 's' : ''}</span>
)}
</div>
</div>
{/* Content */}
{loading ? (
<NonIdealState icon={<Spinner />} title="Loading changesets…" />
) : error ? (
<NonIdealState icon="warning-sign" title="Could not load commits"
description={error} />
) : commits.length === 0 ? (
<NonIdealState icon="git-commit" title="No commits found"
description="Try changing the repo filter or clearing the search." />
) : (
<div className="cs-timeline">
{commits.map(c => {
const branchLabel = getBranchLabel(c.branches ?? []);
return (
<div
key={`${c.repoKey}-${c.hash}`}
className="cs-row"
onClick={() => setViewingHash(c.hash)}
>
<div className="cs-row-left">
<Tag
intent={REPO_INTENT[c.repoKey] ?? Intent.NONE}
minimal round
className="cs-repo-badge"
>
{c.repoKey || '?'}
</Tag>
</div>
<div className="cs-row-body">
<div className="cs-row-top">
<Tooltip content="View diff" placement="top">
<code className="opc-commit-hash">{c.shortHash}</code>
</Tooltip>
<span className="cs-subject">{c.subject}</span>
</div>
<div className="cs-row-meta">
{c.author} · {c.date}
{c.files.length > 0 && (
<span className="cs-file-count"> · {c.files.length} file{c.files.length !== 1 ? 's' : ''}</span>
)}
{branchLabel && (
<Tag minimal className="cs-branch-badge">{branchLabel}</Tag>
)}
</div>
</div>
</div>
);
})}
</div>
))}
</div>
)}
)}
{/* Pagination */}
{!loading && !error && (commits.length > 0 || page > 1) && (
<div className="cs-pagination">
<Button
icon="arrow-left"
minimal
text="Previous"
disabled={page <= 1}
onClick={() => setPage(p => p - 1)}
/>
<span className="cs-page-label">Page {page}</span>
<Button
rightIcon="arrow-right"
minimal
text="Next"
disabled={!hasMore}
onClick={() => setPage(p => p + 1)}
/>
{/* Pagination */}
{!loading && !error && (commits.length > 0 || page > 1) && (
<div className="cs-pagination">
<Button
icon="arrow-left"
minimal
text="Previous"
disabled={page <= 1}
onClick={() => setPage(p => p - 1)}
/>
<span className="cs-page-label">Page {page}</span>
<Button
rightIcon="arrow-right"
minimal
text="Next"
disabled={!hasMore}
onClick={() => setPage(p => p + 1)}
/>
</div>
)}
</div>
)}
</div>
<GitCommitDrawer hash={viewingHash} onClose={() => setViewingHash(null)} />
</div>
@@ -43,6 +43,15 @@ function TenantCard({ t }: { t: TenantRecord }) {
<div style={{ display: 'flex', gap: '0.4rem', alignItems: 'center' }}>
<Tag intent={ENV_INTENT[t.environment] ?? Intent.NONE} round minimal>{t.environment}</Tag>
<Tag intent={t.status === 'Provisioned' ? Intent.SUCCESS : Intent.WARNING} round>{t.status}</Tag>
{t.containerImage && (() => {
const sha = t.containerImage.includes(':') ? t.containerImage.split(':').pop()! : t.containerImage;
return (
<Tag minimal round style={{ fontFamily: 'monospace', fontSize: '0.7rem', color: '#8f99a8' }}
title={t.containerImage}>
{sha.slice(0, 7)}
</Tag>
);
})()}
</div>
</div>