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 { pickSnoozePreset, 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 { copyThreadReference } from "../lib/copyThreadReference";
26import { threadChipCopyTarget } from "@t3tools/client-runtime/thread-reference";
27import { threadEnvironment } from "../state/threads";
28import { useOrchestrationCommand } from "../state/use-orchestration-command";
29import { readEnvironmentScope } from "../state/session";
30import {
31 readEnvironmentServerConfigLoaded,
32 readEnvironmentSupportsAutoSettleOptOut,
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 "@t3tools/client-runtime/state/project-grouping";
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 );
58}
59
60export function useThreadActionMenu(input: {
61 readonly threadRef: ScopedThreadRef | null;
62 readonly projectCwd: string | null;
63 readonly onStartRename: () => void;
64 readonly canShareWithGuest: boolean;
65}) {
66 const { threadRef, projectCwd, onStartRename, canShareWithGuest } = input;
67 const router = useRouter();
68 const projects = useProjects();
69 const primaryEnvironmentId = usePrimaryEnvironmentId();
70 const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);
71 const logicalProjectKeyByPhysicalKey = buildPhysicalToLogicalProjectKeyMap({
72 projects,
73 settings: projectGroupingSettings,
74 primaryEnvironmentId,
75 });
76 const {
77 settleThread,
78 unsettleThread,
79 snoozeThread,
80 unsnoozeThread,
81 pinThread,
82 confirmAndUnpinThread,
83 setThreadAutoSettle,
84 archiveThread,
85 deleteThread,
86 markThreadUnread,
87 } = useThreadActions();
88 const updateThreadMetadata = useOrchestrationCommand(threadEnvironment.updateMetadata, {
89 reportFailure: false,
90 });
91 const handleNewThread = useNewThreadHandler();
92 const confirmThreadDelete = useClientSettings((s) => s.confirmThreadDelete);
93 const confirmThreadArchive = useClientSettings((s) => s.confirmThreadArchive);
94 const timestampFormat = useClientSettings((s) => s.timestampFormat);
95 const { copyToClipboard: copyPathToClipboard } = useCopyToClipboard<{ path: string }>({
96 onCopy: ({ path }) => {
97 toastManager.add({ type: "success", title: "Path copied", description: path });
98 },
99 onError: (error) => failureToast("Failed to copy path", error),
100 });
101 const { copyToClipboard: copyBranchToClipboard } = useCopyToClipboard<{ branch: string }>({
102 target: "branch name",
103 onCopy: ({ branch }) => {
104 toastManager.add({ type: "success", title: "Branch copied", description: branch });
105 },
106 onError: (error) => failureToast("Failed to copy branch", error),
107 });
108 const { copyToClipboard: copyThreadIdToClipboard } = useCopyToClipboard<{ threadId: ThreadId }>({
109 onCopy: ({ threadId }) => {
110 toastManager.add({ type: "success", title: "Thread ID copied", description: threadId });
111 },
112 onError: (error) => failureToast("Failed to copy thread ID", error),
113 });
114
115 const openMenu = (position: { x: number; y: number }) => {
116 if (threadRef === null) return;
117 void (async () => {
118 const api = readLocalApi();
119 if (!api) return;
120 const thread = readThreadShell(threadRef);
121 if (!thread) return;
122 const now = new Date();
123 const configLoaded = readEnvironmentServerConfigLoaded(threadRef.environmentId);
124 const supports = {
125 settlement: configLoaded,
126 autoSettleOptOut: readEnvironmentSupportsAutoSettleOptOut(threadRef.environmentId),
127 snooze: configLoaded,
128 pinning: configLoaded,
129 titleRegeneration: configLoaded,
130 };
131 const isRegeneratingTitle = thread.titleRegeneration != null;
132 const snoozePresets = resolveSnoozePresets(now, timestampFormat, threadRef.environmentId);
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 : pickSnoozePreset(
166 snoozePresets,
167 action.slice("snooze:".length),
168 timestampFormat,
169 threadRef.environmentId,
170 );
171 if (!preset) return;
172 const result = await snoozeThread(threadRef, preset.snoozedUntil);
173 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
174 failureToast("Failed to snooze thread", squashAtomCommandFailure(result));
175 }
176 return;
177 }
178 const reportFailure = async (
179 title: string,
180 run: () => Promise<AtomCommandResult<unknown, unknown>>,
181 ) => {
182 const result = await run();
183 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
184 failureToast(title, squashAtomCommandFailure(result));
185 }
186 };
187 switch (action) {
188 case "project-settings": {
189 const project = projects.find(
190 (candidate) =>
191 candidate.environmentId === thread.environmentId && candidate.id === thread.projectId,
192 );
193 if (!project) return;
194 const projectKey =
195 logicalProjectKeyByPhysicalKey.get(derivePhysicalProjectKey(project)) ??
196 deriveLogicalProjectKeyFromSettings(project, projectGroupingSettings);
197 void router.navigate({
198 to: "/projects/$projectKey",
199 params: { projectKey },
200 });
201 return;
202 }
203 case "new-thread-on-branch": {
204 const result = await settlePromise(() =>
205 handleNewThread(scopeProjectRef(threadRef.environmentId, thread.projectId), {
206 branch: thread.branch,
207 worktreePath: thread.worktreePath,
208 envMode: thread.worktreePath ? "worktree" : "local",
209 startFromOrigin: false,
210 }),
211 );
212 if (result._tag === "Failure") {
213 failureToast("Could not create thread", squashAtomCommandFailure(result));
214 }
215 return;
216 }
217 case "settle":
218 await reportFailure("Failed to settle thread", () => settleThread(threadRef));
219 return;
220 case "unsettle":
221 await reportFailure("Failed to un-settle thread", () => unsettleThread(threadRef));
222 return;
223 case "unsnooze":
224 await reportFailure("Failed to wake thread", () => unsnoozeThread(threadRef));
225 return;
226 case "pin":
227 await reportFailure("Failed to pin thread", () => pinThread(threadRef));
228 return;
229 case "unpin": {
230 await reportFailure("Failed to unpin thread", () => confirmAndUnpinThread(threadRef));
231 return;
232 }
233 case "auto-settle:enabled":
234 case "auto-settle:disabled":
235 await reportFailure("Failed to update auto-settle", () =>
236 setThreadAutoSettle(threadRef, action === "auto-settle:enabled"),
237 );
238 return;
239 case "rename":
240 onStartRename();
241 return;
242 case "regenerate-title":
243 if (isRegeneratingTitle) return;
244 await reportFailure("Failed to regenerate thread title", () =>
245 updateThreadMetadata({
246 environmentId: threadRef.environmentId,
247 input: { threadId: threadRef.threadId, regenerateTitle: true },
248 }),
249 );
250 return;
251 case "mark-unread":
252 markThreadUnread(threadRef);
253 return;
254 case "share-guest":
255 openGuestShareDialog(threadRef);
256 return;
257 case "copy-path": {
258 const workspacePath = thread.worktreePath ?? projectCwd;
259 if (!workspacePath) {
260 toastManager.add(
261 stackedThreadToast({
262 type: "error",
263 title: "Path unavailable",
264 description: "This thread does not have a workspace path to copy.",
265 }),
266 );
267 return;
268 }
269 copyPathToClipboard(workspacePath, { path: workspacePath });
270 return;
271 }
272 case "copy-branch":
273 if (thread.branch) {
274 copyBranchToClipboard(thread.branch, { branch: thread.branch });
275 }
276 return;
277 case "copy-thread":
278 void copyThreadReference(threadChipCopyTarget(threadRef, thread.title));
279 return;
280 case "copy-thread-id":
281 copyThreadIdToClipboard(thread.id, { threadId: thread.id });
282 return;
283 case "archive": {
284 if (confirmThreadArchive) {
285 const confirmed = await settlePromise(() =>
286 api.dialogs.confirm(`Archive thread "${thread.title}"?`),
287 );
288 if (confirmed._tag === "Failure" || !confirmed.value) return;
289 }
290 let didArchive = false;
291 const result = await archiveThread(threadRef, {
292 onArchived: () => {
293 didArchive = true;
294 },
295 });
296 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
297 failureToast(
298 didArchive ? "Thread archived, but navigation failed" : "Failed to archive thread",
299 squashAtomCommandFailure(result),
300 );
301 }
302 return;
303 }
304 case "delete": {
305 if (confirmThreadDelete) {
306 const confirmed = await settlePromise(() =>
307 api.dialogs.confirm(
308 [
309 `Delete thread "${thread.title}"?`,
310 "This permanently clears conversation history for this thread.",
311 ].join("\n"),
312 { variant: "destructive" },
313 ),
314 );
315 if (confirmed._tag === "Failure" || !confirmed.value) return;
316 }
317 const deleted = await deleteThread(threadRef);
318 if (
319 deleted._tag === "Failure" &&
320 !isAtomCommandInterrupted(deleted) &&
321 // A missing thread means cleanup failed after deletion; deleteThread already toasted that failure.
322 readThreadShell(threadRef) !== null
323 ) {
324 failureToast("Failed to delete thread", squashAtomCommandFailure(deleted));
325 }
326 return;
327 }
328 default:
329 return;
330 }
331 })();
332 };
333
334 const closeMenu = () => {
335 void readLocalApi()?.contextMenu.close();
336 };
337
338 return { openMenu, closeMenu };
339}