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