Open History to see the last commit
1import { scopeProjectRef } from "@t3tools/client-runtime/environment";
2import { requestCustomSnooze } from "../components/CustomSnoozeDialog";
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 { threadRuntimeCanArchive } from "@t3tools/client-runtime/state/models";
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 markThreadUnread,
94 } = useThreadActions();
95 const updateThreadMetadata = useAtomCommand(threadEnvironment.updateMetadata, {
96 reportFailure: false,
97 });
98 const handleNewThread = useNewThreadHandler();
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 projectFilter: null,
144 isPinned: thread.pinnedAt != null,
145 isSettled: supports.settlement && thread.settledOverride === "settled",
146 isSnoozed: supports.snooze && effectiveSnoozed(thread, { now: now.toISOString() }),
147 canSnoozeNow: canSnooze(thread, { now: now.toISOString() }),
148 isRegeneratingTitle,
149 isRunning: !threadRuntimeCanArchive(thread.runtime),
150 supports,
151 snoozePresets,
152 });
153 const clicked = await settlePromise(() => api.contextMenu.show(items, position));
154 if (clicked._tag === "Failure" || clicked.value === null) return;
155 const action: ThreadActionMenuId = clicked.value;
156 if (action.startsWith("snooze:")) {
157 const preset =
158 action === "snooze:custom"
159 ? await requestCustomSnooze()
160 : snoozePresets.find((candidate) => `snooze:${candidate.id}` === action);
161 if (!preset) return;
162 const result = await snoozeThread(threadRef, preset.snoozedUntil);
163 if (result._tag === "Failure") {
164 if (!isAtomCommandInterrupted(result)) {
165 failureToast("Failed to snooze thread", squashAtomCommandFailure(result));
166 }
167 return;
168 }
169 toastManager.add(
170 stackedThreadToast({
171 type: "success",
172 title: `Snoozed until ${snoozeWakeDescription(preset.snoozedUntil, new Date(), timestampFormat)}`,
173 timeout: 5_000,
174 actionProps: {
175 children: "Undo",
176 onClick: () => {
177 void unsnoozeThread(threadRef).then((undone) => {
178 if (undone._tag === "Failure" && !isAtomCommandInterrupted(undone)) {
179 failureToast("Failed to wake thread", squashAtomCommandFailure(undone));
180 }
181 });
182 },
183 },
184 }),
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 "project-settings": {
199 const project = projects.find(
200 (candidate) =>
201 candidate.environmentId === thread.environmentId &&
202 candidate.id === thread.projectId,
203 );
204 if (!project) return;
205 const projectKey =
206 logicalProjectKeyByPhysicalKey.get(derivePhysicalProjectKey(project)) ??
207 deriveLogicalProjectKeyFromSettings(project, projectGroupingSettings);
208 void router.navigate({
209 to: "/projects/$projectKey",
210 params: { projectKey },
211 });
212 return;
213 }
214 case "new-thread-on-branch": {
215 // Explicit branch carry-over: reuse the thread's worktree when it
216 // has one, otherwise its branch on the local checkout.
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("Could not create thread", squashAtomCommandFailure(result));
227 }
228 return;
229 }
230 case "settle":
231 await reportFailure("Failed to settle thread", () => settleThread(threadRef));
232 return;
233 case "unsettle":
234 await reportFailure("Failed to un-settle thread", () => unsettleThread(threadRef));
235 return;
236 case "unsnooze":
237 await reportFailure("Failed to wake thread", () => unsnoozeThread(threadRef));
238 return;
239 case "pin":
240 await reportFailure("Failed to pin thread", () => pinThread(threadRef));
241 return;
242 case "unpin": {
243 await reportFailure("Failed to unpin thread", () => confirmAndUnpinThread(threadRef));
244 return;
245 }
246 case "rename":
247 onStartRename();
248 return;
249 case "regenerate-title":
250 if (isRegeneratingTitle) return;
251 await reportFailure("Failed to regenerate thread title", () =>
252 updateThreadMetadata({
253 environmentId: threadRef.environmentId,
254 input: { threadId: threadRef.threadId, regenerateTitle: true },
255 }),
256 );
257 return;
258 case "mark-unread":
259 markThreadUnread(threadRef);
260 return;
261 case "copy-path": {
262 const workspacePath = thread.worktreePath ?? projectCwd;
263 if (!workspacePath) {
264 toastManager.add(
265 stackedThreadToast({
266 type: "error",
267 title: "Path unavailable",
268 description: "This thread does not have a workspace path to copy.",
269 }),
270 );
271 return;
272 }
273 copyPathToClipboard(workspacePath, { path: workspacePath });
274 return;
275 }
276 case "copy-branch":
277 if (thread.branch) {
278 copyBranchToClipboard(thread.branch, { branch: thread.branch });
279 }
280 return;
281 case "copy-thread-id":
282 copyThreadIdToClipboard(thread.id, { threadId: thread.id });
283 return;
284 case "archive": {
285 if (confirmThreadArchive) {
286 const confirmed = await settlePromise(() =>
287 api.dialogs.confirm(`Archive thread "${thread.title}"?`),
288 );
289 if (confirmed._tag === "Failure" || !confirmed.value) return;
290 }
291 let didArchive = false;
292 const result = await archiveThread(threadRef, {
293 onArchived: () => {
294 didArchive = true;
295 },
296 });
297 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
298 failureToast(
299 didArchive ? "Thread archived, but navigation failed" : "Failed to archive thread",
300 squashAtomCommandFailure(result),
301 );
302 }
303 return;
304 }
305 case "delete": {
306 if (confirmThreadDelete) {
307 const confirmed = await settlePromise(() =>
308 api.dialogs.confirm(
309 [
310 `Delete thread "${thread.title}"?`,
311 "This permanently clears conversation history for this thread.",
312 ].join("\n"),
313 { variant: "destructive" },
314 ),
315 );
316 if (confirmed._tag === "Failure" || !confirmed.value) return;
317 }
318 const deleted = await deleteThread(threadRef);
319 if (
320 deleted._tag === "Failure" &&
321 !isAtomCommandInterrupted(deleted) &&
322 // A failure with the thread already gone is worktree cleanup
323 // failing after a successful delete — deleteThread has toasted
324 // that itself, and "Failed to delete thread" would be a lie.
325 readThreadShell(threadRef) !== null
326 ) {
327 failureToast("Failed to delete thread", squashAtomCommandFailure(deleted));
328 }
329 return;
330 }
331 default:
332 return;
333 }
334 })();
335 },
336 [
337 archiveThread,
338 confirmThreadArchive,
339 confirmThreadDelete,
340 confirmAndUnpinThread,
341 copyBranchToClipboard,
342 copyPathToClipboard,
343 copyThreadIdToClipboard,
344 deleteThread,
345 handleNewThread,
346 logicalProjectKeyByPhysicalKey,
347 markThreadUnread,
348 onStartRename,
349 pinThread,
350 projectCwd,
351 projectGroupingSettings,
352 projects,
353 router,
354 settleThread,
355 snoozeThread,
356 threadRef,
357 timestampFormat,
358 unsettleThread,
359 unsnoozeThread,
360 updateThreadMetadata,
361 ],
362 );
363
364 const closeMenu = useCallback(() => {
365 void readLocalApi()?.contextMenu.close();
366 }, []);
367
368 return { openMenu, closeMenu };
369}