Open History to see the last commit
1import { useAtomValue } from "@effect/atom-react";
2import { deriveReportedModelSelection } from "@t3tools/client-runtime/state/thread-execution";
3
4import { appAtomRegistry } from "./atom-registry";
5import type {
6 EnvironmentProject,
7 EnvironmentThread,
8 EnvironmentThreadShell,
9} from "@t3tools/client-runtime/state/shell";
10import {
11 EnvironmentId,
12 ThreadId,
13 type ComposerContextRecord,
14 type ScopedProjectRef,
15 type ScopedThreadRef,
16 type ServerConfig,
17} from "@t3tools/contracts";
18import { scopeThreadRef } from "@t3tools/client-runtime/environment";
19import {
20 guessThreadLinkRef,
21 hasThreadLinks,
22 parseThreadLinkHref,
23 relabelThreadLinks,
24 threadLinkCandidates,
25 threadLinkRefs,
26 type ThreadLink,
27} from "@t3tools/shared/threadLinks";
28import * as Schema from "effect/Schema";
29import { AsyncResult, Atom } from "effect/reactivity";
30
31import { threadChipTargets } from "../lib/enrichedLinkPresentation";
32import { resolveProjectChipIcon } from "../lib/projectIcon";
33import { projectGlyphImageAtom, projectGlyphKey } from "../native/ProjectChipIconImages";
34import { projectFaviconUrlAtom } from "./assets";
35import { environmentProjects } from "./projects";
36import { environmentServerConfigsAtom, serverEnvironment } from "./server";
37import { environmentThreadDetails, environmentThreadShells } from "./threads";
38
39const EMPTY_PROJECT_ATOM = Atom.make<EnvironmentProject | null>(null).pipe(
40 Atom.withLabel("mobile-project:empty"),
41);
42const EMPTY_THREAD_SHELL_ATOM = Atom.make<EnvironmentThreadShell | null>(null).pipe(
43 Atom.withLabel("mobile-thread-shell:empty"),
44);
45const EMPTY_SERVER_CONFIG_ATOM = Atom.make<ServerConfig | null>(null).pipe(
46 Atom.withLabel("mobile-server-config:empty"),
47);
48const EMPTY_THREAD_ATOM = Atom.make<EnvironmentThread | null>(null).pipe(
49 Atom.withLabel("mobile-thread:empty"),
50);
51const EMPTY_THREAD_LINK_TITLES_ATOM = Atom.make<ReadonlyMap<string, string>>(new Map()).pipe(
52 Atom.withLabel("mobile-thread-link-titles:empty"),
53);
54
55const decodeThreadKey = Schema.decodeUnknownSync(Schema.Tuple([EnvironmentId, ThreadId]));
56const threadKey = (ref: ScopedThreadRef) => JSON.stringify([ref.environmentId, ref.threadId]);
57
58// Null when this client doesn't know the thread. Keyed, so a link never walks an environment's threads.
59const threadTitleAtom = Atom.family((key: string) => {
60 const ref = scopeThreadRef(...decodeThreadKey(JSON.parse(key)));
61 return Atom.make((get) => get(environmentThreadShells.threadShellAtom(ref))?.title ?? null).pipe(
62 Atom.withLabel(`mobile-thread-title:${key}`),
63 );
64});
65
66const decodeThreadKeys = Schema.decodeUnknownSync(Schema.Array(Schema.String));
67
68const threadLinkTitlesAtom = Atom.family((key: string) => {
69 const refKeys = decodeThreadKeys(JSON.parse(key));
70 return Atom.make((get) => {
71 const titles = new Map<string, string>();
72 for (const refKey of refKeys) {
73 const title = get(threadTitleAtom(refKey));
74 if (title !== null) titles.set(refKey, title);
75 }
76 return titles;
77 }).pipe(Atom.withLabel(`mobile-thread-link-titles:${key}`));
78});
79
80const decodeThreadChipTargets = Schema.decodeUnknownSync(
81 Schema.Array(
82 Schema.Struct({
83 href: Schema.String,
84 environmentId: EnvironmentId,
85 threadId: ThreadId,
86 link: Schema.Boolean,
87 }),
88 ),
89);
90
91const threadProjectChipIconAtom = Atom.family((key: string) => {
92 const ref = scopeThreadRef(...decodeThreadKey(JSON.parse(key)));
93 return Atom.make((get): string | null => {
94 const shell = get(environmentThreadShells.threadShellAtom(ref));
95 const project = shell
96 ? get(
97 environmentProjects.projectAtom({
98 environmentId: ref.environmentId,
99 projectId: shell.projectId,
100 }),
101 )
102 : null;
103 const icon = resolveProjectChipIcon(
104 project,
105 get(serverEnvironment.configValueAtom(ref.environmentId))?.scratchWorkspaceRoot,
106 () =>
107 project
108 ? get(
109 projectFaviconUrlAtom({
110 environmentId: ref.environmentId,
111 cwd: project.workspaceRoot,
112 faviconPath: project.faviconPath,
113 }),
114 )
115 : null,
116 );
117 if (!icon) return null;
118 if (icon.kind === "favicon") return icon.uri;
119 return AsyncResult.getOrElse(get(projectGlyphImageAtom(projectGlyphKey(icon))), () => null);
120 }).pipe(Atom.withLabel(`mobile-thread-project-chip-icon:${key}`));
121});
122
123const EMPTY_THREAD_CHIP_ICONS: ReadonlyMap<string, string> = new Map();
124const EMPTY_THREAD_CHIP_ICONS_ATOM = Atom.make(EMPTY_THREAD_CHIP_ICONS).pipe(
125 Atom.withLabel("mobile-thread-chip-icons:empty"),
126);
127
128const threadChipIconsAtom = Atom.family((key: string) => {
129 const targets = decodeThreadChipTargets(JSON.parse(key));
130 return Atom.make((get) => {
131 const icons = new Map<string, string>();
132 for (const target of targets) {
133 const link = target.link ? parseThreadLinkHref(target.href) : null;
134 const ref =
135 (link ? resolveThreadLink(get, link, target.environmentId) : null) ??
136 scopeThreadRef(target.environmentId, target.threadId);
137 const icon = get(threadProjectChipIconAtom(threadKey(ref)));
138 if (icon) icons.set(target.href, icon);
139 }
140 return icons;
141 }).pipe(Atom.withLabel(`mobile-thread-chip-icons:${key}`));
142});
143
144export function waitForProject(
145 ref: ScopedProjectRef,
146 timeoutMs = 10_000,
147): Promise<EnvironmentProject | null> {
148 const atom = environmentProjects.projectAtom(ref);
149 const current = appAtomRegistry.get(atom);
150 if (current !== null) return Promise.resolve(current);
151 return new Promise((resolve) => {
152 let unsubscribe: (() => void) | null = null;
153 const timeout = setTimeout(() => {
154 unsubscribe?.();
155 resolve(null);
156 }, timeoutMs);
157 const finish = (project: EnvironmentProject | null) => {
158 if (project === null) return;
159 clearTimeout(timeout);
160 unsubscribe?.();
161 resolve(project);
162 };
163 unsubscribe = appAtomRegistry.subscribe(atom, finish);
164 finish(appAtomRegistry.get(atom));
165 });
166}
167
168export function useProjects(): ReadonlyArray<EnvironmentProject> {
169 return useAtomValue(environmentProjects.projectsAtom);
170}
171
172export function useThreadShells(): ReadonlyArray<EnvironmentThreadShell> {
173 return useAtomValue(environmentThreadShells.threadShellsAtom);
174}
175
176export function useNavigationThreadShells(): ReadonlyArray<EnvironmentThreadShell> {
177 return useAtomValue(environmentThreadShells.navigationThreadShellsAtom);
178}
179
180export function useProject(ref: ScopedProjectRef | null): EnvironmentProject | null {
181 return useAtomValue(ref === null ? EMPTY_PROJECT_ATOM : environmentProjects.projectAtom(ref));
182}
183
184export function useThreadShell(ref: ScopedThreadRef | null): EnvironmentThreadShell | null {
185 return useAtomValue(
186 ref === null ? EMPTY_THREAD_SHELL_ATOM : environmentThreadShells.threadShellAtom(ref),
187 );
188}
189
190/** Streaming timestamps, item counts, and the latest message can be stale during a run. */
191export function useQuietThreadShell(ref: ScopedThreadRef | null): EnvironmentThreadShell | null {
192 return useAtomValue(
193 ref === null ? EMPTY_THREAD_SHELL_ATOM : environmentThreadShells.quietThreadShellAtom(ref),
194 );
195}
196
197export function useChildThreadInputs(ref: ScopedThreadRef) {
198 return useAtomValue(environmentThreadShells.childThreadInputsAtom(ref));
199}
200
201export function useSideChats(ref: ScopedThreadRef) {
202 return useAtomValue(environmentThreadShells.sideChatsAtom(ref));
203}
204
205export function useLiveThreadLinkLabels(markdown: string, environmentId: EnvironmentId): string {
206 const titles = useAtomValue(
207 hasThreadLinks(markdown)
208 ? threadLinkTitlesAtom(JSON.stringify(threadLinkRefs(markdown, environmentId).map(threadKey)))
209 : EMPTY_THREAD_LINK_TITLES_ATOM,
210 );
211 return relabelThreadLinks(markdown, environmentId, (ref) => titles.get(threadKey(ref)));
212}
213
214/** Keyed reads; every thread is read only to place a v1 link its message's environment lacks. */
215export function resolveThreadLink(
216 read: <A>(atom: Atom.Atom<A>) => A,
217 link: ThreadLink,
218 messageEnvironmentId: EnvironmentId,
219): ScopedThreadRef | null {
220 const known = threadLinkCandidates(link, messageEnvironmentId).find(
221 (ref) => read(threadTitleAtom(threadKey(ref))) !== null,
222 );
223 if (known) return known;
224 return link.environmentId === null
225 ? guessThreadLinkRef(link, read(environmentThreadShells.threadRefsAtom))
226 : null;
227}
228
229export function useThreadChipIcons(
230 environmentId: EnvironmentId,
231 markdown: string,
232 records?: ReadonlyArray<ComposerContextRecord>,
233): ReadonlyMap<string, string> {
234 const targets = threadChipTargets(environmentId, markdown, records);
235 return useAtomValue(
236 targets.length === 0
237 ? EMPTY_THREAD_CHIP_ICONS_ATOM
238 : threadChipIconsAtom(JSON.stringify(targets)),
239 );
240}
241
242export function useEnvironmentServerConfig(
243 environmentId: EnvironmentId | null,
244): ServerConfig | null {
245 return useAtomValue(
246 environmentId === null
247 ? EMPTY_SERVER_CONFIG_ATOM
248 : serverEnvironment.configValueAtom(environmentId),
249 );
250}
251
252export function useServerConfigs(): ReadonlyMap<EnvironmentId, ServerConfig> {
253 return useAtomValue(environmentServerConfigsAtom);
254}
255
256const selectReportedModelSelection = (thread: EnvironmentThread | null) =>
257 thread === null ? null : deriveReportedModelSelection(thread.projection);
258
259export function useThreadReportedModelSelection(ref: ScopedThreadRef | null) {
260 return useAtomValue(
261 ref === null ? EMPTY_THREAD_ATOM : environmentThreadDetails.threadAtom(ref),
262 selectReportedModelSelection,
263 );
264}