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