Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

useThreadActionMenu.ts

371 lines14.4 KB

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