mirror of
https://github.com/BradGroux/veritas-kanban.git
synced 2026-12-03 19:27:18 +00:00
* fix: make board drag moves atomic * fix: update gitleaks docs fingerprint * fix: bound board reorder processing
516 lines
16 KiB
TypeScript
516 lines
16 KiB
TypeScript
/**
|
|
* BroadcastService Tests
|
|
* Tests WebSocket broadcast functions for task changes and telemetry.
|
|
*/
|
|
import { describe, it, expect, vi, afterEach } from 'vitest';
|
|
import type { AnyTelemetryEvent, RunSessionEvent, SquadMessage } from '@veritas-kanban/shared';
|
|
import type { WebSocketServer } from 'ws';
|
|
import {
|
|
broadcastChatMessage,
|
|
closeWebSocketClientsForRevokedCredential,
|
|
broadcastSquadEvent,
|
|
broadcastSquadMessage,
|
|
initBroadcast,
|
|
broadcastRunSessionEvent,
|
|
broadcastTaskChange,
|
|
broadcastTelemetryEvent,
|
|
broadcastWorkflowStatus,
|
|
} from '../services/broadcast-service.js';
|
|
import type { WebSocketEventChannel } from '../services/websocket-permissions.js';
|
|
|
|
type MockAuth = {
|
|
role: 'admin' | 'agent' | 'read-only';
|
|
isLocalhost: boolean;
|
|
workspaceId?: string;
|
|
apiTokenId?: string;
|
|
deviceSessionId?: string;
|
|
};
|
|
|
|
type MockClient = {
|
|
readyState: number;
|
|
auth?: MockAuth;
|
|
bufferedAmount: number;
|
|
subscribedChannels?: Set<WebSocketEventChannel>;
|
|
subscribedChatSessionIds?: Set<string>;
|
|
sent: string[];
|
|
send: (data: string) => void;
|
|
close: ReturnType<typeof vi.fn>;
|
|
};
|
|
|
|
type MockClientOptions = {
|
|
bufferedAmount?: number;
|
|
subscribedChannels?: Set<WebSocketEventChannel>;
|
|
subscribedChatSessionIds?: Set<string>;
|
|
};
|
|
|
|
// Minimal mock WebSocket server
|
|
function createMockWss() {
|
|
const sentMessages: string[] = [];
|
|
const clients = new Set<MockClient>();
|
|
|
|
return {
|
|
clients,
|
|
addClient(
|
|
readyState = 1,
|
|
auth: MockAuth = { role: 'admin', isLocalhost: false, workspaceId: 'local' },
|
|
options: MockClientOptions = {}
|
|
) {
|
|
const sent: string[] = [];
|
|
const client = {
|
|
readyState,
|
|
auth,
|
|
bufferedAmount: options.bufferedAmount ?? 0,
|
|
subscribedChannels: options.subscribedChannels,
|
|
subscribedChatSessionIds: options.subscribedChatSessionIds,
|
|
sent,
|
|
send: (data: string) => {
|
|
sent.push(data);
|
|
sentMessages.push(data);
|
|
},
|
|
close: vi.fn(),
|
|
};
|
|
clients.add(client);
|
|
return client;
|
|
},
|
|
sentMessages,
|
|
};
|
|
}
|
|
|
|
function asWebSocketServer(wss: ReturnType<typeof createMockWss>): WebSocketServer {
|
|
return wss as unknown as WebSocketServer;
|
|
}
|
|
|
|
function telemetryEvent(): AnyTelemetryEvent {
|
|
return {
|
|
type: 'run.started',
|
|
taskId: 'task_789',
|
|
agent: 'claude-code',
|
|
timestamp: '2024-01-01T00:00:00Z',
|
|
} as unknown as AnyTelemetryEvent;
|
|
}
|
|
|
|
function workflowRun(status: string) {
|
|
return {
|
|
id: 'run_123',
|
|
workflowId: 'workflow_456',
|
|
workflowVersion: 2,
|
|
taskId: 'task_789',
|
|
status,
|
|
startedAt: '2026-01-01T00:00:00Z',
|
|
completedAt: status === 'completed' ? '2026-01-01T00:00:05Z' : undefined,
|
|
steps: [
|
|
{
|
|
stepId: 'step_1',
|
|
status,
|
|
retries: 0,
|
|
},
|
|
],
|
|
};
|
|
}
|
|
|
|
function runSessionEvent(type: RunSessionEvent['type'] = 'message.sent'): RunSessionEvent {
|
|
return {
|
|
id: `run_event_${type}`,
|
|
shareId: 'run_share_721',
|
|
taskId: 'task_721',
|
|
attemptId: 'attempt_721',
|
|
type,
|
|
actor: {
|
|
id: 'editor-1',
|
|
label: 'Pair Editor',
|
|
workspaceId: 'local',
|
|
},
|
|
createdAt: '2026-06-18T10:00:00.000Z',
|
|
message: type === 'message.sent' ? 'Continue the run' : undefined,
|
|
};
|
|
}
|
|
|
|
afterEach(() => {
|
|
vi.useRealTimers();
|
|
initBroadcast(null as unknown as WebSocketServer);
|
|
});
|
|
|
|
describe('BroadcastService', () => {
|
|
describe('broadcastTaskChange()', () => {
|
|
it('should broadcast to all connected clients', () => {
|
|
const wss = createMockWss();
|
|
wss.addClient(1); // OPEN
|
|
wss.addClient(1); // OPEN
|
|
initBroadcast(asWebSocketServer(wss));
|
|
|
|
broadcastTaskChange('created', 'task_123');
|
|
|
|
expect(wss.sentMessages).toHaveLength(2);
|
|
const msg = JSON.parse(wss.sentMessages[0]);
|
|
expect(msg.type).toBe('task:changed');
|
|
expect(msg.changeType).toBe('created');
|
|
expect(msg.taskId).toBe('task_123');
|
|
expect(msg.timestamp).toBeDefined();
|
|
expect(msg.sequence).toEqual(expect.any(Number));
|
|
expect(msg.workspaceId).toBe('local');
|
|
});
|
|
|
|
it('should skip clients that are not in OPEN state', () => {
|
|
const wss = createMockWss();
|
|
wss.addClient(1); // OPEN
|
|
wss.addClient(0); // CONNECTING
|
|
wss.addClient(3); // CLOSED
|
|
initBroadcast(asWebSocketServer(wss));
|
|
|
|
broadcastTaskChange('updated', 'task_456');
|
|
|
|
expect(wss.sentMessages).toHaveLength(1);
|
|
});
|
|
|
|
it('should handle no connected clients gracefully', () => {
|
|
const wss = createMockWss();
|
|
initBroadcast(asWebSocketServer(wss));
|
|
|
|
// Should not throw
|
|
broadcastTaskChange('deleted');
|
|
expect(wss.sentMessages).toHaveLength(0);
|
|
});
|
|
|
|
it('should support all change types', () => {
|
|
const wss = createMockWss();
|
|
wss.addClient(1);
|
|
initBroadcast(asWebSocketServer(wss));
|
|
|
|
const types = [
|
|
'created',
|
|
'updated',
|
|
'deleted',
|
|
'archived',
|
|
'restored',
|
|
'reordered',
|
|
'moved',
|
|
] as const;
|
|
for (const type of types) {
|
|
broadcastTaskChange(type);
|
|
}
|
|
|
|
expect(wss.sentMessages).toHaveLength(7);
|
|
});
|
|
|
|
it('includes the originating operation ID on board move events', () => {
|
|
const wss = createMockWss();
|
|
wss.addClient(1);
|
|
initBroadcast(asWebSocketServer(wss));
|
|
|
|
broadcastTaskChange('moved', 'task_456', undefined, {
|
|
operationId: '00000000-0000-4000-8000-000000000013',
|
|
});
|
|
|
|
expect(JSON.parse(wss.sentMessages[0])).toMatchObject({
|
|
type: 'task:changed',
|
|
changeType: 'moved',
|
|
taskId: 'task_456',
|
|
operationId: '00000000-0000-4000-8000-000000000013',
|
|
});
|
|
});
|
|
|
|
it('should filter task events by client workspace', () => {
|
|
const wss = createMockWss();
|
|
wss.addClient(1, { role: 'read-only', isLocalhost: false, workspaceId: 'local' });
|
|
wss.addClient(1, { role: 'read-only', isLocalhost: false, workspaceId: 'other' });
|
|
initBroadcast(asWebSocketServer(wss));
|
|
|
|
broadcastTaskChange('updated', 'task_456');
|
|
|
|
expect(wss.sentMessages).toHaveLength(1);
|
|
});
|
|
|
|
it('should filter task events by channel subscription while preserving legacy clients', () => {
|
|
const wss = createMockWss();
|
|
const workflowOnly = wss.addClient(1, undefined, {
|
|
subscribedChannels: new Set(['workflows']),
|
|
});
|
|
const taskSubscriber = wss.addClient(1, undefined, {
|
|
subscribedChannels: new Set(['tasks']),
|
|
});
|
|
const legacySubscriber = wss.addClient(1);
|
|
initBroadcast(asWebSocketServer(wss));
|
|
|
|
broadcastTaskChange('updated', 'task_456');
|
|
|
|
expect(workflowOnly.sent).toHaveLength(0);
|
|
expect(taskSubscriber.sent).toHaveLength(1);
|
|
expect(legacySubscriber.sent).toHaveLength(1);
|
|
expect(wss.sentMessages).toHaveLength(2);
|
|
});
|
|
|
|
it('should close backpressured clients instead of sending task events', () => {
|
|
const wss = createMockWss();
|
|
const backpressuredClient = wss.addClient(1, undefined, {
|
|
bufferedAmount: 1_000_001,
|
|
subscribedChannels: new Set(['tasks']),
|
|
});
|
|
const healthyClient = wss.addClient(1, undefined, {
|
|
subscribedChannels: new Set(['tasks']),
|
|
});
|
|
initBroadcast(asWebSocketServer(wss));
|
|
|
|
broadcastTaskChange('updated', 'task_456');
|
|
|
|
expect(backpressuredClient.sent).toHaveLength(0);
|
|
expect(backpressuredClient.close).toHaveBeenCalledWith(1013, 'Client backpressure');
|
|
expect(healthyClient.sent).toHaveLength(1);
|
|
expect(wss.sentMessages).toHaveLength(1);
|
|
});
|
|
|
|
it('should batch task broadcasts across many clients', async () => {
|
|
const wss = createMockWss();
|
|
for (let index = 0; index < 75; index++) {
|
|
wss.addClient(1, undefined, { subscribedChannels: new Set(['tasks']) });
|
|
}
|
|
initBroadcast(asWebSocketServer(wss));
|
|
|
|
broadcastTaskChange('updated', 'task_456');
|
|
|
|
expect(wss.sentMessages).toHaveLength(50);
|
|
|
|
await new Promise<void>((resolve) => setImmediate(resolve));
|
|
|
|
expect(wss.sentMessages).toHaveLength(75);
|
|
});
|
|
});
|
|
|
|
describe('broadcastChatMessage()', () => {
|
|
it('delivers chat events only to clients subscribed to the matching session', () => {
|
|
const wss = createMockWss();
|
|
const sessionSubscriber = wss.addClient(1, undefined, {
|
|
subscribedChannels: new Set(['chat']),
|
|
subscribedChatSessionIds: new Set(['session_a']),
|
|
});
|
|
const otherSessionSubscriber = wss.addClient(1, undefined, {
|
|
subscribedChannels: new Set(['chat']),
|
|
subscribedChatSessionIds: new Set(['session_b']),
|
|
});
|
|
const chatChannelOnly = wss.addClient(1, undefined, {
|
|
subscribedChannels: new Set(['chat']),
|
|
});
|
|
const legacyUnsubscribed = wss.addClient(1);
|
|
initBroadcast(asWebSocketServer(wss));
|
|
|
|
broadcastChatMessage('session_a', {
|
|
type: 'chat:delta',
|
|
sessionId: 'session_a',
|
|
text: 'private response',
|
|
});
|
|
|
|
expect(sessionSubscriber.sent).toHaveLength(1);
|
|
expect(JSON.parse(sessionSubscriber.sent[0])).toMatchObject({
|
|
type: 'chat:delta',
|
|
sessionId: 'session_a',
|
|
text: 'private response',
|
|
});
|
|
expect(otherSessionSubscriber.sent).toHaveLength(0);
|
|
expect(chatChannelOnly.sent).toHaveLength(0);
|
|
expect(legacyUnsubscribed.sent).toHaveLength(0);
|
|
expect(wss.sentMessages).toHaveLength(1);
|
|
});
|
|
});
|
|
|
|
describe('broadcastSquadMessage() and broadcastSquadEvent()', () => {
|
|
it('broadcasts squad message, mention, read, pin, and reaction events to squad subscribers', () => {
|
|
const wss = createMockWss();
|
|
const squadSubscriber = wss.addClient(1, undefined, {
|
|
subscribedChannels: new Set(['squad']),
|
|
});
|
|
const taskOnly = wss.addClient(1, undefined, {
|
|
subscribedChannels: new Set(['tasks']),
|
|
});
|
|
initBroadcast(asWebSocketServer(wss));
|
|
|
|
const message: SquadMessage = {
|
|
id: 'msg_1',
|
|
agent: 'VERITAS',
|
|
message: 'Need @case review',
|
|
timestamp: '2026-01-01T00:00:00.000Z',
|
|
mentions: [{ target: 'case' }],
|
|
};
|
|
|
|
broadcastSquadMessage(message);
|
|
broadcastSquadEvent({ type: 'squad:mention', message, mentions: message.mentions });
|
|
broadcastSquadEvent({
|
|
type: 'squad:read',
|
|
actor: 'case',
|
|
readState: { actor: 'case', unreadCount: 0, mentionCount: 0 },
|
|
});
|
|
broadcastSquadEvent({ type: 'squad:pin', message: { ...message, pinned: true } });
|
|
broadcastSquadEvent({
|
|
type: 'squad:reaction',
|
|
message: {
|
|
...message,
|
|
reactions: [{ actor: 'case', reaction: 'ack', createdAt: '2026-01-01T00:00:01.000Z' }],
|
|
},
|
|
actor: 'case',
|
|
reaction: 'ack',
|
|
});
|
|
|
|
expect(squadSubscriber.sent).toHaveLength(5);
|
|
expect(taskOnly.sent).toHaveLength(0);
|
|
expect(squadSubscriber.sent.map((payload) => JSON.parse(payload).type)).toEqual([
|
|
'squad:message',
|
|
'squad:mention',
|
|
'squad:read',
|
|
'squad:pin',
|
|
'squad:reaction',
|
|
]);
|
|
});
|
|
});
|
|
|
|
describe('closeWebSocketClientsForRevokedCredential()', () => {
|
|
it('closes active clients that authenticated with a revoked API token or device session', () => {
|
|
const wss = createMockWss();
|
|
const apiTokenClient = wss.addClient(1, {
|
|
role: 'agent',
|
|
isLocalhost: false,
|
|
workspaceId: 'local',
|
|
apiTokenId: 'token_1',
|
|
});
|
|
const deviceSessionClient = wss.addClient(1, {
|
|
role: 'read-only',
|
|
isLocalhost: false,
|
|
workspaceId: 'local',
|
|
deviceSessionId: 'session_1',
|
|
});
|
|
const unrelatedClient = wss.addClient(1, {
|
|
role: 'read-only',
|
|
isLocalhost: false,
|
|
workspaceId: 'local',
|
|
apiTokenId: 'token_2',
|
|
});
|
|
initBroadcast(asWebSocketServer(wss));
|
|
|
|
expect(closeWebSocketClientsForRevokedCredential({ apiTokenId: 'token_1' })).toBe(1);
|
|
expect(closeWebSocketClientsForRevokedCredential({ deviceSessionId: 'session_1' })).toBe(1);
|
|
|
|
expect(apiTokenClient.close).toHaveBeenCalledWith(4001, 'Credential revoked');
|
|
expect(deviceSessionClient.close).toHaveBeenCalledWith(4001, 'Credential revoked');
|
|
expect(unrelatedClient.close).not.toHaveBeenCalled();
|
|
});
|
|
});
|
|
|
|
describe('broadcastTelemetryEvent()', () => {
|
|
it('should broadcast telemetry events to all connected clients', () => {
|
|
const wss = createMockWss();
|
|
wss.addClient(1);
|
|
initBroadcast(asWebSocketServer(wss));
|
|
|
|
broadcastTelemetryEvent(telemetryEvent());
|
|
|
|
expect(wss.sentMessages).toHaveLength(1);
|
|
const msg = JSON.parse(wss.sentMessages[0]);
|
|
expect(msg.type).toBe('telemetry:event');
|
|
expect(msg.event.taskId).toBe('task_789');
|
|
expect(msg.timestamp).toBeDefined();
|
|
expect(msg.sequence).toEqual(expect.any(Number));
|
|
expect(msg.workspaceId).toBe('local');
|
|
});
|
|
|
|
it('should filter telemetry events by read permission', () => {
|
|
const wss = createMockWss();
|
|
wss.addClient(1, { role: 'read-only', isLocalhost: false, workspaceId: 'local' });
|
|
wss.addClient(1, { role: 'agent', isLocalhost: false, workspaceId: 'local' });
|
|
initBroadcast(asWebSocketServer(wss));
|
|
|
|
broadcastTelemetryEvent(telemetryEvent());
|
|
|
|
expect(wss.sentMessages).toHaveLength(1);
|
|
});
|
|
|
|
it('should do nothing when wss is not initialized', () => {
|
|
initBroadcast(null as unknown as WebSocketServer);
|
|
// Should not throw
|
|
broadcastTelemetryEvent(telemetryEvent());
|
|
});
|
|
});
|
|
|
|
describe('broadcastRunSessionEvent()', () => {
|
|
it('fans out shared run session updates to subscribed same-workspace readers', () => {
|
|
const wss = createMockWss();
|
|
const firstSubscriber = wss.addClient(1, undefined, {
|
|
subscribedChannels: new Set(['run-sessions']),
|
|
});
|
|
const secondSubscriber = wss.addClient(1, undefined, {
|
|
subscribedChannels: new Set(['run-sessions']),
|
|
});
|
|
const taskOnly = wss.addClient(1, undefined, {
|
|
subscribedChannels: new Set(['tasks']),
|
|
});
|
|
const otherWorkspace = wss.addClient(
|
|
1,
|
|
{ role: 'read-only', isLocalhost: false, workspaceId: 'other' },
|
|
{ subscribedChannels: new Set(['run-sessions']) }
|
|
);
|
|
initBroadcast(asWebSocketServer(wss));
|
|
|
|
broadcastRunSessionEvent(runSessionEvent(), { workspaceId: 'local' });
|
|
|
|
expect(firstSubscriber.sent).toHaveLength(1);
|
|
expect(secondSubscriber.sent).toHaveLength(1);
|
|
expect(taskOnly.sent).toHaveLength(0);
|
|
expect(otherWorkspace.sent).toHaveLength(0);
|
|
expect(wss.sentMessages).toHaveLength(2);
|
|
expect(JSON.parse(firstSubscriber.sent[0])).toMatchObject({
|
|
type: 'run-session:event',
|
|
event: {
|
|
type: 'message.sent',
|
|
shareId: 'run_share_721',
|
|
message: 'Continue the run',
|
|
},
|
|
workspaceId: 'local',
|
|
sequence: expect.any(Number),
|
|
});
|
|
});
|
|
|
|
it('broadcasts revoke events so viewers can fail closed after access changes', () => {
|
|
const wss = createMockWss();
|
|
const subscriber = wss.addClient(1, undefined, {
|
|
subscribedChannels: new Set(['run-sessions']),
|
|
});
|
|
initBroadcast(asWebSocketServer(wss));
|
|
|
|
broadcastRunSessionEvent(runSessionEvent('share.revoked'), { workspaceId: 'local' });
|
|
|
|
expect(subscriber.sent).toHaveLength(1);
|
|
expect(JSON.parse(subscriber.sent[0]).event.type).toBe('share.revoked');
|
|
});
|
|
});
|
|
|
|
describe('broadcastWorkflowStatus()', () => {
|
|
it('should coalesce high-frequency status updates per workflow run', () => {
|
|
vi.useFakeTimers();
|
|
const wss = createMockWss();
|
|
const workflowSubscriber = wss.addClient(1, undefined, {
|
|
subscribedChannels: new Set(['workflows']),
|
|
});
|
|
initBroadcast(asWebSocketServer(wss));
|
|
|
|
broadcastWorkflowStatus(workflowRun('running'));
|
|
broadcastWorkflowStatus(workflowRun('completed'));
|
|
|
|
expect(wss.sentMessages).toHaveLength(0);
|
|
|
|
vi.advanceTimersByTime(100);
|
|
|
|
expect(workflowSubscriber.sent).toHaveLength(1);
|
|
expect(wss.sentMessages).toHaveLength(1);
|
|
const msg = JSON.parse(workflowSubscriber.sent[0]);
|
|
expect(msg.type).toBe('workflow:status');
|
|
expect(msg.sequence).toEqual(expect.any(Number));
|
|
expect(msg.workspaceId).toBe('local');
|
|
expect(msg.payload.id).toBe('run_123');
|
|
expect(msg.payload.status).toBe('completed');
|
|
expect(msg.payload.completedAt).toBe('2026-01-01T00:00:05Z');
|
|
});
|
|
});
|
|
|
|
describe('initBroadcast()', () => {
|
|
it('should accept a WebSocket server', () => {
|
|
const wss = createMockWss();
|
|
expect(() => initBroadcast(asWebSocketServer(wss))).not.toThrow();
|
|
});
|
|
});
|
|
});
|