From 3fcfd23b440a8d5700f04f643d172d3a50308962 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E4=B8=80=E4=B9=8B?= Date: Mon, 9 Nov 2026 13:55:36 +0800 Subject: [PATCH 01/10] =?UTF-8?q?=E2=9A=A1=EF=B8=8F=20GM=20=E5=80=BC?= =?UTF-8?q?=E6=9B=B4=E6=96=B0=E6=94=B9=E4=B8=BA=E5=AE=9A=E5=90=91=E6=8E=A8?= =?UTF-8?q?=E9=80=81=E7=BB=99=E8=BF=90=E8=A1=8C=E8=AF=A5=E8=84=9A=E6=9C=AC?= =?UTF-8?q?=E7=9A=84=E6=A0=87=E7=AD=BE=E9=A1=B5=EF=BC=8C=E4=B8=8D=E5=86=8D?= =?UTF-8?q?=E7=BB=8F=20storage.local=20=E5=B9=BF=E6=92=AD=E5=88=B0?= =?UTF-8?q?=E6=89=80=E6=9C=89=20frame?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit scripting.js 以 + allFrames 注册并监听 chrome.storage.local.onChanged, 任何一次 local 写入(包括整包的 value:*)的新旧值都会被投递并反序列化到所有页面的所有 frame, 存储数据较大或标签页较多时导致 CPU 占用高(#1834)。 - SW 按弹窗的标签页脚本缓存找出运行该 storageName 的标签页,外加发起写入的标签页,逐个 tabs.sendMessage - scripting 去掉 storage.local.onChanged 监听,runtime/valueUpdate 按本 frame 的 storageName 过滤 - 删除不再使用的 deliveryStorage 与 setSessionAccessLevel --- src/app/service/content/scripting.test.ts | 116 ++++++++++++++++++ src/app/service/content/scripting.ts | 40 ++---- src/app/service/service_worker/popup.test.ts | 22 ++++ src/app/service/service_worker/popup.ts | 8 ++ .../service/service_worker/runtime.test.ts | 42 ++++++- src/app/service/service_worker/runtime.ts | 39 +++--- src/app/service/service_worker/value.test.ts | 48 ++++++++ src/app/service/service_worker/value.ts | 17 ++- 8 files changed, 269 insertions(+), 63 deletions(-) create mode 100644 src/app/service/content/scripting.test.ts diff --git a/src/app/service/content/scripting.test.ts b/src/app/service/content/scripting.test.ts new file mode 100644 index 000000000..55efdf000 --- /dev/null +++ b/src/app/service/content/scripting.test.ts @@ -0,0 +1,116 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; +import type { Server } from "@Packages/message/server"; +import type { MessageSend } from "@Packages/message/types"; +import type { CustomEventMessage } from "@Packages/message/custom_event_message"; +import ScriptingRuntime from "./scripting"; +import type { ValueUpdateDataEncoded } from "./types"; + +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; + + beforeEach(() => { + storageListeners = []; + originalOnChanged = (chrome.storage.local as any).onChanged; + (chrome.storage.local as any).onChanged = { + addListener: (fn: (typeof storageListeners)[number]) => storageListeners.push(fn), + }; + }); + + afterEach(() => { + (chrome.storage.local as any).onChanged = originalOnChanged; + }); + + const setup = (pageLoadData?: unknown) => { + const ext = createServer(); + const page = createServer(); + const toContent = createPageSender(); + const toInject = createPageSender(); + const senderToExt = { + sendMessage: vi.fn().mockResolvedValue({ code: 0, data: pageLoadData ?? { ok: false } }), + } as unknown as MessageSend; + const runtime = new ScriptingRuntime(ext.server, page.server, senderToExt, toContent.sender, toInject.sender); + runtime.init(); + return { runtime, ext, toContent, toInject }; + }; + + // 每个页面的每个 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("pageLoad 之后,runtime/valueUpdate 只转发给运行了该 storageName 的一侧", async () => { + const { runtime, ext, toContent, toInject } = setup({ + ok: true, + injectScriptList: [{ uuid: "a", metadata: { storagename: ["page-store"] } }], + contentScriptList: [{ uuid: "b", metadata: { storagename: ["content-store"] } }], + envInfo: {}, + }); + runtime.pageLoad(); + await vi.waitFor(() => expect(actionsOf(toInject.sendMessage)).toContain("inject/pageLoad")); + toContent.sendMessage.mockClear(); + toInject.sendMessage.mockClear(); + + await ext.handlers.get("runtime/valueUpdate")!(valueUpdate("page-store")); + expect(actionsOf(toInject.sendMessage)).toEqual(["inject/runtime/valueUpdate"]); + expect(toContent.sendMessage).not.toHaveBeenCalled(); + + toInject.sendMessage.mockClear(); + await ext.handlers.get("runtime/valueUpdate")!(valueUpdate("content-store")); + expect(actionsOf(toContent.sendMessage)).toEqual(["content/runtime/valueUpdate"]); + expect(toInject.sendMessage).not.toHaveBeenCalled(); + + toContent.sendMessage.mockClear(); + await ext.handlers.get("runtime/valueUpdate")!(valueUpdate("other-store")); + expect(toContent.sendMessage).not.toHaveBeenCalled(); + expect(toInject.sendMessage).not.toHaveBeenCalled(); + }); + + it("pageLoad 尚未返回时,runtime/valueUpdate 同时转发给 page 与 content", async () => { + const { ext, toContent, toInject } = setup(); + + await ext.handlers.get("runtime/valueUpdate")!(valueUpdate("any-store")); + + expect(actionsOf(toContent.sendMessage)).toEqual(["content/runtime/valueUpdate"]); + expect(actionsOf(toInject.sendMessage)).toEqual(["inject/runtime/valueUpdate"]); + }); +}); diff --git a/src/app/service/content/scripting.ts b/src/app/service/content/scripting.ts index 7286d82b0..d97cd58e1 100644 --- a/src/app/service/content/scripting.ts +++ b/src/app/service/content/scripting.ts @@ -16,11 +16,6 @@ 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; @@ -54,37 +49,20 @@ export default class ScriptingRuntime { // 转发给inject和content return this.broadcastToPage("runtime/emitEvent", data); }); - this.extServer.on("runtime/valueUpdate", (data) => { - // 转发给inject和content - return this.broadcastToPage("runtime/valueUpdate", data); + this.extServer.on("runtime/valueUpdate", (data: ValueUpdateDataEncoded) => { + // SW 按标签页投递,同一标签页里没有运行该脚本的 frame 也会收到,需按 storageName 过滤; + // pageLoad 返回前还不知道本 frame 运行哪些脚本,两侧都转发 + const activeOn = + this.activeStorageNames === null + ? PageOrContent.PAGE_AND_CONTENT + : this.activeStorageNames.get(data.storageName); + if (!activeOn) return; + return this.broadcastToPage("runtime/valueUpdate", data, activeOn); }); 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", diff --git a/src/app/service/service_worker/popup.test.ts b/src/app/service/service_worker/popup.test.ts index 2eeaee436..0cb7c751a 100644 --- a/src/app/service/service_worker/popup.test.ts +++ b/src/app/service/service_worker/popup.test.ts @@ -1259,3 +1259,25 @@ describe("PopupService clearTabData 标签页关闭/替换时释放 tab 数据", await expect(service.getScriptMenu(10)).resolves.toEqual([]); }); }); + +describe("PopupService getTabIdsByStorageName 值更新的投递目标", () => { + beforeEach(async () => { + await cacheInstance.clear(); + }); + + it("只返回脚本菜单中运行了该 storageName 的未丢弃标签页", async () => { + await cacheInstance.set(`${CACHE_KEY_TAB_SCRIPT}${1}`, [createMenu("a", { storageName: "shared" })]); + await cacheInstance.set(`${CACHE_KEY_TAB_SCRIPT}${2}`, [createMenu("b", { storageName: "other" })]); + await cacheInstance.set(`${CACHE_KEY_TAB_SCRIPT}${3}`, [createMenu("c", { storageName: "shared" })]); + await cacheInstance.set(`${CACHE_KEY_TAB_SCRIPT}${5}`, [ + createMenu("d", { storageName: "other" }), + createMenu("e", { storageName: "shared" }), + ]); + const tabs = [{ id: 1 }, { id: 2 }, { id: 3, discarded: true }, { id: 4 }, { id: 5 }] as chrome.tabs.Tab[]; + vi.spyOn(chrome.tabs, "query").mockImplementation((() => Promise.resolve(tabs)) as typeof chrome.tabs.query); + + const { service } = createService(); + + await expect(service.getTabIdsByStorageName("shared")).resolves.toEqual([1, 5]); + }); +}); diff --git a/src/app/service/service_worker/popup.ts b/src/app/service/service_worker/popup.ts index 6944e3aa6..995513879 100644 --- a/src/app/service/service_worker/popup.ts +++ b/src/app/service/service_worker/popup.ts @@ -558,6 +558,14 @@ export class PopupService { return (await cacheInstance.get(cacheKey)) || []; } + // 值更新的页面投递目标;被丢弃的标签页没有存活的 content script,重新激活时会重载并取到最新值 + async getTabIdsByStorageName(storageName: string): Promise { + const tabs = await chrome.tabs.query({}); + const candidates = tabs.filter((tab) => tab.id && !tab.discarded).map((tab) => tab.id!); + const menus = await Promise.all(candidates.map((tabId) => this.getScriptMenu(tabId))); + return candidates.filter((_, i) => menus[i].some((item) => item.storageName === storageName)); + } + // 菜单变化后同步角标计数缓存(脚本数、运行数)。计数为 0 时存空字符串表示不显示角标。 // tabId <= 0 为后台菜单(-1)等非真实标签页,跳过。 private updateCachedScriptMenuCounters(tabId: number, menu: ScriptMenu[]) { diff --git a/src/app/service/service_worker/runtime.test.ts b/src/app/service/service_worker/runtime.test.ts index ac35581be..bdc573c4b 100644 --- a/src/app/service/service_worker/runtime.test.ts +++ b/src/app/service/service_worker/runtime.test.ts @@ -1468,15 +1468,47 @@ describe("pushValueUpdate 判断是否需要为 early-start 脚本重新编译", }); const updateSpy = vi.spyOn(runtime, "updateResourceOnScriptChange").mockResolvedValue(undefined); - await runtime.pushValueUpdate(script, { + await runtime.pushValueUpdate( + script, + { + entries: [], + uuid: script.uuid, + storageName: "test-storage", + sender: { runFlag: "", tabId: -1 }, + valueUpdated: true, + }, + [] + ); + + expect(updateSpy).toHaveBeenCalledWith(script); + }); +}); + +describe("pushValueUpdate 页面投递", () => { + // 改由消息定向投递,不再经 chrome.storage.local 广播,否则每次写入都会扇出到所有 frame(#1834) + it("只向指定标签页发送 scripting/runtime/valueUpdate,不写 chrome.storage.local", async () => { + const { runtime } = _createRuntimeContext(); + const script = _createMockScript(); + const sendData = { + id: "id-1", entries: [], uuid: script.uuid, storageName: "test-storage", - sender: { runFlag: "", tabId: -1 }, - valueUpdated: true, - }); + sender: { runFlag: "", tabId: 2 }, + valueUpdated: false, + }; + const sendSpy = vi.spyOn(chrome.tabs, "sendMessage").mockImplementation(((...args: unknown[]) => { + (args[args.length - 1] as (resp: unknown) => void)({ code: 0 }); + }) as unknown as typeof chrome.tabs.sendMessage); + const setSpy = vi.spyOn(chrome.storage.local, "set"); - expect(updateSpy).toHaveBeenCalledWith(script); + await runtime.pushValueUpdate(script, sendData, [1, 2]); + + expect(sendSpy.mock.calls.map(([tabId, msg]) => [tabId, msg])).toEqual([ + [1, { action: "scripting/runtime/valueUpdate", data: sendData }], + [2, { action: "scripting/runtime/valueUpdate", data: sendData }], + ]); + expect(setSpy).not.toHaveBeenCalled(); }); }); diff --git a/src/app/service/service_worker/runtime.ts b/src/app/service/service_worker/runtime.ts index ec2ba95d6..c10f3d8a6 100644 --- a/src/app/service/service_worker/runtime.ts +++ b/src/app/service/service_worker/runtime.ts @@ -131,11 +131,6 @@ 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 { scriptMatchEnable: UrlMatch = new UrlMatch(); blackMatch: UrlMatch = new UrlMatch(); @@ -475,15 +470,21 @@ export class RuntimeService { await this.loadPageScript(script, apiScript!); } - public async pushValueUpdate(script: Script, sendData: ValueUpdateDataEncoded) { + public async pushValueUpdate(script: Script, sendData: ValueUpdateDataEncoded, tabIds: number[]) { try { - // 前台腳本 (推送值到tab) - await deliveryStorage!.set({ - valueUpdateDelivery: { - rId: `${Date.now()}.${Math.random()}`, // 用于区分不同的更新,确保 deliveryStorage.onChanged 必能触发 - sendData, - }, - }); + // 前台脚本:只投递给运行了该 storageName 的标签页(不指定 frame,由各 frame 的 scripting 按 storageName 过滤)。 + // 不能借 chrome.storage.local 广播:每个 frame 都要为此监听 local.onChanged, + // 任何一次 local 写入(包括整包的 value:*)的新旧值都会被投递并反序列化到所有 frame(#1834) + // 不等待页面回应:某个标签页失败不应阻塞其他标签页与下面的后台脚本投递 + for (const tabId of tabIds) { + sendMessage(new ExtensionContentMessageSend(tabId), "scripting/runtime/valueUpdate", sendData).catch((e) => { + this.logger.error( + "push value update to tab failed", + { uuid: script.uuid, storageName: sendData.storageName, tabId }, + Logger.E(e) + ); + }); + } // 後台腳本 if (bgScriptStorageNames.has(sendData.storageName)) { @@ -511,19 +512,7 @@ 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)); - } - } - init() { - if (deliveryStorage === chrome.storage.session) { - this.setSessionAccessLevel(); - } // 启动gm api const permission = new PermissionVerify(this.group.group("permission"), this.mq); this.gmApi = new GMApi( diff --git a/src/app/service/service_worker/value.test.ts b/src/app/service/service_worker/value.test.ts index 7dcc2ae9a..2035b6c0f 100644 --- a/src/app/service/service_worker/value.test.ts +++ b/src/app/service/service_worker/value.test.ts @@ -528,3 +528,51 @@ describe("ValueService —— 共享 storagename 的回收站感知", () => { expect(await valueDAO.get(lonely)).toBeUndefined(); }); }); + +describe("ValueService pushValueUpdate 投递目标", () => { + const setup = (tabIds: number[]) => { + 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) }; + const popup = { getTabIdsByStorageName: vi.fn().mockResolvedValue(tabIds) }; + service.init(runtime as unknown as RuntimeService, popup as unknown as PopupService); + return { service, runtime, popup }; + }; + 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("投递到运行该 storageName 的标签页,并补上发起写入的标签页", async () => { + const { service, runtime, popup } = setup([1]); + + await service.pushValueUpdate(script, sendData(2)); + + expect(popup.getTabIdsByStorageName).toHaveBeenCalledWith("store"); + expect(runtime.pushValueUpdate).toHaveBeenCalledWith(script, sendData(2), [1, 2]); + }); + + it("查询标签页失败时仍投递给发起方(并由 runtime 继续后台脚本投递)", async () => { + const { service, runtime, popup } = setup([]); + popup.getTabIdsByStorageName.mockRejectedValue(new Error("tabs.query failed")); + + await expect(service.pushValueUpdate(script, sendData(2))).resolves.toBeUndefined(); + + expect(runtime.pushValueUpdate).toHaveBeenCalledWith(script, sendData(2), [2]); + }); + + it("发起方已在目标中或不是标签页(tabId -1)时不重复、不追加", async () => { + const { service, runtime } = setup([1]); + + await service.pushValueUpdate(script, sendData(1)); + await service.pushValueUpdate(script, sendData(-1)); + + expect(runtime.pushValueUpdate).toHaveBeenNthCalledWith(1, script, sendData(1), [1]); + expect(runtime.pushValueUpdate).toHaveBeenNthCalledWith(2, script, sendData(-1), [1]); + }); +}); diff --git a/src/app/service/service_worker/value.ts b/src/app/service/service_worker/value.ts index 6f5af7ba5..2c291bcd7 100644 --- a/src/app/service/service_worker/value.ts +++ b/src/app/service/service_worker/value.ts @@ -1,5 +1,5 @@ import LoggerCore from "@App/app/logger/core"; -import type Logger from "@App/app/logger/logger"; +import Logger from "@App/app/logger/logger"; import { type Script, ScriptDAO, type ValueStore } from "@App/app/repo/scripts"; import { type Value, ValueDAO } from "@App/app/repo/value"; import { TrashScriptDAO } from "@App/app/repo/trash_script"; @@ -77,7 +77,20 @@ export class ValueService { } async pushValueUpdate(script: Script, sendData: T) { - return this.runtime!.pushValueUpdate(script, sendData); + let tabIds: number[] = []; + try { + tabIds = await this.popup!.getTabIdsByStorageName(sendData.storageName); + } catch (e) { + // 查不到其他标签页时,发起方与后台脚本仍需收到更新 + this.logger.error("get value update tabs failed", { storageName: sendData.storageName }, Logger.E(e)); + } + // 发起方的运行记录由 popupPageLoadUpdate 异步写入,脚本在页面早期写值时可能还查不到; + // 漏掉它会让该页的 GM.setValue Promise 等不到回执 + const senderTabId = sendData.sender.tabId; + if (senderTabId !== undefined && senderTabId > 0 && !tabIds.includes(senderTabId)) { + tabIds.push(senderTabId); + } + return this.runtime!.pushValueUpdate(script, sendData, tabIds); } // 批量设置 From 23f939b898d1df26373cc3cf94020a90bd3873ab Mon Sep 17 00:00:00 2001 From: cyfung1031 <44498510+cyfung1031@users.noreply.github.com> Date: Tue, 10 Nov 2026 04:43:25 +0900 Subject: [PATCH 02/10] =?UTF-8?q?=E2=9C=A8=20Add=20indexed=20GM=20value=20?= =?UTF-8?q?Port=20subscriptions=20and=20reconnecting=20client?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../content/value_port.integration.test.ts | 39 +++++ src/app/service/content/value_port.test.ts | 152 ++++++++++++++++++ src/app/service/content/value_port.ts | 129 +++++++++++++++ .../service/service_worker/value_port.test.ts | 120 ++++++++++++++ src/app/service/service_worker/value_port.ts | 69 ++++++++ 5 files changed, 509 insertions(+) create mode 100644 src/app/service/content/value_port.integration.test.ts create mode 100644 src/app/service/content/value_port.test.ts create mode 100644 src/app/service/content/value_port.ts create mode 100644 src/app/service/service_worker/value_port.test.ts create mode 100644 src/app/service/service_worker/value_port.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..49ac40a56 --- /dev/null +++ b/src/app/service/content/value_port.integration.test.ts @@ -0,0 +1,39 @@ +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); + server.group("runtime").on("valueUpdates", (_, sender) => ports.connect(sender)); + const received = vi.fn(); + const channel = new ScriptingValuePort(transport, received); + channel.start(); + + await channel.subscribe(["script-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..ea326f5a3 --- /dev/null +++ b/src/app/service/content/value_port.test.ts @@ -0,0 +1,152 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import type { MessageConnect, MessageSend, TMessage } from "@Packages/message/types"; +import ScriptingValuePort from "./value_port"; + +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); + channel.start(); + const ready = channel.subscribe(["shared", "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: ["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("断连重建 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()); + channel.start(); + const ready = channel.subscribe(["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: ["a"] }]); + newPort.receive({ action: "runtime/valueSubscriptionsReady" }); + channel.stop(); + }); + + it("没有脚本的 frame 释放 Port,不再尝试重连", async () => { + vi.useFakeTimers(); + const port = new TestPort(); + const { sender, connect } = createSender(port); + const channel = new ScriptingValuePort(sender, 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()); + channel.start(); + const ready = channel.subscribe(["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: ["a"] }]); + 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()); + const errorSpy = vi.spyOn(console, "error").mockImplementation(() => undefined); + try { + channel.start(); + const ready = channel.subscribe(["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..1156dc480 --- /dev/null +++ b/src/app/service/content/value_port.ts @@ -0,0 +1,129 @@ +import type { MessageConnect, MessageSend } from "@Packages/message/types"; +import type { ValueUpdateDataEncoded } from "./types"; + +// 由 scripting 持有;SW 重启后重连并重新上报 frame 的脚本订阅。 +export default class ScriptingValuePort { + private port: MessageConnect | undefined; + private connecting = false; + private portReady = false; + private stopped = false; + private storageNames: string[] | undefined; + private subscribeDone: (() => void) | undefined; + private retryTimer: ReturnType | undefined; + private retryDelay = 250; + private readonly onPageShow = (event: PageTransitionEvent) => { + if (!event.persisted || this.stopped) return; + // bfcache 可冻结整个 JS 上下文;恢复后重新向新的 SW 建立索引。 + const port = this.port; + this.port = undefined; + this.portReady = 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 + ) {} + + start() { + this.connect(); + window.addEventListener("pageshow", this.onPageShow); + } + + subscribe(names: string[]): Promise { + if (names.length === 0) { + this.stop(); + return Promise.resolve(); + } + this.storageNames = [...new Set(names)]; + return new Promise((resolve) => { + this.subscribeDone = resolve; + this.sendSubscriptions(); + }); + } + + stop() { + this.stopped = true; + 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; + this.sender + .connect({ action: "serviceWorker/runtime/valueUpdates" }) + .then((port) => { + this.connecting = false; + if (this.stopped) { + port.disconnect(true); + return; + } + this.port = port; + this.portReady = false; + 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.subscribeDone?.(); + this.subscribeDone = undefined; + } else if (message.code === -1) { + this.failPort(port, message.message); + } else if (message.action === "runtime/valueUpdate") { + this.onValueUpdate(message.data as ValueUpdateDataEncoded); + } + }); + port.onDisconnect(() => { + if (this.port !== port) return; + this.port = undefined; + this.portReady = false; + this.scheduleReconnect(); + }); + }) + .catch((error: unknown) => { + this.connecting = false; + console.error("value update Port connection failed", error); + this.scheduleReconnect(); + }); + } + + private sendSubscriptions() { + if (this.portReady && this.port && this.storageNames) { + try { + this.port.sendMessage({ action: "runtime/subscribeValueUpdates", data: this.storageNames }); + } catch (error) { + this.failPort(this.port, error); + } + } + } + + private failPort(port: MessageConnect, error: unknown) { + console.error("value update Port failed", error); + if (this.port !== port) return; + this.port = undefined; + this.portReady = false; + port.disconnect(true); + 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/value_port.test.ts b/src/app/service/service_worker/value_port.test.ts new file mode 100644 index 000000000..3abf09fbf --- /dev/null +++ b/src/app/service/service_worker/value_port.test.ts @@ -0,0 +1,120 @@ +import { describe, expect, it, vi } from "vitest"; +import type { IGetSender } from "@Packages/message/server"; +import type { MessageConnect, TMessage } from "@Packages/message/types"; +import ValueUpdatePorts from "./value_port"; + +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(true); + } + receive(message: TMessage) { + this.messageListener(message); + } +} + +const senderOf = (port: TestPort) => ({ getConnect: () => port }) as unknown as IGetSender; +const update = { + storageName: "a", + uuid: "script-a", + entries: [], + sender: { runFlag: "", tabId: 1 }, + valueUpdated: true, +}; + +describe("ValueUpdatePorts 精准推送", () => { + it("只向订阅指定 storageName 的 frame Port 推送,同名脚本不重复投递", () => { + const ports = new ValueUpdatePorts(vi.fn()); + const first = new TestPort(); + const second = new TestPort(); + const unrelated = new TestPort(); + expect(ports.connect(senderOf(first))).toEqual({ ready: true }); + ports.connect(senderOf(second)); + ports.connect(senderOf(unrelated)); + first.receive({ action: "runtime/subscribeValueUpdates", data: ["a", "c", "a"] }); + second.receive({ action: "runtime/subscribeValueUpdates", data: ["b", "a"] }); + unrelated.receive({ action: "runtime/subscribeValueUpdates", data: ["b"] }); + + ports.push("a", update); + expect(first.sent).toEqual([ + { action: "runtime/valueSubscriptionsReady" }, + { action: "runtime/valueUpdate", data: update }, + ]); + expect(second.sent).toEqual(first.sent); + expect(unrelated.sent).toEqual([{ action: "runtime/valueSubscriptionsReady" }]); + }); + + it("改订阅和断连立刻清理索引,其他 Port 继续接收", () => { + const ports = new ValueUpdatePorts(vi.fn()); + const first = new TestPort(); + const second = new TestPort(); + ports.connect(senderOf(first)); + ports.connect(senderOf(second)); + first.receive({ action: "runtime/subscribeValueUpdates", data: ["a"] }); + second.receive({ action: "runtime/subscribeValueUpdates", data: ["a"] }); + first.receive({ action: "runtime/subscribeValueUpdates", data: ["b"] }); + second.disconnect(); + + first.sent = []; + second.sent = []; + ports.push("a", update); + expect(first.sent).toEqual([]); + expect(second.sent).toEqual([]); + ports.push("b", update); + expect(first.sent).toEqual([{ action: "runtime/valueUpdate", data: update }]); + }); + + it("坏 Port 发送失败后释放,且不会阻断其他收件方", () => { + const onError = vi.fn(); + const ports = new ValueUpdatePorts(onError); + const bad = new TestPort(); + const good = new TestPort(); + ports.connect(senderOf(bad)); + ports.connect(senderOf(good)); + bad.receive({ action: "runtime/subscribeValueUpdates", data: ["a"] }); + good.receive({ action: "runtime/subscribeValueUpdates", data: ["a"] }); + const error = new Error("disconnected"); + bad.sendMessage = () => { + throw error; + }; + good.sent = []; + + ports.push("a", update); + ports.push("a", update); + expect(good.sent).toEqual([ + { action: "runtime/valueUpdate", data: update }, + { action: "runtime/valueUpdate", data: update }, + ]); + expect(onError).toHaveBeenCalledOnce(); + expect(onError).toHaveBeenCalledWith({ kind: "push", storageName: "a" }, error); + }); + + it("订阅确认发送失败时关闭 Port,不保留不能确认的订阅", () => { + const onError = vi.fn(); + const ports = new ValueUpdatePorts(onError); + const broken = new TestPort(); + const error = new Error("closed before acknowledgement"); + ports.connect(senderOf(broken)); + broken.sendMessage = () => { + throw error; + }; + const disconnect = vi.spyOn(broken, "disconnect"); + + broken.receive({ action: "runtime/subscribeValueUpdates", data: ["a"] }); + ports.push("a", update); + + expect(disconnect).toHaveBeenCalledOnce(); + expect(onError).toHaveBeenCalledExactlyOnceWith({ kind: "subscribe" }, error); + }); +}); diff --git a/src/app/service/service_worker/value_port.ts b/src/app/service/service_worker/value_port.ts new file mode 100644 index 000000000..f92a55654 --- /dev/null +++ b/src/app/service/service_worker/value_port.ts @@ -0,0 +1,69 @@ +import type { IGetSender } from "@Packages/message/server"; +import type { MessageConnect } from "@Packages/message/types"; +import type { ValueUpdateDataEncoded } from "../content/types"; + +// 每个 Port 对应一个 frame,索引只保存该 frame 实际运行的 storageName。 +export default class ValueUpdatePorts { + private readonly byStorageName = new Map>(); + private readonly byPort = new Map>(); + + constructor( + private readonly onSendError: ( + context: { kind: "subscribe" } | { kind: "push"; storageName: string }, + error: unknown + ) => void + ) {} + + connect(sender: IGetSender) { + const port = sender.getConnect(); + if (!port) throw new Error("valueUpdates requires a Port connection"); + this.byPort.set(port, new Set()); + port.onMessage((message) => { + if (message.action !== "runtime/subscribeValueUpdates" || !Array.isArray(message.data)) return; + const storageNames = new Set( + message.data.filter((name: unknown): name is string => typeof name === "string") + ); + this.removeSubscriptions(port); + this.byPort.set(port, storageNames); + for (const name of storageNames) { + let ports = this.byStorageName.get(name); + if (!ports) this.byStorageName.set(name, (ports = new Set())); + ports.add(port); + } + try { + port.sendMessage({ action: "runtime/valueSubscriptionsReady" }); + } catch (error) { + this.removeSubscriptions(port); + this.onSendError({ kind: "subscribe" }, error); + port.disconnect(true); + } + }); + port.onDisconnect(() => this.removeSubscriptions(port)); + return { ready: true }; + } + + push(storageName: string, data: ValueUpdateDataEncoded) { + const ports = this.byStorageName.get(storageName); + if (!ports) return; + for (const port of ports) { + try { + port.sendMessage({ action: "runtime/valueUpdate", data }); + } catch (error) { + // Port 关闭可能先于 onDisconnect 事件;一次失败不影响其他 frame。 + this.removeSubscriptions(port); + this.onSendError({ kind: "push", storageName }, error); + } + } + } + + private removeSubscriptions(port: MessageConnect) { + const names = this.byPort.get(port); + if (!names) return; + this.byPort.delete(port); + for (const name of names) { + const ports = this.byStorageName.get(name); + ports?.delete(port); + if (ports?.size === 0) this.byStorageName.delete(name); + } + } +} From 5ec78a44fee6f3b757d933318f5e51a31e31f46d Mon Sep 17 00:00:00 2001 From: cyfung1031 <44498510+cyfung1031@users.noreply.github.com> Date: Tue, 10 Nov 2026 04:44:32 +0900 Subject: [PATCH 03/10] =?UTF-8?q?=E2=9A=A1=EF=B8=8F=20Route=20GM=20updates?= =?UTF-8?q?=20directly=20to=20subscribed=20frame=20Ports?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/app/service/content/scripting.test.ts | 86 +++++++++++++++---- src/app/service/content/scripting.ts | 47 ++++++---- src/app/service/service_worker/index.ts | 2 +- src/app/service/service_worker/popup.test.ts | 22 ----- src/app/service/service_worker/popup.ts | 8 -- .../service/service_worker/runtime.test.ts | 47 +++++----- src/app/service/service_worker/runtime.ts | 26 +++--- .../service_worker/trash_freeze.test.ts | 3 +- src/app/service/service_worker/value.test.ts | 38 ++------ src/app/service/service_worker/value.ts | 22 +---- 10 files changed, 150 insertions(+), 151 deletions(-) diff --git a/src/app/service/content/scripting.test.ts b/src/app/service/content/scripting.test.ts index 55efdf000..462e12802 100644 --- a/src/app/service/content/scripting.test.ts +++ b/src/app/service/content/scripting.test.ts @@ -1,6 +1,6 @@ import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; import type { Server } from "@Packages/message/server"; -import type { MessageSend } from "@Packages/message/types"; +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"; @@ -52,12 +52,30 @@ describe("ScriptingRuntime 值更新投递", () => { 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 }; + return { + runtime, + ext, + toContent, + toInject, + portSend, + onPortMessage, + receive: (message: TMessage) => portMessage(message), + }; }; // 每个页面的每个 frame 都有 scripting.js;若它监听 storage.local,任何一次 local 写入 @@ -78,39 +96,75 @@ describe("ScriptingRuntime 值更新投递", () => { expect(toInject.sendMessage).not.toHaveBeenCalled(); }); - it("pageLoad 之后,runtime/valueUpdate 只转发给运行了该 storageName 的一侧", async () => { - const { runtime, ext, toContent, toInject } = setup({ + it("Port 只转发给当前 frame 运行的脚本世界,且先订阅再启动脚本", async () => { + const { runtime, toContent, toInject, portSend, onPortMessage, receive } = setup({ ok: true, - injectScriptList: [{ uuid: "a", metadata: { storagename: ["page-store"] } }], - contentScriptList: [{ uuid: "b", metadata: { storagename: ["content-store"] } }], + 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: ["page-store", "shared", "content-store", "__proto__"], + }) + ); + 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(); - await ext.handlers.get("runtime/valueUpdate")!(valueUpdate("page-store")); + 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(); - await ext.handlers.get("runtime/valueUpdate")!(valueUpdate("content-store")); + 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(); - await ext.handlers.get("runtime/valueUpdate")!(valueUpdate("other-store")); + receive({ action: "runtime/valueUpdate", data: valueUpdate("other-store") }); + await Promise.resolve(); expect(toContent.sendMessage).not.toHaveBeenCalled(); expect(toInject.sendMessage).not.toHaveBeenCalled(); }); - it("pageLoad 尚未返回时,runtime/valueUpdate 同时转发给 page 与 content", async () => { - const { ext, toContent, toInject } = setup(); - - await ext.handlers.get("runtime/valueUpdate")!(valueUpdate("any-store")); - - expect(actionsOf(toContent.sendMessage)).toEqual(["content/runtime/valueUpdate"]); - expect(actionsOf(toInject.sendMessage)).toEqual(["inject/runtime/valueUpdate"]); + 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 d97cd58e1..2b4eb94ec 100644 --- a/src/app/service/content/scripting.ts +++ b/src/app/service/content/scripting.ts @@ -7,6 +7,7 @@ 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 ScriptingValuePort from "./value_port"; const PageOrContent = { PAGE: 1, @@ -18,7 +19,8 @@ type PageOrContent = ValueOf; // scripting页的处理 export default class ScriptingRuntime { - private activeStorageNames: Map | null = null; + private activeStorageNames = new Map(); + private readonly valuePort: ScriptingValuePort; constructor( // 监听来自service_worker的消息 private readonly extServer: Server, @@ -30,7 +32,17 @@ export default class ScriptingRuntime { private readonly senderToContent: CustomEventMessage, // 发送给inject的消息接口 private readonly senderToInject: CustomEventMessage - ) {} + ) { + this.valuePort = new ScriptingValuePort(this.senderToExt, (data) => this.forwardValueUpdate(data)); + } + + private forwardValueUpdate(data: ValueUpdateDataEncoded) { + const activeOn = this.activeStorageNames.get(data.storageName); + if (!activeOn) return; + void this.broadcastToPage("runtime/valueUpdate", data, activeOn).catch((error) => { + LoggerCore.logger().error("forward value update failed", { storageName: data.storageName, error }); + }); + } // 广播消息给 content 和 inject broadcastToPage( @@ -45,20 +57,11 @@ 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: ValueUpdateDataEncoded) => { - // SW 按标签页投递,同一标签页里没有运行该脚本的 frame 也会收到,需按 storageName 过滤; - // pageLoad 返回前还不知道本 frame 运行哪些脚本,两侧都转发 - const activeOn = - this.activeStorageNames === null - ? PageOrContent.PAGE_AND_CONTENT - : this.activeStorageNames.get(data.storageName); - if (!activeOn) return; - return this.broadcastToPage("runtime/valueUpdate", data, activeOn); - }); this.server.on("logger", (data: Logger) => { LoggerCore.logger().log(data.level, data.message, data.label); }); @@ -135,17 +138,25 @@ 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 = new Map(Object.entries(pairs)); + this.activeStorageNames = pairs; + + // 先确认中央已建立订阅,再启动页面脚本;早期 GM.setValue 的回执不会落入订阅空窗。 + await this.valuePort.subscribe([...this.activeStorageNames.keys()]); // 向页面 发送脚本列表及环境信息 if (contentScriptList.length) { 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/popup.test.ts b/src/app/service/service_worker/popup.test.ts index 0cb7c751a..2eeaee436 100644 --- a/src/app/service/service_worker/popup.test.ts +++ b/src/app/service/service_worker/popup.test.ts @@ -1259,25 +1259,3 @@ describe("PopupService clearTabData 标签页关闭/替换时释放 tab 数据", await expect(service.getScriptMenu(10)).resolves.toEqual([]); }); }); - -describe("PopupService getTabIdsByStorageName 值更新的投递目标", () => { - beforeEach(async () => { - await cacheInstance.clear(); - }); - - it("只返回脚本菜单中运行了该 storageName 的未丢弃标签页", async () => { - await cacheInstance.set(`${CACHE_KEY_TAB_SCRIPT}${1}`, [createMenu("a", { storageName: "shared" })]); - await cacheInstance.set(`${CACHE_KEY_TAB_SCRIPT}${2}`, [createMenu("b", { storageName: "other" })]); - await cacheInstance.set(`${CACHE_KEY_TAB_SCRIPT}${3}`, [createMenu("c", { storageName: "shared" })]); - await cacheInstance.set(`${CACHE_KEY_TAB_SCRIPT}${5}`, [ - createMenu("d", { storageName: "other" }), - createMenu("e", { storageName: "shared" }), - ]); - const tabs = [{ id: 1 }, { id: 2 }, { id: 3, discarded: true }, { id: 4 }, { id: 5 }] as chrome.tabs.Tab[]; - vi.spyOn(chrome.tabs, "query").mockImplementation((() => Promise.resolve(tabs)) as typeof chrome.tabs.query); - - const { service } = createService(); - - await expect(service.getTabIdsByStorageName("shared")).resolves.toEqual([1, 5]); - }); -}); diff --git a/src/app/service/service_worker/popup.ts b/src/app/service/service_worker/popup.ts index 995513879..6944e3aa6 100644 --- a/src/app/service/service_worker/popup.ts +++ b/src/app/service/service_worker/popup.ts @@ -558,14 +558,6 @@ export class PopupService { return (await cacheInstance.get(cacheKey)) || []; } - // 值更新的页面投递目标;被丢弃的标签页没有存活的 content script,重新激活时会重载并取到最新值 - async getTabIdsByStorageName(storageName: string): Promise { - const tabs = await chrome.tabs.query({}); - const candidates = tabs.filter((tab) => tab.id && !tab.discarded).map((tab) => tab.id!); - const menus = await Promise.all(candidates.map((tabId) => this.getScriptMenu(tabId))); - return candidates.filter((_, i) => menus[i].some((item) => item.storageName === storageName)); - } - // 菜单变化后同步角标计数缓存(脚本数、运行数)。计数为 0 时存空字符串表示不显示角标。 // tabId <= 0 为后台菜单(-1)等非真实标签页,跳过。 private updateCachedScriptMenuCounters(tabId: number, menu: ScriptMenu[]) { diff --git a/src/app/service/service_worker/runtime.test.ts b/src/app/service/service_worker/runtime.test.ts index bdc573c4b..793b7f8fd 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"; @@ -1468,25 +1468,20 @@ describe("pushValueUpdate 判断是否需要为 early-start 脚本重新编译", }); const updateSpy = vi.spyOn(runtime, "updateResourceOnScriptChange").mockResolvedValue(undefined); - await runtime.pushValueUpdate( - script, - { - entries: [], - uuid: script.uuid, - storageName: "test-storage", - sender: { runFlag: "", tabId: -1 }, - valueUpdated: true, - }, - [] - ); + await runtime.pushValueUpdate(script, { + entries: [], + uuid: script.uuid, + storageName: "test-storage", + sender: { runFlag: "", tabId: -1 }, + valueUpdated: true, + }); expect(updateSpy).toHaveBeenCalledWith(script); }); }); describe("pushValueUpdate 页面投递", () => { - // 改由消息定向投递,不再经 chrome.storage.local 广播,否则每次写入都会扇出到所有 frame(#1834) - it("只向指定标签页发送 scripting/runtime/valueUpdate,不写 chrome.storage.local", async () => { + it("直接向订阅 storageName 的 Port 投递,不使用 tabs API 或 storage 广播", async () => { const { runtime } = _createRuntimeContext(); const script = _createMockScript(); const sendData = { @@ -1497,17 +1492,25 @@ describe("pushValueUpdate 页面投递", () => { sender: { runFlag: "", tabId: 2 }, valueUpdated: false, }; - const sendSpy = vi.spyOn(chrome.tabs, "sendMessage").mockImplementation(((...args: unknown[]) => { - (args[args.length - 1] as (resp: unknown) => void)({ code: 0 }); - }) as unknown as typeof chrome.tabs.sendMessage); + 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: ["test-storage"] }); + 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, [1, 2]); + await runtime.pushValueUpdate(script, sendData); - expect(sendSpy.mock.calls.map(([tabId, msg]) => [tabId, msg])).toEqual([ - [1, { action: "scripting/runtime/valueUpdate", data: sendData }], - [2, { action: "scripting/runtime/valueUpdate", data: sendData }], - ]); + expect(postMessage).toHaveBeenCalledExactlyOnceWith({ action: "runtime/valueUpdate", data: sendData }); + expect(tabsSpy).not.toHaveBeenCalled(); + expect(querySpy).not.toHaveBeenCalled(); expect(setSpy).not.toHaveBeenCalled(); }); }); diff --git a/src/app/service/service_worker/runtime.ts b/src/app/service/service_worker/runtime.ts index c10f3d8a6..b998028e3 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"; @@ -132,6 +133,9 @@ export type TScriptsForTab = { const bgScriptStorageNames = new Set(); export class RuntimeService { + private readonly valuePorts = new ValueUpdatePorts((context, error) => { + this.logger.error("value update Port delivery failed", context, Logger.E(error)); + }); scriptMatchEnable: UrlMatch = new UrlMatch(); blackMatch: UrlMatch = new UrlMatch(); private gmApi?: GMApi; @@ -470,21 +474,10 @@ export class RuntimeService { await this.loadPageScript(script, apiScript!); } - public async pushValueUpdate(script: Script, sendData: ValueUpdateDataEncoded, tabIds: number[]) { + public async pushValueUpdate(script: Script, sendData: ValueUpdateDataEncoded) { try { - // 前台脚本:只投递给运行了该 storageName 的标签页(不指定 frame,由各 frame 的 scripting 按 storageName 过滤)。 - // 不能借 chrome.storage.local 广播:每个 frame 都要为此监听 local.onChanged, - // 任何一次 local 写入(包括整包的 value:*)的新旧值都会被投递并反序列化到所有 frame(#1834) - // 不等待页面回应:某个标签页失败不应阻塞其他标签页与下面的后台脚本投递 - for (const tabId of tabIds) { - sendMessage(new ExtensionContentMessageSend(tabId), "scripting/runtime/valueUpdate", sendData).catch((e) => { - this.logger.error( - "push value update to tab failed", - { uuid: script.uuid, storageName: sendData.storageName, tabId }, - Logger.E(e) - ); - }); - } + // 直接推送给订阅该 storageName 的存活 frame,不经过 tabs API 或无关 iframe(#1834)。 + this.valuePorts.push(sendData.storageName, sendData); // 後台腳本 if (bgScriptStorageNames.has(sendData.storageName)) { @@ -512,7 +505,12 @@ export class RuntimeService { } } + public connectValueUpdates(_: unknown, sender: IGetSender) { + return this.valuePorts.connect(sender); + } + init() { + this.group.on("valueUpdates", this.connectValueUpdates.bind(this)); // 启动gm api const permission = new PermissionVerify(this.group.group("permission"), this.mq); this.gmApi = new GMApi( 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 2035b6c0f..f17b00f16 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(); @@ -463,7 +462,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 +509,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"; @@ -530,13 +529,12 @@ describe("ValueService —— 共享 storagename 的回收站感知", () => { }); describe("ValueService pushValueUpdate 投递目标", () => { - const setup = (tabIds: number[]) => { + 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) }; - const popup = { getTabIdsByStorageName: vi.fn().mockResolvedValue(tabIds) }; - service.init(runtime as unknown as RuntimeService, popup as unknown as PopupService); - return { service, runtime, popup }; + service.init(runtime as unknown as RuntimeService); + return { service, runtime }; }; const script = { uuid: "uuid-1", metadata: {} } as Script; const sendData = (tabId: number) => ({ @@ -548,31 +546,13 @@ describe("ValueService pushValueUpdate 投递目标", () => { valueUpdated: true, }); - it("投递到运行该 storageName 的标签页,并补上发起写入的标签页", async () => { - const { service, runtime, popup } = setup([1]); - - await service.pushValueUpdate(script, sendData(2)); - - expect(popup.getTabIdsByStorageName).toHaveBeenCalledWith("store"); - expect(runtime.pushValueUpdate).toHaveBeenCalledWith(script, sendData(2), [1, 2]); - }); - - it("查询标签页失败时仍投递给发起方(并由 runtime 继续后台脚本投递)", async () => { - const { service, runtime, popup } = setup([]); - popup.getTabIdsByStorageName.mockRejectedValue(new Error("tabs.query failed")); - - await expect(service.pushValueUpdate(script, sendData(2))).resolves.toBeUndefined(); - - expect(runtime.pushValueUpdate).toHaveBeenCalledWith(script, sendData(2), [2]); - }); - - it("发起方已在目标中或不是标签页(tabId -1)时不重复、不追加", async () => { - const { service, runtime } = setup([1]); + 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), [1]); - expect(runtime.pushValueUpdate).toHaveBeenNthCalledWith(2, script, sendData(-1), [1]); + expect(runtime.pushValueUpdate).toHaveBeenNthCalledWith(1, script, sendData(1)); + expect(runtime.pushValueUpdate).toHaveBeenNthCalledWith(2, script, sendData(-1)); }); }); diff --git a/src/app/service/service_worker/value.ts b/src/app/service/service_worker/value.ts index 2c291bcd7..564cf6cfd 100644 --- a/src/app/service/service_worker/value.ts +++ b/src/app/service/service_worker/value.ts @@ -1,11 +1,10 @@ import LoggerCore from "@App/app/logger/core"; -import Logger from "@App/app/logger/logger"; +import type Logger from "@App/app/logger/logger"; import { type Script, ScriptDAO, type ValueStore } from "@App/app/repo/scripts"; import { type Value, ValueDAO } from "@App/app/repo/value"; import { TrashScriptDAO } from "@App/app/repo/trash_script"; import type { IGetSender, Group } from "@Packages/message/server"; import { type RuntimeService } from "./runtime"; -import { type PopupService } from "./popup"; import { getStorageName } from "@App/pkg/utils/utils"; import type { ValueUpdateDataEncoded, ValueUpdateDataREntry, ValueUpdateSender } from "../content/types"; import { type TDeleteScript } from "../queue"; @@ -29,7 +28,6 @@ export class ValueService { scriptDAO: ScriptDAO = new ScriptDAO(); valueDAO: ValueDAO = new ValueDAO(); trashScriptDAO: TrashScriptDAO = new TrashScriptDAO(); - private popup: PopupService | undefined; private runtime: RuntimeService | undefined; constructor( @@ -77,20 +75,7 @@ export class ValueService { } async pushValueUpdate(script: Script, sendData: T) { - let tabIds: number[] = []; - try { - tabIds = await this.popup!.getTabIdsByStorageName(sendData.storageName); - } catch (e) { - // 查不到其他标签页时,发起方与后台脚本仍需收到更新 - this.logger.error("get value update tabs failed", { storageName: sendData.storageName }, Logger.E(e)); - } - // 发起方的运行记录由 popupPageLoadUpdate 异步写入,脚本在页面早期写值时可能还查不到; - // 漏掉它会让该页的 GM.setValue Promise 等不到回执 - const senderTabId = sendData.sender.tabId; - if (senderTabId !== undefined && senderTabId > 0 && !tabIds.includes(senderTabId)) { - tabIds.push(senderTabId); - } - return this.runtime!.pushValueUpdate(script, sendData, tabIds); + return this.runtime!.pushValueUpdate(script, sendData); } // 批量设置 @@ -187,8 +172,7 @@ export class ValueService { return this.setValues(params); } - init(runtime: RuntimeService, popup: PopupService) { - this.popup = popup; + init(runtime: RuntimeService) { this.runtime = runtime; this.group.on("getScriptValue", this.getScriptValue.bind(this)); this.group.on("setScriptValues", this.setScriptValues.bind(this)); From 1a060234de3a49399735fe1be6ac6c09eb1b6230 Mon Sep 17 00:00:00 2001 From: cyfung1031 <44498510+cyfung1031@users.noreply.github.com> Date: Tue, 10 Nov 2026 19:29:56 +0900 Subject: [PATCH 04/10] =?UTF-8?q?=F0=9F=90=9B=20Recover=20failed=20value?= =?UTF-8?q?=20Ports=20and=20discard=20stale=20bfcache=20connections?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/app/service/content/value_port.test.ts | 27 +++++++++++++++++++ src/app/service/content/value_port.ts | 12 +++++++-- .../service/service_worker/value_port.test.ts | 3 +++ src/app/service/service_worker/value_port.ts | 6 +++++ 4 files changed, 46 insertions(+), 2 deletions(-) diff --git a/src/app/service/content/value_port.test.ts b/src/app/service/content/value_port.test.ts index ea326f5a3..8c32b28fc 100644 --- a/src/app/service/content/value_port.test.ts +++ b/src/app/service/content/value_port.test.ts @@ -123,6 +123,33 @@ describe("ScriptingValuePort 生命周期", () => { 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()); + channel.start(); + const ready = channel.subscribe(["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: ["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(); diff --git a/src/app/service/content/value_port.ts b/src/app/service/content/value_port.ts index 1156dc480..a5dee9adf 100644 --- a/src/app/service/content/value_port.ts +++ b/src/app/service/content/value_port.ts @@ -5,6 +5,7 @@ import type { ValueUpdateDataEncoded } from "./types"; export default class ScriptingValuePort { private port: MessageConnect | undefined; private connecting = false; + private connectionGeneration = 0; private portReady = false; private stopped = false; private storageNames: string[] | undefined; @@ -17,6 +18,9 @@ export default class ScriptingValuePort { 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; @@ -47,6 +51,8 @@ export default class ScriptingValuePort { stop() { this.stopped = true; + this.connectionGeneration++; + this.connecting = false; window.removeEventListener("pageshow", this.onPageShow); if (this.retryTimer !== undefined) clearTimeout(this.retryTimer); this.retryTimer = undefined; @@ -58,14 +64,15 @@ export default class ScriptingValuePort { 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) => { - this.connecting = false; - if (this.stopped) { + if (this.stopped || generation !== this.connectionGeneration) { port.disconnect(true); return; } + this.connecting = false; this.port = port; this.portReady = false; port.onMessage((message) => { @@ -91,6 +98,7 @@ export default class ScriptingValuePort { }); }) .catch((error: unknown) => { + if (this.stopped || generation !== this.connectionGeneration) return; this.connecting = false; console.error("value update Port connection failed", error); this.scheduleReconnect(); diff --git a/src/app/service/service_worker/value_port.test.ts b/src/app/service/service_worker/value_port.test.ts index 3abf09fbf..5a826c4da 100644 --- a/src/app/service/service_worker/value_port.test.ts +++ b/src/app/service/service_worker/value_port.test.ts @@ -88,6 +88,7 @@ describe("ValueUpdatePorts 精准推送", () => { bad.sendMessage = () => { throw error; }; + const disconnect = vi.spyOn(bad, "disconnect"); good.sent = []; ports.push("a", update); @@ -98,6 +99,8 @@ describe("ValueUpdatePorts 精准推送", () => { ]); expect(onError).toHaveBeenCalledOnce(); expect(onError).toHaveBeenCalledWith({ kind: "push", storageName: "a" }, error); + // 只删除 SW 索引不够:客户端仍可能认为 Port 正常,无法自动重连并重新订阅。 + expect(disconnect).toHaveBeenCalledOnce(); }); it("订阅确认发送失败时关闭 Port,不保留不能确认的订阅", () => { diff --git a/src/app/service/service_worker/value_port.ts b/src/app/service/service_worker/value_port.ts index f92a55654..80aa8b687 100644 --- a/src/app/service/service_worker/value_port.ts +++ b/src/app/service/service_worker/value_port.ts @@ -51,6 +51,12 @@ export default class ValueUpdatePorts { } catch (error) { // Port 关闭可能先于 onDisconnect 事件;一次失败不影响其他 frame。 this.removeSubscriptions(port); + // 连接仍可能存活(如 postMessage 序列化失败),必须通知 frame 重连。 + try { + port.disconnect(true); + } catch { + // 清理索引已完成;断开失败也不能阻碍其他 frame。 + } this.onSendError({ kind: "push", storageName }, error); } } From 02c7bb6fdbed435ee220d4cd17d98bb8a76c0865 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E4=B8=80=E4=B9=8B?= Date: Thu, 12 Nov 2026 10:48:13 +0800 Subject: [PATCH 05/10] =?UTF-8?q?=F0=9F=90=9B=20GM=20=E5=86=99=E5=85=A5?= =?UTF-8?q?=E5=9B=9E=E6=89=A7=E6=94=B9=E7=94=B1=20SW=20=E7=9A=84=20RPC=20?= =?UTF-8?q?=E5=93=8D=E5=BA=94=E5=AE=8C=E6=88=90=EF=BC=8C=E4=B8=8D=E5=86=8D?= =?UTF-8?q?=E5=8F=AA=E4=BE=9D=E8=B5=96=20Port=20=E6=8E=A8=E9=80=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit SW 重启或 Port 重连期间推送会丢失,写入方的 GM.setValue Promise 因此一直挂起。 setValues 把推送的同一份更新数据作为响应返回;content 端让响应和推送都走 valueUpdate, 谁先到谁处理,后到的按 id 跳过,本 frame 监听器仍然先于 Promise 完成触发。 --- src/app/service/content/gm_api/gm_api.test.ts | 64 +++++++++++++++++++ src/app/service/content/gm_api/gm_api.ts | 22 +++++-- .../service/service_worker/gm_api/gm_api.ts | 4 +- src/app/service/service_worker/value.test.ts | 18 ++++++ src/app/service/service_worker/value.ts | 2 + 5 files changed, 101 insertions(+), 9 deletions(-) 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..4f80d2896 100644 --- a/src/app/service/content/gm_api/gm_api.ts +++ b/src/app/service/content/gm_api/gm_api.ts @@ -61,6 +61,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 +181,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); @@ -292,9 +302,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 +313,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 +347,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/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/value.test.ts b/src/app/service/service_worker/value.test.ts index f17b00f16..620a30eb3 100644 --- a/src/app/service/service_worker/value.test.ts +++ b/src/app/service/service_worker/value.test.ts @@ -150,6 +150,24 @@ 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("应该成功设置新脚本的值 (storageName fallback)", async () => { // 准备测试数据 const mockScript = createMockScript(); diff --git a/src/app/service/service_worker/value.ts b/src/app/service/service_worker/value.ts index 564cf6cfd..8d21d6ee1 100644 --- a/src/app/service/service_worker/value.ts +++ b/src/app/service/service_worker/value.ts @@ -166,6 +166,8 @@ export class ValueService { valueUpdated, } as ValueUpdateDataEncoded; this.pushValueUpdate(script, sendData); + // 写入方凭这份响应完成回执;Port 推送可能因 SW 重启、重连而丢失 + return sendData; } setScriptValues(params: Pick, _sender: IGetSender) { From e6f3de31b7b9a36ef8140ff33b8f228f6ce5475a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E4=B8=80=E4=B9=8B?= Date: Thu, 12 Nov 2026 10:49:28 +0800 Subject: [PATCH 06/10] =?UTF-8?q?=F0=9F=90=9B=20=E5=80=BC=E6=9B=B4?= =?UTF-8?q?=E6=96=B0=20Port=20=E8=A2=AB=E5=8A=A8=E6=96=AD=E5=BC=80?= =?UTF-8?q?=E5=90=8E=E7=AB=8B=E5=8D=B3=E9=87=8D=E8=BF=9E=EF=BC=8C=E6=89=A9?= =?UTF-8?q?=E5=B1=95=E4=B8=8A=E4=B8=8B=E6=96=87=E5=A4=B1=E6=95=88=E6=97=B6?= =?UTF-8?q?=E5=81=9C=E6=AD=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit SW 空闲回收后 Port 断开,原来要等 250 ms 起的随机退避才重连,这段时间里别的页面的写入全部漏收。 已确认订阅且存活超过 1 秒的 Port 断开时立刻重连;握手未完成或很快又断开时仍按退避重试。 扩展重载、更新后旧页面的 chrome.runtime.id 为空,连接失败或断开时直接停止,不再无限重试。 --- src/app/service/content/value_port.test.ts | 82 ++++++++++++++++++++++ src/app/service/content/value_port.ts | 31 +++++++- 2 files changed, 111 insertions(+), 2 deletions(-) diff --git a/src/app/service/content/value_port.test.ts b/src/app/service/content/value_port.test.ts index 8c32b28fc..07a4a99a8 100644 --- a/src/app/service/content/value_port.test.ts +++ b/src/app/service/content/value_port.test.ts @@ -85,6 +85,88 @@ describe("ScriptingValuePort 生命周期", () => { channel.stop(); }); + const subscribeAndAck = async (channel: ScriptingValuePort, port: TestPort) => { + const ready = channel.subscribe(["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()); + 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()); + 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()); + 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()); + 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(); diff --git a/src/app/service/content/value_port.ts b/src/app/service/content/value_port.ts index a5dee9adf..60ff79c33 100644 --- a/src/app/service/content/value_port.ts +++ b/src/app/service/content/value_port.ts @@ -1,6 +1,12 @@ import type { MessageConnect, MessageSend } from "@Packages/message/types"; import type { 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; @@ -12,6 +18,7 @@ export default class ScriptingValuePort { 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 建立索引。 @@ -82,6 +89,7 @@ export default class ScriptingValuePort { this.sendSubscriptions(); } else if (message.action === "runtime/valueSubscriptionsReady") { this.retryDelay = 250; + this.ackedAt = Date.now(); this.subscribeDone?.(); this.subscribeDone = undefined; } else if (message.code === -1) { @@ -94,12 +102,27 @@ export default class ScriptingValuePort { if (this.port !== port) return; this.port = undefined; this.portReady = false; - this.scheduleReconnect(); + 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(); }); @@ -116,11 +139,15 @@ export default class ScriptingValuePort { } private failPort(port: MessageConnect, error: unknown) { - console.error("value update Port failed", error); 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(); } From b5d9f9669b23eda64c2017549314bf3c0def48cf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E4=B8=80=E4=B9=8B?= Date: Thu, 12 Nov 2026 10:52:48 +0800 Subject: [PATCH 07/10] =?UTF-8?q?=E2=9C=85=20=E7=A7=BB=E9=99=A4=20scriptin?= =?UTF-8?q?g=20=E6=B5=8B=E8=AF=95=E6=AE=8B=E7=95=99=E5=9C=A8=E5=85=B1?= =?UTF-8?q?=E4=BA=AB=20window=20=E4=B8=8A=E7=9A=84=20pageshow=20=E7=9B=91?= =?UTF-8?q?=E5=90=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ScriptingRuntime 没有销毁接口,测试里创建的实例会把 pageshow 监听一直留在 window 上。 fast 项目 isolate: false,utils.test 的 vi.resetAllMocks 清掉这些实例的 mock 后, value_port.test 派发 pageshow 时残留监听调用 connect 得到 undefined 而抛错, 在 baa60b62 上连跑 3 次复现 1 次。测试结束时移除本测试注册的 pageshow 监听。 --- src/app/service/content/scripting.test.ts | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/src/app/service/content/scripting.test.ts b/src/app/service/content/scripting.test.ts index 462e12802..5a41062c6 100644 --- a/src/app/service/content/scripting.test.ts +++ b/src/app/service/content/scripting.test.ts @@ -35,7 +35,22 @@ 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 = { @@ -44,6 +59,8 @@ describe("ScriptingRuntime 值更新投递", () => { }); afterEach(() => { + for (const listener of pageShowListeners.splice(0)) window.removeEventListener("pageshow", listener); + vi.mocked(window.addEventListener).mockRestore(); (chrome.storage.local as any).onChanged = originalOnChanged; }); From 9333e133e2d2fc1d54fa70c470d6394cf5543d1f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E4=B8=80=E4=B9=8B?= Date: Thu, 12 Nov 2026 10:56:04 +0800 Subject: [PATCH 08/10] =?UTF-8?q?=F0=9F=90=9B=20=E5=90=88=E5=B9=B6?= =?UTF-8?q?=E7=94=A8=E6=88=B7=E9=85=8D=E7=BD=AE=E9=BB=98=E8=AE=A4=E5=80=BC?= =?UTF-8?q?=E6=97=B6=E4=B8=8D=E5=86=8D=E6=94=B9=E5=86=99=20ValueDAO=20?= =?UTF-8?q?=E7=BC=93=E5=AD=98=E9=87=8C=E7=9A=84=E8=AE=B0=E5=BD=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit getScriptValueDetails 直接在记录的 data 对象上合并默认值。共用 @storageName 的脚本因此会拿到 彼此的默认值,默认值还会随下一次写入被持久化。合并前先复制一份。 --- src/app/service/service_worker/value.test.ts | 19 +++++++++++++++++++ src/app/service/service_worker/value.ts | 3 ++- 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/src/app/service/service_worker/value.test.ts b/src/app/service/service_worker/value.test.ts index 620a30eb3..2e8e77aee 100644 --- a/src/app/service/service_worker/value.test.ts +++ b/src/app/service/service_worker/value.test.ts @@ -574,3 +574,22 @@ describe("ValueService pushValueUpdate 投递目标", () => { 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" }); + }); +}); diff --git a/src/app/service/service_worker/value.ts b/src/app/service/service_worker/value.ts index 8d21d6ee1..3607c8a5f 100644 --- a/src/app/service/service_worker/value.ts +++ b/src/app/service/service_worker/value.ts @@ -44,7 +44,8 @@ export class ValueService { if (ret) { data = ret.data; } - const newValues = data; + // 复制一份再合并:data 是 ValueDAO 缓存里的记录本身,直接改会让默认值混进其他脚本的值并被持久化 + const newValues = { ...data }; // 和userconfig组装 const { config } = script; if (config) { From 512bfc6f5be64f9c1fa1924020f1cecc9bc909a7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E4=B8=80=E4=B9=8B?= Date: Thu, 12 Nov 2026 11:11:33 +0800 Subject: [PATCH 09/10] =?UTF-8?q?=F0=9F=90=9B=20=E5=80=BC=E6=9B=B4?= =?UTF-8?q?=E6=96=B0=20Port=20=E9=87=8D=E8=AE=A2=E9=98=85=E6=97=B6?= =?UTF-8?q?=E6=8C=89=E7=89=88=E6=9C=AC=E8=A1=A5=E9=BD=90=E6=BC=8F=E6=94=B6?= =?UTF-8?q?=E7=9A=84=E6=9B=B4=E6=96=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit SW 重启后 Port 要经过重连和订阅握手才能再收到推送,这期间其他页面的写入会漏收, 页面缓存会一直停在旧值,直到这个键再被写一次。 - Value 记录增加单调递增的 revision,每次保存时在写锁内更新,并随推送和 pageLoad 下发 - 订阅改为按 storageName 带上已知版本和运行中的脚本;SW 在该存储的写锁里先登记、再读版本, 版本不一致时按脚本 uuid 返回当前全部值(含各自的用户配置默认值) - scripting 在确认前缓存推送,确认后先应用快照,再丢弃版本不新的推送 - 首次订阅的快照和确认前到达的推送在脚本启动前合并进 pageLoad 数据, 顺带补上 pageLoad 读取 value 之后、订阅确认之前的写入 - 脚本已启动时经新消息 runtime/valueSync 交给对应脚本,GMApi 逐键对比, 对变化的键以 remote=true 触发监听;快照只有最终值,中间状态会合并 --- src/app/repo/scripts.ts | 1 + src/app/repo/value.ts | 2 + .../service/content/create_context.test.ts | 25 ++++ src/app/service/content/exec_script.ts | 4 + src/app/service/content/gm_api/gm_api.ts | 17 +++ src/app/service/content/page_load_contract.ts | 1 + .../service/content/script_executor.test.ts | 14 ++ src/app/service/content/script_executor.ts | 10 +- src/app/service/content/script_runtime.ts | 5 +- src/app/service/content/scripting.test.ts | 96 +++++++++++++- src/app/service/content/scripting.ts | 83 +++++++++++- src/app/service/content/types.ts | 20 +++ .../content/value_port.integration.test.ts | 9 +- src/app/service/content/value_port.test.ts | 101 ++++++++++++--- src/app/service/content/value_port.ts | 29 +++-- .../service/service_worker/runtime.test.ts | 24 +++- src/app/service/service_worker/runtime.ts | 13 +- src/app/service/service_worker/value.test.ts | 116 +++++++++++++++++ src/app/service/service_worker/value.ts | 40 +++++- .../service/service_worker/value_port.test.ts | 122 +++++++++++++++--- src/app/service/service_worker/value_port.ts | 59 ++++++--- 21 files changed, 697 insertions(+), 94 deletions(-) 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.ts b/src/app/service/content/gm_api/gm_api.ts index 4f80d2896..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; } @@ -211,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; 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 index 5a41062c6..2c91c3de3 100644 --- a/src/app/service/content/scripting.test.ts +++ b/src/app/service/content/scripting.test.ts @@ -4,6 +4,7 @@ import type { MessageConnect, MessageSend, TMessage } from "@Packages/message/ty 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; @@ -133,7 +134,12 @@ describe("ScriptingRuntime 值更新投递", () => { await vi.waitFor(() => expect(portSend).toHaveBeenCalledWith({ action: "runtime/subscribeValueUpdates", - data: ["page-store", "shared", "content-store", "__proto__"], + 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(); @@ -175,6 +181,94 @@ describe("ScriptingRuntime 值更新投递", () => { 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(); diff --git a/src/app/service/content/scripting.ts b/src/app/service/content/scripting.ts index 2b4eb94ec..3eb70ac41 100644 --- a/src/app/service/content/scripting.ts +++ b/src/app/service/content/scripting.ts @@ -6,7 +6,9 @@ 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 = { @@ -20,6 +22,11 @@ type PageOrContent = ValueOf; // scripting页的处理 export default class ScriptingRuntime { 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的消息 @@ -33,14 +40,65 @@ export default class ScriptingRuntime { // 发送给inject的消息接口 private readonly senderToInject: CustomEventMessage ) { - this.valuePort = new ScriptingValuePort(this.senderToExt, (data) => this.forwardValueUpdate(data)); + 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 activeOn = this.activeStorageNames.get(data.storageName); + const { storageName, revision } = data; + const activeOn = this.activeStorageNames.get(storageName); if (!activeOn) return; - void this.broadcastToPage("runtime/valueUpdate", data, activeOn).catch((error) => { - LoggerCore.logger().error("forward value update failed", { storageName: data.storageName, error }); + 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 }); }); } @@ -154,9 +212,20 @@ export default class ScriptingRuntime { 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]); + } - // 先确认中央已建立订阅,再启动页面脚本;早期 GM.setValue 的回执不会落入订阅空窗。 - await this.valuePort.subscribe([...this.activeStorageNames.keys()]); + // 先确认中央已建立订阅,再启动页面脚本:早期 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 index 49ac40a56..a573273bd 100644 --- a/src/app/service/content/value_port.integration.test.ts +++ b/src/app/service/content/value_port.integration.test.ts @@ -11,13 +11,16 @@ describe("scripting ↔ serviceWorker Port 通道", () => { const transport = new MockMessage(new EventEmitter()); const server = new Server("serviceWorker", transport); const failures = vi.fn(); - const ports = new ValueUpdatePorts(failures); + 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); + const channel = new ScriptingValuePort(transport, received, vi.fn()); channel.start(); - await channel.subscribe(["script-a"]); + await channel.subscribe(() => [{ storageName: "script-a", revision: 0, uuids: ["uuid-a"] }]); const update: ValueUpdateDataEncoded = { uuid: "uuid-a", storageName: "script-a", diff --git a/src/app/service/content/value_port.test.ts b/src/app/service/content/value_port.test.ts index 07a4a99a8..e92ccf00e 100644 --- a/src/app/service/content/value_port.test.ts +++ b/src/app/service/content/value_port.test.ts @@ -1,6 +1,10 @@ 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[] = []; @@ -41,13 +45,13 @@ describe("ScriptingValuePort 生命周期", () => { const port = new TestPort(); const { sender, connect } = createSender(port); const delivered = vi.fn(); - const channel = new ScriptingValuePort(sender, delivered); + const channel = new ScriptingValuePort(sender, delivered, vi.fn()); channel.start(); - const ready = channel.subscribe(["shared", "shared", "content"]); + 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: ["shared", "content"] }]); + expect(port.sent).toEqual([{ action: "runtime/subscribeValueUpdates", data: subs("shared", "content") }]); let subscribed = false; void ready.then(() => (subscribed = true)); @@ -63,14 +67,69 @@ describe("ScriptingValuePort 生命周期", () => { 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()); + const channel = new ScriptingValuePort(sender, vi.fn(), vi.fn()); channel.start(); - const ready = channel.subscribe(["a"]); + const ready = channel.subscribe(() => subs("a")); await Promise.resolve(); oldPort.receive({ code: 0, data: { ready: true } }); oldPort.receive({ action: "runtime/valueSubscriptionsReady" }); @@ -80,13 +139,13 @@ describe("ScriptingValuePort 生命周期", () => { await vi.advanceTimersByTimeAsync(1000); expect(connect).toHaveBeenCalledTimes(2); newPort.receive({ code: 0, data: { ready: true } }); - expect(newPort.sent).toEqual([{ action: "runtime/subscribeValueUpdates", data: ["a"] }]); + 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(["a"]); + const ready = channel.subscribe(() => subs("a")); await Promise.resolve(); port.receive({ code: 0, data: { ready: true } }); port.receive({ action: "runtime/valueSubscriptionsReady" }); @@ -98,7 +157,7 @@ describe("ScriptingValuePort 生命周期", () => { const oldPort = new TestPort(); const newPort = new TestPort(); const { sender, connect } = createSender(oldPort, newPort); - const channel = new ScriptingValuePort(sender, vi.fn()); + const channel = new ScriptingValuePort(sender, vi.fn(), vi.fn()); channel.start(); await subscribeAndAck(channel, oldPort); await vi.advanceTimersByTimeAsync(30_000); @@ -114,7 +173,7 @@ describe("ScriptingValuePort 生命周期", () => { const oldPort = new TestPort(); const newPort = new TestPort(); const { sender, connect } = createSender(oldPort, newPort); - const channel = new ScriptingValuePort(sender, vi.fn()); + const channel = new ScriptingValuePort(sender, vi.fn(), vi.fn()); channel.start(); await subscribeAndAck(channel, oldPort); @@ -138,7 +197,7 @@ describe("ScriptingValuePort 生命周期", () => { const errorSpy = vi.spyOn(console, "error").mockImplementation(() => undefined); try { const { sender, connect } = createSender(); - const channel = new ScriptingValuePort(sender, vi.fn()); + const channel = new ScriptingValuePort(sender, vi.fn(), vi.fn()); runtime.id = undefined; channel.start(); await vi.advanceTimersByTimeAsync(60_000); @@ -154,7 +213,7 @@ describe("ScriptingValuePort 生命周期", () => { vi.useFakeTimers(); const port = new TestPort(); const { sender, connect } = createSender(port, new TestPort()); - const channel = new ScriptingValuePort(sender, vi.fn()); + const channel = new ScriptingValuePort(sender, vi.fn(), vi.fn()); channel.start(); await subscribeAndAck(channel, port); await vi.advanceTimersByTimeAsync(30_000); @@ -171,10 +230,10 @@ describe("ScriptingValuePort 生命周期", () => { vi.useFakeTimers(); const port = new TestPort(); const { sender, connect } = createSender(port); - const channel = new ScriptingValuePort(sender, vi.fn()); + const channel = new ScriptingValuePort(sender, vi.fn(), vi.fn()); channel.start(); await Promise.resolve(); - await channel.subscribe([]); + await channel.subscribe(() => []); port.disconnect(); await vi.advanceTimersByTimeAsync(5000); expect(connect).toHaveBeenCalledOnce(); @@ -184,9 +243,9 @@ describe("ScriptingValuePort 生命周期", () => { const oldPort = new TestPort(); const newPort = new TestPort(); const { sender, connect } = createSender(oldPort, newPort); - const channel = new ScriptingValuePort(sender, vi.fn()); + const channel = new ScriptingValuePort(sender, vi.fn(), vi.fn()); channel.start(); - const ready = channel.subscribe(["a"]); + const ready = channel.subscribe(() => subs("a")); await Promise.resolve(); expect(connect).toHaveBeenCalledOnce(); oldPort.receive({ code: 0, data: { ready: true } }); @@ -201,7 +260,7 @@ describe("ScriptingValuePort 生命周期", () => { await Promise.resolve(); expect(connect).toHaveBeenCalledTimes(2); newPort.receive({ code: 0, data: { ready: true } }); - expect(newPort.sent).toEqual([{ action: "runtime/subscribeValueUpdates", data: ["a"] }]); + expect(newPort.sent).toEqual([{ action: "runtime/subscribeValueUpdates", data: subs("a") }]); channel.stop(); }); @@ -212,9 +271,9 @@ describe("ScriptingValuePort 生命周期", () => { 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()); + const channel = new ScriptingValuePort({ connect } as unknown as MessageSend, vi.fn(), vi.fn()); channel.start(); - const ready = channel.subscribe(["a"]); + const ready = channel.subscribe(() => subs("a")); const pageshow = new PageTransitionEvent("pageshow"); Object.defineProperty(pageshow, "persisted", { value: true }); @@ -224,7 +283,7 @@ describe("ScriptingValuePort 生命周期", () => { resolveOld(oldPort); await Promise.resolve(); newPort.receive({ code: 0, data: { ready: true } }); - expect(newPort.sent).toEqual([{ action: "runtime/subscribeValueUpdates", data: ["a"] }]); + expect(newPort.sent).toEqual([{ action: "runtime/subscribeValueUpdates", data: subs("a") }]); expect(oldPort.sent).toEqual([]); expect(oldDisconnect).toHaveBeenCalledOnce(); newPort.receive({ action: "runtime/valueSubscriptionsReady" }); @@ -237,11 +296,11 @@ describe("ScriptingValuePort 生命周期", () => { const oldPort = new TestPort(); const newPort = new TestPort(); const { sender, connect } = createSender(oldPort, newPort); - const channel = new ScriptingValuePort(sender, vi.fn()); + const channel = new ScriptingValuePort(sender, vi.fn(), vi.fn()); const errorSpy = vi.spyOn(console, "error").mockImplementation(() => undefined); try { channel.start(); - const ready = channel.subscribe(["a"]); + const ready = channel.subscribe(() => subs("a")); await Promise.resolve(); oldPort.sendMessage = () => { throw new Error("closed"); diff --git a/src/app/service/content/value_port.ts b/src/app/service/content/value_port.ts index 60ff79c33..22ea0a30f 100644 --- a/src/app/service/content/value_port.ts +++ b/src/app/service/content/value_port.ts @@ -1,5 +1,5 @@ import type { MessageConnect, MessageSend } from "@Packages/message/types"; -import type { ValueUpdateDataEncoded } from "./types"; +import type { ValueSubscription, ValueSubscriptionAck, ValueUpdateDataEncoded } from "./types"; // 确认订阅后存活不到这么久就断开,视为 SW 异常,改为退避重试,避免反复崩溃时重连死循环。 const STABLE_PORT_MS = 1000; @@ -14,7 +14,9 @@ export default class ScriptingValuePort { private connectionGeneration = 0; private portReady = false; private stopped = false; - private storageNames: string[] | undefined; + private getSubscriptions: (() => ValueSubscription[]) | undefined; + // 订阅确认之前收到的推送;确认里的快照要先应用,之后才能按版本判断这些推送是否已包含在快照里 + private buffered: ValueUpdateDataEncoded[] | undefined; private subscribeDone: (() => void) | undefined; private retryTimer: ReturnType | undefined; private retryDelay = 250; @@ -36,7 +38,8 @@ export default class ScriptingValuePort { constructor( private readonly sender: MessageSend, - private readonly onValueUpdate: (data: ValueUpdateDataEncoded) => void + private readonly onValueUpdate: (data: ValueUpdateDataEncoded) => void, + private readonly onSubscribed: (acks: ValueSubscriptionAck[]) => void ) {} start() { @@ -44,12 +47,13 @@ export default class ScriptingValuePort { window.addEventListener("pageshow", this.onPageShow); } - subscribe(names: string[]): Promise { - if (names.length === 0) { + // 每次(重新)订阅时现取:重连后要带上最新的已知版本 + subscribe(getSubscriptions: () => ValueSubscription[]): Promise { + if (getSubscriptions().length === 0) { this.stop(); return Promise.resolve(); } - this.storageNames = [...new Set(names)]; + this.getSubscriptions = getSubscriptions; return new Promise((resolve) => { this.subscribeDone = resolve; this.sendSubscriptions(); @@ -82,6 +86,7 @@ export default class ScriptingValuePort { 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) { @@ -90,12 +95,18 @@ export default class ScriptingValuePort { } 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") { - this.onValueUpdate(message.data as ValueUpdateDataEncoded); + const data = message.data as ValueUpdateDataEncoded; + if (this.buffered) this.buffered.push(data); + else this.onValueUpdate(data); } }); port.onDisconnect(() => { @@ -129,9 +140,9 @@ export default class ScriptingValuePort { } private sendSubscriptions() { - if (this.portReady && this.port && this.storageNames) { + if (this.portReady && this.port && this.getSubscriptions) { try { - this.port.sendMessage({ action: "runtime/subscribeValueUpdates", data: this.storageNames }); + this.port.sendMessage({ action: "runtime/subscribeValueUpdates", data: this.getSubscriptions() }); } catch (error) { this.failPort(this.port, error); } diff --git a/src/app/service/service_worker/runtime.test.ts b/src/app/service/service_worker/runtime.test.ts index 793b7f8fd..45f4fe7a9 100644 --- a/src/app/service/service_worker/runtime.test.ts +++ b/src/app/service/service_worker/runtime.test.ts @@ -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; @@ -1483,6 +1485,12 @@ 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", @@ -1500,7 +1508,13 @@ describe("pushValueUpdate 页面投递", () => { onDisconnect: vi.fn(), } as unknown as MessageConnect; runtime.connectValueUpdates(undefined, { getConnect: () => port } as unknown as IGetSender); - onMessage({ action: "runtime/subscribeValueUpdates", data: ["test-storage"] }); + 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"); diff --git a/src/app/service/service_worker/runtime.ts b/src/app/service/service_worker/runtime.ts index b998028e3..ff0fb2f15 100644 --- a/src/app/service/service_worker/runtime.ts +++ b/src/app/service/service_worker/runtime.ts @@ -133,9 +133,12 @@ export type TScriptsForTab = { const bgScriptStorageNames = new Set(); export class RuntimeService { - private readonly valuePorts = new ValueUpdatePorts((context, error) => { - this.logger.error("value update Port delivery failed", context, Logger.E(error)); - }); + 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; @@ -1606,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/value.test.ts b/src/app/service/service_worker/value.test.ts index 2e8e77aee..db2d2cda9 100644 --- a/src/app/service/service_worker/value.test.ts +++ b/src/app/service/service_worker/value.test.ts @@ -168,6 +168,36 @@ describe("ValueService - setValue 方法测试", () => { 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(); @@ -593,3 +623,89 @@ describe("ValueService getScriptValue 合并用户配置默认值", () => { expect(record.data).toEqual({ k: "v" }); }); }); + +describe("ValueService subscribeSnapshot 重订阅补齐", () => { + const storageName = "shared-store"; + const createScript = (uuid: string, overrides: Partial