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