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