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

usePullRequestThreads.ts

194 lines7.8 KB

1import { useAtomValue } from "@effect/atom-react";
2import { visibleLinkedThreads } from "@t3tools/client-runtime/state/threads";
3import { AsyncResult } from "effect/reactivity";
4import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
5import * as Dialog from "../../components/ui/Dialog";
6import {
7 StackActions,
8 useNavigation,
9 useNavigationState,
10 useRoute,
11} from "@react-navigation/native";
12import { threadPullRequestLinkMode } from "@t3tools/client-runtime/thread-pull-request-compatibility";
13import {
14 AuthOrchestrationOperateScope,
15 AuthSourceControlWriteScope,
16 ThreadId,
17 type PullRequestDetail,
18 type PullRequestLinkedThreadsResult,
19} from "@t3tools/contracts";
20import { formatComposerContextReference } from "@t3tools/shared/composerContextReferences";
21import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
22import { normalizeThreadPullRequestKey } from "@t3tools/client-runtime/thread-pull-requests";
23import { useRef, useState } from "react";
24import { Platform } from "react-native";
25import { useSelectWorkspaceDetail } from "../workspace/useSelectWorkspaceDetail";
26import { pullRequestComposerContext } from "../../lib/composerContext";
27import { scopedThreadKey } from "../../lib/scopedEntities";
28import { uuidv4 } from "../../lib/uuid";
29import { useEnvironmentServerConfig } from "../../state/entities";
30import { composerPullRequests } from "../../state/pull-requests";
31import { useEnvironmentQuery } from "../../state/query";
32import { environmentThreadShells } from "../../state/threads";
33import { useEnvironmentScope } from "../../state/session";
34import {
35 createNewTaskDraft,
36 getComposerDraftSnapshot,
37 insertComposerDraftContext,
38 setComposerDraftText,
39 updateComposerDraftSettings,
40 waitForComposerDraftsLoaded,
41} from "../../state/use-composer-drafts";
42import { usePullRequestConnected } from "./usePullRequestConnected";
43import { pullRequestTarget, type PullRequestParams } from "./usePullRequestDiff";
44import {
45 appendPullRequestAgentPrompt,
46 pullRequestAgentPrompt,
47 type PullRequestAgentTask,
48} from "./pullRequestAgentTasks";
49​
50type LinkedThread = PullRequestLinkedThreadsResult["threads"][number];
51​
52export function usePullRequestThreads(
53 params: PullRequestParams,
54 pr: PullRequestDetail | null,
55 filePath?: string,
56) {
57 const target = pullRequestTarget(params);
58 const config = useEnvironmentServerConfig(target.environmentId);
59 const supported = threadPullRequestLinkMode(config?.environment.capabilities) === "multiple";
60 const parsed = pr ? sourceControlClients.parseChangeRequestUrl(pr.url)?.link : undefined;
61 const reference = {
62 ...target,
63 input: { ...target.input, ...(parsed ? normalizeThreadPullRequestKey(parsed) : {}) },
64 };
65 const key = JSON.stringify(reference);
66 const route = useRoute();
67 // The iOS synthetic workspace parent's focus differs from the visible detail's focus.
68 const focused = useNavigationState((state) => state.routes[state.index]?.key === route.key);
69 const relations = useEnvironmentQuery(
70 pr && supported && focused ? composerPullRequests.linkedThreads(reference) : null,
71 );
72 const [lastRelations, setLastRelations] = useState({ key, data: relations.data });
73 if (relations.data && (lastRelations.key !== key || relations.data !== lastRelations.data))
74 setLastRelations({ key, data: relations.data });
75 const hiddenKeys = useAtomValue(environmentThreadShells.hiddenThreadKeysAtom);
76 const hidingAnywhere = useAtomValue(environmentThreadShells.anyEnvironmentHidingAtom);
77 const loadedThreadRefs = useAtomValue(
78 environmentThreadShells.environmentThreadRefsAtom(target.environmentId),
79 );
80 const threads = visibleLinkedThreads(
81 (relations.data ?? (lastRelations.key === key ? lastRelations.data : null))?.threads ?? [],
82 target.environmentId,
83 loadedThreadRefs,
84 hiddenKeys,
85 hidingAnywhere,
86 );
87 const connected = usePullRequestConnected(params.environmentId);
88 const canOperate = useEnvironmentScope(target.environmentId, AuthOrchestrationOperateScope);
89 const canAsk = !connected || canOperate;
90 const canCheckout = useEnvironmentScope(target.environmentId, AuthSourceControlWriteScope);
91 const navigation = useNavigation();
92 const selectDetail = useSelectWorkspaceDetail();
93 const pending = useRef(false);
94 const previousPrompts = useRef(new Map<string, string>());
95 const openThread = (thread: LinkedThread) => {
96 openThreadRoute({ environmentId: params.environmentId, threadId: thread.id });
97 };
98 // Android shows one page at a time; iOS opens the thread over the pull request, so Back returns.
99 const openThreadRoute = (destination: ReactNavigation.RootParamList["Thread"]) => {
100 if (Platform.OS === "android") selectDetail({ name: "Thread", params: destination });
101 else navigation.dispatch(StackActions.push("Thread", destination));
102 };
103 const [busy, setBusy] = useState(false);
104 const ask = async (thread?: LinkedThread, task: PullRequestAgentTask = "ask") => {
105 if (!pr || !canAsk || pending.current) return;
106 const terminology = sourceControlClients.get(pr.provider).changeRequest;
107 pending.current = true;
108 setBusy(true);
109 const result = await settlePromise(async () => {
110 if (connected && !thread && !canCheckout)
111 throw new Error(
112 `Starting work from this ${terminology.shortLabel} requires source control write access.`,
113 );
114 await waitForComposerDraftsLoaded();
115 const draftKey = thread
116 ? scopedThreadKey(target.environmentId, ThreadId.make(thread.id))
117 : createNewTaskDraft({
118 environmentId: target.environmentId,
119 projectId: target.input.projectId,
120 });
121 if (!thread)
122 updateComposerDraftSettings(draftKey, {
123 workspaceSelection: {
124 mode: "worktree",
125 branch: pr.headBranch,
126 worktreePath: null,
127 startFromOrigin: false,
128 pullRequestReference: pr.url,
129 },
130 });
131 const context = pullRequestComposerContext(
132 {
133 number: pr.number,
134 title: pr.title,
135 url: pr.url,
136 headBranch: pr.headBranch,
137 baseBranch: pr.baseBranch,
138 state: pr.state,
139 isDraft: pr.isDraft,
140 },
141 uuidv4(),
142 filePath,
143 );
144 const draft = getComposerDraftSnapshot(draftKey);
145 const attached = draft.context?.records.some(
146 (record) =>
147 record.kind === "review-comment" &&
148 "pullRequest" in record &&
149 record.pullRequest?.url === pr.url &&
150 record.filePath === context.filePath,
151 );
152 if (
153 !attached &&
154 !insertComposerDraftContext(
155 draftKey,
156 {
157 text: `${formatComposerContextReference(context)} `,
158 context: { version: 1, records: [context] },
159 },
160 { text: draft.text, start: draft.text.length, end: draft.text.length },
161 )
162 )
163 throw new Error("Remove some context from this thread's draft, then try again.");
164 const withContext = getComposerDraftSnapshot(draftKey);
165 setComposerDraftText(
166 draftKey,
167 appendPullRequestAgentPrompt(
168 withContext.text,
169 task,
170 terminology,
171 previousPrompts.current.get(draftKey),
172 ),
173 );
174 previousPrompts.current.set(draftKey, pullRequestAgentPrompt(task, terminology));
175 if (thread) openThread(thread);
176 else openThreadRoute({ draft: { draftId: draftKey, title: `Ask about #${pr.number}` } });
177 });
178 pending.current = false;
179 setBusy(false);
180 if (AsyncResult.isFailure(result)) {
181 const cause = squashAtomCommandFailure(result);
182 Dialog.alert("Couldn't open a thread", cause instanceof Error ? cause.message : "Try again.");
183 }
184 };
185 return {
186 ...relations,
187 threads,
188 canAsk,
189 canWatch: config?.environment.capabilities.threadPullRequestWatch === true,
190 busy,
191 ask,
192 openThread,
193 };