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