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