Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

entities.ts

269 lines9.6 KB

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 });
167​
168export function useProjects(): ReadonlyArray<EnvironmentProject> {
169 return useAtomValue(environmentProjects.projectsAtom);
171​
172export function useThreadShells(): ReadonlyArray<EnvironmentThreadShell> {
173 return useAtomValue(environmentThreadShells.threadShellsAtom);
175​
176/** Thread shells minus those the tag filter hides, for lists that show threads to the user. */
177export function useVisibleThreadShells(): ReadonlyArray<EnvironmentThreadShell> {
178 return useAtomValue(environmentThreadShells.visibleThreadShellsAtom);
180​
181export function useNavigationThreadShells(): ReadonlyArray<EnvironmentThreadShell> {
182 return useAtomValue(environmentThreadShells.navigationThreadShellsAtom);
184​
185export function useProject(ref: ScopedProjectRef | null): EnvironmentProject | null {
186 return useAtomValue(ref === null ? EMPTY_PROJECT_ATOM : environmentProjects.projectAtom(ref));
188​
189export function useThreadShell(ref: ScopedThreadRef | null): EnvironmentThreadShell | null {
190 return useAtomValue(
191 ref === null ? EMPTY_THREAD_SHELL_ATOM : environmentThreadShells.threadShellAtom(ref),
192 );
194​
195/** Streaming timestamps, item counts, and the latest message can be stale during a run. */
196export function useQuietThreadShell(ref: ScopedThreadRef | null): EnvironmentThreadShell | null {
197 return useAtomValue(
198 ref === null ? EMPTY_THREAD_SHELL_ATOM : environmentThreadShells.quietThreadShellAtom(ref),
199 );
201​
202export function useChildThreadInputs(ref: ScopedThreadRef) {
203 return useAtomValue(environmentThreadShells.childThreadInputsAtom(ref));
205​
206export function useSideChats(ref: ScopedThreadRef) {
207 return useAtomValue(environmentThreadShells.sideChatsAtom(ref));
209​
210export function useLiveThreadLinkLabels(markdown: string, environmentId: EnvironmentId): string {
211 const titles = useAtomValue(
212 hasThreadLinks(markdown)
213 ? threadLinkTitlesAtom(JSON.stringify(threadLinkRefs(markdown, environmentId).map(threadKey)))
214 : EMPTY_THREAD_LINK_TITLES_ATOM,
215 );
216 return relabelThreadLinks(markdown, environmentId, (ref) => titles.get(threadKey(ref)));
218​
219/** Keyed reads; every thread is read only to place a v1 link its message's environment lacks. */
220export function resolveThreadLink(
221 read: <A>(atom: Atom.Atom<A>) => A,
222 link: ThreadLink,
223 messageEnvironmentId: EnvironmentId,
224): ScopedThreadRef | null {
225 const known = threadLinkCandidates(link, messageEnvironmentId).find(
226 (ref) => read(threadTitleAtom(threadKey(ref))) !== null,
227 );
228 if (known) return known;
229 return link.environmentId === null
230 ? guessThreadLinkRef(link, read(environmentThreadShells.threadRefsAtom))
231 : null;
233​
234export function useThreadChipIcons(
235 environmentId: EnvironmentId,
236 markdown: string,
237 records?: ReadonlyArray<ComposerContextRecord>,
238): ReadonlyMap<string, string> {
239 const targets = threadChipTargets(environmentId, markdown, records);
240 return useAtomValue(
241 targets.length === 0
242 ? EMPTY_THREAD_CHIP_ICONS_ATOM
243 : threadChipIconsAtom(JSON.stringify(targets)),
244 );
246​
247export function useEnvironmentServerConfig(
248 environmentId: EnvironmentId | null,
249): ServerConfig | null {
250 return useAtomValue(
251 environmentId === null
252 ? EMPTY_SERVER_CONFIG_ATOM
253 : serverEnvironment.configValueAtom(environmentId),
254 );
256​
257export function useServerConfigs(): ReadonlyMap<EnvironmentId, ServerConfig> {
258 return useAtomValue(environmentServerConfigsAtom);
260​
261const selectReportedModelSelection = (thread: EnvironmentThread | null) =>
262 thread === null ? null : deriveReportedModelSelection(thread.projection);
263​
264export function useThreadReportedModelSelection(ref: ScopedThreadRef | null) {
265 return useAtomValue(
266 ref === null ? EMPTY_THREAD_ATOM : environmentThreadDetails.threadAtom(ref),
267 selectReportedModelSelection,
268 );