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