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