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

useThreadActionMenu.ts

351 lines13.6 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 } 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" && !isAtomCommandInterrupted(result)) {
166 failureToast("Failed to snooze thread", squashAtomCommandFailure(result));
167 }
168 return;
169 }
170 const reportFailure = async (
171 title: string,
172 run: () => Promise<AtomCommandResult<unknown, unknown>>,
173 ) => {
174 const result = await run();
175 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
176 failureToast(title, squashAtomCommandFailure(result));
177 }
178 };
179 switch (action) {
180 case "project-settings": {
181 const project = projects.find(
182 (candidate) =>
183 candidate.environmentId === thread.environmentId &&
184 candidate.id === thread.projectId,
185 );
186 if (!project) return;
187 const projectKey =
188 logicalProjectKeyByPhysicalKey.get(derivePhysicalProjectKey(project)) ??
189 deriveLogicalProjectKeyFromSettings(project, projectGroupingSettings);
190 void router.navigate({
191 to: "/projects/$projectKey",
192 params: { projectKey },
193 });
194 return;
195 }
196 case "new-thread-on-branch": {
197 // Explicit branch carry-over: reuse the thread's worktree when it
198 // has one, otherwise its branch on the local checkout.
199 const result = await settlePromise(() =>
200 handleNewThread(scopeProjectRef(threadRef.environmentId, thread.projectId), {
201 branch: thread.branch,
202 worktreePath: thread.worktreePath,
203 envMode: thread.worktreePath ? "worktree" : "local",
204 startFromOrigin: false,
205 }),
206 );
207 if (result._tag === "Failure") {
208 failureToast("Could not create thread", squashAtomCommandFailure(result));
209 }
210 return;
211 }
212 case "settle":
213 await reportFailure("Failed to settle thread", () => settleThread(threadRef));
214 return;
215 case "unsettle":
216 await reportFailure("Failed to un-settle thread", () => unsettleThread(threadRef));
217 return;
218 case "unsnooze":
219 await reportFailure("Failed to wake thread", () => unsnoozeThread(threadRef));
220 return;
221 case "pin":
222 await reportFailure("Failed to pin thread", () => pinThread(threadRef));
223 return;
224 case "unpin": {
225 await reportFailure("Failed to unpin thread", () => confirmAndUnpinThread(threadRef));
226 return;
227 }
228 case "rename":
229 onStartRename();
230 return;
231 case "regenerate-title":
232 if (isRegeneratingTitle) return;
233 await reportFailure("Failed to regenerate thread title", () =>
234 updateThreadMetadata({
235 environmentId: threadRef.environmentId,
236 input: { threadId: threadRef.threadId, regenerateTitle: true },
237 }),
238 );
239 return;
240 case "mark-unread":
241 markThreadUnread(scopedThreadKey(threadRef), thread.latestTurn?.completedAt);
242 return;
243 case "copy-path": {
244 const workspacePath = thread.worktreePath ?? projectCwd;
245 if (!workspacePath) {
246 toastManager.add(
247 stackedThreadToast({
248 type: "error",
249 title: "Path unavailable",
250 description: "This thread does not have a workspace path to copy.",
251 }),
252 );
253 return;
254 }
255 copyPathToClipboard(workspacePath, { path: workspacePath });
256 return;
257 }
258 case "copy-branch":
259 if (thread.branch) {
260 copyBranchToClipboard(thread.branch, { branch: thread.branch });
261 }
262 return;
263 case "copy-thread-id":
264 copyThreadIdToClipboard(thread.id, { threadId: thread.id });
265 return;
266 case "archive": {
267 if (confirmThreadArchive) {
268 const confirmed = await settlePromise(() =>
269 api.dialogs.confirm(`Archive thread "${thread.title}"?`),
270 );
271 if (confirmed._tag === "Failure" || !confirmed.value) return;
272 }
273 let didArchive = false;
274 const result = await archiveThread(threadRef, {
275 onArchived: () => {
276 didArchive = true;
277 },
278 });
279 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
280 failureToast(
281 didArchive ? "Thread archived, but navigation failed" : "Failed to archive thread",
282 squashAtomCommandFailure(result),
283 );
284 }
285 return;
286 }
287 case "delete": {
288 if (confirmThreadDelete) {
289 const confirmed = await settlePromise(() =>
290 api.dialogs.confirm(
291 [
292 `Delete thread "${thread.title}"?`,
293 "This permanently clears conversation history for this thread.",
294 ].join("\n"),
295 { variant: "destructive" },
296 ),
297 );
298 if (confirmed._tag === "Failure" || !confirmed.value) return;
299 }
300 const deleted = await deleteThread(threadRef);
301 if (
302 deleted._tag === "Failure" &&
303 !isAtomCommandInterrupted(deleted) &&
304 // A failure with the thread already gone is worktree cleanup
305 // failing after a successful delete — deleteThread has toasted
306 // that itself, and "Failed to delete thread" would be a lie.
307 readThreadShell(threadRef) !== null
308 ) {
309 failureToast("Failed to delete thread", squashAtomCommandFailure(deleted));
310 }
311 return;
312 }
313 default:
314 return;
315 }
316 })();
317 },
318 [
319 archiveThread,
320 confirmThreadArchive,
321 confirmThreadDelete,
322 confirmAndUnpinThread,
323 copyBranchToClipboard,
324 copyPathToClipboard,
325 copyThreadIdToClipboard,
326 deleteThread,
327 handleNewThread,
328 logicalProjectKeyByPhysicalKey,
329 markThreadUnread,
330 onStartRename,
331 pinThread,
332 projectCwd,
333 projectGroupingSettings,
334 projects,
335 router,
336 settleThread,
337 snoozeThread,
338 threadRef,
339 timestampFormat,
340 unsettleThread,
341 unsnoozeThread,
342 updateThreadMetadata,
343 ],
344 );
345​
346 const closeMenu = useCallback(() => {
347 void readLocalApi()?.contextMenu.close();
348 }, []);
349​
350 return { openMenu, closeMenu };