Open History to see the last commit
1import { requestCustomSnooze } from "../components/CustomSnoozeDialog";
2import { scopeProjectRef, scopedThreadKey } from "@t3tools/client-runtime/environment";
3import {
4 type AtomCommandResult,
5 isAtomCommandInterrupted,
6 settlePromise,
7 squashAtomCommandFailure,
8} from "@t3tools/client-runtime/state/runtime";
9import { canSnooze, effectiveSnoozed } from "@t3tools/client-runtime/state/thread-settled";
10import type { ScopedThreadRef, ThreadId } from "@t3tools/contracts";
11import { useRouter } from "@tanstack/react-router";
12import { useCallback, useMemo } from "react";
13
14import { resolveSnoozePresets, snoozeWakeDescription } from "../components/Sidebar.snooze";
15import {
16 buildThreadActionMenuItems,
17 type ThreadActionMenuId,
18} from "../components/threadActionMenu.logic";
19import { stackedThreadToast, toastManager } from "../components/ui/toast";
20import { threadEnvironment } from "../state/threads";
21import { useAtomCommand } from "../state/use-atom-command";
22import {
23 readEnvironmentSupportsPinning,
24 readEnvironmentSupportsSettlement,
25 readEnvironmentSupportsSnooze,
26 readEnvironmentSupportsTitleRegeneration,
27 readThreadShell,
28 useProjects,
29} from "../state/entities";
30import { usePrimaryEnvironmentId } from "../state/environments";
31import { readLocalApi } from "../localApi";
32import {
33 deriveLogicalProjectKeyFromSettings,
34 derivePhysicalProjectKey,
35 selectProjectGroupingSettings,
36} from "../logicalProject";
37import { buildPhysicalToLogicalProjectKeyMap } from "../sidebarProjectGrouping";
38import { useUiStateStore } from "../uiStateStore";
39import { useCopyToClipboard } from "./useCopyToClipboard";
40import { useNewThreadHandler } from "./useHandleNewThread";
41import { useClientSettings } from "./useSettings";
42import { useThreadActions } from "./useThreadActions";
43
44function failureToast(title: string, error: unknown) {
45 toastManager.add(
46 stackedThreadToast({
47 type: "error",
48 title,
49 description: error instanceof Error ? error.message : "An error occurred.",
50 }),
51 );
52}
53
54/**
55 * The per-thread action menu (pin, settle, snooze, rename, copy, delete…) as
56 * a self-contained hook, for surfaces other than the sidebar row — today the
57 * chat header. Renders through the native context-menu bridge and dispatches
58 * through the same mutations the sidebar uses.
59 *
60 * Unlike the sidebar, settle and snooze here never navigate away: the caller
61 * is acting on the thread they are reading, and ChatView's parked-thread
62 * banner already offers the way back.
63 */
64export function useThreadActionMenu(input: {
65 readonly threadRef: ScopedThreadRef | null;
66 /** Fallback for "Copy path" when the thread has no worktree. */
67 readonly projectCwd: string | null;
68 readonly onStartRename: () => void;
69}) {
70 const { threadRef, projectCwd, onStartRename } = input;
71 const router = useRouter();
72 const projects = useProjects();
73 const primaryEnvironmentId = usePrimaryEnvironmentId();
74 const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);
75 const logicalProjectKeyByPhysicalKey = useMemo(
76 () =>
77 buildPhysicalToLogicalProjectKeyMap({
78 projects,
79 settings: projectGroupingSettings,
80 primaryEnvironmentId,
81 }),
82 [primaryEnvironmentId, projectGroupingSettings, projects],
83 );
84 const {
85 settleThread,
86 unsettleThread,
87 snoozeThread,
88 unsnoozeThread,
89 pinThread,
90 confirmAndUnpinThread,
91 archiveThread,
92 deleteThread,
93 } = useThreadActions();
94 const updateThreadMetadata = useAtomCommand(threadEnvironment.updateMetadata, {
95 reportFailure: false,
96 });
97 const handleNewThread = useNewThreadHandler();
98 const markThreadUnread = useUiStateStore((s) => s.markThreadUnread);
99 const confirmThreadDelete = useClientSettings((s) => s.confirmThreadDelete);
100 const confirmThreadArchive = useClientSettings((s) => s.confirmThreadArchive);
101 const timestampFormat = useClientSettings((s) => s.timestampFormat);
102 const { copyToClipboard: copyPathToClipboard } = useCopyToClipboard<{ path: string }>({
103 onCopy: ({ path }) => {
104 toastManager.add({ type: "success", title: "Path copied", description: path });
105 },
106 onError: (error) => failureToast("Failed to copy path", error),
107 });
108 const { copyToClipboard: copyBranchToClipboard } = useCopyToClipboard<{ branch: string }>({
109 target: "branch name",
110 onCopy: ({ branch }) => {
111 toastManager.add({ type: "success", title: "Branch copied", description: branch });
112 },
113 onError: (error) => failureToast("Failed to copy branch", error),
114 });
115 const { copyToClipboard: copyThreadIdToClipboard } = useCopyToClipboard<{ threadId: ThreadId }>({
116 onCopy: ({ threadId }) => {
117 toastManager.add({ type: "success", title: "Thread ID copied", description: threadId });
118 },
119 onError: (error) => failureToast("Failed to copy thread ID", error),
120 });
121
122 const openMenu = useCallback(
123 (position: { x: number; y: number }) => {
124 if (threadRef === null) return;
125 void (async () => {
126 const api = readLocalApi();
127 if (!api) return;
128 // Snapshot at open time — the menu is modal, so state read now is
129 // what the user is looking at.
130 const thread = readThreadShell(threadRef);
131 if (!thread) return;
132 const now = new Date();
133 const supports = {
134 settlement: readEnvironmentSupportsSettlement(threadRef.environmentId),
135 snooze: readEnvironmentSupportsSnooze(threadRef.environmentId),
136 pinning: readEnvironmentSupportsPinning(threadRef.environmentId),
137 titleRegeneration: readEnvironmentSupportsTitleRegeneration(threadRef.environmentId),
138 };
139 const isRegeneratingTitle = thread.titleRegeneration != null;
140 const snoozePresets = resolveSnoozePresets(now, timestampFormat);
141 const items = buildThreadActionMenuItems({
142 branch: thread.branch ?? null,
143 isPinned: thread.pinnedAt != null,
144 isSettled: supports.settlement && thread.settledOverride === "settled",
145 isSnoozed: supports.snooze && effectiveSnoozed(thread, { now: now.toISOString() }),
146 canSnoozeNow: canSnooze(thread, { now: now.toISOString() }),
147 isRegeneratingTitle,
148 isRunning: thread.session?.status === "running" && thread.session.activeTurnId != null,
149 supports,
150 snoozePresets,
151 });
152 const clicked = await settlePromise(() => api.contextMenu.show(items, position));
153 if (clicked._tag === "Failure" || clicked.value === null) return;
154 const action: ThreadActionMenuId = clicked.value;
155 if (action.startsWith("snooze:")) {
156 const preset =
157 action === "snooze:custom"
158 ? await requestCustomSnooze()
159 : snoozePresets.find((candidate) => `snooze:${candidate.id}` === action);
160 if (!preset) return;
161 const result = await snoozeThread(threadRef, preset.snoozedUntil);
162 if (result._tag === "Failure") {
163 if (!isAtomCommandInterrupted(result)) {
164 failureToast("Failed to snooze thread", squashAtomCommandFailure(result));
165 }
166 return;
167 }
168 toastManager.add(
169 stackedThreadToast({
170 type: "success",
171 title: `Snoozed until ${snoozeWakeDescription(preset.snoozedUntil, new Date(), timestampFormat)}`,
172 timeout: 5_000,
173 actionProps: {
174 children: "Undo",
175 onClick: () => {
176 void unsnoozeThread(threadRef).then((undone) => {
177 if (undone._tag === "Failure" && !isAtomCommandInterrupted(undone)) {
178 failureToast("Failed to wake thread", squashAtomCommandFailure(undone));
179 }
180 });
181 },
182 },
183 }),
184 );
185 return;
186 }
187 const reportFailure = async (
188 title: string,
189 run: () => Promise<AtomCommandResult<unknown, unknown>>,
190 ) => {
191 const result = await run();
192 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
193 failureToast(title, squashAtomCommandFailure(result));
194 }
195 };
196 switch (action) {
197 case "project-settings": {
198 const project = projects.find(
199 (candidate) =>
200 candidate.environmentId === thread.environmentId &&
201 candidate.id === thread.projectId,
202 );
203 if (!project) return;
204 const projectKey =
205 logicalProjectKeyByPhysicalKey.get(derivePhysicalProjectKey(project)) ??
206 deriveLogicalProjectKeyFromSettings(project, projectGroupingSettings);
207 void router.navigate({
208 to: "/projects/$projectKey",
209 params: { projectKey },
210 });
211 return;
212 }
213 case "new-thread-on-branch": {
214 // Explicit branch carry-over: reuse the thread's worktree when it
215 // has one, otherwise its branch on the local checkout.
216 const result = await settlePromise(() =>
217 handleNewThread(scopeProjectRef(threadRef.environmentId, thread.projectId), {
218 branch: thread.branch,
219 worktreePath: thread.worktreePath,
220 envMode: thread.worktreePath ? "worktree" : "local",
221 startFromOrigin: false,
222 }),
223 );
224 if (result._tag === "Failure") {
225 failureToast("Could not create thread", squashAtomCommandFailure(result));
226 }
227 return;
228 }
229 case "settle":
230 await reportFailure("Failed to settle thread", () => settleThread(threadRef));
231 return;
232 case "unsettle":
233 await reportFailure("Failed to un-settle thread", () => unsettleThread(threadRef));
234 return;
235 case "unsnooze":
236 await reportFailure("Failed to wake thread", () => unsnoozeThread(threadRef));
237 return;
238 case "pin":
239 await reportFailure("Failed to pin thread", () => pinThread(threadRef));
240 return;
241 case "unpin": {
242 await reportFailure("Failed to unpin thread", () => confirmAndUnpinThread(threadRef));
243 return;
244 }
245 case "rename":
246 onStartRename();
247 return;
248 case "regenerate-title":
249 if (isRegeneratingTitle) return;
250 await reportFailure("Failed to regenerate thread title", () =>
251 updateThreadMetadata({
252 environmentId: threadRef.environmentId,
253 input: { threadId: threadRef.threadId, regenerateTitle: true },
254 }),
255 );
256 return;
257 case "mark-unread":
258 markThreadUnread(scopedThreadKey(threadRef), thread.latestTurn?.completedAt);
259 return;
260 case "copy-path": {
261 const workspacePath = thread.worktreePath ?? projectCwd;
262 if (!workspacePath) {
263 toastManager.add(
264 stackedThreadToast({
265 type: "error",
266 title: "Path unavailable",
267 description: "This thread does not have a workspace path to copy.",
268 }),
269 );
270 return;
271 }
272 copyPathToClipboard(workspacePath, { path: workspacePath });
273 return;
274 }
275 case "copy-branch":
276 if (thread.branch) {
277 copyBranchToClipboard(thread.branch, { branch: thread.branch });
278 }
279 return;
280 case "copy-thread-id":
281 copyThreadIdToClipboard(thread.id, { threadId: thread.id });
282 return;
283 case "archive": {
284 if (confirmThreadArchive) {
285 const confirmed = await settlePromise(() =>
286 api.dialogs.confirm(`Archive thread "${thread.title}"?`),
287 );
288 if (confirmed._tag === "Failure" || !confirmed.value) return;
289 }
290 let didArchive = false;
291 const result = await archiveThread(threadRef, {
292 onArchived: () => {
293 didArchive = true;
294 },
295 });
296 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
297 failureToast(
298 didArchive ? "Thread archived, but navigation failed" : "Failed to archive thread",
299 squashAtomCommandFailure(result),
300 );
301 }
302 return;
303 }
304 case "delete": {
305 if (confirmThreadDelete) {
306 const confirmed = await settlePromise(() =>
307 api.dialogs.confirm(
308 [
309 `Delete thread "${thread.title}"?`,
310 "This permanently clears conversation history for this thread.",
311 ].join("\n"),
312 { variant: "destructive" },
313 ),
314 );
315 if (confirmed._tag === "Failure" || !confirmed.value) return;
316 }
317 const deleted = await deleteThread(threadRef);
318 if (
319 deleted._tag === "Failure" &&
320 !isAtomCommandInterrupted(deleted) &&
321 // A failure with the thread already gone is worktree cleanup
322 // failing after a successful delete — deleteThread has toasted
323 // that itself, and "Failed to delete thread" would be a lie.
324 readThreadShell(threadRef) !== null
325 ) {
326 failureToast("Failed to delete thread", squashAtomCommandFailure(deleted));
327 }
328 return;
329 }
330 default:
331 return;
332 }
333 })();
334 },
335 [
336 archiveThread,
337 confirmThreadArchive,
338 confirmThreadDelete,
339 confirmAndUnpinThread,
340 copyBranchToClipboard,
341 copyPathToClipboard,
342 copyThreadIdToClipboard,
343 deleteThread,
344 handleNewThread,
345 logicalProjectKeyByPhysicalKey,
346 markThreadUnread,
347 onStartRename,
348 pinThread,
349 projectCwd,
350 projectGroupingSettings,
351 projects,
352 router,
353 settleThread,
354 snoozeThread,
355 threadRef,
356 timestampFormat,
357 unsettleThread,
358 unsnoozeThread,
359 updateThreadMetadata,
360 ],
361 );
362
363 const closeMenu = useCallback(() => {
364 void readLocalApi()?.contextMenu.close();
365 }, []);
366
367 return { openMenu, closeMenu };
368}