Open History to see the last commit
1import { scopeProjectRef } from "@t3tools/client-runtime/environment";
2import { requestCustomSnooze } from "../components/CustomSnoozeDialog";
3import { openGuestShareDialog } from "../components/chat/guestShareDialogState";
4import {
5 type AtomCommandResult,
6 isAtomCommandInterrupted,
7 settlePromise,
8 squashAtomCommandFailure,
9} from "@t3tools/client-runtime/state/runtime";
10import { canSnooze, effectiveSnoozed } from "@t3tools/client-runtime/state/thread-settled";
11import {
12 AuthOrchestrationOperateScope,
13 type ScopedThreadRef,
14 type ThreadId,
15} from "@t3tools/contracts";
16import { useRouter } from "@tanstack/react-router";
17
18import { pickSnoozePreset, resolveSnoozePresets } from "../components/Sidebar.snooze";
19import {
20 buildThreadActionMenuItems,
21 threadActionRequiresOperate,
22 type ThreadActionMenuId,
23} from "../components/threadActionMenu.logic";
24import { stackedThreadToast, toastManager } from "../components/ui/toast";
25import { copyThreadReference } from "../lib/copyThreadReference";
26import { threadChipCopyTarget } from "@t3tools/client-runtime/thread-reference";
27import { threadEnvironment } from "../state/threads";
28import { useOrchestrationCommand } from "../state/use-orchestration-command";
29import { readEnvironmentScope } from "../state/session";
30import {
31 readEnvironmentServerConfigLoaded,
32 readEnvironmentSupportsAutoSettleOptOut,
33 readThreadShell,
34 useProjects,
35} from "../state/entities";
36import { usePrimaryEnvironmentId } from "../state/environments";
37import { readLocalApi } from "../localApi";
38import { configuredHostedAppUrl } from "../hostedPairing";
39import {
40 deriveLogicalProjectKeyFromSettings,
41 derivePhysicalProjectKey,
42 selectProjectGroupingSettings,
43} from "@t3tools/client-runtime/state/project-grouping";
44import { buildPhysicalToLogicalProjectKeyMap } from "../sidebarProjectGrouping";
45import { threadRuntimeCanArchive } from "@t3tools/client-runtime/state/models";
46import { useCopyToClipboard } from "./useCopyToClipboard";
47import { useNewThreadHandler } from "./useHandleNewThread";
48import { useClientSettings } from "./useSettings";
49import { canTurnThreadIntoProject, useThreadActions } from "./useThreadActions";
50
51function failureToast(title: string, error: unknown) {
52 toastManager.add(
53 stackedThreadToast({
54 type: "error",
55 title,
56 description: error instanceof Error ? error.message : "An error occurred.",
57 }),
58 );
59}
60
61export function useThreadActionMenu(input: {
62 readonly threadRef: ScopedThreadRef | null;
63 readonly projectCwd: string | null;
64 readonly onStartRename: () => void;
65 readonly onFind?: ((threadRef: ScopedThreadRef) => void) | undefined;
66 readonly canShareWithGuest: boolean;
67}) {
68 const { threadRef, projectCwd, onStartRename, onFind, canShareWithGuest } = input;
69 const router = useRouter();
70 const projects = useProjects();
71 const primaryEnvironmentId = usePrimaryEnvironmentId();
72 const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);
73 const logicalProjectKeyByPhysicalKey = buildPhysicalToLogicalProjectKeyMap({
74 projects,
75 settings: projectGroupingSettings,
76 primaryEnvironmentId,
77 });
78 const {
79 settleThread,
80 unsettleThread,
81 snoozeThread,
82 unsnoozeThread,
83 pinThread,
84 confirmAndUnpinThread,
85 setThreadAutoSettle,
86 archiveThread,
87 deleteThread,
88 markThreadUnread,
89 turnThreadIntoProject,
90 } = useThreadActions();
91 const updateThreadMetadata = useOrchestrationCommand(threadEnvironment.updateMetadata, {
92 reportFailure: false,
93 });
94 const handleNewThread = useNewThreadHandler();
95 const confirmThreadDelete = useClientSettings((s) => s.confirmThreadDelete);
96 const confirmThreadArchive = useClientSettings((s) => s.confirmThreadArchive);
97 const timestampFormat = useClientSettings((s) => s.timestampFormat);
98 const { copyToClipboard: copyPathToClipboard } = useCopyToClipboard<{ path: string }>({
99 onCopy: ({ path }) => {
100 toastManager.add({ type: "success", title: "Path copied", description: path });
101 },
102 onError: (error) => failureToast("Failed to copy path", error),
103 });
104 const { copyToClipboard: copyBranchToClipboard } = useCopyToClipboard<{ branch: string }>({
105 target: "branch name",
106 onCopy: ({ branch }) => {
107 toastManager.add({ type: "success", title: "Branch copied", description: branch });
108 },
109 onError: (error) => failureToast("Failed to copy branch", error),
110 });
111 const { copyToClipboard: copyThreadIdToClipboard } = useCopyToClipboard<{ threadId: ThreadId }>({
112 onCopy: ({ threadId }) => {
113 toastManager.add({ type: "success", title: "Thread ID copied", description: threadId });
114 },
115 onError: (error) => failureToast("Failed to copy thread ID", error),
116 });
117
118 const openMenu = (position: { x: number; y: number }) => {
119 if (threadRef === null) return;
120 void (async () => {
121 const api = readLocalApi();
122 if (!api) return;
123 const thread = readThreadShell(threadRef);
124 if (!thread) return;
125 const now = new Date();
126 const configLoaded = readEnvironmentServerConfigLoaded(threadRef.environmentId);
127 const supports = {
128 settlement: configLoaded,
129 autoSettleOptOut: readEnvironmentSupportsAutoSettleOptOut(threadRef.environmentId),
130 snooze: configLoaded,
131 pinning: configLoaded,
132 titleRegeneration: configLoaded,
133 };
134 const isRegeneratingTitle = thread.titleRegeneration != null;
135 const snoozePresets = resolveSnoozePresets(now, timestampFormat, threadRef.environmentId);
136 const items = buildThreadActionMenuItems({
137 canOperate: readEnvironmentScope(threadRef.environmentId, AuthOrchestrationOperateScope),
138 canFind: onFind !== undefined,
139 branch: thread.branch ?? null,
140 projectFilter: null,
141 isPinned: thread.pinnedAt != null,
142 isSettled: supports.settlement && thread.settledOverride === "settled",
143 autoSettleEnabled: thread.autoSettleDisabledAt == null,
144 isSnoozed: supports.snooze && effectiveSnoozed(thread, { now: now.toISOString() }),
145 canSnoozeNow: canSnooze(thread, { now: now.toISOString() }),
146 isRegeneratingTitle,
147 isRunning: !threadRuntimeCanArchive(thread.runtime),
148 supports,
149 snoozePresets,
150 canShareWithGuest,
151 canTurnIntoProject: canTurnThreadIntoProject(threadRef),
152 });
153 const clicked = await settlePromise(() => api.contextMenu.show(items, position));
154 if (clicked._tag === "Failure" || clicked.value === null) return;
155 const action: ThreadActionMenuId = clicked.value;
156 if (
157 threadActionRequiresOperate(action) &&
158 !readEnvironmentScope(threadRef.environmentId, AuthOrchestrationOperateScope)
159 ) {
160 failureToast(
161 "Thread action unavailable",
162 new Error("This connection cannot change threads."),
163 );
164 return;
165 }
166 if (action.startsWith("snooze:")) {
167 const preset =
168 action === "snooze:custom"
169 ? await requestCustomSnooze()
170 : pickSnoozePreset(
171 snoozePresets,
172 action.slice("snooze:".length),
173 timestampFormat,
174 threadRef.environmentId,
175 );
176 if (!preset) return;
177 const result = await snoozeThread(threadRef, preset.snoozedUntil);
178 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
179 failureToast("Failed to snooze thread", squashAtomCommandFailure(result));
180 }
181 return;
182 }
183 const reportFailure = async (
184 title: string,
185 run: () => Promise<AtomCommandResult<unknown, unknown>>,
186 ) => {
187 const result = await run();
188 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
189 failureToast(title, squashAtomCommandFailure(result));
190 }
191 };
192 switch (action) {
193 case "find":
194 onFind?.(threadRef);
195 return;
196 case "project-settings": {
197 const project = projects.find(
198 (candidate) =>
199 candidate.environmentId === thread.environmentId && candidate.id === thread.projectId,
200 );
201 if (!project) return;
202 const projectKey =
203 logicalProjectKeyByPhysicalKey.get(derivePhysicalProjectKey(project)) ??
204 deriveLogicalProjectKeyFromSettings(project, projectGroupingSettings);
205 void router.navigate({
206 to: "/projects/$projectKey",
207 params: { projectKey },
208 });
209 return;
210 }
211 case "new-thread-on-branch": {
212 const result = await settlePromise(() =>
213 handleNewThread(scopeProjectRef(threadRef.environmentId, thread.projectId), {
214 branch: thread.branch,
215 worktreePath: thread.worktreePath,
216 envMode: thread.worktreePath ? "worktree" : "local",
217 startFromOrigin: false,
218 }),
219 );
220 if (result._tag === "Failure") {
221 failureToast("Could not create thread", squashAtomCommandFailure(result));
222 }
223 return;
224 }
225 case "settle":
226 await reportFailure("Failed to settle thread", () => settleThread(threadRef));
227 return;
228 case "unsettle":
229 await reportFailure("Failed to un-settle thread", () => unsettleThread(threadRef));
230 return;
231 case "unsnooze":
232 await reportFailure("Failed to wake thread", () => unsnoozeThread(threadRef));
233 return;
234 case "pin":
235 await reportFailure("Failed to pin thread", () => pinThread(threadRef));
236 return;
237 case "unpin": {
238 await reportFailure("Failed to unpin thread", () => confirmAndUnpinThread(threadRef));
239 return;
240 }
241 case "auto-settle:enabled":
242 case "auto-settle:disabled":
243 await reportFailure("Failed to update auto-settle", () =>
244 setThreadAutoSettle(threadRef, action === "auto-settle:enabled"),
245 );
246 return;
247 case "rename":
248 onStartRename();
249 return;
250 case "regenerate-title":
251 if (isRegeneratingTitle) return;
252 await reportFailure("Failed to regenerate thread title", () =>
253 updateThreadMetadata({
254 environmentId: threadRef.environmentId,
255 input: { threadId: threadRef.threadId, regenerateTitle: true },
256 }),
257 );
258 return;
259 case "mark-unread":
260 markThreadUnread(threadRef);
261 return;
262 case "share-guest":
263 openGuestShareDialog(threadRef);
264 return;
265 case "turn-into-project": {
266 const result = await turnThreadIntoProject(threadRef);
267 if (result._tag === "Success") {
268 toastManager.add({
269 type: "success",
270 title: "Project created",
271 description: thread.title,
272 });
273 } else if (!isAtomCommandInterrupted(result)) {
274 failureToast("Could not turn thread into a project", squashAtomCommandFailure(result));
275 }
276 return;
277 }
278 case "copy-path": {
279 const workspacePath = thread.worktreePath ?? projectCwd;
280 if (!workspacePath) {
281 toastManager.add(
282 stackedThreadToast({
283 type: "error",
284 title: "Path unavailable",
285 description: "This thread does not have a workspace path to copy.",
286 }),
287 );
288 return;
289 }
290 copyPathToClipboard(workspacePath, { path: workspacePath });
291 return;
292 }
293 case "copy-branch":
294 if (thread.branch) {
295 copyBranchToClipboard(thread.branch, { branch: thread.branch });
296 }
297 return;
298 case "copy-thread":
299 void copyThreadReference(
300 threadChipCopyTarget(threadRef, thread.title, configuredHostedAppUrl()),
301 );
302 return;
303 case "copy-thread-id":
304 copyThreadIdToClipboard(thread.id, { threadId: thread.id });
305 return;
306 case "archive": {
307 if (confirmThreadArchive) {
308 const confirmed = await settlePromise(() =>
309 api.dialogs.confirm(`Archive thread "${thread.title}"?`),
310 );
311 if (confirmed._tag === "Failure" || !confirmed.value) return;
312 }
313 let didArchive = false;
314 const result = await archiveThread(threadRef, {
315 onArchived: () => {
316 didArchive = true;
317 },
318 });
319 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
320 failureToast(
321 didArchive ? "Thread archived, but navigation failed" : "Failed to archive thread",
322 squashAtomCommandFailure(result),
323 );
324 }
325 return;
326 }
327 case "delete": {
328 if (confirmThreadDelete) {
329 const confirmed = await settlePromise(() =>
330 api.dialogs.confirm(
331 [
332 `Delete thread "${thread.title}"?`,
333 "This permanently clears conversation history for this thread.",
334 ].join("\n"),
335 { variant: "destructive" },
336 ),
337 );
338 if (confirmed._tag === "Failure" || !confirmed.value) return;
339 }
340 const deleted = await deleteThread(threadRef);
341 if (
342 deleted._tag === "Failure" &&
343 !isAtomCommandInterrupted(deleted) &&
344 // A missing thread means cleanup failed after deletion; deleteThread already toasted that failure.
345 readThreadShell(threadRef) !== null
346 ) {
347 failureToast("Failed to delete thread", squashAtomCommandFailure(deleted));
348 }
349 return;
350 }
351 default:
352 return;
353 }
354 })();
355 };
356
357 const closeMenu = () => {
358 void readLocalApi()?.contextMenu.close();
359 };
360
361 return { openMenu, closeMenu };
362}