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

main
ts 47 lines 1.71 KB
Raw
1 import {
2 type CustomModelDefinition,
3 readCustomModelEntries,
4 toCustomModelSetting,
5 } from "@t3tools/shared/model";
6
7 export interface CustomModelSave {
8 readonly models: ReadonlyArray<CustomModelDefinition>;
9 /** The models as the config stream will read them back once this save lands. */
10 readonly key: string;
11 /** The server accepted it; only its echo is outstanding. */
12 readonly replied?: true;
13 /** Another writer changed the list while this save was in flight, so its echo may never come. */
14 readonly raced?: true;
15 }
16
17 export const customModelsKey = (models: ReadonlyArray<CustomModelDefinition>) =>
18 JSON.stringify(readCustomModelEntries(models.map(toCustomModelSetting)));
19
20 /**
21 * Saves land in order, so an echo settles its save and every one before. The latest match wins
22 * because the stream can coalesce repeats, and a stale save would overwrite another writer later.
23 * Any other change drops replied saves and marks in-flight ones raced.
24 */
25 export function pendingCustomModelSaves(
26 saves: ReadonlyArray<CustomModelSave>,
27 storedKey: string,
28 ): ReadonlyArray<CustomModelSave> {
29 const echoed = saves.findLastIndex((entry) => entry.key === storedKey);
30 if (echoed >= 0) return saves.slice(echoed + 1);
31 return saves.flatMap((entry) => (entry.replied ? [] : [{ ...entry, raced: true as const }]));
32 }
33
34 /** A failed or raced save is dropped; a successful one waits for its echo. */
35 export function settleCustomModelSave(
36 saves: ReadonlyArray<CustomModelSave>,
37 sent: CustomModelSave,
38 saved: boolean,
39 ): ReadonlyArray<CustomModelSave> {
40 return saves.flatMap((entry) =>
41 entry.models !== sent.models
42 ? [entry]
43 : saved && !entry.raced
44 ? [{ ...entry, replied: true as const }]
45 : [],
46 );
47 }