@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 131 lines 5.42 KB
Raw
1 import * as Dialog from "../../components/ui/Dialog";
2 import type { NavigationState, PartialState } from "@react-navigation/native";
3 import { EnvironmentId, ThreadId, type ScopedThreadRef } from "@t3tools/contracts";
4 import type { LinkedPrompt } from "@t3tools/shared/promptLinks";
5 import { parseThreadLinkPrompt } from "@t3tools/shared/promptLinksCopy";
6 import * as Option from "effect/Option";
7 import { AsyncResult } from "effect/reactivity";
8 import { msg } from "gt-react-native";
9
10 import { m } from "../../i18n/messages";
11 import { findStackRoute } from "../../lib/appLinking";
12 import { rootNavigationRef } from "../../lib/rootNavigation";
13 import { scopedThreadKey } from "../../lib/scopedEntities";
14 import { appAtomRegistry } from "../../state/atom-registry";
15 import { environmentThreadShells, environmentThreads } from "../../state/threads";
16 import { applyLinkedPromptToThreadDraft } from "./prompt-link-actions";
17 import {
18 promptLinkNotice,
19 promptLinkSearchFromParams,
20 stepPendingPromptLink,
21 } from "./prompt-link-model";
22
23 const THREAD_LINK_KEYS = ["prompt"];
24
25 type PendingThreadLink = { readonly ref: ScopedThreadRef; readonly prompt: LinkedPrompt };
26
27 function firstString(value: unknown): string | null {
28 const first = Array.isArray(value) ? value[0] : value;
29 return typeof first === "string" && first.length > 0 ? first : null;
30 }
31
32 let pendingLink: PendingThreadLink | null = null;
33 let stopWaitingForShell: (() => void) | null = null;
34 let stopWaitingForDetail: (() => void) | null = null;
35
36 /**
37 * `threads/<environment>/<thread>?prompt=…` fills that thread's composer draft. The param is
38 * dropped as the link arrives, so the thread screen never sees it and a later visit cannot apply
39 * it again. The draft is written only once the thread's screen shows a thread that exists: a
40 * screen for an unknown thread replaces itself with a new-thread draft, which drops the link.
41 */
42 export function takeThreadPromptLink(
43 state: PartialState<NavigationState> | undefined,
44 ): PartialState<NavigationState> | undefined {
45 if (!state) return state;
46 const index = state.routes.findIndex((route) => route.name === "Thread");
47 const route = state.routes[index];
48 const params = route?.params as Readonly<Record<string, unknown>> | undefined;
49 const search = promptLinkSearchFromParams(params, THREAD_LINK_KEYS);
50 if (!route || !params || search === null) return state;
51 // A newer link replaces a waiting one even when it turns out to be invalid.
52 dropPendingLink();
53 const { prompt: _prompt, ...rest } = params;
54 const routes = state.routes.slice();
55 routes[index] = { ...route, params: rest };
56 const nextState = { ...state, routes };
57
58 const environmentId = firstString(params.environmentId);
59 const threadId = firstString(params.threadId);
60 if (environmentId === null || threadId === null) return nextState;
61 const parsed = parseThreadLinkPrompt(search, m);
62 if (!parsed.ok) {
63 Dialog.alert(m(msg("Could not open link")), parsed.error);
64 return nextState;
65 }
66 if (parsed.value !== null) {
67 pendingLink = {
68 ref: { environmentId: EnvironmentId.make(environmentId), threadId: ThreadId.make(threadId) },
69 prompt: parsed.value,
70 };
71 }
72 return nextState;
73 }
74
75 /** Wired to the navigation container's state changes. */
76 export function resolvePendingThreadPromptLink(state: NavigationState | undefined): void {
77 if (pendingLink === null) return;
78 const { ref } = pendingLink;
79 // A subagent thread the environment's list leaves out gets a shell once the screen mounts its
80 // family. An archived thread never does; the screen shows it from its detail.
81 const shellAtom = environmentThreadShells.threadShellAtom(ref);
82 const detailAtom = environmentThreads.stateAtom(ref.environmentId, ref.threadId);
83 // Read detail only while the screen holds it: opening it here for an unknown thread would keep
84 // retrying with no screen to close it.
85 const screenHoldsDetail = appAtomRegistry.getNodes().has(detailAtom);
86 const step = stepPendingPromptLink(pendingLink, {
87 screenOnStack:
88 findStackRoute(
89 state,
90 "Thread",
91 (params) =>
92 firstString(params?.environmentId) === ref.environmentId &&
93 firstString(params?.threadId) === ref.threadId,
94 ) !== undefined,
95 ready:
96 appAtomRegistry.get(shellAtom) !== null ||
97 (screenHoldsDetail && detailLoaded(appAtomRegistry.get(detailAtom))),
98 });
99 if (step.pending === null) dropPendingLink();
100 if (step.resolve !== null) {
101 const { prompt } = step.resolve;
102 void applyLinkedPromptToThreadDraft(
103 scopedThreadKey(ref.environmentId, ref.threadId),
104 prompt,
105 promptLinkNotice({ hiddenCharacters: prompt.hiddenCharacters }),
106 );
107 } else if (step.pending !== null) {
108 stopWaitingForShell ??= appAtomRegistry.subscribe(shellAtom, (shell) => {
109 if (shell !== null) resolvePendingThreadPromptLink(rootNavigationRef.getRootState());
110 });
111 if (screenHoldsDetail) {
112 stopWaitingForDetail ??= appAtomRegistry.subscribe(detailAtom, (detail) => {
113 if (detailLoaded(detail)) resolvePendingThreadPromptLink(rootNavigationRef.getRootState());
114 });
115 }
116 }
117 }
118
119 function detailLoaded(
120 result: AsyncResult.AsyncResult<{ readonly data: Option.Option<unknown> }, unknown>,
121 ): boolean {
122 return Option.isSome(Option.flatMap(AsyncResult.value(result), (state) => state.data));
123 }
124
125 function dropPendingLink(): void {
126 pendingLink = null;
127 stopWaitingForShell?.();
128 stopWaitingForShell = null;
129 stopWaitingForDetail?.();
130 stopWaitingForDetail = null;
131 }