Skip to content

100+ AI Agents, Agent Skills and RAG Apps - Free and Open Source.

fix: preserve Ripple review state and cancel failed checks

cid647965dfbff
diff --git a/advanced_llm_apps/ripple/README.md b/advanced_llm_apps/ripple/README.md
index 45486da8..8b268976 100644
--- a/advanced_llm_apps/ripple/README.md
+++ b/advanced_llm_apps/ripple/README.md
@@ -81,7 +81,7 @@ Click a numbered margin marker or **Review changes** to inspect a finding. The c
- **Keep original** dismisses the finding without changing the document.
- **Next suggestion** lets you move through the review without applying anything.
-After an applied correction, the next suggestion stays open. Once all visible findings are resolved, the card closes. Use Google Docs' normal **Undo** to reverse an edit. Manual edits and Undo trigger a fresh check; confirmed Ripple corrections preserve the current review.
+After an applied correction, the next suggestion stays open. Once all visible findings are resolved, the card closes. Use Google Docs' normal **Undo** to reverse an edit. Manual edits and Undo trigger a fresh check; confirmed Ripple corrections preserve the current review. Ripple remembers the last 20 confirmed corrections in tab memory so Undo and Redo can recheck against your original fact changes. Pause, refresh, or switching document tabs clears that history.
Open the settings button beside the status chip to pause Ripple or restore kept findings. Pause and resume when you want to capture a fresh starting point.
@@ -149,6 +149,7 @@ ripple/
- Both API keys stay in the local backend. The backend does not intentionally save or log document text. Model-provider policies still apply.
- Starting text, findings, and drafts are held in tab memory and reset on refresh. Only the per-document enabled preference is stored locally.
- Up to **120 sentences / 30,000 characters** in the active tab, with a maximum of **2,500 characters per sentence**. Request metadata can reduce the usable limit. Oversized checks report an error.
+- Checks have a 75-second total deadline. Failed or disconnected checks cancel remaining Jev requests. When another Doc is checking, Ripple retries automatically until the service is available or you pause it.
- Up to **four source edits** can be tracked in one session. Pure insertions or deletions without both previous and replacement wording are not checked. Pause and resume after a large rewrite to capture a fresh starting point.
- Images, drawings, footnotes, comments, and other document tabs are not checked. Collaborative edits may be detected without reliable attribution to an author.
- Ripple uses extension-facing Google Docs interfaces that Google can change. Plain-text fixes can affect inline formatting; complex formatting, tables, and Suggesting mode need broader validation. Sentence removal preserves paragraph breaks and can leave an empty paragraph.
diff --git a/advanced_llm_apps/ripple/extension/background.js b/advanced_llm_apps/ripple/extension/background.js
index cffd3e3e..b96bef97 100644
--- a/advanced_llm_apps/ripple/extension/background.js
+++ b/advanced_llm_apps/ripple/extension/background.js
@@ -40,7 +40,14 @@ chrome.runtime.onMessage.addListener((message, sender, respond) => {
);
}
const data = await response.json();
- if (!response.ok) throw new Error(data.error || "The check failed.");
+ if (!response.ok) {
+ respond({
+ ok: false,
+ error: data.error || "The check failed.",
+ retryable: response.status === 429 && data.retryable === true,
+ });
+ return;
+ }
respond({ ok: true, ...data });
} catch (error) {
respond({
diff --git a/advanced_llm_apps/ripple/extension/content.js b/advanced_llm_apps/ripple/extension/content.js
index 72fdcfa3..752fdb1d 100644
--- a/advanced_llm_apps/ripple/extension/content.js
+++ b/advanced_llm_apps/ripple/extension/content.js
@@ -23,6 +23,7 @@
snapshotValid = false;
const pendingApplies = new Map();
let activeApply = null;
+ let corrections = [];
const docId = location.pathname.match(/\/document\/d\/([^/]+)/)?.[1];
const storageKey = "enabled:" + docId;
const send = (message) =>
@@ -78,6 +79,7 @@
current = "";
processed = "";
sources = [];
+ corrections = [];
findings = [];
visible = [];
kept.clear();
@@ -149,7 +151,17 @@
const rev = revision,
snapshot = current;
try {
- sources = reconcile(processed, snapshot, sources, findings);
+ const undo = corrections.findLast(
+ (c) => c.after === processed && c.before === snapshot,
+ );
+ const redo = corrections.findLast(
+ (c) => c.before === processed && c.after === snapshot,
+ );
+ sources = undo
+ ? [...undo.sourcesBefore]
+ : redo
+ ? [...redo.sourcesAfter]
+ : reconcile(processed, snapshot, sources, findings);
processed = snapshot;
if (!sources.length) {
findings = [];
@@ -198,7 +210,11 @@
},
});
if (rev !== revision || !enabled || !snapshotValid) return;
- if (!answer.ok) throw new Error(answer.error);
+ if (!answer.ok) {
+ const failure = new Error(answer.error);
+ failure.retryable = answer.retryable === true;
+ throw failure;
+ }
for (const result of answer.results || []) {
if (result.status !== "likely_conflict") continue;
const s = candidates.find((s) => s.id === result.id);
@@ -222,7 +238,10 @@
error = e.message;
ui.results([]);
ui.draw(new Map());
- state("Could not check", { detail: error });
+ state(e.retryable ? "Waiting for another check…" : "Could not check", {
+ detail: error,
+ });
+ if (e.retryable) schedule(3000, true);
}
} finally {
running = false;
@@ -306,6 +325,12 @@
(action === "delete" ? replacement !== "" : !replacement.trim())
)
return { ok: false, error: "Invalid correction action." };
+ if (replacement.length > 2500 || /[\r\n\u0000-\u001f]/.test(replacement))
+ return {
+ ok: false,
+ error:
+ "Use a single line of at most 2,500 characters for a correction.",
+ };
const requestId = crypto.randomUUID();
const span = uniqueSpan(current, row.text);
const transaction = {
@@ -353,7 +378,15 @@
uniqueSpan(result.text, f.source.after)
);
});
+ const sourcesBefore = [...sources];
sources = sources.filter((s) => uniqueSpan(result.text, s.after));
+ corrections.push({
+ before: transaction.baseText,
+ after: result.text,
+ sourcesBefore,
+ sourcesAfter: [...sources],
+ });
+ corrections = corrections.slice(-20);
current = processed = result.text;
error = "";
publish();
@@ -462,6 +495,7 @@
current = "";
processed = "";
sources = [];
+ corrections = [];
findings = [];
visible = [];
error = "";
diff --git a/advanced_llm_apps/ripple/extension/ui.js b/advanced_llm_apps/ripple/extension/ui.js
index 7ce8f6ca..05f3b437 100644
--- a/advanced_llm_apps/ripple/extension/ui.js
+++ b/advanced_llm_apps/ripple/extension/ui.js
@@ -120,6 +120,7 @@ export function createUI(actions) {
deleting = row.suggestion?.action === "delete";
applying = true;
get("apply").disabled = true;
+ get("keep").disabled = true;
get("apply").textContent = deleting ? "Removing…" : "Applying…";
let result;
try {
@@ -136,7 +137,8 @@ export function createUI(actions) {
};
}
applying = false;
- get("apply").textContent = deleting ? "Remove sentence" : "Apply change";
+ get("keep").disabled = false;
+ if (active) renderSuggestion(active);
if (result.ok) {
drafts.delete(row.key);
if (active?.key === row.key && !card.hidden) {
@@ -152,6 +154,7 @@ export function createUI(actions) {
}
};
get("keep").onclick = () => {
+ if (applying) return;
if (active) {
actions.keep(active);
close();
diff --git a/advanced_llm_apps/ripple/jev.mjs b/advanced_llm_apps/ripple/jev.mjs
index 26c1eb8e..81e66a7a 100644
--- a/advanced_llm_apps/ripple/jev.mjs
+++ b/advanced_llm_apps/ripple/jev.mjs
@@ -1,3 +1,4 @@
+import { setTimeout as sleep } from "node:timers/promises";
import { getApiKey } from "./config.mjs";
const MODEL = "jev-latest";
@@ -64,7 +65,7 @@ export function payload(input) {
};
}
-export async function evaluate(input) {
+export async function evaluate(input, { signal, timeoutMs = 75000 } = {}) {
const body = payload(input);
const key = getApiKey();
if (!key)
@@ -75,43 +76,62 @@ export async function evaluate(input) {
const batches = [];
for (let i = 0; i < entries.length; i += 12)
batches.push(entries.slice(i, i + 12));
- let cursor = 0;
- await Promise.all(
+ let cursor = 0,
+ failure;
+ const controller = new AbortController();
+ const sharedSignal = AbortSignal.any([
+ controller.signal,
+ AbortSignal.timeout(timeoutMs),
+ ...(signal ? [signal] : []),
+ ]);
+ await Promise.allSettled(
[0, 1].map(async () => {
- while (cursor < batches.length) {
- const batch = batches[cursor++];
- let response;
- for (let attempt = 0; attempt < 3; attempt++) {
- if (attempt)
- await new Promise((resolve) => setTimeout(resolve, attempt * 600));
- response = await fetch("https://api.typesafe.ai/v1/systemone", {
- method: "POST",
- headers: {
- Authorization: `Bearer ${key}`,
- "Content-Type": "application/json",
- },
- body: JSON.stringify({
- ...body,
- questions: Object.fromEntries(batch),
- }),
- signal: AbortSignal.timeout(12000),
- });
- if (![502, 503, 504, 429].includes(response.status)) break;
+ try {
+ while (cursor < batches.length) {
+ sharedSignal.throwIfAborted();
+ const batch = batches[cursor++];
+ let response;
+ for (let attempt = 0; attempt < 3; attempt++) {
+ if (attempt)
+ await sleep(attempt * 600, undefined, { signal: sharedSignal });
+ response = await fetch("https://api.typesafe.ai/v1/systemone", {
+ method: "POST",
+ headers: {
+ Authorization: `Bearer ${key}`,
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({
+ ...body,
+ questions: Object.fromEntries(batch),
+ }),
+ signal: AbortSignal.any([
+ sharedSignal,
+ AbortSignal.timeout(12000),
+ ]),
+ });
+ if (![502, 503, 504, 429].includes(response.status)) break;
+ }
+ if (!response.ok)
+ throw new Error(
+ {
+ 401: "The TypeSafe API key was rejected.",
+ 403: "This TypeSafe account cannot access Jev.",
+ 429: "Jev is rate limited. Try again in a moment.",
+ }[response.status] ||
+ `Jev could not complete this check (${response.status}).`,
+ );
+ const data = await response.json();
+ Object.assign(answers, data.answers);
}
- if (!response.ok)
- throw new Error(
- {
- 401: "The TypeSafe API key was rejected.",
- 403: "This TypeSafe account cannot access Jev.",
- 429: "Jev is rate limited. Try again in a moment.",
- }[response.status] ||
- `Jev could not complete this check (${response.status}).`,
- );
- const data = await response.json();
- Object.assign(answers, data.answers);
+ } catch (error) {
+ failure ??= sharedSignal.aborted ? sharedSignal.reason : error;
+ controller.abort(failure);
+ throw error;
}
}),
);
+ if (failure) throw failure;
+ sharedSignal.throwIfAborted();
const results = input.sentences.map((s) => {
const answer = answers[s.id];
if (!statuses.includes(answer?.choice))
diff --git a/advanced_llm_apps/ripple/server.mjs b/advanced_llm_apps/ripple/server.mjs
index 0ff24d9f..cda416b3 100644
--- a/advanced_llm_apps/ripple/server.mjs
+++ b/advanced_llm_apps/ripple/server.mjs
@@ -21,6 +21,7 @@ const origin = "chrome-extension://" + id;
const active = { check: 0, suggest: 0 };
const server = http.createServer(async (req, res) => {
const json = (code, value) => {
+ if (res.destroyed) return;
res.writeHead(code, {
"Content-Type": "application/json",
"Cache-Control": "no-store",
@@ -62,9 +63,15 @@ const server = http.createServer(async (req, res) => {
const route = req.url === "/check" ? "check" : "suggest";
if (active[route] >= (route === "check" ? 1 : 2))
return json(429, {
- error: "Another request is running. Retrying shortly.",
+ error: "Another request is running. Ripple will retry automatically.",
+ retryable: true,
});
active[route]++;
+ const controller = new AbortController();
+ const disconnected = () => {
+ if (!res.writableEnded) controller.abort(new Error("Client disconnected."));
+ };
+ res.on("close", disconnected);
try {
let bytes = 0,
parts = [];
@@ -75,7 +82,9 @@ const server = http.createServer(async (req, res) => {
parts.push(chunk);
}
const input = JSON.parse(Buffer.concat(parts).toString());
- const result = await (route === "check" ? evaluate(input) : suggest(input));
+ const result = await (route === "check"
+ ? evaluate(input, { signal: controller.signal })
+ : suggest(input, { signal: controller.signal }));
json(200, result);
} catch (error) {
json(400, {
@@ -87,6 +96,7 @@ const server = http.createServer(async (req, res) => {
: error.message,
});
} finally {
+ res.off("close", disconnected);
active[route]--;
}
});
diff --git a/advanced_llm_apps/ripple/suggestions.mjs b/advanced_llm_apps/ripple/suggestions.mjs
index f7c05133..2cbb72ca 100644
--- a/advanced_llm_apps/ripple/suggestions.mjs
+++ b/advanced_llm_apps/ripple/suggestions.mjs
@@ -106,7 +106,7 @@ export function parseSuggestions(data, input) {
reason,
}));
}
-export async function suggest(input) {
+export async function suggest(input, { signal } = {}) {
const body = validateSuggestionInput(input),
key = getGeminiKey();
if (!key)
@@ -119,7 +119,10 @@ export async function suggest(input) {
{
method: "POST",
headers: { "x-goog-api-key": key, "Content-Type": "application/json" },
- signal: AbortSignal.timeout(18000),
+ signal: AbortSignal.any([
+ AbortSignal.timeout(18000),
+ ...(signal ? [signal] : []),
+ ]),
body: JSON.stringify({
systemInstruction: { parts: [{ text: instruction }] },
contents: [{ role: "user", parts: [{ text: JSON.stringify(body) }] }],
diff --git a/advanced_llm_apps/ripple/tests/review.test.mjs b/advanced_llm_apps/ripple/tests/review.test.mjs
index 24b916d3..cdbef676 100644
--- a/advanced_llm_apps/ripple/tests/review.test.mjs
+++ b/advanced_llm_apps/ripple/tests/review.test.mjs
@@ -27,7 +27,11 @@ const edited = original.replace(
"Attendance is online.",
"Attendance is in person only.",
);
-async function harness({ deferSuggestions = false, baseline = original } = {}) {
+async function harness({
+ deferSuggestions = false,
+ baseline = original,
+ busyChecks = 0,
+} = {}) {
let actions,
listener,
rows = [],
@@ -54,6 +58,8 @@ async function harness({ deferSuggestions = false, baseline = original } = {}) {
const rpc = async (message) => {
calls.push(message);
if (message.type === "health") return { ok: true, ready: true };
+ if (message.type === "check" && busyChecks-- > 0)
+ return { ok: false, retryable: true, error: "Busy" };
if (message.type === "check")
return {
ok: true,
@@ -338,3 +344,42 @@ test("paragraph-start smart deletion advances the actual baseline without cleari
assert.equal(h.rows()[0], other);
assert.equal(h.calls.length, count);
});
+
+test("replacement Undo and Redo preserve the original governing source", async () => {
+ const h = await harness();
+ const row = h.rows().find((r) => r.text.includes("anywhere"));
+ const pending = h.actions.apply(row, "Attend in person.");
+ const applied = h.confirm(h.request());
+ await pending;
+ for (const text of [edited, applied, edited]) {
+ const start = h.calls.length;
+ h.snapshot(text);
+ await h.runTimers();
+ const checks = h.calls.slice(start).filter((c) => c.type === "check");
+ assert.equal(checks.length, 1);
+ assert.deepEqual(JSON.parse(JSON.stringify(checks[0].input.source)), {
+ before: "Attendance is online.",
+ after: "Attendance is in person only.",
+ });
+ }
+});
+test("invalid replacement text is rejected before sending an editor operation", async () => {
+ const h = await harness();
+ for (const text of ["First line.\nSecond line.", "x".repeat(2501)]) {
+ const result = await h.actions.apply(h.rows()[1], text);
+ assert.equal(result.ok, false);
+ assert.match(result.error, /single line.*2,500/);
+ assert.equal(h.request(), undefined);
+ }
+});
+test("busy backend automatically rechecks unchanged text and respects Pause", async () => {
+ const h = await harness({ busyChecks: 1 });
+ assert.equal(h.rows().length, 0);
+ await h.runTimers();
+ assert.equal(h.rows().length, 2);
+ assert.equal(h.calls.filter((c) => c.type === "check").length, 2);
+ const paused = await harness({ busyChecks: 1 });
+ await paused.actions.toggle(false);
+ await paused.runTimers();
+ assert.equal(paused.calls.filter((c) => c.type === "check").length, 1);
+});
diff --git a/advanced_llm_apps/ripple/tests/server.test.mjs b/advanced_llm_apps/ripple/tests/server.test.mjs
index 0fa9c4b9..887f9688 100644
--- a/advanced_llm_apps/ripple/tests/server.test.mjs
+++ b/advanced_llm_apps/ripple/tests/server.test.mjs
@@ -77,3 +77,123 @@ test("direct TypeSafe transport uses Jev model, Bearer auth, and typed answers",
else process.env.TYPESAFE_API_KEY = originalKey;
}
});
+
+test("failed Jev batches abort siblings and start no remaining work", async () => {
+ const { evaluate } = await import("../jev.mjs");
+ const originalFetch = globalThis.fetch,
+ key = process.env.TYPESAFE_API_KEY;
+ process.env.TYPESAFE_API_KEY = "synthetic";
+ let calls = 0,
+ aborted = false;
+ globalThis.fetch = async (_url, { signal }) => {
+ calls++;
+ if (calls === 1) return new Response("{}", { status: 403 });
+ return new Promise((_resolve, reject) =>
+ signal.addEventListener(
+ "abort",
+ () => {
+ aborted = true;
+ reject(signal.reason);
+ },
+ { once: true },
+ ),
+ );
+ };
+ try {
+ await assert.rejects(
+ evaluate({
+ source: { before: "Online.", after: "In person." },
+ sentences: Array.from({ length: 36 }, (_, i) => ({
+ id: `b0s${i}`,
+ text: `Sentence ${i}.`,
+ section: "",
+ })),
+ }),
+ /cannot access/,
+ );
+ assert.equal(calls, 2);
+ assert.equal(aborted, true);
+ } finally {
+ globalThis.fetch = originalFetch;
+ if (key === undefined) delete process.env.TYPESAFE_API_KEY;
+ else process.env.TYPESAFE_API_KEY = key;
+ }
+});
+test("a shared deadline and caller cancellation stop all 120-sentence work", async () => {
+ const { evaluate } = await import("../jev.mjs");
+ const originalFetch = globalThis.fetch,
+ key = process.env.TYPESAFE_API_KEY;
+ process.env.TYPESAFE_API_KEY = "synthetic";
+ const input = {
+ source: { before: "Online.", after: "In person." },
+ sentences: Array.from({ length: 120 }, (_, i) => ({
+ id: `b0s${i}`,
+ text: `Sentence ${i}.`,
+ section: "",
+ })),
+ };
+ const keepAlive = setInterval(() => {}, 1000);
+ try {
+ for (const mode of ["deadline", "disconnect"]) {
+ let calls = 0,
+ aborted = 0;
+ const controller = new AbortController();
+ globalThis.fetch = async (_url, { signal }) => {
+ calls++;
+ const result = new Promise((_resolve, reject) =>
+ signal.addEventListener(
+ "abort",
+ () => {
+ aborted++;
+ reject(signal.reason);
+ },
+ { once: true },
+ ),
+ );
+ if (mode === "disconnect" && calls === 2)
+ queueMicrotask(() => controller.abort(new Error("Disconnected")));
+ return result;
+ };
+ await assert.rejects(
+ evaluate(input, { timeoutMs: 30, signal: controller.signal }),
+ mode === "deadline" ? { name: "TimeoutError" } : /Disconnected/,
+ );
+ assert.equal(calls, 2);
+ assert.equal(aborted, 2);
+ }
+ } finally {
+ clearInterval(keepAlive);
+ globalThis.fetch = originalFetch;
+ if (key === undefined) delete process.env.TYPESAFE_API_KEY;
+ else process.env.TYPESAFE_API_KEY = key;
+ }
+});
+
+test("shared deadline also interrupts retry backoff", async () => {
+ const { evaluate } = await import("../jev.mjs");
+ const originalFetch = globalThis.fetch,
+ key = process.env.TYPESAFE_API_KEY;
+ process.env.TYPESAFE_API_KEY = "synthetic";
+ let calls = 0;
+ globalThis.fetch = async () => {
+ calls++;
+ return new Response("{}", { status: 503 });
+ };
+ try {
+ await assert.rejects(
+ evaluate(
+ {
+ source: { before: "Online.", after: "In person." },
+ sentences: [{ id: "b0s0", text: "Join remotely.", section: "" }],
+ },
+ { timeoutMs: 30 },
+ ),
+ { name: "TimeoutError" },
+ );
+ assert.equal(calls, 1);
+ } finally {
+ globalThis.fetch = originalFetch;
+ if (key === undefined) delete process.env.TYPESAFE_API_KEY;
+ else process.env.TYPESAFE_API_KEY = key;
+ }
+});
diff --git a/advanced_llm_apps/ripple/tests/transport.test.mjs b/advanced_llm_apps/ripple/tests/transport.test.mjs
new file mode 100644
index 00000000..351f347e
--- /dev/null
+++ b/advanced_llm_apps/ripple/tests/transport.test.mjs
@@ -0,0 +1,164 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import vm from "node:vm";
+import { readFileSync } from "node:fs";
+import { Readable } from "node:stream";
+import { EventEmitter } from "node:events";
+import { fileURLToPath } from "node:url";
+import { createHash } from "node:crypto";
+const root = fileURLToPath(new URL("../", import.meta.url));
+const manifest = JSON.parse(
+ readFileSync(root + "extension/manifest.json", "utf8"),
+);
+const id = [
+ ...createHash("sha256")
+ .update(Buffer.from(manifest.key, "base64"))
+ .digest("hex")
+ .slice(0, 32),
+]
+ .map((h) => String.fromCharCode(97 + parseInt(h, 16)))
+ .join("");
+const serverSource = readFileSync(root + "server.mjs", "utf8")
+ .replace(/^import .*;\n/gm, "")
+ .replace(
+ 'const root = fileURLToPath(new URL(".", import.meta.url));',
+ "const root = testRoot;",
+ );
+function harness(evaluate) {
+ let handler;
+ vm.runInNewContext(serverSource, {
+ http: {
+ createServer(fn) {
+ handler = fn;
+ return { listen() {} };
+ },
+ },
+ readFileSync,
+ createHash,
+ Buffer,
+ AbortController,
+ testRoot: root,
+ evaluate,
+ suggest: async () => ({ suggestions: [] }),
+ getApiKey: () => "",
+ getGeminiKey: () => "",
+ SUGGESTION_MODEL: "test",
+ console,
+ });
+ const request = (headers = {}, url = "/check") => {
+ const req = Readable.from([Buffer.from("{}")]);
+ Object.assign(req, {
+ method: "POST",
+ url,
+ headers: {
+ host: "127.0.0.1:4212",
+ origin: "chrome-extension://" + id,
+ "x-ripple-client": id,
+ "content-type": "application/json",
+ ...headers,
+ },
+ });
+ const res = Object.assign(new EventEmitter(), {
+ destroyed: false,
+ writableEnded: false,
+ setHeader() {},
+ writeHead(status) {
+ this.status = status;
+ },
+ end(body) {
+ this.body = JSON.parse(body);
+ this.writableEnded = true;
+ },
+ });
+ return { req, res, done: handler(req, res) };
+ };
+ return { request };
+}
+test("HTTP rejects foreign callers before model work", async () => {
+ let calls = 0;
+ const h = harness(async () => {
+ calls++;
+ return {};
+ });
+ for (const headers of [
+ { origin: "https://evil.example" },
+ { host: "evil.example" },
+ { "x-ripple-client": "wrong" },
+ { "content-type": "text/plain" },
+ ]) {
+ const r = h.request(headers);
+ await r.done;
+ assert.equal(r.res.status, 403);
+ }
+ assert.equal(calls, 0);
+});
+test("HTTP busy response is retryable; disconnect cancels work before releasing slot", async () => {
+ let signal,
+ calls = 0;
+ const h = harness(async (_input, options) => {
+ calls++;
+ signal = options.signal;
+ if (calls > 1) return { results: [] };
+ await new Promise((_resolve, reject) =>
+ signal.addEventListener("abort", () => reject(signal.reason), {
+ once: true,
+ }),
+ );
+ });
+ const first = h.request();
+ while (!signal) await new Promise((resolve) => setImmediate(resolve));
+ const second = h.request();
+ await second.done;
+ assert.equal(second.res.status, 429);
+ assert.equal(second.res.body.retryable, true);
+ assert.equal(calls, 1);
+ first.res.destroyed = true;
+ first.res.emit("close");
+ await first.done;
+ assert.equal(signal.aborted, true);
+ const third = h.request();
+ await third.done;
+ assert.equal(third.res.status, 200);
+ assert.equal(calls, 2);
+});
+test("extension preserves retryable busy metadata after its bounded attempts", async () => {
+ let listener,
+ calls = 0;
+ const source = readFileSync(root + "extension/background.js", "utf8");
+ vm.runInNewContext(source, {
+ chrome: {
+ runtime: {
+ id,
+ getURL: () => `chrome-extension://${id}/`,
+ onMessage: {
+ addListener(fn) {
+ listener = fn;
+ },
+ },
+ },
+ },
+ AbortSignal,
+ JSON,
+ setTimeout: (fn) => {
+ queueMicrotask(fn);
+ },
+ fetch: async () => {
+ calls++;
+ return {
+ status: 429,
+ ok: false,
+ json: async () => ({ error: "Busy", retryable: true }),
+ };
+ },
+ });
+ const result = await new Promise((resolve) =>
+ listener(
+ { type: "check", input: {} },
+ { id, url: `chrome-extension://${id}/popup.html` },
+ resolve,
+ ),
+ );
+ assert.equal(calls, 3);
+ assert.equal(result.ok, false);
+ assert.equal(result.retryable, true);
+});
diff --git a/advanced_llm_apps/ripple/tests/ui.test.mjs b/advanced_llm_apps/ripple/tests/ui.test.mjs
new file mode 100644
index 00000000..3386c2af
--- /dev/null
+++ b/advanced_llm_apps/ripple/tests/ui.test.mjs
@@ -0,0 +1,98 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import vm from "node:vm";
+import { readFileSync } from "node:fs";
+const source = readFileSync(
+ new URL("../extension/ui.js", import.meta.url),
+ "utf8",
+)
+ .replace('import { logo as icon } from "./logo.js";', 'const icon = "";')
+ .replace("export function createUI", "function createUI");
+function harness() {
+ const nodes = new Map();
+ const element = () => ({
+ dataset: {},
+ style: {},
+ hidden: false,
+ disabled: false,
+ value: "",
+ offsetHeight: 300,
+ setAttribute() {},
+ focus() {},
+ append() {},
+ replaceChildren() {},
+ querySelectorAll: () => [],
+ classList: { toggle() {} },
+ });
+ const root = {
+ getElementById(id) {
+ if (!nodes.has(id)) nodes.set(id, element());
+ return nodes.get(id);
+ },
+ };
+ const host = { ...element(), attachShadow: () => root };
+ let complete,
+ kept = 0;
+ const createUI = vm.runInNewContext(source + "\ncreateUI", {
+ document: {
+ createElement: () => host,
+ documentElement: { append() {} },
+ addEventListener() {},
+ },
+ innerWidth: 1200,
+ innerHeight: 900,
+ });
+ const ui = createUI({
+ navigate() {},
+ keep() {
+ kept++;
+ },
+ apply: () =>
+ new Promise((r) => {
+ complete = r;
+ }),
+ });
+ const rows = ["a", "b", "c"].map((key, i) => ({
+ key,
+ text: key,
+ source: { before: "Online", after: "In person" },
+ suggestionState: "ready",
+ suggestion: {
+ action: i === 1 ? "delete" : "replace",
+ replacement: i === 1 ? "" : "New text",
+ reason: "Changed",
+ },
+ }));
+ nodes.get("menu").hidden = true;
+ nodes.get("card").hidden = true;
+ ui.results(rows);
+ nodes.get("chip").onclick();
+ return { ui, rows, nodes, complete: (r) => complete(r), kept: () => kept };
+}
+test("Keep is blocked throughout a pending Apply, then enabled again", async () => {
+ const h = harness();
+ const pending = h.nodes.get("apply").onclick();
+ assert.equal(h.nodes.get("keep").disabled, true);
+ h.nodes.get("keep").onclick();
+ assert.equal(h.kept(), 0);
+ h.complete({ ok: false, error: "Not accepted" });
+ await pending;
+ assert.equal(h.nodes.get("keep").disabled, false);
+ assert.equal(h.nodes.get("suggestion-status").textContent, "Not accepted");
+ h.nodes.get("keep").onclick();
+ assert.equal(h.kept(), 1);
+});
+test("navigating during Apply restores the active row button and its own action label", async () => {
+ for (const ok of [true, false]) {
+ const h = harness();
+ const pending = h.nodes.get("apply").onclick();
+ h.nodes.get("next").onclick();
+ assert.equal(h.nodes.get("apply").disabled, true);
+ if (ok) h.ui.results(h.rows.slice(1));
+ h.complete({ ok, error: "Not accepted" });
+ await pending;
+ assert.equal(h.nodes.get("apply").disabled, false);
+ assert.equal(h.nodes.get("apply").textContent, "Remove sentence");
+ assert.equal(h.nodes.get("card").hidden, false);
+ }
+});