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