@spaxe-dev/zen-mcp 0.3.1 → 0.3.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +192 -838
- package/dist/bridge.js +1374 -350
- package/dist/cli.js +1281 -79
- package/dist/cli.js.map +4 -4
- package/package.json +1 -1
package/dist/bridge.js
CHANGED
|
@@ -1567,13 +1567,17 @@ return { cleared: removed > 0, removed: removed };
|
|
|
1567
1567
|
// src/shared/evidence.ts
|
|
1568
1568
|
var DEFAULT_MIN_CONFIDENCE = 0.85;
|
|
1569
1569
|
var MAX_CANDIDATES = 5;
|
|
1570
|
-
var
|
|
1570
|
+
var CONTEXT_BEFORE = 240;
|
|
1571
|
+
var CONTEXT_AFTER = 240;
|
|
1572
|
+
var CONTEXT_PROXIMITY_DECAY = 12;
|
|
1571
1573
|
var CONTEXT_MIN_SCORE = 0.2;
|
|
1572
1574
|
var CONTEXT_MIN_MARGIN = 0.1;
|
|
1573
1575
|
var MAX_OCCURRENCES = 50;
|
|
1576
|
+
var MAX_CONTEXT_OCCURRENCES = 300;
|
|
1574
1577
|
var MAX_FUZZY_QUOTE = 300;
|
|
1575
1578
|
var MAX_FUZZY_WINDOWS = 160;
|
|
1576
1579
|
var MIN_FUZZY_SIMILARITY = 0.45;
|
|
1580
|
+
var MIN_FUZZY_PLAUSIBILITY = 0.7;
|
|
1577
1581
|
var NORMALIZED_CONFIDENCE = [0.99, 0.97, 0.93];
|
|
1578
1582
|
var NEGATION_WORDS = /* @__PURE__ */ new Set([
|
|
1579
1583
|
"no",
|
|
@@ -1752,6 +1756,7 @@ return { cleared: removed > 0, removed: removed };
|
|
|
1752
1756
|
const decodedQuote = decodeHtmlEntities(rawQuote).trim();
|
|
1753
1757
|
const quoteVariants = decodedQuote && decodedQuote !== rawQuote ? [rawQuote, decodedQuote] : [rawQuote];
|
|
1754
1758
|
const context = decodeHtmlEntities(options.context ?? "").trim();
|
|
1759
|
+
const occurrenceLimit = context ? MAX_CONTEXT_OCCURRENCES : MAX_OCCURRENCES;
|
|
1755
1760
|
const minConfidence = clamp(
|
|
1756
1761
|
options.minConfidence ?? DEFAULT_MIN_CONFIDENCE,
|
|
1757
1762
|
0.5,
|
|
@@ -1762,7 +1767,7 @@ return { cleared: removed > 0, removed: removed };
|
|
|
1762
1767
|
Math.min(10, Math.trunc(options.maxCandidates ?? MAX_CANDIDATES))
|
|
1763
1768
|
);
|
|
1764
1769
|
for (const variant of quoteVariants) {
|
|
1765
|
-
const exact = exactCandidates(page, variant);
|
|
1770
|
+
const exact = exactCandidates(page, variant, occurrenceLimit);
|
|
1766
1771
|
if (exact.starts.length > 0) {
|
|
1767
1772
|
return resolveOccurrences(
|
|
1768
1773
|
page,
|
|
@@ -1774,7 +1779,8 @@ return { cleared: removed > 0, removed: removed };
|
|
|
1774
1779
|
1,
|
|
1775
1780
|
context,
|
|
1776
1781
|
maxCandidates,
|
|
1777
|
-
exact.truncated
|
|
1782
|
+
exact.truncated,
|
|
1783
|
+
occurrenceLimit
|
|
1778
1784
|
);
|
|
1779
1785
|
}
|
|
1780
1786
|
}
|
|
@@ -1784,7 +1790,12 @@ return { cleared: removed > 0, removed: removed };
|
|
|
1784
1790
|
for (const variant of quoteVariants) {
|
|
1785
1791
|
const quoteCanonical2 = canonicalizeEvidenceText(variant);
|
|
1786
1792
|
if (!quoteCanonical2.text) continue;
|
|
1787
|
-
const found = normalizedCandidates(
|
|
1793
|
+
const found = normalizedCandidates(
|
|
1794
|
+
page,
|
|
1795
|
+
pageCanonical,
|
|
1796
|
+
quoteCanonical2,
|
|
1797
|
+
occurrenceLimit
|
|
1798
|
+
);
|
|
1788
1799
|
normalizedTruncated = normalizedTruncated || found.truncated;
|
|
1789
1800
|
normalizedSpans.push(...found.spans);
|
|
1790
1801
|
}
|
|
@@ -1797,7 +1808,8 @@ return { cleared: removed > 0, removed: removed };
|
|
|
1797
1808
|
0.99,
|
|
1798
1809
|
context,
|
|
1799
1810
|
maxCandidates,
|
|
1800
|
-
normalizedTruncated
|
|
1811
|
+
normalizedTruncated,
|
|
1812
|
+
occurrenceLimit
|
|
1801
1813
|
);
|
|
1802
1814
|
if (outcome.status !== "not_found") return outcome;
|
|
1803
1815
|
}
|
|
@@ -1814,12 +1826,12 @@ return { cleared: removed > 0, removed: removed };
|
|
|
1814
1826
|
maxCandidates
|
|
1815
1827
|
);
|
|
1816
1828
|
}
|
|
1817
|
-
function exactCandidates(page, quote) {
|
|
1818
|
-
return findAll(page, quote,
|
|
1829
|
+
function exactCandidates(page, quote, limit) {
|
|
1830
|
+
return findAll(page, quote, limit);
|
|
1819
1831
|
}
|
|
1820
|
-
function normalizedCandidates(page, canonical, quoteCanonical) {
|
|
1832
|
+
function normalizedCandidates(page, canonical, quoteCanonical, limit) {
|
|
1821
1833
|
const quoteLength = quoteCanonical.text.length;
|
|
1822
|
-
const found = findAll(canonical.text, quoteCanonical.text,
|
|
1834
|
+
const found = findAll(canonical.text, quoteCanonical.text, limit);
|
|
1823
1835
|
const quoteFold = maxFold(quoteCanonical, 0, quoteLength);
|
|
1824
1836
|
const seen = /* @__PURE__ */ new Map();
|
|
1825
1837
|
for (const canonicalStart of found.starts) {
|
|
@@ -1857,7 +1869,7 @@ return { cleared: removed > 0, removed: removed };
|
|
|
1857
1869
|
}
|
|
1858
1870
|
return [...seen.values()];
|
|
1859
1871
|
}
|
|
1860
|
-
function resolveOccurrences(page, spans, method, confidence, context, maxCandidates, occurrencesTruncated
|
|
1872
|
+
function resolveOccurrences(page, spans, method, confidence, context, maxCandidates, occurrencesTruncated, occurrenceLimit) {
|
|
1861
1873
|
const candidates = spans.map(
|
|
1862
1874
|
(span) => candidateFor(
|
|
1863
1875
|
page,
|
|
@@ -1868,18 +1880,23 @@ return { cleared: removed > 0, removed: removed };
|
|
|
1868
1880
|
)
|
|
1869
1881
|
);
|
|
1870
1882
|
if (candidates.length === 1) {
|
|
1871
|
-
return {
|
|
1872
|
-
|
|
1873
|
-
|
|
1874
|
-
|
|
1875
|
-
|
|
1876
|
-
|
|
1877
|
-
`Found at least ${MAX_OCCURRENCES} matching passages and stopped counting at ${MAX_OCCURRENCES}. Supply a longer, more distinctive quote; no passage was highlighted.`,
|
|
1878
|
-
MAX_OCCURRENCES,
|
|
1879
|
-
true
|
|
1880
|
-
);
|
|
1883
|
+
return {
|
|
1884
|
+
status: "matched",
|
|
1885
|
+
candidate: candidates[0],
|
|
1886
|
+
occurrences: 1,
|
|
1887
|
+
...occurrencesTruncated ? { occurrencesTruncated: true } : {}
|
|
1888
|
+
};
|
|
1881
1889
|
}
|
|
1882
1890
|
if (!context) {
|
|
1891
|
+
if (occurrencesTruncated) {
|
|
1892
|
+
return ambiguousOutcome(
|
|
1893
|
+
candidates,
|
|
1894
|
+
maxCandidates,
|
|
1895
|
+
`Found at least ${occurrenceLimit} matching passages and stopped counting at ${occurrenceLimit}. Supply a longer, more distinctive quote or nearby context; no passage was highlighted.`,
|
|
1896
|
+
occurrenceLimit,
|
|
1897
|
+
true
|
|
1898
|
+
);
|
|
1899
|
+
}
|
|
1883
1900
|
return ambiguousOutcome(
|
|
1884
1901
|
candidates,
|
|
1885
1902
|
maxCandidates,
|
|
@@ -1902,14 +1919,16 @@ return { cleared: removed > 0, removed: removed };
|
|
|
1902
1919
|
method: "context",
|
|
1903
1920
|
confidence: Math.min(0.95, best.confidence)
|
|
1904
1921
|
},
|
|
1905
|
-
occurrences: candidates.length
|
|
1922
|
+
occurrences: candidates.length,
|
|
1923
|
+
...occurrencesTruncated ? { occurrencesTruncated: true } : {}
|
|
1906
1924
|
};
|
|
1907
1925
|
}
|
|
1908
1926
|
return ambiguousOutcome(
|
|
1909
1927
|
ranked,
|
|
1910
1928
|
maxCandidates,
|
|
1911
|
-
`Found ${candidates.length} matching passages and the supplied context did not clearly select one. No passage was highlighted.`,
|
|
1912
|
-
candidates.length
|
|
1929
|
+
occurrencesTruncated ? `Found at least ${occurrenceLimit} matching passages and scored the first ${occurrenceLimit}, but the supplied context did not clearly select one. No passage was highlighted.` : `Found ${candidates.length} matching passages and the supplied context did not clearly select one. No passage was highlighted.`,
|
|
1930
|
+
occurrencesTruncated ? occurrenceLimit : candidates.length,
|
|
1931
|
+
occurrencesTruncated
|
|
1913
1932
|
);
|
|
1914
1933
|
}
|
|
1915
1934
|
function ambiguousOutcome(candidates, maxCandidates, message, occurrences, occurrencesTruncated = false) {
|
|
@@ -1971,27 +1990,29 @@ return { cleared: removed > 0, removed: removed };
|
|
|
1971
1990
|
if (candidates.length === 0) {
|
|
1972
1991
|
return {
|
|
1973
1992
|
status: "not_found",
|
|
1974
|
-
message:
|
|
1993
|
+
message: `No passage matching the quote was found on the page. No candidate reached the ${Math.round(
|
|
1994
|
+
MIN_FUZZY_PLAUSIBILITY * 100
|
|
1995
|
+
)}% plausibility floor for a paraphrase (required confidence ${Math.round(threshold * 100)}%). No passage was highlighted.`
|
|
1975
1996
|
};
|
|
1976
1997
|
}
|
|
1977
1998
|
const distinct = dedupeCandidates(candidates);
|
|
1978
1999
|
const best = distinct[0];
|
|
1979
2000
|
if (best.confidence < threshold) {
|
|
1980
|
-
|
|
2001
|
+
const bestPercent = Math.round(best.confidence * 100);
|
|
2002
|
+
const thresholdPercent = Math.round(threshold * 100);
|
|
2003
|
+
if (best.confidence >= MIN_FUZZY_PLAUSIBILITY) {
|
|
1981
2004
|
return {
|
|
1982
2005
|
status: "low_confidence",
|
|
1983
2006
|
candidate: best,
|
|
1984
2007
|
threshold,
|
|
1985
|
-
message: `The closest passage matched at ${
|
|
1986
|
-
best.confidence * 100
|
|
1987
|
-
)}%, below the required ${Math.round(
|
|
1988
|
-
threshold * 100
|
|
1989
|
-
)}%. No passage was highlighted.`
|
|
2008
|
+
message: `The closest passage matched at ${bestPercent}%, below the required ${thresholdPercent}% confidence. No passage was highlighted.`
|
|
1990
2009
|
};
|
|
1991
2010
|
}
|
|
1992
2011
|
return {
|
|
1993
2012
|
status: "not_found",
|
|
1994
|
-
message:
|
|
2013
|
+
message: `The closest passage matched at ${bestPercent}%, below the ${Math.round(
|
|
2014
|
+
MIN_FUZZY_PLAUSIBILITY * 100
|
|
2015
|
+
)}% plausibility floor for a paraphrase and the required ${thresholdPercent}% confidence, so the quote was treated as not found on the page. No passage was highlighted.`
|
|
1995
2016
|
};
|
|
1996
2017
|
}
|
|
1997
2018
|
const runnerUp = distinct.find(
|
|
@@ -2141,25 +2162,42 @@ return { cleared: removed > 0, removed: removed };
|
|
|
2141
2162
|
const uniqueContext = [...new Set(contextTokens)];
|
|
2142
2163
|
const contextBigrams = bigramsOf(contextTokens);
|
|
2143
2164
|
for (const candidate of candidates) {
|
|
2144
|
-
const
|
|
2145
|
-
|
|
2146
|
-
|
|
2147
|
-
|
|
2148
|
-
).text;
|
|
2149
|
-
const
|
|
2165
|
+
const before = tokensOf(
|
|
2166
|
+
canonicalizeEvidenceText(
|
|
2167
|
+
page.slice(Math.max(0, candidate.start - CONTEXT_BEFORE), candidate.start)
|
|
2168
|
+
).text
|
|
2169
|
+
).map((token) => token.text);
|
|
2170
|
+
const after = tokensOf(
|
|
2171
|
+
canonicalizeEvidenceText(
|
|
2172
|
+
page.slice(candidate.end, Math.min(page.length, candidate.end + CONTEXT_AFTER))
|
|
2173
|
+
).text
|
|
2174
|
+
).map((token) => token.text);
|
|
2175
|
+
const windowTokens = [...before, ...after];
|
|
2150
2176
|
const windowSet = new Set(windowTokens);
|
|
2151
2177
|
let tokenHits = 0;
|
|
2178
|
+
let proximityHits = 0;
|
|
2152
2179
|
for (const token of uniqueContext) {
|
|
2153
2180
|
if (windowSet.has(token)) tokenHits += 1;
|
|
2181
|
+
let distance = Number.POSITIVE_INFINITY;
|
|
2182
|
+
const beforeIndex = before.lastIndexOf(token);
|
|
2183
|
+
if (beforeIndex >= 0) distance = before.length - beforeIndex;
|
|
2184
|
+
const afterIndex = after.indexOf(token);
|
|
2185
|
+
if (afterIndex >= 0) distance = Math.min(distance, afterIndex + 1);
|
|
2186
|
+
if (distance !== Number.POSITIVE_INFINITY) {
|
|
2187
|
+
proximityHits += 1 / (1 + (distance - 1) / CONTEXT_PROXIMITY_DECAY);
|
|
2188
|
+
}
|
|
2154
2189
|
}
|
|
2155
2190
|
const tokenScore = uniqueContext.length ? tokenHits / uniqueContext.length : 0;
|
|
2191
|
+
const proximityScore = uniqueContext.length ? proximityHits / uniqueContext.length : 0;
|
|
2156
2192
|
const windowBigrams = bigramsOf(windowTokens);
|
|
2157
2193
|
let bigramHits = 0;
|
|
2158
2194
|
for (const bigram of contextBigrams) {
|
|
2159
2195
|
if (windowBigrams.has(bigram)) bigramHits += 1;
|
|
2160
2196
|
}
|
|
2161
2197
|
const bigramScore = contextBigrams.size ? bigramHits / contextBigrams.size : 0;
|
|
2162
|
-
candidate.contextScore = round(
|
|
2198
|
+
candidate.contextScore = round(
|
|
2199
|
+
tokenScore * 0.45 + bigramScore * 0.3 + proximityScore * 0.25
|
|
2200
|
+
);
|
|
2163
2201
|
}
|
|
2164
2202
|
}
|
|
2165
2203
|
function bigramsOf(tokens) {
|
|
@@ -2296,6 +2334,378 @@ return { cleared: removed > 0, removed: removed };
|
|
|
2296
2334
|
return Math.min(maximum, Math.max(minimum, Math.trunc(value)));
|
|
2297
2335
|
}
|
|
2298
2336
|
|
|
2337
|
+
// src/shared/url-policy.ts
|
|
2338
|
+
function normalizeWebUrl(input) {
|
|
2339
|
+
const trimmed = String(input ?? "").trim();
|
|
2340
|
+
if (!trimmed) return null;
|
|
2341
|
+
const candidate = /^[a-z][a-z0-9+.-]*:/i.test(trimmed) ? trimmed : `https://${trimmed}`;
|
|
2342
|
+
try {
|
|
2343
|
+
const parsed = new URL(candidate);
|
|
2344
|
+
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
|
|
2345
|
+
return null;
|
|
2346
|
+
}
|
|
2347
|
+
if (!parsed.hostname) return null;
|
|
2348
|
+
return parsed;
|
|
2349
|
+
} catch {
|
|
2350
|
+
return null;
|
|
2351
|
+
}
|
|
2352
|
+
}
|
|
2353
|
+
function normalizeDomainEntry(entry) {
|
|
2354
|
+
return String(entry ?? "").trim().toLowerCase().replace(/^\*\./, "").replace(/^\.+/, "").replace(/\.+$/, "");
|
|
2355
|
+
}
|
|
2356
|
+
function normalizeDomainList(entries) {
|
|
2357
|
+
return (entries ?? []).map(normalizeDomainEntry).filter((entry) => entry.length > 0);
|
|
2358
|
+
}
|
|
2359
|
+
function hostOf(url) {
|
|
2360
|
+
const parsed = normalizeWebUrl(url);
|
|
2361
|
+
return parsed ? parsed.hostname.toLowerCase().replace(/\.+$/, "") : null;
|
|
2362
|
+
}
|
|
2363
|
+
function isUrlAllowed(url, allowedDomains) {
|
|
2364
|
+
const configured = allowedDomains ?? [];
|
|
2365
|
+
if (configured.length === 0) return true;
|
|
2366
|
+
const host = hostOf(url);
|
|
2367
|
+
if (!host) return false;
|
|
2368
|
+
const list = normalizeDomainList(configured);
|
|
2369
|
+
return list.some((entry) => host === entry || host.endsWith(`.${entry}`));
|
|
2370
|
+
}
|
|
2371
|
+
|
|
2372
|
+
// src/bridge/tab-activation.ts
|
|
2373
|
+
var DEFAULT_TAB_ACTIVATION_OPTIONS = {
|
|
2374
|
+
attempts: 6,
|
|
2375
|
+
pollMs: 60,
|
|
2376
|
+
workspaceTimeoutMs: 1500,
|
|
2377
|
+
workspacePollMs: 50,
|
|
2378
|
+
focusChecks: 4,
|
|
2379
|
+
focusPollMs: 50
|
|
2380
|
+
};
|
|
2381
|
+
function sleep(ms) {
|
|
2382
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
2383
|
+
}
|
|
2384
|
+
function clampInt(value, min, max, fallback) {
|
|
2385
|
+
const number = Number(value);
|
|
2386
|
+
if (!Number.isFinite(number)) return fallback;
|
|
2387
|
+
return Math.min(max, Math.max(min, Math.floor(number)));
|
|
2388
|
+
}
|
|
2389
|
+
function resolveOptions(options) {
|
|
2390
|
+
return {
|
|
2391
|
+
attempts: clampInt(
|
|
2392
|
+
options.attempts,
|
|
2393
|
+
1,
|
|
2394
|
+
20,
|
|
2395
|
+
DEFAULT_TAB_ACTIVATION_OPTIONS.attempts
|
|
2396
|
+
),
|
|
2397
|
+
pollMs: clampInt(
|
|
2398
|
+
options.pollMs,
|
|
2399
|
+
1,
|
|
2400
|
+
1e3,
|
|
2401
|
+
DEFAULT_TAB_ACTIVATION_OPTIONS.pollMs
|
|
2402
|
+
),
|
|
2403
|
+
workspaceTimeoutMs: clampInt(
|
|
2404
|
+
options.workspaceTimeoutMs,
|
|
2405
|
+
0,
|
|
2406
|
+
1e4,
|
|
2407
|
+
DEFAULT_TAB_ACTIVATION_OPTIONS.workspaceTimeoutMs
|
|
2408
|
+
),
|
|
2409
|
+
workspacePollMs: clampInt(
|
|
2410
|
+
options.workspacePollMs,
|
|
2411
|
+
1,
|
|
2412
|
+
1e3,
|
|
2413
|
+
DEFAULT_TAB_ACTIVATION_OPTIONS.workspacePollMs
|
|
2414
|
+
),
|
|
2415
|
+
focusChecks: clampInt(
|
|
2416
|
+
options.focusChecks,
|
|
2417
|
+
1,
|
|
2418
|
+
10,
|
|
2419
|
+
DEFAULT_TAB_ACTIVATION_OPTIONS.focusChecks
|
|
2420
|
+
),
|
|
2421
|
+
focusPollMs: clampInt(
|
|
2422
|
+
options.focusPollMs,
|
|
2423
|
+
0,
|
|
2424
|
+
1e3,
|
|
2425
|
+
DEFAULT_TAB_ACTIVATION_OPTIONS.focusPollMs
|
|
2426
|
+
)
|
|
2427
|
+
};
|
|
2428
|
+
}
|
|
2429
|
+
function spaceIdOf(tab) {
|
|
2430
|
+
try {
|
|
2431
|
+
return tab.getAttribute?.("zen-workspace-id") || null;
|
|
2432
|
+
} catch {
|
|
2433
|
+
return null;
|
|
2434
|
+
}
|
|
2435
|
+
}
|
|
2436
|
+
function errorMessage(error) {
|
|
2437
|
+
return String(error?.message ?? error);
|
|
2438
|
+
}
|
|
2439
|
+
async function waitForWorkspace(manager, target, timeoutMs, pollMs) {
|
|
2440
|
+
const deadline = Date.now() + timeoutMs;
|
|
2441
|
+
for (; ; ) {
|
|
2442
|
+
if (manager.activeWorkspace === target) return true;
|
|
2443
|
+
const remaining = deadline - Date.now();
|
|
2444
|
+
if (remaining <= 0) return false;
|
|
2445
|
+
await sleep(Math.min(pollMs, remaining));
|
|
2446
|
+
}
|
|
2447
|
+
}
|
|
2448
|
+
function probeWindowFocus(win) {
|
|
2449
|
+
try {
|
|
2450
|
+
const hasFocus = win.document?.hasFocus;
|
|
2451
|
+
if (typeof hasFocus === "function") {
|
|
2452
|
+
return hasFocus.call(win.document) === true;
|
|
2453
|
+
}
|
|
2454
|
+
} catch {
|
|
2455
|
+
}
|
|
2456
|
+
try {
|
|
2457
|
+
if (typeof Services !== "undefined" && Services?.focus) {
|
|
2458
|
+
return Services.focus.activeWindow === win;
|
|
2459
|
+
}
|
|
2460
|
+
} catch {
|
|
2461
|
+
}
|
|
2462
|
+
return typeof win.focused === "boolean" ? win.focused : void 0;
|
|
2463
|
+
}
|
|
2464
|
+
async function observeWindowFocus(win, options) {
|
|
2465
|
+
for (let check = 0; check < options.focusChecks; check += 1) {
|
|
2466
|
+
const observed = probeWindowFocus(win);
|
|
2467
|
+
if (observed === void 0) return void 0;
|
|
2468
|
+
if (observed) return true;
|
|
2469
|
+
if (check + 1 < options.focusChecks && options.focusPollMs > 0) {
|
|
2470
|
+
await sleep(options.focusPollMs);
|
|
2471
|
+
}
|
|
2472
|
+
}
|
|
2473
|
+
return false;
|
|
2474
|
+
}
|
|
2475
|
+
async function activateTab(win, tab, options = {}) {
|
|
2476
|
+
const settings = resolveOptions(options);
|
|
2477
|
+
const spaceId = spaceIdOf(tab);
|
|
2478
|
+
const manager = win.gZenWorkspaces ?? null;
|
|
2479
|
+
if (spaceId && manager && typeof manager.changeWorkspaceWithID === "function" && manager.activeWorkspace !== spaceId) {
|
|
2480
|
+
await manager.changeWorkspaceWithID(spaceId);
|
|
2481
|
+
await waitForWorkspace(
|
|
2482
|
+
manager,
|
|
2483
|
+
spaceId,
|
|
2484
|
+
settings.workspaceTimeoutMs,
|
|
2485
|
+
settings.workspacePollMs
|
|
2486
|
+
);
|
|
2487
|
+
}
|
|
2488
|
+
let attempts = 0;
|
|
2489
|
+
let lastError;
|
|
2490
|
+
while (attempts < settings.attempts) {
|
|
2491
|
+
attempts += 1;
|
|
2492
|
+
try {
|
|
2493
|
+
win.gBrowser.selectedTab = tab;
|
|
2494
|
+
lastError = void 0;
|
|
2495
|
+
} catch (error) {
|
|
2496
|
+
lastError = errorMessage(error);
|
|
2497
|
+
}
|
|
2498
|
+
await sleep(settings.pollMs);
|
|
2499
|
+
if (tab.selected === true) break;
|
|
2500
|
+
}
|
|
2501
|
+
const active = tab.selected === true;
|
|
2502
|
+
const outcome = { active, spaceId, attempts };
|
|
2503
|
+
if (lastError) outcome.lastError = lastError;
|
|
2504
|
+
if (!active) return outcome;
|
|
2505
|
+
try {
|
|
2506
|
+
tab.scrollIntoView?.({ block: "nearest" });
|
|
2507
|
+
} catch {
|
|
2508
|
+
}
|
|
2509
|
+
if (options.focusWindow === true) {
|
|
2510
|
+
const focused = await focusWindowAndObserve(win, options);
|
|
2511
|
+
if (focused !== void 0) outcome.windowFocused = focused;
|
|
2512
|
+
}
|
|
2513
|
+
return outcome;
|
|
2514
|
+
}
|
|
2515
|
+
async function focusWindowAndObserve(win, options = {}) {
|
|
2516
|
+
try {
|
|
2517
|
+
win.focus?.();
|
|
2518
|
+
} catch {
|
|
2519
|
+
return false;
|
|
2520
|
+
}
|
|
2521
|
+
return observeWindowFocus(win, resolveOptions(options));
|
|
2522
|
+
}
|
|
2523
|
+
|
|
2524
|
+
// src/bridge/essentials-state.ts
|
|
2525
|
+
var ESSENTIALS_STATE_LIMIT = 20;
|
|
2526
|
+
var EssentialsStateStore = class {
|
|
2527
|
+
limit;
|
|
2528
|
+
#entries = /* @__PURE__ */ new Map();
|
|
2529
|
+
constructor(limit = ESSENTIALS_STATE_LIMIT) {
|
|
2530
|
+
const normalized = Math.floor(Number(limit));
|
|
2531
|
+
this.limit = Number.isFinite(normalized) && normalized > 0 ? normalized : ESSENTIALS_STATE_LIMIT;
|
|
2532
|
+
}
|
|
2533
|
+
get size() {
|
|
2534
|
+
return this.#entries.size;
|
|
2535
|
+
}
|
|
2536
|
+
/** Stores the state unless this tab already has a capture. */
|
|
2537
|
+
capture(tabId, state) {
|
|
2538
|
+
const existing = this.#entries.get(tabId);
|
|
2539
|
+
if (existing) return existing;
|
|
2540
|
+
const capture = {
|
|
2541
|
+
tabId,
|
|
2542
|
+
spaceId: state.spaceId,
|
|
2543
|
+
pinned: state.pinned
|
|
2544
|
+
};
|
|
2545
|
+
this.#entries.set(tabId, capture);
|
|
2546
|
+
while (this.#entries.size > this.limit) {
|
|
2547
|
+
const oldest = this.#entries.keys().next().value;
|
|
2548
|
+
if (oldest === void 0) break;
|
|
2549
|
+
this.#entries.delete(oldest);
|
|
2550
|
+
}
|
|
2551
|
+
return capture;
|
|
2552
|
+
}
|
|
2553
|
+
get(tabId) {
|
|
2554
|
+
return this.#entries.get(tabId);
|
|
2555
|
+
}
|
|
2556
|
+
/** Removes and returns a capture; used when a tab leaves essentials. */
|
|
2557
|
+
take(tabId) {
|
|
2558
|
+
const capture = this.#entries.get(tabId);
|
|
2559
|
+
if (capture) this.#entries.delete(tabId);
|
|
2560
|
+
return capture;
|
|
2561
|
+
}
|
|
2562
|
+
clear() {
|
|
2563
|
+
this.#entries.clear();
|
|
2564
|
+
}
|
|
2565
|
+
};
|
|
2566
|
+
function readEssentialsTabState(tab) {
|
|
2567
|
+
const spaceId = tab.getAttribute("zen-workspace-id") || null;
|
|
2568
|
+
return { spaceId, pinned: !!tab.pinned };
|
|
2569
|
+
}
|
|
2570
|
+
function captureEssentialsState(store, tabId, tab) {
|
|
2571
|
+
return store.capture(tabId, readEssentialsTabState(tab));
|
|
2572
|
+
}
|
|
2573
|
+
var CLOSED_REASON = "closed before its previous state could be restored";
|
|
2574
|
+
var SPACE_REASON = "could not be returned to its original space";
|
|
2575
|
+
var MOVE_REASON = "had an error while moving back to its original space";
|
|
2576
|
+
var PIN_REASON = "could not have its pinned state restored";
|
|
2577
|
+
function isTabGone(tab) {
|
|
2578
|
+
return tab.isConnected === false || tab.closing === true;
|
|
2579
|
+
}
|
|
2580
|
+
function addReasons(target, reasons) {
|
|
2581
|
+
for (const reason of reasons) {
|
|
2582
|
+
if (!target.includes(reason)) target.push(reason);
|
|
2583
|
+
}
|
|
2584
|
+
}
|
|
2585
|
+
function verifyEssentialsState(capture, tab, options = {}) {
|
|
2586
|
+
if (!capture) {
|
|
2587
|
+
return { spaceRestored: true, pinnedRestored: true, reasons: [] };
|
|
2588
|
+
}
|
|
2589
|
+
if (isTabGone(tab)) {
|
|
2590
|
+
return {
|
|
2591
|
+
spaceRestored: false,
|
|
2592
|
+
pinnedRestored: false,
|
|
2593
|
+
reasons: [CLOSED_REASON]
|
|
2594
|
+
};
|
|
2595
|
+
}
|
|
2596
|
+
const reasons = [];
|
|
2597
|
+
const spaceId = tab.getAttribute("zen-workspace-id") || null;
|
|
2598
|
+
const spaceRestored = capture.spaceId === null || spaceId === capture.spaceId;
|
|
2599
|
+
if (!spaceRestored) reasons.push(SPACE_REASON);
|
|
2600
|
+
const pinnedRestored = options.restorePinned === false || !!tab.pinned === capture.pinned;
|
|
2601
|
+
if (!pinnedRestored) reasons.push(PIN_REASON);
|
|
2602
|
+
return { spaceRestored, pinnedRestored, reasons };
|
|
2603
|
+
}
|
|
2604
|
+
function restoreEssentialsState(capture, tab, host, options = {}) {
|
|
2605
|
+
if (!capture) {
|
|
2606
|
+
return {
|
|
2607
|
+
applied: false,
|
|
2608
|
+
skipped: false,
|
|
2609
|
+
spaceRestored: true,
|
|
2610
|
+
pinnedRestored: true,
|
|
2611
|
+
reasons: []
|
|
2612
|
+
};
|
|
2613
|
+
}
|
|
2614
|
+
if (isTabGone(tab)) {
|
|
2615
|
+
return {
|
|
2616
|
+
applied: false,
|
|
2617
|
+
skipped: true,
|
|
2618
|
+
spaceRestored: false,
|
|
2619
|
+
pinnedRestored: false,
|
|
2620
|
+
reasons: [CLOSED_REASON]
|
|
2621
|
+
};
|
|
2622
|
+
}
|
|
2623
|
+
const reasons = [];
|
|
2624
|
+
if (capture.spaceId !== null) {
|
|
2625
|
+
const currentSpace = tab.getAttribute("zen-workspace-id") || null;
|
|
2626
|
+
if (currentSpace !== capture.spaceId) {
|
|
2627
|
+
tab.setAttribute("zen-workspace-id", capture.spaceId);
|
|
2628
|
+
if (typeof host.moveTabsToWorkspace === "function") {
|
|
2629
|
+
try {
|
|
2630
|
+
host.moveTabsToWorkspace([tab], capture.spaceId);
|
|
2631
|
+
} catch {
|
|
2632
|
+
reasons.push(MOVE_REASON);
|
|
2633
|
+
}
|
|
2634
|
+
}
|
|
2635
|
+
}
|
|
2636
|
+
}
|
|
2637
|
+
if (options.restorePinned !== false && !!tab.pinned !== capture.pinned) {
|
|
2638
|
+
const handler = capture.pinned ? host.pinTab : host.unpinTab;
|
|
2639
|
+
if (typeof handler === "function") {
|
|
2640
|
+
try {
|
|
2641
|
+
handler.call(host, tab);
|
|
2642
|
+
} catch {
|
|
2643
|
+
reasons.push(PIN_REASON);
|
|
2644
|
+
}
|
|
2645
|
+
} else {
|
|
2646
|
+
reasons.push(PIN_REASON);
|
|
2647
|
+
}
|
|
2648
|
+
}
|
|
2649
|
+
const verification = verifyEssentialsState(capture, tab, options);
|
|
2650
|
+
addReasons(reasons, verification.reasons);
|
|
2651
|
+
return {
|
|
2652
|
+
applied: true,
|
|
2653
|
+
skipped: false,
|
|
2654
|
+
spaceRestored: verification.spaceRestored,
|
|
2655
|
+
pinnedRestored: verification.pinnedRestored,
|
|
2656
|
+
reasons
|
|
2657
|
+
};
|
|
2658
|
+
}
|
|
2659
|
+
|
|
2660
|
+
// src/bridge/split-cleanup.ts
|
|
2661
|
+
function normalizeSplitUrl(url) {
|
|
2662
|
+
const lowered = String(url ?? "").trim().toLowerCase();
|
|
2663
|
+
if (!lowered) return "";
|
|
2664
|
+
const withoutHash = lowered.split("#")[0] ?? "";
|
|
2665
|
+
return withoutHash.endsWith("/") ? withoutHash.slice(0, -1) : withoutHash;
|
|
2666
|
+
}
|
|
2667
|
+
function isSyntheticSplitTab(tab) {
|
|
2668
|
+
if (tab.empty === true) return true;
|
|
2669
|
+
const url = String(tab.url ?? "").trim().toLowerCase().split("#")[0] ?? "";
|
|
2670
|
+
return url === "" || url === "about:newtab" || url === "about:blank";
|
|
2671
|
+
}
|
|
2672
|
+
function planSplitCleanup(input, candidates) {
|
|
2673
|
+
const before = new Set(input.beforeTabIds ?? []);
|
|
2674
|
+
const groupUrls = new Set(
|
|
2675
|
+
(input.groupUrls ?? []).map(normalizeSplitUrl).filter(Boolean)
|
|
2676
|
+
);
|
|
2677
|
+
const closeTabIds = [];
|
|
2678
|
+
const duplicates = [];
|
|
2679
|
+
const newTabIds = [];
|
|
2680
|
+
for (const tab of candidates ?? []) {
|
|
2681
|
+
if (!tab?.id) continue;
|
|
2682
|
+
if (input.windowId !== void 0 && tab.windowId !== void 0 && tab.windowId !== input.windowId) {
|
|
2683
|
+
continue;
|
|
2684
|
+
}
|
|
2685
|
+
if (before.has(tab.id)) continue;
|
|
2686
|
+
newTabIds.push(tab.id);
|
|
2687
|
+
if (isSyntheticSplitTab(tab)) {
|
|
2688
|
+
closeTabIds.push(tab.id);
|
|
2689
|
+
continue;
|
|
2690
|
+
}
|
|
2691
|
+
const key = normalizeSplitUrl(tab.url);
|
|
2692
|
+
if (key && groupUrls.has(key)) {
|
|
2693
|
+
duplicates.push({ tabId: tab.id, title: tab.title, url: tab.url });
|
|
2694
|
+
}
|
|
2695
|
+
}
|
|
2696
|
+
let limitation;
|
|
2697
|
+
if (duplicates.length > 0) {
|
|
2698
|
+
const listed = duplicates.map((duplicate) => `"${duplicate.title}" (${duplicate.tabId})`).join(", ");
|
|
2699
|
+
limitation = `Left ${duplicates.length} new tab${duplicates.length === 1 ? "" : "s"} open because they duplicate the split: ${listed}. Close them manually if they were not opened by the user.`;
|
|
2700
|
+
}
|
|
2701
|
+
return {
|
|
2702
|
+
closeTabIds,
|
|
2703
|
+
duplicates,
|
|
2704
|
+
newTabIds,
|
|
2705
|
+
...limitation ? { limitation } : {}
|
|
2706
|
+
};
|
|
2707
|
+
}
|
|
2708
|
+
|
|
2299
2709
|
// src/bridge/ops.ts
|
|
2300
2710
|
var MAX_TABS_PER_OPEN = 30;
|
|
2301
2711
|
var MAX_RESULTS = 100;
|
|
@@ -2308,6 +2718,9 @@ return { cleared: removed > 0, removed: removed };
|
|
|
2308
2718
|
var EVIDENCE_MAX_TEXT = 6e5;
|
|
2309
2719
|
var EVIDENCE_HIGHLIGHT_MS = 2e4;
|
|
2310
2720
|
var EVIDENCE_MAX_ATTEMPTS = 3;
|
|
2721
|
+
var LAYOUT_SETTLE_MS = 120;
|
|
2722
|
+
var SPLIT_CLOSE_TIMEOUT_MS = 1e3;
|
|
2723
|
+
var SPLIT_CLOSE_POLL_MS = 100;
|
|
2311
2724
|
function isHttpUrl(url) {
|
|
2312
2725
|
try {
|
|
2313
2726
|
const scheme = new URL(url).protocol;
|
|
@@ -2331,9 +2744,59 @@ return { cleared: removed > 0, removed: removed };
|
|
|
2331
2744
|
return true;
|
|
2332
2745
|
}
|
|
2333
2746
|
}
|
|
2334
|
-
function
|
|
2747
|
+
function sleep2(ms) {
|
|
2335
2748
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
2336
2749
|
}
|
|
2750
|
+
var GLANCE_SETTLE_MS = 1e4;
|
|
2751
|
+
var GLANCE_POLL_MS = 50;
|
|
2752
|
+
function isGlanceTab(result) {
|
|
2753
|
+
return typeof result === "object" && result !== null && "linkedBrowser" in result;
|
|
2754
|
+
}
|
|
2755
|
+
function glanceUrlOf(result) {
|
|
2756
|
+
const browser = result?.linkedBrowser;
|
|
2757
|
+
const spec = browser?.currentURI?.spec;
|
|
2758
|
+
if (typeof spec !== "string" || !spec || spec === "about:blank") {
|
|
2759
|
+
return void 0;
|
|
2760
|
+
}
|
|
2761
|
+
return spec;
|
|
2762
|
+
}
|
|
2763
|
+
async function waitForGlanceUrl(result) {
|
|
2764
|
+
const deadline = Date.now() + GLANCE_SETTLE_MS;
|
|
2765
|
+
let observed = glanceUrlOf(result);
|
|
2766
|
+
while (!observed && Date.now() < deadline) {
|
|
2767
|
+
await sleep2(GLANCE_POLL_MS);
|
|
2768
|
+
observed = glanceUrlOf(result);
|
|
2769
|
+
}
|
|
2770
|
+
return observed;
|
|
2771
|
+
}
|
|
2772
|
+
function watchGlanceRedirects(result, manager, allowedDomains) {
|
|
2773
|
+
const tab = result;
|
|
2774
|
+
const browser = tab?.linkedBrowser;
|
|
2775
|
+
if (typeof browser?.addEventListener !== "function") return;
|
|
2776
|
+
function stop() {
|
|
2777
|
+
try {
|
|
2778
|
+
browser?.removeEventListener?.("locationchange", check, true);
|
|
2779
|
+
tab?.removeEventListener?.("GlanceClose", stop, true);
|
|
2780
|
+
} catch {
|
|
2781
|
+
}
|
|
2782
|
+
}
|
|
2783
|
+
function check() {
|
|
2784
|
+
const current = glanceUrlOf(result);
|
|
2785
|
+
if (!current) return;
|
|
2786
|
+
const target = normalizeWebUrl(current);
|
|
2787
|
+
if (target && isUrlAllowed(target.href, allowedDomains)) return;
|
|
2788
|
+
stop();
|
|
2789
|
+
try {
|
|
2790
|
+
manager.closeGlance?.({ noAnimation: true, skipPermitUnload: true });
|
|
2791
|
+
} catch {
|
|
2792
|
+
}
|
|
2793
|
+
}
|
|
2794
|
+
try {
|
|
2795
|
+
browser.addEventListener("locationchange", check, true);
|
|
2796
|
+
tab?.addEventListener?.("GlanceClose", stop, true);
|
|
2797
|
+
} catch {
|
|
2798
|
+
}
|
|
2799
|
+
}
|
|
2337
2800
|
var OpsError = class extends Error {
|
|
2338
2801
|
code;
|
|
2339
2802
|
constructor(code, message) {
|
|
@@ -2345,6 +2808,16 @@ return { cleared: removed > 0, removed: removed };
|
|
|
2345
2808
|
const tabIds = /* @__PURE__ */ new WeakMap();
|
|
2346
2809
|
const tabsById = /* @__PURE__ */ new Map();
|
|
2347
2810
|
const evidenceMarkers = /* @__PURE__ */ new Map();
|
|
2811
|
+
const essentialsCaptures = new EssentialsStateStore();
|
|
2812
|
+
const essentialsRestoreHost = () => {
|
|
2813
|
+
const workspaceManager = win.gZenWorkspaces;
|
|
2814
|
+
const browser = win.gBrowser;
|
|
2815
|
+
return {
|
|
2816
|
+
moveTabsToWorkspace: workspaceManager && typeof workspaceManager.moveTabsToWorkspace === "function" ? (tabs, spaceId) => workspaceManager.moveTabsToWorkspace(tabs, spaceId) : void 0,
|
|
2817
|
+
pinTab: browser && typeof browser.pinTab === "function" ? (tab) => browser.pinTab(tab) : void 0,
|
|
2818
|
+
unpinTab: browser && typeof browser.unpinTab === "function" ? (tab) => browser.unpinTab(tab) : void 0
|
|
2819
|
+
};
|
|
2820
|
+
};
|
|
2348
2821
|
const markersFor = (tabId) => evidenceMarkers.get(tabId) ?? [];
|
|
2349
2822
|
const rememberMarkers = (tabId, markers) => {
|
|
2350
2823
|
if (markers.length === 0) {
|
|
@@ -2353,6 +2826,17 @@ return { cleared: removed > 0, removed: removed };
|
|
|
2353
2826
|
}
|
|
2354
2827
|
evidenceMarkers.set(tabId, markers.slice(-20));
|
|
2355
2828
|
};
|
|
2829
|
+
const tabLocks = /* @__PURE__ */ new Map();
|
|
2830
|
+
const serializeTab = (tabId, work) => {
|
|
2831
|
+
const previous = tabLocks.get(tabId) ?? Promise.resolve();
|
|
2832
|
+
const run = previous.then(work, work);
|
|
2833
|
+
tabLocks.set(tabId, run);
|
|
2834
|
+
const release = () => {
|
|
2835
|
+
if (tabLocks.get(tabId) === run) tabLocks.delete(tabId);
|
|
2836
|
+
};
|
|
2837
|
+
void run.then(release, release);
|
|
2838
|
+
return run;
|
|
2839
|
+
};
|
|
2356
2840
|
const idForTab = (tab) => {
|
|
2357
2841
|
let id = tabIds.get(tab);
|
|
2358
2842
|
if (!id) {
|
|
@@ -2367,6 +2851,17 @@ return { cleared: removed > 0, removed: removed };
|
|
|
2367
2851
|
if (!tab.isConnected || tab.closing) tabsById.delete(id);
|
|
2368
2852
|
}
|
|
2369
2853
|
};
|
|
2854
|
+
const waitForSplitGone = async (members, timeoutMs = SPLIT_CLOSE_TIMEOUT_MS) => {
|
|
2855
|
+
const deadline = Date.now() + timeoutMs;
|
|
2856
|
+
const gone = () => members.every(
|
|
2857
|
+
(member) => !member || !member.isConnected || !member.splitView
|
|
2858
|
+
);
|
|
2859
|
+
while (!gone()) {
|
|
2860
|
+
if (Date.now() >= deadline) return false;
|
|
2861
|
+
await sleep2(SPLIT_CLOSE_POLL_MS);
|
|
2862
|
+
}
|
|
2863
|
+
return true;
|
|
2864
|
+
};
|
|
2370
2865
|
const workspaces = () => {
|
|
2371
2866
|
const manager = win.gZenWorkspaces;
|
|
2372
2867
|
if (!manager) {
|
|
@@ -2446,6 +2941,14 @@ return { cleared: removed > 0, removed: removed };
|
|
|
2446
2941
|
};
|
|
2447
2942
|
const containerIdOf = (tab) => Number(tab.userContextId ?? tab.getAttribute("usercontextid") ?? 0) || 0;
|
|
2448
2943
|
const isEssentialTab = (tab) => tab.hasAttribute("zen-essential") || tab.getAttribute("zen-essential") === "true";
|
|
2944
|
+
const describeEssentialsLimitations = (notes) => {
|
|
2945
|
+
if (notes.size === 0) return void 0;
|
|
2946
|
+
return [...notes].map(([tabId, reasons]) => {
|
|
2947
|
+
const tab = tabsById.get(tabId);
|
|
2948
|
+
const label = tab ? `"${tabTitle(tab)}" (${tabId})` : `(${tabId})`;
|
|
2949
|
+
return `The tab ${label} ${[...reasons].join(", ")}.`;
|
|
2950
|
+
}).join(" ");
|
|
2951
|
+
};
|
|
2449
2952
|
const folderOf = (tab) => {
|
|
2450
2953
|
const group = tab.group;
|
|
2451
2954
|
if (!group) return null;
|
|
@@ -2957,19 +3460,34 @@ ${tab.url}`.toLowerCase();
|
|
|
2957
3460
|
"tabs.select": async (params) => {
|
|
2958
3461
|
const [tab] = resolveTabs([String(params?.tabId ?? "")]);
|
|
2959
3462
|
if (!tab) throw new OpsError("tab_not_found", "No tab matched that id");
|
|
2960
|
-
const
|
|
2961
|
-
|
|
2962
|
-
|
|
3463
|
+
const tabId = idForTab(tab);
|
|
3464
|
+
const focusWindow = params?.focusWindow === true;
|
|
3465
|
+
let outcome;
|
|
3466
|
+
try {
|
|
3467
|
+
outcome = await activateTab(win, tab, { focusWindow });
|
|
3468
|
+
} catch (error) {
|
|
3469
|
+
throw new OpsError(
|
|
3470
|
+
"select_failed",
|
|
3471
|
+
`Could not select the tab "${tabTitle(tab)}" (${tabId}): ${String(error?.message ?? error)}`
|
|
3472
|
+
);
|
|
2963
3473
|
}
|
|
2964
|
-
|
|
2965
|
-
|
|
2966
|
-
|
|
2967
|
-
|
|
3474
|
+
if (!outcome.active) {
|
|
3475
|
+
const current = win.gBrowser?.selectedTab;
|
|
3476
|
+
const currentTitle = current && current !== tab ? `"${tabTitle(current)}" (${idForTab(current)})` : "another tab";
|
|
3477
|
+
const detail = outcome.lastError ? ` Last error: ${outcome.lastError}` : "";
|
|
3478
|
+
throw new OpsError(
|
|
3479
|
+
"select_failed",
|
|
3480
|
+
`The tab "${tabTitle(tab)}" (${tabId}) did not become the active tab after ${outcome.attempts} attempt(s); ${currentTitle} is still active.${detail}`
|
|
3481
|
+
);
|
|
2968
3482
|
}
|
|
2969
|
-
|
|
3483
|
+
const result = {
|
|
2970
3484
|
tab: tabInfo(tab, [...realTabs()].indexOf(tab)),
|
|
2971
3485
|
activeSpaceId: spacesEnabled() ? win.gZenWorkspaces.activeWorkspace : null
|
|
2972
3486
|
};
|
|
3487
|
+
if (focusWindow && outcome.windowFocused !== void 0) {
|
|
3488
|
+
result.windowFocused = outcome.windowFocused;
|
|
3489
|
+
}
|
|
3490
|
+
return result;
|
|
2973
3491
|
},
|
|
2974
3492
|
"tabs.pin": (params) => {
|
|
2975
3493
|
const ids = Array.isArray(params?.tabIds) ? params.tabIds : [];
|
|
@@ -3205,186 +3723,92 @@ ${tab.url}`.toLowerCase();
|
|
|
3205
3723
|
"Refusing to search for a quote longer than 20,000 characters."
|
|
3206
3724
|
);
|
|
3207
3725
|
}
|
|
3208
|
-
|
|
3209
|
-
|
|
3210
|
-
|
|
3211
|
-
|
|
3212
|
-
|
|
3213
|
-
|
|
3214
|
-
|
|
3215
|
-
|
|
3216
|
-
|
|
3217
|
-
|
|
3218
|
-
|
|
3219
|
-
|
|
3220
|
-
|
|
3221
|
-
|
|
3222
|
-
|
|
3223
|
-
|
|
3224
|
-
}
|
|
3225
|
-
if (isPdfTab(tab)) {
|
|
3226
|
-
return failed(
|
|
3227
|
-
"UNSUPPORTED_PAGE",
|
|
3228
|
-
"PDF documents render in a viewer that exposes no HTML text, so Evidence Mode cannot locate a quote in them."
|
|
3229
|
-
);
|
|
3230
|
-
}
|
|
3231
|
-
const deadline = Date.now() + EVIDENCE_WAIT_MS;
|
|
3232
|
-
let state = null;
|
|
3233
|
-
let lastError = null;
|
|
3234
|
-
for (; ; ) {
|
|
3235
|
-
try {
|
|
3236
|
-
state = coerceEvidenceState(
|
|
3237
|
-
await runEvidenceScript(tab, buildEvidenceStateScript(), 5e3)
|
|
3726
|
+
return serializeTab(tabId, async () => {
|
|
3727
|
+
const [tab] = resolveTabs([tabId]);
|
|
3728
|
+
const listedUrl = tabUrl(tab);
|
|
3729
|
+
const listedTitle = tabTitle(tab);
|
|
3730
|
+
const failed = (code, message, extra = {}) => ({
|
|
3731
|
+
ok: false,
|
|
3732
|
+
tabId,
|
|
3733
|
+
url: listedUrl,
|
|
3734
|
+
title: listedTitle,
|
|
3735
|
+
...extra,
|
|
3736
|
+
error: { code, message }
|
|
3737
|
+
});
|
|
3738
|
+
if (!isHttpUrl(listedUrl)) {
|
|
3739
|
+
return failed(
|
|
3740
|
+
isPrivilegedUrl(listedUrl) ? "PRIVILEGED_PAGE" : "UNSUPPORTED_PAGE",
|
|
3741
|
+
"Evidence Mode only inspects http(s) pages. Browser-internal pages cannot be read or marked."
|
|
3238
3742
|
);
|
|
3239
|
-
lastError = null;
|
|
3240
|
-
} catch (error) {
|
|
3241
|
-
lastError = error;
|
|
3242
|
-
state = null;
|
|
3243
|
-
}
|
|
3244
|
-
if (state && isHttpUrl(state.url) && state.readyState !== "" && state.readyState !== "loading") {
|
|
3245
|
-
break;
|
|
3246
|
-
}
|
|
3247
|
-
if (Date.now() >= deadline) break;
|
|
3248
|
-
await sleep(EVIDENCE_POLL_MS);
|
|
3249
|
-
}
|
|
3250
|
-
if (!state) {
|
|
3251
|
-
if (lastError instanceof OpsError && lastError.code === "actor_unavailable") {
|
|
3252
|
-
return failed("ACTOR_UNAVAILABLE", lastError.message);
|
|
3253
3743
|
}
|
|
3254
|
-
|
|
3255
|
-
|
|
3256
|
-
|
|
3257
|
-
|
|
3258
|
-
|
|
3259
|
-
if (!state.readyState || state.readyState === "loading") {
|
|
3260
|
-
return failed(
|
|
3261
|
-
"PAGE_STILL_LOADING",
|
|
3262
|
-
`The page "${state.title || listedTitle}" is still loading after ${Math.round(EVIDENCE_WAIT_MS / 1e3)} seconds.`
|
|
3263
|
-
);
|
|
3264
|
-
}
|
|
3265
|
-
if (!isHttpUrl(state.url)) {
|
|
3266
|
-
return failed(
|
|
3267
|
-
isPrivilegedUrl(state.url) ? "PRIVILEGED_PAGE" : "UNSUPPORTED_PAGE",
|
|
3268
|
-
`The tab ended up on ${state.url || "an unsupported page"}. Evidence Mode only inspects http(s) pages.`
|
|
3269
|
-
);
|
|
3270
|
-
}
|
|
3271
|
-
if (state.contentType && !/html|xml/i.test(state.contentType)) {
|
|
3272
|
-
return failed(
|
|
3273
|
-
"UNSUPPORTED_PAGE",
|
|
3274
|
-
`The page is served as ${state.contentType}, which exposes no HTML text to locate a quote in.`
|
|
3275
|
-
);
|
|
3276
|
-
}
|
|
3277
|
-
await sleep(EVIDENCE_SETTLE_MS);
|
|
3278
|
-
const context = typeof params?.context === "string" ? params.context : void 0;
|
|
3279
|
-
const minConfidence = typeof params?.minConfidence === "number" && Number.isFinite(params.minConfidence) ? params.minConfidence : void 0;
|
|
3280
|
-
const highlightMs = clamp3(
|
|
3281
|
-
params?.highlightMs ?? EVIDENCE_HIGHLIGHT_MS,
|
|
3282
|
-
1e3,
|
|
3283
|
-
12e4
|
|
3284
|
-
);
|
|
3285
|
-
const scroll = params?.scroll !== false;
|
|
3286
|
-
const maxChars = EVIDENCE_MAX_TEXT;
|
|
3287
|
-
let snapshot = null;
|
|
3288
|
-
try {
|
|
3289
|
-
snapshot = coerceEvidenceIndex(
|
|
3290
|
-
await runEvidenceScript(
|
|
3291
|
-
tab,
|
|
3292
|
-
buildEvidenceIndexScript({ maxChars }),
|
|
3293
|
-
15e3
|
|
3294
|
-
)
|
|
3295
|
-
);
|
|
3296
|
-
} catch (error) {
|
|
3297
|
-
if (error instanceof OpsError && error.code === "actor_unavailable") {
|
|
3298
|
-
return failed("ACTOR_UNAVAILABLE", error.message);
|
|
3744
|
+
if (isPdfTab(tab)) {
|
|
3745
|
+
return failed(
|
|
3746
|
+
"UNSUPPORTED_PAGE",
|
|
3747
|
+
"PDF documents render in a viewer that exposes no HTML text, so Evidence Mode cannot locate a quote in them."
|
|
3748
|
+
);
|
|
3299
3749
|
}
|
|
3300
|
-
|
|
3301
|
-
|
|
3302
|
-
|
|
3303
|
-
)
|
|
3304
|
-
|
|
3305
|
-
|
|
3306
|
-
|
|
3307
|
-
|
|
3308
|
-
|
|
3309
|
-
|
|
3310
|
-
|
|
3311
|
-
|
|
3312
|
-
return failed("PAGE_STILL_LOADING", "The page is still loading.");
|
|
3313
|
-
}
|
|
3314
|
-
if (snapshot.contentType && !/html|xml/i.test(snapshot.contentType)) {
|
|
3315
|
-
return failed(
|
|
3316
|
-
"UNSUPPORTED_PAGE",
|
|
3317
|
-
`The page is served as ${snapshot.contentType}, which exposes no HTML text to locate a quote in.`
|
|
3318
|
-
);
|
|
3319
|
-
}
|
|
3320
|
-
const base = {
|
|
3321
|
-
tabId,
|
|
3322
|
-
url: isHttpUrl(snapshot.url) ? snapshot.url : state.url,
|
|
3323
|
-
title: snapshot.title || state.title || listedTitle
|
|
3324
|
-
};
|
|
3325
|
-
if (!snapshot.text.trim()) {
|
|
3326
|
-
return {
|
|
3327
|
-
...base,
|
|
3328
|
-
ok: false,
|
|
3329
|
-
error: {
|
|
3330
|
-
code: "QUOTE_NOT_FOUND",
|
|
3331
|
-
message: "The page exposes no readable text to search."
|
|
3750
|
+
const deadline = Date.now() + EVIDENCE_WAIT_MS;
|
|
3751
|
+
let state = null;
|
|
3752
|
+
let lastError = null;
|
|
3753
|
+
for (; ; ) {
|
|
3754
|
+
try {
|
|
3755
|
+
state = coerceEvidenceState(
|
|
3756
|
+
await runEvidenceScript(tab, buildEvidenceStateScript(), 5e3)
|
|
3757
|
+
);
|
|
3758
|
+
lastError = null;
|
|
3759
|
+
} catch (error) {
|
|
3760
|
+
lastError = error;
|
|
3761
|
+
state = null;
|
|
3332
3762
|
}
|
|
3333
|
-
|
|
3334
|
-
|
|
3335
|
-
|
|
3336
|
-
|
|
3337
|
-
|
|
3338
|
-
const outcome = findEvidenceQuote(current.text, {
|
|
3339
|
-
quote,
|
|
3340
|
-
...context ? { context } : {},
|
|
3341
|
-
...minConfidence !== void 0 ? { minConfidence } : {}
|
|
3342
|
-
});
|
|
3343
|
-
if (outcome.status === "not_found") {
|
|
3344
|
-
return {
|
|
3345
|
-
...base,
|
|
3346
|
-
ok: false,
|
|
3347
|
-
error: { code: "QUOTE_NOT_FOUND", message: outcome.message },
|
|
3348
|
-
...current.truncated ? {
|
|
3349
|
-
limitation: `Only the first ${current.text.length} characters of the page were searched.`
|
|
3350
|
-
} : {}
|
|
3351
|
-
};
|
|
3763
|
+
if (state && isHttpUrl(state.url) && state.readyState !== "" && state.readyState !== "loading") {
|
|
3764
|
+
break;
|
|
3765
|
+
}
|
|
3766
|
+
if (Date.now() >= deadline) break;
|
|
3767
|
+
await sleep2(EVIDENCE_POLL_MS);
|
|
3352
3768
|
}
|
|
3353
|
-
if (
|
|
3354
|
-
|
|
3355
|
-
|
|
3356
|
-
|
|
3357
|
-
|
|
3358
|
-
|
|
3359
|
-
|
|
3360
|
-
|
|
3769
|
+
if (!state) {
|
|
3770
|
+
if (lastError instanceof OpsError && lastError.code === "actor_unavailable") {
|
|
3771
|
+
return failed("ACTOR_UNAVAILABLE", lastError.message);
|
|
3772
|
+
}
|
|
3773
|
+
return failed(
|
|
3774
|
+
"PAGE_NOT_FOUND",
|
|
3775
|
+
`Could not reach the page in the tab "${listedTitle}". The tab may have been closed, navigated away, or not loaded yet.`
|
|
3776
|
+
);
|
|
3361
3777
|
}
|
|
3362
|
-
if (
|
|
3363
|
-
return
|
|
3364
|
-
|
|
3365
|
-
|
|
3366
|
-
|
|
3367
|
-
error: { code: "LOW_MATCH_CONFIDENCE", message: outcome.message },
|
|
3368
|
-
limitation: `The closest passage scored ${outcome.candidate.confidence.toFixed(3)} against the requested ${outcome.threshold.toFixed(2)} confidence threshold. No highlight was added.`
|
|
3369
|
-
};
|
|
3778
|
+
if (!state.readyState || state.readyState === "loading") {
|
|
3779
|
+
return failed(
|
|
3780
|
+
"PAGE_STILL_LOADING",
|
|
3781
|
+
`The page "${state.title || listedTitle}" is still loading after ${Math.round(EVIDENCE_WAIT_MS / 1e3)} seconds.`
|
|
3782
|
+
);
|
|
3370
3783
|
}
|
|
3371
|
-
|
|
3372
|
-
|
|
3373
|
-
|
|
3374
|
-
|
|
3784
|
+
if (!isHttpUrl(state.url)) {
|
|
3785
|
+
return failed(
|
|
3786
|
+
isPrivilegedUrl(state.url) ? "PRIVILEGED_PAGE" : "UNSUPPORTED_PAGE",
|
|
3787
|
+
`The tab ended up on ${state.url || "an unsupported page"}. Evidence Mode only inspects http(s) pages.`
|
|
3788
|
+
);
|
|
3789
|
+
}
|
|
3790
|
+
if (state.contentType && !/html|xml/i.test(state.contentType)) {
|
|
3791
|
+
return failed(
|
|
3792
|
+
"UNSUPPORTED_PAGE",
|
|
3793
|
+
`The page is served as ${state.contentType}, which exposes no HTML text to locate a quote in.`
|
|
3794
|
+
);
|
|
3795
|
+
}
|
|
3796
|
+
await sleep2(EVIDENCE_SETTLE_MS);
|
|
3797
|
+
const context = typeof params?.context === "string" ? params.context : void 0;
|
|
3798
|
+
const minConfidence = typeof params?.minConfidence === "number" && Number.isFinite(params.minConfidence) ? params.minConfidence : void 0;
|
|
3799
|
+
const highlightMs = clamp3(
|
|
3800
|
+
params?.highlightMs ?? EVIDENCE_HIGHLIGHT_MS,
|
|
3801
|
+
1e3,
|
|
3802
|
+
12e4
|
|
3803
|
+
);
|
|
3804
|
+
const scroll = params?.scroll !== false;
|
|
3805
|
+
const maxChars = EVIDENCE_MAX_TEXT;
|
|
3806
|
+
let snapshot = null;
|
|
3375
3807
|
try {
|
|
3376
|
-
|
|
3808
|
+
snapshot = coerceEvidenceIndex(
|
|
3377
3809
|
await runEvidenceScript(
|
|
3378
3810
|
tab,
|
|
3379
|
-
|
|
3380
|
-
start: candidate.start,
|
|
3381
|
-
end: candidate.end,
|
|
3382
|
-
expectedText,
|
|
3383
|
-
ttlMs: highlightMs,
|
|
3384
|
-
scroll,
|
|
3385
|
-
marker,
|
|
3386
|
-
clearMarkers: markersFor(tabId)
|
|
3387
|
-
}),
|
|
3811
|
+
buildEvidenceIndexScript({ maxChars }),
|
|
3388
3812
|
15e3
|
|
3389
3813
|
)
|
|
3390
3814
|
);
|
|
@@ -3392,129 +3816,227 @@ ${tab.url}`.toLowerCase();
|
|
|
3392
3816
|
if (error instanceof OpsError && error.code === "actor_unavailable") {
|
|
3393
3817
|
return failed("ACTOR_UNAVAILABLE", error.message);
|
|
3394
3818
|
}
|
|
3395
|
-
|
|
3396
|
-
|
|
3819
|
+
return failed(
|
|
3820
|
+
"PAGE_NOT_FOUND",
|
|
3821
|
+
`Could not read the page in the tab "${state.title || listedTitle}".`
|
|
3822
|
+
);
|
|
3823
|
+
}
|
|
3824
|
+
if (!snapshot) {
|
|
3825
|
+
return failed(
|
|
3826
|
+
"PAGE_NOT_FOUND",
|
|
3827
|
+
`The tab "${state.title || listedTitle}" did not return readable page content.`
|
|
3828
|
+
);
|
|
3829
|
+
}
|
|
3830
|
+
if (snapshot.readyState === "loading") {
|
|
3831
|
+
return failed("PAGE_STILL_LOADING", "The page is still loading.");
|
|
3832
|
+
}
|
|
3833
|
+
if (snapshot.contentType && !/html|xml/i.test(snapshot.contentType)) {
|
|
3834
|
+
return failed(
|
|
3835
|
+
"UNSUPPORTED_PAGE",
|
|
3836
|
+
`The page is served as ${snapshot.contentType}, which exposes no HTML text to locate a quote in.`
|
|
3837
|
+
);
|
|
3838
|
+
}
|
|
3839
|
+
const base = {
|
|
3840
|
+
tabId,
|
|
3841
|
+
url: isHttpUrl(snapshot.url) ? snapshot.url : state.url,
|
|
3842
|
+
title: snapshot.title || state.title || listedTitle
|
|
3843
|
+
};
|
|
3844
|
+
if (!snapshot.text.trim()) {
|
|
3845
|
+
return {
|
|
3846
|
+
...base,
|
|
3397
3847
|
ok: false,
|
|
3398
|
-
|
|
3399
|
-
|
|
3400
|
-
|
|
3401
|
-
|
|
3402
|
-
rects: 0,
|
|
3403
|
-
scrollY: 0,
|
|
3404
|
-
reason: String(error?.message ?? error).slice(0, 200)
|
|
3848
|
+
error: {
|
|
3849
|
+
code: "QUOTE_NOT_FOUND",
|
|
3850
|
+
message: "The page exposes no readable text to search."
|
|
3851
|
+
}
|
|
3405
3852
|
};
|
|
3406
3853
|
}
|
|
3407
|
-
|
|
3408
|
-
|
|
3854
|
+
let current = snapshot;
|
|
3855
|
+
const marker = createEvidenceMarker();
|
|
3856
|
+
for (let attempt = 0; attempt < EVIDENCE_MAX_ATTEMPTS; attempt += 1) {
|
|
3857
|
+
const outcome = findEvidenceQuote(current.text, {
|
|
3858
|
+
quote,
|
|
3859
|
+
...context ? { context } : {},
|
|
3860
|
+
...minConfidence !== void 0 ? { minConfidence } : {}
|
|
3861
|
+
});
|
|
3862
|
+
if (outcome.status === "not_found") {
|
|
3863
|
+
return {
|
|
3864
|
+
...base,
|
|
3865
|
+
ok: false,
|
|
3866
|
+
error: { code: "QUOTE_NOT_FOUND", message: outcome.message },
|
|
3867
|
+
...current.truncated ? {
|
|
3868
|
+
limitation: `Only the first ${current.text.length} characters of the page were searched.`
|
|
3869
|
+
} : {}
|
|
3870
|
+
};
|
|
3871
|
+
}
|
|
3872
|
+
if (outcome.status === "ambiguous") {
|
|
3873
|
+
return {
|
|
3874
|
+
...base,
|
|
3875
|
+
ok: false,
|
|
3876
|
+
occurrences: outcome.occurrences,
|
|
3877
|
+
error: { code: "AMBIGUOUS_MATCH", message: outcome.message },
|
|
3878
|
+
limitation: outcome.occurrencesTruncated ? `At least ${outcome.occurrences} passages matched and the scan stopped at ${outcome.occurrences}. Use a longer, more distinctive quote. No highlight was added.` : `${outcome.occurrences} occurrences matched; add surrounding context to identify the intended passage. No highlight was added.`
|
|
3879
|
+
};
|
|
3880
|
+
}
|
|
3881
|
+
if (outcome.status === "low_confidence") {
|
|
3882
|
+
return {
|
|
3883
|
+
...base,
|
|
3884
|
+
ok: false,
|
|
3885
|
+
confidence: outcome.candidate.confidence,
|
|
3886
|
+
error: { code: "LOW_MATCH_CONFIDENCE", message: outcome.message },
|
|
3887
|
+
limitation: `The closest passage scored ${outcome.candidate.confidence.toFixed(3)} against the requested ${outcome.threshold.toFixed(2)} confidence threshold. No highlight was added.`
|
|
3888
|
+
};
|
|
3889
|
+
}
|
|
3890
|
+
const candidate = outcome.candidate;
|
|
3891
|
+
const expectedText = current.text.slice(candidate.start, candidate.end);
|
|
3892
|
+
let report;
|
|
3893
|
+
let scriptFailed = false;
|
|
3409
3894
|
try {
|
|
3410
|
-
|
|
3895
|
+
report = coerceEvidenceHighlight(
|
|
3411
3896
|
await runEvidenceScript(
|
|
3412
3897
|
tab,
|
|
3413
|
-
|
|
3898
|
+
buildEvidenceHighlightScript({
|
|
3899
|
+
start: candidate.start,
|
|
3900
|
+
end: candidate.end,
|
|
3901
|
+
expectedText,
|
|
3902
|
+
ttlMs: highlightMs,
|
|
3903
|
+
scroll,
|
|
3904
|
+
marker,
|
|
3905
|
+
clearMarkers: markersFor(tabId)
|
|
3906
|
+
}),
|
|
3414
3907
|
15e3
|
|
3415
3908
|
)
|
|
3416
3909
|
);
|
|
3417
|
-
|
|
3418
|
-
|
|
3419
|
-
|
|
3420
|
-
base.title = refreshed.title || base.title;
|
|
3910
|
+
} catch (error) {
|
|
3911
|
+
if (error instanceof OpsError && error.code === "actor_unavailable") {
|
|
3912
|
+
return failed("ACTOR_UNAVAILABLE", error.message);
|
|
3421
3913
|
}
|
|
3422
|
-
|
|
3914
|
+
scriptFailed = true;
|
|
3915
|
+
report = {
|
|
3916
|
+
ok: false,
|
|
3917
|
+
stale: false,
|
|
3918
|
+
highlighted: false,
|
|
3919
|
+
scrolled: false,
|
|
3920
|
+
inView: false,
|
|
3921
|
+
rects: 0,
|
|
3922
|
+
scrollY: 0,
|
|
3923
|
+
reason: String(error?.message ?? error).slice(0, 200)
|
|
3924
|
+
};
|
|
3925
|
+
}
|
|
3926
|
+
if (report.stale) {
|
|
3927
|
+
await sleep2(EVIDENCE_POLL_MS);
|
|
3928
|
+
try {
|
|
3929
|
+
const refreshed = coerceEvidenceIndex(
|
|
3930
|
+
await runEvidenceScript(
|
|
3931
|
+
tab,
|
|
3932
|
+
buildEvidenceIndexScript({ maxChars }),
|
|
3933
|
+
15e3
|
|
3934
|
+
)
|
|
3935
|
+
);
|
|
3936
|
+
if (refreshed) {
|
|
3937
|
+
current = refreshed;
|
|
3938
|
+
base.url = isHttpUrl(refreshed.url) ? refreshed.url : base.url;
|
|
3939
|
+
base.title = refreshed.title || base.title;
|
|
3940
|
+
}
|
|
3941
|
+
} catch {
|
|
3942
|
+
}
|
|
3943
|
+
continue;
|
|
3944
|
+
}
|
|
3945
|
+
if (!report.highlighted) {
|
|
3946
|
+
if (!scriptFailed) rememberMarkers(tabId, []);
|
|
3947
|
+
return {
|
|
3948
|
+
...base,
|
|
3949
|
+
ok: false,
|
|
3950
|
+
matchedQuote: expectedText,
|
|
3951
|
+
matchMethod: candidate.method,
|
|
3952
|
+
confidence: candidate.confidence,
|
|
3953
|
+
occurrences: outcome.occurrences,
|
|
3954
|
+
scrolled: false,
|
|
3955
|
+
highlighted: false,
|
|
3956
|
+
verified: false,
|
|
3957
|
+
limitation: "The passage has no visible pixels in the page, so no highlight was added. It may be hidden, clipped, or placed off-screen.",
|
|
3958
|
+
error: {
|
|
3959
|
+
code: "HIGHLIGHT_FAILED",
|
|
3960
|
+
message: "The matched passage is hidden or has no visible area, so it could not be shown in the page."
|
|
3961
|
+
}
|
|
3962
|
+
};
|
|
3963
|
+
}
|
|
3964
|
+
rememberMarkers(tabId, [marker]);
|
|
3965
|
+
const limitations = [];
|
|
3966
|
+
if (candidate.method === "normalized" && candidate.confidence < 0.99) {
|
|
3967
|
+
limitations.push(
|
|
3968
|
+
"The quote matched after Unicode normalization, so case, spacing, punctuation, or accents differ slightly from the page."
|
|
3969
|
+
);
|
|
3970
|
+
}
|
|
3971
|
+
if (candidate.method === "fuzzy") {
|
|
3972
|
+
limitations.push(
|
|
3973
|
+
"Fuzzy match: the page wording differs from the quote and should be checked. Numbers and negation words matched exactly."
|
|
3974
|
+
);
|
|
3975
|
+
}
|
|
3976
|
+
if (outcome.occurrencesTruncated) {
|
|
3977
|
+
limitations.push(
|
|
3978
|
+
`At least ${outcome.occurrences} passages matched; the occurrence count is a lower bound.`
|
|
3979
|
+
);
|
|
3980
|
+
}
|
|
3981
|
+
if (!report.inView) {
|
|
3982
|
+
limitations.push(
|
|
3983
|
+
"The passage is outside the visible viewport, so the user cannot see the highlight without scrolling."
|
|
3984
|
+
);
|
|
3985
|
+
}
|
|
3986
|
+
if (current.truncated) {
|
|
3987
|
+
limitations.push(
|
|
3988
|
+
`Only the first ${current.text.length} characters of the page were searched.`
|
|
3989
|
+
);
|
|
3423
3990
|
}
|
|
3424
|
-
continue;
|
|
3425
|
-
}
|
|
3426
|
-
if (!report.highlighted) {
|
|
3427
|
-
if (!scriptFailed) rememberMarkers(tabId, []);
|
|
3428
3991
|
return {
|
|
3429
3992
|
...base,
|
|
3430
|
-
ok:
|
|
3993
|
+
ok: true,
|
|
3994
|
+
verified: candidate.method !== "fuzzy" && report.inView,
|
|
3431
3995
|
matchedQuote: expectedText,
|
|
3432
3996
|
matchMethod: candidate.method,
|
|
3433
3997
|
confidence: candidate.confidence,
|
|
3434
3998
|
occurrences: outcome.occurrences,
|
|
3435
|
-
scrolled: false,
|
|
3436
|
-
highlighted:
|
|
3437
|
-
|
|
3438
|
-
limitation: "The passage has no visible pixels in the page, so no highlight was added. It may be hidden, clipped, or placed off-screen.",
|
|
3439
|
-
error: {
|
|
3440
|
-
code: "HIGHLIGHT_FAILED",
|
|
3441
|
-
message: "The matched passage is hidden or has no visible area, so it could not be shown in the page."
|
|
3442
|
-
}
|
|
3999
|
+
scrolled: scroll ? report.scrolled : false,
|
|
4000
|
+
highlighted: true,
|
|
4001
|
+
...limitations.length ? { limitation: limitations.join(" ") } : {}
|
|
3443
4002
|
};
|
|
3444
4003
|
}
|
|
3445
|
-
rememberMarkers(tabId, [marker]);
|
|
3446
|
-
const limitations = [];
|
|
3447
|
-
if (candidate.method === "normalized" && candidate.confidence < 0.99) {
|
|
3448
|
-
limitations.push(
|
|
3449
|
-
"The quote matched after Unicode normalization, so case, spacing, punctuation, or accents differ slightly from the page."
|
|
3450
|
-
);
|
|
3451
|
-
}
|
|
3452
|
-
if (candidate.method === "fuzzy") {
|
|
3453
|
-
limitations.push(
|
|
3454
|
-
"Fuzzy match: the page wording differs from the quote and should be checked. Numbers and negation words matched exactly."
|
|
3455
|
-
);
|
|
3456
|
-
}
|
|
3457
|
-
if (outcome.occurrencesTruncated) {
|
|
3458
|
-
limitations.push(
|
|
3459
|
-
`At least ${outcome.occurrences} passages matched; the occurrence count is a lower bound.`
|
|
3460
|
-
);
|
|
3461
|
-
}
|
|
3462
|
-
if (!report.inView) {
|
|
3463
|
-
limitations.push(
|
|
3464
|
-
"The passage is outside the visible viewport, so the user cannot see the highlight without scrolling."
|
|
3465
|
-
);
|
|
3466
|
-
}
|
|
3467
|
-
if (current.truncated) {
|
|
3468
|
-
limitations.push(
|
|
3469
|
-
`Only the first ${current.text.length} characters of the page were searched.`
|
|
3470
|
-
);
|
|
3471
|
-
}
|
|
3472
4004
|
return {
|
|
3473
4005
|
...base,
|
|
3474
|
-
ok:
|
|
3475
|
-
|
|
3476
|
-
|
|
3477
|
-
|
|
3478
|
-
|
|
3479
|
-
|
|
3480
|
-
scrolled: scroll ? report.scrolled : false,
|
|
3481
|
-
highlighted: true,
|
|
3482
|
-
...limitations.length ? { limitation: limitations.join(" ") } : {}
|
|
4006
|
+
ok: false,
|
|
4007
|
+
limitation: "The page kept changing while Zen MCP located the passage, so no highlight was added.",
|
|
4008
|
+
error: {
|
|
4009
|
+
code: "HIGHLIGHT_FAILED",
|
|
4010
|
+
message: "The page changed before the passage could be marked. Try again once the page settles."
|
|
4011
|
+
}
|
|
3483
4012
|
};
|
|
3484
|
-
}
|
|
3485
|
-
return {
|
|
3486
|
-
...base,
|
|
3487
|
-
ok: false,
|
|
3488
|
-
limitation: "The page kept changing while Zen MCP located the passage, so no highlight was added.",
|
|
3489
|
-
error: {
|
|
3490
|
-
code: "HIGHLIGHT_FAILED",
|
|
3491
|
-
message: "The page changed before the passage could be marked. Try again once the page settles."
|
|
3492
|
-
}
|
|
3493
|
-
};
|
|
4013
|
+
});
|
|
3494
4014
|
},
|
|
3495
4015
|
"tabs.evidenceClear": async (params) => {
|
|
3496
4016
|
const tabId = String(params?.tabId ?? "");
|
|
3497
4017
|
if (!tabId) {
|
|
3498
4018
|
throw new OpsError("no_tab", "Provide the tabId whose marks to clear.");
|
|
3499
4019
|
}
|
|
3500
|
-
|
|
3501
|
-
|
|
3502
|
-
|
|
3503
|
-
|
|
3504
|
-
|
|
3505
|
-
|
|
3506
|
-
|
|
3507
|
-
|
|
3508
|
-
|
|
3509
|
-
|
|
3510
|
-
|
|
3511
|
-
|
|
3512
|
-
|
|
3513
|
-
|
|
3514
|
-
|
|
3515
|
-
|
|
3516
|
-
|
|
3517
|
-
|
|
4020
|
+
return serializeTab(tabId, async () => {
|
|
4021
|
+
const [tab] = resolveTabs([tabId]);
|
|
4022
|
+
const markers = markersFor(tabId);
|
|
4023
|
+
if (markers.length === 0) {
|
|
4024
|
+
return { tabId, removed: 0 };
|
|
4025
|
+
}
|
|
4026
|
+
let raw;
|
|
4027
|
+
try {
|
|
4028
|
+
raw = await runEvidenceScript(
|
|
4029
|
+
tab,
|
|
4030
|
+
buildEvidenceClearScript({ markers }),
|
|
4031
|
+
1e4
|
|
4032
|
+
);
|
|
4033
|
+
} catch {
|
|
4034
|
+
return { tabId, removed: 0 };
|
|
4035
|
+
}
|
|
4036
|
+
const report = coerceEvidenceClear(raw);
|
|
4037
|
+
rememberMarkers(tabId, []);
|
|
4038
|
+
return { tabId, removed: report.removed };
|
|
4039
|
+
});
|
|
3518
4040
|
},
|
|
3519
4041
|
"folders.list": () => ({
|
|
3520
4042
|
folders: collectFolders().map(folderInfo)
|
|
@@ -3601,15 +4123,54 @@ ${tab.url}`.toLowerCase();
|
|
|
3601
4123
|
throw new OpsError("no_tabs", "Provide tabIds to add to essentials");
|
|
3602
4124
|
}
|
|
3603
4125
|
const changed = [];
|
|
4126
|
+
const tracked = [];
|
|
3604
4127
|
for (const tab of tabs) {
|
|
3605
4128
|
if (isEssentialTab(tab)) continue;
|
|
4129
|
+
const tabId = idForTab(tab);
|
|
4130
|
+
const capture = captureEssentialsState(essentialsCaptures, tabId, tab);
|
|
3606
4131
|
const added = await Promise.resolve(manager.addToEssentials(tab));
|
|
3607
|
-
if (added === true)
|
|
4132
|
+
if (added === true) {
|
|
4133
|
+
changed.push(tabId);
|
|
4134
|
+
tracked.push({ tab, tabId, capture });
|
|
4135
|
+
}
|
|
3608
4136
|
}
|
|
3609
|
-
|
|
3610
|
-
|
|
4137
|
+
const notes = /* @__PURE__ */ new Map();
|
|
4138
|
+
const note = (tabId, reasons) => {
|
|
4139
|
+
if (!reasons.length) return;
|
|
4140
|
+
const existing = notes.get(tabId) ?? /* @__PURE__ */ new Set();
|
|
4141
|
+
for (const reason of reasons) existing.add(reason);
|
|
4142
|
+
notes.set(tabId, existing);
|
|
4143
|
+
};
|
|
4144
|
+
let restored = 0;
|
|
4145
|
+
if (tracked.length) {
|
|
4146
|
+
await sleep2(LAYOUT_SETTLE_MS);
|
|
4147
|
+
for (const entry of tracked) {
|
|
4148
|
+
const report = restoreEssentialsState(
|
|
4149
|
+
entry.capture,
|
|
4150
|
+
entry.tab,
|
|
4151
|
+
essentialsRestoreHost(),
|
|
4152
|
+
{ restorePinned: false }
|
|
4153
|
+
);
|
|
4154
|
+
if (report.applied && report.spaceRestored) restored++;
|
|
4155
|
+
note(entry.tabId, report.reasons);
|
|
4156
|
+
}
|
|
4157
|
+
await sleep2(LAYOUT_SETTLE_MS);
|
|
4158
|
+
for (const entry of tracked) {
|
|
4159
|
+
const verification = verifyEssentialsState(
|
|
4160
|
+
entry.capture,
|
|
4161
|
+
entry.tab,
|
|
4162
|
+
{ restorePinned: false }
|
|
4163
|
+
);
|
|
4164
|
+
note(entry.tabId, verification.reasons);
|
|
4165
|
+
}
|
|
3611
4166
|
}
|
|
3612
|
-
|
|
4167
|
+
const limitation = describeEssentialsLimitations(notes);
|
|
4168
|
+
return {
|
|
4169
|
+
tabIds: changed,
|
|
4170
|
+
changed: changed.length,
|
|
4171
|
+
...tracked.length ? { restored } : {},
|
|
4172
|
+
...limitation ? { limitation } : {}
|
|
4173
|
+
};
|
|
3613
4174
|
},
|
|
3614
4175
|
"essentials.remove": async (params) => {
|
|
3615
4176
|
const manager = win.gZenPinnedTabManager;
|
|
@@ -3624,24 +4185,69 @@ ${tab.url}`.toLowerCase();
|
|
|
3624
4185
|
throw new OpsError("no_tabs", "Provide tabIds to remove from essentials");
|
|
3625
4186
|
}
|
|
3626
4187
|
const changed = [];
|
|
4188
|
+
const tracked = [];
|
|
3627
4189
|
for (const tab of tabs) {
|
|
3628
4190
|
if (!isEssentialTab(tab)) continue;
|
|
4191
|
+
const tabId = idForTab(tab);
|
|
3629
4192
|
const removed = await Promise.resolve(manager.removeEssentials(tab));
|
|
3630
|
-
if (removed !== false)
|
|
4193
|
+
if (removed !== false) {
|
|
4194
|
+
changed.push(tabId);
|
|
4195
|
+
tracked.push({
|
|
4196
|
+
tab,
|
|
4197
|
+
tabId,
|
|
4198
|
+
capture: essentialsCaptures.take(tabId)
|
|
4199
|
+
});
|
|
4200
|
+
}
|
|
3631
4201
|
}
|
|
3632
|
-
|
|
3633
|
-
|
|
4202
|
+
const notes = /* @__PURE__ */ new Map();
|
|
4203
|
+
const note = (tabId, reasons) => {
|
|
4204
|
+
if (!reasons.length) return;
|
|
4205
|
+
const existing = notes.get(tabId) ?? /* @__PURE__ */ new Set();
|
|
4206
|
+
for (const reason of reasons) existing.add(reason);
|
|
4207
|
+
notes.set(tabId, existing);
|
|
4208
|
+
};
|
|
4209
|
+
let restored = 0;
|
|
4210
|
+
const withCapture = tracked.filter(
|
|
4211
|
+
(entry) => entry.capture !== void 0
|
|
4212
|
+
);
|
|
4213
|
+
if (withCapture.length) {
|
|
4214
|
+
await sleep2(LAYOUT_SETTLE_MS);
|
|
4215
|
+
for (const entry of withCapture) {
|
|
4216
|
+
const report = restoreEssentialsState(
|
|
4217
|
+
entry.capture,
|
|
4218
|
+
entry.tab,
|
|
4219
|
+
essentialsRestoreHost()
|
|
4220
|
+
);
|
|
4221
|
+
if (report.applied && report.spaceRestored && report.pinnedRestored) {
|
|
4222
|
+
restored++;
|
|
4223
|
+
}
|
|
4224
|
+
note(entry.tabId, report.reasons);
|
|
4225
|
+
}
|
|
4226
|
+
await sleep2(LAYOUT_SETTLE_MS);
|
|
4227
|
+
for (const entry of withCapture) {
|
|
4228
|
+
const verification = verifyEssentialsState(
|
|
4229
|
+
entry.capture,
|
|
4230
|
+
entry.tab
|
|
4231
|
+
);
|
|
4232
|
+
note(entry.tabId, verification.reasons);
|
|
4233
|
+
}
|
|
3634
4234
|
}
|
|
3635
|
-
|
|
4235
|
+
const limitation = describeEssentialsLimitations(notes);
|
|
4236
|
+
return {
|
|
4237
|
+
tabIds: changed,
|
|
4238
|
+
changed: changed.length,
|
|
4239
|
+
...withCapture.length ? { restored } : {},
|
|
4240
|
+
...limitation ? { limitation } : {}
|
|
4241
|
+
};
|
|
3636
4242
|
},
|
|
3637
4243
|
"containers.list": () => ({ containers: containerIdentities() }),
|
|
3638
4244
|
"glance.open": async (params) => {
|
|
3639
4245
|
const sourceTab = params?.tabId ? resolveTabs([String(params.tabId)])[0] : null;
|
|
3640
|
-
let
|
|
4246
|
+
let rawUrl;
|
|
3641
4247
|
let userContextId;
|
|
3642
4248
|
if (sourceTab) {
|
|
3643
|
-
|
|
3644
|
-
if (!
|
|
4249
|
+
rawUrl = tabUrl(sourceTab);
|
|
4250
|
+
if (!rawUrl) {
|
|
3645
4251
|
throw new OpsError(
|
|
3646
4252
|
"invalid_url",
|
|
3647
4253
|
`The tab "${tabTitle(sourceTab)}" has no URL to preview.`
|
|
@@ -3650,12 +4256,29 @@ ${tab.url}`.toLowerCase();
|
|
|
3650
4256
|
const containerId = containerIdOf(sourceTab);
|
|
3651
4257
|
userContextId = containerId > 0 ? containerId : void 0;
|
|
3652
4258
|
} else {
|
|
3653
|
-
|
|
4259
|
+
rawUrl = normalizeUrl(String(params?.url ?? ""));
|
|
3654
4260
|
if (params?.container !== void 0 && params?.container !== null && params?.container !== "") {
|
|
3655
4261
|
const container = resolveContainer(params.container);
|
|
3656
4262
|
userContextId = container.userContextId > 0 ? container.userContextId : void 0;
|
|
3657
4263
|
}
|
|
3658
4264
|
}
|
|
4265
|
+
const preview = normalizeWebUrl(rawUrl);
|
|
4266
|
+
if (!preview) {
|
|
4267
|
+
throw new OpsError(
|
|
4268
|
+
"invalid_url",
|
|
4269
|
+
`Refusing to preview "${rawUrl}". Glance only opens http(s) URLs.`
|
|
4270
|
+
);
|
|
4271
|
+
}
|
|
4272
|
+
const url = preview.href;
|
|
4273
|
+
const allowedDomains = Array.isArray(params?.allowedDomains) ? params.allowedDomains.filter(
|
|
4274
|
+
(entry) => typeof entry === "string"
|
|
4275
|
+
) : [];
|
|
4276
|
+
if (!isUrlAllowed(url, allowedDomains)) {
|
|
4277
|
+
throw new OpsError(
|
|
4278
|
+
"domain_not_allowed",
|
|
4279
|
+
`Refusing to preview ${preview.hostname}, which is outside the configured domain allowlist.`
|
|
4280
|
+
);
|
|
4281
|
+
}
|
|
3659
4282
|
const manager = win.gZenGlanceManager;
|
|
3660
4283
|
if (!manager || typeof manager.openGlance !== "function") {
|
|
3661
4284
|
return {
|
|
@@ -3665,6 +4288,20 @@ ${tab.url}`.toLowerCase();
|
|
|
3665
4288
|
message: "Zen glance is not available in this window. Update Zen or open the URL as a tab instead."
|
|
3666
4289
|
};
|
|
3667
4290
|
}
|
|
4291
|
+
let triggeringPrincipal;
|
|
4292
|
+
try {
|
|
4293
|
+
triggeringPrincipal = Services.scriptSecurityManager.createContentPrincipal(
|
|
4294
|
+
Services.io.newURI(url),
|
|
4295
|
+
userContextId ? { userContextId } : {}
|
|
4296
|
+
);
|
|
4297
|
+
} catch (error) {
|
|
4298
|
+
throw new OpsError(
|
|
4299
|
+
"glance_failed",
|
|
4300
|
+
`Could not prepare the preview: ${String(
|
|
4301
|
+
error?.message ?? error
|
|
4302
|
+
)}`
|
|
4303
|
+
);
|
|
4304
|
+
}
|
|
3668
4305
|
const width = clamp3(Number(params?.width ?? 960), 240, 4096);
|
|
3669
4306
|
const height = clamp3(Number(params?.height ?? 720), 240, 4096);
|
|
3670
4307
|
let result = null;
|
|
@@ -3675,7 +4312,7 @@ ${tab.url}`.toLowerCase();
|
|
|
3675
4312
|
clientY: 120,
|
|
3676
4313
|
width,
|
|
3677
4314
|
height,
|
|
3678
|
-
triggeringPrincipal
|
|
4315
|
+
triggeringPrincipal,
|
|
3679
4316
|
...userContextId ? { userContextId } : {}
|
|
3680
4317
|
});
|
|
3681
4318
|
} catch (error) {
|
|
@@ -3686,11 +4323,48 @@ ${tab.url}`.toLowerCase();
|
|
|
3686
4323
|
)}`
|
|
3687
4324
|
);
|
|
3688
4325
|
}
|
|
4326
|
+
if (!result) {
|
|
4327
|
+
return {
|
|
4328
|
+
opened: false,
|
|
4329
|
+
url,
|
|
4330
|
+
mode: "none",
|
|
4331
|
+
message: "Zen declined to open the glance view."
|
|
4332
|
+
};
|
|
4333
|
+
}
|
|
4334
|
+
const closePreview = () => {
|
|
4335
|
+
try {
|
|
4336
|
+
manager.closeGlance?.({ noAnimation: true, skipPermitUnload: true });
|
|
4337
|
+
} catch {
|
|
4338
|
+
}
|
|
4339
|
+
};
|
|
4340
|
+
const loadedUrl = isGlanceTab(result) ? await waitForGlanceUrl(result) : void 0;
|
|
4341
|
+
if (!loadedUrl) {
|
|
4342
|
+
closePreview();
|
|
4343
|
+
throw new OpsError(
|
|
4344
|
+
"glance_failed",
|
|
4345
|
+
"The preview opened but its URL could not be verified, so it was closed."
|
|
4346
|
+
);
|
|
4347
|
+
}
|
|
4348
|
+
const loaded = normalizeWebUrl(loadedUrl);
|
|
4349
|
+
if (!loaded) {
|
|
4350
|
+
closePreview();
|
|
4351
|
+
throw new OpsError(
|
|
4352
|
+
"invalid_url",
|
|
4353
|
+
`The preview loaded "${loadedUrl}", which is not an http(s) URL.`
|
|
4354
|
+
);
|
|
4355
|
+
}
|
|
4356
|
+
if (!isUrlAllowed(loaded.href, allowedDomains)) {
|
|
4357
|
+
closePreview();
|
|
4358
|
+
throw new OpsError(
|
|
4359
|
+
"domain_not_allowed",
|
|
4360
|
+
`The preview redirected to ${loaded.hostname}, which is outside the configured domain allowlist, so it was closed.`
|
|
4361
|
+
);
|
|
4362
|
+
}
|
|
4363
|
+
watchGlanceRedirects(result, manager, allowedDomains);
|
|
3689
4364
|
return {
|
|
3690
|
-
opened:
|
|
3691
|
-
url,
|
|
3692
|
-
mode:
|
|
3693
|
-
message: result ? void 0 : "Zen declined to open the glance view."
|
|
4365
|
+
opened: true,
|
|
4366
|
+
url: loaded.href,
|
|
4367
|
+
mode: "glance"
|
|
3694
4368
|
};
|
|
3695
4369
|
},
|
|
3696
4370
|
"split.open": async (params) => {
|
|
@@ -3764,7 +4438,7 @@ ${tab.url}`.toLowerCase();
|
|
|
3764
4438
|
gridType
|
|
3765
4439
|
};
|
|
3766
4440
|
},
|
|
3767
|
-
"split.close": (params) => {
|
|
4441
|
+
"split.close": async (params) => {
|
|
3768
4442
|
const splitter = win.gZenViewSplitter;
|
|
3769
4443
|
if (!splitter) {
|
|
3770
4444
|
throw new OpsError(
|
|
@@ -3776,24 +4450,150 @@ ${tab.url}`.toLowerCase();
|
|
|
3776
4450
|
if (!tab) {
|
|
3777
4451
|
throw new OpsError("tab_not_found", "No tab is selected to unsplit.");
|
|
3778
4452
|
}
|
|
4453
|
+
const beforeSnapshot = collectTabs().map((candidate) => ({
|
|
4454
|
+
id: idForTab(candidate),
|
|
4455
|
+
url: tabUrl(candidate),
|
|
4456
|
+
title: tabTitle(candidate)
|
|
4457
|
+
}));
|
|
4458
|
+
const beforeIds = beforeSnapshot.map((entry) => entry.id);
|
|
4459
|
+
const beforeById = new Map(
|
|
4460
|
+
beforeSnapshot.map((entry) => [entry.id, entry])
|
|
4461
|
+
);
|
|
3779
4462
|
const groups = Array.isArray(splitter._data) ? splitter._data : [];
|
|
3780
4463
|
const index = groups.findIndex(
|
|
3781
4464
|
(group) => Array.isArray(group?.tabs) && group.tabs.includes(tab)
|
|
3782
4465
|
);
|
|
3783
|
-
let
|
|
4466
|
+
let groupTabs = [];
|
|
3784
4467
|
if (index >= 0) {
|
|
3785
|
-
|
|
4468
|
+
groupTabs = groups[index].tabs.filter(
|
|
4469
|
+
(member) => member?.isConnected && !member.closing
|
|
4470
|
+
);
|
|
4471
|
+
} else if (tab.splitView) {
|
|
4472
|
+
groupTabs = [tab];
|
|
4473
|
+
}
|
|
4474
|
+
const groupIds = groupTabs.map((member) => idForTab(member));
|
|
4475
|
+
const groupUrls = [
|
|
4476
|
+
...new Set(groupTabs.map((member) => tabUrl(member)).filter(Boolean))
|
|
4477
|
+
];
|
|
4478
|
+
if (groupIds.length === 0) {
|
|
4479
|
+
return {
|
|
4480
|
+
unsplit: false,
|
|
4481
|
+
tabIds: [],
|
|
4482
|
+
limitation: `No split view contains the tab "${tabTitle(tab)}".`
|
|
4483
|
+
};
|
|
3786
4484
|
}
|
|
3787
|
-
|
|
3788
|
-
|
|
3789
|
-
|
|
4485
|
+
const selectedTab = win.gBrowser?.selectedTab ?? null;
|
|
4486
|
+
const targetIsCurrent = selectedTab === tab || !!tab.selected;
|
|
4487
|
+
const canUseCurrentView = typeof splitter.unsplitCurrentView === "function";
|
|
4488
|
+
let cleared = false;
|
|
4489
|
+
let usedSupportedPath = false;
|
|
4490
|
+
let usedRemoveGroup = false;
|
|
4491
|
+
if (canUseCurrentView && targetIsCurrent) {
|
|
4492
|
+
try {
|
|
4493
|
+
win.gBrowser.selectedTab = tab;
|
|
4494
|
+
splitter.unsplitCurrentView();
|
|
4495
|
+
usedSupportedPath = true;
|
|
4496
|
+
} catch {
|
|
4497
|
+
usedSupportedPath = false;
|
|
4498
|
+
}
|
|
4499
|
+
cleared = await waitForSplitGone(groupTabs);
|
|
3790
4500
|
}
|
|
3791
|
-
|
|
3792
|
-
|
|
3793
|
-
|
|
3794
|
-
|
|
4501
|
+
if (!cleared && typeof splitter.removeGroup === "function") {
|
|
4502
|
+
const currentGroups = Array.isArray(splitter._data) ? splitter._data : [];
|
|
4503
|
+
const currentIndex = currentGroups.findIndex(
|
|
4504
|
+
(group) => Array.isArray(group?.tabs) && group.tabs.includes(tab)
|
|
4505
|
+
);
|
|
4506
|
+
if (currentIndex >= 0) {
|
|
4507
|
+
try {
|
|
4508
|
+
splitter.removeGroup(currentIndex);
|
|
4509
|
+
usedRemoveGroup = true;
|
|
4510
|
+
} catch {
|
|
4511
|
+
usedRemoveGroup = false;
|
|
4512
|
+
}
|
|
4513
|
+
if (usedRemoveGroup) cleared = await waitForSplitGone(groupTabs);
|
|
4514
|
+
}
|
|
4515
|
+
}
|
|
4516
|
+
if (!cleared && !usedSupportedPath && canUseCurrentView) {
|
|
4517
|
+
try {
|
|
4518
|
+
win.gBrowser.selectedTab = tab;
|
|
4519
|
+
splitter.unsplitCurrentView();
|
|
4520
|
+
usedSupportedPath = true;
|
|
4521
|
+
} catch {
|
|
4522
|
+
usedSupportedPath = false;
|
|
4523
|
+
}
|
|
4524
|
+
cleared = await waitForSplitGone(groupTabs);
|
|
3795
4525
|
}
|
|
3796
|
-
|
|
4526
|
+
if (!cleared) {
|
|
4527
|
+
throw new OpsError(
|
|
4528
|
+
"split_close_failed",
|
|
4529
|
+
`Zen did not close the split view for "${tabTitle(tab)}". The tabs are unchanged; close the split from Zen's UI and try again.`
|
|
4530
|
+
);
|
|
4531
|
+
}
|
|
4532
|
+
await sleep2(LAYOUT_SETTLE_MS);
|
|
4533
|
+
const candidates = collectTabs().map((candidate) => ({
|
|
4534
|
+
id: idForTab(candidate),
|
|
4535
|
+
url: tabUrl(candidate),
|
|
4536
|
+
title: tabTitle(candidate),
|
|
4537
|
+
empty: candidate.hasAttribute("zen-empty-tab"),
|
|
4538
|
+
windowId
|
|
4539
|
+
}));
|
|
4540
|
+
const plan = planSplitCleanup(
|
|
4541
|
+
{ beforeTabIds: beforeIds, groupUrls, windowId },
|
|
4542
|
+
candidates
|
|
4543
|
+
);
|
|
4544
|
+
const limitations = [];
|
|
4545
|
+
if (plan.limitation) limitations.push(plan.limitation);
|
|
4546
|
+
const removeTab = win.gBrowser && typeof win.gBrowser.removeTab === "function" ? (target) => win.gBrowser.removeTab(target) : void 0;
|
|
4547
|
+
let closedResidue = 0;
|
|
4548
|
+
for (const residueId of plan.closeTabIds) {
|
|
4549
|
+
const residue = tabsById.get(residueId);
|
|
4550
|
+
if (!residue || !residue.isConnected || residue.closing) continue;
|
|
4551
|
+
if (typeof removeTab !== "function") {
|
|
4552
|
+
limitations.push(
|
|
4553
|
+
`Zen cannot close the leftover tab "${tabTitle(residue)}" (${residueId}) automatically.`
|
|
4554
|
+
);
|
|
4555
|
+
continue;
|
|
4556
|
+
}
|
|
4557
|
+
try {
|
|
4558
|
+
await Promise.resolve(removeTab(residue));
|
|
4559
|
+
closedResidue++;
|
|
4560
|
+
} catch {
|
|
4561
|
+
limitations.push(
|
|
4562
|
+
`Could not close the leftover tab "${tabTitle(residue)}" (${residueId}).`
|
|
4563
|
+
);
|
|
4564
|
+
}
|
|
4565
|
+
}
|
|
4566
|
+
if (plan.closeTabIds.length) {
|
|
4567
|
+
await sleep2(LAYOUT_SETTLE_MS);
|
|
4568
|
+
const stillOpen = plan.closeTabIds.filter((residueId) => {
|
|
4569
|
+
const residue = tabsById.get(residueId);
|
|
4570
|
+
return !!residue && residue.isConnected && !residue.closing;
|
|
4571
|
+
});
|
|
4572
|
+
if (stillOpen.length) {
|
|
4573
|
+
limitations.push(
|
|
4574
|
+
`Zen did not close ${stillOpen.length} leftover tab(s): ${stillOpen.join(", ")}.`
|
|
4575
|
+
);
|
|
4576
|
+
}
|
|
4577
|
+
}
|
|
4578
|
+
const missingGroupMembers = groupIds.filter((groupId) => {
|
|
4579
|
+
const member = tabsById.get(groupId);
|
|
4580
|
+
return !member || !member.isConnected || member.closing;
|
|
4581
|
+
});
|
|
4582
|
+
if (missingGroupMembers.length) {
|
|
4583
|
+
const listed = missingGroupMembers.map((groupId) => {
|
|
4584
|
+
const entry = beforeById.get(groupId);
|
|
4585
|
+
return entry ? `"${entry.title}" (${groupId})` : groupId;
|
|
4586
|
+
}).join(", ");
|
|
4587
|
+
limitations.push(
|
|
4588
|
+
`Zen closed ${missingGroupMembers.length} tab(s) from the split: ${listed}. Reopen them if needed.`
|
|
4589
|
+
);
|
|
4590
|
+
}
|
|
4591
|
+
return {
|
|
4592
|
+
unsplit: true,
|
|
4593
|
+
tabIds: groupIds,
|
|
4594
|
+
closedResidue,
|
|
4595
|
+
...limitations.length ? { limitation: limitations.join(" ") } : {}
|
|
4596
|
+
};
|
|
3797
4597
|
},
|
|
3798
4598
|
"history.search": async (params) => {
|
|
3799
4599
|
const limit = clamp3(params?.limit ?? 25, 1, MAX_RESULTS);
|
|
@@ -4038,6 +4838,187 @@ ${tab.url}`.toLowerCase();
|
|
|
4038
4838
|
).PlacesUtils;
|
|
4039
4839
|
}
|
|
4040
4840
|
|
|
4841
|
+
// src/bridge/evidence-reveal.ts
|
|
4842
|
+
var MAX_EVIDENCE_RECORDS = 20;
|
|
4843
|
+
var EVIDENCE_REVEAL_HIGHLIGHT_MS = 25e3;
|
|
4844
|
+
var MAX_QUOTE_CHARS = 2e4;
|
|
4845
|
+
var MAX_CONTEXT_CHARS2 = 8e3;
|
|
4846
|
+
var TAB_ID_PATTERN = /^[A-Za-z0-9_-]{1,64}$/;
|
|
4847
|
+
var EvidenceRevealError = class extends Error {
|
|
4848
|
+
name = "EvidenceRevealError";
|
|
4849
|
+
code;
|
|
4850
|
+
constructor(code, message) {
|
|
4851
|
+
super(`${code}: ${message}`);
|
|
4852
|
+
this.code = code;
|
|
4853
|
+
}
|
|
4854
|
+
};
|
|
4855
|
+
function errorMessage2(error) {
|
|
4856
|
+
return String(error?.message ?? error);
|
|
4857
|
+
}
|
|
4858
|
+
function errorCode(error, fallback) {
|
|
4859
|
+
const code = error?.code;
|
|
4860
|
+
return typeof code === "string" && code ? code : fallback;
|
|
4861
|
+
}
|
|
4862
|
+
function isTabId(value) {
|
|
4863
|
+
return typeof value === "string" && TAB_ID_PATTERN.test(value);
|
|
4864
|
+
}
|
|
4865
|
+
function clampHighlightMs(value) {
|
|
4866
|
+
const number = Number(value);
|
|
4867
|
+
if (!Number.isFinite(number)) return EVIDENCE_REVEAL_HIGHLIGHT_MS;
|
|
4868
|
+
return Math.min(12e4, Math.max(1e3, Math.floor(number)));
|
|
4869
|
+
}
|
|
4870
|
+
var EvidenceRecordStore = class {
|
|
4871
|
+
#records = /* @__PURE__ */ new Map();
|
|
4872
|
+
#limit;
|
|
4873
|
+
constructor(limit = MAX_EVIDENCE_RECORDS) {
|
|
4874
|
+
this.#limit = Math.max(1, Math.floor(limit));
|
|
4875
|
+
}
|
|
4876
|
+
get size() {
|
|
4877
|
+
return this.#records.size;
|
|
4878
|
+
}
|
|
4879
|
+
remember(tabId, record) {
|
|
4880
|
+
if (!isTabId(tabId)) return;
|
|
4881
|
+
const quote = typeof record?.quote === "string" ? record.quote.replace(/\r\n?/g, "\n").trim() : "";
|
|
4882
|
+
if (!quote) return;
|
|
4883
|
+
const stored = {
|
|
4884
|
+
quote: quote.slice(0, MAX_QUOTE_CHARS)
|
|
4885
|
+
};
|
|
4886
|
+
const context = typeof record.context === "string" ? record.context.trim() : "";
|
|
4887
|
+
if (context) stored.context = context.slice(0, MAX_CONTEXT_CHARS2);
|
|
4888
|
+
if (typeof record.minConfidence === "number" && Number.isFinite(record.minConfidence)) {
|
|
4889
|
+
stored.minConfidence = record.minConfidence;
|
|
4890
|
+
}
|
|
4891
|
+
this.#records.delete(tabId);
|
|
4892
|
+
this.#records.set(tabId, stored);
|
|
4893
|
+
while (this.#records.size > this.#limit) {
|
|
4894
|
+
const oldest = this.#records.keys().next().value;
|
|
4895
|
+
if (oldest === void 0) break;
|
|
4896
|
+
this.#records.delete(oldest);
|
|
4897
|
+
}
|
|
4898
|
+
}
|
|
4899
|
+
peek(tabId) {
|
|
4900
|
+
const record = this.#records.get(tabId);
|
|
4901
|
+
return record ? { ...record } : void 0;
|
|
4902
|
+
}
|
|
4903
|
+
clear(tabId) {
|
|
4904
|
+
return this.#records.delete(tabId);
|
|
4905
|
+
}
|
|
4906
|
+
clearAll() {
|
|
4907
|
+
this.#records.clear();
|
|
4908
|
+
}
|
|
4909
|
+
};
|
|
4910
|
+
function cacheEvidenceRequest(store, tabId, params, result) {
|
|
4911
|
+
if (!isTabId(tabId)) return false;
|
|
4912
|
+
const request = params ?? {};
|
|
4913
|
+
const outcome = result ?? {};
|
|
4914
|
+
if (outcome.ok !== true) {
|
|
4915
|
+
store.clear(tabId);
|
|
4916
|
+
return false;
|
|
4917
|
+
}
|
|
4918
|
+
const quote = typeof request.quote === "string" ? request.quote.replace(/\r\n?/g, "\n").trim() : "";
|
|
4919
|
+
if (!quote) {
|
|
4920
|
+
store.clear(tabId);
|
|
4921
|
+
return false;
|
|
4922
|
+
}
|
|
4923
|
+
store.remember(tabId, {
|
|
4924
|
+
quote,
|
|
4925
|
+
...typeof request.context === "string" && request.context.trim() ? { context: request.context.trim() } : {},
|
|
4926
|
+
...typeof request.minConfidence === "number" && Number.isFinite(request.minConfidence) ? { minConfidence: request.minConfidence } : {}
|
|
4927
|
+
});
|
|
4928
|
+
return true;
|
|
4929
|
+
}
|
|
4930
|
+
async function revealEvidence(dispatch, store, tabId, options = {}) {
|
|
4931
|
+
if (!isTabId(tabId)) {
|
|
4932
|
+
throw new EvidenceRevealError(
|
|
4933
|
+
"invalid_tab",
|
|
4934
|
+
"The Show source action did not carry a valid tab id."
|
|
4935
|
+
);
|
|
4936
|
+
}
|
|
4937
|
+
let selection;
|
|
4938
|
+
try {
|
|
4939
|
+
selection = await dispatch("tabs.select", {
|
|
4940
|
+
tabId,
|
|
4941
|
+
focusWindow: true
|
|
4942
|
+
});
|
|
4943
|
+
} catch (error) {
|
|
4944
|
+
throw new EvidenceRevealError(
|
|
4945
|
+
errorCode(error, "select_failed"),
|
|
4946
|
+
errorMessage2(error)
|
|
4947
|
+
);
|
|
4948
|
+
}
|
|
4949
|
+
if (selection?.tab?.active !== true) {
|
|
4950
|
+
throw new EvidenceRevealError(
|
|
4951
|
+
"select_failed",
|
|
4952
|
+
`The tab ${tabId} did not become the active tab, so the source was not brought forward.`
|
|
4953
|
+
);
|
|
4954
|
+
}
|
|
4955
|
+
const record = store.peek(tabId);
|
|
4956
|
+
if (!record) return null;
|
|
4957
|
+
const params = {
|
|
4958
|
+
tabId,
|
|
4959
|
+
quote: record.quote,
|
|
4960
|
+
...record.context ? { context: record.context } : {},
|
|
4961
|
+
...typeof record.minConfidence === "number" ? { minConfidence: record.minConfidence } : {},
|
|
4962
|
+
scroll: true,
|
|
4963
|
+
highlightMs: clampHighlightMs(options.highlightMs)
|
|
4964
|
+
};
|
|
4965
|
+
let result;
|
|
4966
|
+
try {
|
|
4967
|
+
result = await dispatch("tabs.evidence", params);
|
|
4968
|
+
} catch (error) {
|
|
4969
|
+
throw new EvidenceRevealError(
|
|
4970
|
+
errorCode(error, "highlight_failed"),
|
|
4971
|
+
errorMessage2(error)
|
|
4972
|
+
);
|
|
4973
|
+
}
|
|
4974
|
+
if (!result || result.ok !== true) {
|
|
4975
|
+
throw new EvidenceRevealError(
|
|
4976
|
+
result?.error?.code ?? "HIGHLIGHT_FAILED",
|
|
4977
|
+
result?.error?.message ?? "Zen MCP could not mark the passage again. The page may have changed."
|
|
4978
|
+
);
|
|
4979
|
+
}
|
|
4980
|
+
return result;
|
|
4981
|
+
}
|
|
4982
|
+
|
|
4983
|
+
// src/bridge/pending-stop.ts
|
|
4984
|
+
var PendingStopStore = class {
|
|
4985
|
+
#pending = null;
|
|
4986
|
+
/** Takes at most one entry; the latest press wins. */
|
|
4987
|
+
get size() {
|
|
4988
|
+
return this.#pending ? 1 : 0;
|
|
4989
|
+
}
|
|
4990
|
+
/** Queues a press, replacing any earlier queued press. */
|
|
4991
|
+
set(progressId, ts = Date.now()) {
|
|
4992
|
+
if (!progressId) return;
|
|
4993
|
+
this.#pending = { progressId, ts };
|
|
4994
|
+
}
|
|
4995
|
+
/** Returns the queued press without removing it, or null when empty. */
|
|
4996
|
+
peek() {
|
|
4997
|
+
return this.#pending ? { ...this.#pending } : null;
|
|
4998
|
+
}
|
|
4999
|
+
clear() {
|
|
5000
|
+
this.#pending = null;
|
|
5001
|
+
}
|
|
5002
|
+
/**
|
|
5003
|
+
* Drops the queued press when the card it belongs to disappeared (null) or
|
|
5004
|
+
* was replaced by a different progress id. Stops for replaced cards must not
|
|
5005
|
+
* be resent.
|
|
5006
|
+
*/
|
|
5007
|
+
clearIfProgressMoved(progressId) {
|
|
5008
|
+
if (this.#pending && this.#pending.progressId !== progressId) {
|
|
5009
|
+
this.#pending = null;
|
|
5010
|
+
}
|
|
5011
|
+
}
|
|
5012
|
+
};
|
|
5013
|
+
function deliverStop(store, progressId, sender, ts = Date.now()) {
|
|
5014
|
+
if (sender({ progressId, ts })) {
|
|
5015
|
+
store.clear();
|
|
5016
|
+
return true;
|
|
5017
|
+
}
|
|
5018
|
+
store.set(progressId, ts);
|
|
5019
|
+
return false;
|
|
5020
|
+
}
|
|
5021
|
+
|
|
4041
5022
|
// src/bridge/ui.ts
|
|
4042
5023
|
var FALLBACK_ACCENT = "#4ec3f7";
|
|
4043
5024
|
var STYLE = `
|
|
@@ -5040,10 +6021,16 @@ ${tab.url}`.toLowerCase();
|
|
|
5040
6021
|
view.stopRequested = true;
|
|
5041
6022
|
view.stop.disabled = true;
|
|
5042
6023
|
view.stop.textContent = "Stopping…";
|
|
6024
|
+
let delivered = true;
|
|
5043
6025
|
try {
|
|
5044
|
-
this.#handlers.onStop?.(view.id);
|
|
6026
|
+
delivered = this.#handlers.onStop?.(view.id) !== false;
|
|
5045
6027
|
} catch {
|
|
6028
|
+
delivered = false;
|
|
5046
6029
|
}
|
|
6030
|
+
if (delivered || view.removed) return;
|
|
6031
|
+
view.stopRequested = false;
|
|
6032
|
+
view.stop.disabled = false;
|
|
6033
|
+
view.stop.textContent = "Retry stop";
|
|
5047
6034
|
});
|
|
5048
6035
|
this.#updateProgress(view, progress);
|
|
5049
6036
|
if (restoreFocus && !stop.hidden && !stop.disabled) {
|
|
@@ -5300,8 +6287,11 @@ ${tab.url}`.toLowerCase();
|
|
|
5300
6287
|
let authenticated = false;
|
|
5301
6288
|
let clientNonce = "";
|
|
5302
6289
|
let authTimer = null;
|
|
6290
|
+
const pendingStop = new PendingStopStore();
|
|
5303
6291
|
const send = (message) => {
|
|
5304
|
-
if (!socket || socket.readyState !== WebSocket.OPEN)
|
|
6292
|
+
if (!authenticated || !socket || socket.readyState !== WebSocket.OPEN) {
|
|
6293
|
+
return false;
|
|
6294
|
+
}
|
|
5305
6295
|
try {
|
|
5306
6296
|
socket.send(JSON.stringify(message));
|
|
5307
6297
|
return true;
|
|
@@ -5350,13 +6340,20 @@ ${tab.url}`.toLowerCase();
|
|
|
5350
6340
|
return difference === 0;
|
|
5351
6341
|
};
|
|
5352
6342
|
const ui = new ZenMcpUi(win.document, {
|
|
5353
|
-
onStop: (progressId) =>
|
|
5354
|
-
|
|
5355
|
-
|
|
6343
|
+
onStop: (progressId) => deliverStop(
|
|
6344
|
+
pendingStop,
|
|
6345
|
+
progressId,
|
|
6346
|
+
(stop) => send({
|
|
6347
|
+
type: "ui.stop",
|
|
6348
|
+
progressId: stop.progressId,
|
|
6349
|
+
ts: stop.ts
|
|
6350
|
+
})
|
|
6351
|
+
),
|
|
5356
6352
|
onConsent: (id, granted) => send({ type: "ui.consentResult", id, granted }),
|
|
5357
6353
|
onBannerAction: (action) => send({ type: "ui.bannerAction", action, ts: Date.now() })
|
|
5358
6354
|
});
|
|
5359
6355
|
const ops = createOps(win, windowId);
|
|
6356
|
+
const evidenceRecords = new EvidenceRecordStore();
|
|
5360
6357
|
const sendHello = () => {
|
|
5361
6358
|
send({
|
|
5362
6359
|
type: "hello",
|
|
@@ -5368,6 +6365,15 @@ ${tab.url}`.toLowerCase();
|
|
|
5368
6365
|
platform: String(Services.appinfo.OS)
|
|
5369
6366
|
});
|
|
5370
6367
|
};
|
|
6368
|
+
const flushPendingStop = () => {
|
|
6369
|
+
const pending = pendingStop.peek();
|
|
6370
|
+
if (!pending) return;
|
|
6371
|
+
send({
|
|
6372
|
+
type: "ui.stop",
|
|
6373
|
+
progressId: pending.progressId,
|
|
6374
|
+
ts: pending.ts
|
|
6375
|
+
});
|
|
6376
|
+
};
|
|
5371
6377
|
const scheduleReconnect = () => {
|
|
5372
6378
|
if (destroyed || retryTimer) return;
|
|
5373
6379
|
const delay = Math.min(retryMs, 15e3);
|
|
@@ -5431,6 +6437,7 @@ ${tab.url}`.toLowerCase();
|
|
|
5431
6437
|
authenticated = true;
|
|
5432
6438
|
clearAuthTimer();
|
|
5433
6439
|
sendHello();
|
|
6440
|
+
flushPendingStop();
|
|
5434
6441
|
};
|
|
5435
6442
|
const handleMessage = async (message, ws) => {
|
|
5436
6443
|
if (!authenticated) {
|
|
@@ -5457,9 +6464,15 @@ ${tab.url}`.toLowerCase();
|
|
|
5457
6464
|
case "ui.cancel":
|
|
5458
6465
|
ui.cancelQuestion(message.id);
|
|
5459
6466
|
return;
|
|
5460
|
-
case "ui.progress":
|
|
6467
|
+
case "ui.progress": {
|
|
5461
6468
|
ui.showProgress(message.progress);
|
|
6469
|
+
if (!message.progress || message.progress.stopRequested) {
|
|
6470
|
+
pendingStop.clear();
|
|
6471
|
+
} else {
|
|
6472
|
+
pendingStop.clearIfProgressMoved(message.progress.id);
|
|
6473
|
+
}
|
|
5462
6474
|
return;
|
|
6475
|
+
}
|
|
5463
6476
|
case "ui.consent":
|
|
5464
6477
|
ui.showConsent(message.consent);
|
|
5465
6478
|
return;
|
|
@@ -5476,10 +6489,11 @@ ${tab.url}`.toLowerCase();
|
|
|
5476
6489
|
if (action.kind === "space") {
|
|
5477
6490
|
await ops.dispatch("spaces.switch", { space: action.target });
|
|
5478
6491
|
} else if (action.kind === "tab") {
|
|
5479
|
-
await
|
|
5480
|
-
|
|
5481
|
-
|
|
5482
|
-
|
|
6492
|
+
await revealEvidence(
|
|
6493
|
+
(method, params) => ops.dispatch(method, params),
|
|
6494
|
+
evidenceRecords,
|
|
6495
|
+
action.target
|
|
6496
|
+
);
|
|
5483
6497
|
} else {
|
|
5484
6498
|
return {
|
|
5485
6499
|
ok: false,
|
|
@@ -5513,6 +6527,15 @@ ${tab.url}`.toLowerCase();
|
|
|
5513
6527
|
case "req": {
|
|
5514
6528
|
try {
|
|
5515
6529
|
const result = await ops.dispatch(message.method, message.params);
|
|
6530
|
+
if (message.method === "tabs.evidence") {
|
|
6531
|
+
const params = message.params;
|
|
6532
|
+
cacheEvidenceRequest(
|
|
6533
|
+
evidenceRecords,
|
|
6534
|
+
params?.tabId,
|
|
6535
|
+
message.params,
|
|
6536
|
+
result
|
|
6537
|
+
);
|
|
6538
|
+
}
|
|
5516
6539
|
send({
|
|
5517
6540
|
type: "res",
|
|
5518
6541
|
id: message.id,
|
|
@@ -5610,6 +6633,7 @@ ${tab.url}`.toLowerCase();
|
|
|
5610
6633
|
}
|
|
5611
6634
|
}
|
|
5612
6635
|
ui.destroy();
|
|
6636
|
+
pendingStop.clear();
|
|
5613
6637
|
if (win.__zenMcpBridge?.windowId === windowId) {
|
|
5614
6638
|
delete win.__zenMcpBridge;
|
|
5615
6639
|
}
|