summaryrefslogtreecommitdiffhomepage
path: root/packages/cache-warming/src/warmer.ts
blob: 6ad5c33a8e8fb8e8af0dbfd4ca65b884c20323f0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
import type { Logger, StorageNamespace } from "@dispatch/kernel";
import type { WarmCompletedPayload, WarmService } from "@dispatch/session-orchestrator";
import {
	type ConversationContext,
	type ConversationSettings,
	type ConversationState,
	computeCachePct,
	computeExpectedCacheRate,
	DEFAULT_INTERVAL_MS,
	MIN_INTERVAL_MS,
	parseSettings,
	serializeSettings,
	settingsKey,
	shouldWarm,
} from "./pure.js";

// --- Timer abstraction (injectable for tests) ---

export interface TimerDeps {
	readonly setTimer: (fn: () => void, ms: number) => number;
	readonly clearTimer: (id: number) => void;
}

// --- Warmer interface ---

export interface CacheWarmer {
	/** Handle a turnStarted event — mark conversation active, cancel pending warm. */
	readonly onTurnStarted: (conversationId: string) => void;

	/** Handle a turnSettled event — mark idle, store context, arm timer if enabled. */
	readonly onTurnSettled: (conversationId: string, ctx: ConversationContext) => void;

	/** Handle a warmCompleted event — process warm result, re-arm timer, update surface. */
	readonly onWarmCompleted: (payload: WarmCompletedPayload) => void;

	/**
	 * Handle an explicit "conversation closed" (tab close ≠ disconnect): stop the
	 * schedule and persist warming OFF for the conversation. The enabled flip is
	 * applied to in-memory state synchronously (so a turnSettled racing this close
	 * can never re-arm); only the settings persist is awaited.
	 */
	readonly onConversationClosed: (conversationId: string) => Promise<void>;

	/** Get the current state for a conversation (for surface rendering). */
	readonly getState: (conversationId: string) => ConversationState;

	/** Get the stored context for a conversation. */
	readonly getContext: (conversationId: string) => ConversationContext;

	/** Toggle enabled for a conversation. Returns updated settings. */
	readonly setEnabled: (conversationId: string, enabled: boolean) => Promise<ConversationSettings>;

	/** Set the refresh interval for a conversation. Returns updated settings. */
	readonly setIntervalMs: (
		conversationId: string,
		intervalMs: number,
	) => Promise<ConversationSettings>;

	/** Dispose all timers (for cleanup). */
	readonly dispose: () => void;
}

export interface CacheWarmerDeps {
	readonly warm: WarmService["warm"];
	readonly storage: StorageNamespace;
	readonly logger: Logger;
	readonly timers: TimerDeps;
	/** Injected clock — returns epoch-ms. */
	readonly now: () => number;
	/** Called when surface subscribers should re-fetch the spec. */
	readonly onSurfaceChange: () => void;
}

// Warming is OPT-IN per conversation (CR-4a): default OFF, no warm scheduled
// until the user enables it.
const DEFAULT_STATE: ConversationState = {
	enabled: false,
	intervalMs: DEFAULT_INTERVAL_MS,
	active: false,
	lastPct: null,
	lastExpectedPct: null,
	lastWarmAt: null,
	nextWarmAt: null,
	token: 0,
};

export function createCacheWarmer(deps: CacheWarmerDeps): CacheWarmer {
	// Per-conversation runtime state (not persisted — reconstructed from storage + events)
	const states = new Map<string, ConversationState>();
	// Per-conversation context from latest lifecycle event
	const contexts = new Map<string, ConversationContext>();
	// Per-conversation pending timer id
	const timers = new Map<string, number>();
	// Monotonic token per conversation for in-flight invalidation
	let nextToken = 1;

	function getState(conversationId: string): ConversationState {
		return states.get(conversationId) ?? DEFAULT_STATE;
	}

	function getContext(conversationId: string): ConversationContext {
		return contexts.get(conversationId) ?? {};
	}

	function setState(conversationId: string, state: ConversationState): void {
		states.set(conversationId, state);
	}

	function cancelTimer(conversationId: string): void {
		const existing = timers.get(conversationId);
		if (existing !== undefined) {
			deps.timers.clearTimer(existing);
			timers.delete(conversationId);
		}
		mergeState(conversationId, { nextWarmAt: null });
	}

	function armTimer(conversationId: string): void {
		cancelTimer(conversationId);
		const state = getState(conversationId);
		if (!state.enabled || state.active) return;

		const token = nextToken++;
		const nowMs = deps.now();
		const nextWarmAt = nowMs + state.intervalMs;
		setState(conversationId, { ...state, token, nextWarmAt });

		const timerId = deps.timers.setTimer(() => {
			timers.delete(conversationId);
			void fireWarm(conversationId, token);
		}, state.intervalMs);

		timers.set(conversationId, timerId);
	}

	async function fireWarm(conversationId: string, token: number): Promise<void> {
		const state = getState(conversationId);
		if (!shouldWarm(state, token)) {
			deps.logger.debug("cache-warming: skip warm (superseded or disabled)", {
				conversationId,
			});
			return;
		}

		const ctx = getContext(conversationId);
		deps.logger.debug("cache-warming: firing warm", { conversationId });

		await deps.warm(conversationId, {
			...(ctx.cwd !== undefined ? { cwd: ctx.cwd } : {}),
			...(ctx.modelName !== undefined ? { modelName: ctx.modelName } : {}),
		});

		// Result processing is handled by the warmCompleted event handler.
		// Timer re-arm is also handled there on success.
	}

	async function loadSettings(conversationId: string): Promise<ConversationSettings> {
		const raw = await deps.storage.get(settingsKey(conversationId));
		return parseSettings(raw);
	}

	async function persistSettings(
		conversationId: string,
		settings: ConversationSettings,
	): Promise<void> {
		await deps.storage.set(settingsKey(conversationId), serializeSettings(settings));
	}

	function mergeState(
		conversationId: string,
		partial: Partial<ConversationState>,
	): ConversationState {
		const current = getState(conversationId);
		const updated = { ...current, ...partial };
		setState(conversationId, updated);
		return updated;
	}

	return {
		onTurnStarted(conversationId) {
			deps.logger.debug("cache-warming: turn started", { conversationId });
			mergeState(conversationId, { active: true });
			cancelTimer(conversationId);
			// Push the cleared schedule (nextWarmAt: null) so subscribers see
			// "no warm scheduled" while the turn is generating.
			deps.onSurfaceChange();
		},

		onTurnSettled(conversationId, ctx) {
			deps.logger.debug("cache-warming: turn settled", { conversationId });
			contexts.set(conversationId, ctx);
			mergeState(conversationId, { active: false });

			const state = getState(conversationId);
			if (state.enabled) {
				armTimer(conversationId);
			}
			// Push the post-seal reschedule so subscribers get the NEW (future)
			// nextWarmAt instead of a stale pre-turn one (CR-4b).
			deps.onSurfaceChange();
		},

		onWarmCompleted(payload) {
			const { conversationId, usage } = payload;
			const state = getState(conversationId);

			// Drop if the conversation became active while the warm was in flight
			if (state.active) {
				deps.logger.debug("cache-warming: dropping warm result (conversation active)", {
					conversationId,
				});
				return;
			}

			const pct = computeCachePct(usage.inputTokens, usage.cacheReadTokens);
			const expectedPct = computeExpectedCacheRate(usage.cacheReadTokens, usage.cacheWriteTokens);
			const nowMs = deps.now();
			setState(conversationId, {
				...state,
				lastPct: pct,
				lastExpectedPct: expectedPct,
				lastWarmAt: nowMs,
				// The just-fired schedule is consumed; cleared here so a non-re-armed
				// path never reports a stale (past) nextWarmAt.
				nextWarmAt: null,
			});

			// Re-arm the automatic timer if enabled and not active — BEFORE the
			// surface notify, so the pushed update carries the NEW future nextWarmAt
			// instead of the fire time of the warm that just completed (CR-4b).
			const updated = getState(conversationId);
			if (updated.enabled && !updated.active) {
				armTimer(conversationId);
			}

			deps.onSurfaceChange();
			deps.logger.debug("cache-warming: warm complete", {
				conversationId,
				pct,
				expectedPct,
			});
		},

		getState,
		getContext,

		async onConversationClosed(conversationId) {
			deps.logger.debug("cache-warming: conversation closed", { conversationId });
			// Synchronous part FIRST: stop the schedule + flip enabled in memory so
			// any racing turnSettled sees enabled=false and never re-arms.
			cancelTimer(conversationId);
			const updated = mergeState(conversationId, { enabled: false });
			deps.onSurfaceChange();
			// Persist OFF so a reopened conversation stays opt-in.
			await persistSettings(conversationId, {
				enabled: false,
				intervalMs: updated.intervalMs,
			});
		},

		async setEnabled(conversationId, enabled) {
			const settings = await loadSettings(conversationId);
			const updated = { ...settings, enabled };
			await persistSettings(conversationId, updated);
			// Merge the FULL settings (not just `enabled`) so re-enabling restores
			// the persisted interval into runtime state.
			mergeState(conversationId, updated);

			if (enabled) {
				const state = getState(conversationId);
				if (!state.active) {
					armTimer(conversationId);
				}
			} else {
				cancelTimer(conversationId);
			}

			deps.onSurfaceChange();
			return updated;
		},

		async setIntervalMs(conversationId, intervalMs) {
			const clamped =
				!Number.isFinite(intervalMs) || intervalMs <= 0
					? MIN_INTERVAL_MS
					: Math.max(MIN_INTERVAL_MS, Math.round(intervalMs));
			const settings = await loadSettings(conversationId);
			const updated = { ...settings, intervalMs: clamped };
			await persistSettings(conversationId, updated);
			mergeState(conversationId, { intervalMs: clamped });

			// Re-arm with new interval if currently armed
			const state = getState(conversationId);
			if (state.enabled && !state.active && timers.has(conversationId)) {
				armTimer(conversationId);
			}

			deps.onSurfaceChange();
			return updated;
		},

		dispose() {
			for (const [conversationId] of timers) {
				cancelTimer(conversationId);
			}
		},
	};
}