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