The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(webapp): send from plain-HTTP origins without losing the draft
dokterdok4ca9b11ccfce
diff --git a/apps/desktop/eslint.config.mjs b/apps/desktop/eslint.config.mjsindex 5d86f89ad25..1a9728a8e12 100644--- a/apps/desktop/eslint.config.mjs+++ b/apps/desktop/eslint.config.mjs@@ -40,6 +40,21 @@ export default ['no-restricted-globals': ['warn', 'document']}},+ {+ // crypto.randomUUID is secure-context-only: a Webapp opened over plain HTTP from another+ // machine has none, so every id minted with it threw and nothing was sent.+ files: ['src/**/*.{ts,tsx}'],+ ignores: ['src/**/*.test.{ts,tsx}'],+ rules: {+ 'no-restricted-properties': [+ 'error',+ {+ property: 'randomUUID',+ message: 'Use randomUuid from @hermes/shared (plugins: @hermes/plugin-sdk); it works on insecure origins.'+ }+ ]+ }+ },{// Ban mirroring reactive values into refs via useEffect — the "atom-mirrored// ref" antipattern. A ref synced from a nanostores atom via useEffect lags thediff --git a/apps/desktop/src/api/canonical-protocol.test.ts b/apps/desktop/src/api/canonical-protocol.test.tsindex 9be58a6f092..ad967256b7f 100644--- a/apps/desktop/src/api/canonical-protocol.test.ts+++ b/apps/desktop/src/api/canonical-protocol.test.ts@@ -1,4 +1,4 @@-import { expect, test } from 'vitest'+import { expect, test, vi } from 'vitest'import { CanonicalDesktopProtocol } from './canonical-protocol'@@ -252,3 +252,25 @@ test('a message-level branch carries its durable boundary row; a whole-chat branexpect(() => protocol.prepare('session.branch', { session_id: 's', count: 2 })).toThrow(/not saved yet/)expect(protocol.prepare('session.branch', { session_id: 's' })).toMatchObject({ payload: {} })})++test('mints v4 create, submit and mutation ids where crypto.randomUUID is absent (plain-HTTP LAN origin)', () => {+ const V4 = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/+ vi.stubGlobal('crypto', { getRandomValues: crypto.getRandomValues.bind(crypto) })++ try {+ const protocol = new CanonicalDesktopProtocol()+ protocol.result('session.resume', { profile: 'default', session_id: 's' }, { session_id: 's', revision: 2, execution_generation: 3 })++ const cases: Array<[string, Record<string, unknown>, string]> = [+ ['session.create', { profile: 'default', source: 'desktop' }, 'request_id'],+ ['prompt.submit', { profile: 'default', session_id: 's', text: 'hi' }, 'submission_id'],+ ['session.title', { profile: 'default', session_id: 's', title: 't' }, 'request_id']+ ]++ for (const [method, params, key] of cases) {+ expect(JSON.stringify(protocol.prepare(method, params)).match(new RegExp(`"${key}":"([^"]+)"`))?.[1]).toMatch(V4)+ }+ } finally {+ vi.unstubAllGlobals()+ }+})diff --git a/apps/desktop/src/api/canonical-protocol.ts b/apps/desktop/src/api/canonical-protocol.tsindex 0a16a701035..4450f76eb6a 100644--- a/apps/desktop/src/api/canonical-protocol.ts+++ b/apps/desktop/src/api/canonical-protocol.ts@@ -1,6 +1,8 @@// Canonical local authority wire adapter. Remote legacy transports keep their// existing protocol; unsupported explicit semantics fail before network admission.+import { randomUuid } from '@hermes/shared'+export const CANONICAL_GATEWAY_PROTOCOL = 'hermes-gateway-v1'/** Dial `/api/ws` or a sibling stream beside it. A local gateway's one-use ticket leaves the URL@@ -209,7 +211,7 @@ function canonicalProducerFrame(method: string, params: Record<string, unknown>)// The owner admits identified input only. An identityless producer (session tile, quick entry,// bot chats) is a fresh send on every call, which is what the legacy wire did with it.- if (method === 'prompt.submit' && !params.submission_id && !params.input_id) { return { ...params, submission_id: crypto.randomUUID() } }+ if (method === 'prompt.submit' && !params.submission_id && !params.input_id) { return { ...params, submission_id: randomUuid() } }return method === 'bot_relay.deliver' ? canonicalBotDelivery(params) : params}@@ -335,7 +337,7 @@ export class CanonicalDesktopProtocol {if (withGeneration && generation === undefined) { throw new Error('Session execution identity unavailable; reconnect before this command') }- const mutation: Record<string, unknown> = { session_id: sessionId, request_id: crypto.randomUUID(), expected_revision: revision,+ const mutation: Record<string, unknown> = { session_id: sessionId, request_id: randomUuid(), expected_revision: revision,...(withGeneration ? { expected_generation: generation } : {}), operation, payload }this.mutations.set(key, mutation)@@ -537,7 +539,7 @@ export class CanonicalDesktopProtocol {['request_id', 'cwd', 'model', 'provider', 'toolsets', 'reasoning', 'title', 'hidden', 'follow_profile_config', 'service_tier', 'cwd_explicit'].includes(key) || (key === 'profile' && typeof value === 'string' && value !== '')))const key = JSON.stringify(result)- const requestId = params.request_id ?? this.creates.get(key) ?? crypto.randomUUID()+ const requestId = params.request_id ?? this.creates.get(key) ?? randomUuid()this.creates.set(key, String(requestId))return { ...result, request_id: requestId, source: 'gui' }diff --git a/apps/desktop/src/app/chat/composer/hooks/use-composer-queue.ts b/apps/desktop/src/app/chat/composer/hooks/use-composer-queue.tsindex 88de17bec64..3b5dcefc0c4 100644--- a/apps/desktop/src/app/chat/composer/hooks/use-composer-queue.ts+++ b/apps/desktop/src/app/chat/composer/hooks/use-composer-queue.ts@@ -1,3 +1,4 @@+import { randomUuid } from '@hermes/shared'import { useStore } from '@nanostores/react'import { type RefObject, useCallback, useEffect, useRef, useState } from 'react'@@ -320,7 +321,7 @@ export function useComposerQueue({const retained = unconfirmedRef.currentconst submissionId =- retained?.admissionId === entryId && retained.edited === edited ? retained.submissionId : crypto.randomUUID()+ retained?.admissionId === entryId && retained.edited === edited ? retained.submissionId : randomUuid()serverSaveRef.current = savediff --git a/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.test.tsx b/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.test.tsxindex 5b5dbd4989e..f3411c27494 100644--- a/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.test.tsx+++ b/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.test.tsx@@ -1114,3 +1114,43 @@ describe('useComposerSubmit with a setup card waiting in the onboarding chat', (expect(onSubmit).toHaveBeenCalledWith('/help', expect.anything())})})++describe('useComposerSubmit on an insecure origin (plain-HTTP LAN: no crypto.randomUUID)', () => {+ const V4 = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/++ beforeEach(() => vi.stubGlobal('crypto', { getRandomValues: crypto.getRandomValues.bind(crypto) }))++ afterEach(() => {+ cleanup()+ vi.unstubAllGlobals()+ })++ it('sends a fresh draft with a v4 submission_id', async () => {+ const { hook, onSubmit } = renderSubmitHook({ text: 'hello from the LAN' })++ act(() => hook.result.current.submitDraft())+ await waitFor(() => expect(onSubmit).toHaveBeenCalledTimes(1))+ expect(onSubmit.mock.calls[0]).toEqual([+ 'hello from the LAN',+ expect.objectContaining({ submission_id: expect.stringMatching(V4) })+ ])+ })++ it('puts the draft back when preparing the send throws', async () => {+ const attachment = { id: 'file-1', kind: 'file', label: 'notes.txt', path: '/work/notes.txt' } as ComposerAttachment++ const { clearDraft, hook, loadIntoComposer, onSubmit, stashAt } = renderSubmitHook({+ attachments: [attachment],+ text: 'keep these words'+ })++ onSubmit.mockImplementation(() => {+ throw new TypeError('preparation failed')+ })++ act(() => hook.result.current.submitDraft())+ expect(clearDraft).toHaveBeenCalledTimes(1)+ await waitFor(() => expect(loadIntoComposer).toHaveBeenCalledWith('keep these words', [attachment]))+ expect(stashAt).toHaveBeenCalledWith('stored-session', 'keep these words', [attachment])+ })+})diff --git a/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.ts b/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.tsindex 5d71745743c..b7e1b8b35ab 100644--- a/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.ts+++ b/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.ts@@ -1,4 +1,4 @@-import { SLASH_COMMAND_RE } from '@hermes/shared'+import { randomUuid, SLASH_COMMAND_RE } from '@hermes/shared'import { type RefObject, useLayoutEffect, useRef } from 'react'import { usePaneVisible } from '@/components/pane-shell/pane-visibility'@@ -156,7 +156,7 @@ export function useComposerSubmit({// The composer owns this send's identity: the caller's (a queue entry), the restored draft's// (the explicit retry), else a new one. Equal text never inherits an identity, so a new// message that repeats an uncertain send, in this pane or another, is its own turn.- const submissionId = target?.submission_id ?? crypto.randomUUID()+ const submissionId = target?.submission_id ?? randomUuid()const restore = () => {stashAt(restoreScope, text, submittedAttachments)@@ -172,15 +172,19 @@ export function useComposerSubmit({// typed), so a rejection drops it instead of loading it into the draft.const rejected = displayKind ? () => {} : restore- void Promise.resolve(- onSubmit(text, {- ...target,- submission_id: submissionId,- ...(attachments ? { attachments } : {}),- composerScope: submittedScope,- ...assignment,- ...(displayKind ? { displayKind } : {})- })+ // A synchronous throw takes the rejection path too: the caller has already cleared the+ // composer, so a send that fails while it is being prepared must not take the words with it.+ void new Promise<boolean>(resolve =>+ resolve(+ onSubmit(text, {+ ...target,+ submission_id: submissionId,+ ...(attachments ? { attachments } : {}),+ composerScope: submittedScope,+ ...assignment,+ ...(displayKind ? { displayKind } : {})+ })+ )).then(accepted => {if (accepted === false) {diff --git a/apps/desktop/src/app/gateway/report-startup-latency.ts b/apps/desktop/src/app/gateway/report-startup-latency.tsindex 9e13e6bbba6..9c596d5b6aa 100644--- a/apps/desktop/src/app/gateway/report-startup-latency.ts+++ b/apps/desktop/src/app/gateway/report-startup-latency.ts@@ -1,3 +1,5 @@+import { randomUuid } from '@hermes/shared'+type GatewayRequest = (method: 'shared_metrics.startup_latency',params: { elapsed_ms: number; launch_id: string; surface: 'desktop_attach' }@@ -21,7 +23,7 @@ export async function reportStartupLatency(// Declared, not env-detected: a URL/cloud backend has no HERMES_DESKTOP to tell it who attached.await request('shared_metrics.startup_latency', {elapsed_ms: elapsedMs,- launch_id: crypto.randomUUID(),+ launch_id: randomUuid(),surface: 'desktop_attach'}).catch(() => undefined)}diff --git a/apps/desktop/src/app/right-sidebar/terminal/terminals.ts b/apps/desktop/src/app/right-sidebar/terminal/terminals.tsindex 05af1ff0ebf..65b2c12c1a0 100644--- a/apps/desktop/src/app/right-sidebar/terminal/terminals.ts+++ b/apps/desktop/src/app/right-sidebar/terminal/terminals.ts@@ -1,3 +1,4 @@+import { randomUuid } from '@hermes/shared'import type { WebglAddon } from '@xterm/addon-webgl'import type { Terminal } from '@xterm/xterm'import { atom, computed } from 'nanostores'@@ -258,8 +259,7 @@ export const $activeTerminal = computed((list, id) => list.find(term => term.id === id) ?? null)-const newId = () =>- globalThis.crypto?.randomUUID?.() ?? `term-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`+const newId = () => randomUuid()/** Append a fresh terminal and focus it. Captures the current cwd once (its only* tie to session/project state); pass an explicit cwd to override. Returns the id. */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 b27260e9527..dd190784d0b 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,5 @@+import { randomUuid } from '@hermes/shared'+import type { ComposerAttachment } from '@/store/composer'import type { SessionOwnerScope } from '@/store/session-request-router'@@ -293,7 +295,7 @@ 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()])+ const key = JSON.stringify([...JSON.parse(intent), randomUuid()])await holdPreparedSubmission(key)return keydiff --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 ddd5c8f29c2..5bb14c63cc1 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@@ -1,5 +1,5 @@import { skillInvocationText } from '@hermes/shared'-import { mergeUsage, parseCommandDispatch, parseSlashCommand } from '@hermes/shared'+import { mergeUsage, parseCommandDispatch, parseSlashCommand, randomUuid } from '@hermes/shared'import { type MutableRefObject, useCallback, useRef } from 'react'import { mergeOlderTranscriptPage } from '@/app/chat/transcript-backfill'@@ -268,7 +268,7 @@ export function useSlashCommand(deps: SlashCommandDeps) {return false}- const submissionId = options?.submission_id ?? crypto.randomUUID()+ const submissionId = options?.submission_id ?? randomUuid()// Resolve the session this command targets through the SHARED ladder that// submit.ts uses. A slash command runs backend commands against a runtimediff --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 df0fc7b7c36..3104c497283 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@@ -1,4 +1,4 @@-import type { PromptSubmitResult } from '@hermes/shared'+import { type PromptSubmitResult, randomUuid } from '@hermes/shared'import { type MutableRefObject, useCallback } from 'react'import { getSession, PROMPT_SUBMIT_REQUEST_TIMEOUT_MS } from '@/hermes'@@ -513,7 +513,7 @@ export function useSubmitPrompt(deps: SubmitPromptDeps) {: capturedlet requestGateway = destination.requestGateway- const submissionId = retained?.id ?? options?.submission_id ?? crypto.randomUUID()+ const submissionId = retained?.id ?? options?.submission_id ?? randomUuid()let startingStoredSessionId = routedSessionNeedsResume? routedStoredSessionIddiff --git a/apps/desktop/src/app/session/hooks/use-session-actions/index.ts b/apps/desktop/src/app/session/hooks/use-session-actions/index.tsindex 291480e83ba..104da47602e 100644--- a/apps/desktop/src/app/session/hooks/use-session-actions/index.ts+++ b/apps/desktop/src/app/session/hooks/use-session-actions/index.ts@@ -1,4 +1,4 @@-import { mergeUsage } from '@hermes/shared'+import { mergeUsage, randomUuid } from '@hermes/shared'import { useStore } from '@nanostores/react'import { type MutableRefObject, useCallback, useEffect, useRef } from 'react'import type { NavigateFunction } from 'react-router'@@ -620,7 +620,7 @@ export function useSessionActions({async (preview: string | null = null, createOverrides?: SessionCreateOverrides): Promise<string | null> => {const startingStoredSessionId = selectedStoredSessionIdRef.currentconst startingRouteToken = getRouteToken()- const createIntent = (createIntentRef.current ??= crypto.randomUUID())+ const createIntent = (createIntentRef.current ??= randomUuid())creatingSessionRef.current = true@@ -1076,7 +1076,7 @@ export function useSessionActions({options?.route === null || defaultTarget?.route === null,workspaceScope.workspaceMode !== 'bots')),- request_id: crypto.randomUUID()+ request_id: randomUuid()}// Same lease chain as createBackendSessionForSend: owner socket helddiff --git a/apps/desktop/src/app/settings/billing/api.ts b/apps/desktop/src/app/settings/billing/api.tsindex 348b1f33a86..c6c68334cb1 100644--- a/apps/desktop/src/app/settings/billing/api.ts+++ b/apps/desktop/src/app/settings/billing/api.ts@@ -1,3 +1,4 @@+import { randomUuid } from '@hermes/shared'import { createContext, useContext, useMemo } from 'react'import { useGatewayRequest } from '@/app/gateway/hooks/use-gateway-request'@@ -146,7 +147,7 @@ const callBilling = async <T>(}export const createBillingApi = (requestGateway: BillingRequestGateway): BillingApi => ({- charge: async (amountUsd, idempotencyKey = crypto.randomUUID()) => {+ charge: async (amountUsd, idempotencyKey = randomUuid()) => {const result = await callBilling<BillingChargeResponse>(requestGateway, 'billing.charge', {amount_usd: amountUsd,idempotency_key: idempotencyKeydiff --git a/apps/desktop/src/lib/browser-window.ts b/apps/desktop/src/lib/browser-window.tsindex 7a72df971be..c7253513e45 100644--- a/apps/desktop/src/lib/browser-window.ts+++ b/apps/desktop/src/lib/browser-window.ts@@ -1,3 +1,5 @@+import { randomUuid } from '@hermes/shared'+import type { HermesApiRequest } from '@/global'interface BrowserWindowOptions {@@ -15,7 +17,7 @@ export function createBrowserWindowOpener({ api, basePath, privateSession }: Broreturn Promise.resolve({ ok: true })}- const id = crypto.randomUUID()+ const id = randomUuid()const channel = new BroadcastChannel(`hermes.webapp.window:${id}`)const launch = new URL(`${basePath}/webapp/window`, window.location.origin)launch.hash = new URLSearchParams({ channel: id, query: target.search, route: target.hash.slice(1) }).toString()diff --git a/apps/desktop/src/lib/preview-annotate/handoff.ts b/apps/desktop/src/lib/preview-annotate/handoff.tsindex 7040f0f1831..81ef45d2c80 100644--- a/apps/desktop/src/lib/preview-annotate/handoff.ts+++ b/apps/desktop/src/lib/preview-annotate/handoff.ts@@ -1,3 +1,5 @@+import { randomUuid } from '@hermes/shared'+import { queryAllVisible, queryVisible } from '@/components/pane-shell/pane-visibility'import { $workspaceOwnerKey } from '@/components/pane-shell/workspace-scope'@@ -72,8 +74,7 @@ export interface PreviewAnnotateHandoffResult {ok: boolean}-const randomId = () =>- globalThis.crypto?.randomUUID?.() ?? `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`+const randomId = () => randomUuid()/** One id per renderer window. sessionStorage is deliberately window-scoped. */export function previewAnnotateWindowId(): string {diff --git a/apps/desktop/src/plugins/hermes-bots/canonical-group-attachments.test.tsx b/apps/desktop/src/plugins/hermes-bots/canonical-group-attachments.test.tsxindex 93824b078d4..02b3df2d957 100644--- a/apps/desktop/src/plugins/hermes-bots/canonical-group-attachments.test.tsx+++ b/apps/desktop/src/plugins/hermes-bots/canonical-group-attachments.test.tsx@@ -5,7 +5,8 @@ import { afterEach, expect, it, vi } from 'vitest'import { expectDownloaded, observeDownloads } from './canonical-download-test-utils'const request = vi.hoisted(() => vi.fn())-vi.mock('@hermes/plugin-sdk', () => ({+vi.mock('@hermes/plugin-sdk', async () => ({+ randomUuid: (await import('@hermes/shared')).randomUuid,host: { requestProfile: request },Button: (props: ComponentProps<'button'>) => <button {...props} />}))diff --git a/apps/desktop/src/plugins/hermes-bots/canonical-group-attachments.tsx b/apps/desktop/src/plugins/hermes-bots/canonical-group-attachments.tsxindex cce14acdb27..6ad990d7103 100644--- a/apps/desktop/src/plugins/hermes-bots/canonical-group-attachments.tsx+++ b/apps/desktop/src/plugins/hermes-bots/canonical-group-attachments.tsx@@ -1,4 +1,4 @@-import { Button } from '@hermes/plugin-sdk'+import { Button, randomUuid } from '@hermes/plugin-sdk'import { type Ref, useImperativeHandle, useLayoutEffect, useRef, useState } from 'react'import { downloadCanonicalAttachment } from './canonical-attachment-download'@@ -78,7 +78,7 @@ export function CanonicalGroupAttachments({ binding, attachments, onChange, onUp})const result = await canonicalGroupRequest<Attachment>(binding, 'groups.attachment.upload', {- room_id: binding.roomId, upload_id: crypto.randomUUID(), kind: kindFor(file), name: file.name,+ room_id: binding.roomId, upload_id: randomUuid(), kind: kindFor(file), name: file.name,mime: file.type || 'application/octet-stream', data_base64: data})diff --git a/apps/desktop/src/plugins/hermes-bots/canonical-group-history.test.tsx b/apps/desktop/src/plugins/hermes-bots/canonical-group-history.test.tsxindex 2ec34e15647..ebbb3eb5de7 100644--- a/apps/desktop/src/plugins/hermes-bots/canonical-group-history.test.tsx+++ b/apps/desktop/src/plugins/hermes-bots/canonical-group-history.test.tsx@@ -9,7 +9,8 @@ vi.mock('@hermes/plugin-sdk', async () => {const { en } = await import('@/i18n/en')const { Textarea } = await import('@/components/ui/textarea')- return { Textarea, atom: (await import('nanostores')).atom, host: { requestProfile: request }, useI18n: () => ({ locale: 'en', t: en }),+ return { Textarea, atom: (await import('nanostores')).atom, host: { requestProfile: request }, randomUuid: (await import('@hermes/shared')).randomUuid,+ useI18n: () => ({ locale: 'en', t: en }),Button: (props: ComponentProps<'button'>) => <button {...props} />,MessageTextContent: ({ text }: { text: string }) => <div data-testid="markdown">{text}</div>,Streamdown: ({ children }: { children: ReactNode }) => <div data-testid="markdown">{children}</div>,diff --git a/apps/desktop/src/plugins/hermes-bots/canonical-group-send.ts b/apps/desktop/src/plugins/hermes-bots/canonical-group-send.tsindex def4b362a63..b3e017591ed 100644--- a/apps/desktop/src/plugins/hermes-bots/canonical-group-send.ts+++ b/apps/desktop/src/plugins/hermes-bots/canonical-group-send.ts@@ -1,3 +1,5 @@+import { randomUuid } from '@hermes/plugin-sdk'+import type { CanonicalGroupBinding } from './canonical-groups'const STORAGE_KEY = 'hermes.desktop.canonicalGroupSends.v1'@@ -94,7 +96,7 @@ export async function prepareCanonicalGroupSend(if (existing) {return existing}- const eventId = crypto.randomUUID()+ const eventId = randomUuid()const entry: PreparedCanonicalGroupSend = JSON.parse(JSON.stringify({binding,diff --git a/apps/desktop/src/plugins/hermes-bots/canonical-group-workspace.tsx b/apps/desktop/src/plugins/hermes-bots/canonical-group-workspace.tsxindex 3607e8e26e2..3c85c68bd47 100644--- a/apps/desktop/src/plugins/hermes-bots/canonical-group-workspace.tsx+++ b/apps/desktop/src/plugins/hermes-bots/canonical-group-workspace.tsx@@ -1,4 +1,4 @@-import { Button, host } from '@hermes/plugin-sdk'+import { Button, host, randomUuid } from '@hermes/plugin-sdk'import { type ClipboardEvent, type DragEvent, useEffect, useRef, useState } from 'react'import { type CanonicalDriverActivity, CanonicalGroupWorkingLine, canonicalMemberPhases } from './canonical-group-activity'@@ -164,11 +164,11 @@ function CanonicalRoomView({ binding: initialBinding, visible, onBack }: {mutate(() => actCanonicalGroup(binding, action, choice))const rename = (name: string) =>- void mutate(() => canonicalGroupRequest(binding, 'groups.rename', { room_id: binding.roomId, event_id: crypto.randomUUID(), name }))+ void mutate(() => canonicalGroupRequest(binding, 'groups.rename', { room_id: binding.roomId, event_id: randomUuid(), name }))// Rejects so ConfirmDialog stays open with the error; a disbanded room no longer reads back, so leave it.const end = async () => {- await canonicalGroupRequest(binding, 'groups.disband', { room_id: binding.roomId, cancel_id: crypto.randomUUID() })+ await canonicalGroupRequest(binding, 'groups.disband', { room_id: binding.roomId, cancel_id: randomUuid() })if (alive.current) {onBack?.()}forgetCanonicalGroup(binding)@@ -191,7 +191,7 @@ function CanonicalRoomView({ binding: initialBinding, visible, onBack }: {return <section className="flex h-full min-h-0 flex-col gap-3 p-3"><CanonicalGroupHeader busy={busy} canStop={!!state?.driver_status} onBack={onBack} onDisband={end} onRename={rename}- onStop={() => void mutate(() => canonicalGroupRequest(binding, 'groups.stop', { room_id: binding.roomId, cancel_id: crypto.randomUUID() }))} phases={phases} room={state?.room} />+ onStop={() => void mutate(() => canonicalGroupRequest(binding, 'groups.stop', { room_id: binding.roomId, cancel_id: randomUuid() }))} phases={phases} room={state?.room} />{readError && <div role="alert">{readError}<Button onClick={() => void refresh().catch(e => setReadError(String(e)))}>{labels.refresh}</Button></div>}{error && <div role="alert">{error}</div>}{state && !state.driver_status && <p>{labels.driverUnavailable}</p>}diff --git a/apps/desktop/src/plugins/hermes-bots/canonical-groups.test.ts b/apps/desktop/src/plugins/hermes-bots/canonical-groups.test.tsindex 68b35fabf6b..57c65617594 100644--- a/apps/desktop/src/plugins/hermes-bots/canonical-groups.test.ts+++ b/apps/desktop/src/plugins/hermes-bots/canonical-groups.test.ts@@ -6,7 +6,7 @@ const host = vi.hoisted(() => ({state: { connectionId: { get: vi.fn() }, profile: { get: vi.fn() } }}))-vi.mock('@hermes/plugin-sdk', () => ({ host }))+vi.mock('@hermes/plugin-sdk', async () => ({ host, randomUuid: (await import('@hermes/shared')).randomUuid }))import { actCanonicalGroup, canonicalGroupRequest, captureCanonicalGroupRoute, createCanonicalGroup, discoverCanonicalGroups } from './canonical-groups'diff --git a/apps/desktop/src/plugins/hermes-bots/canonical-groups.ts b/apps/desktop/src/plugins/hermes-bots/canonical-groups.tsindex 0d6a02db4cb..5f8daa39e03 100644--- a/apps/desktop/src/plugins/hermes-bots/canonical-groups.ts+++ b/apps/desktop/src/plugins/hermes-bots/canonical-groups.ts@@ -1,4 +1,4 @@-import { host } from '@hermes/plugin-sdk'+import { host, randomUuid } from '@hermes/plugin-sdk'import type { GroupMember } from './types'@@ -138,7 +138,7 @@ export async function createCanonicalGroup(})const { room } = await canonicalGroupRequest<{ room: CanonicalRoom }>(route, 'groups.create', {- room_id: crypto.randomUUID(), name, members: roster+ room_id: randomUuid(), name, members: roster})return { binding: { ...route, roomId: room.room_id }, room }diff --git a/apps/desktop/src/plugins/hermes-bots/group-chat.ts b/apps/desktop/src/plugins/hermes-bots/group-chat.tsindex 13fbfc35d8d..d74f5378cec 100644--- a/apps/desktop/src/plugins/hermes-bots/group-chat.ts+++ b/apps/desktop/src/plugins/hermes-bots/group-chat.ts@@ -9,7 +9,7 @@* store, one writer.*/-import { atom, host } from '@hermes/plugin-sdk'+import { atom, host, randomUuid } from '@hermes/plugin-sdk'import { $botMeta, $lastRoster, botRosterKey } from './data'import { groupMemberReferencesConnection, markOrphanedGroupMemberDescriptor } from './hygiene'@@ -1703,11 +1703,7 @@ export function setGroupChatImage(group: string, image: null | string | undefine}function groupChatEntryId(): string {- if (globalThis.crypto && typeof globalThis.crypto.randomUUID === 'function') {- return globalThis.crypto.randomUUID()- }-- return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`+ return randomUuid()}/** The agent loop's "(empty)" terminal sentinel (empty_response_exhausted) isdiff --git a/apps/desktop/src/plugins/hermes-bots/group-test-utils.ts b/apps/desktop/src/plugins/hermes-bots/group-test-utils.tsindex 29666d6aa20..637c0399f36 100644--- a/apps/desktop/src/plugins/hermes-bots/group-test-utils.ts+++ b/apps/desktop/src/plugins/hermes-bots/group-test-utils.ts@@ -457,6 +457,7 @@ export async function pluginSdkMock(host: Record<string, unknown>) {const nanostores = await import('nanostores')const { Textarea } = await import('@/components/ui/textarea')const { cn } = await import('@/lib/utils')+ const { randomUuid } = await import('@hermes/shared')return {Textarea,@@ -474,6 +475,7 @@ export async function pluginSdkMock(host: Record<string, unknown>) {gatewayActivationEpoch: () => 0,GlyphSpinner: () => null,host,+ randomUuid,CapabilitiesView: undefined,MessageTextContent: undefined,Streamdown: undefined,diff --git a/apps/desktop/src/plugins/hermes-bots/group-turns.ts b/apps/desktop/src/plugins/hermes-bots/group-turns.tsindex 23411aae03c..a391cad00c7 100644--- a/apps/desktop/src/plugins/hermes-bots/group-turns.ts+++ b/apps/desktop/src/plugins/hermes-bots/group-turns.ts@@ -6,7 +6,7 @@* Room-level sequencing lives in group-rounds.ts, which drives these.*/-import { APPROVAL_RESPOND_TIMEOUT_MS, host } from '@hermes/plugin-sdk'+import { APPROVAL_RESPOND_TIMEOUT_MS, host, randomUuid } from '@hermes/plugin-sdk'import { noteBotAttention } from './data'import { groupFailureReason, recordGroupActivity } from './group-activity'@@ -1252,7 +1252,7 @@ async function runGroupChatMemberTurnLeased(runtimeIds.add(liveRuntime)// A UUID, not a clock+random suffix: a marker persisted by a previous process must never equal a token this one mints.- const turn = `${liveRuntime}:${crypto.randomUUID()}`+ const turn = `${liveRuntime}:${randomUuid()}`liveGroupTurns.add(turn)markGroupTurnInFlight(group, member, {before,diff --git a/apps/desktop/src/sdk/index.ts b/apps/desktop/src/sdk/index.tsindex bb29146c118..b4afb8b33d9 100644--- a/apps/desktop/src/sdk/index.ts+++ b/apps/desktop/src/sdk/index.ts@@ -1604,14 +1604,7 @@ export { WorkspacePageHeaderControl } from '@/app/contrib/workspace-page-header'* that prints a next run switches its label on this (`t.cron.next` →* `t.cron.overdueSince`) so a dead scheduler never reads as "Next: 7 hr ago". */export { nextRunOverdueMs } from '@/app/cron/job-state'-/** THE master-detail toolkit core uses for list+inspector surfaces (Scheduled- * jobs, Kanban, …): a dense left `PanelList` of `PanelListRow`s beside a- * scrolling `PanelDetail` of `PanelSectionLabel` / `PanelMeta` / `PanelBlock`.- * `PanelEmpty` is the icon+action empty state (plain `EmptyState` is title +- * description only, and silently drops an `icon`). A row takes a custom `lead`- * (avatar/swatch), trailing `meta`, and `menuItems` for kebab + right-click- * parity, so a roster needs no hand-rolled row. The overlay-bound `Panel` root- * is deliberately NOT exported — these compose inside a pane just as well. */+/** Master-detail components for pane content; the overlay-bound Panel root is deliberately private. */export {PanelAction,PanelAddButton,@@ -1958,6 +1951,9 @@ export { compactNumber } from '@hermes/shared'* `approvals.timeout` (300s) so a plugin answering an approval never rejects* its own RPC while the backend still applies the decision (#60654). */export { APPROVAL_RESPOND_TIMEOUT_MS } from '@hermes/shared'+/** THE id minter: a v4 UUID on every origin. `crypto.randomUUID` exists only in secure contexts,+ * so a Webapp opened over plain HTTP from another machine has none. */+export { randomUuid } from '@hermes/shared'/** Hermes' reasoning levels, so a plugin surfacing a thinking depth uses the* same scale as the rest of the app (labels: `reasoningEffortLabel`). */export {diff --git a/apps/desktop/src/store/composer.ts b/apps/desktop/src/store/composer.tsindex 5478429984a..a2429476efa 100644--- a/apps/desktop/src/store/composer.ts+++ b/apps/desktop/src/store/composer.ts@@ -1,3 +1,4 @@+import { randomUuid } from '@hermes/shared'import { atom } from 'nanostores'import type { HermesStagedUpload } from '@/global'@@ -106,7 +107,7 @@ export const $composerTerminalSelections = atom<Record<string, string>>({})export const $voiceConversationStartRequest = atom(0)let nextVoiceStartRequest = 0let handledVoiceStartRequest = 0-export const createComposerAttachmentOccurrenceId = (): string => crypto.randomUUID()+export const createComposerAttachmentOccurrenceId = (): string => randomUuid()export const requestVoiceConversationStart = (): void => $voiceConversationStartRequest.set(++nextVoiceStartRequest)@@ -270,8 +271,7 @@ export interface SessionDraft {// cannot bleed into the next lifecycle.const FRESH_DRAFT_STORAGE_KEY = 'hermes.desktop.freshDraftKey'-const createFreshDraftKey = (): string =>- `__new__:${globalThis.crypto?.randomUUID?.() ?? `${Date.now()}-${Math.random().toString(36).slice(2)}`}`+const createFreshDraftKey = (): string => `__new__:${randomUuid()}`export const $freshDraftKey = atom<string>(storedString(FRESH_DRAFT_STORAGE_KEY) ?? NEW_SESSION_DRAFT_KEY)diff --git a/apps/desktop/src/store/desktop-metrics.ts b/apps/desktop/src/store/desktop-metrics.tsindex e76db469408..81a46b9a3c6 100644--- a/apps/desktop/src/store/desktop-metrics.ts+++ b/apps/desktop/src/store/desktop-metrics.ts@@ -29,6 +29,7 @@* instead of overwriting each other; the backend latches each day and area once.*/+import { randomUuid } from '@hermes/shared'import { atom } from 'nanostores'import { $workspaceMode } from '@/components/pane-shell/workspace-scope'@@ -358,7 +359,7 @@ export type DesktopMetricsGate = 'off' | 'on' | nullexport const $desktopMetricsGate = atom<DesktopMetricsGate>(null)/** One id per renderer load: an onboarding step still open from another load was abandoned. */-const LAUNCH_ID = typeof crypto !== 'undefined' && 'randomUUID' in crypto ? crypto.randomUUID() : String(Math.random())+const LAUNCH_ID = randomUuid()/** Hash of the bound `connection|profile`: names the local record and main's crash consent. */let scope = scopeKey('|default')diff --git a/apps/desktop/src/store/pet-generate.ts b/apps/desktop/src/store/pet-generate.tsindex fc8f18335d9..67053701737 100644--- a/apps/desktop/src/store/pet-generate.ts+++ b/apps/desktop/src/store/pet-generate.ts@@ -1,3 +1,4 @@+import { randomUuid } from '@hermes/shared'import { atom } from 'nanostores'import { isMissingRpcMethod } from '@/lib/gateway-rpc'@@ -476,7 +477,7 @@ export async function hatchSelected(request: GatewayRequest, options: HatchOptio// Hatch cancellation rides its own token (not the draft token): hatching// mid-generation leaves pet.generate releasing that token, which would race// the arm. The draft token still locates the staged image server-side.- const cancelToken = crypto.randomUUID()+ const cancelToken = randomUuid()const hatchRunId = hatch.begin()const controller = new AbortController()hatch.arm(() => {diff --git a/apps/desktop/src/store/preview.ts b/apps/desktop/src/store/preview.tsindex 22f8f53d804..38b57200dce 100644--- a/apps/desktop/src/store/preview.ts+++ b/apps/desktop/src/store/preview.ts@@ -1,3 +1,4 @@+import { randomUuid } from '@hermes/shared'import { atom, computed } from 'nanostores'import { dismissTreePane, isPaneVisible } from '@/components/pane-shell/tree/store'@@ -853,8 +854,7 @@ const isBrowserTab = (tab: PreviewTab): boolean => tab.target.kind === 'url'* handed out twice, so per-tab state keyed by it (`$browserPages`, the console* buffer) cannot resurface under a later tab if a close ever fails to wipe it. */function mintBrowserTabId(): RightRailTabId {- const unique =- globalThis.crypto?.randomUUID?.() ?? `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`+ const unique = randomUuid()return `url:browser-${unique}`}diff --git a/apps/shared/src/index.ts b/apps/shared/src/index.tsindex b653088776f..17d5a851e10 100644--- a/apps/shared/src/index.ts+++ b/apps/shared/src/index.ts@@ -131,6 +131,7 @@ export {reconnectBackoffDelayMs,type ReconnectBackoffOptions} from './reconnect-backoff'+export { randomUuid } from './session-http-mutations'export { skillInvocationText } from './skill-scaffold'export {type HermesSkin,diff --git a/apps/shared/src/session-http-mutations.ts b/apps/shared/src/session-http-mutations.tsindex b3c0bc95656..a2973ee2da5 100644--- a/apps/shared/src/session-http-mutations.ts+++ b/apps/shared/src/session-http-mutations.ts@@ -31,7 +31,7 @@ export function createSessionMutationClient() {|| (snapshot.exists && (!Number.isSafeInteger(snapshot.runtime_generation) || snapshot.runtime_generation! < 0))) {throw new Error('Session mutation snapshot unavailable; refresh before trying again')}- return { request_id: newMutationRequestId(), expected_revision: snapshot.runtime_revision,+ return { request_id: randomUuid(), expected_revision: snapshot.runtime_revision,...(snapshot.exists ? { expected_generation: snapshot.runtime_generation! } : {}) }})pending.set(key, prepared)@@ -54,7 +54,9 @@ export function createSessionMutationClient() {}}-function newMutationRequestId(): string {+/** A v4 UUID on every origin, the one id minter for renderer and plugin code. `crypto.randomUUID`+ * exists only in secure contexts, so a Webapp opened over plain HTTP from another machine has none. */+export function randomUuid(): string {if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {return crypto.randomUUID()}