Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,15 @@ jobs:
NEXT_PUBLIC_CONTROL_PLANE_URL: http://localhost:8080
NEXT_PUBLIC_CONTROL_PLANE_WS_URL: ws://localhost:8080/v1/ui/stream

- name: Test
run: pnpm test:ci

- name: Install Playwright browser
run: pnpm exec playwright install --with-deps chromium

- name: Dashboard smoke
run: pnpm test:smoke:dashboard

go:
name: Go tests
runs-on: ubuntu-latest
Expand Down
59 changes: 48 additions & 11 deletions agents/agentd/internal/ws/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,12 @@ import (
"github.com/gorilla/websocket"
)

const (
writeWait = 10 * time.Second
pongWait = 75 * time.Second
pingPeriod = 30 * time.Second
)

type MessageHandler func(msgType string, payload json.RawMessage)

type Client struct {
Expand Down Expand Up @@ -75,13 +81,19 @@ func (c *Client) Connect() error {
return fmt.Errorf("failed to connect: %w", err)
}

_ = conn.SetReadDeadline(time.Now().Add(pongWait))
conn.SetPongHandler(func(string) error {
return conn.SetReadDeadline(time.Now().Add(pongWait))
})

c.conn = conn
c.reconnecting = false
metrics.SetWSConnected(true)
metrics.SetWSReconnecting(false)

// Start reader goroutine
go c.reader()
go c.reader(conn)
go c.pinger(conn)

if c.onConnect != nil {
go c.onConnect()
Expand All @@ -90,11 +102,12 @@ func (c *Client) Connect() error {
return nil
}

func (c *Client) reader() {
func (c *Client) reader(conn *websocket.Conn) {
defer func() {
c.mu.Lock()
if c.conn != nil {
if c.conn == conn {
c.conn.Close()
c.conn = nil
}
c.mu.Unlock()

Expand All @@ -111,14 +124,6 @@ func (c *Client) reader() {
default:
}

c.mu.Lock()
conn := c.conn
c.mu.Unlock()

if conn == nil {
return
}

_, message, err := conn.ReadMessage()
if err != nil {
log.Printf("WebSocket read error: %v", err)
Expand Down Expand Up @@ -170,6 +175,36 @@ func (c *Client) reader() {
}
}

func (c *Client) pinger(conn *websocket.Conn) {
ticker := time.NewTicker(pingPeriod)
defer ticker.Stop()

for {
select {
case <-c.done:
return
case <-ticker.C:
}

c.mu.Lock()
current := c.conn
c.mu.Unlock()
if current != conn || conn == nil {
return
}

if err := conn.WriteControl(
websocket.PingMessage,
[]byte("keepalive"),
time.Now().Add(writeWait),
); err != nil {
log.Printf("WebSocket ping error: %v", err)
_ = conn.Close()
return
}
}
}

func (c *Client) reconnect() {
c.mu.Lock()
if c.reconnecting {
Expand Down Expand Up @@ -255,6 +290,7 @@ func (c *Client) Send(msgType string, payload any) error {
return fmt.Errorf("failed to marshal message: %w", err)
}

_ = c.conn.SetWriteDeadline(time.Now().Add(writeWait))
return c.conn.WriteMessage(websocket.TextMessage, data)
}

Expand Down Expand Up @@ -300,6 +336,7 @@ func (c *Client) ResendQueued() {
c.mu.Unlock()
return
}
_ = conn.SetWriteDeadline(time.Now().Add(writeWait))
err = conn.WriteMessage(websocket.TextMessage, data)
c.mu.Unlock()
if err != nil {
Expand Down
5 changes: 4 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
"dev": "turbo dev",
"build": "turbo build",
"test": "turbo test",
"test:ci": "turbo test",
"test:smoke:dashboard": "playwright test -c playwright.dashboard.config.ts",
"lint": "turbo lint",
"db:migrate": "pnpm --filter @agent-command/control-plane db:migrate",
"format": "prettier --write \"**/*.{ts,tsx,js,jsx,json,md}\"",
Expand All @@ -21,7 +23,8 @@
"eslint-config-next": "16.2.1",
"prettier": "^3.8.1",
"turbo": "^2.3.0",
"typescript": "^5.3.0"
"typescript": "^5.3.0",
"vitest": "^4.1.6"
},
"packageManager": "pnpm@9.15.0",
"engines": {
Expand Down
1 change: 1 addition & 0 deletions packages/ac-schema/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
"scripts": {
"build": "tsc",
"dev": "tsc --watch",
"test": "vitest run",
"typecheck": "tsc --noEmit",
"lint": "ESLINT_USE_FLAT_CONFIG=false eslint src/"
},
Expand Down
139 changes: 139 additions & 0 deletions packages/ac-schema/tests/core-workflows.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
import { describe, expect, it } from 'vitest';
import {
ApprovalDecideRequestSchema,
AutomationAgentSchema,
AutomationRunSchema,
CreateWorkItemSchema,
MemorySearchQuerySchema,
UpsertAutomationAgentSchema,
UpsertMemoryEntrySchema,
WorkItemsQuerySchema,
} from '../src/index.js';

const uuid = '11111111-1111-4111-8111-111111111111';

describe('approval schemas', () => {
it('defaults dashboard approval decisions to both hook and command behavior', () => {
const parsed = ApprovalDecideRequestSchema.parse({ decision: 'allow' });

expect(parsed).toEqual({ decision: 'allow', mode: 'both' });
});

it('accepts structured updated input for approval edits', () => {
const parsed = ApprovalDecideRequestSchema.parse({
decision: 'allow',
mode: 'hook',
payload: {
updatedInput: { command: 'pnpm test:ci' },
},
});

expect(parsed.payload?.updatedInput).toEqual({ command: 'pnpm test:ci' });
});
});

describe('memory schemas', () => {
it('bounds memory search limits for operator queries', () => {
const parsed = MemorySearchQuerySchema.parse({ q: 'approval policy', limit: '25' });

expect(parsed.limit).toBe(25);
expect(MemorySearchQuerySchema.safeParse({ q: 'approval policy', limit: 101 }).success).toBe(false);
});

it('requires durable memory content and confidence in range', () => {
expect(
UpsertMemoryEntrySchema.safeParse({
scope_type: 'repo',
tier: 'procedural',
summary: 'Run pnpm test:ci before release',
content: 'The repo has Vitest coverage for schema and control-plane auth.',
confidence: 0.9,
}).success
).toBe(true);

expect(
UpsertMemoryEntrySchema.safeParse({
scope_type: 'repo',
tier: 'procedural',
summary: '',
content: 'Missing summary should fail.',
}).success
).toBe(false);
});
});

describe('automation and work item schemas', () => {
it('keeps automation agent slugs operator-safe', () => {
expect(
UpsertAutomationAgentSchema.safeParse({
role: 'worker',
name: 'Release Builder',
slug: 'release-builder',
provider: 'claude_code',
}).success
).toBe(true);

expect(
UpsertAutomationAgentSchema.safeParse({
role: 'worker',
name: 'Release Builder',
slug: 'Release Builder',
provider: 'claude_code',
}).success
).toBe(false);
});

it('parses automation run records with default JSON containers', () => {
const parsed = AutomationRunSchema.parse({
id: uuid,
automation_agent_id: uuid,
wakeup_id: uuid,
status: 'running',
objective: 'Add CI ratchets',
});

expect(parsed.memory_snapshot_json).toEqual({});
expect(parsed.pending_followups_json).toEqual([]);
expect(parsed.usage_json).toEqual({});
});

it('defaults and bounds work item queries', () => {
const parsed = WorkItemsQuerySchema.parse({ limit: '20', status: 'queued' });

expect(parsed).toMatchObject({ limit: 20, status: 'queued' });
expect(WorkItemsQuerySchema.safeParse({ limit: 101 }).success).toBe(false);
});

it('requires actionable work item title and objective', () => {
expect(
CreateWorkItemSchema.safeParse({
title: 'Add auth tests',
objective: 'Cover service token and JWT verification.',
priority: 2,
}).success
).toBe(true);

expect(
CreateWorkItemSchema.safeParse({
title: '',
objective: 'No title should fail.',
}).success
).toBe(false);
});

it('validates persisted automation agents used by the dashboard and API', () => {
const parsed = AutomationAgentSchema.parse({
id: uuid,
user_id: uuid,
role: 'orchestrator',
name: 'Daily Operator',
slug: 'daily-operator',
status: 'active',
provider: 'codex',
max_parallel_runs: 2,
});

expect(parsed.wake_policy_json).toEqual({});
expect(parsed.worker_pool_json).toEqual({});
});
});
46 changes: 46 additions & 0 deletions playwright.dashboard.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { defineConfig, devices } from '@playwright/test';

const port = Number.parseInt(process.env.PLAYWRIGHT_DASHBOARD_PORT || '3210', 10);
const host = '127.0.0.1';
const baseURL = process.env.PLAYWRIGHT_BASE_URL || `http://${host}:${port}`;
const accessCode = process.env.PLAYWRIGHT_ACCESS_CODE || 'playwright-access';

export default defineConfig({
testDir: './tests/smoke',
timeout: 60_000,
expect: {
timeout: 10_000,
},
fullyParallel: false,
retries: process.env.CI ? 1 : 0,
reporter: process.env.CI ? [['github'], ['list']] : 'list',
use: {
...devices['Desktop Chrome'],
baseURL,
trace: 'retain-on-failure',
},
webServer: process.env.PLAYWRIGHT_BASE_URL
? undefined
: {
command: `pnpm --filter @agent-command/dashboard dev --hostname ${host} --port ${port}`,
url: `${baseURL}/signin`,
reuseExistingServer: !process.env.CI,
timeout: 120_000,
env: {
ACCESS_SECRET: accessCode,
ADMIN_EMAILS: 'admin@local.test',
AUTH_SESSION_DAYS: '1',
CONTROL_PLANE_JWT_SECRET: 'dashboard-smoke-control-plane-secret',
NEXTAUTH_SECRET: 'dashboard-smoke-nextauth-secret',
NEXTAUTH_URL: baseURL,
NEXT_PUBLIC_CONTROL_PLANE_URL: baseURL,
NEXT_PUBLIC_CONTROL_PLANE_WS_URL: `ws://${host}:${port}/v1/ui/stream`,
},
},
projects: [
{
name: 'chromium',
use: { ...devices['Desktop Chrome'] },
},
],
});
Loading
Loading