Skip to content

The agent that grows with you

fix(webapp): isolate plain-HTTP tabs that have no Web Locks

Adolanium9a290094bd42
diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/prepared-submissions.test.ts b/apps/desktop/src/app/session/hooks/use-prompt-actions/prepared-submissions.test.ts
index 1b334681211..802b1a00182 100644
--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/prepared-submissions.test.ts
+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/prepared-submissions.test.ts
@@ -47,3 +47,173 @@ test('native preparation waits for acknowledgement and never downgrades a write
await removePreparedSubmission('key', 'a')
expect(await readPreparedSubmission('key')).toBeUndefined()
})
+
+function sharedStorage(): Storage {
+ const rows = new Map<string, string>()
+
+ return {
+ get length() { return rows.size },
+ clear() { rows.clear() },
+ getItem(key: string) {
+ const value = rows.get(key)
+
+ return value === undefined ? null : value
+ },
+ key(index: number) { return [...rows.keys()][index] ?? null },
+ removeItem(key: string) { rows.delete(key) },
+ setItem(key: string, value: string) { rows.set(key, String(value)) }
+ }
+}
+
+function installSharedStorage(): () => void {
+ const real = window.localStorage
+
+ Object.defineProperty(window, 'localStorage', { configurable: true, value: sharedStorage() })
+
+ return () => {
+ Object.defineProperty(window, 'localStorage', { configurable: true, value: real })
+ }
+}
+
+function hideWebLocks(): void {
+ Object.defineProperty(navigator, 'locks', { configurable: true, value: undefined })
+}
+
+const destination = { scopeKey: 'local::default' } as SubmissionDestination
+const owner = { connectionId: 'local', profile: 'default' }
+
+async function twoWindows() {
+ vi.resetModules()
+ const windowA = await import('./prepared-submissions')
+ vi.resetModules()
+ const windowB = await import('./prepared-submissions')
+
+ return { windowA, windowB }
+}
+
+test('two plain-HTTP windows do not adopt one prepared submission', async () => {
+ hideWebLocks()
+ vi.stubGlobal('hermesDesktop', undefined)
+ const restoreStorage = installSharedStorage()
+ const intent = preparedSubmissionKey('stored', destination, 'same text', [])
+
+ const entry: PreparedSubmission = {
+ id: 'sub-1',
+ text: 'same text',
+ attachments: [],
+ params: { submission_id: 'sub-1' },
+ owner
+ }
+
+ try {
+ const { windowA, windowB } = await twoWindows()
+
+ await windowA.writePreparedSubmission(intent, entry)
+ const held = await windowA.adoptPreparedSubmission(intent, 'sub-1')
+ expect(held?.entry.id).toBe('sub-1')
+ expect(await windowB.adoptPreparedSubmission(intent, 'sub-1')).toBeUndefined()
+
+ const [racedA, racedB] = await Promise.all([
+ windowA.adoptPreparedSubmission(intent, 'sub-1'),
+ windowB.adoptPreparedSubmission(intent, 'sub-1')
+ ])
+
+ // The holder already owns it, so a racing adopt from the other window still loses.
+ expect(racedA?.entry.id).toBe('sub-1')
+ expect(racedB).toBeUndefined()
+ await windowA.removePreparedSubmission(intent, 'sub-1')
+ } finally {
+ Reflect.deleteProperty(navigator, 'locks')
+ restoreStorage()
+ }
+})
+
+test('a closed plain-HTTP window leaves its prepared submission adoptable', async () => {
+ hideWebLocks()
+ vi.stubGlobal('hermesDesktop', undefined)
+ const restoreStorage = installSharedStorage()
+ const intent = preparedSubmissionKey('stored', destination, 'same text', [])
+
+ const entry: PreparedSubmission = {
+ id: 'sub-1',
+ text: 'same text',
+ attachments: [],
+ params: { submission_id: 'sub-1' },
+ owner
+ }
+
+ try {
+ const { windowA, windowB } = await twoWindows()
+
+ await windowA.writePreparedSubmission(intent, entry)
+ expect((await windowA.adoptPreparedSubmission(intent, 'sub-1'))?.entry.id).toBe('sub-1')
+ expect(await windowB.adoptPreparedSubmission(intent, 'sub-1')).toBeUndefined()
+ window.dispatchEvent(new Event('pagehide'))
+ const adopted = await windowB.adoptPreparedSubmission(intent, 'sub-1')
+ expect(adopted?.entry.id).toBe('sub-1')
+ await windowB.removePreparedSubmission(adopted!.key, adopted!.entry.id)
+ } finally {
+ Reflect.deleteProperty(navigator, 'locks')
+ restoreStorage()
+ }
+})
+
+test('two plain-HTTP windows do not share one slash retry slot', async () => {
+ hideWebLocks()
+ vi.stubGlobal('hermesDesktop', undefined)
+ const restoreStorage = installSharedStorage()
+ const intent = preparedSubmissionKey('stored', destination, '/skill task', [], { retryText: '/skill task' })
+
+ try {
+ const { windowA, windowB } = await twoWindows()
+
+ const [slotA, slotB] = await Promise.all([
+ windowA.preparedSubmissionSlot(intent),
+ windowB.preparedSubmissionSlot(intent)
+ ])
+
+ expect(slotA).not.toBe(slotB)
+ await windowA.removePreparedSubmission(slotA, 'release-a')
+ await windowB.removePreparedSubmission(slotB, 'release-b')
+ } finally {
+ Reflect.deleteProperty(navigator, 'locks')
+ restoreStorage()
+ }
+})
+
+test('Web Locks still exclude a live window from adopting the same prepared submission', async () => {
+ vi.stubGlobal('hermesDesktop', undefined)
+ const held = new Set<string>()
+
+ const request = vi.fn((name: string, options: { ifAvailable?: boolean }, callback: (lock: { name: string } | null) => unknown) => {
+ if (options?.ifAvailable && held.has(name)) { return callback(null) }
+
+ held.add(name)
+
+ return Promise.resolve(callback({ name })).finally(() => { held.delete(name) })
+ })
+
+ Object.defineProperty(navigator, 'locks', { configurable: true, value: { request } })
+ const intent = preparedSubmissionKey('stored', destination, 'same text', [])
+
+ const entry: PreparedSubmission = {
+ id: 'sub-1',
+ text: 'same text',
+ attachments: [],
+ params: { submission_id: 'sub-1' },
+ owner
+ }
+
+ try {
+ const { windowA, windowB } = await twoWindows()
+
+ await windowA.writePreparedSubmission(intent, entry)
+ expect((await windowA.adoptPreparedSubmission(intent, 'sub-1'))?.entry.id).toBe('sub-1')
+ expect(await windowB.adoptPreparedSubmission(intent, 'sub-1')).toBeUndefined()
+ expect(request).toHaveBeenCalled()
+ expect(Array.from({ length: localStorage.length }, (_, index) => localStorage.key(index)).some(key => key?.startsWith('hermes.desktop.tabLease.v1:'))).toBe(false)
+ await windowA.removePreparedSubmission(intent, 'sub-1')
+ } finally {
+ Reflect.deleteProperty(navigator, 'locks')
+ }
+})
diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/prepared-submissions.ts b/apps/desktop/src/app/session/hooks/use-prompt-actions/prepared-submissions.ts
index 9f7b602473c..d6217216980 100644
--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/prepared-submissions.ts
+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/prepared-submissions.ts
@@ -1,3 +1,4 @@
+import { tryPlainHttpTabLease } from '@/lib/plain-http-tab-lease'
import type { ComposerAttachment } from '@/store/composer'
import type { SessionOwnerScope } from '@/store/session-request-router'
@@ -155,10 +156,11 @@ export async function readPreparedSubmission(key: string): Promise<PreparedSubmi
return (await readJournal())[key]
}
-// Uncertain sends this window journaled or adopted: journal key -> release of its Web Lock.
-// The journal is shared by every window of the origin; a held lock marks an entry whose
-// window is alive, and only that window may retry it. A closed window's lock is freed, so its
-// entry stays adoptable after a reload. Without Web Locks there is no other window to exclude.
+// Uncertain sends this window journaled or adopted: journal key -> release of its claim.
+// The journal is shared by every window of the origin; a held claim marks an entry whose
+// window is alive, and only that window may retry it. A closed window's claim is freed, so its
+// entry stays adoptable after a reload. Plain HTTP has no Web Locks, but two tabs still share
+// this origin: the claim is a localStorage lease there. Electron and HTTPS keep Web Locks.
const owned = new Map<string, () => void>()
function holdPreparedSubmission(key: string): Promise<boolean> {
@@ -167,9 +169,13 @@ function holdPreparedSubmission(key: string): Promise<boolean> {
if (owned.has(key)) { return Promise.resolve(true) }
if (!locks) {
- owned.set(key, () => undefined)
+ return tryPlainHttpTabLease(`${STORAGE_KEY}.${key}`).then(release => {
+ if (!release) { return false }
- return Promise.resolve(true)
+ owned.set(key, release)
+
+ return true
+ })
}
return new Promise<boolean>(acquired => {
diff --git a/apps/desktop/src/lib/plain-http-tab-lease.ts b/apps/desktop/src/lib/plain-http-tab-lease.ts
new file mode 100644
index 00000000000..0ab1135fc78
--- /dev/null
+++ b/apps/desktop/src/lib/plain-http-tab-lease.ts
@@ -0,0 +1,251 @@
+// Cross-tab exclusion for origins where `navigator.locks` does not exist.
+// Plain HTTP is not a secure context, so two tabs of the webapp share an
+// origin and have no Web Locks. A localStorage compare-and-swap lease is the
+// claim there. Callers that already have `navigator.locks` (Electron, HTTPS)
+// must keep using Web Locks; this module does not replace that path.
+//
+// The lease outlives one missed renewal on a background tab (Chromium clamps
+// those timers to about a minute) and is dropped on `pagehide`, so a reload
+// does not wait it out. A crashed tab stops renewing and the other tab takes
+// the name once `expires` is past.
+
+const PREFIX = 'hermes.desktop.tabLease.v1:'
+const LEASE_MS = 180_000
+const RENEW_MS = 30_000
+const POLL_MS = 40
+
+interface Lease {
+ owner: string
+ expires: number
+}
+
+type AcquireResult = 'acquired' | 'busy' | 'unavailable'
+
+type Taken =
+ | { ok: false; reason: 'busy' | 'unavailable' }
+ | { ok: true; release: () => void }
+
+const held = new Set<() => void>()
+
+function localStorageOrNull(): Storage | null {
+ try {
+ if (typeof window === 'undefined') {
+ return null
+ }
+
+ return window.localStorage
+ } catch {
+ return null
+ }
+}
+
+function storageKey(name: string): string {
+ // Journal names carry the message text and can be long. The lease only needs
+ // a stable id, and a short key stays inside localStorage limits.
+ let high = 0x811c9dc5
+ let low = 0x811c9dc5 ^ name.length
+
+ for (let index = 0; index < name.length; index += 1) {
+ const code = name.charCodeAt(index)
+
+ high = Math.imul(high ^ code, 0x01000193)
+ low = Math.imul(low ^ (code + index), 0x01000193)
+ }
+
+ const hex = (value: number) => (value >>> 0).toString(16).padStart(8, '0')
+
+ return `${PREFIX}${hex(high)}${hex(low)}`
+}
+
+function readLease(store: Storage, key: string): Lease | null {
+ const raw = store.getItem(key)
+
+ if (!raw) {
+ return null
+ }
+
+ try {
+ const parsed = JSON.parse(raw) as Partial<Lease>
+
+ if (typeof parsed.owner !== 'string' || typeof parsed.expires !== 'number') {
+ return null
+ }
+
+ return { expires: parsed.expires, owner: parsed.owner }
+ } catch {
+ return null
+ }
+}
+
+function compareAndSwap(key: string, owner: string, now: number): AcquireResult {
+ const store = localStorageOrNull()
+
+ if (!store) {
+ return 'unavailable'
+ }
+
+ try {
+ const current = readLease(store, key)
+
+ if (current && current.owner !== owner && current.expires > now) {
+ return 'busy'
+ }
+
+ const next = JSON.stringify({ expires: now + LEASE_MS, owner } satisfies Lease)
+
+ store.setItem(key, next)
+
+ return store.getItem(key) === next ? 'acquired' : 'busy'
+ } catch {
+ return 'unavailable'
+ }
+}
+
+function releaseLease(key: string, owner: string): void {
+ const store = localStorageOrNull()
+
+ if (!store) {
+ return
+ }
+
+ try {
+ const current = readLease(store, key)
+
+ if (current && current.owner !== owner) {
+ return
+ }
+
+ store.removeItem(key)
+ } catch {
+ // Already gone, or storage is locked down. The record expires on its own.
+ }
+}
+
+function randomOwner(): string {
+ const bytes = new Uint8Array(16)
+ const cryptoApi = globalThis.crypto
+
+ if (cryptoApi?.getRandomValues) {
+ cryptoApi.getRandomValues(bytes)
+ } else {
+ for (let index = 0; index < bytes.length; index += 1) {
+ bytes[index] = Math.floor(Math.random() * 256)
+ }
+ }
+
+ return Array.from(bytes, byte => byte.toString(16).padStart(2, '0')).join('')
+}
+
+function delay(ms: number): Promise<void> {
+ return new Promise(resolve => {
+ setTimeout(resolve, ms)
+ })
+}
+
+function beginHold(key: string, owner: string): () => void {
+ let stopped = false
+ let timer: ReturnType<typeof setInterval> | undefined = undefined
+
+ const release = () => {
+ if (stopped) {
+ return
+ }
+
+ stopped = true
+ held.delete(release)
+
+ if (timer !== undefined) {
+ clearInterval(timer)
+ }
+
+ releaseLease(key, owner)
+ }
+
+ timer = setInterval(() => {
+ if (stopped) {
+ return
+ }
+
+ const store = localStorageOrNull()
+ const current = store ? readLease(store, key) : null
+
+ if (current && current.owner !== owner && current.expires > Date.now()) {
+ stopped = true
+ held.delete(release)
+
+ if (timer !== undefined) {
+ clearInterval(timer)
+ }
+
+ return
+ }
+
+ compareAndSwap(key, owner, Date.now())
+ }, RENEW_MS)
+
+ held.add(release)
+
+ return release
+}
+
+function releaseAll(): void {
+ for (const release of [...held]) {
+ release()
+ }
+}
+
+if (typeof window !== 'undefined') {
+ window.addEventListener('pagehide', event => {
+ if (event.persisted) {
+ return
+ }
+
+ releaseAll()
+ })
+}
+
+function takeLease(name: string): Taken {
+ const owner = randomOwner()
+ const key = storageKey(name)
+ const wrote = compareAndSwap(key, owner, Date.now())
+
+ if (wrote !== 'acquired') {
+ return { ok: false, reason: wrote === 'unavailable' ? 'unavailable' : 'busy' }
+ }
+
+ // setItem + getItem is the compare-and-swap. The loser does not start a
+ // renewal timer, so it cannot overwrite the winner on the next tick.
+ return { ok: true, release: beginHold(key, owner) }
+}
+
+/** Take `name` if no live tab holds it. Null means another live tab has it, or storage cannot record a lease. */
+export async function tryPlainHttpTabLease(name: string): Promise<null | (() => void)> {
+ const taken = takeLease(name)
+
+ return taken.ok ? taken.release : null
+}
+
+/**
+ * Wait until this tab holds `name`, then run `task`. Matches Web Locks
+ * `request` (exclusive, queued). If storage cannot record a lease at all,
+ * run anyway so a queue drain is not stuck with no way to claim it.
+ */
+export async function withPlainHttpTabLease<T>(name: string, task: () => Promise<T>): Promise<T> {
+ for (;;) {
+ const taken = takeLease(name)
+
+ if (taken.ok) {
+ try {
+ return await task()
+ } finally {
+ taken.release()
+ }
+ }
+
+ if (taken.reason === 'unavailable') {
+ return task()
+ }
+
+ await delay(POLL_MS)
+ }
+}
diff --git a/apps/desktop/src/store/composer-queue.test.ts b/apps/desktop/src/store/composer-queue.test.ts
index 09da587b26c..52a609163c5 100644
--- a/apps/desktop/src/store/composer-queue.test.ts
+++ b/apps/desktop/src/store/composer-queue.test.ts
@@ -20,7 +20,8 @@ import {
simulateComposerQueueReloadForTests,
unparkQueuedPrompts,
updateQueuedPrompt,
- updateQueuedPromptText
+ updateQueuedPromptText,
+ withQueueDrainClaim
} from './composer-queue'
const SESSION_KEY = 'session-abc'
@@ -576,3 +577,186 @@ describe('composer queue terminal payload persistence', () => {
expect(getFrozenQueuedTransport(entry!.id)).toBeUndefined()
})
})
+
+function sharedStorage(): Storage {
+ const rows = new Map<string, string>()
+
+ return {
+ get length() {
+ return rows.size
+ },
+ clear() {
+ rows.clear()
+ },
+ getItem(key: string) {
+ const value = rows.get(key)
+
+ return value === undefined ? null : value
+ },
+ key(index: number) {
+ return [...rows.keys()][index] ?? null
+ },
+ removeItem(key: string) {
+ rows.delete(key)
+ },
+ setItem(key: string, value: string) {
+ rows.set(key, String(value))
+ }
+ }
+}
+
+function installSharedStorage(): () => void {
+ const real = window.localStorage
+
+ Object.defineProperty(window, 'localStorage', { configurable: true, value: sharedStorage() })
+
+ return () => {
+ Object.defineProperty(window, 'localStorage', { configurable: true, value: real })
+ }
+}
+
+function hideWebLocks(): void {
+ Object.defineProperty(navigator, 'locks', { configurable: true, value: undefined })
+}
+
+/** Crash stand-in: the holder stopped renewing, so its record is already expired. */
+function expireLiveLeases(): number {
+ let expired = 0
+
+ for (let index = 0; index < window.localStorage.length; index += 1) {
+ const key = window.localStorage.key(index)
+
+ if (!key) {
+ continue
+ }
+
+ const raw = window.localStorage.getItem(key)
+
+ if (!raw) {
+ continue
+ }
+
+ try {
+ const parsed = JSON.parse(raw) as { expires?: unknown; owner?: unknown }
+
+ if (typeof parsed.owner !== 'string' || typeof parsed.expires !== 'number') {
+ continue
+ }
+
+ window.localStorage.setItem(key, JSON.stringify({ expires: Date.now() - 1, owner: parsed.owner }))
+ expired += 1
+ } catch {
+ // Queue rows and other records are not leases.
+ }
+ }
+
+ return expired
+}
+
+describe('plain HTTP tabs have no Web Locks', () => {
+ it('does not drain one session from two windows at the same time', async () => {
+ hideWebLocks()
+ const restoreStorage = installSharedStorage()
+
+ try {
+ vi.resetModules()
+ const windowA = await import('./composer-queue')
+ vi.resetModules()
+ const windowB = await import('./composer-queue')
+
+ windowA.enqueueQueuedPrompt(SESSION_KEY, { attachments: [], text: 'send once' })
+
+ let inFlight = 0
+ let maxInFlight = 0
+ const seen: string[][] = []
+
+ const drain = async (
+ queue: { id: string; text: string }[],
+ owner: { removeQueuedPrompt: typeof windowA.removeQueuedPrompt }
+ ) => {
+ inFlight += 1
+ maxInFlight = Math.max(maxInFlight, inFlight)
+ seen.push(queue.map(entry => entry.text))
+ await new Promise(resolve => setTimeout(resolve, 40))
+ const head = queue[0]
+
+ if (head) {
+ owner.removeQueuedPrompt(SESSION_KEY, head.id)
+ }
+
+ inFlight -= 1
+ }
+
+ await Promise.all([
+ windowA.withQueueDrainClaim(SESSION_KEY, queue => drain(queue, windowA)),
+ windowB.withQueueDrainClaim(SESSION_KEY, queue => drain(queue, windowB))
+ ])
+
+ expect(maxInFlight).toBe(1)
+ expect(seen).toEqual([['send once'], []])
+ expect(windowB.getQueuedPrompts(SESSION_KEY)).toEqual([])
+ } finally {
+ Reflect.deleteProperty(navigator, 'locks')
+ restoreStorage()
+ }
+ })
+
+ it('lets the other window drain once a crashed holder lease expires', async () => {
+ hideWebLocks()
+ const restoreStorage = installSharedStorage()
+ let entered = false
+
+ let finishHolder = () => {}
+ let holder: Promise<unknown> = Promise.resolve()
+
+ try {
+ vi.resetModules()
+ const windowA = await import('./composer-queue')
+ vi.resetModules()
+ const windowB = await import('./composer-queue')
+
+ holder = windowA.withQueueDrainClaim(
+ SESSION_KEY,
+ () =>
+ new Promise<void>(resolve => {
+ entered = true
+ finishHolder = resolve
+ })
+ )
+ await vi.waitFor(() => expect(entered).toBe(true))
+ expect(expireLiveLeases()).toBeGreaterThan(0)
+
+ let drained = false
+
+ await windowB.withQueueDrainClaim(SESSION_KEY, async () => {
+ drained = true
+ })
+ expect(drained).toBe(true)
+ } finally {
+ finishHolder()
+ await holder
+ Reflect.deleteProperty(navigator, 'locks')
+ restoreStorage()
+ }
+ })
+
+ it('keeps Web Locks when the browser provides them', async () => {
+ const request = vi.fn((_name: string, callback: () => Promise<unknown>) => callback())
+
+ Object.defineProperty(navigator, 'locks', { configurable: true, value: { request } })
+
+ try {
+ const before = Array.from({ length: window.localStorage.length }, (_, index) => window.localStorage.key(index))
+
+ await expect(withQueueDrainClaim(SESSION_KEY, async () => 'done')).resolves.toBe('done')
+ expect(request).toHaveBeenCalledTimes(1)
+ expect(request.mock.calls[0]?.[0]).toBe(`${QUEUE_STORAGE_KEY}.drain.${SESSION_KEY}`)
+
+ const after = Array.from({ length: window.localStorage.length }, (_, index) => window.localStorage.key(index))
+
+ expect(after.filter(key => !before.includes(key))).toEqual([])
+ } finally {
+ Reflect.deleteProperty(navigator, 'locks')
+ }
+ })
+})
diff --git a/apps/desktop/src/store/composer-queue.ts b/apps/desktop/src/store/composer-queue.ts
index e3240c6f851..3345fa31962 100644
--- a/apps/desktop/src/store/composer-queue.ts
+++ b/apps/desktop/src/store/composer-queue.ts
@@ -1,6 +1,8 @@
import { SLASH_COMMAND_RE } from '@hermes/shared'
import { atom } from 'nanostores'
+import { withPlainHttpTabLease } from '@/lib/plain-http-tab-lease'
+
import {
type ComposerAttachment,
draftHasTerminalChips,
@@ -340,13 +342,16 @@ export const getQueuedPrompts = (key: string | null | undefined): QueuedPromptEn
* them submitting the same entry — and the gateway runs the second copy as its
* own turn. Web Locks are arbitrated by the browser across windows and freed if
* the holder closes; a waiting window then finds an entry the holder sent
- * already gone. Without Web Locks there is no other window to exclude.
+ * already gone. Plain HTTP is not a secure context, so `navigator.locks` is
+ * missing there, but two tabs still share the origin. A localStorage lease
+ * is the claim in that case. Electron and HTTPS keep Web Locks.
*/
export const withQueueDrainClaim = <T>(sid: string, task: (queue: QueuedPromptEntry[]) => Promise<T>): Promise<T> => {
const run = () => task(current()[sid] ?? [])
+ const name = `${STORAGE_KEY}.drain.${sid}`
const locks = typeof navigator === 'undefined' ? undefined : navigator.locks
- return locks ? locks.request(`${STORAGE_KEY}.drain.${sid}`, run) : run()
+ return locks ? locks.request(name, run) : withPlainHttpTabLease(name, run)
}
export const enqueueQueuedPrompt = (