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

useThreadActionMenu.ts

359 lines13.9 KB

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 ChangeRequestSettleSource,
13} from "@t3tools/client-runtime/state/thread-settled";
14import type { ScopedThreadRef, ThreadId } 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 { readThreadLink } from "../threadLink";
34import { useUiStateStore } from "../uiStateStore";
35import { useCopyToClipboard } from "./useCopyToClipboard";
36import { useNewThreadHandler } from "./useHandleNewThread";
37import { useClientSettings } from "./useSettings";
38import { useThreadActions } from "./useThreadActions";
39​
40function failureToast(title: string, error: unknown) {
41 toastManager.add(
42 stackedThreadToast({
43 type: "error",
44 title,
45 description: error instanceof Error ? error.message : "An error occurred.",
46 }),
47 );
49​
50/**
51 * The per-thread action menu (pin, settle, snooze, rename, copy, delete…) as
52 * a self-contained hook, for surfaces other than the sidebar row — today the
53 * chat header. Renders through the native context-menu bridge and dispatches
54 * through the same mutations the sidebar uses.
55 *
56 * Unlike the sidebar, settle and snooze here never navigate away: the caller
57 * is acting on the thread they are reading, and ChatView's parked-thread
58 * banner already offers the way back.
59 */
60export function useThreadActionMenu(input: {
61 readonly threadRef: ScopedThreadRef | null;
62 /** Fallback for "Copy path" when the thread has no worktree. */
63 readonly projectCwd: string | null;
64 /** PR feeding auto-settle classification, as resolved by the caller. */
65 readonly changeRequest: ChangeRequestSettleSource | null;
66 readonly onStartRename: () => void;
67}) {
68 const { threadRef, projectCwd, changeRequest, onStartRename } = input;
69 const {
70 settleThread,
71 unsettleThread,
72 snoozeThread,
73 unsnoozeThread,
74 pinThread,
75 unpinThread,
76 archiveThread,
77 deleteThread,
78 } = useThreadActions();
79 const updateThreadMetadata = useAtomCommand(threadEnvironment.updateMetadata, {
80 reportFailure: false,
81 });
82 const handleNewThread = useNewThreadHandler();
83 const markThreadUnread = useUiStateStore((s) => s.markThreadUnread);
84 const autoSettleAfterDays = useClientSettings((s) => s.sidebarAutoSettleAfterDays);
85 const autoSettleOnMerge = useClientSettings((s) => s.sidebarAutoSettleOnMerge);
86 const confirmThreadDelete = useClientSettings((s) => s.confirmThreadDelete);
87 const confirmThreadArchive = useClientSettings((s) => s.confirmThreadArchive);
88 const timestampFormat = useClientSettings((s) => s.timestampFormat);
89 const { copyToClipboard: copyPathToClipboard } = useCopyToClipboard<{ path: string }>({
90 onCopy: ({ path }) => {
91 toastManager.add({ type: "success", title: "Path copied", description: path });
92 },
93 onError: (error) => failureToast("Failed to copy path", error),
94 });
95 const { copyToClipboard: copyBranchToClipboard } = useCopyToClipboard<{ branch: string }>({
96 target: "branch name",
97 onCopy: ({ branch }) => {
98 toastManager.add({ type: "success", title: "Branch copied", description: branch });
99 },
100 onError: (error) => failureToast("Failed to copy branch", error),
101 });
102 const { copyToClipboard: copyLinkToClipboard } = useCopyToClipboard<{ link: string }>({
103 target: "link",
104 onCopy: ({ link }) => {
105 toastManager.add({ type: "success", title: "Link copied", description: link });
106 },
107 onError: (error) => failureToast("Failed to copy link", error),
108 });
109 const { copyToClipboard: copyThreadIdToClipboard } = useCopyToClipboard<{ threadId: ThreadId }>({
110 onCopy: ({ threadId }) => {
111 toastManager.add({ type: "success", title: "Thread ID copied", description: threadId });
112 },
113 onError: (error) => failureToast("Failed to copy thread ID", error),
114 });
115​
116 const openMenu = useCallback(
117 (position: { x: number; y: number }) => {
118 if (threadRef === null) return;
119 void (async () => {
120 const api = readLocalApi();
121 if (!api) return;
122 // Snapshot at open time — the menu is modal, so state read now is
123 // what the user is looking at.
124 const thread = readThreadShell(threadRef);
125 if (!thread) return;
126 const now = new Date();
127 const supports = {
128 settlement: readEnvironmentSupportsSettlement(threadRef.environmentId),
129 snooze: readEnvironmentSupportsSnooze(threadRef.environmentId),
130 pinning: readEnvironmentSupportsPinning(threadRef.environmentId),
131 titleRegeneration: readEnvironmentSupportsTitleRegeneration(threadRef.environmentId),
132 };
133 const isRegeneratingTitle = thread.titleRegeneration != null;
134 const snoozePresets = resolveSnoozePresets(now, timestampFormat);
135 const threadLink = readThreadLink(threadRef);
136 const items = buildThreadActionMenuItems({
137 branch: thread.branch ?? null,
138 isPinned: thread.pinnedAt != null,
139 isSettled:
140 supports.settlement &&
141 effectiveSettled(thread, {
142 // Minute-quantized like useNowMinute, so this classification
143 // can never disagree with the sidebar partition or ChatView's
144 // parked-thread banner within the same minute.
145 now: `${now.toISOString().slice(0, 16)}:00.000Z`,
146 autoSettleAfterDays,
147 autoSettleOnMerge,
148 changeRequest,
149 }),
150 isSnoozed: supports.snooze && effectiveSnoozed(thread, { now: now.toISOString() }),
151 canSnoozeNow: canSnooze(thread, { now: now.toISOString() }),
152 isRegeneratingTitle,
153 isRunning: thread.session?.status === "running" && thread.session.activeTurnId != null,
154 supports,
155 snoozePresets,
156 canCopyLink: threadLink !== null,
157 });
158 const clicked = await settlePromise(() => api.contextMenu.show(items, position));
159 if (clicked._tag === "Failure" || clicked.value === null) return;
160 const action: ThreadActionMenuId = clicked.value;
161 if (action.startsWith("snooze:")) {
162 const preset = 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 "new-thread-on-branch": {
201 // Explicit branch carry-over: reuse the thread's worktree when it
202 // has one, otherwise its branch on the local checkout.
203 const result = await settlePromise(() =>
204 handleNewThread(scopeProjectRef(threadRef.environmentId, thread.projectId), {
205 branch: thread.branch,
206 worktreePath: thread.worktreePath,
207 envMode: thread.worktreePath ? "worktree" : "local",
208 startFromOrigin: false,
209 }),
210 );
211 if (result._tag === "Failure") {
212 failureToast("Could not create thread", squashAtomCommandFailure(result));
213 }
214 return;
215 }
216 case "settle":
217 await reportFailure("Failed to settle thread", () => settleThread(threadRef));
218 return;
219 case "unsettle":
220 await reportFailure("Failed to un-settle thread", () => unsettleThread(threadRef));
221 return;
222 case "unsnooze":
223 await reportFailure("Failed to wake thread", () => unsnoozeThread(threadRef));
224 return;
225 case "pin":
226 await reportFailure("Failed to pin thread", () => pinThread(threadRef));
227 return;
228 case "unpin":
229 await reportFailure("Failed to unpin thread", () => unpinThread(threadRef));
230 return;
231 case "rename":
232 onStartRename();
233 return;
234 case "regenerate-title":
235 if (isRegeneratingTitle) return;
236 await reportFailure("Failed to regenerate thread title", () =>
237 updateThreadMetadata({
238 environmentId: threadRef.environmentId,
239 input: { threadId: threadRef.threadId, regenerateTitle: true },
240 }),
241 );
242 return;
243 case "mark-unread":
244 markThreadUnread(scopedThreadKey(threadRef), thread.latestTurn?.completedAt);
245 return;
246 case "copy-link":
247 if (threadLink) {
248 copyLinkToClipboard(threadLink, { link: threadLink });
249 }
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 autoSettleAfterDays,
329 autoSettleOnMerge,
330 changeRequest,
331 confirmThreadArchive,
332 confirmThreadDelete,
333 copyBranchToClipboard,
334 copyLinkToClipboard,
335 copyPathToClipboard,
336 copyThreadIdToClipboard,
337 deleteThread,
338 handleNewThread,
339 markThreadUnread,
340 onStartRename,
341 pinThread,
342 projectCwd,
343 settleThread,
344 snoozeThread,
345 threadRef,
346 timestampFormat,
347 unpinThread,
348 unsettleThread,
349 unsnoozeThread,
350 updateThreadMetadata,
351 ],
352 );
353​
354 const closeMenu = useCallback(() => {
355 void readLocalApi()?.contextMenu.close();
356 }, []);
357​
358 return { openMenu, closeMenu };