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

usePullRequestThreads.ts

181 lines7.3 KB

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