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