Repository navigation
Expand file tree
/
Copy pathbackground.js
More file actions
229 lines (217 loc) · 14.6 KB
/
Copy pathbackground.js
File metadata and controls
229 lines (217 loc) · 14.6 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
// Service worker:
// • toolbar button opens the dashboard; keeps the NetBox/Jira/… snapshot warm every 10 minutes so new tabs open instantly
// • after every new snapshot: desktop alerts, the toolbar badge, and a compact daily history (for the brief's deltas)
// • the daily brief notification at the time set in Settings
// • makes the extension's API requests look like a plain client, not a browser (drop Origin/Referer/Sec-*, own UA)
importScripts('apptabs.js', 'live.js', 'data.js', 'ai.js', 'smart.js', 'alerts.js', 'updates.js');
const PLAIN_CLIENT_RULE_ID = 1;
const BROWSER_HEADERS = ['origin', 'referer', 'sec-fetch-site', 'sec-fetch-mode', 'sec-fetch-dest', 'sec-ch-ua', 'sec-ch-ua-mobile', 'sec-ch-ua-platform'];
async function installPlainClientRule() {
const rule = headers => ({
id: PLAIN_CLIENT_RULE_ID, priority: 1,
action: {
type: 'modifyHeaders',
requestHeaders: [
...headers.map(header => ({ header, operation: 'remove' })),
{ header: 'user-agent', operation: 'set', value: `lambda-os/${chrome.runtime.getManifest().version}` },
],
},
// Google, NetSuite and the AI chats are signed-in web pages, not APIs: leave their requests looking like the browser so bot checks don't trip.
condition: { initiatorDomains: [chrome.runtime.id], resourceTypes: ['xmlhttprequest', 'other'], excludedRequestDomains: ['google.com', 'netsuite.com', 'claude.ai', 'chatgpt.com'] },
});
try {
await chrome.declarativeNetRequest.updateDynamicRules({ removeRuleIds: [PLAIN_CLIENT_RULE_ID], addRules: [rule(BROWSER_HEADERS)] });
} catch (e) {
console.warn('plain client rule', e);
await chrome.declarativeNetRequest.updateDynamicRules({ removeRuleIds: [PLAIN_CLIENT_RULE_ID], addRules: [rule(['origin', 'referer'])] })
.catch(e2 => console.warn('plain client rule', e2));
}
}
installPlainClientRule();
// Ask AI no longer calls AI APIs (it uses the browser chat), so drop the old API header rule and any saved API keys.
chrome.declarativeNetRequest.updateDynamicRules({ removeRuleIds: [2] }).catch(() => {});
chrome.storage.local.get('settings').then(({ settings: s }) => {
const chosen = s?.ai?.picked && ['claude', 'chatgpt', 'gemini'].includes(s.ai.web);
if (s?.ai && (s.ai.keys || s.ai.models || s.ai.provider !== 'web' || (!chosen && s.ai.web !== 'auto'))) chrome.storage.local.set({ settings: { ...s, ai: chosen ? { provider: 'web', web: s.ai.web, picked: true } : { provider: 'web', web: 'auto' } } });
}).catch(() => {});
const DASH = () => chrome.runtime.getURL('newtab.html');
chrome.action.onClicked.addListener(() => chrome.tabs.create({ url: DASH() }));
/* ---------------- Background refresh ---------------- */
const REFRESH_ALARM = 'refresh', BRIEF_ALARM = 'brief';
// Refresh interval comes from Settings → Data (refreshMinutes; 0 = manual only). Re-created only when it changes.
async function scheduleRefresh() {
const s = await LambdaLive.settings(), every = Number(s.refreshMinutes) || 0;
const cur = await chrome.alarms.get(REFRESH_ALARM);
if (!every || s.mode !== 'live') { if (cur) await chrome.alarms.clear(REFRESH_ALARM); return; }
if (cur?.periodInMinutes === every) return;
await chrome.alarms.clear(REFRESH_ALARM);
chrome.alarms.create(REFRESH_ALARM, { delayInMinutes: Math.min(1, every), periodInMinutes: every });
}
scheduleRefresh();
/* ---------------- Alerts ---------------- */
async function buildD(snap) {
await LambdaData.prepare(); // load tracked deployments
const D = LambdaData.buildLive(snap);
(D.RAW ||= {}).myPrefs = await LambdaData.loadMySites(); // sites you starred as yours in the site picker
return D;
}
// Notifications and the brief follow the site picker in the top bar (all sites, your sites, or chosen ones).
const scoped = async D => LambdaData.scope(D, await LambdaData.loadScope());
// Toolbar badge: your urgent ticket count wins; otherwise "NEW" while an update is waiting (until "Later" for that version).
async function setBadge(count, on) {
if (count !== undefined) await chrome.storage.session.set({ badgeUrgent: on ? count : 0 });
const { badgeUrgent = 0 } = await chrome.storage.session.get('badgeUrgent');
const { updateCheck, updateLater } = await chrome.storage.local.get(['updateCheck', 'updateLater']);
const latest = updateCheck?.ok ? updateCheck.latest : null;
const update = latest && LambdaUpdates.newer(latest, chrome.runtime.getManifest().version) && updateLater !== latest;
const text = badgeUrgent ? String(badgeUrgent > 99 ? '99+' : badgeUrgent) : update ? 'NEW' : '';
await chrome.action.setBadgeText({ text });
if (text) await chrome.action.setBadgeBackgroundColor({ color: badgeUrgent ? '#d03b3b' : '#2a78d6' });
await chrome.action.setTitle({ title: [badgeUrgent ? `${badgeUrgent} urgent tickets` : '', update ? `Lambda OS ${latest} is available` : ''].filter(Boolean).join(' · ') || 'Open Lambda OS' });
}
/* ---------------- Updates (like Lambda Rackside) ---------------- */
const UPDATE_ALARM = 'updateCheck';
async function updateCheck(force = false) {
const u = await LambdaUpdates.check(force);
await setBadge();
if (!u.available) return u;
const { updateNotified } = await chrome.storage.local.get('updateNotified');
if (updateNotified !== u.latest) {
await chrome.storage.local.set({ updateNotified: u.latest });
await notify([{ id: `update:${u.latest}`, url: chrome.runtime.getURL('settings.html#updates'), title: `Lambda OS ${u.latest} is available`,
message: `You have ${u.current}. Click to see what's new and update.` }], { log: false });
}
return u;
}
chrome.alarms.get(UPDATE_ALARM).then(a => a || chrome.alarms.create(UPDATE_ALARM, { delayInMinutes: 1, periodInMinutes: 120 }));
// Every alert is also kept in an in-app log (🔔 in the dashboard), so nothing is lost when the OS hides pop-ups.
async function logAlerts(notes) {
const { alertLog = [] } = await chrome.storage.local.get('alertLog');
const now = Date.now();
const add = notes.map(n => ({ id: n.id, at: now, title: n.title, message: n.message || '', url: n.url || '', urgent: !!n.urgent, read: false }));
await chrome.storage.local.set({ alertLog: [...add, ...alertLog].slice(0, 60) });
}
async function notify(notes, { log = true } = {}) {
if (log) await logAlerts(notes);
const urls = (await chrome.storage.session.get('notifUrls')).notifUrls || {};
const show = notes.length > 3
? [{ id: `batch:${Date.now()}`, urgent: notes.some(n => n.urgent), url: DASH(), title: `${notes.length} Lambda OS alerts`,
message: notes.slice(0, 4).map(n => n.title).join('\n') + (notes.length > 4 ? `\n+${notes.length - 4} more` : '') }]
: notes;
for (const n of show) {
const id = `${n.id}:${Date.now()}`;
urls[id] = n.url || DASH();
try {
await chrome.notifications.create(id, { type: 'basic', iconUrl: chrome.runtime.getURL('icons/icon128.png'), title: n.title, message: n.message || '',
priority: n.urgent ? 2 : 0, requireInteraction: !!n.urgent });
await chrome.storage.local.set({ notifyStatus: { ok: true, at: Date.now() } });
} catch (e) {
console.warn('notification', e);
await chrome.storage.local.set({ notifyStatus: { ok: false, at: Date.now(), error: String(e.message || e) } });
}
}
await chrome.storage.session.set({ notifUrls: urls });
}
let running = null, queued = null;
async function runAlerts(snap) {
if (running) { queued = snap; return running; } // a newer snapshot during a pass runs right after it
running = (async () => {
const s = await LambdaLive.settings();
if (s.mode !== 'live' || !snap) return;
const D = await buildD(snap);
const { alertState, history } = await chrome.storage.local.get(['alertState', 'history']);
// Sites whose Atium purchase orders the next refresh should read (for alerts and the brief).
const watch = D.SITES.filter(x => x.atium && LambdaAlerts.mySites(D).has(x.id)).map(x => x.atium.id).slice(0, 6);
const { atiumWatch } = await chrome.storage.local.get('atiumWatch');
if (JSON.stringify(watch) !== JSON.stringify(atiumWatch || [])) await chrome.storage.local.set({ atiumWatch: watch });
const res = LambdaAlerts.evaluate(await scoped(D), alertState, s.alerts); // the daily record below stays fleet-wide
await chrome.storage.local.set({ alertState: res.state, history: LambdaAlerts.addToHistory(history, D) });
await setBadge(res.urgentCount, s.alerts.enabled && s.alerts.badge);
if (s.alerts.enabled && res.notes.length && !LambdaAlerts.quiet(s.alerts)) await notify(res.notes);
})().catch(e => console.warn('alerts', e)).finally(() => { running = null; if (queued) { const q = queued; queued = null; runAlerts(q); } });
return running;
}
/* ---------------- Daily brief ---------------- */
async function scheduleBrief() {
const s = await LambdaLive.settings();
await chrome.alarms.clear(BRIEF_ALARM);
if (s.brief.enabled) chrome.alarms.create(BRIEF_ALARM, { when: LambdaAlerts.nextBriefAt(s.brief) });
}
async function briefNotification() {
const s = await LambdaLive.settings();
const { snapshot, history } = await chrome.storage.local.get(['snapshot', 'history']);
let message = 'Open it for today’s meetings, your tickets and tracked deployments.';
if (snapshot && s.mode === 'live') {
const b = LambdaAlerts.brief(await scoped(await buildD(snapshot)), history);
const down = b.troubled.map(s => s.name);
message = [down.length ? `⚠ ${down.join(', ')} not up to date` : '', `${b.meetings.length} meetings today`, `${b.myBreached.length} of your tickets breached`, `${b.myDue.length} due today`,
`${b.tracked.length} tracked deployments`, b.partsArrived.length ? `${b.partsArrived.length} parts arrived` : ''].filter(Boolean).join(' · ');
}
await notify([{ id: 'brief', url: `${DASH()}#brief`, title: 'Your daily brief is ready', message }]);
}
/* ---------------- Self-healing app tabs (apptabs.js) ---------------- */
// One tick a minute (an alarm, because the service worker sleeps): heal the pinned tabs, close the ones for apps that
// were turned off, and close temporary tabs that sat idle for 5 minutes.
const APPTABS_ALARM = 'appTabs';
chrome.alarms.get(APPTABS_ALARM).then(a => a || chrome.alarms.create(APPTABS_ALARM, { delayInMinutes: 1, periodInMinutes: 1 }));
let ticking = null;
function tabsTick() {
ticking ||= LambdaLive.settings().then(s => LambdaTabs.tick(s)).catch(e => console.warn('app tabs', e)).finally(() => { ticking = null; });
return ticking;
}
chrome.alarms.onAlarm.addListener(async a => {
if (a.name === APPTABS_ALARM) await tabsTick();
if (a.name === REFRESH_ALARM) {
const s = await LambdaLive.settings();
if (s.mode === 'live') await LambdaLive.refresh().catch(e => console.warn('refresh', e)); // the new snapshot triggers alerts below
}
if (a.name === UPDATE_ALARM) await updateCheck().catch(e => console.warn('update check', e));
if (a.name === BRIEF_ALARM) { await briefNotification().catch(e => console.warn('brief', e)); await scheduleBrief(); }
});
// Every new snapshot (from this worker or from a dashboard tab) runs the alerts; settings changes reschedule the brief.
chrome.storage.onChanged.addListener((changes, area) => {
if (area !== 'local') return;
if (changes.snapshot?.newValue && !changes.snapshot.newValue.partial) runAlerts(changes.snapshot.newValue); // alerts only on a finished load
if (changes.settings) { scheduleBrief(); scheduleRefresh(); tabsTick(); } // tick: a source turned off closes its tab now
});
chrome.notifications.onClicked.addListener(async id => {
const urls = (await chrome.storage.session.get('notifUrls')).notifUrls || {};
chrome.tabs.create({ url: urls[id] || DASH() });
chrome.notifications.clear(id);
delete urls[id]; await chrome.storage.session.set({ notifUrls: urls });
});
// Settings → "Send a test alert"
chrome.runtime.onMessage.addListener((msg, _sender, reply) => {
if (msg?.type === 'ping') { reply({ ok: true, version: chrome.runtime.getManifest().version }); return; }
if (msg?.type === 'test-alert') {
notify([{ id: 'test', url: DASH(), title: 'Lambda OS alerts are on', message: 'This is what an alert looks like. Click to open the dashboard.' }])
.then(async () => reply({ ok: true, status: (await chrome.storage.local.get('notifyStatus')).notifyStatus }))
.catch(e => reply({ ok: false, error: String(e.message || e) }));
return true;
}
if (msg?.type === 'update-check') { updateCheck(!!msg.force).then(reply).catch(e => reply({ ok: false, error: String(e.message || e) })); return true; }
if (msg?.type === 'update-later') { chrome.storage.local.set({ updateLater: msg.version }).then(() => setBadge()).then(() => reply({ ok: true })); return true; }
if (msg?.type === 'test-brief') { briefNotification().then(() => reply({ ok: true })); return true; }
});
// Lambda Rackside (the Jira side panel, a separate extension) asks to show a ticket here. Its ID is remembered
// from the sender; on startup we say hello so Rackside learns ours and can show its "Lambda OS" button.
chrome.runtime.onMessageExternal.addListener((msg, sender, reply) => {
if (msg?.app !== 'lambda-rackside' || msg.type !== 'lambdaos.open' || !sender.id) return;
chrome.storage.local.set({ peerRackside: sender.id });
const key = /^[A-Z][A-Z0-9_]+-\d+$/.test(msg.ticket || '') ? msg.ticket : '';
chrome.tabs.create({ url: DASH() + (key ? '#ticket=' + key : '') }).then(() => reply({ ok: true }), e => reply({ ok: false, error: String(e.message || e) }));
return true;
});
async function helloRackside() {
const { peerRackside } = await chrome.storage.local.get('peerRackside');
if (!peerRackside) return;
const r = await chrome.runtime.sendMessage(peerRackside, { app: 'lambda-os', type: 'hello' }).catch(() => null);
if (!r?.ok) await chrome.storage.local.remove('peerRackside'); // removed or reinstalled: found again on the next click
}
// A fresh install (also after removing and adding Lambda OS again) starts clean: the page clears its own leftovers
// (tour, view choices, "Later") the first time it opens. An update keeps everything.
chrome.runtime.onInstalled.addListener(d => { chrome.storage.local.get('installId').then(({ installId }) => {
if (d.reason === 'install') chrome.storage.local.set({ installId: String(Date.now()), freshInstall: true, adoptPinned: true });
else if (!installId) chrome.storage.local.set({ installId: String(Date.now()) }); }).catch(() => {}); });
chrome.runtime.onInstalled.addListener(d => { helloRackside(); scheduleBrief(); scheduleRefresh(); updateCheck(true).catch(() => {}); if (d.reason === 'install') chrome.tabs.create({ url: DASH() }); });
chrome.runtime.onStartup.addListener(() => { helloRackside(); scheduleBrief(); scheduleRefresh(); LambdaTabs.hiddenWindow().catch(() => {}); }); // after a restart: find the restored hidden window (merges any copies)