Skip to content

The agent that grows with you

fix(webapp): give each send its own retry record when Web Locks are missing

Adolaniuma0e0b72e3bb6
diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/prepared-submission-windows.test.tsx b/apps/desktop/src/app/session/hooks/use-prompt-actions/prepared-submission-windows.test.tsx
index 9f58c3e6bd0..3505702f76c 100644
--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/prepared-submission-windows.test.tsx
+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/prepared-submission-windows.test.tsx
@@ -4,7 +4,7 @@ import { afterEach, expect, it, vi } from 'vitest'
import { en } from '@/i18n/en'
import { createClientSessionState } from '@/lib/chat-runtime'
-import type { GatewayRequest } from './utils'
+import type { GatewayRequest, SubmitTextOptions } from './utils'
vi.mock('@/store/gateway', async original => ({
...(await original<Record<string, unknown>>()),
@@ -58,7 +58,7 @@ async function openWindow(submit: (params: Record<string, unknown>) => unknown)
const hook = renderHook(() => useSubmitPrompt(deps))
- return { send: (text: string, options?: { submission_id: string }) => act(async () => hook.result.current(text, options)) }
+ return { send: (text: string, options?: SubmitTextOptions) => act(async () => hook.result.current(text, options)) }
}
afterEach(() => {
@@ -94,3 +94,32 @@ it('two windows sending the same text keep separate identities; only the writer
expect(await first.send('same text', { submission_id: ids[0] })).toBe(true)
expect(ids[2]).toBe(ids[0])
})
+
+it('without Web Locks, a slash command sent from two tabs keeps each tab its own retry record', async () => {
+ // A plain-HTTP origin other than loopback: no Web Locks and no crypto.randomUUID.
+ vi.stubGlobal('crypto', { getRandomValues: crypto.getRandomValues.bind(crypto) })
+ const sent: unknown[][] = []
+ let loseAck = true
+
+ const admit = (params: Record<string, unknown>) => {
+ sent.push([params.submission_id, params.text])
+
+ if (loseAck) { loseAck = false; throw new Error('connection closed') }
+
+ return { admission_id: params.submission_id, status: 'started' }
+ }
+
+ try {
+ const first = await openWindow(admit)
+ expect(await first.send('expanded skill', { retryText: '/skill task', submission_id: 'first' })).toBe(false)
+
+ const second = await openWindow(admit)
+ expect(await second.send('expanded skill', { retryText: '/skill task', submission_id: 'second' })).toBe(true)
+
+ // The first tab's retry re-sends its retained expansion under its own id, never a new expansion.
+ expect(await first.send('expanded again', { retryText: '/skill task', submission_id: 'first' })).toBe(true)
+ expect(sent).toEqual([['first', 'expanded skill'], ['second', 'expanded skill'], ['first', 'expanded skill']])
+ } finally {
+ vi.unstubAllGlobals()
+ }
+})
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 802b1a00182..3f787991de9 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
@@ -48,171 +48,37 @@ test('native preparation waits for acknowledgement and never downgrades a write
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')
+// One browser tab: its own module instance over the origin's shared localStorage.
+async function openTab() {
vi.resetModules()
- const windowB = await import('./prepared-submissions')
- return { windowA, windowB }
+ return import('./prepared-submissions')
}
-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()
+test('tabs without Web Locks never share one slash command retry record', async () => {
+ // A plain-HTTP origin other than loopback: no Web Locks and no crypto.randomUUID.
+ Object.defineProperty(navigator, 'locks', { configurable: true, value: undefined })
+ vi.stubGlobal('crypto', { getRandomValues: crypto.getRandomValues.bind(crypto) })
vi.stubGlobal('hermesDesktop', undefined)
- const restoreStorage = installSharedStorage()
+ const destination = { scopeKey: 'webapp::default' } as SubmissionDestination
+ // A slash command's intent carries no submission id, so every tab builds the same one.
const intent = preparedSubmissionKey('stored', destination, '/skill task', [], { retryText: '/skill task' })
+ const owner = { connectionId: 'local', profile: 'default' }
+ const entry = (id: string): PreparedSubmission => ({ id, text: `expansion ${id}`, attachments: [], params: { submission_id: id }, owner })
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')
+ const [tabA, tabB, tabC] = [await openTab(), await openTab(), await openTab()]
+ // A and B reserve before either writes; C reserves once A's entry is in the journal.
+ const [slotA, slotB] = await Promise.all([tabA.preparedSubmissionSlot(intent), tabB.preparedSubmissionSlot(intent)])
+ await tabA.writePreparedSubmission(slotA, entry('a'))
+ await tabB.writePreparedSubmission(slotB, entry('b'))
+ const slotC = await tabC.preparedSubmissionSlot(intent)
+ await tabC.writePreparedSubmission(slotC, entry('c'))
+
+ // B and C were acknowledged. A's acknowledgement was lost: its retry still finds its own expansion.
+ await tabB.removePreparedSubmission(slotB, 'b')
+ await tabC.removePreparedSubmission(slotC, 'c')
+ expect((await tabA.adoptPreparedSubmission(intent, 'a'))?.entry.text).toBe('expansion a')
} 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 d6217216980..2714422eb5e 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,4 +1,3 @@
-import { tryPlainHttpTabLease } from '@/lib/plain-http-tab-lease'
import type { ComposerAttachment } from '@/store/composer'
import type { SessionOwnerScope } from '@/store/session-request-router'
@@ -156,26 +155,29 @@ export async function readPreparedSubmission(key: string): Promise<PreparedSubmi
return (await readJournal())[key]
}
-// 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.
+// 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.
+// Web Locks exist only in secure contexts, so the Webapp served over plain HTTP to a
+// non-loopback address has none, while its tabs still share this journal. The browser gives
+// such a page no other atomic cross-tab primitive, so nothing is excluded there; each step is
+// safe to run in two tabs instead. A new send gets a key no other send uses
+// (preparedSubmissionSlot). Adoption matches an exact submission id, so two tabs that adopt one
+// entry both send its retained request id and payload, which the gateway admits once.
const owned = new Map<string, () => void>()
+const webLocks = () => (typeof navigator === 'undefined' ? undefined : navigator.locks)
+
function holdPreparedSubmission(key: string): Promise<boolean> {
- const locks = typeof navigator === 'undefined' ? undefined : navigator.locks
+ const locks = webLocks()
if (owned.has(key)) { return Promise.resolve(true) }
if (!locks) {
- return tryPlainHttpTabLease(`${STORAGE_KEY}.${key}`).then(release => {
- if (!release) { return false }
-
- owned.set(key, release)
+ owned.set(key, () => undefined)
- return true
- })
+ return Promise.resolve(true)
}
return new Promise<boolean>(acquired => {
@@ -204,7 +206,7 @@ const sameDestination = (intent: string, key: string) => {
/** The retained entry an explicit retry may reuse: the one carrying exactly `submissionId` on the
* same destination (scope + session) as `intent`, held by this window or left by a closed one.
* Equal text never selects an entry: a new message is a new intent even when it repeats an
- * uncertain one, and a live other window's uncertain send is never adopted. */
+ * uncertain one. With Web Locks, a live other window's uncertain send is never adopted. */
export async function adoptPreparedSubmission(
intent: string,
submissionId: string
@@ -222,9 +224,16 @@ export async function adoptPreparedSubmission(
return undefined
}
+// `crypto.randomUUID` exists only in secure contexts; `getRandomValues` exists in every context.
+const sendNonce = () => Array.from(crypto.getRandomValues(new Uint8Array(16)), byte => byte.toString(16).padStart(2, '0')).join('')
+
/** A journal key for a NEW send of `intent`, held by this window. Never another live window's
- * entry, so a separate send from another window cannot overwrite or share its identity. */
+ * entry, so a separate send from another window cannot overwrite or share its identity. Without
+ * Web Locks no window can tell which keys a live one holds, so every send gets a fresh key: a
+ * slash command's intent carries no submission id, and two tabs would otherwise share it. */
export async function preparedSubmissionSlot(intent: string): Promise<string> {
+ if (!webLocks()) { return JSON.stringify([...JSON.parse(intent), sendNonce()]) }
+
if (!(await readJournal())[intent] && (await holdPreparedSubmission(intent))) { return intent }
const key = JSON.stringify([...JSON.parse(intent), crypto.randomUUID()])
await holdPreparedSubmission(key)
diff --git a/apps/desktop/src/lib/plain-http-tab-lease.ts b/apps/desktop/src/lib/plain-http-tab-lease.ts
deleted file mode 100644
index 0ab1135fc78..00000000000
--- a/apps/desktop/src/lib/plain-http-tab-lease.ts
+++ /dev/null
@@ -1,251 +0,0 @@
-// 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 52a609163c5..09da587b26c 100644
--- a/apps/desktop/src/store/composer-queue.test.ts
+++ b/apps/desktop/src/store/composer-queue.test.ts
@@ -20,8 +20,7 @@ import {
simulateComposerQueueReloadForTests,
unparkQueuedPrompts,
updateQueuedPrompt,
- updateQueuedPromptText,
- withQueueDrainClaim
+ updateQueuedPromptText
} from './composer-queue'
const SESSION_KEY = 'session-abc'
@@ -577,186 +576,3 @@ 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 3345fa31962..aa5f21c7785 100644
--- a/apps/desktop/src/store/composer-queue.ts
+++ b/apps/desktop/src/store/composer-queue.ts
@@ -1,8 +1,6 @@
import { SLASH_COMMAND_RE } from '@hermes/shared'
import { atom } from 'nanostores'
-import { withPlainHttpTabLease } from '@/lib/plain-http-tab-lease'
-
import {
type ComposerAttachment,
draftHasTerminalChips,
@@ -342,16 +340,18 @@ 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. 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.
+ * already gone. Web Locks exist only in secure contexts: the Webapp served over
+ * plain HTTP to a non-loopback address has none, nothing here excludes its other
+ * tabs, and two of them can submit one entry. Both copies carry the entry id as
+ * their submission id, and the Webapp always dials the canonical gateway, which
+ * answers a repeated request id carrying the same payload with the first
+ * admission, not a second turn.
*/
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(name, run) : withPlainHttpTabLease(name, run)
+ return locks ? locks.request(`${STORAGE_KEY}.drain.${sid}`, run) : run()
}
export const enqueueQueuedPrompt = (