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 threadLinkCandidates,
24 threadLinkRefs,
25 type ThreadLink,
26} from "@t3tools/shared/threadLinks";
27import { relabelThreadLinks } from "@t3tools/shared/threadLinksCopy";
28import * as Schema from "effect/Schema";
29import { AsyncResult, Atom } from "effect/reactivity";
30import { msg, useMessages } from "gt-react-native";
31
32import { threadChipTargets } from "../lib/enrichedLinkPresentation";
33import { resolveProjectChipIcon } from "../lib/projectIcon";
34import { projectGlyphImageAtom, projectGlyphKey } from "../native/ProjectChipIconImages";
35import { projectFaviconUrlAtom } from "./assets";
36import { orchestrationEnvironment } from "./orchestration";
37import { environmentProjects } from "./projects";
38import { environmentServerConfigsAtom, serverEnvironment } from "./server";
39import { environmentThreadDetails, environmentThreadShells } from "./threads";
40
41const EMPTY_PROJECT_ATOM = Atom.make<EnvironmentProject | null>(null).pipe(
42 Atom.withLabel("mobile-project:empty"),
43);
44const EMPTY_THREAD_SHELL_ATOM = Atom.make<EnvironmentThreadShell | null>(null).pipe(
45 Atom.withLabel("mobile-thread-shell:empty"),
46);
47const EMPTY_SERVER_CONFIG_ATOM = Atom.make<ServerConfig | null>(null).pipe(
48 Atom.withLabel("mobile-server-config:empty"),
49);
50const EMPTY_THREAD_ATOM = Atom.make<EnvironmentThread | null>(null).pipe(
51 Atom.withLabel("mobile-thread:empty"),
52);
53/** Stands for the localized fallback title, resolved where the link renders. */
54const FALLBACK_THREAD_TITLE = Symbol("fallback-thread-title");
55type ThreadLinkTitle = string | typeof FALLBACK_THREAD_TITLE;
56
57const EMPTY_THREAD_LINK_TITLES_ATOM = Atom.make<ReadonlyMap<string, ThreadLinkTitle>>(
58 new Map(),
59).pipe(Atom.withLabel("mobile-thread-link-titles:empty"));
60
61const decodeThreadKey = Schema.decodeUnknownSync(Schema.Tuple([EnvironmentId, ThreadId]));
62const threadKey = (ref: ScopedThreadRef) => JSON.stringify([ref.environmentId, ref.threadId]);
63
64// Omitted and archived targets need only a metadata lookup, not their conversation history.
65const threadTitleAtom = Atom.family((key: string) => {
66 const ref = scopeThreadRef(...decodeThreadKey(JSON.parse(key)));
67 return Atom.make((get): ThreadLinkTitle | null => {
68 const shell = get(environmentThreadShells.threadShellAtom(ref));
69 if (shell !== null) return shell.title;
70 const titles = get(
71 orchestrationEnvironment.threadLinkMetadata({
72 environmentId: ref.environmentId,
73 input: { threadIds: [ref.threadId] },
74 }),
75 );
76 return AsyncResult.isSuccess(titles)
77 ? (titles.value[ref.threadId]?.title ?? (titles.waiting ? FALLBACK_THREAD_TITLE : null))
78 : FALLBACK_THREAD_TITLE;
79 }).pipe(Atom.withLabel(`mobile-thread-title:${key}`));
80});
81
82const decodeThreadKeys = Schema.decodeUnknownSync(Schema.Array(Schema.String));
83
84const threadLinkTitlesAtom = Atom.family((key: string) => {
85 const refKeys = decodeThreadKeys(JSON.parse(key));
86 return Atom.make((get) => {
87 const titles = new Map<string, ThreadLinkTitle>();
88 for (const refKey of refKeys) {
89 const title = get(threadTitleAtom(refKey));
90 if (title !== null) titles.set(refKey, title);
91 }
92 return titles;
93 }).pipe(Atom.withLabel(`mobile-thread-link-titles:${key}`));
94});
95
96const decodeThreadChipTargets = Schema.decodeUnknownSync(
97 Schema.Array(
98 Schema.Struct({
99 href: Schema.String,
100 environmentId: EnvironmentId,
101 threadId: ThreadId,
102 link: Schema.Boolean,
103 }),
104 ),
105);
106
107const threadProjectChipIconAtom = Atom.family((key: string) => {
108 const ref = scopeThreadRef(...decodeThreadKey(JSON.parse(key)));
109 return Atom.make((get): string | null => {
110 const shell = get(environmentThreadShells.threadShellAtom(ref));
111 const metadata =
112 shell ??
113 AsyncResult.getOrElse(
114 get(
115 orchestrationEnvironment.threadLinkMetadata({
116 environmentId: ref.environmentId,
117 input: { threadIds: [ref.threadId] },
118 }),
119 ),
120 () => null,
121 )?.[ref.threadId];
122 const project = metadata?.projectId
123 ? get(
124 environmentProjects.projectAtom({
125 environmentId: ref.environmentId,
126 projectId: metadata.projectId,
127 }),
128 )
129 : null;
130 const icon = resolveProjectChipIcon(
131 project,
132 get(serverEnvironment.configValueAtom(ref.environmentId))?.scratchWorkspaceRoot,
133 () =>
134 project
135 ? get(
136 projectFaviconUrlAtom({
137 environmentId: ref.environmentId,
138 cwd: project.workspaceRoot,
139 faviconPath: project.faviconPath,
140 }),
141 )
142 : null,
143 );
144 if (!icon) return null;
145 if (icon.kind === "favicon") return icon.uri;
146 return AsyncResult.getOrElse(get(projectGlyphImageAtom(projectGlyphKey(icon))), () => null);
147 }).pipe(Atom.withLabel(`mobile-thread-project-chip-icon:${key}`));
148});
149
150const EMPTY_THREAD_CHIP_ICONS: ReadonlyMap<string, string> = new Map();
151const EMPTY_THREAD_CHIP_ICONS_ATOM = Atom.make(EMPTY_THREAD_CHIP_ICONS).pipe(
152 Atom.withLabel("mobile-thread-chip-icons:empty"),
153);
154
155const threadChipIconsAtom = Atom.family((key: string) => {
156 const targets = decodeThreadChipTargets(JSON.parse(key));
157 return Atom.make((get) => {
158 const icons = new Map<string, string>();
159 for (const target of targets) {
160 const link = target.link ? parseThreadLinkHref(target.href) : null;
161 const ref =
162 (link ? resolveThreadLink(get, link, target.environmentId) : null) ??
163 scopeThreadRef(target.environmentId, target.threadId);
164 const icon = get(threadProjectChipIconAtom(threadKey(ref)));
165 if (icon) icons.set(target.href, icon);
166 }
167 return icons;
168 }).pipe(Atom.withLabel(`mobile-thread-chip-icons:${key}`));
169});
170
171export function waitForProject(
172 ref: ScopedProjectRef,
173 timeoutMs = 10_000,
174): Promise<EnvironmentProject | null> {
175 const atom = environmentProjects.projectAtom(ref);
176 const current = appAtomRegistry.get(atom);
177 if (current !== null) return Promise.resolve(current);
178 return new Promise((resolve) => {
179 let unsubscribe: (() => void) | null = null;
180 const timeout = setTimeout(() => {
181 unsubscribe?.();
182 resolve(null);
183 }, timeoutMs);
184 const finish = (project: EnvironmentProject | null) => {
185 if (project === null) return;
186 clearTimeout(timeout);
187 unsubscribe?.();
188 resolve(project);
189 };
190 unsubscribe = appAtomRegistry.subscribe(atom, finish);
191 finish(appAtomRegistry.get(atom));
192 });
193}
194
195export function useProjects(): ReadonlyArray<EnvironmentProject> {
196 return useAtomValue(environmentProjects.projectsAtom);
197}
198
199export function useThreadShells(): ReadonlyArray<EnvironmentThreadShell> {
200 return useAtomValue(environmentThreadShells.threadShellsAtom);
201}
202
203/** Thread shells minus those the tag filter hides, for lists that show threads to the user. */
204export function useVisibleThreadShells(): ReadonlyArray<EnvironmentThreadShell> {
205 return useAtomValue(environmentThreadShells.visibleThreadShellsAtom);
206}
207
208/** Tasks linked environments run for a listed thread, by thread key; lists show them under it. */
209export function useDelegatedUnderParent(): ReadonlySet<string> {
210 return useAtomValue(environmentThreadShells.delegatedUnderParentAtom);
211}
212
213export function useNavigationThreadShells(): ReadonlyArray<EnvironmentThreadShell> {
214 return useAtomValue(environmentThreadShells.navigationThreadShellsAtom);
215}
216
217export function useProject(ref: ScopedProjectRef | null): EnvironmentProject | null {
218 return useAtomValue(ref === null ? EMPTY_PROJECT_ATOM : environmentProjects.projectAtom(ref));
219}
220
221export function useThreadShell(ref: ScopedThreadRef | null): EnvironmentThreadShell | null {
222 return useAtomValue(
223 ref === null ? EMPTY_THREAD_SHELL_ATOM : environmentThreadShells.threadShellAtom(ref),
224 );
225}
226
227/** Streaming timestamps, item counts, and the latest message can be stale during a run. */
228export function useQuietThreadShell(ref: ScopedThreadRef | null): EnvironmentThreadShell | null {
229 return useAtomValue(
230 ref === null ? EMPTY_THREAD_SHELL_ATOM : environmentThreadShells.quietThreadShellAtom(ref),
231 );
232}
233
234export function useChildThreadInputs(ref: ScopedThreadRef) {
235 return useAtomValue(environmentThreadShells.childThreadInputsAtom(ref));
236}
237
238export function useSideChats(ref: ScopedThreadRef) {
239 return useAtomValue(environmentThreadShells.sideChatsAtom(ref));
240}
241
242export function useLiveThreadLinkLabels(markdown: string, environmentId: EnvironmentId): string {
243 const resolve = useMessages();
244 const titles = useAtomValue(
245 hasThreadLinks(markdown)
246 ? threadLinkTitlesAtom(JSON.stringify(threadLinkRefs(markdown, environmentId).map(threadKey)))
247 : EMPTY_THREAD_LINK_TITLES_ATOM,
248 );
249 return relabelThreadLinks(
250 markdown,
251 environmentId,
252 (ref) => {
253 const title = titles.get(threadKey(ref));
254 return title === FALLBACK_THREAD_TITLE
255 ? resolve(msg("Thread", { $context: "fallback title of a linked thread" }))
256 : title;
257 },
258 resolve,
259 );
260}
261
262/** Keyed reads; every thread is read only to place a v1 link its message's environment lacks. */
263export function resolveThreadLink(
264 read: <A>(atom: Atom.Atom<A>) => A,
265 link: ThreadLink,
266 messageEnvironmentId: EnvironmentId,
267): ScopedThreadRef | null {
268 const known = threadLinkCandidates(link, messageEnvironmentId).find((ref) => {
269 if (read(environmentThreadShells.threadShellAtom(ref)) !== null) return true;
270 const metadata = read(
271 orchestrationEnvironment.threadLinkMetadata({
272 environmentId: ref.environmentId,
273 input: { threadIds: [ref.threadId] },
274 }),
275 );
276 return AsyncResult.getOrElse(metadata, () => null)?.[ref.threadId] !== undefined;
277 });
278 if (known) return known;
279 return link.environmentId === null
280 ? guessThreadLinkRef(link, read(environmentThreadShells.threadRefsAtom))
281 : scopeThreadRef(link.environmentId, link.threadId);
282}
283
284export function useThreadChipIcons(
285 environmentId: EnvironmentId,
286 markdown: string,
287 records?: ReadonlyArray<ComposerContextRecord>,
288): ReadonlyMap<string, string> {
289 const targets = threadChipTargets(environmentId, markdown, records);
290 return useAtomValue(
291 targets.length === 0
292 ? EMPTY_THREAD_CHIP_ICONS_ATOM
293 : threadChipIconsAtom(JSON.stringify(targets)),
294 );
295}
296
297export function useEnvironmentServerConfig(
298 environmentId: EnvironmentId | null,
299): ServerConfig | null {
300 return useAtomValue(
301 environmentId === null
302 ? EMPTY_SERVER_CONFIG_ATOM
303 : serverEnvironment.configValueAtom(environmentId),
304 );
305}
306
307export function useServerConfigs(): ReadonlyMap<EnvironmentId, ServerConfig> {
308 return useAtomValue(environmentServerConfigsAtom);
309}
310
311const selectReportedModelSelection = (thread: EnvironmentThread | null) =>
312 thread === null ? null : deriveReportedModelSelection(thread.projection);
313
314export function useThreadReportedModelSelection(ref: ScopedThreadRef | null) {
315 return useAtomValue(
316 ref === null ? EMPTY_THREAD_ATOM : environmentThreadDetails.threadAtom(ref),
317 selectReportedModelSelection,
318 );
319}