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

usePullRequestThreads.ts

169 lines6.9 KB

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​
42/** Stay in the PR's environment when entering a thread or creating its draft. */
43export function usePullRequestThreads(
44 params: PullRequestParams,
45 pr: PullRequestDetail | null,
46 filePath?: string,
47) {
48 const target = pullRequestTarget(params);
49 const config = useEnvironmentServerConfig(target.environmentId);
50 const supported = threadPullRequestLinkMode(config?.environment.capabilities) === "multiple";
51 const parsed = pr ? parseChangeRequestUrl(pr.url) : null;
52 const reference = {
53 ...target,
54 input: { ...target.input, ...(parsed ? normalizeThreadPullRequestKey(parsed) : {}) },
55 };
56 const key = JSON.stringify(reference);
57 const route = useRoute();
58 // The iOS split host projects detail screens beneath a synthetic workspace
59 // route. Its parent's focus flag is not the visible detail's focus flag.
60 const focused = useNavigationState((state) => state.routes[state.index]?.key === route.key);
61 const relations = useEnvironmentQuery(
62 pr && supported && focused ? composerPullRequests.linkedThreads(reference) : null,
63 );
64 const [lastRelations, setLastRelations] = useState({ key, data: relations.data });
65 if (relations.data && (lastRelations.key !== key || relations.data !== lastRelations.data))
66 setLastRelations({ key, data: relations.data });
67 const threads =
68 (relations.data ?? (lastRelations.key === key ? lastRelations.data : null))?.threads ?? [];
69 const connected = usePullRequestConnected(params.environmentId);
70 const canOperate = useEnvironmentScope(target.environmentId, AuthOrchestrationOperateScope);
71 // Composing offline only writes a local draft. The outbox checks grants on delivery.
72 const canAsk = !connected || canOperate;
73 const canCheckout = useEnvironmentScope(target.environmentId, AuthSourceControlWriteScope);
74 const navigation = useNavigation();
75 const selectAndroidWorkspace = useAndroidWorkspaceSelection();
76 const pending = useRef(false);
77 const previousPrompts = useRef(new Map<string, string>());
78 const openThread = (thread: LinkedThread) => {
79 const destination = { environmentId: params.environmentId, threadId: thread.id };
80 if (Platform.OS === "android") selectAndroidWorkspace({ name: "Thread", params: destination });
81 else navigation.navigate("Thread", destination);
82 };
83 const [busy, setBusy] = useState(false);
84 const ask = async (thread?: LinkedThread, task: PullRequestAgentTask = "ask") => {
85 if (!pr || !canAsk || pending.current) return;
86 pending.current = true;
87 setBusy(true);
88 try {
89 if (connected && !thread && !canCheckout)
90 throw new Error("Starting work from this PR requires source control write access.");
91 await waitForComposerDraftsLoaded();
92 const draftKey = thread
93 ? scopedThreadKey(target.environmentId, ThreadId.make(thread.id))
94 : createNewTaskDraft({
95 environmentId: target.environmentId,
96 projectId: target.input.projectId,
97 });
98 if (!thread)
99 updateComposerDraftSettings(draftKey, {
100 workspaceSelection: {
101 mode: "worktree",
102 branch: pr.headBranch,
103 worktreePath: null,
104 startFromOrigin: false,
105 pullRequestReference: pr.url,
106 },
107 });
108 const context = pullRequestComposerContext(
109 {
110 number: pr.number,
111 title: pr.title,
112 url: pr.url,
113 headBranch: pr.headBranch,
114 baseBranch: pr.baseBranch,
115 state: pr.state,
116 isDraft: pr.isDraft,
117 },
118 uuidv4(),
119 filePath,
120 );
121 const draft = getComposerDraftSnapshot(draftKey);
122 const attached = draft.context?.records.some(
123 (record) =>
124 record.kind === "review-comment" &&
125 "pullRequest" in record &&
126 record.pullRequest?.url === pr.url &&
127 record.filePath === context.filePath,
128 );
129 if (
130 !attached &&
131 !insertComposerDraftContext(
132 draftKey,
133 {
134 text: `${formatComposerContextReference(context)} `,
135 context: { version: 1, records: [context] },
136 },
137 { text: draft.text, start: draft.text.length, end: draft.text.length },
138 )
139 )
140 throw new Error("Remove some context from this thread's draft, then try again.");
141 const withContext = getComposerDraftSnapshot(draftKey);
142 setComposerDraftText(
143 draftKey,
144 appendPullRequestAgentPrompt(withContext.text, task, previousPrompts.current.get(draftKey)),
145 );
146 previousPrompts.current.set(draftKey, pullRequestAgentPrompt(task));
147 if (thread) openThread(thread);
148 else
149 navigation.navigate("NewTaskSheet", {
150 screen: "NewTaskDraft",
151 params: { draftId: draftKey, title: `Ask about #${pr.number}` },
152 });
153 } catch (cause) {
154 Dialog.alert("Couldn't open a thread", cause instanceof Error ? cause.message : "Try again.");
155 } finally {
156 pending.current = false;
157 setBusy(false);
158 }
159 };
160 return {
161 ...relations,
162 threads,
163 canAsk,
164 canWatch: config?.environment.capabilities.threadPullRequestWatch === true,
165 busy,
166 ask,
167 openThread,
168 };