Repository navigation
Expand file tree
/
Copy pathwebchat.js
More file actions
371 lines (359 loc) · 21.3 KB
/
Copy pathwebchat.js
File metadata and controls
371 lines (359 loc) · 21.3 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
// The AI through the chat you're already signed in to in this browser (Claude, ChatGPT or Gemini), with no API key.
// Rackside loads the chat site, pastes the request (masked when Privacy mode is on), presses Send and reads the
// answer back off the page as it's written (chatpage.js does the page part). Every request is a private chat
// (Claude incognito, ChatGPT temporary chat, Gemini temporary chat), so none of them show up in your chat history.
//
// Where the chat page runs:
// 1. A hidden frame inside the Rackside page itself: no window, no tab. Chat sites refuse to be framed, so a
// session rule drops those headers, only for frames Rackside itself opens (see allowFrames).
// 2. If the frame can't do it (the site doesn't load there, wants a human check, or you need to sign in): one
// minimized window, reused for every request, which comes up only when you need to act in it.
// The chat page stays loaded between requests: right after an answer (and when the panel opens) the next blank
// private chat is loaded in the background (warm), so a request starts by pasting, not by waiting for the site.
// It reads the chat page itself, so it can stop working when a site changes its layout; the selectors are in chatpage.js.
const LambdaWebChat = (() => {
// Private-chat addresses; Gemini's temporary chat is switched on by a button (pagePrivate in chatpage.js).
const SITES = {
claude: { name: 'Claude', url: 'https://claude.ai/new?incognito', host: 'claude.ai' },
chatgpt: { name: 'ChatGPT', url: 'https://chatgpt.com/?temporary-chat=true', host: 'chatgpt.com' },
gemini: { name: 'Gemini', url: 'https://gemini.google.com/app', host: 'gemini.google.com' },
};
const sleep = ms => new Promise(r => setTimeout(r, ms));
const fail = (code, msg) => Object.assign(new Error(msg), { code });
let myUrl = ''; // the last answer's chat address, for "Show Claude"
let lastKind = ''; // 'frame' or 'window': where the last request ran
/* ---------- 1. The hidden frame ---------- */
const CAN_FRAME = typeof document !== 'undefined' && typeof chrome !== 'undefined' && !!chrome.declarativeNetRequest?.updateSessionRules && !!chrome.scripting?.registerContentScripts;
const FRAME_RULE_ID = 3, BRIDGE_ID = 'rackside-chatpage';
let frameEl = null, frameReady = null, frameBusy = false, callSeq = 0, setup = null;
let frameFresh = null; // the site whose blank private chat is loaded in the frame and not used yet
// The frame didn't work in this browser (e.g. the site doesn't see your sign-in inside a frame): use the window
// for the rest of the browser session instead of trying the frame first every time.
const NO_FRAME = 'webchatNoFrame';
const frameOff = async () => !!(await chrome.storage.session.get(NO_FRAME).catch(() => ({})))[NO_FRAME];
const pending = new Map();
if (CAN_FRAME) addEventListener('message', (e) => {
if (!frameEl || e.source !== frameEl.contentWindow || !e.data?.rackside) return;
if (e.data.type === 'ready') frameReady = e.data.host;
if (e.data.type === 'result') {
const p = pending.get(e.data.id); if (!p) return;
pending.delete(e.data.id);
e.data.error ? p.reject(new Error(e.data.error)) : p.resolve(e.data.result);
}
});
// Lets Rackside's own pages frame the three chat sites: drops X-Frame-Options and CSP (frame-ancestors) only on
// frame loads that Rackside starts, so your own tabs keep them. And puts chatpage.js into those frames.
function allowFrames() {
return setup ||= (async () => {
await chrome.declarativeNetRequest.updateSessionRules({ removeRuleIds: [FRAME_RULE_ID], addRules: [{
id: FRAME_RULE_ID, priority: 3,
action: { type: 'modifyHeaders', responseHeaders: ['x-frame-options', 'content-security-policy', 'content-security-policy-report-only'].map(header => ({ header, operation: 'remove' })) },
condition: { initiatorDomains: [chrome.runtime.id], requestDomains: Object.values(SITES).map(s => s.host), resourceTypes: ['sub_frame'] },
}] });
const have = await chrome.scripting.getRegisteredContentScripts({ ids: [BRIDGE_ID] }).catch(() => []);
if (!have.length) await chrome.scripting.registerContentScripts([{ id: BRIDGE_ID, js: ['chatpage.js'], allFrames: true, runAt: 'document_idle', persistAcrossSessions: true,
matches: Object.values(SITES).map(s => `https://${s.host}/*`) }]);
})().catch((e) => { setup = null; throw fail('frame', `Couldn't set up the hidden chat frame (${e.message}).`); });
}
function frameTransport(site) {
const S = SITES[site], origin = new URL(S.url).origin;
const T = {
kind: 'frame',
async open() {
await allowFrames();
if (frameEl?.isConnected && frameFresh === site && frameReady === S.host) { frameFresh = null; return; } // already loaded and waiting
if (!frameEl?.isConnected) {
frameEl = document.createElement('iframe');
frameEl.setAttribute('aria-hidden', 'true');
frameEl.tabIndex = -1;
frameEl.style.cssText = 'position:fixed;left:-12000px;top:0;width:1000px;height:800px;border:0;opacity:0;pointer-events:none';
document.body.appendChild(frameEl);
}
frameFresh = null;
frameReady = null;
frameEl.src = S.url;
const t0 = Date.now();
while (frameReady !== S.host) { // a sign-in on another site (accounts.google.com…) never says ready
if (Date.now() - t0 > 15000) throw fail('frame', `${S.name} didn't load in the hidden frame.`);
await sleep(200);
}
},
call(fn, args = [], ms = 10000) {
return new Promise((resolve, reject) => {
const id = ++callSeq;
pending.set(id, { resolve, reject });
try { frameEl.contentWindow.postMessage({ rackside: true, type: 'call', id, fn, args }, origin); }
catch (e) { pending.delete(id); return reject(fail('frame', e.message)); }
setTimeout(() => { if (pending.delete(id)) reject(fail('frame', `${S.name} stopped answering in the hidden frame.`)); }, ms);
});
},
async state() {
let p = null; try { p = await T.call('pageProbe', [site], 5000); } catch { return { s: 'loading' }; }
if (!p) return { s: 'loading' };
return { s: p.check ? 'check' : p.login ? 'login' : p.ready ? 'ready' : 'loading', limit: p.limit };
},
alive: async () => !!frameEl?.isConnected,
};
return T;
}
/* ---------- 2. The minimized window ---------- */
// One chat window for every Rackside page, opened minimized so it never shows up in your tab strip. Its ids live
// in session storage (cleared when Chrome quits), so every page reuses it instead of opening another.
const KEY = 'webchatWorker', LOCK = 'webchatBusy';
const run = async (tabId, fn, args = []) => {
const [r] = await chrome.scripting.executeScript({ target: { tabId }, func: RacksideChatPage[fn], args });
return r?.result;
};
async function alive(tabId) { try { return await chrome.tabs.get(tabId); } catch { return null; } }
const getW = async () => (await chrome.storage.session.get(KEY))[KEY] || null;
const setW = w => chrome.storage.session.set({ [KEY]: w });
async function worker() { const w = await getW(); return w && await alive(w.tabId) ? w : null; }
function waitLoaded(tabId, ms = 30000) {
return new Promise(resolve => {
const done = () => { clearTimeout(t); chrome.tabs.onUpdated.removeListener(l); resolve(); };
const l = (id, info) => { if (id === tabId && info.status === 'complete') done(); };
const t = setTimeout(done, ms);
chrome.tabs.onUpdated.addListener(l);
chrome.tabs.get(tabId).then(tb => { if (tb.status === 'complete') done(); }).catch(done);
});
}
async function hiddenWindow(url) {
let win;
try { win = await chrome.windows.create({ url, focused: false, state: 'minimized' }); }
catch { win = await chrome.windows.create({ url, focused: false, width: 900, height: 700 }); chrome.windows.update(win.id, { state: 'minimized' }).catch(() => {}); }
return { tabId: win.tabs[0].id, windowId: win.id };
}
function windowTransport(site) {
const S = SITES[site];
let w = null;
const T = {
kind: 'window',
async open() {
w = await worker();
const t = w && await alive(w.tabId);
if (w && w.fresh === site && t?.status === 'complete' && t.url?.startsWith(S.url)) { // already loaded and waiting
await setW({ tabId: w.tabId, windowId: w.windowId, site });
return;
}
if (w) {
await chrome.tabs.update(w.tabId, { url: S.url });
chrome.windows.get(w.windowId).then(win => { if (!win.focused && win.state !== 'minimized') chrome.windows.update(w.windowId, { state: 'minimized' }); }).catch(() => {});
} else w = await hiddenWindow(S.url);
await setW({ tabId: w.tabId, windowId: w.windowId, site });
await sleep(400); await waitLoaded(w.tabId);
},
call: (fn, args = []) => run(w.tabId, fn, args),
// Where the chat page stands: 'ready' | 'login' | 'check' | 'loading' | 'closed' (plus a usage-limit notice).
async state() {
const t = await alive(w.tabId); if (!t) return { s: 'closed' };
// A sign-in on another site (accounts.google.com, auth.openai.com…) can't be read: that's a sign-in in progress.
if (t.url && /^https?:/.test(t.url) && !new URL(t.url).hostname.endsWith(S.host)) return { s: 'login' };
let p = null; try { p = await run(w.tabId, 'pageProbe', [site]); } catch { return { s: 'loading' }; }
if (!p) return { s: 'loading' };
return { s: p.check ? 'check' : p.login ? 'login' : p.ready ? 'ready' : 'loading', limit: p.limit };
},
alive: async () => !!(await alive(w.tabId)),
// Brings the chat window up for the person to act on…
reveal() {
chrome.windows.update(w.windowId, { state: 'normal', focused: true }).catch(() => {});
chrome.tabs.update(w.tabId, { active: true }).catch(() => {});
},
// …and puts things back: chat window minimized, the window with the side panel in front again.
comeBack(home) {
chrome.windows.update(w.windowId, { state: 'minimized' }).catch(() => {});
if (home) chrome.windows.update(home.windowId, { focused: true }).catch(() => {});
},
};
return T;
}
// Only one request at a time goes through the shared window; a second one waits its turn.
// Each holder has its own id (a request, or warm loading the next blank chat). Returns the id, or '' if aborted.
async function lock(signal, warm = false) {
const id = Math.random().toString(36).slice(2);
for (let i = 0; i < 300; i++) {
const l = (await chrome.storage.session.get(LOCK))[LOCK];
if (!l || Date.now() - l.at > 120000) {
await chrome.storage.session.set({ [LOCK]: { id, warm, at: Date.now() } });
if ((await chrome.storage.session.get(LOCK))[LOCK]?.id === id) return id; // two takers at once: one wins
}
if (signal?.aborted) return '';
await sleep(l?.warm ? 250 : 1000);
}
return id;
}
const beat = (id) => chrome.storage.session.set({ [LOCK]: { id, at: Date.now() } });
const unlock = async (id) => { const l = (await chrome.storage.session.get(LOCK))[LOCK]; if (l?.id === id) await chrome.storage.session.remove(LOCK); };
/* ---------- One request ---------- */
// Waits until the chat can take a question. In the window, if it needs the person (sign in, a human check), it
// shows them the window ({ wait: text }), keeps watching, and comes back to the panel by itself once the chat is
// ready ({ wait: null }). Without showWindow (the frame, or Auto with another chat to try) it throws 'login' /
// 'check' / 'timeout' instead. Rackside never types into a sign-in or check; the person does that.
async function* ready(site, T, signal, showWindow) {
const S = SITES[site], t0 = Date.now();
const home = showWindow ? await chrome.windows.getCurrent().then((w) => ({ windowId: w.id })).catch(() => null) : null; // the side panel's window
let shown = null;
while (true) {
if (signal?.aborted) return false;
T.beat?.(); // keep the shared window reserved while the person signs in
const st = await T.state();
if (st.s === 'closed') throw fail('closed', `The ${S.name} window was closed.`);
if (st.limit) throw fail('limit', `${S.name} says: “${st.limit.slice(0, 200)}”`);
if (st.s === 'ready') {
if (shown) { T.comeBack(home); yield { wait: null }; await sleep(800); }
return true;
}
if (!showWindow && (st.s === 'login' || st.s === 'check')) throw fail(st.s, st.s === 'login' ? `You're signed out of ${S.name}.` : `${S.name} wants to check you're human.`);
if (!showWindow && st.s === 'loading' && Date.now() - t0 > 20000) throw fail('timeout', `${S.name} didn't load.`);
if ((st.s === 'login' || st.s === 'check') && shown !== st.s) {
shown = st.s; T.reveal();
yield { wait: st.s === 'login'
? `Sign in to ${S.name} in the window that just opened. Rackside brings you back and carries on as soon as you're in.`
: `${S.name} wants to check you're human. Finish that in the window that just opened; Rackside brings you back and carries on.` };
}
if (!shown && st.s === 'loading' && Date.now() - t0 > 20000) { // neither ready nor asking for anything: let the person look
shown = 'stuck'; T.reveal();
yield { wait: `${S.name} hasn't finished loading. Have a look in the window that just opened (sign in, or close any pop-up); Rackside carries on as soon as the chat box shows.` };
}
if (Date.now() - t0 > 600000) throw fail('timeout', `Gave up waiting for ${S.name} after 10 minutes.`);
await sleep(shown ? 1000 : 500);
}
}
// Private chat on, paste, send, then read the answer as it's written. Yields { sent: true } once it's sent.
async function* converse(T, site, text, signal) {
const S = SITES[site];
if (site === 'gemini') {
const p = await T.call('pagePrivate', [site]).catch(() => null);
if (!p?.ok) yield { note: `Couldn't switch ${S.name} to a temporary chat; this one may show in your ${S.name} history.` };
}
yield { note: `Sending to ${S.name}…` };
const sent = await T.call('pageSend', [site, text], 60000);
if (!sent?.ok) throw fail('layout', `Couldn't find the ${S.name} message box. ${S.name} may have changed its page; pick another chat in Settings → Start, or update Rackside.`);
yield { sent: true };
yield { note: `${S.name} is thinking…` };
let last = '', same = 0, started = false, idle = 0;
const t0 = Date.now();
while (true) {
if (signal?.aborted) { T.call('pageStop').catch(() => {}); return; }
await sleep(700);
T.beat?.();
if (!(await T.alive())) throw fail('closed', `The ${S.name} ${T.kind} was closed before it answered.`);
let r; try { r = await T.call('pageRead', [site, sent.before]); } catch { continue; }
if (!r) continue;
if (!r.started) {
if (Date.now() - t0 > 6000 && ++idle % 4 === 0) { const st = await T.state(); if (st.limit) throw fail('limit', `${S.name} says: “${st.limit.slice(0, 200)}”`); if (st.s === 'login' || st.s === 'check') throw fail(st.s, `${S.name} signed you out. Click Re-analyze or ask again to sign in and retry.`); }
if (Date.now() - t0 > 120000) throw fail('timeout', `${S.name} hasn't answered after 2 minutes.`);
continue;
}
if (!started) { started = true; yield { note: `${S.name} is writing…` }; }
myUrl = r.url || myUrl;
if (r.text !== last) {
if (r.text.startsWith(last)) yield { text: r.text.slice(last.length) }; else yield { full: r.text };
last = r.text; same = 0;
} else same++;
if (!r.busy && last && same >= 2) break;
if (!r.busy && !last && same >= 6) break;
if (Date.now() - t0 > 600000) break;
}
}
// Yields { text } / { full } / { note } / { wait } chunks. Every request is a new private chat; earlier turns of a
// ticket's chat are sent along as text. reveal false (Auto, with another signed-in chat to try): never shows a
// window, throws 'login' / 'check' / 'limit' so the next chat can be tried.
async function* stream({ site = 'claude', system, user, history = [], signal, reveal = true }) {
const S = SITES[site]; if (!S) throw new Error('Unknown chat site.');
if (typeof chrome === 'undefined' || !chrome.scripting || !chrome.storage?.session) throw new Error('Asking through the browser chat works inside the extension only.');
const earlier = history.length ? `EARLIER IN THIS CONVERSATION:\n${history.map(h => `[${h.role}] ${h.content}`).join('\n\n')}\n\n` : '';
const text = `${system}\n\n${earlier}${user}`;
myUrl = '';
// 1. The hidden frame. Falls back to the window if the frame can't load the chat, it wants a human check, you
// need to sign in (when the window may be shown), or the page looks different in a frame. Never after sending.
if (CAN_FRAME && !(await frameOff())) {
let sent = false;
while (frameBusy) { if (signal?.aborted) return; await sleep(300); } // one request at a time per page
frameBusy = true;
try {
const T = frameTransport(site);
yield { note: `Opening ${S.name}…` };
await T.open();
if (!(yield* ready(site, T, signal, false))) return;
for await (const c of converse(T, site, text, signal)) { if (c.sent) sent = true; else yield c; }
lastKind = 'frame';
setTimeout(() => warm(site), 1500); // the next blank chat, ready for the next request
return;
} catch (e) {
const useWindow = ['frame', 'check', 'timeout', 'layout'].includes(e.code) || (e.code === 'login' && reveal);
if (sent || signal?.aborted || !useWindow) throw e;
console.warn(`Rackside: ${S.name} in the hidden frame didn't work (${e.message}); using a window.`);
if (e.code !== 'check') await chrome.storage.session.set({ [NO_FRAME]: e.message }).catch(() => {});
} finally { frameBusy = false; }
}
// 2. The minimized window.
const l = (await chrome.storage.session.get(LOCK))[LOCK];
if (l && !l.warm && Date.now() - l.at < 120000) yield { note: 'Waiting for another AI request to finish…' };
const lockId = await lock(signal); // waits for a warm-up in progress too, then uses the page it loaded
if (!lockId) return;
try {
const T = windowTransport(site);
T.beat = () => beat(lockId);
yield { note: `Opening ${S.name}…` };
await T.open();
if (!(yield* ready(site, T, signal, reveal))) return;
if (signal?.aborted) return;
for await (const c of converse(T, site, text, signal)) if (!c.sent) yield c;
lastKind = 'window';
} finally { await unlock(lockId); }
setTimeout(() => warm(site), 1500); // the next blank chat, ready for the next request
}
// Loads a blank private chat for the next request in the background, so it's ready when you ask. Does nothing
// while a request is running, or if the right blank chat is already loaded.
let warming = false;
async function warm(site) {
const S = SITES[site];
if (!S || warming || typeof chrome === 'undefined' || !chrome.scripting) return;
warming = true;
try {
if (CAN_FRAME && !(await frameOff())) {
if (frameBusy || (frameFresh === site && frameReady === S.host)) return;
frameBusy = true;
try { await frameTransport(site).open(); frameFresh = site; } catch { /* the request itself will try again */ }
finally { frameBusy = false; }
return;
}
const l = (await chrome.storage.session.get(LOCK))[LOCK];
if (l && Date.now() - l.at < 120000) return; // a request is using the window
const id = await lock(null, true); // a request that starts now waits for this, then uses the page
try {
const w = await worker();
if (w?.fresh === site) return;
await windowTransport(site).open();
const now = await worker();
if (now) await setW({ ...now, fresh: site });
} finally { await unlock(id); }
} catch { /* best effort */ } finally { warming = false; }
}
// "Show Claude": brings up the chat window if the last answer came from it, otherwise opens the chat in a tab.
async function show() {
const w = lastKind === 'window' ? await worker() : null;
if (w) {
chrome.windows.update(w.windowId, { state: 'normal', focused: true }).catch(() => {});
return chrome.tabs.update(w.tabId, { active: true }).catch(() => {});
}
if (myUrl) chrome.tabs.create({ url: myUrl });
}
function reset() { myUrl = ''; }
// Runs one request and returns the whole answer. onNote(text, needsYou) gets progress and "sign in" messages (null
// clears them); onText(full) gets the answer so far while it's written.
async function ask({ site, system, user, history = [], signal, onNote, onText, reveal = true }) {
let full = '';
for await (const c of stream({ site, system, user, history, signal, reveal })) {
if (c.wait !== undefined) onNote?.(c.wait, true);
else if (c.note) onNote?.(c.note, false);
if (c.full != null) full = c.full;
if (c.text) full += c.text;
if ((c.full != null || c.text) && onText) onText(full);
}
onNote?.(null, false);
return full.trim();
}
return { SITES, stream, ask, show, reset, warm, where: () => lastKind };
})();
if (typeof self !== 'undefined') self.LambdaWebChat = LambdaWebChat;