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

useThreadActionMenu.ts

339 lines13.2 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 archiveThread,
76 deleteThread,
77 } = useThreadActions();
78 const updateThreadMetadata = useAtomCommand(threadEnvironment.updateMetadata, {
79 reportFailure: false,
80 });
81 const handleNewThread = useNewThreadHandler();
82 const markThreadUnread = useUiStateStore((s) => s.markThreadUnread);
83 const autoSettleAfterDays = useClientSettings((s) => s.sidebarAutoSettleAfterDays);
84 const autoSettleOnMerge = useClientSettings((s) => s.sidebarAutoSettleOnMerge);
85 const confirmThreadDelete = useClientSettings((s) => s.confirmThreadDelete);
86 const confirmThreadArchive = useClientSettings((s) => s.confirmThreadArchive);
87 const timestampFormat = useClientSettings((s) => s.timestampFormat);
88 const { copyToClipboard: copyPathToClipboard } = useCopyToClipboard<{ path: string }>({
89 onCopy: ({ path }) => {
90 toastManager.add({ type: "success", title: "Path copied", description: path });
91 },
92 onError: (error) => failureToast("Failed to copy path", error),
93 });
94 const { copyToClipboard: copyBranchToClipboard } = useCopyToClipboard<{ branch: string }>({
95 target: "branch name",
96 onCopy: ({ branch }) => {
97 toastManager.add({ type: "success", title: "Branch copied", description: branch });
98 },
99 onError: (error) => failureToast("Failed to copy branch", error),
100 });
101 const { copyToClipboard: copyThreadIdToClipboard } = useCopyToClipboard<{ threadId: ThreadId }>({
102 onCopy: ({ threadId }) => {
103 toastManager.add({ type: "success", title: "Thread ID copied", description: threadId });
104 },
105 onError: (error) => failureToast("Failed to copy thread ID", error),
106 });
107​
108 const openMenu = useCallback(
109 (position: { x: number; y: number }) => {
110 if (threadRef === null) return;
111 void (async () => {
112 const api = readLocalApi();
113 if (!api) return;
114 // Snapshot at open time — the menu is modal, so state read now is
115 // what the user is looking at.
116 const thread = readThreadShell(threadRef);
117 if (!thread) return;
118 const now = new Date();
119 const supports = {
120 settlement: readEnvironmentSupportsSettlement(threadRef.environmentId),
121 snooze: readEnvironmentSupportsSnooze(threadRef.environmentId),
122 pinning: readEnvironmentSupportsPinning(threadRef.environmentId),
123 titleRegeneration: readEnvironmentSupportsTitleRegeneration(threadRef.environmentId),
124 };
125 const isRegeneratingTitle = thread.titleRegeneration != null;
126 const snoozePresets = resolveSnoozePresets(now, timestampFormat);
127 const items = buildThreadActionMenuItems({
128 branch: thread.branch ?? null,
129 isPinned: thread.pinnedAt != null,
130 isSettled:
131 supports.settlement &&
132 effectiveSettled(thread, {
133 // Minute-quantized like useNowMinute, so this classification
134 // can never disagree with the sidebar partition or ChatView's
135 // parked-thread banner within the same minute.
136 now: `${now.toISOString().slice(0, 16)}:00.000Z`,
137 autoSettleAfterDays,
138 autoSettleOnMerge,
139 changeRequestState,
140 }),
141 isSnoozed: supports.snooze && effectiveSnoozed(thread, { now: now.toISOString() }),
142 canSnoozeNow: canSnooze(thread, { now: now.toISOString() }),
143 isRegeneratingTitle,
144 isRunning: thread.session?.status === "running" && thread.session.activeTurnId != null,
145 supports,
146 snoozePresets,
147 });
148 const clicked = await settlePromise(() => api.contextMenu.show(items, position));
149 if (clicked._tag === "Failure" || clicked.value === null) return;
150 const action: ThreadActionMenuId = clicked.value;
151 if (action.startsWith("snooze:")) {
152 const preset = snoozePresets.find((candidate) => `snooze:${candidate.id}` === action);
153 if (!preset) return;
154 const result = await snoozeThread(threadRef, preset.snoozedUntil);
155 if (result._tag === "Failure") {
156 if (!isAtomCommandInterrupted(result)) {
157 failureToast("Failed to snooze thread", squashAtomCommandFailure(result));
158 }
159 return;
160 }
161 toastManager.add(
162 stackedThreadToast({
163 type: "success",
164 title: `Snoozed until ${snoozeWakeDescription(preset.snoozedUntil, new Date(), timestampFormat)}`,
165 timeout: 5_000,
166 actionProps: {
167 children: "Undo",
168 onClick: () => {
169 void unsnoozeThread(threadRef).then((undone) => {
170 if (undone._tag === "Failure" && !isAtomCommandInterrupted(undone)) {
171 failureToast("Failed to wake thread", squashAtomCommandFailure(undone));
172 }
173 });
174 },
175 },
176 }),
177 );
178 return;
179 }
180 const reportFailure = async (
181 title: string,
182 run: () => Promise<AtomCommandResult<unknown, unknown>>,
183 ) => {
184 const result = await run();
185 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
186 failureToast(title, squashAtomCommandFailure(result));
187 }
188 };
189 switch (action) {
190 case "new-thread-on-branch": {
191 // Explicit branch carry-over: reuse the thread's worktree when it
192 // has one, otherwise its branch on the local checkout.
193 const result = await settlePromise(() =>
194 handleNewThread(scopeProjectRef(threadRef.environmentId, thread.projectId), {
195 branch: thread.branch,
196 worktreePath: thread.worktreePath,
197 envMode: thread.worktreePath ? "worktree" : "local",
198 startFromOrigin: false,
199 }),
200 );
201 if (result._tag === "Failure") {
202 failureToast("Could not create thread", squashAtomCommandFailure(result));
203 }
204 return;
205 }
206 case "settle":
207 await reportFailure("Failed to settle thread", () => settleThread(threadRef));
208 return;
209 case "unsettle":
210 await reportFailure("Failed to un-settle thread", () => unsettleThread(threadRef));
211 return;
212 case "unsnooze":
213 await reportFailure("Failed to wake thread", () => unsnoozeThread(threadRef));
214 return;
215 case "pin":
216 await reportFailure("Failed to pin thread", () => pinThread(threadRef));
217 return;
218 case "unpin":
219 await reportFailure("Failed to unpin thread", () => unpinThread(threadRef));
220 return;
221 case "rename":
222 onStartRename();
223 return;
224 case "regenerate-title":
225 if (isRegeneratingTitle) return;
226 await reportFailure("Failed to regenerate thread title", () =>
227 updateThreadMetadata({
228 environmentId: threadRef.environmentId,
229 input: { threadId: threadRef.threadId, regenerateTitle: true },
230 }),
231 );
232 return;
233 case "mark-unread":
234 markThreadUnread(scopedThreadKey(threadRef), thread.latestTurn?.completedAt);
235 return;
236 case "copy-path": {
237 const workspacePath = thread.worktreePath ?? projectCwd;
238 if (!workspacePath) {
239 toastManager.add(
240 stackedThreadToast({
241 type: "error",
242 title: "Path unavailable",
243 description: "This thread does not have a workspace path to copy.",
244 }),
245 );
246 return;
247 }
248 copyPathToClipboard(workspacePath, { path: workspacePath });
249 return;
250 }
251 case "copy-branch":
252 if (thread.branch) {
253 copyBranchToClipboard(thread.branch, { branch: thread.branch });
254 }
255 return;
256 case "copy-thread-id":
257 copyThreadIdToClipboard(thread.id, { threadId: thread.id });
258 return;
259 case "archive": {
260 if (confirmThreadArchive) {
261 const confirmed = await settlePromise(() =>
262 api.dialogs.confirm(`Archive thread "${thread.title}"?`),
263 );
264 if (confirmed._tag === "Failure" || !confirmed.value) return;
265 }
266 let didArchive = false;
267 const result = await archiveThread(threadRef, {
268 onArchived: () => {
269 didArchive = true;
270 },
271 });
272 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
273 failureToast(
274 didArchive ? "Thread archived, but navigation failed" : "Failed to archive thread",
275 squashAtomCommandFailure(result),
276 );
277 }
278 return;
279 }
280 case "delete": {
281 if (confirmThreadDelete) {
282 const confirmed = await settlePromise(() =>
283 api.dialogs.confirm(
284 [
285 `Delete thread "${thread.title}"?`,
286 "This permanently clears conversation history for this thread.",
287 ].join("\n"),
288 { variant: "destructive" },
289 ),
290 );
291 if (confirmed._tag === "Failure" || !confirmed.value) return;
292 }
293 const deleted = await deleteThread(threadRef);
294 if (
295 deleted._tag === "Failure" &&
296 !isAtomCommandInterrupted(deleted) &&
297 // A failure with the thread already gone is worktree cleanup
298 // failing after a successful delete — deleteThread has toasted
299 // that itself, and "Failed to delete thread" would be a lie.
300 readThreadShell(threadRef) !== null
301 ) {
302 failureToast("Failed to delete thread", squashAtomCommandFailure(deleted));
303 }
304 return;
305 }
306 default:
307 return;
308 }
309 })();
310 },
311 [
312 archiveThread,
313 autoSettleAfterDays,
314 autoSettleOnMerge,
315 changeRequestState,
316 confirmThreadArchive,
317 confirmThreadDelete,
318 copyBranchToClipboard,
319 copyPathToClipboard,
320 copyThreadIdToClipboard,
321 deleteThread,
322 handleNewThread,
323 markThreadUnread,
324 onStartRename,
325 pinThread,
326 projectCwd,
327 settleThread,
328 snoozeThread,
329 threadRef,
330 timestampFormat,
331 unpinThread,
332 unsettleThread,
333 unsnoozeThread,
334 updateThreadMetadata,
335 ],
336 );
337​
338 return { openMenu };