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

useThreadActionMenu.ts

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