A full-featured download manager.
fix(bridge): isolate browser extension installations (#2468)
Dr_rOot3093fd84717f
diff --git a/.claude/rules/bridge.md b/.claude/rules/bridge.mdindex ce415fc6..5bad573f 100644--- a/.claude/rules/bridge.md+++ b/.claude/rules/bridge.md@@ -40,6 +40,14 @@ Import `ErrorCodes` and `makeMdxpError` from the package.`motrix/initialized` notification. Providers passed to`UrlResolutionService` must filter to ready connections before sendingserver-initiated `url/probe` or `url/resolve` requests.+- Live session and task-notification routing uses the authenticated credential's+ full `{browser, verifiedOrigin, clientInstallationId}` principal. Keep the+ extension-wide trust/revocation key separate. Only the same installation's+ reconnect replaces and closes its predecessor; an Origin-wide revoke must+ cut authorization and close every installation. Legacy task keys without an+ installation broadcast task notifications to every authorized, ready profile+ matching their browser and extension ID. A modern key must never fall back+ to siblings when its installation is offline or not ready.- The connection close handler removes its own current session and disposes theconnection. Do not mutate the server's session map from feature code.diff --git a/docs/bridge-pairing-protocol.md b/docs/bridge-pairing-protocol.mdindex b3ac92da..ee8df2f5 100644--- a/docs/bridge-pairing-protocol.md+++ b/docs/bridge-pairing-protocol.md@@ -790,6 +790,14 @@ Atomicity rules:- Credential principal: `{browser, verifiedOrigin, clientInstallationId}`. Asecond browser profile is a **new principal** and pairs as a newcredential; issuing or rotating one credential MUST NOT affect another.+ Live connections MUST also be indexed by this full authenticated principal.+ A reconnect replaces and closes only that installation's previous connection;+ other installations remain usable. New task notification routing and+ submission idempotency MUST retain the installation boundary. Legacy tasks+ that only store `{browser, extensionId}` broadcast their notifications to all+ authorized, ready installations of that extension; no credential or task+ migration is required. Extension-wide revocation still applies to every+ principal for the selected verified Origin.- Expired or revoked credentials always require a fresh code-entry pairing —never silent re-trust.diff --git a/docs/bridge-pairing-protocol.zh-CN.md b/docs/bridge-pairing-protocol.zh-CN.mdindex 856083e0..927f4329 100644--- a/docs/bridge-pairing-protocol.zh-CN.md+++ b/docs/bridge-pairing-protocol.zh-CN.md@@ -541,6 +541,11 @@ kS2C = HKDF-SHA-256(ikm=Ke, salt="MBP1/pair/v1", info="MBP1-pair-traffic-s2c", L- 凭据 principal:`{browser, verifiedOrigin, clientInstallationId}`。第二个浏览器 profile 是**新的 principal**,作为新凭据配对;签发或轮换一个凭据MUST NOT 影响另一个。+ 活动连接也 MUST 按完整的已认证 principal 索引。重连只替换并关闭同一安装+ 实例的旧连接,其他安装实例继续可用。新任务的通知路由和提交幂等性 MUST+ 保留安装实例边界。只保存 `{browser, extensionId}` 的旧任务将通知广播到+ 该扩展所有已授权、就绪的安装实例,无需迁移凭据或任务数据。扩展级撤销+ 仍作用于所选 verified Origin 下的全部 principal。- 过期或被吊销的凭据一律要求重新 code-entry 配对——绝不静默重新信任。这与扩展既有的“先持久化、再发送 `motrix/initialized`”顺序保持一致。diff --git a/e2e/bridge/remote-extension-harness.ts b/e2e/bridge/remote-extension-harness.tsindex 4ee3db33..0c58d0d4 100644--- a/e2e/bridge/remote-extension-harness.ts+++ b/e2e/bridge/remote-extension-harness.ts@@ -1,11 +1,11 @@import { request as httpRequest } from 'node:http'import { createServer as createHttpsServer } from 'node:https'import { connect as connectTcp } from 'node:net'+import type { Duplex } from 'node:stream'import type { BridgeEventBus } from '@core/bridge/bridge-event-bus'import type { ReadHandlerDeps } from '@core/bridge/handlers/read-handlers'import type { WriteHandlerDeps } from '@core/bridge/handlers/write-handlers'import type { DownloadSubmitParams } from '@motrix/mdxp'-import { makeSessionKey } from '@shared/protocol/bridge'import { EngineState } from '@shared/types/engine'import {bootstrapBridgeForServer,@@ -58,14 +58,15 @@ function createReceiver(submissions.push(structuredClone(params))const taskId = `browser-task-${submissions.length}`const identity = context.identity- if (identity.kind !== 'extension') {+ if (identity.kind !== 'extension' || !context.sessionKey) {throw new Error('remote Extension receiver got a non-Extension session')}+ const sessionKey = context.sessionKeyconst progressTimer = setTimeout(() => {progressTimers.delete(progressTimer)if (stopped) returnbridgeBus.emitTaskProgress({- sessionKey: makeSessionKey(identity.browser, identity.extensionId),+ sessionKey,params: {taskId,bytesDone: 512,@@ -128,6 +129,12 @@ export async function startTlsProxy(input: {cert: string}): Promise<() => Promise<void>> {const proxy = createHttpsServer({ key: input.key, cert: input.cert })+ const sockets = new Set<Duplex>()+ const track = (socket: Duplex) => {+ sockets.add(socket)+ socket.once('close', () => sockets.delete(socket))+ }+ proxy.on('connection', track)proxy.on('request', (request, response) => {const upstream = httpRequest({@@ -153,6 +160,10 @@ export async function startTlsProxy(input: {})proxy.on('upgrade', (request, downstream, head) => {const upstream = connectTcp(input.upstreamPort, '127.0.0.1')+ track(downstream)+ track(upstream)+ downstream.once('close', () => upstream.destroy())+ upstream.once('close', () => downstream.destroy())upstream.once('connect', () => {upstream.write(`${request.method ?? 'GET'} ${request.url ?? '/'} HTTP/${request.httpVersion}\r\n`@@ -174,6 +185,9 @@ export async function startTlsProxy(input: {})return () =>new Promise<void>((resolve, reject) => {+ // HTTPS close does not terminate upgraded tunnels. Own them explicitly+ // so a failed assertion cannot hide behind a hanging fixture teardown.+ for (const socket of sockets) socket.destroy()proxy.close((error) => (error ? reject(error) : resolve()))})}diff --git a/e2e/bridge/remote-extension-wss.spec.ts b/e2e/bridge/remote-extension-wss.spec.tsindex 6c9037fe..2a14894d 100644--- a/e2e/bridge/remote-extension-wss.spec.ts+++ b/e2e/bridge/remote-extension-wss.spec.ts@@ -7,6 +7,11 @@ import type { DownloadSubmitParams } from '@motrix/mdxp'import type { BrowserContext, Page } from '@playwright/test'import { chromium, expect, test } from '@playwright/test'import type { ServerBridgeRuntime } from '../../src/server/bridge/bootstrap'+import {+ BridgeCommands,+ BridgeQueries,+ type PairedClientInfo,+} from '../../src/shared/protocol/bridge'import { getFreePort } from '../helpers/free-port'import {PUBLIC_HOST,@@ -45,6 +50,19 @@ async function launchExtension(input: {const serviceWorker =context.serviceWorkers()[0] ??(await context.waitForEvent('serviceworker', { timeout: 15_000 }))+ // macOS can keep chrome.i18n.getUILanguage() on the OS language even with+ // --lang and Playwright's navigator locale override. Set this fresh test+ // profile's supported application preference before opening extension UI.+ await serviceWorker.evaluate(async () => {+ const extensionGlobal = globalThis as typeof globalThis & {+ chrome: {+ storage: {+ local: { set(values: Record<string, unknown>): Promise<void> }+ }+ }+ }+ await extensionGlobal.chrome.storage.local.set({ 'motrix.locale': 'en-US' })+ })return {context,extensionId: new URL(serviceWorker.url()).hostname,@@ -56,6 +74,7 @@ async function openIntegration(extensionId: string): Promise<Page> {const page = await context.newPage()+ page.setDefaultTimeout(15_000)await page.goto(`chrome-extension://${extensionId}/options.html`)await page.getByRole('tab', { name: 'Integration' }).click()await expect(@@ -505,3 +524,158 @@ test('real Chromium: local profile keeps two remote Servers paired and policy-isawait rm(root, { recursive: true, force: true })}})++test('real Chromium: two profiles of the same extension stay connected across RPC, notifications, restart, and revoke', async () => {+ const extensionBuild = process.env.MOTRIX_EXTENSION_BUILD+ if (!extensionBuild || !existsSync(join(extensionBuild, 'manifest.json'))) {+ throw new Error(+ 'MOTRIX_EXTENSION_BUILD must point to a built Chromium Extension directory'+ )+ }+ const fixtureRoot = join(process.cwd(), 'src/server/bridge/__fixtures__')+ const [cert, key] = await Promise.all([+ readFile(join(fixtureRoot, 'motrix.test-cert.pem'), 'utf8'),+ readFile(join(fixtureRoot, 'motrix.test-key.pem'), 'utf8'),+ ])+ const root = await mkdtemp(join(tmpdir(), 'motrix-multi-profile-e2e-'))+ const [bridgePort, proxyPort] = await Promise.all([+ getFreePort(),+ getFreePort(),+ ])+ const contexts: BrowserContext[] = []+ let runtime: ServerBridgeRuntime | null = null+ let closeProxy: (() => Promise<void>) | null = null+ try {+ runtime = await startRuntime({+ dataDir: join(root, 'server'),+ bridgePort,+ proxyPort,+ submissions: [],+ })+ closeProxy = await startTlsProxy({+ listenPort: proxyPort,+ upstreamPort: bridgePort,+ key,+ cert,+ })+ const installations = async () => {+ const paired = (await runtime!.bridgeQueryHandlers[+ BridgeQueries.ListPaired+ ]()) as PairedClientInfo[]+ return paired.flatMap((client) =>+ client.kind === 'extension' ? (client.installations ?? []) : []+ )+ }+ const pages: Page[] = []+ const ids: string[] = []+ const installationIds: string[] = []+ for (const profile of ['a', 'b']) {+ const launch = await launchExtension({+ extensionBuild,+ profileDir: join(root, profile),+ spkiPin: certificateSpkiPin(cert),+ })+ contexts.push(launch.context)+ ids.push(launch.extensionId)+ const page = await openIntegration(launch.context, launch.extensionId)+ pages.push(page)+ await addServerFromOptions(+ page,+ 'Shared Motrix',+ `wss://${PUBLIC_HOST}:${proxyPort}${ROUTE_PREFIX}`+ )+ await page.getByRole('button', { name: 'Use Shared Motrix' }).click()+ await pairFromOptions(page, runtime)+ const installation = (await installations()).find(+ (item) => !installationIds.includes(item.id)+ )+ if (!installation) throw new Error('paired installation was not listed')+ installationIds.push(installation.id)+ }+ expect(ids[0]).toBe(ids[1])+ await expect+ .poll(+ async () =>+ (await installations()).filter((item) => item.connected).length+ )+ .toBe(2)+ const assertResponsive = async () => {+ for (const page of pages) {+ await expect(page.getByText('Connected', { exact: true })).toBeVisible()+ const result = await page.evaluate(async () => {+ const api = (+ globalThis as unknown as {+ chrome: {+ runtime: { sendMessage(message: unknown): Promise<unknown> }+ }+ }+ ).chrome+ return api.runtime.sendMessage({ kind: 'bg.taskList', payload: {} })+ })+ expect(result).toEqual({ tasks: [], total: 0 })+ }+ }+ await assertResponsive()+ const notifyProgress = (index: number) => {+ const session = runtime!.server.getSession(installationIds[index])+ if (!session) throw new Error('installation session is unavailable')+ session.conn.sendNotification('$/task/progress', {+ taskId: `profile-task-${index}`,+ bytesDone: 512,+ bytesTotal: 1024,+ speedBps: 256,+ etaSec: 2,+ phase: 'downloading',+ })+ }+ notifyProgress(0)+ await expect.poll(() => actionBadgeText(pages[0])).toBe('↓')+ expect(await actionBadgeText(pages[1])).not.toBe('↓')+ notifyProgress(1)+ await expect.poll(() => actionBadgeText(pages[1])).toBe('↓')++ // Reopening one profile reuses its credential without evicting its sibling.+ await contexts[0].close()+ await expect+ .poll(+ async () =>+ (await installations()).filter((item) => item.connected).length+ )+ .toBe(1)+ const back = await launchExtension({+ extensionBuild,+ profileDir: join(root, 'a'),+ spkiPin: certificateSpkiPin(cert),+ })+ contexts[0] = back.context+ pages[0] = await openIntegration(back.context, back.extensionId)+ await expect(pages[0].getByText('Pairing ready')).toBeVisible()+ await expect+ .poll(+ async () =>+ (await installations()).filter((item) => item.connected).length+ )+ .toBe(2)+ expect((await installations()).map((item) => item.id).sort()).toEqual(+ [...installationIds].sort()+ )+ await assertResponsive()+ notifyProgress(0)+ await expect.poll(() => actionBadgeText(pages[0])).toBe('↓')++ await runtime.bridgeCommandHandlers[BridgeCommands.RevokePair]({+ identity: { kind: 'extension', browser: 'chromium', extensionId: ids[0] },+ })+ for (const page of pages) {+ await page.reload()+ await page.getByRole('tab', { name: 'Integration' }).click()+ await expect(page.getByText('Not paired')).toBeVisible()+ }+ expect(await installations()).toHaveLength(0)+ } finally {+ await Promise.all(contexts.map((context) => context.close()))+ if (closeProxy) await closeProxy()+ if (runtime) await runtime.shutdown()+ await rm(root, { recursive: true, force: true })+ }+})diff --git a/screenshots/motrix-browser-extension-profiles-en-light.png b/screenshots/motrix-browser-extension-profiles-en-light.pngnew file mode 100644index 00000000..73a28855Binary files /dev/null and b/screenshots/motrix-browser-extension-profiles-en-light.png differdiff --git a/src/core/bridge-receiver/bridge-receiver.test.ts b/src/core/bridge-receiver/bridge-receiver.test.tsindex c089bd5d..e57cca5d 100644--- a/src/core/bridge-receiver/bridge-receiver.test.ts+++ b/src/core/bridge-receiver/bridge-receiver.test.ts@@ -1,4 +1,6 @@import { NOOP_TASK_ACTIVITY_RECORDER } from '@core/activity'+import { principalKey } from '@core/bridge/credential-store'+import type { MdxpSessionContext } from '@core/bridge/mdxp-session-context'import type { SegmentAria2 } from '@core/download/segment-downloader'import { MediaTaskCoordinator } from '@core/task/media-task-coordinator'import { TaskManager } from '@core/task/task-manager'@@ -825,6 +827,52 @@ describe('BridgeReceiver', () => {expect(r2.taskId).toBe(r1.taskId)})+ it('isolates same-key submissions and notification metadata between installations, while reconnect retries deduplicate', async () => {+ let n = 0+ const createTask = vi.fn(async () => ({+ gid: 'g',+ taskId: `task-${++n}`,+ }))+ const r = new BridgeReceiver(+ fakeDeps({ createTask: createTask as never }) as never+ )+ const context = (clientInstallationId: string): MdxpSessionContext => ({+ ...(extCtx as MdxpSessionContext),+ sessionKey: principalKey({+ browser: 'chromium',+ verifiedOrigin: 'chrome-extension://e',+ clientInstallationId,+ }),+ })+ const a = context('profile-a')+ const b = context('profile-b')+ const first = await r.handle(submitParams('shared-key'), a)+ const second = await r.handle(submitParams('shared-key'), b)+ const retry = await r.handle(+ submitParams('shared-key'),+ context('profile-a')+ )+ expect(first.taskId).not.toBe(second.taskId)+ expect(retry).toEqual(first)+ expect(createTask).toHaveBeenCalledTimes(2)+ expect(createTask).toHaveBeenNthCalledWith(+ 1,+ expect.anything(),+ undefined,+ expect.objectContaining({+ sourceMeta: expect.objectContaining({ sessionKey: a.sessionKey }),+ })+ )+ expect(createTask).toHaveBeenNthCalledWith(+ 2,+ expect.anything(),+ undefined,+ expect.objectContaining({+ sourceMeta: expect.objectContaining({ sessionKey: b.sessionKey }),+ })+ )+ })+it('different keys create independent tasks', async () => {let n = 0const createTask = vi.fn(async () => ({diff --git a/src/core/bridge-receiver/bridge-receiver.ts b/src/core/bridge-receiver/bridge-receiver.tsindex c74f6b2e..0070c842 100644--- a/src/core/bridge-receiver/bridge-receiver.ts+++ b/src/core/bridge-receiver/bridge-receiver.ts@@ -185,8 +185,8 @@ export class BridgeReceiver {private readonly terminalEmitted = new Map<string, string>()/*** In-flight and settled download/submit results keyed by- * [clientKey(identity), idempotencyKey]. A retransmit of the same logical- * submit (lost response, reconnect replay) awaits or receives the original+ * [authenticated installation key, idempotencyKey]. A retransmit of the same+ * logical submit (lost response, reconnect replay) awaits or receives the original* result instead of creating a duplicate task — dedup semantics live in* IdempotencyCache (failure eviction, settled-only capacity eviction).*/@@ -309,13 +309,14 @@ export class BridgeReceiver {)}const identity = ctx.identity+ const sessionKey = ctx.sessionKey ?? clientKey(identity)const key = params.idempotencyKey- if (!key) return this.dispatchSubmit(params, identity)+ if (!key) return this.dispatchSubmit(params, identity, sessionKey)const result = await this.submitsByKey.run(- JSON.stringify([clientKey(identity), key]),+ JSON.stringify([sessionKey, key]),async () => ({- ...(await this.dispatchSubmit(params, identity)),+ ...(await this.dispatchSubmit(params, identity, sessionKey)),requestedSaveDir: params.saveDir,}))@@ -330,7 +331,8 @@ export class BridgeReceiver {private async dispatchSubmit(params: DownloadSubmitParams,- identity: Extract<MdxpSessionContext['identity'], { kind: 'extension' }>+ identity: Extract<MdxpSessionContext['identity'], { kind: 'extension' }>,+ sessionKey: string): Promise<{ taskId: string }> {// Hold the submit until startup restore has settled (see the dep doc).// Awaited before adapt so even the name pick sees the@@ -341,6 +343,7 @@ export class BridgeReceiver {const adapted = await this.adapter.adapt(params, {extensionId: identity.extensionId,browser: identity.browser,+ sessionKey,})const result = await this.dispatchAdapted(adapted, params)diff --git a/src/core/bridge-receiver/submit-download-adapter.ts b/src/core/bridge-receiver/submit-download-adapter.tsindex dfae56b0..07d4ac1a 100644--- a/src/core/bridge-receiver/submit-download-adapter.ts+++ b/src/core/bridge-receiver/submit-download-adapter.ts@@ -83,6 +83,8 @@ export interface AdaptedMux {}export interface AdaptInput {+ /** Authenticated routing key supplied by the transport, never the request. */+ sessionKey?: stringextensionId: stringbrowser: Browser}@@ -253,7 +255,8 @@ export class SubmitDownloadAdapter {source: DownloadSubmitParams['source'],meta: DownloadSubmitParams['meta']): BridgeSourceMeta {- const sessionKey = makeSessionKey(input.browser, input.extensionId)+ const sessionKey =+ input.sessionKey ?? makeSessionKey(input.browser, input.extensionId)return {kind,extensionId: input.extensionId,diff --git a/src/core/bridge/__tests__/integration.e2e.test.ts b/src/core/bridge/__tests__/integration.e2e.test.tsindex 7b08741d..3a5226c4 100644--- a/src/core/bridge/__tests__/integration.e2e.test.ts+++ b/src/core/bridge/__tests__/integration.e2e.test.ts@@ -9,6 +9,7 @@ import {import {type IssuedCredential,initializeParams,+ installationSessionKey,mdxpOverChannel,pairAndExchange,reconnect,@@ -115,7 +116,9 @@ describe('integration: ext ↔ Motrix end-to-end (MDXP spec appendix B.2)', () =// --- 4. server pushes $/task/progress + $/task/completed, sealed by the// session's own envelope and opened by the client's.- const session = server.getSession(`chromium:${EXTENSION_ID}`)+ const session = server.getSession(+ installationSessionKey(`chrome-extension://${EXTENSION_ID}`)+ )if (!session) throw new Error('session not found after submit')session.conn.sendNotification('$/task/progress', {taskId: 'task-1',diff --git a/src/core/bridge/__tests__/mbp1-client.ts b/src/core/bridge/__tests__/mbp1-client.tsindex ae43a280..5c28b957 100644--- a/src/core/bridge/__tests__/mbp1-client.ts+++ b/src/core/bridge/__tests__/mbp1-client.ts@@ -18,6 +18,7 @@ import { createMdxpConnection, type MdxpConnection } from '@motrix/mdxp'import { utf8ToBytes } from '@noble/hashes/utils.js'import type { Browser } from '@shared/protocol/bridge'import WebSocket, { type RawData } from 'ws'+import { principalKey } from '../credential-store'import { fromBase64Url, toBase64Url } from '../mbp1/canonical'import {DIR_C2S,@@ -699,3 +700,12 @@ function digestOf(wire: Record<string, unknown>): Uint8Array {mac: fromBase64Url(wire.mac as string),})}++/** Routing identity retained across reconnects and credential rotation. */+export function installationSessionKey(+ verifiedOrigin: string,+ browser: Browser = 'chromium',+ clientInstallationId = 'install-1'+): string {+ return principalKey({ browser, verifiedOrigin, clientInstallationId })+}diff --git a/src/core/bridge/__tests__/mbp1-transport.test.ts b/src/core/bridge/__tests__/mbp1-transport.test.tsindex 0eb21697..67a3b453 100644--- a/src/core/bridge/__tests__/mbp1-transport.test.ts+++ b/src/core/bridge/__tests__/mbp1-transport.test.ts@@ -26,6 +26,7 @@ import {fetchNonce,type IssuedCredential,initializeParams,+ installationSessionKey,mdxpOverChannel,openSealedJson,PairAborted,@@ -167,7 +168,12 @@ function upgradeWithHost(/** Drive a complete first pair and return the credential the client stored. */async function pairFully(h: Harness,- opts: { origin?: string; browser?: Browser; claimedExtensionId?: string } = {}+ opts: {+ origin?: string+ browser?: Browser+ claimedExtensionId?: string+ clientInstallationId?: string+ } = {}): Promise<{wire: WireClientcredential: IssuedCredential@@ -178,6 +184,9 @@ async function pairFully(origin: opts.origin ?? OFFICIAL_ORIGIN,browser: opts.browser ?? 'chromium',claimedExtensionId: opts.claimedExtensionId ?? OFFICIAL_ID,+ ...(opts.clientInstallationId+ ? { clientInstallationId: opts.clientInstallationId }+ : {}),})const { channel } = await runPake(hs, h.dialogs.latestCode())const credential = await exchangeCredential(hs, channel)@@ -838,7 +847,9 @@ describe('§6 first pair over the wire', () => {// The token mint is gone: extensions never receive one again.expect(result.pairToken).toBeUndefined()- const session = h.server.getSession(`chromium:${OFFICIAL_ID}`)+ const session = h.server.getSession(+ installationSessionKey(`chrome-extension://${OFFICIAL_ID}`)+ )expect(session).toBeDefined()expect(Array.from(h.server.iterSessions())).toHaveLength(1)expect(h.authenticated).toEqual([@@ -897,7 +908,9 @@ describe('§6 first pair over the wire', () => {const conn = mdxpOverChannel(hs.wire, channel)await conn.sendRequest('motrix/initialize', initializeParams(OFFICIAL_ID))- const session = h.server.getSession(`chromium:${OFFICIAL_ID}`)+ const session = h.server.getSession(+ installationSessionKey(`chrome-extension://${OFFICIAL_ID}`)+ )// The sealer arrived with two frames already spent on the credential// exchange, and the initialize response is the third.expect(session?.envelope.usage.frames).toBe(3)@@ -921,7 +934,11 @@ describe('§6 first pair over the wire', () => {paired.wire.sendBytes(paired.channel.sealer.seal(plaintext))await vi.waitFor(() =>expect(- h.server.getSession(`chromium:${OFFICIAL_ID}`)?.conn.isReady()+ h.server+ .getSession(+ installationSessionKey(`chrome-extension://${OFFICIAL_ID}`)+ )+ ?.conn.isReady()).toBe(true))@@ -1080,7 +1097,9 @@ describe('§6 first pair over the wire', () => {const conn = mdxpOverChannel(hs.wire, channel)await conn.sendRequest('motrix/initialize', initializeParams(OFFICIAL_ID))- const session = h.server.getSession(`chromium:${OFFICIAL_ID}`)+ const session = h.server.getSession(+ installationSessionKey(`chrome-extension://${OFFICIAL_ID}`)+ )expect(session).toBeDefined()for (const ws of (h.server as unknown as {@@ -1200,7 +1219,9 @@ describe('R3 adoption boundary', () => {'motrix/initialize',initializeParams(OFFICIAL_ID))- const liveSession = h.server.getSession(`chromium:${OFFICIAL_ID}`)+ const liveSession = h.server.getSession(+ installationSessionKey(`chrome-extension://${OFFICIAL_ID}`)+ )expect(liveSession).toBeDefined()// A second /pair for the SAME principal, driven only to mid-handshake.@@ -1221,6 +1242,317 @@ describe('R3 adoption boundary', () => {live.wire.ws.close()})+ it('keeps independent installations online and routes task notifications to their submitting installation', async () => {+ const a = await pairFully(h, { clientInstallationId: 'profile-a' })+ const b = await pairFully(h, { clientInstallationId: 'profile-b' })+ const aConn = mdxpOverChannel(a.wire, a.channel)+ const bConn = mdxpOverChannel(b.wire, b.channel)+ const keyA = installationSessionKey(+ OFFICIAL_ORIGIN,+ 'chromium',+ 'profile-a'+ )+ const keyB = installationSessionKey(+ OFFICIAL_ORIGIN,+ 'chromium',+ 'profile-b'+ )+ const aNotifications = vi.fn()+ const bNotifications = vi.fn()+ aConn.onNotification(Notifications.TaskCompleted, aNotifications)+ bConn.onNotification(Notifications.TaskCompleted, bNotifications)+ try {+ for (const conn of [aConn, bConn]) {+ await conn.sendRequest(+ 'motrix/initialize',+ initializeParams(OFFICIAL_ID)+ )+ conn.sendNotification('motrix/initialized', undefined)+ expect(+ await conn.sendRequest('system/ping', { sentAt: 12 })+ ).toMatchObject({ sentAt: 12 })+ }+ expect(h.credentials.listCommitted()).toHaveLength(2)+ expect([...h.server.iterSessions()]).toHaveLength(2)+ expect(+ h.server.getExtensionInstallations({+ kind: 'extension',+ browser: 'chromium',+ extensionId: OFFICIAL_ID,+ })+ ).toEqual([+ { id: keyA, pairedAt: expect.any(Number), connected: true },+ { id: keyB, pairedAt: expect.any(Number), connected: true },+ ])+ const completed = {+ taskId: 'task-a',+ filePath: '/tmp/task-a',+ durationMs: 1000,+ }+ for (const session of h.server.getTaskNotificationSessions(keyA)) {+ session.conn.sendNotification(Notifications.TaskCompleted, completed)+ }+ await vi.waitFor(() =>+ expect(aNotifications).toHaveBeenCalledWith(completed)+ )+ expect(bNotifications).not.toHaveBeenCalled()+ // Exact session lookup does not guess a legacy task’s profile.+ expect(h.server.getSession(`chromium:${OFFICIAL_ID}`)).toBeUndefined()++ const back = await reconnect({+ port: h.port,+ origin: OFFICIAL_ORIGIN,+ instanceId: INSTANCE_ID,+ credential: a.credential,+ })+ const backConn = mdxpOverChannel(back.wire, back.channel)+ try {+ await a.wire.closed+ expect(a.wire.ws.readyState).toBe(3)+ expect([...h.server.iterSessions()]).toHaveLength(2)+ expect(+ await backConn.sendRequest('system/ping', { sentAt: 13 })+ ).toMatchObject({ sentAt: 13 })+ expect(+ await bConn.sendRequest('system/ping', { sentAt: 14 })+ ).toMatchObject({ sentAt: 14 })+ expect(h.server.getSession(keyA)?.conn.isAuthorized()).toBe(true)+ expect(h.server.getSession(keyB)?.conn.isAuthorized()).toBe(true)+ } finally {+ backConn.dispose()+ back.wire.ws.close()+ await back.wire.closed+ }+ await vi.waitFor(() => expect(h.server.getSession(keyA)).toBeUndefined())+ expect(+ h.server.getExtensionInstallations({+ kind: 'extension',+ browser: 'chromium',+ extensionId: OFFICIAL_ID,+ })+ ).toEqual([+ { id: keyA, pairedAt: expect.any(Number), connected: false },+ { id: keyB, pairedAt: expect.any(Number), connected: true },+ ])+ } finally {+ aConn.dispose()+ bConn.dispose()+ a.wire.ws.close()+ b.wire.ws.close()+ }+ })++ it('broadcasts legacy task notifications to matching ready profiles while preserving exact modern routing', async () => {+ const a = await pairFully(h, { clientInstallationId: 'profile-a' })+ const b = await pairFully(h, { clientInstallationId: 'profile-b' })+ const unready = await pairFully(h, { clientInstallationId: 'profile-c' })+ const other = await pairFully(h, {+ origin: SIDELOADED_ORIGIN,+ claimedExtensionId: SIDELOADED_ID,+ })+ const peers = [a, b, unready, other]+ const conns = peers.map((peer) => mdxpOverChannel(peer.wire, peer.channel))+ const received = conns.map(() => [] as string[])+ conns.forEach((conn, index) => {+ conn.onNotification(Notifications.TaskProgress, () =>+ received[index].push('progress')+ )+ conn.onNotification(Notifications.TaskCompleted, () =>+ received[index].push('completed')+ )+ conn.onNotification(Notifications.TaskError, () =>+ received[index].push('error')+ )+ })+ const legacyKey = `chromium:${OFFICIAL_ID}`+ const keyA = installationSessionKey(+ OFFICIAL_ORIGIN,+ 'chromium',+ 'profile-a'+ )+ const keyC = installationSessionKey(+ OFFICIAL_ORIGIN,+ 'chromium',+ 'profile-c'+ )+ const lifecycle = ['progress', 'completed', 'error']+ const publish = (sessionKey: string) => {+ for (const { conn } of h.server.getTaskNotificationSessions(sessionKey)) {+ conn.sendNotification(Notifications.TaskProgress, {+ taskId: 'restored-task',+ bytesDone: 1,+ bytesTotal: 2,+ speedBps: 1,+ etaSec: 1,+ phase: 'downloading',+ })+ conn.sendNotification(Notifications.TaskCompleted, {+ taskId: 'restored-task',+ filePath: '/tmp/restored-task',+ durationMs: 1,+ })+ conn.sendNotification(Notifications.TaskError, {+ taskId: 'restored-task',+ code: 'disk-full',+ message: 'full',+ })+ }+ }+ const flush = (clients = conns) =>+ Promise.all(+ clients.map((conn) => conn.sendRequest('system/ping', { sentAt: 1 }))+ )+ try {+ for (const [index, conn] of conns.entries()) {+ await conn.sendRequest(+ 'motrix/initialize',+ initializeParams(index === 3 ? SIDELOADED_ID : OFFICIAL_ID)+ )+ if (index !== 2) conn.sendNotification('motrix/initialized', undefined)+ }+ await flush()+ publish(legacyKey)+ await flush()+ expect(received).toEqual([lifecycle, lifecycle, [], []])++ publish(keyA)+ publish(keyC) // An authenticated but unready modern peer must not fall back to siblings.+ publish('chromium:unknown-extension')+ await flush()+ expect(received).toEqual([+ [...lifecycle, ...lifecycle],+ lifecycle,+ [],+ [],+ ])++ a.wire.ws.close()+ await a.wire.closed+ await vi.waitFor(() => expect(h.server.getSession(keyA)).toBeUndefined())+ publish(keyA) // An offline modern peer must not fall back to siblings either.+ await flush(conns.slice(1))+ expect(received[1]).toEqual(lifecycle)+ publish(legacyKey)+ await flush(conns.slice(1))+ expect(received[1]).toEqual([...lifecycle, ...lifecycle])+ expect(received[2]).toEqual([])+ expect(received[3]).toEqual([])++ const lease = h.server.beginExtensionRevocation({+ kind: 'extension',+ browser: 'chromium',+ extensionId: OFFICIAL_ID,+ })+ publish(legacyKey)+ await flush(conns.slice(1))+ expect(received[1]).toEqual([...lifecycle, ...lifecycle])+ expect(received[2]).toEqual([])+ await h.server.deleteExtensionAuthorization(lease, 'user-revoked')+ h.server.completeExtensionRevocation(lease)+ } finally {+ for (const conn of conns) conn.dispose()+ for (const peer of peers) peer.wire.ws.close()+ }+ })++ it('revokes all installations of an extension without disconnecting another extension', async () => {+ const a = await pairFully(h, { clientInstallationId: 'profile-a' })+ const b = await pairFully(h, { clientInstallationId: 'profile-b' })+ const other = await pairFully(h, {+ origin: SIDELOADED_ORIGIN,+ claimedExtensionId: SIDELOADED_ID,+ })+ const peers = [a, b, other]+ const conns = peers.map((peer) => mdxpOverChannel(peer.wire, peer.channel))+ const revoked = conns.map((conn) => {+ const handler = vi.fn()+ conn.onNotification(Notifications.PairRevoked, handler)+ return handler+ })+ try {+ const sessions = [...h.server.iterSessions()]+ const lease = h.server.beginExtensionRevocation({+ kind: 'extension',+ browser: 'chromium',+ extensionId: OFFICIAL_ID,+ })+ expect(sessions.map((session) => session.conn.isAuthorized())).toEqual([+ false,+ false,+ true,+ ])+ await expect(+ h.server.deleteExtensionAuthorization(lease, 'user-revoked')+ ).resolves.toBe(2)+ await Promise.all([a.wire.closed, b.wire.closed])+ expect(revoked[0]).toHaveBeenCalledWith({ reason: 'user-revoked' })+ expect(revoked[1]).toHaveBeenCalledWith({ reason: 'user-revoked' })+ expect(revoked[2]).not.toHaveBeenCalled()+ expect([...h.server.iterSessions()]).toHaveLength(1)+ expect(h.credentials.findForAuth(a.credential.credentialId)).toBeNull()+ expect(h.credentials.findForAuth(b.credential.credentialId)).toBeNull()+ expect(+ await conns[2].sendRequest('system/ping', { sentAt: 15 })+ ).toMatchObject({ sentAt: 15 })+ h.server.completeExtensionRevocation(lease)+ } finally {+ for (const conn of conns) conn.dispose()+ for (const peer of peers) peer.wire.ws.close()+ }+ })++ it('closes every installation and retains the shared deny gate if durable revocation fails', async () => {+ const a = await pairFully(h, { clientInstallationId: 'profile-a' })+ const b = await pairFully(h, { clientInstallationId: 'profile-b' })+ const conns = [a, b].map((peer) => mdxpOverChannel(peer.wire, peer.channel))+ const revoked = vi.fn()+ for (const conn of conns)+ conn.onNotification(Notifications.PairRevoked, revoked)+ const identity = {+ kind: 'extension' as const,+ browser: 'chromium' as const,+ extensionId: OFFICIAL_ID,+ }+ try {+ vi.spyOn(h.credentials, 'revokeExtensionIdentity').mockRejectedValueOnce(+ new Error('write failed')+ )+ const lease = h.server.beginExtensionRevocation(identity)+ await expect(+ h.server.deleteExtensionAuthorization(lease, 'user-revoked')+ ).rejects.toThrow('write failed')+ await Promise.all([a.wire.closed, b.wire.closed])+ expect([...h.server.iterSessions()]).toHaveLength(0)+ expect(revoked).not.toHaveBeenCalled()+ expect(h.credentials.listCommitted()).toHaveLength(2)+ expect(+ h.server+ .getExtensionInstallations(identity)+ .map((entry) => entry.connected)+ ).toEqual([false, false])+ for (const credential of [a.credential, b.credential]) {+ await expect(+ reconnect({+ port: h.port,+ origin: OFFICIAL_ORIGIN,+ instanceId: INSTANCE_ID,+ credential,+ })+ ).rejects.toThrow('401')+ }+ expect(h.server.beginExtensionRevocation(identity)).toBe(lease)+ await expect(+ h.server.deleteExtensionAuthorization(lease, 'user-revoked')+ ).resolves.toBe(2)+ h.server.completeExtensionRevocation(lease)+ expect(h.credentials.listCommitted()).toHaveLength(0)+ } finally {+ for (const conn of conns) conn.dispose()+ a.wire.ws.close()+ b.wire.ws.close()+ }+ })+it('replaces a live session atomically, and the old close does not undo it', async () => {const first = await pairFully(h)const firstConn = mdxpOverChannel(first.wire, first.channel)@@ -1228,10 +1560,14 @@ describe('R3 adoption boundary', () => {'motrix/initialize',initializeParams(OFFICIAL_ID))- const firstSession = h.server.getSession(`chromium:${OFFICIAL_ID}`)+ const firstSession = h.server.getSession(+ installationSessionKey(`chrome-extension://${OFFICIAL_ID}`)+ )const second = await pairFully(h)- const secondSession = h.server.getSession(`chromium:${OFFICIAL_ID}`)+ const secondSession = h.server.getSession(+ installationSessionKey(`chrome-extension://${OFFICIAL_ID}`)+ )expect(second.credential.credentialId).not.toBe(first.credential.credentialId@@ -1250,7 +1586,11 @@ describe('R3 adoption boundary', () => {first.wire.ws.close()await first.wire.closedawait new Promise((r) => setTimeout(r, 20))- expect(h.server.getSession(`chromium:${OFFICIAL_ID}`)).toBe(secondSession)+ expect(+ h.server.getSession(+ installationSessionKey(`chrome-extension://${OFFICIAL_ID}`)+ )+ ).toBe(secondSession)const secondConn = mdxpOverChannel(second.wire, second.channel)const pong = await secondConn.sendRequest('system/ping', { sentAt: 5 })@@ -1265,14 +1605,22 @@ describe('R3 adoption boundary', () => {const paired = await pairFully(h)const conn = mdxpOverChannel(paired.wire, paired.channel)await conn.sendRequest('motrix/initialize', initializeParams(OFFICIAL_ID))- expect(h.server.getSession(`chromium:${OFFICIAL_ID}`)).toBeDefined()+ expect(+ h.server.getSession(+ installationSessionKey(`chrome-extension://${OFFICIAL_ID}`)+ )+ ).toBeDefined()conn.dispose()paired.wire.ws.close()await paired.wire.closedawait new Promise((r) => setTimeout(r, 20))- expect(h.server.getSession(`chromium:${OFFICIAL_ID}`)).toBeUndefined()+ expect(+ h.server.getSession(+ installationSessionKey(`chrome-extension://${OFFICIAL_ID}`)+ )+ ).toBeUndefined()})it('keys a Firefox session by its moz-extension UUID, not the claimed id', async () => {@@ -1289,7 +1637,9 @@ describe('R3 adoption boundary', () => {initializeParams('[email protected]', 'firefox'))- expect(h.server.getSession(`firefox:${FIREFOX_UUID}`)).toBeDefined()+ expect(+ h.server.getSession(installationSessionKey(FIREFOX_ORIGIN, 'firefox'))+ ).toBeDefined()expect(h.server.getSession('firefox:[email protected]')).toBeUndefined()conn.dispose()@@ -1603,7 +1953,11 @@ describe('§8 reconnect over the wire', () => {)expect(result.server.name).toBe('motrix')- expect(h.server.getSession(`chromium:${OFFICIAL_ID}`)).toBeDefined()+ expect(+ h.server.getSession(+ installationSessionKey(`chrome-extension://${OFFICIAL_ID}`)+ )+ ).toBeDefined()expect(h.authenticated.map(({ credentialId }) => credentialId)).toEqual([paired.credential.credentialId,paired.credential.credentialId,@@ -1643,7 +1997,11 @@ describe('§8 reconnect over the wire', () => {})await expect(revoke).resolves.toBe(1)await expect(paired.wire.closed).resolves.toMatchObject({ code: 1000 })- expect(h.server.getSession(`chromium:${OFFICIAL_ID}`)).toBeUndefined()+ expect(+ h.server.getSession(+ installationSessionKey(`chrome-extension://${OFFICIAL_ID}`)+ )+ ).toBeUndefined()await expect(reconnect({port: h.port,@@ -1854,7 +2212,11 @@ describe('§8 reconnect over the wire', () => {await Promise.resolve()await Promise.resolve()expect(h.authenticated).toHaveLength(0)- expect(h.server.getSession(`chromium:${OFFICIAL_ID}`)).toBeUndefined()+ expect(+ h.server.getSession(+ installationSessionKey(`chrome-extension://${OFFICIAL_ID}`)+ )+ ).toBeUndefined()const credential = delayedCredential.valueif (credential === undefined) {diff --git a/src/core/bridge/__tests__/web-socket-bridge-server.test.ts b/src/core/bridge/__tests__/web-socket-bridge-server.test.tsindex aff15368..eb654fd8 100644--- a/src/core/bridge/__tests__/web-socket-bridge-server.test.ts+++ b/src/core/bridge/__tests__/web-socket-bridge-server.test.ts@@ -42,6 +42,7 @@ import {} from './fakes'import {initializeParams,+ installationSessionKey,mdxpOverChannel,pairAndExchange,} from './mbp1-client'@@ -640,7 +641,7 @@ class FakeExtensionSocket extends EventEmitter {describe('WebSocketBridgeServer.adoptAuthenticatedSession — envelope fault close codes', () => {let server: WebSocketBridgeServerconst KEY = new Uint8Array(32).fill(3)- const CREDENTIAL_ID = 'credential-used-by-this-transport'+ let credentialId: stringconst IDENTITY = {kind: 'extension' as const,browser: 'chromium' as const,@@ -653,6 +654,17 @@ describe('WebSocketBridgeServer.adoptAuthenticatedSession — envelope fault clobeforeEach(async () => {authenticated = []+ const wiring = await makeMbp1TestWiring([['chromium', EXTENSION_ID]])+ const offered = await wiring.options.credentials.offerProvisional(+ {+ browser: 'chromium',+ verifiedOrigin: ORIGIN,+ clientInstallationId: 'install-1',+ },+ 'official'+ )+ credentialId = offered.credentialId+ await wiring.options.credentials.commitFromPair(credentialId)server = new WebSocketBridgeServer({pairing: makeStatefulFakePairing(),registry: makeFakeRegistry(),@@ -660,6 +672,7 @@ describe('WebSocketBridgeServer.adoptAuthenticatedSession — envelope fault cloruntime: 'electron',ffmpegAvailable: true,localToken: 'test-token',+ ...wiring.options,onExtensionAuthenticated: (identity, credentialId) => {authenticated.push({ identity, credentialId })},@@ -682,7 +695,7 @@ describe('WebSocketBridgeServer.adoptAuthenticatedSession — envelope fault clo// EnvelopeLimitError before it even looks at the frame's contents.opener: new EnvelopeOpener(KEY, DIR_C2S, MAX_ENVELOPE_FRAMES),},- CREDENTIAL_ID+ credentialId)ws.emit('message', Buffer.alloc(8 + 16), true)@@ -699,7 +712,7 @@ describe('WebSocketBridgeServer.adoptAuthenticatedSession — envelope fault closealer: new EnvelopeSealer(KEY, DIR_S2C),opener: new EnvelopeOpener(KEY, DIR_C2S),},- CREDENTIAL_ID+ credentialId)// §10: a text frame after channel activation is a protocol violation.@@ -721,9 +734,11 @@ describe('WebSocketBridgeServer.adoptAuthenticatedSession — envelope fault closealer: new EnvelopeSealer(KEY, DIR_S2C, MAX_ENVELOPE_FRAMES),opener: new EnvelopeOpener(KEY, DIR_C2S),},- CREDENTIAL_ID+ credentialId+ )+ const session = server.getSession(+ installationSessionKey(`chrome-extension://${EXTENSION_ID}`))- const session = server.getSession(`chromium:${EXTENSION_ID}`)if (!session) throw new Error('session was not registered')expect(() => session.envelope.send('{"jsonrpc":"2.0"}')).toThrow(@@ -745,9 +760,11 @@ describe('WebSocketBridgeServer.adoptAuthenticatedSession — envelope fault closealer: new EnvelopeSealer(KEY, DIR_S2C),opener: new EnvelopeOpener(KEY, DIR_C2S),},- CREDENTIAL_ID+ credentialId+ )+ const session = server.getSession(+ installationSessionKey(`chrome-extension://${EXTENSION_ID}`))- const session = server.getSession(`chromium:${EXTENSION_ID}`)if (!session) throw new Error('session was not registered')expect(() =>@@ -769,11 +786,11 @@ describe('WebSocketBridgeServer.adoptAuthenticatedSession — envelope fault closealer: new EnvelopeSealer(KEY, DIR_S2C),opener: new EnvelopeOpener(KEY, DIR_C2S),},- CREDENTIAL_ID+ credentialId)expect(authenticated).toEqual([- { identity: IDENTITY, credentialId: CREDENTIAL_ID },+ { identity: IDENTITY, credentialId: credentialId },])})})diff --git a/src/core/bridge/bridge-connection.ts b/src/core/bridge/bridge-connection.tsindex f94f382c..9bda8076 100644--- a/src/core/bridge/bridge-connection.ts+++ b/src/core/bridge/bridge-connection.ts@@ -18,7 +18,7 @@ import {export type { Browser } from '@shared/protocol/bridge'export interface BridgeSessionMeta {- /** `${browser}:${extensionId}`, used as the session map key. */+ /** Stable authenticated installation key, also used for task notifications. */sessionKey: stringextensionId: stringbrowser: Browserdiff --git a/src/core/bridge/credential-store.ts b/src/core/bridge/credential-store.tsindex 0e04b6c8..aa362f07 100644--- a/src/core/bridge/credential-store.ts+++ b/src/core/bridge/credential-store.ts@@ -853,7 +853,7 @@ function freezeCredential(credential: StoredCredential): StoredCredential {})}-function transportIdentityForPrincipal(principal: CredentialPrincipal): {+export function transportIdentityForPrincipal(principal: CredentialPrincipal): {browser: BrowserextensionId: string} | null {diff --git a/src/core/bridge/mdxp-session-context.ts b/src/core/bridge/mdxp-session-context.tsindex 02685c7e..c87c80f7 100644--- a/src/core/bridge/mdxp-session-context.ts+++ b/src/core/bridge/mdxp-session-context.ts@@ -14,6 +14,8 @@ import type { PairRequestArgs } from './web-socket-bridge-server'export interface MdxpSessionContext {/** Who the peer is. Spec 1 only ever produces the `extension` kind. */readonly identity: ClientIdentity+ /** Authenticated installation routing key; absent for unary CLI contexts. */+ readonly sessionKey?: stringreadonly startedAt: numberisReady(): booleanmarkReady(): void@@ -57,6 +59,7 @@ export function contextFromConnection(browser: conn.session.browser,extensionId: conn.session.extensionId,},+ sessionKey: conn.sessionKey,startedAt: conn.session.startedAt,isReady: () => conn.isReady(),markReady: () => conn.markReady(),diff --git a/src/core/bridge/web-socket-bridge-server.ts b/src/core/bridge/web-socket-bridge-server.tsindex f5e8e7af..7eddb954 100644--- a/src/core/bridge/web-socket-bridge-server.ts+++ b/src/core/bridge/web-socket-bridge-server.ts@@ -24,6 +24,7 @@ import {type ClientIdentity,clientKey,EXTENSION_ORIGIN_SCHEMES,+ type ExtensionInstallationInfo,isBridgeBrowser,isSafariExtensionOrigin,makeSessionKey,@@ -31,7 +32,11 @@ import {} from '@shared/protocol/bridge'import { type RawData, type WebSocket, WebSocketServer } from 'ws'import { BridgeConnection } from './bridge-connection'-import type { Mbp1CredentialStore } from './credential-store'+import {+ type Mbp1CredentialStore,+ principalKey,+ transportIdentityForPrincipal,+} from './credential-store'import type { DeviceCodeService } from './device-code-service'import { createInitializeHandler } from './handlers/initialize-handler'import {@@ -174,6 +179,8 @@ export interface BridgeServerOptions {/** The exact credential that authenticated this transport. */credentialId: string) => void+ /** Invalidate installation connection status after readiness or disconnect. */+ onExtensionSessionsChanged?: () => void}export interface ExtensionMbp1RouteRequest {@@ -1029,6 +1036,7 @@ export class WebSocketBridgeServer {session.conn.dispose()}this.sessions.clear()+ this.notifyExtensionSessionsChanged()// End open SSE streams first — otherwise http.close() hangs waiting for the// keep-alive connections to drain.for (const [res, { heartbeat }] of this.sseClients) {@@ -1240,11 +1248,61 @@ export class WebSocketBridgeServer {}}- /** Find an active session by `${browser}:${extensionId}` key. */+ /** Exact installation routing key; legacy extension-wide keys never select a peer. */getSession(sessionKey: string): BridgeSession | undefined {return this.sessions.get(sessionKey)}+ /** Older task metadata identifies an extension, but not its installation.+ * Deliver those notifications to all ready profiles of that extension. A+ * modern installation key remains exact even when its peer is offline. */+ getTaskNotificationSessions(sessionKey: string): BridgeSession[] {+ const exact = this.sessions.get(sessionKey)+ const candidates = exact ? [exact] : this.sessionsForExtension(sessionKey)+ return candidates.filter(+ ({ conn }) => conn.isAuthorized() && conn.isReady()+ )+ }++ /** Public installation summaries contain no credential IDs or key material. */+ getExtensionInstallations(+ identity: ClientIdentity & { kind: 'extension' }+ ): ExtensionInstallationInfo[] {+ return (this.mbp1?.credentials.listCommitted() ?? [])+ .filter((credential) => {+ const transport = transportIdentityForPrincipal(credential.principal)+ return (+ transport?.browser === identity.browser &&+ transport.extensionId === identity.extensionId+ )+ })+ .map((credential) => {+ const id = principalKey(credential.principal)+ const conn = this.sessions.get(id)?.conn+ return {+ id,+ pairedAt: credential.createdAt,+ connected: conn?.isAuthorized() === true && conn.isReady(),+ }+ })+ .sort((a, b) => a.id.localeCompare(b.id))+ }++ private notifyExtensionSessionsChanged(): void {+ try {+ this.opts.onExtensionSessionsChanged?.()+ } catch {+ // Presentation invalidation must never interrupt transport teardown.+ }+ }++ private sessionsForExtension(extensionKey: string): BridgeSession[] {+ return [...this.sessions.values()].filter(+ (session) =>+ makeSessionKey(session.browser, session.extensionId) === extensionKey+ )+ }+/*** Enter the verified-identity revoke gate synchronously. This method performs* every in-memory authorization cutoff before returning: live MDXP is marked@@ -1268,8 +1326,11 @@ export class WebSocketBridgeServer {// Repeat the cutoff even for a resumed attempt: a test double or future// transport must not be able to attach work between retry calls.- this.sessions.get(sessionKey)?.conn.revokeAuthorization()+ for (const session of this.sessionsForExtension(sessionKey)) {+ session.conn.revokeAuthorization()+ }this.cancelPreAuthForSessionKey(sessionKey)+ this.notifyExtensionSessionsChanged()if (existing !== undefined) return existingconst lease = { identity: normalized } as ExtensionRevocationLease@@ -1452,41 +1513,40 @@ export class WebSocketBridgeServer {reason: string): Promise<void> {const sessionKey = makeSessionKey(identity.browser, identity.extensionId)- const notified = this.sessions.get(sessionKey)- if (!notified) return-- notified.conn.revokeAuthorization()+ const notified = this.sessionsForExtension(sessionKey)+ if (notified.length === 0) return- try {- notified.conn.sendNotification(Notifications.PairRevoked, { reason })- } catch {- // A broken writer is already equivalent to a disconnected peer; the- // authorization cutoff below must still run.+ for (const session of notified) {+ session.conn.revokeAuthorization()+ try {+ session.conn.sendNotification(Notifications.PairRevoked, { reason })+ } catch {+ // A broken writer must not prevent revoking its sibling installations.+ }}await new Promise((resolve) =>setTimeout(resolve, REVOKE_NOTIFICATION_GRACE_MS))- // Authentication can replace a map entry while the final notification is- // draining. Close both the notified record and whichever matching record- // is current so revocation cannot lose that race.- const current = this.sessions.get(sessionKey)- const targets =- current && current !== notified ? [notified, current] : [notified]+ // Include any current records as well as the notification recipients.+ const targets = new Set([+ ...notified,+ ...this.sessionsForExtension(sessionKey),+ ])for (const target of targets) {- if (this.sessions.get(sessionKey) === target) {- this.sessions.delete(sessionKey)+ if (this.sessions.get(target.conn.sessionKey) === target) {+ this.sessions.delete(target.conn.sessionKey)}this.closeSessionTransport(target)}}- private closeExtensionSessionNow(sessionKey: string): void {- const session = this.sessions.get(sessionKey)- if (!session) return- session.conn.revokeAuthorization()- this.sessions.delete(sessionKey)- this.closeSessionTransport(session)+ private closeExtensionSessionNow(extensionKey: string): void {+ for (const session of this.sessionsForExtension(extensionKey)) {+ session.conn.revokeAuthorization()+ this.sessions.delete(session.conn.sessionKey)+ this.closeSessionTransport(session)+ }}private closeSessionTransport(session: BridgeSession): void {@@ -2083,9 +2143,21 @@ export class WebSocketBridgeServer {channel: EnvelopeChannel,credentialId: string): void {- // Byte-identical to `clientKey(identity)`, which the SSE revoke matcher- // and `getSession` both rely on.- const sessionKey = makeSessionKey(identity.browser, identity.extensionId)+ // Only the authenticated, committed credential can supply the installation+ // identity. A client-provided initialize field must never select a session.+ const credential = this.mbp1?.credentials.findForAuth(credentialId)+ const transport =+ credential && transportIdentityForPrincipal(credential.principal)+ if (+ credential?.state !== 'committed' ||+ transport?.browser !== identity.browser ||+ transport.extensionId !== identity.extensionId+ ) {+ ws.close()+ return+ }+ const sessionKey = principalKey(credential.principal)+ const extensionKey = makeSessionKey(identity.browser, identity.extensionId)const startedAt = Date.now()// The handed-over endpoints, never fresh ones: their sequence counters// continue from the handshake (`/pair` has already sealed@@ -2108,7 +2180,7 @@ export class WebSocketBridgeServer {// MBP1 authenticated the transport below MDXP, so the session is// authorized on arrival. No handler grants this any more.conn.markAuthorized()- if (this.revokingExtensionKeys.has(sessionKey)) {+ if (this.revokingExtensionKeys.has(extensionKey)) {conn.revokeAuthorization()this.closeSessionTransport({conn,@@ -2134,14 +2206,19 @@ export class WebSocketBridgeServer {// just by opening a socket (§4).const existing = this.sessions.get(sessionKey)this.sessions.set(sessionKey, session)- existing?.conn.dispose()+ if (existing) {+ existing.conn.revokeAuthorization()+ this.closeSessionTransport(existing)+ }ws.on('close', () => {// Only ever remove OUR OWN entry: the replaced socket's imminent close// must not delete the replacement that just took its key.if (this.sessions.get(sessionKey) === session) {this.sessions.delete(sessionKey)+ this.notifyExtensionSessionsChanged()}+ conn.revokeAuthorization()conn.dispose()})@@ -2264,7 +2341,9 @@ export class WebSocketBridgeServer {recvAt: Date.now(),}))conn.onNotification('motrix/initialized', () => {+ if (!conn.isAuthorized()) returnconn.markReady()+ this.notifyExtensionSessionsChanged()})}diff --git a/src/main/bridge/bootstrap-lifecycle.test.ts b/src/main/bridge/bootstrap-lifecycle.test.tsindex 69de685d..4e8f6976 100644--- a/src/main/bridge/bootstrap-lifecycle.test.ts+++ b/src/main/bridge/bootstrap-lifecycle.test.ts@@ -20,6 +20,7 @@ import { BridgeReceiver } from '@core/bridge-receiver/bridge-receiver'import { BridgeStreamSource } from '@core/bridge-receiver/bridge-stream-source'import { CompletionShutdownController } from '@core/task/completion-shutdown-controller'import * as taskCreation from '@core/task/create-task-handler'+import { Notifications } from '@motrix/mdxp'import {BridgeCommands,BridgeQueries,@@ -346,6 +347,46 @@ describe('desktop bridge bootstrap ownership', () => {}})+ it('delivers every task lifecycle event once to each eligible profile', async () => {+ const runtime = await bootstrapBridge(args())+ if (!runtime) throw new Error('bridge did not start')+ const recipients = [vi.fn(), vi.fn()]+ vi.spyOn(runtime.server, 'getTaskNotificationSessions').mockReturnValue(+ recipients.map((sendNotification) => ({+ conn: { sendNotification },+ })) as never+ )+ try {+ const sessionKey = 'chromium:legacy-extension'+ const progress = {+ taskId: 'old-task',+ bytesDone: 1,+ bytesTotal: 2,+ speedBps: 1,+ etaSec: 1,+ phase: 'downloading' as const,+ }+ const completed = {+ taskId: 'old-task',+ filePath: '/downloads/file.bin',+ durationMs: 1,+ }+ const failed = { taskId: 'old-task', code: 'disk-full', message: 'full' }+ runtime.bus.emitTaskProgress({ sessionKey, params: progress })+ runtime.bus.emitTaskCompleted({ sessionKey, params: completed })+ runtime.bus.emitTaskError({ sessionKey, params: failed })+ for (const recipient of recipients) {+ expect(recipient.mock.calls).toEqual([+ [Notifications.TaskProgress, progress],+ [Notifications.TaskCompleted, completed],+ [Notifications.TaskError, failed],+ ])+ }+ } finally {+ await runtime.shutdown()+ }+ })+it('acquires the data-root lock before the first bridge store load', async () => {const lockPath = join(userDataDir, 'bridge', BRIDGE_DATA_DIR_LOCK_FILE_NAME)const load = vi.spyOn(PairingService.prototype, 'load')@@ -1104,6 +1145,7 @@ describe('desktop bridge bootstrap ownership', () => {// Inject a live session the way `adoptAuthenticatedSession` would,// so the revoke-kick has something to find and close.const conn = {+ sessionKey: 'chromium:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',sendNotification: vi.fn(),revokeAuthorization: vi.fn(),dispose: vi.fn(),@@ -1178,6 +1220,7 @@ describe('desktop bridge bootstrap ownership', () => {runtime.bus.on('Paired', paired)runtime.bus.on('Error', errors)const conn = {+ sessionKey: 'chromium:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',revokeAuthorization: vi.fn(),dispose: vi.fn(),}@@ -1271,6 +1314,7 @@ describe('desktop bridge bootstrap ownership', () => {await commitAndProjectExtension(runtime)const conn = {+ sessionKey: 'chromium:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',revokeAuthorization: vi.fn(),dispose: vi.fn(),}diff --git a/src/main/bridge/index.ts b/src/main/bridge/index.tsindex b365c1ac..c1a28e92 100644--- a/src/main/bridge/index.ts+++ b/src/main/bridge/index.ts@@ -718,6 +718,8 @@ export async function bootstrapBridge(args: {queueMbp1Dialog: (req) => dialog.queueMbp1Prompt(req),canAdmitExtensionIdentity: (identity) =>extensionPairings.canAdmitIdentity(identity),+ onExtensionSessionsChanged: () =>+ forwardToRenderer(BridgeEvents.ExtensionSessionsChanged, {}),// The only remaining signal that an extension became usable now that// `motrix/initialize` mints nothing (R18-10): refresh the extension// management projection from the authoritative MBP1 credential set, then@@ -813,16 +815,19 @@ export async function bootstrapBridge(args: {)bus.on('TaskProgress', ({ sessionKey, params }) => {- const session = server.getSession(sessionKey)- session?.conn.sendNotification(Notifications.TaskProgress, params)+ for (const session of server.getTaskNotificationSessions(sessionKey)) {+ session.conn.sendNotification(Notifications.TaskProgress, params)+ }})bus.on('TaskCompleted', ({ sessionKey, params }) => {- const session = server.getSession(sessionKey)- session?.conn.sendNotification(Notifications.TaskCompleted, params)+ for (const session of server.getTaskNotificationSessions(sessionKey)) {+ session.conn.sendNotification(Notifications.TaskCompleted, params)+ }})bus.on('TaskError', ({ sessionKey, params }) => {- const session = server.getSession(sessionKey)- session?.conn.sendNotification(Notifications.TaskError, params)+ for (const session of server.getTaskNotificationSessions(sessionKey)) {+ session.conn.sendNotification(Notifications.TaskError, params)+ }})// Spec 5 — global SSE firehose. BridgeStreamSource subscribes the core@@ -925,7 +930,10 @@ export async function bootstrapBridge(args: {}installIpcHandler(BridgeQueries.ListPaired, () => [- ...extensionPairings.list().map(toPairedClientInfo),+ ...extensionPairings.list().map((entry) => ({+ ...toPairedClientInfo(entry),+ installations: server.getExtensionInstallations(entry.identity),+ })),...pairing.listPaired().filter((entry) => entry.identity.kind === 'cli')diff --git a/src/renderer/routes/settings/cards/integration/browser-extensions-section.test.tsx b/src/renderer/routes/settings/cards/integration/browser-extensions-section.test.tsxnew file mode 100644index 00000000..c0175ffa--- /dev/null+++ b/src/renderer/routes/settings/cards/integration/browser-extensions-section.test.tsx@@ -0,0 +1,137 @@+import '@testing-library/jest-dom/vitest'+import { i18n } from '@renderer/lib/i18n'+import { transport } from '@renderer/lib/transport'+import {+ BridgeCommands,+ BridgeEvents,+ BridgeQueries,+ type PairedClientInfo,+} from '@shared/protocol/bridge'+import {+ act,+ fireEvent,+ render,+ screen,+ waitFor,+ within,+} from '@testing-library/react'+import { FormProvider, useForm } from 'react-hook-form'+import { beforeEach, describe, expect, it, vi } from 'vitest'+import { BrowserExtensionsSection } from './browser-extensions-section'+import type { IntegrationFormValues } from './integration-dialog'++vi.mock('@renderer/lib/transport', () => ({+ transport: {+ invoke: vi.fn(),+ on: vi.fn(),+ off: vi.fn(),+ onConnectionChange: vi.fn(() => () => {}),+ },+}))+vi.mock('@renderer/hooks/use-portable-mode', () => ({+ usePortableMode: () => false,+}))+vi.mock('./browser-extension-installs', () => ({+ BrowserExtensionInstalls: () => null,+}))+vi.mock('./trusted-extensions-section', () => ({+ TrustedExtensionsSection: () => null,+}))++function Wrapper() {+ const form = useForm<IntegrationFormValues>({+ defaultValues: { app: { browserBridgeEnabled: true } },+ })+ return (+ <FormProvider {...form}>+ <BrowserExtensionsSection />+ </FormProvider>+ )+}++describe('browser extension installations', () => {+ let paired: PairedClientInfo[]+ const listeners = new Map<string, () => void>()+ beforeEach(async () => {+ await i18n.changeLanguage('en-US')+ listeners.clear()+ vi.clearAllMocks()+ paired = [+ {+ kind: 'extension',+ browser: 'chromium',+ id: 'same-extension',+ name: '',+ pairedAt: 1,+ lastActiveAt: 2,+ identityTrust: 'official',+ status: 'ready',+ installations: [+ { id: 'installation-a', pairedAt: 1, connected: true },+ { id: 'installation-b', pairedAt: 2, connected: true },+ ],+ },+ ]+ vi.mocked(transport.on).mockImplementation((event, listener) => {+ listeners.set(event, listener)+ })+ vi.mocked(transport.off).mockImplementation((event) => {+ listeners.delete(event)+ })+ vi.mocked(transport.invoke).mockImplementation(async (channel) => {+ if (String(channel) === BridgeQueries.ListPaired)+ return structuredClone(paired)+ if (String(channel) === BridgeCommands.RevokePair) {+ paired = []+ return undefined+ }+ return null+ })+ })++ it('shows both profiles, refreshes disconnect status, and revokes the entire extension group', async () => {+ render(<Wrapper />)+ expect(await screen.findByText('Browser profile 1')).toBeVisible()+ expect(screen.getByText('Browser profile 2')).toBeVisible()+ expect(screen.getAllByText('Connected')).toHaveLength(2)+ const first = paired[0]+ if (first?.kind !== 'extension' || !first.installations)+ throw new Error('fixture missing')+ first.installations[0].connected = false+ act(() => listeners.get(BridgeEvents.ExtensionSessionsChanged)?.())+ await waitFor(() => {+ expect(+ within(screen.getByText('Browser profile 1').closest('li')!).getByText(+ 'Not connected'+ )+ ).toBeVisible()+ expect(+ within(screen.getByText('Browser profile 2').closest('li')!).getByText(+ 'Connected'+ )+ ).toBeVisible()+ })+ fireEvent.click(screen.getByRole('button', { name: 'Disconnect all' }))+ await waitFor(() =>+ expect(transport.invoke).toHaveBeenCalledWith(BridgeCommands.RevokePair, {+ identity: {+ kind: 'extension',+ browser: 'chromium',+ extensionId: 'same-extension',+ },+ })+ )+ await waitFor(() =>+ expect(screen.queryByText('Browser profile 1')).not.toBeInTheDocument()+ )+ })++ it('still renders paired entries supplied by an older backend without installation summaries', async () => {+ const first = paired[0]+ if (first?.kind !== 'extension') throw new Error('fixture missing')+ delete first.installations+ render(<Wrapper />)+ expect(await screen.findByText('same-extension')).toBeVisible()+ expect(screen.getByRole('button', { name: /^Disconnect$/ })).toBeEnabled()+ })+})diff --git a/src/renderer/routes/settings/cards/integration/browser-extensions-section.tsx b/src/renderer/routes/settings/cards/integration/browser-extensions-section.tsxindex d8c48275..236e7212 100644--- a/src/renderer/routes/settings/cards/integration/browser-extensions-section.tsx+++ b/src/renderer/routes/settings/cards/integration/browser-extensions-section.tsx@@ -108,7 +108,13 @@ export function BrowserExtensionsSection() {<div className="text-xs font-medium text-foreground">{t('settings.integration.browser.pairedTitle')}{' '}<span className="text-muted-foreground">- ({pairedExtensions.length})+ (+ {pairedExtensions.reduce(+ (count, item) =>+ count + Math.max(item.installations?.length ?? 1, 1),+ 0+ )}+ )</span></div>{pairedExtensions.length === 0 ? (@@ -119,37 +125,64 @@ export function BrowserExtensionsSection() {pairedExtensions.map((it) => (<divkey={`${it.browser}:${it.id}`}- className="flex items-center justify-between rounded border border-border px-3 py-2 text-xs"+ className="rounded border border-border px-3 py-2 text-xs">- <div className="flex flex-col gap-0.5">- <span className="font-mono">{it.name || it.id}</span>- <span className="text-muted-foreground">- {browserDisplayName(it.browser)}- {` · ${t(IDENTITY_LABEL_KEYS[it.identityTrust])}`}- {it.lastActiveAt- ? ` · ${t('settings.integration.browser.lastActive')}: ${new Date(it.lastActiveAt).toLocaleString()}`- : ''}- </span>+ <div className="flex items-center justify-between gap-3">+ <div className="flex flex-col gap-0.5">+ <span className="font-mono">{it.name || it.id}</span>+ <span className="text-muted-foreground">+ {browserDisplayName(it.browser)}+ {` · ${t(IDENTITY_LABEL_KEYS[it.identityTrust])}`}+ {it.lastActiveAt+ ? ` · ${t('settings.integration.browser.lastActive')}: ${new Date(it.lastActiveAt).toLocaleString()}`+ : ''}+ </span>+ </div>+ <Button+ type="button"+ size="xs"+ variant="outline"+ onClick={() =>+ void revoke({+ kind: 'extension',+ browser: it.browser,+ extensionId: it.id,+ })+ }+ disabled={it.status === 'cleanup-pending'}+ >+ {t(+ it.status === 'cleanup-pending'+ ? 'settings.integration.browser.disconnecting'+ : (it.installations?.length ?? 0) > 1+ ? 'settings.integration.browser.revokeAll'+ : 'settings.integration.browser.revoke'+ )}+ </Button></div>- <Button- type="button"- size="xs"- variant="outline"- onClick={() =>- void revoke({- kind: 'extension',- browser: it.browser,- extensionId: it.id,- })- }- disabled={it.status === 'cleanup-pending'}- >- {t(- it.status === 'cleanup-pending'- ? 'settings.integration.browser.disconnecting'- : 'settings.integration.browser.revoke'- )}- </Button>+ {it.installations && it.installations.length > 0 && (+ <ul className="mt-2 space-y-1 border-t border-border pt-2">+ {it.installations.map((installation, index) => (+ <li+ key={installation.id}+ className="flex items-center justify-between gap-3"+ >+ <span>+ {t('settings.integration.browser.profile', {+ number: index + 1,+ })}+ </span>+ <span className="text-muted-foreground">+ {t(+ installation.connected+ ? 'settings.integration.browser.connected'+ : 'settings.integration.browser.disconnected'+ )}+ </span>+ </li>+ ))}+ </ul>+ )}</div>)))}diff --git a/src/renderer/routes/settings/cards/integration/use-bridge.ts b/src/renderer/routes/settings/cards/integration/use-bridge.tsindex 1bfa0d36..ad252b91 100644--- a/src/renderer/routes/settings/cards/integration/use-bridge.ts+++ b/src/renderer/routes/settings/cards/integration/use-bridge.ts@@ -30,27 +30,19 @@ import { resolvePairWithFeedback } from './pair-resolve'export function usePairedExtensions() {const [items, setItems] = useState<PairedClientInfo[]>([])- const refresh = useCallback(async () => {- const list = await transport.invoke(- BridgeQueries.ListPaired as unknown as QueryChannel- )- setItems(list as PairedClientInfo[])- }, [])-- useEffect(() => {- void refresh()- const onChange = () => {- void refresh()- }- const paired = BridgeEvents.Paired as unknown as EventChannel- const revoked = BridgeEvents.Revoked as unknown as EventChannel- transport.on(paired, onChange)- transport.on(revoked, onChange)- return () => {- transport.off(paired, onChange)- transport.off(revoked, onChange)- }- }, [refresh])+ const { refresh } = useTransportMirror({+ events: [+ BridgeEvents.Paired,+ BridgeEvents.Revoked,+ BridgeEvents.ExtensionSessionsChanged,+ ] as unknown as EventChannel[],+ load: async (stale, read) => {+ const list = await read(+ BridgeQueries.ListPaired as unknown as QueryChannel+ )+ if (!stale()) setItems(list as PairedClientInfo[])+ },+ })const revoke = useCallback(async (identity: ClientIdentity) => {diff --git a/src/server/bridge/bootstrap.test.ts b/src/server/bridge/bootstrap.test.tsindex a826e120..26920baf 100644--- a/src/server/bridge/bootstrap.test.ts+++ b/src/server/bridge/bootstrap.test.ts@@ -26,7 +26,11 @@ import { BridgeStreamSource } from '@core/bridge-receiver/bridge-stream-source'import { EventBus } from '@core/events/event-bus'import { SettingsManager } from '@core/settings/settings-manager'import { Methods, Notifications } from '@motrix/mdxp'-import { BridgeEvents, BridgeQueries } from '@shared/protocol/bridge'+import {+ BridgeEvents,+ BridgeQueries,+ type PairedClientInfo,+} from '@shared/protocol/bridge'import { Events } from '@shared/protocol/events'import { EngineState } from '@shared/types/engine'import { TaskStatus } from '@shared/types/task'@@ -36,6 +40,7 @@ import {} from '@test-utils/bridge-receiver'import { makeDownloadTask } from '@test-utils/task'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import WebSocket from 'ws'import { createApp } from '../http/app'import { OperatorAdminExitCode, runOperatorAdmin } from '../operator-admin'import {@@ -459,6 +464,163 @@ describe('bootstrapBridgeForServer', () => {}})+ it('broadcasts profile readiness, disconnect, and reconnect to an authenticated Web UI socket', async () => {+ const eventBus = new EventBus()+ const remoteExtensionConfig = parseRemoteExtensionConfig({+ MOTRIX_REMOTE_EXTENSION_ENABLED: 'true',+ MOTRIX_REMOTE_EXTENSION_PUBLIC_URL: 'ws://motrix.example/bridge',+ MOTRIX_PUBLIC_URL: 'https://motrix.example',+ })+ runtime = await bootstrapBridgeForServer({+ userDataDir,+ host: '127.0.0.1',+ port: 0,+ motrixVersion: '2.0',+ eventBus,+ readHandlerDeps: readDeps(),+ writeHandlerDeps: writeDeps(),+ remoteExtensionConfig,+ createExtensionReceiver: extensionReceiver,+ })+ const bridge = runtime+ const token = 'web-event-test-operator'+ const app = await createApp({+ eventBus,+ remoteExtensionConfig,+ operatorAuth: { operatorToken: token },+ bridgeQueryHandlers: bridge.bridgeQueryHandlers,+ })+ const closeExtensions: Array<() => void> = []+ let webSocket: WebSocket | undefined+ try {+ const base = await app.listen({ host: '127.0.0.1', port: 0 })+ const login = await fetch(`${base}/rpc/auth/login`, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ token }),+ })+ expect(login.status).toBe(200)+ const cookie = login.headers.get('set-cookie')!.split(';')[0]+ const readInstallations = async () => {+ const response = await fetch(+ `${base}/rpc/query/${encodeURIComponent(BridgeQueries.ListPaired)}`,+ {+ method: 'POST',+ headers: {+ 'content-type': 'application/json',+ cookie,+ origin: base,+ },+ body: JSON.stringify({ args: [] }),+ }+ )+ expect(response.status).toBe(200)+ const paired = (await response.json()) as PairedClientInfo[]+ return paired.flatMap((client) =>+ client.kind === 'extension' ? (client.installations ?? []) : []+ )+ }+ webSocket = new WebSocket(`${base.replace('http:', 'ws:')}/rpc/events`, {+ headers: { cookie, origin: base },+ })+ const changes: unknown[][] = []+ webSocket.on('message', (data) => {+ const frame = JSON.parse(String(data)) as {+ channel: string+ args: unknown[]+ }+ if (frame.channel === BridgeEvents.ExtensionSessionsChanged) {+ changes.push(frame.args)+ }+ })+ await new Promise<void>((resolve, reject) => {+ webSocket!.once('open', resolve)+ webSocket!.once('error', reject)+ })++ const extensionId = 'a'.repeat(32)+ const origin = `chrome-extension://${extensionId}`+ const handshake = await startPair({+ port: bridge.port,+ origin,+ browser: 'chromium',+ claimedExtensionId: extensionId,+ routePrefix: '/bridge',+ hostHeader: 'motrix.example',+ })+ closeExtensions.push(() => handshake.wire.ws.terminate())+ const pending = (await bridge.bridgeQueryHandlers[+ BridgeQueries.ListPendingPairRequests+ ]()) as Array<{ code?: string }>+ const code = pending[0]?.code+ if (!code) throw new Error('pairing code missing')+ const { channel } = await runPake(handshake, code)+ const credential = await exchangeCredential(handshake, channel)+ const connection = mdxpOverChannel(handshake.wire, channel)+ closeExtensions.push(() => connection.dispose())+ await connection.sendRequest(+ Methods.MotrixInitialize,+ initializeParams(extensionId)+ )+ await vi.waitFor(async () =>+ expect(await readInstallations()).toEqual([+ expect.objectContaining({ connected: false }),+ ])+ )+ expect(changes).toEqual([])++ await connection.sendNotification(+ Notifications.MotrixInitialized,+ undefined+ )+ await vi.waitFor(() => expect(changes).toEqual([[{}]]))+ const ready = await readInstallations()+ expect(ready).toEqual([expect.objectContaining({ connected: true })])++ handshake.wire.ws.close()+ await handshake.wire.closed+ await vi.waitFor(() => expect(changes).toEqual([[{}], [{}]]))+ expect(await readInstallations()).toEqual([+ { ...ready[0], connected: false },+ ])++ const instanceId = (+ await readFile(+ join(userDataDir, 'bridge', 'server-instance-id'),+ 'utf8'+ )+ ).trim()+ const back = await reconnect({+ port: bridge.port,+ origin,+ instanceId,+ credential,+ routePrefix: '/bridge',+ hostHeader: 'motrix.example',+ })+ closeExtensions.push(() => back.wire.ws.terminate())+ const reconnected = mdxpOverChannel(back.wire, back.channel)+ closeExtensions.push(() => reconnected.dispose())+ await reconnected.sendRequest(+ Methods.MotrixInitialize,+ initializeParams(extensionId)+ )+ await reconnected.sendNotification(+ Notifications.MotrixInitialized,+ undefined+ )+ await vi.waitFor(() => expect(changes).toEqual([[{}], [{}], [{}]]))+ expect(await readInstallations()).toEqual(ready)+ } finally {+ try {+ webSocket?.terminate()+ await app.close()+ } finally {+ for (const close of closeExtensions.reverse()) close()+ }+ }+ })+it.each([true, false])('serves direct-LAN Extension routes across restart with operator URL=%s',async (withOperatorUrl) => {@@ -793,75 +955,82 @@ describe('bootstrapBridgeForServer', () => {).rejects.toMatchObject({ code: 'ENOENT' })})- it('routes Extension task lifecycle events only to their authenticated session', async () => {- const remoteExtensionConfig = parseRemoteExtensionConfig({- MOTRIX_REMOTE_EXTENSION_ENABLED: 'true',- MOTRIX_REMOTE_EXTENSION_PUBLIC_URL: 'wss://motrix.example/bridge',- MOTRIX_PUBLIC_URL: 'https://motrix.example',- })- const captured: { bridgeBus?: BridgeEventBus } = {}- const sendNotification = vi.fn()- vi.spyOn(WebSocketBridgeServer.prototype, 'getSession').mockImplementation(- (sessionKey) =>- sessionKey === 'chromium:target'- ? ({ conn: { sendNotification } } as never)- : undefined- )+ it.each([1, 2])(+ 'routes task lifecycle events once to each of %i eligible sessions',+ async (count) => {+ const remoteExtensionConfig = parseRemoteExtensionConfig({+ MOTRIX_REMOTE_EXTENSION_ENABLED: 'true',+ MOTRIX_REMOTE_EXTENSION_PUBLIC_URL: 'wss://motrix.example/bridge',+ MOTRIX_PUBLIC_URL: 'https://motrix.example',+ })+ const captured: { bridgeBus?: BridgeEventBus } = {}+ const recipients = Array.from({ length: count }, () => ({+ conn: { sendNotification: vi.fn() },+ }))+ vi.spyOn(+ WebSocketBridgeServer.prototype,+ 'getTaskNotificationSessions'+ ).mockImplementation((sessionKey) =>+ sessionKey === 'chromium:target' ? (recipients as never) : []+ )- runtime = await bootstrapBridgeForServer({- userDataDir,- host: '127.0.0.1',- port: 0,- motrixVersion: '2.0',- eventBus: { on: vi.fn(), off: vi.fn(), emit: vi.fn() },- readHandlerDeps: readDeps(),- writeHandlerDeps: writeDeps(),- remoteExtensionConfig,- createExtensionReceiver: (context) => {- captured.bridgeBus = context.bridgeBus- return extensionReceiver()- },- })- const bridgeBus = captured.bridgeBus- if (bridgeBus === undefined) throw new Error('bridge event bus missing')-- const progress = {- taskId: 'task-1',- bytesDone: 1,- bytesTotal: 2,- speedBps: 3,- etaSec: 4,- phase: 'downloading' as const,- }- bridgeBus.emitTaskProgress({- sessionKey: 'chromium:target',- params: progress,- })- const completed = {- taskId: 'task-1',- filePath: '/downloads/file.bin',- durationMs: 5,- }- bridgeBus.emitTaskCompleted({- sessionKey: 'chromium:target',- params: completed,- })- const failed = { taskId: 'task-2', code: 'disk-full', message: 'full' }- bridgeBus.emitTaskError({- sessionKey: 'chromium:target',- params: failed,- })- bridgeBus.emitTaskProgress({- sessionKey: 'chromium:other',- params: progress,- })+ runtime = await bootstrapBridgeForServer({+ userDataDir,+ host: '127.0.0.1',+ port: 0,+ motrixVersion: '2.0',+ eventBus: { on: vi.fn(), off: vi.fn(), emit: vi.fn() },+ readHandlerDeps: readDeps(),+ writeHandlerDeps: writeDeps(),+ remoteExtensionConfig,+ createExtensionReceiver: (context) => {+ captured.bridgeBus = context.bridgeBus+ return extensionReceiver()+ },+ })+ const bridgeBus = captured.bridgeBus+ if (bridgeBus === undefined) throw new Error('bridge event bus missing')++ const progress = {+ taskId: 'task-1',+ bytesDone: 1,+ bytesTotal: 2,+ speedBps: 3,+ etaSec: 4,+ phase: 'downloading' as const,+ }+ bridgeBus.emitTaskProgress({+ sessionKey: 'chromium:target',+ params: progress,+ })+ const completed = {+ taskId: 'task-1',+ filePath: '/downloads/file.bin',+ durationMs: 5,+ }+ bridgeBus.emitTaskCompleted({+ sessionKey: 'chromium:target',+ params: completed,+ })+ const failed = { taskId: 'task-2', code: 'disk-full', message: 'full' }+ bridgeBus.emitTaskError({+ sessionKey: 'chromium:target',+ params: failed,+ })+ bridgeBus.emitTaskProgress({+ sessionKey: 'chromium:other',+ params: progress,+ })- expect(sendNotification.mock.calls).toEqual([- [Notifications.TaskProgress, progress],- [Notifications.TaskCompleted, completed],- [Notifications.TaskError, failed],- ])- })+ for (const { conn } of recipients) {+ expect(conn.sendNotification.mock.calls).toEqual([+ [Notifications.TaskProgress, progress],+ [Notifications.TaskCompleted, completed],+ [Notifications.TaskError, failed],+ ])+ }+ }+ )it('device-code: request emits a web prompt, approve issues a token, listPaired shows the cli', async () => {const emit = vi.fn()diff --git a/src/server/bridge/bootstrap.ts b/src/server/bridge/bootstrap.tsindex 611b0c7d..9fb31cc1 100644--- a/src/server/bridge/bootstrap.ts+++ b/src/server/bridge/bootstrap.ts@@ -279,6 +279,8 @@ export async function bootstrapBridgeForServer(localToken,deviceCode,onPairRequested: (payload) => bridgeBus.emitPairRequested(payload),+ onExtensionSessionsChanged: () =>+ opts.eventBus.emit(BridgeEvents.ExtensionSessionsChanged, {}),verificationUri: opts.verificationUri,...(extensionMbp1 === null? {}@@ -371,8 +373,10 @@ export async function bootstrapBridgeForServer(}const bridgeQueryHandlers: Record<string, Handler> = {[BridgeQueries.ListPaired]: async () => [- ...(extensionMbp1?.extensionPairings.list().map(toPairedClientInfo) ??- []),+ ...(extensionMbp1?.extensionPairings.list().map((entry) => ({+ ...toPairedClientInfo(entry),+ installations: server.getExtensionInstallations(entry.identity),+ })) ?? []),...pairing.listPaired().map(toPairedClientInfo),],[BridgeQueries.ListPendingPairRequests]: async () => [@@ -433,25 +437,23 @@ export async function bootstrapBridgeForServer(const port = await server.start(opts.host, opts.port)boundPort = port- // Per-session Extension task lifecycle push. This mirrors the Desktop- // shell: BridgeReceiver publishes against the authenticated session key;- // the shell converts those events into encrypted MDXP notifications on- // that session only. The global SSE stream below remains a separate agent- // surface and must not substitute for this routing.+ // Match Desktop routing: modern tasks target their installation; legacy+ // extension-wide task keys reach every ready profile of that extension.+ // The global SSE stream remains a separate agent surface.bridgeBus.on('TaskProgress', ({ sessionKey, params }) => {- server- .getSession(sessionKey)- ?.conn.sendNotification(Notifications.TaskProgress, params)+ for (const session of server.getTaskNotificationSessions(sessionKey)) {+ session.conn.sendNotification(Notifications.TaskProgress, params)+ }})bridgeBus.on('TaskCompleted', ({ sessionKey, params }) => {- server- .getSession(sessionKey)- ?.conn.sendNotification(Notifications.TaskCompleted, params)+ for (const session of server.getTaskNotificationSessions(sessionKey)) {+ session.conn.sendNotification(Notifications.TaskCompleted, params)+ }})bridgeBus.on('TaskError', ({ sessionKey, params }) => {- server- .getSession(sessionKey)- ?.conn.sendNotification(Notifications.TaskError, params)+ for (const session of server.getTaskNotificationSessions(sessionKey)) {+ session.conn.sendNotification(Notifications.TaskError, params)+ }})const streamSource = new BridgeStreamSource(server, opts.localize)diff --git a/src/shared/locales/ar.json b/src/shared/locales/ar.jsonindex a8571465..76c4fa95 100644--- a/src/shared/locales/ar.json+++ b/src/shared/locales/ar.json@@ -2470,6 +2470,10 @@},"pairUnavailable": "لم يعد طلب الاقتران هذا معلّقًا — أعد محاولة الاقتران من امتداد المتصفح.","pairedEmpty": "لا توجد امتدادات متصلة بعد.",+ "profile": "ملف المتصفح {{number}}",+ "connected": "متصل",+ "disconnected": "غير متصل",+ "revokeAll": "قطع اتصال الكل","pairedTitle": "الامتدادات المتصلة","pairingStateDegraded": {"description": "تعذّر على Motrix تحديث سجلات الامتدادات المقترنة بأمان. أُغلقت جلسات الامتدادات الحالية وحُظر الوصول الجديد خلال هذا التشغيل. أعد تشغيل Motrix لإعادة محاولة الإصلاح؛ لا تعتمد على القائمة أدناه حتى تختفي هذه الرسالة.",diff --git a/src/shared/locales/bg.json b/src/shared/locales/bg.jsonindex 8121c649..282b2fd4 100644--- a/src/shared/locales/bg.json+++ b/src/shared/locales/bg.json@@ -2394,6 +2394,10 @@},"pairUnavailable": "Тази заявка за сдвояване вече не чака решение — опитайте отново от разширението за браузър.","pairedEmpty": "Все още няма свързани разширения.",+ "profile": "Профил на браузъра {{number}}",+ "connected": "Свързан",+ "disconnected": "Няма връзка",+ "revokeAll": "Прекъсване на всички","pairedTitle": "Свързани разширения","pairingStateDegraded": {"description": "Motrix не успя безопасно да обнови записите за сдвоени разширения. Съществуващите сесии на разширенията са затворени, а новият достъп е блокиран за това стартиране. Рестартирайте Motrix, за да опитате поправката отново; не разчитайте на списъка по-долу, докато това съобщение не изчезне.",diff --git a/src/shared/locales/ca.json b/src/shared/locales/ca.jsonindex 34b53550..357d11c5 100644--- a/src/shared/locales/ca.json+++ b/src/shared/locales/ca.json@@ -2413,6 +2413,10 @@},"pairUnavailable": "Aquesta petició d'aparellament ja no està pendent; torneu a aparellar des de l'extensió del navegador.","pairedEmpty": "Encara no hi ha extensions connectades.",+ "profile": "Perfil del navegador {{number}}",+ "connected": "Connectat",+ "disconnected": "No connectat",+ "revokeAll": "Desconnecta’ls tots","pairedTitle": "Extensions connectades","pairingStateDegraded": {"description": "El Motrix no ha pogut actualitzar de manera segura els registres d'extensions aparellades. S'han tancat les sessions d'extensions existents i s'ha bloquejat l'accés nou durant aquesta execució. Reinicieu el Motrix per tornar a provar la reparació; no us refieu de la llista següent fins que desaparegui aquest missatge.",diff --git a/src/shared/locales/de.json b/src/shared/locales/de.jsonindex 4141123f..0bb20c3a 100644--- a/src/shared/locales/de.json+++ b/src/shared/locales/de.json@@ -1926,6 +1926,10 @@},"pairedTitle": "Verbundene Erweiterungen","pairedEmpty": "Noch keine Erweiterungen verbunden.",+ "profile": "Browserprofil {{number}}",+ "connected": "Verbunden",+ "disconnected": "Nicht verbunden",+ "revokeAll": "Alle trennen","lastActive": "Zuletzt aktiv","revoke": "Trennen","disconnecting": "Verbindung wird getrennt…",diff --git a/src/shared/locales/el.json b/src/shared/locales/el.jsonindex a4ff2bbb..28e9cf6b 100644--- a/src/shared/locales/el.json+++ b/src/shared/locales/el.json@@ -2394,6 +2394,10 @@},"pairUnavailable": "Αυτό το αίτημα σύζευξης δεν εκκρεμεί πλέον — δοκιμάστε ξανά τη σύζευξη από την επέκταση του προγράμματος περιήγησης.","pairedEmpty": "Δεν έχουν συνδεθεί ακόμη επεκτάσεις.",+ "profile": "Προφίλ προγράμματος περιήγησης {{number}}",+ "connected": "Συνδεδεμένο",+ "disconnected": "Μη συνδεδεμένο",+ "revokeAll": "Αποσύνδεση όλων","pairedTitle": "Συνδεδεμένες επεκτάσεις","pairingStateDegraded": {"description": "Το Motrix δεν μπόρεσε να ενημερώσει με ασφάλεια τις εγγραφές συζευγμένων επεκτάσεων. Οι υπάρχουσες συνεδρίες επεκτάσεων έχουν κλείσει και η νέα πρόσβαση έχει αποκλειστεί για αυτή την εκτέλεση. Επανεκκινήστε το Motrix για νέα προσπάθεια επιδιόρθωσης· μη βασίζεστε στην παρακάτω λίστα μέχρι να εξαφανιστεί αυτό το μήνυμα.",diff --git a/src/shared/locales/en-US.json b/src/shared/locales/en-US.jsonindex dcb143ed..6c497635 100644--- a/src/shared/locales/en-US.json+++ b/src/shared/locales/en-US.json@@ -1926,6 +1926,10 @@},"pairedTitle": "Connected extensions","pairedEmpty": "No extensions connected yet.",+ "profile": "Browser profile {{number}}",+ "connected": "Connected",+ "disconnected": "Not connected",+ "revokeAll": "Disconnect all","lastActive": "Last active","revoke": "Disconnect","disconnecting": "Disconnecting…",diff --git a/src/shared/locales/es.json b/src/shared/locales/es.jsonindex 910aee54..2e45c21c 100644--- a/src/shared/locales/es.json+++ b/src/shared/locales/es.json@@ -1940,6 +1940,10 @@},"pairedTitle": "Extensiones conectadas","pairedEmpty": "Todavía no hay extensiones conectadas.",+ "profile": "Perfil del navegador {{number}}",+ "connected": "Conectado",+ "disconnected": "Sin conexión",+ "revokeAll": "Desconectar todos","lastActive": "Última actividad","revoke": "Desconectar","disconnecting": "Desconectando…",diff --git a/src/shared/locales/fa.json b/src/shared/locales/fa.jsonindex b5fbf4f7..27b2fdb0 100644--- a/src/shared/locales/fa.json+++ b/src/shared/locales/fa.json@@ -2394,6 +2394,10 @@},"pairUnavailable": "این درخواست جفتسازی دیگر در انتظار نیست؛ جفتسازی را از افزونهٔ مرورگر دوباره امتحان کنید.","pairedEmpty": "هنوز افزونهای متصل نشده است.",+ "profile": "نمایه مرورگر {{number}}",+ "connected": "متصل",+ "disconnected": "متصل نیست",+ "revokeAll": "قطع اتصال همه","pairedTitle": "افزونههای متصل","pairingStateDegraded": {"description": "Motrix نتوانست سوابق افزونههای جفتشده را ایمن بهروز کند. نشستهای فعلی افزونهها بسته شدهاند و دسترسی جدید در این اجرای برنامه مسدود است. برای تلاش دوباره جهت ترمیم، Motrix را دوباره راهاندازی کنید؛ تا رفع این پیام به فهرست زیر اتکا نکنید.",diff --git a/src/shared/locales/fr.json b/src/shared/locales/fr.jsonindex 0db7adc9..34260d4d 100644--- a/src/shared/locales/fr.json+++ b/src/shared/locales/fr.json@@ -2413,6 +2413,10 @@},"pairUnavailable": "Cette demande d’association n’est plus en attente. Relancez l’association depuis l’extension du navigateur.","pairedEmpty": "Aucune extension connectée pour le moment.",+ "profile": "Profil du navigateur {{number}}",+ "connected": "Connecté",+ "disconnected": "Non connecté",+ "revokeAll": "Tout déconnecter","pairedTitle": "Extensions connectées","pairingStateDegraded": {"description": "Motrix n’a pas pu mettre à jour en toute sécurité les enregistrements des extensions associées. Les sessions existantes sont fermées et les nouveaux accès sont bloqués pour cette exécution. Redémarrez Motrix pour retenter la réparation ; ne vous fiez pas à la liste ci-dessous tant que ce message est présent.",diff --git a/src/shared/locales/hu.json b/src/shared/locales/hu.jsonindex f10616d5..63691186 100644--- a/src/shared/locales/hu.json+++ b/src/shared/locales/hu.json@@ -1926,6 +1926,10 @@},"pairedTitle": "Csatlakoztatott bővítmények","pairedEmpty": "Még nincs csatlakoztatott bővítmény.",+ "profile": "Böngészőprofil {{number}}",+ "connected": "Csatlakoztatva",+ "disconnected": "Nincs csatlakoztatva",+ "revokeAll": "Összes leválasztása","lastActive": "Utolsó aktivitás","revoke": "Leválasztás","disconnecting": "Leválasztás…",diff --git a/src/shared/locales/id.json b/src/shared/locales/id.jsonindex c8a30a36..024436e1 100644--- a/src/shared/locales/id.json+++ b/src/shared/locales/id.json@@ -1912,6 +1912,10 @@},"pairedTitle": "Ekstensi terhubung","pairedEmpty": "Belum ada ekstensi yang terhubung.",+ "profile": "Profil browser {{number}}",+ "connected": "Terhubung",+ "disconnected": "Tidak terhubung",+ "revokeAll": "Putuskan semua","lastActive": "Terakhir aktif","revoke": "Putuskan koneksi","disconnecting": "Memutuskan koneksi…",diff --git a/src/shared/locales/it.json b/src/shared/locales/it.jsonindex c6d4ae3f..35dea12c 100644--- a/src/shared/locales/it.json+++ b/src/shared/locales/it.json@@ -1940,6 +1940,10 @@},"pairedTitle": "Estensioni collegate","pairedEmpty": "Nessuna estensione collegata.",+ "profile": "Profilo del browser {{number}}",+ "connected": "Connesso",+ "disconnected": "Non connesso",+ "revokeAll": "Disconnetti tutti","lastActive": "Ultima attività","revoke": "Scollega","disconnecting": "Disconnessione…",diff --git a/src/shared/locales/ja.json b/src/shared/locales/ja.jsonindex f2f0e2ea..9e6f9daf 100644--- a/src/shared/locales/ja.json+++ b/src/shared/locales/ja.json@@ -1912,6 +1912,10 @@},"pairedTitle": "接続済みの拡張機能","pairedEmpty": "接続済みの拡張機能はまだありません。",+ "profile": "ブラウザープロファイル {{number}}",+ "connected": "接続済み",+ "disconnected": "未接続",+ "revokeAll": "すべて切断","lastActive": "最終利用","revoke": "接続を解除","disconnecting": "接続を解除中…",diff --git a/src/shared/locales/ko.json b/src/shared/locales/ko.jsonindex c49647f4..6ee34bbf 100644--- a/src/shared/locales/ko.json+++ b/src/shared/locales/ko.json@@ -1912,6 +1912,10 @@},"pairedTitle": "연결된 확장 프로그램","pairedEmpty": "아직 연결된 확장 프로그램이 없습니다.",+ "profile": "브라우저 프로필 {{number}}",+ "connected": "연결됨",+ "disconnected": "연결되지 않음",+ "revokeAll": "모두 연결 해제","lastActive": "마지막 활동","revoke": "연결 해제","disconnecting": "연결 해제 중…",diff --git a/src/shared/locales/nb.json b/src/shared/locales/nb.jsonindex 08f504ff..1746389e 100644--- a/src/shared/locales/nb.json+++ b/src/shared/locales/nb.json@@ -2394,6 +2394,10 @@},"pairUnavailable": "Denne sammenkoblingsforespørselen venter ikke lenger — prøv sammenkoblingen på nytt fra nettleserutvidelsen.","pairedEmpty": "Ingen utvidelser er tilkoblet ennå.",+ "profile": "Nettleserprofil {{number}}",+ "connected": "Tilkoblet",+ "disconnected": "Ikke tilkoblet",+ "revokeAll": "Koble fra alle","pairedTitle": "Tilkoblede utvidelser","pairingStateDegraded": {"description": "Motrix kunne ikke oppdatere registreringene for sammenkoblede utvidelser trygt. Eksisterende utvidelsesøkter er lukket, og ny tilgang er blokkert for denne kjøringen. Start Motrix på nytt for å prøve reparasjonen igjen; ikke stol på listen nedenfor før denne meldingen forsvinner.",diff --git a/src/shared/locales/nl.json b/src/shared/locales/nl.jsonindex 9c9b2c21..a3aa8392 100644--- a/src/shared/locales/nl.json+++ b/src/shared/locales/nl.json@@ -2394,6 +2394,10 @@},"pairUnavailable": "Dit koppelingsverzoek is niet meer in behandeling — probeer opnieuw te koppelen vanuit de browserextensie.","pairedEmpty": "Nog geen extensies verbonden.",+ "profile": "Browserprofiel {{number}}",+ "connected": "Verbonden",+ "disconnected": "Niet verbonden",+ "revokeAll": "Alles ontkoppelen","pairedTitle": "Verbonden extensies","pairingStateDegraded": {"description": "Motrix kon de gegevens van gekoppelde extensies niet veilig bijwerken. Bestaande extensiesessies zijn gesloten en nieuwe toegang is voor deze uitvoering geblokkeerd. Herstart Motrix om het herstel opnieuw te proberen; vertrouw niet op de onderstaande lijst totdat dit bericht verdwenen is.",diff --git a/src/shared/locales/pl.json b/src/shared/locales/pl.jsonindex 11245074..481b0709 100644--- a/src/shared/locales/pl.json+++ b/src/shared/locales/pl.json@@ -1954,6 +1954,10 @@},"pairedTitle": "Połączone rozszerzenia","pairedEmpty": "Nie połączono jeszcze żadnych rozszerzeń.",+ "profile": "Profil przeglądarki {{number}}",+ "connected": "Połączono",+ "disconnected": "Nie połączono",+ "revokeAll": "Rozłącz wszystkie","lastActive": "Ostatnia aktywność","revoke": "Rozłącz","disconnecting": "Rozłączanie…",diff --git a/src/shared/locales/pt-BR.json b/src/shared/locales/pt-BR.jsonindex 17786139..73d672fe 100644--- a/src/shared/locales/pt-BR.json+++ b/src/shared/locales/pt-BR.json@@ -1940,6 +1940,10 @@},"pairedTitle": "Extensões conectadas","pairedEmpty": "Nenhuma extensão conectada ainda.",+ "profile": "Perfil do navegador {{number}}",+ "connected": "Conectado",+ "disconnected": "Não conectado",+ "revokeAll": "Desconectar todos","lastActive": "Última atividade","revoke": "Desconectar","disconnecting": "Desconectando…",diff --git a/src/shared/locales/ro.json b/src/shared/locales/ro.jsonindex c5baa905..b3283dd7 100644--- a/src/shared/locales/ro.json+++ b/src/shared/locales/ro.json@@ -2413,6 +2413,10 @@},"pairUnavailable": "Această cerere de asociere nu mai este în așteptare — reîncearcă asocierea din extensia de browser.","pairedEmpty": "Încă nu există extensii conectate.",+ "profile": "Profil de browser {{number}}",+ "connected": "Conectat",+ "disconnected": "Neconectat",+ "revokeAll": "Deconectează toate","pairedTitle": "Extensii conectate","pairingStateDegraded": {"description": "Motrix nu a putut actualiza în siguranță înregistrările extensiilor asociate. Sesiunile existente ale extensiilor sunt închise, iar accesul nou este blocat pentru această rulare. Repornește Motrix pentru a reîncerca repararea; nu te baza pe lista de mai jos până când dispare acest mesaj.",diff --git a/src/shared/locales/ru.json b/src/shared/locales/ru.jsonindex b2eadf6a..828fdaae 100644--- a/src/shared/locales/ru.json+++ b/src/shared/locales/ru.json@@ -1954,6 +1954,10 @@},"pairedTitle": "Подключённые расширения","pairedEmpty": "Расширения ещё не подключены.",+ "profile": "Профиль браузера {{number}}",+ "connected": "Подключён",+ "disconnected": "Не подключён",+ "revokeAll": "Отключить все","lastActive": "Последняя активность","revoke": "Отключить","disconnecting": "Отключение…",diff --git a/src/shared/locales/th.json b/src/shared/locales/th.jsonindex feb81e9c..b4b64efc 100644--- a/src/shared/locales/th.json+++ b/src/shared/locales/th.json@@ -2375,6 +2375,10 @@},"pairUnavailable": "คำขอจับคู่นี้ไม่ได้อยู่ระหว่างรอแล้ว — ลองจับคู่จากส่วนขยายเบราว์เซอร์อีกครั้ง","pairedEmpty": "ยังไม่มีส่วนขยายเชื่อมต่อ",+ "profile": "โปรไฟล์เบราว์เซอร์ {{number}}",+ "connected": "เชื่อมต่อแล้ว",+ "disconnected": "ไม่ได้เชื่อมต่อ",+ "revokeAll": "ยกเลิกการเชื่อมต่อทั้งหมด","pairedTitle": "ส่วนขยายที่เชื่อมต่อ","pairingStateDegraded": {"description": "Motrix ไม่สามารถอัปเดตระเบียนส่วนขยายที่จับคู่แล้วได้อย่างปลอดภัย เซสชันส่วนขยายที่มีอยู่ถูกปิด และการเข้าถึงใหม่ถูกบล็อกสำหรับการเปิดแอปครั้งนี้ เริ่ม Motrix ใหม่เพื่อลองซ่อมอีกครั้ง อย่าอ้างอิงรายการด้านล่างจนกว่าข้อความนี้จะหายไป",diff --git a/src/shared/locales/tr.json b/src/shared/locales/tr.jsonindex e3461be6..7b7063b0 100644--- a/src/shared/locales/tr.json+++ b/src/shared/locales/tr.json@@ -1926,6 +1926,10 @@},"pairedTitle": "Bağlı uzantılar","pairedEmpty": "Henüz bağlı uzantı yok.",+ "profile": "Tarayıcı profili {{number}}",+ "connected": "Bağlı",+ "disconnected": "Bağlı değil",+ "revokeAll": "Tüm bağlantıları kes","lastActive": "Son etkinlik","revoke": "Bağlantıyı kes","disconnecting": "Bağlantı kesiliyor…",diff --git a/src/shared/locales/uk.json b/src/shared/locales/uk.jsonindex ddf78155..f4d980d3 100644--- a/src/shared/locales/uk.json+++ b/src/shared/locales/uk.json@@ -2432,6 +2432,10 @@},"pairUnavailable": "Цей запит на сполучення вже не очікує відповіді — повторіть сполучення з розширення браузера.","pairedEmpty": "Ще немає підключених розширень.",+ "profile": "Профіль браузера {{number}}",+ "connected": "Підключено",+ "disconnected": "Не підключено",+ "revokeAll": "Від’єднати всі","pairedTitle": "Підключені розширення","pairingStateDegraded": {"description": "Motrix не вдалося безпечно оновити записи про сполучені розширення. Поточні сеанси розширень закрито, а новий доступ заблоковано до завершення цього запуску. Перезапустіть Motrix, щоб повторити відновлення; не покладайтеся на список нижче, доки це повідомлення не зникне.",diff --git a/src/shared/locales/vi.json b/src/shared/locales/vi.jsonindex 36116f5c..162bd84c 100644--- a/src/shared/locales/vi.json+++ b/src/shared/locales/vi.json@@ -1912,6 +1912,10 @@},"pairedTitle": "Tiện ích mở rộng đã kết nối","pairedEmpty": "Chưa có tiện ích mở rộng nào kết nối.",+ "profile": "Hồ sơ trình duyệt {{number}}",+ "connected": "Đã kết nối",+ "disconnected": "Chưa kết nối",+ "revokeAll": "Ngắt kết nối tất cả","lastActive": "Hoạt động gần nhất","revoke": "Ngắt kết nối","disconnecting": "Đang ngắt kết nối…",diff --git a/src/shared/locales/zh-CN.json b/src/shared/locales/zh-CN.jsonindex 30880601..813c866c 100644--- a/src/shared/locales/zh-CN.json+++ b/src/shared/locales/zh-CN.json@@ -1912,6 +1912,10 @@},"pairedTitle": "已连接的扩展","pairedEmpty": "还没有扩展连接到 Motrix。",+ "profile": "浏览器配置 {{number}}",+ "connected": "已连接",+ "disconnected": "未连接",+ "revokeAll": "全部断开","lastActive": "上次活跃","revoke": "断开","disconnecting": "正在断开…",diff --git a/src/shared/locales/zh-TW.json b/src/shared/locales/zh-TW.jsonindex 7185cdd8..27e88093 100644--- a/src/shared/locales/zh-TW.json+++ b/src/shared/locales/zh-TW.json@@ -1912,6 +1912,10 @@},"pairedTitle": "已連線的擴充功能","pairedEmpty": "尚未連線任何擴充功能。",+ "profile": "瀏覽器設定檔 {{number}}",+ "connected": "已連線",+ "disconnected": "未連線",+ "revokeAll": "全部中斷","lastActive": "上次使用","revoke": "中斷連線","disconnecting": "正在中斷連線…",diff --git a/src/shared/protocol/bridge.ts b/src/shared/protocol/bridge.tsindex 30ae802a..95aa5dc5 100644--- a/src/shared/protocol/bridge.ts+++ b/src/shared/protocol/bridge.ts@@ -24,12 +24,8 @@ export function isSafariExtensionOrigin(origin: string): boolean {)}-/**- * Compose the session/index key shared by the pairing store, the trusted- * registry, and the live WebSocket session map. The wire shape is- * `${browser}:${extensionId}`; keep every call site funneled through here so- * the three subsystems can never drift apart.- */+/** Extension-wide trust/revocation key. Active connections use the full MBP1+ * credential principal, including its installation ID, instead. */export function makeSessionKey(browser: Browser, extensionId: string): string {return `${browser}:${extensionId}`}@@ -49,14 +45,7 @@ export type ClientIdentity =}| { readonly kind: 'cli'; readonly id: string }-/**- * Stable session/index key for a {@link ClientIdentity}. For the `extension`- * kind this is byte-identical to {@link makeSessionKey}- * (`${browser}:${extensionId}`), so the live session map, persisted pairing- * keys, and task `sourceMeta.sessionKey` are all unchanged. The `cli` kind is- * namespaced under a `cli:` prefix so it can never collide with an extension- * key (`${browser}:${extensionId}`), even for an adversarial cli id.- */+/** Group identity key for extension trust/revocation and CLI authorization. */export function clientKey(identity: ClientIdentity): string {switch (identity.kind) {case 'extension':@@ -87,6 +76,7 @@ export const BridgeEvents = {PairRequested: 'bridge:pairRequested',Paired: 'bridge:paired',Revoked: 'bridge:revoked',+ ExtensionSessionsChanged: 'bridge:extensionSessionsChanged',Error: 'bridge:error',/** A pending request reached a non-TTL terminal outcome. */PairRequestSettled: 'bridge:pairRequestSettled',@@ -98,6 +88,13 @@ export type BridgeCommand = (typeof BridgeCommands)[keyof typeof BridgeCommands]export type BridgeQuery = (typeof BridgeQueries)[keyof typeof BridgeQueries]export type BridgeEvent = (typeof BridgeEvents)[keyof typeof BridgeEvents]+export interface ExtensionInstallationInfo {+ /** Opaque non-secret installation key, stable across reconnects. */+ id: string+ pairedAt: number+ connected: boolean+}+/*** Renderer-facing paired-client DTO (the token is never exposed). Discriminated* on `kind`, mirroring {@link ClientIdentity}: an `extension` carries its@@ -112,6 +109,8 @@ export type PairedClientInfo =name: stringidentityTrust: IdentityTriStatestatus: 'ready' | 'cleanup-pending'+ /** Optional for compatibility with older paired-list providers. */+ installations?: ExtensionInstallationInfo[]pairedAt: numberlastActiveAt: number | null}diff --git a/src/shared/protocol/forwardable-events.ts b/src/shared/protocol/forwardable-events.tsindex fe84ec35..1c8119db 100644--- a/src/shared/protocol/forwardable-events.ts+++ b/src/shared/protocol/forwardable-events.ts@@ -57,11 +57,12 @@ export const ForwardableEvents = [Events.SpeedLimitChanged,Events.NotificationAdded,Events.NotificationsChanged,- // Bridge approval events (Spec 7b) — forwarded so the web renderer's pairing- // toast + paired-client list work on the server shell, same as Electron IPC.+ // Bridge pairing and session events keep the web renderer's approval UI and+ // profile connection status synchronized, same as Electron IPC.BridgeEvents.PairRequested,BridgeEvents.Paired,BridgeEvents.Revoked,+ BridgeEvents.ExtensionSessionsChanged,BridgeEvents.Error,// Pending pair request lifecycle (pending -> settled | expired) — same// web-shell forwarding rationale as the approval events above.diff --git a/src/shared/types/task.ts b/src/shared/types/task.tsindex 7acbbd32..6f1e6f71 100644--- a/src/shared/types/task.ts+++ b/src/shared/types/task.ts@@ -263,7 +263,7 @@ export interface BridgeSourceMeta {kind: 'direct' | 'hls' | 'dash' | 'mux' | 'magnet'extensionId: stringbrowser: Browser- sessionKey: string // `${browser}:${extensionId}`+ sessionKey: string // Authenticated installation routing key; older tasks use an extension-wide key.pageUrl: stringpageTitle: stringqualityLabel: stringdiff --git a/tests/scripts/production-build.test.ts b/tests/scripts/production-build.test.tsindex d6468661..c51d16c9 100644--- a/tests/scripts/production-build.test.ts+++ b/tests/scripts/production-build.test.ts@@ -5,8 +5,9 @@ import { beforeAll, describe, expect, it } from 'vitest'const MIB = 1024 * 1024const ROOT = path.resolve(import.meta.dirname, '../..')const TARGETS = [- // Explicit resource lifetimes add ~6 KiB; retain the 2 MiB startup ceiling.- { name: 'main', initial: 2 * MIB, total: 5.5 * MIB + 8 * 1024 },+ // Installation-aware bridge routing and localized profile summaries add+ // ~5 KiB over the resource-lifetime baseline; retain the 2 MiB startup ceiling.+ { name: 'main', initial: 2 * MIB, total: 5.5 * MIB + 12 * 1024 },{ name: 'preload', initial: 80 * 1024, total: 80 * 1024 },{ name: 'worker', initial: 48 * 1024, total: 48 * 1024 },{ name: 'renderer', initial: 2.75 * MIB, total: 8 * MIB },