The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): same-text sends from two windows stay separate turns
Teknium38a36f467491
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.tsxnew file mode 100644index 00000000000..60990d35db2--- /dev/null+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/prepared-submission-windows.test.tsx@@ -0,0 +1,96 @@+import { act, cleanup, renderHook } from '@testing-library/react'+import { afterEach, expect, it, vi } from 'vitest'++import { en } from '@/i18n/en'+import { createClientSessionState } from '@/lib/chat-runtime'++import type { GatewayRequest } from './utils'++vi.mock('@/store/gateway', async original => ({+ ...(await original<Record<string, unknown>>()),+ retainGatewayForSessionTurn: vi.fn(async () => () => undefined)+}))++// Web Locks as Chromium arbitrates them across the windows of one origin: a held+// lock is visible to every window until its holder releases it or goes away.+function sharedLocks() {+ const held = new Set<string>()++ return {+ query: async () => ({ held: [...held].map(name => ({ name })) }),+ request: async (name: string, ...rest: unknown[]) => {+ const callback = rest.at(-1) as (lock: { name: string } | null) => Promise<unknown>+ const options = (rest.length > 1 ? rest[0] : {}) as { ifAvailable?: boolean }++ if (held.has(name) && options.ifAvailable) { return callback(null) }+ held.add(name)++ try { return await callback({ name }) } finally { held.delete(name) }+ }+ }+}++// One Desktop window: its own module graph (renderer), the shared journal and locks.+async function openWindow(submit: (params: Record<string, unknown>) => unknown) {+ vi.resetModules()+ const { useSubmitPrompt } = await import('./submit')++ const requestGateway = vi.fn(async (method: string, params?: Record<string, unknown>) =>+ (method === 'prompt.submit' ? submit(params!) : {}) as never)++ const state = createClientSessionState()++ const deps = {+ activeSessionIdRef: { current: 'runtime-a' as string | null },+ selectedStoredSessionIdRef: { current: 'stored-a' as string | null },+ busyRef: { current: false },+ copy: en.desktop,+ createBackendSessionForSend: vi.fn(async () => null),+ getRoutedStoredSessionId: () => null,+ getRuntimeIdForStoredSession: () => 'runtime-a',+ getRouteToken: () => 'same-route',+ requestGateway: requestGateway as GatewayRequest,+ runtimeIdByStoredSessionIdRef: { current: new Map([['stored-a', 'runtime-a']]) },+ resumeStoredSession: vi.fn(),+ syncAttachmentsForSubmit: vi.fn(async (sessionId: string) => ({ sessionId, attachments: [] })),+ updateSessionState: vi.fn((_sid, updater) => updater(state))+ }++ const hook = renderHook(() => useSubmitPrompt(deps))++ return { send: (text: string) => act(async () => hook.result.current(text)) }+}++afterEach(() => {+ cleanup()+ Reflect.deleteProperty(navigator, 'locks')+ window.localStorage.clear()+})++it('two windows sending the same text keep separate identities; only the writer retries its own', async () => {+ Object.defineProperty(navigator, 'locks', { configurable: true, value: sharedLocks() })+ window.localStorage.clear()+ const ids: string[] = []+ let loseAck = true++ const admit = (params: Record<string, unknown>) => {+ ids.push(String(params.submission_id))++ if (loseAck) { loseAck = false; throw new Error('connection closed') }++ return { admission_id: params.submission_id, status: 'started' }+ }++ const first = await openWindow(admit)+ expect(await first.send('same text')).toBe(false)++ const second = await openWindow(admit)+ expect(await second.send('same text')).toBe(true)+ // A separate send from a live other window is its own turn, never a retry of the uncertain one,+ // and its acknowledgement must not erase the identity the first window still needs.+ expect(ids[1]).not.toBe(ids[0])++ // The writer's explicit retry reuses its own retained identity.+ expect(await first.send('same text')).toBe(true)+ expect(ids[2]).toBe(ids[0])+})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.tsindex 5268a0fbca6..c5e802c57df 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@@ -71,6 +71,63 @@ export async function readPreparedSubmission(key: string): Promise<PreparedSubmireturn (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.+const owned = new Map<string, () => void>()++function holdPreparedSubmission(key: string): Promise<boolean> {+ const locks = typeof navigator === 'undefined' ? undefined : navigator.locks++ if (owned.has(key)) { return Promise.resolve(true) }++ if (!locks) {+ owned.set(key, () => undefined)++ return Promise.resolve(true)+ }++ return new Promise<boolean>(acquired => {+ void locks.request(`${STORAGE_KEY}.${key}`, { ifAvailable: true }, lock => {+ if (!lock) {+ acquired(false)++ return null+ }++ return new Promise<void>(release => {+ owned.set(key, release)+ acquired(true)+ })+ })+ })+}++const intentVariant = (intent: string, key: string) => key === intent || key.startsWith(`${intent.slice(0, -1)},`)++/** The retained entry an explicit retry of `intent` may reuse: this window's own, or one a+ * closed window left. A live other window's uncertain send is never adopted. */+export async function adoptPreparedSubmission(intent: string): Promise<{ key: string; entry: PreparedSubmission } | undefined> {+ const journal = await readJournal()++ for (const key of Object.keys(journal).filter(key => intentVariant(intent, key)).sort()) {+ if (await holdPreparedSubmission(key)) { return { key, entry: journal[key] } }+ }++ return undefined+}++/** 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. */+export async function preparedSubmissionSlot(intent: string): Promise<string> {+ if (!(await readJournal())[intent] && (await holdPreparedSubmission(intent))) { return intent }+ const key = JSON.stringify([...JSON.parse(intent), crypto.randomUUID()])+ await holdPreparedSubmission(key)++ return key+}+export async function writePreparedSubmission(key: string, entry: PreparedSubmission): Promise<void> {const native = window.hermesDesktop?.preparedSubmissions@@ -92,11 +149,12 @@ export async function removePreparedSubmission(key: string): Promise<void> {if (native) {await native.update(key, null)-- return+ } else {+ const journal: Record<string, PreparedSubmission> = JSON.parse(window.localStorage.getItem(STORAGE_KEY) || '{}')+ delete journal[key]+ window.localStorage.setItem(STORAGE_KEY, JSON.stringify(journal))}- const journal: Record<string, PreparedSubmission> = JSON.parse(window.localStorage.getItem(STORAGE_KEY) || '{}')- delete journal[key]- window.localStorage.setItem(STORAGE_KEY, JSON.stringify(journal))+ owned.get(key)?.()+ owned.delete(key)}diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/slash.ts b/apps/desktop/src/app/session/hooks/use-prompt-actions/slash.tsindex a050687fe90..9f5992462a3 100644--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/slash.ts+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/slash.ts@@ -68,7 +68,7 @@ import type {SlashExecResponse} from '../../../types'-import { preparedSubmissionKey, readPreparedSubmission } from './prepared-submissions'+import { adoptPreparedSubmission, preparedSubmissionKey } from './prepared-submissions'import { queueKickoffIfSessionBusy } from './queue-if-busy'import { resolveTargetSessionId } from './resolve-target-session'import { captureSubmissionDestination } from './submission-destination'@@ -229,6 +229,7 @@ export function useSlashCommand(deps: SlashCommandDeps) {options?.destination ?? captureSubmissionDestination(initialStoredId ?? initialRuntimeId, ambientRequestGateway)const requestGateway = destination.requestGateway+// `hidden` (the first-run `/initiate-setup`) types the saved user row hidden: no bubble, live// or after a reload. It rides retryOptions so a prepared-submission retry stays hidden too.const retryOptions = {@@ -238,7 +239,7 @@ export function useSlashCommand(deps: SlashCommandDeps) {}try {- const prepared = await readPreparedSubmission(+ const prepared = (await adoptPreparedSubmission(preparedSubmissionKey(resolveComposerSessionKey(initialStoredId ?? initialRuntimeId, $sessions.get()),destination,@@ -246,7 +247,7 @@ export function useSlashCommand(deps: SlashCommandDeps) {options?.attachments ?? $composerAttachments.get(),retryOptions)- )+ ))?.entryif (prepared) {return await submitPromptText(prepared.text, {diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/submit.ts b/apps/desktop/src/app/session/hooks/use-prompt-actions/submit.tsindex 320157160ed..15ad4a8517b 100644--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/submit.ts+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/submit.ts@@ -48,8 +48,10 @@ import type { CreateBackendSessionForSend } from '../use-session-actions/create-import { resolveSessionOwner, resolveSessionProfile } from '../use-session-actions/utils'import {+ adoptPreparedSubmission,+ type PreparedSubmission,preparedSubmissionKey,- readPreparedSubmission,+ preparedSubmissionSlot,removePreparedSubmission,writePreparedSubmission} from './prepared-submissions'@@ -438,10 +440,13 @@ export function useSubmitPrompt(deps: SubmitPromptDeps) {)let startingRouteToken = getRouteToken()- let retained: Awaited<ReturnType<typeof readPreparedSubmission>>+ let retained: PreparedSubmission | undefined+ let retainedKey: string | undefinedtry {- retained = await readPreparedSubmission(retryKeyForTarget())+ const adopted = await adoptPreparedSubmission(retryKeyForTarget())+ retained = adopted?.entry+ retainedKey = adopted?.key// A legacy send has no deduplication identity. After an ambiguous ACK// even an upgraded server cannot safely admit it under the saved ID.@@ -1068,7 +1073,7 @@ export function useSubmitPrompt(deps: SubmitPromptDeps) {params: submitParams(liveSessionId)}- const retryKey = retryKeyForTarget()+ const retryKey = retainedKey ?? (await preparedSubmissionSlot(retryKeyForTarget()))await writePreparedSubmission(retryKey, prepared)if (sessionDriftReason()) {