mirror of
https://github.com/Ark0N/Codeman.git
synced 2026-11-15 18:59:33 +01:00
Claude Code lets a subscription's one-hour prompt cache expire after an hour idle, and the first turn back re-writes the whole conversation at the cache-write rate; nearly every gap over an hour goes cold, while the saving is concentrated in gaps of one to four hours. Codeman now sends one short keep-alive turn five minutes before the expiry Claude Code reports on its statusline, so the next real prompt still reads the conversation from cache, and stops two hours (configurable) after the last real prompt. Codeman owns the idle policy for these sessions, as agreed in Discussion #554: a launch with keep-warm on also carries idleCompaction: false in its one --settings JSON, so Claude Code's own idle compaction cannot replace the conversation with a summary a minute before the nudge. It is decided once per launch (keep-warm on, the statusLine exporter injected, Claude Code 2.1.290 or newer, an unknown version fails closed like --name), recorded on the mux record, and picked up by any relaunch; a launch with keep-warm off is byte-identical. A session switched on after launch is kept warm best-effort and the readout says so. Every guard lives in one pure rulebook: the opt-in (an agent-spawned session does not inherit the app default), a launch that reports cache state, a warm 1h cache with enough tokens at stake and no compaction this gap, a live pane, no usage-limit pause, no respawn, Ralph, task or waiting agent, idle, no open dialog, an empty composer and no recent keystroke. The nudge is a submit and moves lastSubmitAt, which the response viewer's conversation correlation needs; the cap counts from its own persisted lastRealPromptAt instead. Read My Mind drops the exact nudge text, and the turn's stop hook and idle prompt open pre-acknowledged so nothing alerts. The last cache report and the clock survive a restart, so the timer re-arms.
186 lines
6.8 KiB
TypeScript
186 lines
6.8 KiB
TypeScript
/**
|
|
* Mock context for route handler testing.
|
|
*
|
|
* Satisfies ALL port interfaces (SessionPort, EventPort, RespawnPort,
|
|
* ConfigPort, InfraPort, AuthPort) so any route module can be tested.
|
|
* Override specific methods in individual tests as needed.
|
|
*
|
|
* Uses app.inject() — no real HTTP ports needed.
|
|
*/
|
|
import { vi } from 'vitest';
|
|
import { MockSession, createMockSession } from './mock-session.js';
|
|
import { resolveTerminalHistoryConfig } from '../../src/config/terminal-history.js';
|
|
|
|
/**
|
|
* Creates a mock context that satisfies all port interfaces.
|
|
* Pre-populated with one session for convenience.
|
|
*/
|
|
export function createMockRouteContext(options?: {
|
|
sessionId?: string;
|
|
agentSkillEnabled?: boolean;
|
|
claudeVoiceEnabled?: boolean;
|
|
workspaceHooksEnabled?: boolean;
|
|
}) {
|
|
const sessionId = options?.sessionId ?? 'test-session-1';
|
|
const session = createMockSession(sessionId);
|
|
const sessions = new Map<string, MockSession>();
|
|
sessions.set(sessionId, session);
|
|
|
|
// Stateful backing for the global tab order (COD-131) so route tests can
|
|
// assert that setSessionOrder() actually persists what the handler computed.
|
|
let sessionOrder: string[] = [];
|
|
|
|
return {
|
|
// -- SessionPort --
|
|
sessions,
|
|
addSession: vi.fn(async (s: MockSession) => {
|
|
sessions.set(s.id, s);
|
|
}),
|
|
tabLayouts: {
|
|
get: vi.fn(),
|
|
put: vi.fn(),
|
|
putLegacyOrder: vi.fn(async (_actor: unknown, order: readonly string[]) => ({
|
|
order: [...order],
|
|
changedOwnerOrders: {},
|
|
globalOrder: [...order],
|
|
globalChanged: false,
|
|
})),
|
|
sessionCreated: vi.fn(),
|
|
webviewCreated: vi.fn(),
|
|
sessionsRemoved: vi.fn(async () => {}),
|
|
webviewDeleted: vi.fn(async () => {}),
|
|
markRestorationComplete: vi.fn(),
|
|
markRestorationFailed: vi.fn(),
|
|
markRestorationSkipped: vi.fn(),
|
|
assertDeletionReady: vi.fn(),
|
|
runSessionDeletion: vi.fn(async (_removed, action) => action()),
|
|
runStaleSessionCleanup: vi.fn(async (_activeIds, action) => action(new Set())),
|
|
reconcileAfterRestoration: vi.fn(async () => {}),
|
|
},
|
|
cleanupSession: vi.fn(async () => {}),
|
|
setupSessionListeners: vi.fn(async () => {}),
|
|
persistSessionState: vi.fn(),
|
|
persistSessionStateNow: vi.fn(),
|
|
reapplyPersistedSessionState: vi.fn(async () => {}),
|
|
discardPartiallyBuiltSession: vi.fn(async (id: string) => {
|
|
sessions.delete(id);
|
|
}),
|
|
getSessionStateWithRespawn: vi.fn((s: MockSession) => s.toState()),
|
|
|
|
// -- EventPort --
|
|
broadcast: vi.fn(),
|
|
sendPushNotifications: vi.fn(),
|
|
batchTerminalData: vi.fn(),
|
|
broadcastSessionStateDebounced: vi.fn(),
|
|
batchTaskUpdate: vi.fn(),
|
|
getSseClientCount: vi.fn(() => 0),
|
|
|
|
// -- RespawnPort --
|
|
respawnControllers: new Map(),
|
|
respawnTimers: new Map(),
|
|
setupRespawnListeners: vi.fn(),
|
|
setupTimedRespawn: vi.fn(),
|
|
restoreRespawnController: vi.fn(),
|
|
saveRespawnConfig: vi.fn(),
|
|
|
|
// -- KeepWarmPort --
|
|
keepWarm: { schedule: vi.fn(), rescheduleAll: vi.fn(), remove: vi.fn() },
|
|
|
|
// -- ConfigPort --
|
|
store: {
|
|
getConfig: vi.fn(() => ({ ralphEnabled: false, maxConcurrentSessions: 5 })),
|
|
getSessions: vi.fn(() => ({})),
|
|
getSession: vi.fn(),
|
|
setSession: vi.fn(),
|
|
removeSession: vi.fn(),
|
|
demoteOrRemoveSession: vi.fn(() => 'removed' as const),
|
|
getSettings: vi.fn(() => ({})),
|
|
setSettings: vi.fn(),
|
|
getRalphLoopState: vi.fn(() => ({})),
|
|
setRalphLoopState: vi.fn(),
|
|
getTasks: vi.fn(() => ({})),
|
|
save: vi.fn(),
|
|
load: vi.fn(),
|
|
incrementSessionsCreated: vi.fn(),
|
|
setConfig: vi.fn(),
|
|
getSessionOrder: vi.fn(() => sessionOrder),
|
|
setSessionOrder: vi.fn((order: string[]) => {
|
|
sessionOrder = order;
|
|
}),
|
|
getAggregateStats: vi.fn(() => ({ totalInputTokens: 0, totalOutputTokens: 0, totalCost: 0 })),
|
|
getGlobalStats: vi.fn(() => ({ sessionsCreated: 0 })),
|
|
getDailyStats: vi.fn(() => []),
|
|
cleanupStaleSessions: vi.fn(() => ({ count: 0, cleaned: [] })),
|
|
cleanupSessionsByIds: vi.fn(() => ({ count: 0, cleaned: [] })),
|
|
},
|
|
port: 3000,
|
|
https: false,
|
|
testMode: true,
|
|
serverStartTime: Date.now(),
|
|
getGlobalNiceConfig: vi.fn(async () => undefined),
|
|
getModelConfig: vi.fn(async () => null),
|
|
getClaudeModeConfig: vi.fn(async () => ({})),
|
|
getTerminalHistoryConfig: vi.fn(async () => resolveTerminalHistoryConfig({})),
|
|
// Default OFF mirrors the shipped setting, so existing tests never touch a
|
|
// case's .claude/skills. Overridable per test because the create-time
|
|
// injection call sites are otherwise unreachable from a route test.
|
|
getAgentSkillEnabled: vi.fn(async () => options?.agentSkillEnabled ?? false),
|
|
// Default OFF mirrors the shipped setting: no test opens a voice relay by accident.
|
|
getClaudeVoiceEnabled: vi.fn(async () => options?.claudeVoiceEnabled ?? false),
|
|
// Default ON mirrors the shipped setting, so a route test sees what a user sees.
|
|
// Writes land in the test's temp working dir, never in a real repo.
|
|
getWorkspaceHooksEnabled: vi.fn(async () => options?.workspaceHooksEnabled ?? true),
|
|
getDefaultClaudeMdPath: vi.fn(async () => undefined),
|
|
getLightState: vi.fn(() => ({ sessions: [], status: 'ok' })),
|
|
getLightSessionsState: vi.fn(() => {
|
|
const result: Record<string, unknown>[] = [];
|
|
for (const s of sessions.values()) {
|
|
result.push(s.toState());
|
|
}
|
|
return result;
|
|
}),
|
|
startTranscriptWatcher: vi.fn(),
|
|
stopTranscriptWatcher: vi.fn(),
|
|
getTranscriptPath: vi.fn(() => null),
|
|
getReadMyMindModel: vi.fn(async () => 'claude-opus-4-5-20251101'),
|
|
|
|
// -- InfraPort --
|
|
mux: {
|
|
muxSocket: 'codeman',
|
|
createSession: vi.fn(),
|
|
killSession: vi.fn(),
|
|
listSessions: vi.fn(() => []),
|
|
getStats: vi.fn(() => ({})),
|
|
updateSessionName: vi.fn(() => true),
|
|
getSession: vi.fn(() => null),
|
|
clearRespawnConfig: vi.fn(),
|
|
updateRespawnConfig: vi.fn(),
|
|
setHistoryLimit: vi.fn(async () => {}),
|
|
startStatsCollection: vi.fn(),
|
|
},
|
|
runSummaryTrackers: new Map(),
|
|
activePlanOrchestrators: new Map(),
|
|
scheduledRuns: new Map(),
|
|
teamWatcher: { getTeams: vi.fn(() => []), getTeamTasks: vi.fn(() => []), hasActiveTeammates: vi.fn(() => false) },
|
|
tunnelManager: null,
|
|
pushStore: null,
|
|
startScheduledRun: vi.fn(),
|
|
stopScheduledRun: vi.fn(),
|
|
|
|
// -- AuthPort --
|
|
authSessions: null,
|
|
qrAuthFailures: null,
|
|
// https already declared above in ConfigPort (shared property)
|
|
|
|
// -- OrchestratorPort --
|
|
orchestratorLoop: null,
|
|
initOrchestratorLoop: vi.fn(),
|
|
|
|
// Convenience accessors (not part of any port interface)
|
|
_session: session,
|
|
_sessionId: sessionId,
|
|
};
|
|
}
|
|
|
|
export type MockRouteContext = ReturnType<typeof createMockRouteContext>;
|