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

main
ts 184 lines 6.56 KB
Raw
1 import * as QuickActions from "expo-quick-actions";
2 import { Platform } from "react-native";
3 import type { NavigationState } from "@react-navigation/native";
4 import type { ScopedThreadRef } from "@t3tools/contracts";
5 import { Atom } from "effect/reactivity";
6
7 import { environmentCatalog } from "../../connection/catalog";
8 import {
9 loadRecentThreadShortcuts,
10 saveRecentThreadShortcuts,
11 type RecentThreadShortcut,
12 } from "../../persistence/imperative";
13 import { appAtomRegistry } from "../../state/atom-registry";
14 import { environmentThreadShells } from "../../state/threads";
15 import {
16 activeThreadRef,
17 buildShortcutActions,
18 shortcutHref,
19 withRecentThreadShortcut,
20 } from "./appShortcuts";
21
22 export interface RecentThreadShortcutsDependencies {
23 readonly load: () => Promise<ReadonlyArray<RecentThreadShortcut>>;
24 readonly save: (recents: ReadonlyArray<RecentThreadShortcut>) => Promise<void>;
25 readonly publish: (recents: ReadonlyArray<RecentThreadShortcut>) => Promise<void>;
26 }
27
28 /**
29 * Keeps the launcher's recent-thread list. Recording waits for the persisted
30 * list so the first thread opened after a cold start cannot clobber older
31 * entries, and a failed load never persists its empty fallback over valid
32 * history until a real thread open makes the in-memory list the new truth.
33 */
34 export function createRecentThreadShortcuts(dependencies: RecentThreadShortcutsDependencies) {
35 let recents: ReadonlyArray<RecentThreadShortcut> | null = null;
36 let persistable = false;
37 let active: RecentThreadShortcut | null = null;
38 let savedEnvironmentIds: ReadonlySet<string> | null = null;
39 // Serialize saves so older lists cannot overwrite newer ones.
40 let saveQueue: Promise<unknown> = Promise.resolve();
41
42 const commit = (next: ReadonlyArray<RecentThreadShortcut>) => {
43 recents = next;
44 if (persistable) {
45 saveQueue = saveQueue.then(
46 () =>
47 dependencies.save(next).catch((error: unknown) => {
48 console.warn("[app-shortcuts] failed to persist recent threads", error);
49 }),
50 () => undefined,
51 );
52 }
53 publish(next);
54 };
55
56 const publish = (list: ReadonlyArray<RecentThreadShortcut>) => {
57 void dependencies.publish(list).catch((error: unknown) => {
58 console.warn("[app-shortcuts] failed to update launcher shortcuts", error);
59 });
60 };
61
62 const isSaved = (thread: RecentThreadShortcut) =>
63 savedEnvironmentIds?.has(thread.environmentId) ?? true;
64
65 const withActive = (list: ReadonlyArray<RecentThreadShortcut>) => {
66 if (active === null || !isSaved(active)) return list;
67 const next = withRecentThreadShortcut(list, active);
68 if (next !== list) persistable = true;
69 return next;
70 };
71
72 const loaded = dependencies.load().then(
73 (threads) => {
74 persistable = true;
75 commit(withActive(threads.filter(isSaved)));
76 },
77 (error: unknown) => {
78 console.warn("[app-shortcuts] failed to load recent threads", error);
79 commit(withActive([]));
80 },
81 );
82
83 return {
84 loaded,
85 /** Resolves once every save issued so far has finished. */
86 saved: () => saveQueue,
87 recordActiveThread(next: RecentThreadShortcut | null): void {
88 active = next;
89 if (recents === null || next === null) return;
90 const updated = withActive(recents);
91 if (updated !== recents) commit(updated);
92 },
93 retainEnvironments(next: ReadonlySet<string>): void {
94 savedEnvironmentIds = next;
95 if (recents === null) return;
96 const kept = recents.filter(isSaved);
97 if (kept.length !== recents.length) commit(kept);
98 },
99 /** Publishes the current list again, for titles that follow the UI language. */
100 republish(): void {
101 if (recents !== null) publish(recents);
102 },
103 };
104 }
105
106 let installedRecents: ReturnType<typeof createRecentThreadShortcuts> | null = null;
107
108 export function republishAppShortcuts(): void {
109 installedRecents?.republish();
110 }
111
112 const activeThreadRefAtom = Atom.make<ScopedThreadRef | null>(null).pipe(
113 Atom.keepAlive,
114 Atom.withLabel("mobile:app-shortcuts-active-thread-ref"),
115 );
116
117 const activeThreadShortcutAtom = Atom.make((get): RecentThreadShortcut | null => {
118 const ref = get(activeThreadRefAtom);
119 if (ref === null) return null;
120 const title = get(environmentThreadShells.threadShellAtom(ref))?.title ?? "";
121 return { environmentId: ref.environmentId, threadId: ref.threadId, title };
122 }).pipe(
123 Atom.withEquality(
124 (left: RecentThreadShortcut | null, right: RecentThreadShortcut | null) =>
125 left === right ||
126 (left !== null &&
127 right !== null &&
128 left.environmentId === right.environmentId &&
129 left.threadId === right.threadId &&
130 left.title === right.title),
131 ),
132 );
133
134 /** Wired to the root navigation container's state changes. */
135 export function recordAppShortcutNavigationState(state: NavigationState): void {
136 // Launcher shortcuts are Android-only; iOS never subscribes to thread shells.
137 if (Platform.OS !== "android") return;
138 const next = activeThreadRef(state);
139 const current = appAtomRegistry.get(activeThreadRefAtom);
140 if (next?.environmentId === current?.environmentId && next?.threadId === current?.threadId) {
141 return;
142 }
143 appAtomRegistry.set(activeThreadRefAtom, next);
144 }
145
146 /**
147 * App-lifetime quick actions. `navigate` must queue until navigation is ready:
148 * a cold-start shortcut arrives as the launch action, and pushing it over the
149 * initial Home route makes back return home instead of exiting the app.
150 */
151 export function installAppShortcuts(navigate: (href: string) => void): () => void {
152 const initialHref = QuickActions.initial ? shortcutHref(QuickActions.initial) : null;
153 if (initialHref !== null) navigate(initialHref);
154 const subscription = QuickActions.addListener((action) => {
155 const href = shortcutHref(action);
156 if (href !== null) navigate(href);
157 });
158 if (Platform.OS !== "android") return () => subscription.remove();
159
160 const recents = createRecentThreadShortcuts({
161 load: loadRecentThreadShortcuts,
162 save: saveRecentThreadShortcuts,
163 publish: (list) => QuickActions.setItems(buildShortcutActions(list)),
164 });
165 installedRecents = recents;
166 const unsubscribe = appAtomRegistry.subscribe(
167 activeThreadShortcutAtom,
168 (active) => recents.recordActiveThread(active),
169 { immediate: true },
170 );
171 const unsubscribeCatalog = appAtomRegistry.subscribe(
172 environmentCatalog.catalogValueAtom,
173 (catalog) => {
174 if (catalog.isReady) recents.retainEnvironments(new Set(catalog.entries.keys()));
175 },
176 { immediate: true },
177 );
178 return () => {
179 if (installedRecents === recents) installedRecents = null;
180 subscription.remove();
181 unsubscribe();
182 unsubscribeCatalog();
183 };
184 }