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

useThreadActionMenu.ts

362 lines14.1 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 readEnvironmentSupportsAutoSettleOptOut,
24 readEnvironmentSupportsPinning,
25 readEnvironmentSupportsSettlement,
26 readEnvironmentSupportsSnooze,
27 readEnvironmentSupportsTitleRegeneration,
28 readThreadShell,
29 useProjects,
30} from "../state/entities";
31import { usePrimaryEnvironmentId } from "../state/environments";
32import { readLocalApi } from "../localApi";
33import {
34 deriveLogicalProjectKeyFromSettings,
35 derivePhysicalProjectKey,
36 selectProjectGroupingSettings,
37} from "../logicalProject";
38import { buildPhysicalToLogicalProjectKeyMap } from "../sidebarProjectGrouping";
39import { useUiStateStore } from "../uiStateStore";
40import { useCopyToClipboard } from "./useCopyToClipboard";
41import { useNewThreadHandler } from "./useHandleNewThread";
42import { useClientSettings } from "./useSettings";
43import { useThreadActions } from "./useThreadActions";
44​
45function failureToast(title: string, error: unknown) {
46 toastManager.add(
47 stackedThreadToast({
48 type: "error",
49 title,
50 description: error instanceof Error ? error.message : "An error occurred.",
51 }),
52 );
54​
55/**
56 * The per-thread action menu (pin, settle, snooze, rename, copy, delete…) as
57 * a self-contained hook, for surfaces other than the sidebar row — today the
58 * chat header. Renders through the native context-menu bridge and dispatches
59 * through the same mutations the sidebar uses.
60 *
61 * Unlike the sidebar, settle and snooze here never navigate away: the caller
62 * is acting on the thread they are reading, and ChatView's parked-thread
63 * banner already offers the way back.
64 */
65export function useThreadActionMenu(input: {
66 readonly threadRef: ScopedThreadRef | null;
67 /** Fallback for "Copy path" when the thread has no worktree. */
68 readonly projectCwd: string | null;
69 readonly onStartRename: () => void;
70}) {
71 const { threadRef, projectCwd, onStartRename } = input;
72 const router = useRouter();
73 const projects = useProjects();
74 const primaryEnvironmentId = usePrimaryEnvironmentId();
75 const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);
76 const logicalProjectKeyByPhysicalKey = useMemo(
77 () =>
78 buildPhysicalToLogicalProjectKeyMap({
79 projects,
80 settings: projectGroupingSettings,
81 primaryEnvironmentId,
82 }),
83 [primaryEnvironmentId, projectGroupingSettings, projects],
84 );
85 const {
86 settleThread,
87 unsettleThread,
88 snoozeThread,
89 unsnoozeThread,
90 pinThread,
91 confirmAndUnpinThread,
92 setThreadAutoSettle,
93 archiveThread,
94 deleteThread,
95 } = useThreadActions();
96 const updateThreadMetadata = useAtomCommand(threadEnvironment.updateMetadata, {
97 reportFailure: false,
98 });
99 const handleNewThread = useNewThreadHandler();
100 const markThreadUnread = useUiStateStore((s) => s.markThreadUnread);
101 const confirmThreadDelete = useClientSettings((s) => s.confirmThreadDelete);
102 const confirmThreadArchive = useClientSettings((s) => s.confirmThreadArchive);
103 const timestampFormat = useClientSettings((s) => s.timestampFormat);
104 const { copyToClipboard: copyPathToClipboard } = useCopyToClipboard<{ path: string }>({
105 onCopy: ({ path }) => {
106 toastManager.add({ type: "success", title: "Path copied", description: path });
107 },
108 onError: (error) => failureToast("Failed to copy path", error),
109 });
110 const { copyToClipboard: copyBranchToClipboard } = useCopyToClipboard<{ branch: string }>({
111 target: "branch name",
112 onCopy: ({ branch }) => {
113 toastManager.add({ type: "success", title: "Branch copied", description: branch });
114 },
115 onError: (error) => failureToast("Failed to copy branch", error),
116 });
117 const { copyToClipboard: copyThreadIdToClipboard } = useCopyToClipboard<{ threadId: ThreadId }>({
118 onCopy: ({ threadId }) => {
119 toastManager.add({ type: "success", title: "Thread ID copied", description: threadId });
120 },
121 onError: (error) => failureToast("Failed to copy thread ID", error),
122 });
123​
124 const openMenu = useCallback(
125 (position: { x: number; y: number }) => {
126 if (threadRef === null) return;
127 void (async () => {
128 const api = readLocalApi();
129 if (!api) return;
130 // Snapshot at open time — the menu is modal, so state read now is
131 // what the user is looking at.
132 const thread = readThreadShell(threadRef);
133 if (!thread) return;
134 const now = new Date();
135 const supports = {
136 settlement: readEnvironmentSupportsSettlement(threadRef.environmentId),
137 autoSettleOptOut: readEnvironmentSupportsAutoSettleOptOut(threadRef.environmentId),
138 snooze: readEnvironmentSupportsSnooze(threadRef.environmentId),
139 pinning: readEnvironmentSupportsPinning(threadRef.environmentId),
140 titleRegeneration: readEnvironmentSupportsTitleRegeneration(threadRef.environmentId),
141 };
142 const isRegeneratingTitle = thread.titleRegeneration != null;
143 const snoozePresets = resolveSnoozePresets(now, timestampFormat);
144 const items = buildThreadActionMenuItems({
145 branch: thread.branch ?? null,
146 // The chat header has no project-scoped thread list behind the
147 // menu, so the "Filter by project" affordance is sidebar-only.
148 projectFilter: null,
149 isPinned: thread.pinnedAt != null,
150 isSettled: supports.settlement && thread.settledOverride === "settled",
151 autoSettleEnabled: thread.autoSettleDisabledAt == null,
152 isSnoozed: supports.snooze && effectiveSnoozed(thread, { now: now.toISOString() }),
153 canSnoozeNow: canSnooze(thread, { now: now.toISOString() }),
154 isRegeneratingTitle,
155 isRunning: thread.session?.status === "running" && thread.session.activeTurnId != null,
156 supports,
157 snoozePresets,
158 });
159 const clicked = await settlePromise(() => api.contextMenu.show(items, position));
160 if (clicked._tag === "Failure" || clicked.value === null) return;
161 const action: ThreadActionMenuId = clicked.value;
162 if (action.startsWith("snooze:")) {
163 const preset =
164 action === "snooze:custom"
165 ? await requestCustomSnooze()
166 : snoozePresets.find((candidate) => `snooze:${candidate.id}` === action);
167 if (!preset) return;
168 const result = await snoozeThread(threadRef, preset.snoozedUntil);
169 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
170 failureToast("Failed to snooze thread", squashAtomCommandFailure(result));
171 }
172 return;
173 }
174 const reportFailure = async (
175 title: string,
176 run: () => Promise<AtomCommandResult<unknown, unknown>>,
177 ) => {
178 const result = await run();
179 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
180 failureToast(title, squashAtomCommandFailure(result));
181 }
182 };
183 switch (action) {
184 case "project-settings": {
185 const project = projects.find(
186 (candidate) =>
187 candidate.environmentId === thread.environmentId &&
188 candidate.id === thread.projectId,
189 );
190 if (!project) return;
191 const projectKey =
192 logicalProjectKeyByPhysicalKey.get(derivePhysicalProjectKey(project)) ??
193 deriveLogicalProjectKeyFromSettings(project, projectGroupingSettings);
194 void router.navigate({
195 to: "/projects/$projectKey",
196 params: { projectKey },
197 });
198 return;
199 }
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", () => confirmAndUnpinThread(threadRef));
230 return;
231 }
232 case "auto-settle:enabled":
233 case "auto-settle:disabled":
234 await reportFailure("Failed to update auto-settle", () =>
235 setThreadAutoSettle(threadRef, action === "auto-settle:enabled"),
236 );
237 return;
238 case "rename":
239 onStartRename();
240 return;
241 case "regenerate-title":
242 if (isRegeneratingTitle) return;
243 await reportFailure("Failed to regenerate thread title", () =>
244 updateThreadMetadata({
245 environmentId: threadRef.environmentId,
246 input: { threadId: threadRef.threadId, regenerateTitle: true },
247 }),
248 );
249 return;
250 case "mark-unread":
251 markThreadUnread(scopedThreadKey(threadRef), thread.latestTurn?.completedAt);
252 return;
253 case "copy-path": {
254 const workspacePath = thread.worktreePath ?? projectCwd;
255 if (!workspacePath) {
256 toastManager.add(
257 stackedThreadToast({
258 type: "error",
259 title: "Path unavailable",
260 description: "This thread does not have a workspace path to copy.",
261 }),
262 );
263 return;
264 }
265 copyPathToClipboard(workspacePath, { path: workspacePath });
266 return;
267 }
268 case "copy-branch":
269 if (thread.branch) {
270 copyBranchToClipboard(thread.branch, { branch: thread.branch });
271 }
272 return;
273 case "copy-thread-id":
274 copyThreadIdToClipboard(thread.id, { threadId: thread.id });
275 return;
276 case "archive": {
277 if (confirmThreadArchive) {
278 const confirmed = await settlePromise(() =>
279 api.dialogs.confirm(`Archive thread "${thread.title}"?`),
280 );
281 if (confirmed._tag === "Failure" || !confirmed.value) return;
282 }
283 let didArchive = false;
284 const result = await archiveThread(threadRef, {
285 onArchived: () => {
286 didArchive = true;
287 },
288 });
289 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
290 failureToast(
291 didArchive ? "Thread archived, but navigation failed" : "Failed to archive thread",
292 squashAtomCommandFailure(result),
293 );
294 }
295 return;
296 }
297 case "delete": {
298 if (confirmThreadDelete) {
299 const confirmed = await settlePromise(() =>
300 api.dialogs.confirm(
301 [
302 `Delete thread "${thread.title}"?`,
303 "This permanently clears conversation history for this thread.",
304 ].join("\n"),
305 { variant: "destructive" },
306 ),
307 );
308 if (confirmed._tag === "Failure" || !confirmed.value) return;
309 }
310 const deleted = await deleteThread(threadRef);
311 if (
312 deleted._tag === "Failure" &&
313 !isAtomCommandInterrupted(deleted) &&
314 // A failure with the thread already gone is worktree cleanup
315 // failing after a successful delete — deleteThread has toasted
316 // that itself, and "Failed to delete thread" would be a lie.
317 readThreadShell(threadRef) !== null
318 ) {
319 failureToast("Failed to delete thread", squashAtomCommandFailure(deleted));
320 }
321 return;
322 }
323 default:
324 return;
325 }
326 })();
327 },
328 [
329 archiveThread,
330 confirmThreadArchive,
331 confirmThreadDelete,
332 confirmAndUnpinThread,
333 copyBranchToClipboard,
334 copyPathToClipboard,
335 copyThreadIdToClipboard,
336 deleteThread,
337 handleNewThread,
338 logicalProjectKeyByPhysicalKey,
339 markThreadUnread,
340 onStartRename,
341 pinThread,
342 projectCwd,
343 projectGroupingSettings,
344 projects,
345 router,
346 setThreadAutoSettle,
347 settleThread,
348 snoozeThread,
349 threadRef,
350 timestampFormat,
351 unsettleThread,
352 unsnoozeThread,
353 updateThreadMetadata,
354 ],
355 );
356​
357 const closeMenu = useCallback(() => {
358 void readLocalApi()?.contextMenu.close();
359 }, []);
360​
361 return { openMenu, closeMenu };