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

useThreadActionMenu.ts

313 lines12.1 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 ChangeRequestStateLike,
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 { useUiStateStore } from "../uiStateStore";
34import { useCopyToClipboard } from "./useCopyToClipboard";
35import { useNewThreadHandler } from "./useHandleNewThread";
36import { useClientSettings } from "./useSettings";
37import { useThreadActions } from "./useThreadActions";
38​
39function failureToast(title: string, error: unknown) {
40 toastManager.add(
41 stackedThreadToast({
42 type: "error",
43 title,
44 description: error instanceof Error ? error.message : "An error occurred.",
45 }),
46 );
48​
49/**
50 * The per-thread action menu (pin, settle, snooze, rename, copy, delete…) as
51 * a self-contained hook, for surfaces other than the sidebar row — today the
52 * chat header. Renders through the native context-menu bridge and dispatches
53 * through the same mutations the sidebar uses.
54 *
55 * Unlike the sidebar, settle and snooze here never navigate away: the caller
56 * is acting on the thread they are reading, and ChatView's parked-thread
57 * banner already offers the way back.
58 */
59export function useThreadActionMenu(input: {
60 readonly threadRef: ScopedThreadRef | null;
61 /** Fallback for "Copy path" when the thread has no worktree. */
62 readonly projectCwd: string | null;
63 /** PR state feeding auto-settle classification, as resolved by the caller. */
64 readonly changeRequestState: ChangeRequestStateLike | null;
65 readonly onStartRename: () => void;
66}) {
67 const { threadRef, projectCwd, changeRequestState, onStartRename } = input;
68 const {
69 settleThread,
70 unsettleThread,
71 snoozeThread,
72 unsnoozeThread,
73 pinThread,
74 unpinThread,
75 deleteThread,
76 } = useThreadActions();
77 const updateThreadMetadata = useAtomCommand(threadEnvironment.updateMetadata, {
78 reportFailure: false,
79 });
80 const handleNewThread = useNewThreadHandler();
81 const markThreadUnread = useUiStateStore((s) => s.markThreadUnread);
82 const autoSettleAfterDays = useClientSettings((s) => s.sidebarAutoSettleAfterDays);
83 const confirmThreadDelete = useClientSettings((s) => s.confirmThreadDelete);
84 const timestampFormat = useClientSettings((s) => s.timestampFormat);
85 const { copyToClipboard: copyPathToClipboard } = useCopyToClipboard<{ path: string }>({
86 onCopy: ({ path }) => {
87 toastManager.add({ type: "success", title: "Path copied", description: path });
88 },
89 onError: (error) => failureToast("Failed to copy path", error),
90 });
91 const { copyToClipboard: copyBranchToClipboard } = useCopyToClipboard<{ branch: string }>({
92 target: "branch name",
93 onCopy: ({ branch }) => {
94 toastManager.add({ type: "success", title: "Branch copied", description: branch });
95 },
96 onError: (error) => failureToast("Failed to copy branch", error),
97 });
98 const { copyToClipboard: copyThreadIdToClipboard } = useCopyToClipboard<{ threadId: ThreadId }>({
99 onCopy: ({ threadId }) => {
100 toastManager.add({ type: "success", title: "Thread ID copied", description: threadId });
101 },
102 onError: (error) => failureToast("Failed to copy thread ID", error),
103 });
104​
105 const openMenu = useCallback(
106 (position: { x: number; y: number }) => {
107 if (threadRef === null) return;
108 void (async () => {
109 const api = readLocalApi();
110 if (!api) return;
111 // Snapshot at open time — the menu is modal, so state read now is
112 // what the user is looking at.
113 const thread = readThreadShell(threadRef);
114 if (!thread) return;
115 const now = new Date();
116 const supports = {
117 settlement: readEnvironmentSupportsSettlement(threadRef.environmentId),
118 snooze: readEnvironmentSupportsSnooze(threadRef.environmentId),
119 pinning: readEnvironmentSupportsPinning(threadRef.environmentId),
120 titleRegeneration: readEnvironmentSupportsTitleRegeneration(threadRef.environmentId),
121 };
122 const isRegeneratingTitle = thread.titleRegeneration != null;
123 const snoozePresets = resolveSnoozePresets(now, timestampFormat);
124 const items = buildThreadActionMenuItems({
125 branch: thread.branch ?? null,
126 isPinned: thread.pinnedAt != null,
127 isSettled:
128 supports.settlement &&
129 effectiveSettled(thread, {
130 // Minute-quantized like useNowMinute, so this classification
131 // can never disagree with the sidebar partition or ChatView's
132 // parked-thread banner within the same minute.
133 now: `${now.toISOString().slice(0, 16)}:00.000Z`,
134 autoSettleAfterDays,
135 changeRequestState,
136 }),
137 isSnoozed: supports.snooze && effectiveSnoozed(thread, { now: now.toISOString() }),
138 canSnoozeNow: canSnooze(thread, { now: now.toISOString() }),
139 isRegeneratingTitle,
140 supports,
141 snoozePresets,
142 });
143 const clicked = await settlePromise(() => api.contextMenu.show(items, position));
144 if (clicked._tag === "Failure" || clicked.value === null) return;
145 const action: ThreadActionMenuId = clicked.value;
146 if (action.startsWith("snooze:")) {
147 const preset = snoozePresets.find((candidate) => `snooze:${candidate.id}` === action);
148 if (!preset) return;
149 const result = await snoozeThread(threadRef, preset.snoozedUntil);
150 if (result._tag === "Failure") {
151 if (!isAtomCommandInterrupted(result)) {
152 failureToast("Failed to snooze thread", squashAtomCommandFailure(result));
153 }
154 return;
155 }
156 toastManager.add(
157 stackedThreadToast({
158 type: "success",
159 title: `Snoozed until ${snoozeWakeDescription(preset.snoozedUntil, new Date(), timestampFormat)}`,
160 timeout: 5_000,
161 actionProps: {
162 children: "Undo",
163 onClick: () => {
164 void unsnoozeThread(threadRef).then((undone) => {
165 if (undone._tag === "Failure" && !isAtomCommandInterrupted(undone)) {
166 failureToast("Failed to wake thread", squashAtomCommandFailure(undone));
167 }
168 });
169 },
170 },
171 }),
172 );
173 return;
174 }
175 const reportFailure = async (
176 title: string,
177 run: () => Promise<AtomCommandResult<unknown, unknown>>,
178 ) => {
179 const result = await run();
180 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
181 failureToast(title, squashAtomCommandFailure(result));
182 }
183 };
184 switch (action) {
185 case "new-thread-on-branch": {
186 // Explicit branch carry-over: reuse the thread's worktree when it
187 // has one, otherwise its branch on the local checkout.
188 const result = await settlePromise(() =>
189 handleNewThread(scopeProjectRef(threadRef.environmentId, thread.projectId), {
190 branch: thread.branch,
191 worktreePath: thread.worktreePath,
192 envMode: thread.worktreePath ? "worktree" : "local",
193 startFromOrigin: false,
194 }),
195 );
196 if (result._tag === "Failure") {
197 failureToast("Could not create thread", squashAtomCommandFailure(result));
198 }
199 return;
200 }
201 case "settle":
202 await reportFailure("Failed to settle thread", () => settleThread(threadRef));
203 return;
204 case "unsettle":
205 await reportFailure("Failed to un-settle thread", () => unsettleThread(threadRef));
206 return;
207 case "unsnooze":
208 await reportFailure("Failed to wake thread", () => unsnoozeThread(threadRef));
209 return;
210 case "pin":
211 await reportFailure("Failed to pin thread", () => pinThread(threadRef));
212 return;
213 case "unpin":
214 await reportFailure("Failed to unpin thread", () => unpinThread(threadRef));
215 return;
216 case "rename":
217 onStartRename();
218 return;
219 case "regenerate-title":
220 if (isRegeneratingTitle) return;
221 await reportFailure("Failed to regenerate thread title", () =>
222 updateThreadMetadata({
223 environmentId: threadRef.environmentId,
224 input: { threadId: threadRef.threadId, regenerateTitle: true },
225 }),
226 );
227 return;
228 case "mark-unread":
229 markThreadUnread(
230 scopedThreadKey(threadRef),
231 thread.latestRun?.completedAt ?? undefined,
232 );
233 return;
234 case "copy-path": {
235 const workspacePath = thread.worktreePath ?? projectCwd;
236 if (!workspacePath) {
237 toastManager.add(
238 stackedThreadToast({
239 type: "error",
240 title: "Path unavailable",
241 description: "This thread does not have a workspace path to copy.",
242 }),
243 );
244 return;
245 }
246 copyPathToClipboard(workspacePath, { path: workspacePath });
247 return;
248 }
249 case "copy-branch":
250 if (thread.branch) {
251 copyBranchToClipboard(thread.branch, { branch: thread.branch });
252 }
253 return;
254 case "copy-thread-id":
255 copyThreadIdToClipboard(thread.id, { threadId: thread.id });
256 return;
257 case "delete": {
258 if (confirmThreadDelete) {
259 const confirmed = await settlePromise(() =>
260 api.dialogs.confirm(
261 [
262 `Delete thread "${thread.title}"?`,
263 "This permanently clears conversation history for this thread.",
264 ].join("\n"),
265 { variant: "destructive" },
266 ),
267 );
268 if (confirmed._tag === "Failure" || !confirmed.value) return;
269 }
270 const deleted = await deleteThread(threadRef);
271 if (
272 deleted._tag === "Failure" &&
273 !isAtomCommandInterrupted(deleted) &&
274 // A failure with the thread already gone is worktree cleanup
275 // failing after a successful delete — deleteThread has toasted
276 // that itself, and "Failed to delete thread" would be a lie.
277 readThreadShell(threadRef) !== null
278 ) {
279 failureToast("Failed to delete thread", squashAtomCommandFailure(deleted));
280 }
281 return;
282 }
283 default:
284 return;
285 }
286 })();
287 },
288 [
289 autoSettleAfterDays,
290 changeRequestState,
291 confirmThreadDelete,
292 copyBranchToClipboard,
293 copyPathToClipboard,
294 copyThreadIdToClipboard,
295 deleteThread,
296 handleNewThread,
297 markThreadUnread,
298 onStartRename,
299 pinThread,
300 projectCwd,
301 settleThread,
302 snoozeThread,
303 threadRef,
304 timestampFormat,
305 unpinThread,
306 unsettleThread,
307 unsnoozeThread,
308 updateThreadMetadata,
309 ],
310 );
311​
312 return { openMenu };