Repository navigation
Expand file tree
/
Copy pathbackground.js
More file actions
451 lines (378 loc) · 13.2 KB
/
Copy pathbackground.js
File metadata and controls
451 lines (378 loc) · 13.2 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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
// background.js - Service worker
import { formatTimeRange, groupByTimeline, getGroupColor } from './timeline-utils.js';
// Timeline tracking: store tab creation times (for tabs that haven't been activated yet)
const tabTimeline = new Map(); // tabId -> { createdAt, url, windowId, title }
let timelineLoaded = false;
// Load timeline data from storage on startup
async function loadTimelineFromStorage() {
if (timelineLoaded) return;
try {
const result = await chrome.storage.local.get('tabTimeline');
if (result.tabTimeline) {
const entries = Object.entries(result.tabTimeline);
for (const [tabId, data] of entries) {
tabTimeline.set(parseInt(tabId), data);
}
console.log(`Loaded ${tabTimeline.size} timeline entries from storage`);
}
} catch (error) {
console.error('Failed to load timeline from storage:', error);
}
timelineLoaded = true;
}
// Save timeline data to storage
async function saveTimelineToStorage() {
try {
const obj = {};
for (const [tabId, data] of tabTimeline) {
obj[tabId] = data;
}
await chrome.storage.local.set({ tabTimeline: obj });
} catch (error) {
console.error('Failed to save timeline to storage:', error);
}
}
// Initialize on startup
loadTimelineFromStorage();
// Get tab creation time using native API (Chrome 121+) or fallback
function getTabCreatedAt(tab) {
// Chrome 121+ provides lastAccessed (last time tab became active)
// For a newly created tab that was immediately active, this ≈ creation time
if (tab.lastAccessed && tab.lastAccessed > 0) {
return tab.lastAccessed;
}
// Fallback: check our manual tracking
const entry = tabTimeline.get(tab.id);
if (entry && entry.createdAt) {
return entry.createdAt;
}
// Last resort: use current time
return Date.now();
}
// Handle messages from popup
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
console.log('Received message:', message.action);
(async () => {
try {
await loadTimelineFromStorage();
if (message.action === 'groupAll') {
await groupAllWindows();
sendResponse({ success: true });
} else if (message.action === 'groupCurrentWindow') {
await groupCurrentWindow();
sendResponse({ success: true });
} else if (message.action === 'groupTimeline') {
await groupByTimelineAction(message.windowId === 'all' ? null : message.windowId);
sendResponse({ success: true });
} else if (message.action === 'ungroupAll') {
await ungroupAll();
sendResponse({ success: true });
} else if (message.action === 'debugTimeline') {
const tabs = await chrome.tabs.query({});
const data = tabs.map(t => ({
id: t.id,
url: t.url,
lastAccessed: t.lastAccessed,
lastAccessedStr: t.lastAccessed ? new Date(t.lastAccessed).toLocaleString() : 'N/A',
tracked: tabTimeline.get(t.id)?.createdAt
}));
sendResponse({ success: true, tabs: data, tracked: tabTimeline.size });
} else {
sendResponse({ success: false, error: 'Unknown action' });
}
} catch (error) {
console.error('Action failed:', error);
sendResponse({ success: false, error: error.message });
}
})();
return true;
});
// Track pending auto-group to avoid duplicates
let pendingAutoGroup = null;
// Track tab creation for timeline grouping (fallback for tabs never activated)
chrome.tabs.onCreated.addListener((tab) => {
if (tab.id && tab.windowId) {
// Only track if not already tracked (lastAccessed might be set)
if (!tabTimeline.has(tab.id)) {
const entry = {
createdAt: Date.now(),
url: tab.url || tab.pendingUrl || '',
windowId: tab.windowId,
title: tab.title || ''
};
tabTimeline.set(tab.id, entry);
saveTimelineToStorage();
console.log(`Tab ${tab.id} created at ${new Date(entry.createdAt).toLocaleString()}`);
}
}
});
// Update timeline when tab URL changes
chrome.tabs.onUpdated.addListener(async (tabId, changeInfo, tab) => {
// Update URL in timeline
if (changeInfo.url && tabTimeline.has(tabId)) {
const entry = tabTimeline.get(tabId);
entry.url = changeInfo.url;
saveTimelineToStorage();
}
// Update title
if (changeInfo.title && tabTimeline.has(tabId)) {
const entry = tabTimeline.get(tabId);
entry.title = changeInfo.title;
saveTimelineToStorage();
}
// Auto-group when tab is loaded
if (changeInfo.status === 'complete' && tab.url) {
const settings = await getSettings();
if (settings.autoGroup) {
clearTimeout(pendingAutoGroup);
pendingAutoGroup = setTimeout(() => autoGroupTab(tab), 500);
}
}
});
// Clean up timeline when tab is closed
chrome.tabs.onRemoved.addListener((tabId) => {
if (tabTimeline.has(tabId)) {
tabTimeline.delete(tabId);
saveTimelineToStorage();
console.log(`Tab ${tabId} removed from timeline`);
}
});
// ==================== Core Grouping Logic ====================
async function groupCurrentWindow() {
console.log('Grouping current window...');
const tabs = await chrome.tabs.query({ currentWindow: true });
console.log(`Found ${tabs.length} tabs in current window`);
await ungroupTabs(tabs);
const groups = await analyzeAndGroup(tabs);
await createGroups(groups);
}
async function groupAllWindows() {
console.log('Grouping all windows...');
const allTabs = await chrome.tabs.query({});
const windowTabs = {};
for (const tab of allTabs) {
if (!windowTabs[tab.windowId]) {
windowTabs[tab.windowId] = [];
}
windowTabs[tab.windowId].push(tab);
}
console.log(`Found ${allTabs.length} tabs in ${Object.keys(windowTabs).length} windows`);
for (const [windowId, tabs] of Object.entries(windowTabs)) {
console.log(`Processing window ${windowId} with ${tabs.length} tabs`);
await ungroupTabs(tabs);
const groups = await analyzeAndGroup(tabs);
await createGroups(groups);
}
}
// ==================== Timeline Grouping ====================
async function groupByTimelineAction(targetWindowId) {
console.log('Grouping by timeline...', targetWindowId ? `window ${targetWindowId}` : 'all windows');
const settings = await getSettings();
const timeThresholdMs = (settings.timelineThreshold || 5) * 60 * 1000; // Default 5 minutes
// Get tabs to group
let tabs;
if (targetWindowId) {
tabs = await chrome.tabs.query({ windowId: targetWindowId });
} else {
tabs = await chrome.tabs.query({});
}
// Filter valid tabs and get creation time using native API
const validTabs = [];
for (const tab of tabs) {
if (!tab.url || tab.url.startsWith('chrome://') || tab.url.startsWith('chrome-extension://')) {
continue;
}
const createdAt = getTabCreatedAt(tab);
validTabs.push({
...tab,
createdAt: createdAt
});
console.log(`Tab ${tab.id}: lastAccessed=${tab.lastAccessed}, createdAt=${new Date(createdAt).toLocaleString()}`);
}
console.log(`Found ${validTabs.length} valid tabs for timeline grouping`);
if (validTabs.length === 0) {
console.log('No valid tabs available for timeline grouping');
return;
}
// Use the tested groupByTimeline function from timeline-utils.js
const timeGroups = groupByTimeline(validTabs, timeThresholdMs);
console.log(`Created ${timeGroups.length} time groups`);
// Ungroup all first
await ungroupTabs(tabs);
// Create Chrome tab groups (process in reverse order so later groups end up on the right)
const sortedGroups = [...timeGroups].sort((a, b) => b.startTime - a.startTime);
for (const group of sortedGroups) {
if (group.tabs.length >= 2) {
const sortedTabs = [...group.tabs].sort((a, b) => a.createdAt - b.createdAt);
const tabIds = sortedTabs.map(t => t.id);
const title = formatTimeRange(group.startTime, group.endTime);
try {
const groupId = await chrome.tabs.group({ tabIds });
await chrome.tabGroups.update(groupId, {
title: title,
color: getGroupColor(title)
});
console.log(`Created timeline group: ${title} with ${tabIds.length} tabs`);
} catch (error) {
console.error(`Failed to create timeline group: ${error.message}`);
}
}
}
}
// ==================== Helpers ====================
async function ungroupTabs(tabs) {
for (const tab of tabs) {
if (tab.groupId !== chrome.tabGroups.TAB_GROUP_ID_NONE) {
try {
await chrome.tabs.ungroup(tab.id);
} catch (error) {
console.error(`Failed to ungroup tab ${tab.id}:`, error);
}
}
}
}
async function createGroups(groups) {
for (const [groupKey, tabIds] of Object.entries(groups)) {
if (tabIds.length > 1) {
try {
const groupId = await chrome.tabs.group({ tabIds });
await chrome.tabGroups.update(groupId, {
title: truncateTitle(groupKey, 25),
color: getGroupColor(groupKey)
});
console.log(`Created group: ${groupKey} with ${tabIds.length} tabs`);
} catch (error) {
console.error(`Failed to create group ${groupKey}:`, error);
}
}
}
}
async function ungroupAll() {
console.log('Ungrouping all tabs...');
const tabs = await chrome.tabs.query({});
await ungroupTabs(tabs);
}
async function autoGroupTab(tab) {
if (!tab.id || !tab.url) return;
if (tab.url.startsWith('chrome://') || tab.url.startsWith('chrome-extension://')) {
return;
}
try {
const settings = await getSettings();
const groupKey = await getGroupKey(tab, settings);
const existingGroups = await chrome.tabGroups.query({ windowId: tab.windowId });
const matchingGroup = existingGroups.find(g => g.title === groupKey || g.title?.includes(groupKey));
if (matchingGroup) {
await chrome.tabs.group({ tabIds: tab.id, groupId: matchingGroup.id });
console.log(`Added tab to existing group: ${groupKey}`);
} else {
const otherTabs = await chrome.tabs.query({ windowId: tab.windowId });
const similarTabs = [];
for (const otherTab of otherTabs) {
if (otherTab.id !== tab.id && otherTab.url) {
const otherKey = await getGroupKey(otherTab, settings);
if (otherKey === groupKey) {
similarTabs.push(otherTab.id);
}
}
}
if (similarTabs.length > 0) {
const allTabIds = [tab.id, ...similarTabs];
const groupId = await chrome.tabs.group({ tabIds: allTabIds });
await chrome.tabGroups.update(groupId, {
title: truncateTitle(groupKey, 25),
color: getGroupColor(groupKey)
});
console.log(`Created new group: ${groupKey} with ${allTabIds.length} tabs`);
}
}
} catch (error) {
console.error('Auto-group failed:', error);
}
}
// ==================== Analysis Engine ====================
async function analyzeAndGroup(tabs) {
const groups = {};
const settings = await getSettings();
for (const tab of tabs) {
if (!tab.url || tab.url.startsWith('chrome://') || tab.url.startsWith('chrome-extension://')) {
continue;
}
const groupKey = await getGroupKey(tab, settings);
if (!groups[groupKey]) {
groups[groupKey] = [];
}
groups[groupKey].push(tab.id);
}
return groups;
}
async function getGroupKey(tab, settings) {
const urlInfo = parseUrl(tab.url);
if (settings.useUrlHierarchy && urlInfo.pathSegments.length > 1) {
if (isCodeHostingSite(urlInfo.domain)) {
const projectPath = urlInfo.pathSegments.slice(0, 2).join('/');
return `${urlInfo.domain}/${projectPath}`;
}
if (isDocsSite(urlInfo.domain)) {
return `${urlInfo.domain}/${urlInfo.pathSegments[0]}`;
}
}
return urlInfo.domain;
}
// ==================== URL Parsing ====================
function parseUrl(url) {
try {
const urlObj = new URL(url);
const domain = urlObj.hostname;
const pathSegments = urlObj.pathname
.split('/')
.filter(s => s.length > 0);
return { domain, pathSegments, fullUrl: url };
} catch {
return { domain: 'unknown', pathSegments: [], fullUrl: url };
}
}
function isCodeHostingSite(domain) {
const codeSites = [
'github.com',
'gitlab.com',
'bitbucket.org',
'gitee.com',
'codeberg.org'
];
return codeSites.includes(domain);
}
function isDocsSite(domain) {
const docsSites = [
'docs.google.com',
'notion.so',
'atlassian.net',
'atlassian.com',
'readthedocs.io',
'docs.python.org',
'developer.mozilla.org',
'react.dev',
'vuejs.org',
'tailwindcss.com'
];
return docsSites.some(d => domain === d || domain.endsWith('.' + d));
}
// ==================== Helpers ====================
function truncateTitle(title, maxLength) {
if (title.length <= maxLength) return title;
return title.substring(0, maxLength - 2) + '..';
}
// ==================== Settings ====================
async function getSettings() {
const result = await chrome.storage.sync.get({
useUrlHierarchy: true,
useContentAnalysis: false,
autoGroup: false,
timelineThreshold: 5,
llmEnabled: false,
llmApiKey: '',
llmApiUrl: 'https://api.openai.com/v1/chat/completions',
llmModel: 'gpt-4o-mini'
});
return result;
}