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

useThreadActionMenu.ts

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