Open History to see the last commit
1import {
2 pullRequestLinkProject,
3 resolveLinkPullRequestInput,
4} from "@t3tools/client-runtime/pull-request-link-input";
5import type {
6 EnvironmentProject,
7 EnvironmentThreadShell,
8} from "@t3tools/client-runtime/state/shell";
9import {
10 isAtomCommandInterrupted,
11 squashAtomCommandFailure,
12 type AtomCommandResult,
13} from "@t3tools/client-runtime/state/runtime";
14import { planThreadPullRequestMutation } from "@t3tools/client-runtime/thread-pull-request-compatibility";
15import { AuthOrchestrationOperateScope, type ThreadPullRequestLink } from "@t3tools/contracts";
16import * as Clipboard from "expo-clipboard";
17import { useCallback, useMemo } from "react";
18
19import * as Dialog from "../../components/ui/Dialog";
20import { tryOpenExternalUrl } from "../../lib/openExternalUrl";
21import type { MenuProps } from "../../components/ui/Menu.types";
22import type { EnvironmentRuntimeState } from "../../state/remote-runtime-types";
23import { useEnvironmentScope } from "../../state/session";
24import { threadEnvironment } from "../../state/threads";
25import { useAtomCommand } from "../../state/use-atom-command";
26
27type MenuAction = MenuProps["actions"][number];
28
29export function useLinkedPullRequestActions(input: {
30 readonly thread: EnvironmentThreadShell | null;
31 readonly project: EnvironmentProject | null;
32 readonly runtime: EnvironmentRuntimeState | null;
33}) {
34 const { thread, project, runtime } = input;
35 const capabilities = runtime?.serverConfig?.environment.capabilities;
36 const canOperate = useEnvironmentScope(
37 thread?.environmentId ?? null,
38 AuthOrchestrationOperateScope,
39 );
40 const canEdit = canOperate && capabilities?.threadPullRequests === true;
41 const canWatch = canOperate && capabilities?.threadPullRequestWatch === true;
42 const canStartWatch =
43 canWatch &&
44 thread !== null &&
45 thread.archivedAt === null &&
46 thread.settledAt === null &&
47 thread.settledOverride !== "settled" &&
48 thread.lineage.relationshipToParent !== "subagent";
49 const link = useAtomCommand(threadEnvironment.linkPullRequest, { reportFailure: false });
50 const unlink = useAtomCommand(threadEnvironment.unlinkPullRequest, { reportFailure: false });
51 const watch = useAtomCommand(threadEnvironment.watchPullRequest, { reportFailure: false });
52
53 const run = useCallback(
54 async (failureTitle: string, pending: Promise<AtomCommandResult<unknown, unknown>>) => {
55 const result = await pending;
56 if (result._tag === "Success" || isAtomCommandInterrupted(result)) return;
57 const cause = squashAtomCommandFailure(result);
58 Dialog.alert(failureTitle, cause instanceof Error ? cause.message : "Try again.");
59 },
60 [],
61 );
62
63 const setLinked = useCallback(
64 (
65 reference: { host: string; repository: string; number: number; url: string },
66 linked: boolean,
67 ) => {
68 if (thread === null) return;
69 const mutation = planThreadPullRequestMutation({
70 capabilities,
71 threadId: thread.id,
72 reference,
73 legacyProjectId: null,
74 linked,
75 });
76 if (mutation === null || mutation.type === "thread.meta.update") return;
77 const environmentId = thread.environmentId;
78 void run(
79 linked ? "Couldn't link this pull request" : "Couldn't unlink this pull request",
80 mutation.type === "thread.pull-request.link"
81 ? link({ environmentId, input: mutation.input })
82 : unlink({ environmentId, input: mutation.input }),
83 );
84 },
85 [capabilities, link, run, thread, unlink],
86 );
87
88 const promptLink = useCallback(() => {
89 Dialog.prompt({
90 title: "Link pull request",
91 message: "Paste a pull request URL, or enter 123 / #123 for this thread's repository.",
92 placeholder: "Pull request URL or #42",
93 initialValue: "",
94 confirmText: "Link",
95 onConfirm: (reference) => {
96 const resolved = resolveLinkPullRequestInput({
97 reference,
98 project: pullRequestLinkProject(project?.repositoryIdentity),
99 hasProject: () => true,
100 });
101 if (resolved === null) {
102 Dialog.alert("Couldn't link this pull request", "Use a pull request URL, 123, or #123.");
103 return;
104 }
105 if ("error" in resolved) {
106 Dialog.alert("Couldn't link this pull request", resolved.error);
107 return;
108 }
109 setLinked(resolved.link, true);
110 },
111 });
112 }, [project, setLinked]);
113
114 const menuActions = useCallback(
115 (link: ThreadPullRequestLink): MenuAction[] => {
116 const open = link.snapshot === null || link.snapshot.state === "open";
117 const watching = link.watch !== undefined;
118 return [
119 { id: "copy", title: "Copy link", image: "link" },
120 { id: "browser", title: "Open in browser", image: "safari" },
121 ...((watching ? canWatch : canStartWatch) && open
122 ? [
123 {
124 id: "watch",
125 title: watching ? "Stop watching" : "Watch for changes",
126 image: watching ? "eye.slash" : "eye",
127 },
128 ]
129 : []),
130 ...(canEdit
131 ? [
132 {
133 id: "unlink",
134 title: link.source === "stack" ? "Dismiss from thread" : "Unlink from thread",
135 image: "xmark",
136 attributes: { destructive: true },
137 },
138 ]
139 : []),
140 ];
141 },
142 [canEdit, canStartWatch, canWatch],
143 );
144
145 const onMenuAction = useCallback(
146 (link: ThreadPullRequestLink, action: string) => {
147 if (action === "copy") void Clipboard.setStringAsync(link.url);
148 else if (action === "browser")
149 void tryOpenExternalUrl(link.url, "pull-request").then((opened) => {
150 if (!opened) Dialog.alert("Unable to open PR", "The pull request could not be opened.");
151 });
152 else if (action === "watch" && thread !== null)
153 void run(
154 "Couldn't change watching",
155 watch({
156 environmentId: thread.environmentId,
157 input: {
158 threadId: thread.id,
159 host: link.host,
160 repository: link.repository,
161 number: link.number,
162 watching: link.watch === undefined,
163 },
164 }),
165 );
166 else if (action === "unlink") setLinked(link, false);
167 },
168 [run, setLinked, thread, watch],
169 );
170
171 return useMemo(
172 () => ({ canLink: canEdit, promptLink, menuActions, onMenuAction }),
173 [canEdit, promptLink, menuActions, onMenuAction],
174 );
175}
176
177export type LinkedPullRequestActions = ReturnType<typeof useLinkedPullRequestActions>;