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

useThreadActionMenu.ts

359 lines13.6 KB

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