refactor: remove web dashboard, Android app and Glasses UI
WEB_DASHBOARD_ENABLED defaulted to false and was never set, so nothing served the dashboard. Remove the server/routes, apps/dashboard, apps/android, the dashboard-only settings modules (settings-store, settings-store-moa, room-skill-settings, runtime-inventory, codex-live-status, settings-effort), WEB_DASHBOARD_* config, the web-dashboard-only startup mode, dashboard/android scripts and the react/vite/playwright dependencies. The Codex account refresh loop in settings-store is dropped with it: it refreshed account index 0 through the shared ~/.codex/auth.json instead of the isolated ~/.codex-accounts/0 used by the reviewer. Host evidence loses the dashboard_dist / android_debug_apk artifact kinds. The Discord status dashboard is unchanged. Room skill overrides are still read from the DB by agent-runner. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,245 +0,0 @@
|
||||
export interface CodexRateLimitWindowSummary {
|
||||
limitWindowSeconds: number | null;
|
||||
resetAfterSeconds: number | null;
|
||||
resetAt: string | null;
|
||||
usedPercent: number | null;
|
||||
}
|
||||
|
||||
export interface CodexRateLimitSummary {
|
||||
allowed: boolean | null;
|
||||
limitReached: boolean | null;
|
||||
primaryWindow: CodexRateLimitWindowSummary | null;
|
||||
secondaryWindow: CodexRateLimitWindowSummary | null;
|
||||
}
|
||||
|
||||
export interface CodexAdditionalRateLimitSummary {
|
||||
limitName: string | null;
|
||||
meteredFeature: string | null;
|
||||
rateLimit: CodexRateLimitSummary | null;
|
||||
}
|
||||
|
||||
export interface CodexCreditsSummary {
|
||||
hasCredits: boolean | null;
|
||||
overageLimitReached: boolean | null;
|
||||
unlimited: boolean | null;
|
||||
}
|
||||
|
||||
export interface CodexSpendControlSummary {
|
||||
reached: boolean | null;
|
||||
}
|
||||
|
||||
export interface CodexLiveStatusSummary {
|
||||
checkedAt: string;
|
||||
source: 'wham/usage';
|
||||
planType: string | null;
|
||||
email: string | null;
|
||||
rateLimit: CodexRateLimitSummary | null;
|
||||
rateLimitReachedType: string | null;
|
||||
additionalRateLimits: CodexAdditionalRateLimitSummary[];
|
||||
credits: CodexCreditsSummary | null;
|
||||
spendControl: CodexSpendControlSummary | null;
|
||||
}
|
||||
|
||||
interface CodexLiveRateLimitWindow {
|
||||
limit_window_seconds?: number | null;
|
||||
reset_after_seconds?: number | null;
|
||||
reset_at?: number | null;
|
||||
used_percent?: number | null;
|
||||
}
|
||||
|
||||
interface CodexLiveRateLimit {
|
||||
allowed?: boolean | null;
|
||||
limit_reached?: boolean | null;
|
||||
primary_window?: CodexLiveRateLimitWindow | null;
|
||||
secondary_window?: CodexLiveRateLimitWindow | null;
|
||||
}
|
||||
|
||||
interface CodexAdditionalLiveRateLimit {
|
||||
limit_name?: string | null;
|
||||
metered_feature?: string | null;
|
||||
rate_limit?: CodexLiveRateLimit | null;
|
||||
}
|
||||
|
||||
interface CodexLiveCredits {
|
||||
has_credits?: boolean | null;
|
||||
overage_limit_reached?: boolean | null;
|
||||
unlimited?: boolean | null;
|
||||
}
|
||||
|
||||
interface CodexLiveSpendControl {
|
||||
reached?: boolean | null;
|
||||
}
|
||||
|
||||
export interface CodexLiveStatus {
|
||||
checked_at: string;
|
||||
plan_type?: string | null;
|
||||
email?: string | null;
|
||||
rate_limit?: CodexLiveRateLimit | null;
|
||||
rate_limit_reached_type?: string | null;
|
||||
additional_rate_limits?: CodexAdditionalLiveRateLimit[];
|
||||
credits?: CodexLiveCredits | null;
|
||||
spend_control?: CodexLiveSpendControl | null;
|
||||
}
|
||||
|
||||
function recordOrNull(value: unknown): Record<string, unknown> | null {
|
||||
return value && typeof value === 'object' && !Array.isArray(value)
|
||||
? (value as Record<string, unknown>)
|
||||
: null;
|
||||
}
|
||||
|
||||
function stringOrNull(value: unknown): string | null {
|
||||
return typeof value === 'string' ? value : null;
|
||||
}
|
||||
|
||||
function numberOrNull(value: unknown): number | null {
|
||||
if (typeof value === 'number' && Number.isFinite(value)) return value;
|
||||
if (typeof value === 'string' && value.trim() !== '') {
|
||||
const parsed = Number(value);
|
||||
return Number.isFinite(parsed) ? parsed : null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function booleanOrNull(value: unknown): boolean | null {
|
||||
return typeof value === 'boolean' ? value : null;
|
||||
}
|
||||
|
||||
function epochSecondsToIso(value: number | null | undefined): string | null {
|
||||
if (typeof value !== 'number' || !Number.isFinite(value)) return null;
|
||||
return new Date(value * 1000).toISOString();
|
||||
}
|
||||
|
||||
function normalizeRateLimitWindow(
|
||||
value: unknown,
|
||||
): CodexLiveRateLimitWindow | null {
|
||||
const record = recordOrNull(value);
|
||||
if (!record) return null;
|
||||
return {
|
||||
limit_window_seconds: numberOrNull(record.limit_window_seconds),
|
||||
reset_after_seconds: numberOrNull(record.reset_after_seconds),
|
||||
reset_at: numberOrNull(record.reset_at),
|
||||
used_percent: numberOrNull(record.used_percent),
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeRateLimit(value: unknown): CodexLiveRateLimit | null {
|
||||
const record = recordOrNull(value);
|
||||
if (!record) return null;
|
||||
return {
|
||||
allowed: booleanOrNull(record.allowed),
|
||||
limit_reached: booleanOrNull(record.limit_reached),
|
||||
primary_window: normalizeRateLimitWindow(record.primary_window),
|
||||
secondary_window: normalizeRateLimitWindow(record.secondary_window),
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeAdditionalRateLimits(
|
||||
value: unknown,
|
||||
): CodexAdditionalLiveRateLimit[] {
|
||||
if (!Array.isArray(value)) return [];
|
||||
return value
|
||||
.map((item): CodexAdditionalLiveRateLimit | null => {
|
||||
const record = recordOrNull(item);
|
||||
if (!record) return null;
|
||||
return {
|
||||
limit_name: stringOrNull(record.limit_name),
|
||||
metered_feature: stringOrNull(record.metered_feature),
|
||||
rate_limit: normalizeRateLimit(record.rate_limit),
|
||||
};
|
||||
})
|
||||
.filter((item): item is CodexAdditionalLiveRateLimit => item !== null);
|
||||
}
|
||||
|
||||
function normalizeCredits(value: unknown): CodexLiveCredits | null {
|
||||
const record = recordOrNull(value);
|
||||
if (!record) return null;
|
||||
return {
|
||||
has_credits: booleanOrNull(record.has_credits),
|
||||
overage_limit_reached: booleanOrNull(record.overage_limit_reached),
|
||||
unlimited: booleanOrNull(record.unlimited),
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeSpendControl(value: unknown): CodexLiveSpendControl | null {
|
||||
const record = recordOrNull(value);
|
||||
if (!record) return null;
|
||||
return {
|
||||
reached: booleanOrNull(record.reached),
|
||||
};
|
||||
}
|
||||
|
||||
export function normalizeCodexLiveStatus(
|
||||
value: unknown,
|
||||
checkedAt: string,
|
||||
): CodexLiveStatus | null {
|
||||
const record = recordOrNull(value);
|
||||
if (!record) return null;
|
||||
return {
|
||||
checked_at: checkedAt,
|
||||
plan_type: stringOrNull(record.plan_type),
|
||||
email: stringOrNull(record.email),
|
||||
rate_limit: normalizeRateLimit(record.rate_limit),
|
||||
rate_limit_reached_type: stringOrNull(record.rate_limit_reached_type),
|
||||
additional_rate_limits: normalizeAdditionalRateLimits(
|
||||
record.additional_rate_limits,
|
||||
),
|
||||
credits: normalizeCredits(record.credits),
|
||||
spend_control: normalizeSpendControl(record.spend_control),
|
||||
};
|
||||
}
|
||||
|
||||
function toRateLimitWindowSummary(
|
||||
window: CodexLiveRateLimitWindow | null | undefined,
|
||||
): CodexRateLimitWindowSummary | null {
|
||||
if (!window) return null;
|
||||
return {
|
||||
limitWindowSeconds: window.limit_window_seconds ?? null,
|
||||
resetAfterSeconds: window.reset_after_seconds ?? null,
|
||||
resetAt: epochSecondsToIso(window.reset_at),
|
||||
usedPercent: window.used_percent ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
function toRateLimitSummary(
|
||||
rateLimit: CodexLiveRateLimit | null | undefined,
|
||||
): CodexRateLimitSummary | null {
|
||||
if (!rateLimit) return null;
|
||||
return {
|
||||
allowed: rateLimit.allowed ?? null,
|
||||
limitReached: rateLimit.limit_reached ?? null,
|
||||
primaryWindow: toRateLimitWindowSummary(rateLimit.primary_window),
|
||||
secondaryWindow: toRateLimitWindowSummary(rateLimit.secondary_window),
|
||||
};
|
||||
}
|
||||
|
||||
export function toCodexLiveStatusSummary(
|
||||
status: CodexLiveStatus,
|
||||
): CodexLiveStatusSummary {
|
||||
return {
|
||||
checkedAt: status.checked_at,
|
||||
source: 'wham/usage',
|
||||
planType: status.plan_type ?? null,
|
||||
email: status.email ?? null,
|
||||
rateLimit: toRateLimitSummary(status.rate_limit),
|
||||
rateLimitReachedType: status.rate_limit_reached_type ?? null,
|
||||
additionalRateLimits: (status.additional_rate_limits ?? []).map(
|
||||
(limit) => ({
|
||||
limitName: limit.limit_name ?? null,
|
||||
meteredFeature: limit.metered_feature ?? null,
|
||||
rateLimit: toRateLimitSummary(limit.rate_limit),
|
||||
}),
|
||||
),
|
||||
credits: status.credits
|
||||
? {
|
||||
hasCredits: status.credits.has_credits ?? null,
|
||||
overageLimitReached: status.credits.overage_limit_reached ?? null,
|
||||
unlimited: status.credits.unlimited ?? null,
|
||||
}
|
||||
: null,
|
||||
spendControl: status.spend_control
|
||||
? {
|
||||
reached: status.spend_control.reached ?? null,
|
||||
}
|
||||
: null,
|
||||
};
|
||||
}
|
||||
@@ -42,11 +42,6 @@ describe('config/env loading', () => {
|
||||
delete process.env.CODEX_WARMUP_COMMAND_TIMEOUT_MS;
|
||||
delete process.env.CODEX_WARMUP_FAILURE_COOLDOWN_MS;
|
||||
delete process.env.CODEX_WARMUP_MAX_CONSECUTIVE_FAILURES;
|
||||
delete process.env.WEB_DASHBOARD_ENABLED;
|
||||
delete process.env.WEB_DASHBOARD_HOST;
|
||||
delete process.env.WEB_DASHBOARD_PORT;
|
||||
delete process.env.WEB_DASHBOARD_STATIC_DIR;
|
||||
delete process.env.WEB_DASHBOARD_TOKEN;
|
||||
delete process.env.SESSION_COMMAND_USER_IDS;
|
||||
vi.resetModules();
|
||||
});
|
||||
@@ -168,33 +163,6 @@ describe('config/env loading', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('keeps the web dashboard disabled by default and loads explicit bind/static settings', async () => {
|
||||
let config = await import('./config.js');
|
||||
expect(config.WEB_DASHBOARD.enabled).toBe(false);
|
||||
expect(config.WEB_DASHBOARD.host).toBe('127.0.0.1');
|
||||
expect(config.WEB_DASHBOARD.port).toBe(8734);
|
||||
expect(config.WEB_DASHBOARD.staticDir).toBe(
|
||||
path.resolve(tempRoot, 'apps', 'dashboard', 'dist'),
|
||||
);
|
||||
expect(config.WEB_DASHBOARD.token).toBe('');
|
||||
|
||||
vi.resetModules();
|
||||
process.env.WEB_DASHBOARD_ENABLED = 'true';
|
||||
process.env.WEB_DASHBOARD_HOST = '0.0.0.0';
|
||||
process.env.WEB_DASHBOARD_PORT = '9001';
|
||||
process.env.WEB_DASHBOARD_STATIC_DIR = './custom-dashboard-dist';
|
||||
process.env.WEB_DASHBOARD_TOKEN = 'mobile-secret';
|
||||
config = await import('./config.js');
|
||||
|
||||
expect(config.WEB_DASHBOARD).toEqual({
|
||||
enabled: true,
|
||||
host: '0.0.0.0',
|
||||
port: 9001,
|
||||
staticDir: path.resolve(tempRoot, 'custom-dashboard-dist'),
|
||||
token: 'mobile-secret',
|
||||
});
|
||||
});
|
||||
|
||||
it('fails fast when a legacy Discord token alias is configured', async () => {
|
||||
process.env.DISCORD_BOT_TOKEN = 'legacy...oken';
|
||||
|
||||
|
||||
@@ -149,7 +149,6 @@ export const STATUS_SHOW_ROOMS = CONFIG.status.showRooms;
|
||||
export const STATUS_SHOW_ROOM_DETAILS = CONFIG.status.showRoomDetails;
|
||||
export const USAGE_DASHBOARD_ENABLED = CONFIG.status.usageDashboardEnabled;
|
||||
export const CODEX_WARMUP_CONFIG = CONFIG.codexWarmup;
|
||||
export const WEB_DASHBOARD = CONFIG.webDashboard;
|
||||
|
||||
// Timezone for scheduled tasks (cron expressions, etc.)
|
||||
// Uses system timezone by default
|
||||
|
||||
@@ -269,16 +269,6 @@ export function loadConfig(): AppConfig {
|
||||
timezone:
|
||||
readText('TZ') ?? Intl.DateTimeFormat().resolvedOptions().timeZone,
|
||||
},
|
||||
webDashboard: {
|
||||
enabled: readBoolean('WEB_DASHBOARD_ENABLED', false),
|
||||
host: readNonEmptyText('WEB_DASHBOARD_HOST') ?? '127.0.0.1',
|
||||
port: readIntegerAtLeast('WEB_DASHBOARD_PORT', 8734, 1),
|
||||
staticDir: path.resolve(
|
||||
readNonEmptyText('WEB_DASHBOARD_STATIC_DIR') ??
|
||||
path.join(projectRoot, 'apps', 'dashboard', 'dist'),
|
||||
),
|
||||
token: readNonEmptyText('WEB_DASHBOARD_TOKEN') ?? '',
|
||||
},
|
||||
codexWarmup: {
|
||||
enabled: readBoolean('CODEX_WARMUP_ENABLED', false),
|
||||
prompt:
|
||||
|
||||
@@ -79,13 +79,6 @@ export interface AppConfig {
|
||||
usageDashboardEnabled: boolean;
|
||||
timezone: string;
|
||||
};
|
||||
webDashboard: {
|
||||
enabled: boolean;
|
||||
host: string;
|
||||
port: number;
|
||||
staticDir: string;
|
||||
token: string;
|
||||
};
|
||||
codexWarmup: {
|
||||
enabled: boolean;
|
||||
prompt: string;
|
||||
|
||||
@@ -13,7 +13,7 @@ import type { SchemaMigrationDefinition } from './types.js';
|
||||
* applied migrations by version number alone, the upstream `turn_progress_text`
|
||||
* migration is skipped on the live DB and `paired_turns.progress_text` /
|
||||
* `progress_updated_at` are never created — even though merged runtime code
|
||||
* (src/db/paired-turns.ts, src/web-dashboard-data.ts) reads and writes them.
|
||||
* (src/db/paired-turns.ts) reads and writes them.
|
||||
*
|
||||
* This migration re-applies those columns idempotently under a fresh version
|
||||
* number so the live deployment gets them. It is a no-op on databases where
|
||||
|
||||
@@ -12,9 +12,7 @@ import {
|
||||
describe('deploy evidence helpers', () => {
|
||||
it('normalizes fixed artifact kinds', () => {
|
||||
expect(normalizeArtifactEvidenceKind()).toBe('build_outputs');
|
||||
expect(normalizeArtifactEvidenceKind('dashboard_dist')).toBe(
|
||||
'dashboard_dist',
|
||||
);
|
||||
expect(normalizeArtifactEvidenceKind('runner_dist')).toBe('runner_dist');
|
||||
expect(() => normalizeArtifactEvidenceKind('/etc/passwd')).toThrow(
|
||||
'Unsupported artifact evidence kind',
|
||||
);
|
||||
@@ -22,18 +20,16 @@ describe('deploy evidence helpers', () => {
|
||||
|
||||
it('returns metadata only for build artifacts', () => {
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'ejclaw-deploy-'));
|
||||
const dashboardDir = path.join(root, 'apps', 'dashboard', 'dist');
|
||||
fs.mkdirSync(path.join(dashboardDir, 'assets'), { recursive: true });
|
||||
fs.writeFileSync(path.join(dashboardDir, 'index.html'), '<html></html>');
|
||||
fs.writeFileSync(path.join(dashboardDir, 'assets', 'index.js'), 'secret');
|
||||
const runnerDist = path.join(root, 'runners', 'agent-runner', 'dist');
|
||||
fs.mkdirSync(runnerDist, { recursive: true });
|
||||
fs.writeFileSync(path.join(runnerDist, 'index.js'), 'secret');
|
||||
|
||||
const text = collectArtifactMetadata(
|
||||
{
|
||||
projectRoot: root,
|
||||
dataDir: path.join(root, 'data'),
|
||||
dashboardStaticDir: dashboardDir,
|
||||
},
|
||||
{ action: 'ejclaw_artifact_metadata', artifactKind: 'dashboard_dist' },
|
||||
{ action: 'ejclaw_artifact_metadata', artifactKind: 'runner_dist' },
|
||||
);
|
||||
|
||||
expect(text).toContain('"file_count"');
|
||||
|
||||
@@ -27,7 +27,6 @@ export interface DeployEvidenceRequest {
|
||||
export interface DeployEvidencePaths {
|
||||
projectRoot: string;
|
||||
dataDir: string;
|
||||
dashboardStaticDir: string;
|
||||
}
|
||||
|
||||
const COMMAND_TIMEOUT_MS = 5_000;
|
||||
@@ -155,12 +154,6 @@ function buildOutputArtifacts(
|
||||
): Record<string, unknown> {
|
||||
return {
|
||||
root_dist: fileMetadata(path.join(paths.projectRoot, 'dist', 'index.js')),
|
||||
dashboard_index: fileMetadata(
|
||||
path.join(paths.dashboardStaticDir, 'index.html'),
|
||||
),
|
||||
dashboard_assets: directoryMetadata(
|
||||
path.join(paths.dashboardStaticDir, 'assets'),
|
||||
),
|
||||
agent_runner: fileMetadata(
|
||||
path.join(
|
||||
paths.projectRoot,
|
||||
@@ -223,32 +216,16 @@ export function collectArtifactMetadata(
|
||||
const payload =
|
||||
kind === 'build_outputs'
|
||||
? buildOutputArtifacts(paths)
|
||||
: kind === 'dashboard_dist'
|
||||
? directoryMetadata(paths.dashboardStaticDir)
|
||||
: kind === 'runner_dist'
|
||||
? {
|
||||
agent_runner: directoryMetadata(
|
||||
path.join(paths.projectRoot, 'runners', 'agent-runner', 'dist'),
|
||||
),
|
||||
codex_runner: directoryMetadata(
|
||||
path.join(paths.projectRoot, 'runners', 'codex-runner', 'dist'),
|
||||
),
|
||||
}
|
||||
: kind === 'android_debug_apk'
|
||||
? fileMetadata(
|
||||
path.join(
|
||||
paths.projectRoot,
|
||||
'apps',
|
||||
'android',
|
||||
'app',
|
||||
'build',
|
||||
'outputs',
|
||||
'apk',
|
||||
'debug',
|
||||
'app-debug.apk',
|
||||
),
|
||||
)
|
||||
: directoryMetadata(path.join(paths.dataDir, 'attachments'));
|
||||
: kind === 'runner_dist'
|
||||
? {
|
||||
agent_runner: directoryMetadata(
|
||||
path.join(paths.projectRoot, 'runners', 'agent-runner', 'dist'),
|
||||
),
|
||||
codex_runner: directoryMetadata(
|
||||
path.join(paths.projectRoot, 'runners', 'codex-runner', 'dist'),
|
||||
),
|
||||
}
|
||||
: directoryMetadata(path.join(paths.dataDir, 'attachments'));
|
||||
|
||||
return JSON.stringify(
|
||||
{
|
||||
|
||||
@@ -20,7 +20,6 @@ import {
|
||||
SERVICE_ID,
|
||||
SERVICE_SESSION_SCOPE,
|
||||
DATA_DIR,
|
||||
WEB_DASHBOARD,
|
||||
} from './config.js';
|
||||
import type { AgentType } from './types.js';
|
||||
import {
|
||||
@@ -341,7 +340,6 @@ export async function runHostEvidenceRequest(
|
||||
await collectDeployState({
|
||||
projectRoot: PROJECT_ROOT,
|
||||
dataDir: DATA_DIR,
|
||||
dashboardStaticDir: WEB_DASHBOARD.staticDir,
|
||||
}),
|
||||
),
|
||||
stderr: '',
|
||||
@@ -360,7 +358,6 @@ export async function runHostEvidenceRequest(
|
||||
{
|
||||
projectRoot: PROJECT_ROOT,
|
||||
dataDir: DATA_DIR,
|
||||
dashboardStaticDir: WEB_DASHBOARD.staticDir,
|
||||
},
|
||||
{
|
||||
action: request.action,
|
||||
|
||||
28
src/index.ts
28
src/index.ts
@@ -12,7 +12,6 @@ import {
|
||||
TIMEZONE,
|
||||
TRIGGER_PATTERN,
|
||||
USAGE_UPDATE_INTERVAL,
|
||||
WEB_DASHBOARD,
|
||||
} from './config.js';
|
||||
import './channels/index.js';
|
||||
import {
|
||||
@@ -57,14 +56,9 @@ import {
|
||||
startUnifiedDashboard,
|
||||
} from './unified-dashboard.js';
|
||||
import { startUsagePrimer } from './usage-primer.js';
|
||||
import { startWebDashboardServer } from './web-dashboard-server.js';
|
||||
import { Channel, NewMessage, RegisteredGroup } from './types.js';
|
||||
import { logger } from './logger.js';
|
||||
import { initCodexTokenRotation } from './codex-token-rotation.js';
|
||||
import {
|
||||
startCodexAccountRefreshLoop,
|
||||
stopCodexAccountRefreshLoop,
|
||||
} from './settings-store.js';
|
||||
import {
|
||||
hasAvailableClaudeToken,
|
||||
initTokenRotation,
|
||||
@@ -320,23 +314,18 @@ async function main(): Promise<void> {
|
||||
initTokenRotation();
|
||||
initCodexTokenRotation();
|
||||
startTokenRefreshLoop();
|
||||
startCodexAccountRefreshLoop();
|
||||
|
||||
runtimeState.loadState();
|
||||
|
||||
// Graceful shutdown handlers
|
||||
let leaseRecoveryTimer: ReturnType<typeof setInterval> | null = null;
|
||||
let webDashboardServer: ReturnType<typeof startWebDashboardServer> = null;
|
||||
const shutdown = async (signal: string) => {
|
||||
logger.info({ signal }, 'Shutdown signal received');
|
||||
stopTokenRefreshLoop();
|
||||
stopCodexAccountRefreshLoop();
|
||||
if (leaseRecoveryTimer) {
|
||||
clearInterval(leaseRecoveryTimer);
|
||||
leaseRecoveryTimer = null;
|
||||
}
|
||||
webDashboardServer?.stop();
|
||||
webDashboardServer = null;
|
||||
const roomBindings = runtimeState.getRoomBindings();
|
||||
const interruptedGroups = queue
|
||||
.getStatuses(Object.keys(roomBindings))
|
||||
@@ -449,14 +438,8 @@ async function main(): Promise<void> {
|
||||
}
|
||||
}
|
||||
if (channels.length === 0) {
|
||||
if (WEB_DASHBOARD.enabled) {
|
||||
logger.warn(
|
||||
'No channels connected; continuing in web-dashboard-only mode',
|
||||
);
|
||||
} else {
|
||||
logger.fatal('No channels connected');
|
||||
process.exit(1);
|
||||
}
|
||||
logger.fatal('No channels connected');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// Start subsystems (independently of connection handler)
|
||||
@@ -591,13 +574,6 @@ async function main(): Promise<void> {
|
||||
// Refresh the status dashboard immediately when an agent starts/finishes a run
|
||||
// (activity moves between rooms) rather than waiting for the periodic tick.
|
||||
queue.setOnActivityChange(requestImmediateStatusUpdate);
|
||||
webDashboardServer = startWebDashboardServer({
|
||||
...WEB_DASHBOARD,
|
||||
getRoomBindings: runtimeState.getRoomBindings,
|
||||
enqueueMessageCheck: (chatJid, groupFolder) =>
|
||||
queue.enqueueMessageCheck(chatJid, resolveGroupIpcPath(groupFolder)),
|
||||
nudgeScheduler: nudgeSchedulerLoop,
|
||||
});
|
||||
startUsagePrimer();
|
||||
|
||||
leaseRecoveryTimer = setInterval(() => {
|
||||
|
||||
@@ -1,286 +0,0 @@
|
||||
import { Database } from 'bun:sqlite';
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { initializeDatabaseSchema } from './db/bootstrap.js';
|
||||
import {
|
||||
deleteStoredRoomSkillOverrideFromDatabase,
|
||||
getStoredRoomSkillOverridesFromDatabase,
|
||||
upsertStoredRoomSkillOverrideInDatabase,
|
||||
} from './db/rooms.js';
|
||||
import {
|
||||
buildRoomSkillSettingsSnapshot,
|
||||
type RoomSkillSettingsBuildInput,
|
||||
} from './room-skill-settings.js';
|
||||
import type { RuntimeInventorySnapshot } from './runtime-inventory.js';
|
||||
|
||||
function skill(name: string, skillPath: string, description = `${name} desc`) {
|
||||
return { name, description, path: skillPath };
|
||||
}
|
||||
|
||||
function inventoryFixture(): RuntimeInventorySnapshot {
|
||||
return {
|
||||
generatedAt: '2026-05-04T00:00:00.000Z',
|
||||
projectRoot: '/repo',
|
||||
dataDir: '/repo/data',
|
||||
service: {
|
||||
id: 'codex-main',
|
||||
sessionScope: 'codex-main',
|
||||
agentType: 'codex',
|
||||
},
|
||||
codex: {
|
||||
configFiles: [],
|
||||
skillDirs: [
|
||||
{
|
||||
label: 'Codex user skills',
|
||||
path: '/home/.agents/skills',
|
||||
exists: true,
|
||||
count: 1,
|
||||
skills: [skill('agent-browser', '/home/.agents/skills/browser')],
|
||||
},
|
||||
],
|
||||
mcp: {
|
||||
configPath: {
|
||||
label: 'Codex config.toml',
|
||||
path: '/home/.codex/config.toml',
|
||||
exists: true,
|
||||
},
|
||||
ejclawConfigured: true,
|
||||
serverCount: 1,
|
||||
},
|
||||
},
|
||||
claude: {
|
||||
configFiles: [],
|
||||
skillDirs: [
|
||||
{
|
||||
label: 'Claude user skills',
|
||||
path: '/home/.claude/skills',
|
||||
exists: true,
|
||||
count: 1,
|
||||
skills: [
|
||||
skill('review-helper', '/home/.claude/skills/review-helper'),
|
||||
],
|
||||
},
|
||||
],
|
||||
mcp: {
|
||||
configPath: {
|
||||
label: 'Claude settings.json',
|
||||
path: '/home/.claude/settings.json',
|
||||
exists: true,
|
||||
},
|
||||
ejclawConfigured: true,
|
||||
serverCount: 1,
|
||||
},
|
||||
},
|
||||
ejclaw: {
|
||||
runnerSkillDir: {
|
||||
label: 'EJClaw runner skills',
|
||||
path: '/repo/runners/skills',
|
||||
exists: true,
|
||||
count: 1,
|
||||
skills: [
|
||||
skill('runner-browser', '/repo/runners/skills/runner-browser'),
|
||||
],
|
||||
},
|
||||
mcpServer: {
|
||||
label: 'EJClaw IPC MCP server',
|
||||
path: '/repo/runners/agent-runner/dist/ipc-mcp-stdio.js',
|
||||
exists: true,
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe('room skill settings', () => {
|
||||
it('builds room-scoped effective skill policy from inventory and overrides', () => {
|
||||
const input: RoomSkillSettingsBuildInput = {
|
||||
generatedAt: '2026-05-04T00:00:00.000Z',
|
||||
inventory: inventoryFixture(),
|
||||
roomBindings: {
|
||||
'room-1': {
|
||||
name: 'Room One',
|
||||
folder: 'room-one',
|
||||
added_at: '2026-05-04T00:00:00.000Z',
|
||||
agentType: 'codex',
|
||||
},
|
||||
},
|
||||
registeredAgentTypesByJid: new Map([
|
||||
['room-1', ['claude-code', 'codex']],
|
||||
]),
|
||||
overrides: [
|
||||
{
|
||||
chatJid: 'room-1',
|
||||
agentType: 'claude-code',
|
||||
skillScope: 'claude-user',
|
||||
skillName: 'review-helper',
|
||||
enabled: false,
|
||||
createdAt: '2026-05-04T00:00:00.000Z',
|
||||
updatedAt: '2026-05-04T00:00:00.000Z',
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const snapshot = buildRoomSkillSettingsSnapshot(input);
|
||||
|
||||
expect(snapshot.catalog.map((skill) => skill.id).sort()).toEqual([
|
||||
'claude-user:review-helper',
|
||||
'codex-user:browser',
|
||||
'runner:runner-browser',
|
||||
]);
|
||||
expect(snapshot.rooms).toHaveLength(1);
|
||||
const room = snapshot.rooms[0]!;
|
||||
expect(room.agents.map((agent) => agent.agentType)).toEqual([
|
||||
'claude-code',
|
||||
'codex',
|
||||
]);
|
||||
expect(
|
||||
room.agents.find((agent) => agent.agentType === 'codex'),
|
||||
).toMatchObject({
|
||||
mode: 'all-enabled',
|
||||
availableSkillIds: ['codex-user:browser', 'runner:runner-browser'],
|
||||
effectiveEnabledSkillIds: ['codex-user:browser', 'runner:runner-browser'],
|
||||
});
|
||||
expect(
|
||||
room.agents.find((agent) => agent.agentType === 'claude-code'),
|
||||
).toMatchObject({
|
||||
mode: 'custom',
|
||||
availableSkillIds: ['claude-user:review-helper', 'runner:runner-browser'],
|
||||
disabledSkillIds: ['claude-user:review-helper'],
|
||||
effectiveEnabledSkillIds: ['runner:runner-browser'],
|
||||
});
|
||||
});
|
||||
|
||||
it('keeps default mode when explicit enable rows do not change effective skills', () => {
|
||||
const snapshot = buildRoomSkillSettingsSnapshot({
|
||||
generatedAt: '2026-05-04T00:00:00.000Z',
|
||||
inventory: inventoryFixture(),
|
||||
roomBindings: {
|
||||
'room-1': {
|
||||
name: 'Room One',
|
||||
folder: 'room-one',
|
||||
added_at: '2026-05-04T00:00:00.000Z',
|
||||
agentType: 'codex',
|
||||
},
|
||||
},
|
||||
registeredAgentTypesByJid: new Map([['room-1', ['codex']]]),
|
||||
overrides: [
|
||||
{
|
||||
chatJid: 'room-1',
|
||||
agentType: 'codex',
|
||||
skillScope: 'runner',
|
||||
skillName: 'runner-browser',
|
||||
enabled: true,
|
||||
createdAt: '2026-05-04T00:00:00.000Z',
|
||||
updatedAt: '2026-05-04T00:00:00.000Z',
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(snapshot.rooms[0]?.agents[0]).toMatchObject({
|
||||
mode: 'all-enabled',
|
||||
explicitEnabledSkillIds: ['runner:runner-browser'],
|
||||
effectiveEnabledSkillIds: ['codex-user:browser', 'runner:runner-browser'],
|
||||
});
|
||||
});
|
||||
|
||||
it('reads normalized room skill overrides from the database', () => {
|
||||
const database = new Database(':memory:');
|
||||
try {
|
||||
initializeDatabaseSchema(database);
|
||||
database
|
||||
.prepare(
|
||||
`INSERT INTO room_settings (
|
||||
chat_jid, room_mode, mode_source, name, folder, updated_at
|
||||
) VALUES (?, 'single', 'explicit', ?, ?, ?)`,
|
||||
)
|
||||
.run('room-1', 'Room One', 'room-one', '2026-05-04T00:00:00.000Z');
|
||||
database
|
||||
.prepare(
|
||||
`INSERT INTO room_skill_overrides (
|
||||
chat_jid, agent_type, skill_scope, skill_name, enabled,
|
||||
created_at, updated_at
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?)`,
|
||||
)
|
||||
.run(
|
||||
'room-1',
|
||||
'codex',
|
||||
'runner',
|
||||
'agent-browser',
|
||||
0,
|
||||
'2026-05-04T00:00:00.000Z',
|
||||
'2026-05-04T00:00:00.000Z',
|
||||
);
|
||||
|
||||
expect(getStoredRoomSkillOverridesFromDatabase(database)).toEqual([
|
||||
{
|
||||
chatJid: 'room-1',
|
||||
agentType: 'codex',
|
||||
skillScope: 'runner',
|
||||
skillName: 'agent-browser',
|
||||
enabled: false,
|
||||
createdAt: '2026-05-04T00:00:00.000Z',
|
||||
updatedAt: '2026-05-04T00:00:00.000Z',
|
||||
},
|
||||
]);
|
||||
expect(
|
||||
getStoredRoomSkillOverridesFromDatabase(database, 'missing-room'),
|
||||
).toEqual([]);
|
||||
} finally {
|
||||
database.close();
|
||||
}
|
||||
});
|
||||
|
||||
it('upserts and deletes room skill overrides in the database', () => {
|
||||
const database = new Database(':memory:');
|
||||
try {
|
||||
initializeDatabaseSchema(database);
|
||||
database
|
||||
.prepare(
|
||||
`INSERT INTO room_settings (
|
||||
chat_jid, room_mode, mode_source, name, folder, updated_at
|
||||
) VALUES (?, 'single', 'explicit', ?, ?, ?)`,
|
||||
)
|
||||
.run('room-1', 'Room One', 'room-one', '2026-05-04T00:00:00.000Z');
|
||||
|
||||
upsertStoredRoomSkillOverrideInDatabase(database, {
|
||||
chatJid: 'room-1',
|
||||
agentType: 'codex',
|
||||
skillScope: 'runner',
|
||||
skillName: 'agent-browser',
|
||||
enabled: false,
|
||||
});
|
||||
expect(getStoredRoomSkillOverridesFromDatabase(database)).toMatchObject([
|
||||
{
|
||||
chatJid: 'room-1',
|
||||
agentType: 'codex',
|
||||
skillScope: 'runner',
|
||||
skillName: 'agent-browser',
|
||||
enabled: false,
|
||||
},
|
||||
]);
|
||||
|
||||
upsertStoredRoomSkillOverrideInDatabase(database, {
|
||||
chatJid: 'room-1',
|
||||
agentType: 'codex',
|
||||
skillScope: 'runner',
|
||||
skillName: 'agent-browser',
|
||||
enabled: true,
|
||||
});
|
||||
expect(
|
||||
getStoredRoomSkillOverridesFromDatabase(database)[0],
|
||||
).toMatchObject({
|
||||
enabled: true,
|
||||
});
|
||||
|
||||
deleteStoredRoomSkillOverrideFromDatabase(database, {
|
||||
chatJid: 'room-1',
|
||||
agentType: 'codex',
|
||||
skillScope: 'runner',
|
||||
skillName: 'agent-browser',
|
||||
});
|
||||
expect(getStoredRoomSkillOverridesFromDatabase(database)).toEqual([]);
|
||||
} finally {
|
||||
database.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,329 +0,0 @@
|
||||
import path from 'node:path';
|
||||
|
||||
import {
|
||||
deleteStoredRoomSkillOverride,
|
||||
getAllRoomBindings,
|
||||
getRegisteredAgentTypesForJid,
|
||||
getStoredRoomSkillOverrides,
|
||||
upsertStoredRoomSkillOverride,
|
||||
} from './db.js';
|
||||
import {
|
||||
getRuntimeInventory,
|
||||
type RuntimeInventorySnapshot,
|
||||
type RuntimeSkillDirSnapshot,
|
||||
type RuntimeSkillSummary,
|
||||
} from './runtime-inventory.js';
|
||||
import type { AgentType, RegisteredGroup, RoomMode } from './types.js';
|
||||
import type { StoredRoomSkillOverride } from './db/rooms.js';
|
||||
|
||||
export type RoomSkillScope = 'codex-user' | 'claude-user' | 'runner';
|
||||
|
||||
export interface RoomSkillCatalogItem {
|
||||
id: string;
|
||||
scope: RoomSkillScope;
|
||||
name: string;
|
||||
displayName: string;
|
||||
description: string | null;
|
||||
path: string;
|
||||
agentTypes: AgentType[];
|
||||
}
|
||||
|
||||
export interface RoomSkillAgentPolicy {
|
||||
agentType: AgentType;
|
||||
mode: 'all-enabled' | 'custom';
|
||||
availableSkillIds: string[];
|
||||
disabledSkillIds: string[];
|
||||
explicitEnabledSkillIds: string[];
|
||||
effectiveEnabledSkillIds: string[];
|
||||
}
|
||||
|
||||
export interface RoomSkillPolicyRoom {
|
||||
jid: string;
|
||||
name: string;
|
||||
folder: string;
|
||||
roomMode?: RoomMode;
|
||||
agents: RoomSkillAgentPolicy[];
|
||||
}
|
||||
|
||||
export interface RoomSkillSettingsSnapshot {
|
||||
generatedAt: string;
|
||||
catalog: RoomSkillCatalogItem[];
|
||||
rooms: RoomSkillPolicyRoom[];
|
||||
}
|
||||
|
||||
export interface RoomSkillSettingsBuildInput {
|
||||
generatedAt?: string;
|
||||
inventory: RuntimeInventorySnapshot;
|
||||
roomBindings: Record<string, RegisteredGroup>;
|
||||
registeredAgentTypesByJid?: Map<string, AgentType[]>;
|
||||
overrides?: StoredRoomSkillOverride[];
|
||||
}
|
||||
|
||||
export interface RoomSkillSettingUpdateInput {
|
||||
roomJid: string;
|
||||
agentType: string;
|
||||
skillId: string;
|
||||
enabled: boolean;
|
||||
}
|
||||
|
||||
export class RoomSkillSettingsError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
readonly status: number,
|
||||
) {
|
||||
super(message);
|
||||
this.name = 'RoomSkillSettingsError';
|
||||
}
|
||||
}
|
||||
|
||||
function skillId(scope: RoomSkillScope, name: string): string {
|
||||
return `${scope}:${name}`;
|
||||
}
|
||||
|
||||
function skillNameFromPath(skill: RuntimeSkillSummary): string {
|
||||
return path.basename(skill.path);
|
||||
}
|
||||
|
||||
function addSkillsFromDir(
|
||||
catalog: Map<string, RoomSkillCatalogItem>,
|
||||
dir: RuntimeSkillDirSnapshot,
|
||||
scope: RoomSkillScope,
|
||||
agentTypes: AgentType[],
|
||||
): void {
|
||||
if (!dir.exists) return;
|
||||
for (const skill of dir.skills) {
|
||||
const name = skillNameFromPath(skill);
|
||||
if (!name) continue;
|
||||
const id = skillId(scope, name);
|
||||
const existing = catalog.get(id);
|
||||
if (existing) {
|
||||
const types = new Set<AgentType>([...existing.agentTypes, ...agentTypes]);
|
||||
existing.agentTypes = [...types].sort();
|
||||
continue;
|
||||
}
|
||||
catalog.set(id, {
|
||||
id,
|
||||
scope,
|
||||
name,
|
||||
displayName: skill.name,
|
||||
description: skill.description,
|
||||
path: skill.path,
|
||||
agentTypes: [...agentTypes].sort(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export function buildRoomSkillCatalog(
|
||||
inventory: RuntimeInventorySnapshot,
|
||||
): RoomSkillCatalogItem[] {
|
||||
const catalog = new Map<string, RoomSkillCatalogItem>();
|
||||
const runnerPath = inventory.ejclaw.runnerSkillDir.path;
|
||||
const codexUserDir = inventory.codex.skillDirs.find(
|
||||
(dir) => dir.path !== runnerPath,
|
||||
);
|
||||
const claudeUserDir = inventory.claude.skillDirs.find(
|
||||
(dir) => dir.path !== runnerPath,
|
||||
);
|
||||
|
||||
if (codexUserDir) {
|
||||
addSkillsFromDir(catalog, codexUserDir, 'codex-user', ['codex']);
|
||||
}
|
||||
if (claudeUserDir) {
|
||||
addSkillsFromDir(catalog, claudeUserDir, 'claude-user', ['claude-code']);
|
||||
}
|
||||
addSkillsFromDir(catalog, inventory.ejclaw.runnerSkillDir, 'runner', [
|
||||
'claude-code',
|
||||
'codex',
|
||||
]);
|
||||
|
||||
return [...catalog.values()].sort((a, b) => {
|
||||
const scopeCompare = a.scope.localeCompare(b.scope);
|
||||
return scopeCompare === 0
|
||||
? a.displayName.localeCompare(b.displayName)
|
||||
: scopeCompare;
|
||||
});
|
||||
}
|
||||
|
||||
function overrideKey(
|
||||
jid: string,
|
||||
agentType: AgentType,
|
||||
scope: string,
|
||||
name: string,
|
||||
): string {
|
||||
return `${jid}\u0000${agentType}\u0000${scope}\u0000${name}`;
|
||||
}
|
||||
|
||||
function parseSkillId(id: string): { scope: RoomSkillScope; name: string } {
|
||||
const separator = id.indexOf(':');
|
||||
if (separator <= 0 || separator === id.length - 1) {
|
||||
throw new RoomSkillSettingsError('skillId must be "<scope>:<name>"', 400);
|
||||
}
|
||||
const scope = id.slice(0, separator);
|
||||
const name = id.slice(separator + 1);
|
||||
if (scope !== 'codex-user' && scope !== 'claude-user' && scope !== 'runner') {
|
||||
throw new RoomSkillSettingsError(`Unsupported skill scope: ${scope}`, 400);
|
||||
}
|
||||
return { scope, name };
|
||||
}
|
||||
|
||||
function normalizeRoomSkillAgentType(agentType: string): AgentType {
|
||||
if (agentType === 'codex' || agentType === 'claude-code') {
|
||||
return agentType;
|
||||
}
|
||||
throw new RoomSkillSettingsError(`Unsupported agent type: ${agentType}`, 400);
|
||||
}
|
||||
|
||||
function resolveRoomAgentTypes(
|
||||
jid: string,
|
||||
group: RegisteredGroup,
|
||||
registeredAgentTypesByJid?: Map<string, AgentType[]>,
|
||||
): AgentType[] {
|
||||
const registered = registeredAgentTypesByJid?.get(jid) ?? [];
|
||||
const types = new Set<AgentType>(registered);
|
||||
if (group.agentType) types.add(group.agentType);
|
||||
if (types.size === 0) types.add('claude-code');
|
||||
return [...types].sort();
|
||||
}
|
||||
|
||||
export function buildRoomSkillSettingsSnapshot({
|
||||
generatedAt,
|
||||
inventory,
|
||||
roomBindings,
|
||||
registeredAgentTypesByJid,
|
||||
overrides = [],
|
||||
}: RoomSkillSettingsBuildInput): RoomSkillSettingsSnapshot {
|
||||
const catalog = buildRoomSkillCatalog(inventory);
|
||||
const overridesByKey = new Map(
|
||||
overrides.map((override) => [
|
||||
overrideKey(
|
||||
override.chatJid,
|
||||
override.agentType,
|
||||
override.skillScope,
|
||||
override.skillName,
|
||||
),
|
||||
override,
|
||||
]),
|
||||
);
|
||||
|
||||
const rooms = Object.entries(roomBindings)
|
||||
.map(([jid, group]) => {
|
||||
const agentTypes = resolveRoomAgentTypes(
|
||||
jid,
|
||||
group,
|
||||
registeredAgentTypesByJid,
|
||||
);
|
||||
return {
|
||||
jid,
|
||||
name: group.name,
|
||||
folder: group.folder,
|
||||
agents: agentTypes.map((agentType) => {
|
||||
const available = catalog.filter((skill) =>
|
||||
skill.agentTypes.includes(agentType),
|
||||
);
|
||||
const disabledSkillIds: string[] = [];
|
||||
const explicitEnabledSkillIds: string[] = [];
|
||||
const effectiveEnabledSkillIds: string[] = [];
|
||||
|
||||
for (const skill of available) {
|
||||
const override = overridesByKey.get(
|
||||
overrideKey(jid, agentType, skill.scope, skill.name),
|
||||
);
|
||||
if (override?.enabled === false) {
|
||||
disabledSkillIds.push(skill.id);
|
||||
continue;
|
||||
}
|
||||
if (override?.enabled === true) {
|
||||
explicitEnabledSkillIds.push(skill.id);
|
||||
}
|
||||
effectiveEnabledSkillIds.push(skill.id);
|
||||
}
|
||||
|
||||
return {
|
||||
agentType,
|
||||
mode:
|
||||
disabledSkillIds.length > 0 ||
|
||||
effectiveEnabledSkillIds.length !== available.length
|
||||
? 'custom'
|
||||
: 'all-enabled',
|
||||
availableSkillIds: available.map((skill) => skill.id),
|
||||
disabledSkillIds,
|
||||
explicitEnabledSkillIds,
|
||||
effectiveEnabledSkillIds,
|
||||
} satisfies RoomSkillAgentPolicy;
|
||||
}),
|
||||
} satisfies RoomSkillPolicyRoom;
|
||||
})
|
||||
.sort((a, b) => a.name.localeCompare(b.name));
|
||||
|
||||
return {
|
||||
generatedAt: generatedAt ?? new Date().toISOString(),
|
||||
catalog,
|
||||
rooms,
|
||||
};
|
||||
}
|
||||
|
||||
export function getRoomSkillSettings(): RoomSkillSettingsSnapshot {
|
||||
const roomBindings = getAllRoomBindings();
|
||||
const registeredAgentTypesByJid = new Map(
|
||||
Object.keys(roomBindings).map((jid) => [
|
||||
jid,
|
||||
getRegisteredAgentTypesForJid(jid),
|
||||
]),
|
||||
);
|
||||
return buildRoomSkillSettingsSnapshot({
|
||||
inventory: getRuntimeInventory(),
|
||||
roomBindings,
|
||||
registeredAgentTypesByJid,
|
||||
overrides: getStoredRoomSkillOverrides(),
|
||||
});
|
||||
}
|
||||
|
||||
export function updateRoomSkillSetting(
|
||||
input: RoomSkillSettingUpdateInput,
|
||||
): RoomSkillSettingsSnapshot {
|
||||
const roomJid = input.roomJid.trim();
|
||||
const agentType = normalizeRoomSkillAgentType(input.agentType);
|
||||
const { scope, name } = parseSkillId(input.skillId.trim());
|
||||
const before = getRoomSkillSettings();
|
||||
const room = before.rooms.find((candidate) => candidate.jid === roomJid);
|
||||
if (!room) {
|
||||
throw new RoomSkillSettingsError('Room not found', 404);
|
||||
}
|
||||
const agent = room.agents.find(
|
||||
(candidate) => candidate.agentType === agentType,
|
||||
);
|
||||
if (!agent) {
|
||||
throw new RoomSkillSettingsError(
|
||||
'Agent is not registered for this room',
|
||||
400,
|
||||
);
|
||||
}
|
||||
const skill = before.catalog.find(
|
||||
(candidate) => candidate.scope === scope && candidate.name === name,
|
||||
);
|
||||
if (!skill || !agent.availableSkillIds.includes(skill.id)) {
|
||||
throw new RoomSkillSettingsError(
|
||||
'Skill is not available for this room agent',
|
||||
400,
|
||||
);
|
||||
}
|
||||
|
||||
if (input.enabled) {
|
||||
deleteStoredRoomSkillOverride({
|
||||
chatJid: roomJid,
|
||||
agentType,
|
||||
skillScope: scope,
|
||||
skillName: name,
|
||||
});
|
||||
} else {
|
||||
upsertStoredRoomSkillOverride({
|
||||
chatJid: roomJid,
|
||||
agentType,
|
||||
skillScope: scope,
|
||||
skillName: name,
|
||||
enabled: false,
|
||||
});
|
||||
}
|
||||
|
||||
return getRoomSkillSettings();
|
||||
}
|
||||
@@ -1,108 +0,0 @@
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
|
||||
|
||||
import { getRuntimeInventory } from './runtime-inventory.js';
|
||||
|
||||
describe('runtime inventory', () => {
|
||||
let tempDir: string;
|
||||
let homeDir: string;
|
||||
let projectRoot: string;
|
||||
|
||||
beforeEach(() => {
|
||||
tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'ejclaw-runtime-inv-'));
|
||||
homeDir = path.join(tempDir, 'home');
|
||||
projectRoot = path.join(tempDir, 'repo');
|
||||
fs.mkdirSync(homeDir, { recursive: true });
|
||||
fs.mkdirSync(projectRoot, { recursive: true });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
fs.rmSync(tempDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it('summarizes safe Codex and Claude runtime metadata without reading secrets', () => {
|
||||
const codexDir = path.join(homeDir, '.codex');
|
||||
const claudeDir = path.join(homeDir, '.claude');
|
||||
fs.mkdirSync(codexDir, { recursive: true });
|
||||
fs.mkdirSync(claudeDir, { recursive: true });
|
||||
fs.writeFileSync(
|
||||
path.join(codexDir, 'config.toml'),
|
||||
'[mcp_servers.ejclaw]\ncommand = "node"\n[mcp_servers.other]\ncommand = "x"\n',
|
||||
);
|
||||
fs.writeFileSync(
|
||||
path.join(claudeDir, 'settings.json'),
|
||||
JSON.stringify({
|
||||
fastMode: true,
|
||||
secret: 'should-not-leak',
|
||||
mcpServers: {
|
||||
ejclaw: {
|
||||
command: 'node',
|
||||
args: ['secret-arg-should-not-leak'],
|
||||
},
|
||||
filesystem: {
|
||||
command: 'node',
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
fs.writeFileSync(
|
||||
path.join(codexDir, 'auth.json'),
|
||||
'{"OPENAI_API_KEY":"sk-secret"}\n',
|
||||
);
|
||||
|
||||
const codexSkill = path.join(homeDir, '.agents', 'skills', 'browser');
|
||||
fs.mkdirSync(codexSkill, { recursive: true });
|
||||
fs.writeFileSync(
|
||||
path.join(codexSkill, 'SKILL.md'),
|
||||
'---\nname: browser\ndescription: Browser automation\n---\n# Body\n',
|
||||
);
|
||||
|
||||
const runnerSkill = path.join(projectRoot, 'runners', 'skills', 'runner');
|
||||
fs.mkdirSync(runnerSkill, { recursive: true });
|
||||
fs.writeFileSync(
|
||||
path.join(runnerSkill, 'SKILL.md'),
|
||||
'---\nname: runner\ndescription: Runner skill\n---\n',
|
||||
);
|
||||
const mcpServerPath = path.join(
|
||||
projectRoot,
|
||||
'runners',
|
||||
'agent-runner',
|
||||
'dist',
|
||||
'ipc-mcp-stdio.js',
|
||||
);
|
||||
fs.mkdirSync(path.dirname(mcpServerPath), { recursive: true });
|
||||
fs.writeFileSync(mcpServerPath, 'console.log("mcp");\n');
|
||||
|
||||
const snapshot = getRuntimeInventory({
|
||||
generatedAt: '2026-05-04T00:00:00.000Z',
|
||||
homeDir,
|
||||
projectRoot,
|
||||
});
|
||||
|
||||
expect(snapshot.projectRoot).toBe(projectRoot);
|
||||
expect(snapshot.codex.mcp).toMatchObject({
|
||||
ejclawConfigured: true,
|
||||
serverCount: 2,
|
||||
});
|
||||
expect(snapshot.claude.mcp).toMatchObject({
|
||||
ejclawConfigured: true,
|
||||
serverCount: 2,
|
||||
});
|
||||
expect(snapshot.codex.skillDirs[0]).toMatchObject({
|
||||
count: 1,
|
||||
skills: [{ name: 'browser', description: 'Browser automation' }],
|
||||
});
|
||||
expect(snapshot.ejclaw.runnerSkillDir).toMatchObject({
|
||||
count: 1,
|
||||
skills: [{ name: 'runner', description: 'Runner skill' }],
|
||||
});
|
||||
|
||||
const serialized = JSON.stringify(snapshot);
|
||||
expect(serialized).not.toContain('sk-secret');
|
||||
expect(serialized).not.toContain('should-not-leak');
|
||||
expect(serialized).not.toContain('secret-arg-should-not-leak');
|
||||
});
|
||||
});
|
||||
@@ -1,258 +0,0 @@
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
|
||||
import { getClaudeCredentialsPath } from './claude-credentials-path.js';
|
||||
import {
|
||||
CURRENT_RUNTIME_AGENT_TYPE,
|
||||
DATA_DIR,
|
||||
SERVICE_ID,
|
||||
SERVICE_SESSION_SCOPE,
|
||||
} from './config.js';
|
||||
|
||||
export interface RuntimePathSnapshot {
|
||||
label: string;
|
||||
path: string;
|
||||
exists: boolean;
|
||||
}
|
||||
|
||||
export interface RuntimeSkillSummary {
|
||||
name: string;
|
||||
description: string | null;
|
||||
path: string;
|
||||
}
|
||||
|
||||
export interface RuntimeSkillDirSnapshot extends RuntimePathSnapshot {
|
||||
count: number;
|
||||
skills: RuntimeSkillSummary[];
|
||||
}
|
||||
|
||||
export interface RuntimeMcpSnapshot {
|
||||
configPath: RuntimePathSnapshot;
|
||||
ejclawConfigured: boolean;
|
||||
serverCount: number;
|
||||
}
|
||||
|
||||
export interface RuntimeAgentInventory {
|
||||
configFiles: RuntimePathSnapshot[];
|
||||
skillDirs: RuntimeSkillDirSnapshot[];
|
||||
mcp: RuntimeMcpSnapshot;
|
||||
}
|
||||
|
||||
export interface RuntimeInventorySnapshot {
|
||||
generatedAt: string;
|
||||
projectRoot: string;
|
||||
dataDir: string;
|
||||
service: {
|
||||
id: string;
|
||||
sessionScope: string;
|
||||
agentType: string;
|
||||
};
|
||||
codex: RuntimeAgentInventory;
|
||||
claude: RuntimeAgentInventory;
|
||||
ejclaw: {
|
||||
runnerSkillDir: RuntimeSkillDirSnapshot;
|
||||
mcpServer: RuntimePathSnapshot;
|
||||
};
|
||||
}
|
||||
|
||||
interface RuntimeInventoryOptions {
|
||||
homeDir?: string;
|
||||
projectRoot?: string;
|
||||
generatedAt?: string;
|
||||
}
|
||||
|
||||
interface McpConfigSummary {
|
||||
ejclawConfigured: boolean;
|
||||
serverCount: number;
|
||||
}
|
||||
|
||||
function pathSnapshot(label: string, filePath: string): RuntimePathSnapshot {
|
||||
return {
|
||||
label,
|
||||
path: filePath,
|
||||
exists: fs.existsSync(filePath),
|
||||
};
|
||||
}
|
||||
|
||||
function parseSkillMetadata(skillMdPath: string): {
|
||||
name: string | null;
|
||||
description: string | null;
|
||||
} {
|
||||
let content: string;
|
||||
try {
|
||||
content = fs.readFileSync(skillMdPath, 'utf-8').slice(0, 8000);
|
||||
} catch {
|
||||
return { name: null, description: null };
|
||||
}
|
||||
|
||||
const name = content.match(/^name:\s*(.+?)\s*$/m)?.[1]?.trim() ?? null;
|
||||
const description =
|
||||
content.match(/^description:\s*(.+?)\s*$/m)?.[1]?.trim() ?? null;
|
||||
return { name, description };
|
||||
}
|
||||
|
||||
function readSkillDir(label: string, dirPath: string): RuntimeSkillDirSnapshot {
|
||||
if (!fs.existsSync(dirPath)) {
|
||||
return {
|
||||
...pathSnapshot(label, dirPath),
|
||||
count: 0,
|
||||
skills: [],
|
||||
};
|
||||
}
|
||||
|
||||
const skills = fs
|
||||
.readdirSync(dirPath, { withFileTypes: true })
|
||||
.filter((entry) => entry.isDirectory())
|
||||
.map((entry) => {
|
||||
const skillDir = path.join(dirPath, entry.name);
|
||||
const skillMdPath = path.join(skillDir, 'SKILL.md');
|
||||
if (!fs.existsSync(skillMdPath)) return null;
|
||||
const metadata = parseSkillMetadata(skillMdPath);
|
||||
return {
|
||||
name: metadata.name || entry.name,
|
||||
description: metadata.description,
|
||||
path: skillDir,
|
||||
};
|
||||
})
|
||||
.filter((skill): skill is RuntimeSkillSummary => Boolean(skill))
|
||||
.sort((a, b) => a.name.localeCompare(b.name));
|
||||
|
||||
return {
|
||||
...pathSnapshot(label, dirPath),
|
||||
count: skills.length,
|
||||
skills,
|
||||
};
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function summarizeTomlMcpConfig(content: string): McpConfigSummary {
|
||||
const serverMatches = content.match(/^\s*\[mcp_servers\.[^\]]+\]/gm) ?? [];
|
||||
return {
|
||||
ejclawConfigured: /^\s*\[mcp_servers\.ejclaw(?:\.[^\]]+)?\]/m.test(content),
|
||||
serverCount: serverMatches.length,
|
||||
};
|
||||
}
|
||||
|
||||
function summarizeJsonMcpConfig(content: string): McpConfigSummary | null {
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(content);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
if (!isRecord(parsed)) return null;
|
||||
|
||||
const servers = parsed.mcpServers ?? parsed.mcp_servers;
|
||||
if (!isRecord(servers)) {
|
||||
return {
|
||||
ejclawConfigured: false,
|
||||
serverCount: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const names = Object.keys(servers);
|
||||
return {
|
||||
ejclawConfigured: names.includes('ejclaw'),
|
||||
serverCount: names.length,
|
||||
};
|
||||
}
|
||||
|
||||
function readMcpSnapshot(
|
||||
label: string,
|
||||
configPath: string,
|
||||
): RuntimeMcpSnapshot {
|
||||
let content = '';
|
||||
if (fs.existsSync(configPath)) {
|
||||
try {
|
||||
content = fs.readFileSync(configPath, 'utf-8');
|
||||
} catch {
|
||||
content = '';
|
||||
}
|
||||
}
|
||||
|
||||
const summary =
|
||||
path.extname(configPath) === '.json'
|
||||
? (summarizeJsonMcpConfig(content) ?? summarizeTomlMcpConfig(content))
|
||||
: summarizeTomlMcpConfig(content);
|
||||
|
||||
return {
|
||||
configPath: pathSnapshot(label, configPath),
|
||||
...summary,
|
||||
};
|
||||
}
|
||||
|
||||
export function getRuntimeInventory(
|
||||
options: RuntimeInventoryOptions = {},
|
||||
): RuntimeInventorySnapshot {
|
||||
const homeDir = options.homeDir ?? os.homedir();
|
||||
const projectRoot = options.projectRoot ?? process.cwd();
|
||||
const codexConfigPath = path.join(homeDir, '.codex', 'config.toml');
|
||||
const claudeSettingsPath = path.join(homeDir, '.claude', 'settings.json');
|
||||
const runnerSkillDir = path.join(projectRoot, 'runners', 'skills');
|
||||
const mcpServerPath = path.join(
|
||||
projectRoot,
|
||||
'runners',
|
||||
'agent-runner',
|
||||
'dist',
|
||||
'ipc-mcp-stdio.js',
|
||||
);
|
||||
|
||||
const ejclawRunnerSkills = readSkillDir(
|
||||
'EJClaw runner skills',
|
||||
runnerSkillDir,
|
||||
);
|
||||
|
||||
return {
|
||||
generatedAt: options.generatedAt ?? new Date().toISOString(),
|
||||
projectRoot,
|
||||
dataDir: DATA_DIR,
|
||||
service: {
|
||||
id: SERVICE_ID,
|
||||
sessionScope: SERVICE_SESSION_SCOPE,
|
||||
agentType: CURRENT_RUNTIME_AGENT_TYPE,
|
||||
},
|
||||
codex: {
|
||||
configFiles: [
|
||||
pathSnapshot('Codex config.toml', codexConfigPath),
|
||||
pathSnapshot(
|
||||
'Codex auth.json',
|
||||
path.join(homeDir, '.codex', 'auth.json'),
|
||||
),
|
||||
],
|
||||
skillDirs: [
|
||||
readSkillDir(
|
||||
'Codex user skills',
|
||||
path.join(homeDir, '.agents', 'skills'),
|
||||
),
|
||||
ejclawRunnerSkills,
|
||||
],
|
||||
mcp: readMcpSnapshot('Codex config.toml', codexConfigPath),
|
||||
},
|
||||
claude: {
|
||||
configFiles: [
|
||||
pathSnapshot('Claude settings.json', claudeSettingsPath),
|
||||
pathSnapshot(
|
||||
'Claude credentials',
|
||||
getClaudeCredentialsPath(0, { allowHomeFallback: true }) ??
|
||||
path.join(homeDir, '.claude', '.credentials.json'),
|
||||
),
|
||||
],
|
||||
skillDirs: [
|
||||
readSkillDir(
|
||||
'Claude user skills',
|
||||
path.join(homeDir, '.claude', 'skills'),
|
||||
),
|
||||
ejclawRunnerSkills,
|
||||
],
|
||||
mcp: readMcpSnapshot('Claude settings.json', claudeSettingsPath),
|
||||
},
|
||||
ejclaw: {
|
||||
runnerSkillDir: ejclawRunnerSkills,
|
||||
mcpServer: pathSnapshot('EJClaw IPC MCP server', mcpServerPath),
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { agentTypeForRole, isEffortSupported } from './settings-effort.js';
|
||||
|
||||
describe('settings-effort', () => {
|
||||
it('maps roles to agent types with defaults', () => {
|
||||
expect(agentTypeForRole('owner', {})).toBe('codex');
|
||||
expect(agentTypeForRole('reviewer', {})).toBe('claude-code');
|
||||
expect(agentTypeForRole('arbiter', {})).toBeNull();
|
||||
expect(agentTypeForRole('owner', { OWNER_AGENT_TYPE: 'claude-code' })).toBe(
|
||||
'claude-code',
|
||||
);
|
||||
});
|
||||
|
||||
it('rejects xhigh for Claude agents', () => {
|
||||
expect(isEffortSupported('claude-code', 'xhigh')).toBe(false);
|
||||
expect(isEffortSupported('codex', 'xhigh')).toBe(true);
|
||||
expect(isEffortSupported('claude-code', '')).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -1,64 +0,0 @@
|
||||
export type SettingsAgentType = 'claude-code' | 'codex';
|
||||
|
||||
export const CODEX_EFFORT_VALUES = [
|
||||
'',
|
||||
'low',
|
||||
'medium',
|
||||
'high',
|
||||
'xhigh',
|
||||
'max',
|
||||
] as const;
|
||||
|
||||
export const CLAUDE_EFFORT_VALUES = [
|
||||
'',
|
||||
'low',
|
||||
'medium',
|
||||
'high',
|
||||
'max',
|
||||
] as const;
|
||||
|
||||
export type EffortValue = (typeof CODEX_EFFORT_VALUES)[number];
|
||||
|
||||
export function effortValuesForAgent(
|
||||
agentType: SettingsAgentType,
|
||||
): readonly EffortValue[] {
|
||||
return agentType === 'claude-code'
|
||||
? CLAUDE_EFFORT_VALUES
|
||||
: CODEX_EFFORT_VALUES;
|
||||
}
|
||||
|
||||
export function isEffortSupported(
|
||||
agentType: SettingsAgentType | null | undefined,
|
||||
effort: string,
|
||||
): boolean {
|
||||
if (!effort) return true;
|
||||
if (!agentType) return true;
|
||||
return effortValuesForAgent(agentType).includes(effort as EffortValue);
|
||||
}
|
||||
|
||||
export function readSettingsAgentType(
|
||||
value: string | undefined,
|
||||
): SettingsAgentType | null {
|
||||
if (value === 'claude-code' || value === 'codex') return value;
|
||||
return null;
|
||||
}
|
||||
|
||||
export function agentTypeForRole(
|
||||
role: 'owner' | 'reviewer' | 'arbiter',
|
||||
env:
|
||||
| Record<string, string | undefined>
|
||||
| ((key: string) => string | undefined),
|
||||
): SettingsAgentType | null {
|
||||
const read = typeof env === 'function' ? env : (key: string) => env[key];
|
||||
const key =
|
||||
role === 'owner'
|
||||
? 'OWNER_AGENT_TYPE'
|
||||
: role === 'reviewer'
|
||||
? 'REVIEWER_AGENT_TYPE'
|
||||
: 'ARBITER_AGENT_TYPE';
|
||||
const raw = read(key);
|
||||
if (raw !== undefined) return readSettingsAgentType(raw);
|
||||
if (role === 'owner') return 'codex';
|
||||
if (role === 'reviewer') return 'claude-code';
|
||||
return null;
|
||||
}
|
||||
@@ -1,106 +0,0 @@
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
|
||||
import { afterEach, describe, expect, it } from 'vitest';
|
||||
|
||||
import { getMoaSettings, updateMoaSettings } from './settings-store-moa.js';
|
||||
|
||||
const originalCwd = process.cwd();
|
||||
let tempDir: string | null = null;
|
||||
|
||||
function writeTempEnv(content: string): string {
|
||||
tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'ejclaw-moa-settings-'));
|
||||
fs.writeFileSync(path.join(tempDir, '.env'), content, { mode: 0o600 });
|
||||
process.chdir(tempDir);
|
||||
return path.join(tempDir, '.env');
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
process.chdir(originalCwd);
|
||||
if (tempDir) fs.rmSync(tempDir, { recursive: true, force: true });
|
||||
tempDir = null;
|
||||
});
|
||||
|
||||
describe('MoA settings store', () => {
|
||||
it('reads MoA config without exposing API keys', () => {
|
||||
writeTempEnv(
|
||||
[
|
||||
'MOA_ENABLED=true',
|
||||
'MOA_REF_MODELS=kimi,glm',
|
||||
'MOA_KIMI_MODEL=kimi-k2.6',
|
||||
'MOA_KIMI_BASE_URL=https://api.kimi.com/coding',
|
||||
'MOA_KIMI_API_FORMAT=anthropic',
|
||||
'MOA_KIMI_API_KEY=sk-kimi-secret',
|
||||
'MOA_GLM_MODEL=glm-5.1',
|
||||
'MOA_GLM_BASE_URL=https://open.bigmodel.cn/api/anthropic',
|
||||
'MOA_GLM_API_FORMAT=anthropic',
|
||||
'MOA_GLM_API_KEY=glm-secret',
|
||||
'',
|
||||
].join('\n'),
|
||||
);
|
||||
|
||||
expect(getMoaSettings()).toMatchObject({
|
||||
enabled: true,
|
||||
referenceModels: ['kimi', 'glm'],
|
||||
models: [
|
||||
{
|
||||
name: 'kimi',
|
||||
enabled: true,
|
||||
model: 'kimi-k2.6',
|
||||
apiFormat: 'anthropic',
|
||||
apiKeyConfigured: true,
|
||||
},
|
||||
{
|
||||
name: 'glm',
|
||||
enabled: true,
|
||||
model: 'glm-5.1',
|
||||
apiFormat: 'anthropic',
|
||||
apiKeyConfigured: true,
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(JSON.stringify(getMoaSettings())).not.toContain('sk-kimi-secret');
|
||||
});
|
||||
|
||||
it('updates the master toggle, active models, and replacement API keys', () => {
|
||||
const envFile = writeTempEnv(
|
||||
[
|
||||
'MOA_ENABLED=true',
|
||||
'MOA_REF_MODELS=kimi,glm',
|
||||
'MOA_KIMI_MODEL=kimi-k2.6',
|
||||
'MOA_KIMI_BASE_URL=https://api.kimi.com/coding',
|
||||
'MOA_KIMI_API_FORMAT=anthropic',
|
||||
'MOA_KIMI_API_KEY=old-secret',
|
||||
'MOA_GLM_MODEL=glm-5.1',
|
||||
'MOA_GLM_BASE_URL=https://open.bigmodel.cn/api/anthropic',
|
||||
'MOA_GLM_API_FORMAT=anthropic',
|
||||
'MOA_GLM_API_KEY=glm-secret',
|
||||
'',
|
||||
].join('\n'),
|
||||
);
|
||||
|
||||
const updated = updateMoaSettings({
|
||||
enabled: false,
|
||||
models: [
|
||||
{
|
||||
name: 'kimi',
|
||||
enabled: false,
|
||||
model: 'kimi-k2.7',
|
||||
baseUrl: 'https://api.kimi.com/coding',
|
||||
apiFormat: 'anthropic',
|
||||
apiKey: 'new-secret',
|
||||
},
|
||||
{ name: 'glm', enabled: true },
|
||||
],
|
||||
});
|
||||
|
||||
expect(updated.enabled).toBe(false);
|
||||
expect(updated.referenceModels).toEqual(['glm']);
|
||||
const content = fs.readFileSync(envFile, 'utf-8');
|
||||
expect(content).toContain('MOA_ENABLED=false');
|
||||
expect(content).toContain('MOA_REF_MODELS=glm');
|
||||
expect(content).toContain('MOA_KIMI_MODEL=kimi-k2.7');
|
||||
expect(content).toContain('MOA_KIMI_API_KEY=new-secret');
|
||||
});
|
||||
});
|
||||
@@ -1,277 +0,0 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
import {
|
||||
getMoaReferenceStatuses,
|
||||
probeMoaReferenceModel,
|
||||
type MoaModelConfig,
|
||||
type MoaReferenceStatus,
|
||||
} from './moa.js';
|
||||
|
||||
export interface MoaModelSettingsSnapshot {
|
||||
name: string;
|
||||
enabled: boolean;
|
||||
model: string;
|
||||
baseUrl: string;
|
||||
apiFormat: 'openai' | 'anthropic';
|
||||
apiKeyConfigured: boolean;
|
||||
lastStatus: MoaReferenceStatus | null;
|
||||
}
|
||||
|
||||
export interface MoaSettingsSnapshot {
|
||||
enabled: boolean;
|
||||
referenceModels: string[];
|
||||
models: MoaModelSettingsSnapshot[];
|
||||
}
|
||||
|
||||
export interface MoaModelSettingsUpdate {
|
||||
name: string;
|
||||
enabled?: boolean;
|
||||
model?: string;
|
||||
baseUrl?: string;
|
||||
apiFormat?: 'openai' | 'anthropic';
|
||||
apiKey?: string;
|
||||
}
|
||||
|
||||
export interface MoaSettingsUpdateInput {
|
||||
enabled?: boolean;
|
||||
models?: MoaModelSettingsUpdate[];
|
||||
}
|
||||
|
||||
const DEFAULT_MOA_MODEL_NAMES = ['kimi', 'glm'] as const;
|
||||
|
||||
function envFilePath(): string {
|
||||
return path.join(process.cwd(), '.env');
|
||||
}
|
||||
|
||||
function pickEnvValue(content: string, key: string): string | undefined {
|
||||
const re = new RegExp(`^${key}=(.*)$`, 'm');
|
||||
const match = content.match(re);
|
||||
if (!match) return undefined;
|
||||
return match[1].trim().replace(/^['"]|['"]$/g, '');
|
||||
}
|
||||
|
||||
function readEnvFile(): string {
|
||||
const file = envFilePath();
|
||||
if (!fs.existsSync(file)) return '';
|
||||
return fs.readFileSync(file, 'utf-8');
|
||||
}
|
||||
|
||||
function readEnvOrProcess(key: string): string | undefined {
|
||||
const fromFile = pickEnvValue(readEnvFile(), key);
|
||||
if (fromFile !== undefined) return fromFile;
|
||||
return process.env[key];
|
||||
}
|
||||
|
||||
function listSettingsEnvKeys(): string[] {
|
||||
const keys = new Set<string>();
|
||||
for (const line of readEnvFile().split('\n')) {
|
||||
const trimmed = line.trim();
|
||||
if (!trimmed || trimmed.startsWith('#')) continue;
|
||||
const eqIdx = trimmed.indexOf('=');
|
||||
if (eqIdx > 0) keys.add(trimmed.slice(0, eqIdx).trim());
|
||||
}
|
||||
for (const key of Object.keys(process.env)) keys.add(key);
|
||||
return [...keys].sort();
|
||||
}
|
||||
|
||||
function parseCommaList(value: string | undefined): string[] {
|
||||
return (value ?? '')
|
||||
.split(',')
|
||||
.map((item) => item.trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
function normalizeMoaModelName(name: string): string {
|
||||
const normalized = name.trim().toLowerCase();
|
||||
if (!/^[a-z0-9_]+$/.test(normalized)) {
|
||||
throw new Error(`invalid MoA model name: ${name}`);
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
function moaPrefix(name: string): string {
|
||||
return `MOA_${normalizeMoaModelName(name).toUpperCase()}`;
|
||||
}
|
||||
|
||||
function sanitizeEnvValue(value: string): string {
|
||||
if (/[\r\n]/.test(value)) {
|
||||
throw new Error('env values must not contain newlines');
|
||||
}
|
||||
return value.trim();
|
||||
}
|
||||
|
||||
function setOrInsertEnvLine(
|
||||
content: string,
|
||||
key: string,
|
||||
value: string,
|
||||
): string {
|
||||
const re = new RegExp(`^${key}=.*$`, 'm');
|
||||
if (re.test(content)) return content.replace(re, `${key}=${value}`);
|
||||
const trimmed = content.replace(/\s*$/, '');
|
||||
return `${trimmed}\n${key}=${value}\n`;
|
||||
}
|
||||
|
||||
function configuredMoaModelNames(): string[] {
|
||||
const names = new Set<string>(DEFAULT_MOA_MODEL_NAMES);
|
||||
for (const name of parseCommaList(readEnvOrProcess('MOA_REF_MODELS'))) {
|
||||
names.add(normalizeMoaModelName(name));
|
||||
}
|
||||
for (const key of listSettingsEnvKeys()) {
|
||||
const match = key.match(
|
||||
/^MOA_([A-Z0-9_]+)_(MODEL|BASE_URL|API_KEY|API_FORMAT)$/,
|
||||
);
|
||||
if (match) names.add(match[1].toLowerCase());
|
||||
}
|
||||
return [...names].sort((a, b) => {
|
||||
const defaultA = DEFAULT_MOA_MODEL_NAMES.indexOf(
|
||||
a as (typeof DEFAULT_MOA_MODEL_NAMES)[number],
|
||||
);
|
||||
const defaultB = DEFAULT_MOA_MODEL_NAMES.indexOf(
|
||||
b as (typeof DEFAULT_MOA_MODEL_NAMES)[number],
|
||||
);
|
||||
if (defaultA !== -1 || defaultB !== -1) {
|
||||
if (defaultA === -1) return 1;
|
||||
if (defaultB === -1) return -1;
|
||||
return defaultA - defaultB;
|
||||
}
|
||||
return a.localeCompare(b);
|
||||
});
|
||||
}
|
||||
|
||||
function readMoaModelConfig(name: string): MoaModelConfig | null {
|
||||
const normalized = normalizeMoaModelName(name);
|
||||
const prefix = moaPrefix(normalized);
|
||||
const model = readEnvOrProcess(`${prefix}_MODEL`) ?? '';
|
||||
const baseUrl = readEnvOrProcess(`${prefix}_BASE_URL`) ?? '';
|
||||
const apiKey = readEnvOrProcess(`${prefix}_API_KEY`) ?? '';
|
||||
const rawFormat = readEnvOrProcess(`${prefix}_API_FORMAT`) ?? '';
|
||||
const apiFormat: 'openai' | 'anthropic' =
|
||||
rawFormat === 'anthropic' ? 'anthropic' : 'openai';
|
||||
if (!model || !baseUrl || !apiKey) return null;
|
||||
return { name: normalized, model, baseUrl, apiKey, apiFormat };
|
||||
}
|
||||
|
||||
export function getMoaSettings(): MoaSettingsSnapshot {
|
||||
const referenceModels = parseCommaList(
|
||||
readEnvOrProcess('MOA_REF_MODELS'),
|
||||
).map(normalizeMoaModelName);
|
||||
const active = new Set(referenceModels);
|
||||
const statuses = new Map(
|
||||
getMoaReferenceStatuses().map((status) => [status.model, status]),
|
||||
);
|
||||
return {
|
||||
enabled: readEnvOrProcess('MOA_ENABLED') === 'true',
|
||||
referenceModels,
|
||||
models: configuredMoaModelNames().map((name) => {
|
||||
const prefix = moaPrefix(name);
|
||||
const rawFormat = readEnvOrProcess(`${prefix}_API_FORMAT`) ?? '';
|
||||
const apiFormat: 'openai' | 'anthropic' =
|
||||
rawFormat === 'anthropic' ? 'anthropic' : 'openai';
|
||||
return {
|
||||
name,
|
||||
enabled: active.has(name),
|
||||
model: readEnvOrProcess(`${prefix}_MODEL`) ?? '',
|
||||
baseUrl: readEnvOrProcess(`${prefix}_BASE_URL`) ?? '',
|
||||
apiFormat,
|
||||
apiKeyConfigured: Boolean(readEnvOrProcess(`${prefix}_API_KEY`)),
|
||||
lastStatus: statuses.get(name) ?? null,
|
||||
};
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
export function updateMoaSettings(
|
||||
input: MoaSettingsUpdateInput,
|
||||
): MoaSettingsSnapshot {
|
||||
const file = envFilePath();
|
||||
let content = fs.existsSync(file) ? fs.readFileSync(file, 'utf-8') : '';
|
||||
|
||||
if (typeof input.enabled === 'boolean') {
|
||||
content = setOrInsertEnvLine(
|
||||
content,
|
||||
'MOA_ENABLED',
|
||||
input.enabled ? 'true' : 'false',
|
||||
);
|
||||
}
|
||||
|
||||
if (Array.isArray(input.models)) {
|
||||
const byName = new Map<string, MoaModelSettingsUpdate>();
|
||||
for (const update of input.models) {
|
||||
byName.set(normalizeMoaModelName(update.name), update);
|
||||
}
|
||||
content = applyMoaModelUpdates(content, byName);
|
||||
}
|
||||
|
||||
const tempPath = `${file}.tmp`;
|
||||
fs.writeFileSync(tempPath, content, { mode: 0o600 });
|
||||
fs.renameSync(tempPath, file);
|
||||
|
||||
return getMoaSettings();
|
||||
}
|
||||
|
||||
function applyMoaModelUpdates(
|
||||
content: string,
|
||||
byName: Map<string, MoaModelSettingsUpdate>,
|
||||
): string {
|
||||
let next = content;
|
||||
const allNames = new Set(configuredMoaModelNames());
|
||||
for (const name of byName.keys()) allNames.add(name);
|
||||
|
||||
const enabledNames: string[] = [];
|
||||
for (const name of allNames) {
|
||||
const update = byName.get(name);
|
||||
const currentlyEnabled = parseCommaList(readEnvOrProcess('MOA_REF_MODELS'))
|
||||
.map(normalizeMoaModelName)
|
||||
.includes(name);
|
||||
if (update?.enabled ?? currentlyEnabled) enabledNames.push(name);
|
||||
if (update) next = applyMoaModelUpdate(next, name, update);
|
||||
}
|
||||
|
||||
return setOrInsertEnvLine(next, 'MOA_REF_MODELS', enabledNames.join(','));
|
||||
}
|
||||
|
||||
function applyMoaModelUpdate(
|
||||
content: string,
|
||||
name: string,
|
||||
update: MoaModelSettingsUpdate,
|
||||
): string {
|
||||
let next = content;
|
||||
const prefix = moaPrefix(name);
|
||||
if (update.model !== undefined) {
|
||||
next = setOrInsertEnvLine(
|
||||
next,
|
||||
`${prefix}_MODEL`,
|
||||
sanitizeEnvValue(update.model),
|
||||
);
|
||||
}
|
||||
if (update.baseUrl !== undefined) {
|
||||
next = setOrInsertEnvLine(
|
||||
next,
|
||||
`${prefix}_BASE_URL`,
|
||||
sanitizeEnvValue(update.baseUrl),
|
||||
);
|
||||
}
|
||||
if (update.apiFormat !== undefined) {
|
||||
if (update.apiFormat !== 'openai' && update.apiFormat !== 'anthropic') {
|
||||
throw new Error(`invalid MoA API format for ${name}`);
|
||||
}
|
||||
next = setOrInsertEnvLine(next, `${prefix}_API_FORMAT`, update.apiFormat);
|
||||
}
|
||||
if (update.apiKey !== undefined && update.apiKey.trim() !== '') {
|
||||
next = setOrInsertEnvLine(
|
||||
next,
|
||||
`${prefix}_API_KEY`,
|
||||
sanitizeEnvValue(update.apiKey),
|
||||
);
|
||||
}
|
||||
return next;
|
||||
}
|
||||
|
||||
export async function checkMoaModel(name: string): Promise<MoaReferenceStatus> {
|
||||
const config = readMoaModelConfig(name);
|
||||
if (!config) {
|
||||
throw new Error(`MoA model ${name} is missing model/baseUrl/apiKey`);
|
||||
}
|
||||
return probeMoaReferenceModel(config);
|
||||
}
|
||||
@@ -1,206 +0,0 @@
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import {
|
||||
getCodexFeatures,
|
||||
listCodexAccounts,
|
||||
refreshCodexAccount,
|
||||
updateCodexFeatures,
|
||||
} from './settings-store.js';
|
||||
|
||||
describe('settings-store Codex features', () => {
|
||||
let tempDir: string;
|
||||
let previousCwd: string;
|
||||
let previousCodexGoals: string | undefined;
|
||||
let previousHome: string | undefined;
|
||||
let previousSettingsHome: string | undefined;
|
||||
let previousFetch: typeof fetch;
|
||||
|
||||
beforeEach(() => {
|
||||
tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'ejclaw-settings-'));
|
||||
previousCwd = process.cwd();
|
||||
previousCodexGoals = process.env.CODEX_GOALS;
|
||||
previousHome = process.env.HOME;
|
||||
previousSettingsHome = process.env.EJCLAW_SETTINGS_HOME;
|
||||
previousFetch = globalThis.fetch;
|
||||
delete process.env.CODEX_GOALS;
|
||||
process.env.HOME = tempDir;
|
||||
process.env.EJCLAW_SETTINGS_HOME = tempDir;
|
||||
fs.mkdirSync(path.join(tempDir, '.codex'), { recursive: true });
|
||||
process.chdir(tempDir);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
process.chdir(previousCwd);
|
||||
globalThis.fetch = previousFetch;
|
||||
if (previousCodexGoals === undefined) {
|
||||
delete process.env.CODEX_GOALS;
|
||||
} else {
|
||||
process.env.CODEX_GOALS = previousCodexGoals;
|
||||
}
|
||||
if (previousHome === undefined) {
|
||||
delete process.env.HOME;
|
||||
} else {
|
||||
process.env.HOME = previousHome;
|
||||
}
|
||||
if (previousSettingsHome === undefined) {
|
||||
delete process.env.EJCLAW_SETTINGS_HOME;
|
||||
} else {
|
||||
process.env.EJCLAW_SETTINGS_HOME = previousSettingsHome;
|
||||
}
|
||||
fs.rmSync(tempDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
function fakeJwt(payload: Record<string, unknown>): string {
|
||||
const encode = (value: Record<string, unknown>) =>
|
||||
Buffer.from(JSON.stringify(value)).toString('base64');
|
||||
return `${encode({ alg: 'none', typ: 'JWT' })}.${encode(payload)}.`;
|
||||
}
|
||||
|
||||
it('stores Codex goals in ~/.codex/config.toml [features]', () => {
|
||||
expect(getCodexFeatures()).toEqual({ goals: false });
|
||||
|
||||
expect(updateCodexFeatures({ goals: true })).toEqual({ goals: true });
|
||||
expect(
|
||||
fs.readFileSync(path.join(tempDir, '.codex', 'config.toml'), 'utf-8'),
|
||||
).toContain('goals = true');
|
||||
|
||||
expect(updateCodexFeatures({ goals: false })).toEqual({ goals: false });
|
||||
expect(
|
||||
fs.readFileSync(path.join(tempDir, '.codex', 'config.toml'), 'utf-8'),
|
||||
).toContain('goals = false');
|
||||
});
|
||||
|
||||
it('still honors legacy CODEX_GOALS=true until migrated', () => {
|
||||
fs.writeFileSync(path.join(tempDir, '.env'), 'CODEX_GOALS=true\n');
|
||||
expect(getCodexFeatures()).toEqual({ goals: true });
|
||||
|
||||
updateCodexFeatures({ goals: false });
|
||||
expect(getCodexFeatures()).toEqual({ goals: false });
|
||||
expect(fs.readFileSync(path.join(tempDir, '.env'), 'utf-8')).not.toContain(
|
||||
'CODEX_GOALS',
|
||||
);
|
||||
});
|
||||
|
||||
it('stores wham usage status and does not expose stale JWT expiry as live billing', async () => {
|
||||
const accountDir = path.join(tempDir, '.codex-accounts', '1');
|
||||
fs.mkdirSync(accountDir, { recursive: true });
|
||||
const staleJwt = fakeJwt({
|
||||
email: 'cached@example.com',
|
||||
sub: 'acct_cached',
|
||||
'https://api.openai.com/auth': {
|
||||
chatgpt_plan_type: 'free',
|
||||
chatgpt_subscription_active_until: '2026-01-01T00:00:00.000Z',
|
||||
chatgpt_subscription_last_checked: '2026-01-01T00:00:00.000Z',
|
||||
},
|
||||
});
|
||||
fs.writeFileSync(
|
||||
path.join(accountDir, 'auth.json'),
|
||||
`${JSON.stringify(
|
||||
{
|
||||
tokens: {
|
||||
access_token: 'old-access',
|
||||
id_token: staleJwt,
|
||||
refresh_token: 'refresh-token',
|
||||
},
|
||||
},
|
||||
null,
|
||||
2,
|
||||
)}\n`,
|
||||
);
|
||||
|
||||
const resetAt = 1_779_300_000;
|
||||
const fetchMock = vi.fn(async (input: string | URL | Request) => {
|
||||
const url = String(input);
|
||||
if (url === 'https://auth.openai.com/oauth/token') {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
access_token: 'live-access',
|
||||
id_token: staleJwt,
|
||||
refresh_token: 'next-refresh-token',
|
||||
}),
|
||||
{ status: 200 },
|
||||
);
|
||||
}
|
||||
if (url === 'https://chatgpt.com/backend-api/wham/usage') {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
email: 'live@example.com',
|
||||
plan_type: 'pro',
|
||||
rate_limit: {
|
||||
allowed: true,
|
||||
limit_reached: false,
|
||||
primary_window: {
|
||||
limit_window_seconds: 18000,
|
||||
reset_after_seconds: 600,
|
||||
reset_at: resetAt,
|
||||
used_percent: 21,
|
||||
},
|
||||
secondary_window: {
|
||||
limit_window_seconds: 604800,
|
||||
reset_after_seconds: 3600,
|
||||
reset_at: resetAt + 600,
|
||||
used_percent: 7,
|
||||
},
|
||||
},
|
||||
rate_limit_reached_type: null,
|
||||
credits: {
|
||||
has_credits: false,
|
||||
overage_limit_reached: false,
|
||||
unlimited: false,
|
||||
},
|
||||
spend_control: { reached: false },
|
||||
}),
|
||||
{ status: 200 },
|
||||
);
|
||||
}
|
||||
return new Response('not found', { status: 404 });
|
||||
});
|
||||
globalThis.fetch = fetchMock as unknown as typeof fetch;
|
||||
|
||||
const refreshed = await refreshCodexAccount(1);
|
||||
|
||||
expect(refreshed.planType).toBe('pro');
|
||||
expect(refreshed.email).toBe('live@example.com');
|
||||
expect(refreshed.subscriptionUntil).toBeNull();
|
||||
expect(refreshed.subscriptionSource).toBeNull();
|
||||
expect(refreshed.liveStatus).toMatchObject({
|
||||
source: 'wham/usage',
|
||||
planType: 'pro',
|
||||
rateLimit: {
|
||||
allowed: true,
|
||||
limitReached: false,
|
||||
primaryWindow: {
|
||||
limitWindowSeconds: 18000,
|
||||
resetAfterSeconds: 600,
|
||||
resetAt: new Date(resetAt * 1000).toISOString(),
|
||||
usedPercent: 21,
|
||||
},
|
||||
},
|
||||
credits: {
|
||||
hasCredits: false,
|
||||
overageLimitReached: false,
|
||||
unlimited: false,
|
||||
},
|
||||
spendControl: { reached: false },
|
||||
});
|
||||
|
||||
const sidecar = JSON.parse(
|
||||
fs.readFileSync(path.join(accountDir, 'plan-status.json'), 'utf-8'),
|
||||
) as Record<string, unknown>;
|
||||
expect(sidecar).toMatchObject({
|
||||
plan_type: 'pro',
|
||||
rate_limit: {
|
||||
primary_window: { used_percent: 21 },
|
||||
},
|
||||
});
|
||||
expect(listCodexAccounts()[0]).toMatchObject({
|
||||
planType: 'pro',
|
||||
subscriptionUntil: null,
|
||||
liveStatus: { source: 'wham/usage' },
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,760 +0,0 @@
|
||||
/**
|
||||
* Settings store for the web dashboard:
|
||||
* - lists Claude / Codex accounts (safe metadata only, no tokens)
|
||||
* - reads/writes model role configuration via .env
|
||||
* - removes account directories on the filesystem
|
||||
*
|
||||
* Account directory layout (existing convention):
|
||||
* Claude default: ~/.claude/.credentials.json
|
||||
* Claude index N≥1: ~/.claude-accounts/{N}/.credentials.json
|
||||
* Codex default: ~/.codex/auth.json
|
||||
* Codex index N≥1: ~/.codex-accounts/{N}/auth.json
|
||||
*/
|
||||
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
|
||||
import {
|
||||
findCodexAccountIndexByAuthPath,
|
||||
getActiveCodexAuthPath,
|
||||
setCurrentCodexAccountIndex as setRotationIndex,
|
||||
} from './codex-token-rotation.js';
|
||||
import {
|
||||
normalizeCodexLiveStatus,
|
||||
toCodexLiveStatusSummary,
|
||||
type CodexLiveStatus,
|
||||
type CodexLiveStatusSummary,
|
||||
} from './codex-live-status.js';
|
||||
import {
|
||||
readCodexFeatureFromFile,
|
||||
writeCodexFeatureToFile,
|
||||
} from './codex-config-features.js';
|
||||
import { readHostClaudeFastMode } from './claude-session-settings.js';
|
||||
import { agentTypeForRole, isEffortSupported } from './settings-effort.js';
|
||||
|
||||
export type {
|
||||
CodexAdditionalRateLimitSummary,
|
||||
CodexCreditsSummary,
|
||||
CodexLiveStatusSummary,
|
||||
CodexRateLimitSummary,
|
||||
CodexRateLimitWindowSummary,
|
||||
CodexSpendControlSummary,
|
||||
} from './codex-live-status.js';
|
||||
|
||||
export interface ClaudeAccountSummary {
|
||||
index: number;
|
||||
expiresAt: number | null;
|
||||
scopes: string[];
|
||||
subscriptionType?: string;
|
||||
rateLimitTier?: string;
|
||||
exists: boolean;
|
||||
}
|
||||
|
||||
export interface CodexAccountSummary {
|
||||
index: number;
|
||||
accountId: string | null;
|
||||
email: string | null;
|
||||
planType: string | null;
|
||||
subscriptionUntil: string | null;
|
||||
subscriptionLastChecked: string | null;
|
||||
subscriptionSource: 'jwt-cache' | null;
|
||||
liveStatus: CodexLiveStatusSummary | null;
|
||||
exists: boolean;
|
||||
}
|
||||
|
||||
export interface ModelRoleConfig {
|
||||
model: string;
|
||||
effort: string;
|
||||
}
|
||||
|
||||
export interface ModelAgentTypes {
|
||||
owner: 'claude-code' | 'codex';
|
||||
reviewer: 'claude-code' | 'codex';
|
||||
arbiter: 'claude-code' | 'codex' | null;
|
||||
}
|
||||
|
||||
export interface ModelConfigSnapshot {
|
||||
owner: ModelRoleConfig;
|
||||
reviewer: ModelRoleConfig;
|
||||
arbiter: ModelRoleConfig;
|
||||
agentTypes: ModelAgentTypes;
|
||||
}
|
||||
|
||||
export interface FastModeSnapshot {
|
||||
codex: boolean;
|
||||
claude: boolean;
|
||||
}
|
||||
|
||||
export interface CodexFeatureSnapshot {
|
||||
goals: boolean;
|
||||
}
|
||||
|
||||
const ROLE_KEYS = ['OWNER', 'REVIEWER', 'ARBITER'] as const;
|
||||
|
||||
function envFilePath(): string {
|
||||
return path.join(process.cwd(), '.env');
|
||||
}
|
||||
|
||||
function readJson<T>(file: string): T | null {
|
||||
try {
|
||||
if (!fs.existsSync(file)) return null;
|
||||
return JSON.parse(fs.readFileSync(file, 'utf-8')) as T;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function settingsHomeDir(): string {
|
||||
return process.env.EJCLAW_SETTINGS_HOME || os.homedir();
|
||||
}
|
||||
|
||||
function claudeCredsPath(index: number): string {
|
||||
if (index === 0) {
|
||||
return path.join(settingsHomeDir(), '.claude', '.credentials.json');
|
||||
}
|
||||
return path.join(
|
||||
settingsHomeDir(),
|
||||
'.claude-accounts',
|
||||
String(index),
|
||||
'.credentials.json',
|
||||
);
|
||||
}
|
||||
|
||||
function codexAuthPath(index: number): string {
|
||||
if (index === 0) {
|
||||
return path.join(settingsHomeDir(), '.codex', 'auth.json');
|
||||
}
|
||||
return path.join(
|
||||
settingsHomeDir(),
|
||||
'.codex-accounts',
|
||||
String(index),
|
||||
'auth.json',
|
||||
);
|
||||
}
|
||||
|
||||
function readClaudeAccount(index: number): ClaudeAccountSummary | null {
|
||||
const file = claudeCredsPath(index);
|
||||
if (!fs.existsSync(file)) return null;
|
||||
const data = readJson<{ claudeAiOauth?: Record<string, unknown> }>(file);
|
||||
const oauth = data?.claudeAiOauth ?? {};
|
||||
return {
|
||||
index,
|
||||
expiresAt: typeof oauth.expiresAt === 'number' ? oauth.expiresAt : null,
|
||||
scopes: Array.isArray(oauth.scopes) ? (oauth.scopes as string[]) : [],
|
||||
subscriptionType:
|
||||
typeof oauth.subscriptionType === 'string'
|
||||
? oauth.subscriptionType
|
||||
: undefined,
|
||||
rateLimitTier:
|
||||
typeof oauth.rateLimitTier === 'string' ? oauth.rateLimitTier : undefined,
|
||||
exists: true,
|
||||
};
|
||||
}
|
||||
|
||||
function readCodexAccount(index: number): CodexAccountSummary | null {
|
||||
const file = codexAuthPath(index);
|
||||
if (!fs.existsSync(file)) return null;
|
||||
const data = readJson<{
|
||||
OPENAI_API_KEY?: string;
|
||||
tokens?: { id_token?: string; access_token?: string };
|
||||
}>(file);
|
||||
const live = readCodexLiveStatus(index);
|
||||
let accountId: string | null = null;
|
||||
let email: string | null = null;
|
||||
let planType: string | null = null;
|
||||
let subscriptionUntil: string | null = null;
|
||||
let subscriptionLastChecked: string | null = null;
|
||||
let subscriptionSource: 'jwt-cache' | null = null;
|
||||
let liveStatus: CodexLiveStatusSummary | null = null;
|
||||
const idToken = data?.tokens?.id_token;
|
||||
if (idToken && typeof idToken === 'string') {
|
||||
const parts = idToken.split('.');
|
||||
if (parts.length >= 2) {
|
||||
try {
|
||||
const payload = JSON.parse(
|
||||
Buffer.from(parts[1], 'base64').toString('utf-8'),
|
||||
) as Record<string, unknown>;
|
||||
if (typeof payload.sub === 'string') accountId = payload.sub;
|
||||
if (typeof payload.email === 'string') email = payload.email;
|
||||
const auth = payload['https://api.openai.com/auth'] as
|
||||
| Record<string, unknown>
|
||||
| undefined;
|
||||
if (auth) {
|
||||
if (typeof auth.chatgpt_plan_type === 'string') {
|
||||
planType = auth.chatgpt_plan_type;
|
||||
}
|
||||
if (typeof auth.chatgpt_subscription_active_until === 'string') {
|
||||
subscriptionUntil = auth.chatgpt_subscription_active_until;
|
||||
subscriptionSource = 'jwt-cache';
|
||||
}
|
||||
if (typeof auth.chatgpt_subscription_last_checked === 'string') {
|
||||
subscriptionLastChecked = auth.chatgpt_subscription_last_checked;
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
/* ignore parse errors */
|
||||
}
|
||||
}
|
||||
}
|
||||
// Live wham/usage data, written by refreshCodexAccount, takes precedence.
|
||||
// When live status exists, do not surface the stale JWT active_until claim as
|
||||
// a real billing expiry. OpenAI/Auth0 can cache that claim for days.
|
||||
if (live) {
|
||||
liveStatus = toCodexLiveStatusSummary(live);
|
||||
if (typeof live.plan_type === 'string') planType = live.plan_type;
|
||||
if (typeof live.email === 'string') email = live.email;
|
||||
subscriptionLastChecked = live.checked_at;
|
||||
subscriptionUntil = null;
|
||||
subscriptionSource = null;
|
||||
}
|
||||
return {
|
||||
index,
|
||||
accountId,
|
||||
email,
|
||||
planType,
|
||||
subscriptionUntil,
|
||||
subscriptionLastChecked,
|
||||
subscriptionSource,
|
||||
liveStatus,
|
||||
exists: true,
|
||||
};
|
||||
}
|
||||
|
||||
export function listClaudeAccounts(): ClaudeAccountSummary[] {
|
||||
const out: ClaudeAccountSummary[] = [];
|
||||
const def = readClaudeAccount(0);
|
||||
if (def) out.push(def);
|
||||
const dir = path.join(settingsHomeDir(), '.claude-accounts');
|
||||
if (fs.existsSync(dir)) {
|
||||
for (const i of readAccountIndices(dir)) {
|
||||
const acc = readClaudeAccount(i);
|
||||
if (acc) out.push(acc);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export function listCodexAccounts(): CodexAccountSummary[] {
|
||||
const out: CodexAccountSummary[] = [];
|
||||
const def = readCodexAccount(0);
|
||||
if (def) out.push(def);
|
||||
const dir = path.join(settingsHomeDir(), '.codex-accounts');
|
||||
if (fs.existsSync(dir)) {
|
||||
for (const i of readAccountIndices(dir)) {
|
||||
const acc = readCodexAccount(i);
|
||||
if (acc) out.push(acc);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function readAccountIndices(dir: string): number[] {
|
||||
const indices: number[] = [];
|
||||
for (const entry of fs.readdirSync(dir)) {
|
||||
if (!/^\d+$/.test(entry)) continue;
|
||||
const index = Number.parseInt(entry, 10);
|
||||
if (Number.isFinite(index) && index >= 1) indices.push(index);
|
||||
}
|
||||
return indices.sort((a, b) => a - b);
|
||||
}
|
||||
|
||||
function pickEnvValue(content: string, key: string): string | undefined {
|
||||
const re = new RegExp(`^${key}=(.*)$`, 'm');
|
||||
const match = content.match(re);
|
||||
if (!match) return undefined;
|
||||
return match[1].trim().replace(/^['"]|['"]$/g, '');
|
||||
}
|
||||
|
||||
function readEnvFile(): string {
|
||||
const file = envFilePath();
|
||||
if (!fs.existsSync(file)) return '';
|
||||
return fs.readFileSync(file, 'utf-8');
|
||||
}
|
||||
|
||||
function readEnvOrProcess(key: string): string | undefined {
|
||||
const fromFile = pickEnvValue(readEnvFile(), key);
|
||||
if (fromFile !== undefined) return fromFile;
|
||||
const fromProc = process.env[key];
|
||||
return fromProc;
|
||||
}
|
||||
|
||||
export function getModelConfig(): ModelConfigSnapshot {
|
||||
const env = readEnvFile();
|
||||
const envLookup = (key: string): string | undefined => {
|
||||
const fromFile = pickEnvValue(env, key);
|
||||
if (fromFile !== undefined) return fromFile;
|
||||
return process.env[key];
|
||||
};
|
||||
const out: Partial<ModelConfigSnapshot> = {
|
||||
agentTypes: {
|
||||
owner: agentTypeForRole('owner', envLookup) ?? 'codex',
|
||||
reviewer: agentTypeForRole('reviewer', envLookup) ?? 'claude-code',
|
||||
arbiter: agentTypeForRole('arbiter', envLookup),
|
||||
},
|
||||
};
|
||||
for (const role of ROLE_KEYS) {
|
||||
const model = readEnvOrProcess(`${role}_MODEL`) ?? '';
|
||||
const effort = readEnvOrProcess(`${role}_EFFORT`) ?? '';
|
||||
(out as Record<string, ModelRoleConfig>)[role.toLowerCase()] = {
|
||||
model,
|
||||
effort,
|
||||
};
|
||||
}
|
||||
return out as ModelConfigSnapshot;
|
||||
}
|
||||
|
||||
export interface ModelUpdateInput {
|
||||
owner?: Partial<ModelRoleConfig>;
|
||||
reviewer?: Partial<ModelRoleConfig>;
|
||||
arbiter?: Partial<ModelRoleConfig>;
|
||||
}
|
||||
|
||||
function setOrInsertEnvLine(
|
||||
content: string,
|
||||
key: string,
|
||||
value: string,
|
||||
): string {
|
||||
const re = new RegExp(`^${key}=.*$`, 'm');
|
||||
if (re.test(content)) {
|
||||
return content.replace(re, `${key}=${value}`);
|
||||
}
|
||||
const trimmed = content.replace(/\s*$/, '');
|
||||
return `${trimmed}\n${key}=${value}\n`;
|
||||
}
|
||||
|
||||
export function updateModelConfig(
|
||||
input: ModelUpdateInput,
|
||||
): ModelConfigSnapshot {
|
||||
const file = envFilePath();
|
||||
let content = '';
|
||||
if (fs.existsSync(file)) {
|
||||
content = fs.readFileSync(file, 'utf-8');
|
||||
}
|
||||
const envLookup = (key: string): string | undefined =>
|
||||
pickEnvValue(content, key) ?? process.env[key];
|
||||
|
||||
for (const role of ROLE_KEYS) {
|
||||
const update = (
|
||||
input as Record<string, Partial<ModelRoleConfig> | undefined>
|
||||
)[role.toLowerCase()];
|
||||
if (!update) continue;
|
||||
if (update.model !== undefined) {
|
||||
content = setOrInsertEnvLine(content, `${role}_MODEL`, update.model);
|
||||
}
|
||||
if (update.effort !== undefined) {
|
||||
const agentType = agentTypeForRole(
|
||||
role.toLowerCase() as 'owner' | 'reviewer' | 'arbiter',
|
||||
envLookup,
|
||||
);
|
||||
if (
|
||||
update.effort &&
|
||||
agentType &&
|
||||
!isEffortSupported(agentType, update.effort)
|
||||
) {
|
||||
throw new Error(
|
||||
`${role}_EFFORT=${update.effort} is not supported for ${agentType} agents`,
|
||||
);
|
||||
}
|
||||
content = setOrInsertEnvLine(content, `${role}_EFFORT`, update.effort);
|
||||
}
|
||||
}
|
||||
|
||||
const tempPath = `${file}.tmp`;
|
||||
fs.writeFileSync(tempPath, content, { mode: 0o600 });
|
||||
fs.renameSync(tempPath, file);
|
||||
|
||||
return getModelConfig();
|
||||
}
|
||||
|
||||
const CODEX_OAUTH_TOKEN_URL = 'https://auth.openai.com/oauth/token';
|
||||
const CODEX_OAUTH_CLIENT_ID = 'app_EMoamEEZ73f0CkXaXp7hrann';
|
||||
const CODEX_USAGE_URL = 'https://chatgpt.com/backend-api/wham/usage';
|
||||
|
||||
interface CodexAuthFile {
|
||||
auth_mode?: string;
|
||||
OPENAI_API_KEY?: string | null;
|
||||
tokens?: {
|
||||
id_token?: string;
|
||||
access_token?: string;
|
||||
refresh_token?: string;
|
||||
account_id?: string;
|
||||
};
|
||||
last_refresh?: string;
|
||||
}
|
||||
|
||||
function planStatusPath(index: number): string {
|
||||
if (index === 0) {
|
||||
return path.join(settingsHomeDir(), '.codex', 'plan-status.json');
|
||||
}
|
||||
return path.join(
|
||||
settingsHomeDir(),
|
||||
'.codex-accounts',
|
||||
String(index),
|
||||
'plan-status.json',
|
||||
);
|
||||
}
|
||||
|
||||
function readCodexLiveStatus(index: number): CodexLiveStatus | null {
|
||||
return readJson<CodexLiveStatus>(planStatusPath(index));
|
||||
}
|
||||
|
||||
function writeCodexLiveStatus(index: number, status: CodexLiveStatus): void {
|
||||
const file = planStatusPath(index);
|
||||
fs.mkdirSync(path.dirname(file), { recursive: true });
|
||||
const tempPath = `${file}.tmp`;
|
||||
fs.writeFileSync(tempPath, `${JSON.stringify(status, null, 2)}\n`, {
|
||||
mode: 0o600,
|
||||
});
|
||||
fs.renameSync(tempPath, file);
|
||||
}
|
||||
|
||||
async function fetchCodexLiveUsage(
|
||||
accessToken: string,
|
||||
): Promise<CodexLiveStatus | null> {
|
||||
try {
|
||||
const res = await fetch(CODEX_USAGE_URL, {
|
||||
method: 'GET',
|
||||
headers: { authorization: `Bearer ${accessToken}` },
|
||||
});
|
||||
if (!res.ok) return null;
|
||||
const json = (await res.json()) as unknown;
|
||||
return normalizeCodexLiveStatus(json, new Date().toISOString());
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function readCodexAuthFile(file: string): CodexAuthFile | null {
|
||||
return readJson<CodexAuthFile>(file);
|
||||
}
|
||||
|
||||
function writeCodexAuthFile(file: string, data: CodexAuthFile): void {
|
||||
const tempPath = `${file}.tmp`;
|
||||
fs.writeFileSync(tempPath, `${JSON.stringify(data, null, 2)}\n`, {
|
||||
mode: 0o600,
|
||||
});
|
||||
fs.renameSync(tempPath, file);
|
||||
}
|
||||
|
||||
export async function refreshCodexAccount(
|
||||
index: number,
|
||||
): Promise<CodexAccountSummary> {
|
||||
const file = codexAuthPath(index);
|
||||
if (!fs.existsSync(file)) {
|
||||
throw new Error(`codex auth.json not found for index ${index}`);
|
||||
}
|
||||
const data = readCodexAuthFile(file);
|
||||
const refreshToken = data?.tokens?.refresh_token;
|
||||
if (!refreshToken) {
|
||||
throw new Error(`codex account #${index} has no refresh_token`);
|
||||
}
|
||||
|
||||
const body = new URLSearchParams({
|
||||
grant_type: 'refresh_token',
|
||||
refresh_token: refreshToken,
|
||||
client_id: CODEX_OAUTH_CLIENT_ID,
|
||||
});
|
||||
|
||||
const res = await fetch(CODEX_OAUTH_TOKEN_URL, {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/x-www-form-urlencoded' },
|
||||
body: body.toString(),
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const text = await res.text().catch(() => '');
|
||||
throw new Error(
|
||||
`codex refresh failed (#${index}): ${res.status} ${text.slice(0, 200)}`,
|
||||
);
|
||||
}
|
||||
|
||||
const payload = (await res.json()) as {
|
||||
access_token?: string;
|
||||
id_token?: string;
|
||||
refresh_token?: string;
|
||||
};
|
||||
|
||||
const updated: CodexAuthFile = {
|
||||
...(data ?? {}),
|
||||
tokens: {
|
||||
...(data?.tokens ?? {}),
|
||||
id_token: payload.id_token ?? data?.tokens?.id_token,
|
||||
access_token: payload.access_token ?? data?.tokens?.access_token,
|
||||
refresh_token: payload.refresh_token ?? refreshToken,
|
||||
},
|
||||
last_refresh: new Date().toISOString(),
|
||||
};
|
||||
writeCodexAuthFile(file, updated);
|
||||
|
||||
// Hit chatgpt.com/backend-api/wham/usage to read the live plan, rate limit,
|
||||
// and spend-control state. The JWT id_token's chatgpt_plan_type /
|
||||
// *_active_until / *_last_checked claims are cached on OpenAI's Auth0 side and
|
||||
// don't refresh on every OAuth refresh_token grant, so the dashboard must not
|
||||
// present that cached expiry as live billing truth.
|
||||
const accessToken =
|
||||
payload.access_token ?? data?.tokens?.access_token ?? null;
|
||||
if (accessToken) {
|
||||
const live = await fetchCodexLiveUsage(accessToken);
|
||||
if (live) {
|
||||
writeCodexLiveStatus(index, live);
|
||||
}
|
||||
}
|
||||
|
||||
const summary = readCodexAccount(index);
|
||||
if (!summary)
|
||||
throw new Error('failed to re-read codex account after refresh');
|
||||
return summary;
|
||||
}
|
||||
|
||||
/**
|
||||
* settings-store lists codex accounts in an order that includes the default
|
||||
* `~/.codex/auth.json` as index 0 plus `~/.codex-accounts/{N}` as index N.
|
||||
* The rotation array (codex-token-rotation) only loads `~/.codex-accounts/{N}`
|
||||
* when those dirs exist (it ignores `~/.codex/auth.json` in that mode), so its
|
||||
* array indices are off-by-one vs. the settings indices. Translate via path.
|
||||
*/
|
||||
export function getActiveCodexSettingsIndex(): number | null {
|
||||
const activePath = getActiveCodexAuthPath();
|
||||
if (!activePath) return null;
|
||||
// Walk the same listing order as listCodexAccounts() to find the matching
|
||||
// settings-store index.
|
||||
if (codexAuthPath(0) === activePath && fs.existsSync(activePath)) {
|
||||
return 0;
|
||||
}
|
||||
const dir = path.join(settingsHomeDir(), '.codex-accounts');
|
||||
if (fs.existsSync(dir)) {
|
||||
for (const i of readAccountIndices(dir)) {
|
||||
if (codexAuthPath(i) === activePath) return i;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function setActiveCodexSettingsIndex(settingsIndex: number): void {
|
||||
const file = codexAuthPath(settingsIndex);
|
||||
if (!fs.existsSync(file)) {
|
||||
throw new Error(
|
||||
`codex auth.json not found for settings index ${settingsIndex}`,
|
||||
);
|
||||
}
|
||||
const rotationIndex = findCodexAccountIndexByAuthPath(file);
|
||||
if (rotationIndex === null) {
|
||||
throw new Error(
|
||||
`codex switch: settings #${settingsIndex} (${file}) is not part of the rotation pool. ` +
|
||||
`Rotation only manages accounts under ~/.codex-accounts/. ` +
|
||||
`If you want to use ~/.codex/auth.json directly, remove the ~/.codex-accounts dir first.`,
|
||||
);
|
||||
}
|
||||
setRotationIndex(rotationIndex);
|
||||
}
|
||||
|
||||
export async function refreshAllCodexAccounts(): Promise<{
|
||||
refreshed: number[];
|
||||
failed: Array<{ index: number; error: string }>;
|
||||
}> {
|
||||
const refreshed: number[] = [];
|
||||
const failed: Array<{ index: number; error: string }> = [];
|
||||
const accounts = listCodexAccounts();
|
||||
for (const acc of accounts) {
|
||||
try {
|
||||
await refreshCodexAccount(acc.index);
|
||||
refreshed.push(acc.index);
|
||||
} catch (err) {
|
||||
failed.push({
|
||||
index: acc.index,
|
||||
error: err instanceof Error ? err.message : String(err),
|
||||
});
|
||||
}
|
||||
}
|
||||
return { refreshed, failed };
|
||||
}
|
||||
|
||||
const CODEX_REFRESH_INTERVAL_MS = 6 * 60 * 60 * 1000;
|
||||
let codexRefreshTimer: ReturnType<typeof setInterval> | null = null;
|
||||
|
||||
export function startCodexAccountRefreshLoop(): void {
|
||||
if (codexRefreshTimer) return;
|
||||
// Stagger first refresh so server boot isn't slowed.
|
||||
setTimeout(() => {
|
||||
void refreshAllCodexAccounts().catch(() => {
|
||||
/* swallow; per-account errors logged inside */
|
||||
});
|
||||
}, 60_000).unref?.();
|
||||
codexRefreshTimer = setInterval(() => {
|
||||
void refreshAllCodexAccounts().catch(() => {
|
||||
/* swallow */
|
||||
});
|
||||
}, CODEX_REFRESH_INTERVAL_MS);
|
||||
codexRefreshTimer.unref?.();
|
||||
}
|
||||
|
||||
export function stopCodexAccountRefreshLoop(): void {
|
||||
if (codexRefreshTimer) {
|
||||
clearInterval(codexRefreshTimer);
|
||||
codexRefreshTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
function codexConfigFile(): string {
|
||||
return path.join(settingsHomeDir(), '.codex', 'config.toml');
|
||||
}
|
||||
|
||||
function claudeSettingsPath(): string {
|
||||
return path.join(settingsHomeDir(), '.claude', 'settings.json');
|
||||
}
|
||||
|
||||
function readCodexFastMode(): boolean {
|
||||
return readCodexFeatureFromFile(codexConfigFile(), 'fast_mode');
|
||||
}
|
||||
|
||||
function writeCodexFastMode(value: boolean): void {
|
||||
writeCodexFeatureToFile(codexConfigFile(), 'fast_mode', value);
|
||||
}
|
||||
|
||||
function readClaudeFastMode(): boolean {
|
||||
return readHostClaudeFastMode();
|
||||
}
|
||||
|
||||
function writeClaudeFastMode(value: boolean): void {
|
||||
const file = claudeSettingsPath();
|
||||
fs.mkdirSync(path.dirname(file), { recursive: true });
|
||||
let data: Record<string, unknown> = {};
|
||||
if (fs.existsSync(file)) {
|
||||
try {
|
||||
data = JSON.parse(fs.readFileSync(file, 'utf-8')) as Record<
|
||||
string,
|
||||
unknown
|
||||
>;
|
||||
} catch {
|
||||
data = {};
|
||||
}
|
||||
}
|
||||
data.fastMode = value;
|
||||
const tempPath = `${file}.tmp`;
|
||||
fs.writeFileSync(tempPath, `${JSON.stringify(data, null, 2)}\n`, {
|
||||
mode: 0o600,
|
||||
});
|
||||
fs.renameSync(tempPath, file);
|
||||
}
|
||||
|
||||
export function getFastMode(): FastModeSnapshot {
|
||||
return {
|
||||
codex: readCodexFastMode(),
|
||||
claude: readClaudeFastMode(),
|
||||
};
|
||||
}
|
||||
|
||||
export function updateFastMode(
|
||||
input: Partial<FastModeSnapshot>,
|
||||
): FastModeSnapshot {
|
||||
if (typeof input.codex === 'boolean') writeCodexFastMode(input.codex);
|
||||
if (typeof input.claude === 'boolean') writeClaudeFastMode(input.claude);
|
||||
return getFastMode();
|
||||
}
|
||||
|
||||
function readCodexGoals(): boolean {
|
||||
const fromConfig = readCodexFeatureFromFile(codexConfigFile(), 'goals');
|
||||
if (fromConfig) return true;
|
||||
// Legacy .env opt-in kept for backward compatibility until migrated.
|
||||
return readEnvOrProcess('CODEX_GOALS') === 'true';
|
||||
}
|
||||
|
||||
function writeCodexGoals(value: boolean): void {
|
||||
writeCodexFeatureToFile(codexConfigFile(), 'goals', value);
|
||||
|
||||
const file = envFilePath();
|
||||
if (!fs.existsSync(file)) return;
|
||||
const content = fs.readFileSync(file, 'utf-8');
|
||||
if (!/^CODEX_GOALS=.*$/m.test(content)) return;
|
||||
const updated = content
|
||||
.split('\n')
|
||||
.filter((line) => !/^CODEX_GOALS=.*$/.test(line))
|
||||
.join('\n')
|
||||
.replace(/\n+$/, '');
|
||||
const tempPath = `${file}.tmp`;
|
||||
fs.writeFileSync(tempPath, updated ? `${updated}\n` : '', { mode: 0o600 });
|
||||
fs.renameSync(tempPath, file);
|
||||
}
|
||||
|
||||
export function getCodexFeatures(): CodexFeatureSnapshot {
|
||||
return {
|
||||
goals: readCodexGoals(),
|
||||
};
|
||||
}
|
||||
|
||||
export function updateCodexFeatures(
|
||||
input: Partial<CodexFeatureSnapshot>,
|
||||
): CodexFeatureSnapshot {
|
||||
if (typeof input.goals === 'boolean') writeCodexGoals(input.goals);
|
||||
return getCodexFeatures();
|
||||
}
|
||||
|
||||
export function removeAccountDirectory(
|
||||
provider: 'claude' | 'codex',
|
||||
index: number,
|
||||
): void {
|
||||
if (!Number.isFinite(index) || index < 1) {
|
||||
throw new Error('cannot remove default account (index 0)');
|
||||
}
|
||||
const baseDir =
|
||||
provider === 'claude'
|
||||
? path.join(settingsHomeDir(), '.claude-accounts', String(index))
|
||||
: path.join(settingsHomeDir(), '.codex-accounts', String(index));
|
||||
if (!fs.existsSync(baseDir)) {
|
||||
throw new Error(`account directory not found: ${baseDir}`);
|
||||
}
|
||||
fs.rmSync(baseDir, { recursive: true, force: true });
|
||||
}
|
||||
|
||||
export function addClaudeAccountFromToken(token: string): {
|
||||
index: number;
|
||||
accountId: string | null;
|
||||
} {
|
||||
const trimmed = token.trim();
|
||||
if (!trimmed) throw new Error('empty token');
|
||||
|
||||
const parts = trimmed.split('.');
|
||||
if (parts.length < 2) {
|
||||
throw new Error('invalid OAuth token: expected JWT format');
|
||||
}
|
||||
let payload: Record<string, unknown>;
|
||||
try {
|
||||
payload = JSON.parse(
|
||||
Buffer.from(parts[1], 'base64').toString('utf-8'),
|
||||
) as Record<string, unknown>;
|
||||
} catch {
|
||||
throw new Error('invalid OAuth token: payload not parseable');
|
||||
}
|
||||
const exp = typeof payload.exp === 'number' ? payload.exp * 1000 : 0;
|
||||
const accountId = typeof payload.sub === 'string' ? payload.sub : null;
|
||||
|
||||
const baseDir = path.join(settingsHomeDir(), '.claude-accounts');
|
||||
if (!fs.existsSync(baseDir)) {
|
||||
fs.mkdirSync(baseDir, { recursive: true, mode: 0o700 });
|
||||
}
|
||||
|
||||
let nextIndex = 1;
|
||||
while (
|
||||
fs.existsSync(path.join(baseDir, String(nextIndex), '.credentials.json'))
|
||||
) {
|
||||
nextIndex += 1;
|
||||
}
|
||||
const dir = path.join(baseDir, String(nextIndex));
|
||||
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
||||
|
||||
const creds = {
|
||||
claudeAiOauth: {
|
||||
accessToken: trimmed,
|
||||
refreshToken: '',
|
||||
expiresAt: exp,
|
||||
scopes: ['user:profile', 'user:inference'],
|
||||
},
|
||||
};
|
||||
const credsPath = path.join(dir, '.credentials.json');
|
||||
const tempPath = `${credsPath}.tmp`;
|
||||
fs.writeFileSync(tempPath, JSON.stringify(creds, null, 2), { mode: 0o600 });
|
||||
fs.renameSync(tempPath, credsPath);
|
||||
|
||||
return { index: nextIndex, accountId };
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
import fs from 'fs';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
|
||||
import { afterEach, describe, expect, it } from 'vitest';
|
||||
|
||||
import { createWebDashboardHandler } from './web-dashboard-server.js';
|
||||
|
||||
const ONE_PIXEL_PNG = Buffer.from(
|
||||
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+/p9sAAAAASUVORK5CYII=',
|
||||
'base64',
|
||||
);
|
||||
|
||||
const tempDirs: string[] = [];
|
||||
|
||||
afterEach(() => {
|
||||
for (const dir of tempDirs.splice(0)) {
|
||||
fs.rmSync(dir, { force: true, recursive: true });
|
||||
}
|
||||
});
|
||||
|
||||
describe('web dashboard attachment previews', () => {
|
||||
it('serves validated direct temp image attachments', async () => {
|
||||
const tempDir = fs.mkdtempSync(
|
||||
path.join(os.tmpdir(), 'ejclaw-dashboard-attachment-'),
|
||||
);
|
||||
tempDirs.push(tempDir);
|
||||
const filePath = path.join(tempDir, 'bar-chart-label-fit-playwright.png');
|
||||
fs.writeFileSync(filePath, ONE_PIXEL_PNG);
|
||||
const handler = createWebDashboardHandler({
|
||||
readStatusSnapshots: () => [],
|
||||
getTasks: () => [],
|
||||
getPairedTasks: () => [],
|
||||
});
|
||||
|
||||
const response = await handler(
|
||||
new Request(
|
||||
`http://localhost/api/attachments?path=${encodeURIComponent(filePath)}`,
|
||||
),
|
||||
);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.headers.get('content-type')).toBe('image/png');
|
||||
expect(Buffer.from(await response.arrayBuffer())).toEqual(ONE_PIXEL_PNG);
|
||||
});
|
||||
});
|
||||
@@ -1,50 +0,0 @@
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
|
||||
import { validateOutboundAttachments } from './outbound-attachments.js';
|
||||
|
||||
function attachmentJsonResponse(value: unknown, init?: ResponseInit): Response {
|
||||
return new Response(JSON.stringify(value), {
|
||||
...init,
|
||||
headers: {
|
||||
'content-type': 'application/json; charset=utf-8',
|
||||
...(init?.headers as Record<string, string> | undefined),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function getAttachmentContentType(filePath: string): string {
|
||||
const ext = path.extname(filePath).toLowerCase();
|
||||
if (ext === '.png') return 'image/png';
|
||||
if (ext === '.jpg' || ext === '.jpeg') return 'image/jpeg';
|
||||
if (ext === '.gif') return 'image/gif';
|
||||
if (ext === '.webp') return 'image/webp';
|
||||
if (ext === '.bmp') return 'image/bmp';
|
||||
return 'application/octet-stream';
|
||||
}
|
||||
|
||||
export function serveValidatedAttachment(url: URL): Response {
|
||||
const requestedPath = url.searchParams.get('path');
|
||||
if (!requestedPath) {
|
||||
return attachmentJsonResponse(
|
||||
{ error: 'Missing attachment path' },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
const validation = validateOutboundAttachments([{ path: requestedPath }]);
|
||||
const file = validation.files[0];
|
||||
if (!file) {
|
||||
return attachmentJsonResponse(
|
||||
{ error: 'Attachment not found or not allowed' },
|
||||
{ status: 404 },
|
||||
);
|
||||
}
|
||||
|
||||
return new Response(fs.readFileSync(file.attachment), {
|
||||
headers: {
|
||||
'content-type': getAttachmentContentType(file.attachment),
|
||||
'cache-control': 'private, max-age=300',
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -1,72 +0,0 @@
|
||||
import fs from 'fs';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
|
||||
import { afterEach, describe, expect, it } from 'vitest';
|
||||
|
||||
import { createWebDashboardHandler } from './web-dashboard-server.js';
|
||||
|
||||
const tempDirs: string[] = [];
|
||||
|
||||
afterEach(() => {
|
||||
for (const dir of tempDirs.splice(0)) {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
describe('web dashboard API auth', () => {
|
||||
it('requires a bearer token for API routes when dashboard auth is configured', async () => {
|
||||
const handler = createWebDashboardHandler({
|
||||
authToken: 'mobile-secret',
|
||||
readStatusSnapshots: () => [],
|
||||
getTasks: () => [],
|
||||
getPairedTasks: () => [],
|
||||
startBackgroundCacheRefresh: false,
|
||||
});
|
||||
|
||||
const missing = await handler(new Request('http://localhost/api/health'));
|
||||
expect(missing.status).toBe(401);
|
||||
expect(missing.headers.get('www-authenticate')).toBe('Bearer');
|
||||
|
||||
const wrong = await handler(
|
||||
new Request('http://localhost/api/health', {
|
||||
headers: { authorization: 'Bearer wrong-secret' },
|
||||
}),
|
||||
);
|
||||
expect(wrong.status).toBe(401);
|
||||
|
||||
const ok = await handler(
|
||||
new Request('http://localhost/api/health', {
|
||||
headers: { authorization: 'Bearer mobile-secret' },
|
||||
}),
|
||||
);
|
||||
expect(ok.status).toBe(200);
|
||||
await expect(ok.json()).resolves.toEqual({ ok: true });
|
||||
});
|
||||
|
||||
it('accepts the mobile token header and leaves static assets readable', async () => {
|
||||
const staticDir = fs.mkdtempSync(
|
||||
path.join(os.tmpdir(), 'ejclaw-dashboard-auth-'),
|
||||
);
|
||||
tempDirs.push(staticDir);
|
||||
fs.writeFileSync(path.join(staticDir, 'index.html'), '<main>ok</main>');
|
||||
const handler = createWebDashboardHandler({
|
||||
authToken: 'mobile-secret',
|
||||
staticDir,
|
||||
readStatusSnapshots: () => [],
|
||||
getTasks: () => [],
|
||||
startBackgroundCacheRefresh: false,
|
||||
});
|
||||
|
||||
const asset = await handler(new Request('http://localhost/'));
|
||||
expect(asset.status).toBe(200);
|
||||
await expect(asset.text()).resolves.toContain('<main>ok</main>');
|
||||
|
||||
const api = await handler(
|
||||
new Request('http://localhost/api/health', {
|
||||
headers: { 'x-ejclaw-dashboard-token': 'mobile-secret' },
|
||||
}),
|
||||
);
|
||||
expect(api.status).toBe(200);
|
||||
});
|
||||
});
|
||||
@@ -1,231 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import type { NewMessage, PairedTask, PairedTurnOutput } from './types.js';
|
||||
import { buildWebDashboardRoomActivity } from './web-dashboard-data.js';
|
||||
|
||||
function makePairedTask(overrides: Partial<PairedTask>): PairedTask {
|
||||
return {
|
||||
id: 'paired-1',
|
||||
chat_jid: 'dc:ops',
|
||||
group_folder: 'ops',
|
||||
owner_service_id: 'codex-main',
|
||||
reviewer_service_id: 'claude-reviewer',
|
||||
owner_agent_type: 'codex',
|
||||
reviewer_agent_type: 'claude-code',
|
||||
arbiter_agent_type: 'codex',
|
||||
title: 'Dashboard PR',
|
||||
source_ref: null,
|
||||
plan_notes: null,
|
||||
review_requested_at: null,
|
||||
round_trip_count: 0,
|
||||
owner_failure_count: 0,
|
||||
owner_step_done_streak: 0,
|
||||
finalize_step_done_count: 0,
|
||||
task_done_then_user_reopen_count: 0,
|
||||
empty_step_done_streak: 0,
|
||||
status: 'review_ready',
|
||||
arbiter_verdict: null,
|
||||
arbiter_requested_at: null,
|
||||
completion_reason: null,
|
||||
created_at: '2026-04-26T04:00:00.000Z',
|
||||
updated_at: '2026-04-26T04:30:00.000Z',
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
const roomEntry = {
|
||||
jid: 'dc:ops',
|
||||
name: '#ops',
|
||||
folder: 'ops',
|
||||
agentType: 'codex' as const,
|
||||
status: 'inactive' as const,
|
||||
elapsedMs: null,
|
||||
pendingMessages: false,
|
||||
pendingTasks: 0,
|
||||
};
|
||||
|
||||
describe('web dashboard attachment data', () => {
|
||||
it('normalizes structured EJClaw envelopes in room messages and outputs', () => {
|
||||
const task = makePairedTask({ id: 'paired-structured' });
|
||||
const structured = JSON.stringify({
|
||||
ejclaw: {
|
||||
visibility: 'public',
|
||||
text: '라벨 좌측 클리핑 회귀 수정했습니다.',
|
||||
verdict: 'done',
|
||||
attachments: [
|
||||
{
|
||||
path: '/tmp/bar-chart-label-fit-playwright.png',
|
||||
name: 'bar-chart-label-fit-playwright.png',
|
||||
mime: 'image/png',
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
const output: PairedTurnOutput = {
|
||||
id: 1,
|
||||
task_id: task.id,
|
||||
turn_number: 1,
|
||||
role: 'owner',
|
||||
output_text: structured,
|
||||
verdict: 'done',
|
||||
created_at: '2026-04-26T05:30:00.000Z',
|
||||
};
|
||||
const message: NewMessage = {
|
||||
id: 'msg-structured',
|
||||
chat_jid: 'dc:ops',
|
||||
sender: 'bot-1',
|
||||
sender_name: 'owner',
|
||||
content: structured,
|
||||
timestamp: '2026-04-26T05:31:00.000Z',
|
||||
is_from_me: true,
|
||||
is_bot_message: true,
|
||||
message_source_kind: 'bot',
|
||||
};
|
||||
|
||||
const activity = buildWebDashboardRoomActivity({
|
||||
serviceId: 'codex-main',
|
||||
entry: roomEntry,
|
||||
pairedTask: task,
|
||||
turns: [],
|
||||
attempts: [],
|
||||
outputs: [output],
|
||||
messages: [message],
|
||||
});
|
||||
|
||||
expect(activity.messages[0]).toMatchObject({
|
||||
content: '라벨 좌측 클리핑 회귀 수정했습니다.',
|
||||
attachments: [
|
||||
{
|
||||
path: '/tmp/bar-chart-label-fit-playwright.png',
|
||||
name: 'bar-chart-label-fit-playwright.png',
|
||||
mime: 'image/png',
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(activity.messages[0]?.content).not.toContain('"ejclaw"');
|
||||
expect(activity.pairedTask?.outputs[0]).toMatchObject({
|
||||
outputText: '라벨 좌측 클리핑 회귀 수정했습니다.',
|
||||
attachments: [
|
||||
{
|
||||
path: '/tmp/bar-chart-label-fit-playwright.png',
|
||||
name: 'bar-chart-label-fit-playwright.png',
|
||||
mime: 'image/png',
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(activity.pairedTask?.outputs[0]?.outputText).not.toContain(
|
||||
'"ejclaw"',
|
||||
);
|
||||
});
|
||||
|
||||
it('turns legacy Discord image placeholders into dashboard attachments', () => {
|
||||
const message: NewMessage = {
|
||||
id: 'msg-image',
|
||||
chat_jid: 'dc:ops',
|
||||
sender: 'bot-1',
|
||||
sender_name: 'owner',
|
||||
content:
|
||||
'라벨 좌측 클리핑 회귀 수정했습니다.\n[Image: screenshot.png → /tmp/bar-chart-label-fit-playwright.png]',
|
||||
timestamp: '2026-04-26T05:31:00.000Z',
|
||||
is_from_me: true,
|
||||
is_bot_message: true,
|
||||
message_source_kind: 'bot',
|
||||
};
|
||||
|
||||
const activity = buildWebDashboardRoomActivity({
|
||||
serviceId: 'codex-main',
|
||||
entry: roomEntry,
|
||||
pairedTask: null,
|
||||
turns: [],
|
||||
attempts: [],
|
||||
outputs: [],
|
||||
messages: [message],
|
||||
});
|
||||
|
||||
expect(activity.messages[0]).toMatchObject({
|
||||
content: '라벨 좌측 클리핑 회귀 수정했습니다.',
|
||||
attachments: [
|
||||
{
|
||||
path: '/tmp/bar-chart-label-fit-playwright.png',
|
||||
name: 'bar-chart-label-fit-playwright.png',
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it('shows stored paired turn output attachments in room activity', () => {
|
||||
const task = makePairedTask({ id: 'paired-output-attachments' });
|
||||
const output: PairedTurnOutput = {
|
||||
id: 1,
|
||||
task_id: task.id,
|
||||
turn_number: 1,
|
||||
role: 'owner',
|
||||
output_text: 'TASK_DONE\n\n새 렌더 증거 첨부',
|
||||
attachments: [
|
||||
{
|
||||
path: '/tmp/settings-v0.1.92-deployed-390.png',
|
||||
name: 'settings-v0.1.92-deployed-390.png',
|
||||
mime: 'image/png',
|
||||
},
|
||||
],
|
||||
verdict: 'task_done',
|
||||
created_at: '2026-04-26T05:30:00.000Z',
|
||||
};
|
||||
|
||||
const activity = buildWebDashboardRoomActivity({
|
||||
serviceId: 'codex-main',
|
||||
entry: roomEntry,
|
||||
pairedTask: task,
|
||||
turns: [],
|
||||
attempts: [],
|
||||
outputs: [output],
|
||||
messages: [],
|
||||
});
|
||||
|
||||
expect(activity.pairedTask?.outputs[0]).toMatchObject({
|
||||
outputText: 'TASK_DONE\n\n새 렌더 증거 첨부',
|
||||
attachments: [
|
||||
{
|
||||
path: '/tmp/settings-v0.1.92-deployed-390.png',
|
||||
name: 'settings-v0.1.92-deployed-390.png',
|
||||
mime: 'image/png',
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it('turns markdown image output into dashboard attachments', () => {
|
||||
const message: NewMessage = {
|
||||
id: 'msg-markdown-image',
|
||||
chat_jid: 'dc:ops',
|
||||
sender: 'bot-1',
|
||||
sender_name: 'owner',
|
||||
content:
|
||||
'라벨 좌측 클리핑 회귀 수정했습니다.\n',
|
||||
timestamp: '2026-04-26T05:31:00.000Z',
|
||||
is_from_me: true,
|
||||
is_bot_message: true,
|
||||
message_source_kind: 'bot',
|
||||
};
|
||||
|
||||
const activity = buildWebDashboardRoomActivity({
|
||||
serviceId: 'codex-main',
|
||||
entry: roomEntry,
|
||||
pairedTask: null,
|
||||
turns: [],
|
||||
attempts: [],
|
||||
outputs: [],
|
||||
messages: [message],
|
||||
});
|
||||
|
||||
expect(activity.messages[0]).toMatchObject({
|
||||
content: '라벨 좌측 클리핑 회귀 수정했습니다.',
|
||||
attachments: [
|
||||
{
|
||||
path: '/tmp/bar-chart-label-fit-playwright.png',
|
||||
name: 'bar-chart-label-fit-playwright.png',
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,879 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import type { StatusSnapshot } from './status-dashboard.js';
|
||||
import type {
|
||||
PairedTurnAttemptRecord,
|
||||
PairedTurnRecord,
|
||||
WorkItem,
|
||||
} from './db.js';
|
||||
import type {
|
||||
NewMessage,
|
||||
PairedTask,
|
||||
PairedTurnOutput,
|
||||
ScheduledTask,
|
||||
} from './types.js';
|
||||
import {
|
||||
buildWebDashboardRoomActivity,
|
||||
buildWebDashboardOverview,
|
||||
sanitizeScheduledTask,
|
||||
} from './web-dashboard-data.js';
|
||||
|
||||
function makeTask(overrides: Partial<ScheduledTask>): ScheduledTask {
|
||||
return {
|
||||
id: 'task-1',
|
||||
group_folder: 'general',
|
||||
chat_jid: 'dc:general',
|
||||
agent_type: null,
|
||||
status_message_id: null,
|
||||
status_started_at: null,
|
||||
prompt: 'secret long prompt that should not be exposed in full',
|
||||
schedule_type: 'cron',
|
||||
schedule_value: '* * * * *',
|
||||
context_mode: 'group',
|
||||
next_run: '2026-04-26T05:00:00.000Z',
|
||||
last_run: null,
|
||||
last_result: null,
|
||||
status: 'active',
|
||||
created_at: '2026-04-26T04:00:00.000Z',
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function makePairedTask(overrides: Partial<PairedTask>): PairedTask {
|
||||
return {
|
||||
id: 'paired-1',
|
||||
chat_jid: 'dc:general',
|
||||
group_folder: 'general',
|
||||
owner_service_id: 'codex-main',
|
||||
reviewer_service_id: 'claude-reviewer',
|
||||
owner_agent_type: 'codex',
|
||||
reviewer_agent_type: 'claude-code',
|
||||
arbiter_agent_type: 'codex',
|
||||
title: 'Dashboard PR',
|
||||
source_ref: null,
|
||||
plan_notes: null,
|
||||
review_requested_at: null,
|
||||
round_trip_count: 0,
|
||||
owner_failure_count: 0,
|
||||
owner_step_done_streak: 0,
|
||||
finalize_step_done_count: 0,
|
||||
task_done_then_user_reopen_count: 0,
|
||||
empty_step_done_streak: 0,
|
||||
status: 'review_ready',
|
||||
arbiter_verdict: null,
|
||||
arbiter_requested_at: null,
|
||||
completion_reason: null,
|
||||
created_at: '2026-04-26T04:00:00.000Z',
|
||||
updated_at: '2026-04-26T04:30:00.000Z',
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function makeDeliveredWorkItem(overrides: Partial<WorkItem> = {}): WorkItem {
|
||||
return {
|
||||
id: 100,
|
||||
group_folder: 'ops',
|
||||
chat_jid: 'dc:ops',
|
||||
agent_type: 'codex',
|
||||
service_id: 'codex-main',
|
||||
delivery_role: 'owner',
|
||||
status: 'delivered',
|
||||
start_seq: null,
|
||||
end_seq: null,
|
||||
result_payload: 'TASK_DONE\n\ncanonical delivered output',
|
||||
attachments: [],
|
||||
delivery_attempts: 1,
|
||||
delivery_message_id: 'discord-msg-100',
|
||||
last_error: null,
|
||||
created_at: '2026-04-26T05:30:00.000Z',
|
||||
updated_at: '2026-04-26T05:30:10.000Z',
|
||||
delivered_at: '2026-04-26T05:30:10.000Z',
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe('web dashboard data', () => {
|
||||
it('builds overview counts from status snapshots and scheduled tasks', () => {
|
||||
const snapshots: StatusSnapshot[] = [
|
||||
{
|
||||
serviceId: 'codex-main',
|
||||
agentType: 'codex',
|
||||
assistantName: 'Codex',
|
||||
updatedAt: '2026-04-26T04:59:00.000Z',
|
||||
entries: [
|
||||
{
|
||||
jid: 'dc:1',
|
||||
name: '#general',
|
||||
folder: 'general',
|
||||
agentType: 'codex',
|
||||
status: 'processing',
|
||||
elapsedMs: 1200,
|
||||
pendingMessages: true,
|
||||
pendingTasks: 2,
|
||||
},
|
||||
{
|
||||
jid: 'dc:2',
|
||||
name: '#brain',
|
||||
folder: 'brain',
|
||||
agentType: 'claude-code',
|
||||
status: 'inactive',
|
||||
elapsedMs: null,
|
||||
pendingMessages: false,
|
||||
pendingTasks: 0,
|
||||
},
|
||||
],
|
||||
usageRows: [
|
||||
{
|
||||
name: 'codex-a',
|
||||
h5pct: 10,
|
||||
h5reset: '1h',
|
||||
d7pct: 20,
|
||||
d7reset: '2d',
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
const overview = buildWebDashboardOverview({
|
||||
now: '2026-04-26T05:00:00.000Z',
|
||||
snapshots,
|
||||
tasks: [
|
||||
makeTask({
|
||||
id: 'watch-1',
|
||||
prompt: '[BACKGROUND CI WATCH] owner/repo#1',
|
||||
status: 'active',
|
||||
}),
|
||||
makeTask({ id: 'cron-1', prompt: 'regular cleanup', status: 'paused' }),
|
||||
],
|
||||
});
|
||||
|
||||
expect(overview.rooms.total).toBe(2);
|
||||
expect(overview.rooms.active).toBe(1);
|
||||
expect(overview.rooms.waiting).toBe(0);
|
||||
expect(overview.rooms.inactive).toBe(1);
|
||||
expect(overview.tasks.total).toBe(2);
|
||||
expect(overview.tasks.active).toBe(1);
|
||||
expect(overview.tasks.paused).toBe(1);
|
||||
expect(overview.tasks.watchers.active).toBe(1);
|
||||
expect(overview.usage.rows).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('deduplicates full usage rows from renderer and codex snapshots', () => {
|
||||
const snapshots: StatusSnapshot[] = [
|
||||
{
|
||||
serviceId: 'codex-main',
|
||||
agentType: 'codex',
|
||||
assistantName: 'Codex',
|
||||
updatedAt: '2026-04-26T04:59:00.000Z',
|
||||
entries: [],
|
||||
usageRowsFetchedAt: '2026-04-26T04:59:00.000Z',
|
||||
usageRows: [
|
||||
{
|
||||
name: 'Codex1',
|
||||
h5pct: 20,
|
||||
h5reset: '1h',
|
||||
d7pct: 30,
|
||||
d7reset: '2d',
|
||||
},
|
||||
{
|
||||
name: 'Codex2',
|
||||
h5pct: 15,
|
||||
h5reset: '1h',
|
||||
d7pct: 18,
|
||||
d7reset: '2d',
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
serviceId: 'claude-main',
|
||||
agentType: 'claude-code',
|
||||
assistantName: 'Claude',
|
||||
updatedAt: '2026-04-26T05:00:00.000Z',
|
||||
entries: [],
|
||||
usageRowsFetchedAt: '2026-04-26T05:00:00.000Z',
|
||||
usageRows: [
|
||||
{
|
||||
name: 'Claude1 Max',
|
||||
h5pct: 66,
|
||||
h5reset: '2h',
|
||||
d7pct: 40,
|
||||
d7reset: '4d',
|
||||
},
|
||||
{
|
||||
name: 'Kimi',
|
||||
h5pct: 10,
|
||||
h5reset: '3h',
|
||||
d7pct: 12,
|
||||
d7reset: '5d',
|
||||
},
|
||||
{
|
||||
name: 'Codex1',
|
||||
h5pct: 25,
|
||||
h5reset: '55m',
|
||||
d7pct: 35,
|
||||
d7reset: '2d',
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
const overview = buildWebDashboardOverview({
|
||||
now: '2026-04-26T05:01:00.000Z',
|
||||
snapshots,
|
||||
tasks: [],
|
||||
});
|
||||
|
||||
expect(overview.usage.rows.map((row) => row.name)).toEqual([
|
||||
'Claude1 Max',
|
||||
'Kimi',
|
||||
'Codex1',
|
||||
'Codex2',
|
||||
]);
|
||||
expect(
|
||||
overview.usage.rows.filter((row) => row.name === 'Codex1'),
|
||||
).toHaveLength(1);
|
||||
expect(overview.usage.fetchedAt).toBe('2026-04-26T05:00:00.000Z');
|
||||
});
|
||||
|
||||
it('does not expose full scheduled task prompts through API payloads', () => {
|
||||
const sanitized = sanitizeScheduledTask(
|
||||
makeTask({
|
||||
prompt: 'x'.repeat(220),
|
||||
last_result: 'ok',
|
||||
}),
|
||||
);
|
||||
|
||||
expect(sanitized).not.toHaveProperty('prompt');
|
||||
expect(sanitized.promptPreview.length).toBeLessThanOrEqual(123);
|
||||
expect(sanitized.promptLength).toBe(220);
|
||||
});
|
||||
|
||||
it('redacts common secret values from scheduled task prompt previews', () => {
|
||||
const sanitized = sanitizeScheduledTask(
|
||||
makeTask({
|
||||
prompt:
|
||||
'deploy with OPENAI_API_KEY=sk-abcdefghijklmnopqrstuvwxyz123456 and BOT_TOKEN=plain-secret-value',
|
||||
}),
|
||||
);
|
||||
|
||||
expect(sanitized.promptPreview).toContain('OPENAI_API_KEY=<redacted>');
|
||||
expect(sanitized.promptPreview).toContain('BOT_TOKEN=<redacted>');
|
||||
expect(sanitized.promptPreview).not.toContain(
|
||||
'sk-abcdefghijklmnopqrstuvwxyz123456',
|
||||
);
|
||||
expect(sanitized.promptPreview).not.toContain('plain-secret-value');
|
||||
});
|
||||
});
|
||||
|
||||
describe('web dashboard room activity data', () => {
|
||||
it('builds redacted room activity from messages and paired turn output', () => {
|
||||
const longMessageTail = 'TAIL_MESSAGE_VISIBLE';
|
||||
const longOutputTail = 'TAIL_OUTPUT_VISIBLE';
|
||||
const task = makePairedTask({
|
||||
id: 'paired-room-1',
|
||||
chat_jid: 'dc:ops',
|
||||
status: 'in_review',
|
||||
round_trip_count: 3,
|
||||
updated_at: '2026-04-26T05:30:00.000Z',
|
||||
});
|
||||
const turn: PairedTurnRecord = {
|
||||
turn_id: 'turn-1',
|
||||
task_id: task.id,
|
||||
task_updated_at: task.updated_at,
|
||||
role: 'reviewer',
|
||||
intent_kind: 'reviewer-turn',
|
||||
state: 'queued',
|
||||
executor_service_id: null,
|
||||
executor_agent_type: null,
|
||||
attempt_no: 0,
|
||||
created_at: '2026-04-26T05:19:00.000Z',
|
||||
updated_at: '2026-04-26T05:31:00.000Z',
|
||||
completed_at: null,
|
||||
last_error: null,
|
||||
};
|
||||
const attempt: PairedTurnAttemptRecord = {
|
||||
attempt_id: 'turn-1:attempt:2',
|
||||
parent_attempt_id: null,
|
||||
parent_handoff_id: null,
|
||||
continuation_handoff_id: null,
|
||||
turn_id: 'turn-1',
|
||||
task_id: task.id,
|
||||
task_updated_at: task.updated_at,
|
||||
role: 'reviewer',
|
||||
intent_kind: 'reviewer-turn',
|
||||
state: 'running',
|
||||
executor_service_id: 'claude-reviewer',
|
||||
executor_agent_type: 'claude-code',
|
||||
active_run_id: 'run-reviewer-1',
|
||||
attempt_no: 2,
|
||||
created_at: '2026-04-26T05:20:00.000Z',
|
||||
updated_at: '2026-04-26T05:31:00.000Z',
|
||||
completed_at: null,
|
||||
last_error: 'OPENAI_API_KEY=plain-secret-value',
|
||||
};
|
||||
const outputs: PairedTurnOutput[] = [
|
||||
{
|
||||
id: 2,
|
||||
task_id: task.id,
|
||||
turn_number: 2,
|
||||
role: 'reviewer',
|
||||
output_text: `reviewer output with BOT_TOKEN=plain-secret-value ${'x'.repeat(1900)} ${longOutputTail}`,
|
||||
verdict: null,
|
||||
created_at: '2026-04-26T05:30:00.000Z',
|
||||
},
|
||||
];
|
||||
const messages: NewMessage[] = [
|
||||
{
|
||||
id: 'msg-1',
|
||||
chat_jid: 'dc:ops',
|
||||
sender: 'user-1',
|
||||
sender_name: '눈쟁이',
|
||||
content: `latest message ${'y'.repeat(950)} ${longMessageTail}`,
|
||||
timestamp: '2026-04-26T05:29:00.000Z',
|
||||
is_from_me: false,
|
||||
is_bot_message: false,
|
||||
message_source_kind: 'human',
|
||||
},
|
||||
];
|
||||
|
||||
const activity = buildWebDashboardRoomActivity({
|
||||
serviceId: 'codex-main',
|
||||
entry: {
|
||||
jid: 'dc:ops',
|
||||
name: '#ops',
|
||||
folder: 'ops',
|
||||
agentType: 'codex',
|
||||
status: 'processing',
|
||||
elapsedMs: 15_000,
|
||||
pendingMessages: true,
|
||||
pendingTasks: 1,
|
||||
},
|
||||
pairedTask: task,
|
||||
turns: [turn],
|
||||
attempts: [attempt],
|
||||
outputs,
|
||||
messages,
|
||||
outputLimit: 1,
|
||||
});
|
||||
|
||||
expect(activity.pairedTask).toMatchObject({
|
||||
id: 'paired-room-1',
|
||||
roundTripCount: 3,
|
||||
currentTurn: {
|
||||
role: 'reviewer',
|
||||
state: 'running',
|
||||
attemptNo: 2,
|
||||
lastError: 'OPENAI_API_KEY=<redacted>',
|
||||
},
|
||||
outputs: [
|
||||
{
|
||||
turnNumber: 2,
|
||||
role: 'reviewer',
|
||||
outputText: expect.stringMatching(
|
||||
new RegExp(`BOT_TOKEN=<redacted>[\\s\\S]*${longOutputTail}`),
|
||||
),
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(activity.messages).toMatchObject([
|
||||
{
|
||||
senderName: '눈쟁이',
|
||||
content: expect.stringContaining(longMessageTail),
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it('uses delivered work items as the visible outbound source when supplied', () => {
|
||||
const task = makePairedTask({
|
||||
id: 'paired-canonical-outbound',
|
||||
chat_jid: 'dc:ops',
|
||||
status: 'in_review',
|
||||
updated_at: '2026-04-26T05:30:00.000Z',
|
||||
});
|
||||
const output: PairedTurnOutput = {
|
||||
id: 22,
|
||||
task_id: task.id,
|
||||
turn_number: 2,
|
||||
role: 'owner',
|
||||
output_text: 'TASK_DONE\n\nexecution artifact only',
|
||||
verdict: 'task_done',
|
||||
created_at: '2026-04-26T05:30:00.000Z',
|
||||
};
|
||||
|
||||
const activity = buildWebDashboardRoomActivity({
|
||||
serviceId: 'codex-main',
|
||||
entry: {
|
||||
jid: 'dc:ops',
|
||||
name: '#ops',
|
||||
folder: 'ops',
|
||||
agentType: 'codex',
|
||||
status: 'inactive',
|
||||
elapsedMs: null,
|
||||
pendingMessages: false,
|
||||
pendingTasks: 0,
|
||||
},
|
||||
pairedTask: task,
|
||||
turns: [],
|
||||
attempts: [],
|
||||
outputs: [output],
|
||||
outboundItems: [makeDeliveredWorkItem()],
|
||||
messages: [
|
||||
{
|
||||
id: 'discord-msg-100',
|
||||
chat_jid: 'dc:ops',
|
||||
sender: 'bot-owner',
|
||||
sender_name: '오너',
|
||||
content: 'TASK_DONE\n\ncanonical delivered output',
|
||||
timestamp: '2026-04-26T05:30:10.000Z',
|
||||
is_from_me: true,
|
||||
is_bot_message: true,
|
||||
message_source_kind: 'bot',
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(activity.pairedTask?.outputs).toEqual([]);
|
||||
expect(activity.messages).toEqual([
|
||||
expect.objectContaining({
|
||||
id: 'work:100',
|
||||
senderName: 'owner',
|
||||
content: 'TASK_DONE\n\ncanonical delivered output',
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
it('hides legacy delivered work items without discord delivery evidence', () => {
|
||||
const activity = buildWebDashboardRoomActivity({
|
||||
serviceId: 'codex-main',
|
||||
entry: {
|
||||
jid: 'dc:ops',
|
||||
name: '#ops',
|
||||
folder: 'ops',
|
||||
agentType: 'codex',
|
||||
status: 'inactive',
|
||||
elapsedMs: null,
|
||||
pendingMessages: false,
|
||||
pendingTasks: 0,
|
||||
},
|
||||
pairedTask: null,
|
||||
turns: [],
|
||||
attempts: [],
|
||||
outputs: [],
|
||||
outboundItems: [
|
||||
makeDeliveredWorkItem({
|
||||
id: 103,
|
||||
delivery_role: null,
|
||||
delivery_message_id: null,
|
||||
result_payload: '서비스 재시작으로 이전 작업이 중단됐습니다.',
|
||||
}),
|
||||
],
|
||||
messages: [],
|
||||
});
|
||||
|
||||
expect(activity.messages).toEqual([]);
|
||||
});
|
||||
|
||||
it('keeps legacy delivered work items when a discord echo exists', () => {
|
||||
const activity = buildWebDashboardRoomActivity({
|
||||
serviceId: 'codex-main',
|
||||
entry: {
|
||||
jid: 'dc:ops',
|
||||
name: '#ops',
|
||||
folder: 'ops',
|
||||
agentType: 'codex',
|
||||
status: 'inactive',
|
||||
elapsedMs: null,
|
||||
pendingMessages: false,
|
||||
pendingTasks: 0,
|
||||
},
|
||||
pairedTask: null,
|
||||
turns: [],
|
||||
attempts: [],
|
||||
outputs: [],
|
||||
outboundItems: [
|
||||
makeDeliveredWorkItem({
|
||||
id: 104,
|
||||
delivery_message_id: null,
|
||||
result_payload: 'TASK_DONE\n\nlegacy delivered output',
|
||||
}),
|
||||
],
|
||||
messages: [
|
||||
{
|
||||
id: 'discord-legacy-echo',
|
||||
chat_jid: 'dc:ops',
|
||||
sender: 'bot-owner',
|
||||
sender_name: '오너',
|
||||
content: 'TASK_DONE\n\nlegacy delivered output',
|
||||
timestamp: '2026-04-26T05:30:11.000Z',
|
||||
is_from_me: true,
|
||||
is_bot_message: true,
|
||||
message_source_kind: 'bot',
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(activity.messages).toEqual([
|
||||
expect.objectContaining({
|
||||
id: 'work:104',
|
||||
content: 'TASK_DONE\n\nlegacy delivered output',
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
it('merges canonical outbound and recent messages in chronological order', () => {
|
||||
const activity = buildWebDashboardRoomActivity({
|
||||
serviceId: 'codex-main',
|
||||
entry: {
|
||||
jid: 'dc:ops',
|
||||
name: '#ops',
|
||||
folder: 'ops',
|
||||
agentType: 'codex',
|
||||
status: 'inactive',
|
||||
elapsedMs: null,
|
||||
pendingMessages: false,
|
||||
pendingTasks: 0,
|
||||
},
|
||||
pairedTask: null,
|
||||
turns: [],
|
||||
attempts: [],
|
||||
outputs: [],
|
||||
outboundItems: [
|
||||
makeDeliveredWorkItem({
|
||||
id: 101,
|
||||
delivered_at: '2026-04-26T05:30:00.000Z',
|
||||
result_payload: 'owner canonical',
|
||||
}),
|
||||
],
|
||||
messages: [
|
||||
{
|
||||
id: 'human-after',
|
||||
chat_jid: 'dc:ops',
|
||||
sender: 'user-1',
|
||||
sender_name: '눈쟁이',
|
||||
content: 'human after',
|
||||
timestamp: '2026-04-26T05:31:00.000Z',
|
||||
is_from_me: false,
|
||||
is_bot_message: false,
|
||||
message_source_kind: 'human',
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(activity.messages.map((message) => message.id)).toEqual([
|
||||
'work:101',
|
||||
'human-after',
|
||||
]);
|
||||
});
|
||||
|
||||
it('uses canonical turn progress without exposing status messages as recent chat', () => {
|
||||
const task = makePairedTask({
|
||||
id: 'paired-room-progress',
|
||||
chat_jid: 'dc:ops',
|
||||
status: 'active',
|
||||
updated_at: '2026-04-26T06:10:00.000Z',
|
||||
});
|
||||
const turn: PairedTurnRecord = {
|
||||
turn_id: 'turn-progress',
|
||||
task_id: task.id,
|
||||
task_updated_at: task.updated_at,
|
||||
role: 'owner',
|
||||
intent_kind: 'owner-turn',
|
||||
state: 'running',
|
||||
executor_service_id: 'codex-main',
|
||||
executor_agent_type: 'codex',
|
||||
attempt_no: 1,
|
||||
created_at: '2026-04-26T06:00:00.000Z',
|
||||
updated_at: '2026-04-26T06:10:00.000Z',
|
||||
completed_at: null,
|
||||
last_error: null,
|
||||
progress_text: 'building mobile parity',
|
||||
progress_updated_at: '2026-04-26T06:07:00.000Z',
|
||||
};
|
||||
const statusPrefix = '';
|
||||
const messages: NewMessage[] = [
|
||||
{
|
||||
id: 'msg-latest',
|
||||
chat_jid: 'dc:ops',
|
||||
sender: 'user-1',
|
||||
sender_name: '눈쟁이',
|
||||
content: 'recent human message',
|
||||
timestamp: '2026-04-26T06:09:00.000Z',
|
||||
is_from_me: false,
|
||||
is_bot_message: false,
|
||||
message_source_kind: 'human',
|
||||
},
|
||||
{
|
||||
id: 'msg-status-progress',
|
||||
chat_jid: 'dc:ops',
|
||||
sender: 'bot-1',
|
||||
sender_name: '오너',
|
||||
content: `${statusPrefix}status noise that belongs to display only\n\n12s`,
|
||||
timestamp: '2026-04-26T06:08:00.000Z',
|
||||
is_from_me: true,
|
||||
is_bot_message: true,
|
||||
message_source_kind: 'bot',
|
||||
},
|
||||
];
|
||||
|
||||
const activity = buildWebDashboardRoomActivity({
|
||||
serviceId: 'codex-main',
|
||||
entry: {
|
||||
jid: 'dc:ops',
|
||||
name: '#ops',
|
||||
folder: 'ops',
|
||||
agentType: 'codex',
|
||||
status: 'processing',
|
||||
elapsedMs: 20_000,
|
||||
pendingMessages: false,
|
||||
pendingTasks: 0,
|
||||
},
|
||||
pairedTask: task,
|
||||
turns: [turn],
|
||||
attempts: [],
|
||||
outputs: [],
|
||||
messages,
|
||||
});
|
||||
|
||||
expect(activity.pairedTask?.currentTurn).toMatchObject({
|
||||
progressText: 'building mobile parity',
|
||||
progressUpdatedAt: '2026-04-26T06:07:00.000Z',
|
||||
});
|
||||
expect(activity.messages).toEqual([
|
||||
expect.objectContaining({
|
||||
senderName: '눈쟁이',
|
||||
content: 'recent human message',
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
it('keeps a progress-updated turn current when a newer empty reservation exists', () => {
|
||||
const task = makePairedTask({
|
||||
id: 'paired-room-progress-race',
|
||||
chat_jid: 'dc:ops',
|
||||
status: 'active',
|
||||
updated_at: '2026-04-26T06:10:00.000Z',
|
||||
});
|
||||
const activeProgressTurn: PairedTurnRecord = {
|
||||
turn_id: 'turn-progress-active',
|
||||
task_id: task.id,
|
||||
task_updated_at: task.updated_at,
|
||||
role: 'owner',
|
||||
intent_kind: 'owner-follow-up',
|
||||
state: 'running',
|
||||
executor_service_id: 'codex-main',
|
||||
executor_agent_type: 'codex',
|
||||
attempt_no: 1,
|
||||
created_at: '2026-04-26T06:00:00.000Z',
|
||||
updated_at: '2026-04-26T06:10:00.000Z',
|
||||
completed_at: null,
|
||||
last_error: null,
|
||||
progress_text: 'checking dashboard parity',
|
||||
progress_updated_at: '2026-04-26T06:12:00.000Z',
|
||||
};
|
||||
const queuedEmptyTurn: PairedTurnRecord = {
|
||||
...activeProgressTurn,
|
||||
turn_id: 'turn-queued-empty',
|
||||
state: 'queued',
|
||||
executor_service_id: null,
|
||||
executor_agent_type: null,
|
||||
attempt_no: 0,
|
||||
created_at: '2026-04-26T06:11:00.000Z',
|
||||
updated_at: '2026-04-26T06:11:00.000Z',
|
||||
progress_text: null,
|
||||
progress_updated_at: null,
|
||||
};
|
||||
|
||||
const activity = buildWebDashboardRoomActivity({
|
||||
serviceId: 'codex-main',
|
||||
entry: {
|
||||
jid: 'dc:ops',
|
||||
name: '#ops',
|
||||
folder: 'ops',
|
||||
agentType: 'codex',
|
||||
status: 'processing',
|
||||
elapsedMs: 20_000,
|
||||
pendingMessages: false,
|
||||
pendingTasks: 0,
|
||||
},
|
||||
pairedTask: task,
|
||||
turns: [activeProgressTurn, queuedEmptyTurn],
|
||||
attempts: [],
|
||||
outputs: [],
|
||||
messages: [],
|
||||
});
|
||||
|
||||
expect(activity.pairedTask?.currentTurn).toMatchObject({
|
||||
turnId: 'turn-progress-active',
|
||||
progressText: 'checking dashboard parity',
|
||||
progressUpdatedAt: '2026-04-26T06:12:00.000Z',
|
||||
});
|
||||
});
|
||||
|
||||
it('does not show active turn placeholders when canonical progress is absent', () => {
|
||||
const task = makePairedTask({
|
||||
id: 'paired-progress-internal',
|
||||
chat_jid: 'dc:ops',
|
||||
status: 'active',
|
||||
updated_at: '2026-04-26T06:10:00.000Z',
|
||||
});
|
||||
const turn: PairedTurnRecord = {
|
||||
turn_id: 'turn-progress-internal',
|
||||
task_id: task.id,
|
||||
task_updated_at: task.updated_at,
|
||||
role: 'owner',
|
||||
intent_kind: 'owner-turn',
|
||||
state: 'running',
|
||||
executor_service_id: 'codex-main',
|
||||
executor_agent_type: 'codex',
|
||||
attempt_no: 1,
|
||||
created_at: '2026-04-26T06:00:00.000Z',
|
||||
updated_at: '2026-04-26T06:10:00.000Z',
|
||||
completed_at: null,
|
||||
last_error: null,
|
||||
progress_text: null,
|
||||
progress_updated_at: null,
|
||||
};
|
||||
|
||||
const activity = buildWebDashboardRoomActivity({
|
||||
serviceId: 'codex-main',
|
||||
entry: {
|
||||
jid: 'dc:ops',
|
||||
name: '#ops',
|
||||
folder: 'ops',
|
||||
agentType: 'codex',
|
||||
status: 'processing',
|
||||
elapsedMs: 20_000,
|
||||
pendingMessages: false,
|
||||
pendingTasks: 0,
|
||||
},
|
||||
pairedTask: task,
|
||||
turns: [turn],
|
||||
attempts: [],
|
||||
outputs: [],
|
||||
messages: [],
|
||||
});
|
||||
|
||||
expect(activity.pairedTask?.currentTurn).toMatchObject({
|
||||
progressText: null,
|
||||
progressUpdatedAt: null,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('web dashboard inbox data', () => {
|
||||
it('builds user-action inbox items from merge-ready paired tasks only', () => {
|
||||
const snapshots: StatusSnapshot[] = [
|
||||
{
|
||||
serviceId: 'codex-main',
|
||||
agentType: 'codex',
|
||||
assistantName: 'Codex',
|
||||
updatedAt: '2026-04-26T05:00:00.000Z',
|
||||
entries: [
|
||||
{
|
||||
jid: 'dc:ops',
|
||||
name: '#ops',
|
||||
folder: 'ops',
|
||||
agentType: 'codex',
|
||||
status: 'waiting',
|
||||
elapsedMs: 1000,
|
||||
pendingMessages: true,
|
||||
pendingTasks: 0,
|
||||
},
|
||||
{
|
||||
jid: 'dc:idle',
|
||||
name: '#idle',
|
||||
folder: 'idle',
|
||||
agentType: 'codex',
|
||||
status: 'inactive',
|
||||
elapsedMs: null,
|
||||
pendingMessages: false,
|
||||
pendingTasks: 0,
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
const overview = buildWebDashboardOverview({
|
||||
now: '2026-04-26T05:10:00.000Z',
|
||||
snapshots,
|
||||
pairedTasks: [
|
||||
makePairedTask({
|
||||
id: 'review-1',
|
||||
status: 'review_ready',
|
||||
review_requested_at: '2026-04-26T05:03:00.000Z',
|
||||
}),
|
||||
makePairedTask({
|
||||
chat_jid: 'dc:ops',
|
||||
group_folder: 'ops',
|
||||
id: 'merge-1',
|
||||
status: 'merge_ready',
|
||||
title: 'Ready to merge',
|
||||
updated_at: '2026-04-26T05:04:00.000Z',
|
||||
}),
|
||||
makePairedTask({
|
||||
id: 'done-1',
|
||||
status: 'completed',
|
||||
}),
|
||||
],
|
||||
tasks: [
|
||||
makeTask({
|
||||
id: 'ci-1',
|
||||
prompt:
|
||||
'[BACKGROUND CI WATCH]\nWatch target:\nPR #21\n\nCheck instructions:\nwatch',
|
||||
last_run: '2026-04-26T05:05:00.000Z',
|
||||
last_result: 'Error: BOT_TOKEN=plain-secret-value failed',
|
||||
status: 'paused',
|
||||
}),
|
||||
makeTask({
|
||||
id: 'ci-2',
|
||||
prompt:
|
||||
'[BACKGROUND CI WATCH]\nWatch target:\nPR #22\n\nCheck instructions:\nwatch',
|
||||
last_run: '2026-04-26T05:07:00.000Z',
|
||||
last_result: 'Error: BOT_TOKEN=plain-secret-value failed',
|
||||
status: 'active',
|
||||
}),
|
||||
makeTask({
|
||||
id: 'cron-1',
|
||||
prompt: 'regular cron',
|
||||
last_run: '2026-04-26T05:06:00.000Z',
|
||||
last_result: 'Error: non-watch task failed',
|
||||
}),
|
||||
],
|
||||
});
|
||||
|
||||
expect(overview.inbox.map((item) => item.kind)).toEqual(['approval']);
|
||||
expect(overview.inbox).toContainEqual(
|
||||
expect.objectContaining({
|
||||
id: 'paired:merge-1:merge_ready',
|
||||
kind: 'approval',
|
||||
severity: 'warn',
|
||||
roomJid: 'dc:ops',
|
||||
taskId: 'merge-1',
|
||||
serviceId: 'codex-main',
|
||||
occurredAt: '2026-04-26T05:04:00.000Z',
|
||||
createdAt: '2026-04-26T05:10:00.000Z',
|
||||
}),
|
||||
);
|
||||
expect(overview.inbox.some((item) => item.kind === 'pending-room')).toBe(
|
||||
false,
|
||||
);
|
||||
expect(
|
||||
overview.inbox.some((item) => item.kind === 'reviewer-request'),
|
||||
).toBe(false);
|
||||
expect(overview.inbox.some((item) => item.kind === 'arbiter-request')).toBe(
|
||||
false,
|
||||
);
|
||||
expect(overview.inbox.some((item) => item.kind === 'ci-failure')).toBe(
|
||||
false,
|
||||
);
|
||||
expect(overview.inbox.some((item) => item.taskId === 'ci-1')).toBe(false);
|
||||
expect(overview.inbox.some((item) => item.taskId === 'ci-2')).toBe(false);
|
||||
expect(overview.inbox.some((item) => item.taskId === 'cron-1')).toBe(false);
|
||||
expect(overview.inbox.some((item) => item.taskId === 'done-1')).toBe(false);
|
||||
expect(overview.tasks.watchers).toEqual({
|
||||
active: 1,
|
||||
paused: 1,
|
||||
completed: 0,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,809 +0,0 @@
|
||||
import {
|
||||
extractImageTagPaths,
|
||||
normalizeAgentOutput,
|
||||
} from './agent-protocol.js';
|
||||
import { isWatchCiTask } from './task-watch-status.js';
|
||||
import type {
|
||||
PairedTurnAttemptRecord,
|
||||
PairedTurnRecord,
|
||||
WorkItem,
|
||||
} from './db.js';
|
||||
import type { StatusSnapshot, UsageRowSnapshot } from './status-dashboard.js';
|
||||
import type {
|
||||
NewMessage,
|
||||
OutboundAttachment,
|
||||
PairedTask,
|
||||
PairedTurnOutput,
|
||||
ScheduledTask,
|
||||
} from './types.js';
|
||||
|
||||
export interface SanitizedScheduledTask {
|
||||
id: string;
|
||||
groupFolder: string;
|
||||
chatJid: string;
|
||||
agentType: ScheduledTask['agent_type'];
|
||||
ciProvider: ScheduledTask['ci_provider'];
|
||||
ciMetadata: ScheduledTask['ci_metadata'];
|
||||
scheduleType: ScheduledTask['schedule_type'];
|
||||
scheduleValue: string;
|
||||
contextMode: ScheduledTask['context_mode'];
|
||||
nextRun: string | null;
|
||||
lastRun: string | null;
|
||||
lastResult: string | null;
|
||||
status: ScheduledTask['status'];
|
||||
suspendedUntil: string | null;
|
||||
createdAt: string;
|
||||
promptPreview: string;
|
||||
promptLength: number;
|
||||
isWatcher: boolean;
|
||||
}
|
||||
|
||||
export interface WebDashboardOverview {
|
||||
generatedAt: string;
|
||||
services: Array<{
|
||||
serviceId: string;
|
||||
assistantName: string;
|
||||
agentType: StatusSnapshot['agentType'];
|
||||
updatedAt: string;
|
||||
totalRooms: number;
|
||||
activeRooms: number;
|
||||
}>;
|
||||
rooms: {
|
||||
total: number;
|
||||
active: number;
|
||||
waiting: number;
|
||||
inactive: number;
|
||||
};
|
||||
tasks: {
|
||||
total: number;
|
||||
active: number;
|
||||
paused: number;
|
||||
completed: number;
|
||||
watchers: {
|
||||
active: number;
|
||||
paused: number;
|
||||
completed: number;
|
||||
};
|
||||
};
|
||||
usage: {
|
||||
rows: UsageRowSnapshot[];
|
||||
fetchedAt: string | null;
|
||||
};
|
||||
inbox: InboxItem[];
|
||||
}
|
||||
|
||||
export interface WebDashboardRoomMessage {
|
||||
id: string;
|
||||
sender: string;
|
||||
senderName: string;
|
||||
content: string;
|
||||
attachments: OutboundAttachment[];
|
||||
timestamp: string;
|
||||
isFromMe: boolean;
|
||||
isBotMessage: boolean;
|
||||
sourceKind: NonNullable<NewMessage['message_source_kind']>;
|
||||
}
|
||||
|
||||
export interface WebDashboardRoomTurn {
|
||||
turnId: string;
|
||||
role: PairedTurnRecord['role'];
|
||||
intentKind: PairedTurnRecord['intent_kind'];
|
||||
state: PairedTurnRecord['state'];
|
||||
attemptNo: number;
|
||||
executorServiceId: string | null;
|
||||
executorAgentType: PairedTurnRecord['executor_agent_type'];
|
||||
activeRunId: string | null;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
completedAt: string | null;
|
||||
lastError: string | null;
|
||||
progressText: string | null;
|
||||
progressUpdatedAt: string | null;
|
||||
}
|
||||
|
||||
export interface WebDashboardRoomTurnOutput {
|
||||
id: number;
|
||||
turnNumber: number;
|
||||
role: PairedTurnOutput['role'];
|
||||
verdict: PairedTurnOutput['verdict'] | null;
|
||||
createdAt: string;
|
||||
outputText: string;
|
||||
attachments: OutboundAttachment[];
|
||||
}
|
||||
|
||||
export interface WebDashboardRoomActivity {
|
||||
serviceId: string;
|
||||
jid: string;
|
||||
name: string;
|
||||
folder: string;
|
||||
agentType: StatusSnapshot['agentType'];
|
||||
status: StatusSnapshot['entries'][number]['status'];
|
||||
elapsedMs: number | null;
|
||||
pendingMessages: boolean;
|
||||
pendingTasks: number;
|
||||
messages: WebDashboardRoomMessage[];
|
||||
pairedTask: {
|
||||
id: string;
|
||||
title: string | null;
|
||||
status: PairedTask['status'];
|
||||
roundTripCount: number;
|
||||
updatedAt: string;
|
||||
currentTurn: WebDashboardRoomTurn | null;
|
||||
outputs: WebDashboardRoomTurnOutput[];
|
||||
} | null;
|
||||
}
|
||||
|
||||
export type InboxItemKind =
|
||||
| 'pending-room'
|
||||
| 'reviewer-request'
|
||||
| 'approval'
|
||||
| 'arbiter-request'
|
||||
| 'ci-failure'
|
||||
| 'mention';
|
||||
|
||||
export type InboxItemSeverity = 'info' | 'warn' | 'error';
|
||||
|
||||
export interface InboxItem {
|
||||
id: string;
|
||||
groupKey: string;
|
||||
kind: InboxItemKind;
|
||||
severity: InboxItemSeverity;
|
||||
title: string;
|
||||
summary: string;
|
||||
occurredAt: string;
|
||||
lastOccurredAt: string;
|
||||
createdAt: string;
|
||||
occurrences: number;
|
||||
source: 'status-snapshot' | 'paired-task' | 'scheduled-task';
|
||||
roomJid?: string;
|
||||
roomName?: string;
|
||||
groupFolder?: string;
|
||||
serviceId?: string;
|
||||
taskId?: string;
|
||||
taskStatus?: string;
|
||||
}
|
||||
|
||||
const SECRET_ASSIGNMENT_RE =
|
||||
/\b([A-Z0-9_]*(?:TOKEN|SECRET|PASSWORD|API_KEY|AUTH|PRIVATE_KEY)[A-Z0-9_]*)\s*=\s*([^\s"'`]+)/gi;
|
||||
const SECRET_VALUE_RE =
|
||||
/\b(?:sk-[A-Za-z0-9_-]{12,}|gh[pousr]_[A-Za-z0-9_]{12,}|xox[baprs]-[A-Za-z0-9-]{12,}|eyJ[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{10,})\b/g;
|
||||
|
||||
function redactSensitiveText(value: string): string {
|
||||
return value
|
||||
.replace(SECRET_ASSIGNMENT_RE, '$1=<redacted>')
|
||||
.replace(SECRET_VALUE_RE, '<redacted-token>');
|
||||
}
|
||||
|
||||
function truncateText(value: string, maxLength = 120): string {
|
||||
if (value.length <= maxLength) return value;
|
||||
return `${value.slice(0, maxLength)}...`;
|
||||
}
|
||||
|
||||
function buildPromptPreview(prompt: string): string {
|
||||
return truncateText(redactSensitiveText(prompt).replace(/\s+/g, ' ').trim());
|
||||
}
|
||||
|
||||
function buildRoomBody(value: string): string {
|
||||
return redactSensitiveText(value).trim();
|
||||
}
|
||||
|
||||
function decodeCommonHtmlEntities(value: string): string {
|
||||
return value
|
||||
.replace(/"|"|"/gi, '"')
|
||||
.replace(/'|'|'/gi, "'")
|
||||
.replace(/<|<|</gi, '<')
|
||||
.replace(/>|>|>/gi, '>')
|
||||
.replace(/&|&|&/gi, '&');
|
||||
}
|
||||
|
||||
function hasStructuredOutputHint(value: string): boolean {
|
||||
return value.includes('"ejclaw"') || /"ejclaw"/i.test(value);
|
||||
}
|
||||
|
||||
function imagePathsToAttachments(paths: string[]): OutboundAttachment[] {
|
||||
return paths.map((filePath) => ({
|
||||
path: filePath,
|
||||
name: filePath.split(/[\\/]/).at(-1) || undefined,
|
||||
}));
|
||||
}
|
||||
|
||||
function splitLegacyImageTags(
|
||||
text: string,
|
||||
attachments: OutboundAttachment[] = [],
|
||||
): { text: string; attachments: OutboundAttachment[] } {
|
||||
const extracted = extractImageTagPaths(text);
|
||||
if (extracted.imagePaths.length === 0) {
|
||||
return { text, attachments };
|
||||
}
|
||||
return {
|
||||
text: extracted.cleanText,
|
||||
attachments: [
|
||||
...attachments,
|
||||
...imagePathsToAttachments(extracted.imagePaths),
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeStructuredVisibleContent(value: string): {
|
||||
text: string | null;
|
||||
attachments: OutboundAttachment[];
|
||||
} {
|
||||
const candidates = hasStructuredOutputHint(value)
|
||||
? [value, decodeCommonHtmlEntities(value)]
|
||||
: [value];
|
||||
for (const candidate of candidates) {
|
||||
const normalized = normalizeAgentOutput(candidate);
|
||||
if (normalized.output?.visibility === 'silent') {
|
||||
return { text: null, attachments: [] };
|
||||
}
|
||||
if (
|
||||
normalized.output?.visibility === 'public' &&
|
||||
(normalized.output.text !== candidate ||
|
||||
(normalized.output.attachments?.length ?? 0) > 0)
|
||||
) {
|
||||
return splitLegacyImageTags(
|
||||
normalized.output.text,
|
||||
normalized.output.attachments ?? [],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return splitLegacyImageTags(value);
|
||||
}
|
||||
|
||||
function collectUsageRows(snapshots: StatusSnapshot[]): UsageRowSnapshot[] {
|
||||
const rows: UsageRowSnapshot[] = [];
|
||||
const seen = new Set<string>();
|
||||
const sortedSnapshots = Array.from(snapshots).sort((a, b) =>
|
||||
(b.usageRowsFetchedAt ?? b.updatedAt).localeCompare(
|
||||
a.usageRowsFetchedAt ?? a.updatedAt,
|
||||
),
|
||||
);
|
||||
|
||||
for (const snapshot of sortedSnapshots) {
|
||||
for (const row of snapshot.usageRows ?? []) {
|
||||
if (seen.has(row.name)) continue;
|
||||
seen.add(row.name);
|
||||
rows.push(row);
|
||||
}
|
||||
}
|
||||
|
||||
return rows;
|
||||
}
|
||||
|
||||
function pairedTaskInboxKind(
|
||||
status: PairedTask['status'],
|
||||
): InboxItemKind | null {
|
||||
if (status === 'merge_ready') return 'approval';
|
||||
return null;
|
||||
}
|
||||
|
||||
function collectInboxItems(args: {
|
||||
pairedTasks: PairedTask[];
|
||||
createdAt: string;
|
||||
}): InboxItem[] {
|
||||
const items: InboxItem[] = [];
|
||||
|
||||
for (const task of args.pairedTasks) {
|
||||
const kind = pairedTaskInboxKind(task.status);
|
||||
if (!kind) continue;
|
||||
|
||||
items.push({
|
||||
id: `paired:${task.id}:${task.status}`,
|
||||
groupKey: `paired:${task.id}:${task.status}`,
|
||||
kind,
|
||||
severity: 'warn',
|
||||
title: task.title || task.group_folder,
|
||||
summary: task.status,
|
||||
occurredAt: task.updated_at,
|
||||
lastOccurredAt: task.updated_at,
|
||||
createdAt: args.createdAt,
|
||||
occurrences: 1,
|
||||
source: 'paired-task',
|
||||
roomJid: task.chat_jid,
|
||||
groupFolder: task.group_folder,
|
||||
serviceId: task.owner_service_id,
|
||||
taskId: task.id,
|
||||
taskStatus: task.status,
|
||||
});
|
||||
}
|
||||
|
||||
const severityRank: Record<InboxItemSeverity, number> = {
|
||||
error: 0,
|
||||
warn: 1,
|
||||
info: 2,
|
||||
};
|
||||
|
||||
const groupedItems = new Map<string, InboxItem>();
|
||||
for (const item of items) {
|
||||
const existing = groupedItems.get(item.groupKey);
|
||||
if (!existing) {
|
||||
groupedItems.set(item.groupKey, item);
|
||||
continue;
|
||||
}
|
||||
|
||||
const occurrences = existing.occurrences + item.occurrences;
|
||||
const severity =
|
||||
severityRank[item.severity] < severityRank[existing.severity]
|
||||
? item.severity
|
||||
: existing.severity;
|
||||
const latest =
|
||||
item.lastOccurredAt.localeCompare(existing.lastOccurredAt) > 0
|
||||
? item
|
||||
: existing;
|
||||
|
||||
groupedItems.set(item.groupKey, {
|
||||
...latest,
|
||||
severity,
|
||||
occurrences,
|
||||
lastOccurredAt:
|
||||
item.lastOccurredAt.localeCompare(existing.lastOccurredAt) > 0
|
||||
? item.lastOccurredAt
|
||||
: existing.lastOccurredAt,
|
||||
});
|
||||
}
|
||||
|
||||
return Array.from(groupedItems.values())
|
||||
.sort((a, b) => {
|
||||
const severityDelta = severityRank[a.severity] - severityRank[b.severity];
|
||||
if (severityDelta !== 0) return severityDelta;
|
||||
return b.lastOccurredAt.localeCompare(a.lastOccurredAt);
|
||||
})
|
||||
.slice(0, 50);
|
||||
}
|
||||
|
||||
export function sanitizeScheduledTask(
|
||||
task: ScheduledTask,
|
||||
): SanitizedScheduledTask {
|
||||
return {
|
||||
id: task.id,
|
||||
groupFolder: task.group_folder,
|
||||
chatJid: task.chat_jid,
|
||||
agentType: task.agent_type,
|
||||
ciProvider: task.ci_provider ?? null,
|
||||
ciMetadata: task.ci_metadata ?? null,
|
||||
scheduleType: task.schedule_type,
|
||||
scheduleValue: task.schedule_value,
|
||||
contextMode: task.context_mode,
|
||||
nextRun: task.next_run,
|
||||
lastRun: task.last_run,
|
||||
lastResult: task.last_result,
|
||||
status: task.status,
|
||||
suspendedUntil: task.suspended_until ?? null,
|
||||
createdAt: task.created_at,
|
||||
promptPreview: buildPromptPreview(task.prompt),
|
||||
promptLength: task.prompt.length,
|
||||
isWatcher: isWatchCiTask(task),
|
||||
};
|
||||
}
|
||||
|
||||
function sanitizeRoomMessage(
|
||||
message: NewMessage,
|
||||
): WebDashboardRoomMessage | null {
|
||||
const normalized = normalizeStructuredVisibleContent(message.content ?? '');
|
||||
if (normalized.text === null) return null;
|
||||
|
||||
return {
|
||||
id: message.id,
|
||||
sender: message.sender,
|
||||
senderName: message.sender_name || message.sender,
|
||||
content: buildRoomBody(normalized.text),
|
||||
attachments: normalized.attachments,
|
||||
timestamp: message.timestamp,
|
||||
isFromMe: !!message.is_from_me,
|
||||
isBotMessage: !!message.is_bot_message,
|
||||
sourceKind: message.message_source_kind ?? 'human',
|
||||
};
|
||||
}
|
||||
|
||||
function roleSenderName(role: WorkItem['delivery_role']): string {
|
||||
return role ?? 'system';
|
||||
}
|
||||
|
||||
function sanitizeCanonicalOutboundMessage(
|
||||
item: WorkItem,
|
||||
): WebDashboardRoomMessage | null {
|
||||
if (item.status !== 'delivered') return null;
|
||||
const normalized = normalizeStructuredVisibleContent(item.result_payload);
|
||||
if (normalized.text === null) return null;
|
||||
|
||||
return {
|
||||
id: `work:${item.id}`,
|
||||
sender: `work-item:${item.delivery_role ?? 'system'}`,
|
||||
senderName: roleSenderName(item.delivery_role ?? null),
|
||||
content: buildRoomBody(normalized.text),
|
||||
attachments:
|
||||
normalized.attachments.length > 0
|
||||
? normalized.attachments
|
||||
: (item.attachments ?? []),
|
||||
timestamp: item.delivered_at ?? item.updated_at,
|
||||
isFromMe: false,
|
||||
isBotMessage: true,
|
||||
sourceKind: 'bot',
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeForOutboundDedupe(value: string): string {
|
||||
return value.replace(/\s+/g, ' ').trim();
|
||||
}
|
||||
|
||||
function senderMatchesCanonicalOutbound(
|
||||
messageSender: string,
|
||||
outboundSender: string,
|
||||
): boolean {
|
||||
const message = messageSender.trim().toLowerCase();
|
||||
const outbound = outboundSender.trim().toLowerCase();
|
||||
if (message === outbound) return true;
|
||||
const aliases: Record<string, string[]> = {
|
||||
owner: ['owner', '오너'],
|
||||
reviewer: ['reviewer', '리뷰어'],
|
||||
arbiter: ['arbiter', '중재자'],
|
||||
system: ['system', '시스템'],
|
||||
};
|
||||
return (aliases[outbound] ?? [outbound]).includes(message);
|
||||
}
|
||||
|
||||
function isDuplicateOfCanonicalOutbound(
|
||||
message: WebDashboardRoomMessage,
|
||||
canonical: WebDashboardRoomMessage[],
|
||||
): boolean {
|
||||
if (!message.isBotMessage) return false;
|
||||
const messageText = normalizeForOutboundDedupe(message.content);
|
||||
if (!messageText) return false;
|
||||
const messageTime = new Date(message.timestamp).getTime();
|
||||
|
||||
return canonical.some((outbound) => {
|
||||
if (
|
||||
!senderMatchesCanonicalOutbound(message.senderName, outbound.senderName)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
const outboundText = normalizeForOutboundDedupe(outbound.content);
|
||||
if (!outboundText) return false;
|
||||
const contentMatches =
|
||||
outboundText === messageText ||
|
||||
outboundText.startsWith(messageText) ||
|
||||
messageText.startsWith(outboundText) ||
|
||||
outboundText.includes(messageText) ||
|
||||
messageText.includes(outboundText);
|
||||
if (!contentMatches) return false;
|
||||
const outboundTime = new Date(outbound.timestamp).getTime();
|
||||
if (!Number.isFinite(messageTime) || !Number.isFinite(outboundTime)) {
|
||||
return true;
|
||||
}
|
||||
return Math.abs(outboundTime - messageTime) <= 120_000;
|
||||
});
|
||||
}
|
||||
|
||||
function hasDiscordEchoForCanonicalOutbound(
|
||||
canonical: WebDashboardRoomMessage,
|
||||
messages: WebDashboardRoomMessage[],
|
||||
): boolean {
|
||||
return messages.some((message) =>
|
||||
isDuplicateOfCanonicalOutbound(message, [canonical]),
|
||||
);
|
||||
}
|
||||
|
||||
function compareRoomMessagesByTimestamp(
|
||||
a: WebDashboardRoomMessage,
|
||||
b: WebDashboardRoomMessage,
|
||||
): number {
|
||||
const aTime = new Date(a.timestamp).getTime();
|
||||
const bTime = new Date(b.timestamp).getTime();
|
||||
if (!Number.isFinite(aTime) || !Number.isFinite(bTime)) return 0;
|
||||
return aTime - bTime;
|
||||
}
|
||||
|
||||
function getRoomTurnActivityTimestamp(turn: PairedTurnRecord): string {
|
||||
const progressUpdatedAt =
|
||||
turn.completed_at === null && turn.progress_text?.trim()
|
||||
? turn.progress_updated_at
|
||||
: null;
|
||||
if (progressUpdatedAt && progressUpdatedAt > turn.updated_at) {
|
||||
return progressUpdatedAt;
|
||||
}
|
||||
return turn.updated_at;
|
||||
}
|
||||
|
||||
const TASK_STATUS_PREFIX = '';
|
||||
|
||||
function isTaskStatusMessage(message: NewMessage): boolean {
|
||||
return (message.content ?? '').startsWith(TASK_STATUS_PREFIX);
|
||||
}
|
||||
|
||||
function sanitizeRoomTurn(
|
||||
turn: PairedTurnRecord,
|
||||
attempt: PairedTurnAttemptRecord | null,
|
||||
): WebDashboardRoomTurn {
|
||||
const role = attempt?.role ?? turn.role;
|
||||
const createdAt = attempt?.created_at ?? turn.created_at;
|
||||
const completedAt = attempt?.completed_at ?? turn.completed_at;
|
||||
const canonicalProgress =
|
||||
completedAt === null && turn.progress_text?.trim()
|
||||
? {
|
||||
progressText: buildRoomBody(turn.progress_text),
|
||||
progressUpdatedAt: turn.progress_updated_at ?? turn.updated_at,
|
||||
}
|
||||
: { progressText: null, progressUpdatedAt: null };
|
||||
|
||||
return {
|
||||
turnId: turn.turn_id,
|
||||
role,
|
||||
intentKind: attempt?.intent_kind ?? turn.intent_kind,
|
||||
state: attempt?.state ?? turn.state,
|
||||
attemptNo: attempt?.attempt_no ?? turn.attempt_no,
|
||||
executorServiceId: attempt?.executor_service_id ?? turn.executor_service_id,
|
||||
executorAgentType: attempt?.executor_agent_type ?? turn.executor_agent_type,
|
||||
activeRunId: attempt?.active_run_id ?? null,
|
||||
createdAt,
|
||||
updatedAt: attempt?.updated_at ?? turn.updated_at,
|
||||
completedAt,
|
||||
lastError:
|
||||
(attempt?.last_error ?? turn.last_error)
|
||||
? buildRoomBody(attempt?.last_error ?? turn.last_error ?? '')
|
||||
: null,
|
||||
progressText: canonicalProgress.progressText,
|
||||
progressUpdatedAt: canonicalProgress.progressUpdatedAt,
|
||||
};
|
||||
}
|
||||
|
||||
function sanitizeRoomTurnOutput(
|
||||
output: PairedTurnOutput,
|
||||
): WebDashboardRoomTurnOutput | null {
|
||||
const normalized = normalizeStructuredVisibleContent(output.output_text);
|
||||
if (normalized.text === null) return null;
|
||||
|
||||
return {
|
||||
id: output.id,
|
||||
turnNumber: output.turn_number,
|
||||
role: output.role,
|
||||
verdict: output.verdict ?? null,
|
||||
createdAt: output.created_at,
|
||||
outputText: buildRoomBody(normalized.text),
|
||||
attachments:
|
||||
normalized.attachments.length > 0
|
||||
? normalized.attachments
|
||||
: (output.attachments ?? []),
|
||||
};
|
||||
}
|
||||
|
||||
function getCurrentRoomTurn(
|
||||
turns: PairedTurnRecord[],
|
||||
): PairedTurnRecord | null {
|
||||
let currentTurn: PairedTurnRecord | null = null;
|
||||
let currentTimestamp = '';
|
||||
for (const turn of turns) {
|
||||
const timestamp = getRoomTurnActivityTimestamp(turn);
|
||||
if (!currentTurn || timestamp.localeCompare(currentTimestamp) > 0) {
|
||||
currentTurn = turn;
|
||||
currentTimestamp = timestamp;
|
||||
}
|
||||
}
|
||||
return currentTurn;
|
||||
}
|
||||
|
||||
function collectSanitizedRecentMessages(
|
||||
messages: NewMessage[],
|
||||
): WebDashboardRoomMessage[] {
|
||||
const sanitizedMessages: WebDashboardRoomMessage[] = [];
|
||||
for (const message of messages) {
|
||||
if (isTaskStatusMessage(message)) continue;
|
||||
const sanitized = sanitizeRoomMessage(message);
|
||||
if (sanitized) sanitizedMessages.push(sanitized);
|
||||
}
|
||||
return sanitizedMessages;
|
||||
}
|
||||
|
||||
function collectCanonicalOutboundMessages(
|
||||
outboundItems: WorkItem[] | undefined,
|
||||
sanitizedRecentMessages: WebDashboardRoomMessage[],
|
||||
): WebDashboardRoomMessage[] {
|
||||
const messages: WebDashboardRoomMessage[] = [];
|
||||
for (const item of outboundItems ?? []) {
|
||||
const message = sanitizeCanonicalOutboundMessage(item);
|
||||
if (!message) continue;
|
||||
if (
|
||||
item.delivery_message_id ||
|
||||
hasDiscordEchoForCanonicalOutbound(message, sanitizedRecentMessages)
|
||||
) {
|
||||
messages.push(message);
|
||||
}
|
||||
}
|
||||
return messages;
|
||||
}
|
||||
|
||||
function collectCanonicalDeliveryMessageIds(
|
||||
outboundItems: WorkItem[] | undefined,
|
||||
): Set<string> {
|
||||
const ids = new Set<string>();
|
||||
for (const item of outboundItems ?? []) {
|
||||
if (item.delivery_message_id) ids.add(item.delivery_message_id);
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
||||
function collectRecentMessages(args: {
|
||||
canonicalDeliveryMessageIds: Set<string>;
|
||||
canonicalOutboundMessages: WebDashboardRoomMessage[];
|
||||
sanitizedRecentMessages: WebDashboardRoomMessage[];
|
||||
}): WebDashboardRoomMessage[] {
|
||||
const messages: WebDashboardRoomMessage[] = [];
|
||||
for (const message of args.sanitizedRecentMessages) {
|
||||
if (args.canonicalDeliveryMessageIds.has(message.id)) continue;
|
||||
if (
|
||||
isDuplicateOfCanonicalOutbound(message, args.canonicalOutboundMessages)
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
messages.push(message);
|
||||
}
|
||||
return messages;
|
||||
}
|
||||
|
||||
function collectRecentOutputs(
|
||||
outputs: PairedTurnOutput[],
|
||||
outputLimit: number,
|
||||
): WebDashboardRoomTurnOutput[] {
|
||||
const recentOutputs: WebDashboardRoomTurnOutput[] = [];
|
||||
for (const output of outputs.slice(-outputLimit)) {
|
||||
const sanitized = sanitizeRoomTurnOutput(output);
|
||||
if (sanitized) recentOutputs.push(sanitized);
|
||||
}
|
||||
return recentOutputs;
|
||||
}
|
||||
|
||||
export function buildWebDashboardRoomActivity(args: {
|
||||
serviceId: string;
|
||||
entry: StatusSnapshot['entries'][number];
|
||||
pairedTask: PairedTask | null;
|
||||
turns: PairedTurnRecord[];
|
||||
attempts: PairedTurnAttemptRecord[];
|
||||
outputs: PairedTurnOutput[];
|
||||
outboundItems?: WorkItem[];
|
||||
messages: NewMessage[];
|
||||
outputLimit?: number;
|
||||
}): WebDashboardRoomActivity {
|
||||
const latestAttemptByTurnId = new Map<string, PairedTurnAttemptRecord>();
|
||||
for (const attempt of args.attempts) {
|
||||
const previous = latestAttemptByTurnId.get(attempt.turn_id);
|
||||
if (!previous || attempt.attempt_no > previous.attempt_no) {
|
||||
latestAttemptByTurnId.set(attempt.turn_id, attempt);
|
||||
}
|
||||
}
|
||||
const currentTurn = getCurrentRoomTurn(args.turns);
|
||||
const currentAttempt = currentTurn
|
||||
? (latestAttemptByTurnId.get(currentTurn.turn_id) ?? null)
|
||||
: null;
|
||||
const outputLimit = args.outputLimit ?? 4;
|
||||
const sanitizedRecentMessages = collectSanitizedRecentMessages(args.messages);
|
||||
const canonicalOutboundMessages = collectCanonicalOutboundMessages(
|
||||
args.outboundItems,
|
||||
sanitizedRecentMessages,
|
||||
);
|
||||
const canonicalDeliveryMessageIds = collectCanonicalDeliveryMessageIds(
|
||||
args.outboundItems,
|
||||
);
|
||||
const recentMessages = collectRecentMessages({
|
||||
canonicalDeliveryMessageIds,
|
||||
canonicalOutboundMessages,
|
||||
sanitizedRecentMessages,
|
||||
});
|
||||
const shouldExposeExecutionOutputs = args.outboundItems === undefined;
|
||||
|
||||
return {
|
||||
serviceId: args.serviceId,
|
||||
jid: args.entry.jid,
|
||||
name: args.entry.name,
|
||||
folder: args.entry.folder,
|
||||
agentType: args.entry.agentType,
|
||||
status: args.entry.status,
|
||||
elapsedMs: args.entry.elapsedMs,
|
||||
pendingMessages: args.entry.pendingMessages,
|
||||
pendingTasks: args.entry.pendingTasks,
|
||||
messages: recentMessages
|
||||
.concat(canonicalOutboundMessages)
|
||||
.sort(compareRoomMessagesByTimestamp),
|
||||
pairedTask: args.pairedTask
|
||||
? {
|
||||
id: args.pairedTask.id,
|
||||
title: args.pairedTask.title,
|
||||
status: args.pairedTask.status,
|
||||
roundTripCount: args.pairedTask.round_trip_count,
|
||||
updatedAt: args.pairedTask.updated_at,
|
||||
currentTurn: currentTurn
|
||||
? sanitizeRoomTurn(currentTurn, currentAttempt)
|
||||
: null,
|
||||
outputs: shouldExposeExecutionOutputs
|
||||
? collectRecentOutputs(args.outputs, outputLimit)
|
||||
: [],
|
||||
}
|
||||
: null,
|
||||
};
|
||||
}
|
||||
|
||||
export function buildWebDashboardOverview(args: {
|
||||
now?: string;
|
||||
snapshots: StatusSnapshot[];
|
||||
tasks: ScheduledTask[];
|
||||
pairedTasks?: PairedTask[];
|
||||
}): WebDashboardOverview {
|
||||
const generatedAt = args.now ?? new Date().toISOString();
|
||||
const rooms = {
|
||||
total: 0,
|
||||
active: 0,
|
||||
waiting: 0,
|
||||
inactive: 0,
|
||||
};
|
||||
|
||||
const services = args.snapshots.map((snapshot) => {
|
||||
let activeRooms = 0;
|
||||
for (const entry of snapshot.entries) {
|
||||
rooms.total += 1;
|
||||
if (entry.status === 'processing') {
|
||||
rooms.active += 1;
|
||||
activeRooms += 1;
|
||||
} else if (entry.status === 'waiting') {
|
||||
rooms.waiting += 1;
|
||||
activeRooms += 1;
|
||||
} else {
|
||||
rooms.inactive += 1;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
serviceId: snapshot.serviceId,
|
||||
assistantName: snapshot.assistantName,
|
||||
agentType: snapshot.agentType,
|
||||
updatedAt: snapshot.updatedAt,
|
||||
totalRooms: snapshot.entries.length,
|
||||
activeRooms,
|
||||
};
|
||||
});
|
||||
|
||||
const tasks = {
|
||||
total: args.tasks.length,
|
||||
active: 0,
|
||||
paused: 0,
|
||||
completed: 0,
|
||||
watchers: {
|
||||
active: 0,
|
||||
paused: 0,
|
||||
completed: 0,
|
||||
},
|
||||
};
|
||||
|
||||
for (const task of args.tasks) {
|
||||
if (task.status === 'active') tasks.active += 1;
|
||||
if (task.status === 'paused') tasks.paused += 1;
|
||||
if (task.status === 'completed') tasks.completed += 1;
|
||||
|
||||
if (isWatchCiTask(task)) {
|
||||
if (task.status === 'active') tasks.watchers.active += 1;
|
||||
if (task.status === 'paused') tasks.watchers.paused += 1;
|
||||
if (task.status === 'completed') tasks.watchers.completed += 1;
|
||||
}
|
||||
}
|
||||
|
||||
const usageRows = collectUsageRows(args.snapshots);
|
||||
const usageFetchedAt =
|
||||
args.snapshots
|
||||
.map((snapshot) => snapshot.usageRowsFetchedAt)
|
||||
.filter((value): value is string => !!value)
|
||||
.sort()
|
||||
.at(-1) ?? null;
|
||||
|
||||
return {
|
||||
generatedAt,
|
||||
services,
|
||||
rooms,
|
||||
tasks,
|
||||
usage: {
|
||||
rows: usageRows,
|
||||
fetchedAt: usageFetchedAt,
|
||||
},
|
||||
inbox: collectInboxItems({
|
||||
pairedTasks: args.pairedTasks ?? [],
|
||||
createdAt: generatedAt,
|
||||
}),
|
||||
};
|
||||
}
|
||||
@@ -1,285 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import type { NewMessage, PairedTask } from './types.js';
|
||||
import {
|
||||
createInboxDismissTracker,
|
||||
handleInboxActionRoute,
|
||||
type InboxActionRouteDependencies,
|
||||
} from './web-dashboard-inbox-routes.js';
|
||||
|
||||
function makePairedTask(overrides: Partial<PairedTask>): PairedTask {
|
||||
return {
|
||||
id: 'paired-1',
|
||||
chat_jid: 'dc:general',
|
||||
group_folder: 'general',
|
||||
owner_service_id: 'codex-main',
|
||||
reviewer_service_id: 'claude-reviewer',
|
||||
owner_agent_type: 'codex',
|
||||
reviewer_agent_type: 'claude-code',
|
||||
arbiter_agent_type: 'codex',
|
||||
title: 'Dashboard PR',
|
||||
source_ref: null,
|
||||
plan_notes: null,
|
||||
review_requested_at: null,
|
||||
round_trip_count: 0,
|
||||
owner_failure_count: 0,
|
||||
owner_step_done_streak: 0,
|
||||
finalize_step_done_count: 0,
|
||||
task_done_then_user_reopen_count: 0,
|
||||
empty_step_done_streak: 0,
|
||||
status: 'review_ready',
|
||||
arbiter_verdict: null,
|
||||
arbiter_requested_at: null,
|
||||
completion_reason: null,
|
||||
created_at: '2026-04-26T04:00:00.000Z',
|
||||
updated_at: '2026-04-26T04:30:00.000Z',
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function jsonResponse(value: unknown, init?: ResponseInit): Response {
|
||||
return new Response(JSON.stringify(value), {
|
||||
...init,
|
||||
headers: { 'content-type': 'application/json', ...init?.headers },
|
||||
});
|
||||
}
|
||||
|
||||
function inboxRequest(
|
||||
inboxId: string,
|
||||
body: unknown,
|
||||
method = 'POST',
|
||||
): Request {
|
||||
return new Request(
|
||||
`http://localhost/api/inbox/${encodeURIComponent(inboxId)}/actions`,
|
||||
{
|
||||
method,
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: method === 'POST' ? JSON.stringify(body) : undefined,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
function makeDeps(
|
||||
task: PairedTask | undefined,
|
||||
overrides: Partial<InboxActionRouteDependencies> = {},
|
||||
): InboxActionRouteDependencies {
|
||||
return {
|
||||
dismissTracker: createInboxDismissTracker(),
|
||||
enqueueMessageCheck: () => undefined,
|
||||
loadPairedTaskById: (id) => (id === task?.id ? task : undefined),
|
||||
messageExists: () => false,
|
||||
mutatePairedTaskIfUnchanged: () => true,
|
||||
schedulePairedFollowUp: () => true,
|
||||
writeChatMetadata: () => undefined,
|
||||
writeMessage: () => undefined,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe('web dashboard inbox action routes', () => {
|
||||
it('tracks timestamped and global inbox dismissals separately', () => {
|
||||
const tracker = createInboxDismissTracker();
|
||||
|
||||
tracker.dismiss('ci:task-1', '2026-04-26T05:00:00.000Z');
|
||||
expect(
|
||||
tracker.isDismissed({
|
||||
id: 'ci:task-1',
|
||||
lastOccurredAt: '2026-04-26T05:00:00.000Z',
|
||||
}),
|
||||
).toBe(true);
|
||||
expect(
|
||||
tracker.isDismissed({
|
||||
id: 'ci:task-1',
|
||||
lastOccurredAt: '2026-04-26T05:05:00.000Z',
|
||||
}),
|
||||
).toBe(false);
|
||||
|
||||
tracker.dismiss('ci:task-2', null);
|
||||
expect(
|
||||
tracker.isDismissed({
|
||||
id: 'ci:task-2',
|
||||
lastOccurredAt: '2026-04-26T05:00:00.000Z',
|
||||
}),
|
||||
).toBe(true);
|
||||
expect(
|
||||
tracker.isDismissed({
|
||||
id: 'ci:task-2',
|
||||
lastOccurredAt: '2026-04-26T05:05:00.000Z',
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('dismisses inbox items and queues paired follow-up intents', async () => {
|
||||
const dismissTracker = createInboxDismissTracker();
|
||||
const task = makePairedTask({ id: 'merge-1', status: 'merge_ready' });
|
||||
const scheduled: Array<{ taskId: string; intentKind: string }> = [];
|
||||
const queued: Array<{ chatJid: string; groupFolder: string }> = [];
|
||||
const deps = makeDeps(task, {
|
||||
dismissTracker,
|
||||
enqueueMessageCheck: (chatJid, groupFolder) => {
|
||||
queued.push({ chatJid, groupFolder });
|
||||
},
|
||||
schedulePairedFollowUp: (args) => {
|
||||
scheduled.push({
|
||||
taskId: args.task.id,
|
||||
intentKind: args.intentKind,
|
||||
});
|
||||
args.enqueue();
|
||||
return true;
|
||||
},
|
||||
});
|
||||
|
||||
const fallThrough = await handleInboxActionRoute({
|
||||
...deps,
|
||||
jsonResponse,
|
||||
request: new Request('http://localhost/api/overview'),
|
||||
url: new URL('http://localhost/api/overview'),
|
||||
});
|
||||
expect(fallThrough).toBeNull();
|
||||
|
||||
const dismiss = await handleInboxActionRoute({
|
||||
...deps,
|
||||
jsonResponse,
|
||||
request: inboxRequest('ci:task-1', {
|
||||
action: 'dismiss',
|
||||
lastOccurredAt: '2026-04-26T05:00:00.000Z',
|
||||
}),
|
||||
url: new URL('http://localhost/api/inbox/ci%3Atask-1/actions'),
|
||||
});
|
||||
expect(dismiss?.status).toBe(200);
|
||||
expect(
|
||||
dismissTracker.isDismissed({
|
||||
id: 'ci:task-1',
|
||||
lastOccurredAt: '2026-04-26T05:00:00.000Z',
|
||||
}),
|
||||
).toBe(true);
|
||||
|
||||
const run = await handleInboxActionRoute({
|
||||
...deps,
|
||||
jsonResponse,
|
||||
request: inboxRequest('paired:merge-1:merge_ready', { action: 'run' }),
|
||||
url: new URL(
|
||||
'http://localhost/api/inbox/paired%3Amerge-1%3Amerge_ready/actions',
|
||||
),
|
||||
});
|
||||
expect(run?.status).toBe(200);
|
||||
await expect(run?.json()).resolves.toMatchObject({
|
||||
intentKind: 'finalize-owner-turn',
|
||||
ok: true,
|
||||
queued: true,
|
||||
taskId: 'merge-1',
|
||||
});
|
||||
expect(scheduled).toEqual([
|
||||
{ taskId: 'merge-1', intentKind: 'finalize-owner-turn' },
|
||||
]);
|
||||
expect(queued).toEqual([{ chatJid: 'dc:general', groupFolder: 'general' }]);
|
||||
});
|
||||
|
||||
it('declines paired tasks and rejects invalid inbox actions', async () => {
|
||||
const task = makePairedTask({
|
||||
id: 'arbiter-1',
|
||||
status: 'arbiter_requested',
|
||||
arbiter_requested_at: '2026-04-26T05:00:00.000Z',
|
||||
});
|
||||
const messages: NewMessage[] = [];
|
||||
const updates: unknown[] = [];
|
||||
const deps = makeDeps(task, {
|
||||
enqueueMessageCheck: () => undefined,
|
||||
messageExists: (chatJid, id) =>
|
||||
messages.some(
|
||||
(message) => message.chat_jid === chatJid && message.id === id,
|
||||
),
|
||||
mutatePairedTaskIfUnchanged: (_id, _expectedUpdatedAt, update) => {
|
||||
updates.push(update);
|
||||
return true;
|
||||
},
|
||||
writeMessage: (message) => {
|
||||
messages.push(message);
|
||||
},
|
||||
});
|
||||
|
||||
const decline = () =>
|
||||
handleInboxActionRoute({
|
||||
...deps,
|
||||
jsonResponse,
|
||||
now: () => '2026-04-26T05:15:00.000Z',
|
||||
request: inboxRequest('paired:arbiter-1:arbiter_requested', {
|
||||
action: 'decline',
|
||||
requestId: 'decline 1',
|
||||
}),
|
||||
url: new URL(
|
||||
'http://localhost/api/inbox/paired%3Aarbiter-1%3Aarbiter_requested/actions',
|
||||
),
|
||||
});
|
||||
|
||||
const response = await decline();
|
||||
expect(response?.status).toBe(200);
|
||||
await expect(response?.json()).resolves.toMatchObject({
|
||||
ok: true,
|
||||
queued: true,
|
||||
status: 'active',
|
||||
taskId: 'arbiter-1',
|
||||
});
|
||||
expect(updates).toHaveLength(1);
|
||||
expect(updates[0]).toMatchObject({
|
||||
arbiter_requested_at: null,
|
||||
status: 'active',
|
||||
updated_at: '2026-04-26T05:15:00.000Z',
|
||||
});
|
||||
expect(messages[0]).toMatchObject({
|
||||
id: 'web-inbox-decline-1',
|
||||
content:
|
||||
'Dashboard declined arbiter escalation. Continue with the owner turn.',
|
||||
message_source_kind: 'ipc_injected_human',
|
||||
});
|
||||
|
||||
const duplicate = await decline();
|
||||
expect(duplicate?.status).toBe(200);
|
||||
await expect(duplicate?.json()).resolves.toMatchObject({
|
||||
duplicate: true,
|
||||
queued: false,
|
||||
});
|
||||
expect(messages).toHaveLength(1);
|
||||
|
||||
const invalidBody = await handleInboxActionRoute({
|
||||
...deps,
|
||||
jsonResponse,
|
||||
request: inboxRequest('paired:arbiter-1:active', { action: 'approve' }),
|
||||
url: new URL(
|
||||
'http://localhost/api/inbox/paired%3Aarbiter-1%3Aactive/actions',
|
||||
),
|
||||
});
|
||||
expect(invalidBody?.status).toBe(400);
|
||||
|
||||
const stale = await handleInboxActionRoute({
|
||||
...deps,
|
||||
jsonResponse,
|
||||
request: inboxRequest('paired:arbiter-1:merge_ready', { action: 'run' }),
|
||||
url: new URL(
|
||||
'http://localhost/api/inbox/paired%3Aarbiter-1%3Amerge_ready/actions',
|
||||
),
|
||||
});
|
||||
expect(stale?.status).toBe(409);
|
||||
|
||||
const notWired = await handleInboxActionRoute({
|
||||
...deps,
|
||||
enqueueMessageCheck: undefined,
|
||||
jsonResponse,
|
||||
request: inboxRequest('paired:arbiter-1:active', { action: 'run' }),
|
||||
url: new URL(
|
||||
'http://localhost/api/inbox/paired%3Aarbiter-1%3Aactive/actions',
|
||||
),
|
||||
});
|
||||
expect(notWired?.status).toBe(503);
|
||||
|
||||
const wrongMethod = await handleInboxActionRoute({
|
||||
...deps,
|
||||
jsonResponse,
|
||||
request: inboxRequest('paired:arbiter-1:active', null, 'GET'),
|
||||
url: new URL(
|
||||
'http://localhost/api/inbox/paired%3Aarbiter-1%3Aactive/actions',
|
||||
),
|
||||
});
|
||||
expect(wrongMethod?.status).toBe(405);
|
||||
});
|
||||
});
|
||||
@@ -1,379 +0,0 @@
|
||||
import type { ScheduledPairedFollowUpIntentKind } from './paired-follow-up-scheduler.js';
|
||||
import type { NewMessage, PairedTask } from './types.js';
|
||||
|
||||
type JsonResponse = (
|
||||
value: unknown,
|
||||
init?: ResponseInit,
|
||||
request?: Request,
|
||||
) => Response;
|
||||
|
||||
type InboxAction = 'run' | 'decline' | 'dismiss';
|
||||
|
||||
interface InboxActionRequest {
|
||||
action: InboxAction;
|
||||
requestId: string | null;
|
||||
lastOccurredAt: string | null;
|
||||
}
|
||||
|
||||
type InboxFollowUpTask = Pick<
|
||||
PairedTask,
|
||||
'id' | 'status' | 'round_trip_count' | 'updated_at'
|
||||
>;
|
||||
|
||||
export type InboxFollowUpScheduler = (args: {
|
||||
chatJid: string;
|
||||
runId: string;
|
||||
task: InboxFollowUpTask;
|
||||
intentKind: ScheduledPairedFollowUpIntentKind;
|
||||
enqueue: () => void;
|
||||
}) => boolean;
|
||||
|
||||
export interface InboxDismissTracker {
|
||||
dismiss: (inboxId: string, lastOccurredAt: string | null) => void;
|
||||
isDismissed: (item: { id: string; lastOccurredAt: string }) => boolean;
|
||||
}
|
||||
|
||||
export interface InboxActionRouteDependencies {
|
||||
dismissTracker: InboxDismissTracker;
|
||||
enqueueMessageCheck?: (chatJid: string, groupFolder: string) => void;
|
||||
loadPairedTaskById: (id: string) => PairedTask | undefined;
|
||||
messageExists: (chatJid: string, id: string) => boolean;
|
||||
mutatePairedTaskIfUnchanged: (
|
||||
id: string,
|
||||
expectedUpdatedAt: string,
|
||||
updates: Partial<
|
||||
Pick<
|
||||
PairedTask,
|
||||
'status' | 'updated_at' | 'arbiter_requested_at' | 'completion_reason'
|
||||
>
|
||||
>,
|
||||
) => boolean;
|
||||
schedulePairedFollowUp: InboxFollowUpScheduler;
|
||||
writeChatMetadata: (
|
||||
chatJid: string,
|
||||
timestamp: string,
|
||||
name?: string,
|
||||
channel?: string,
|
||||
isGroup?: boolean,
|
||||
) => void;
|
||||
writeMessage: (message: NewMessage) => void;
|
||||
}
|
||||
|
||||
interface InboxActionRouteContext extends InboxActionRouteDependencies {
|
||||
jsonResponse: JsonResponse;
|
||||
now?: () => string;
|
||||
request: Request;
|
||||
url: URL;
|
||||
}
|
||||
|
||||
export function createInboxDismissTracker(): InboxDismissTracker {
|
||||
const dismissedInboxKeys = new Set<string>();
|
||||
return {
|
||||
dismiss: (inboxId, lastOccurredAt) => {
|
||||
dismissedInboxKeys.add(makeInboxDismissKey(inboxId, lastOccurredAt));
|
||||
},
|
||||
isDismissed: (item) =>
|
||||
dismissedInboxKeys.has(item.id) ||
|
||||
dismissedInboxKeys.has(makeInboxDismissKey(item.id, item.lastOccurredAt)),
|
||||
};
|
||||
}
|
||||
|
||||
function parseInboxActionPath(pathname: string): string | null {
|
||||
const match = pathname.match(/^\/api\/inbox\/([^/]+)\/actions$/);
|
||||
if (!match) return null;
|
||||
try {
|
||||
return decodeURIComponent(match[1]);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function parsePairedInboxTarget(
|
||||
inboxId: string,
|
||||
): { taskId: string; status: PairedTask['status'] } | null {
|
||||
if (!inboxId.startsWith('paired:')) return null;
|
||||
const rest = inboxId.slice('paired:'.length);
|
||||
const separatorIndex = rest.lastIndexOf(':');
|
||||
if (separatorIndex <= 0 || separatorIndex === rest.length - 1) return null;
|
||||
const status = rest.slice(separatorIndex + 1);
|
||||
if (!isPairedTaskStatus(status)) return null;
|
||||
return {
|
||||
taskId: rest.slice(0, separatorIndex),
|
||||
status,
|
||||
};
|
||||
}
|
||||
|
||||
function isInboxAction(value: unknown): value is InboxAction {
|
||||
return value === 'run' || value === 'decline' || value === 'dismiss';
|
||||
}
|
||||
|
||||
function isPairedTaskStatus(value: unknown): value is PairedTask['status'] {
|
||||
return (
|
||||
value === 'active' ||
|
||||
value === 'review_ready' ||
|
||||
value === 'in_review' ||
|
||||
value === 'merge_ready' ||
|
||||
value === 'completed' ||
|
||||
value === 'arbiter_requested' ||
|
||||
value === 'in_arbitration'
|
||||
);
|
||||
}
|
||||
|
||||
async function readInboxAction(
|
||||
request: Request,
|
||||
): Promise<InboxActionRequest | null> {
|
||||
try {
|
||||
const body = (await request.json()) as {
|
||||
action?: unknown;
|
||||
requestId?: unknown;
|
||||
lastOccurredAt?: unknown;
|
||||
};
|
||||
if (!isInboxAction(body.action)) return null;
|
||||
return {
|
||||
action: body.action,
|
||||
requestId: sanitizeInboxActionRequestId(body.requestId),
|
||||
lastOccurredAt:
|
||||
typeof body.lastOccurredAt === 'string' && body.lastOccurredAt.trim()
|
||||
? body.lastOccurredAt.trim()
|
||||
: null,
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function makeWebRunId(prefix: string): string {
|
||||
return `web-${prefix}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
|
||||
}
|
||||
|
||||
function sanitizeInboxActionRequestId(value: unknown): string | null {
|
||||
if (typeof value !== 'string') return null;
|
||||
const trimmed = value.trim();
|
||||
if (!trimmed) return null;
|
||||
const safe = trimmed.replace(/[^A-Za-z0-9._:-]/g, '-').slice(0, 120);
|
||||
return safe || null;
|
||||
}
|
||||
|
||||
function makeInboxDismissKey(
|
||||
inboxId: string,
|
||||
lastOccurredAt: string | null,
|
||||
): string {
|
||||
return lastOccurredAt ? `${inboxId}\0${lastOccurredAt}` : inboxId;
|
||||
}
|
||||
|
||||
function makeWebInboxMessageId(requestId: string | null): string {
|
||||
return requestId
|
||||
? `web-inbox-${requestId}`
|
||||
: `web-inbox-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
|
||||
}
|
||||
|
||||
function declinedInboxMessage(status: PairedTask['status']): string {
|
||||
if (status === 'review_ready' || status === 'in_review') {
|
||||
return 'Dashboard declined review. Continue with the owner turn.';
|
||||
}
|
||||
if (status === 'merge_ready') {
|
||||
return 'Dashboard declined finalization. Continue with the owner turn.';
|
||||
}
|
||||
if (status === 'arbiter_requested' || status === 'in_arbitration') {
|
||||
return 'Dashboard declined arbiter escalation. Continue with the owner turn.';
|
||||
}
|
||||
return 'Dashboard declined this inbox item. Continue with the owner turn.';
|
||||
}
|
||||
|
||||
function pairedFollowUpIntentForStatus(
|
||||
status: PairedTask['status'],
|
||||
): ScheduledPairedFollowUpIntentKind | null {
|
||||
if (status === 'review_ready' || status === 'in_review') {
|
||||
return 'reviewer-turn';
|
||||
}
|
||||
if (status === 'merge_ready') {
|
||||
return 'finalize-owner-turn';
|
||||
}
|
||||
if (status === 'arbiter_requested' || status === 'in_arbitration') {
|
||||
return 'arbiter-turn';
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export async function handleInboxActionRoute({
|
||||
dismissTracker,
|
||||
enqueueMessageCheck,
|
||||
jsonResponse,
|
||||
loadPairedTaskById,
|
||||
messageExists,
|
||||
mutatePairedTaskIfUnchanged,
|
||||
now,
|
||||
request,
|
||||
schedulePairedFollowUp,
|
||||
url,
|
||||
writeChatMetadata,
|
||||
writeMessage,
|
||||
}: InboxActionRouteContext): Promise<Response | null> {
|
||||
const actionInboxId = parseInboxActionPath(url.pathname);
|
||||
if (!actionInboxId) return null;
|
||||
|
||||
if (request.method !== 'POST') {
|
||||
return jsonResponse({ error: 'Method not allowed' }, { status: 405 });
|
||||
}
|
||||
|
||||
const inboxRequest = await readInboxAction(request);
|
||||
if (!inboxRequest) {
|
||||
return jsonResponse({ error: 'Invalid inbox action' }, { status: 400 });
|
||||
}
|
||||
|
||||
if (inboxRequest.action === 'dismiss') {
|
||||
dismissTracker.dismiss(actionInboxId, inboxRequest.lastOccurredAt);
|
||||
return jsonResponse({ ok: true, id: actionInboxId, dismissed: true });
|
||||
}
|
||||
|
||||
const pairedTarget = parsePairedInboxTarget(actionInboxId);
|
||||
if (!pairedTarget) {
|
||||
return jsonResponse(
|
||||
{ error: 'Unsupported inbox action target' },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
if (!enqueueMessageCheck) {
|
||||
return jsonResponse(
|
||||
{ error: 'Paired follow-up queue is not configured' },
|
||||
{ status: 503 },
|
||||
);
|
||||
}
|
||||
|
||||
const task = loadPairedTaskById(pairedTarget.taskId);
|
||||
if (!task) {
|
||||
return jsonResponse({ error: 'Paired task not found' }, { status: 404 });
|
||||
}
|
||||
|
||||
if (inboxRequest.action === 'decline') {
|
||||
const messageId = makeWebInboxMessageId(inboxRequest.requestId);
|
||||
if (inboxRequest.requestId && messageExists(task.chat_jid, messageId)) {
|
||||
return jsonResponse({
|
||||
ok: true,
|
||||
id: actionInboxId,
|
||||
taskId: task.id,
|
||||
queued: false,
|
||||
duplicate: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (task.status !== pairedTarget.status) {
|
||||
return jsonResponse(
|
||||
{
|
||||
error: 'Inbox item is stale',
|
||||
status: task.status,
|
||||
},
|
||||
{ status: 409 },
|
||||
);
|
||||
}
|
||||
|
||||
if (inboxRequest.action === 'decline') {
|
||||
return handleDeclineInboxAction({
|
||||
actionInboxId,
|
||||
enqueueMessageCheck,
|
||||
jsonResponse,
|
||||
messageId: makeWebInboxMessageId(inboxRequest.requestId),
|
||||
mutatePairedTaskIfUnchanged,
|
||||
now,
|
||||
task,
|
||||
writeChatMetadata,
|
||||
writeMessage,
|
||||
});
|
||||
}
|
||||
|
||||
const intentKind = pairedFollowUpIntentForStatus(task.status);
|
||||
if (!intentKind) {
|
||||
return jsonResponse(
|
||||
{ error: 'Paired task is not actionable' },
|
||||
{ status: 409 },
|
||||
);
|
||||
}
|
||||
|
||||
const queued = schedulePairedFollowUp({
|
||||
chatJid: task.chat_jid,
|
||||
runId: makeWebRunId('inbox'),
|
||||
task,
|
||||
intentKind,
|
||||
enqueue: () => enqueueMessageCheck(task.chat_jid, task.group_folder),
|
||||
});
|
||||
|
||||
return jsonResponse({
|
||||
ok: true,
|
||||
id: actionInboxId,
|
||||
taskId: task.id,
|
||||
intentKind,
|
||||
queued,
|
||||
});
|
||||
}
|
||||
|
||||
function handleDeclineInboxAction({
|
||||
actionInboxId,
|
||||
enqueueMessageCheck,
|
||||
jsonResponse,
|
||||
messageId,
|
||||
mutatePairedTaskIfUnchanged,
|
||||
now,
|
||||
task,
|
||||
writeChatMetadata,
|
||||
writeMessage,
|
||||
}: {
|
||||
actionInboxId: string;
|
||||
enqueueMessageCheck: (chatJid: string, groupFolder: string) => void;
|
||||
jsonResponse: JsonResponse;
|
||||
messageId: string;
|
||||
mutatePairedTaskIfUnchanged: InboxActionRouteDependencies['mutatePairedTaskIfUnchanged'];
|
||||
now?: () => string;
|
||||
task: PairedTask;
|
||||
writeChatMetadata: InboxActionRouteDependencies['writeChatMetadata'];
|
||||
writeMessage: InboxActionRouteDependencies['writeMessage'];
|
||||
}): Response {
|
||||
const timestamp = now?.() ?? new Date().toISOString();
|
||||
const updates: Partial<
|
||||
Pick<
|
||||
PairedTask,
|
||||
'status' | 'updated_at' | 'arbiter_requested_at' | 'completion_reason'
|
||||
>
|
||||
> = {
|
||||
status: 'active',
|
||||
updated_at: timestamp,
|
||||
};
|
||||
if (task.status === 'arbiter_requested' || task.status === 'in_arbitration') {
|
||||
updates.arbiter_requested_at = null;
|
||||
}
|
||||
|
||||
const updated = mutatePairedTaskIfUnchanged(
|
||||
task.id,
|
||||
task.updated_at,
|
||||
updates,
|
||||
);
|
||||
if (!updated) {
|
||||
return jsonResponse(
|
||||
{ error: 'Inbox item is stale', status: task.status },
|
||||
{ status: 409 },
|
||||
);
|
||||
}
|
||||
|
||||
writeChatMetadata(task.chat_jid, timestamp, undefined, 'web-dashboard', true);
|
||||
writeMessage({
|
||||
id: messageId,
|
||||
chat_jid: task.chat_jid,
|
||||
sender: 'web-dashboard',
|
||||
sender_name: 'Web Dashboard',
|
||||
content: declinedInboxMessage(task.status),
|
||||
timestamp,
|
||||
is_from_me: false,
|
||||
is_bot_message: false,
|
||||
message_source_kind: 'ipc_injected_human',
|
||||
});
|
||||
enqueueMessageCheck(task.chat_jid, task.group_folder);
|
||||
|
||||
return jsonResponse({
|
||||
ok: true,
|
||||
id: actionInboxId,
|
||||
taskId: task.id,
|
||||
status: 'active',
|
||||
queued: true,
|
||||
});
|
||||
}
|
||||
@@ -1,158 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import type { StatusSnapshot } from './status-dashboard.js';
|
||||
import type { PairedTask, ScheduledTask } from './types.js';
|
||||
import {
|
||||
handleOverviewRoute,
|
||||
type OverviewRouteDependencies,
|
||||
} from './web-dashboard-overview-routes.js';
|
||||
import type { ServiceRestartRecord } from './web-dashboard-service-routes.js';
|
||||
|
||||
function jsonResponse(value: unknown, init?: ResponseInit): Response {
|
||||
return new Response(JSON.stringify(value), {
|
||||
...init,
|
||||
headers: {
|
||||
'content-type': 'application/json; charset=utf-8',
|
||||
...(init?.headers as Record<string, string> | undefined),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function makeTask(overrides: Partial<ScheduledTask>): ScheduledTask {
|
||||
return {
|
||||
id: 'task-1',
|
||||
group_folder: 'ops',
|
||||
chat_jid: 'dc:ops',
|
||||
agent_type: null,
|
||||
status_message_id: null,
|
||||
status_started_at: null,
|
||||
prompt: 'run task',
|
||||
schedule_type: 'once',
|
||||
schedule_value: '2026-04-26T05:20:00.000Z',
|
||||
context_mode: 'isolated',
|
||||
next_run: '2026-04-26T05:20:00.000Z',
|
||||
last_run: null,
|
||||
last_result: null,
|
||||
status: 'active',
|
||||
suspended_until: null,
|
||||
created_at: '2026-04-26T05:00:00.000Z',
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function makePairedTask(overrides: Partial<PairedTask>): PairedTask {
|
||||
return {
|
||||
id: 'paired-1',
|
||||
chat_jid: 'dc:ops',
|
||||
group_folder: 'ops',
|
||||
owner_service_id: 'codex-main',
|
||||
reviewer_service_id: 'claude-reviewer',
|
||||
owner_agent_type: 'codex',
|
||||
reviewer_agent_type: 'claude-code',
|
||||
arbiter_agent_type: 'codex',
|
||||
title: 'Review dashboard',
|
||||
source_ref: null,
|
||||
plan_notes: null,
|
||||
review_requested_at: null,
|
||||
round_trip_count: 0,
|
||||
owner_failure_count: 0,
|
||||
owner_step_done_streak: 0,
|
||||
finalize_step_done_count: 0,
|
||||
task_done_then_user_reopen_count: 0,
|
||||
empty_step_done_streak: 0,
|
||||
status: 'review_ready',
|
||||
arbiter_verdict: null,
|
||||
arbiter_requested_at: null,
|
||||
completion_reason: null,
|
||||
created_at: '2026-04-26T04:00:00.000Z',
|
||||
updated_at: '2026-04-26T05:00:00.000Z',
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function route(
|
||||
pathname: string,
|
||||
overrides: Partial<OverviewRouteDependencies> = {},
|
||||
): Response | null {
|
||||
return handleOverviewRoute({
|
||||
url: new URL(`http://localhost${pathname}`),
|
||||
jsonResponse,
|
||||
loadPairedTasks: () => [],
|
||||
loadTasks: () => [],
|
||||
readSnapshots: () => [],
|
||||
recentServiceRestarts: [],
|
||||
statusMaxAgeMs: 1234,
|
||||
now: () => '2026-04-26T05:10:00.000Z',
|
||||
...overrides,
|
||||
});
|
||||
}
|
||||
|
||||
describe('web dashboard overview route', () => {
|
||||
it('serves overview JSON with operation restart records', async () => {
|
||||
const recentServiceRestarts: ServiceRestartRecord[] = [
|
||||
{
|
||||
id: 'web-restart-1',
|
||||
target: 'stack',
|
||||
requestedAt: '2026-04-26T05:00:00.000Z',
|
||||
completedAt: '2026-04-26T05:00:01.000Z',
|
||||
status: 'success',
|
||||
services: ['ejclaw'],
|
||||
},
|
||||
];
|
||||
const response = route('/api/overview', {
|
||||
loadTasks: () => [makeTask({ id: 'task-active' })],
|
||||
recentServiceRestarts,
|
||||
});
|
||||
|
||||
expect(response?.status).toBe(200);
|
||||
await expect(response?.json()).resolves.toMatchObject({
|
||||
generatedAt: '2026-04-26T05:10:00.000Z',
|
||||
tasks: { total: 1, active: 1 },
|
||||
operations: {
|
||||
serviceRestarts: [
|
||||
{
|
||||
id: 'web-restart-1',
|
||||
status: 'success',
|
||||
services: ['ejclaw'],
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('filters dismissed inbox items and falls through for other paths', async () => {
|
||||
const snapshots: StatusSnapshot[] = [
|
||||
{
|
||||
serviceId: 'codex-main',
|
||||
agentType: 'codex',
|
||||
assistantName: 'Codex',
|
||||
updatedAt: '2026-04-26T05:00:00.000Z',
|
||||
entries: [
|
||||
{
|
||||
jid: 'dc:ops',
|
||||
name: '#ops',
|
||||
folder: 'ops',
|
||||
agentType: 'codex',
|
||||
status: 'waiting',
|
||||
elapsedMs: 2500,
|
||||
pendingMessages: true,
|
||||
pendingTasks: 1,
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
const overview = route('/api/overview', {
|
||||
loadPairedTasks: () => [
|
||||
makePairedTask({ id: 'merge-1', status: 'merge_ready' }),
|
||||
],
|
||||
readSnapshots: () => snapshots,
|
||||
isInboxItemDismissed: () => true,
|
||||
});
|
||||
|
||||
expect(overview?.status).toBe(200);
|
||||
await expect(overview?.json()).resolves.toMatchObject({ inbox: [] });
|
||||
|
||||
const unmatched = route('/api/tasks');
|
||||
expect(unmatched).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,63 +0,0 @@
|
||||
import type { StatusSnapshot } from './status-dashboard.js';
|
||||
import type { PairedTask, ScheduledTask } from './types.js';
|
||||
import { buildWebDashboardOverview } from './web-dashboard-data.js';
|
||||
import type { ServiceRestartRecord } from './web-dashboard-service-routes.js';
|
||||
|
||||
type JsonResponse = (
|
||||
value: unknown,
|
||||
init?: ResponseInit,
|
||||
request?: Request,
|
||||
) => Response;
|
||||
|
||||
type DismissableInboxItem = {
|
||||
id: string;
|
||||
lastOccurredAt: string;
|
||||
};
|
||||
|
||||
export interface OverviewRouteDependencies {
|
||||
isInboxItemDismissed?: (item: DismissableInboxItem) => boolean;
|
||||
loadPairedTasks: () => PairedTask[];
|
||||
loadTasks: () => ScheduledTask[];
|
||||
readSnapshots: (maxAgeMs: number) => StatusSnapshot[];
|
||||
recentServiceRestarts: ServiceRestartRecord[];
|
||||
statusMaxAgeMs: number;
|
||||
now?: () => string;
|
||||
}
|
||||
|
||||
interface OverviewRouteContext extends OverviewRouteDependencies {
|
||||
url: URL;
|
||||
jsonResponse: JsonResponse;
|
||||
}
|
||||
|
||||
export function handleOverviewRoute({
|
||||
isInboxItemDismissed,
|
||||
jsonResponse,
|
||||
loadPairedTasks,
|
||||
loadTasks,
|
||||
now,
|
||||
readSnapshots,
|
||||
recentServiceRestarts,
|
||||
statusMaxAgeMs,
|
||||
url,
|
||||
}: OverviewRouteContext): Response | null {
|
||||
if (url.pathname !== '/api/overview') return null;
|
||||
|
||||
const snapshots = readSnapshots(statusMaxAgeMs);
|
||||
const tasks = loadTasks();
|
||||
const pairedTasks = loadPairedTasks();
|
||||
const overview = buildWebDashboardOverview({
|
||||
now: now?.(),
|
||||
snapshots,
|
||||
tasks,
|
||||
pairedTasks,
|
||||
});
|
||||
return jsonResponse({
|
||||
...overview,
|
||||
operations: {
|
||||
serviceRestarts: recentServiceRestarts,
|
||||
},
|
||||
inbox: isInboxItemDismissed
|
||||
? overview.inbox.filter((item) => !isInboxItemDismissed(item))
|
||||
: overview.inbox,
|
||||
});
|
||||
}
|
||||
@@ -1,77 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import type { NewMessage } from './types.js';
|
||||
import { buildWebDashboardRoomActivity } from './web-dashboard-data.js';
|
||||
|
||||
describe('web dashboard room envelope rendering', () => {
|
||||
it('unwraps EJClaw structured envelopes in room messages', () => {
|
||||
const envelope = JSON.stringify({
|
||||
ejclaw: {
|
||||
visibility: 'public',
|
||||
text: 'PR #52 모바일/룸 parity 검증 스크린샷입니다.',
|
||||
verdict: 'done',
|
||||
attachments: [
|
||||
{
|
||||
path: '/tmp/ejclaw-room-mobile-list-390.png',
|
||||
name: 'room.png',
|
||||
mime: 'image/png',
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
const htmlEscapedEnvelope = envelope.replace(/"/g, '"');
|
||||
const messages: NewMessage[] = [
|
||||
makeMessage('msg-json', envelope, 'owner'),
|
||||
makeMessage('msg-html-json', htmlEscapedEnvelope, 'reviewer'),
|
||||
makeMessage(
|
||||
'msg-silent',
|
||||
'{"ejclaw":{"visibility":"silent","verdict":"silent"}}',
|
||||
'arbiter',
|
||||
),
|
||||
];
|
||||
|
||||
const activity = buildWebDashboardRoomActivity({
|
||||
serviceId: 'codex-main',
|
||||
entry: {
|
||||
jid: 'dc:ops',
|
||||
name: '#ops',
|
||||
folder: 'ops',
|
||||
agentType: 'codex',
|
||||
status: 'processing',
|
||||
elapsedMs: 15_000,
|
||||
pendingMessages: true,
|
||||
pendingTasks: 1,
|
||||
},
|
||||
pairedTask: null,
|
||||
turns: [],
|
||||
attempts: [],
|
||||
outputs: [],
|
||||
messages,
|
||||
});
|
||||
|
||||
expect(activity.messages).toHaveLength(2);
|
||||
expect(activity.messages.map((message) => message.content)).toEqual([
|
||||
'PR #52 모바일/룸 parity 검증 스크린샷입니다.',
|
||||
'PR #52 모바일/룸 parity 검증 스크린샷입니다.',
|
||||
]);
|
||||
expect(JSON.stringify(activity.messages)).not.toContain('"ejclaw"');
|
||||
});
|
||||
});
|
||||
|
||||
function makeMessage(
|
||||
id: string,
|
||||
content: string,
|
||||
senderName: string,
|
||||
): NewMessage {
|
||||
return {
|
||||
id,
|
||||
chat_jid: 'dc:ops',
|
||||
sender: senderName,
|
||||
sender_name: senderName,
|
||||
content,
|
||||
timestamp: '2026-04-26T05:29:00.000Z',
|
||||
is_from_me: false,
|
||||
is_bot_message: true,
|
||||
message_source_kind: 'bot',
|
||||
};
|
||||
}
|
||||
@@ -1,176 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import type { NewMessage, RegisteredGroup } from './types.js';
|
||||
import {
|
||||
createRoomMessageIdCache,
|
||||
handleRoomMessageRoute,
|
||||
} from './web-dashboard-room-message-routes.js';
|
||||
|
||||
function jsonResponse(value: unknown, init?: ResponseInit): Response {
|
||||
return new Response(JSON.stringify(value), {
|
||||
...init,
|
||||
headers: { 'content-type': 'application/json', ...init?.headers },
|
||||
});
|
||||
}
|
||||
|
||||
function roomMessageRequest(
|
||||
roomJid: string,
|
||||
body: unknown,
|
||||
method = 'POST',
|
||||
): Request {
|
||||
return new Request(
|
||||
`http://localhost/api/rooms/${encodeURIComponent(roomJid)}/messages`,
|
||||
{
|
||||
method,
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: method === 'POST' ? JSON.stringify(body) : undefined,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
function makeDeps(
|
||||
overrides: {
|
||||
rooms?: Record<string, RegisteredGroup>;
|
||||
existingMessage?: (chatJid: string, id: string) => boolean;
|
||||
messages?: NewMessage[];
|
||||
queued?: Array<{ chatJid: string; groupFolder: string }>;
|
||||
} = {},
|
||||
) {
|
||||
const messages = overrides.messages ?? [];
|
||||
const queued = overrides.queued ?? [];
|
||||
return {
|
||||
enqueueMessageCheck: (chatJid: string, groupFolder: string) => {
|
||||
queued.push({ chatJid, groupFolder });
|
||||
},
|
||||
loadRoomBindings: () =>
|
||||
overrides.rooms ?? {
|
||||
'dc:ops': {
|
||||
name: '#ops',
|
||||
folder: 'ops-room',
|
||||
added_at: '2026-04-26T05:00:00.000Z',
|
||||
},
|
||||
},
|
||||
messageExists: overrides.existingMessage ?? (() => false),
|
||||
rememberRoomMessageId: createRoomMessageIdCache(),
|
||||
writeChatMetadata: (
|
||||
_chatJid: string,
|
||||
_timestamp: string,
|
||||
_name?: string,
|
||||
_channel?: string,
|
||||
_isGroup?: boolean,
|
||||
) => undefined,
|
||||
writeMessage: (message: NewMessage) => {
|
||||
messages.push(message);
|
||||
},
|
||||
messages,
|
||||
queued,
|
||||
};
|
||||
}
|
||||
|
||||
describe('web dashboard room message routes', () => {
|
||||
it('expires the oldest remembered room message ids after the cache limit', () => {
|
||||
const remember = createRoomMessageIdCache(2);
|
||||
|
||||
expect(remember('room:message-1')).toBe(true);
|
||||
expect(remember('room:message-1')).toBe(false);
|
||||
expect(remember('room:message-2')).toBe(true);
|
||||
expect(remember('room:message-3')).toBe(true);
|
||||
expect(remember('room:message-1')).toBe(true);
|
||||
expect(remember('room:message-2')).toBe(true);
|
||||
});
|
||||
|
||||
it('injects messages and deduplicates repeated request ids', async () => {
|
||||
const messages: NewMessage[] = [];
|
||||
const queued: Array<{ chatJid: string; groupFolder: string }> = [];
|
||||
const deps = makeDeps({ messages, queued });
|
||||
|
||||
const first = await handleRoomMessageRoute({
|
||||
...deps,
|
||||
jsonResponse,
|
||||
now: () => '2026-04-26T05:10:00.000Z',
|
||||
request: roomMessageRequest('dc:ops', {
|
||||
nickname: ' 눈쟁이 ',
|
||||
requestId: 'compose 1',
|
||||
text: ' run a dashboard check ',
|
||||
}),
|
||||
url: new URL('http://localhost/api/rooms/dc%3Aops/messages'),
|
||||
});
|
||||
const second = await handleRoomMessageRoute({
|
||||
...deps,
|
||||
jsonResponse,
|
||||
request: roomMessageRequest('dc:ops', {
|
||||
requestId: 'compose 1',
|
||||
text: 'second submit',
|
||||
}),
|
||||
url: new URL('http://localhost/api/rooms/dc%3Aops/messages'),
|
||||
});
|
||||
|
||||
expect(first?.status).toBe(200);
|
||||
expect(second?.status).toBe(200);
|
||||
await expect(first?.json()).resolves.toMatchObject({
|
||||
id: 'web-compose-1',
|
||||
queued: true,
|
||||
});
|
||||
await expect(second?.json()).resolves.toMatchObject({
|
||||
id: 'web-compose-1',
|
||||
queued: false,
|
||||
duplicate: true,
|
||||
});
|
||||
expect(messages).toHaveLength(1);
|
||||
expect(messages[0]).toMatchObject({
|
||||
chat_jid: 'dc:ops',
|
||||
content: 'run a dashboard check',
|
||||
id: 'web-compose-1',
|
||||
message_source_kind: 'ipc_injected_human',
|
||||
sender: 'web-dashboard',
|
||||
sender_name: '눈쟁이',
|
||||
timestamp: '2026-04-26T05:10:00.000Z',
|
||||
});
|
||||
expect(queued).toEqual([{ chatJid: 'dc:ops', groupFolder: 'ops-room' }]);
|
||||
});
|
||||
|
||||
it('handles fall-through and invalid room message requests', async () => {
|
||||
const deps = makeDeps({ rooms: {} });
|
||||
|
||||
const fallThrough = await handleRoomMessageRoute({
|
||||
...deps,
|
||||
jsonResponse,
|
||||
request: new Request('http://localhost/api/overview'),
|
||||
url: new URL('http://localhost/api/overview'),
|
||||
});
|
||||
expect(fallThrough).toBeNull();
|
||||
|
||||
const notConfigured = await handleRoomMessageRoute({
|
||||
...deps,
|
||||
enqueueMessageCheck: undefined,
|
||||
jsonResponse,
|
||||
request: roomMessageRequest('dc:ops', { text: 'hello' }),
|
||||
url: new URL('http://localhost/api/rooms/dc%3Aops/messages'),
|
||||
});
|
||||
expect(notConfigured?.status).toBe(503);
|
||||
|
||||
const empty = await handleRoomMessageRoute({
|
||||
...deps,
|
||||
jsonResponse,
|
||||
request: roomMessageRequest('dc:ops', { text: ' ' }),
|
||||
url: new URL('http://localhost/api/rooms/dc%3Aops/messages'),
|
||||
});
|
||||
expect(empty?.status).toBe(400);
|
||||
|
||||
const missing = await handleRoomMessageRoute({
|
||||
...deps,
|
||||
jsonResponse,
|
||||
request: roomMessageRequest('dc:missing', { text: 'hello' }),
|
||||
url: new URL('http://localhost/api/rooms/dc%3Amissing/messages'),
|
||||
});
|
||||
expect(missing?.status).toBe(404);
|
||||
|
||||
const wrongMethod = await handleRoomMessageRoute({
|
||||
...deps,
|
||||
jsonResponse,
|
||||
request: roomMessageRequest('dc:ops', null, 'GET'),
|
||||
url: new URL('http://localhost/api/rooms/dc%3Aops/messages'),
|
||||
});
|
||||
expect(wrongMethod?.status).toBe(405);
|
||||
});
|
||||
});
|
||||
@@ -1,175 +0,0 @@
|
||||
import type { NewMessage, RegisteredGroup } from './types.js';
|
||||
|
||||
type JsonResponse = (
|
||||
value: unknown,
|
||||
init?: ResponseInit,
|
||||
request?: Request,
|
||||
) => Response;
|
||||
|
||||
export type RoomMessageIdRememberer = (id: string) => boolean;
|
||||
|
||||
export interface RoomMessageRouteDependencies {
|
||||
enqueueMessageCheck?: (chatJid: string, groupFolder: string) => void;
|
||||
loadRoomBindings?: () => Record<string, RegisteredGroup>;
|
||||
messageExists: (chatJid: string, id: string) => boolean;
|
||||
rememberRoomMessageId: RoomMessageIdRememberer;
|
||||
writeChatMetadata: (
|
||||
chatJid: string,
|
||||
timestamp: string,
|
||||
name?: string,
|
||||
channel?: string,
|
||||
isGroup?: boolean,
|
||||
) => void;
|
||||
writeMessage: (message: NewMessage) => void;
|
||||
}
|
||||
|
||||
interface RoomMessageRouteContext extends RoomMessageRouteDependencies {
|
||||
jsonResponse: JsonResponse;
|
||||
now?: () => string;
|
||||
request: Request;
|
||||
url: URL;
|
||||
}
|
||||
|
||||
const ROOM_MESSAGE_ID_CACHE_LIMIT = 500;
|
||||
|
||||
export function createRoomMessageIdCache(
|
||||
limit = ROOM_MESSAGE_ID_CACHE_LIMIT,
|
||||
): RoomMessageIdRememberer {
|
||||
const ids: string[] = [];
|
||||
const idSet = new Set<string>();
|
||||
|
||||
return (id: string): boolean => {
|
||||
if (idSet.has(id)) return false;
|
||||
idSet.add(id);
|
||||
ids.push(id);
|
||||
if (ids.length > limit) {
|
||||
const oldest = ids.shift();
|
||||
if (oldest) idSet.delete(oldest);
|
||||
}
|
||||
return true;
|
||||
};
|
||||
}
|
||||
|
||||
function parseRoomMessagePath(pathname: string): string | null {
|
||||
const match = pathname.match(/^\/api\/rooms\/([^/]+)\/messages$/);
|
||||
if (!match) return null;
|
||||
try {
|
||||
return decodeURIComponent(match[1]);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function sanitizeRoomMessageRequestId(value: unknown): string | null {
|
||||
if (typeof value !== 'string') return null;
|
||||
const trimmed = value.trim();
|
||||
if (!trimmed) return null;
|
||||
const safe = trimmed.replace(/[^A-Za-z0-9._:-]/g, '-').slice(0, 120);
|
||||
return safe || null;
|
||||
}
|
||||
|
||||
async function readRoomMessageBody(request: Request): Promise<{
|
||||
text: string;
|
||||
requestId: string | null;
|
||||
nickname: string | null;
|
||||
} | null> {
|
||||
try {
|
||||
const body = (await request.json()) as {
|
||||
text?: unknown;
|
||||
requestId?: unknown;
|
||||
nickname?: unknown;
|
||||
};
|
||||
if (typeof body.text !== 'string') return null;
|
||||
const text = body.text.trim();
|
||||
if (!text) return null;
|
||||
let nickname: string | null = null;
|
||||
if (typeof body.nickname === 'string') {
|
||||
const trimmed = body.nickname.trim().slice(0, 32);
|
||||
if (trimmed) nickname = trimmed;
|
||||
}
|
||||
return {
|
||||
text: text.length > 8000 ? text.slice(0, 8000) : text,
|
||||
requestId: sanitizeRoomMessageRequestId(body.requestId),
|
||||
nickname,
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function makeWebMessageId(): string {
|
||||
return `web-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
|
||||
}
|
||||
|
||||
function makeWebMessageIdFromRequest(requestId: string | null): string {
|
||||
return requestId ? `web-${requestId}` : makeWebMessageId();
|
||||
}
|
||||
|
||||
export async function handleRoomMessageRoute({
|
||||
enqueueMessageCheck,
|
||||
jsonResponse,
|
||||
loadRoomBindings,
|
||||
messageExists,
|
||||
now,
|
||||
rememberRoomMessageId,
|
||||
request,
|
||||
url,
|
||||
writeChatMetadata,
|
||||
writeMessage,
|
||||
}: RoomMessageRouteContext): Promise<Response | null> {
|
||||
const messageRoomJid = parseRoomMessagePath(url.pathname);
|
||||
if (!messageRoomJid) return null;
|
||||
|
||||
if (request.method !== 'POST') {
|
||||
return jsonResponse({ error: 'Method not allowed' }, { status: 405 });
|
||||
}
|
||||
|
||||
if (!loadRoomBindings || !enqueueMessageCheck) {
|
||||
return jsonResponse(
|
||||
{ error: 'Room message injection is not configured' },
|
||||
{ status: 503 },
|
||||
);
|
||||
}
|
||||
|
||||
const body = await readRoomMessageBody(request);
|
||||
if (!body) {
|
||||
return jsonResponse({ error: 'Message text is required' }, { status: 400 });
|
||||
}
|
||||
|
||||
const binding = loadRoomBindings()[messageRoomJid];
|
||||
if (!binding) {
|
||||
return jsonResponse({ error: 'Room not found' }, { status: 404 });
|
||||
}
|
||||
|
||||
const timestamp = now?.() ?? new Date().toISOString();
|
||||
const id = makeWebMessageIdFromRequest(body.requestId);
|
||||
if (body.requestId && messageExists(messageRoomJid, id)) {
|
||||
return jsonResponse({ ok: true, id, queued: false, duplicate: true });
|
||||
}
|
||||
|
||||
if (!rememberRoomMessageId(`${messageRoomJid}:${id}`)) {
|
||||
return jsonResponse({ ok: true, id, queued: false, duplicate: true });
|
||||
}
|
||||
|
||||
writeChatMetadata(
|
||||
messageRoomJid,
|
||||
timestamp,
|
||||
binding.name,
|
||||
'web-dashboard',
|
||||
true,
|
||||
);
|
||||
writeMessage({
|
||||
id,
|
||||
chat_jid: messageRoomJid,
|
||||
sender: 'web-dashboard',
|
||||
sender_name: body.nickname ?? 'Web Dashboard',
|
||||
content: body.text,
|
||||
timestamp,
|
||||
is_from_me: false,
|
||||
is_bot_message: false,
|
||||
message_source_kind: 'ipc_injected_human',
|
||||
});
|
||||
enqueueMessageCheck(messageRoomJid, binding.folder);
|
||||
|
||||
return jsonResponse({ ok: true, id, queued: true });
|
||||
}
|
||||
@@ -1,281 +0,0 @@
|
||||
import { gunzipSync } from 'node:zlib';
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import type {
|
||||
PairedTurnAttemptRecord,
|
||||
PairedTurnRecord,
|
||||
WorkItem,
|
||||
} from './db.js';
|
||||
import type { StatusSnapshot } from './status-dashboard.js';
|
||||
import type { NewMessage, PairedTask, PairedTurnOutput } from './types.js';
|
||||
import {
|
||||
handleRoomTimelineRoute,
|
||||
type RoomsTimelineRouteDependencies,
|
||||
} from './web-dashboard-room-routes.js';
|
||||
|
||||
function jsonResponse(value: unknown, init?: ResponseInit): Response {
|
||||
return new Response(JSON.stringify(value), {
|
||||
...init,
|
||||
headers: {
|
||||
'content-type': 'application/json; charset=utf-8',
|
||||
...(init?.headers as Record<string, string> | undefined),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function makePairedTask(overrides: Partial<PairedTask> = {}): PairedTask {
|
||||
return {
|
||||
id: 'paired-room-1',
|
||||
chat_jid: 'dc:ops',
|
||||
group_folder: 'ops-room',
|
||||
owner_service_id: 'codex-main',
|
||||
reviewer_service_id: 'claude-reviewer',
|
||||
owner_agent_type: 'codex',
|
||||
reviewer_agent_type: 'claude-code',
|
||||
arbiter_agent_type: 'codex',
|
||||
title: 'Dashboard PR',
|
||||
source_ref: null,
|
||||
plan_notes: null,
|
||||
review_requested_at: null,
|
||||
round_trip_count: 2,
|
||||
owner_failure_count: 0,
|
||||
owner_step_done_streak: 0,
|
||||
finalize_step_done_count: 0,
|
||||
task_done_then_user_reopen_count: 0,
|
||||
empty_step_done_streak: 0,
|
||||
status: 'in_review',
|
||||
arbiter_verdict: null,
|
||||
arbiter_requested_at: null,
|
||||
completion_reason: null,
|
||||
created_at: '2026-04-26T04:00:00.000Z',
|
||||
updated_at: '2026-04-26T05:20:00.000Z',
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function snapshot(updatedAt = '2026-04-26T05:22:00.000Z'): StatusSnapshot {
|
||||
return {
|
||||
serviceId: 'codex-main',
|
||||
agentType: 'codex',
|
||||
assistantName: 'Codex',
|
||||
updatedAt,
|
||||
entries: [
|
||||
{
|
||||
jid: 'dc:ops',
|
||||
name: '#ops',
|
||||
folder: 'ops-room',
|
||||
agentType: 'codex',
|
||||
status: 'processing',
|
||||
elapsedMs: 120_000,
|
||||
pendingMessages: true,
|
||||
pendingTasks: 1,
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
function roomDeps(
|
||||
overrides: Partial<RoomsTimelineRouteDependencies> = {},
|
||||
): RoomsTimelineRouteDependencies {
|
||||
return {
|
||||
statusMaxAgeMs: 1234,
|
||||
readSnapshots: () => [snapshot()],
|
||||
loadLatestPairedTaskForChat: () => null,
|
||||
loadPairedTurnsForTask: () => [],
|
||||
loadLatestPairedTurnForTask: () => null,
|
||||
loadPairedTurnAttempts: () => [],
|
||||
loadPairedTurnOutputs: () => [],
|
||||
loadRecentPairedTurnOutputsForChat: () => [],
|
||||
loadRecentDeliveredWorkItemsForChat: () => [],
|
||||
loadRecentChatMessages: () => [],
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function workItem(overrides: Partial<WorkItem> = {}): WorkItem {
|
||||
return {
|
||||
id: 9001,
|
||||
group_folder: 'ops-room',
|
||||
chat_jid: 'dc:ops',
|
||||
agent_type: 'codex',
|
||||
service_id: 'codex-main',
|
||||
delivery_role: 'owner',
|
||||
status: 'delivered',
|
||||
start_seq: null,
|
||||
end_seq: null,
|
||||
result_payload: 'owner final output',
|
||||
attachments: [],
|
||||
delivery_attempts: 1,
|
||||
delivery_message_id: 'discord-owner-final',
|
||||
last_error: null,
|
||||
created_at: '2026-04-26T05:18:00.000Z',
|
||||
updated_at: '2026-04-26T05:18:30.000Z',
|
||||
delivered_at: '2026-04-26T05:18:30.000Z',
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe('web dashboard room routes', () => {
|
||||
it('serves room timeline with paired progress and recent messages', async () => {
|
||||
const pairedTask = makePairedTask();
|
||||
const turns: PairedTurnRecord[] = [
|
||||
{
|
||||
turn_id: 'paired-room-1:reviewer-turn',
|
||||
task_id: pairedTask.id,
|
||||
task_updated_at: pairedTask.updated_at,
|
||||
role: 'reviewer',
|
||||
intent_kind: 'reviewer-turn',
|
||||
state: 'queued',
|
||||
executor_service_id: null,
|
||||
executor_agent_type: null,
|
||||
attempt_no: 0,
|
||||
created_at: '2026-04-26T05:18:30.000Z',
|
||||
updated_at: '2026-04-26T05:21:00.000Z',
|
||||
completed_at: null,
|
||||
last_error: null,
|
||||
progress_text: 'checking current output',
|
||||
progress_updated_at: '2026-04-26T05:20:00.000Z',
|
||||
},
|
||||
];
|
||||
const attempts: PairedTurnAttemptRecord[] = [
|
||||
{
|
||||
attempt_id: 'paired-room-1:reviewer-turn:attempt:2',
|
||||
parent_attempt_id: null,
|
||||
parent_handoff_id: null,
|
||||
continuation_handoff_id: null,
|
||||
turn_id: 'paired-room-1:reviewer-turn',
|
||||
task_id: pairedTask.id,
|
||||
task_updated_at: pairedTask.updated_at,
|
||||
role: 'reviewer',
|
||||
intent_kind: 'reviewer-turn',
|
||||
state: 'running',
|
||||
executor_service_id: 'claude-reviewer',
|
||||
executor_agent_type: 'claude-code',
|
||||
active_run_id: 'run-reviewer-1',
|
||||
attempt_no: 2,
|
||||
created_at: '2026-04-26T05:19:00.000Z',
|
||||
updated_at: '2026-04-26T05:21:00.000Z',
|
||||
completed_at: null,
|
||||
last_error: 'OPENAI_API_KEY=plain-secret-value',
|
||||
},
|
||||
];
|
||||
const outputs: PairedTurnOutput[] = [
|
||||
{
|
||||
id: 1,
|
||||
task_id: pairedTask.id,
|
||||
turn_number: 1,
|
||||
role: 'owner',
|
||||
output_text: 'owner final output',
|
||||
verdict: 'step_done',
|
||||
created_at: '2026-04-26T05:18:00.000Z',
|
||||
},
|
||||
];
|
||||
const messages: NewMessage[] = [
|
||||
{
|
||||
id: 'msg-1',
|
||||
chat_jid: 'dc:ops',
|
||||
sender: 'u1',
|
||||
sender_name: '눈쟁이',
|
||||
content: '진행 어디까지야? BOT_TOKEN=plain-secret-value',
|
||||
timestamp: '2026-04-26T05:17:00.000Z',
|
||||
is_from_me: false,
|
||||
is_bot_message: false,
|
||||
message_source_kind: 'human',
|
||||
},
|
||||
];
|
||||
const requestedMessageLimits: number[] = [];
|
||||
const response = handleRoomTimelineRoute({
|
||||
url: new URL(
|
||||
`http://localhost/api/rooms/${encodeURIComponent('dc:ops')}/timeline`,
|
||||
),
|
||||
request: new Request('http://localhost'),
|
||||
jsonResponse,
|
||||
...roomDeps({
|
||||
loadLatestPairedTaskForChat: () => pairedTask,
|
||||
loadPairedTurnsForTask: () => turns,
|
||||
loadPairedTurnAttempts: () => attempts,
|
||||
loadPairedTurnOutputs: () => outputs,
|
||||
loadRecentDeliveredWorkItemsForChat: () => [workItem()],
|
||||
loadRecentChatMessages: (_jid, limit) => {
|
||||
requestedMessageLimits.push(limit ?? 20);
|
||||
return messages;
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
expect(response?.status).toBe(200);
|
||||
const body = (await response?.json()) as {
|
||||
pairedTask: {
|
||||
currentTurn: { lastError: string; progressText: string };
|
||||
outputs: Array<{ outputText: string }>;
|
||||
};
|
||||
messages: Array<{ content: string; senderName: string }>;
|
||||
};
|
||||
expect(body.pairedTask.currentTurn).toMatchObject({
|
||||
lastError: 'OPENAI_API_KEY=<redacted>',
|
||||
progressText: 'checking current output',
|
||||
});
|
||||
expect(body.pairedTask.outputs).toEqual([]);
|
||||
expect(requestedMessageLimits).toEqual([8]);
|
||||
expect(body.messages).toEqual([
|
||||
expect.objectContaining({
|
||||
content: expect.stringContaining('BOT_TOKEN=<redacted>'),
|
||||
senderName: '눈쟁이',
|
||||
}),
|
||||
expect.objectContaining({
|
||||
content: 'owner final output',
|
||||
senderName: 'owner',
|
||||
}),
|
||||
]);
|
||||
expect(body.messages[0]).toMatchObject({
|
||||
content: expect.stringContaining('BOT_TOKEN=<redacted>'),
|
||||
senderName: '눈쟁이',
|
||||
});
|
||||
});
|
||||
|
||||
it('serves cached room timelines and falls through outside room routes', async () => {
|
||||
const pairedTask = makePairedTask({ id: 'paired-cache-1' });
|
||||
const response = handleRoomTimelineRoute({
|
||||
url: new URL('http://localhost/api/rooms-timeline'),
|
||||
request: new Request('http://localhost/api/rooms-timeline', {
|
||||
headers: { 'accept-encoding': 'gzip' },
|
||||
}),
|
||||
jsonResponse,
|
||||
...roomDeps({
|
||||
readSnapshots: () => [snapshot('2026-04-26T06:22:00.000Z')],
|
||||
loadLatestPairedTaskForChat: () => pairedTask,
|
||||
loadLatestPairedTurnForTask: () => null,
|
||||
loadRecentChatMessages: () => [
|
||||
{
|
||||
id: 'msg-cache',
|
||||
chat_jid: 'dc:ops',
|
||||
sender: 'u1',
|
||||
sender_name: '눈쟁이',
|
||||
content: 'cache message',
|
||||
timestamp: '2026-04-26T06:17:00.000Z',
|
||||
is_from_me: false,
|
||||
is_bot_message: false,
|
||||
message_source_kind: 'human',
|
||||
},
|
||||
],
|
||||
}),
|
||||
});
|
||||
|
||||
expect(response?.status).toBe(200);
|
||||
expect(response?.headers.get('content-encoding')).toBe('gzip');
|
||||
const bytes = new Uint8Array(await response!.arrayBuffer());
|
||||
const body = JSON.parse(
|
||||
new TextDecoder().decode(gunzipSync(bytes)),
|
||||
) as Record<string, { pairedTask: { id: string } }>;
|
||||
expect(body['dc:ops']?.pairedTask.id).toBe('paired-cache-1');
|
||||
expect(
|
||||
handleRoomTimelineRoute({
|
||||
url: new URL('http://localhost/api/overview'),
|
||||
request: new Request('http://localhost/api/overview'),
|
||||
jsonResponse,
|
||||
...roomDeps(),
|
||||
}),
|
||||
).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,355 +0,0 @@
|
||||
import { gzipSync } from 'node:zlib';
|
||||
|
||||
import type {
|
||||
PairedTurnAttemptRecord,
|
||||
PairedTurnRecord,
|
||||
WorkItem,
|
||||
} from './db.js';
|
||||
import type { StatusSnapshot } from './status-dashboard.js';
|
||||
import type { NewMessage, PairedTask, PairedTurnOutput } from './types.js';
|
||||
import {
|
||||
buildWebDashboardRoomActivity,
|
||||
type WebDashboardRoomActivity,
|
||||
} from './web-dashboard-data.js';
|
||||
|
||||
type JsonResponse = (
|
||||
value: unknown,
|
||||
init?: ResponseInit,
|
||||
request?: Request,
|
||||
) => Response;
|
||||
|
||||
export interface RoomsTimelineRouteDependencies {
|
||||
statusMaxAgeMs: number;
|
||||
readSnapshots: (maxAgeMs: number) => StatusSnapshot[];
|
||||
loadLatestPairedTaskForChat: (
|
||||
chatJid: string,
|
||||
) => PairedTask | null | undefined;
|
||||
loadPairedTurnsForTask: (taskId: string) => PairedTurnRecord[];
|
||||
loadLatestPairedTurnForTask: (
|
||||
taskId: string,
|
||||
) => PairedTurnRecord | null | undefined;
|
||||
loadPairedTurnAttempts: (turnId: string) => PairedTurnAttemptRecord[];
|
||||
loadPairedTurnOutputs: (taskId: string) => PairedTurnOutput[];
|
||||
loadRecentPairedTurnOutputsForChat: (
|
||||
chatJid: string,
|
||||
limit: number,
|
||||
) => PairedTurnOutput[];
|
||||
loadRecentDeliveredWorkItemsForChat: (
|
||||
chatJid: string,
|
||||
limit: number,
|
||||
) => WorkItem[];
|
||||
loadRecentChatMessages: (chatJid: string, limit?: number) => NewMessage[];
|
||||
}
|
||||
|
||||
interface RoomsTimelineRouteContext extends RoomsTimelineRouteDependencies {
|
||||
url: URL;
|
||||
request: Request;
|
||||
jsonResponse: JsonResponse;
|
||||
}
|
||||
|
||||
interface RoomsTimelineCache {
|
||||
key: string;
|
||||
builtAt: number;
|
||||
rawJson: string;
|
||||
gzipBuffer: Uint8Array;
|
||||
}
|
||||
|
||||
const ROOMS_TIMELINE_BG_INTERVAL_MS = 2000;
|
||||
|
||||
let roomsTimelineCache: RoomsTimelineCache | null = null;
|
||||
|
||||
function parseRoomTimelinePath(pathname: string): string | null {
|
||||
const match = pathname.match(/^\/api\/rooms\/([^/]+)\/timeline$/);
|
||||
if (!match) return null;
|
||||
try {
|
||||
return decodeURIComponent(match[1]);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function isReadMethod(method: string): boolean {
|
||||
return method === 'GET' || method === 'HEAD';
|
||||
}
|
||||
|
||||
function latestSnapshotEntry(
|
||||
snapshots: StatusSnapshot[],
|
||||
jid: string,
|
||||
):
|
||||
| { snapshot: StatusSnapshot; entry: StatusSnapshot['entries'][number] }
|
||||
| undefined {
|
||||
return snapshots
|
||||
.flatMap((snapshot) =>
|
||||
snapshot.entries
|
||||
.filter((entry) => entry.jid === jid)
|
||||
.map((entry) => ({ snapshot, entry })),
|
||||
)
|
||||
.sort((a, b) => b.snapshot.updatedAt.localeCompare(a.snapshot.updatedAt))
|
||||
.at(0);
|
||||
}
|
||||
|
||||
function buildRoomActivity(
|
||||
deps: RoomsTimelineRouteDependencies,
|
||||
snapshot: StatusSnapshot,
|
||||
entry: StatusSnapshot['entries'][number],
|
||||
): WebDashboardRoomActivity {
|
||||
const pairedTask = deps.loadLatestPairedTaskForChat(entry.jid) ?? null;
|
||||
const turns = pairedTask ? deps.loadPairedTurnsForTask(pairedTask.id) : [];
|
||||
const attempts = turns.flatMap((turn) =>
|
||||
deps.loadPairedTurnAttempts(turn.turn_id),
|
||||
);
|
||||
return buildWebDashboardRoomActivity({
|
||||
serviceId: snapshot.serviceId,
|
||||
entry,
|
||||
pairedTask,
|
||||
turns,
|
||||
attempts,
|
||||
outputs: pairedTask ? deps.loadPairedTurnOutputs(pairedTask.id) : [],
|
||||
outboundItems: deps.loadRecentDeliveredWorkItemsForChat(entry.jid, 12),
|
||||
messages: deps.loadRecentChatMessages(entry.jid, 8),
|
||||
});
|
||||
}
|
||||
|
||||
export function buildRoomsTimelineResult(
|
||||
deps: RoomsTimelineRouteDependencies,
|
||||
): Record<string, WebDashboardRoomActivity> {
|
||||
const snapshots = deps.readSnapshots(deps.statusMaxAgeMs);
|
||||
const uniqueByJid = new Map<
|
||||
string,
|
||||
{
|
||||
snapshot: StatusSnapshot;
|
||||
entry: StatusSnapshot['entries'][number];
|
||||
}
|
||||
>();
|
||||
for (const snapshot of snapshots) {
|
||||
for (const entry of snapshot.entries) {
|
||||
const existing = uniqueByJid.get(entry.jid);
|
||||
if (
|
||||
!existing ||
|
||||
existing.snapshot.updatedAt.localeCompare(snapshot.updatedAt) < 0
|
||||
) {
|
||||
uniqueByJid.set(entry.jid, { snapshot, entry });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const result: Record<string, WebDashboardRoomActivity> = {};
|
||||
for (const [jid, { snapshot, entry }] of uniqueByJid) {
|
||||
const pairedTask = deps.loadLatestPairedTaskForChat(jid) ?? null;
|
||||
const messages = deps.loadRecentChatMessages(jid, 8);
|
||||
const outputs = deps.loadRecentPairedTurnOutputsForChat(jid, 8);
|
||||
const outboundItems = deps.loadRecentDeliveredWorkItemsForChat(jid, 8);
|
||||
if (
|
||||
!pairedTask &&
|
||||
messages.length === 0 &&
|
||||
outputs.length === 0 &&
|
||||
outboundItems.length === 0
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const latestTurn = pairedTask
|
||||
? deps.loadLatestPairedTurnForTask(pairedTask.id)
|
||||
: null;
|
||||
const turns = latestTurn ? [latestTurn] : [];
|
||||
result[jid] = buildWebDashboardRoomActivity({
|
||||
serviceId: snapshot.serviceId,
|
||||
entry,
|
||||
pairedTask,
|
||||
turns,
|
||||
attempts: [],
|
||||
outputs,
|
||||
outboundItems,
|
||||
messages,
|
||||
outputLimit: 8,
|
||||
});
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function computeRoomsCacheKey(deps: RoomsTimelineRouteDependencies): string {
|
||||
return deps
|
||||
.readSnapshots(deps.statusMaxAgeMs)
|
||||
.map((s) => s.updatedAt)
|
||||
.sort()
|
||||
.join('|');
|
||||
}
|
||||
|
||||
export function ensureRoomsTimelineCache(
|
||||
deps: RoomsTimelineRouteDependencies,
|
||||
): RoomsTimelineCache {
|
||||
const key = computeRoomsCacheKey(deps);
|
||||
const result = buildRoomsTimelineResult(deps);
|
||||
const rawJson = JSON.stringify(result);
|
||||
const gzipBuffer = gzipSync(new TextEncoder().encode(rawJson));
|
||||
roomsTimelineCache = {
|
||||
key,
|
||||
builtAt: Date.now(),
|
||||
rawJson,
|
||||
gzipBuffer,
|
||||
};
|
||||
return roomsTimelineCache;
|
||||
}
|
||||
|
||||
export function startRoomsTimelineCacheRefresh(
|
||||
deps: RoomsTimelineRouteDependencies,
|
||||
): void {
|
||||
setTimeout(() => {
|
||||
try {
|
||||
ensureRoomsTimelineCache(deps);
|
||||
} catch {
|
||||
/* warm-up failure is non-fatal */
|
||||
}
|
||||
}, 0);
|
||||
setInterval(() => {
|
||||
try {
|
||||
ensureRoomsTimelineCache(deps);
|
||||
} catch {
|
||||
/* refresh failure is non-fatal */
|
||||
}
|
||||
}, ROOMS_TIMELINE_BG_INTERVAL_MS).unref();
|
||||
}
|
||||
|
||||
function createRoomsTimelineStream(
|
||||
deps: RoomsTimelineRouteDependencies,
|
||||
request: Request,
|
||||
): ReadableStream<Uint8Array> {
|
||||
const encoder = new TextEncoder();
|
||||
return new ReadableStream({
|
||||
start(controller) {
|
||||
let lastBuiltAt = 0;
|
||||
let closed = false;
|
||||
|
||||
const enqueue = (chunk: string) => {
|
||||
if (closed) return;
|
||||
try {
|
||||
controller.enqueue(encoder.encode(chunk));
|
||||
} catch {
|
||||
closed = true;
|
||||
}
|
||||
};
|
||||
|
||||
enqueue(`retry: 3000\n\n`);
|
||||
try {
|
||||
const cache = ensureRoomsTimelineCache(deps);
|
||||
lastBuiltAt = cache.builtAt;
|
||||
enqueue(`event: rooms-timeline\ndata: ${cache.rawJson}\n\n`);
|
||||
} catch {
|
||||
/* warm-up failure is non-fatal */
|
||||
}
|
||||
|
||||
const tick = () => {
|
||||
if (closed) return;
|
||||
try {
|
||||
const cache = ensureRoomsTimelineCache(deps);
|
||||
if (cache.builtAt !== lastBuiltAt) {
|
||||
lastBuiltAt = cache.builtAt;
|
||||
enqueue(`event: rooms-timeline\ndata: ${cache.rawJson}\n\n`);
|
||||
} else {
|
||||
enqueue(`: ping ${Date.now()}\n\n`);
|
||||
}
|
||||
} catch {
|
||||
/* skip this tick */
|
||||
}
|
||||
};
|
||||
|
||||
const interval = setInterval(tick, 1500);
|
||||
const close = () => {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
clearInterval(interval);
|
||||
try {
|
||||
controller.close();
|
||||
} catch {
|
||||
/* already closed */
|
||||
}
|
||||
};
|
||||
request.signal.addEventListener('abort', close);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function handleRoomsStream(
|
||||
deps: RoomsTimelineRouteDependencies,
|
||||
request: Request,
|
||||
jsonResponse: JsonResponse,
|
||||
): Response {
|
||||
if (!isReadMethod(request.method)) {
|
||||
return jsonResponse({ error: 'Method not allowed' }, { status: 405 });
|
||||
}
|
||||
return new Response(createRoomsTimelineStream(deps, request), {
|
||||
headers: {
|
||||
'content-type': 'text/event-stream; charset=utf-8',
|
||||
'cache-control': 'no-cache, no-transform',
|
||||
connection: 'keep-alive',
|
||||
'x-accel-buffering': 'no',
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function handleRoomsTimelineSnapshot(
|
||||
deps: RoomsTimelineRouteDependencies,
|
||||
request: Request,
|
||||
jsonResponse: JsonResponse,
|
||||
): Response {
|
||||
if (!isReadMethod(request.method)) {
|
||||
return jsonResponse({ error: 'Method not allowed' }, { status: 405 });
|
||||
}
|
||||
const cache = ensureRoomsTimelineCache(deps);
|
||||
const acceptsGzip =
|
||||
request.headers.get('accept-encoding')?.includes('gzip') ?? false;
|
||||
if (acceptsGzip) {
|
||||
return new Response(cache.gzipBuffer, {
|
||||
headers: {
|
||||
'content-type': 'application/json; charset=utf-8',
|
||||
'content-encoding': 'gzip',
|
||||
vary: 'accept-encoding',
|
||||
'x-cache-age': String(Date.now() - cache.builtAt),
|
||||
},
|
||||
});
|
||||
}
|
||||
return new Response(cache.rawJson, {
|
||||
headers: {
|
||||
'content-type': 'application/json; charset=utf-8',
|
||||
'x-cache-age': String(Date.now() - cache.builtAt),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function handleSingleRoomTimeline({
|
||||
request,
|
||||
jsonResponse,
|
||||
...deps
|
||||
}: RoomsTimelineRouteContext & { timelineRoomJid: string }): Response {
|
||||
if (!isReadMethod(request.method)) {
|
||||
return jsonResponse({ error: 'Method not allowed' }, { status: 405 });
|
||||
}
|
||||
|
||||
const snapshots = deps.readSnapshots(deps.statusMaxAgeMs);
|
||||
const matched = latestSnapshotEntry(snapshots, deps.timelineRoomJid);
|
||||
if (!matched) {
|
||||
return jsonResponse({ error: 'Room timeline not found' }, { status: 404 });
|
||||
}
|
||||
|
||||
return jsonResponse(buildRoomActivity(deps, matched.snapshot, matched.entry));
|
||||
}
|
||||
|
||||
export function handleRoomTimelineRoute(
|
||||
context: RoomsTimelineRouteContext,
|
||||
): Response | null {
|
||||
const timelineRoomJid = parseRoomTimelinePath(context.url.pathname);
|
||||
if (timelineRoomJid) {
|
||||
return handleSingleRoomTimeline({ ...context, timelineRoomJid });
|
||||
}
|
||||
if (context.url.pathname === '/api/stream') {
|
||||
return handleRoomsStream(context, context.request, context.jsonResponse);
|
||||
}
|
||||
if (context.url.pathname === '/api/rooms-timeline') {
|
||||
return handleRoomsTimelineSnapshot(
|
||||
context,
|
||||
context.request,
|
||||
context.jsonResponse,
|
||||
);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -1,100 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import type { StatusSnapshot } from './status-dashboard.js';
|
||||
import type { ScheduledTask } from './types.js';
|
||||
import { handleSimpleGetRoute } from './web-dashboard-routes.js';
|
||||
|
||||
function jsonResponse(value: unknown, init?: ResponseInit): Response {
|
||||
return new Response(JSON.stringify(value), {
|
||||
...init,
|
||||
headers: {
|
||||
'content-type': 'application/json; charset=utf-8',
|
||||
...(init?.headers as Record<string, string> | undefined),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function makeTask(overrides: Partial<ScheduledTask> = {}): ScheduledTask {
|
||||
return {
|
||||
id: 'task-1',
|
||||
group_folder: 'general',
|
||||
chat_jid: 'dc:general',
|
||||
agent_type: null,
|
||||
status_message_id: null,
|
||||
status_started_at: null,
|
||||
prompt: 'regular scheduled task',
|
||||
schedule_type: 'cron',
|
||||
schedule_value: '* * * * *',
|
||||
context_mode: 'group',
|
||||
next_run: '2026-04-26T05:00:00.000Z',
|
||||
last_run: null,
|
||||
last_result: null,
|
||||
status: 'active',
|
||||
created_at: '2026-04-26T04:00:00.000Z',
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe('web dashboard simple routes', () => {
|
||||
const snapshots: StatusSnapshot[] = [
|
||||
{
|
||||
serviceId: 'codex-main',
|
||||
agentType: 'codex',
|
||||
assistantName: 'Codex',
|
||||
updatedAt: '2026-04-26T05:00:00.000Z',
|
||||
entries: [],
|
||||
},
|
||||
];
|
||||
|
||||
it('serves health, snapshots, and task JSON routes', async () => {
|
||||
const routeContext = {
|
||||
statusMaxAgeMs: 1234,
|
||||
readSnapshots: (maxAgeMs: number) => {
|
||||
expect(maxAgeMs).toBe(1234);
|
||||
return snapshots;
|
||||
},
|
||||
loadTasks: () => [makeTask()],
|
||||
jsonResponse,
|
||||
};
|
||||
|
||||
const health = handleSimpleGetRoute({
|
||||
...routeContext,
|
||||
url: new URL('http://localhost/api/health'),
|
||||
});
|
||||
expect(health?.status).toBe(200);
|
||||
await expect(health?.json()).resolves.toEqual({ ok: true });
|
||||
|
||||
const status = handleSimpleGetRoute({
|
||||
...routeContext,
|
||||
url: new URL('http://localhost/api/status-snapshots'),
|
||||
});
|
||||
expect(status?.status).toBe(200);
|
||||
await expect(status?.json()).resolves.toEqual(snapshots);
|
||||
|
||||
const tasks = handleSimpleGetRoute({
|
||||
...routeContext,
|
||||
url: new URL('http://localhost/api/tasks'),
|
||||
});
|
||||
expect(tasks?.status).toBe(200);
|
||||
await expect(tasks?.json()).resolves.toMatchObject([
|
||||
{
|
||||
id: 'task-1',
|
||||
groupFolder: 'general',
|
||||
promptPreview: 'regular scheduled task',
|
||||
status: 'active',
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it('returns null for routes outside the simple table', () => {
|
||||
const result = handleSimpleGetRoute({
|
||||
url: new URL('http://localhost/api/overview'),
|
||||
statusMaxAgeMs: 1234,
|
||||
readSnapshots: () => [],
|
||||
loadTasks: () => [],
|
||||
jsonResponse,
|
||||
});
|
||||
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,35 +0,0 @@
|
||||
import type { StatusSnapshot } from './status-dashboard.js';
|
||||
import type { ScheduledTask } from './types.js';
|
||||
import { sanitizeScheduledTask } from './web-dashboard-data.js';
|
||||
import { serveValidatedAttachment } from './web-dashboard-attachments.js';
|
||||
|
||||
type JsonResponse = (
|
||||
value: unknown,
|
||||
init?: ResponseInit,
|
||||
request?: Request,
|
||||
) => Response;
|
||||
|
||||
interface SimpleGetRouteContext {
|
||||
url: URL;
|
||||
statusMaxAgeMs: number;
|
||||
readSnapshots: (maxAgeMs: number) => StatusSnapshot[];
|
||||
loadTasks: () => ScheduledTask[];
|
||||
jsonResponse: JsonResponse;
|
||||
}
|
||||
|
||||
export function handleSimpleGetRoute({
|
||||
url,
|
||||
statusMaxAgeMs,
|
||||
readSnapshots,
|
||||
loadTasks,
|
||||
jsonResponse,
|
||||
}: SimpleGetRouteContext): Response | null {
|
||||
const simpleGetRoutes: Record<string, () => Response> = {
|
||||
'/api/health': () => jsonResponse({ ok: true }),
|
||||
'/api/status-snapshots': () => jsonResponse(readSnapshots(statusMaxAgeMs)),
|
||||
'/api/tasks': () => jsonResponse(loadTasks().map(sanitizeScheduledTask)),
|
||||
'/api/attachments': () => serveValidatedAttachment(url),
|
||||
};
|
||||
const route = simpleGetRoutes[url.pathname];
|
||||
return route ? route() : null;
|
||||
}
|
||||
@@ -1,396 +0,0 @@
|
||||
import fs from 'fs';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
|
||||
import { afterEach, describe, expect, it } from 'vitest';
|
||||
|
||||
import type { NewMessage, PairedTask, RegisteredGroup } from './types.js';
|
||||
import {
|
||||
assertDashboardAuthPosture,
|
||||
createWebDashboardHandler,
|
||||
} from './web-dashboard-server.js';
|
||||
|
||||
const tempDirs: string[] = [];
|
||||
|
||||
function makePairedTask(overrides: Partial<PairedTask>): PairedTask {
|
||||
return {
|
||||
id: 'paired-1',
|
||||
chat_jid: 'dc:general',
|
||||
group_folder: 'general',
|
||||
owner_service_id: 'codex-main',
|
||||
reviewer_service_id: 'claude-reviewer',
|
||||
owner_agent_type: 'codex',
|
||||
reviewer_agent_type: 'claude-code',
|
||||
arbiter_agent_type: 'codex',
|
||||
title: 'Dashboard PR',
|
||||
source_ref: null,
|
||||
plan_notes: null,
|
||||
review_requested_at: null,
|
||||
round_trip_count: 0,
|
||||
owner_failure_count: 0,
|
||||
owner_step_done_streak: 0,
|
||||
finalize_step_done_count: 0,
|
||||
task_done_then_user_reopen_count: 0,
|
||||
empty_step_done_streak: 0,
|
||||
status: 'review_ready',
|
||||
arbiter_verdict: null,
|
||||
arbiter_requested_at: null,
|
||||
completion_reason: null,
|
||||
created_at: '2026-04-26T04:00:00.000Z',
|
||||
updated_at: '2026-04-26T04:30:00.000Z',
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
for (const dir of tempDirs.splice(0)) {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
describe('assertDashboardAuthPosture', () => {
|
||||
it('allows loopback binding without a token', () => {
|
||||
expect(() => assertDashboardAuthPosture('127.0.0.1', '')).not.toThrow();
|
||||
expect(() => assertDashboardAuthPosture('localhost', '')).not.toThrow();
|
||||
});
|
||||
|
||||
it('allows any host when a token is set', () => {
|
||||
expect(() => assertDashboardAuthPosture('0.0.0.0', 'secret')).not.toThrow();
|
||||
expect(() =>
|
||||
assertDashboardAuthPosture('203.0.113.5', 'secret'),
|
||||
).not.toThrow();
|
||||
});
|
||||
|
||||
it('warns but starts on a private / tailnet host without a token', () => {
|
||||
expect(() =>
|
||||
assertDashboardAuthPosture('100.101.210.95', ''),
|
||||
).not.toThrow();
|
||||
expect(() => assertDashboardAuthPosture('192.168.1.10', '')).not.toThrow();
|
||||
});
|
||||
|
||||
it('refuses a public / all-interface bind without a token', () => {
|
||||
expect(() => assertDashboardAuthPosture('0.0.0.0', '')).toThrow(
|
||||
/WEB_DASHBOARD_TOKEN/,
|
||||
);
|
||||
expect(() => assertDashboardAuthPosture('203.0.113.5', '')).toThrow(
|
||||
/WEB_DASHBOARD_TOKEN/,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('web dashboard server handler', () => {
|
||||
it('serves health and overview JSON without requiring Discord', async () => {
|
||||
const handler = createWebDashboardHandler({
|
||||
readStatusSnapshots: () => [],
|
||||
getTasks: () => [],
|
||||
getPairedTasks: () => [],
|
||||
startBackgroundCacheRefresh: false,
|
||||
});
|
||||
|
||||
const health = await handler(new Request('http://localhost/api/health'));
|
||||
expect(health.status).toBe(200);
|
||||
await expect(health.json()).resolves.toEqual({ ok: true });
|
||||
|
||||
const overview = await handler(
|
||||
new Request('http://localhost/api/overview'),
|
||||
);
|
||||
expect(overview.status).toBe(200);
|
||||
const body = (await overview.json()) as {
|
||||
rooms: { total: number };
|
||||
tasks: { total: number };
|
||||
inbox: unknown[];
|
||||
};
|
||||
expect(body.rooms.total).toBe(0);
|
||||
expect(body.tasks.total).toBe(0);
|
||||
expect(body.inbox).toEqual([]);
|
||||
});
|
||||
|
||||
it('shares inbox dismiss state with overview JSON', async () => {
|
||||
const pairedTask = makePairedTask({
|
||||
chat_jid: 'dc:ops',
|
||||
group_folder: 'ops',
|
||||
id: 'merge-1',
|
||||
status: 'merge_ready',
|
||||
updated_at: '2026-04-26T05:00:00.000Z',
|
||||
});
|
||||
const handler = createWebDashboardHandler({
|
||||
readStatusSnapshots: () => [],
|
||||
getTasks: () => [],
|
||||
getPairedTasks: () => [pairedTask],
|
||||
now: () => '2026-04-26T05:10:00.000Z',
|
||||
startBackgroundCacheRefresh: false,
|
||||
});
|
||||
|
||||
const firstOverview = await handler(
|
||||
new Request('http://localhost/api/overview'),
|
||||
);
|
||||
expect(firstOverview.status).toBe(200);
|
||||
const firstBody = (await firstOverview.json()) as {
|
||||
inbox: Array<{ id: string; lastOccurredAt: string }>;
|
||||
};
|
||||
expect(firstBody.inbox).toHaveLength(1);
|
||||
|
||||
const dismiss = await handler(
|
||||
new Request(
|
||||
`http://localhost/api/inbox/${encodeURIComponent(firstBody.inbox[0]!.id)}/actions`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
action: 'dismiss',
|
||||
lastOccurredAt: firstBody.inbox[0]!.lastOccurredAt,
|
||||
}),
|
||||
},
|
||||
),
|
||||
);
|
||||
expect(dismiss.status).toBe(200);
|
||||
|
||||
const dismissedOverview = await handler(
|
||||
new Request('http://localhost/api/overview'),
|
||||
);
|
||||
await expect(dismissedOverview.json()).resolves.toMatchObject({
|
||||
inbox: [],
|
||||
});
|
||||
|
||||
pairedTask.updated_at = '2026-04-26T05:01:00.000Z';
|
||||
const changedOverview = await handler(
|
||||
new Request('http://localhost/api/overview'),
|
||||
);
|
||||
const changedBody = (await changedOverview.json()) as { inbox: unknown[] };
|
||||
expect(changedBody.inbox).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('shares service restart records with overview JSON', async () => {
|
||||
let restartCalls = 0;
|
||||
const handler = createWebDashboardHandler({
|
||||
readStatusSnapshots: () => [],
|
||||
getTasks: () => [],
|
||||
getPairedTasks: () => [],
|
||||
restartServiceStack: () => {
|
||||
restartCalls += 1;
|
||||
return ['ejclaw'];
|
||||
},
|
||||
now: () => '2026-04-26T05:30:00.000Z',
|
||||
startBackgroundCacheRefresh: false,
|
||||
});
|
||||
|
||||
const restart = await handler(
|
||||
new Request('http://localhost/api/services/stack/actions', {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
action: 'restart',
|
||||
requestId: 'stack-restart-1',
|
||||
}),
|
||||
}),
|
||||
);
|
||||
expect(restart.status).toBe(200);
|
||||
expect(restartCalls).toBe(1);
|
||||
|
||||
const overview = await handler(
|
||||
new Request('http://localhost/api/overview'),
|
||||
);
|
||||
await expect(overview.json()).resolves.toMatchObject({
|
||||
operations: {
|
||||
serviceRestarts: [
|
||||
{
|
||||
id: 'web-restart-stack-restart-1',
|
||||
status: 'success',
|
||||
services: ['ejclaw'],
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('wires room message injection dependencies', async () => {
|
||||
const messages: NewMessage[] = [];
|
||||
const metadata: Array<{
|
||||
chatJid: string;
|
||||
timestamp: string;
|
||||
name?: string;
|
||||
channel?: string;
|
||||
isGroup?: boolean;
|
||||
}> = [];
|
||||
const queued: Array<{ chatJid: string; groupFolder: string }> = [];
|
||||
const rooms: Record<string, RegisteredGroup> = {
|
||||
'dc:ops': {
|
||||
name: '#ops',
|
||||
folder: 'ops-room',
|
||||
added_at: '2026-04-26T05:00:00.000Z',
|
||||
},
|
||||
};
|
||||
const handler = createWebDashboardHandler({
|
||||
readStatusSnapshots: () => [],
|
||||
getTasks: () => [],
|
||||
getPairedTasks: () => [],
|
||||
getRoomBindings: () => rooms,
|
||||
storeChatMetadata: (chatJid, timestamp, name, channel, isGroup) => {
|
||||
metadata.push({ chatJid, timestamp, name, channel, isGroup });
|
||||
},
|
||||
storeMessage: (message) => {
|
||||
messages.push(message);
|
||||
},
|
||||
hasMessage: () => false,
|
||||
enqueueMessageCheck: (chatJid, groupFolder) => {
|
||||
queued.push({ chatJid, groupFolder });
|
||||
},
|
||||
now: () => '2026-04-26T05:10:00.000Z',
|
||||
startBackgroundCacheRefresh: false,
|
||||
});
|
||||
|
||||
const response = await handler(
|
||||
new Request(
|
||||
`http://localhost/api/rooms/${encodeURIComponent('dc:ops')}/messages`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
requestId: 'room-compose-1',
|
||||
text: ' run a dashboard check ',
|
||||
}),
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
await expect(response.json()).resolves.toMatchObject({
|
||||
id: 'web-room-compose-1',
|
||||
ok: true,
|
||||
queued: true,
|
||||
});
|
||||
expect(metadata).toEqual([
|
||||
{
|
||||
chatJid: 'dc:ops',
|
||||
timestamp: '2026-04-26T05:10:00.000Z',
|
||||
name: '#ops',
|
||||
channel: 'web-dashboard',
|
||||
isGroup: true,
|
||||
},
|
||||
]);
|
||||
expect(messages).toHaveLength(1);
|
||||
expect(messages[0]).toMatchObject({
|
||||
chat_jid: 'dc:ops',
|
||||
sender_name: 'Web Dashboard',
|
||||
content: 'run a dashboard check',
|
||||
message_source_kind: 'ipc_injected_human',
|
||||
});
|
||||
expect(queued).toEqual([{ chatJid: 'dc:ops', groupFolder: 'ops-room' }]);
|
||||
});
|
||||
|
||||
it('wires room timeline dependencies', async () => {
|
||||
const pairedTask = makePairedTask({
|
||||
id: 'paired-room-1',
|
||||
chat_jid: 'dc:ops',
|
||||
group_folder: 'ops-room',
|
||||
status: 'in_review',
|
||||
round_trip_count: 2,
|
||||
updated_at: '2026-04-26T05:20:00.000Z',
|
||||
});
|
||||
const messages: NewMessage[] = [
|
||||
{
|
||||
id: 'msg-1',
|
||||
chat_jid: 'dc:ops',
|
||||
sender: 'u1',
|
||||
sender_name: '눈쟁이',
|
||||
content: '진행 어디까지야?',
|
||||
timestamp: '2026-04-26T05:17:00.000Z',
|
||||
is_from_me: false,
|
||||
is_bot_message: false,
|
||||
message_source_kind: 'human',
|
||||
},
|
||||
];
|
||||
const requestedMessageLimits: number[] = [];
|
||||
const handler = createWebDashboardHandler({
|
||||
readStatusSnapshots: () => [
|
||||
{
|
||||
serviceId: 'codex-main',
|
||||
agentType: 'codex',
|
||||
assistantName: 'Codex',
|
||||
updatedAt: '2026-04-26T05:22:00.000Z',
|
||||
entries: [
|
||||
{
|
||||
jid: 'dc:ops',
|
||||
name: '#ops',
|
||||
folder: 'ops-room',
|
||||
agentType: 'codex',
|
||||
status: 'processing',
|
||||
elapsedMs: 120_000,
|
||||
pendingMessages: true,
|
||||
pendingTasks: 1,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
getTasks: () => [],
|
||||
getPairedTasks: () => [pairedTask],
|
||||
getLatestPairedTaskForChat: () => pairedTask,
|
||||
getPairedTurnsForTask: () => [],
|
||||
getPairedTurnAttempts: () => [],
|
||||
getPairedTurnOutputs: () => [],
|
||||
getRecentPairedTurnOutputsForChat: () => [],
|
||||
getRecentDeliveredWorkItemsForChat: () => [],
|
||||
getRecentChatMessages: (_jid, limit) => {
|
||||
requestedMessageLimits.push(limit ?? 20);
|
||||
return messages;
|
||||
},
|
||||
startBackgroundCacheRefresh: false,
|
||||
});
|
||||
const response = await handler(
|
||||
new Request(
|
||||
`http://localhost/api/rooms/${encodeURIComponent('dc:ops')}/timeline`,
|
||||
),
|
||||
);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
const body = (await response.json()) as {
|
||||
jid: string;
|
||||
pairedTask: { id: string; roundTripCount: number };
|
||||
messages: Array<{ content: string; senderName: string }>;
|
||||
};
|
||||
expect(body.jid).toBe('dc:ops');
|
||||
expect(body.pairedTask).toMatchObject({
|
||||
id: 'paired-room-1',
|
||||
roundTripCount: 2,
|
||||
});
|
||||
expect(requestedMessageLimits).toEqual([8]);
|
||||
expect(body.messages).toMatchObject([
|
||||
{ content: '진행 어디까지야?', senderName: '눈쟁이' },
|
||||
]);
|
||||
});
|
||||
|
||||
it('serves Vite static assets and falls back to index for SPA routes', async () => {
|
||||
const staticDir = fs.mkdtempSync(
|
||||
path.join(os.tmpdir(), 'ejclaw-dashboard-'),
|
||||
);
|
||||
tempDirs.push(staticDir);
|
||||
fs.writeFileSync(
|
||||
path.join(staticDir, 'index.html'),
|
||||
'<div id="root"></div>',
|
||||
);
|
||||
fs.mkdirSync(path.join(staticDir, 'assets'));
|
||||
fs.writeFileSync(
|
||||
path.join(staticDir, 'assets', 'app.js'),
|
||||
'console.log("ok")',
|
||||
);
|
||||
|
||||
const handler = createWebDashboardHandler({
|
||||
staticDir,
|
||||
readStatusSnapshots: () => [],
|
||||
getTasks: () => [],
|
||||
startBackgroundCacheRefresh: false,
|
||||
});
|
||||
|
||||
const asset = await handler(new Request('http://localhost/assets/app.js'));
|
||||
expect(asset.status).toBe(200);
|
||||
expect(asset.headers.get('content-type')).toContain('text/javascript');
|
||||
await expect(asset.text()).resolves.toContain('console.log');
|
||||
|
||||
const fallback = await handler(
|
||||
new Request('http://localhost/tasks/swarm_123'),
|
||||
);
|
||||
expect(fallback.status).toBe(200);
|
||||
expect(fallback.headers.get('content-type')).toContain('text/html');
|
||||
await expect(fallback.text()).resolves.toContain('root');
|
||||
});
|
||||
});
|
||||
@@ -1,591 +0,0 @@
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import { execFileSync } from 'child_process';
|
||||
import { timingSafeEqual } from 'crypto';
|
||||
|
||||
import { WEB_DASHBOARD } from './config.js';
|
||||
import {
|
||||
createTask,
|
||||
deleteTask,
|
||||
getAllOpenPairedTasks,
|
||||
getAllTasks,
|
||||
getLatestPairedTaskForChat,
|
||||
getPairedTaskById,
|
||||
getPairedTurnAttempts,
|
||||
getPairedTurnOutputs,
|
||||
getRecentPairedTurnOutputsForChat,
|
||||
getPairedTurnsForTask,
|
||||
getLatestPairedTurnForTask,
|
||||
getRecentDeliveredWorkItemsForChat,
|
||||
getRecentChatMessages,
|
||||
getTaskById,
|
||||
hasMessage,
|
||||
storeChatMetadata,
|
||||
storeMessage,
|
||||
updatePairedTaskIfUnchanged,
|
||||
updateTask,
|
||||
} from './db.js';
|
||||
import { logger } from './logger.js';
|
||||
import { schedulePairedFollowUpIntent } from './message-runtime-follow-up.js';
|
||||
import {
|
||||
readStatusSnapshots,
|
||||
type StatusSnapshot,
|
||||
} from './status-dashboard.js';
|
||||
import type {
|
||||
AgentType,
|
||||
NewMessage,
|
||||
PairedTask,
|
||||
RegisteredGroup,
|
||||
ScheduledTask,
|
||||
} from './types.js';
|
||||
import {
|
||||
createInboxDismissTracker,
|
||||
handleInboxActionRoute,
|
||||
type InboxFollowUpScheduler,
|
||||
} from './web-dashboard-inbox-routes.js';
|
||||
import { handleOverviewRoute } from './web-dashboard-overview-routes.js';
|
||||
import {
|
||||
createRoomMessageIdCache,
|
||||
handleRoomMessageRoute,
|
||||
} from './web-dashboard-room-message-routes.js';
|
||||
import {
|
||||
handleRoomTimelineRoute,
|
||||
startRoomsTimelineCacheRefresh,
|
||||
type RoomsTimelineRouteDependencies,
|
||||
} from './web-dashboard-room-routes.js';
|
||||
import { handleSimpleGetRoute } from './web-dashboard-routes.js';
|
||||
import {
|
||||
handleServiceRoute,
|
||||
type ServiceRestartRecord,
|
||||
} from './web-dashboard-service-routes.js';
|
||||
import { handleSettingsRoute } from './web-dashboard-settings-routes.js';
|
||||
import { handleScheduledTaskRoute } from './web-dashboard-task-routes.js';
|
||||
|
||||
const DEFAULT_STATUS_MAX_AGE_MS = 10 * 60 * 1000;
|
||||
const STACK_RESTART_UNIT_NAME = 'ejclaw-stack-restart.service';
|
||||
const MANAGED_SERVICE_CALLER_FALLBACK_MESSAGE =
|
||||
'Stack restart unit is not installed yet. Run setup service from an external shell before retrying from a managed EJClaw service.';
|
||||
const UNIT_NOT_FOUND_PATTERN =
|
||||
/(Unit .* not found|Could not find the requested service|not-found)/i;
|
||||
|
||||
type JsonResponse = (
|
||||
value: unknown,
|
||||
init?: ResponseInit,
|
||||
request?: Request,
|
||||
) => Response;
|
||||
|
||||
export type { ServiceRestartRecord } from './web-dashboard-service-routes.js';
|
||||
|
||||
export interface WebDashboardHandlerOptions {
|
||||
staticDir?: string;
|
||||
statusMaxAgeMs?: number;
|
||||
startBackgroundCacheRefresh?: boolean;
|
||||
readStatusSnapshots?: (maxAgeMs: number) => StatusSnapshot[];
|
||||
getTasks?: () => ScheduledTask[];
|
||||
getTaskById?: (id: string) => ScheduledTask | undefined;
|
||||
updateTask?: (
|
||||
id: string,
|
||||
updates: Partial<
|
||||
Pick<
|
||||
ScheduledTask,
|
||||
| 'prompt'
|
||||
| 'schedule_type'
|
||||
| 'schedule_value'
|
||||
| 'next_run'
|
||||
| 'status'
|
||||
| 'suspended_until'
|
||||
>
|
||||
>,
|
||||
) => void;
|
||||
createTask?: (task: {
|
||||
id: string;
|
||||
group_folder: string;
|
||||
chat_jid: string;
|
||||
agent_type?: AgentType | null;
|
||||
prompt: string;
|
||||
schedule_type: ScheduledTask['schedule_type'];
|
||||
schedule_value: string;
|
||||
context_mode: ScheduledTask['context_mode'];
|
||||
next_run: string | null;
|
||||
status: ScheduledTask['status'];
|
||||
created_at: string;
|
||||
}) => void;
|
||||
deleteTask?: (id: string) => void;
|
||||
getPairedTasks?: () => PairedTask[];
|
||||
getLatestPairedTaskForChat?: (chatJid: string) => PairedTask | undefined;
|
||||
getPairedTurnsForTask?: typeof getPairedTurnsForTask;
|
||||
getLatestPairedTurnForTask?: typeof getLatestPairedTurnForTask;
|
||||
getPairedTurnAttempts?: typeof getPairedTurnAttempts;
|
||||
getPairedTurnOutputs?: typeof getPairedTurnOutputs;
|
||||
getRecentPairedTurnOutputsForChat?: typeof getRecentPairedTurnOutputsForChat;
|
||||
getRecentDeliveredWorkItemsForChat?: typeof getRecentDeliveredWorkItemsForChat;
|
||||
getRecentChatMessages?: typeof getRecentChatMessages;
|
||||
getPairedTaskById?: (id: string) => PairedTask | undefined;
|
||||
updatePairedTaskIfUnchanged?: (
|
||||
id: string,
|
||||
expectedUpdatedAt: string,
|
||||
updates: Partial<
|
||||
Pick<
|
||||
PairedTask,
|
||||
'status' | 'updated_at' | 'arbiter_requested_at' | 'completion_reason'
|
||||
>
|
||||
>,
|
||||
) => boolean;
|
||||
schedulePairedFollowUp?: InboxFollowUpScheduler;
|
||||
getRoomBindings?: () => Record<string, RegisteredGroup>;
|
||||
storeChatMetadata?: (
|
||||
chatJid: string,
|
||||
timestamp: string,
|
||||
name?: string,
|
||||
channel?: string,
|
||||
isGroup?: boolean,
|
||||
) => void;
|
||||
storeMessage?: (message: NewMessage) => void;
|
||||
hasMessage?: (chatJid: string, id: string) => boolean;
|
||||
enqueueMessageCheck?: (chatJid: string, groupFolder: string) => void;
|
||||
nudgeScheduler?: () => void;
|
||||
restartServiceStack?: () => string[];
|
||||
authToken?: string;
|
||||
now?: () => string;
|
||||
}
|
||||
|
||||
export interface StartedWebDashboardServer {
|
||||
url: string;
|
||||
stop: () => void;
|
||||
}
|
||||
|
||||
function jsonResponse(
|
||||
value: unknown,
|
||||
init?: ResponseInit,
|
||||
request?: Request,
|
||||
): Response {
|
||||
const body = JSON.stringify(value);
|
||||
const acceptsGzip =
|
||||
request?.headers.get('accept-encoding')?.includes('gzip') ?? false;
|
||||
const baseHeaders: Record<string, string> = {
|
||||
'content-type': 'application/json; charset=utf-8',
|
||||
...(init?.headers as Record<string, string> | undefined),
|
||||
};
|
||||
if (acceptsGzip && body.length > 1024) {
|
||||
const compressed = Bun.gzipSync(new TextEncoder().encode(body));
|
||||
return new Response(compressed, {
|
||||
...init,
|
||||
headers: {
|
||||
...baseHeaders,
|
||||
'content-encoding': 'gzip',
|
||||
vary: 'accept-encoding',
|
||||
},
|
||||
});
|
||||
}
|
||||
return new Response(body, {
|
||||
...init,
|
||||
headers: baseHeaders,
|
||||
});
|
||||
}
|
||||
|
||||
function getContentType(filePath: string): string {
|
||||
const ext = path.extname(filePath).toLowerCase();
|
||||
switch (ext) {
|
||||
case '.html':
|
||||
return 'text/html; charset=utf-8';
|
||||
case '.js':
|
||||
case '.mjs':
|
||||
return 'text/javascript; charset=utf-8';
|
||||
case '.css':
|
||||
return 'text/css; charset=utf-8';
|
||||
case '.json':
|
||||
return 'application/json; charset=utf-8';
|
||||
case '.svg':
|
||||
return 'image/svg+xml';
|
||||
case '.png':
|
||||
return 'image/png';
|
||||
case '.jpg':
|
||||
case '.jpeg':
|
||||
return 'image/jpeg';
|
||||
case '.webp':
|
||||
return 'image/webp';
|
||||
case '.ico':
|
||||
return 'image/x-icon';
|
||||
default:
|
||||
return 'application/octet-stream';
|
||||
}
|
||||
}
|
||||
|
||||
function resolveStaticFile(staticDir: string, pathname: string): string | null {
|
||||
const normalizedPath = decodeURIComponent(pathname).replace(/^\/+/, '');
|
||||
const candidate = path.resolve(staticDir, normalizedPath || 'index.html');
|
||||
const root = path.resolve(staticDir);
|
||||
if (candidate !== root && !candidate.startsWith(`${root}${path.sep}`)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (fs.existsSync(candidate) && fs.statSync(candidate).isFile()) {
|
||||
return candidate;
|
||||
}
|
||||
|
||||
const indexPath = path.join(root, 'index.html');
|
||||
if (fs.existsSync(indexPath) && fs.statSync(indexPath).isFile()) {
|
||||
return indexPath;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function serveStaticFile(staticDir: string, pathname: string): Response {
|
||||
const filePath = resolveStaticFile(staticDir, pathname);
|
||||
if (!filePath) {
|
||||
return new Response('Not found', { status: 404 });
|
||||
}
|
||||
|
||||
return new Response(fs.readFileSync(filePath), {
|
||||
headers: {
|
||||
'content-type': getContentType(filePath),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function extractDashboardAuthToken(request: Request): string {
|
||||
const authorization = request.headers.get('authorization') ?? '';
|
||||
const bearer = authorization.match(/^Bearer\s+(.+)$/i);
|
||||
if (bearer) return bearer[1]!.trim();
|
||||
return request.headers.get('x-ejclaw-dashboard-token')?.trim() ?? '';
|
||||
}
|
||||
|
||||
function safeTokenEquals(actual: string, expected: string): boolean {
|
||||
const actualBytes = Buffer.from(actual);
|
||||
const expectedBytes = Buffer.from(expected);
|
||||
if (actualBytes.length !== expectedBytes.length) return false;
|
||||
return timingSafeEqual(actualBytes, expectedBytes);
|
||||
}
|
||||
|
||||
function isDashboardApiAuthorized(request: Request, token: string): boolean {
|
||||
if (!token) return true;
|
||||
const actual = extractDashboardAuthToken(request);
|
||||
return Boolean(actual) && safeTokenEquals(actual, token);
|
||||
}
|
||||
|
||||
function rejectUnauthorizedApi(
|
||||
url: URL,
|
||||
request: Request,
|
||||
token: string,
|
||||
jsonResponse: JsonResponse,
|
||||
): Response | null {
|
||||
if (!url.pathname.startsWith('/api/')) return null;
|
||||
if (isDashboardApiAuthorized(request, token)) return null;
|
||||
return jsonResponse(
|
||||
{ error: 'Unauthorized' },
|
||||
{
|
||||
status: 401,
|
||||
headers: { 'www-authenticate': 'Bearer' },
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
function isRoot(): boolean {
|
||||
return typeof process.getuid === 'function' && process.getuid() === 0;
|
||||
}
|
||||
|
||||
function restartEjclawStackServices(): string[] {
|
||||
if (process.platform !== 'linux') {
|
||||
throw new Error('Service restart only supports Linux systemd services');
|
||||
}
|
||||
|
||||
const services = ['ejclaw'];
|
||||
const systemctlArgs = isRoot() ? [] : ['--user'];
|
||||
|
||||
try {
|
||||
execFileSync(
|
||||
'systemctl',
|
||||
[...systemctlArgs, 'start', '--wait', STACK_RESTART_UNIT_NAME],
|
||||
{ stdio: 'ignore' },
|
||||
);
|
||||
} catch (error) {
|
||||
const stderr =
|
||||
error && typeof error === 'object' && 'stderr' in error
|
||||
? String((error as { stderr?: unknown }).stderr || '')
|
||||
: '';
|
||||
const stdout =
|
||||
error && typeof error === 'object' && 'stdout' in error
|
||||
? String((error as { stdout?: unknown }).stdout || '')
|
||||
: '';
|
||||
const message =
|
||||
error instanceof Error ? error.message : `${stdout}\n${stderr}`.trim();
|
||||
const combined = `${message}\n${stdout}\n${stderr}`;
|
||||
if (!UNIT_NOT_FOUND_PATTERN.test(combined)) {
|
||||
throw error;
|
||||
}
|
||||
if (process.env.SERVICE_ID) {
|
||||
throw new Error(MANAGED_SERVICE_CALLER_FALLBACK_MESSAGE, {
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
execFileSync('systemctl', [...systemctlArgs, 'restart', ...services], {
|
||||
stdio: 'ignore',
|
||||
});
|
||||
for (const service of services) {
|
||||
execFileSync(
|
||||
'systemctl',
|
||||
[...systemctlArgs, 'is-active', '--quiet', service],
|
||||
{ stdio: 'ignore' },
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return services;
|
||||
}
|
||||
|
||||
export function createWebDashboardHandler(
|
||||
opts: WebDashboardHandlerOptions = {},
|
||||
): (request: Request) => Response | Promise<Response> {
|
||||
const readSnapshots = opts.readStatusSnapshots ?? readStatusSnapshots;
|
||||
const loadTasks = opts.getTasks ?? getAllTasks;
|
||||
const loadTaskById = opts.getTaskById ?? getTaskById;
|
||||
const mutateTask = opts.updateTask ?? updateTask;
|
||||
const createScheduledTask = opts.createTask ?? createTask;
|
||||
const removeTask = opts.deleteTask ?? deleteTask;
|
||||
const loadPairedTasks = opts.getPairedTasks ?? getAllOpenPairedTasks;
|
||||
const loadPairedTaskById = opts.getPairedTaskById ?? getPairedTaskById;
|
||||
const mutatePairedTaskIfUnchanged =
|
||||
opts.updatePairedTaskIfUnchanged ?? updatePairedTaskIfUnchanged;
|
||||
const loadLatestPairedTaskForChat =
|
||||
opts.getLatestPairedTaskForChat ?? getLatestPairedTaskForChat;
|
||||
const loadPairedTurnsForTask =
|
||||
opts.getPairedTurnsForTask ?? getPairedTurnsForTask;
|
||||
const loadLatestPairedTurnForTask =
|
||||
opts.getLatestPairedTurnForTask ?? getLatestPairedTurnForTask;
|
||||
const loadPairedTurnOutputs =
|
||||
opts.getPairedTurnOutputs ?? getPairedTurnOutputs;
|
||||
const loadRecentPairedTurnOutputsForChat =
|
||||
opts.getRecentPairedTurnOutputsForChat ?? getRecentPairedTurnOutputsForChat;
|
||||
const loadRecentDeliveredWorkItemsForChat =
|
||||
opts.getRecentDeliveredWorkItemsForChat ??
|
||||
getRecentDeliveredWorkItemsForChat;
|
||||
const loadPairedTurnAttempts =
|
||||
opts.getPairedTurnAttempts ?? getPairedTurnAttempts;
|
||||
const loadRecentChatMessages =
|
||||
opts.getRecentChatMessages ?? getRecentChatMessages;
|
||||
const schedulePairedFollowUp =
|
||||
opts.schedulePairedFollowUp ?? schedulePairedFollowUpIntent;
|
||||
const loadRoomBindings = opts.getRoomBindings;
|
||||
const writeChatMetadata = opts.storeChatMetadata ?? storeChatMetadata;
|
||||
const writeMessage = opts.storeMessage ?? storeMessage;
|
||||
const messageExists = opts.hasMessage ?? hasMessage;
|
||||
const enqueueMessageCheck = opts.enqueueMessageCheck;
|
||||
const nudgeScheduler = opts.nudgeScheduler;
|
||||
const restartServiceStack =
|
||||
opts.restartServiceStack ?? restartEjclawStackServices;
|
||||
const statusMaxAgeMs = opts.statusMaxAgeMs ?? DEFAULT_STATUS_MAX_AGE_MS;
|
||||
const authToken = opts.authToken ?? WEB_DASHBOARD.token;
|
||||
const roomsTimelineDeps: RoomsTimelineRouteDependencies = {
|
||||
statusMaxAgeMs,
|
||||
readSnapshots,
|
||||
loadLatestPairedTaskForChat,
|
||||
loadPairedTurnsForTask,
|
||||
loadLatestPairedTurnForTask,
|
||||
loadPairedTurnAttempts,
|
||||
loadPairedTurnOutputs,
|
||||
loadRecentPairedTurnOutputsForChat,
|
||||
loadRecentDeliveredWorkItemsForChat,
|
||||
loadRecentChatMessages,
|
||||
};
|
||||
if (opts.startBackgroundCacheRefresh !== false) {
|
||||
startRoomsTimelineCacheRefresh(roomsTimelineDeps);
|
||||
}
|
||||
const rememberRoomMessageId = createRoomMessageIdCache();
|
||||
const inboxDismissTracker = createInboxDismissTracker();
|
||||
const recentServiceRestarts: ServiceRestartRecord[] = [];
|
||||
const activeServiceRestartTargets = new Set<string>();
|
||||
return async (request: Request): Promise<Response> => {
|
||||
const url = new URL(request.url);
|
||||
const authFailure = rejectUnauthorizedApi(
|
||||
url,
|
||||
request,
|
||||
authToken,
|
||||
jsonResponse,
|
||||
);
|
||||
if (authFailure) return authFailure;
|
||||
const scheduledTaskRoute = await handleScheduledTaskRoute({
|
||||
url,
|
||||
request,
|
||||
jsonResponse,
|
||||
createScheduledTask,
|
||||
loadRoomBindings,
|
||||
loadTaskById,
|
||||
mutateTask,
|
||||
nudgeScheduler,
|
||||
removeTask,
|
||||
now: opts.now,
|
||||
});
|
||||
if (scheduledTaskRoute) return scheduledTaskRoute;
|
||||
const inboxActionRoute = await handleInboxActionRoute({
|
||||
url,
|
||||
request,
|
||||
jsonResponse,
|
||||
dismissTracker: inboxDismissTracker,
|
||||
enqueueMessageCheck,
|
||||
loadPairedTaskById,
|
||||
messageExists,
|
||||
mutatePairedTaskIfUnchanged,
|
||||
schedulePairedFollowUp,
|
||||
writeChatMetadata,
|
||||
writeMessage,
|
||||
now: opts.now,
|
||||
});
|
||||
if (inboxActionRoute) return inboxActionRoute;
|
||||
const roomMessageRoute = await handleRoomMessageRoute({
|
||||
url,
|
||||
request,
|
||||
jsonResponse,
|
||||
enqueueMessageCheck,
|
||||
loadRoomBindings,
|
||||
messageExists,
|
||||
rememberRoomMessageId,
|
||||
writeChatMetadata,
|
||||
writeMessage,
|
||||
now: opts.now,
|
||||
});
|
||||
if (roomMessageRoute) return roomMessageRoute;
|
||||
const roomTimelineRoute = handleRoomTimelineRoute({
|
||||
url,
|
||||
request,
|
||||
jsonResponse,
|
||||
...roomsTimelineDeps,
|
||||
});
|
||||
if (roomTimelineRoute) return roomTimelineRoute;
|
||||
const serviceRoute = await handleServiceRoute({
|
||||
url,
|
||||
request,
|
||||
jsonResponse,
|
||||
recentServiceRestarts,
|
||||
activeServiceRestartTargets,
|
||||
restartServiceStack,
|
||||
now: opts.now,
|
||||
});
|
||||
if (serviceRoute) return serviceRoute;
|
||||
const settingsRoute = await handleSettingsRoute({
|
||||
url,
|
||||
request,
|
||||
jsonResponse,
|
||||
});
|
||||
if (settingsRoute) return settingsRoute;
|
||||
if (request.method !== 'GET' && request.method !== 'HEAD') {
|
||||
return jsonResponse({ error: 'Method not allowed' }, { status: 405 });
|
||||
}
|
||||
const simpleGetRoute = handleSimpleGetRoute({
|
||||
url,
|
||||
statusMaxAgeMs,
|
||||
readSnapshots,
|
||||
loadTasks,
|
||||
jsonResponse,
|
||||
});
|
||||
if (simpleGetRoute) return simpleGetRoute;
|
||||
const overviewRoute = handleOverviewRoute({
|
||||
url,
|
||||
jsonResponse,
|
||||
isInboxItemDismissed: inboxDismissTracker.isDismissed,
|
||||
loadPairedTasks,
|
||||
loadTasks,
|
||||
readSnapshots,
|
||||
recentServiceRestarts,
|
||||
statusMaxAgeMs,
|
||||
now: opts.now,
|
||||
});
|
||||
if (overviewRoute) return overviewRoute;
|
||||
if (url.pathname.startsWith('/api/')) {
|
||||
return jsonResponse({ error: 'Not found' }, { status: 404 });
|
||||
}
|
||||
if (!opts.staticDir) {
|
||||
return new Response('Dashboard static directory is not configured', {
|
||||
status: 404,
|
||||
});
|
||||
}
|
||||
return serveStaticFile(opts.staticDir, url.pathname);
|
||||
};
|
||||
}
|
||||
|
||||
function isLoopbackHost(host: string): boolean {
|
||||
const h = host.replace(/^\[|\]$/g, '').toLowerCase();
|
||||
return h === 'localhost' || h === '::1' || /^127\./.test(h);
|
||||
}
|
||||
|
||||
function isPrivateBindHost(host: string): boolean {
|
||||
const h = host.replace(/^\[|\]$/g, '').toLowerCase();
|
||||
if (h.startsWith('fe80:') || h.startsWith('fc') || h.startsWith('fd')) {
|
||||
return true;
|
||||
}
|
||||
const ipv4 = h.match(/^(\d{1,3})\.(\d{1,3})\./);
|
||||
if (!ipv4) return false;
|
||||
const [a, b] = [Number(ipv4[1]), Number(ipv4[2])];
|
||||
if (a === 10) return true;
|
||||
if (a === 169 && b === 254) return true;
|
||||
if (a === 172 && b >= 16 && b <= 31) return true;
|
||||
if (a === 192 && b === 168) return true;
|
||||
if (a === 100 && b >= 64 && b <= 127) return true; // CGNAT / tailnet
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Refuse to expose an unauthenticated dashboard on a public interface.
|
||||
*
|
||||
* With no token the API auth gate passes for everyone (see
|
||||
* isDashboardApiAuthorized). Binding that to a public interface / all
|
||||
* interfaces (0.0.0.0) would let any reachable client drive agents and restart
|
||||
* the service, so we fail fast. Loopback is fine; private / tailnet binds warn
|
||||
* loudly but still start so existing deployments keep running.
|
||||
*/
|
||||
export function assertDashboardAuthPosture(host: string, token: string): void {
|
||||
if (token) return;
|
||||
if (isLoopbackHost(host)) return;
|
||||
if (isPrivateBindHost(host)) {
|
||||
logger.warn(
|
||||
{ host },
|
||||
'Web dashboard is bound to a non-loopback host without WEB_DASHBOARD_TOKEN; ' +
|
||||
'anyone who can reach this host can drive agents and restart the service. ' +
|
||||
'Set WEB_DASHBOARD_TOKEN to require authentication.',
|
||||
);
|
||||
return;
|
||||
}
|
||||
throw new Error(
|
||||
`Refusing to start web dashboard on public host "${host}" without WEB_DASHBOARD_TOKEN. ` +
|
||||
'Set WEB_DASHBOARD_TOKEN or bind to 127.0.0.1.',
|
||||
);
|
||||
}
|
||||
|
||||
export function startWebDashboardServer(
|
||||
opts: {
|
||||
enabled?: boolean;
|
||||
host?: string;
|
||||
port?: number;
|
||||
staticDir?: string;
|
||||
getRoomBindings?: () => Record<string, RegisteredGroup>;
|
||||
enqueueMessageCheck?: (chatJid: string, groupFolder: string) => void;
|
||||
nudgeScheduler?: () => void;
|
||||
} = {},
|
||||
): StartedWebDashboardServer | null {
|
||||
const enabled = opts.enabled ?? WEB_DASHBOARD.enabled;
|
||||
if (!enabled) return null;
|
||||
|
||||
const host = opts.host ?? WEB_DASHBOARD.host;
|
||||
const port = opts.port ?? WEB_DASHBOARD.port;
|
||||
const staticDir = opts.staticDir ?? WEB_DASHBOARD.staticDir;
|
||||
assertDashboardAuthPosture(host, WEB_DASHBOARD.token);
|
||||
const server = Bun.serve({
|
||||
hostname: host,
|
||||
port,
|
||||
fetch: createWebDashboardHandler({
|
||||
staticDir,
|
||||
getRoomBindings: opts.getRoomBindings,
|
||||
enqueueMessageCheck: opts.enqueueMessageCheck,
|
||||
nudgeScheduler: opts.nudgeScheduler,
|
||||
}),
|
||||
});
|
||||
const url = `http://${host}:${server.port}`;
|
||||
|
||||
logger.info({ url, staticDir }, 'Web dashboard started');
|
||||
|
||||
return {
|
||||
url,
|
||||
stop: () => server.stop(true),
|
||||
};
|
||||
}
|
||||
@@ -1,172 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import {
|
||||
handleServiceRoute,
|
||||
type ServiceRestartRecord,
|
||||
} from './web-dashboard-service-routes.js';
|
||||
|
||||
function jsonResponse(value: unknown, init?: ResponseInit): Response {
|
||||
return new Response(JSON.stringify(value), {
|
||||
...init,
|
||||
headers: {
|
||||
'content-type': 'application/json; charset=utf-8',
|
||||
...(init?.headers as Record<string, string> | undefined),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function request(
|
||||
pathname: string,
|
||||
method = 'POST',
|
||||
body?: Record<string, unknown>,
|
||||
): Request {
|
||||
return new Request(`http://localhost${pathname}`, {
|
||||
method,
|
||||
body: body === undefined ? undefined : JSON.stringify(body),
|
||||
headers:
|
||||
body === undefined ? undefined : { 'content-type': 'application/json' },
|
||||
});
|
||||
}
|
||||
|
||||
async function route({
|
||||
activeServiceRestartTargets = new Set<string>(),
|
||||
body,
|
||||
method,
|
||||
now,
|
||||
pathname,
|
||||
recentServiceRestarts = [],
|
||||
restartServiceStack = () => ['ejclaw'],
|
||||
}: {
|
||||
activeServiceRestartTargets?: Set<string>;
|
||||
body?: Record<string, unknown>;
|
||||
method?: string;
|
||||
now?: () => string;
|
||||
pathname: string;
|
||||
recentServiceRestarts?: ServiceRestartRecord[];
|
||||
restartServiceStack?: () => string[];
|
||||
}): Promise<Response | null> {
|
||||
return handleServiceRoute({
|
||||
url: new URL(`http://localhost${pathname}`),
|
||||
request: request(pathname, method, body),
|
||||
jsonResponse,
|
||||
recentServiceRestarts,
|
||||
activeServiceRestartTargets,
|
||||
restartServiceStack,
|
||||
now,
|
||||
});
|
||||
}
|
||||
|
||||
describe('web dashboard service routes', () => {
|
||||
it('handles stack restarts and duplicate request ids', async () => {
|
||||
const recentServiceRestarts: ServiceRestartRecord[] = [];
|
||||
let restartCalls = 0;
|
||||
|
||||
const restart = async () =>
|
||||
route({
|
||||
pathname: '/api/services/stack/actions',
|
||||
body: { action: 'restart', requestId: 'stack-restart-1' },
|
||||
recentServiceRestarts,
|
||||
restartServiceStack: () => {
|
||||
restartCalls += 1;
|
||||
return ['ejclaw', 'reviewer'];
|
||||
},
|
||||
now: () => '2026-04-28T09:20:00.000Z',
|
||||
});
|
||||
|
||||
const response = await restart();
|
||||
expect(response?.status).toBe(200);
|
||||
await expect(response?.json()).resolves.toMatchObject({
|
||||
ok: true,
|
||||
restart: {
|
||||
id: 'web-restart-stack-restart-1',
|
||||
target: 'stack',
|
||||
requestedAt: '2026-04-28T09:20:00.000Z',
|
||||
completedAt: '2026-04-28T09:20:00.000Z',
|
||||
status: 'success',
|
||||
services: ['ejclaw', 'reviewer'],
|
||||
},
|
||||
});
|
||||
expect(recentServiceRestarts).toHaveLength(1);
|
||||
expect(restartCalls).toBe(1);
|
||||
|
||||
const duplicate = await restart();
|
||||
expect(duplicate?.status).toBe(200);
|
||||
await expect(duplicate?.json()).resolves.toMatchObject({
|
||||
ok: true,
|
||||
duplicate: true,
|
||||
restart: {
|
||||
id: 'web-restart-stack-restart-1',
|
||||
status: 'success',
|
||||
},
|
||||
});
|
||||
expect(restartCalls).toBe(1);
|
||||
|
||||
const unmatched = await route({ pathname: '/api/overview' });
|
||||
expect(unmatched).toBeNull();
|
||||
});
|
||||
|
||||
it('rejects invalid service actions without restarting', async () => {
|
||||
const recentServiceRestarts: ServiceRestartRecord[] = [
|
||||
{
|
||||
id: 'web-restart-failed-request',
|
||||
target: 'stack',
|
||||
requestedAt: '2026-04-28T09:10:00.000Z',
|
||||
completedAt: '2026-04-28T09:10:01.000Z',
|
||||
status: 'failed',
|
||||
services: [],
|
||||
error: 'systemctl failed',
|
||||
},
|
||||
];
|
||||
let restartCalls = 0;
|
||||
const restartServiceStack = () => {
|
||||
restartCalls += 1;
|
||||
return ['ejclaw'];
|
||||
};
|
||||
|
||||
const active = await route({
|
||||
pathname: '/api/services/stack/actions',
|
||||
body: { action: 'restart' },
|
||||
activeServiceRestartTargets: new Set(['stack']),
|
||||
restartServiceStack,
|
||||
});
|
||||
expect(active?.status).toBe(409);
|
||||
|
||||
const invalidAction = await route({
|
||||
pathname: '/api/services/stack/actions',
|
||||
body: { action: 'stop' },
|
||||
restartServiceStack,
|
||||
});
|
||||
expect(invalidAction?.status).toBe(400);
|
||||
|
||||
const invalidTarget = await route({
|
||||
pathname: '/api/services/ejclaw/actions',
|
||||
body: { action: 'restart' },
|
||||
restartServiceStack,
|
||||
});
|
||||
expect(invalidTarget?.status).toBe(400);
|
||||
|
||||
const wrongMethod = await route({
|
||||
pathname: '/api/services/stack/actions',
|
||||
method: 'GET',
|
||||
restartServiceStack,
|
||||
});
|
||||
expect(wrongMethod?.status).toBe(405);
|
||||
|
||||
const failedDuplicate = await route({
|
||||
pathname: '/api/services/stack/actions',
|
||||
body: { action: 'restart', requestId: 'failed-request' },
|
||||
recentServiceRestarts,
|
||||
restartServiceStack,
|
||||
});
|
||||
expect(failedDuplicate?.status).toBe(500);
|
||||
await expect(failedDuplicate?.json()).resolves.toMatchObject({
|
||||
error: 'systemctl failed',
|
||||
duplicate: true,
|
||||
restart: {
|
||||
id: 'web-restart-failed-request',
|
||||
status: 'failed',
|
||||
},
|
||||
});
|
||||
expect(restartCalls).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -1,175 +0,0 @@
|
||||
type JsonResponse = (
|
||||
value: unknown,
|
||||
init?: ResponseInit,
|
||||
request?: Request,
|
||||
) => Response;
|
||||
|
||||
type ServiceAction = 'restart';
|
||||
|
||||
interface ServiceActionRequest {
|
||||
action: ServiceAction;
|
||||
requestId: string | null;
|
||||
}
|
||||
|
||||
export interface ServiceRestartRecord {
|
||||
id: string;
|
||||
target: 'stack';
|
||||
requestedAt: string;
|
||||
completedAt: string | null;
|
||||
status: 'running' | 'success' | 'failed';
|
||||
services: string[];
|
||||
error?: string;
|
||||
}
|
||||
|
||||
interface ServiceRouteContext {
|
||||
url: URL;
|
||||
request: Request;
|
||||
jsonResponse: JsonResponse;
|
||||
recentServiceRestarts: ServiceRestartRecord[];
|
||||
activeServiceRestartTargets: Set<string>;
|
||||
restartServiceStack: () => string[];
|
||||
now?: () => string;
|
||||
}
|
||||
|
||||
const SERVICE_RESTART_LOG_LIMIT = 20;
|
||||
|
||||
function parseServiceActionPath(pathname: string): string | null {
|
||||
const match = pathname.match(/^\/api\/services\/([^/]+)\/actions$/);
|
||||
if (!match) return null;
|
||||
try {
|
||||
return decodeURIComponent(match[1]);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function isServiceAction(value: unknown): value is ServiceAction {
|
||||
return value === 'restart';
|
||||
}
|
||||
|
||||
function sanitizeServiceActionRequestId(value: unknown): string | null {
|
||||
if (typeof value !== 'string') return null;
|
||||
const trimmed = value.trim();
|
||||
if (!trimmed) return null;
|
||||
const safe = trimmed.replace(/[^A-Za-z0-9._:-]/g, '-').slice(0, 120);
|
||||
return safe || null;
|
||||
}
|
||||
|
||||
function makeServiceRestartId(requestId: string | null): string {
|
||||
return requestId
|
||||
? `web-restart-${requestId}`
|
||||
: `web-restart-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
|
||||
}
|
||||
|
||||
async function readServiceAction(
|
||||
request: Request,
|
||||
): Promise<ServiceActionRequest | null> {
|
||||
try {
|
||||
const body = (await request.json()) as {
|
||||
action?: unknown;
|
||||
requestId?: unknown;
|
||||
};
|
||||
if (!isServiceAction(body.action)) return null;
|
||||
return {
|
||||
action: body.action,
|
||||
requestId: sanitizeServiceActionRequestId(body.requestId),
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function rememberServiceRestart(
|
||||
records: ServiceRestartRecord[],
|
||||
record: ServiceRestartRecord,
|
||||
): void {
|
||||
records.unshift(record);
|
||||
if (records.length > SERVICE_RESTART_LOG_LIMIT) {
|
||||
records.length = SERVICE_RESTART_LOG_LIMIT;
|
||||
}
|
||||
}
|
||||
|
||||
function errorMessage(err: unknown): string {
|
||||
return err instanceof Error ? err.message : String(err);
|
||||
}
|
||||
|
||||
export async function handleServiceRoute({
|
||||
url,
|
||||
request,
|
||||
jsonResponse,
|
||||
recentServiceRestarts,
|
||||
activeServiceRestartTargets,
|
||||
restartServiceStack,
|
||||
now,
|
||||
}: ServiceRouteContext): Promise<Response | null> {
|
||||
const actionServiceId = parseServiceActionPath(url.pathname);
|
||||
if (!actionServiceId) return null;
|
||||
|
||||
if (request.method !== 'POST') {
|
||||
return jsonResponse({ error: 'Method not allowed' }, { status: 405 });
|
||||
}
|
||||
if (actionServiceId !== 'stack') {
|
||||
return jsonResponse(
|
||||
{ error: 'Unsupported service restart target' },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
const serviceRequest = await readServiceAction(request);
|
||||
if (!serviceRequest) {
|
||||
return jsonResponse({ error: 'Invalid service action' }, { status: 400 });
|
||||
}
|
||||
|
||||
const id = makeServiceRestartId(serviceRequest.requestId);
|
||||
const previous = recentServiceRestarts.find((record) => record.id === id);
|
||||
if (serviceRequest.requestId && previous) {
|
||||
if (previous.status === 'failed') {
|
||||
return jsonResponse(
|
||||
{
|
||||
error: previous.error ?? 'Service restart failed',
|
||||
duplicate: true,
|
||||
restart: previous,
|
||||
},
|
||||
{ status: 500 },
|
||||
);
|
||||
}
|
||||
return jsonResponse({ ok: true, duplicate: true, restart: previous });
|
||||
}
|
||||
|
||||
if (activeServiceRestartTargets.has(actionServiceId)) {
|
||||
return jsonResponse(
|
||||
{ error: 'Service restart is already running' },
|
||||
{ status: 409 },
|
||||
);
|
||||
}
|
||||
|
||||
const requestedAt = now?.() ?? new Date().toISOString();
|
||||
const record: ServiceRestartRecord = {
|
||||
id,
|
||||
target: 'stack',
|
||||
requestedAt,
|
||||
completedAt: null,
|
||||
status: 'running',
|
||||
services: [],
|
||||
};
|
||||
rememberServiceRestart(recentServiceRestarts, record);
|
||||
activeServiceRestartTargets.add(actionServiceId);
|
||||
|
||||
try {
|
||||
const services = restartServiceStack();
|
||||
record.completedAt = now?.() ?? new Date().toISOString();
|
||||
record.status = 'success';
|
||||
record.services = services;
|
||||
return jsonResponse({ ok: true, restart: record });
|
||||
} catch (err) {
|
||||
record.completedAt = now?.() ?? new Date().toISOString();
|
||||
record.status = 'failed';
|
||||
record.error = errorMessage(err);
|
||||
return jsonResponse(
|
||||
{ error: record.error, restart: record },
|
||||
{ status: 500 },
|
||||
);
|
||||
} finally {
|
||||
activeServiceRestartTargets.delete(actionServiceId);
|
||||
}
|
||||
}
|
||||
@@ -1,524 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import {
|
||||
handleSettingsRoute,
|
||||
type SettingsRouteDependencies,
|
||||
} from './web-dashboard-settings-routes.js';
|
||||
import type {
|
||||
ClaudeAccountSummary,
|
||||
CodexAccountSummary,
|
||||
CodexFeatureSnapshot,
|
||||
FastModeSnapshot,
|
||||
ModelConfigSnapshot,
|
||||
} from './settings-store.js';
|
||||
import type { RuntimeInventorySnapshot } from './runtime-inventory.js';
|
||||
import type { RoomSkillSettingsSnapshot } from './room-skill-settings.js';
|
||||
import type { MoaSettingsSnapshot } from './settings-store-moa.js';
|
||||
|
||||
function jsonResponse(value: unknown, init?: ResponseInit): Response {
|
||||
return new Response(JSON.stringify(value), {
|
||||
...init,
|
||||
headers: {
|
||||
'content-type': 'application/json; charset=utf-8',
|
||||
...(init?.headers as Record<string, string> | undefined),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function request(
|
||||
pathname: string,
|
||||
method = 'GET',
|
||||
body?: Record<string, unknown>,
|
||||
): Request {
|
||||
return new Request(`http://localhost${pathname}`, {
|
||||
method,
|
||||
body: body === undefined ? undefined : JSON.stringify(body),
|
||||
headers:
|
||||
body === undefined ? undefined : { 'content-type': 'application/json' },
|
||||
});
|
||||
}
|
||||
|
||||
const modelConfig: ModelConfigSnapshot = {
|
||||
owner: { model: 'gpt-5.4', effort: 'medium' },
|
||||
reviewer: { model: 'claude-sonnet', effort: 'high' },
|
||||
arbiter: { model: 'gpt-5.4', effort: 'high' },
|
||||
agentTypes: {
|
||||
owner: 'codex',
|
||||
reviewer: 'claude-code',
|
||||
arbiter: null,
|
||||
},
|
||||
};
|
||||
|
||||
const fastMode: FastModeSnapshot = { codex: true, claude: false };
|
||||
const codexFeatures: CodexFeatureSnapshot = { goals: false };
|
||||
const runtimeInventory: RuntimeInventorySnapshot = {
|
||||
generatedAt: '2026-05-04T00:00:00.000Z',
|
||||
projectRoot: '/repo',
|
||||
dataDir: '/repo/data',
|
||||
service: {
|
||||
id: 'codex-main',
|
||||
sessionScope: 'codex-main',
|
||||
agentType: 'codex',
|
||||
},
|
||||
codex: {
|
||||
configFiles: [
|
||||
{
|
||||
label: 'Codex config.toml',
|
||||
path: '/home/.codex/config.toml',
|
||||
exists: true,
|
||||
},
|
||||
],
|
||||
skillDirs: [
|
||||
{
|
||||
label: 'Codex user skills',
|
||||
path: '/home/.agents/skills',
|
||||
exists: true,
|
||||
count: 1,
|
||||
skills: [
|
||||
{
|
||||
name: 'agent-browser',
|
||||
description: 'Browser automation',
|
||||
path: '/home/.agents/skills/agent-browser',
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
mcp: {
|
||||
configPath: {
|
||||
label: 'Codex config.toml',
|
||||
path: '/home/.codex/config.toml',
|
||||
exists: true,
|
||||
},
|
||||
ejclawConfigured: true,
|
||||
serverCount: 1,
|
||||
},
|
||||
},
|
||||
claude: {
|
||||
configFiles: [
|
||||
{
|
||||
label: 'Claude settings.json',
|
||||
path: '/home/.claude/settings.json',
|
||||
exists: true,
|
||||
},
|
||||
],
|
||||
skillDirs: [],
|
||||
mcp: {
|
||||
configPath: {
|
||||
label: 'Claude settings.json',
|
||||
path: '/home/.claude/settings.json',
|
||||
exists: true,
|
||||
},
|
||||
ejclawConfigured: false,
|
||||
serverCount: 0,
|
||||
},
|
||||
},
|
||||
ejclaw: {
|
||||
runnerSkillDir: {
|
||||
label: 'EJClaw runner skills',
|
||||
path: '/repo/runners/skills',
|
||||
exists: true,
|
||||
count: 1,
|
||||
skills: [
|
||||
{
|
||||
name: 'agent-browser',
|
||||
description: 'Browser automation',
|
||||
path: '/repo/runners/skills/agent-browser',
|
||||
},
|
||||
],
|
||||
},
|
||||
mcpServer: {
|
||||
label: 'EJClaw IPC MCP server',
|
||||
path: '/repo/runners/agent-runner/dist/ipc-mcp-stdio.js',
|
||||
exists: true,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const moaSettings: MoaSettingsSnapshot = {
|
||||
enabled: true,
|
||||
referenceModels: ['kimi', 'glm'],
|
||||
models: [
|
||||
{
|
||||
name: 'kimi',
|
||||
enabled: true,
|
||||
model: 'kimi-k2.6',
|
||||
baseUrl: 'https://api.kimi.com/coding',
|
||||
apiFormat: 'anthropic',
|
||||
apiKeyConfigured: true,
|
||||
lastStatus: {
|
||||
model: 'kimi',
|
||||
checkedAt: '2026-04-30T00:00:00.000Z',
|
||||
ok: false,
|
||||
error: '402 Payment Required',
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'glm',
|
||||
enabled: true,
|
||||
model: 'glm-5.1',
|
||||
baseUrl: 'https://open.bigmodel.cn/api/anthropic',
|
||||
apiFormat: 'anthropic',
|
||||
apiKeyConfigured: true,
|
||||
lastStatus: null,
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const roomSkillSettings: RoomSkillSettingsSnapshot = {
|
||||
generatedAt: '2026-05-04T00:00:00.000Z',
|
||||
catalog: [
|
||||
{
|
||||
id: 'runner:agent-browser',
|
||||
scope: 'runner',
|
||||
name: 'agent-browser',
|
||||
displayName: 'agent-browser',
|
||||
description: 'Browser automation',
|
||||
path: '/repo/runners/skills/agent-browser',
|
||||
agentTypes: ['claude-code', 'codex'],
|
||||
},
|
||||
],
|
||||
rooms: [
|
||||
{
|
||||
jid: 'room@example',
|
||||
name: 'EJClaw',
|
||||
folder: 'ejclaw',
|
||||
agents: [
|
||||
{
|
||||
agentType: 'codex',
|
||||
mode: 'all-enabled',
|
||||
availableSkillIds: ['runner:agent-browser'],
|
||||
disabledSkillIds: [],
|
||||
explicitEnabledSkillIds: [],
|
||||
effectiveEnabledSkillIds: ['runner:agent-browser'],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
function makeClaudeAccount(): ClaudeAccountSummary {
|
||||
return {
|
||||
index: 0,
|
||||
expiresAt: 1777348544000,
|
||||
scopes: ['openid'],
|
||||
exists: true,
|
||||
};
|
||||
}
|
||||
|
||||
function makeCodexAccount(): CodexAccountSummary {
|
||||
return {
|
||||
index: 1,
|
||||
accountId: 'acct_1',
|
||||
email: 'codex@example.com',
|
||||
planType: 'pro',
|
||||
subscriptionUntil: null,
|
||||
subscriptionLastChecked: '2026-04-28T08:00:00.000Z',
|
||||
subscriptionSource: null,
|
||||
liveStatus: {
|
||||
checkedAt: '2026-04-28T08:00:00.000Z',
|
||||
source: 'wham/usage',
|
||||
planType: 'pro',
|
||||
email: 'codex@example.com',
|
||||
rateLimit: {
|
||||
allowed: true,
|
||||
limitReached: false,
|
||||
primaryWindow: {
|
||||
limitWindowSeconds: 18000,
|
||||
resetAfterSeconds: 1200,
|
||||
resetAt: '2026-04-28T08:20:00.000Z',
|
||||
usedPercent: 12,
|
||||
},
|
||||
secondaryWindow: null,
|
||||
},
|
||||
rateLimitReachedType: null,
|
||||
additionalRateLimits: [],
|
||||
credits: null,
|
||||
spendControl: null,
|
||||
},
|
||||
exists: true,
|
||||
};
|
||||
}
|
||||
|
||||
function makeDeps(
|
||||
overrides: Partial<SettingsRouteDependencies> = {},
|
||||
): SettingsRouteDependencies {
|
||||
return {
|
||||
addClaudeAccountFromToken: () => ({ index: 2, accountId: null }),
|
||||
checkMoaModel: async (name) => ({
|
||||
model: name,
|
||||
checkedAt: '2026-04-30T00:01:00.000Z',
|
||||
ok: true,
|
||||
error: null,
|
||||
responseLength: 2,
|
||||
}),
|
||||
getActiveCodexSettingsIndex: () => 1,
|
||||
getCodexFeatures: () => codexFeatures,
|
||||
getFastMode: () => fastMode,
|
||||
getModelConfig: () => modelConfig,
|
||||
getMoaSettings: () => moaSettings,
|
||||
getRuntimeInventory: () => runtimeInventory,
|
||||
getRoomSkillSettings: () => roomSkillSettings,
|
||||
listClaudeAccounts: () => [makeClaudeAccount()],
|
||||
listCodexAccounts: () => [makeCodexAccount()],
|
||||
refreshAllCodexAccounts: async () => ({ refreshed: [1], failed: [] }),
|
||||
refreshCodexAccount: async () => makeCodexAccount(),
|
||||
removeAccountDirectory: () => undefined,
|
||||
setActiveCodexSettingsIndex: () => undefined,
|
||||
updateCodexFeatures: () => codexFeatures,
|
||||
updateFastMode: () => fastMode,
|
||||
updateModelConfig: () => modelConfig,
|
||||
updateMoaSettings: () => moaSettings,
|
||||
updateRoomSkillSetting: () => roomSkillSettings,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
async function route(
|
||||
pathname: string,
|
||||
method = 'GET',
|
||||
body?: Record<string, unknown>,
|
||||
deps: SettingsRouteDependencies = makeDeps(),
|
||||
): Promise<Response | null> {
|
||||
return handleSettingsRoute({
|
||||
url: new URL(`http://localhost${pathname}`),
|
||||
request: request(pathname, method, body),
|
||||
jsonResponse,
|
||||
deps,
|
||||
});
|
||||
}
|
||||
|
||||
describe('web dashboard settings routes', () => {
|
||||
it('serves settings snapshots without touching the server router', async () => {
|
||||
const accounts = await route('/api/settings/accounts');
|
||||
expect(accounts?.status).toBe(200);
|
||||
await expect(accounts?.json()).resolves.toMatchObject({
|
||||
claude: [{ index: 0, exists: true }],
|
||||
codex: [{ index: 1, email: 'codex@example.com' }],
|
||||
codexCurrentIndex: 1,
|
||||
});
|
||||
|
||||
const models = await route('/api/settings/models');
|
||||
expect(models?.status).toBe(200);
|
||||
await expect(models?.json()).resolves.toEqual(modelConfig);
|
||||
|
||||
const mode = await route('/api/settings/fast-mode');
|
||||
expect(mode?.status).toBe(200);
|
||||
await expect(mode?.json()).resolves.toEqual(fastMode);
|
||||
|
||||
const inventory = await route('/api/settings/runtime-inventory');
|
||||
expect(inventory?.status).toBe(200);
|
||||
await expect(inventory?.json()).resolves.toMatchObject({
|
||||
service: { id: 'codex-main', agentType: 'codex' },
|
||||
codex: { mcp: { ejclawConfigured: true } },
|
||||
ejclaw: { runnerSkillDir: { count: 1 } },
|
||||
});
|
||||
|
||||
const roomSkills = await route('/api/settings/room-skills');
|
||||
expect(roomSkills?.status).toBe(200);
|
||||
await expect(roomSkills?.json()).resolves.toMatchObject({
|
||||
catalog: [{ id: 'runner:agent-browser' }],
|
||||
rooms: [{ jid: 'room@example', agents: [{ agentType: 'codex' }] }],
|
||||
});
|
||||
|
||||
const features = await route('/api/settings/codex-features');
|
||||
expect(features?.status).toBe(200);
|
||||
await expect(features?.json()).resolves.toEqual(codexFeatures);
|
||||
|
||||
const moa = await route('/api/settings/moa');
|
||||
expect(moa?.status).toBe(200);
|
||||
const moaJson = (await moa?.json()) as MoaSettingsSnapshot;
|
||||
expect(moaJson.enabled).toBe(true);
|
||||
expect(moaJson.models.find((model) => model.name === 'kimi')).toMatchObject(
|
||||
{
|
||||
enabled: true,
|
||||
lastStatus: { ok: false, error: '402 Payment Required' },
|
||||
},
|
||||
);
|
||||
|
||||
const unmatched = await route('/api/overview');
|
||||
expect(unmatched).toBeNull();
|
||||
});
|
||||
|
||||
it('handles settings mutations through injected dependencies', async () => {
|
||||
const calls: string[] = [];
|
||||
const deps = makeDeps({
|
||||
addClaudeAccountFromToken: (token) => {
|
||||
calls.push(`add:${token}`);
|
||||
return { index: 3, accountId: null };
|
||||
},
|
||||
removeAccountDirectory: (provider, index) => {
|
||||
calls.push(`delete:${provider}:${index}`);
|
||||
},
|
||||
setActiveCodexSettingsIndex: (index) => {
|
||||
calls.push(`current:${index}`);
|
||||
},
|
||||
updateModelConfig: (input) => {
|
||||
calls.push(`models:${JSON.stringify(input)}`);
|
||||
return modelConfig;
|
||||
},
|
||||
updateCodexFeatures: (input) => {
|
||||
calls.push(`codex-features:${JSON.stringify(input)}`);
|
||||
return { goals: input.goals === true };
|
||||
},
|
||||
updateMoaSettings: (input) => {
|
||||
calls.push(`moa:${JSON.stringify(input)}`);
|
||||
return moaSettings;
|
||||
},
|
||||
updateRoomSkillSetting: (input) => {
|
||||
calls.push(`room-skill:${JSON.stringify(input)}`);
|
||||
return {
|
||||
...roomSkillSettings,
|
||||
rooms: [
|
||||
{
|
||||
...roomSkillSettings.rooms[0]!,
|
||||
agents: [
|
||||
{
|
||||
...roomSkillSettings.rooms[0]!.agents[0]!,
|
||||
mode: 'custom',
|
||||
disabledSkillIds: [input.skillId],
|
||||
effectiveEnabledSkillIds: [],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
const modelUpdate = await route(
|
||||
'/api/settings/models',
|
||||
'PATCH',
|
||||
{ owner: { model: 'gpt-5.5' } },
|
||||
deps,
|
||||
);
|
||||
expect(modelUpdate?.status).toBe(200);
|
||||
|
||||
const add = await route(
|
||||
'/api/settings/accounts/claude',
|
||||
'POST',
|
||||
{ token: ' claude-token ' },
|
||||
deps,
|
||||
);
|
||||
expect(add?.status).toBe(200);
|
||||
await expect(add?.json()).resolves.toMatchObject({ ok: true, index: 3 });
|
||||
|
||||
const del = await route(
|
||||
'/api/settings/accounts/codex/4',
|
||||
'DELETE',
|
||||
undefined,
|
||||
deps,
|
||||
);
|
||||
expect(del?.status).toBe(200);
|
||||
|
||||
const current = await route(
|
||||
'/api/settings/accounts/codex/current',
|
||||
'PUT',
|
||||
{ index: 4 },
|
||||
deps,
|
||||
);
|
||||
expect(current?.status).toBe(200);
|
||||
await expect(current?.json()).resolves.toMatchObject({
|
||||
ok: true,
|
||||
codexCurrentIndex: 1,
|
||||
});
|
||||
|
||||
const goals = await route(
|
||||
'/api/settings/codex-features',
|
||||
'PATCH',
|
||||
{ goals: true },
|
||||
deps,
|
||||
);
|
||||
expect(goals?.status).toBe(200);
|
||||
await expect(goals?.json()).resolves.toEqual({ goals: true });
|
||||
|
||||
const moa = await route(
|
||||
'/api/settings/moa',
|
||||
'PATCH',
|
||||
{ enabled: false, models: [{ name: 'kimi', enabled: false }] },
|
||||
deps,
|
||||
);
|
||||
expect(moa?.status).toBe(200);
|
||||
|
||||
const check = await route(
|
||||
'/api/settings/moa/check',
|
||||
'POST',
|
||||
{ name: 'glm' },
|
||||
deps,
|
||||
);
|
||||
expect(check?.status).toBe(200);
|
||||
await expect(check?.json()).resolves.toMatchObject({
|
||||
ok: true,
|
||||
status: { model: 'glm', ok: true },
|
||||
});
|
||||
|
||||
const roomSkill = await route(
|
||||
'/api/settings/room-skills',
|
||||
'PATCH',
|
||||
{
|
||||
roomJid: 'room@example',
|
||||
agentType: 'codex',
|
||||
skillId: 'runner:agent-browser',
|
||||
enabled: false,
|
||||
},
|
||||
deps,
|
||||
);
|
||||
expect(roomSkill?.status).toBe(200);
|
||||
await expect(roomSkill?.json()).resolves.toMatchObject({
|
||||
rooms: [
|
||||
{
|
||||
agents: [
|
||||
{
|
||||
mode: 'custom',
|
||||
disabledSkillIds: ['runner:agent-browser'],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(calls).toEqual([
|
||||
'models:{"owner":{"model":"gpt-5.5"}}',
|
||||
'add:claude-token',
|
||||
'delete:codex:4',
|
||||
'current:4',
|
||||
'codex-features:{"goals":true}',
|
||||
'moa:{"enabled":false,"models":[{"name":"kimi","enabled":false}]}',
|
||||
'room-skill:{"roomJid":"room@example","agentType":"codex","skillId":"runner:agent-browser","enabled":false}',
|
||||
]);
|
||||
});
|
||||
|
||||
it('rejects unsupported room skill methods with 405', async () => {
|
||||
const response = await route('/api/settings/room-skills', 'DELETE');
|
||||
expect(response?.status).toBe(405);
|
||||
expect(response?.headers.get('allow')).toBe('GET, HEAD, PATCH, PUT');
|
||||
await expect(response?.json()).resolves.toEqual({
|
||||
error: 'Method not allowed',
|
||||
});
|
||||
});
|
||||
|
||||
it('validates room skill mutation payloads', async () => {
|
||||
const missingEnabled = await route('/api/settings/room-skills', 'PATCH', {
|
||||
roomJid: 'room@example',
|
||||
agentType: 'codex',
|
||||
skillId: 'runner:agent-browser',
|
||||
});
|
||||
expect(missingEnabled?.status).toBe(400);
|
||||
|
||||
const invalid = await route(
|
||||
'/api/settings/room-skills',
|
||||
'PATCH',
|
||||
{
|
||||
roomJid: 'room@example',
|
||||
agentType: 'codex',
|
||||
skillId: 'runner:agent-browser',
|
||||
enabled: false,
|
||||
},
|
||||
makeDeps({
|
||||
updateRoomSkillSetting: () => {
|
||||
throw new Error('boom');
|
||||
},
|
||||
}),
|
||||
);
|
||||
expect(invalid?.status).toBe(500);
|
||||
});
|
||||
});
|
||||
@@ -1,456 +0,0 @@
|
||||
import {
|
||||
addClaudeAccountFromToken,
|
||||
getActiveCodexSettingsIndex,
|
||||
getCodexFeatures,
|
||||
getFastMode,
|
||||
getModelConfig,
|
||||
listClaudeAccounts,
|
||||
listCodexAccounts,
|
||||
refreshAllCodexAccounts,
|
||||
refreshCodexAccount,
|
||||
removeAccountDirectory,
|
||||
setActiveCodexSettingsIndex,
|
||||
updateCodexFeatures,
|
||||
updateFastMode,
|
||||
updateModelConfig,
|
||||
type ClaudeAccountSummary,
|
||||
type CodexFeatureSnapshot,
|
||||
type CodexAccountSummary,
|
||||
type FastModeSnapshot,
|
||||
type ModelConfigSnapshot,
|
||||
} from './settings-store.js';
|
||||
import {
|
||||
getRuntimeInventory,
|
||||
type RuntimeInventorySnapshot,
|
||||
} from './runtime-inventory.js';
|
||||
import {
|
||||
getRoomSkillSettings,
|
||||
RoomSkillSettingsError,
|
||||
updateRoomSkillSetting,
|
||||
type RoomSkillSettingsSnapshot,
|
||||
type RoomSkillSettingUpdateInput,
|
||||
} from './room-skill-settings.js';
|
||||
import {
|
||||
checkMoaModel,
|
||||
getMoaSettings,
|
||||
updateMoaSettings,
|
||||
type MoaSettingsSnapshot,
|
||||
} from './settings-store-moa.js';
|
||||
|
||||
type JsonResponse = (
|
||||
value: unknown,
|
||||
init?: ResponseInit,
|
||||
request?: Request,
|
||||
) => Response;
|
||||
|
||||
export interface SettingsRouteDependencies {
|
||||
addClaudeAccountFromToken: typeof addClaudeAccountFromToken;
|
||||
checkMoaModel: typeof checkMoaModel;
|
||||
getActiveCodexSettingsIndex: typeof getActiveCodexSettingsIndex;
|
||||
getCodexFeatures: typeof getCodexFeatures;
|
||||
getFastMode: typeof getFastMode;
|
||||
getModelConfig: typeof getModelConfig;
|
||||
getMoaSettings: typeof getMoaSettings;
|
||||
getRuntimeInventory: typeof getRuntimeInventory;
|
||||
getRoomSkillSettings: typeof getRoomSkillSettings;
|
||||
listClaudeAccounts: typeof listClaudeAccounts;
|
||||
listCodexAccounts: typeof listCodexAccounts;
|
||||
refreshAllCodexAccounts: typeof refreshAllCodexAccounts;
|
||||
refreshCodexAccount: typeof refreshCodexAccount;
|
||||
removeAccountDirectory: typeof removeAccountDirectory;
|
||||
setActiveCodexSettingsIndex: typeof setActiveCodexSettingsIndex;
|
||||
updateCodexFeatures: typeof updateCodexFeatures;
|
||||
updateFastMode: typeof updateFastMode;
|
||||
updateModelConfig: typeof updateModelConfig;
|
||||
updateMoaSettings: typeof updateMoaSettings;
|
||||
updateRoomSkillSetting: typeof updateRoomSkillSetting;
|
||||
}
|
||||
|
||||
interface SettingsRouteContext {
|
||||
url: URL;
|
||||
request: Request;
|
||||
jsonResponse: JsonResponse;
|
||||
deps?: SettingsRouteDependencies;
|
||||
}
|
||||
|
||||
const defaultSettingsRouteDependencies: SettingsRouteDependencies = {
|
||||
addClaudeAccountFromToken,
|
||||
checkMoaModel,
|
||||
getActiveCodexSettingsIndex,
|
||||
getCodexFeatures,
|
||||
getFastMode,
|
||||
getModelConfig,
|
||||
getMoaSettings,
|
||||
getRuntimeInventory,
|
||||
getRoomSkillSettings,
|
||||
listClaudeAccounts,
|
||||
listCodexAccounts,
|
||||
refreshAllCodexAccounts,
|
||||
refreshCodexAccount,
|
||||
removeAccountDirectory,
|
||||
setActiveCodexSettingsIndex,
|
||||
updateCodexFeatures,
|
||||
updateFastMode,
|
||||
updateModelConfig,
|
||||
updateMoaSettings,
|
||||
updateRoomSkillSetting,
|
||||
};
|
||||
|
||||
function readMethod(method: string): boolean {
|
||||
return method === 'GET' || method === 'HEAD';
|
||||
}
|
||||
|
||||
async function readJsonObject(
|
||||
request: Request,
|
||||
jsonResponse: JsonResponse,
|
||||
): Promise<Record<string, unknown> | Response> {
|
||||
let body: unknown;
|
||||
try {
|
||||
body = await request.json();
|
||||
} catch {
|
||||
return jsonResponse({ error: 'Invalid JSON body' }, { status: 400 });
|
||||
}
|
||||
if (!body || typeof body !== 'object' || Array.isArray(body)) {
|
||||
return jsonResponse(
|
||||
{ error: 'Body must be a JSON object' },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
return body as Record<string, unknown>;
|
||||
}
|
||||
|
||||
function errorMessage(err: unknown): string {
|
||||
return err instanceof Error ? err.message : String(err);
|
||||
}
|
||||
|
||||
function methodNotAllowed(
|
||||
jsonResponse: JsonResponse,
|
||||
allowed: string[],
|
||||
): Response {
|
||||
return jsonResponse(
|
||||
{ error: 'Method not allowed' },
|
||||
{
|
||||
status: 405,
|
||||
headers: { Allow: allowed.join(', ') },
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
async function handleModelSettingsRoute(
|
||||
request: Request,
|
||||
jsonResponse: JsonResponse,
|
||||
deps: SettingsRouteDependencies,
|
||||
): Promise<Response | null> {
|
||||
if (readMethod(request.method)) return jsonResponse(deps.getModelConfig());
|
||||
if (request.method !== 'PUT' && request.method !== 'PATCH') return null;
|
||||
|
||||
const body = await readJsonObject(request, jsonResponse);
|
||||
if (body instanceof Response) return body;
|
||||
try {
|
||||
return jsonResponse(deps.updateModelConfig(body));
|
||||
} catch (err) {
|
||||
const message = errorMessage(err);
|
||||
const status = message.includes('not supported') ? 400 : 500;
|
||||
return jsonResponse({ error: message }, { status });
|
||||
}
|
||||
}
|
||||
|
||||
async function handleFastModeRoute(
|
||||
request: Request,
|
||||
jsonResponse: JsonResponse,
|
||||
deps: SettingsRouteDependencies,
|
||||
): Promise<Response | null> {
|
||||
if (readMethod(request.method)) return jsonResponse(deps.getFastMode());
|
||||
if (request.method !== 'PUT' && request.method !== 'PATCH') return null;
|
||||
|
||||
const body = await readJsonObject(request, jsonResponse);
|
||||
if (body instanceof Response) return body;
|
||||
try {
|
||||
return jsonResponse(deps.updateFastMode(body));
|
||||
} catch (err) {
|
||||
return jsonResponse({ error: errorMessage(err) }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
async function handleCodexFeaturesRoute(
|
||||
request: Request,
|
||||
jsonResponse: JsonResponse,
|
||||
deps: SettingsRouteDependencies,
|
||||
): Promise<Response | null> {
|
||||
if (readMethod(request.method)) return jsonResponse(deps.getCodexFeatures());
|
||||
if (request.method !== 'PUT' && request.method !== 'PATCH') return null;
|
||||
|
||||
const body = await readJsonObject(request, jsonResponse);
|
||||
if (body instanceof Response) return body;
|
||||
try {
|
||||
return jsonResponse(deps.updateCodexFeatures(body));
|
||||
} catch (err) {
|
||||
return jsonResponse({ error: errorMessage(err) }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
async function handleMoaSettingsRoute(
|
||||
request: Request,
|
||||
jsonResponse: JsonResponse,
|
||||
deps: SettingsRouteDependencies,
|
||||
): Promise<Response | null> {
|
||||
if (readMethod(request.method)) return jsonResponse(deps.getMoaSettings());
|
||||
if (request.method !== 'PUT' && request.method !== 'PATCH') return null;
|
||||
|
||||
const body = await readJsonObject(request, jsonResponse);
|
||||
if (body instanceof Response) return body;
|
||||
try {
|
||||
return jsonResponse(deps.updateMoaSettings(body));
|
||||
} catch (err) {
|
||||
return jsonResponse({ error: errorMessage(err) }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
async function handleMoaCheckRoute(
|
||||
request: Request,
|
||||
jsonResponse: JsonResponse,
|
||||
deps: SettingsRouteDependencies,
|
||||
): Promise<Response | null> {
|
||||
if (request.method !== 'POST') return null;
|
||||
|
||||
const body = await readJsonObject(request, jsonResponse);
|
||||
if (body instanceof Response) return body;
|
||||
const name = typeof body.name === 'string' ? body.name.trim() : '';
|
||||
if (!name)
|
||||
return jsonResponse({ error: 'name is required' }, { status: 400 });
|
||||
|
||||
try {
|
||||
return jsonResponse({ ok: true, status: await deps.checkMoaModel(name) });
|
||||
} catch (err) {
|
||||
return jsonResponse({ error: errorMessage(err) }, { status: 400 });
|
||||
}
|
||||
}
|
||||
|
||||
function handleAccountsRoute(
|
||||
request: Request,
|
||||
jsonResponse: JsonResponse,
|
||||
deps: SettingsRouteDependencies,
|
||||
): Response | null {
|
||||
if (!readMethod(request.method)) return null;
|
||||
return jsonResponse({
|
||||
claude: deps.listClaudeAccounts(),
|
||||
codex: deps.listCodexAccounts(),
|
||||
codexCurrentIndex: deps.getActiveCodexSettingsIndex(),
|
||||
});
|
||||
}
|
||||
|
||||
function handleRuntimeInventoryRoute(
|
||||
request: Request,
|
||||
jsonResponse: JsonResponse,
|
||||
deps: SettingsRouteDependencies,
|
||||
): Response | null {
|
||||
if (!readMethod(request.method)) return null;
|
||||
return jsonResponse(deps.getRuntimeInventory());
|
||||
}
|
||||
|
||||
async function handleRoomSkillsRoute(
|
||||
request: Request,
|
||||
jsonResponse: JsonResponse,
|
||||
deps: SettingsRouteDependencies,
|
||||
): Promise<Response> {
|
||||
if (readMethod(request.method)) {
|
||||
return jsonResponse(deps.getRoomSkillSettings());
|
||||
}
|
||||
if (request.method !== 'PATCH' && request.method !== 'PUT') {
|
||||
return methodNotAllowed(jsonResponse, ['GET', 'HEAD', 'PATCH', 'PUT']);
|
||||
}
|
||||
|
||||
const body = await readJsonObject(request, jsonResponse);
|
||||
if (body instanceof Response) return body;
|
||||
|
||||
const input: RoomSkillSettingUpdateInput = {
|
||||
roomJid: typeof body.roomJid === 'string' ? body.roomJid : '',
|
||||
agentType: typeof body.agentType === 'string' ? body.agentType : '',
|
||||
skillId: typeof body.skillId === 'string' ? body.skillId : '',
|
||||
enabled: body.enabled === true,
|
||||
};
|
||||
if (typeof body.enabled !== 'boolean') {
|
||||
return jsonResponse(
|
||||
{ error: 'enabled must be a boolean' },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
return jsonResponse(deps.updateRoomSkillSetting(input));
|
||||
} catch (err) {
|
||||
if (err instanceof RoomSkillSettingsError) {
|
||||
return jsonResponse({ error: err.message }, { status: err.status });
|
||||
}
|
||||
return jsonResponse({ error: errorMessage(err) }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
async function handleClaudeAccountAddRoute(
|
||||
request: Request,
|
||||
jsonResponse: JsonResponse,
|
||||
deps: SettingsRouteDependencies,
|
||||
): Promise<Response | null> {
|
||||
if (request.method !== 'POST') return null;
|
||||
|
||||
let body: { token?: unknown };
|
||||
try {
|
||||
body = (await request.json()) as { token?: unknown };
|
||||
} catch {
|
||||
return jsonResponse({ error: 'Invalid JSON body' }, { status: 400 });
|
||||
}
|
||||
const token = typeof body?.token === 'string' ? body.token.trim() : '';
|
||||
if (!token)
|
||||
return jsonResponse({ error: 'token is required' }, { status: 400 });
|
||||
|
||||
try {
|
||||
const result = deps.addClaudeAccountFromToken(token);
|
||||
return jsonResponse({ ok: true, ...result });
|
||||
} catch (err) {
|
||||
return jsonResponse({ error: errorMessage(err) }, { status: 400 });
|
||||
}
|
||||
}
|
||||
|
||||
function handleAccountDeleteRoute(
|
||||
request: Request,
|
||||
accountMatch: RegExpMatchArray,
|
||||
jsonResponse: JsonResponse,
|
||||
deps: SettingsRouteDependencies,
|
||||
): Response | null {
|
||||
if (request.method !== 'DELETE') return null;
|
||||
const provider = accountMatch[1] as 'claude' | 'codex';
|
||||
const index = Number.parseInt(accountMatch[2], 10);
|
||||
try {
|
||||
deps.removeAccountDirectory(provider, index);
|
||||
return jsonResponse({ ok: true, provider, index });
|
||||
} catch (err) {
|
||||
return jsonResponse({ error: errorMessage(err) }, { status: 400 });
|
||||
}
|
||||
}
|
||||
|
||||
async function handleCodexRefreshRoute(
|
||||
request: Request,
|
||||
refreshMatch: RegExpMatchArray,
|
||||
jsonResponse: JsonResponse,
|
||||
deps: SettingsRouteDependencies,
|
||||
): Promise<Response | null> {
|
||||
if (request.method !== 'POST') return null;
|
||||
const index = Number.parseInt(refreshMatch[1], 10);
|
||||
try {
|
||||
const updated = await deps.refreshCodexAccount(index);
|
||||
return jsonResponse({ ok: true, account: updated });
|
||||
} catch (err) {
|
||||
return jsonResponse({ error: errorMessage(err) }, { status: 400 });
|
||||
}
|
||||
}
|
||||
|
||||
async function handleCodexRefreshAllRoute(
|
||||
request: Request,
|
||||
jsonResponse: JsonResponse,
|
||||
deps: SettingsRouteDependencies,
|
||||
): Promise<Response | null> {
|
||||
if (request.method !== 'POST') return null;
|
||||
try {
|
||||
const result = await deps.refreshAllCodexAccounts();
|
||||
return jsonResponse({ ok: true, ...result });
|
||||
} catch (err) {
|
||||
return jsonResponse({ error: errorMessage(err) }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
async function handleCodexCurrentRoute(
|
||||
request: Request,
|
||||
jsonResponse: JsonResponse,
|
||||
deps: SettingsRouteDependencies,
|
||||
): Promise<Response | null> {
|
||||
if (request.method !== 'PUT') return null;
|
||||
|
||||
let body: { index?: unknown };
|
||||
try {
|
||||
body = (await request.json()) as { index?: unknown };
|
||||
} catch {
|
||||
return jsonResponse({ error: 'Invalid JSON body' }, { status: 400 });
|
||||
}
|
||||
const idx = typeof body?.index === 'number' ? body.index : Number.NaN;
|
||||
if (!Number.isInteger(idx)) {
|
||||
return jsonResponse({ error: 'index must be an integer' }, { status: 400 });
|
||||
}
|
||||
|
||||
try {
|
||||
deps.setActiveCodexSettingsIndex(idx);
|
||||
return jsonResponse({
|
||||
ok: true,
|
||||
codexCurrentIndex: deps.getActiveCodexSettingsIndex(),
|
||||
});
|
||||
} catch (err) {
|
||||
return jsonResponse({ error: errorMessage(err) }, { status: 400 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function handleSettingsRoute({
|
||||
url,
|
||||
request,
|
||||
jsonResponse,
|
||||
deps = defaultSettingsRouteDependencies,
|
||||
}: SettingsRouteContext): Promise<Response | null> {
|
||||
if (url.pathname === '/api/settings/accounts') {
|
||||
return handleAccountsRoute(request, jsonResponse, deps);
|
||||
}
|
||||
if (url.pathname === '/api/settings/models') {
|
||||
return handleModelSettingsRoute(request, jsonResponse, deps);
|
||||
}
|
||||
if (url.pathname === '/api/settings/runtime-inventory') {
|
||||
return handleRuntimeInventoryRoute(request, jsonResponse, deps);
|
||||
}
|
||||
if (url.pathname === '/api/settings/room-skills') {
|
||||
return handleRoomSkillsRoute(request, jsonResponse, deps);
|
||||
}
|
||||
if (url.pathname === '/api/settings/fast-mode') {
|
||||
return handleFastModeRoute(request, jsonResponse, deps);
|
||||
}
|
||||
if (url.pathname === '/api/settings/codex-features') {
|
||||
return handleCodexFeaturesRoute(request, jsonResponse, deps);
|
||||
}
|
||||
if (url.pathname === '/api/settings/moa') {
|
||||
return handleMoaSettingsRoute(request, jsonResponse, deps);
|
||||
}
|
||||
if (url.pathname === '/api/settings/moa/check') {
|
||||
return handleMoaCheckRoute(request, jsonResponse, deps);
|
||||
}
|
||||
if (url.pathname === '/api/settings/accounts/claude') {
|
||||
return handleClaudeAccountAddRoute(request, jsonResponse, deps);
|
||||
}
|
||||
if (url.pathname === '/api/settings/accounts/codex/refresh-all') {
|
||||
return handleCodexRefreshAllRoute(request, jsonResponse, deps);
|
||||
}
|
||||
if (url.pathname === '/api/settings/accounts/codex/current') {
|
||||
return handleCodexCurrentRoute(request, jsonResponse, deps);
|
||||
}
|
||||
|
||||
const accountMatch = url.pathname.match(
|
||||
/^\/api\/settings\/accounts\/(claude|codex)\/(\d+)$/,
|
||||
);
|
||||
if (accountMatch) {
|
||||
return handleAccountDeleteRoute(request, accountMatch, jsonResponse, deps);
|
||||
}
|
||||
|
||||
const refreshMatch = url.pathname.match(
|
||||
/^\/api\/settings\/accounts\/codex\/(\d+)\/refresh$/,
|
||||
);
|
||||
if (refreshMatch) {
|
||||
return handleCodexRefreshRoute(request, refreshMatch, jsonResponse, deps);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
export type {
|
||||
ClaudeAccountSummary,
|
||||
CodexAccountSummary,
|
||||
CodexFeatureSnapshot,
|
||||
FastModeSnapshot,
|
||||
ModelConfigSnapshot,
|
||||
MoaSettingsSnapshot,
|
||||
RuntimeInventorySnapshot,
|
||||
RoomSkillSettingsSnapshot,
|
||||
};
|
||||
@@ -1,254 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import type { RegisteredGroup, ScheduledTask } from './types.js';
|
||||
import {
|
||||
handleScheduledTaskRoute,
|
||||
type ScheduledTaskRouteDependencies,
|
||||
} from './web-dashboard-task-routes.js';
|
||||
|
||||
function jsonResponse(value: unknown, init?: ResponseInit): Response {
|
||||
return new Response(JSON.stringify(value), {
|
||||
...init,
|
||||
headers: {
|
||||
'content-type': 'application/json; charset=utf-8',
|
||||
...(init?.headers as Record<string, string> | undefined),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function request(
|
||||
pathname: string,
|
||||
method: string,
|
||||
body?: Record<string, unknown>,
|
||||
): Request {
|
||||
return new Request(`http://localhost${pathname}`, {
|
||||
method,
|
||||
body: body === undefined ? undefined : JSON.stringify(body),
|
||||
headers:
|
||||
body === undefined ? undefined : { 'content-type': 'application/json' },
|
||||
});
|
||||
}
|
||||
|
||||
function makeTask(overrides: Partial<ScheduledTask>): ScheduledTask {
|
||||
return {
|
||||
id: 'task-1',
|
||||
group_folder: 'ops-room',
|
||||
chat_jid: 'dc:ops',
|
||||
agent_type: null,
|
||||
status_message_id: null,
|
||||
status_started_at: null,
|
||||
prompt: 'regular scheduled task',
|
||||
schedule_type: 'once',
|
||||
schedule_value: '2026-04-26T05:20:00.000Z',
|
||||
context_mode: 'isolated',
|
||||
next_run: '2026-04-26T05:20:00.000Z',
|
||||
last_run: null,
|
||||
last_result: null,
|
||||
status: 'active',
|
||||
suspended_until: null,
|
||||
created_at: '2026-04-26T05:00:00.000Z',
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function makeDeps(
|
||||
tasks: Map<string, ScheduledTask>,
|
||||
overrides: Partial<ScheduledTaskRouteDependencies> = {},
|
||||
): ScheduledTaskRouteDependencies {
|
||||
return {
|
||||
createScheduledTask: (task) => {
|
||||
tasks.set(task.id, {
|
||||
...task,
|
||||
agent_type: task.agent_type ?? null,
|
||||
ci_provider: null,
|
||||
ci_metadata: null,
|
||||
max_duration_ms: null,
|
||||
status_message_id: null,
|
||||
status_started_at: null,
|
||||
last_run: null,
|
||||
last_result: null,
|
||||
suspended_until: null,
|
||||
});
|
||||
},
|
||||
loadTaskById: (id) => tasks.get(id),
|
||||
mutateTask: (id, updates) => {
|
||||
const task = tasks.get(id);
|
||||
if (task) tasks.set(id, { ...task, ...updates });
|
||||
},
|
||||
removeTask: (id) => {
|
||||
tasks.delete(id);
|
||||
},
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
async function route({
|
||||
body,
|
||||
deps,
|
||||
method,
|
||||
now,
|
||||
pathname,
|
||||
}: {
|
||||
body?: Record<string, unknown>;
|
||||
deps: ScheduledTaskRouteDependencies;
|
||||
method: string;
|
||||
now?: () => string;
|
||||
pathname: string;
|
||||
}): Promise<Response | null> {
|
||||
return handleScheduledTaskRoute({
|
||||
url: new URL(`http://localhost${pathname}`),
|
||||
request: request(pathname, method, body),
|
||||
jsonResponse,
|
||||
now,
|
||||
...deps,
|
||||
});
|
||||
}
|
||||
|
||||
describe('web dashboard scheduled task routes', () => {
|
||||
it('creates scheduled tasks with room resolution and duplicate request ids', async () => {
|
||||
const tasks = new Map<string, ScheduledTask>();
|
||||
const rooms: Record<string, RegisteredGroup> = {
|
||||
'dc:ops': {
|
||||
name: '#ops',
|
||||
folder: 'ops-room',
|
||||
added_at: '2026-04-26T05:00:00.000Z',
|
||||
agentType: 'codex',
|
||||
},
|
||||
};
|
||||
let nudges = 0;
|
||||
const deps = makeDeps(tasks, {
|
||||
loadRoomBindings: () => rooms,
|
||||
nudgeScheduler: () => {
|
||||
nudges += 1;
|
||||
},
|
||||
});
|
||||
|
||||
const create = await route({
|
||||
pathname: '/api/tasks',
|
||||
method: 'POST',
|
||||
body: {
|
||||
roomJid: 'dc:ops',
|
||||
prompt: ' run deployment audit ',
|
||||
requestId: 'task-create-1',
|
||||
scheduleType: 'once',
|
||||
scheduleValue: '2026-04-26T05:10:00.000Z',
|
||||
contextMode: 'group',
|
||||
},
|
||||
deps,
|
||||
now: () => '2026-04-26T05:10:00.000Z',
|
||||
});
|
||||
|
||||
expect(create?.status).toBe(200);
|
||||
await expect(create?.json()).resolves.toMatchObject({
|
||||
ok: true,
|
||||
task: {
|
||||
id: 'web-task-task-create-1',
|
||||
groupFolder: 'ops-room',
|
||||
chatJid: 'dc:ops',
|
||||
agentType: 'codex',
|
||||
promptLength: 20,
|
||||
scheduleType: 'once',
|
||||
status: 'active',
|
||||
},
|
||||
});
|
||||
expect(tasks.get('web-task-task-create-1')).toMatchObject({
|
||||
prompt: 'run deployment audit',
|
||||
next_run: '2026-04-26T05:10:00.000Z',
|
||||
});
|
||||
expect(nudges).toBe(1);
|
||||
|
||||
const duplicate = await route({
|
||||
pathname: '/api/tasks',
|
||||
method: 'POST',
|
||||
body: {
|
||||
roomJid: 'dc:ops',
|
||||
prompt: 'run deployment audit',
|
||||
requestId: 'task-create-1',
|
||||
scheduleType: 'once',
|
||||
scheduleValue: '2026-04-26T05:10:00.000Z',
|
||||
},
|
||||
deps,
|
||||
now: () => '2026-04-26T05:10:00.000Z',
|
||||
});
|
||||
expect(duplicate?.status).toBe(200);
|
||||
await expect(duplicate?.json()).resolves.toMatchObject({
|
||||
ok: true,
|
||||
duplicate: true,
|
||||
task: { id: 'web-task-task-create-1' },
|
||||
});
|
||||
expect(tasks).toHaveLength(1);
|
||||
expect(nudges).toBe(1);
|
||||
});
|
||||
|
||||
it('handles task actions, edits, invalid watchers, and fall-through', async () => {
|
||||
const tasks = new Map<string, ScheduledTask>([
|
||||
['active-task', makeTask({ id: 'active-task' })],
|
||||
[
|
||||
'watch-task',
|
||||
makeTask({
|
||||
id: 'watch-task',
|
||||
prompt: '[BACKGROUND CI WATCH]\nwatch',
|
||||
}),
|
||||
],
|
||||
]);
|
||||
const deps = makeDeps(tasks);
|
||||
|
||||
const pause = await route({
|
||||
pathname: '/api/tasks/active-task/actions',
|
||||
method: 'POST',
|
||||
body: { action: 'pause' },
|
||||
deps,
|
||||
});
|
||||
expect(pause?.status).toBe(200);
|
||||
await expect(pause?.json()).resolves.toMatchObject({
|
||||
ok: true,
|
||||
task: { id: 'active-task', status: 'paused' },
|
||||
});
|
||||
expect(tasks.get('active-task')).toMatchObject({
|
||||
status: 'paused',
|
||||
suspended_until: null,
|
||||
});
|
||||
|
||||
const edit = await route({
|
||||
pathname: '/api/tasks/active-task',
|
||||
method: 'PATCH',
|
||||
body: {
|
||||
prompt: 'watch every minute',
|
||||
scheduleType: 'interval',
|
||||
scheduleValue: '60000',
|
||||
},
|
||||
deps,
|
||||
now: () => '2026-04-26T05:10:00.000Z',
|
||||
});
|
||||
expect(edit?.status).toBe(200);
|
||||
expect(tasks.get('active-task')).toMatchObject({
|
||||
next_run: '2026-04-26T05:11:00.000Z',
|
||||
prompt: 'watch every minute',
|
||||
schedule_type: 'interval',
|
||||
schedule_value: '60000',
|
||||
suspended_until: null,
|
||||
});
|
||||
|
||||
const watcherEdit = await route({
|
||||
pathname: '/api/tasks/watch-task',
|
||||
method: 'PATCH',
|
||||
body: { prompt: 'run again' },
|
||||
deps,
|
||||
});
|
||||
expect(watcherEdit?.status).toBe(409);
|
||||
|
||||
const wrongMethod = await route({
|
||||
pathname: '/api/tasks/active-task/actions',
|
||||
method: 'GET',
|
||||
deps,
|
||||
});
|
||||
expect(wrongMethod?.status).toBe(405);
|
||||
|
||||
const unmatched = await route({
|
||||
pathname: '/api/overview',
|
||||
method: 'GET',
|
||||
deps,
|
||||
});
|
||||
expect(unmatched).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,441 +0,0 @@
|
||||
import { CronExpressionParser } from 'cron-parser';
|
||||
import {
|
||||
DEFAULT_TASK_CONTEXT_MODE,
|
||||
isTaskContextMode,
|
||||
} from 'ejclaw-runners-shared';
|
||||
|
||||
import { TIMEZONE } from './config.js';
|
||||
import { isWatchCiTask } from './task-watch-status.js';
|
||||
import type { AgentType, RegisteredGroup, ScheduledTask } from './types.js';
|
||||
import { sanitizeScheduledTask } from './web-dashboard-data.js';
|
||||
|
||||
type JsonResponse = (
|
||||
value: unknown,
|
||||
init?: ResponseInit,
|
||||
request?: Request,
|
||||
) => Response;
|
||||
|
||||
type TaskAction = 'pause' | 'resume' | 'cancel';
|
||||
|
||||
interface ScheduledTaskMutationBody {
|
||||
roomJid?: unknown;
|
||||
groupFolder?: unknown;
|
||||
prompt?: unknown;
|
||||
scheduleType?: unknown;
|
||||
scheduleValue?: unknown;
|
||||
contextMode?: unknown;
|
||||
agentType?: unknown;
|
||||
requestId?: unknown;
|
||||
}
|
||||
|
||||
type ScheduledTaskCreateInput = Pick<
|
||||
ScheduledTask,
|
||||
| 'id'
|
||||
| 'group_folder'
|
||||
| 'chat_jid'
|
||||
| 'prompt'
|
||||
| 'schedule_type'
|
||||
| 'schedule_value'
|
||||
| 'context_mode'
|
||||
| 'next_run'
|
||||
| 'status'
|
||||
| 'created_at'
|
||||
> & {
|
||||
agent_type?: AgentType | null;
|
||||
};
|
||||
|
||||
type ScheduledTaskUpdateInput = Partial<
|
||||
Pick<
|
||||
ScheduledTask,
|
||||
| 'prompt'
|
||||
| 'schedule_type'
|
||||
| 'schedule_value'
|
||||
| 'next_run'
|
||||
| 'status'
|
||||
| 'suspended_until'
|
||||
>
|
||||
>;
|
||||
|
||||
export interface ScheduledTaskRouteDependencies {
|
||||
createScheduledTask: (task: ScheduledTaskCreateInput) => void;
|
||||
loadRoomBindings?: () => Record<string, RegisteredGroup>;
|
||||
loadTaskById: (id: string) => ScheduledTask | undefined;
|
||||
mutateTask: (id: string, updates: ScheduledTaskUpdateInput) => void;
|
||||
nudgeScheduler?: () => void;
|
||||
removeTask: (id: string) => void;
|
||||
}
|
||||
|
||||
interface ScheduledTaskRouteContext extends ScheduledTaskRouteDependencies {
|
||||
url: URL;
|
||||
request: Request;
|
||||
jsonResponse: JsonResponse;
|
||||
now?: () => string;
|
||||
}
|
||||
|
||||
const WEB_TASK_PROMPT_MAX_LENGTH = 8000;
|
||||
|
||||
function parseTaskPath(pathname: string): string | null {
|
||||
const match = pathname.match(/^\/api\/tasks\/([^/]+)$/);
|
||||
if (!match) return null;
|
||||
try {
|
||||
return decodeURIComponent(match[1]);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function parseTaskActionPath(pathname: string): string | null {
|
||||
const match = pathname.match(/^\/api\/tasks\/([^/]+)\/actions$/);
|
||||
if (!match) return null;
|
||||
try {
|
||||
return decodeURIComponent(match[1]);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function isTaskAction(value: unknown): value is TaskAction {
|
||||
return value === 'pause' || value === 'resume' || value === 'cancel';
|
||||
}
|
||||
|
||||
function isScheduleType(
|
||||
value: unknown,
|
||||
): value is ScheduledTask['schedule_type'] {
|
||||
return value === 'cron' || value === 'interval' || value === 'once';
|
||||
}
|
||||
|
||||
function isAgentType(value: unknown): value is AgentType {
|
||||
return value === 'claude-code' || value === 'codex';
|
||||
}
|
||||
|
||||
async function readTaskAction(request: Request): Promise<TaskAction | null> {
|
||||
try {
|
||||
const body = (await request.json()) as { action?: unknown };
|
||||
return isTaskAction(body.action) ? body.action : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function readScheduledTaskMutationBody(
|
||||
request: Request,
|
||||
): Promise<ScheduledTaskMutationBody | null> {
|
||||
try {
|
||||
return (await request.json()) as ScheduledTaskMutationBody;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeNonEmptyString(value: unknown): string | null {
|
||||
if (typeof value !== 'string') return null;
|
||||
const trimmed = value.trim();
|
||||
return trimmed ? trimmed : null;
|
||||
}
|
||||
|
||||
function normalizeTaskPrompt(value: unknown): string | null {
|
||||
const prompt = normalizeNonEmptyString(value);
|
||||
if (!prompt) return null;
|
||||
return prompt.length > WEB_TASK_PROMPT_MAX_LENGTH
|
||||
? prompt.slice(0, WEB_TASK_PROMPT_MAX_LENGTH)
|
||||
: prompt;
|
||||
}
|
||||
|
||||
function computeInitialNextRun(
|
||||
scheduleType: ScheduledTask['schedule_type'],
|
||||
scheduleValue: string,
|
||||
nowIso: string,
|
||||
): { nextRun: string | null; error?: string } {
|
||||
if (scheduleType === 'cron') {
|
||||
try {
|
||||
const interval = CronExpressionParser.parse(scheduleValue, {
|
||||
tz: TIMEZONE,
|
||||
});
|
||||
return { nextRun: interval.next().toISOString() };
|
||||
} catch {
|
||||
return { nextRun: null, error: 'Invalid cron schedule' };
|
||||
}
|
||||
}
|
||||
|
||||
if (scheduleType === 'interval') {
|
||||
const ms = Number.parseInt(scheduleValue, 10);
|
||||
if (!Number.isFinite(ms) || ms <= 0) {
|
||||
return { nextRun: null, error: 'Invalid interval schedule' };
|
||||
}
|
||||
return {
|
||||
nextRun: new Date(new Date(nowIso).getTime() + ms).toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
const date = new Date(scheduleValue);
|
||||
if (Number.isNaN(date.getTime())) {
|
||||
return { nextRun: null, error: 'Invalid timestamp schedule' };
|
||||
}
|
||||
return { nextRun: date.toISOString() };
|
||||
}
|
||||
|
||||
function resolveTaskRoom(
|
||||
body: ScheduledTaskMutationBody,
|
||||
roomBindings: Record<string, RegisteredGroup>,
|
||||
): { chatJid: string; group: RegisteredGroup } | null {
|
||||
const roomJid = normalizeNonEmptyString(body.roomJid);
|
||||
const groupFolder = normalizeNonEmptyString(body.groupFolder);
|
||||
if (roomJid && roomBindings[roomJid]) {
|
||||
return { chatJid: roomJid, group: roomBindings[roomJid] };
|
||||
}
|
||||
if (groupFolder) {
|
||||
const match = Object.entries(roomBindings).find(
|
||||
([, group]) => group.folder === groupFolder,
|
||||
);
|
||||
if (match) return { chatJid: match[0], group: match[1] };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function makeWebTaskId(): string {
|
||||
return `web-task-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
|
||||
}
|
||||
|
||||
function sanitizeScheduledTaskRequestId(value: unknown): string | null {
|
||||
if (typeof value !== 'string') return null;
|
||||
const trimmed = value.trim();
|
||||
if (!trimmed) return null;
|
||||
const safe = trimmed.replace(/[^A-Za-z0-9._:-]/g, '-').slice(0, 120);
|
||||
return safe || null;
|
||||
}
|
||||
|
||||
function makeWebTaskIdFromRequest(requestId: string | null): string {
|
||||
return requestId ? `web-task-${requestId}` : makeWebTaskId();
|
||||
}
|
||||
|
||||
async function handleTaskActionRoute(
|
||||
context: ScheduledTaskRouteContext,
|
||||
taskId: string,
|
||||
): Promise<Response> {
|
||||
const { request, jsonResponse, loadTaskById, mutateTask, removeTask } =
|
||||
context;
|
||||
if (request.method !== 'POST') {
|
||||
return jsonResponse({ error: 'Method not allowed' }, { status: 405 });
|
||||
}
|
||||
|
||||
const action = await readTaskAction(request);
|
||||
if (!action) {
|
||||
return jsonResponse({ error: 'Invalid task action' }, { status: 400 });
|
||||
}
|
||||
|
||||
const task = loadTaskById(taskId);
|
||||
if (!task) {
|
||||
return jsonResponse({ error: 'Task not found' }, { status: 404 });
|
||||
}
|
||||
|
||||
if (task.status === 'completed' && action !== 'cancel') {
|
||||
return jsonResponse(
|
||||
{ error: 'Completed tasks cannot be changed' },
|
||||
{ status: 409 },
|
||||
);
|
||||
}
|
||||
|
||||
if (action === 'cancel') {
|
||||
removeTask(taskId);
|
||||
return jsonResponse({ ok: true, id: taskId, deleted: true });
|
||||
}
|
||||
|
||||
mutateTask(taskId, {
|
||||
status: action === 'pause' ? 'paused' : 'active',
|
||||
suspended_until: null,
|
||||
});
|
||||
|
||||
const updatedTask = loadTaskById(taskId);
|
||||
return jsonResponse({
|
||||
ok: true,
|
||||
task: updatedTask ? sanitizeScheduledTask(updatedTask) : null,
|
||||
});
|
||||
}
|
||||
|
||||
async function handleTaskCreateRoute(
|
||||
context: ScheduledTaskRouteContext,
|
||||
): Promise<Response> {
|
||||
const {
|
||||
createScheduledTask,
|
||||
jsonResponse,
|
||||
loadRoomBindings,
|
||||
loadTaskById,
|
||||
nudgeScheduler,
|
||||
request,
|
||||
now,
|
||||
} = context;
|
||||
if (!loadRoomBindings) {
|
||||
return jsonResponse(
|
||||
{ error: 'Task creation is not configured' },
|
||||
{ status: 503 },
|
||||
);
|
||||
}
|
||||
|
||||
const body = await readScheduledTaskMutationBody(request);
|
||||
const prompt = normalizeTaskPrompt(body?.prompt);
|
||||
const scheduleType =
|
||||
body && isScheduleType(body.scheduleType) ? body.scheduleType : null;
|
||||
const scheduleValue = normalizeNonEmptyString(body?.scheduleValue);
|
||||
if (!body || !prompt || !scheduleType || !scheduleValue) {
|
||||
return jsonResponse(
|
||||
{ error: 'Task prompt, schedule type, and schedule value are required' },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
const room = resolveTaskRoom(body, loadRoomBindings());
|
||||
if (!room) {
|
||||
return jsonResponse({ error: 'Room not found' }, { status: 404 });
|
||||
}
|
||||
|
||||
const nowIso = now?.() ?? new Date().toISOString();
|
||||
const next = computeInitialNextRun(scheduleType, scheduleValue, nowIso);
|
||||
if (next.error) {
|
||||
return jsonResponse({ error: next.error }, { status: 400 });
|
||||
}
|
||||
|
||||
const contextMode = isTaskContextMode(body.contextMode)
|
||||
? body.contextMode
|
||||
: DEFAULT_TASK_CONTEXT_MODE;
|
||||
const agentType = isAgentType(body.agentType)
|
||||
? body.agentType
|
||||
: (room.group.agentType ?? 'claude-code');
|
||||
const requestId = sanitizeScheduledTaskRequestId(body.requestId);
|
||||
const id = makeWebTaskIdFromRequest(requestId);
|
||||
const existing = requestId ? loadTaskById(id) : undefined;
|
||||
if (existing) {
|
||||
return jsonResponse({
|
||||
ok: true,
|
||||
duplicate: true,
|
||||
task: sanitizeScheduledTask(existing),
|
||||
});
|
||||
}
|
||||
|
||||
createScheduledTask({
|
||||
id,
|
||||
group_folder: room.group.folder,
|
||||
chat_jid: room.chatJid,
|
||||
agent_type: agentType,
|
||||
prompt,
|
||||
schedule_type: scheduleType,
|
||||
schedule_value: scheduleValue,
|
||||
context_mode: contextMode,
|
||||
next_run: next.nextRun,
|
||||
status: 'active',
|
||||
created_at: nowIso,
|
||||
});
|
||||
|
||||
const created = loadTaskById(id);
|
||||
if (
|
||||
next.nextRun &&
|
||||
new Date(next.nextRun).getTime() <= new Date(nowIso).getTime()
|
||||
) {
|
||||
nudgeScheduler?.();
|
||||
}
|
||||
return jsonResponse({
|
||||
ok: true,
|
||||
task: created ? sanitizeScheduledTask(created) : null,
|
||||
});
|
||||
}
|
||||
|
||||
async function handleTaskUpdateRoute(
|
||||
context: ScheduledTaskRouteContext,
|
||||
taskId: string,
|
||||
): Promise<Response> {
|
||||
const { jsonResponse, loadTaskById, mutateTask, request, now } = context;
|
||||
const task = loadTaskById(taskId);
|
||||
if (!task) {
|
||||
return jsonResponse({ error: 'Task not found' }, { status: 404 });
|
||||
}
|
||||
if (task.status === 'completed') {
|
||||
return jsonResponse(
|
||||
{ error: 'Completed tasks cannot be edited' },
|
||||
{ status: 409 },
|
||||
);
|
||||
}
|
||||
if (isWatchCiTask(task)) {
|
||||
return jsonResponse(
|
||||
{ error: 'CI watchers cannot be edited here' },
|
||||
{ status: 409 },
|
||||
);
|
||||
}
|
||||
|
||||
const body = await readScheduledTaskMutationBody(request);
|
||||
if (!body) {
|
||||
return jsonResponse({ error: 'Invalid task update' }, { status: 400 });
|
||||
}
|
||||
if (
|
||||
body.roomJid !== undefined ||
|
||||
body.groupFolder !== undefined ||
|
||||
body.contextMode !== undefined ||
|
||||
body.agentType !== undefined
|
||||
) {
|
||||
return jsonResponse(
|
||||
{ error: 'Task room, context, and agent cannot be edited here' },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
const prompt =
|
||||
body.prompt === undefined ? task.prompt : normalizeTaskPrompt(body.prompt);
|
||||
const scheduleChanged =
|
||||
body.scheduleType !== undefined || body.scheduleValue !== undefined;
|
||||
const scheduleType =
|
||||
body.scheduleType === undefined
|
||||
? task.schedule_type
|
||||
: isScheduleType(body.scheduleType)
|
||||
? body.scheduleType
|
||||
: null;
|
||||
const scheduleValue =
|
||||
body.scheduleValue === undefined
|
||||
? task.schedule_value
|
||||
: normalizeNonEmptyString(body.scheduleValue);
|
||||
if (!prompt || !scheduleType || !scheduleValue) {
|
||||
return jsonResponse({ error: 'Invalid task update' }, { status: 400 });
|
||||
}
|
||||
|
||||
const updates: ScheduledTaskUpdateInput = {
|
||||
prompt,
|
||||
schedule_type: scheduleType,
|
||||
schedule_value: scheduleValue,
|
||||
};
|
||||
|
||||
if (scheduleChanged) {
|
||||
const next = computeInitialNextRun(
|
||||
scheduleType,
|
||||
scheduleValue,
|
||||
now?.() ?? new Date().toISOString(),
|
||||
);
|
||||
if (next.error) {
|
||||
return jsonResponse({ error: next.error }, { status: 400 });
|
||||
}
|
||||
updates.next_run = next.nextRun;
|
||||
updates.suspended_until = null;
|
||||
}
|
||||
|
||||
mutateTask(taskId, updates);
|
||||
const updatedTask = loadTaskById(taskId);
|
||||
return jsonResponse({
|
||||
ok: true,
|
||||
task: updatedTask ? sanitizeScheduledTask(updatedTask) : null,
|
||||
});
|
||||
}
|
||||
|
||||
export async function handleScheduledTaskRoute(
|
||||
context: ScheduledTaskRouteContext,
|
||||
): Promise<Response | null> {
|
||||
const { request, url } = context;
|
||||
const actionTaskId = parseTaskActionPath(url.pathname);
|
||||
if (actionTaskId) return handleTaskActionRoute(context, actionTaskId);
|
||||
|
||||
if (url.pathname === '/api/tasks' && request.method === 'POST') {
|
||||
return handleTaskCreateRoute(context);
|
||||
}
|
||||
|
||||
const taskId = parseTaskPath(url.pathname);
|
||||
if (taskId && request.method === 'PATCH') {
|
||||
return handleTaskUpdateRoute(context, taskId);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
Reference in New Issue
Block a user