refactor(server): move the team runtime into a postponed package (P1.1)
Team mode stays in the repository but is not built or shipped (ADR-0003). - The team server (index.ts, config, db, daemons, plugins, proactive, routes, scheduler, services, ws, drizzle migrations) and its tests move from @waggle/server to packages/team-server (@waggle/team-server, private). It keeps its own copies of the logger and the agent-group executor, so it does not import @waggle/server. @clerk/fastify, bullmq, ioredis, postgres, drizzle-orm, drizzle-kit, cron-parser and @waggle/waggle-dance leave @waggle/server; the launcher drops the same team-only dependencies. - build:packages no longer builds waggle-dance or the worker: nothing in the community edition imports them, and the worker's project reference would otherwise build the team server. The worker now imports from team-server; the team Dockerfile builds both explicitly. - The sidecar no longer starts the team server when DATABASE_URL is set, and loses the team routes (/api/team/*, /api/teams), the WaggleDance routes and bridge (/api/waggle-dance/*), the Team server binding and egress guard, the WebSocket team client, the TeamSync cache and pushes, team audit forwarding, team workspace registration and the team capability-policy lookup in chat. The in-process room signal bus stays: agent groups, fleet runs and external tool runs use it. middleware/audit.ts was dead and is deleted. - @waggle/core loses TeamSync and the teamServer part of WaggleConfig. A teamServer key in config.json is ignored and kept on save, as P0.1 does for the tier keys. Workspaces lose teamServerUrl and teamUserId; teamId and teamRole stay because workspaces from a shared data directory still carry them and the viewer write guards read them. POST /api/workspaces ignores team fields. - The sidecar bundle no longer marks the team packages as external. The agent still references the TeamSync type in orchestrator.ts and pattern-write-back.ts; those files are being rewritten in P1.5 and drop it there. Logs UF-030 and UF-031 (team sync and team policy defects found while removing the code).
This commit is contained in:
@@ -1,411 +0,0 @@
|
||||
/**
|
||||
* Chat Governance — Permission Lookup Tests
|
||||
*
|
||||
* Covers:
|
||||
* chat-governance.ts: getGovernancePermissions
|
||||
*
|
||||
* Mocks WaggleConfig (from @waggle/core) and global fetch
|
||||
* to test governance policy resolution, caching, and error paths.
|
||||
*/
|
||||
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
|
||||
// ─── Mock @waggle/core ──────────────────────────────────────────────
|
||||
|
||||
const { mockGetTeamServer } = vi.hoisted(() => {
|
||||
const mockGetTeamServer = vi.fn();
|
||||
return { mockGetTeamServer };
|
||||
});
|
||||
|
||||
vi.mock('@waggle/core', async (importOriginal) => ({
|
||||
...await importOriginal<typeof import('@waggle/core')>(),
|
||||
WaggleConfig: vi.fn(() => ({
|
||||
getTeamServer: mockGetTeamServer,
|
||||
})),
|
||||
}));
|
||||
|
||||
import { getGovernancePermissions } from '../../src/local/routes/chat-governance.js';
|
||||
|
||||
// ─── Helpers ────────────────────────────────────────────────────────
|
||||
|
||||
function createFetchResponse(body: unknown, ok = true, status = 200): Response {
|
||||
return {
|
||||
ok,
|
||||
status,
|
||||
json: () => Promise.resolve(body),
|
||||
} as unknown as Response;
|
||||
}
|
||||
|
||||
// ─── Setup / Teardown ───────────────────────────────────────────────
|
||||
|
||||
let originalFetch: typeof globalThis.fetch;
|
||||
|
||||
beforeEach(() => {
|
||||
originalFetch = globalThis.fetch;
|
||||
mockGetTeamServer.mockReset();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
globalThis.fetch = originalFetch;
|
||||
});
|
||||
|
||||
// ─── No team server configured ──────────────────────────────────────
|
||||
|
||||
describe('getGovernancePermissions — no team server', () => {
|
||||
it('returns undefined when getTeamServer() returns null', async () => {
|
||||
mockGetTeamServer.mockReturnValue(null);
|
||||
|
||||
const result = await getGovernancePermissions('/fake/data', 'ws-no-server-1', 'member');
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
it('returns undefined when team server has no url', async () => {
|
||||
mockGetTeamServer.mockReturnValue({ token: 'tok-123' });
|
||||
|
||||
const result = await getGovernancePermissions('/fake/data', 'ws-no-url-1', 'member');
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
it('returns undefined when team server has no token', async () => {
|
||||
mockGetTeamServer.mockReturnValue({ url: 'https://93.184.216.34' });
|
||||
|
||||
const result = await getGovernancePermissions('/fake/data', 'ws-no-token-1', 'member');
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
it('does not call fetch when no team server is configured', async () => {
|
||||
mockGetTeamServer.mockReturnValue(null);
|
||||
const fetchSpy = vi.fn();
|
||||
globalThis.fetch = fetchSpy;
|
||||
|
||||
await getGovernancePermissions('/fake/data', 'ws-no-fetch-1', 'member');
|
||||
expect(fetchSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Successful fetch ───────────────────────────────────────────────
|
||||
|
||||
describe('getGovernancePermissions — successful fetch', () => {
|
||||
it('returns blockedTools for the matching role', async () => {
|
||||
mockGetTeamServer.mockReturnValue({
|
||||
url: 'https://93.184.216.34',
|
||||
token: 'tok-123',
|
||||
teamSlug: 'acme',
|
||||
});
|
||||
|
||||
const policies = [
|
||||
{ role: 'admin', blockedTools: ['delete_workspace'] },
|
||||
{ role: 'member', blockedTools: ['bash', 'write_file'] },
|
||||
];
|
||||
|
||||
globalThis.fetch = vi.fn().mockResolvedValue(createFetchResponse(policies));
|
||||
|
||||
const result = await getGovernancePermissions('/fake/data', 'ws-success-1', 'member');
|
||||
expect(result).toEqual({ blockedTools: ['bash', 'write_file'] });
|
||||
});
|
||||
|
||||
it('returns undefined when no policy matches the teamRole', async () => {
|
||||
mockGetTeamServer.mockReturnValue({
|
||||
url: 'https://93.184.216.34',
|
||||
token: 'tok-123',
|
||||
teamSlug: 'acme',
|
||||
});
|
||||
|
||||
const policies = [
|
||||
{ role: 'admin', blockedTools: ['delete_workspace'] },
|
||||
];
|
||||
|
||||
globalThis.fetch = vi.fn().mockResolvedValue(createFetchResponse(policies));
|
||||
|
||||
const result = await getGovernancePermissions('/fake/data', 'ws-no-role-match-1', 'viewer');
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
it('returns undefined when permissions is not an array', async () => {
|
||||
mockGetTeamServer.mockReturnValue({
|
||||
url: 'https://93.184.216.34',
|
||||
token: 'tok-123',
|
||||
teamSlug: 'acme',
|
||||
});
|
||||
|
||||
globalThis.fetch = vi.fn().mockResolvedValue(createFetchResponse({ not: 'an array' }));
|
||||
|
||||
const result = await getGovernancePermissions('/fake/data', 'ws-not-array-1', 'member');
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
it('returns undefined when the matching role policy has no blockedTools', async () => {
|
||||
mockGetTeamServer.mockReturnValue({
|
||||
url: 'https://93.184.216.34',
|
||||
token: 'tok-123',
|
||||
teamSlug: 'acme',
|
||||
});
|
||||
|
||||
const policies = [
|
||||
{ role: 'member', allowedSources: ['web'] }, // no blockedTools
|
||||
];
|
||||
|
||||
globalThis.fetch = vi.fn().mockResolvedValue(createFetchResponse(policies));
|
||||
|
||||
const result = await getGovernancePermissions('/fake/data', 'ws-no-blocked-1', 'member');
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
it('constructs the correct URL with teamSlug and Authorization header', async () => {
|
||||
mockGetTeamServer.mockReturnValue({
|
||||
url: 'https://93.184.216.34/',
|
||||
token: 'bearer-token-abc',
|
||||
teamSlug: 'my-team',
|
||||
});
|
||||
|
||||
const fetchMock = vi.fn().mockResolvedValue(createFetchResponse([]));
|
||||
globalThis.fetch = fetchMock;
|
||||
|
||||
await getGovernancePermissions('/fake/data', 'ws-url-check-1', 'member');
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||
const [url, options] = fetchMock.mock.calls[0];
|
||||
expect(url).toBe('https://93.184.216.34/api/teams/my-team/capability-policies');
|
||||
expect(options.headers.Authorization).toBe('Bearer bearer-token-abc');
|
||||
});
|
||||
|
||||
it('strips trailing slash from team server URL', async () => {
|
||||
mockGetTeamServer.mockReturnValue({
|
||||
url: 'https://93.184.216.34///',
|
||||
token: 'tok',
|
||||
teamSlug: 'slug',
|
||||
});
|
||||
|
||||
const fetchMock = vi.fn().mockResolvedValue(createFetchResponse([]));
|
||||
globalThis.fetch = fetchMock;
|
||||
|
||||
await getGovernancePermissions('/fake/data', 'ws-trailing-slash-1', 'admin');
|
||||
|
||||
const [url] = fetchMock.mock.calls[0];
|
||||
// Only the last slash is stripped by the regex /$/ → but the function uses .replace(/\/$/, '')
|
||||
// which strips one trailing slash. With '///' it becomes '//'
|
||||
expect(url).toContain('/api/teams/slug/capability-policies');
|
||||
});
|
||||
});
|
||||
|
||||
describe('getGovernancePermissions — guarded Team egress', () => {
|
||||
it('blocks cloud metadata before sending the Team token', async () => {
|
||||
mockGetTeamServer.mockReturnValue({
|
||||
url: 'https://169.254.169.254/latest/meta-data',
|
||||
token: 'metadata-token',
|
||||
teamSlug: 'acme',
|
||||
});
|
||||
const fetchMock = vi.fn().mockResolvedValue(createFetchResponse([
|
||||
{ role: 'member', blockedTools: ['write_file'] },
|
||||
]));
|
||||
globalThis.fetch = fetchMock;
|
||||
|
||||
const result = await getGovernancePermissions('/fake/data', 'ws-metadata-block-1', 'member');
|
||||
|
||||
expect(result).toBeUndefined();
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('blocks cleartext public Team URLs even when loopback access is enabled', async () => {
|
||||
const previousAllowLocal = process.env.WAGGLE_ALLOW_LOCAL_FETCH;
|
||||
process.env.WAGGLE_ALLOW_LOCAL_FETCH = '1';
|
||||
mockGetTeamServer.mockReturnValue({
|
||||
url: 'http://93.184.216.34',
|
||||
token: 'cleartext-token',
|
||||
teamSlug: 'acme',
|
||||
});
|
||||
const fetchMock = vi.fn().mockResolvedValue(createFetchResponse([
|
||||
{ role: 'member', blockedTools: ['write_file'] },
|
||||
]));
|
||||
globalThis.fetch = fetchMock;
|
||||
|
||||
try {
|
||||
const result = await getGovernancePermissions('/fake/data', 'ws-cleartext-block-1', 'member');
|
||||
|
||||
expect(result).toBeUndefined();
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
if (previousAllowLocal === undefined) delete process.env.WAGGLE_ALLOW_LOCAL_FETCH;
|
||||
else process.env.WAGGLE_ALLOW_LOCAL_FETCH = previousAllowLocal;
|
||||
}
|
||||
});
|
||||
|
||||
it('does not forward the Team token across redirects', async () => {
|
||||
mockGetTeamServer.mockReturnValue({
|
||||
url: 'https://93.184.216.34',
|
||||
token: 'redirect-token',
|
||||
teamSlug: 'acme',
|
||||
});
|
||||
const fetchMock = vi.fn().mockResolvedValue(new Response(null, {
|
||||
status: 302,
|
||||
headers: { location: 'https://169.254.169.254/latest/meta-data' },
|
||||
}));
|
||||
globalThis.fetch = fetchMock;
|
||||
|
||||
const result = await getGovernancePermissions('/fake/data', 'ws-redirect-block-1', 'member');
|
||||
|
||||
expect(result).toBeUndefined();
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||
expect(fetchMock.mock.calls[0][1]?.redirect).toBe('manual');
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Fetch failure ──────────────────────────────────────────────────
|
||||
|
||||
describe('getGovernancePermissions — fetch failure', () => {
|
||||
it('returns undefined when fetch throws (network error)', async () => {
|
||||
mockGetTeamServer.mockReturnValue({
|
||||
url: 'https://93.184.216.34',
|
||||
token: 'tok-123',
|
||||
teamSlug: 'acme',
|
||||
});
|
||||
|
||||
globalThis.fetch = vi.fn().mockRejectedValue(new Error('ECONNREFUSED'));
|
||||
|
||||
const result = await getGovernancePermissions('/fake/data', 'ws-net-error-1', 'member');
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
it('returns undefined when server responds with non-ok status', async () => {
|
||||
mockGetTeamServer.mockReturnValue({
|
||||
url: 'https://93.184.216.34',
|
||||
token: 'tok-123',
|
||||
teamSlug: 'acme',
|
||||
});
|
||||
|
||||
globalThis.fetch = vi.fn().mockResolvedValue(createFetchResponse(null, false, 500));
|
||||
|
||||
const result = await getGovernancePermissions('/fake/data', 'ws-500-error-1', 'member');
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Caching behavior ───────────────────────────────────────────────
|
||||
|
||||
describe('getGovernancePermissions — caching', () => {
|
||||
it('caches successful responses and does not re-fetch for the same workspace', async () => {
|
||||
mockGetTeamServer.mockReturnValue({
|
||||
url: 'https://93.184.216.34',
|
||||
token: 'tok-123',
|
||||
teamSlug: 'acme',
|
||||
});
|
||||
|
||||
const policies = [
|
||||
{ role: 'member', blockedTools: ['bash'] },
|
||||
];
|
||||
|
||||
const fetchMock = vi.fn().mockResolvedValue(createFetchResponse(policies));
|
||||
globalThis.fetch = fetchMock;
|
||||
|
||||
// Use a unique workspace ID for this cache test
|
||||
const wsId = 'ws-cache-hit-1';
|
||||
|
||||
// First call — should fetch
|
||||
const result1 = await getGovernancePermissions('/fake/data', wsId, 'member');
|
||||
expect(result1).toEqual({ blockedTools: ['bash'] });
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||
|
||||
// Second call — should use cache
|
||||
const result2 = await getGovernancePermissions('/fake/data', wsId, 'member');
|
||||
expect(result2).toEqual({ blockedTools: ['bash'] });
|
||||
// fetch should NOT have been called again
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('returns cached data when fetch fails on subsequent calls', async () => {
|
||||
mockGetTeamServer.mockReturnValue({
|
||||
url: 'https://93.184.216.34',
|
||||
token: 'tok-123',
|
||||
teamSlug: 'acme',
|
||||
});
|
||||
|
||||
const policies = [
|
||||
{ role: 'admin', blockedTools: ['delete_all'] },
|
||||
];
|
||||
|
||||
const wsId = 'ws-cache-fallback-1';
|
||||
|
||||
// First call succeeds and populates cache
|
||||
const successFetch = vi.fn().mockResolvedValue(createFetchResponse(policies));
|
||||
globalThis.fetch = successFetch;
|
||||
await getGovernancePermissions('/fake/data', wsId, 'admin');
|
||||
expect(successFetch).toHaveBeenCalledTimes(1);
|
||||
|
||||
// Expire the cache by manipulating Date.now
|
||||
const realDateNow = Date.now;
|
||||
Date.now = () => realDateNow() + 6 * 60 * 1000; // 6 minutes later (past 5-min TTL)
|
||||
|
||||
// Second call — fetch fails, but cached data should be returned
|
||||
const failFetch = vi.fn().mockRejectedValue(new Error('timeout'));
|
||||
globalThis.fetch = failFetch;
|
||||
|
||||
const result = await getGovernancePermissions('/fake/data', wsId, 'admin');
|
||||
expect(result).toEqual({ blockedTools: ['delete_all'] });
|
||||
expect(failFetch).toHaveBeenCalledTimes(1);
|
||||
|
||||
// Restore Date.now
|
||||
Date.now = realDateNow;
|
||||
});
|
||||
|
||||
it('uses different cache entries for different workspaceIds', async () => {
|
||||
mockGetTeamServer.mockReturnValue({
|
||||
url: 'https://93.184.216.34',
|
||||
token: 'tok-123',
|
||||
teamSlug: 'acme',
|
||||
});
|
||||
|
||||
const policies1 = [{ role: 'member', blockedTools: ['tool-a'] }];
|
||||
const policies2 = [{ role: 'member', blockedTools: ['tool-b'] }];
|
||||
|
||||
const fetchMock = vi.fn()
|
||||
.mockResolvedValueOnce(createFetchResponse(policies1))
|
||||
.mockResolvedValueOnce(createFetchResponse(policies2));
|
||||
globalThis.fetch = fetchMock;
|
||||
|
||||
const r1 = await getGovernancePermissions('/fake/data', 'ws-diff-cache-a', 'member');
|
||||
const r2 = await getGovernancePermissions('/fake/data', 'ws-diff-cache-b', 'member');
|
||||
|
||||
expect(r1).toEqual({ blockedTools: ['tool-a'] });
|
||||
expect(r2).toEqual({ blockedTools: ['tool-b'] });
|
||||
expect(fetchMock).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Edge cases ─────────────────────────────────────────────────────
|
||||
|
||||
describe('getGovernancePermissions — edge cases', () => {
|
||||
it('handles undefined teamRole gracefully', async () => {
|
||||
mockGetTeamServer.mockReturnValue({
|
||||
url: 'https://93.184.216.34',
|
||||
token: 'tok-123',
|
||||
teamSlug: 'acme',
|
||||
});
|
||||
|
||||
const policies = [
|
||||
{ role: undefined, blockedTools: ['hidden_tool'] },
|
||||
{ role: 'member', blockedTools: ['bash'] },
|
||||
];
|
||||
|
||||
globalThis.fetch = vi.fn().mockResolvedValue(createFetchResponse(policies));
|
||||
|
||||
const result = await getGovernancePermissions('/fake/data', 'ws-undef-role-1', undefined);
|
||||
// Should match the policy where role === undefined
|
||||
expect(result).toEqual({ blockedTools: ['hidden_tool'] });
|
||||
});
|
||||
|
||||
it('defaults teamSlug to "default" when not set on teamServer', async () => {
|
||||
mockGetTeamServer.mockReturnValue({
|
||||
url: 'https://93.184.216.34',
|
||||
token: 'tok-123',
|
||||
// No teamSlug property
|
||||
});
|
||||
|
||||
const fetchMock = vi.fn().mockResolvedValue(createFetchResponse([]));
|
||||
globalThis.fetch = fetchMock;
|
||||
|
||||
await getGovernancePermissions('/fake/data', 'ws-default-slug-1', 'member');
|
||||
|
||||
const [url] = fetchMock.mock.calls[0];
|
||||
expect(url).toBe('https://93.184.216.34/api/teams/default/capability-policies');
|
||||
});
|
||||
});
|
||||
@@ -585,12 +585,6 @@ describe('persona acceptance prompt budget', () => {
|
||||
const toolInputMarker = 'PRIVATE_TOOL_INPUT_CERULEAN_20260808';
|
||||
const toolResultMarker = 'PRIVATE_TOOL_RESULT_AMBER_20260808';
|
||||
const responseMarker = 'PRIVATE_RESPONSE_VIOLET_20260808';
|
||||
const teamId = 'privacy-derived-sink-team';
|
||||
const teamServerUrl = 'https://93.184.216.34';
|
||||
const auditUrl = `${teamServerUrl}/api/teams/${teamId}/audit`;
|
||||
const workspaceBefore = server.workspaceManager.get(collaborationWorkspaceId)!;
|
||||
const waggleConfig = new WaggleConfig(tmpDir);
|
||||
const teamServerBefore = waggleConfig.getTeamServer();
|
||||
const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(
|
||||
new Response(JSON.stringify([]), {
|
||||
status: 200,
|
||||
@@ -599,14 +593,6 @@ describe('persona acceptance prompt budget', () => {
|
||||
);
|
||||
|
||||
try {
|
||||
server.workspaceManager.update(collaborationWorkspaceId, {
|
||||
teamId,
|
||||
teamServerUrl,
|
||||
teamRole: 'member',
|
||||
});
|
||||
waggleConfig.setTeamServer({ url: teamServerUrl, token: 'privacy-test-token' });
|
||||
waggleConfig.save();
|
||||
|
||||
testState.runAgentLoop.mockImplementationOnce(async (config: AgentLoopConfig) => {
|
||||
capturedConfig = config;
|
||||
const input = { path: toolInputMarker };
|
||||
@@ -656,14 +642,7 @@ describe('persona acceptance prompt budget', () => {
|
||||
expect(legacySignals.statusCode).toBe(200);
|
||||
const activityProjection = legacySignals.body;
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(fetchSpy.mock.calls.filter(([url]) => String(url) === auditUrl)).toHaveLength(2);
|
||||
});
|
||||
const remoteAuditProjection = JSON.stringify(fetchSpy.mock.calls
|
||||
.filter(([url]) => String(url) === auditUrl)
|
||||
.map(([, options]) => options?.body));
|
||||
|
||||
for (const projection of [traceProjection, auditProjection, activityProjection, remoteAuditProjection]) {
|
||||
for (const projection of [traceProjection, auditProjection, activityProjection]) {
|
||||
for (const marker of [promptMarker, toolInputMarker, toolResultMarker, responseMarker]) {
|
||||
expect(projection, marker).not.toContain(marker);
|
||||
}
|
||||
@@ -671,17 +650,7 @@ describe('persona acceptance prompt budget', () => {
|
||||
expect(traceProjection).toContain('Not retained');
|
||||
expect(auditProjection).toContain('Not retained');
|
||||
expect(activityProjection).toContain('Not retained');
|
||||
expect(remoteAuditProjection).toContain('Not retained');
|
||||
} finally {
|
||||
server.workspaceManager.update(collaborationWorkspaceId, {
|
||||
teamId: workspaceBefore.teamId,
|
||||
teamServerUrl: workspaceBefore.teamServerUrl,
|
||||
teamRole: workspaceBefore.teamRole,
|
||||
});
|
||||
const restoreConfig = new WaggleConfig(tmpDir);
|
||||
if (teamServerBefore) restoreConfig.setTeamServer(teamServerBefore);
|
||||
else restoreConfig.clearTeamServer();
|
||||
restoreConfig.save();
|
||||
fetchSpy.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1,575 +0,0 @@
|
||||
/**
|
||||
* Team Integration Tests — GAP-028 / GAP-029
|
||||
*
|
||||
* Tests fire-and-forget team server pushes:
|
||||
* - emitAuditEvent with team workspace → fetch called to team server
|
||||
* - emitAuditEvent with personal workspace → no fetch called
|
||||
* - POST /api/workspaces with teamId → fetch called to register
|
||||
* - POST /api/workspaces without teamId → no fetch called
|
||||
*/
|
||||
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import os from 'node:os';
|
||||
import { MindDB, SessionStore, FrameStore, type TeamSync } from '@waggle/core';
|
||||
import type { AgentLoopConfig, AgentResponse } from '@waggle/agent';
|
||||
import { buildLocalServer } from '../../src/local/index.js';
|
||||
import type { FastifyInstance } from 'fastify';
|
||||
import { emitAuditEvent, closeAuditDb } from '../../src/local/routes/events.js';
|
||||
import { injectWithAuth } from '../test-utils.js';
|
||||
|
||||
// ── Mock global fetch ───────────────────────────────────────────────
|
||||
|
||||
const mockFetch = vi.fn().mockResolvedValue({ ok: true });
|
||||
|
||||
/**
|
||||
* Helper: write config.json with team server credentials into dataDir.
|
||||
* The real WaggleConfig will read this file.
|
||||
*/
|
||||
function writeTeamConfig(dataDir: string, token?: string, url = 'https://93.184.216.34') {
|
||||
const config: Record<string, unknown> = {
|
||||
defaultModel: 'claude-sonnet-4-6',
|
||||
providers: {},
|
||||
};
|
||||
if (token) {
|
||||
config.teamServer = { url, token };
|
||||
}
|
||||
fs.writeFileSync(path.join(dataDir, 'config.json'), JSON.stringify(config));
|
||||
}
|
||||
|
||||
describe('Team Integration — Audit Event Push (GAP-028)', () => {
|
||||
let tmpDir: string;
|
||||
|
||||
beforeEach(() => {
|
||||
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'waggle-team-audit-'));
|
||||
writeTeamConfig(tmpDir, 'test-token-123');
|
||||
vi.stubGlobal('fetch', mockFetch);
|
||||
mockFetch.mockClear();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
closeAuditDb();
|
||||
vi.unstubAllGlobals();
|
||||
try { fs.rmSync(tmpDir, { recursive: true, force: true }); } catch { /* ignore EBUSY on Windows */ }
|
||||
});
|
||||
|
||||
it('pushes audit event to team server for team workspace', async () => {
|
||||
const fakeServer = {
|
||||
localConfig: { dataDir: tmpDir },
|
||||
workspaceManager: {
|
||||
get: vi.fn().mockReturnValue({
|
||||
id: 'ws-team-1',
|
||||
name: 'Team WS',
|
||||
teamId: 'team-abc',
|
||||
teamServerUrl: 'https://93.184.216.34',
|
||||
}),
|
||||
},
|
||||
eventBus: { emit: vi.fn() },
|
||||
} as unknown as FastifyInstance;
|
||||
|
||||
emitAuditEvent(fakeServer, {
|
||||
workspaceId: 'ws-team-1',
|
||||
eventType: 'tool_call',
|
||||
toolName: 'memory_write',
|
||||
});
|
||||
|
||||
// The team push is inside an async IIFE — wait for it to resolve
|
||||
await new Promise(resolve => setTimeout(resolve, 300));
|
||||
|
||||
expect(mockFetch).toHaveBeenCalledTimes(1);
|
||||
const [url, opts] = mockFetch.mock.calls[0];
|
||||
expect(url).toBe('https://93.184.216.34/api/teams/team-abc/audit');
|
||||
expect(opts.method).toBe('POST');
|
||||
expect(opts.headers['Authorization']).toBe('Bearer test-token-123');
|
||||
const body = JSON.parse(opts.body);
|
||||
expect(body.workspaceId).toBe('ws-team-1');
|
||||
expect(body.eventType).toBe('tool_call');
|
||||
expect(body.source).toBe('local-agent');
|
||||
expect(body.timestamp).toBeDefined();
|
||||
});
|
||||
|
||||
it('does NOT push for personal workspace (no teamId)', async () => {
|
||||
const fakeServer = {
|
||||
localConfig: { dataDir: tmpDir },
|
||||
workspaceManager: {
|
||||
get: vi.fn().mockReturnValue({
|
||||
id: 'ws-personal',
|
||||
name: 'Personal WS',
|
||||
// no teamId, no teamServerUrl
|
||||
}),
|
||||
},
|
||||
eventBus: { emit: vi.fn() },
|
||||
} as unknown as FastifyInstance;
|
||||
|
||||
emitAuditEvent(fakeServer, {
|
||||
workspaceId: 'ws-personal',
|
||||
eventType: 'memory_write',
|
||||
});
|
||||
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
|
||||
expect(mockFetch).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does NOT push if team server has no token', async () => {
|
||||
// Overwrite config without token
|
||||
writeTeamConfig(tmpDir); // no token
|
||||
|
||||
const fakeServer = {
|
||||
localConfig: { dataDir: tmpDir },
|
||||
workspaceManager: {
|
||||
get: vi.fn().mockReturnValue({
|
||||
id: 'ws-team-2',
|
||||
name: 'Team WS 2',
|
||||
teamId: 'team-xyz',
|
||||
teamServerUrl: 'https://team.example.com',
|
||||
}),
|
||||
},
|
||||
eventBus: { emit: vi.fn() },
|
||||
} as unknown as FastifyInstance;
|
||||
|
||||
emitAuditEvent(fakeServer, {
|
||||
workspaceId: 'ws-team-2',
|
||||
eventType: 'session_start',
|
||||
});
|
||||
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
|
||||
expect(mockFetch).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('blocks a metadata-bound audit target before sending the Team token', async () => {
|
||||
writeTeamConfig(tmpDir, 'metadata-token', 'https://169.254.169.254/latest/meta-data');
|
||||
const fakeServer = {
|
||||
localConfig: { dataDir: tmpDir },
|
||||
workspaceManager: {
|
||||
get: vi.fn().mockReturnValue({
|
||||
id: 'ws-metadata',
|
||||
name: 'Metadata Workspace',
|
||||
teamId: 'team-metadata',
|
||||
teamServerUrl: 'https://169.254.169.254/latest/meta-data',
|
||||
}),
|
||||
},
|
||||
eventBus: { emit: vi.fn() },
|
||||
} as unknown as FastifyInstance;
|
||||
|
||||
emitAuditEvent(fakeServer, {
|
||||
workspaceId: 'ws-metadata',
|
||||
eventType: 'tool_call',
|
||||
});
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
|
||||
expect(mockFetch).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not send a newly configured Team token to a workspace bound to the previous server', async () => {
|
||||
writeTeamConfig(tmpDir, 'server-b-token', 'https://team-b.example.com');
|
||||
const fakeServer = {
|
||||
localConfig: { dataDir: tmpDir },
|
||||
workspaceManager: {
|
||||
get: vi.fn().mockReturnValue({
|
||||
id: 'ws-server-a',
|
||||
name: 'Old Team Workspace',
|
||||
teamId: 'team-a',
|
||||
teamServerUrl: 'https://team-a.example.com',
|
||||
}),
|
||||
},
|
||||
eventBus: { emit: vi.fn() },
|
||||
} as unknown as FastifyInstance;
|
||||
|
||||
emitAuditEvent(fakeServer, {
|
||||
workspaceId: 'ws-server-a',
|
||||
eventType: 'tool_call',
|
||||
});
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
|
||||
expect(mockFetch).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Team Integration — Workspace Registration (GAP-029)', () => {
|
||||
let server: FastifyInstance;
|
||||
let tmpDir: string;
|
||||
|
||||
beforeEach(async () => {
|
||||
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'waggle-team-ws-'));
|
||||
|
||||
// Create personal.mind (required by buildLocalServer)
|
||||
const personalPath = path.join(tmpDir, 'personal.mind');
|
||||
const mind = new MindDB(personalPath);
|
||||
const sessions = new SessionStore(mind);
|
||||
const frames = new FrameStore(mind);
|
||||
const s1 = sessions.create('team-test');
|
||||
frames.createIFrame(s1.gop_id, 'Team test frame', 'normal');
|
||||
mind.close();
|
||||
|
||||
// Create config.json with team server config
|
||||
writeTeamConfig(tmpDir, 'ws-reg-token');
|
||||
|
||||
vi.stubGlobal('fetch', mockFetch);
|
||||
mockFetch.mockClear();
|
||||
|
||||
server = await buildLocalServer({ dataDir: tmpDir });
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await server.close();
|
||||
vi.unstubAllGlobals();
|
||||
try { fs.rmSync(tmpDir, { recursive: true, force: true }); } catch { /* ignore */ }
|
||||
});
|
||||
|
||||
it('registers workspace on team server when teamId is provided', async () => {
|
||||
const res = await injectWithAuth(server, {
|
||||
method: 'POST',
|
||||
url: '/api/workspaces',
|
||||
payload: {
|
||||
name: 'Team Project',
|
||||
group: 'work',
|
||||
teamId: 'team-abc',
|
||||
teamServerUrl: 'https://93.184.216.34/',
|
||||
teamUserId: 'user-42',
|
||||
},
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(201);
|
||||
const ws = res.json();
|
||||
expect(ws.name).toBe('Team Project');
|
||||
expect(ws.teamServerUrl).toBe('https://93.184.216.34');
|
||||
|
||||
// Wait for fire-and-forget fetch to complete
|
||||
await new Promise(resolve => setTimeout(resolve, 300));
|
||||
|
||||
// Find the registration call (not audit event calls or health checks)
|
||||
const registrationCalls = mockFetch.mock.calls.filter(
|
||||
([url]: [string]) => typeof url === 'string' && url.includes('/entities'),
|
||||
);
|
||||
|
||||
expect(registrationCalls.length).toBeGreaterThanOrEqual(1);
|
||||
const [url, opts] = registrationCalls[0];
|
||||
expect(url).toBe('https://93.184.216.34/api/teams/team-abc/entities');
|
||||
expect(opts.method).toBe('POST');
|
||||
expect(opts.headers['Authorization']).toBe('Bearer ws-reg-token');
|
||||
const body = JSON.parse(opts.body);
|
||||
expect(body.entityType).toBe('workspace');
|
||||
expect(body.properties.displayName).toBe('Team Project');
|
||||
expect(body.properties.group).toBe('work');
|
||||
expect(body.properties.createdBy).toBe('user-42');
|
||||
});
|
||||
|
||||
it('blocks a metadata-bound workspace registration before sending the Team token', async () => {
|
||||
writeTeamConfig(tmpDir, 'metadata-token', 'https://169.254.169.254/latest/meta-data');
|
||||
const res = await injectWithAuth(server, {
|
||||
method: 'POST',
|
||||
url: '/api/workspaces',
|
||||
payload: {
|
||||
name: 'Metadata Team Project',
|
||||
group: 'work',
|
||||
teamId: 'team-metadata',
|
||||
teamServerUrl: 'https://169.254.169.254/latest/meta-data',
|
||||
},
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(201);
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
expect(mockFetch.mock.calls.filter(([url, options]) =>
|
||||
String(url).startsWith('https://169.254.169.254/')
|
||||
|| options?.headers?.Authorization === 'Bearer metadata-token',
|
||||
)).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('rejects a cleartext public configured Team destination without creating a workspace', async () => {
|
||||
const previousAllowLocal = process.env.WAGGLE_ALLOW_LOCAL_FETCH;
|
||||
process.env.WAGGLE_ALLOW_LOCAL_FETCH = '1';
|
||||
writeTeamConfig(tmpDir, 'cleartext-token', 'http://93.184.216.34');
|
||||
const workspaceCount = server.workspaceManager.list().length;
|
||||
try {
|
||||
const res = await injectWithAuth(server, {
|
||||
method: 'POST',
|
||||
url: '/api/workspaces',
|
||||
payload: {
|
||||
name: 'Cleartext Team Project',
|
||||
group: 'work',
|
||||
teamId: 'team-cleartext',
|
||||
teamServerUrl: 'http://93.184.216.34',
|
||||
},
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(400);
|
||||
expect(server.workspaceManager.list()).toHaveLength(workspaceCount);
|
||||
expect(mockFetch.mock.calls.filter(([url, options]) =>
|
||||
String(url).startsWith('http://93.184.216.34/')
|
||||
|| options?.headers?.Authorization === 'Bearer cleartext-token',
|
||||
)).toHaveLength(0);
|
||||
} finally {
|
||||
if (previousAllowLocal === undefined) delete process.env.WAGGLE_ALLOW_LOCAL_FETCH;
|
||||
else process.env.WAGGLE_ALLOW_LOCAL_FETCH = previousAllowLocal;
|
||||
}
|
||||
});
|
||||
|
||||
it('rejects a team workspace URL that does not match the configured destination', async () => {
|
||||
const workspaceCount = server.workspaceManager.list().length;
|
||||
const res = await injectWithAuth(server, {
|
||||
method: 'POST',
|
||||
url: '/api/workspaces',
|
||||
payload: {
|
||||
name: 'Redirected Team Project',
|
||||
group: 'work',
|
||||
teamId: 'team-abc',
|
||||
teamServerUrl: 'https://attacker.example',
|
||||
},
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(400);
|
||||
expect(res.json().error).toMatch(/configured team server/i);
|
||||
expect(server.workspaceManager.list()).toHaveLength(workspaceCount);
|
||||
expect(mockFetch.mock.calls.filter(
|
||||
([url]: [string]) => typeof url === 'string' && url.includes('/entities'),
|
||||
)).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('rejects a team workspace when no Team server destination is configured', async () => {
|
||||
writeTeamConfig(tmpDir);
|
||||
const workspaceCount = server.workspaceManager.list().length;
|
||||
const res = await injectWithAuth(server, {
|
||||
method: 'POST',
|
||||
url: '/api/workspaces',
|
||||
payload: {
|
||||
name: 'Unbound Team Project',
|
||||
group: 'work',
|
||||
teamId: 'team-abc',
|
||||
teamServerUrl: 'https://team.example.com',
|
||||
},
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(400);
|
||||
expect(res.json().error).toMatch(/configured team server/i);
|
||||
expect(server.workspaceManager.list()).toHaveLength(workspaceCount);
|
||||
});
|
||||
|
||||
it.each([
|
||||
['teamId', { teamId: 'team-abc' }],
|
||||
['teamServerUrl', { teamServerUrl: 'https://team.example.com' }],
|
||||
])('rejects a team workspace with only %s', async (_field, teamFields) => {
|
||||
const workspaceCount = server.workspaceManager.list().length;
|
||||
const res = await injectWithAuth(server, {
|
||||
method: 'POST',
|
||||
url: '/api/workspaces',
|
||||
payload: {
|
||||
name: 'Partial Team Project',
|
||||
group: 'work',
|
||||
...teamFields,
|
||||
},
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(400);
|
||||
expect(res.json().error).toMatch(/teamId and teamServerUrl/i);
|
||||
expect(server.workspaceManager.list()).toHaveLength(workspaceCount);
|
||||
});
|
||||
|
||||
it('does NOT register when no teamId is provided', async () => {
|
||||
const res = await injectWithAuth(server, {
|
||||
method: 'POST',
|
||||
url: '/api/workspaces',
|
||||
payload: {
|
||||
name: 'Personal Project',
|
||||
group: 'personal',
|
||||
},
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(201);
|
||||
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
|
||||
// No calls to /entities endpoint
|
||||
const registrationCalls = mockFetch.mock.calls.filter(
|
||||
([url]: [string]) => typeof url === 'string' && url.includes('/entities'),
|
||||
);
|
||||
expect(registrationCalls).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('does not push save_memory with a Team token bound to another server', async () => {
|
||||
const workspace = server.workspaceManager.create({
|
||||
name: 'Server A Workspace',
|
||||
group: 'work',
|
||||
teamId: 'team-a',
|
||||
teamServerUrl: 'https://team-a.example.com',
|
||||
});
|
||||
writeTeamConfig(tmpDir, 'server-b-token', 'https://team-b.example.com');
|
||||
mockFetch.mockClear();
|
||||
mockFetch.mockResolvedValue({ ok: true, json: async () => ({ id: 'remote-frame' }) });
|
||||
const originalRunner = server.agentRunner;
|
||||
server.agentRunner = async (config: AgentLoopConfig): Promise<AgentResponse> => {
|
||||
config.onToolResult?.('save_memory', {}, 'saved memory');
|
||||
return { content: 'saved', toolsUsed: ['save_memory'], usage: { inputTokens: 1, outputTokens: 1 } };
|
||||
};
|
||||
|
||||
try {
|
||||
const res = await injectWithAuth(server, {
|
||||
method: 'POST',
|
||||
url: '/api/chat',
|
||||
payload: { message: 'Remember this', workspace: workspace.id },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
|
||||
expect(mockFetch.mock.calls.filter(([url, options]) =>
|
||||
String(url).startsWith('https://team-a.example.com')
|
||||
&& options?.headers?.Authorization === 'Bearer server-b-token',
|
||||
)).toHaveLength(0);
|
||||
} finally {
|
||||
server.agentRunner = originalRunner;
|
||||
mockFetch.mockResolvedValue({ ok: true });
|
||||
}
|
||||
});
|
||||
|
||||
it('routes save_memory TeamSync pushes through the guarded Team transport', async () => {
|
||||
const teamServerUrl = 'https://93.184.216.34';
|
||||
const workspace = server.workspaceManager.create({
|
||||
name: 'Guarded Team Workspace',
|
||||
group: 'work',
|
||||
teamId: 'team-guarded',
|
||||
teamServerUrl,
|
||||
});
|
||||
writeTeamConfig(tmpDir, 'guarded-team-token', teamServerUrl);
|
||||
mockFetch.mockClear();
|
||||
mockFetch.mockResolvedValue({ ok: true, json: async () => ({ id: 'remote-frame' }) });
|
||||
const originalRunner = server.agentRunner;
|
||||
server.agentRunner = async (config: AgentLoopConfig): Promise<AgentResponse> => {
|
||||
config.onToolResult?.('save_memory', {}, 'saved memory');
|
||||
return { content: 'saved', toolsUsed: ['save_memory'], usage: { inputTokens: 1, outputTokens: 1 } };
|
||||
};
|
||||
|
||||
try {
|
||||
const res = await injectWithAuth(server, {
|
||||
method: 'POST',
|
||||
url: '/api/chat',
|
||||
payload: { message: 'Remember this safely', workspace: workspace.id },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
|
||||
const guardedPush = mockFetch.mock.calls.find(([url, options]) =>
|
||||
String(url) === `${teamServerUrl}/api/teams/team-guarded/entities`
|
||||
&& options?.method === 'POST',
|
||||
);
|
||||
expect(guardedPush?.[1]?.headers?.Authorization).toBe('Bearer guarded-team-token');
|
||||
expect(guardedPush?.[1]?.redirect).toBe('manual');
|
||||
expect(guardedPush?.[1]?.dispatcher).toBeDefined();
|
||||
} finally {
|
||||
server.agentRunner = originalRunner;
|
||||
mockFetch.mockResolvedValue({ ok: true });
|
||||
}
|
||||
});
|
||||
|
||||
it('rebinds the TeamSync cache on token rotation and rejects a server change', async () => {
|
||||
const teamServerUrl = 'https://93.184.216.34';
|
||||
writeTeamConfig(tmpDir, 'server-a-token', teamServerUrl);
|
||||
const workspace = server.workspaceManager.create({
|
||||
name: 'Cached Server A Workspace',
|
||||
group: 'work',
|
||||
teamId: 'team-a',
|
||||
teamServerUrl,
|
||||
});
|
||||
mockFetch.mockResolvedValue({ ok: true, json: async () => [] });
|
||||
|
||||
try {
|
||||
server.agentState.activateWorkspaceMind(workspace.id);
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
|
||||
writeTeamConfig(tmpDir, 'rotated-a-token', teamServerUrl);
|
||||
mockFetch.mockClear();
|
||||
await server.agentState.orchestrator.autoSaveFromExchange(
|
||||
'We decided to use the rotated credential guard for this workspace architecture.',
|
||||
'Acknowledged.',
|
||||
);
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
const rotatedPush = mockFetch.mock.calls.find(([, options]) => options?.method === 'POST');
|
||||
expect(rotatedPush?.[1]?.headers?.Authorization).toBe('Bearer rotated-a-token');
|
||||
expect(rotatedPush?.[1]?.redirect).toBe('manual');
|
||||
expect(rotatedPush?.[1]?.dispatcher).toBeDefined();
|
||||
|
||||
mockFetch.mockClear();
|
||||
server.agentState.activateWorkspaceMind(workspace.id);
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
const rotatedPull = mockFetch.mock.calls.find(([url]) => String(url).includes('/entities?type=memory_frame'));
|
||||
expect(rotatedPull?.[1]?.headers?.Authorization).toBe('Bearer rotated-a-token');
|
||||
expect(rotatedPull?.[1]?.redirect).toBe('manual');
|
||||
expect(rotatedPull?.[1]?.dispatcher).toBeDefined();
|
||||
|
||||
writeTeamConfig(tmpDir, 'server-b-token', 'https://team-b.example.com');
|
||||
mockFetch.mockClear();
|
||||
server.agentState.activateWorkspaceMind(workspace.id);
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
expect(mockFetch.mock.calls.filter(([url]) => String(url).includes('/entities?type=memory_frame'))).toHaveLength(0);
|
||||
} finally {
|
||||
mockFetch.mockResolvedValue({ ok: true });
|
||||
}
|
||||
});
|
||||
|
||||
it('does not push through an already-bound orchestrator after Team disconnect', async () => {
|
||||
writeTeamConfig(tmpDir, 'server-a-token', 'https://team-a.example.com');
|
||||
const workspace = server.workspaceManager.create({
|
||||
name: 'Disconnected Server A Workspace',
|
||||
group: 'work',
|
||||
teamId: 'team-a',
|
||||
teamServerUrl: 'https://team-a.example.com',
|
||||
});
|
||||
mockFetch.mockResolvedValue({ ok: true, json: async () => [] });
|
||||
|
||||
try {
|
||||
server.agentState.activateWorkspaceMind(workspace.id);
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
|
||||
writeTeamConfig(tmpDir);
|
||||
mockFetch.mockClear();
|
||||
await server.agentState.orchestrator.autoSaveFromExchange(
|
||||
'We decided to use the disconnect guard for this workspace architecture.',
|
||||
'Acknowledged.',
|
||||
);
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
|
||||
expect(mockFetch.mock.calls.filter(([url, options]) =>
|
||||
String(url).includes('/entities') && options?.method === 'POST',
|
||||
)).toHaveLength(0);
|
||||
} finally {
|
||||
mockFetch.mockResolvedValue({ ok: true });
|
||||
}
|
||||
});
|
||||
|
||||
it('clears the active TeamSync when a team workspace mind is closed', async () => {
|
||||
writeTeamConfig(tmpDir, 'server-a-token', 'https://team-a.example.com');
|
||||
const workspace = server.workspaceManager.create({
|
||||
name: 'Deleted Server A Workspace',
|
||||
group: 'work',
|
||||
teamId: 'team-a',
|
||||
teamServerUrl: 'https://team-a.example.com',
|
||||
});
|
||||
mockFetch.mockResolvedValue({ ok: true, json: async () => [] });
|
||||
|
||||
server.agentState.activateWorkspaceMind(workspace.id);
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
const sharedOrchestrator = server.agentState.orchestrator as unknown as { teamSync: TeamSync | null };
|
||||
expect(sharedOrchestrator.teamSync).not.toBeNull();
|
||||
const capturedTeamSync = sharedOrchestrator.teamSync!;
|
||||
|
||||
server.agentState.closeWorkspaceMind(workspace.id);
|
||||
|
||||
expect(sharedOrchestrator.teamSync).toBeNull();
|
||||
mockFetch.mockClear();
|
||||
await capturedTeamSync.pushFrame({
|
||||
id: 99,
|
||||
gop_id: 'closed-workspace',
|
||||
t: 0,
|
||||
frame_type: 'I',
|
||||
base_frame_id: null,
|
||||
content: 'must remain local after workspace close',
|
||||
importance: 'normal',
|
||||
source: 'agent_inferred',
|
||||
access_count: 0,
|
||||
created_at: new Date().toISOString(),
|
||||
last_accessed: new Date().toISOString(),
|
||||
});
|
||||
expect(mockFetch).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -1,190 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { EventEmitter } from 'node:events';
|
||||
import { WsTeamClient } from '../../src/local/ws-team-client.js';
|
||||
|
||||
/** Shape of the mock WebSocket the test inspects. */
|
||||
interface MockWs extends EventEmitter {
|
||||
readyState: number;
|
||||
sent: string[];
|
||||
send(data: string): void;
|
||||
close(): void;
|
||||
}
|
||||
|
||||
/** Typed accessor for the last mock WebSocket instance stashed on globalThis. */
|
||||
const globalWithMock = globalThis as typeof globalThis & {
|
||||
__lastMockWs: MockWs | null;
|
||||
};
|
||||
|
||||
// Mock the 'ws' module
|
||||
vi.mock('ws', async () => {
|
||||
const { EventEmitter } = await import('node:events');
|
||||
|
||||
class MockWebSocket extends EventEmitter {
|
||||
readyState = 1; // OPEN
|
||||
sent: string[] = [];
|
||||
|
||||
send(data: string) {
|
||||
this.sent.push(data);
|
||||
}
|
||||
|
||||
close() {
|
||||
this.readyState = 3; // CLOSED
|
||||
this.emit('close');
|
||||
}
|
||||
}
|
||||
|
||||
// Store last instance for test access
|
||||
(globalThis as typeof globalThis & { __lastMockWs: MockWs | null }).__lastMockWs = null;
|
||||
|
||||
return {
|
||||
default: class extends MockWebSocket {
|
||||
constructor(_url: string) {
|
||||
super();
|
||||
(globalThis as typeof globalThis & { __lastMockWs: MockWs | null }).__lastMockWs = this;
|
||||
// Simulate async open
|
||||
setTimeout(() => this.emit('open'), 5);
|
||||
}
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
function getLastWs(): MockWs {
|
||||
const ws = globalWithMock.__lastMockWs;
|
||||
if (!ws) throw new Error('No mock WebSocket instance available');
|
||||
return ws;
|
||||
}
|
||||
|
||||
describe('WsTeamClient', () => {
|
||||
const config = {
|
||||
serverUrl: 'http://team.example.com',
|
||||
token: 'test-jwt-token',
|
||||
teamSlug: 'my-team',
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
globalWithMock.__lastMockWs = null;
|
||||
});
|
||||
|
||||
it('stores config in constructor', () => {
|
||||
const client = new WsTeamClient(config);
|
||||
expect(client).toBeDefined();
|
||||
expect(client.isConnected()).toBe(false);
|
||||
});
|
||||
|
||||
it('sends authenticate on WebSocket open', async () => {
|
||||
const client = new WsTeamClient(config);
|
||||
await client.connect();
|
||||
|
||||
// Wait for 'open' event
|
||||
await new Promise(r => setTimeout(r, 20));
|
||||
|
||||
const ws = getLastWs();
|
||||
expect(ws).toBeTruthy();
|
||||
expect(ws.sent.length).toBeGreaterThanOrEqual(1);
|
||||
|
||||
const authMsg = JSON.parse(ws.sent[0]);
|
||||
expect(authMsg.type).toBe('authenticate');
|
||||
expect(authMsg.token).toBe('test-jwt-token');
|
||||
|
||||
client.disconnect();
|
||||
});
|
||||
|
||||
it('sends join_team after authenticated response', async () => {
|
||||
const client = new WsTeamClient(config);
|
||||
await client.connect();
|
||||
await new Promise(r => setTimeout(r, 20));
|
||||
|
||||
const ws = getLastWs();
|
||||
|
||||
// Simulate server responding with authenticated
|
||||
ws.emit('message', JSON.stringify({ type: 'authenticated', userId: 'user-123' }));
|
||||
|
||||
// Should have sent join_team
|
||||
const joinMsg = JSON.parse(ws.sent[ws.sent.length - 1]);
|
||||
expect(joinMsg.type).toBe('join_team');
|
||||
expect(joinMsg.teamSlug).toBe('my-team');
|
||||
|
||||
client.disconnect();
|
||||
});
|
||||
|
||||
it('emits message event on waggle_message', async () => {
|
||||
const client = new WsTeamClient(config);
|
||||
const messages: unknown[] = [];
|
||||
client.on('message', (msg) => messages.push(msg));
|
||||
|
||||
await client.connect();
|
||||
await new Promise(r => setTimeout(r, 20));
|
||||
|
||||
const ws = getLastWs();
|
||||
|
||||
// Simulate waggle_message
|
||||
const testMessage = { type: 'request', subtype: 'knowledge_check', content: { query: 'test' } };
|
||||
ws.emit('message', JSON.stringify({ type: 'waggle_message', message: testMessage }));
|
||||
|
||||
expect(messages).toHaveLength(1);
|
||||
expect(messages[0]).toEqual(testMessage);
|
||||
|
||||
client.disconnect();
|
||||
});
|
||||
|
||||
it('emits connected event on joined_team', async () => {
|
||||
const client = new WsTeamClient(config);
|
||||
const connected: Array<{ teamSlug?: string }> = [];
|
||||
client.on('connected', (data) => connected.push(data));
|
||||
|
||||
await client.connect();
|
||||
await new Promise(r => setTimeout(r, 20));
|
||||
|
||||
const ws = getLastWs();
|
||||
|
||||
// Full protocol flow
|
||||
ws.emit('message', JSON.stringify({ type: 'authenticated', userId: 'user-123' }));
|
||||
ws.emit('message', JSON.stringify({ type: 'joined_team', teamSlug: 'my-team' }));
|
||||
|
||||
expect(connected).toHaveLength(1);
|
||||
expect(connected[0].teamSlug).toBe('my-team');
|
||||
|
||||
client.disconnect();
|
||||
});
|
||||
|
||||
it('isConnected returns true after authentication', async () => {
|
||||
const client = new WsTeamClient(config);
|
||||
|
||||
expect(client.isConnected()).toBe(false);
|
||||
|
||||
await client.connect();
|
||||
await new Promise(r => setTimeout(r, 20));
|
||||
|
||||
const ws = getLastWs();
|
||||
ws.emit('message', JSON.stringify({ type: 'authenticated', userId: 'user-123' }));
|
||||
|
||||
expect(client.isConnected()).toBe(true);
|
||||
|
||||
client.disconnect();
|
||||
expect(client.isConnected()).toBe(false);
|
||||
});
|
||||
|
||||
it('disconnect stops reconnection and closes WebSocket', async () => {
|
||||
const client = new WsTeamClient(config);
|
||||
await client.connect();
|
||||
await new Promise(r => setTimeout(r, 20));
|
||||
|
||||
client.disconnect();
|
||||
|
||||
expect(client.isConnected()).toBe(false);
|
||||
});
|
||||
|
||||
it('handles invalid JSON messages gracefully', async () => {
|
||||
const client = new WsTeamClient(config);
|
||||
await client.connect();
|
||||
await new Promise(r => setTimeout(r, 20));
|
||||
|
||||
const ws = getLastWs();
|
||||
|
||||
// Should not throw
|
||||
ws.emit('message', 'not-json{{{');
|
||||
ws.emit('message', '');
|
||||
|
||||
client.disconnect();
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user