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 hasThreadLinks,
21 relabelThreadLinks,
22 resolveThreadLinkRef,
23} from "@t3tools/shared/threadLinks";
24import * as Option from "effect/Option";
25import * as Schema from "effect/Schema";
26import { AsyncResult, Atom } from "effect/reactivity";
27import { useMemo } from "react";
28
29import { threadChipTargets } from "../lib/enrichedLinkPresentation";
30import { resolveProjectChipIcon } from "../lib/projectIcon";
31import { projectGlyphImageAtom, projectGlyphKey } from "../native/ProjectChipIconImages";
32import { projectFaviconUrlAtom } from "./assets";
33import { environmentProjects } from "./projects";
34import { environmentServerConfigsAtom, serverEnvironment } from "./server";
35import { environmentThreadDetails, environmentThreadShells } from "./threads";
36
37const EMPTY_PROJECT_ATOM = Atom.make<EnvironmentProject | null>(null).pipe(
38 Atom.withLabel("mobile-project:empty"),
39);
40const EMPTY_THREAD_SHELL_ATOM = Atom.make<EnvironmentThreadShell | null>(null).pipe(
41 Atom.withLabel("mobile-thread-shell:empty"),
42);
43const EMPTY_SERVER_CONFIG_ATOM = Atom.make<ServerConfig | null>(null).pipe(
44 Atom.withLabel("mobile-server-config:empty"),
45);
46const EMPTY_THREAD_ATOM = Atom.make<EnvironmentThread | null>(null).pipe(
47 Atom.withLabel("mobile-thread:empty"),
48);
49const EMPTY_THREAD_TITLES: ReadonlyMap<ThreadId, string> = new Map();
50const EMPTY_THREAD_TITLES_ATOM = Atom.make(EMPTY_THREAD_TITLES).pipe(
51 Atom.withLabel("mobile-thread-titles:empty"),
52);
53
54const threadTitlesAtom = Atom.family((environmentId: EnvironmentId) => {
55 let previous = EMPTY_THREAD_TITLES;
56 return Atom.make((get) => {
57 const index = get(environmentThreadShells.environmentThreadIndexAtom(environmentId));
58 const unchanged =
59 index.size === previous.size &&
60 Array.from(index).every(([threadId, shell]) => previous.get(threadId) === shell.title);
61 if (!unchanged) {
62 previous = new Map(Array.from(index, ([threadId, shell]) => [threadId, shell.title]));
63 }
64 return previous;
65 }).pipe(Atom.withLabel(`mobile-thread-titles:${environmentId}`));
66});
67
68const decodeThreadKey = Schema.decodeUnknownSync(Schema.Tuple([EnvironmentId, ThreadId]));
69const decodeThreadChipTargets = Schema.decodeUnknownSync(
70 Schema.Array(
71 Schema.Struct({
72 href: Schema.String,
73 environmentId: EnvironmentId,
74 threadId: ThreadId,
75 link: Schema.Boolean,
76 }),
77 ),
78);
79
80const threadProjectChipIconAtom = Atom.family((key: string) => {
81 const ref = scopeThreadRef(...decodeThreadKey(JSON.parse(key)));
82 return Atom.make((get): string | null => {
83 const shell = get(environmentThreadShells.threadShellAtom(ref));
84 const project = shell
85 ? get(
86 environmentProjects.projectAtom({
87 environmentId: ref.environmentId,
88 projectId: shell.projectId,
89 }),
90 )
91 : null;
92 const icon = resolveProjectChipIcon(
93 project,
94 get(serverEnvironment.configValueAtom(ref.environmentId))?.scratchWorkspaceRoot,
95 () =>
96 project
97 ? get(
98 projectFaviconUrlAtom({
99 environmentId: ref.environmentId,
100 cwd: project.workspaceRoot,
101 faviconPath: project.faviconPath,
102 }),
103 )
104 : null,
105 );
106 if (!icon) return null;
107 if (icon.kind === "favicon") return icon.uri;
108 return Option.getOrNull(AsyncResult.value(get(projectGlyphImageAtom(projectGlyphKey(icon)))));
109 }).pipe(Atom.withLabel(`mobile-thread-project-chip-icon:${key}`));
110});
111
112const EMPTY_THREAD_CHIP_ICONS: ReadonlyMap<string, string> = new Map();
113const EMPTY_THREAD_CHIP_ICONS_ATOM = Atom.make(EMPTY_THREAD_CHIP_ICONS).pipe(
114 Atom.withLabel("mobile-thread-chip-icons:empty"),
115);
116
117const threadChipIconsAtom = Atom.family((key: string) => {
118 const targets = decodeThreadChipTargets(JSON.parse(key));
119 return Atom.make((get) => {
120 const icons = new Map<string, string>();
121 for (const target of targets) {
122 const source = scopeThreadRef(target.environmentId, target.threadId);
123 const ref = target.link
124 ? (resolveThreadLinkRef(source, get(environmentThreadShells.threadRefsAtom)) ?? source)
125 : source;
126 const icon = get(
127 threadProjectChipIconAtom(JSON.stringify([ref.environmentId, ref.threadId])),
128 );
129 if (icon) icons.set(target.href, icon);
130 }
131 return icons;
132 }).pipe(Atom.withLabel(`mobile-thread-chip-icons:${key}`));
133});
134
135export function waitForProject(
136 ref: ScopedProjectRef,
137 timeoutMs = 10_000,
138): Promise<EnvironmentProject | null> {
139 const atom = environmentProjects.projectAtom(ref);
140 const current = appAtomRegistry.get(atom);
141 if (current !== null) return Promise.resolve(current);
142 return new Promise((resolve) => {
143 let unsubscribe: (() => void) | null = null;
144 const timeout = setTimeout(() => {
145 unsubscribe?.();
146 resolve(null);
147 }, timeoutMs);
148 const finish = (project: EnvironmentProject | null) => {
149 if (project === null) return;
150 clearTimeout(timeout);
151 unsubscribe?.();
152 resolve(project);
153 };
154 unsubscribe = appAtomRegistry.subscribe(atom, finish);
155 finish(appAtomRegistry.get(atom));
156 });
157}
158
159export function useProjects(): ReadonlyArray<EnvironmentProject> {
160 return useAtomValue(environmentProjects.projectsAtom);
161}
162
163export function useThreadShells(): ReadonlyArray<EnvironmentThreadShell> {
164 return useAtomValue(environmentThreadShells.threadShellsAtom);
165}
166
167export function useNavigationThreadShells(): ReadonlyArray<EnvironmentThreadShell> {
168 return useAtomValue(environmentThreadShells.navigationThreadShellsAtom);
169}
170
171export function useProject(ref: ScopedProjectRef | null): EnvironmentProject | null {
172 return useAtomValue(ref === null ? EMPTY_PROJECT_ATOM : environmentProjects.projectAtom(ref));
173}
174
175export function useThreadShell(ref: ScopedThreadRef | null): EnvironmentThreadShell | null {
176 return useAtomValue(
177 ref === null ? EMPTY_THREAD_SHELL_ATOM : environmentThreadShells.threadShellAtom(ref),
178 );
179}
180
181/** Streaming timestamps, item counts, and the latest message can be stale during a run. */
182export function useQuietThreadShell(ref: ScopedThreadRef | null): EnvironmentThreadShell | null {
183 return useAtomValue(
184 ref === null ? EMPTY_THREAD_SHELL_ATOM : environmentThreadShells.quietThreadShellAtom(ref),
185 );
186}
187
188export function useChildThreadInputs(ref: ScopedThreadRef) {
189 return useAtomValue(environmentThreadShells.childThreadInputsAtom(ref));
190}
191
192export function useLiveThreadLinkLabels(markdown: string, environmentId: EnvironmentId): string {
193 const titles = useAtomValue(
194 hasThreadLinks(markdown) ? threadTitlesAtom(environmentId) : EMPTY_THREAD_TITLES_ATOM,
195 );
196 return useMemo(
197 () =>
198 titles.size === 0
199 ? markdown
200 : relabelThreadLinks(markdown, (threadId) => titles.get(threadId)),
201 [markdown, titles],
202 );
203}
204
205export function useThreadChipIcons(
206 environmentId: EnvironmentId,
207 markdown: string,
208 records?: ReadonlyArray<ComposerContextRecord>,
209): ReadonlyMap<string, string> {
210 const targets = threadChipTargets(environmentId, markdown, records);
211 return useAtomValue(
212 targets.length === 0
213 ? EMPTY_THREAD_CHIP_ICONS_ATOM
214 : threadChipIconsAtom(JSON.stringify(targets)),
215 );
216}
217
218export function useEnvironmentServerConfig(
219 environmentId: EnvironmentId | null,
220): ServerConfig | null {
221 return useAtomValue(
222 environmentId === null
223 ? EMPTY_SERVER_CONFIG_ATOM
224 : serverEnvironment.configValueAtom(environmentId),
225 );
226}
227
228export function useServerConfigs(): ReadonlyMap<EnvironmentId, ServerConfig> {
229 return useAtomValue(environmentServerConfigsAtom);
230}
231
232const selectReportedModelSelection = (thread: EnvironmentThread | null) =>
233 thread === null ? null : deriveReportedModelSelection(thread.projection);
234
235export function useThreadReportedModelSelection(ref: ScopedThreadRef | null) {
236 return useAtomValue(
237 ref === null ? EMPTY_THREAD_ATOM : environmentThreadDetails.threadAtom(ref),
238 selectReportedModelSelection,
239 );
240}