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