mirror of
https://github.com/multipleof4/sune.git
synced 2026-01-14 16:47:59 +00:00
This build was committed by a bot.
This commit is contained in:
250
docs/sw.js
250
docs/sw.js
@@ -1,18 +1,16 @@
|
|||||||
importScripts("https://cdn.jsdelivr.net/npm/localforage@1.10.0/dist/localforage.min.js");
|
importScripts("https://cdn.jsdelivr.net/npm/localforage@1.10.0/dist/localforage.min.js");
|
||||||
const TARGET_SUBSTRING = "openrouter.ai/api/v1/chat/completions";
|
|
||||||
const THREADS_KEY = "threads_v1";
|
const THREADS_KEY = "threads_v1";
|
||||||
const BUFFER_SAVE_BYTES = 32 * 1024;
|
const TARGET_SUBSTRING = "openrouter.ai/api/v1/chat/completions";
|
||||||
const SAVE_INTERVAL_MS = 2e3;
|
const LOG = (...a) => {
|
||||||
|
console.log("[sw-debug]", ...a);
|
||||||
|
};
|
||||||
const gid = () => Math.random().toString(36).slice(2, 9) + "-" + Date.now().toString(36);
|
const gid = () => Math.random().toString(36).slice(2, 9) + "-" + Date.now().toString(36);
|
||||||
function now() {
|
|
||||||
return Date.now();
|
|
||||||
}
|
|
||||||
async function readThreads() {
|
async function readThreads() {
|
||||||
try {
|
try {
|
||||||
const v = await localforage.getItem(THREADS_KEY);
|
const v = await localforage.getItem(THREADS_KEY);
|
||||||
return Array.isArray(v) ? v : [];
|
return Array.isArray(v) ? v : [];
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error("sw: idb read error", e);
|
LOG("readThreads err", e);
|
||||||
return [];
|
return [];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -20,47 +18,40 @@ async function writeThreads(arr) {
|
|||||||
try {
|
try {
|
||||||
await localforage.setItem(THREADS_KEY, arr);
|
await localforage.setItem(THREADS_KEY, arr);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error("sw: idb write error", e);
|
LOG("writeThreads err", e);
|
||||||
throw e;
|
throw e;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
function pickThread(threads) {
|
function pickThread(threads) {
|
||||||
if (!threads || threads.length === 0) return null;
|
if (!threads || !threads.length) return null;
|
||||||
threads.sort((a, b) => (b.updatedAt || 0) - (a.updatedAt || 0));
|
threads.sort((a, b) => (b.updatedAt || 0) - (a.updatedAt || 0));
|
||||||
return threads[0];
|
return threads[0];
|
||||||
}
|
}
|
||||||
async function upsertStreamMessage(streamId, text, meta = {}) {
|
async function upsertStreamMessage(streamId, text, meta = {}) {
|
||||||
const threads = await readThreads();
|
const threads = await readThreads();
|
||||||
let th = pickThread(threads);
|
let th = pickThread(threads);
|
||||||
const createdNow = now();
|
const now = Date.now();
|
||||||
if (!th) {
|
if (!th) {
|
||||||
th = {
|
th = { id: "sw-" + gid(), title: "Missed while backgrounded", pinned: false, updatedAt: now, messages: [] };
|
||||||
id: "sw-" + gid(),
|
|
||||||
title: "Missed while backgrounded",
|
|
||||||
pinned: false,
|
|
||||||
updatedAt: createdNow,
|
|
||||||
messages: []
|
|
||||||
};
|
|
||||||
threads.unshift(th);
|
threads.unshift(th);
|
||||||
}
|
}
|
||||||
let msgIndex = -1;
|
let msgIndex = -1;
|
||||||
for (let i = th.messages.length - 1; i >= 0; i--) {
|
for (let i = th.messages.length - 1; i >= 0; i--) {
|
||||||
const m = th.messages[i];
|
if (th.messages[i] && th.messages[i].sw_streamId === streamId) {
|
||||||
if (m && m.sw_streamId === streamId) {
|
|
||||||
msgIndex = i;
|
msgIndex = i;
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const contentParts = [{ type: "text", text }];
|
const contentParts = [{ type: "text", text }];
|
||||||
if (msgIndex >= 0) {
|
if (msgIndex >= 0) {
|
||||||
const existing = th.messages[msgIndex];
|
const ex = th.messages[msgIndex];
|
||||||
existing.content = text;
|
ex.content = text;
|
||||||
existing.contentParts = contentParts;
|
ex.contentParts = contentParts;
|
||||||
existing.updatedAt = createdNow;
|
ex.updatedAt = now;
|
||||||
existing._sw_lastSave = createdNow;
|
ex._sw_lastSave = now;
|
||||||
existing._sw_meta = Object.assign({}, existing._sw_meta || {}, meta);
|
ex._sw_meta = Object.assign({}, ex._sw_meta || {}, meta);
|
||||||
} else {
|
} else {
|
||||||
const msg = {
|
th.messages.push({
|
||||||
id: "swmsg-" + gid(),
|
id: "swmsg-" + gid(),
|
||||||
role: "assistant",
|
role: "assistant",
|
||||||
content: text,
|
content: text,
|
||||||
@@ -68,13 +59,12 @@ async function upsertStreamMessage(streamId, text, meta = {}) {
|
|||||||
kind: "assistant",
|
kind: "assistant",
|
||||||
sw_saved: true,
|
sw_saved: true,
|
||||||
sw_streamId: streamId,
|
sw_streamId: streamId,
|
||||||
createdAt: createdNow,
|
createdAt: now,
|
||||||
updatedAt: createdNow,
|
updatedAt: now,
|
||||||
_sw_meta: Object.assign({}, meta)
|
_sw_meta: meta
|
||||||
};
|
});
|
||||||
th.messages.push(msg);
|
|
||||||
}
|
}
|
||||||
th.updatedAt = createdNow;
|
th.updatedAt = now;
|
||||||
await writeThreads(threads);
|
await writeThreads(threads);
|
||||||
return { threadId: th.id };
|
return { threadId: th.id };
|
||||||
}
|
}
|
||||||
@@ -85,20 +75,37 @@ async function finalizeStream(streamId, meta = {}) {
|
|||||||
for (let i = th.messages.length - 1; i >= 0; i--) {
|
for (let i = th.messages.length - 1; i >= 0; i--) {
|
||||||
const m = th.messages[i];
|
const m = th.messages[i];
|
||||||
if (m && m.sw_streamId === streamId) {
|
if (m && m.sw_streamId === streamId) {
|
||||||
m._sw_meta = Object.assign({}, m._sw_meta || {}, meta, { completeAt: now() });
|
m._sw_meta = Object.assign({}, m._sw_meta || {}, meta, { completeAt: Date.now() });
|
||||||
m.updatedAt = now();
|
m.updatedAt = Date.now();
|
||||||
th.updatedAt = now();
|
th.updatedAt = Date.now();
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
await writeThreads(threads);
|
await writeThreads(threads);
|
||||||
const clientsList = await self.clients.matchAll({ includeUncontrolled: true, type: "window" });
|
const clientsList = await self.clients.matchAll({ includeUncontrolled: true, type: "window" });
|
||||||
clientsList.forEach((c) => {
|
for (const c of clientsList) {
|
||||||
try {
|
try {
|
||||||
c.postMessage({ type: "stream-saved", streamId, meta });
|
c.postMessage({ type: "stream-saved", streamId, meta });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
}
|
}
|
||||||
});
|
}
|
||||||
|
}
|
||||||
|
async function listSwStreams() {
|
||||||
|
const threads = await readThreads();
|
||||||
|
const found = [];
|
||||||
|
for (const t of threads || []) {
|
||||||
|
for (const m of t.messages || []) {
|
||||||
|
if (m && m.sw_streamId) found.push({
|
||||||
|
threadId: t.id,
|
||||||
|
threadTitle: t.title,
|
||||||
|
messageId: m.id,
|
||||||
|
sw_streamId: m.sw_streamId,
|
||||||
|
snippet: (m.content || "").slice(0, 200),
|
||||||
|
updatedAt: m.updatedAt
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return found;
|
||||||
}
|
}
|
||||||
async function notifyClients(msg) {
|
async function notifyClients(msg) {
|
||||||
try {
|
try {
|
||||||
@@ -110,118 +117,117 @@ async function notifyClients(msg) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
LOG("notifyClients err", e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
self.addEventListener("install", (e) => {
|
||||||
|
self.skipWaiting();
|
||||||
|
});
|
||||||
|
self.addEventListener("activate", (e) => {
|
||||||
|
e.waitUntil(self.clients.claim());
|
||||||
|
});
|
||||||
self.addEventListener("fetch", (event) => {
|
self.addEventListener("fetch", (event) => {
|
||||||
try {
|
const reqUrl = event.request.url || "";
|
||||||
const url = event.request.url || "";
|
if (new URL(reqUrl).pathname === "/__sw_tee_test") {
|
||||||
if (!url.includes(TARGET_SUBSTRING)) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
event.respondWith((async () => {
|
event.respondWith((async () => {
|
||||||
const upstream = await fetch(event.request);
|
const probeId = new URL(reqUrl).searchParams.get("probeId") || gid();
|
||||||
if (!upstream || !upstream.body) return upstream;
|
LOG("Received tee-test probe", probeId);
|
||||||
const streamId = "swstream-" + gid();
|
const encoder = new TextEncoder();
|
||||||
const headers = new Headers(upstream.headers);
|
const stream = new ReadableStream({
|
||||||
const [clientStream, swStream] = upstream.body.tee();
|
start(ctrl) {
|
||||||
const savePromise = (async () => {
|
let count = 0;
|
||||||
try {
|
const id = setInterval(() => {
|
||||||
const reader = swStream.getReader();
|
count++;
|
||||||
const dec = new TextDecoder("utf-8");
|
const chunk = `probe(${probeId}) chunk ${count}
|
||||||
let bufferText = "";
|
`;
|
||||||
let bufferedBytes = 0;
|
ctrl.enqueue(encoder.encode(chunk));
|
||||||
let lastSaveAt = 0;
|
if (count >= 6) {
|
||||||
const saveIfNeeded = async (force = false) => {
|
clearInterval(id);
|
||||||
const nowMs = Date.now();
|
ctrl.close();
|
||||||
if (!force && bufferedBytes < BUFFER_SAVE_BYTES && nowMs - lastSaveAt < SAVE_INTERVAL_MS) return;
|
|
||||||
try {
|
|
||||||
await upsertStreamMessage(streamId, bufferText, { partialBytes: bufferedBytes, savedAt: Date.now() });
|
|
||||||
lastSaveAt = nowMs;
|
|
||||||
} catch (e) {
|
|
||||||
console.error("sw: upsert save error", e);
|
|
||||||
}
|
}
|
||||||
};
|
}, 300);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
const [clientBranch, swBranch] = stream.tee();
|
||||||
|
(async () => {
|
||||||
|
try {
|
||||||
|
const reader = swBranch.getReader();
|
||||||
|
const dec = new TextDecoder("utf-8");
|
||||||
|
let collected = "";
|
||||||
|
let bytes = 0;
|
||||||
while (true) {
|
while (true) {
|
||||||
const { value, done } = await reader.read();
|
const { value, done } = await reader.read();
|
||||||
if (done) break;
|
if (done) break;
|
||||||
const chunkText = dec.decode(value, { stream: true });
|
const chunkText = dec.decode(value, { stream: true });
|
||||||
bufferText += chunkText;
|
collected += chunkText;
|
||||||
bufferedBytes += value && value.byteLength ? value.byteLength : chunkText.length;
|
bytes += value && value.byteLength ? value.byteLength : chunkText.length;
|
||||||
await saveIfNeeded(false);
|
await upsertStreamMessage("probe-" + probeId, collected, { probeId, bytesSoFar: bytes });
|
||||||
|
await notifyClients({ type: "tee-probe-chunk", probeId, bytes, snippet: chunkText.slice(0, 200) });
|
||||||
}
|
}
|
||||||
await saveIfNeeded(true);
|
await finalizeStream("probe-" + probeId, { totalBytes: bytes, probeId });
|
||||||
await finalizeStream(streamId, { totalBytes: bufferedBytes });
|
LOG("tee-probe: save complete", probeId, "bytes", bytes);
|
||||||
|
await notifyClients({ type: "tee-probe-complete", probeId, totalBytes: bytes });
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error("sw: error saving stream", err);
|
LOG("tee-probe save error", err);
|
||||||
try {
|
await notifyClients({ type: "tee-probe-error", probeId, error: String(err) });
|
||||||
await finalizeStream(streamId, { error: String(err) });
|
|
||||||
} catch (e) {
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
})();
|
})();
|
||||||
event.waitUntil(savePromise);
|
return new Response(clientBranch, { status: 200, headers: { "Content-Type": "text/plain; charset=utf-8" } });
|
||||||
return new Response(clientStream, {
|
|
||||||
status: upstream.status,
|
|
||||||
statusText: upstream.statusText,
|
|
||||||
headers
|
|
||||||
});
|
|
||||||
})());
|
})());
|
||||||
} catch (err) {
|
return;
|
||||||
console.error("sw: fetch handler error", err);
|
}
|
||||||
|
if (reqUrl.includes(TARGET_SUBSTRING)) {
|
||||||
|
event.respondWith(fetch(event.request));
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
self.addEventListener("message", (event) => {
|
self.addEventListener("message", (event) => {
|
||||||
const data = event.data || {};
|
const data = event.data || {};
|
||||||
try {
|
try {
|
||||||
if (data && data.type === "PING") {
|
if (data && data.type === "PING") {
|
||||||
if (event.ports && event.ports[0]) {
|
|
||||||
try {
|
|
||||||
event.ports[0].postMessage({ type: "PONG", ts: Date.now(), ok: true });
|
|
||||||
} catch (e) {
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
if (event.source && typeof event.source.postMessage === "function") {
|
|
||||||
try {
|
|
||||||
event.source.postMessage({ type: "PONG", ts: Date.now(), ok: true });
|
|
||||||
} catch (e) {
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
notifyClients({ type: "PONG", ts: Date.now(), ok: true });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (data && data.type === "list-sw-streams") {
|
|
||||||
(async () => {
|
(async () => {
|
||||||
const threads = await readThreads();
|
const streams = await listSwStreams();
|
||||||
const found = [];
|
const info = {
|
||||||
for (const t of threads || []) {
|
type: "PONG",
|
||||||
for (const m of t.messages || []) {
|
ts: Date.now(),
|
||||||
if (m && m.sw_streamId) found.push({ threadId: t.id, threadTitle: t.title, messageId: m.id, sw_streamId: m.sw_streamId, summary: (m.content || "").slice(0, 200), updatedAt: m.updatedAt });
|
ok: true,
|
||||||
}
|
canTeeProbe: true,
|
||||||
}
|
savedStreamCount: streams.length,
|
||||||
|
lastSaved: streams[0] || null
|
||||||
|
};
|
||||||
if (event.ports && event.ports[0]) {
|
if (event.ports && event.ports[0]) {
|
||||||
event.ports[0].postMessage({ type: "sw-streams-list", streams: found });
|
event.ports[0].postMessage(info);
|
||||||
} else if (event.source && typeof event.source.postMessage === "function") {
|
} else if (event.source && typeof event.source.postMessage === "function") {
|
||||||
event.source.postMessage({ type: "sw-streams-list", streams: found });
|
event.source.postMessage(info);
|
||||||
} else {
|
} else {
|
||||||
notifyClients({ type: "sw-streams-list", streams: found });
|
await notifyClients(info);
|
||||||
}
|
}
|
||||||
})();
|
})();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
} catch (e) {
|
if (data && data.type === "list-sw-streams") {
|
||||||
console.error("sw: message handler error", e);
|
(async () => {
|
||||||
|
const streams = await listSwStreams();
|
||||||
|
const payload = { type: "sw-streams-list", streams };
|
||||||
|
if (event.ports && event.ports[0]) event.ports[0].postMessage(payload);
|
||||||
|
else if (event.source && typeof event.source.postMessage === "function") event.source.postMessage(payload);
|
||||||
|
else await notifyClients(payload);
|
||||||
|
})();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (data && data.type === "run-tee-probe" && data.probeId) {
|
||||||
|
(async () => {
|
||||||
|
try {
|
||||||
|
const probeUrl = "/__sw_tee_test?probeId=" + encodeURIComponent(data.probeId);
|
||||||
|
if (event.ports && event.ports[0]) event.ports[0].postMessage({ type: "run-tee-probe-ok", probeId: data.probeId, probeUrl });
|
||||||
|
else if (event.source && typeof event.source.postMessage === "function") event.source.postMessage({ type: "run-tee-probe-ok", probeId: data.probeId, probeUrl });
|
||||||
|
} catch (e) {
|
||||||
|
if (event.ports && event.ports[0]) event.ports[0].postMessage({ type: "run-tee-probe-error", error: String(e) });
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
LOG("message handler error", err);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
self.addEventListener("install", (event) => {
|
|
||||||
self.skipWaiting();
|
|
||||||
});
|
|
||||||
self.addEventListener("activate", (event) => {
|
|
||||||
event.waitUntil((async () => {
|
|
||||||
try {
|
|
||||||
await self.clients.claim();
|
|
||||||
} catch (e) {
|
|
||||||
}
|
|
||||||
})());
|
|
||||||
});
|
|
||||||
|
|||||||
Reference in New Issue
Block a user