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

useThreadActionMenu.ts

380 lines14.4 KB

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