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