Repository navigation
Expand file tree
/
Copy pathTranscriptExportDialog.tsx
More file actions
320 lines (303 loc) · 11.8 KB
/
Copy pathTranscriptExportDialog.tsx
File metadata and controls
320 lines (303 loc) · 11.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
import { useAtomValue } from "@effect/atom-react";
import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime/environment";
import { loadFullThreadSnapshot } from "@t3tools/client-runtime/state/threads";
import type {
OrchestrationV2ThreadProjection,
ScopedThreadRef,
ThreadId,
} from "@t3tools/contracts";
import { CopyIcon, DownloadIcon } from "lucide-react";
import { Atom } from "effect/reactivity";
import { useEffect, useRef, useState } from "react";
import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
import { runtime } from "~/lib/runtime";
import { saveMarkdownFile, showSavedFileInFolder } from "~/lib/saveTextFile";
import {
buildThreadTranscript,
transcriptFileName,
type TranscriptDetail,
} from "~/lib/threadTranscript";
import { isMacPlatform, isWindowsPlatform } from "~/lib/utils";
import { appAtomRegistry } from "~/rpc/atomRegistry";
import { useProject } from "~/state/entities";
import { readPreparedConnection } from "~/state/session";
import { useThreadTabGroup } from "./chat/ThreadTabs";
import { Button } from "./ui/button";
import {
Dialog,
DialogDescription,
DialogFooter,
DialogHeader,
DialogPanel,
DialogPopup,
DialogTitle,
} from "./ui/dialog";
import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "./ui/select";
import { Spinner } from "./ui/spinner";
import { Switch } from "./ui/switch";
import { toastManager } from "./ui/toast";
import { Toggle, ToggleGroup } from "./ui/toggle-group";
/** Long threads export in full; the preview only needs to show the shape. */
const PREVIEW_MAX_CHARS = 20_000;
const transcriptExportThreadAtom = Atom.make<ScopedThreadRef | null>(null).pipe(
Atom.keepAlive,
Atom.withLabel("transcript-export:thread"),
);
/** Opens the export dialog for a thread, from any menu, palette, or tab. */
export function openTranscriptExportDialog(threadRef: ScopedThreadRef): void {
appAtomRegistry.set(transcriptExportThreadAtom, threadRef);
}
function closeTranscriptExportDialog() {
appAtomRegistry.set(transcriptExportThreadAtom, null);
}
// The last choices, so repeat exports skip the setup.
let lastOptions: { detail: TranscriptDetail; includeHeader: boolean } = {
detail: "concise",
includeHeader: true,
};
export function TranscriptExportDialogHost() {
const threadRef = useAtomValue(transcriptExportThreadAtom);
if (threadRef === null) return null;
return (
<TranscriptExportDialog
key={`${threadRef.environmentId}:${threadRef.threadId}`}
threadRef={threadRef}
/>
);
}
type LoadState =
| { readonly status: "loading" }
| { readonly status: "ready"; readonly projection: OrchestrationV2ThreadProjection }
| { readonly status: "failed"; readonly message: string };
/** Full snapshots by thread, loaded on first view so switching tabs back is instant. */
function useFullThread(threadRef: ScopedThreadRef): LoadState {
const [loaded, setLoaded] = useState<ReadonlyMap<ThreadId, LoadState>>(() => new Map());
const requested = useRef(new Set<ThreadId>());
const connected = readPreparedConnection(threadRef.environmentId) !== null;
useEffect(() => {
const prepared = readPreparedConnection(threadRef.environmentId);
const { threadId } = threadRef;
if (prepared === null || requested.current.has(threadId)) return;
requested.current.add(threadId);
const settle = (state: LoadState) =>
setLoaded((previous) => new Map(previous).set(threadId, state));
void runtime.runPromise(loadFullThreadSnapshot(prepared, threadId)).then(
(snapshot) => settle({ status: "ready", projection: snapshot.projection }),
(error: unknown) =>
settle({
status: "failed",
message: error instanceof Error ? error.message : "Could not load this thread.",
}),
);
}, [threadRef]);
if (!connected) {
return { status: "failed", message: "This thread's environment is not connected." };
}
return loaded.get(threadRef.threadId) ?? { status: "loading" };
}
function revealLabel(): string {
if (isMacPlatform(navigator.platform)) return "Reveal in Finder";
if (isWindowsPlatform(navigator.platform)) return "Reveal in File Explorer";
return "Reveal in Files";
}
function formatTokenEstimate(characters: number): string {
// ~4 characters per token is close enough to size a paste.
const tokens = Math.round(characters / 4);
return tokens < 1000 ? `~${tokens} tokens` : `~${(tokens / 1000).toFixed(1)}k tokens`;
}
function TranscriptExportDialog({ threadRef: openedRef }: { threadRef: ScopedThreadRef }) {
const { environmentId } = openedRef;
// A thread with sibling chat tabs can export any of them; it starts on the one it was opened from.
const tabGroup = useThreadTabGroup(environmentId, openedRef.threadId);
const tabs = tabGroup && tabGroup.tabs.length > 1 ? tabGroup.tabs : null;
const [selectedThreadId, setSelectedThreadId] = useState(openedRef.threadId);
const threadRef = scopeThreadRef(environmentId, selectedThreadId);
const load = useFullThread(threadRef);
const projection = load.status === "ready" ? load.projection : null;
const thread = projection?.thread ?? null;
const project = useProject(
thread ? scopeProjectRef(threadRef.environmentId, thread.projectId) : null,
);
const [detail, setDetail] = useState(lastOptions.detail);
const [includeHeader, setIncludeHeader] = useState(lastOptions.includeHeader);
const [saving, setSaving] = useState(false);
useEffect(() => {
lastOptions = { detail, includeHeader };
}, [detail, includeHeader]);
const transcript = projection
? buildThreadTranscript({
projection,
projectTitle: project?.title ?? null,
detail,
includeHeader,
exportedAt: new Date(),
})
: null;
const title =
thread?.title ?? tabs?.find((tab) => tab.threadId === selectedThreadId)?.title ?? null;
const fileName = thread ? transcriptFileName(thread.title) : null;
const { copyToClipboard } = useCopyToClipboard({
target: "transcript",
onCopy: () => {
closeTranscriptExportDialog();
toastManager.add({ type: "success", title: "Transcript copied" });
},
onError: (error) => {
toastManager.add({
type: "error",
title: "Could not copy transcript",
description: error.message,
});
},
});
const save = async () => {
if (!transcript || !fileName || saving) return;
setSaving(true);
try {
const saved = await saveMarkdownFile(fileName, transcript.markdown);
if (saved !== null) {
closeTranscriptExportDialog();
toastManager.add(
saved.kind === "path"
? {
type: "success",
title: "Transcript saved",
description: saved.path,
actionProps: {
children: revealLabel(),
onClick: () => showSavedFileInFolder(saved.path),
},
}
: { type: "success", title: "Transcript saved", description: saved.fileName },
);
}
} catch (error) {
toastManager.add({
type: "error",
title: "Could not save transcript",
description: error instanceof Error ? error.message : "An error occurred.",
});
}
setSaving(false);
};
const stats = transcript
? [
`${transcript.messageCount} ${transcript.messageCount === 1 ? "message" : "messages"}`,
...(detail === "full"
? [
`${transcript.toolCallCount} ${transcript.toolCallCount === 1 ? "tool call" : "tool calls"}`,
]
: []),
formatTokenEstimate(transcript.markdown.length),
].join(" · ")
: null;
const preview =
transcript && transcript.markdown.length > PREVIEW_MAX_CHARS
? `${transcript.markdown.slice(0, PREVIEW_MAX_CHARS)}…`
: transcript?.markdown;
return (
<Dialog
open
onOpenChange={(open) => {
if (!open) closeTranscriptExportDialog();
}}
>
<DialogPopup className="sm:max-w-2xl">
<form
className="flex min-h-0 flex-col"
onSubmit={(event) => {
event.preventDefault();
void save();
}}
>
<DialogHeader>
<DialogTitle>Export transcript</DialogTitle>
<DialogDescription>
<span className="block truncate">
{[title, project?.title].filter(Boolean).join(" · ") || "Loading thread…"}
</span>
</DialogDescription>
</DialogHeader>
<DialogPanel>
<div className="overflow-hidden rounded-xl border bg-background">
<div className="flex items-center gap-3 border-b p-2">
{tabs ? (
<Select
value={selectedThreadId}
items={Object.fromEntries(tabs.map((tab) => [tab.threadId, tab.title]))}
onValueChange={(value) => {
const tab = tabs.find((candidate) => candidate.threadId === value);
if (tab) setSelectedThreadId(tab.threadId);
}}
>
<SelectTrigger
size="compact"
aria-label="Tab to export"
className="w-auto min-w-0 max-w-56"
>
<span className="min-w-0 truncate">
<SelectValue />
</span>
</SelectTrigger>
<SelectPopup>
{tabs.map((tab) => (
<SelectItem key={tab.threadId} value={tab.threadId}>
{tab.title}
</SelectItem>
))}
</SelectPopup>
</Select>
) : null}
<ToggleGroup
aria-label="Transcript detail"
value={[detail]}
onValueChange={(next) => {
const value = next[0];
if (value === "concise" || value === "full") setDetail(value);
}}
>
<Toggle value="concise">Concise</Toggle>
<Toggle value="full">Full</Toggle>
</ToggleGroup>
<label className="ms-auto flex cursor-pointer items-center gap-2 px-1 text-muted-foreground text-xs">
Header
<Switch size="sm" checked={includeHeader} onCheckedChange={setIncludeHeader} />
</label>
</div>
{load.status === "ready" ? (
<pre className="h-72 overflow-auto whitespace-pre-wrap break-words px-4 py-3 font-mono text-foreground/80 text-xs leading-relaxed">
{preview}
</pre>
) : (
<div className="flex h-72 items-center justify-center px-6 text-center text-muted-foreground text-sm">
{load.status === "loading" ? <Spinner size="md" tone="muted" /> : load.message}
</div>
)}
<div className="flex items-center gap-3 border-t px-3 py-2 text-muted-foreground text-xs">
<span className="min-w-0 truncate font-mono">{fileName}</span>
<span className="ms-auto shrink-0">{stats}</span>
</div>
</div>
</DialogPanel>
<DialogFooter variant="bare">
<Button
type="button"
variant="outline"
disabled={!transcript}
onClick={() => {
if (transcript) copyToClipboard(transcript.markdown, undefined);
}}
>
<CopyIcon />
Copy
</Button>
<Button type="submit" disabled={!transcript || saving}>
<DownloadIcon />
Save…
</Button>
</DialogFooter>
</form>
</DialogPopup>
</Dialog>
);
}