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