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