-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
311 lines (266 loc) · 9.84 KB
/
background.js
File metadata and controls
311 lines (266 loc) · 9.84 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
// background.js — Service worker: manages SSE subscriptions, badge, notifications
// Manifest V3 service workers don't support ES module EventSource reliably,
// so we use fetch-based SSE parsing instead.
importScripts('utils.js');
// ---------- Polling config ----------
const POLL_INTERVAL_NORMAL = 15_000; // 15s when all sessions are stable
const POLL_INTERVAL_FAST = 3_000; // 3s when any session is transitioning
// Transitional phases that warrant faster polling
const TRANSITIONAL_PHASES = new Set(['Creating', 'Pending', 'Stopping']);
let pollTimer = null;
let currentPollInterval = POLL_INTERVAL_NORMAL;
let sseControllers = new Map(); // sessionName → AbortController
let lastKnownPhases = new Map(); // sessionName → phase (for change detection)
let workspaceGoneNotified = false; // Throttle WORKSPACE_GONE notifications
// ---------- Notification store ----------
async function getNotifications() {
const { notifications = [] } = await chrome.storage.local.get('notifications');
return notifications;
}
async function addNotification(notif) {
const list = await getNotifications();
list.unshift({ ...notif, id: Date.now(), read: false, ts: new Date().toISOString() });
// Keep last 50
const trimmed = list.slice(0, 50);
await chrome.storage.local.set({ notifications: trimmed });
await updateBadge();
// Broadcast to popup / sidepanel
chrome.runtime.sendMessage({ type: 'NOTIFICATION_ADDED', notification: trimmed[0] }).catch(() => {});
}
async function markAllRead() {
const list = await getNotifications();
list.forEach(n => n.read = true);
await chrome.storage.local.set({ notifications: list });
await updateBadge();
}
async function updateBadge() {
const list = await getNotifications();
const unread = list.filter(n => !n.read).length;
const text = unread > 0 ? String(unread > 99 ? '99+' : unread) : '';
chrome.action.setBadgeText({ text });
chrome.action.setBadgeBackgroundColor({ color: unread > 0 ? '#A3000F' : '#0C1014' });
}
// ---------- SSE per session ----------
async function connectSSE(sessionName) {
if (sseControllers.has(sessionName)) return; // already connected
const { baseUrl, apiKey, projectName } = await getConfig();
if (!projectName) return;
const controller = new AbortController();
sseControllers.set(sessionName, controller);
const url = `${baseUrl}/api/projects/${projectName}/agentic-sessions/${sessionName}/agui/events`;
try {
const res = await fetch(url, {
signal: controller.signal,
headers: { 'Authorization': `Bearer ${apiKey}` },
});
if (!res.ok || !res.body) {
sseControllers.delete(sessionName);
return;
}
const reader = res.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split('\n');
buffer = lines.pop() || '';
for (const line of lines) {
if (!line.startsWith('data: ')) continue;
try {
const event = JSON.parse(line.slice(6));
handleSSEEvent(sessionName, event);
} catch { /* skip */ }
}
}
} catch (err) {
if (err.name !== 'AbortError') {
console.warn(`SSE error for ${sessionName}:`, err.message);
}
} finally {
sseControllers.delete(sessionName);
}
}
function disconnectSSE(sessionName) {
const controller = sseControllers.get(sessionName);
if (controller) {
controller.abort();
sseControllers.delete(sessionName);
}
}
function handleSSEEvent(sessionName, event) {
const type = event.type;
// AskUserQuestion detection — tool call with name containing "ask" or "question"
if (type === 'TOOL_CALL_START') {
const toolName = event.toolCall?.name || event.name || '';
if (/ask.*user|user.*question|askuserquestion/i.test(toolName)) {
addNotification({
sessionName,
kind: 'input_needed',
title: 'Input needed',
body: `Session "${sessionName}" is waiting for your response.`,
});
}
}
// RUN_FINISHED and RUN_ERROR are phase transitions — trigger an immediate refresh
// so the session list updates without waiting for the next poll cycle.
if (type === 'RUN_FINISHED') {
addNotification({
sessionName,
kind: 'run_finished',
title: 'Run finished',
body: `Session "${sessionName}" completed a run.`,
});
// Immediate refresh: session likely changed phase
pollSessions();
}
if (type === 'RUN_ERROR') {
const msg = event.error || event.message || 'Unknown error';
addNotification({
sessionName,
kind: 'error',
title: 'Error',
body: `Session "${sessionName}": ${msg}`,
});
// Immediate refresh: session likely changed phase
pollSessions();
}
// Forward all events to sidepanel
chrome.runtime.sendMessage({
type: 'SSE_EVENT',
sessionName,
event,
}).catch(() => {});
}
// ---------- Adaptive polling ----------
// Drops to 3s when any session is in a transitional phase (Creating, Pending,
// Stopping), returns to 15s when all sessions are stable. Also detects phase
// changes between polls and pushes instant updates to the sidepanel.
function adjustPollInterval(sessions) {
const hasTransitional = sessions.some(s => {
const phase = s.status?.phase || s.phase || '';
return TRANSITIONAL_PHASES.has(phase);
});
const desiredInterval = hasTransitional ? POLL_INTERVAL_FAST : POLL_INTERVAL_NORMAL;
if (desiredInterval !== currentPollInterval) {
currentPollInterval = desiredInterval;
// Restart the timer with the new interval
if (pollTimer) clearInterval(pollTimer);
pollTimer = setInterval(pollSessions, currentPollInterval);
console.log(`[ACP] Poll interval → ${currentPollInterval / 1000}s (transitional: ${hasTransitional})`);
}
}
function detectPhaseChanges(sessions) {
let changed = false;
for (const s of sessions) {
const name = s.metadata?.name || s.name;
const phase = s.status?.phase || s.phase || '';
const prev = lastKnownPhases.get(name);
if (prev && prev !== phase) {
changed = true;
console.log(`[ACP] Phase change: ${name} ${prev} → ${phase}`);
}
lastKnownPhases.set(name, phase);
}
return changed;
}
// ---------- Session polling ----------
async function pollSessions() {
try {
const { baseUrl, apiKey, projectName } = await getConfig();
if (!apiKey || !projectName) return;
const res = await fetch(
`${baseUrl}/api/projects/${projectName}/agentic-sessions?limit=100`,
{ headers: { 'Authorization': `Bearer ${apiKey}` } }
);
if (!res.ok) {
// Workspace may have been deleted externally — notify sidepanel once
if ((res.status === 404 || res.status === 403) && !workspaceGoneNotified) {
workspaceGoneNotified = true;
chrome.runtime.sendMessage({ type: 'WORKSPACE_GONE', projectName }).catch(() => {});
}
return;
}
workspaceGoneNotified = false; // Reset on successful poll
const data = await res.json();
const sessions = data.items || data.sessions || data || [];
// Detect phase changes before caching (side effect: updates lastKnownPhases)
detectPhaseChanges(sessions);
// Cache for sidepanel
await chrome.storage.local.set({ cachedSessions: sessions });
chrome.runtime.sendMessage({ type: 'SESSIONS_UPDATED', sessions }).catch(() => {});
// Adaptive polling: speed up during transitions, slow down when stable
adjustPollInterval(sessions);
// Connect SSE to running sessions
const runningSessions = new Set();
for (const s of sessions) {
const name = s.metadata?.name || s.name;
const phase = s.status?.phase || s.phase || '';
if (['Running', 'Creating'].includes(phase)) {
runningSessions.add(name);
connectSSE(name);
}
}
// Disconnect SSE for sessions no longer running
for (const name of sseControllers.keys()) {
if (!runningSessions.has(name)) {
disconnectSSE(name);
}
}
} catch (err) {
console.warn('pollSessions error:', err.message);
}
}
function startPolling() {
if (pollTimer) clearInterval(pollTimer);
currentPollInterval = POLL_INTERVAL_NORMAL;
pollSessions();
pollTimer = setInterval(pollSessions, currentPollInterval);
}
// ---------- Message handlers ----------
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
// Only accept messages from our own extension context
if (sender.id !== chrome.runtime.id) return;
if (msg.type === 'MARK_ALL_READ') {
markAllRead().then(() => sendResponse({ ok: true }));
return true;
}
if (msg.type === 'GET_NOTIFICATIONS') {
getNotifications().then(n => sendResponse(n));
return true;
}
if (msg.type === 'REFRESH_SESSIONS') {
pollSessions().then(() => sendResponse({ ok: true }));
return true;
}
if (msg.type === 'CONNECT_SESSION_SSE') {
connectSSE(msg.sessionName);
sendResponse({ ok: true });
return false;
}
// Trigger fast polling when user initiates a state transition (Start/Stop)
if (msg.type === 'SESSION_TRANSITIONING') {
if (currentPollInterval !== POLL_INTERVAL_FAST) {
currentPollInterval = POLL_INTERVAL_FAST;
if (pollTimer) clearInterval(pollTimer);
pollTimer = setInterval(pollSessions, POLL_INTERVAL_FAST);
console.log('[ACP] Poll interval → 3s (user-initiated transition)');
}
sendResponse({ ok: true });
return false;
}
});
// ---------- Lifecycle ----------
chrome.runtime.onInstalled.addListener(() => {
updateBadge();
startPolling();
});
chrome.runtime.onStartup.addListener(() => {
updateBadge();
startPolling();
});
// Open side panel on action click (right-click opens popup by default)
chrome.sidePanel.setPanelBehavior({ openPanelOnActionClick: true }).catch(() => {});
// Start polling immediately when service worker loads
startPolling();