refactor(cli): run local mode only (P1.1)

Team mode is not part of the community edition (ADR-0003), so the CLI
no longer detects or switches to it.

- Remove the mode detector, the --local and --team flags, the Clerk
  browser login (/login, /logout, /whoami) and /mode.
- Remove the /admin command and its team-server REST client.
- The welcome banner drops the Mode line.
- The installed-REPL test starts plain `waggle` and checks that the team
  commands are gone.
This commit is contained in:
shumeiko.it
2026-10-24 16:39:00 +02:00
parent d51ea0aed5
commit 697517d378
11 changed files with 11 additions and 657 deletions

View File

@@ -47,7 +47,7 @@
},
"scripts": {
"build": "tsc",
"test": "node ../../node_modules/vitest/vitest.mjs run --root ../.. --config vitest.config.ts packages/cli/tests/commands.test.ts packages/cli/tests/admin.test.ts packages/cli/tests/renderer.test.ts packages/cli/tests/memory-persistence-hard.test.ts packages/cli/tests/auth.test.ts packages/cli/tests/mode-detector.test.ts packages/cli/tests/comprehensive-e2e.test.ts packages/cli/tests/cli-runtime.test.ts",
"test": "node ../../node_modules/vitest/vitest.mjs run --root ../.. --config vitest.config.ts packages/cli/tests/commands.test.ts packages/cli/tests/renderer.test.ts packages/cli/tests/memory-persistence-hard.test.ts packages/cli/tests/comprehensive-e2e.test.ts packages/cli/tests/cli-runtime.test.ts",
"dev": "tsx --conditions=source src/index.ts"
},
"dependencies": {

View File

@@ -1,147 +0,0 @@
import { readFileSync, writeFileSync, mkdirSync, existsSync } from 'node:fs';
import { join } from 'node:path';
import { homedir } from 'node:os';
import { createServer } from 'node:http';
import { execFile } from 'node:child_process';
import { URL } from 'node:url';
const DEFAULT_CONFIG_DIR = join(homedir(), '.waggle');
const DEFAULT_SERVER_URL = 'http://localhost:3000';
const LOGIN_TIMEOUT_MS = 5 * 60 * 1000; // 5 minutes
interface AuthData {
token: string;
email: string;
serverUrl: string;
}
interface WaggleConfig {
auth?: AuthData;
[key: string]: unknown;
}
export class AuthManager {
private configDir: string;
private configPath: string;
constructor(configDir?: string) {
this.configDir = configDir ?? DEFAULT_CONFIG_DIR;
this.configPath = join(this.configDir, 'config.json');
}
getToken(): string | null {
const auth = this.readAuth();
return auth?.token ?? null;
}
getEmail(): string | null {
const auth = this.readAuth();
return auth?.email ?? null;
}
getServerUrl(): string {
const auth = this.readAuth();
return auth?.serverUrl ?? DEFAULT_SERVER_URL;
}
isLoggedIn(): boolean {
return this.getToken() !== null;
}
saveToken(token: string, email: string): void {
const config = this.readConfig();
config.auth = {
token,
email,
serverUrl: config.auth?.serverUrl ?? DEFAULT_SERVER_URL,
};
this.writeConfig(config);
}
logout(): void {
const config = this.readConfig();
delete config.auth;
this.writeConfig(config);
}
async loginWithBrowser(clerkUrl: string): Promise<{ token: string; email: string }> {
return new Promise((resolve, reject) => {
const server = createServer((req, res) => {
if (!req.url?.startsWith('/callback')) {
res.writeHead(404);
res.end('Not found');
return;
}
const url = new URL(req.url, `http://127.0.0.1`);
const token = url.searchParams.get('token');
const email = url.searchParams.get('email');
if (!token || !email) {
res.writeHead(400, { 'Content-Type': 'text/html' });
res.end('<html><body><h1>Login failed</h1><p>Missing token or email.</p></body></html>');
return;
}
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end('<html><body><h1>Login successful!</h1><p>You can close this tab and return to the terminal.</p></body></html>');
clearTimeout(timeout);
server.close();
resolve({ token, email });
});
server.listen(0, '127.0.0.1', () => {
const address = server.address();
if (!address || typeof address === 'string') {
reject(new Error('Failed to start callback server'));
return;
}
const port = address.port;
const redirectUrl = `http://127.0.0.1:${port}/callback`;
const loginUrl = `${clerkUrl}?redirect_url=${encodeURIComponent(redirectUrl)}`;
openBrowser(loginUrl);
});
const timeout = setTimeout(() => {
server.close();
reject(new Error('Login timed out after 5 minutes'));
}, LOGIN_TIMEOUT_MS);
});
}
private readAuth(): AuthData | null {
const config = this.readConfig();
return config.auth ?? null;
}
private readConfig(): WaggleConfig {
try {
if (!existsSync(this.configPath)) return {};
const raw = readFileSync(this.configPath, 'utf-8');
const parsed: unknown = JSON.parse(raw);
if (parsed && typeof parsed === 'object') {
return parsed as WaggleConfig;
}
return {};
} catch {
return {};
}
}
private writeConfig(config: WaggleConfig): void {
mkdirSync(this.configDir, { recursive: true });
writeFileSync(this.configPath, JSON.stringify(config, null, 2));
}
}
export function openBrowser(url: string): void {
const platform = process.platform;
if (platform === 'win32') {
execFile('cmd.exe', ['/c', 'start', '""', url]);
} else if (platform === 'darwin') {
execFile('open', [url]);
} else {
execFile('xdg-open', [url]);
}
}

View File

@@ -39,11 +39,6 @@ export const COMMANDS: Record<string, string> = {
clear: '/clear — Clear conversation history',
help: '/help — Show this help message',
identity: '/identity — Show agent identity',
admin: '/admin <cmd> — Admin commands (teams|jobs|cron|audit|stats)',
login: '/login — Log in via browser (Clerk OAuth)',
logout: '/logout — Log out and clear stored token',
whoami: '/whoami — Show current user and mode',
mode: '/mode — Show current mode (local/team)',
cost: '/cost — Show token usage and estimated cost',
plan: '/plan — Show current execution plan',
git: '/git — Show git status for workspace',

View File

@@ -1,78 +0,0 @@
/**
* Admin CLI client for Waggle server REST API.
*
* Provides methods to manage teams, jobs, cron schedules,
* audit logs, and usage stats from the CLI.
*/
const DEFAULT_API_BASE = 'http://localhost:3100';
export class AdminClient {
private readonly apiBase: string;
private readonly token: string;
constructor(apiBase?: string, token?: string) {
this.apiBase = apiBase ?? process.env.WAGGLE_API_URL ?? DEFAULT_API_BASE;
this.token = token ?? process.env.WAGGLE_TOKEN ?? '';
}
private async request<T = unknown>(path: string): Promise<T> {
const res = await fetch(`${this.apiBase}${path}`, {
headers: {
Authorization: `Bearer ${this.token}`,
'Content-Type': 'application/json',
},
});
if (!res.ok) {
const body = await res.text().catch(() => '');
throw new Error(`API ${res.status}: ${body || res.statusText}`);
}
return res.json() as Promise<T>;
}
/** List all teams the authenticated user has access to. */
async listTeams(): Promise<unknown> {
return this.request('/api/teams');
}
/** List agent jobs, optionally filtered by team slug. */
async listJobs(teamSlug: string): Promise<unknown> {
return this.request(`/api/jobs?teamSlug=${encodeURIComponent(teamSlug)}`);
}
/** List cron schedules for a team. */
async listCron(teamSlug: string): Promise<unknown> {
return this.request(`/api/teams/${encodeURIComponent(teamSlug)}/cron`);
}
/** List audit log entries for a team. */
async listAudit(teamSlug: string): Promise<unknown> {
return this.request(`/api/admin/teams/${encodeURIComponent(teamSlug)}/audit`);
}
/** Get usage statistics for a team. */
async getStats(teamSlug: string): Promise<unknown> {
return this.request(`/api/admin/teams/${encodeURIComponent(teamSlug)}/usage`);
}
}
/**
* Format admin data as a simple table for CLI output.
* Takes an array of objects and prints key-value columns.
*/
export function formatTable(rows: Record<string, unknown>[], columns?: string[]): string {
if (rows.length === 0) return ' (no data)';
const keys = columns ?? Object.keys(rows[0]);
const widths = keys.map((k) =>
Math.max(k.length, ...rows.map((r) => String(r[k] ?? '').length)),
);
const header = keys.map((k, i) => k.padEnd(widths[i])).join(' ');
const separator = widths.map((w) => '-'.repeat(w)).join(' ');
const body = rows
.map((r) => keys.map((k, i) => String(r[k] ?? '').padEnd(widths[i])).join(' '))
.join('\n');
return ` ${header}\n ${separator}\n ${body}`;
}

View File

@@ -14,8 +14,6 @@ Waggle CLI — interactive AI agent with persistent memory
Usage:
waggle Start interactive REPL
waggle --model <name> Start with a specific model
waggle --local Force local mode (no server)
waggle --team Force team mode (requires login)
waggle --help Show this help message
Configuration:
@@ -25,7 +23,6 @@ Commands (inside REPL):
/model <name> Switch model
/models List available models
/identity Show agent identity
/admin <cmd> Admin commands (teams|jobs|cron|audit|stats)
/clear Clear conversation
/help Show commands
/exit Quit
@@ -45,12 +42,9 @@ if (modelIdx !== -1 && args[modelIdx + 1]) {
model = args[modelIdx + 1];
}
const local = args.includes('--local');
const team = args.includes('--team');
async function main(): Promise<void> {
const { startRepl } = await import('./repl.js');
await startRepl({ model, local, team });
await startRepl({ model });
}
main().catch((err) => {

View File

@@ -1,56 +0,0 @@
export type WaggleMode = {
type: 'local' | 'team' | 'error';
warning?: string;
error?: string;
};
export interface ModeDetectorDeps {
hasToken: boolean;
serverUrl: string;
forceLocal: boolean;
forceTeam: boolean;
healthCheck: (serverUrl: string) => Promise<boolean>;
}
export async function detectMode(deps: ModeDetectorDeps): Promise<WaggleMode> {
// 1. --local flag → always local mode
if (deps.forceLocal) {
return { type: 'local' };
}
// 2. --team flag + no token → error
if (deps.forceTeam && !deps.hasToken) {
return { type: 'error', error: 'Team mode requires login. Run: waggle login' };
}
// 3. --team flag + token → team mode
if (deps.forceTeam && deps.hasToken) {
return { type: 'team' };
}
// 4. No token → local mode
if (!deps.hasToken) {
return { type: 'local' };
}
// 5. Token + server reachable → team mode
const reachable = await deps.healthCheck(deps.serverUrl);
if (reachable) {
return { type: 'team' };
}
// 6. Token + server unreachable → local mode with warning
return { type: 'local', warning: 'Server unreachable — running in local mode.' };
}
export async function checkServerHealth(serverUrl: string): Promise<boolean> {
try {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 3000);
const response = await fetch(`${serverUrl}/health`, { signal: controller.signal });
clearTimeout(timeout);
return response.ok;
} catch {
return false;
}
}

View File

@@ -16,14 +16,9 @@ import { createMem0MemoryStore } from '@waggle/memory-mem0';
import { Orchestrator, ModelRouter, runAgentLoop, createSystemTools, createPlanTools, createGitTools, Workspace, ensureIdentity, loadSystemPromptWithOverrides, loadSkills, CostTracker, HookRegistry, loadHooksFromConfig, needsConfirmation } from '@waggle/agent';
import { parseCommand, COMMANDS } from './commands.js';
import { renderMarkdown } from './renderer.js';
import { AdminClient, formatTable } from './commands/admin.js';
import { AuthManager } from './auth.js';
import { detectMode, checkServerHealth } from './mode-detector.js';
export interface ReplOptions {
model?: string;
local?: boolean;
team?: boolean;
}
export async function startRepl(options: ReplOptions = {}): Promise<void> {
@@ -58,21 +53,6 @@ export async function startRepl(options: ReplOptions = {}): Promise<void> {
const hookRegistry = new HookRegistry();
await loadHooksFromConfig(path.join(waggleHome, 'hooks.json'), hookRegistry);
// Detect mode
const auth = new AuthManager();
const modeResult = await detectMode({
hasToken: auth.isLoggedIn(),
serverUrl: auth.getServerUrl(),
forceLocal: options.local ?? false,
forceTeam: options.team ?? false,
healthCheck: checkServerHealth,
});
if (modeResult.type === 'error') {
console.log(chalk.red(modeResult.error ?? 'Mode detection failed.'));
process.exit(1);
}
// Get LiteLLM config from workspace
const wsConfig = workspace.getConfig();
const litellmUrl = wsConfig.litellmUrl ?? 'http://localhost:4000/v1';
@@ -111,14 +91,10 @@ export async function startRepl(options: ReplOptions = {}): Promise<void> {
console.log('');
console.log(chalk.bold.magenta(' Waggle') + chalk.dim(' — AI agent with persistent memory'));
console.log(chalk.dim(' ─────────────────────────────────────'));
console.log(chalk.dim(' Mode: ') + chalk.cyan(modeResult.type));
console.log(chalk.dim(' Model: ') + chalk.cyan(currentModel));
console.log(chalk.dim(' Memory: ') + chalk.cyan(`${frameCount} memories`));
console.log(chalk.dim(' Store: ') + chalk.cyan(path.join(waggleHome, 'memory')));
console.log(chalk.dim(' Workspace:') + chalk.cyan(` ${process.cwd()}`));
if (modeResult.warning) {
console.log(chalk.yellow(' ⚠ ' + modeResult.warning));
}
console.log(chalk.dim(' Type /help for commands'));
console.log('');
@@ -221,40 +197,6 @@ export async function startRepl(options: ReplOptions = {}): Promise<void> {
break;
}
case 'login': {
try {
const clerkUrl = process.env.CLERK_URL ?? 'https://waggle.clerk.accounts.dev/sign-in';
console.log(chalk.dim('Opening browser for login...'));
const { token, email } = await auth.loginWithBrowser(clerkUrl);
auth.saveToken(token, email);
console.log(chalk.green(`Logged in as ${email}`));
} catch (err) {
console.log(chalk.red(`Login failed: ${(err as Error).message}`));
}
break;
}
case 'logout':
auth.logout();
console.log(chalk.dim('Logged out.'));
break;
case 'whoami': {
const email = auth.getEmail();
console.log('');
console.log(chalk.dim(' User: ') + (email ? chalk.cyan(email) : chalk.dim('not logged in')));
console.log(chalk.dim(' Mode: ') + chalk.cyan(modeResult.type));
console.log(chalk.dim(' Server: ') + chalk.cyan(auth.getServerUrl()));
if (modeResult.warning) console.log(chalk.yellow(' ⚠ ' + modeResult.warning));
console.log('');
break;
}
case 'mode':
console.log(chalk.dim(`Current mode: ${modeResult.type}`));
if (modeResult.warning) console.log(chalk.yellow(modeResult.warning));
break;
case 'cost':
console.log('');
console.log(chalk.dim(costTracker.formatSummary()));
@@ -283,67 +225,6 @@ export async function startRepl(options: ReplOptions = {}): Promise<void> {
break;
}
case 'admin': {
const adminClient = new AdminClient();
const parts = cmd.args.split(/\s+/);
const subCmd = parts[0] || '';
const teamSlug = parts[1] || '';
if (!subCmd) {
console.log('');
console.log(chalk.bold('Admin commands:'));
console.log(chalk.dim(' /admin teams — List teams'));
console.log(chalk.dim(' /admin jobs <team-slug> — List agent jobs'));
console.log(chalk.dim(' /admin cron <team-slug> — List cron schedules'));
console.log(chalk.dim(' /admin audit <team-slug> — List audit log'));
console.log(chalk.dim(' /admin stats <team-slug> — Show usage stats'));
console.log('');
console.log(chalk.dim(' Set WAGGLE_API_URL and WAGGLE_TOKEN env vars to connect.'));
console.log('');
break;
}
try {
let result: unknown;
switch (subCmd) {
case 'teams':
result = await adminClient.listTeams();
break;
case 'jobs':
if (!teamSlug) { console.log(chalk.red('Usage: /admin jobs <team-slug>')); break; }
result = await adminClient.listJobs(teamSlug);
break;
case 'cron':
if (!teamSlug) { console.log(chalk.red('Usage: /admin cron <team-slug>')); break; }
result = await adminClient.listCron(teamSlug);
break;
case 'audit':
if (!teamSlug) { console.log(chalk.red('Usage: /admin audit <team-slug>')); break; }
result = await adminClient.listAudit(teamSlug);
break;
case 'stats':
if (!teamSlug) { console.log(chalk.red('Usage: /admin stats <team-slug>')); break; }
result = await adminClient.getStats(teamSlug);
break;
default:
console.log(chalk.red(`Unknown admin command: ${subCmd}`));
console.log(chalk.dim('Type /admin for available commands.'));
}
if (result !== undefined) {
console.log('');
if (Array.isArray(result)) {
console.log(formatTable(result as Record<string, unknown>[]));
} else {
console.log(JSON.stringify(result, null, 2));
}
console.log('');
}
} catch (err) {
console.log(chalk.red(`Admin error: ${(err as Error).message}`));
}
break;
}
default:
console.log(chalk.red(`Unknown command: /${cmd.name}`));
console.log(chalk.dim('Type /help for available commands.'));

View File

@@ -1,75 +0,0 @@
import { describe, it, expect } from 'vitest';
import { AdminClient, formatTable } from '../src/commands/admin.js';
describe('AdminClient', () => {
it('constructs with defaults', () => {
const client = new AdminClient();
expect(client).toBeInstanceOf(AdminClient);
});
it('constructs with custom base URL and token', () => {
const client = new AdminClient('http://localhost:9999', 'my-token');
expect(client).toBeInstanceOf(AdminClient);
});
it('has all admin methods', () => {
const client = new AdminClient('http://localhost:3100', 'test-token');
expect(typeof client.listTeams).toBe('function');
expect(typeof client.listJobs).toBe('function');
expect(typeof client.listCron).toBe('function');
expect(typeof client.listAudit).toBe('function');
expect(typeof client.getStats).toBe('function');
});
it('methods return promises', () => {
const client = new AdminClient('http://localhost:3100', 'test-token');
// These will fail to connect, but they should return promises
const p = client.listTeams();
expect(p).toBeInstanceOf(Promise);
// Suppress unhandled rejection
p.catch(() => {});
});
});
describe('formatTable', () => {
it('returns "(no data)" for empty array', () => {
expect(formatTable([])).toBe(' (no data)');
});
it('formats rows into aligned columns', () => {
const rows = [
{ id: '1', name: 'Alice', role: 'admin' },
{ id: '2', name: 'Bob', role: 'member' },
];
const result = formatTable(rows);
expect(result).toContain('id');
expect(result).toContain('name');
expect(result).toContain('role');
expect(result).toContain('Alice');
expect(result).toContain('Bob');
expect(result).toContain('admin');
expect(result).toContain('member');
});
it('respects explicit column selection', () => {
const rows = [
{ id: '1', name: 'Alice', secret: 'hidden' },
];
const result = formatTable(rows, ['id', 'name']);
expect(result).toContain('id');
expect(result).toContain('name');
expect(result).not.toContain('secret');
expect(result).not.toContain('hidden');
});
it('handles missing values gracefully', () => {
const rows = [
{ id: '1', name: 'Alice' },
{ id: '2' },
];
const result = formatTable(rows);
expect(result).toContain('Alice');
// Second row should have empty name
expect(result).toContain('2');
});
});

View File

@@ -1,90 +0,0 @@
import { describe, it, expect, afterEach } from 'vitest';
import { AuthManager } from '../src/auth.js';
import { mkdtempSync, rmSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
describe('AuthManager', () => {
let tempDir: string;
let auth: AuthManager;
function setup() {
tempDir = mkdtempSync(join(tmpdir(), 'waggle-auth-test-'));
auth = new AuthManager(tempDir);
}
afterEach(() => {
if (tempDir) {
rmSync(tempDir, { recursive: true, force: true });
}
});
it('returns null when no token stored', () => {
setup();
expect(auth.getToken()).toBeNull();
expect(auth.getEmail()).toBeNull();
});
it('saves and retrieves token', () => {
setup();
auth.saveToken('test-jwt-token', 'user@example.com');
expect(auth.getToken()).toBe('test-jwt-token');
expect(auth.getEmail()).toBe('user@example.com');
});
it('clears token on logout', () => {
setup();
auth.saveToken('test-jwt-token', 'user@example.com');
expect(auth.getToken()).toBe('test-jwt-token');
auth.logout();
expect(auth.getToken()).toBeNull();
expect(auth.getEmail()).toBeNull();
});
it('isLoggedIn returns true/false correctly', () => {
setup();
expect(auth.isLoggedIn()).toBe(false);
auth.saveToken('test-jwt-token', 'user@example.com');
expect(auth.isLoggedIn()).toBe(true);
auth.logout();
expect(auth.isLoggedIn()).toBe(false);
});
it('stores token in config.json file', () => {
setup();
auth.saveToken('file-check-token', 'file@example.com');
const configPath = join(tempDir, 'config.json');
const raw = readFileSync(configPath, 'utf-8');
const config = JSON.parse(raw);
expect(config.auth).toEqual({
token: 'file-check-token',
email: 'file@example.com',
serverUrl: 'http://localhost:3000',
});
});
it('getServerUrl returns default', () => {
setup();
expect(auth.getServerUrl()).toBe('http://localhost:3000');
});
it('preserves existing config keys when saving auth', () => {
setup();
// Write some pre-existing config
const configPath = join(tempDir, 'config.json');
try {
mkdirSync(tempDir, { recursive: true });
} catch {
// tempDir already exists from setup(); recursive mkdir is idempotent.
}
writeFileSync(configPath, JSON.stringify({ apiKey: 'sk-existing', model: 'claude' }));
auth.saveToken('my-token', 'me@test.com');
const raw = readFileSync(configPath, 'utf-8');
const config = JSON.parse(raw);
expect(config.apiKey).toBe('sk-existing');
expect(config.model).toBe('claude');
expect(config.auth.token).toBe('my-token');
});
});

View File

@@ -458,7 +458,7 @@ describe('@waggle/cli runtime UX', () => {
let stdout = '';
let stderr = '';
child = spawnInCwd(bin('npx'), ['waggle', '--local'], projectDir, home);
child = spawnInCwd(bin('npx'), ['waggle'], projectDir, home);
child.stdout.setEncoding('utf8');
child.stderr.setEncoding('utf8');
child.stdout.on('data', (chunk) => { stdout += chunk; });
@@ -484,9 +484,12 @@ describe('@waggle/cli runtime UX', () => {
await waitFor(() => expectedText.every((text) => stdout.includes(text)), 10_000);
};
await writeCommand('/help', ['Available commands:', '/models', '/whoami']);
await writeCommand('/mode', 'Current mode: local');
await writeCommand('/whoami', ['User:', 'not logged in', 'Server:']);
await writeCommand('/help', ['Available commands:', '/models', '/cost']);
// The CLI runs local mode only: team login and admin commands are gone (ADR-0003).
for (const teamCommand of ['login', 'logout', 'whoami', 'mode', 'admin']) {
expect(stdout).not.toMatch(new RegExp(`/${teamCommand}\\b`));
}
await writeCommand('/admin', 'Unknown command: /admin');
await writeCommand('/models', ['Available models:', 'No models configured']);
await writeCommand('/cost', ['Tokens: 0 in / 0 out', 'Est. cost: $0.0000']);
await writeCommand('/clear', 'Conversation cleared.');
@@ -496,10 +499,8 @@ describe('@waggle/cli runtime UX', () => {
expect(child.exitCode).toBe(0);
expect(stdout).toContain('Waggle');
expect(stdout).toContain('Mode:');
expect(stdout).toContain('local');
expect(stdout).not.toContain('Mode:');
expect(stdout).toContain('Available commands:');
expect(stdout).toContain('Current mode: local');
expect(stdout).toContain('No models configured');
expect(stdout).toContain('Conversation cleared.');
expect(stdout).toContain('Goodbye!');
@@ -592,7 +593,7 @@ describe('@waggle/cli runtime UX', () => {
let stderr = '';
child = spawnInCwd(
bin('npx'),
['waggle', '--local'],
['waggle'],
projectDir,
home,
{

View File

@@ -1,71 +0,0 @@
import { describe, it, expect, vi } from 'vitest';
import { detectMode, type ModeDetectorDeps } from '../src/mode-detector.js';
function makeDeps(overrides: Partial<ModeDetectorDeps> = {}): ModeDetectorDeps {
return {
hasToken: false,
serverUrl: 'http://localhost:3000',
forceLocal: false,
forceTeam: false,
healthCheck: vi.fn().mockResolvedValue(true),
...overrides,
};
}
describe('detectMode', () => {
it('returns local when no token', async () => {
const result = await detectMode(makeDeps({ hasToken: false }));
expect(result).toEqual({ type: 'local' });
});
it('returns team when token + server reachable', async () => {
const result = await detectMode(makeDeps({
hasToken: true,
healthCheck: vi.fn().mockResolvedValue(true),
}));
expect(result).toEqual({ type: 'team' });
});
it('returns local with warning when token + server unreachable', async () => {
const result = await detectMode(makeDeps({
hasToken: true,
healthCheck: vi.fn().mockResolvedValue(false),
}));
expect(result).toEqual({
type: 'local',
warning: 'Server unreachable — running in local mode.',
});
});
it('returns local when --local forced', async () => {
const result = await detectMode(makeDeps({
hasToken: true,
forceLocal: true,
healthCheck: vi.fn().mockResolvedValue(true),
}));
expect(result).toEqual({ type: 'local' });
});
it('returns team when --team forced + token', async () => {
const healthCheck = vi.fn().mockResolvedValue(false);
const result = await detectMode(makeDeps({
hasToken: true,
forceTeam: true,
healthCheck,
}));
expect(result).toEqual({ type: 'team' });
// Should not even check health when forced
expect(healthCheck).not.toHaveBeenCalled();
});
it('returns error when --team forced + no token', async () => {
const result = await detectMode(makeDeps({
hasToken: false,
forceTeam: true,
}));
expect(result).toEqual({
type: 'error',
error: 'Team mode requires login. Run: waggle login',
});
});
});