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

useThreadActionMenu.ts

327 lines12.5 KB

1import { scopeProjectRef } from "@t3tools/client-runtime/environment";
2import { requestCustomSnooze } from "../components/CustomSnoozeDialog";
3import {
4 type AtomCommandResult,
5 isAtomCommandInterrupted,
6 settlePromise,
7 squashAtomCommandFailure,
8} from "@t3tools/client-runtime/state/runtime";
9import { canSnooze, effectiveSnoozed } from "@t3tools/client-runtime/state/thread-settled";
10import {
11 AuthOrchestrationOperateScope,
12 type ScopedThreadRef,
13 type ThreadId,
14} from "@t3tools/contracts";
15import { useRouter } from "@tanstack/react-router";
16​
17import { resolveSnoozePresets } from "../components/Sidebar.snooze";
18import {
19 buildThreadActionMenuItems,
20 threadActionRequiresOperate,
21 type ThreadActionMenuId,
22} from "../components/threadActionMenu.logic";
23import { stackedThreadToast, toastManager } from "../components/ui/toast";
24import { threadEnvironment } from "../state/threads";
25import { useOrchestrationCommand } from "../state/use-orchestration-command";
26import { readEnvironmentScope } from "../state/session";
27import {
28 readEnvironmentSupportsAutoSettleOptOut,
29 readEnvironmentSupportsPinning,
30 readEnvironmentSupportsSettlement,
31 readEnvironmentSupportsSnooze,
32 readEnvironmentSupportsTitleRegeneration,
33 readThreadShell,
34 useProjects,
35} from "../state/entities";
36import { usePrimaryEnvironmentId } from "../state/environments";
37import { readLocalApi } from "../localApi";
38import {
39 deriveLogicalProjectKeyFromSettings,
40 derivePhysicalProjectKey,
41 selectProjectGroupingSettings,
42} from "../logicalProject";
43import { buildPhysicalToLogicalProjectKeyMap } from "../sidebarProjectGrouping";
44import { threadRuntimeCanArchive } from "@t3tools/client-runtime/state/models";
45import { useCopyToClipboard } from "./useCopyToClipboard";
46import { useNewThreadHandler } from "./useHandleNewThread";
47import { useClientSettings } from "./useSettings";
48import { useThreadActions } from "./useThreadActions";
49​
50function failureToast(title: string, error: unknown) {
51 toastManager.add(
52 stackedThreadToast({
53 type: "error",
54 title,
55 description: error instanceof Error ? error.message : "An error occurred.",
56 }),
57 );
59​
60export function useThreadActionMenu(input: {
61 readonly threadRef: ScopedThreadRef | null;
62 readonly projectCwd: string | null;
63 readonly onStartRename: () => void;
64}) {
65 const { threadRef, projectCwd, onStartRename } = input;
66 const router = useRouter();
67 const projects = useProjects();
68 const primaryEnvironmentId = usePrimaryEnvironmentId();
69 const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);
70 const logicalProjectKeyByPhysicalKey = buildPhysicalToLogicalProjectKeyMap({
71 projects,
72 settings: projectGroupingSettings,
73 primaryEnvironmentId,
74 });
75 const {
76 settleThread,
77 unsettleThread,
78 snoozeThread,
79 unsnoozeThread,
80 pinThread,
81 confirmAndUnpinThread,
82 setThreadAutoSettle,
83 archiveThread,
84 deleteThread,
85 markThreadUnread,
86 } = useThreadActions();
87 const updateThreadMetadata = useOrchestrationCommand(threadEnvironment.updateMetadata, {
88 reportFailure: false,
89 });
90 const handleNewThread = useNewThreadHandler();
91 const confirmThreadDelete = useClientSettings((s) => s.confirmThreadDelete);
92 const confirmThreadArchive = useClientSettings((s) => s.confirmThreadArchive);
93 const timestampFormat = useClientSettings((s) => s.timestampFormat);
94 const { copyToClipboard: copyPathToClipboard } = useCopyToClipboard<{ path: string }>({
95 onCopy: ({ path }) => {
96 toastManager.add({ type: "success", title: "Path copied", description: path });
97 },
98 onError: (error) => failureToast("Failed to copy path", error),
99 });
100 const { copyToClipboard: copyBranchToClipboard } = useCopyToClipboard<{ branch: string }>({
101 target: "branch name",
102 onCopy: ({ branch }) => {
103 toastManager.add({ type: "success", title: "Branch copied", description: branch });
104 },
105 onError: (error) => failureToast("Failed to copy branch", error),
106 });
107 const { copyToClipboard: copyThreadIdToClipboard } = useCopyToClipboard<{ threadId: ThreadId }>({
108 onCopy: ({ threadId }) => {
109 toastManager.add({ type: "success", title: "Thread ID copied", description: threadId });
110 },
111 onError: (error) => failureToast("Failed to copy thread ID", error),
112 });
113​
114 const openMenu = (position: { x: number; y: number }) => {
115 if (threadRef === null) return;
116 void (async () => {
117 const api = readLocalApi();
118 if (!api) return;
119 const thread = readThreadShell(threadRef);
120 if (!thread) return;
121 const now = new Date();
122 const supports = {
123 settlement: readEnvironmentSupportsSettlement(threadRef.environmentId),
124 autoSettleOptOut: readEnvironmentSupportsAutoSettleOptOut(threadRef.environmentId),
125 snooze: readEnvironmentSupportsSnooze(threadRef.environmentId),
126 pinning: readEnvironmentSupportsPinning(threadRef.environmentId),
127 titleRegeneration: readEnvironmentSupportsTitleRegeneration(threadRef.environmentId),
128 };
129 const isRegeneratingTitle = thread.titleRegeneration != null;
130 const snoozePresets = resolveSnoozePresets(now, timestampFormat);
131 const items = buildThreadActionMenuItems({
132 canOperate: readEnvironmentScope(threadRef.environmentId, AuthOrchestrationOperateScope),
133 branch: thread.branch ?? null,
134 projectFilter: null,
135 isPinned: thread.pinnedAt != null,
136 isSettled: supports.settlement && thread.settledOverride === "settled",
137 autoSettleEnabled: thread.autoSettleDisabledAt == null,
138 isSnoozed: supports.snooze && effectiveSnoozed(thread, { now: now.toISOString() }),
139 canSnoozeNow: canSnooze(thread, { now: now.toISOString() }),
140 isRegeneratingTitle,
141 isRunning: !threadRuntimeCanArchive(thread.runtime),
142 supports,
143 snoozePresets,
144 });
145 const clicked = await settlePromise(() => api.contextMenu.show(items, position));
146 if (clicked._tag === "Failure" || clicked.value === null) return;
147 const action: ThreadActionMenuId = clicked.value;
148 if (
149 threadActionRequiresOperate(action) &&
150 !readEnvironmentScope(threadRef.environmentId, AuthOrchestrationOperateScope)
151 ) {
152 failureToast(
153 "Thread action unavailable",
154 new Error("This connection cannot change threads."),
155 );
156 return;
157 }
158 if (action.startsWith("snooze:")) {
159 const preset =
160 action === "snooze:custom"
161 ? await requestCustomSnooze()
162 : snoozePresets.find((candidate) => `snooze:${candidate.id}` === action);
163 if (!preset) return;
164 const result = await snoozeThread(threadRef, preset.snoozedUntil);
165 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
166 failureToast("Failed to snooze thread", squashAtomCommandFailure(result));
167 }
168 return;
169 }
170 const reportFailure = async (
171 title: string,
172 run: () => Promise<AtomCommandResult<unknown, unknown>>,
173 ) => {
174 const result = await run();
175 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
176 failureToast(title, squashAtomCommandFailure(result));
177 }
178 };
179 switch (action) {
180 case "project-settings": {
181 const project = projects.find(
182 (candidate) =>
183 candidate.environmentId === thread.environmentId && candidate.id === thread.projectId,
184 );
185 if (!project) return;
186 const projectKey =
187 logicalProjectKeyByPhysicalKey.get(derivePhysicalProjectKey(project)) ??
188 deriveLogicalProjectKeyFromSettings(project, projectGroupingSettings);
189 void router.navigate({
190 to: "/projects/$projectKey",
191 params: { projectKey },
192 });
193 return;
194 }
195 case "new-thread-on-branch": {
196 const result = await settlePromise(() =>
197 handleNewThread(scopeProjectRef(threadRef.environmentId, thread.projectId), {
198 branch: thread.branch,
199 worktreePath: thread.worktreePath,
200 envMode: thread.worktreePath ? "worktree" : "local",
201 startFromOrigin: false,
202 }),
203 );
204 if (result._tag === "Failure") {
205 failureToast("Could not create thread", squashAtomCommandFailure(result));
206 }
207 return;
208 }
209 case "settle":
210 await reportFailure("Failed to settle thread", () => settleThread(threadRef));
211 return;
212 case "unsettle":
213 await reportFailure("Failed to un-settle thread", () => unsettleThread(threadRef));
214 return;
215 case "unsnooze":
216 await reportFailure("Failed to wake thread", () => unsnoozeThread(threadRef));
217 return;
218 case "pin":
219 await reportFailure("Failed to pin thread", () => pinThread(threadRef));
220 return;
221 case "unpin": {
222 await reportFailure("Failed to unpin thread", () => confirmAndUnpinThread(threadRef));
223 return;
224 }
225 case "auto-settle:enabled":
226 case "auto-settle:disabled":
227 await reportFailure("Failed to update auto-settle", () =>
228 setThreadAutoSettle(threadRef, action === "auto-settle:enabled"),
229 );
230 return;
231 case "rename":
232 onStartRename();
233 return;
234 case "regenerate-title":
235 if (isRegeneratingTitle) return;
236 await reportFailure("Failed to regenerate thread title", () =>
237 updateThreadMetadata({
238 environmentId: threadRef.environmentId,
239 input: { threadId: threadRef.threadId, regenerateTitle: true },
240 }),
241 );
242 return;
243 case "mark-unread":
244 markThreadUnread(threadRef);
245 return;
246 case "copy-path": {
247 const workspacePath = thread.worktreePath ?? projectCwd;
248 if (!workspacePath) {
249 toastManager.add(
250 stackedThreadToast({
251 type: "error",
252 title: "Path unavailable",
253 description: "This thread does not have a workspace path to copy.",
254 }),
255 );
256 return;
257 }
258 copyPathToClipboard(workspacePath, { path: workspacePath });
259 return;
260 }
261 case "copy-branch":
262 if (thread.branch) {
263 copyBranchToClipboard(thread.branch, { branch: thread.branch });
264 }
265 return;
266 case "copy-thread-id":
267 copyThreadIdToClipboard(thread.id, { threadId: thread.id });
268 return;
269 case "archive": {
270 if (confirmThreadArchive) {
271 const confirmed = await settlePromise(() =>
272 api.dialogs.confirm(`Archive thread "${thread.title}"?`),
273 );
274 if (confirmed._tag === "Failure" || !confirmed.value) return;
275 }
276 let didArchive = false;
277 const result = await archiveThread(threadRef, {
278 onArchived: () => {
279 didArchive = true;
280 },
281 });
282 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
283 failureToast(
284 didArchive ? "Thread archived, but navigation failed" : "Failed to archive thread",
285 squashAtomCommandFailure(result),
286 );
287 }
288 return;
289 }
290 case "delete": {
291 if (confirmThreadDelete) {
292 const confirmed = await settlePromise(() =>
293 api.dialogs.confirm(
294 [
295 `Delete thread "${thread.title}"?`,
296 "This permanently clears conversation history for this thread.",
297 ].join("\n"),
298 { variant: "destructive" },
299 ),
300 );
301 if (confirmed._tag === "Failure" || !confirmed.value) return;
302 }
303 const deleted = await deleteThread(threadRef);
304 if (
305 deleted._tag === "Failure" &&
306 !isAtomCommandInterrupted(deleted) &&
307 // A failure with the thread already gone is worktree cleanup
308 // failing after a successful delete — deleteThread has toasted
309 // that itself, and "Failed to delete thread" would be a lie.
310 readThreadShell(threadRef) !== null
311 ) {
312 failureToast("Failed to delete thread", squashAtomCommandFailure(deleted));
313 }
314 return;
315 }
316 default:
317 return;
318 }
319 })();
320 };
321​
322 const closeMenu = () => {
323 void readLocalApi()?.contextMenu.close();
324 };
325​
326 return { openMenu, closeMenu };