nyk commited on
Commit
23a0e33
·
unverified ·
2 Parent(s): bd337531c2355d

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

Browse files
.env.example CHANGED
@@ -54,6 +54,9 @@ OPENCLAW_GATEWAY_HOST=127.0.0.1
54
  OPENCLAW_GATEWAY_PORT=18789
55
  # Optional: token used by server-side gateway calls
56
  OPENCLAW_GATEWAY_TOKEN=
 
 
 
57
 
58
  # Frontend env vars (NEXT_PUBLIC_ prefix = available in browser)
59
  NEXT_PUBLIC_GATEWAY_HOST=
@@ -61,6 +64,8 @@ NEXT_PUBLIC_GATEWAY_PORT=18789
61
  NEXT_PUBLIC_GATEWAY_PROTOCOL=
62
  NEXT_PUBLIC_GATEWAY_URL=
63
  # NEXT_PUBLIC_GATEWAY_TOKEN= # Optional, set if gateway requires auth token
 
 
64
 
65
  # === Data Paths (all optional, defaults to .data/ in project root) ===
66
  # MISSION_CONTROL_DATA_DIR=.data
 
54
  OPENCLAW_GATEWAY_PORT=18789
55
  # Optional: token used by server-side gateway calls
56
  OPENCLAW_GATEWAY_TOKEN=
57
+ # Tools profile used when Mission Control spawns sessions via sessions_spawn.
58
+ # OpenClaw 2026.3.2+ defaults to "messaging" if omitted.
59
+ OPENCLAW_TOOLS_PROFILE=coding
60
 
61
  # Frontend env vars (NEXT_PUBLIC_ prefix = available in browser)
62
  NEXT_PUBLIC_GATEWAY_HOST=
 
64
  NEXT_PUBLIC_GATEWAY_PROTOCOL=
65
  NEXT_PUBLIC_GATEWAY_URL=
66
  # NEXT_PUBLIC_GATEWAY_TOKEN= # Optional, set if gateway requires auth token
67
+ # Gateway client id used in websocket handshake (role=operator UI client).
68
+ NEXT_PUBLIC_GATEWAY_CLIENT_ID=control-ui
69
 
70
  # === Data Paths (all optional, defaults to .data/ in project root) ===
71
  # MISSION_CONTROL_DATA_DIR=.data
README.md CHANGED
@@ -346,7 +346,9 @@ See [`.env.example`](.env.example) for the complete list. Key variables:
346
  | `OPENCLAW_GATEWAY_HOST` | No | Gateway host (default: `127.0.0.1`) |
347
  | `OPENCLAW_GATEWAY_PORT` | No | Gateway WebSocket port (default: `18789`) |
348
  | `OPENCLAW_GATEWAY_TOKEN` | No | Server-side gateway auth token |
 
349
  | `NEXT_PUBLIC_GATEWAY_TOKEN` | No | Browser-side gateway auth token (must use `NEXT_PUBLIC_` prefix) |
 
350
  | `OPENCLAW_MEMORY_DIR` | No | Memory browser root (see note below) |
351
  | `MC_CLAUDE_HOME` | No | Path to `~/.claude` directory (default: `~/.claude`) |
352
  | `MC_TRUSTED_PROXIES` | No | Comma-separated trusted proxy IPs for XFF parsing |
 
346
  | `OPENCLAW_GATEWAY_HOST` | No | Gateway host (default: `127.0.0.1`) |
347
  | `OPENCLAW_GATEWAY_PORT` | No | Gateway WebSocket port (default: `18789`) |
348
  | `OPENCLAW_GATEWAY_TOKEN` | No | Server-side gateway auth token |
349
+ | `OPENCLAW_TOOLS_PROFILE` | No | Tools profile for `sessions_spawn` (recommended: `coding`) |
350
  | `NEXT_PUBLIC_GATEWAY_TOKEN` | No | Browser-side gateway auth token (must use `NEXT_PUBLIC_` prefix) |
351
+ | `NEXT_PUBLIC_GATEWAY_CLIENT_ID` | No | Gateway UI client ID for websocket handshake (default: `control-ui`) |
352
  | `OPENCLAW_MEMORY_DIR` | No | Memory browser root (see note below) |
353
  | `MC_CLAUDE_HOME` | No | Path to `~/.claude` directory (default: `~/.claude`) |
354
  | `MC_TRUSTED_PROXIES` | No | Comma-separated trusted proxy IPs for XFF parsing |
src/app/api/gateways/health/route.ts CHANGED
@@ -19,9 +19,33 @@ interface HealthResult {
19
  latency: number | null
20
  agents: string[]
21
  sessions_count: number
 
 
22
  error?: string
23
  }
24
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
  function isBlockedUrl(urlStr: string): boolean {
26
  try {
27
  const url = new URL(urlStr)
@@ -77,6 +101,10 @@ export async function POST(request: NextRequest) {
77
 
78
  const latency = Date.now() - start
79
  const status = res.ok ? "online" : "error"
 
 
 
 
80
 
81
  updateOnlineStmt.run(status, latency, gw.id)
82
 
@@ -87,6 +115,8 @@ export async function POST(request: NextRequest) {
87
  latency,
88
  agents: [],
89
  sessions_count: 0,
 
 
90
  })
91
  } catch (err: any) {
92
  updateOfflineStmt.run("offline", gw.id)
 
19
  latency: number | null
20
  agents: string[]
21
  sessions_count: number
22
+ gateway_version?: string | null
23
+ compatibility_warning?: string
24
  error?: string
25
  }
26
 
27
+ function parseGatewayVersion(res: Response): string | null {
28
+ const direct = res.headers.get('x-openclaw-version') || res.headers.get('x-clawdbot-version')
29
+ if (direct) return direct.trim()
30
+ const server = res.headers.get('server') || ''
31
+ const m = server.match(/(\d{4}\.\d+\.\d+)/)
32
+ return m?.[1] || null
33
+ }
34
+
35
+ function hasOpenClaw32ToolsProfileRisk(version: string | null): boolean {
36
+ if (!version) return false
37
+ const m = version.match(/^(\d{4})\.(\d+)\.(\d+)/)
38
+ if (!m) return false
39
+ const year = Number(m[1])
40
+ const major = Number(m[2])
41
+ const minor = Number(m[3])
42
+ if (year > 2026) return true
43
+ if (year < 2026) return false
44
+ if (major > 3) return true
45
+ if (major < 3) return false
46
+ return minor >= 2
47
+ }
48
+
49
  function isBlockedUrl(urlStr: string): boolean {
50
  try {
51
  const url = new URL(urlStr)
 
101
 
102
  const latency = Date.now() - start
103
  const status = res.ok ? "online" : "error"
104
+ const gatewayVersion = parseGatewayVersion(res)
105
+ const compatibilityWarning = hasOpenClaw32ToolsProfileRisk(gatewayVersion)
106
+ ? 'OpenClaw 2026.3.2+ defaults tools.profile=messaging; Mission Control should enforce coding profile when spawning.'
107
+ : undefined
108
 
109
  updateOnlineStmt.run(status, latency, gw.id)
110
 
 
115
  latency,
116
  agents: [],
117
  sessions_count: 0,
118
+ gateway_version: gatewayVersion,
119
+ compatibility_warning: compatibilityWarning,
120
  })
121
  } catch (err: any) {
122
  updateOfflineStmt.run("offline", gw.id)
src/app/api/spawn/route.ts CHANGED
@@ -8,6 +8,15 @@ import { heavyLimiter } from '@/lib/rate-limit'
8
  import { logger } from '@/lib/logger'
9
  import { validateBody, spawnAgentSchema } from '@/lib/validation'
10
 
 
 
 
 
 
 
 
 
 
11
  export async function POST(request: NextRequest) {
12
  const auth = requireRole(request, 'operator')
13
  if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status })
@@ -31,15 +40,38 @@ export async function POST(request: NextRequest) {
31
  task,
32
  model,
33
  label,
34
- runTimeoutSeconds: timeout
 
 
 
35
  }
36
- const commandArg = `sessions_spawn(${JSON.stringify(spawnPayload)})`
37
 
38
  try {
39
- // Execute the spawn command
40
- const { stdout, stderr } = await runClawdbot(['-c', commandArg], {
41
- timeoutMs: 10000
42
- })
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
 
44
  // Parse the response to extract session info
45
  let sessionInfo = null
@@ -63,7 +95,11 @@ export async function POST(request: NextRequest) {
63
  timeoutSeconds: timeout,
64
  createdAt: Date.now(),
65
  stdout: stdout.trim(),
66
- stderr: stderr.trim()
 
 
 
 
67
  })
68
 
69
  } catch (execError: any) {
 
8
  import { logger } from '@/lib/logger'
9
  import { validateBody, spawnAgentSchema } from '@/lib/validation'
10
 
11
+ function getPreferredToolsProfile(): string {
12
+ return String(process.env.OPENCLAW_TOOLS_PROFILE || 'coding').trim() || 'coding'
13
+ }
14
+
15
+ async function runSpawnWithCompatibility(spawnPayload: Record<string, unknown>) {
16
+ const commandArg = `sessions_spawn(${JSON.stringify(spawnPayload)})`
17
+ return runClawdbot(['-c', commandArg], { timeoutMs: 10000 })
18
+ }
19
+
20
  export async function POST(request: NextRequest) {
21
  const auth = requireRole(request, 'operator')
22
  if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status })
 
40
  task,
41
  model,
42
  label,
43
+ runTimeoutSeconds: timeout,
44
+ tools: {
45
+ profile: getPreferredToolsProfile(),
46
+ },
47
  }
 
48
 
49
  try {
50
+ // Execute the spawn command (OpenClaw 2026.3.2+ defaults tools.profile to messaging).
51
+ let stdout = ''
52
+ let stderr = ''
53
+ let compatibilityFallbackUsed = false
54
+ try {
55
+ const result = await runSpawnWithCompatibility(spawnPayload)
56
+ stdout = result.stdout
57
+ stderr = result.stderr
58
+ } catch (firstError: any) {
59
+ const rawErr = String(firstError?.stderr || firstError?.message || '').toLowerCase()
60
+ const likelySchemaMismatch =
61
+ rawErr.includes('unknown field') ||
62
+ rawErr.includes('unknown key') ||
63
+ rawErr.includes('invalid argument') ||
64
+ rawErr.includes('tools') ||
65
+ rawErr.includes('profile')
66
+ if (!likelySchemaMismatch) throw firstError
67
+
68
+ const fallbackPayload = { ...spawnPayload }
69
+ delete (fallbackPayload as any).tools
70
+ const fallback = await runSpawnWithCompatibility(fallbackPayload)
71
+ stdout = fallback.stdout
72
+ stderr = fallback.stderr
73
+ compatibilityFallbackUsed = true
74
+ }
75
 
76
  // Parse the response to extract session info
77
  let sessionInfo = null
 
95
  timeoutSeconds: timeout,
96
  createdAt: Date.now(),
97
  stdout: stdout.trim(),
98
+ stderr: stderr.trim(),
99
+ compatibility: {
100
+ toolsProfile: getPreferredToolsProfile(),
101
+ fallbackUsed: compatibilityFallbackUsed,
102
+ },
103
  })
104
 
105
  } catch (execError: any) {
src/components/panels/agent-detail-tabs.tsx CHANGED
@@ -2,8 +2,9 @@
2
 
3
  import { useState, useEffect } from 'react'
4
  import { createClientLogger } from '@/lib/client-logger'
5
-
6
  const log = createClientLogger('AgentDetailTabs')
 
 
7
 
8
  interface Agent {
9
  id: number
@@ -513,7 +514,12 @@ export function MemoryTab({
513
  return (
514
  <div className="p-6 space-y-4">
515
  <div className="flex justify-between items-center">
516
- <h4 className="text-lg font-medium text-foreground">Working Memory</h4>
 
 
 
 
 
517
  <div className="flex gap-2">
518
  {!editing && (
519
  <>
@@ -663,7 +669,10 @@ export function TasksTab({ agent }: { agent: Agent }) {
663
  <div key={task.id} className="bg-surface-1/50 rounded-lg p-4">
664
  <div className="flex items-start justify-between">
665
  <div>
666
- <h5 className="font-medium text-foreground">{task.title}</h5>
 
 
 
667
  {task.description && (
668
  <p className="text-foreground/80 text-sm mt-1">{task.description}</p>
669
  )}
 
2
 
3
  import { useState, useEffect } from 'react'
4
  import { createClientLogger } from '@/lib/client-logger'
 
5
  const log = createClientLogger('AgentDetailTabs')
6
+ import Link from 'next/link'
7
+
8
 
9
  interface Agent {
10
  id: number
 
514
  return (
515
  <div className="p-6 space-y-4">
516
  <div className="flex justify-between items-center">
517
+ <div>
518
+ <h4 className="text-lg font-medium text-foreground">Working Memory</h4>
519
+ <p className="text-xs text-muted-foreground mt-1">
520
+ Agent-level scratchpad only. Use the global Memory page to browse all workspace memory files.
521
+ </p>
522
+ </div>
523
  <div className="flex gap-2">
524
  {!editing && (
525
  <>
 
669
  <div key={task.id} className="bg-surface-1/50 rounded-lg p-4">
670
  <div className="flex items-start justify-between">
671
  <div>
672
+ <Link href={`/tasks?taskId=${task.id}`} className="font-medium text-foreground hover:text-primary transition-colors">
673
+ {task.title}
674
+ </Link>
675
+ <div className="text-xs text-muted-foreground mt-1">Task #{task.id}</div>
676
  {task.description && (
677
  <p className="text-foreground/80 text-sm mt-1">{task.description}</p>
678
  )}
src/components/panels/cron-management-panel.tsx CHANGED
@@ -1,10 +1,10 @@
1
  'use client'
2
 
3
- import { useState, useEffect, useCallback } from 'react'
4
  import { useMissionControl, CronJob } from '@/store'
5
  import { createClientLogger } from '@/lib/client-logger'
6
-
7
  const log = createClientLogger('CronManagement')
 
8
 
9
  interface NewJobForm {
10
  name: string
@@ -59,6 +59,7 @@ export function CronManagementPanel() {
59
  const [availableModels, setAvailableModels] = useState<string[]>([])
60
  const [calendarView, setCalendarView] = useState<CalendarViewMode>('week')
61
  const [calendarDate, setCalendarDate] = useState<Date>(startOfDay(new Date()))
 
62
  const [searchQuery, setSearchQuery] = useState('')
63
  const [agentFilter, setAgentFilter] = useState('all')
64
  const [stateFilter, setStateFilter] = useState<'all' | 'enabled' | 'disabled'>('all')
@@ -310,39 +311,69 @@ export function CronManagementPanel() {
310
  return matchesQuery && matchesAgent && matchesState
311
  })
312
 
313
- const agendaJobs = [...filteredJobs].sort((a, b) => {
314
- const aRun = typeof a.nextRun === 'number' ? a.nextRun : Number.POSITIVE_INFINITY
315
- const bRun = typeof b.nextRun === 'number' ? b.nextRun : Number.POSITIVE_INFINITY
316
- return aRun - bRun
317
- })
318
-
319
  const dayStart = startOfDay(calendarDate)
320
  const dayEnd = addDays(dayStart, 1)
321
- const dayJobs = filteredJobs
322
- .filter((job) => typeof job.nextRun === 'number' && job.nextRun >= dayStart.getTime() && job.nextRun < dayEnd.getTime())
323
- .sort((a, b) => (a.nextRun || 0) - (b.nextRun || 0))
324
 
325
  const weekStart = getWeekStart(calendarDate)
326
  const weekDays = Array.from({ length: 7 }, (_, idx) => addDays(weekStart, idx))
327
- const jobsByWeekDay = weekDays.map((date) => {
328
- const start = startOfDay(date).getTime()
329
- const end = addDays(date, 1).getTime()
330
- const jobs = filteredJobs
331
- .filter((job) => typeof job.nextRun === 'number' && job.nextRun >= start && job.nextRun < end)
332
- .sort((a, b) => (a.nextRun || 0) - (b.nextRun || 0))
333
- return { date, jobs }
334
- })
335
 
336
  const monthGridStart = getMonthStartGrid(calendarDate)
337
  const monthDays = Array.from({ length: 42 }, (_, idx) => addDays(monthGridStart, idx))
338
- const jobsByMonthDay = monthDays.map((date) => {
339
- const start = startOfDay(date).getTime()
340
- const end = addDays(date, 1).getTime()
341
- const jobs = filteredJobs
342
- .filter((job) => typeof job.nextRun === 'number' && job.nextRun >= start && job.nextRun < end)
343
- .sort((a, b) => (a.nextRun || 0) - (b.nextRun || 0))
344
- return { date, jobs }
345
- })
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
346
 
347
  const moveCalendar = (direction: -1 | 1) => {
348
  setCalendarDate((prev) => {
@@ -395,7 +426,7 @@ export function CronManagementPanel() {
395
  <div className="flex flex-wrap items-center justify-between gap-3">
396
  <div>
397
  <h2 className="text-xl font-semibold">Calendar View</h2>
398
- <p className="text-sm text-muted-foreground">Read-only schedule visibility across all cron jobs</p>
399
  </div>
400
  <div className="flex items-center gap-2">
401
  <button
@@ -469,23 +500,27 @@ export function CronManagementPanel() {
469
  {calendarView === 'agenda' && (
470
  <div className="border border-border rounded-lg overflow-hidden">
471
  <div className="max-h-80 overflow-y-auto divide-y divide-border">
472
- {agendaJobs.length === 0 ? (
473
  <div className="p-4 text-sm text-muted-foreground">No jobs match the current filters.</div>
474
  ) : (
475
- agendaJobs.map((job) => (
476
- <div key={`agenda-${job.id || job.name}`} className="p-3 flex flex-col md:flex-row md:items-center md:justify-between gap-2">
 
 
 
 
477
  <div>
478
- <div className="font-medium text-foreground">{job.name}</div>
479
  <div className="text-xs text-muted-foreground">
480
- {job.agentId || 'system'} · {job.enabled ? 'enabled' : 'disabled'} · {job.schedule}
481
  </div>
482
  </div>
483
  <div className="text-sm text-muted-foreground">
484
- {job.nextRun ? new Date(job.nextRun).toLocaleString() : 'No upcoming run'}
485
  </div>
486
- </div>
487
  ))
488
- )}
489
  </div>
490
  </div>
491
  )}
@@ -496,13 +531,17 @@ export function CronManagementPanel() {
496
  <div className="text-sm text-muted-foreground">No scheduled jobs for this day.</div>
497
  ) : (
498
  <div className="space-y-2">
499
- {dayJobs.map((job) => (
500
- <div key={`day-${job.id || job.name}`} className="p-2 rounded border border-border bg-secondary/40">
501
- <div className="text-sm font-medium text-foreground">{job.name}</div>
 
 
 
 
502
  <div className="text-xs text-muted-foreground">
503
- {job.nextRun ? new Date(job.nextRun).toLocaleTimeString() : 'Unknown time'} · {job.agentId || 'system'} · {job.enabled ? 'enabled' : 'disabled'}
504
  </div>
505
- </div>
506
  ))}
507
  </div>
508
  )}
@@ -512,21 +551,25 @@ export function CronManagementPanel() {
512
  {calendarView === 'week' && (
513
  <div className="grid grid-cols-1 md:grid-cols-7 gap-2">
514
  {jobsByWeekDay.map(({ date, jobs }) => (
515
- <div key={`week-${date.toISOString()}`} className="border border-border rounded-lg p-2 min-h-36">
 
 
 
 
516
  <div className={`text-xs font-medium mb-2 ${isSameDay(date, new Date()) ? 'text-primary' : 'text-muted-foreground'}`}>
517
  {date.toLocaleDateString(undefined, { weekday: 'short', month: 'numeric', day: 'numeric' })}
518
  </div>
519
  <div className="space-y-1">
520
- {jobs.slice(0, 4).map((job) => (
521
- <div key={`week-job-${job.id || job.name}`} className="text-xs px-2 py-1 rounded bg-secondary text-foreground truncate" title={job.name}>
522
- {job.nextRun ? new Date(job.nextRun).toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit' }) : '--:--'} {job.name}
523
  </div>
524
  ))}
525
  {jobs.length > 4 && (
526
  <div className="text-xs text-muted-foreground">+{jobs.length - 4} more</div>
527
  )}
528
  </div>
529
- </div>
530
  ))}
531
  </div>
532
  )}
@@ -538,15 +581,16 @@ export function CronManagementPanel() {
538
  return (
539
  <div
540
  key={`month-${date.toISOString()}`}
541
- className={`border border-border rounded-lg p-2 min-h-24 ${inCurrentMonth ? 'bg-transparent' : 'bg-secondary/30'}`}
 
542
  >
543
  <div className={`text-xs mb-1 ${isSameDay(date, new Date()) ? 'text-primary font-semibold' : inCurrentMonth ? 'text-foreground' : 'text-muted-foreground'}`}>
544
  {date.getDate()}
545
  </div>
546
  <div className="space-y-1">
547
- {jobs.slice(0, 2).map((job) => (
548
- <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}>
549
- {job.name}
550
  </div>
551
  ))}
552
  {jobs.length > 2 && <div className="text-[11px] text-muted-foreground">+{jobs.length - 2}</div>}
@@ -556,6 +600,35 @@ export function CronManagementPanel() {
556
  })}
557
  </div>
558
  )}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
559
  </div>
560
  </div>
561
 
 
1
  'use client'
2
 
3
+ import { useState, useEffect, useCallback, useMemo } from 'react'
4
  import { useMissionControl, CronJob } from '@/store'
5
  import { createClientLogger } from '@/lib/client-logger'
 
6
  const log = createClientLogger('CronManagement')
7
+ import { buildDayKey, getCronOccurrences } from '@/lib/cron-occurrences'
8
 
9
  interface NewJobForm {
10
  name: string
 
59
  const [availableModels, setAvailableModels] = useState<string[]>([])
60
  const [calendarView, setCalendarView] = useState<CalendarViewMode>('week')
61
  const [calendarDate, setCalendarDate] = useState<Date>(startOfDay(new Date()))
62
+ const [selectedCalendarDate, setSelectedCalendarDate] = useState<Date>(startOfDay(new Date()))
63
  const [searchQuery, setSearchQuery] = useState('')
64
  const [agentFilter, setAgentFilter] = useState('all')
65
  const [stateFilter, setStateFilter] = useState<'all' | 'enabled' | 'disabled'>('all')
 
311
  return matchesQuery && matchesAgent && matchesState
312
  })
313
 
 
 
 
 
 
 
314
  const dayStart = startOfDay(calendarDate)
315
  const dayEnd = addDays(dayStart, 1)
 
 
 
316
 
317
  const weekStart = getWeekStart(calendarDate)
318
  const weekDays = Array.from({ length: 7 }, (_, idx) => addDays(weekStart, idx))
 
 
 
 
 
 
 
 
319
 
320
  const monthGridStart = getMonthStartGrid(calendarDate)
321
  const monthDays = Array.from({ length: 42 }, (_, idx) => addDays(monthGridStart, idx))
322
+
323
+ const calendarBounds = useMemo(() => {
324
+ if (calendarView === 'day') {
325
+ return { startMs: dayStart.getTime(), endMs: dayEnd.getTime() }
326
+ }
327
+ if (calendarView === 'week') {
328
+ return { startMs: weekStart.getTime(), endMs: addDays(weekStart, 7).getTime() }
329
+ }
330
+ if (calendarView === 'month') {
331
+ return { startMs: monthGridStart.getTime(), endMs: addDays(monthGridStart, 42).getTime() }
332
+ }
333
+ const agendaStart = Date.now()
334
+ return { startMs: agendaStart, endMs: addDays(startOfDay(new Date()), 30).getTime() }
335
+ }, [calendarView, dayEnd, dayStart, monthGridStart, weekStart])
336
+
337
+ const calendarOccurrences = useMemo(() => {
338
+ const rows: Array<{ job: CronJob; atMs: number; dayKey: string }> = []
339
+ for (const job of filteredJobs) {
340
+ const occurrences = getCronOccurrences(job.schedule, calendarBounds.startMs, calendarBounds.endMs, 1000)
341
+ for (const occurrence of occurrences) {
342
+ rows.push({ job, atMs: occurrence.atMs, dayKey: occurrence.dayKey })
343
+ }
344
+
345
+ if (occurrences.length === 0 && typeof job.nextRun === 'number' && job.nextRun >= calendarBounds.startMs && job.nextRun < calendarBounds.endMs) {
346
+ rows.push({ job, atMs: job.nextRun, dayKey: buildDayKey(new Date(job.nextRun)) })
347
+ }
348
+ }
349
+
350
+ rows.sort((a, b) => a.atMs - b.atMs)
351
+ return rows
352
+ }, [calendarBounds.endMs, calendarBounds.startMs, filteredJobs])
353
+
354
+ const occurrencesByDay = useMemo(() => {
355
+ const dayMap = new Map<string, Array<{ job: CronJob; atMs: number }>>()
356
+ for (const row of calendarOccurrences) {
357
+ const existing = dayMap.get(row.dayKey) || []
358
+ existing.push({ job: row.job, atMs: row.atMs })
359
+ dayMap.set(row.dayKey, existing)
360
+ }
361
+ return dayMap
362
+ }, [calendarOccurrences])
363
+
364
+ const dayJobs = occurrencesByDay.get(buildDayKey(dayStart)) || []
365
+
366
+ const jobsByWeekDay = weekDays.map((date) => ({
367
+ date,
368
+ jobs: occurrencesByDay.get(buildDayKey(date)) || [],
369
+ }))
370
+
371
+ const jobsByMonthDay = monthDays.map((date) => ({
372
+ date,
373
+ jobs: occurrencesByDay.get(buildDayKey(date)) || [],
374
+ }))
375
+
376
+ const selectedDayJobs = occurrencesByDay.get(buildDayKey(selectedCalendarDate)) || []
377
 
378
  const moveCalendar = (direction: -1 | 1) => {
379
  setCalendarDate((prev) => {
 
426
  <div className="flex flex-wrap items-center justify-between gap-3">
427
  <div>
428
  <h2 className="text-xl font-semibold">Calendar View</h2>
429
+ <p className="text-sm text-muted-foreground">Interactive schedule across all matching cron jobs</p>
430
  </div>
431
  <div className="flex items-center gap-2">
432
  <button
 
500
  {calendarView === 'agenda' && (
501
  <div className="border border-border rounded-lg overflow-hidden">
502
  <div className="max-h-80 overflow-y-auto divide-y divide-border">
503
+ {calendarOccurrences.length === 0 ? (
504
  <div className="p-4 text-sm text-muted-foreground">No jobs match the current filters.</div>
505
  ) : (
506
+ calendarOccurrences.map((row) => (
507
+ <button
508
+ key={`agenda-${row.job.id || row.job.name}-${row.atMs}`}
509
+ onClick={() => handleJobSelect(row.job)}
510
+ 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"
511
+ >
512
  <div>
513
+ <div className="font-medium text-foreground">{row.job.name}</div>
514
  <div className="text-xs text-muted-foreground">
515
+ {row.job.agentId || 'system'} · {row.job.enabled ? 'enabled' : 'disabled'} · {row.job.schedule}
516
  </div>
517
  </div>
518
  <div className="text-sm text-muted-foreground">
519
+ {new Date(row.atMs).toLocaleString()}
520
  </div>
521
+ </button>
522
  ))
523
+ )}
524
  </div>
525
  </div>
526
  )}
 
531
  <div className="text-sm text-muted-foreground">No scheduled jobs for this day.</div>
532
  ) : (
533
  <div className="space-y-2">
534
+ {dayJobs.map((row) => (
535
+ <button
536
+ key={`day-${row.job.id || row.job.name}-${row.atMs}`}
537
+ onClick={() => handleJobSelect(row.job)}
538
+ className="w-full p-2 rounded border border-border bg-secondary/40 hover:bg-secondary transition-colors text-left"
539
+ >
540
+ <div className="text-sm font-medium text-foreground">{row.job.name}</div>
541
  <div className="text-xs text-muted-foreground">
542
+ {new Date(row.atMs).toLocaleTimeString()} · {row.job.agentId || 'system'} · {row.job.enabled ? 'enabled' : 'disabled'}
543
  </div>
544
+ </button>
545
  ))}
546
  </div>
547
  )}
 
551
  {calendarView === 'week' && (
552
  <div className="grid grid-cols-1 md:grid-cols-7 gap-2">
553
  {jobsByWeekDay.map(({ date, jobs }) => (
554
+ <button
555
+ key={`week-${date.toISOString()}`}
556
+ onClick={() => setSelectedCalendarDate(startOfDay(date))}
557
+ 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'}`}
558
+ >
559
  <div className={`text-xs font-medium mb-2 ${isSameDay(date, new Date()) ? 'text-primary' : 'text-muted-foreground'}`}>
560
  {date.toLocaleDateString(undefined, { weekday: 'short', month: 'numeric', day: 'numeric' })}
561
  </div>
562
  <div className="space-y-1">
563
+ {jobs.slice(0, 4).map((row) => (
564
+ <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}>
565
+ {new Date(row.atMs).toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit' })} {row.job.name}
566
  </div>
567
  ))}
568
  {jobs.length > 4 && (
569
  <div className="text-xs text-muted-foreground">+{jobs.length - 4} more</div>
570
  )}
571
  </div>
572
+ </button>
573
  ))}
574
  </div>
575
  )}
 
581
  return (
582
  <div
583
  key={`month-${date.toISOString()}`}
584
+ onClick={() => setSelectedCalendarDate(startOfDay(date))}
585
+ 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'}`}
586
  >
587
  <div className={`text-xs mb-1 ${isSameDay(date, new Date()) ? 'text-primary font-semibold' : inCurrentMonth ? 'text-foreground' : 'text-muted-foreground'}`}>
588
  {date.getDate()}
589
  </div>
590
  <div className="space-y-1">
591
+ {jobs.slice(0, 2).map((row) => (
592
+ <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}>
593
+ {row.job.name}
594
  </div>
595
  ))}
596
  {jobs.length > 2 && <div className="text-[11px] text-muted-foreground">+{jobs.length - 2}</div>}
 
600
  })}
601
  </div>
602
  )}
603
+
604
+ {calendarView !== 'agenda' && (
605
+ <div className="border border-border rounded-lg p-3">
606
+ <div className="flex items-center justify-between mb-2">
607
+ <h3 className="text-sm font-medium text-foreground">
608
+ {selectedCalendarDate.toLocaleDateString(undefined, { weekday: 'long', month: 'short', day: 'numeric', year: 'numeric' })}
609
+ </h3>
610
+ <span className="text-xs text-muted-foreground">{selectedDayJobs.length} jobs</span>
611
+ </div>
612
+ {selectedDayJobs.length === 0 ? (
613
+ <div className="text-sm text-muted-foreground">No jobs scheduled on this date.</div>
614
+ ) : (
615
+ <div className="space-y-2">
616
+ {selectedDayJobs.map((row) => (
617
+ <button
618
+ key={`selected-day-${row.job.id || row.job.name}-${row.atMs}`}
619
+ onClick={() => handleJobSelect(row.job)}
620
+ className="w-full text-left p-2 rounded border border-border bg-secondary/40 hover:bg-secondary transition-colors"
621
+ >
622
+ <div className="text-sm font-medium text-foreground">{row.job.name}</div>
623
+ <div className="text-xs text-muted-foreground">
624
+ {new Date(row.atMs).toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit' })} · {row.job.agentId || 'system'}
625
+ </div>
626
+ </button>
627
+ ))}
628
+ </div>
629
+ )}
630
+ </div>
631
+ )}
632
  </div>
633
  </div>
634
 
src/components/panels/memory-browser-panel.tsx CHANGED
@@ -356,6 +356,9 @@ export function MemoryBrowserPanel() {
356
  ? 'Browse and manage local knowledge files and memory'
357
  : 'Explore knowledge files and memory structure'}
358
  </p>
 
 
 
359
 
360
  {/* Tab Navigation */}
361
  <div className="flex gap-2 mt-4">
 
356
  ? 'Browse and manage local knowledge files and memory'
357
  : 'Explore knowledge files and memory structure'}
358
  </p>
359
+ <p className="text-xs text-muted-foreground mt-1">
360
+ This page shows all workspace memory files. The agent profile Memory tab only edits that single agent&apos;s working memory.
361
+ </p>
362
 
363
  {/* Tab Navigation */}
364
  <div className="flex gap-2 mt-4">
src/components/panels/multi-gateway-panel.tsx CHANGED
@@ -35,12 +35,23 @@ interface DirectConnection {
35
  agent_role: string
36
  }
37
 
 
 
 
 
 
 
 
 
 
 
38
  export function MultiGatewayPanel() {
39
  const [gateways, setGateways] = useState<Gateway[]>([])
40
  const [directConnections, setDirectConnections] = useState<DirectConnection[]>([])
41
  const [loading, setLoading] = useState(true)
42
  const [showAdd, setShowAdd] = useState(false)
43
  const [probing, setProbing] = useState<number | null>(null)
 
44
  const { connection } = useMissionControl()
45
  const { connect } = useWebSocket()
46
 
@@ -89,7 +100,14 @@ export function MultiGatewayPanel() {
89
 
90
  const probeAll = async () => {
91
  try {
92
- await fetch("/api/gateways/health", { method: "POST" })
 
 
 
 
 
 
 
93
  } catch { /* ignore */ }
94
  fetchGateways()
95
  }
@@ -172,6 +190,7 @@ export function MultiGatewayPanel() {
172
  <GatewayCard
173
  key={gw.id}
174
  gateway={gw}
 
175
  isProbing={probing === gw.id}
176
  isCurrentlyConnected={connection.url?.includes(`:${gw.port}`) ?? false}
177
  onSetPrimary={() => setPrimary(gw)}
@@ -250,8 +269,9 @@ export function MultiGatewayPanel() {
250
  )
251
  }
252
 
253
- function GatewayCard({ gateway, isProbing, isCurrentlyConnected, onSetPrimary, onDelete, onConnect, onProbe }: {
254
  gateway: Gateway
 
255
  isProbing: boolean
256
  isCurrentlyConnected: boolean
257
  onSetPrimary: () => void
@@ -269,6 +289,7 @@ function GatewayCard({ gateway, isProbing, isCurrentlyConnected, onSetPrimary, o
269
  const lastSeen = gateway.last_seen
270
  ? new Date(gateway.last_seen * 1000).toLocaleString()
271
  : 'Never probed'
 
272
 
273
  return (
274
  <div className={`bg-card border rounded-lg p-4 transition-smooth ${
@@ -296,6 +317,16 @@ function GatewayCard({ gateway, isProbing, isCurrentlyConnected, onSetPrimary, o
296
  {gateway.latency != null && <span>Latency: {gateway.latency}ms</span>}
297
  <span>Last: {lastSeen}</span>
298
  </div>
 
 
 
 
 
 
 
 
 
 
299
  </div>
300
  <div className="flex items-center gap-1.5 shrink-0 flex-wrap justify-end">
301
  <button
 
35
  agent_role: string
36
  }
37
 
38
+ interface GatewayHealthProbe {
39
+ id: number
40
+ name: string
41
+ status: 'online' | 'offline' | 'error'
42
+ latency: number | null
43
+ gateway_version?: string | null
44
+ compatibility_warning?: string
45
+ error?: string
46
+ }
47
+
48
  export function MultiGatewayPanel() {
49
  const [gateways, setGateways] = useState<Gateway[]>([])
50
  const [directConnections, setDirectConnections] = useState<DirectConnection[]>([])
51
  const [loading, setLoading] = useState(true)
52
  const [showAdd, setShowAdd] = useState(false)
53
  const [probing, setProbing] = useState<number | null>(null)
54
+ const [healthByGatewayId, setHealthByGatewayId] = useState<Map<number, GatewayHealthProbe>>(new Map())
55
  const { connection } = useMissionControl()
56
  const { connect } = useWebSocket()
57
 
 
100
 
101
  const probeAll = async () => {
102
  try {
103
+ const res = await fetch("/api/gateways/health", { method: "POST" })
104
+ const data = await res.json().catch(() => ({}))
105
+ const rows = Array.isArray(data?.results) ? data.results as GatewayHealthProbe[] : []
106
+ const mapped = new Map<number, GatewayHealthProbe>()
107
+ for (const row of rows) {
108
+ if (typeof row?.id === 'number') mapped.set(row.id, row)
109
+ }
110
+ setHealthByGatewayId(mapped)
111
  } catch { /* ignore */ }
112
  fetchGateways()
113
  }
 
190
  <GatewayCard
191
  key={gw.id}
192
  gateway={gw}
193
+ health={healthByGatewayId.get(gw.id)}
194
  isProbing={probing === gw.id}
195
  isCurrentlyConnected={connection.url?.includes(`:${gw.port}`) ?? false}
196
  onSetPrimary={() => setPrimary(gw)}
 
269
  )
270
  }
271
 
272
+ function GatewayCard({ gateway, health, isProbing, isCurrentlyConnected, onSetPrimary, onDelete, onConnect, onProbe }: {
273
  gateway: Gateway
274
+ health?: GatewayHealthProbe
275
  isProbing: boolean
276
  isCurrentlyConnected: boolean
277
  onSetPrimary: () => void
 
289
  const lastSeen = gateway.last_seen
290
  ? new Date(gateway.last_seen * 1000).toLocaleString()
291
  : 'Never probed'
292
+ const compatibilityWarning = health?.compatibility_warning
293
 
294
  return (
295
  <div className={`bg-card border rounded-lg p-4 transition-smooth ${
 
317
  {gateway.latency != null && <span>Latency: {gateway.latency}ms</span>}
318
  <span>Last: {lastSeen}</span>
319
  </div>
320
+ {health?.gateway_version && (
321
+ <div className="mt-1 text-2xs text-muted-foreground">
322
+ Gateway version: <span className="font-mono text-foreground/80">{health.gateway_version}</span>
323
+ </div>
324
+ )}
325
+ {compatibilityWarning && (
326
+ <div className="mt-1.5 text-2xs rounded border border-amber-500/30 bg-amber-500/10 text-amber-300 px-2 py-1">
327
+ {compatibilityWarning}
328
+ </div>
329
+ )}
330
  </div>
331
  <div className="flex items-center gap-1.5 shrink-0 flex-wrap justify-end">
332
  <button
src/components/panels/super-admin-panel.tsx CHANGED
@@ -461,6 +461,9 @@ export function SuperAdminPanel() {
461
  </button>
462
  {createExpanded && (
463
  <div className="p-4 space-y-3">
 
 
 
464
  {gatewayLoadError && (
465
  <div className="px-3 py-2 rounded-md text-xs border bg-amber-500/10 text-amber-300 border-amber-500/20">
466
  Gateway list unavailable: {gatewayLoadError}. Using fallback owner value.
 
461
  </button>
462
  {createExpanded && (
463
  <div className="p-4 space-y-3">
464
+ <div className="text-xs text-muted-foreground">
465
+ Add a new workspace/client instance here. Fill the form below and click <span className="text-foreground font-medium">Create + Queue</span>.
466
+ </div>
467
  {gatewayLoadError && (
468
  <div className="px-3 py-2 rounded-md text-xs border bg-amber-500/10 text-amber-300 border-amber-500/20">
469
  Gateway list unavailable: {gatewayLoadError}. Using fallback owner value.
src/components/panels/task-board-panel.tsx CHANGED
@@ -1,6 +1,7 @@
1
  'use client'
2
 
3
  import { useState, useEffect, useCallback, useRef } from 'react'
 
4
  import { useMissionControl } from '@/store'
5
  import { useSmartPoll } from '@/lib/use-smart-poll'
6
 
@@ -73,6 +74,9 @@ const priorityColors: Record<string, string> = {
73
 
74
  export function TaskBoardPanel() {
75
  const { tasks: storeTasks, setTasks: storeSetTasks, selectedTask, setSelectedTask } = useMissionControl()
 
 
 
76
  const [agents, setAgents] = useState<Agent[]>([])
77
  const [loading, setLoading] = useState(true)
78
  const [error, setError] = useState<string | null>(null)
@@ -81,6 +85,23 @@ export function TaskBoardPanel() {
81
  const [showCreateModal, setShowCreateModal] = useState(false)
82
  const [editingTask, setEditingTask] = useState<Task | null>(null)
83
  const dragCounter = useRef(0)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84
 
85
  // Augment store tasks with aegisApproved flag (computed, not stored)
86
  const tasks: Task[] = storeTasks.map(t => ({
@@ -142,6 +163,26 @@ export function TaskBoardPanel() {
142
  fetchData()
143
  }, [fetchData])
144
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
145
  // Poll as SSE fallback — pauses when SSE is delivering events
146
  useSmartPoll(fetchData, 30000, { pauseWhenSseConnected: true })
147
 
@@ -348,8 +389,17 @@ export function TaskBoardPanel() {
348
  tabIndex={0}
349
  aria-label={`${task.title}, ${task.priority} priority, ${task.status}`}
350
  onDragStart={(e) => handleDragStart(e, task)}
351
- onClick={() => setSelectedTask(task)}
352
- onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); setSelectedTask(task) } }}
 
 
 
 
 
 
 
 
 
353
  className={`bg-surface-1 rounded-lg p-3 cursor-pointer hover:bg-surface-2 transition-smooth border-l-4 ${priorityColors[task.priority]} ${
354
  draggedTask?.id === task.id ? 'opacity-50' : ''
355
  }`}
@@ -446,11 +496,15 @@ export function TaskBoardPanel() {
446
  <TaskDetailModal
447
  task={selectedTask}
448
  agents={agents}
449
- onClose={() => setSelectedTask(null)}
 
 
 
450
  onUpdate={fetchData}
451
  onEdit={(taskToEdit) => {
452
  setEditingTask(taskToEdit)
453
  setSelectedTask(null)
 
454
  }}
455
  />
456
  )}
 
1
  'use client'
2
 
3
  import { useState, useEffect, useCallback, useRef } from 'react'
4
+ import { usePathname, useRouter, useSearchParams } from 'next/navigation'
5
  import { useMissionControl } from '@/store'
6
  import { useSmartPoll } from '@/lib/use-smart-poll'
7
 
 
74
 
75
  export function TaskBoardPanel() {
76
  const { tasks: storeTasks, setTasks: storeSetTasks, selectedTask, setSelectedTask } = useMissionControl()
77
+ const router = useRouter()
78
+ const pathname = usePathname()
79
+ const searchParams = useSearchParams()
80
  const [agents, setAgents] = useState<Agent[]>([])
81
  const [loading, setLoading] = useState(true)
82
  const [error, setError] = useState<string | null>(null)
 
85
  const [showCreateModal, setShowCreateModal] = useState(false)
86
  const [editingTask, setEditingTask] = useState<Task | null>(null)
87
  const dragCounter = useRef(0)
88
+ const selectedTaskIdFromUrl = Number.parseInt(searchParams.get('taskId') || '', 10)
89
+
90
+ const updateTaskUrl = useCallback((taskId: number | null, mode: 'push' | 'replace' = 'push') => {
91
+ const params = new URLSearchParams(searchParams.toString())
92
+ if (typeof taskId === 'number' && Number.isFinite(taskId)) {
93
+ params.set('taskId', String(taskId))
94
+ } else {
95
+ params.delete('taskId')
96
+ }
97
+ const query = params.toString()
98
+ const href = query ? `${pathname}?${query}` : pathname
99
+ if (mode === 'replace') {
100
+ router.replace(href)
101
+ return
102
+ }
103
+ router.push(href)
104
+ }, [pathname, router, searchParams])
105
 
106
  // Augment store tasks with aegisApproved flag (computed, not stored)
107
  const tasks: Task[] = storeTasks.map(t => ({
 
163
  fetchData()
164
  }, [fetchData])
165
 
166
+ useEffect(() => {
167
+ if (!Number.isFinite(selectedTaskIdFromUrl)) {
168
+ if (selectedTask) setSelectedTask(null)
169
+ return
170
+ }
171
+
172
+ const match = tasks.find((task) => task.id === selectedTaskIdFromUrl)
173
+ if (match) {
174
+ if (selectedTask?.id !== match.id) {
175
+ setSelectedTask(match)
176
+ }
177
+ return
178
+ }
179
+
180
+ if (!loading) {
181
+ setError(`Task #${selectedTaskIdFromUrl} not found in current workspace`)
182
+ setSelectedTask(null)
183
+ }
184
+ }, [loading, selectedTask, selectedTaskIdFromUrl, setSelectedTask, tasks])
185
+
186
  // Poll as SSE fallback — pauses when SSE is delivering events
187
  useSmartPoll(fetchData, 30000, { pauseWhenSseConnected: true })
188
 
 
389
  tabIndex={0}
390
  aria-label={`${task.title}, ${task.priority} priority, ${task.status}`}
391
  onDragStart={(e) => handleDragStart(e, task)}
392
+ onClick={() => {
393
+ setSelectedTask(task)
394
+ updateTaskUrl(task.id)
395
+ }}
396
+ onKeyDown={(e) => {
397
+ if (e.key === 'Enter' || e.key === ' ') {
398
+ e.preventDefault()
399
+ setSelectedTask(task)
400
+ updateTaskUrl(task.id)
401
+ }
402
+ }}
403
  className={`bg-surface-1 rounded-lg p-3 cursor-pointer hover:bg-surface-2 transition-smooth border-l-4 ${priorityColors[task.priority]} ${
404
  draggedTask?.id === task.id ? 'opacity-50' : ''
405
  }`}
 
496
  <TaskDetailModal
497
  task={selectedTask}
498
  agents={agents}
499
+ onClose={() => {
500
+ setSelectedTask(null)
501
+ updateTaskUrl(null)
502
+ }}
503
  onUpdate={fetchData}
504
  onEdit={(taskToEdit) => {
505
  setEditingTask(taskToEdit)
506
  setSelectedTask(null)
507
+ updateTaskUrl(null, 'replace')
508
  }}
509
  />
510
  )}
src/lib/__tests__/auth.test.ts CHANGED
@@ -105,4 +105,23 @@ describe('requireRole', () => {
105
  )
106
  expect(result.user).toBeDefined()
107
  })
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
108
  })
 
105
  )
106
  expect(result.user).toBeDefined()
107
  })
108
+
109
+ it('accepts Authorization Bearer API key', () => {
110
+ const result = requireRole(
111
+ makeRequest({ authorization: 'Bearer test-api-key-secret' }),
112
+ 'admin',
113
+ )
114
+ expect(result.user).toBeDefined()
115
+ expect(result.user!.username).toBe('api')
116
+ })
117
+
118
+ it('rejects API key auth when API_KEY is not configured', () => {
119
+ process.env = { ...originalEnv, API_KEY: '' }
120
+ const result = requireRole(
121
+ makeRequest({ 'x-api-key': 'test-api-key-secret' }),
122
+ 'viewer',
123
+ )
124
+ expect(result.status).toBe(401)
125
+ expect(result.user).toBeUndefined()
126
+ })
127
  })
src/lib/__tests__/cron-occurrences.test.ts ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { describe, expect, it } from 'vitest'
2
+ import { buildDayKey, getCronOccurrences } from '@/lib/cron-occurrences'
3
+
4
+ describe('buildDayKey', () => {
5
+ it('formats YYYY-MM-DD in local time', () => {
6
+ const date = new Date(2026, 2, 4, 9, 15, 0, 0)
7
+ expect(buildDayKey(date)).toBe('2026-03-04')
8
+ })
9
+ })
10
+
11
+ describe('getCronOccurrences', () => {
12
+ it('expands daily schedule across range', () => {
13
+ const start = new Date(2026, 2, 1, 0, 0, 0, 0).getTime()
14
+ const end = new Date(2026, 2, 5, 0, 0, 0, 0).getTime()
15
+ const rows = getCronOccurrences('0 0 * * *', start, end)
16
+ expect(rows).toHaveLength(4)
17
+ expect(rows.map((r) => r.dayKey)).toEqual([
18
+ '2026-03-01',
19
+ '2026-03-02',
20
+ '2026-03-03',
21
+ '2026-03-04',
22
+ ])
23
+ })
24
+
25
+ it('supports step values', () => {
26
+ const start = new Date(2026, 2, 1, 0, 0, 0, 0).getTime()
27
+ const end = new Date(2026, 2, 1, 3, 0, 0, 0).getTime()
28
+ const rows = getCronOccurrences('*/30 * * * *', start, end)
29
+ expect(rows).toHaveLength(6)
30
+ })
31
+
32
+ it('ignores OpenClaw timezone suffix in display schedule', () => {
33
+ const start = new Date(2026, 2, 1, 0, 0, 0, 0).getTime()
34
+ const end = new Date(2026, 2, 2, 0, 0, 0, 0).getTime()
35
+ const rows = getCronOccurrences('0 6 * * * (UTC)', start, end)
36
+ expect(rows).toHaveLength(1)
37
+ })
38
+
39
+ it('returns empty list for invalid cron', () => {
40
+ const start = new Date(2026, 2, 1, 0, 0, 0, 0).getTime()
41
+ const end = new Date(2026, 2, 2, 0, 0, 0, 0).getTime()
42
+ expect(getCronOccurrences('invalid', start, end)).toEqual([])
43
+ })
44
+ })
src/lib/auth.ts CHANGED
@@ -277,8 +277,9 @@ export function getUserFromRequest(request: Request): User | null {
277
  }
278
 
279
  // Check API key - return synthetic user
280
- const apiKey = request.headers.get('x-api-key')
281
- if (apiKey && safeCompare(apiKey, process.env.API_KEY || '')) {
 
282
  return {
283
  id: 0,
284
  username: 'api',
@@ -294,6 +295,24 @@ export function getUserFromRequest(request: Request): User | null {
294
  return null
295
  }
296
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
297
  /**
298
  * Role hierarchy levels for access control.
299
  * viewer < operator < admin
 
277
  }
278
 
279
  // Check API key - return synthetic user
280
+ const configuredApiKey = (process.env.API_KEY || '').trim()
281
+ const apiKey = extractApiKeyFromHeaders(request.headers)
282
+ if (configuredApiKey && apiKey && safeCompare(apiKey, configuredApiKey)) {
283
  return {
284
  id: 0,
285
  username: 'api',
 
295
  return null
296
  }
297
 
298
+ function extractApiKeyFromHeaders(headers: Headers): string | null {
299
+ const direct = (headers.get('x-api-key') || '').trim()
300
+ if (direct) return direct
301
+
302
+ const authorization = (headers.get('authorization') || '').trim()
303
+ if (!authorization) return null
304
+
305
+ const [scheme, ...rest] = authorization.split(/\s+/)
306
+ if (!scheme || rest.length === 0) return null
307
+
308
+ const normalized = scheme.toLowerCase()
309
+ if (normalized === 'bearer' || normalized === 'apikey' || normalized === 'token') {
310
+ return rest.join(' ').trim() || null
311
+ }
312
+
313
+ return null
314
+ }
315
+
316
  /**
317
  * Role hierarchy levels for access control.
318
  * viewer < operator < admin
src/lib/cron-occurrences.ts ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ export interface CronOccurrence {
2
+ atMs: number
3
+ dayKey: string
4
+ }
5
+
6
+ interface ParsedField {
7
+ any: boolean
8
+ matches: (value: number) => boolean
9
+ }
10
+
11
+ interface ParsedCron {
12
+ minute: ParsedField
13
+ hour: ParsedField
14
+ dayOfMonth: ParsedField
15
+ month: ParsedField
16
+ dayOfWeek: ParsedField
17
+ }
18
+
19
+ function normalizeCronExpression(raw: string): string {
20
+ const trimmed = raw.trim()
21
+ const tzSuffixMatch = trimmed.match(/^(.*)\s+\([^)]+\)$/)
22
+ return (tzSuffixMatch?.[1] || trimmed).trim()
23
+ }
24
+
25
+ function parseToken(token: string, min: number, max: number): { any: boolean; values: Set<number> } {
26
+ const valueSet = new Set<number>()
27
+ const trimmed = token.trim()
28
+ if (trimmed === '*') {
29
+ for (let i = min; i <= max; i += 1) valueSet.add(i)
30
+ return { any: true, values: valueSet }
31
+ }
32
+
33
+ for (const part of trimmed.split(',')) {
34
+ const section = part.trim()
35
+ if (!section) continue
36
+
37
+ const [rangePart, stepPart] = section.split('/')
38
+ const step = stepPart ? Number(stepPart) : 1
39
+ if (!Number.isFinite(step) || step <= 0) continue
40
+
41
+ if (rangePart === '*') {
42
+ for (let i = min; i <= max; i += step) valueSet.add(i)
43
+ continue
44
+ }
45
+
46
+ if (rangePart.includes('-')) {
47
+ const [fromRaw, toRaw] = rangePart.split('-')
48
+ const from = Number(fromRaw)
49
+ const to = Number(toRaw)
50
+ if (!Number.isFinite(from) || !Number.isFinite(to)) continue
51
+ const start = Math.max(min, Math.min(max, from))
52
+ const end = Math.max(min, Math.min(max, to))
53
+ for (let i = start; i <= end; i += step) valueSet.add(i)
54
+ continue
55
+ }
56
+
57
+ const single = Number(rangePart)
58
+ if (!Number.isFinite(single)) continue
59
+ if (single >= min && single <= max) valueSet.add(single)
60
+ }
61
+
62
+ return { any: false, values: valueSet }
63
+ }
64
+
65
+ function parseField(token: string, min: number, max: number): ParsedField {
66
+ const parsed = parseToken(token, min, max)
67
+ return {
68
+ any: parsed.any,
69
+ matches: (value: number) => parsed.values.has(value),
70
+ }
71
+ }
72
+
73
+ function parseCron(raw: string): ParsedCron | null {
74
+ const normalized = normalizeCronExpression(raw)
75
+ const parts = normalized.split(/\s+/).filter(Boolean)
76
+ if (parts.length !== 5) return null
77
+
78
+ return {
79
+ minute: parseField(parts[0], 0, 59),
80
+ hour: parseField(parts[1], 0, 23),
81
+ dayOfMonth: parseField(parts[2], 1, 31),
82
+ month: parseField(parts[3], 1, 12),
83
+ dayOfWeek: parseField(parts[4], 0, 6),
84
+ }
85
+ }
86
+
87
+ function matchesDay(parsed: ParsedCron, date: Date): boolean {
88
+ const dayOfMonthMatches = parsed.dayOfMonth.matches(date.getDate())
89
+ const dayOfWeekMatches = parsed.dayOfWeek.matches(date.getDay())
90
+
91
+ if (parsed.dayOfMonth.any && parsed.dayOfWeek.any) return true
92
+ if (parsed.dayOfMonth.any) return dayOfWeekMatches
93
+ if (parsed.dayOfWeek.any) return dayOfMonthMatches
94
+ return dayOfMonthMatches || dayOfWeekMatches
95
+ }
96
+
97
+ export function buildDayKey(date: Date): string {
98
+ const year = date.getFullYear()
99
+ const month = String(date.getMonth() + 1).padStart(2, '0')
100
+ const day = String(date.getDate()).padStart(2, '0')
101
+ return `${year}-${month}-${day}`
102
+ }
103
+
104
+ export function getCronOccurrences(
105
+ schedule: string,
106
+ rangeStartMs: number,
107
+ rangeEndMs: number,
108
+ max = 1000
109
+ ): CronOccurrence[] {
110
+ if (!schedule || !Number.isFinite(rangeStartMs) || !Number.isFinite(rangeEndMs)) return []
111
+ if (rangeEndMs <= rangeStartMs || max <= 0) return []
112
+
113
+ const parsed = parseCron(schedule)
114
+ if (!parsed) return []
115
+
116
+ const occurrences: CronOccurrence[] = []
117
+ const cursor = new Date(rangeStartMs)
118
+ cursor.setSeconds(0, 0)
119
+ if (cursor.getTime() < rangeStartMs) {
120
+ cursor.setMinutes(cursor.getMinutes() + 1, 0, 0)
121
+ }
122
+
123
+ while (cursor.getTime() < rangeEndMs && occurrences.length < max) {
124
+ if (
125
+ parsed.month.matches(cursor.getMonth() + 1) &&
126
+ matchesDay(parsed, cursor) &&
127
+ parsed.hour.matches(cursor.getHours()) &&
128
+ parsed.minute.matches(cursor.getMinutes())
129
+ ) {
130
+ occurrences.push({
131
+ atMs: cursor.getTime(),
132
+ dayKey: buildDayKey(cursor),
133
+ })
134
+ }
135
+ cursor.setMinutes(cursor.getMinutes() + 1, 0, 0)
136
+ }
137
+
138
+ return occurrences
139
+ }
src/lib/websocket.ts CHANGED
@@ -16,6 +16,7 @@ const log = createClientLogger('WebSocket')
16
 
17
  // Gateway protocol version (v3 required by OpenClaw 2026.x)
18
  const PROTOCOL_VERSION = 3
 
19
 
20
  // Heartbeat configuration
21
  const PING_INTERVAL_MS = 30_000
@@ -182,7 +183,7 @@ export function useWebSocket() {
182
 
183
  const cachedToken = getCachedDeviceToken()
184
 
185
- const clientId = 'gateway-client'
186
  const clientMode = 'ui'
187
  const role = 'operator'
188
  const scopes = ['operator.admin']
 
16
 
17
  // Gateway protocol version (v3 required by OpenClaw 2026.x)
18
  const PROTOCOL_VERSION = 3
19
+ const DEFAULT_GATEWAY_CLIENT_ID = process.env.NEXT_PUBLIC_GATEWAY_CLIENT_ID || 'control-ui'
20
 
21
  // Heartbeat configuration
22
  const PING_INTERVAL_MS = 30_000
 
183
 
184
  const cachedToken = getCachedDeviceToken()
185
 
186
+ const clientId = DEFAULT_GATEWAY_CLIENT_ID
187
  const clientMode = 'ui'
188
  const role = 'operator'
189
  const scopes = ['operator.admin']
src/proxy.ts CHANGED
@@ -52,6 +52,22 @@ function applySecurityHeaders(response: NextResponse): NextResponse {
52
  return response
53
  }
54
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
  export function proxy(request: NextRequest) {
56
  // Network access control.
57
  // In production: default-deny unless explicitly allowed.
@@ -63,7 +79,8 @@ export function proxy(request: NextRequest) {
63
  .map((s) => s.trim())
64
  .filter(Boolean)
65
 
66
- const isAllowedHost = allowAnyHost || allowedPatterns.some((p) => hostMatches(p, hostName))
 
67
 
68
  if (!isAllowedHost) {
69
  return new NextResponse('Forbidden', { status: 403 })
@@ -97,8 +114,10 @@ export function proxy(request: NextRequest) {
97
 
98
  // API routes: accept session cookie OR API key
99
  if (pathname.startsWith('/api/')) {
100
- const apiKey = request.headers.get('x-api-key')
101
- if (sessionToken || (apiKey && safeCompare(apiKey, process.env.API_KEY || ''))) {
 
 
102
  return applySecurityHeaders(NextResponse.next())
103
  }
104
 
 
52
  return response
53
  }
54
 
55
+ function extractApiKeyFromRequest(request: NextRequest): string {
56
+ const direct = (request.headers.get('x-api-key') || '').trim()
57
+ if (direct) return direct
58
+
59
+ const authorization = (request.headers.get('authorization') || '').trim()
60
+ if (!authorization) return ''
61
+
62
+ const [scheme, ...rest] = authorization.split(/\s+/)
63
+ if (!scheme || rest.length === 0) return ''
64
+ const normalized = scheme.toLowerCase()
65
+ if (normalized === 'bearer' || normalized === 'apikey' || normalized === 'token') {
66
+ return rest.join(' ').trim()
67
+ }
68
+ return ''
69
+ }
70
+
71
  export function proxy(request: NextRequest) {
72
  // Network access control.
73
  // In production: default-deny unless explicitly allowed.
 
79
  .map((s) => s.trim())
80
  .filter(Boolean)
81
 
82
+ const enforceAllowlist = !allowAnyHost && allowedPatterns.length > 0
83
+ const isAllowedHost = !enforceAllowlist || allowedPatterns.some((p) => hostMatches(p, hostName))
84
 
85
  if (!isAllowedHost) {
86
  return new NextResponse('Forbidden', { status: 403 })
 
114
 
115
  // API routes: accept session cookie OR API key
116
  if (pathname.startsWith('/api/')) {
117
+ const configuredApiKey = (process.env.API_KEY || '').trim()
118
+ const apiKey = extractApiKeyFromRequest(request)
119
+ const hasValidApiKey = Boolean(configuredApiKey && apiKey && safeCompare(apiKey, configuredApiKey))
120
+ if (sessionToken || hasValidApiKey) {
121
  return applySecurityHeaders(NextResponse.next())
122
  }
123