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