The best way to control Claude Code, Codex and more from any computer or phone

main
ts 481 lines 17.7 KB
Raw
1 // @effect-diagnostics globalDate:off -- UI snooze presets use local calendar boundaries and Intl labels.
2 import * as DateTime from "effect/DateTime";
3 import { DEFAULT_SNOOZE_PRESETS, type SnoozePresetSetting } from "@t3tools/contracts/settings";
4
5 import type { EnvironmentThreadShell, PendingSubagentRequest } from "./models.ts";
6 import { mFallback, msg } from "gt-i18n";
7 import type { MFunctionType } from "gt-i18n/types";
8
9 interface SettlementRunLike {
10 readonly turnId?: unknown;
11 readonly assistantMessageId?: unknown;
12 readonly status?: string;
13 readonly state?: string;
14 readonly requestedAt?: string | null;
15 readonly startedAt?: string | null;
16 readonly completedAt?: string | null;
17 }
18
19 interface SettlementRuntimeLike {
20 readonly threadId?: unknown;
21 readonly providerName?: unknown;
22 readonly runtimeMode?: unknown;
23 readonly activeTurnId?: unknown;
24 readonly lastError?: unknown;
25 readonly status: string;
26 readonly updatedAt?: string;
27 }
28
29 interface QueuedThreadShell {
30 readonly latestUserMessageAt?: string | null;
31 readonly latestTurn?: SettlementRunLike | null;
32 readonly latestRun?: SettlementRunLike | null;
33 readonly session?: SettlementRuntimeLike | null;
34 readonly runtime?: SettlementRuntimeLike | null;
35 }
36
37 /**
38 * Failed starts and stale shells from older servers can leave user messages unadopted.
39 * Bound the pending window so those threads can eventually settle.
40 */
41 export const QUEUED_TURN_START_GRACE_MS = 2 * 60 * 1_000;
42
43 export function hasQueuedTurnStart(
44 shell: QueuedThreadShell,
45 options: { readonly now: string },
46 ): boolean {
47 if (
48 shell.runtime?.status === "preparing" ||
49 shell.runtime?.status === "queued" ||
50 shell.runtime?.status === "starting"
51 ) {
52 return true;
53 }
54 if (shell.latestUserMessageAt == null) return false;
55 if (shell.session?.status === "error") return false;
56 const messageAt = Date.parse(shell.latestUserMessageAt);
57 if (Number.isNaN(messageAt)) return false;
58 const nowMs = Date.parse(options.now);
59 if (Number.isNaN(nowMs)) return false;
60 // Bounded on both sides: message timestamps originate on whichever device
61 // sent the message, so a clock ahead of this one yields a negative age
62 // that would otherwise hold the queued state for the whole skew. Mirrors
63 // the decider's guard.
64 if (Math.abs(nowMs - messageAt) > QUEUED_TURN_START_GRACE_MS) return false;
65 const turn = shell.latestRun ?? shell.latestTurn ?? null;
66 if (turn === null) return true;
67 return [turn.requestedAt, turn.startedAt, turn.completedAt].every(
68 (candidate) => candidate == null || Date.parse(candidate) < messageAt,
69 );
70 }
71
72 export interface ThreadSnoozeShell extends QueuedThreadShell {
73 readonly source?: Pick<EnvironmentThreadShell["source"], "pendingRuntimeRequest">;
74 readonly snoozedUntil?: string | null;
75 readonly snoozedAt?: string | null;
76 readonly hasPendingApprovals: boolean;
77 readonly hasPendingUserInput: boolean;
78 readonly pendingUserInputAt?: string | null;
79 readonly pendingSubagentRequest?: PendingSubagentRequest | null;
80 readonly pendingGuestMessageCount?: number;
81 }
82
83 function pendingQuestionAt(shell: ThreadSnoozeShell): string | null {
84 const request = shell.source?.pendingRuntimeRequest;
85 return (
86 shell.pendingUserInputAt ??
87 (request?.kind === "user_input" ? DateTime.formatIso(request.createdAt) : null)
88 );
89 }
90
91 /**
92 * Only a request for the user or a fresh failure ends a snooze early. Completed runs never do:
93 * a snoozed long-running thread keeps waking itself for background work and stays hidden
94 * until its timer.
95 */
96 export function threadRaisedHandWhileSnoozed(shell: ThreadSnoozeShell): boolean {
97 const request = shell.source?.pendingRuntimeRequest;
98 if (shell.hasPendingApprovals || (request != null && request.kind !== "user_input")) return true;
99 const questionAt = pendingQuestionAt(shell);
100 // Snoozing an existing question means "ask me later". Only a new question
101 // wakes it early; missing or invalid timestamps keep the request visible.
102 if (
103 (shell.hasPendingUserInput || request?.kind === "user_input") &&
104 (shell.snoozedAt == null ||
105 questionAt == null ||
106 !(Date.parse(questionAt) <= Date.parse(shell.snoozedAt)))
107 ) {
108 return true;
109 }
110 if (shell.pendingSubagentRequest != null) return true;
111 if ((shell.pendingGuestMessageCount ?? 0) > 0) return true;
112 const failedAt = failureEdgeAt(shell);
113 return (
114 failedAt !== undefined &&
115 (shell.snoozedAt == null ||
116 (failedAt != null && Date.parse(failedAt) > Date.parse(shell.snoozedAt)))
117 );
118 }
119
120 // V2 runtime.updatedAt includes metadata writes, not just failures.
121 // Legacy sessions only expose the runtime timestamp.
122 function failureEdgeAt(shell: ThreadSnoozeShell): string | null | undefined {
123 const runtime = shell.runtime ?? shell.session ?? null;
124 if (runtime?.status !== "error" && runtime?.status !== "failed") return undefined;
125 const latestRun = shell.latestRun ?? shell.latestTurn ?? null;
126 if (latestRun?.status === "failed") {
127 return latestRun.completedAt ?? null;
128 }
129 return runtime.updatedAt ?? null;
130 }
131
132 export function canSnooze(
133 shell: Pick<
134 ThreadSnoozeShell,
135 | "hasPendingApprovals"
136 | "hasPendingUserInput"
137 | "pendingSubagentRequest"
138 | "pendingGuestMessageCount"
139 | "latestUserMessageAt"
140 | "latestTurn"
141 | "latestRun"
142 | "session"
143 | "runtime"
144 | "source"
145 >,
146 options: { readonly now: string },
147 ): boolean {
148 if (shell.hasPendingApprovals) return false;
149 const request = shell.source?.pendingRuntimeRequest;
150 if (request != null && request.kind !== "user_input") return false;
151 if (shell.pendingSubagentRequest != null) return false;
152 // A waiting guest message would wake it at once.
153 if ((shell.pendingGuestMessageCount ?? 0) > 0) return false;
154 if (hasQueuedTurnStart(shell, options)) return false;
155 return true;
156 }
157
158 export function effectiveSnoozed(
159 shell: ThreadSnoozeShell,
160 options: { readonly now: string },
161 ): boolean {
162 if (shell.snoozedUntil == null) return false;
163 const wakeAtMs = Date.parse(shell.snoozedUntil);
164 if (Number.isNaN(wakeAtMs)) return false;
165 if (wakeAtMs <= Date.parse(options.now)) return false;
166 return !threadRaisedHandWhileSnoozed(shell);
167 }
168
169 export function threadWokeAt(
170 shell: ThreadSnoozeShell,
171 options: { readonly now: string },
172 ): string | null {
173 if (shell.snoozedUntil == null) return null;
174 const wakeAtMs = Date.parse(shell.snoozedUntil);
175 if (Number.isNaN(wakeAtMs)) return null;
176 // An early hand-raise wake stays authoritative even after the scheduled
177 // wake time passes: reporting snoozedUntil then would resurface a Woke
178 // indicator the user already cleared by visiting (snoozedUntil is newer
179 // than that visit's lastVisitedAt).
180 if (threadRaisedHandWhileSnoozed(shell)) {
181 const failedAt = failureEdgeAt(shell);
182 const questionAt = pendingQuestionAt(shell);
183 const freshFailure =
184 failedAt != null &&
185 (shell.snoozedAt == null || Date.parse(failedAt) > Date.parse(shell.snoozedAt));
186 const freshQuestion =
187 questionAt != null &&
188 shell.snoozedAt != null &&
189 Date.parse(questionAt) > Date.parse(shell.snoozedAt);
190 if (freshFailure && (!freshQuestion || Date.parse(failedAt) >= Date.parse(questionAt))) {
191 return failedAt;
192 }
193 if (freshQuestion) return questionAt;
194 const runtime = shell.runtime ?? shell.session ?? null;
195 return runtime?.updatedAt ?? shell.snoozedAt ?? null;
196 }
197 return wakeAtMs <= Date.parse(options.now) ? shell.snoozedUntil : null;
198 }
199
200 const HOUR_MS = 60 * 60 * 1_000;
201
202 const WEEKDAY_INDEX = {
203 sunday: 0,
204 monday: 1,
205 tuesday: 2,
206 wednesday: 3,
207 thursday: 4,
208 friday: 5,
209 saturday: 6,
210 } as const;
211
212 export interface SnoozePreset {
213 readonly id: string;
214 readonly label: string;
215 readonly whenLabel: string;
216 readonly snoozedUntil: string;
217 }
218
219 export interface SnoozePresetOptions {
220 readonly presets?: ReadonlyArray<SnoozePresetSetting>;
221 readonly formatTime?: (date: Date) => string;
222 }
223
224 function snoozeTimeOfDayLabel(date: Date): string {
225 return date.toLocaleTimeString(undefined, { hour: "numeric", minute: "2-digit" });
226 }
227
228 // Calendar-day advance instead of adding DAY_MS: fixed millisecond offsets
229 // land on the wrong local day across DST transitions (a spring-forward day
230 // is 23 hours, so 23:30 + 24h skips the whole next day).
231 function addSnoozeDays(base: Date, days: number): Date {
232 const next = DateTime.toDate(DateTime.makeUnsafe(base));
233 next.setDate(next.getDate() + days);
234 return next;
235 }
236
237 /** "In 3 hours", "In 90 minutes", "In 2 days": the largest unit that divides evenly. */
238 function snoozeDurationLabel(minutes: number, resolve: MFunctionType): string {
239 if (minutes % (24 * 60) === 0) {
240 return resolve(
241 msg("{count, plural, one {In {count} day} other {In {count} days}}", {
242 count: minutes / (24 * 60),
243 }),
244 );
245 }
246 if (minutes % 60 === 0) {
247 return resolve(
248 msg("{count, plural, one {In {count} hour} other {In {count} hours}}", {
249 count: minutes / 60,
250 }),
251 );
252 }
253 return resolve(
254 msg("{count, plural, one {In {count} minute} other {In {count} minutes}}", { count: minutes }),
255 );
256 }
257
258 const WEEKDAY_LABELS = {
259 sunday: msg("Sunday"),
260 monday: msg("Monday"),
261 tuesday: msg("Tuesday"),
262 wednesday: msg("Wednesday"),
263 thursday: msg("Thursday"),
264 friday: msg("Friday"),
265 saturday: msg("Saturday"),
266 } satisfies Record<keyof typeof WEEKDAY_INDEX, string>;
267
268 const NEXT_WEEKDAY_LABELS = {
269 sunday: msg("Next Sunday"),
270 monday: msg("Next Monday"),
271 tuesday: msg("Next Tuesday"),
272 wednesday: msg("Next Wednesday"),
273 thursday: msg("Next Thursday"),
274 friday: msg("Next Friday"),
275 saturday: msg("Next Saturday"),
276 } satisfies Record<keyof typeof WEEKDAY_INDEX, string>;
277
278 function snoozePresetDaysAhead(
279 setting: Extract<SnoozePresetSetting, { kind: "at" }>,
280 now: Date,
281 ): number {
282 if (setting.day === "today") return 0;
283 if (setting.day === "tomorrow") return 1;
284 return (WEEKDAY_INDEX[setting.day] - now.getDay() + 7) % 7 || 7;
285 }
286
287 /** Labels follow the actual day gap, so a Monday option on a Sunday reads "Tomorrow". */
288 function snoozePresetLabel(
289 setting: SnoozePresetSetting,
290 daysAhead: number,
291 resolve: MFunctionType,
292 ): string {
293 if (setting.kind === "after") return snoozeDurationLabel(setting.minutes, resolve);
294 if (daysAhead === 0) {
295 const hour = Number(setting.time.slice(0, 2));
296 return hour < 12
297 ? resolve(msg("This morning"))
298 : hour < 17
299 ? resolve(msg("This afternoon"))
300 : resolve(msg("This evening"));
301 }
302 if (daysAhead === 1) return resolve(msg("Tomorrow"));
303 if (setting.day === "monday") return resolve(msg("Next week"));
304 if (setting.day === "today" || setting.day === "tomorrow") return "";
305 return resolve(daysAhead === 7 ? NEXT_WEEKDAY_LABELS[setting.day] : WEEKDAY_LABELS[setting.day]);
306 }
307
308 export function snoozePresetId(setting: SnoozePresetSetting): string {
309 return setting.kind === "after"
310 ? `after:${setting.minutes}`
311 : `at:${setting.day}:${setting.time}`;
312 }
313
314 export function resolveSnoozePreset(
315 setting: SnoozePresetSetting,
316 now: Date,
317 formatTime: (date: Date) => string = snoozeTimeOfDayLabel,
318 resolve: MFunctionType = mFallback,
319 ): SnoozePreset | null {
320 let wake: Date;
321 let daysAhead = 0;
322 if (setting.kind === "after") {
323 wake = DateTime.toDate(DateTime.makeUnsafe(now.getTime() + setting.minutes * 60_000));
324 } else {
325 daysAhead = snoozePresetDaysAhead(setting, now);
326 wake = addSnoozeDays(now, daysAhead);
327 wake.setHours(Number(setting.time.slice(0, 2)), Number(setting.time.slice(3)), 0, 0);
328 // A today option whose time has passed is left out until tomorrow.
329 if (wake.getTime() <= now.getTime()) return null;
330 }
331 const label = snoozePresetLabel(setting, daysAhead, resolve);
332 // Durations and "Next week" don't name the wake day, so a wake on another day shows it.
333 const labelNamesDay = setting.kind === "at" && !(daysAhead > 1 && setting.day === "monday");
334 const time = formatTime(wake);
335 return {
336 id: snoozePresetId(setting),
337 label,
338 whenLabel:
339 labelNamesDay || wake.toDateString() === now.toDateString()
340 ? time
341 : `${wake.toLocaleDateString(undefined, { weekday: "short" })} ${time}`,
342 snoozedUntil: wake.toISOString(),
343 };
344 }
345
346 /** The snooze menu: soonest first, one row per wake minute. */
347 export function resolveSnoozePresets(
348 now: Date,
349 options: SnoozePresetOptions = {},
350 resolve: MFunctionType = mFallback,
351 ): ReadonlyArray<SnoozePreset> {
352 // By minute, so a duration (which keeps the clock's seconds) and a set time in the same
353 // minute tie, and the stable sort keeps whichever comes first in settings.
354 const wakeMinute = (preset: SnoozePreset) => Math.floor(Date.parse(preset.snoozedUntil) / 60_000);
355 const seen = new Set<number>();
356 return (
357 (options.presets ?? DEFAULT_SNOOZE_PRESETS)
358 .flatMap((setting) => resolveSnoozePreset(setting, now, options.formatTime, resolve) ?? [])
359 // flatMap returned a new array; Hermes has no `toSorted`.
360 .sort((a, b) => wakeMinute(a) - wakeMinute(b))
361 .filter((preset) => {
362 if (seen.has(wakeMinute(preset))) return false;
363 seen.add(wakeMinute(preset));
364 return true;
365 })
366 );
367 }
368
369 /**
370 * A menu choice as picked. A duration re-resolves from its setting (not the deduped menu) so it
371 * starts at selection. A set time keeps the shown wake, which a day change would otherwise shift.
372 */
373 export function pickSnoozePreset(input: {
374 readonly shown: ReadonlyArray<SnoozePreset>;
375 readonly id: string;
376 readonly now: Date;
377 readonly presets?: ReadonlyArray<SnoozePresetSetting>;
378 readonly formatTime?: (date: Date) => string;
379 readonly resolve?: MFunctionType;
380 }): SnoozePreset | undefined {
381 const original = input.shown.find((preset) => preset.id === input.id);
382 const ahead =
383 original && Date.parse(original.snoozedUntil) > input.now.getTime() ? original : undefined;
384 const setting = (input.presets ?? DEFAULT_SNOOZE_PRESETS).find(
385 (candidate) => candidate.kind === "after" && snoozePresetId(candidate) === input.id,
386 );
387 return (
388 (setting && resolveSnoozePreset(setting, input.now, input.formatTime, input.resolve)) ?? ahead
389 );
390 }
391
392 export function snoozeWakeLabel(
393 snoozedUntil: string,
394 options: { readonly now: string },
395 resolve: MFunctionType = mFallback,
396 ): string {
397 const wakeMs = Date.parse(snoozedUntil);
398 const nowMs = Date.parse(options.now);
399 const now = () => resolve(msg("now", { $context: "a snoozed thread wakes now" }));
400 if (Number.isNaN(wakeMs) || Number.isNaN(nowMs)) return now();
401 if (wakeMs <= nowMs) return now();
402 // Count clock minutes: callers pass a minute-floored or live `now`, and durations keep seconds.
403 const minutes = Math.max(1, Math.floor(wakeMs / 60_000) - Math.floor(nowMs / 60_000));
404 if (minutes < 60) return resolve(msg("{minutes}m", { minutes: String(minutes) }));
405 if (minutes < 24 * 60) {
406 return resolve(msg("{hours}h", { hours: String(Math.ceil(minutes / 60)) }));
407 }
408 return resolve(msg("{days}d", { days: String(Math.ceil(minutes / (24 * 60))) }));
409 }
410
411 export type CustomSnoozeInput =
412 | { readonly mode: "date"; readonly date: string; readonly time: string }
413 | {
414 readonly mode: "duration";
415 readonly amount: string;
416 readonly unit: "minutes" | "hours" | "days";
417 };
418
419 export function resolveCustomSnooze(input: CustomSnoozeInput, now: Date): string | null {
420 let wake: Date;
421 if (input.mode === "duration") {
422 const amount = Number(input.amount);
423 if (!Number.isFinite(amount) || amount <= 0) return null;
424 const unitMs = { minutes: 60_000, hours: HOUR_MS, days: 24 * HOUR_MS }[input.unit];
425 wake = new Date(now.getTime() + amount * unitMs);
426 } else {
427 if (!/^\d{4}-\d{2}-\d{2}$/.test(input.date) || !/^\d{2}:\d{2}$/.test(input.time)) return null;
428 wake = new Date(`${input.date}T${input.time}:00`);
429 // Reject rolled-over dates and nonexistent local times during DST changes.
430 if (localSnoozeDate(wake) !== input.date || localSnoozeTime(wake) !== input.time) return null;
431 }
432 return Number.isFinite(wake.getTime()) && wake.getTime() > now.getTime()
433 ? wake.toISOString()
434 : null;
435 }
436
437 export function localSnoozeDate(date: Date): string {
438 return `${String(date.getFullYear()).padStart(4, "0")}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`;
439 }
440
441 export function localSnoozeTime(date: Date): string {
442 return `${String(date.getHours()).padStart(2, "0")}:${String(date.getMinutes()).padStart(2, "0")}`;
443 }
444
445 /**
446 * Whether a woken thread woke after the user last saw it. A run that completed
447 * after the last visit counts as seeing it, since the user watched it finish.
448 */
449 export function isThreadWokeUnseen(input: {
450 readonly wokeAt: string | null;
451 readonly settled: boolean;
452 readonly lastVisitedAt: string | null | undefined;
453 readonly latestRunCompletedAt: string | null;
454 }): boolean {
455 if (input.wokeAt === null || input.settled) return false;
456 const wokeAtMs = Date.parse(input.wokeAt);
457 if (Number.isNaN(wokeAtMs)) return false;
458 const seenAt = [input.lastVisitedAt, input.latestRunCompletedAt]
459 .map((value) => (value ? Date.parse(value) : NaN))
460 .filter((ms) => !Number.isNaN(ms));
461 return seenAt.every((ms) => ms < wokeAtMs);
462 }
463
464 /**
465 * Whether the latest run failed after the user last saw the thread. Only the run dates the
466 * failure, since the shell's updatedAt also moves on renames. A failed run without a
467 * completion time, from older data, is dated by its start.
468 */
469 export function hasUnseenRunFailure(
470 thread: Pick<EnvironmentThreadShell, "latestRun"> & {
471 readonly lastVisitedAt?: string | null | undefined;
472 },
473 ): boolean {
474 const run = thread.latestRun;
475 if (run?.status !== "failed") return false;
476 if (!thread.lastVisitedAt) return true;
477 const failedAtMs = Date.parse(run.completedAt ?? run.startedAt ?? run.requestedAt ?? "");
478 const lastVisitedAtMs = Date.parse(thread.lastVisitedAt);
479 if (Number.isNaN(failedAtMs) || Number.isNaN(lastVisitedAtMs)) return true;
480 return failedAtMs > lastVisitedAtMs;
481 }