diff --git a/docs/references/architecture-gm-api.md b/docs/references/architecture-gm-api.md index 8282aae48..b39ee74b0 100644 --- a/docs/references/architecture-gm-api.md +++ b/docs/references/architecture-gm-api.md @@ -12,7 +12,8 @@ across contexts to a privileged handler, then streams the result back. The imple — the privileged half: permission verification, cross-origin requests, DNR rule building. - **Offscreen side** ([`src/app/service/offscreen/gm_api.ts`](../../src/app/service/offscreen/gm_api.ts)) — DOM-dependent operations for background scripts (page-context XHR, `window.open`, clipboard). -- **Values** flow through `ValueService` and are broadcast so every tab running the same script sees updates. +- **Values** flow through `ValueService` and are pushed to every frame running a script with the same storage + name; see [Value updates](#value-updates). ### Registration: the `@GMContext.API` decorator @@ -54,6 +55,34 @@ The **persistent connection** (`MessageConnect`, opened via `connect()`) matters back in chunks rather than returned by a single request/reply, which is how progress events and large bodies work. +### Value updates + +`GM_setValue` / `GM_setValues` are saved by `ValueService.setValues` +([`service_worker/value.ts`](../../src/app/service/service_worker/value.ts)) under a per-storage-name lock. Each +save gets a new, increasing `revision`, stored on the `Value` record and sent with the update. Updates reach +other frames over one value Port per content-script frame +([`content/value_port.ts`](../../src/app/service/content/value_port.ts) ↔ +[`service_worker/value_port.ts`](../../src/app/service/service_worker/value_port.ts)); the SW keeps the +storage-name → Port index in memory only. + +- **Writer receipt.** The writer's own update comes back in the `GM_setValue` RPC response, not only through + the Port. The Port push for the same update id is then ignored, so the writer neither waits on a lost push + nor fires its listeners twice. +- **Subscription and resync.** The Port is dropped whenever the SW stops, and is reopened when a page is + restored from bfcache. On every (re)connect the frame sends, per storage name, the last `revision` it knows and the script uuids it + runs. `ValueService.subscribeSnapshot` registers the Port and reads the stored revision inside the same + write lock, so a concurrent save is either included in the reply or pushed to the newly registered Port. + If the revisions differ, the reply carries a snapshot of each script's values. The frame buffers pushes + until that reply arrives and drops any push whose revision is not newer than what it already has. +- **Listener semantics after a gap.** If the scripts are still loading, the snapshot replaces the values they + will start with. Once they are running, `runtime/valueSync` compares the snapshot with the cached values key + by key and fires `GM_addValueChangeListener` once per changed key with `remote = true`. Intermediate values + missed during the gap are not replayed. +- **Reconnect policy.** A Port that was acknowledged and stayed up for at least a second reconnects + immediately when it drops. Otherwise the frame retries with backoff, so a SW that keeps failing cannot cause + a tight reconnect loop. Once the extension context is invalidated (reload, update, uninstall), the frame + stops reconnecting. + ### Adding a GM API (sketch) 1. Add the method to the content `GMApi` with `@GMContext.API({ alias: "GM.foo" })`. diff --git a/src/app/repo/scripts.ts b/src/app/repo/scripts.ts index 301ba7304..209a138f1 100644 --- a/src/app/repo/scripts.ts +++ b/src/app/repo/scripts.ts @@ -105,6 +105,7 @@ export type PageScriptResource = Record { diff --git a/src/app/service/content/create_context.test.ts b/src/app/service/content/create_context.test.ts index 058e59c95..13fcc00c6 100644 --- a/src/app/service/content/create_context.test.ts +++ b/src/app/service/content/create_context.test.ts @@ -413,6 +413,31 @@ describe("createContext: capability and lifecycle contract", () => { expect(contextValues.loadScriptResolve).toBeUndefined(); }); + it("valueSync 只对变化的键更新缓存并以 remote=true 触发监听,删除的键也会通知", () => { + const script = createScriptInfo(); + script.value = { same: 1, changed: "old", removed: { a: 1 } }; + const context = createContext( + script, + {}, + "vitest", + undefined as any, + undefined as any, + new Set(["GM_addValueChangeListener", "GM_getValue"]) + ); + const listener = vi.fn(); + for (const key of ["same", "changed", "removed", "added"]) context.GM_addValueChangeListener(key, listener); + + context.valueSync({ same: 1, changed: "new", added: [1] }); + + expect(listener.mock.calls).toEqual([ + ["changed", "old", "new", true, undefined], + ["removed", { a: 1 }, undefined, true, undefined], + ["added", undefined, [1], true, undefined], + ]); + expect(context.GM_getValue("changed")).toBe("new"); + expect(context.GM_getValue("removed")).toBeUndefined(); + }); + it("失效清理是 idempotent,且舊 value listener 不再收到更新", () => { const script = createScriptInfo(); const context = createContext( diff --git a/src/app/service/content/exec_script.ts b/src/app/service/content/exec_script.ts index ae8ee47c7..1fa7d7e63 100644 --- a/src/app/service/content/exec_script.ts +++ b/src/app/service/content/exec_script.ts @@ -78,6 +78,10 @@ export default class ExecScript { this.sandboxContext?.valueUpdate(data); } + valueSync(values: Record) { + this.sandboxContext?.valueSync(values); + } + execContext: any; /** diff --git a/src/app/service/content/gm_api/gm_api.test.ts b/src/app/service/content/gm_api/gm_api.test.ts index d09336d0a..c050f2a3c 100644 --- a/src/app/service/content/gm_api/gm_api.test.ts +++ b/src/app/service/content/gm_api/gm_api.test.ts @@ -1212,6 +1212,70 @@ return { value1, value2, value3, values1,values2, allValues1, allValues2, value4 const ret2 = await retPromise; expect(ret2).toEqual({ name: "param2", oldValue: undefined, newValue: 456, remote: true }); }); + // SW 处理写入后把同一份更新数据作为 RPC 响应返回;按 Port 推送的那份可能因 SW 重启而丢失 + const createReceiptExec = (code: string, holdResponse = false) => { + const script = Object.assign({ uuid: uuidv4() }, scriptRes) as ScriptLoadInfo; + script.value = {}; + script.metadata = { ...scriptRes.metadata, grant: ["GM.setValue", "GM_addValueChangeListener"] }; + script.code = code; + const responses: any[] = []; + let release: () => void = () => undefined; + const held = new Promise((resolve) => (release = resolve)); + const mockSendMessage = vi.fn().mockImplementation(async (msg: any) => { + const [id, key, value] = msg.data.params; + const data = { + id, + entries: [[key, encodeRValue(value), encodeRValue(undefined)]], + uuid: script.uuid, + storageName: script.uuid, + sender: { runFlag: msg.data.runFlag, tabId: 3 }, + valueUpdated: true, + }; + responses.push(data); + if (holdResponse) await held; + return { code: 0, data }; + }); + const exec = new ExecScript(script, { + envPrefix: "scripting", + message: { sendMessage: mockSendMessage } as unknown as Message, + contentMsg: undefined as any, + code: nilFn, + envInfo, + }); + exec.scriptFunc = compileScript(compileScriptCode(script)); + return { exec, responses, release }; + }; + const listenAndSet = ` + const calls = []; + GM_addValueChangeListener("k", (name, oldValue, newValue, remote) => calls.push([oldValue, newValue, remote])); + await GM.setValue("k", 1); + await new Promise((resolve) => setTimeout(resolve, 50)); + return calls; + `; + + it.concurrent("GM.setValue 没有收到推送时,凭 SW 的响应完成,并触发自身监听一次", async () => { + const { exec } = createReceiptExec(listenAndSet); + expect(await exec.exec()).toEqual([[undefined, 1, false]]); + }); + + it.concurrent("推送晚于响应到达时只处理一次", async () => { + const { exec, responses } = createReceiptExec(listenAndSet); + const ret = exec.exec(); + await vi.waitFor(() => expect(responses).toHaveLength(1)); + await Promise.resolve(); + exec.valueUpdate(responses[0]); + expect(await ret).toEqual([[undefined, 1, false]]); + }); + + it.concurrent("推送早于响应到达时只处理一次", async () => { + const { exec, responses, release } = createReceiptExec(listenAndSet, true); + const ret = exec.exec(); + await vi.waitFor(() => expect(responses).toHaveLength(1)); + exec.valueUpdate(responses[0]); + release(); + expect(await ret).toEqual([[undefined, 1, false]]); + }); + it.concurrent("异步GM.setValue,等待回调", async () => { const script = Object.assign({}, scriptRes) as ScriptLoadInfo; script.metadata.grant = ["GM.getValue", "GM.setValue"]; diff --git a/src/app/service/content/gm_api/gm_api.ts b/src/app/service/content/gm_api/gm_api.ts index d9c52c8e4..0c9149832 100644 --- a/src/app/service/content/gm_api/gm_api.ts +++ b/src/app/service/content/gm_api/gm_api.ts @@ -45,6 +45,7 @@ export interface IGM_Base { sendMessage(api: string, params: any[]): Promise; connect(api: string, params: any[]): Promise; valueUpdate(data: ValueUpdateDataEncoded): void; + valueSync(values: Record): void; emitEvent(event: string, eventId: string, data: any): void; } @@ -61,6 +62,11 @@ let valChangeRandomId = `${randNum(8e11, 2e12).toString(36)}`; const valueChangePromiseMap = new Map(); +// 本 world 发起的写入,其更新会经 RPC 响应和 Port 推送各到达一次,谁先到谁处理,后到的按 id 跳过。 +// 只记录处理过一次的 id;推送丢失时第二份永远不会到,所以限制数量,淘汰最早的。 +const handledOwnValueIds = new Set(); +const HANDLED_OWN_VALUE_IDS_LIMIT = 1024; + const execEnvInit = (execEnv: GMApi) => { if (!execEnv.contentEnvKey) { execEnv.contentEnvKey = randomMessageFlag(); // 不重复识别字串。用于区分 mainframe subframe 等执行环境 @@ -176,6 +182,11 @@ class GM_Base implements IGM_Base { const valueStore = scriptRes.value; const remote = sender.runFlag !== this.runFlag; if (!remote && id) { + if (handledOwnValueIds.delete(id)) return; + handledOwnValueIds.add(id); + if (handledOwnValueIds.size > HANDLED_OWN_VALUE_IDS_LIMIT) { + handledOwnValueIds.delete(handledOwnValueIds.values().next().value!); + } const fn = valueChangePromiseMap.get(id); if (fn) { valueChangePromiseMap.delete(id); @@ -201,6 +212,22 @@ class GM_Base implements IGM_Base { } } + // 重订阅补齐:快照只有最终值,逐键对比本地缓存,对变化的键更新并以 remote=true 触发监听 + @GMContext.protected() + public valueSync(values: Record) { + if (!this.scriptRes || !this.valueChangeListener) return; + const valueStore = this.scriptRes.value; + const encode = (value: unknown) => JSON.stringify(encodeRValue(value)); + for (const key of new Set([...Object.keys(valueStore), ...Object.keys(values)])) { + const oldValue = valueStore[key]; + const value = values[key]; + if (encode(oldValue) === encode(value)) continue; + if (value === undefined) delete valueStore[key]; + else valueStore[key] = value; + this.valueChangeListener.execute(key, oldValue, value, true, undefined); + } + } + @GMContext.protected() emitEvent(event: string, eventId: string, data: any) { if (!this.EE) return; @@ -292,9 +319,10 @@ export default class GMApi extends GM_Base { if (promise) { valueChangePromiseMap.set(id, promise); } + let params: [string, string] | [string, string, unknown]; if (value === undefined) { delete a.scriptRes.value[key]; - a.sendMessage("GM_setValue", [id, key]); + params = [id, key]; } else { // 对object的value进行一次转化 if (value && typeof value === "object") { @@ -302,12 +330,9 @@ export default class GMApi extends GM_Base { } // customClone 可能返回 undefined a.scriptRes.value[key] = value; - if (value === undefined) { - a.sendMessage("GM_setValue", [id, key]); - } else { - a.sendMessage("GM_setValue", [id, key, value]); - } + params = value === undefined ? [id, key] : [id, key, value]; } + a.sendMessage("GM_setValue", params).then((ret) => ret && a.valueUpdate(ret)); return id; } @@ -339,7 +364,7 @@ export default class GMApi extends GM_Base { // 避免undefined 等空值流失,先进行映射处理 keyValuePairs.push([key, encodeRValue(value_)]); } - a.sendMessage("GM_setValues", [id, keyValuePairs]); + a.sendMessage("GM_setValues", [id, keyValuePairs]).then((ret) => ret && a.valueUpdate(ret)); return id; } diff --git a/src/app/service/content/page_load_contract.ts b/src/app/service/content/page_load_contract.ts index fdb53dd5b..4432c0e87 100644 --- a/src/app/service/content/page_load_contract.ts +++ b/src/app/service/content/page_load_contract.ts @@ -25,6 +25,7 @@ const PAGE_LOAD_SCRIPT_OPTIONAL_KEYS = [ "requireCssResource", "userConfig", "scriptUrlPatterns", + "valueRevision", ] as const; type PageLoadScriptRequiredKey = (typeof PAGE_LOAD_SCRIPT_REQUIRED_KEYS)[number]; diff --git a/src/app/service/content/script_executor.test.ts b/src/app/service/content/script_executor.test.ts index a4fe6c02a..991a012aa 100644 --- a/src/app/service/content/script_executor.test.ts +++ b/src/app/service/content/script_executor.test.ts @@ -3,6 +3,7 @@ import type { Message } from "@Packages/message/types"; import type { ScriptLoadInfo } from "../service_worker/types"; import type { TScriptInfo } from "@App/app/repo/scripts"; import { initEnvInfo, ScriptExecutor } from "./script_executor"; +import type ExecScript from "./exec_script"; const styleUrl = "https://example.com/style.css"; const secondStyleUrl = "https://example.com/second-style.css"; @@ -129,4 +130,17 @@ describe("ScriptExecutor", () => { expect((adoptedSheets[0] as CSSStyleSheet & { cssText: string }).cssText).toBe("body { color: green; }"); }); }); + + it("valueSync 只把快照交给 uuid 对应的脚本", () => { + const executor = new ScriptExecutor({} as Message, {} as Message); + const target = { scriptRes: { uuid: "a" }, valueSync: vi.fn() }; + const other = { scriptRes: { uuid: "b" }, valueSync: vi.fn() }; + executor.execScriptMap.set("a", target as unknown as ExecScript); + executor.execScriptMap.set("b", other as unknown as ExecScript); + + executor.valueSync({ storageName: "s", values: { a: { k: 1 } } }); + + expect(target.valueSync).toHaveBeenCalledExactlyOnceWith({ k: 1 }); + expect(other.valueSync).not.toHaveBeenCalled(); + }); }); diff --git a/src/app/service/content/script_executor.ts b/src/app/service/content/script_executor.ts index b4ccc0e44..250600fd7 100644 --- a/src/app/service/content/script_executor.ts +++ b/src/app/service/content/script_executor.ts @@ -2,7 +2,7 @@ import type { Message } from "@Packages/message/types"; import { getStorageName } from "@App/pkg/utils/utils"; import type { EmitEventRequest } from "../service_worker/types"; import ExecScript from "./exec_script"; -import type { GMInfoEnv, ScriptFunc, ValueUpdateDataEncoded } from "./types"; +import type { GMInfoEnv, ScriptFunc, ValueSyncData, ValueUpdateDataEncoded } from "./types"; import { addStyleSheet, definePropertyListener, waitBody } from "./utils"; import type { ScriptLoadInfo, TScriptInfo } from "@App/app/repo/scripts"; import { DefinedFlags } from "../service_worker/runtime.consts"; @@ -58,6 +58,14 @@ export class ScriptExecutor { } } + valueSync(data: ValueSyncData) { + // runtime/valueSync + for (const val of this.execScriptMap.values()) { + const values = data.values[val.scriptRes.uuid]; + if (values) val.valueSync(values); + } + } + startScripts(scripts: TScriptInfo[], envInfo: GMInfoEnv) { const loadExec = (script: TScriptInfo, scriptFunc: any) => { this.execScriptEntry({ diff --git a/src/app/service/content/script_runtime.ts b/src/app/service/content/script_runtime.ts index 817dd2a23..55523d737 100644 --- a/src/app/service/content/script_runtime.ts +++ b/src/app/service/content/script_runtime.ts @@ -3,7 +3,7 @@ import type { Message } from "@Packages/message/types"; import { initEnvInfo, type ScriptExecutor } from "./script_executor"; import type { TScriptInfo } from "@App/app/repo/scripts"; import type { EmitEventRequest } from "../service_worker/types"; -import type { GMInfoEnv, ValueUpdateDataEncoded } from "./types"; +import type { GMInfoEnv, ValueSyncData, ValueUpdateDataEncoded } from "./types"; import type { ScriptEnvTag } from "@Packages/message/consts"; import { onInjectPageLoaded } from "./external"; import type { CustomEventMessage } from "@Packages/message/custom_event_message"; @@ -62,6 +62,9 @@ export class ScriptRuntime { this.server.on("runtime/valueUpdate", (data: ValueUpdateDataEncoded) => { this.scriptExecutor.valueUpdate(data); }); + this.server.on("runtime/valueSync", (data: ValueSyncData) => { + this.scriptExecutor.valueSync(data); + }); this.server.on("pageLoad", (data: { scripts: TScriptInfo[]; envInfo: GMInfoEnv }) => { // 监听事件 diff --git a/src/app/service/content/scripting.test.ts b/src/app/service/content/scripting.test.ts new file mode 100644 index 000000000..2c91c3de3 --- /dev/null +++ b/src/app/service/content/scripting.test.ts @@ -0,0 +1,281 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; +import type { Server } from "@Packages/message/server"; +import type { MessageConnect, MessageSend, TMessage } from "@Packages/message/types"; +import type { CustomEventMessage } from "@Packages/message/custom_event_message"; +import ScriptingRuntime from "./scripting"; +import type { ValueUpdateDataEncoded } from "./types"; +import { encodeRValue } from "@App/pkg/utils/message_value"; + +type Handler = (data: any) => any; + +const createServer = () => { + const handlers = new Map(); + return { + server: { on: (name: string, fn: Handler) => handlers.set(name, fn) } as unknown as Server, + handlers, + }; +}; + +const createPageSender = () => { + const sendMessage = vi.fn().mockResolvedValue({ code: 0, data: undefined }); + return { sender: { sendMessage } as unknown as CustomEventMessage, sendMessage }; +}; + +const valueUpdate = (storageName: string): ValueUpdateDataEncoded => ({ + id: "id-1", + entries: [["k", "v", undefined] as any], + uuid: "uuid-1", + storageName, + sender: { runFlag: "", tabId: 1 }, + valueUpdated: true, +}); + +const actionsOf = (fn: ReturnType) => fn.mock.calls.map(([msg]) => msg.action); + +describe("ScriptingRuntime 值更新投递", () => { + let storageListeners: Array<(changes: Record) => void>; + let originalOnChanged: unknown; + + // ScriptingRuntime 没有销毁接口,它注册的 pageshow 监听会留在共享的 window 上; + // 测试间 vi.resetAllMocks 清掉 mock 实现后,别的文件派发 pageshow 会触发这些残留监听而报错 + const pageShowListeners: EventListenerOrEventListenerObject[] = []; + const originalAddEventListener = EventTarget.prototype.addEventListener; + + beforeEach(() => { + vi.spyOn(window, "addEventListener").mockImplementation( + ( + type: string, + listener: EventListenerOrEventListenerObject | null, + options?: boolean | AddEventListenerOptions + ) => { + if (type === "pageshow" && listener) pageShowListeners.push(listener); + originalAddEventListener.call(window, type, listener, options); + } + ); + storageListeners = []; + originalOnChanged = (chrome.storage.local as any).onChanged; + (chrome.storage.local as any).onChanged = { + addListener: (fn: (typeof storageListeners)[number]) => storageListeners.push(fn), + }; + }); + + afterEach(() => { + for (const listener of pageShowListeners.splice(0)) window.removeEventListener("pageshow", listener); + vi.mocked(window.addEventListener).mockRestore(); + (chrome.storage.local as any).onChanged = originalOnChanged; + }); + + const setup = (pageLoadData?: unknown) => { + const ext = createServer(); + const page = createServer(); + const toContent = createPageSender(); + const toInject = createPageSender(); + let portMessage: (message: TMessage) => void = () => undefined; + const portSend = vi.fn(); + const onPortMessage = vi.fn((fn: (message: TMessage) => void) => (portMessage = fn)); + const port = { + sendMessage: portSend, + onMessage: onPortMessage, + onDisconnect: vi.fn(), + disconnect: vi.fn(), + } as unknown as MessageConnect; + const senderToExt = { + sendMessage: vi.fn().mockResolvedValue({ code: 0, data: pageLoadData ?? { ok: false } }), + connect: vi.fn().mockResolvedValue(port), + } as unknown as MessageSend; + const runtime = new ScriptingRuntime(ext.server, page.server, senderToExt, toContent.sender, toInject.sender); + runtime.init(); + return { + runtime, + ext, + toContent, + toInject, + portSend, + onPortMessage, + receive: (message: TMessage) => portMessage(message), + }; + }; + + // 每个页面的每个 frame 都有 scripting.js;若它监听 storage.local,任何一次 local 写入 + // (包括整包 value:*)的新旧值都会被序列化投递到所有 frame,见 #1834。 + it("chrome.storage.local 的变化不会被转发给页面", async () => { + const { toContent, toInject } = setup(); + + for (const fn of storageListeners) { + fn({ + valueUpdateDelivery: { newValue: { rId: "1", sendData: valueUpdate("s1") } }, + "value:s1": { newValue: { data: { k: "v" } }, oldValue: { data: {} } }, + }); + } + await Promise.resolve(); + + expect(storageListeners).toHaveLength(0); + expect(toContent.sendMessage).not.toHaveBeenCalled(); + expect(toInject.sendMessage).not.toHaveBeenCalled(); + }); + + it("Port 只转发给当前 frame 运行的脚本世界,且先订阅再启动脚本", async () => { + const { runtime, toContent, toInject, portSend, onPortMessage, receive } = setup({ + ok: true, + injectScriptList: [ + { uuid: "a", metadata: { storagename: ["page-store"] } }, + { uuid: "c", metadata: { storagename: ["shared"] } }, + ], + contentScriptList: [ + { uuid: "b", metadata: { storagename: ["content-store"] } }, + { uuid: "d", metadata: { storagename: ["shared"] } }, + { uuid: "e", metadata: { storagename: ["__proto__"] } }, + ], + envInfo: {}, + }); + runtime.pageLoad(); + await vi.waitFor(() => expect(onPortMessage).toHaveBeenCalledOnce()); + receive({ code: 0, data: { ready: true } }); + await vi.waitFor(() => + expect(portSend).toHaveBeenCalledWith({ + action: "runtime/subscribeValueUpdates", + data: [ + { storageName: "page-store", revision: 0, uuids: ["a"] }, + { storageName: "shared", revision: 0, uuids: ["c", "d"] }, + { storageName: "content-store", revision: 0, uuids: ["b"] }, + { storageName: "__proto__", revision: 0, uuids: ["e"] }, + ], + }) + ); + expect(toContent.sendMessage).not.toHaveBeenCalled(); + expect(toInject.sendMessage).not.toHaveBeenCalled(); + + receive({ action: "runtime/valueSubscriptionsReady" }); + await vi.waitFor(() => expect(actionsOf(toInject.sendMessage)).toContain("inject/pageLoad")); + toContent.sendMessage.mockClear(); + toInject.sendMessage.mockClear(); + + receive({ action: "runtime/valueUpdate", data: valueUpdate("shared") }); + await Promise.resolve(); + expect(actionsOf(toContent.sendMessage)).toEqual(["content/runtime/valueUpdate"]); + expect(actionsOf(toInject.sendMessage)).toEqual(["inject/runtime/valueUpdate"]); + toContent.sendMessage.mockClear(); + toInject.sendMessage.mockClear(); + + receive({ action: "runtime/valueUpdate", data: valueUpdate("__proto__") }); + await Promise.resolve(); + expect(actionsOf(toContent.sendMessage)).toEqual(["content/runtime/valueUpdate"]); + expect(toInject.sendMessage).not.toHaveBeenCalled(); + toContent.sendMessage.mockClear(); + + receive({ action: "runtime/valueUpdate", data: valueUpdate("page-store") }); + await Promise.resolve(); + expect(actionsOf(toInject.sendMessage)).toEqual(["inject/runtime/valueUpdate"]); + expect(toContent.sendMessage).not.toHaveBeenCalled(); + + toInject.sendMessage.mockClear(); + receive({ action: "runtime/valueUpdate", data: valueUpdate("content-store") }); + await Promise.resolve(); + expect(actionsOf(toContent.sendMessage)).toEqual(["content/runtime/valueUpdate"]); + expect(toInject.sendMessage).not.toHaveBeenCalled(); + + toContent.sendMessage.mockClear(); + receive({ action: "runtime/valueUpdate", data: valueUpdate("other-store") }); + await Promise.resolve(); + expect(toContent.sendMessage).not.toHaveBeenCalled(); + expect(toInject.sendMessage).not.toHaveBeenCalled(); + }); + + describe("按版本补齐", () => { + const script = (uuid: string, storageName: string, valueRevision: number, value: Record = {}) => ({ + uuid, + metadata: { storagename: [storageName] }, + value, + valueRevision, + }); + const pushed = (storageName: string, revision: number | undefined, key = "k", value: unknown = "pushed") => + ({ + ...valueUpdate(storageName), + entries: [[key, encodeRValue(value), encodeRValue(undefined)]], + revision, + }) as ValueUpdateDataEncoded; + const pageLoadScripts = (send: ReturnType) => + send.mock.calls.find(([msg]) => msg.action === "inject/pageLoad")![0].data.scripts; + + const loadAndSubscribe = async (setupResult: ReturnType) => { + setupResult.runtime.pageLoad(); + await vi.waitFor(() => expect(setupResult.onPortMessage).toHaveBeenCalledOnce()); + setupResult.receive({ code: 0, data: { ready: true } }); + await vi.waitFor(() => expect(setupResult.portSend).toHaveBeenCalled()); + }; + + it("订阅带上 pageLoad 读到的版本;同一存储的脚本读到的版本不同时取最小值", async () => { + const ctx = setup({ + ok: true, + injectScriptList: [script("a", "s", 7), script("b", "s", 5)], + contentScriptList: [], + envInfo: {}, + }); + await loadAndSubscribe(ctx); + expect(ctx.portSend).toHaveBeenCalledWith({ + action: "runtime/subscribeValueUpdates", + data: [{ storageName: "s", revision: 5, uuids: ["a", "b"] }], + }); + }); + + it("首次订阅确认里的快照和确认前到达的推送,都在脚本启动前合并进 pageLoad 数据", async () => { + const ctx = setup({ + ok: true, + injectScriptList: [script("a", "s", 1, { k: "old", other: 1 })], + contentScriptList: [], + envInfo: {}, + }); + await loadAndSubscribe(ctx); + ctx.receive({ action: "runtime/valueUpdate", data: pushed("s", 3, "late", "pushed") }); + ctx.receive({ + action: "runtime/valueSubscriptionsReady", + data: [{ storageName: "s", revision: 2, values: { a: { k: "snapshot" } } }], + }); + await vi.waitFor(() => expect(actionsOf(ctx.toInject.sendMessage)).toContain("inject/pageLoad")); + + expect(pageLoadScripts(ctx.toInject.sendMessage)[0].value).toEqual({ k: "snapshot", late: "pushed" }); + expect(actionsOf(ctx.toInject.sendMessage)).toEqual(["inject/pageLoad"]); + }); + + it("脚本启动后:版本不比已知版本新的推送丢弃,重连确认里的快照以 runtime/valueSync 发给对应世界", async () => { + const ctx = setup({ + ok: true, + injectScriptList: [script("a", "s", 1)], + contentScriptList: [], + envInfo: {}, + }); + await loadAndSubscribe(ctx); + ctx.receive({ action: "runtime/valueSubscriptionsReady", data: [{ storageName: "s", revision: 1 }] }); + await vi.waitFor(() => expect(actionsOf(ctx.toInject.sendMessage)).toContain("inject/pageLoad")); + ctx.toInject.sendMessage.mockClear(); + + for (const revision of [5, 5, 4, 6, undefined]) { + ctx.receive({ action: "runtime/valueUpdate", data: pushed("s", revision) }); + } + await Promise.resolve(); + expect(ctx.toInject.sendMessage.mock.calls.map(([msg]) => msg.data.revision)).toEqual([5, 6, undefined]); + ctx.toInject.sendMessage.mockClear(); + + const values = { a: { k: "synced" } }; + ctx.receive({ action: "runtime/valueSubscriptionsReady", data: [{ storageName: "s", revision: 9, values }] }); + await Promise.resolve(); + expect(ctx.toInject.sendMessage).toHaveBeenCalledWith( + expect.objectContaining({ action: "inject/runtime/valueSync", data: { storageName: "s", values } }) + ); + ctx.toInject.sendMessage.mockClear(); + ctx.receive({ action: "runtime/valueUpdate", data: pushed("s", 9) }); + await Promise.resolve(); + expect(ctx.toInject.sendMessage).not.toHaveBeenCalled(); + }); + }); + + it("pageLoad 没有运行脚本的 frame 不会订阅,释放 Port", async () => { + const { runtime, toContent, toInject, portSend } = setup(); + runtime.pageLoad(); + await Promise.resolve(); + await Promise.resolve(); + expect(portSend).not.toHaveBeenCalled(); + expect(toContent.sendMessage).not.toHaveBeenCalled(); + expect(toInject.sendMessage).not.toHaveBeenCalled(); + }); +}); diff --git a/src/app/service/content/scripting.ts b/src/app/service/content/scripting.ts index 7286d82b0..3eb70ac41 100644 --- a/src/app/service/content/scripting.ts +++ b/src/app/service/content/scripting.ts @@ -6,7 +6,10 @@ import { RuntimeClient } from "../service_worker/client"; import { getStorageName, makeBlobURL } from "@App/pkg/utils/utils"; import type { Logger } from "@App/app/repo/logger"; import LoggerCore from "@App/app/logger/core"; -import type { ValueUpdateDataEncoded } from "./types"; +import type { ValueSubscription, ValueSubscriptionAck, ValueUpdateDataEncoded } from "./types"; +import type { TScriptInfo } from "@App/app/repo/scripts"; +import { decodeRValue } from "@App/pkg/utils/message_value"; +import ScriptingValuePort from "./value_port"; const PageOrContent = { PAGE: 1, @@ -16,14 +19,15 @@ const PageOrContent = { type PageOrContent = ValueOf; -// For Firefox, StorageArea.setAccessLevel is not implemented. -// See https://bugzilla.mozilla.org/show_bug.cgi?id=1724754 -// const deliveryStorage = isFirefox() ? chrome.storage.local : chrome.storage.session; -const deliveryStorage = chrome.storage.local; // 日后再处理 - // scripting页的处理 export default class ScriptingRuntime { - private activeStorageNames: Map | null = null; + private activeStorageNames = new Map(); + // 每个 storageName 已应用到的版本;重订阅时交给 SW 判断是否漏收,收到推送时据此去重 + private readonly knownRevisions = new Map(); + private readonly uuidsByStorageName = new Map(); + // 还没交给 content/inject 启动的脚本;这期间的快照和推送直接合并进它们的 value + private pendingScripts: TScriptInfo[] | undefined; + private readonly valuePort: ScriptingValuePort; constructor( // 监听来自service_worker的消息 private readonly extServer: Server, @@ -35,7 +39,68 @@ export default class ScriptingRuntime { private readonly senderToContent: CustomEventMessage, // 发送给inject的消息接口 private readonly senderToInject: CustomEventMessage - ) {} + ) { + this.valuePort = new ScriptingValuePort( + this.senderToExt, + (data) => this.forwardValueUpdate(data), + (acks) => this.applySubscriptionAcks(acks) + ); + } + + private valueSubscriptions(): ValueSubscription[] { + return [...this.activeStorageNames.keys()].map((storageName) => ({ + storageName, + revision: this.knownRevisions.get(storageName) ?? 0, + uuids: this.uuidsByStorageName.get(storageName) ?? [], + })); + } + + private applySubscriptionAcks(acks: ValueSubscriptionAck[]) { + for (const { storageName, revision, values } of acks) { + const activeOn = this.activeStorageNames.get(storageName); + if (!activeOn) continue; + this.knownRevisions.set(storageName, revision); + if (!values) continue; + if (this.pendingScripts) { + for (const script of this.pendingScripts) { + if (values[script.uuid]) script.value = values[script.uuid]; + } + } else { + this.sendToPage("runtime/valueSync", { storageName, values }, activeOn); + } + } + } + + private forwardValueUpdate(data: ValueUpdateDataEncoded) { + const { storageName, revision } = data; + const activeOn = this.activeStorageNames.get(storageName); + if (!activeOn) return; + if (data.valueUpdated && revision !== undefined) { + // 已经包含在快照里,或者重复到达 + if (revision <= (this.knownRevisions.get(storageName) ?? -1)) return; + this.knownRevisions.set(storageName, revision); + } + if (this.pendingScripts) { + // 脚本还没启动,页面里没有 GMApi 能接收;直接改写将要下发的初始值 + if (!data.valueUpdated) return; + for (const script of this.pendingScripts) { + if (script.uuid !== data.uuid && getStorageName(script) !== storageName) continue; + for (const [key, encoded] of data.entries) { + const value = decodeRValue(encoded); + if (value === undefined) delete script.value[key]; + else script.value[key] = value; + } + } + return; + } + this.sendToPage("runtime/valueUpdate", data, activeOn); + } + + private sendToPage(action: string, data: unknown, activeOn: PageOrContent) { + void this.broadcastToPage(action, data, activeOn).catch((error) => { + LoggerCore.logger().error("forward value message failed", { action, error }); + }); + } // 广播消息给 content 和 inject broadcastToPage( @@ -50,41 +115,15 @@ export default class ScriptingRuntime { } init() { + this.valuePort.start(); this.extServer.on("runtime/emitEvent", (data) => { // 转发给inject和content return this.broadcastToPage("runtime/emitEvent", data); }); - this.extServer.on("runtime/valueUpdate", (data) => { - // 转发给inject和content - return this.broadcastToPage("runtime/valueUpdate", data); - }); this.server.on("logger", (data: Logger) => { LoggerCore.logger().log(data.level, data.message, data.label); }); - // ================================ - // 来自 service_worker 的投递:storage 广播(类似 UDP) - // ================================ - - // 接收 service_worker 的 chrome.storage.local 值改变通知 (一对多广播) - // 类似 UDP 原理,service_worker 不会有任何「等待处理」 - // 由于 changes 会包括新旧值 (Chrome: JSON serialization, Firefox: Structured Clone) - // 因此需要注意资讯量不要过大导致 onChanged 的触发过慢 - deliveryStorage.onChanged.addListener((changes) => { - const record = changes["valueUpdateDelivery"]; - if (record?.newValue) { - const sendData = (record.newValue as { sendData: ValueUpdateDataEncoded }).sendData; - const activeOn = - this.activeStorageNames === null - ? PageOrContent.PAGE_AND_CONTENT - : this.activeStorageNames.get(sendData.storageName); - if (activeOn) { - // 转发给 content 和 inject - this.broadcastToPage("runtime/valueUpdate", sendData, activeOn); - } - } - }); - forwardMessage("serviceWorker", "script/isInstalled", this.server, this.senderToExt); forwardMessage( "serviceWorker", @@ -157,17 +196,36 @@ export default class ScriptingRuntime { }); } // 向service_worker请求脚本列表及环境信息 - client.pageLoad().then((o) => { - if (!o.ok) return; + client.pageLoad().then(async (o) => { + if (!o.ok) { + this.valuePort.stop(); + return; + } const { injectScriptList, contentScriptList, envInfo } = o; - const pairs = {} as Record; + const pairs = new Map(); for (const script of injectScriptList) { - pairs[getStorageName(script)] |= PageOrContent.PAGE; + const name = getStorageName(script); + pairs.set(name, ((pairs.get(name) || 0) | PageOrContent.PAGE) as PageOrContent); } for (const script of contentScriptList) { - pairs[getStorageName(script)] |= PageOrContent.CONTENT; + const name = getStorageName(script); + pairs.set(name, ((pairs.get(name) || 0) | PageOrContent.CONTENT) as PageOrContent); + } + this.activeStorageNames = pairs; + for (const script of [...injectScriptList, ...contentScriptList]) { + const name = getStorageName(script); + // 同一存储的脚本读取 value 的时刻可能不同,取最早的版本,宁可多补一次快照 + const known = this.knownRevisions.get(name); + const revision = script.valueRevision ?? 0; + this.knownRevisions.set(name, known === undefined ? revision : Math.min(known, revision)); + this.uuidsByStorageName.set(name, [...(this.uuidsByStorageName.get(name) ?? []), script.uuid]); } - this.activeStorageNames = new Map(Object.entries(pairs)); + + // 先确认中央已建立订阅,再启动页面脚本:早期 GM.setValue 的回执不会落入订阅空窗, + // pageLoad 读取 value 之后到订阅确认之前的写入也会经快照或推送合并进初始值。 + this.pendingScripts = [...injectScriptList, ...contentScriptList]; + await this.valuePort.subscribe(() => this.valueSubscriptions()); + this.pendingScripts = undefined; // 向页面 发送脚本列表及环境信息 if (contentScriptList.length) { diff --git a/src/app/service/content/types.ts b/src/app/service/content/types.ts index 87962e4a4..7a510cc41 100644 --- a/src/app/service/content/types.ts +++ b/src/app/service/content/types.ts @@ -30,6 +30,26 @@ export type ValueUpdateDataEncoded = { storageName: string; // 储存name sender: ValueUpdateSender; valueUpdated: boolean; + revision?: number; // 这次操作之后该存储的版本 +}; + +// 一个 frame 对一个 storageName 的订阅:带上已知版本和运行中的脚本,SW 发现版本不一致时按脚本下发快照 +export type ValueSubscription = { + storageName: string; + revision: number; + uuids: string[]; +}; + +// 重订阅补齐时下发给脚本世界:uuid → 该脚本当前的全部值 +export type ValueSyncData = { + storageName: string; + values: Record>; +}; + +export type ValueSubscriptionAck = { + storageName: string; + revision: number; + values?: Record>; // uuid → 该脚本当前的全部值 }; // gm_api.ts diff --git a/src/app/service/content/value_port.integration.test.ts b/src/app/service/content/value_port.integration.test.ts new file mode 100644 index 000000000..a573273bd --- /dev/null +++ b/src/app/service/content/value_port.integration.test.ts @@ -0,0 +1,42 @@ +import EventEmitter from "eventemitter3"; +import { describe, expect, it, vi } from "vitest"; +import { MockMessage } from "@Packages/message/mock_message"; +import { Server } from "@Packages/message/server"; +import ValueUpdatePorts from "../service_worker/value_port"; +import ScriptingValuePort from "./value_port"; +import type { ValueUpdateDataEncoded } from "./types"; + +describe("scripting ↔ serviceWorker Port 通道", () => { + it("实际消息 Server/Group 协议能完成订阅确认并精准传递 GM 更新", async () => { + const transport = new MockMessage(new EventEmitter()); + const server = new Server("serviceWorker", transport); + const failures = vi.fn(); + const ports = new ValueUpdatePorts(failures, async (sub, register) => { + register(); + return { storageName: sub.storageName, revision: sub.revision }; + }); + server.group("runtime").on("valueUpdates", (_, sender) => ports.connect(sender)); + const received = vi.fn(); + const channel = new ScriptingValuePort(transport, received, vi.fn()); + channel.start(); + + await channel.subscribe(() => [{ storageName: "script-a", revision: 0, uuids: ["uuid-a"] }]); + const update: ValueUpdateDataEncoded = { + uuid: "uuid-a", + storageName: "script-a", + id: "set-1", + entries: [], + sender: { runFlag: "", tabId: 1 }, + valueUpdated: true, + }; + ports.push("script-a", update); + ports.push("script-b", { ...update, storageName: "script-b" }); + + expect(received).toHaveBeenCalledExactlyOnceWith(update); + expect(failures).not.toHaveBeenCalled(); + channel.stop(); + received.mockClear(); + ports.push("script-a", update); + expect(received).not.toHaveBeenCalled(); + }); +}); diff --git a/src/app/service/content/value_port.test.ts b/src/app/service/content/value_port.test.ts new file mode 100644 index 000000000..e92ccf00e --- /dev/null +++ b/src/app/service/content/value_port.test.ts @@ -0,0 +1,320 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import type { MessageConnect, MessageSend, TMessage } from "@Packages/message/types"; +import ScriptingValuePort from "./value_port"; +import type { ValueSubscription } from "./types"; + +const subs = (...names: string[]): ValueSubscription[] => + names.map((storageName) => ({ storageName, revision: 0, uuids: [] })); + +class TestPort implements MessageConnect { + sent: TMessage[] = []; + private messageListener: (message: TMessage) => void = () => undefined; + private disconnectListener: (self: boolean) => void = () => undefined; + sendMessage(message: TMessage) { + this.sent.push(message); + } + onMessage(callback: (message: TMessage) => void) { + this.messageListener = callback; + } + onDisconnect(callback: (self: boolean) => void) { + this.disconnectListener = callback; + } + disconnect() { + this.disconnectListener(false); + } + receive(message: TMessage) { + this.messageListener(message); + } +} + +const createSender = (...ports: TestPort[]) => { + const connect = vi.fn().mockImplementation(async () => { + const port = ports.shift(); + if (!port) throw new Error("no test port available"); + return port; + }); + return { sender: { connect } as unknown as MessageSend, connect }; +}; + +describe("ScriptingValuePort 生命周期", () => { + afterEach(() => { + vi.useRealTimers(); + }); + + it("启动即连接,待 SW 确认订阅后才放行页面脚本,按 Port 接收值更新", async () => { + const port = new TestPort(); + const { sender, connect } = createSender(port); + const delivered = vi.fn(); + const channel = new ScriptingValuePort(sender, delivered, vi.fn()); + channel.start(); + const ready = channel.subscribe(() => subs("shared", "content")); + await vi.waitFor(() => expect(connect).toHaveBeenCalledOnce()); + expect(connect).toHaveBeenCalledWith({ action: "serviceWorker/runtime/valueUpdates" }); + port.receive({ code: 0, data: { ready: true } }); + expect(port.sent).toEqual([{ action: "runtime/subscribeValueUpdates", data: subs("shared", "content") }]); + + let subscribed = false; + void ready.then(() => (subscribed = true)); + await Promise.resolve(); + expect(subscribed).toBe(false); + port.receive({ action: "runtime/valueSubscriptionsReady" }); + await ready; + expect(subscribed).toBe(true); + + const update = { storageName: "shared", entries: [] }; + port.receive({ action: "runtime/valueUpdate", data: update }); + expect(delivered).toHaveBeenCalledWith(update); + channel.stop(); + }); + + it("确认前收到的推送先缓存;确认后先交出订阅结果,再按顺序放出缓存的推送", async () => { + const port = new TestPort(); + const { sender } = createSender(port); + const events: unknown[] = []; + const channel = new ScriptingValuePort( + sender, + (data) => events.push(["update", data]), + (acks) => events.push(["ack", acks]) + ); + channel.start(); + const ready = channel.subscribe(() => subs("a")); + await Promise.resolve(); + port.receive({ code: 0, data: { ready: true } }); + port.receive({ action: "runtime/valueUpdate", data: { storageName: "a", revision: 1 } }); + port.receive({ action: "runtime/valueUpdate", data: { storageName: "a", revision: 2 } }); + expect(events).toEqual([]); + + const acks = [{ storageName: "a", revision: 1, values: { u: { k: 1 } } }]; + port.receive({ action: "runtime/valueSubscriptionsReady", data: acks }); + await ready; + expect(events).toEqual([ + ["ack", acks], + ["update", { storageName: "a", revision: 1 }], + ["update", { storageName: "a", revision: 2 }], + ]); + port.receive({ action: "runtime/valueUpdate", data: { storageName: "a", revision: 3 } }); + expect(events).toHaveLength(4); + channel.stop(); + }); + + it("重连时重新取订阅,带上最新的已知版本", async () => { + vi.useFakeTimers(); + const oldPort = new TestPort(); + const newPort = new TestPort(); + const { sender } = createSender(oldPort, newPort); + const channel = new ScriptingValuePort(sender, vi.fn(), vi.fn()); + let revision = 3; + channel.start(); + const ready = channel.subscribe(() => [{ storageName: "a", revision, uuids: ["u"] }]); + await Promise.resolve(); + oldPort.receive({ code: 0, data: { ready: true } }); + oldPort.receive({ action: "runtime/valueSubscriptionsReady", data: [] }); + await ready; + await vi.advanceTimersByTimeAsync(30_000); + + revision = 8; + oldPort.disconnect(); + await Promise.resolve(); + newPort.receive({ code: 0, data: { ready: true } }); + expect(newPort.sent).toEqual([ + { action: "runtime/subscribeValueUpdates", data: [{ storageName: "a", revision: 8, uuids: ["u"] }] }, + ]); + channel.stop(); + }); + + it("断连重建 Port 并恢复存储订阅,旧 Port 不再使用", async () => { + vi.useFakeTimers(); + const oldPort = new TestPort(); + const newPort = new TestPort(); + const { sender, connect } = createSender(oldPort, newPort); + const channel = new ScriptingValuePort(sender, vi.fn(), vi.fn()); + channel.start(); + const ready = channel.subscribe(() => subs("a")); + await Promise.resolve(); + oldPort.receive({ code: 0, data: { ready: true } }); + oldPort.receive({ action: "runtime/valueSubscriptionsReady" }); + await ready; + + oldPort.disconnect(); + await vi.advanceTimersByTimeAsync(1000); + expect(connect).toHaveBeenCalledTimes(2); + newPort.receive({ code: 0, data: { ready: true } }); + expect(newPort.sent).toEqual([{ action: "runtime/subscribeValueUpdates", data: subs("a") }]); + newPort.receive({ action: "runtime/valueSubscriptionsReady" }); + channel.stop(); + }); + + const subscribeAndAck = async (channel: ScriptingValuePort, port: TestPort) => { + const ready = channel.subscribe(() => subs("a")); + await Promise.resolve(); + port.receive({ code: 0, data: { ready: true } }); + port.receive({ action: "runtime/valueSubscriptionsReady" }); + await ready; + }; + + it("已确认订阅的 Port 被动断开(SW 休眠或重启)后立即重连,不等待退避", async () => { + vi.useFakeTimers(); + const oldPort = new TestPort(); + const newPort = new TestPort(); + const { sender, connect } = createSender(oldPort, newPort); + const channel = new ScriptingValuePort(sender, vi.fn(), vi.fn()); + channel.start(); + await subscribeAndAck(channel, oldPort); + await vi.advanceTimersByTimeAsync(30_000); + + oldPort.disconnect(); + await Promise.resolve(); + expect(connect).toHaveBeenCalledTimes(2); + channel.stop(); + }); + + it("确认订阅后很快又断开时按退避重试,避免 SW 反复崩溃时陷入重连死循环", async () => { + vi.useFakeTimers(); + const oldPort = new TestPort(); + const newPort = new TestPort(); + const { sender, connect } = createSender(oldPort, newPort); + const channel = new ScriptingValuePort(sender, vi.fn(), vi.fn()); + channel.start(); + await subscribeAndAck(channel, oldPort); + + oldPort.disconnect(); + await Promise.resolve(); + expect(connect).toHaveBeenCalledOnce(); + await vi.advanceTimersByTimeAsync(1000); + expect(connect).toHaveBeenCalledTimes(2); + channel.stop(); + }); + + describe("扩展上下文失效(扩展重载、更新或卸载)", () => { + const runtime = chrome.runtime as { id?: string }; + const extensionId = runtime.id; + afterEach(() => { + runtime.id = extensionId; + }); + + it("连接失败后停止,不再设定重试", async () => { + vi.useFakeTimers(); + const errorSpy = vi.spyOn(console, "error").mockImplementation(() => undefined); + try { + const { sender, connect } = createSender(); + const channel = new ScriptingValuePort(sender, vi.fn(), vi.fn()); + runtime.id = undefined; + channel.start(); + await vi.advanceTimersByTimeAsync(60_000); + expect(connect).toHaveBeenCalledOnce(); + expect(vi.getTimerCount()).toBe(0); + expect(errorSpy).not.toHaveBeenCalled(); + } finally { + errorSpy.mockRestore(); + } + }); + + it("Port 断开后停止,不再重连", async () => { + vi.useFakeTimers(); + const port = new TestPort(); + const { sender, connect } = createSender(port, new TestPort()); + const channel = new ScriptingValuePort(sender, vi.fn(), vi.fn()); + channel.start(); + await subscribeAndAck(channel, port); + await vi.advanceTimersByTimeAsync(30_000); + + runtime.id = undefined; + port.disconnect(); + await vi.advanceTimersByTimeAsync(60_000); + expect(connect).toHaveBeenCalledOnce(); + expect(vi.getTimerCount()).toBe(0); + }); + }); + + it("没有脚本的 frame 释放 Port,不再尝试重连", async () => { + vi.useFakeTimers(); + const port = new TestPort(); + const { sender, connect } = createSender(port); + const channel = new ScriptingValuePort(sender, vi.fn(), vi.fn()); + channel.start(); + await Promise.resolve(); + await channel.subscribe(() => []); + port.disconnect(); + await vi.advanceTimersByTimeAsync(5000); + expect(connect).toHaveBeenCalledOnce(); + }); + + it("bfcache 恢复时主动重建 Port,确保新 SW 知道订阅", async () => { + const oldPort = new TestPort(); + const newPort = new TestPort(); + const { sender, connect } = createSender(oldPort, newPort); + const channel = new ScriptingValuePort(sender, vi.fn(), vi.fn()); + channel.start(); + const ready = channel.subscribe(() => subs("a")); + await Promise.resolve(); + expect(connect).toHaveBeenCalledOnce(); + oldPort.receive({ code: 0, data: { ready: true } }); + oldPort.receive({ action: "runtime/valueSubscriptionsReady" }); + await ready; + + const pageshow = new PageTransitionEvent("pageshow"); + // happy-dom 未实现 PageTransitionEvent.persisted,补上浏览器会提供的字段。 + Object.defineProperty(pageshow, "persisted", { value: true }); + expect(pageshow.persisted).toBe(true); + window.dispatchEvent(pageshow); + await Promise.resolve(); + expect(connect).toHaveBeenCalledTimes(2); + newPort.receive({ code: 0, data: { ready: true } }); + expect(newPort.sent).toEqual([{ action: "runtime/subscribeValueUpdates", data: subs("a") }]); + channel.stop(); + }); + + it("bfcache 恢复时旧连接仍在建立也能重连,迟到的旧 Port 不覆盖新 Port", async () => { + let resolveOld!: (port: MessageConnect) => void; + const oldPortPromise = new Promise((resolve) => (resolveOld = resolve)); + const newPort = new TestPort(); + const oldPort = new TestPort(); + const oldDisconnect = vi.spyOn(oldPort, "disconnect"); + const connect = vi.fn().mockReturnValueOnce(oldPortPromise).mockResolvedValueOnce(newPort); + const channel = new ScriptingValuePort({ connect } as unknown as MessageSend, vi.fn(), vi.fn()); + channel.start(); + const ready = channel.subscribe(() => subs("a")); + + const pageshow = new PageTransitionEvent("pageshow"); + Object.defineProperty(pageshow, "persisted", { value: true }); + window.dispatchEvent(pageshow); + await vi.waitFor(() => expect(connect).toHaveBeenCalledTimes(2)); + + resolveOld(oldPort); + await Promise.resolve(); + newPort.receive({ code: 0, data: { ready: true } }); + expect(newPort.sent).toEqual([{ action: "runtime/subscribeValueUpdates", data: subs("a") }]); + expect(oldPort.sent).toEqual([]); + expect(oldDisconnect).toHaveBeenCalledOnce(); + newPort.receive({ action: "runtime/valueSubscriptionsReady" }); + await ready; + channel.stop(); + }); + + it("订阅发送时 Port 已经断开则重试,而非永久卡住 pageLoad", async () => { + vi.useFakeTimers(); + const oldPort = new TestPort(); + const newPort = new TestPort(); + const { sender, connect } = createSender(oldPort, newPort); + const channel = new ScriptingValuePort(sender, vi.fn(), vi.fn()); + const errorSpy = vi.spyOn(console, "error").mockImplementation(() => undefined); + try { + channel.start(); + const ready = channel.subscribe(() => subs("a")); + await Promise.resolve(); + oldPort.sendMessage = () => { + throw new Error("closed"); + }; + oldPort.receive({ code: 0, data: { ready: true } }); + await vi.advanceTimersByTimeAsync(1000); + expect(connect).toHaveBeenCalledTimes(2); + newPort.receive({ code: 0, data: { ready: true } }); + newPort.receive({ action: "runtime/valueSubscriptionsReady" }); + await ready; + expect(errorSpy).toHaveBeenCalledOnce(); + channel.stop(); + } finally { + errorSpy.mockRestore(); + } + }); +}); diff --git a/src/app/service/content/value_port.ts b/src/app/service/content/value_port.ts new file mode 100644 index 000000000..22ea0a30f --- /dev/null +++ b/src/app/service/content/value_port.ts @@ -0,0 +1,175 @@ +import type { MessageConnect, MessageSend } from "@Packages/message/types"; +import type { ValueSubscription, ValueSubscriptionAck, ValueUpdateDataEncoded } from "./types"; + +// 确认订阅后存活不到这么久就断开,视为 SW 异常,改为退避重试,避免反复崩溃时重连死循环。 +const STABLE_PORT_MS = 1000; + +// 扩展重载、更新或卸载后,旧页面里的 content script 失去扩展上下文,再也连不上新的 SW。 +const isContextInvalidated = () => !chrome.runtime?.id; + +// 由 scripting 持有;SW 重启后重连并重新上报 frame 的脚本订阅。 +export default class ScriptingValuePort { + private port: MessageConnect | undefined; + private connecting = false; + private connectionGeneration = 0; + private portReady = false; + private stopped = false; + private getSubscriptions: (() => ValueSubscription[]) | undefined; + // 订阅确认之前收到的推送;确认里的快照要先应用,之后才能按版本判断这些推送是否已包含在快照里 + private buffered: ValueUpdateDataEncoded[] | undefined; + private subscribeDone: (() => void) | undefined; + private retryTimer: ReturnType | undefined; + private retryDelay = 250; + private ackedAt: number | undefined; + private readonly onPageShow = (event: PageTransitionEvent) => { + if (!event.persisted || this.stopped) return; + // bfcache 可冻结整个 JS 上下文;恢复后重新向新的 SW 建立索引。 + const port = this.port; + this.port = undefined; + this.portReady = false; + // 冻结前发出的 connect Promise 可能在恢复后才完成,不能接受其旧 Port。 + this.connectionGeneration++; + this.connecting = false; + port?.disconnect(true); + if (this.retryTimer !== undefined) clearTimeout(this.retryTimer); + this.retryTimer = undefined; + this.connect(); + }; + + constructor( + private readonly sender: MessageSend, + private readonly onValueUpdate: (data: ValueUpdateDataEncoded) => void, + private readonly onSubscribed: (acks: ValueSubscriptionAck[]) => void + ) {} + + start() { + this.connect(); + window.addEventListener("pageshow", this.onPageShow); + } + + // 每次(重新)订阅时现取:重连后要带上最新的已知版本 + subscribe(getSubscriptions: () => ValueSubscription[]): Promise { + if (getSubscriptions().length === 0) { + this.stop(); + return Promise.resolve(); + } + this.getSubscriptions = getSubscriptions; + return new Promise((resolve) => { + this.subscribeDone = resolve; + this.sendSubscriptions(); + }); + } + + stop() { + this.stopped = true; + this.connectionGeneration++; + this.connecting = false; + window.removeEventListener("pageshow", this.onPageShow); + if (this.retryTimer !== undefined) clearTimeout(this.retryTimer); + this.retryTimer = undefined; + const port = this.port; + this.port = undefined; + port?.disconnect(true); + } + + private connect() { + if (this.stopped || this.connecting || this.port) return; + this.connecting = true; + const generation = this.connectionGeneration; + this.sender + .connect({ action: "serviceWorker/runtime/valueUpdates" }) + .then((port) => { + if (this.stopped || generation !== this.connectionGeneration) { + port.disconnect(true); + return; + } + this.connecting = false; + this.port = port; + this.portReady = false; + this.buffered = []; + port.onMessage((message) => { + if (this.port !== port) return; + if (message.code === 0 && message.data?.ready === true) { + this.portReady = true; + this.sendSubscriptions(); + } else if (message.action === "runtime/valueSubscriptionsReady") { + this.retryDelay = 250; + this.ackedAt = Date.now(); + this.onSubscribed(Array.isArray(message.data) ? message.data : []); + const buffered = this.buffered ?? []; + this.buffered = undefined; + for (const data of buffered) this.onValueUpdate(data); + this.subscribeDone?.(); + this.subscribeDone = undefined; + } else if (message.code === -1) { + this.failPort(port, message.message); + } else if (message.action === "runtime/valueUpdate") { + const data = message.data as ValueUpdateDataEncoded; + if (this.buffered) this.buffered.push(data); + else this.onValueUpdate(data); + } + }); + port.onDisconnect(() => { + if (this.port !== port) return; + this.port = undefined; + this.portReady = false; + if (isContextInvalidated()) { + this.stop(); + return; + } + const ackedAt = this.ackedAt; + this.ackedAt = undefined; + // SW 空闲回收或重启时 Port 被动断开;立刻重连能把漏收更新的窗口缩到一次握手 + if (ackedAt !== undefined && Date.now() - ackedAt >= STABLE_PORT_MS) { + this.connect(); + } else { + this.scheduleReconnect(); + } + }); + }) + .catch((error: unknown) => { + if (this.stopped || generation !== this.connectionGeneration) return; + this.connecting = false; + if (isContextInvalidated()) { + this.stop(); + return; + } + console.error("value update Port connection failed", error); + this.scheduleReconnect(); + }); + } + + private sendSubscriptions() { + if (this.portReady && this.port && this.getSubscriptions) { + try { + this.port.sendMessage({ action: "runtime/subscribeValueUpdates", data: this.getSubscriptions() }); + } catch (error) { + this.failPort(this.port, error); + } + } + } + + private failPort(port: MessageConnect, error: unknown) { + if (this.port !== port) return; + this.port = undefined; + this.portReady = false; + port.disconnect(true); + if (isContextInvalidated()) { + this.stop(); + return; + } + console.error("value update Port failed", error); + this.scheduleReconnect(); + } + + private scheduleReconnect() { + if (this.stopped || this.retryTimer !== undefined) return; + // 错峰退避,避免 SW 重启后所有 frame 同时建立 Port。 + const delay = this.retryDelay + Math.random() * this.retryDelay; + this.retryDelay = Math.min(this.retryDelay * 2, 10000); + this.retryTimer = setTimeout(() => { + this.retryTimer = undefined; + this.connect(); + }, delay); + } +} diff --git a/src/app/service/service_worker/gm_api/gm_api.ts b/src/app/service/service_worker/gm_api/gm_api.ts index a658951ed..0021f8950 100644 --- a/src/app/service/service_worker/gm_api/gm_api.ts +++ b/src/app/service/service_worker/gm_api/gm_api.ts @@ -600,7 +600,7 @@ export default class GMApi { runFlag: request.runFlag, tabId: sender.getSender()?.tab?.id || -1, }; - await this.value.setValues({ uuid: request.script.uuid, id, keyValuePairs, isReplace: false, valueSender }); + return this.value.setValues({ uuid: request.script.uuid, id, keyValuePairs, isReplace: false, valueSender }); } @PermissionVerify.API({ link: ["GM_deleteValues"] }) @@ -613,7 +613,7 @@ export default class GMApi { runFlag: request.runFlag, tabId: sender.getSender()?.tab?.id || -1, }; - await this.value.setValues({ uuid: request.script.uuid, id, keyValuePairs, isReplace: false, valueSender }); + return this.value.setValues({ uuid: request.script.uuid, id, keyValuePairs, isReplace: false, valueSender }); } @PermissionVerify.API() diff --git a/src/app/service/service_worker/index.ts b/src/app/service/service_worker/index.ts index 70b9d7e92..e74d1bd32 100644 --- a/src/app/service/service_worker/index.ts +++ b/src/app/service/service_worker/index.ts @@ -156,7 +156,7 @@ export default class ServiceWorkerManager { runtime.init(); const popup = new PopupService(this.api.group("popup"), this.mq, runtime, scriptDAO, systemConfig); popup.init(); - value.init(runtime, popup); + value.init(runtime); const synchronize = new SynchronizeService( this.offscreenSend, this.api.group("synchronize"), diff --git a/src/app/service/service_worker/runtime.test.ts b/src/app/service/service_worker/runtime.test.ts index ac35581be..45f4fe7a9 100644 --- a/src/app/service/service_worker/runtime.test.ts +++ b/src/app/service/service_worker/runtime.test.ts @@ -11,7 +11,7 @@ import { } from "@App/app/repo/scripts"; import { buildScriptRunResourceBasic, getCombinedMeta, scriptURLPatternResults } from "./utils"; import type { SystemConfig } from "@App/pkg/config/config"; -import { SenderRuntime, type Group } from "@Packages/message/server"; +import { SenderRuntime, type Group, type IGetSender } from "@Packages/message/server"; import type { ServiceWorkerMessageSend, WindowMessageBody } from "@Packages/message/window_message"; import type { IMessageQueue } from "@Packages/message/message_queue"; import type { ValueService } from "./value"; @@ -541,7 +541,7 @@ describe.concurrent("RuntimeService - getPageScriptMatchingResultByUrl 脚本匹 }; const mockValueService = { - getScriptValue: vi.fn().mockResolvedValue({}), + getScriptValueDetails: vi.fn().mockResolvedValue([{}, { revision: 42 }]), }; (mockScriptDAO as any).gets = vi.fn().mockResolvedValue([script]); @@ -573,8 +573,10 @@ describe.concurrent("RuntimeService - getPageScriptMatchingResultByUrl 脚本匹 expect(result).not.toBeNull(); expect(mockCompiledResourceDAO.gets).toHaveBeenCalledTimes(1); expect(mockScriptCodeDAO.get).toHaveBeenCalledWith(script.uuid); - expect(mockValueService.getScriptValue).toHaveBeenCalledTimes(1); + expect(mockValueService.getScriptValueDetails).toHaveBeenCalledTimes(1); expect(result!.injectScriptList.length + result!.contentScriptList.length).toBe(1); + // 页面据此在重订阅时判断是否漏收了更新 + expect([...result!.injectScriptList, ...result!.contentScriptList][0].valueRevision).toBe(42); }); it("第二次请求命中缓存,不再调用 compiledResourceDAO,但每次都重新加载 value", async () => { @@ -587,7 +589,7 @@ describe.concurrent("RuntimeService - getPageScriptMatchingResultByUrl 脚本匹 expect(mockCompiledResourceDAO.gets).toHaveBeenCalledTimes(1); expect(mockScriptCodeDAO.get).toHaveBeenCalledTimes(1); - expect(mockValueService.getScriptValue).toHaveBeenCalledTimes(2); + expect(mockValueService.getScriptValueDetails).toHaveBeenCalledTimes(2); }); it("deleteScriptRuntimeCache 后下一次请求重新从 DAO 获取 compiledResource", async () => { @@ -995,7 +997,7 @@ describe("getScriptsForTab 附加边界场景", () => { getScriptResourceValue: vi.fn().mockResolvedValue({}), getScriptResourceValueByType: vi.fn().mockResolvedValue({ require: {}, "require-css": {}, resource: {} }), }; - const mockValueService = { getScriptValue: vi.fn().mockResolvedValue({}) }; + const mockValueService = { getScriptValueDetails: vi.fn().mockResolvedValue([{}, { revision: 42 }]) }; (mockScriptDAO as any).gets = vi.fn().mockResolvedValue([script]); (mockScriptDAO as any).scriptCodeDAO = mockScriptCodeDAO; @@ -1480,6 +1482,53 @@ describe("pushValueUpdate 判断是否需要为 early-start 脚本重新编译", }); }); +describe("pushValueUpdate 页面投递", () => { + it("直接向订阅 storageName 的 Port 投递,不使用 tabs API 或 storage 广播", async () => { + const { runtime } = _createRuntimeContext(); + (runtime as unknown as { value: Pick }).value = { + subscribeSnapshot: async (sub, register) => { + register(); + return { storageName: sub.storageName, revision: sub.revision }; + }, + }; + const script = _createMockScript(); + const sendData = { + id: "id-1", + entries: [], + uuid: script.uuid, + storageName: "test-storage", + sender: { runFlag: "", tabId: 2 }, + valueUpdated: false, + }; + let onMessage: (message: TMessage) => void = () => undefined; + const postMessage = vi.fn(); + const port = { + sendMessage: postMessage, + onMessage: (callback: (message: TMessage) => void) => (onMessage = callback), + onDisconnect: vi.fn(), + } as unknown as MessageConnect; + runtime.connectValueUpdates(undefined, { getConnect: () => port } as unknown as IGetSender); + onMessage({ + action: "runtime/subscribeValueUpdates", + data: [{ storageName: "test-storage", revision: 0, uuids: [script.uuid] }], + }); + await vi.waitFor(() => + expect(postMessage).toHaveBeenCalledWith(expect.objectContaining({ action: "runtime/valueSubscriptionsReady" })) + ); + postMessage.mockClear(); + const tabsSpy = vi.spyOn(chrome.tabs, "sendMessage"); + const querySpy = vi.spyOn(chrome.tabs, "query"); + const setSpy = vi.spyOn(chrome.storage.local, "set"); + + await runtime.pushValueUpdate(script, sendData); + + expect(postMessage).toHaveBeenCalledExactlyOnceWith({ action: "runtime/valueUpdate", data: sendData }); + expect(tabsSpy).not.toHaveBeenCalled(); + expect(querySpy).not.toHaveBeenCalled(); + expect(setSpy).not.toHaveBeenCalled(); + }); +}); + describe("registerUserscripts 注册健康检查", () => { let runtime: RuntimeService; let originalScripting: unknown; diff --git a/src/app/service/service_worker/runtime.ts b/src/app/service/service_worker/runtime.ts index ec2ba95d6..ff0fb2f15 100644 --- a/src/app/service/service_worker/runtime.ts +++ b/src/app/service/service_worker/runtime.ts @@ -64,6 +64,7 @@ import { parseUserConfig } from "@App/pkg/utils/yaml"; import type { CompiledResource, Resource, ResourceType } from "@App/app/repo/resource"; import { CompiledResourceDAO, CompiledResourceNamespace } from "@App/app/repo/resource"; import { setOnTabURLChanged } from "./url_monitor"; +import ValueUpdatePorts from "./value_port"; import { scriptToMenu, type TPopupPageLoadInfo, type TPopupPageRestoreInfo } from "./popup_scriptmenu"; import { getExtensionUserAgentData } from "../extension/extension_env"; @@ -131,12 +132,13 @@ export type TScriptsForTab = { const bgScriptStorageNames = new Set(); -// For Firefox, StorageArea.setAccessLevel is not implemented. -// See https://bugzilla.mozilla.org/show_bug.cgi?id=1724754 -// const deliveryStorage = isFirefox() ? chrome.storage.local : chrome.storage.session; -const deliveryStorage = chrome.storage.local; // 日后再处理 - export class RuntimeService { + private readonly valuePorts = new ValueUpdatePorts( + (context, error) => { + this.logger.error("value update Port delivery failed", context, Logger.E(error)); + }, + (sub, register) => this.value.subscribeSnapshot(sub, register) + ); scriptMatchEnable: UrlMatch = new UrlMatch(); blackMatch: UrlMatch = new UrlMatch(); private gmApi?: GMApi; @@ -477,13 +479,8 @@ export class RuntimeService { public async pushValueUpdate(script: Script, sendData: ValueUpdateDataEncoded) { try { - // 前台腳本 (推送值到tab) - await deliveryStorage!.set({ - valueUpdateDelivery: { - rId: `${Date.now()}.${Math.random()}`, // 用于区分不同的更新,确保 deliveryStorage.onChanged 必能触发 - sendData, - }, - }); + // 直接推送给订阅该 storageName 的存活 frame,不经过 tabs API 或无关 iframe(#1834)。 + this.valuePorts.push(sendData.storageName, sendData); // 後台腳本 if (bgScriptStorageNames.has(sendData.storageName)) { @@ -511,19 +508,12 @@ export class RuntimeService { } } - async setSessionAccessLevel() { - try { - // 让 scripting 存取 chrome.storage.session - await chrome.storage.session.setAccessLevel({ accessLevel: "TRUSTED_AND_UNTRUSTED_CONTEXTS" }); - } catch (e) { - this.logger.error("set session storage access level failed", Logger.E(e)); - } + public connectValueUpdates(_: unknown, sender: IGetSender) { + return this.valuePorts.connect(sender); } init() { - if (deliveryStorage === chrome.storage.session) { - this.setSessionAccessLevel(); - } + this.group.on("valueUpdates", this.connectValueUpdates.bind(this)); // 启动gm api const permission = new PermissionVerify(this.group.group("permission"), this.mq); this.gmApi = new GMApi( @@ -1619,7 +1609,9 @@ export class RuntimeService { await Promise.all( enableScriptList.map(async (script) => { // value(GM 值)会在页面间变化,必须每次页面加载都实时读取,绝不能走页面加载缓存。 - script.value = await value.getScriptValue(script); + const [values, record] = await value.getScriptValueDetails(script); + script.value = values; + script.valueRevision = record?.revision ?? 0; }) ); diff --git a/src/app/service/service_worker/trash_freeze.test.ts b/src/app/service/service_worker/trash_freeze.test.ts index 67baf063f..9ccd06629 100644 --- a/src/app/service/service_worker/trash_freeze.test.ts +++ b/src/app/service/service_worker/trash_freeze.test.ts @@ -13,7 +13,6 @@ import EventEmitter from "eventemitter3"; import type { ResourceService } from "./resource"; import { createMockOPFS } from "@App/app/repo/test-helpers"; import type { RuntimeService } from "./runtime"; -import type { PopupService } from "./popup"; initTestEnv(); @@ -61,7 +60,7 @@ describe("回收站期间的数据冻结", () => { valueDAO = new ValueDAO(); // 真实挂载 ValueService,使其订阅 deleteScripts const valueService = new ValueService(server.group("value"), mq); - valueService.init({} as RuntimeService, {} as PopupService); + valueService.init({} as RuntimeService); service = new ScriptService( systemConfig, server.group("script"), diff --git a/src/app/service/service_worker/value.test.ts b/src/app/service/service_worker/value.test.ts index 7dcc2ae9a..db2d2cda9 100644 --- a/src/app/service/service_worker/value.test.ts +++ b/src/app/service/service_worker/value.test.ts @@ -20,7 +20,6 @@ import { TrashScriptDAO, type TrashScript } from "@App/app/repo/trash_script"; import type { TDeleteScript } from "@App/app/service/queue"; import { createMockOPFS } from "@App/app/repo/test-helpers"; import type { RuntimeService } from "./runtime"; -import type { PopupService } from "./popup"; initTestEnv(); @@ -151,6 +150,54 @@ describe("ValueService - setValue 方法测试", () => { expect(savedValue.updatetime).toBeTypeOf("number"); }); + it("返回与推送相同的更新数据,写入方可凭 RPC 响应完成回执,不依赖推送到达", async () => { + const mockScript = createMockScript(); + vi.mocked(mockScriptDAO.get).mockResolvedValue(mockScript); + vi.mocked(mockValueDAO.get).mockResolvedValue(undefined); + vi.mocked(mockValueDAO.save).mockResolvedValue({} as any); + + const ret = await valueService.setValues({ + uuid: mockScript.uuid, + id: "receipt-id", + keyValuePairs: [["k", encodeRValue(1)]], + valueSender: createMockValueSender(), + isReplace: false, + }); + + expect(ret).toBe(vi.mocked(valueService.pushValueUpdate).mock.calls[0][1]); + expect(ret).toMatchObject({ id: "receipt-id", valueUpdated: true }); + }); + + it("保存时版本号单调递增并随推送下发,值未改变时沿用当前版本", async () => { + const mockScript = createMockScript(); + vi.mocked(mockScriptDAO.get).mockResolvedValue(mockScript); + let stored: Value | undefined; + vi.mocked(mockValueDAO.get).mockImplementation(async () => stored); + vi.mocked(mockValueDAO.save).mockImplementation(async (_: string, model: Value) => { + stored = model; + return model; + }); + const set = (value: unknown) => + valueService.setValues({ + uuid: mockScript.uuid, + keyValuePairs: [["k", encodeRValue(value)]], + valueSender: createMockValueSender(), + isReplace: false, + }); + + const before = Date.now() * 1000; + const first = await set(1); + expect(first.revision).toBeGreaterThanOrEqual(before); + expect(stored!.revision).toBe(first.revision); + // 时钟没走也要比上一次大 + vi.spyOn(Date, "now").mockReturnValue(0); + const second = await set(2); + expect(second.revision).toBe(first.revision! + 1); + const unchanged = await set(2); + expect(unchanged.valueUpdated).toBe(false); + expect(unchanged.revision).toBe(second.revision); + }); + it("应该成功设置新脚本的值 (storageName fallback)", async () => { // 准备测试数据 const mockScript = createMockScript(); @@ -463,7 +510,7 @@ describe("ValueService —— 共享 storagename 的回收站感知", () => { const server = new Server("test", new MockMessage(eventEmitter)); const mq = new MessageQueue(); const service = new ValueService(server.group("value"), mq); - service.init({} as RuntimeService, {} as PopupService); + service.init({} as RuntimeService); const trashDAO = new TrashScriptDAO(); const valueDAO = new ValueDAO(); @@ -510,7 +557,7 @@ describe("ValueService —— 共享 storagename 的回收站感知", () => { const server = new Server("test", new MockMessage(eventEmitter)); const mq = new MessageQueue(); const service = new ValueService(server.group("value"), mq); - service.init({} as RuntimeService, {} as PopupService); + service.init({} as RuntimeService); const valueDAO = new ValueDAO(); const lonely = "lonely-storage"; @@ -528,3 +575,137 @@ describe("ValueService —— 共享 storagename 的回收站感知", () => { expect(await valueDAO.get(lonely)).toBeUndefined(); }); }); + +describe("ValueService pushValueUpdate 投递目标", () => { + const setup = () => { + const server = new Server("test", new MockMessage(new EventEmitter())); + const service = new ValueService(server.group("value"), new MessageQueue()); + const runtime = { pushValueUpdate: vi.fn().mockResolvedValue(undefined) }; + service.init(runtime as unknown as RuntimeService); + return { service, runtime }; + }; + const script = { uuid: "uuid-1", metadata: {} } as Script; + const sendData = (tabId: number) => ({ + id: "id-1", + entries: [], + uuid: "uuid-1", + storageName: "store", + sender: { runFlag: "", tabId }, + valueUpdated: true, + }); + + it("直接交给 Port 索引投递,发起方 tabId 不影响选择", async () => { + const { service, runtime } = setup(); + + await service.pushValueUpdate(script, sendData(1)); + await service.pushValueUpdate(script, sendData(-1)); + + expect(runtime.pushValueUpdate).toHaveBeenNthCalledWith(1, script, sendData(1)); + expect(runtime.pushValueUpdate).toHaveBeenNthCalledWith(2, script, sendData(-1)); + }); +}); + +describe("ValueService getScriptValue 合并用户配置默认值", () => { + it("不改写存储记录,共用 storageName 的脚本各自只带自己的默认值", async () => { + const service = new ValueService({ on: vi.fn() } as unknown as Group, new MessageQueue()); + const record: Value = { uuid: "a", storageName: "shared", data: { k: "v" }, createtime: 0, updatetime: 0 }; + service.valueDAO = { get: vi.fn(async () => record) } as unknown as ValueDAO; + const script = (uuid: string, config?: unknown) => + ({ uuid, metadata: { storagename: ["shared"] }, config }) as unknown as Script; + + const plain = await service.getScriptValue(script("a")); + const withConfig = await service.getScriptValue( + script("b", { group: { opt: { title: "opt", type: "text", default: "dflt" } } }) + ); + + expect(withConfig).toEqual({ k: "v", "group.opt": "dflt" }); + expect(plain).toEqual({ k: "v" }); + expect(record.data).toEqual({ k: "v" }); + }); +}); + +describe("ValueService subscribeSnapshot 重订阅补齐", () => { + const storageName = "shared-store"; + const createScript = (uuid: string, overrides: Partial