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

usePullRequestThreads.ts

177 lines7.2 KB

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