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

usePullRequestThreads.ts

184 lines7.5 KB

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