Open History to see the last commit
1import { scopeProjectRef } from "@t3tools/client-runtime/environment";
2import { requestCustomSnooze } from "../components/CustomSnoozeDialog";
3import {
4 type AtomCommandResult,
5 isAtomCommandInterrupted,
6 settlePromise,
7 squashAtomCommandFailure,
8} from "@t3tools/client-runtime/state/runtime";
9import { canSnooze, effectiveSnoozed } from "@t3tools/client-runtime/state/thread-settled";
10import type { ScopedThreadRef, ThreadId } from "@t3tools/contracts";
11import { useRouter } from "@tanstack/react-router";
12import { useCallback, useMemo } from "react";
13
14import { resolveSnoozePresets } from "../components/Sidebar.snooze";
15import {
16 buildThreadActionMenuItems,
17 type ThreadActionMenuId,
18} from "../components/threadActionMenu.logic";
19import { stackedThreadToast, toastManager } from "../components/ui/toast";
20import { threadEnvironment } from "../state/threads";
21import { useAtomCommand } from "../state/use-atom-command";
22import {
23 readEnvironmentSupportsAutoSettleOptOut,
24 readEnvironmentSupportsPinning,
25 readEnvironmentSupportsSettlement,
26 readEnvironmentSupportsSnooze,
27 readEnvironmentSupportsTitleRegeneration,
28 readThreadShell,
29 useProjects,
30} from "../state/entities";
31import { usePrimaryEnvironmentId } from "../state/environments";
32import { readLocalApi } from "../localApi";
33import {
34 deriveLogicalProjectKeyFromSettings,
35 derivePhysicalProjectKey,
36 selectProjectGroupingSettings,
37} from "../logicalProject";
38import { buildPhysicalToLogicalProjectKeyMap } from "../sidebarProjectGrouping";
39import { threadRuntimeCanArchive } from "@t3tools/client-runtime/state/models";
40import { useCopyToClipboard } from "./useCopyToClipboard";
41import { useNewThreadHandler } from "./useHandleNewThread";
42import { useClientSettings } from "./useSettings";
43import { useThreadActions } from "./useThreadActions";
44
45function failureToast(title: string, error: unknown) {
46 toastManager.add(
47 stackedThreadToast({
48 type: "error",
49 title,
50 description: error instanceof Error ? error.message : "An error occurred.",
51 }),
52 );
53}
54
55/**
56 * The per-thread action menu (pin, settle, snooze, rename, copy, delete…) as
57 * a self-contained hook, for surfaces other than the sidebar row — today the
58 * chat header. Renders through the native context-menu bridge and dispatches
59 * through the same mutations the sidebar uses.
60 *
61 * Unlike the sidebar, settle and snooze here never navigate away: the caller
62 * is acting on the thread they are reading, and ChatView's parked-thread
63 * banner already offers the way back.
64 */
65export function useThreadActionMenu(input: {
66 readonly threadRef: ScopedThreadRef | null;
67 /** Fallback for "Copy path" when the thread has no worktree. */
68 readonly projectCwd: string | null;
69 readonly onStartRename: () => void;
70}) {
71 const { threadRef, projectCwd, onStartRename } = input;
72 const router = useRouter();
73 const projects = useProjects();
74 const primaryEnvironmentId = usePrimaryEnvironmentId();
75 const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);
76 const logicalProjectKeyByPhysicalKey = useMemo(
77 () =>
78 buildPhysicalToLogicalProjectKeyMap({
79 projects,
80 settings: projectGroupingSettings,
81 primaryEnvironmentId,
82 }),
83 [primaryEnvironmentId, projectGroupingSettings, projects],
84 );
85 const {
86 settleThread,
87 unsettleThread,
88 snoozeThread,
89 unsnoozeThread,
90 pinThread,
91 confirmAndUnpinThread,
92 setThreadAutoSettle,
93 archiveThread,
94 deleteThread,
95 markThreadUnread,
96 } = useThreadActions();
97 const updateThreadMetadata = useAtomCommand(threadEnvironment.updateMetadata, {
98 reportFailure: false,
99 });
100 const handleNewThread = useNewThreadHandler();
101 const confirmThreadDelete = useClientSettings((s) => s.confirmThreadDelete);
102 const confirmThreadArchive = useClientSettings((s) => s.confirmThreadArchive);
103 const timestampFormat = useClientSettings((s) => s.timestampFormat);
104 const { copyToClipboard: copyPathToClipboard } = useCopyToClipboard<{ path: string }>({
105 onCopy: ({ path }) => {
106 toastManager.add({ type: "success", title: "Path copied", description: path });
107 },
108 onError: (error) => failureToast("Failed to copy path", error),
109 });
110 const { copyToClipboard: copyBranchToClipboard } = useCopyToClipboard<{ branch: string }>({
111 target: "branch name",
112 onCopy: ({ branch }) => {
113 toastManager.add({ type: "success", title: "Branch copied", description: branch });
114 },
115 onError: (error) => failureToast("Failed to copy branch", error),
116 });
117 const { copyToClipboard: copyThreadIdToClipboard } = useCopyToClipboard<{ threadId: ThreadId }>({
118 onCopy: ({ threadId }) => {
119 toastManager.add({ type: "success", title: "Thread ID copied", description: threadId });
120 },
121 onError: (error) => failureToast("Failed to copy thread ID", error),
122 });
123
124 const openMenu = useCallback(
125 (position: { x: number; y: number }) => {
126 if (threadRef === null) return;
127 void (async () => {
128 const api = readLocalApi();
129 if (!api) return;
130 // Snapshot at open time — the menu is modal, so state read now is
131 // what the user is looking at.
132 const thread = readThreadShell(threadRef);
133 if (!thread) return;
134 const now = new Date();
135 const supports = {
136 settlement: readEnvironmentSupportsSettlement(threadRef.environmentId),
137 autoSettleOptOut: readEnvironmentSupportsAutoSettleOptOut(threadRef.environmentId),
138 snooze: readEnvironmentSupportsSnooze(threadRef.environmentId),
139 pinning: readEnvironmentSupportsPinning(threadRef.environmentId),
140 titleRegeneration: readEnvironmentSupportsTitleRegeneration(threadRef.environmentId),
141 };
142 const isRegeneratingTitle = thread.titleRegeneration != null;
143 const snoozePresets = resolveSnoozePresets(now, timestampFormat);
144 const items = buildThreadActionMenuItems({
145 branch: thread.branch ?? null,
146 projectFilter: null,
147 isPinned: thread.pinnedAt != null,
148 isSettled: supports.settlement && thread.settledOverride === "settled",
149 autoSettleEnabled: thread.autoSettleDisabledAt == null,
150 isSnoozed: supports.snooze && effectiveSnoozed(thread, { now: now.toISOString() }),
151 canSnoozeNow: canSnooze(thread, { now: now.toISOString() }),
152 isRegeneratingTitle,
153 isRunning: !threadRuntimeCanArchive(thread.runtime),
154 supports,
155 snoozePresets,
156 });
157 const clicked = await settlePromise(() => api.contextMenu.show(items, position));
158 if (clicked._tag === "Failure" || clicked.value === null) return;
159 const action: ThreadActionMenuId = clicked.value;
160 if (action.startsWith("snooze:")) {
161 const preset =
162 action === "snooze:custom"
163 ? await requestCustomSnooze()
164 : snoozePresets.find((candidate) => `snooze:${candidate.id}` === action);
165 if (!preset) return;
166 const result = await snoozeThread(threadRef, preset.snoozedUntil);
167 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
168 failureToast("Failed to snooze thread", squashAtomCommandFailure(result));
169 }
170 return;
171 }
172 const reportFailure = async (
173 title: string,
174 run: () => Promise<AtomCommandResult<unknown, unknown>>,
175 ) => {
176 const result = await run();
177 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
178 failureToast(title, squashAtomCommandFailure(result));
179 }
180 };
181 switch (action) {
182 case "project-settings": {
183 const project = projects.find(
184 (candidate) =>
185 candidate.environmentId === thread.environmentId &&
186 candidate.id === thread.projectId,
187 );
188 if (!project) return;
189 const projectKey =
190 logicalProjectKeyByPhysicalKey.get(derivePhysicalProjectKey(project)) ??
191 deriveLogicalProjectKeyFromSettings(project, projectGroupingSettings);
192 void router.navigate({
193 to: "/projects/$projectKey",
194 params: { projectKey },
195 });
196 return;
197 }
198 case "new-thread-on-branch": {
199 // Explicit branch carry-over: reuse the thread's worktree when it
200 // has one, otherwise its branch on the local checkout.
201 const result = await settlePromise(() =>
202 handleNewThread(scopeProjectRef(threadRef.environmentId, thread.projectId), {
203 branch: thread.branch,
204 worktreePath: thread.worktreePath,
205 envMode: thread.worktreePath ? "worktree" : "local",
206 startFromOrigin: false,
207 }),
208 );
209 if (result._tag === "Failure") {
210 failureToast("Could not create thread", squashAtomCommandFailure(result));
211 }
212 return;
213 }
214 case "settle":
215 await reportFailure("Failed to settle thread", () => settleThread(threadRef));
216 return;
217 case "unsettle":
218 await reportFailure("Failed to un-settle thread", () => unsettleThread(threadRef));
219 return;
220 case "unsnooze":
221 await reportFailure("Failed to wake thread", () => unsnoozeThread(threadRef));
222 return;
223 case "pin":
224 await reportFailure("Failed to pin thread", () => pinThread(threadRef));
225 return;
226 case "unpin": {
227 await reportFailure("Failed to unpin thread", () => confirmAndUnpinThread(threadRef));
228 return;
229 }
230 case "auto-settle:enabled":
231 case "auto-settle:disabled":
232 await reportFailure("Failed to update auto-settle", () =>
233 setThreadAutoSettle(threadRef, action === "auto-settle:enabled"),
234 );
235 return;
236 case "rename":
237 onStartRename();
238 return;
239 case "regenerate-title":
240 if (isRegeneratingTitle) return;
241 await reportFailure("Failed to regenerate thread title", () =>
242 updateThreadMetadata({
243 environmentId: threadRef.environmentId,
244 input: { threadId: threadRef.threadId, regenerateTitle: true },
245 }),
246 );
247 return;
248 case "mark-unread":
249 markThreadUnread(threadRef);
250 return;
251 case "copy-path": {
252 const workspacePath = thread.worktreePath ?? projectCwd;
253 if (!workspacePath) {
254 toastManager.add(
255 stackedThreadToast({
256 type: "error",
257 title: "Path unavailable",
258 description: "This thread does not have a workspace path to copy.",
259 }),
260 );
261 return;
262 }
263 copyPathToClipboard(workspacePath, { path: workspacePath });
264 return;
265 }
266 case "copy-branch":
267 if (thread.branch) {
268 copyBranchToClipboard(thread.branch, { branch: thread.branch });
269 }
270 return;
271 case "copy-thread-id":
272 copyThreadIdToClipboard(thread.id, { threadId: thread.id });
273 return;
274 case "archive": {
275 if (confirmThreadArchive) {
276 const confirmed = await settlePromise(() =>
277 api.dialogs.confirm(`Archive thread "${thread.title}"?`),
278 );
279 if (confirmed._tag === "Failure" || !confirmed.value) return;
280 }
281 let didArchive = false;
282 const result = await archiveThread(threadRef, {
283 onArchived: () => {
284 didArchive = true;
285 },
286 });
287 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
288 failureToast(
289 didArchive ? "Thread archived, but navigation failed" : "Failed to archive thread",
290 squashAtomCommandFailure(result),
291 );
292 }
293 return;
294 }
295 case "delete": {
296 if (confirmThreadDelete) {
297 const confirmed = await settlePromise(() =>
298 api.dialogs.confirm(
299 [
300 `Delete thread "${thread.title}"?`,
301 "This permanently clears conversation history for this thread.",
302 ].join("\n"),
303 { variant: "destructive" },
304 ),
305 );
306 if (confirmed._tag === "Failure" || !confirmed.value) return;
307 }
308 const deleted = await deleteThread(threadRef);
309 if (
310 deleted._tag === "Failure" &&
311 !isAtomCommandInterrupted(deleted) &&
312 // A failure with the thread already gone is worktree cleanup
313 // failing after a successful delete — deleteThread has toasted
314 // that itself, and "Failed to delete thread" would be a lie.
315 readThreadShell(threadRef) !== null
316 ) {
317 failureToast("Failed to delete thread", squashAtomCommandFailure(deleted));
318 }
319 return;
320 }
321 default:
322 return;
323 }
324 })();
325 },
326 [
327 archiveThread,
328 confirmThreadArchive,
329 confirmThreadDelete,
330 confirmAndUnpinThread,
331 copyBranchToClipboard,
332 copyPathToClipboard,
333 copyThreadIdToClipboard,
334 deleteThread,
335 handleNewThread,
336 logicalProjectKeyByPhysicalKey,
337 markThreadUnread,
338 onStartRename,
339 pinThread,
340 projectCwd,
341 projectGroupingSettings,
342 projects,
343 router,
344 setThreadAutoSettle,
345 settleThread,
346 snoozeThread,
347 threadRef,
348 timestampFormat,
349 unsettleThread,
350 unsnoozeThread,
351 updateThreadMetadata,
352 ],
353 );
354
355 const closeMenu = useCallback(() => {
356 void readLocalApi()?.contextMenu.close();
357 }, []);
358
359 return { openMenu, closeMenu };
360}