-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathcontent.js
More file actions
343 lines (288 loc) · 11.5 KB
/
Copy pathcontent.js
File metadata and controls
343 lines (288 loc) · 11.5 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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
// Note: Organization ID is now stored in extension settings
// Users need to configure it in the extension options page
// Default model timeline for null models
const DEFAULT_MODEL_TIMELINE = [
{ date: new Date('2024-01-01'), model: 'claude-3-sonnet-20240229' }, // Before June 20, 2024
{ date: new Date('2024-06-20'), model: 'claude-3-5-sonnet-20240620' }, // Starting June 20, 2024
{ date: new Date('2024-10-22'), model: 'claude-3-5-sonnet-20241022' }, // Starting October 22, 2024
{ date: new Date('2025-02-29'), model: 'claude-3-7-sonnet-20250219' }, // Starting February 29, 2025
{ date: new Date('2025-05-14'), model: 'claude-sonnet-4-20250514' }, // Starting May 14, 2025
{ date: new Date('2025-09-29'), model: 'claude-sonnet-4-5-20250929' }, // Starting September 29, 2025
{ date: new Date('2026-02-17'), model: 'claude-sonnet-4-6' } // Starting February 17, 2026
];
// Infer model for conversations with null model based on date
function inferModel(conversation) {
if (conversation.model) {
return conversation.model;
}
// Use created_at date to determine which default model was active
const conversationDate = new Date(conversation.created_at);
// Find the appropriate model based on the conversation date
// Start from the end and work backwards to find the right period
for (let i = DEFAULT_MODEL_TIMELINE.length - 1; i >= 0; i--) {
if (conversationDate >= DEFAULT_MODEL_TIMELINE[i].date) {
return DEFAULT_MODEL_TIMELINE[i].model;
}
}
// If date is before all known dates, use the first model
return DEFAULT_MODEL_TIMELINE[0].model;
}
// Fetch conversation data
async function fetchConversation(orgId, conversationId) {
const url = `https://claude.ai/api/organizations/${orgId}/chat_conversations/${conversationId}?tree=True&rendering_mode=messages&render_all_tools=true`;
const response = await fetch(url, {
credentials: 'include',
headers: {
'Accept': 'application/json',
}
});
if (!response.ok) {
throw new Error(`Failed to fetch conversation: ${response.status}`);
}
return await response.json();
}
// Fetch all conversations
async function fetchAllConversations(orgId) {
const url = `https://claude.ai/api/organizations/${orgId}/chat_conversations`;
const response = await fetch(url, {
credentials: 'include',
headers: {
'Accept': 'application/json',
}
});
if (!response.ok) {
throw new Error(`Failed to fetch conversations: ${response.status}`);
}
return await response.json();
}
// Helper function to reconstruct the current branch from the message tree
function getCurrentBranch(data) {
if (!data.chat_messages || !data.current_leaf_message_uuid) {
return [];
}
// Create a map of UUID to message for quick lookup
const messageMap = new Map();
data.chat_messages.forEach(msg => {
messageMap.set(msg.uuid, msg);
});
// Trace back from the current leaf to the root
const branch = [];
let currentUuid = data.current_leaf_message_uuid;
while (currentUuid && messageMap.has(currentUuid)) {
const message = messageMap.get(currentUuid);
branch.unshift(message); // Add to beginning to maintain order
currentUuid = message.parent_message_uuid;
// Stop if we hit the root (parent UUID that doesn't exist in our messages)
if (!messageMap.has(currentUuid)) {
break;
}
}
return branch;
}
// Convert to markdown format
function convertToMarkdown(data, includeMetadata) {
let markdown = `# ${data.name || 'Untitled Conversation'}\n\n`;
if (includeMetadata) {
markdown += `**Created:** ${new Date(data.created_at).toLocaleString()}\n`;
markdown += `**Updated:** ${new Date(data.updated_at).toLocaleString()}\n`;
markdown += `**Model:** ${data.model}\n`;
if (data.truncated !== undefined) {
markdown += `**Truncated:** ${data.truncated}\n`;
}
markdown += '\n---\n\n';
}
// Get only the current branch messages
const branchMessages = getCurrentBranch(data);
for (const message of branchMessages) {
const sender = message.sender === 'human' ? '**You**' : '**Claude**';
markdown += `${sender}:\n\n`;
// Show attachments if metadata enabled
if (includeMetadata && message.attachments && message.attachments.length > 0) {
for (const attachment of message.attachments) {
markdown += `> **Attachment:** ${attachment.file_name || '(unnamed)'}`;
if (attachment.file_size) {
const sizeKB = (attachment.file_size / 1024).toFixed(1);
markdown += ` (${sizeKB} KB)`;
}
if (attachment.file_type) {
markdown += ` [${attachment.file_type}]`;
}
markdown += '\n';
if (attachment.extracted_content) {
markdown += `>\n> <details><summary>Extracted content</summary>\n>\n> \`\`\`\n> ${attachment.extracted_content.replace(/\n/g, '\n> ')}\n> \`\`\`\n>\n> </details>\n`;
}
}
markdown += '\n';
}
if (message.content) {
for (const content of message.content) {
if (content.text) {
markdown += `${content.text}\n\n`;
}
}
} else if (message.text) {
markdown += `${message.text}\n\n`;
}
if (includeMetadata && message.created_at) {
markdown += `*${new Date(message.created_at).toLocaleString()}*\n\n`;
}
markdown += '---\n\n';
}
return markdown;
}
// Convert to plain text
function convertToText(data, includeMetadata) {
let text = '';
// Add metadata header if requested
if (includeMetadata) {
text += `${data.name || 'Untitled Conversation'}\n`;
text += `Created: ${new Date(data.created_at).toLocaleString()}\n`;
text += `Updated: ${new Date(data.updated_at).toLocaleString()}\n`;
text += `Model: ${data.model}\n\n`;
text += '---\n\n';
}
// Get only the current branch messages
const branchMessages = getCurrentBranch(data);
// Use simplified format
let humanSeen = false;
let assistantSeen = false;
branchMessages.forEach((message) => {
// Get the message text
let messageText = '';
if (message.content) {
for (const content of message.content) {
if (content.text) {
messageText += content.text;
}
}
} else if (message.text) {
messageText = message.text;
}
// Use full label on first occurrence, then abbreviate
let senderLabel;
if (message.sender === 'human') {
senderLabel = humanSeen ? 'H' : 'Human';
humanSeen = true;
} else {
senderLabel = assistantSeen ? 'A' : 'Assistant';
assistantSeen = true;
}
text += `${senderLabel}: ${messageText}\n\n`;
});
return text.trim();
}
// Download file utility
function downloadFile(content, filename, type = 'application/json') {
const blob = new Blob([content], { type });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
}
// Handle messages from popup
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.action === 'exportConversation') {
console.log('Export conversation request received:', request);
fetchConversation(request.orgId, request.conversationId)
.then(data => {
console.log('Conversation data fetched successfully:', data);
// Infer model if null
data.model = inferModel(data);
let content, filename, type;
switch (request.format) {
case 'markdown':
content = convertToMarkdown(data, request.includeMetadata);
filename = `claude-conversation-${data.name || request.conversationId}.md`;
type = 'text/markdown';
break;
case 'text':
content = convertToText(data, request.includeMetadata);
filename = `claude-conversation-${data.name || request.conversationId}.txt`;
type = 'text/plain';
break;
default:
content = JSON.stringify(data, null, 2);
filename = `claude-conversation-${data.name || request.conversationId}.json`;
type = 'application/json';
}
console.log('Downloading file:', filename);
downloadFile(content, filename, type);
sendResponse({ success: true });
})
.catch(error => {
console.error('Export conversation error:', error);
sendResponse({
success: false,
error: error.message,
details: error.stack
});
});
return true;
}
if (request.action === 'exportAllConversations') {
console.log('Export all conversations request received:', request);
fetchAllConversations(request.orgId)
.then(async conversations => {
console.log(`Fetched ${conversations.length} conversations`);
if (request.format === 'json') {
// For JSON, export as a single file with all conversations
const filename = `claude-all-conversations-${new Date().toISOString().split('T')[0]}.json`;
console.log('Downloading all conversations as JSON:', filename);
downloadFile(JSON.stringify(conversations, null, 2), filename);
sendResponse({ success: true, count: conversations.length });
} else {
// For other formats, create individual files
let count = 0;
let errors = [];
for (const conv of conversations) {
try {
console.log(`Fetching full conversation ${count + 1}/${conversations.length}: ${conv.uuid}`);
const fullConv = await fetchConversation(request.orgId, conv.uuid);
// Infer model if null
fullConv.model = inferModel(fullConv);
let content, filename, type;
if (request.format === 'markdown') {
content = convertToMarkdown(fullConv, request.includeMetadata);
filename = `claude-${conv.name || conv.uuid}.md`;
type = 'text/markdown';
} else {
content = convertToText(fullConv, request.includeMetadata);
filename = `claude-${conv.name || conv.uuid}.txt`;
type = 'text/plain';
}
downloadFile(content, filename, type);
count++;
// Add a small delay to avoid overwhelming the API
await new Promise(resolve => setTimeout(resolve, 500));
} catch (error) {
console.error(`Failed to export conversation ${conv.uuid}:`, error);
errors.push(`${conv.name || conv.uuid}: ${error.message}`);
}
}
if (errors.length > 0) {
console.warn('Some conversations failed to export:', errors);
sendResponse({
success: true,
count,
warnings: `Exported ${count}/${conversations.length} conversations. Some failed: ${errors.join('; ')}`
});
} else {
sendResponse({ success: true, count });
}
}
})
.catch(error => {
console.error('Export all conversations error:', error);
sendResponse({
success: false,
error: error.message,
details: error.stack
});
});
return true;
}
});