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