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.runtime?.status === "running" && thread.runtime.activeRunId != 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(
255 scopedThreadKey(threadRef),
256 thread.latestRun?.completedAt ?? undefined,
257 );
258 return;
259 case "copy-path": {
260 const workspacePath = thread.worktreePath ?? projectCwd;
261 if (!workspacePath) {
262 toastManager.add(
263 stackedThreadToast({
264 type: "error",
265 title: "Path unavailable",
266 description: "This thread does not have a workspace path to copy.",
267 }),
268 );
269 return;
270 }
271 copyPathToClipboard(workspacePath, { path: workspacePath });
272 return;
273 }
274 case "copy-branch":
275 if (thread.branch) {
276 copyBranchToClipboard(thread.branch, { branch: thread.branch });
277 }
278 return;
279 case "copy-thread-id":
280 copyThreadIdToClipboard(thread.id, { threadId: thread.id });
281 return;
282 case "archive": {
283 if (confirmThreadArchive) {
284 const confirmed = await settlePromise(() =>
285 api.dialogs.confirm(`Archive thread "${thread.title}"?`),
286 );
287 if (confirmed._tag === "Failure" || !confirmed.value) return;
288 }
289 let didArchive = false;
290 const result = await archiveThread(threadRef, {
291 onArchived: () => {
292 didArchive = true;
293 },
294 });
295 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
296 failureToast(
297 didArchive ? "Thread archived, but navigation failed" : "Failed to archive thread",
298 squashAtomCommandFailure(result),
299 );
300 }
301 return;
302 }
303 case "delete": {
304 if (confirmThreadDelete) {
305 const confirmed = await settlePromise(() =>
306 api.dialogs.confirm(
307 [
308 `Delete thread "${thread.title}"?`,
309 "This permanently clears conversation history for this thread.",
310 ].join("\n"),
311 { variant: "destructive" },
312 ),
313 );
314 if (confirmed._tag === "Failure" || !confirmed.value) return;
315 }
316 const deleted = await deleteThread(threadRef);
317 if (
318 deleted._tag === "Failure" &&
319 !isAtomCommandInterrupted(deleted) &&
320 // A failure with the thread already gone is worktree cleanup
321 // failing after a successful delete — deleteThread has toasted
322 // that itself, and "Failed to delete thread" would be a lie.
323 readThreadShell(threadRef) !== null
324 ) {
325 failureToast("Failed to delete thread", squashAtomCommandFailure(deleted));
326 }
327 return;
328 }
329 default:
330 return;
331 }
332 })();
333 },
334 [
335 archiveThread,
336 confirmThreadArchive,
337 confirmThreadDelete,
338 confirmAndUnpinThread,
339 copyBranchToClipboard,
340 copyPathToClipboard,
341 copyThreadIdToClipboard,
342 deleteThread,
343 handleNewThread,
344 logicalProjectKeyByPhysicalKey,
345 markThreadUnread,
346 onStartRename,
347 pinThread,
348 projectCwd,
349 projectGroupingSettings,
350 projects,
351 router,
352 settleThread,
353 snoozeThread,
354 threadRef,
355 timestampFormat,
356 unsettleThread,
357 unsnoozeThread,
358 updateThreadMetadata,
359 ],
360 );
361
362 const closeMenu = useCallback(() => {
363 void readLocalApi()?.contextMenu.close();
364 }, []);
365
366 return { openMenu, closeMenu };
367}