Merge branch 'main' into feat/39-structured-logging

This commit is contained in:
nyk 2026-03-04 22:27:52 +07:00 committed by GitHub
commit e67350095b
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
16 changed files with 558 additions and 71 deletions

View File

@ -54,6 +54,9 @@ OPENCLAW_GATEWAY_HOST=127.0.0.1
OPENCLAW_GATEWAY_PORT=18789
# Optional: token used by server-side gateway calls
OPENCLAW_GATEWAY_TOKEN=
# Tools profile used when Mission Control spawns sessions via sessions_spawn.
# OpenClaw 2026.3.2+ defaults to "messaging" if omitted.
OPENCLAW_TOOLS_PROFILE=coding
# Frontend env vars (NEXT_PUBLIC_ prefix = available in browser)
NEXT_PUBLIC_GATEWAY_HOST=
@ -61,6 +64,8 @@ NEXT_PUBLIC_GATEWAY_PORT=18789
NEXT_PUBLIC_GATEWAY_PROTOCOL=
NEXT_PUBLIC_GATEWAY_URL=
# NEXT_PUBLIC_GATEWAY_TOKEN= # Optional, set if gateway requires auth token
# Gateway client id used in websocket handshake (role=operator UI client).
NEXT_PUBLIC_GATEWAY_CLIENT_ID=control-ui
# === Data Paths (all optional, defaults to .data/ in project root) ===
# MISSION_CONTROL_DATA_DIR=.data

View File

@ -346,7 +346,9 @@ See [`.env.example`](.env.example) for the complete list. Key variables:
| `OPENCLAW_GATEWAY_HOST` | No | Gateway host (default: `127.0.0.1`) |
| `OPENCLAW_GATEWAY_PORT` | No | Gateway WebSocket port (default: `18789`) |
| `OPENCLAW_GATEWAY_TOKEN` | No | Server-side gateway auth token |
| `OPENCLAW_TOOLS_PROFILE` | No | Tools profile for `sessions_spawn` (recommended: `coding`) |
| `NEXT_PUBLIC_GATEWAY_TOKEN` | No | Browser-side gateway auth token (must use `NEXT_PUBLIC_` prefix) |
| `NEXT_PUBLIC_GATEWAY_CLIENT_ID` | No | Gateway UI client ID for websocket handshake (default: `control-ui`) |
| `OPENCLAW_MEMORY_DIR` | No | Memory browser root (see note below) |
| `MC_CLAUDE_HOME` | No | Path to `~/.claude` directory (default: `~/.claude`) |
| `MC_TRUSTED_PROXIES` | No | Comma-separated trusted proxy IPs for XFF parsing |

View File

@ -19,9 +19,33 @@ interface HealthResult {
latency: number | null
agents: string[]
sessions_count: number
gateway_version?: string | null
compatibility_warning?: string
error?: string
}
function parseGatewayVersion(res: Response): string | null {
const direct = res.headers.get('x-openclaw-version') || res.headers.get('x-clawdbot-version')
if (direct) return direct.trim()
const server = res.headers.get('server') || ''
const m = server.match(/(\d{4}\.\d+\.\d+)/)
return m?.[1] || null
}
function hasOpenClaw32ToolsProfileRisk(version: string | null): boolean {
if (!version) return false
const m = version.match(/^(\d{4})\.(\d+)\.(\d+)/)
if (!m) return false
const year = Number(m[1])
const major = Number(m[2])
const minor = Number(m[3])
if (year > 2026) return true
if (year < 2026) return false
if (major > 3) return true
if (major < 3) return false
return minor >= 2
}
function isBlockedUrl(urlStr: string): boolean {
try {
const url = new URL(urlStr)
@ -77,6 +101,10 @@ export async function POST(request: NextRequest) {
const latency = Date.now() - start
const status = res.ok ? "online" : "error"
const gatewayVersion = parseGatewayVersion(res)
const compatibilityWarning = hasOpenClaw32ToolsProfileRisk(gatewayVersion)
? 'OpenClaw 2026.3.2+ defaults tools.profile=messaging; Mission Control should enforce coding profile when spawning.'
: undefined
updateOnlineStmt.run(status, latency, gw.id)
@ -87,6 +115,8 @@ export async function POST(request: NextRequest) {
latency,
agents: [],
sessions_count: 0,
gateway_version: gatewayVersion,
compatibility_warning: compatibilityWarning,
})
} catch (err: any) {
updateOfflineStmt.run("offline", gw.id)

View File

@ -8,6 +8,15 @@ import { heavyLimiter } from '@/lib/rate-limit'
import { logger } from '@/lib/logger'
import { validateBody, spawnAgentSchema } from '@/lib/validation'
function getPreferredToolsProfile(): string {
return String(process.env.OPENCLAW_TOOLS_PROFILE || 'coding').trim() || 'coding'
}
async function runSpawnWithCompatibility(spawnPayload: Record<string, unknown>) {
const commandArg = `sessions_spawn(${JSON.stringify(spawnPayload)})`
return runClawdbot(['-c', commandArg], { timeoutMs: 10000 })
}
export async function POST(request: NextRequest) {
const auth = requireRole(request, 'operator')
if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status })
@ -31,15 +40,38 @@ export async function POST(request: NextRequest) {
task,
model,
label,
runTimeoutSeconds: timeout
runTimeoutSeconds: timeout,
tools: {
profile: getPreferredToolsProfile(),
},
}
const commandArg = `sessions_spawn(${JSON.stringify(spawnPayload)})`
try {
// Execute the spawn command
const { stdout, stderr } = await runClawdbot(['-c', commandArg], {
timeoutMs: 10000
})
// Execute the spawn command (OpenClaw 2026.3.2+ defaults tools.profile to messaging).
let stdout = ''
let stderr = ''
let compatibilityFallbackUsed = false
try {
const result = await runSpawnWithCompatibility(spawnPayload)
stdout = result.stdout
stderr = result.stderr
} catch (firstError: any) {
const rawErr = String(firstError?.stderr || firstError?.message || '').toLowerCase()
const likelySchemaMismatch =
rawErr.includes('unknown field') ||
rawErr.includes('unknown key') ||
rawErr.includes('invalid argument') ||
rawErr.includes('tools') ||
rawErr.includes('profile')
if (!likelySchemaMismatch) throw firstError
const fallbackPayload = { ...spawnPayload }
delete (fallbackPayload as any).tools
const fallback = await runSpawnWithCompatibility(fallbackPayload)
stdout = fallback.stdout
stderr = fallback.stderr
compatibilityFallbackUsed = true
}
// Parse the response to extract session info
let sessionInfo = null
@ -63,7 +95,11 @@ export async function POST(request: NextRequest) {
timeoutSeconds: timeout,
createdAt: Date.now(),
stdout: stdout.trim(),
stderr: stderr.trim()
stderr: stderr.trim(),
compatibility: {
toolsProfile: getPreferredToolsProfile(),
fallbackUsed: compatibilityFallbackUsed,
},
})
} catch (execError: any) {

View File

@ -2,8 +2,9 @@
import { useState, useEffect } from 'react'
import { createClientLogger } from '@/lib/client-logger'
const log = createClientLogger('AgentDetailTabs')
import Link from 'next/link'
interface Agent {
id: number
@ -513,7 +514,12 @@ export function MemoryTab({
return (
<div className="p-6 space-y-4">
<div className="flex justify-between items-center">
<h4 className="text-lg font-medium text-foreground">Working Memory</h4>
<div>
<h4 className="text-lg font-medium text-foreground">Working Memory</h4>
<p className="text-xs text-muted-foreground mt-1">
Agent-level scratchpad only. Use the global Memory page to browse all workspace memory files.
</p>
</div>
<div className="flex gap-2">
{!editing && (
<>
@ -663,7 +669,10 @@ export function TasksTab({ agent }: { agent: Agent }) {
<div key={task.id} className="bg-surface-1/50 rounded-lg p-4">
<div className="flex items-start justify-between">
<div>
<h5 className="font-medium text-foreground">{task.title}</h5>
<Link href={`/tasks?taskId=${task.id}`} className="font-medium text-foreground hover:text-primary transition-colors">
{task.title}
</Link>
<div className="text-xs text-muted-foreground mt-1">Task #{task.id}</div>
{task.description && (
<p className="text-foreground/80 text-sm mt-1">{task.description}</p>
)}

View File

@ -1,10 +1,10 @@
'use client'
import { useState, useEffect, useCallback } from 'react'
import { useState, useEffect, useCallback, useMemo } from 'react'
import { useMissionControl, CronJob } from '@/store'
import { createClientLogger } from '@/lib/client-logger'
const log = createClientLogger('CronManagement')
import { buildDayKey, getCronOccurrences } from '@/lib/cron-occurrences'
interface NewJobForm {
name: string
@ -59,6 +59,7 @@ export function CronManagementPanel() {
const [availableModels, setAvailableModels] = useState<string[]>([])
const [calendarView, setCalendarView] = useState<CalendarViewMode>('week')
const [calendarDate, setCalendarDate] = useState<Date>(startOfDay(new Date()))
const [selectedCalendarDate, setSelectedCalendarDate] = useState<Date>(startOfDay(new Date()))
const [searchQuery, setSearchQuery] = useState('')
const [agentFilter, setAgentFilter] = useState('all')
const [stateFilter, setStateFilter] = useState<'all' | 'enabled' | 'disabled'>('all')
@ -310,39 +311,69 @@ export function CronManagementPanel() {
return matchesQuery && matchesAgent && matchesState
})
const agendaJobs = [...filteredJobs].sort((a, b) => {
const aRun = typeof a.nextRun === 'number' ? a.nextRun : Number.POSITIVE_INFINITY
const bRun = typeof b.nextRun === 'number' ? b.nextRun : Number.POSITIVE_INFINITY
return aRun - bRun
})
const dayStart = startOfDay(calendarDate)
const dayEnd = addDays(dayStart, 1)
const dayJobs = filteredJobs
.filter((job) => typeof job.nextRun === 'number' && job.nextRun >= dayStart.getTime() && job.nextRun < dayEnd.getTime())
.sort((a, b) => (a.nextRun || 0) - (b.nextRun || 0))
const weekStart = getWeekStart(calendarDate)
const weekDays = Array.from({ length: 7 }, (_, idx) => addDays(weekStart, idx))
const jobsByWeekDay = weekDays.map((date) => {
const start = startOfDay(date).getTime()
const end = addDays(date, 1).getTime()
const jobs = filteredJobs
.filter((job) => typeof job.nextRun === 'number' && job.nextRun >= start && job.nextRun < end)
.sort((a, b) => (a.nextRun || 0) - (b.nextRun || 0))
return { date, jobs }
})
const monthGridStart = getMonthStartGrid(calendarDate)
const monthDays = Array.from({ length: 42 }, (_, idx) => addDays(monthGridStart, idx))
const jobsByMonthDay = monthDays.map((date) => {
const start = startOfDay(date).getTime()
const end = addDays(date, 1).getTime()
const jobs = filteredJobs
.filter((job) => typeof job.nextRun === 'number' && job.nextRun >= start && job.nextRun < end)
.sort((a, b) => (a.nextRun || 0) - (b.nextRun || 0))
return { date, jobs }
})
const calendarBounds = useMemo(() => {
if (calendarView === 'day') {
return { startMs: dayStart.getTime(), endMs: dayEnd.getTime() }
}
if (calendarView === 'week') {
return { startMs: weekStart.getTime(), endMs: addDays(weekStart, 7).getTime() }
}
if (calendarView === 'month') {
return { startMs: monthGridStart.getTime(), endMs: addDays(monthGridStart, 42).getTime() }
}
const agendaStart = Date.now()
return { startMs: agendaStart, endMs: addDays(startOfDay(new Date()), 30).getTime() }
}, [calendarView, dayEnd, dayStart, monthGridStart, weekStart])
const calendarOccurrences = useMemo(() => {
const rows: Array<{ job: CronJob; atMs: number; dayKey: string }> = []
for (const job of filteredJobs) {
const occurrences = getCronOccurrences(job.schedule, calendarBounds.startMs, calendarBounds.endMs, 1000)
for (const occurrence of occurrences) {
rows.push({ job, atMs: occurrence.atMs, dayKey: occurrence.dayKey })
}
if (occurrences.length === 0 && typeof job.nextRun === 'number' && job.nextRun >= calendarBounds.startMs && job.nextRun < calendarBounds.endMs) {
rows.push({ job, atMs: job.nextRun, dayKey: buildDayKey(new Date(job.nextRun)) })
}
}
rows.sort((a, b) => a.atMs - b.atMs)
return rows
}, [calendarBounds.endMs, calendarBounds.startMs, filteredJobs])
const occurrencesByDay = useMemo(() => {
const dayMap = new Map<string, Array<{ job: CronJob; atMs: number }>>()
for (const row of calendarOccurrences) {
const existing = dayMap.get(row.dayKey) || []
existing.push({ job: row.job, atMs: row.atMs })
dayMap.set(row.dayKey, existing)
}
return dayMap
}, [calendarOccurrences])
const dayJobs = occurrencesByDay.get(buildDayKey(dayStart)) || []
const jobsByWeekDay = weekDays.map((date) => ({
date,
jobs: occurrencesByDay.get(buildDayKey(date)) || [],
}))
const jobsByMonthDay = monthDays.map((date) => ({
date,
jobs: occurrencesByDay.get(buildDayKey(date)) || [],
}))
const selectedDayJobs = occurrencesByDay.get(buildDayKey(selectedCalendarDate)) || []
const moveCalendar = (direction: -1 | 1) => {
setCalendarDate((prev) => {
@ -395,7 +426,7 @@ export function CronManagementPanel() {
<div className="flex flex-wrap items-center justify-between gap-3">
<div>
<h2 className="text-xl font-semibold">Calendar View</h2>
<p className="text-sm text-muted-foreground">Read-only schedule visibility across all cron jobs</p>
<p className="text-sm text-muted-foreground">Interactive schedule across all matching cron jobs</p>
</div>
<div className="flex items-center gap-2">
<button
@ -469,23 +500,27 @@ export function CronManagementPanel() {
{calendarView === 'agenda' && (
<div className="border border-border rounded-lg overflow-hidden">
<div className="max-h-80 overflow-y-auto divide-y divide-border">
{agendaJobs.length === 0 ? (
{calendarOccurrences.length === 0 ? (
<div className="p-4 text-sm text-muted-foreground">No jobs match the current filters.</div>
) : (
agendaJobs.map((job) => (
<div key={`agenda-${job.id || job.name}`} className="p-3 flex flex-col md:flex-row md:items-center md:justify-between gap-2">
calendarOccurrences.map((row) => (
<button
key={`agenda-${row.job.id || row.job.name}-${row.atMs}`}
onClick={() => handleJobSelect(row.job)}
className="w-full p-3 text-left flex flex-col md:flex-row md:items-center md:justify-between gap-2 hover:bg-secondary transition-colors"
>
<div>
<div className="font-medium text-foreground">{job.name}</div>
<div className="font-medium text-foreground">{row.job.name}</div>
<div className="text-xs text-muted-foreground">
{job.agentId || 'system'} · {job.enabled ? 'enabled' : 'disabled'} · {job.schedule}
{row.job.agentId || 'system'} · {row.job.enabled ? 'enabled' : 'disabled'} · {row.job.schedule}
</div>
</div>
<div className="text-sm text-muted-foreground">
{job.nextRun ? new Date(job.nextRun).toLocaleString() : 'No upcoming run'}
{new Date(row.atMs).toLocaleString()}
</div>
</div>
</button>
))
)}
)}
</div>
</div>
)}
@ -496,13 +531,17 @@ export function CronManagementPanel() {
<div className="text-sm text-muted-foreground">No scheduled jobs for this day.</div>
) : (
<div className="space-y-2">
{dayJobs.map((job) => (
<div key={`day-${job.id || job.name}`} className="p-2 rounded border border-border bg-secondary/40">
<div className="text-sm font-medium text-foreground">{job.name}</div>
{dayJobs.map((row) => (
<button
key={`day-${row.job.id || row.job.name}-${row.atMs}`}
onClick={() => handleJobSelect(row.job)}
className="w-full p-2 rounded border border-border bg-secondary/40 hover:bg-secondary transition-colors text-left"
>
<div className="text-sm font-medium text-foreground">{row.job.name}</div>
<div className="text-xs text-muted-foreground">
{job.nextRun ? new Date(job.nextRun).toLocaleTimeString() : 'Unknown time'} · {job.agentId || 'system'} · {job.enabled ? 'enabled' : 'disabled'}
{new Date(row.atMs).toLocaleTimeString()} · {row.job.agentId || 'system'} · {row.job.enabled ? 'enabled' : 'disabled'}
</div>
</div>
</button>
))}
</div>
)}
@ -512,21 +551,25 @@ export function CronManagementPanel() {
{calendarView === 'week' && (
<div className="grid grid-cols-1 md:grid-cols-7 gap-2">
{jobsByWeekDay.map(({ date, jobs }) => (
<div key={`week-${date.toISOString()}`} className="border border-border rounded-lg p-2 min-h-36">
<button
key={`week-${date.toISOString()}`}
onClick={() => setSelectedCalendarDate(startOfDay(date))}
className={`border border-border rounded-lg p-2 min-h-36 text-left ${isSameDay(date, selectedCalendarDate) ? 'bg-primary/10 border-primary/40' : 'hover:bg-secondary/50'}`}
>
<div className={`text-xs font-medium mb-2 ${isSameDay(date, new Date()) ? 'text-primary' : 'text-muted-foreground'}`}>
{date.toLocaleDateString(undefined, { weekday: 'short', month: 'numeric', day: 'numeric' })}
</div>
<div className="space-y-1">
{jobs.slice(0, 4).map((job) => (
<div key={`week-job-${job.id || job.name}`} className="text-xs px-2 py-1 rounded bg-secondary text-foreground truncate" title={job.name}>
{job.nextRun ? new Date(job.nextRun).toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit' }) : '--:--'} {job.name}
{jobs.slice(0, 4).map((row) => (
<div key={`week-job-${row.job.id || row.job.name}-${row.atMs}`} className="text-xs px-2 py-1 rounded bg-secondary text-foreground truncate" title={row.job.name}>
{new Date(row.atMs).toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit' })} {row.job.name}
</div>
))}
{jobs.length > 4 && (
<div className="text-xs text-muted-foreground">+{jobs.length - 4} more</div>
)}
</div>
</div>
</button>
))}
</div>
)}
@ -538,15 +581,16 @@ export function CronManagementPanel() {
return (
<div
key={`month-${date.toISOString()}`}
className={`border border-border rounded-lg p-2 min-h-24 ${inCurrentMonth ? 'bg-transparent' : 'bg-secondary/30'}`}
onClick={() => setSelectedCalendarDate(startOfDay(date))}
className={`border border-border rounded-lg p-2 min-h-24 cursor-pointer ${inCurrentMonth ? 'bg-transparent' : 'bg-secondary/30'} ${isSameDay(date, selectedCalendarDate) ? 'border-primary/40 bg-primary/10' : 'hover:bg-secondary/50'}`}
>
<div className={`text-xs mb-1 ${isSameDay(date, new Date()) ? 'text-primary font-semibold' : inCurrentMonth ? 'text-foreground' : 'text-muted-foreground'}`}>
{date.getDate()}
</div>
<div className="space-y-1">
{jobs.slice(0, 2).map((job) => (
<div key={`month-job-${job.id || job.name}`} className="text-[11px] px-1.5 py-0.5 rounded bg-secondary text-foreground truncate" title={job.name}>
{job.name}
{jobs.slice(0, 2).map((row) => (
<div key={`month-job-${row.job.id || row.job.name}-${row.atMs}`} className="text-[11px] px-1.5 py-0.5 rounded bg-secondary text-foreground truncate" title={row.job.name}>
{row.job.name}
</div>
))}
{jobs.length > 2 && <div className="text-[11px] text-muted-foreground">+{jobs.length - 2}</div>}
@ -556,6 +600,35 @@ export function CronManagementPanel() {
})}
</div>
)}
{calendarView !== 'agenda' && (
<div className="border border-border rounded-lg p-3">
<div className="flex items-center justify-between mb-2">
<h3 className="text-sm font-medium text-foreground">
{selectedCalendarDate.toLocaleDateString(undefined, { weekday: 'long', month: 'short', day: 'numeric', year: 'numeric' })}
</h3>
<span className="text-xs text-muted-foreground">{selectedDayJobs.length} jobs</span>
</div>
{selectedDayJobs.length === 0 ? (
<div className="text-sm text-muted-foreground">No jobs scheduled on this date.</div>
) : (
<div className="space-y-2">
{selectedDayJobs.map((row) => (
<button
key={`selected-day-${row.job.id || row.job.name}-${row.atMs}`}
onClick={() => handleJobSelect(row.job)}
className="w-full text-left p-2 rounded border border-border bg-secondary/40 hover:bg-secondary transition-colors"
>
<div className="text-sm font-medium text-foreground">{row.job.name}</div>
<div className="text-xs text-muted-foreground">
{new Date(row.atMs).toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit' })} · {row.job.agentId || 'system'}
</div>
</button>
))}
</div>
)}
</div>
)}
</div>
</div>

View File

@ -356,6 +356,9 @@ export function MemoryBrowserPanel() {
? 'Browse and manage local knowledge files and memory'
: 'Explore knowledge files and memory structure'}
</p>
<p className="text-xs text-muted-foreground mt-1">
This page shows all workspace memory files. The agent profile Memory tab only edits that single agent&apos;s working memory.
</p>
{/* Tab Navigation */}
<div className="flex gap-2 mt-4">

View File

@ -35,12 +35,23 @@ interface DirectConnection {
agent_role: string
}
interface GatewayHealthProbe {
id: number
name: string
status: 'online' | 'offline' | 'error'
latency: number | null
gateway_version?: string | null
compatibility_warning?: string
error?: string
}
export function MultiGatewayPanel() {
const [gateways, setGateways] = useState<Gateway[]>([])
const [directConnections, setDirectConnections] = useState<DirectConnection[]>([])
const [loading, setLoading] = useState(true)
const [showAdd, setShowAdd] = useState(false)
const [probing, setProbing] = useState<number | null>(null)
const [healthByGatewayId, setHealthByGatewayId] = useState<Map<number, GatewayHealthProbe>>(new Map())
const { connection } = useMissionControl()
const { connect } = useWebSocket()
@ -89,7 +100,14 @@ export function MultiGatewayPanel() {
const probeAll = async () => {
try {
await fetch("/api/gateways/health", { method: "POST" })
const res = await fetch("/api/gateways/health", { method: "POST" })
const data = await res.json().catch(() => ({}))
const rows = Array.isArray(data?.results) ? data.results as GatewayHealthProbe[] : []
const mapped = new Map<number, GatewayHealthProbe>()
for (const row of rows) {
if (typeof row?.id === 'number') mapped.set(row.id, row)
}
setHealthByGatewayId(mapped)
} catch { /* ignore */ }
fetchGateways()
}
@ -172,6 +190,7 @@ export function MultiGatewayPanel() {
<GatewayCard
key={gw.id}
gateway={gw}
health={healthByGatewayId.get(gw.id)}
isProbing={probing === gw.id}
isCurrentlyConnected={connection.url?.includes(`:${gw.port}`) ?? false}
onSetPrimary={() => setPrimary(gw)}
@ -250,8 +269,9 @@ export function MultiGatewayPanel() {
)
}
function GatewayCard({ gateway, isProbing, isCurrentlyConnected, onSetPrimary, onDelete, onConnect, onProbe }: {
function GatewayCard({ gateway, health, isProbing, isCurrentlyConnected, onSetPrimary, onDelete, onConnect, onProbe }: {
gateway: Gateway
health?: GatewayHealthProbe
isProbing: boolean
isCurrentlyConnected: boolean
onSetPrimary: () => void
@ -269,6 +289,7 @@ function GatewayCard({ gateway, isProbing, isCurrentlyConnected, onSetPrimary, o
const lastSeen = gateway.last_seen
? new Date(gateway.last_seen * 1000).toLocaleString()
: 'Never probed'
const compatibilityWarning = health?.compatibility_warning
return (
<div className={`bg-card border rounded-lg p-4 transition-smooth ${
@ -296,6 +317,16 @@ function GatewayCard({ gateway, isProbing, isCurrentlyConnected, onSetPrimary, o
{gateway.latency != null && <span>Latency: {gateway.latency}ms</span>}
<span>Last: {lastSeen}</span>
</div>
{health?.gateway_version && (
<div className="mt-1 text-2xs text-muted-foreground">
Gateway version: <span className="font-mono text-foreground/80">{health.gateway_version}</span>
</div>
)}
{compatibilityWarning && (
<div className="mt-1.5 text-2xs rounded border border-amber-500/30 bg-amber-500/10 text-amber-300 px-2 py-1">
{compatibilityWarning}
</div>
)}
</div>
<div className="flex items-center gap-1.5 shrink-0 flex-wrap justify-end">
<button

View File

@ -461,6 +461,9 @@ export function SuperAdminPanel() {
</button>
{createExpanded && (
<div className="p-4 space-y-3">
<div className="text-xs text-muted-foreground">
Add a new workspace/client instance here. Fill the form below and click <span className="text-foreground font-medium">Create + Queue</span>.
</div>
{gatewayLoadError && (
<div className="px-3 py-2 rounded-md text-xs border bg-amber-500/10 text-amber-300 border-amber-500/20">
Gateway list unavailable: {gatewayLoadError}. Using fallback owner value.

View File

@ -1,6 +1,7 @@
'use client'
import { useState, useEffect, useCallback, useRef } from 'react'
import { usePathname, useRouter, useSearchParams } from 'next/navigation'
import { useMissionControl } from '@/store'
import { useSmartPoll } from '@/lib/use-smart-poll'
@ -73,6 +74,9 @@ const priorityColors: Record<string, string> = {
export function TaskBoardPanel() {
const { tasks: storeTasks, setTasks: storeSetTasks, selectedTask, setSelectedTask } = useMissionControl()
const router = useRouter()
const pathname = usePathname()
const searchParams = useSearchParams()
const [agents, setAgents] = useState<Agent[]>([])
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
@ -81,6 +85,23 @@ export function TaskBoardPanel() {
const [showCreateModal, setShowCreateModal] = useState(false)
const [editingTask, setEditingTask] = useState<Task | null>(null)
const dragCounter = useRef(0)
const selectedTaskIdFromUrl = Number.parseInt(searchParams.get('taskId') || '', 10)
const updateTaskUrl = useCallback((taskId: number | null, mode: 'push' | 'replace' = 'push') => {
const params = new URLSearchParams(searchParams.toString())
if (typeof taskId === 'number' && Number.isFinite(taskId)) {
params.set('taskId', String(taskId))
} else {
params.delete('taskId')
}
const query = params.toString()
const href = query ? `${pathname}?${query}` : pathname
if (mode === 'replace') {
router.replace(href)
return
}
router.push(href)
}, [pathname, router, searchParams])
// Augment store tasks with aegisApproved flag (computed, not stored)
const tasks: Task[] = storeTasks.map(t => ({
@ -142,6 +163,26 @@ export function TaskBoardPanel() {
fetchData()
}, [fetchData])
useEffect(() => {
if (!Number.isFinite(selectedTaskIdFromUrl)) {
if (selectedTask) setSelectedTask(null)
return
}
const match = tasks.find((task) => task.id === selectedTaskIdFromUrl)
if (match) {
if (selectedTask?.id !== match.id) {
setSelectedTask(match)
}
return
}
if (!loading) {
setError(`Task #${selectedTaskIdFromUrl} not found in current workspace`)
setSelectedTask(null)
}
}, [loading, selectedTask, selectedTaskIdFromUrl, setSelectedTask, tasks])
// Poll as SSE fallback — pauses when SSE is delivering events
useSmartPoll(fetchData, 30000, { pauseWhenSseConnected: true })
@ -348,8 +389,17 @@ export function TaskBoardPanel() {
tabIndex={0}
aria-label={`${task.title}, ${task.priority} priority, ${task.status}`}
onDragStart={(e) => handleDragStart(e, task)}
onClick={() => setSelectedTask(task)}
onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); setSelectedTask(task) } }}
onClick={() => {
setSelectedTask(task)
updateTaskUrl(task.id)
}}
onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault()
setSelectedTask(task)
updateTaskUrl(task.id)
}
}}
className={`bg-surface-1 rounded-lg p-3 cursor-pointer hover:bg-surface-2 transition-smooth border-l-4 ${priorityColors[task.priority]} ${
draggedTask?.id === task.id ? 'opacity-50' : ''
}`}
@ -446,11 +496,15 @@ export function TaskBoardPanel() {
<TaskDetailModal
task={selectedTask}
agents={agents}
onClose={() => setSelectedTask(null)}
onClose={() => {
setSelectedTask(null)
updateTaskUrl(null)
}}
onUpdate={fetchData}
onEdit={(taskToEdit) => {
setEditingTask(taskToEdit)
setSelectedTask(null)
updateTaskUrl(null, 'replace')
}}
/>
)}

View File

@ -105,4 +105,23 @@ describe('requireRole', () => {
)
expect(result.user).toBeDefined()
})
it('accepts Authorization Bearer API key', () => {
const result = requireRole(
makeRequest({ authorization: 'Bearer test-api-key-secret' }),
'admin',
)
expect(result.user).toBeDefined()
expect(result.user!.username).toBe('api')
})
it('rejects API key auth when API_KEY is not configured', () => {
process.env = { ...originalEnv, API_KEY: '' }
const result = requireRole(
makeRequest({ 'x-api-key': 'test-api-key-secret' }),
'viewer',
)
expect(result.status).toBe(401)
expect(result.user).toBeUndefined()
})
})

View File

@ -0,0 +1,44 @@
import { describe, expect, it } from 'vitest'
import { buildDayKey, getCronOccurrences } from '@/lib/cron-occurrences'
describe('buildDayKey', () => {
it('formats YYYY-MM-DD in local time', () => {
const date = new Date(2026, 2, 4, 9, 15, 0, 0)
expect(buildDayKey(date)).toBe('2026-03-04')
})
})
describe('getCronOccurrences', () => {
it('expands daily schedule across range', () => {
const start = new Date(2026, 2, 1, 0, 0, 0, 0).getTime()
const end = new Date(2026, 2, 5, 0, 0, 0, 0).getTime()
const rows = getCronOccurrences('0 0 * * *', start, end)
expect(rows).toHaveLength(4)
expect(rows.map((r) => r.dayKey)).toEqual([
'2026-03-01',
'2026-03-02',
'2026-03-03',
'2026-03-04',
])
})
it('supports step values', () => {
const start = new Date(2026, 2, 1, 0, 0, 0, 0).getTime()
const end = new Date(2026, 2, 1, 3, 0, 0, 0).getTime()
const rows = getCronOccurrences('*/30 * * * *', start, end)
expect(rows).toHaveLength(6)
})
it('ignores OpenClaw timezone suffix in display schedule', () => {
const start = new Date(2026, 2, 1, 0, 0, 0, 0).getTime()
const end = new Date(2026, 2, 2, 0, 0, 0, 0).getTime()
const rows = getCronOccurrences('0 6 * * * (UTC)', start, end)
expect(rows).toHaveLength(1)
})
it('returns empty list for invalid cron', () => {
const start = new Date(2026, 2, 1, 0, 0, 0, 0).getTime()
const end = new Date(2026, 2, 2, 0, 0, 0, 0).getTime()
expect(getCronOccurrences('invalid', start, end)).toEqual([])
})
})

View File

@ -277,8 +277,9 @@ export function getUserFromRequest(request: Request): User | null {
}
// Check API key - return synthetic user
const apiKey = request.headers.get('x-api-key')
if (apiKey && safeCompare(apiKey, process.env.API_KEY || '')) {
const configuredApiKey = (process.env.API_KEY || '').trim()
const apiKey = extractApiKeyFromHeaders(request.headers)
if (configuredApiKey && apiKey && safeCompare(apiKey, configuredApiKey)) {
return {
id: 0,
username: 'api',
@ -294,6 +295,24 @@ export function getUserFromRequest(request: Request): User | null {
return null
}
function extractApiKeyFromHeaders(headers: Headers): string | null {
const direct = (headers.get('x-api-key') || '').trim()
if (direct) return direct
const authorization = (headers.get('authorization') || '').trim()
if (!authorization) return null
const [scheme, ...rest] = authorization.split(/\s+/)
if (!scheme || rest.length === 0) return null
const normalized = scheme.toLowerCase()
if (normalized === 'bearer' || normalized === 'apikey' || normalized === 'token') {
return rest.join(' ').trim() || null
}
return null
}
/**
* Role hierarchy levels for access control.
* viewer < operator < admin

139
src/lib/cron-occurrences.ts Normal file
View File

@ -0,0 +1,139 @@
export interface CronOccurrence {
atMs: number
dayKey: string
}
interface ParsedField {
any: boolean
matches: (value: number) => boolean
}
interface ParsedCron {
minute: ParsedField
hour: ParsedField
dayOfMonth: ParsedField
month: ParsedField
dayOfWeek: ParsedField
}
function normalizeCronExpression(raw: string): string {
const trimmed = raw.trim()
const tzSuffixMatch = trimmed.match(/^(.*)\s+\([^)]+\)$/)
return (tzSuffixMatch?.[1] || trimmed).trim()
}
function parseToken(token: string, min: number, max: number): { any: boolean; values: Set<number> } {
const valueSet = new Set<number>()
const trimmed = token.trim()
if (trimmed === '*') {
for (let i = min; i <= max; i += 1) valueSet.add(i)
return { any: true, values: valueSet }
}
for (const part of trimmed.split(',')) {
const section = part.trim()
if (!section) continue
const [rangePart, stepPart] = section.split('/')
const step = stepPart ? Number(stepPart) : 1
if (!Number.isFinite(step) || step <= 0) continue
if (rangePart === '*') {
for (let i = min; i <= max; i += step) valueSet.add(i)
continue
}
if (rangePart.includes('-')) {
const [fromRaw, toRaw] = rangePart.split('-')
const from = Number(fromRaw)
const to = Number(toRaw)
if (!Number.isFinite(from) || !Number.isFinite(to)) continue
const start = Math.max(min, Math.min(max, from))
const end = Math.max(min, Math.min(max, to))
for (let i = start; i <= end; i += step) valueSet.add(i)
continue
}
const single = Number(rangePart)
if (!Number.isFinite(single)) continue
if (single >= min && single <= max) valueSet.add(single)
}
return { any: false, values: valueSet }
}
function parseField(token: string, min: number, max: number): ParsedField {
const parsed = parseToken(token, min, max)
return {
any: parsed.any,
matches: (value: number) => parsed.values.has(value),
}
}
function parseCron(raw: string): ParsedCron | null {
const normalized = normalizeCronExpression(raw)
const parts = normalized.split(/\s+/).filter(Boolean)
if (parts.length !== 5) return null
return {
minute: parseField(parts[0], 0, 59),
hour: parseField(parts[1], 0, 23),
dayOfMonth: parseField(parts[2], 1, 31),
month: parseField(parts[3], 1, 12),
dayOfWeek: parseField(parts[4], 0, 6),
}
}
function matchesDay(parsed: ParsedCron, date: Date): boolean {
const dayOfMonthMatches = parsed.dayOfMonth.matches(date.getDate())
const dayOfWeekMatches = parsed.dayOfWeek.matches(date.getDay())
if (parsed.dayOfMonth.any && parsed.dayOfWeek.any) return true
if (parsed.dayOfMonth.any) return dayOfWeekMatches
if (parsed.dayOfWeek.any) return dayOfMonthMatches
return dayOfMonthMatches || dayOfWeekMatches
}
export function buildDayKey(date: Date): string {
const year = date.getFullYear()
const month = String(date.getMonth() + 1).padStart(2, '0')
const day = String(date.getDate()).padStart(2, '0')
return `${year}-${month}-${day}`
}
export function getCronOccurrences(
schedule: string,
rangeStartMs: number,
rangeEndMs: number,
max = 1000
): CronOccurrence[] {
if (!schedule || !Number.isFinite(rangeStartMs) || !Number.isFinite(rangeEndMs)) return []
if (rangeEndMs <= rangeStartMs || max <= 0) return []
const parsed = parseCron(schedule)
if (!parsed) return []
const occurrences: CronOccurrence[] = []
const cursor = new Date(rangeStartMs)
cursor.setSeconds(0, 0)
if (cursor.getTime() < rangeStartMs) {
cursor.setMinutes(cursor.getMinutes() + 1, 0, 0)
}
while (cursor.getTime() < rangeEndMs && occurrences.length < max) {
if (
parsed.month.matches(cursor.getMonth() + 1) &&
matchesDay(parsed, cursor) &&
parsed.hour.matches(cursor.getHours()) &&
parsed.minute.matches(cursor.getMinutes())
) {
occurrences.push({
atMs: cursor.getTime(),
dayKey: buildDayKey(cursor),
})
}
cursor.setMinutes(cursor.getMinutes() + 1, 0, 0)
}
return occurrences
}

View File

@ -16,6 +16,7 @@ const log = createClientLogger('WebSocket')
// Gateway protocol version (v3 required by OpenClaw 2026.x)
const PROTOCOL_VERSION = 3
const DEFAULT_GATEWAY_CLIENT_ID = process.env.NEXT_PUBLIC_GATEWAY_CLIENT_ID || 'control-ui'
// Heartbeat configuration
const PING_INTERVAL_MS = 30_000
@ -182,7 +183,7 @@ export function useWebSocket() {
const cachedToken = getCachedDeviceToken()
const clientId = 'gateway-client'
const clientId = DEFAULT_GATEWAY_CLIENT_ID
const clientMode = 'ui'
const role = 'operator'
const scopes = ['operator.admin']

View File

@ -52,6 +52,22 @@ function applySecurityHeaders(response: NextResponse): NextResponse {
return response
}
function extractApiKeyFromRequest(request: NextRequest): string {
const direct = (request.headers.get('x-api-key') || '').trim()
if (direct) return direct
const authorization = (request.headers.get('authorization') || '').trim()
if (!authorization) return ''
const [scheme, ...rest] = authorization.split(/\s+/)
if (!scheme || rest.length === 0) return ''
const normalized = scheme.toLowerCase()
if (normalized === 'bearer' || normalized === 'apikey' || normalized === 'token') {
return rest.join(' ').trim()
}
return ''
}
export function proxy(request: NextRequest) {
// Network access control.
// In production: default-deny unless explicitly allowed.
@ -63,7 +79,8 @@ export function proxy(request: NextRequest) {
.map((s) => s.trim())
.filter(Boolean)
const isAllowedHost = allowAnyHost || allowedPatterns.some((p) => hostMatches(p, hostName))
const enforceAllowlist = !allowAnyHost && allowedPatterns.length > 0
const isAllowedHost = !enforceAllowlist || allowedPatterns.some((p) => hostMatches(p, hostName))
if (!isAllowedHost) {
return new NextResponse('Forbidden', { status: 403 })
@ -97,8 +114,10 @@ export function proxy(request: NextRequest) {
// API routes: accept session cookie OR API key
if (pathname.startsWith('/api/')) {
const apiKey = request.headers.get('x-api-key')
if (sessionToken || (apiKey && safeCompare(apiKey, process.env.API_KEY || ''))) {
const configuredApiKey = (process.env.API_KEY || '').trim()
const apiKey = extractApiKeyFromRequest(request)
const hasValidApiKey = Boolean(configuredApiKey && apiKey && safeCompare(apiKey, configuredApiKey))
if (sessionToken || hasValidApiKey) {
return applySecurityHeaders(NextResponse.next())
}