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

usePullRequestThreads.ts

209 lines8.1 KB

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