The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): honor artifact dismissal across navigation and replay
BearHuddleston30f0b220214c
diff --git a/apps/desktop/src/app/chat/composer/status-stack/index.tsx b/apps/desktop/src/app/chat/composer/status-stack/index.tsxindex 62a351fd6d7..5ead6286bee 100644--- a/apps/desktop/src/app/chat/composer/status-stack/index.tsx+++ b/apps/desktop/src/app/chat/composer/status-stack/index.tsx@@ -4,8 +4,8 @@ import { useNavigate } from 'react-router'import { blurComposerInput } from '@/app/chat/composer/focus'import { useComposerSurfaceId } from '@/app/chat/composer/scope'-import { AGENTS_ROUTE } from '@/app/routes'import { useSessionView } from '@/app/chat/session-view'+import { AGENTS_ROUTE } from '@/app/routes'import type { SubmitTextOptions } from '@/app/session/hooks/use-prompt-actions/utils'import { BillingBanner } from '@/components/billing-banner'import { composerDockCard } from '@/components/chat/composer-dock'diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/tools-preview.test.ts b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/tools-preview.test.tsnew file mode 100644index 00000000000..6f8bcc764d3--- /dev/null+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/tools-preview.test.ts@@ -0,0 +1,178 @@+import { type GatewayEvent, JsonRpcGatewayClient } from '@hermes/shared'+import { afterEach, expect, it, vi } from 'vitest'++import { type GatewayEventPayload, upsertToolPart } from '@/lib/chat-messages'+import { createClientSessionState } from '@/lib/chat-runtime'+import { $previewStatusBySession, dismissPreviewArtifact, recordPreviewArtifact } from '@/store/preview-status'+import {+ $sessionStates,+ clearAllSessionStates,+ publishSessionState,+ recordSessionEventScope+} from '@/store/session-states'++import { handleToolEvent } from './tools'+import type { GatewayEventContext } from './types'++const sid = 'preview-production'+const args = { path: '/work/report.html' }++function pending() {+ const state = createClientSessionState('production-stored')+ state.busy = true+ state.messages = [+ {+ id: 'live-tool-message',+ role: 'assistant',+ parts: upsertToolPart(+ [],+ {+ name: 'write_file',+ tool_id: 'reused-tool-id',+ args+ },+ 'running',+ 1+ )+ }+ ]+ publishSessionState(sid, state)+}++function event(seq: number, result: unknown = { verified: true }): GatewayEvent<'tool.complete'> {+ return {+ type: 'tool.complete',+ session_id: sid,+ seq,+ payload: { name: 'write_file', tool_id: 'reused-tool-id', args, result }+ }+}++function deliver(event: GatewayEvent<'tool.complete'>) {+ return handleToolEvent({+ event,+ payload: event.payload,+ sessionId: sid,+ occurredAt: 2,+ isActiveEvent: false,+ deps: {+ flushQueuedDeltas: vi.fn(),+ updateSessionState: vi.fn(),+ sessionInterrupted: () => false,+ upsertToolCall: () => {+ const state = $sessionStates.get()[sid]++ if (state) {+ publishSessionState(sid, {+ ...state,+ messages: state.messages.map(message => ({+ ...message,+ parts: upsertToolPart(message.parts, event.payload as GatewayEventPayload, 'complete', 2)+ }))+ })+ }+ }+ }+ } as unknown as GatewayEventContext)+}++afterEach(() => {+ $previewStatusBySession.set({})+ clearAllSessionStates()+ window.localStorage.clear()+})++it('reoffers a real later production, never a historical mount or duplicate completion', () => {+ recordSessionEventScope({ session_id: sid, connectionId: 'local', profile: 'default' })+ pending()+ deliver(event(10))+ expect($previewStatusBySession.get()[sid]).toHaveLength(1)+ dismissPreviewArtifact(sid, '/work/report.html')+ recordPreviewArtifact(sid, 'file:///work/report.html', '/work')+ deliver(event(10))+ pending()+ deliver(event(11, { error: 'Permission denied' }))+ expect($previewStatusBySession.get()[sid]).toBeUndefined()+ pending()+ deliver(event(12))+ expect($previewStatusBySession.get()[sid]).toHaveLength(1)+ dismissPreviewArtifact(sid, '/work/report.html')+ deliver(event(12))+ expect($previewStatusBySession.get()[sid]).toBeUndefined()+})++class Socket extends EventTarget {+ readyState = 0+ sent: string[] = []+ send(data: string) {+ this.sent.push(data)+ }+ close() {+ this.readyState = 3+ this.dispatchEvent(new CloseEvent('close'))+ }+ open() {+ this.readyState = 1+ this.dispatchEvent(new Event('open'))+ }+ frame(data: unknown) {+ this.dispatchEvent(new MessageEvent('message', { data: JSON.stringify(data) }))+ }+}++it('keeps dismissal when a missed completion arrives through the real reconnect replay path', async () => {+ const sockets: Socket[] = []++ const client = new JsonRpcGatewayClient({+ heartbeatIntervalMs: 0,+ heartbeatDeadlineMs: 0,+ socketFactory: () => {+ const socket = new Socket()+ sockets.push(socket)++ return socket as unknown as WebSocket+ }+ })++ client.on('tool.complete', deliver)++ try {+ let connecting = client.connect('ws://fixture.invalid')+ sockets[0].open()+ await connecting+ sockets[0].frame({+ jsonrpc: '2.0',+ method: 'event',+ params: { type: 'message.delta', session_id: sid, seq: 1, payload: { text: '' } }+ })+ client.invalidate('fixture disconnect')+ connecting = client.connect('ws://fixture.invalid')+ sockets[1].open()+ await connecting+ await vi.waitFor(() =>+ expect(sockets[1].sent.map(text => JSON.parse(text).method)).toContain('session.events.since')+ )+ const request = sockets[1].sent.map(text => JSON.parse(text)).find(value => value.method === 'session.events.since')+ recordSessionEventScope({ session_id: sid, connectionId: 'local', profile: 'default' })+ pending()+ recordPreviewArtifact(sid, '/work/report.html', '/work', 'production-stored')+ dismissPreviewArtifact(sid, '/work/report.html', 'production-stored')+ const seen = vi.fn()+ client.on('tool.complete', seen)+ sockets[1].frame({+ jsonrpc: '2.0',+ id: request.id,+ result: {+ events: [event(2)],+ latest_seq: 2,+ truncated: false,+ count: 1+ }+ })+ await vi.waitFor(() => expect(seen).toHaveBeenCalledOnce())+ expect(seen.mock.calls[0][0].replayed).toBe(true)+ expect($previewStatusBySession.get()[sid]).toBeUndefined()+ } finally {+ client.close()+ }+})diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/tools.ts b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/tools.tsindex 4b919e863a7..8d533deedcd 100644--- a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/tools.ts+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/tools.ts@@ -1,7 +1,11 @@+import { buildToolView, isPreviewableTarget } from '@/components/assistant-ui/tool/fallback-model'import { reportFirstBuildToolComplete } from '@/components/onboarding-chat/first-build'+import { toolCallOwnerMessageId } from '@/lib/chat-messages'import { invalidateSlashCompletions } from '@/lib/slash-completion-cache'import { refreshBackgroundProcesses } from '@/store/composer-status'import { flashPetActivity, setPetActivity } from '@/store/pet'+import { recordPreviewArtifact } from '@/store/preview-status'+import { $sessionStates, storedSessionIdForRuntimeId } from '@/store/session-states'import { pruneDelegateFallbackSubagents, upsertSubagent } from '@/store/subagents'import { reportMcpToolResult } from '@/store/suggestion-providers/repair'import { invalidateSkillSuggestionIndex } from '@/store/suggestion-providers/skill'@@ -68,7 +72,36 @@ export function handleToolEvent(ctx: GatewayEventContext): boolean {if (event.type === 'tool.complete') {if (sessionId) {flushQueuedDeltas(sessionId)++ const pendingProduction =+ !event.replayed && Boolean(toolCallOwnerMessageId($sessionStates.get()[sessionId]?.messages ?? [], payload))+upsertToolCall(sessionId, toTodoPayload(payload) ?? payload, 'complete', event.type, occurredAt)++ if (!sessionInterrupted(sessionId) && payload?.name && payload.result !== undefined && event.seq !== undefined) {+ const view = buildToolView(+ {+ type: 'tool-call',+ toolName: payload.name,+ args: payload.args ?? {},+ result: payload.result,+ toolResultMetadata: payload,+ completedAt: occurredAt+ },+ ''+ )++ if (view.status === 'success' && view.previewTarget && isPreviewableTarget(view.previewTarget)) {+ recordPreviewArtifact(+ sessionId,+ view.previewTarget,+ $sessionStates.get()[sessionId]?.cwd ?? '',+ storedSessionIdForRuntimeId(sessionId) ?? sessionId,+ pendingProduction+ )+ }+ }+// Onboarding's first build paces its check-ins off real work done// (no-op in every other session).reportFirstBuildToolComplete(sessionId)diff --git a/apps/desktop/src/components/assistant-ui/tool/fallback-model/index.ts b/apps/desktop/src/components/assistant-ui/tool/fallback-model/index.tsindex a0aaed80ca1..468ce141bd3 100644--- a/apps/desktop/src/components/assistant-ui/tool/fallback-model/index.ts+++ b/apps/desktop/src/components/assistant-ui/tool/fallback-model/index.ts@@ -751,6 +751,11 @@ function durationLabel(resultRecord: Record<string, unknown>): string | undefine}function toolPreviewTarget(toolName: string, args: Record<string, unknown>, result: Record<string, unknown>): string {+ // Reading an existing file is not producing a deliverable.+ if (toolName === 'read_file' || toolName === 'search_files' || toolName === 'list_files') {+ return ''+ }+const direct =firstStringField(result, ['preview', 'url', 'target']) ||firstStringField(args, ['preview', 'url', 'target', 'path', 'file', 'filepath']) ||diff --git a/apps/desktop/src/components/assistant-ui/tool/fallback-model/targets.ts b/apps/desktop/src/components/assistant-ui/tool/fallback-model/targets.tsindex c2168f0502c..01605f80b45 100644--- a/apps/desktop/src/components/assistant-ui/tool/fallback-model/targets.ts+++ b/apps/desktop/src/components/assistant-ui/tool/fallback-model/targets.ts@@ -9,6 +9,11 @@ export function looksLikePath(value: string): boolean {}export function isPreviewableTarget(target: string): boolean {+ // Renderer metadata is not a deliverable; app.asar.unpacked is a real directory.+ if (/^file:\/\//i.test(target) && target.replace(/\\/g, '/').split('/').includes('app.asar')) {+ return false+ }+return Boolean(target &&(/^file:\/\//i.test(target) ||diff --git a/apps/desktop/src/components/assistant-ui/tool/fallback-preview-scope.test.tsx b/apps/desktop/src/components/assistant-ui/tool/fallback-preview-scope.test.tsxindex 19c0868be32..c853f565bfe 100644--- a/apps/desktop/src/components/assistant-ui/tool/fallback-preview-scope.test.tsx+++ b/apps/desktop/src/components/assistant-ui/tool/fallback-preview-scope.test.tsx@@ -4,8 +4,9 @@ import type { ComponentProps, ReactNode } from 'react'import { afterEach, describe, expect, it, vi } from 'vitest'import { type SessionView, SessionViewProvider } from '@/app/chat/session-view'+import type { ChatMessage } from '@/lib/chat-messages'import { $previewStatusBySession } from '@/store/preview-status'-import { $activeSessionId, $currentCwd } from '@/store/session'+import { $activeSessionId, $currentCwd, $messages } from '@/store/session'vi.mock('@assistant-ui/react', async importOriginal => ({...(await importOriginal<Record<string, unknown>>()),@@ -17,24 +18,26 @@ const { ToolFallback } = await import('./fallback')const PRIMARY_ID = 'primary-session'const TILE_ID = 'tile-session'+const messages: ChatMessage[] = [{ id: 'msg-1', role: 'assistant', parts: [] }]/** Minimal tile view: only the fields the tool row reads. */function tileView(): SessionView {return {...({} as SessionView),$cwd: atom('/tile/work'),- $messages: atom([]),+ $messages: atom(messages),$runtimeId: atom<null | string>(TILE_ID),kind: 'tile'}}-function renderToolRow(wrap: (node: ReactNode) => ReactNode) {+function renderToolRow(wrap: (node: ReactNode) => ReactNode, overrides: Record<string, unknown> = {}) {const props = {args: { path: '/tile/work/report.html' },result: { path: '/tile/work/report.html' },toolCallId: 'call-1',- toolName: 'write_file'+ toolName: 'write_file',+ ...overrides} as unknown as ComponentProps<typeof ToolFallback>render(<>{wrap(<ToolFallback {...props} />)}</>)@@ -45,6 +48,7 @@ afterEach(() => {$previewStatusBySession.set({})$activeSessionId.set(null)$currentCwd.set('')+ $messages.set([])})describe('tool row preview recording', () => {@@ -68,9 +72,36 @@ describe('tool row preview recording', () => {it('still records into the primary session for the main chat', () => {$activeSessionId.set(PRIMARY_ID)$currentCwd.set('/primary/work')+ $messages.set(messages)renderToolRow(node => node)expect(Object.keys($previewStatusBySession.get())).toEqual([PRIMARY_ID])})++ it('does not promote reads, failed writes or packaged renderer URLs into artifacts', () => {+ $activeSessionId.set(PRIMARY_ID)+ $messages.set(messages)++ for (const overrides of [+ { toolName: 'read_file' },+ { isError: true, result: { error: 'Permission denied' } },+ { args: { path: '/work/missing.html' }, result: undefined },+ { result: { preview: 'file:///opt/Hermes/resources/app.asar/dist/index.html' } }+ ]) {+ renderToolRow(node => node, overrides)+ expect($previewStatusBySession.get()[PRIMARY_ID]).toBeUndefined()+ cleanup()+ }++ renderToolRow(node => node)+ expect($previewStatusBySession.get()[PRIMARY_ID]).toHaveLength(1)+ })++ it('does not register a previous conversation row under the newly selected chat', () => {+ $activeSessionId.set('next-conversation')+ $messages.set([{ id: 'next-message', role: 'assistant', parts: [] }])+ renderToolRow(node => node)+ expect($previewStatusBySession.get()['next-conversation']).toBeUndefined()+ })})diff --git a/apps/desktop/src/components/assistant-ui/tool/fallback.tsx b/apps/desktop/src/components/assistant-ui/tool/fallback.tsxindex 898b84e5bd5..54d98fa79d0 100644--- a/apps/desktop/src/components/assistant-ui/tool/fallback.tsx+++ b/apps/desktop/src/components/assistant-ui/tool/fallback.tsx@@ -418,10 +418,22 @@ function ToolEntry({ part }: ToolEntryProps) {const previewTarget = view.previewTarget// The session whose transcript this row is IN, which is not necessarily the// primary one: a tool row inside a session tile must feed that tile's composer.- const { $cwd: $sessionCwd, $runtimeId: $sessionRuntimeId, $storedId: $sessionStoredId } = useSessionView()++ const {+ $cwd: $sessionCwd,+ $runtimeId: $sessionRuntimeId,+ $storedId: $sessionStoredId,+ $messages: $sessionMessages+ } = useSessionView()useEffect(() => {- if (isPending || !previewTarget || !isPreviewableTarget(previewTarget)) {+ if (+ isPending ||+ result === undefined ||+ view.status !== 'success' ||+ !previewTarget ||+ !isPreviewableTarget(previewTarget)+ ) {return}@@ -431,10 +443,22 @@ function ToolEntry({ part }: ToolEntryProps) {const sessionId = $sessionRuntimeId.get()const dismissalSessionId = $sessionStoredId?.get() ?? sessionId- if (sessionId) {+ // A route switch can paint the previous assistant row while these atoms+ // already describe the next chat. Only that chat's own messages may feed it.+ if (sessionId && $sessionMessages.get().some(message => message.id === messageId)) {recordPreviewArtifact(sessionId, previewTarget, $sessionCwd.get() || '', dismissalSessionId ?? '')}- }, [$sessionCwd, $sessionRuntimeId, $sessionStoredId, isPending, previewTarget])+ }, [+ $sessionCwd,+ $sessionRuntimeId,+ $sessionStoredId,+ $sessionMessages,+ isPending,+ messageId,+ previewTarget,+ result,+ view.status+ ])const detailSections = useMemo(() => {if (!view.detail) {diff --git a/apps/desktop/src/lib/preview-targets.ts b/apps/desktop/src/lib/preview-targets.tsindex 3b6dfe78b37..8e16b3cc241 100644--- a/apps/desktop/src/lib/preview-targets.ts+++ b/apps/desktop/src/lib/preview-targets.ts@@ -52,6 +52,52 @@ export function previewName(target: string): string {}}+/** File identity only: do not resolve symlinks, guess home, or fold path case. */+export function previewArtifactKey(target: string, cwd: string): string {+ let path = target.trim()++ if (/^https?:\/\//i.test(path)) {+ return path+ }++ if (/^file:\/\//i.test(path)) {+ try {+ const url = new URL(path)++ // Encoded separators are not legal file-URL path segments.+ if (/%2f|%5c/i.test(url.pathname)) {+ return path+ }++ path = decodeURIComponent(url.pathname)++ if (url.hostname) {+ path = `//${url.hostname}${path}`+ } else if (/^\/[a-z]:\//i.test(path)) {+ path = path.slice(1)+ }+ } catch {+ return path+ }+ }++ const windows = /^[a-z]:[\\/]/i.test(path) || path.startsWith('\\\\')++ if (windows) {+ path = path.replace(/\\/g, '/')+ }++ if (!/^(?:\/|~\/|[a-z]:\/)/i.test(path) && cwd) {+ path = `${cwd.replace(/\/$/, '')}/${path.replace(/^\.\//, '')}`+ }++ if (/^[a-z]:[\\/]/i.test(path) || path.startsWith('\\\\')) {+ path = path.replace(/\\/g, '/')+ }++ return path.replace(/\/\.\//g, '/')+}+export function previewDisplayLabel(target: string): string {const escaped = previewName(target).replace(/[[\]\\]/g, '\\$&')diff --git a/apps/desktop/src/store/preview-status-edge-cases.test.ts b/apps/desktop/src/store/preview-status-edge-cases.test.tsnew file mode 100644index 00000000000..835c4818757--- /dev/null+++ b/apps/desktop/src/store/preview-status-edge-cases.test.ts@@ -0,0 +1,49 @@+import { afterEach, expect, it } from 'vitest'++import { createClientSessionState } from '@/lib/chat-runtime'+import { makeSessionInfo } from '@/test/session-info'++import { $previewStatusBySession, dismissPreviewArtifact, recordPreviewArtifact } from './preview-status'+import { setSessions } from './session'+import {+ clearAllSessionStates,+ migrateTilesForProfile,+ publishSessionState,+ recordSessionEventScope+} from './session-states'++afterEach(() => {+ $previewStatusBySession.set({})+ setSessions([])+ clearAllSessionStates()+ window.localStorage.clear()+})++it('retains a close when the same runtime owner is refined from profile-only to an exact route', () => {+ setSessions([makeSessionInfo({ id: 'refined-stored', profile: 'probe' })])+ publishSessionState('refined-runtime', createClientSessionState('refined-stored'))+ recordPreviewArtifact('refined-runtime', '/work/refined.html', '/work', 'refined-stored')+ recordSessionEventScope({ session_id: 'refined-runtime', connectionId: 'local', profile: 'probe' })+ dismissPreviewArtifact('refined-runtime', '/work/refined.html', 'refined-stored')+ recordPreviewArtifact('refined-runtime', '/work/refined.html', '/work', 'refined-stored')+ expect($previewStatusBySession.get()['refined-runtime']).toBeUndefined()++ setSessions([makeSessionInfo({ id: 'refined-append-stored', profile: 'probe-append' })])+ publishSessionState('refined-append', createClientSessionState('refined-append-stored'))+ recordPreviewArtifact('refined-append', '/work/first.html', '/work', 'refined-append-stored')+ recordSessionEventScope({ session_id: 'refined-append', connectionId: 'local', profile: 'probe-append' })+ recordPreviewArtifact('refined-append', '/work/second.html', '/work', 'refined-append-stored')+ dismissPreviewArtifact('refined-append', '/work/first.html', 'refined-append-stored')+ recordPreviewArtifact('refined-append', '/work/first.html', '/work', 'refined-append-stored')+ expect($previewStatusBySession.get()['refined-append'].map(item => item.id)).toEqual(['/work/second.html'])+})++it('tolerates malformed persisted scope keys and keeps Windows aliases identical', () => {+ window.localStorage.setItem('hermes.desktop.previewDismissals.v1', '{"__proto__":["x"],"constructor":["y"]}')+ expect(() => migrateTilesForProfile('old-profile', 'new-profile')).not.toThrow()+ recordPreviewArtifact('windows-alias', './report.html', 'C:\\work')+ const item = $previewStatusBySession.get()['windows-alias'][0]+ dismissPreviewArtifact('windows-alias', item.id)+ recordPreviewArtifact('windows-alias', 'file:///C:/work/report.html', 'C:\\work')+ expect($previewStatusBySession.get()['windows-alias']).toBeUndefined()+})diff --git a/apps/desktop/src/store/preview-status-lifecycle.test.ts b/apps/desktop/src/store/preview-status-lifecycle.test.tsnew file mode 100644index 00000000000..a482a72033a--- /dev/null+++ b/apps/desktop/src/store/preview-status-lifecycle.test.ts@@ -0,0 +1,63 @@+import { afterEach, expect, it, vi } from 'vitest'++import {+ $previewStatusBySession,+ clearPreviewArtifacts,+ dismissPreviewArtifact,+ recordPreviewArtifact+} from './preview-status'+import { dropTilesForProfile, migrateTilesForProfile, recordSessionEventScope } from './session-states'++afterEach(() => {+ vi.restoreAllMocks()+ $previewStatusBySession.set({})+ window.localStorage.clear()+})++it('moves local dismissals on rename and removes only the deleted owner', () => {+ for (const [runtime, connectionId] of [+ ['rename-local', 'local'],+ ['rename-remote', 'remote']+ ]) {+ recordSessionEventScope({ session_id: runtime, connectionId, profile: 'before-rename' })+ recordPreviewArtifact(runtime, '/work/rename.html', '/work', 'rename-stored')+ dismissPreviewArtifact(runtime, '/work/rename.html', 'rename-stored')+ }++ migrateTilesForProfile('before-rename', 'after-rename')+ recordSessionEventScope({ session_id: 'rename-new', connectionId: 'local', profile: 'after-rename' })+ recordPreviewArtifact('rename-new', '/work/rename.html', '/work', 'rename-stored')+ recordPreviewArtifact('rename-remote', '/work/rename.html', '/work', 'rename-stored')+ expect($previewStatusBySession.get()['rename-new']).toBeUndefined()+ expect($previewStatusBySession.get()['rename-remote']).toBeUndefined()+ dropTilesForProfile('after-rename')+ recordPreviewArtifact('rename-new', '/work/rename.html', '/work', 'rename-stored')+ recordPreviewArtifact('rename-remote', '/work/rename.html', '/work', 'rename-stored')+ expect($previewStatusBySession.get()['rename-new']).toHaveLength(1)+ expect($previewStatusBySession.get()['rename-remote']).toBeUndefined()+})++it('honors memory-only closes on storage failure and durable closes after module reload', async () => {+ recordSessionEventScope({ session_id: 'quota', connectionId: 'local', profile: 'quota' })+ recordPreviewArtifact('quota', '/work/quota.html', '/work', 'quota-stored')++ const write = vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => {+ throw new Error('quota')+ })++ dismissPreviewArtifact('quota', '/work/quota.html', 'quota-stored')+ clearPreviewArtifacts('quota')+ recordPreviewArtifact('quota', '/work/quota.html', '/work', 'quota-stored')+ expect($previewStatusBySession.get().quota).toBeUndefined()+ write.mockRestore()++ recordSessionEventScope({ session_id: 'before-reload', connectionId: 'local', profile: 'persist' })+ recordPreviewArtifact('before-reload', '/work/saved.html', '/work', 'persist-stored')+ dismissPreviewArtifact('before-reload', '/work/saved.html', 'persist-stored')+ vi.resetModules()+ const fresh = await import('./preview-status')+ const { recordSessionEventScope: scope } = await import('./session-states')+ scope({ session_id: 'after-reload', connectionId: 'local', profile: 'persist' })+ fresh.recordPreviewArtifact('after-reload', '/work/saved.html', '/work', 'persist-stored')+ expect(fresh.$previewStatusBySession.get()['after-reload']).toBeUndefined()+})diff --git a/apps/desktop/src/store/preview-status.test.ts b/apps/desktop/src/store/preview-status.test.tsindex 522eaedbd8f..41c76228992 100644--- a/apps/desktop/src/store/preview-status.test.ts+++ b/apps/desktop/src/store/preview-status.test.ts@@ -1,11 +1,14 @@import { beforeEach, describe, expect, it } from 'vitest'+import { rescopeConnectionScopedStores } from '@/lib/connection-scoped'+import {$previewStatusBySession,clearPreviewArtifacts,dismissPreviewArtifact,recordPreviewArtifact} from './preview-status'+import { recordSessionEventScope } from './session-states'beforeEach(() => {window.localStorage.clear()@@ -43,6 +46,10 @@ describe('recordPreviewArtifact', () => {})it('suppresses a dismissed historical target when the row mounts again', () => {+ for (const session_id of ['runtime-a', 'runtime-b']) {+ recordSessionEventScope({ session_id, connectionId: 'owner', profile: 'default' })+ }+recordPreviewArtifact('runtime-a', '/a/index.html', '/work', 'stored-a')dismissPreviewArtifact('runtime-a', '/a/index.html', 'stored-a')$previewStatusBySession.set({})@@ -52,4 +59,37 @@ describe('recordPreviewArtifact', () => {expect($previewStatusBySession.get()['runtime-b']).toBeUndefined()expect(window.localStorage.getItem('hermes.desktop.previewDismissals.v1')).toContain('stored-a')})++ it('keeps dismissal with the session owner across foreground changes and runtime rebinds', () => {+ const record = (runtime: string, connectionId: string, profile: string) => {+ recordSessionEventScope({ session_id: runtime, connectionId, profile })+ recordPreviewArtifact(runtime, '/work/report.html', '/work', 'same-stored-id')+ }++ record('owner-a', 'local', 'alpha')+ dismissPreviewArtifact('owner-a', '/work/report.html', 'same-stored-id')+ $previewStatusBySession.set({})+ rescopeConnectionScopedStores({ mode: 'remote', baseUrl: 'https://other.invalid', profile: 'other' })+ record('owner-a-rebound', 'local', 'alpha')+ record('other-profile', 'local', 'beta')+ record('other-connection', 'remote', 'alpha')+ expect($previewStatusBySession.get()['owner-a-rebound']).toBeUndefined()+ expect($previewStatusBySession.get()['other-profile']).toHaveLength(1)+ expect($previewStatusBySession.get()['other-connection']).toHaveLength(1)+ rescopeConnectionScopedStores({ mode: 'local' })+ })++ it('deduplicates equivalent file URLs without hiding distinct same-named files', () => {+ recordPreviewArtifact('files', '/work/one/index.html', '/work')+ recordPreviewArtifact('files', 'file:///work/one/index.html', '/work')+ recordPreviewArtifact('files', './one/index.html', '/work')+ recordPreviewArtifact('files', '/work/two/index.html', '/work')++ const items = $previewStatusBySession.get().files+ expect(items).toHaveLength(2)+ expect(new Set(items.map(item => item.label)).size).toBe(2)+ dismissPreviewArtifact('files', items[0].id)+ recordPreviewArtifact('files', 'file:///work/one/index.html', '/work')+ expect($previewStatusBySession.get().files).toHaveLength(1)+ })})diff --git a/apps/desktop/src/store/preview-status.ts b/apps/desktop/src/store/preview-status.tsindex a457b6ba6c9..f9d62a97c0d 100644--- a/apps/desktop/src/store/preview-status.ts+++ b/apps/desktop/src/store/preview-status.ts@@ -1,9 +1,12 @@import { atom } from 'nanostores'-import { activeConnectionScopeSuffix } from '@/lib/connection-scoped'-import { previewName } from '@/lib/preview-targets'+import { previewArtifactKey, previewName } from '@/lib/preview-targets'import { readJson, writeJson } from '@/lib/storage'+import { ownerLookupSessionRows, resolveComposerSessionKey } from './session'+import type { SessionOwnerRoute } from './session-request-router'+import { knownOwnerForSession, runtimeSessionOwner, storedSessionIdForRuntimeId } from './session-states'+/*** Session-scoped feed of previewable artifacts (HTML files, localhost dev URLs)* a tool produced. Surfaced as compact links in the composer status stack —@@ -16,51 +19,211 @@ import { readJson, writeJson } from '@/lib/storage'export interface PreviewArtifact {/** cwd captured at detection so a relative path still resolves on click. */cwd: string- /** Dedupe key + display id (the raw target). */+ /** Canonical target identity, independent of its display label. */id: stringlabel: stringtarget: string+ /** Captured owner; foreground switches must not retarget a later dismiss. */+ dismissalScope?: string}const MAX_PER_SESSION = 4const DISMISSED_PREVIEWS_KEY = 'hermes.desktop.previewDismissals.v1'+const MAX_DISMISSED_SESSIONS = 128+const MAX_DISMISSED_TARGETS = 64export const $previewStatusBySession = atom<Record<string, PreviewArtifact[]>>({})-type DismissedPreviewIds = Record<string, string[]>+interface DismissedPreviewIds {+ [session: string]: string[]+}+const volatileDismissals = new Map<string, string[]>()+const scopeByRuntime = new Map<string, string>()++function dismissalKey(runtimeId: string, storedId: string): string {+ // The route's stored selection can advance before the old runtime unmounts.+ storedId = storedSessionIdForRuntimeId(runtimeId) ?? storedId+ // Historical rows in background tiles do not belong to the active connection.+ const owner = knownOwnerForSession(runtimeId) ?? runtimeSessionOwner(runtimeId) ?? knownOwnerForSession(storedId)+ const profile = typeof owner === 'string' ? owner : owner?.targetProfile || owner?.profile++ const rows = ownerLookupSessionRows().filter(+ row =>+ row.profile === profile &&+ (row.connection_id || 'local') === (typeof owner === 'object' && owner ? owner.connectionId : 'local')+ )++ const stableId = resolveComposerSessionKey(storedId, rows) ?? storedId++ // Bare profiles name the legacy profile pool, not the foreground connection.+ const scope =+ owner && typeof owner === 'object'+ ? JSON.stringify([owner.connectionId, owner.profile, owner.targetProfile || owner.profile, stableId])+ : typeof owner === 'string'+ ? JSON.stringify([null, owner, owner, stableId])+ : JSON.stringify(['runtime', runtimeId])++ const previous = scopeByRuntime.get(runtimeId)+ const before = previous ? storedOwner(previous) : null+ const after = storedOwner(scope)++ if (+ previous &&+ previous !== scope &&+ after &&+ (previous === JSON.stringify(['runtime', runtimeId]) ||+ (before && before[0] === null && before[1] === after[1] && before[2] === after[2] && before[3] === after[3]))+ ) {+ // Only refinement observed on THIS runtime joins keys. Another profile or+ // connection with a coincidentally equal stored id must not inherit it.+ rewriteDismissalScopes(key => (key === previous ? scope : key))+ }++ scopeByRuntime.set(runtimeId, scope)-function dismissedPreviewsKey(): string {- return `${DISMISSED_PREVIEWS_KEY}${activeConnectionScopeSuffix()}`+ while (scopeByRuntime.size > MAX_DISMISSED_SESSIONS) {+ scopeByRuntime.delete(scopeByRuntime.keys().next().value!)+ }++ return scope}function readDismissedPreviewIds(): DismissedPreviewIds {- const value = readJson<unknown>(dismissedPreviewsKey())+ const value = readJson<unknown>(DISMISSED_PREVIEWS_KEY)if (!value || typeof value !== 'object' || Array.isArray(value)) {return {}}return Object.fromEntries(- Object.entries(value).flatMap(([sid, ids]) => {- if (!Array.isArray(ids)) {- return []- }+ Object.entries(value)+ .slice(-MAX_DISMISSED_SESSIONS)+ .flatMap(([sid, ids]) => {+ if (!Array.isArray(ids)) {+ return []+ }- const strings = ids.filter((id): id is string => typeof id === 'string' && id.length > 0)- return strings.length > 0 ? [[sid, strings]] : []- })+ if (sid.length > 4096 || !storedOwner(sid)) {+ return []+ }++ const strings = ids+ .filter((id): id is string => typeof id === 'string' && id.length > 0 && id.length <= 8192)+ .slice(-MAX_DISMISSED_TARGETS)++ return strings.length > 0 ? [[sid, strings]] : []+ }))}function rememberDismissedPreview(sid: string, id: string): void {const dismissed = readDismissedPreviewIds()- const ids = dismissed[sid] ?? []+ const ids = [...new Set([...(dismissed[sid] ?? []), ...(volatileDismissals.get(sid) ?? [])])]if (ids.includes(id)) {return}- writeJson(dismissedPreviewsKey(), { ...dismissed, [sid]: [...ids, id] })+ const { [sid]: _previous, ...rest } = dismissed++ const next = Object.fromEntries(+ [...Object.entries(rest), [sid, [...ids, id].slice(-MAX_DISMISSED_TARGETS)]].slice(-MAX_DISMISSED_SESSIONS)+ )++ // Keep the close effective for this renderer even when storage is unavailable.+ volatileDismissals.set(sid, next[sid])++ while (volatileDismissals.size > MAX_DISMISSED_SESSIONS) {+ volatileDismissals.delete(volatileDismissals.keys().next().value!)+ }++ if (!sid.startsWith('["runtime",')) {+ writeJson(DISMISSED_PREVIEWS_KEY, next)++ if (readDismissedPreviewIds()[sid]?.includes(id)) {+ volatileDismissals.delete(sid)+ }+ }+}++function rewriteDismissalScopes(rewrite: (scope: string) => string | null): void {+ const current = { ...readDismissedPreviewIds(), ...Object.fromEntries(volatileDismissals) }+ const next: DismissedPreviewIds = Object.create(null)++ for (const [scope, ids] of Object.entries(current)) {+ const target = rewrite(scope)++ if (target) {+ next[target] = [...new Set([...(next[target] ?? []), ...ids])].slice(-MAX_DISMISSED_TARGETS)+ }+ }++ volatileDismissals.clear()++ for (const [scope, ids] of Object.entries(next).slice(-MAX_DISMISSED_SESSIONS)) {+ volatileDismissals.set(scope, ids)+ }++ writeJson(+ DISMISSED_PREVIEWS_KEY,+ Object.fromEntries(Object.entries(next).filter(([key]) => !key.startsWith('["runtime",')))+ )++ for (const [sid, items] of Object.entries($previewStatusBySession.get())) {+ writePreviews(+ sid,+ items.flatMap(item => {+ const scope = item.dismissalScope ? rewrite(item.dismissalScope) : undefined++ return scope === null ? [] : [{ ...item, dismissalScope: scope }]+ })+ )+ }+}++function storedOwner(scope: string): [string | null, string, string, string] | null {+ try {+ const value: unknown = JSON.parse(scope)++ return Array.isArray(value) &&+ value.length === 4 &&+ (value[0] === null || typeof value[0] === 'string') &&+ value.slice(1).every(item => typeof item === 'string')+ ? (value as [string | null, string, string, string])+ : null+ } catch {+ return null+ }+}++export function migratePreviewArtifactsForProfile(from: string, to: string): void {+ rewriteDismissalScopes(scope => {+ const owner = storedOwner(scope)++ if (!owner || (owner[0] && owner[0] !== 'local')) {+ return scope+ }++ return JSON.stringify([owner[0], owner[1] === from ? to : owner[1], owner[2] === from ? to : owner[2], owner[3]])+ })+}++export function dropPreviewArtifactsForProfile(profile: string, route?: Partial<SessionOwnerRoute>): void {+ rewriteDismissalScopes(scope => {+ const owner = storedOwner(scope)++ if (!owner) {+ return scope+ }++ const matches = route+ ? owner[1] === route.profile?.trim() &&+ (!route.connectionId || owner[0] === route.connectionId.trim()) &&+ (!route.targetProfile || owner[2] === route.targetProfile.trim())+ : (!owner[0] || owner[0] === 'local') && (owner[1] === profile || owner[2] === profile)++ return matches ? null : scope+ })}const writePreviews = (sid: string, items: PreviewArtifact[]) => {@@ -78,7 +241,27 @@ const writePreviews = (sid: string, items: PreviewArtifact[]) => {return}- $previewStatusBySession.set({ ...current, [sid]: items })+ const labelled = items.map(item => {+ const name = previewName(item.target)+ const peers = items.filter(other => previewName(other.target) === name)+ let label = name++ if (peers.length > 1) {+ const parts = item.id.split('/')++ for (let depth = 2; depth <= parts.length; depth += 1) {+ label = parts.slice(-depth).join('/')++ if (peers.every(other => other.id === item.id || other.id.split('/').slice(-depth).join('/') !== label)) {+ break+ }+ }+ }++ return item.label === label ? item : { ...item, label }+ })++ $previewStatusBySession.set({ ...current, [sid]: labelled })}/**@@ -86,28 +269,56 @@ const writePreviews = (sid: string, items: PreviewArtifact[]) => {* in the list keeps its slot (the tool row re-registers on every render, so this* must not churn the atom or reorder rows).*/-export function recordPreviewArtifact(sid: string, target: string, cwd: string, dismissalSid = sid) {+export function recordPreviewArtifact(+ sid: string,+ target: string,+ cwd: string,+ dismissalSid = sid,+ newProduction = false+) {const raw = target.trim()+ const id = previewArtifactKey(raw, cwd)if (!sid || !raw) {return}+ const scope = dismissalKey(sid, dismissalSid)const list = $previewStatusBySession.get()[sid] ?? []- if (list.some(item => item.id === raw)) {+ // Only the live completion handler may re-offer a newly produced file.+ // Historical mounts and reconnect replay never grant this intent.+ if (newProduction) {+ const dismissed = readDismissedPreviewIds()++ if (dismissed[scope]?.includes(id) || volatileDismissals.get(scope)?.includes(id)) {+ dismissed[scope] = (dismissed[scope] ?? []).filter(value => value !== id)+ volatileDismissals.set(+ scope,+ (volatileDismissals.get(scope) ?? []).filter(value => value !== id)+ )+ writeJson(DISMISSED_PREVIEWS_KEY, dismissed)+ }+ }++ if (list.some(item => item.id === id)) {return}- if (readDismissedPreviewIds()[dismissalSid]?.includes(raw)) {+ if (readDismissedPreviewIds()[scope]?.includes(id) || volatileDismissals.get(scope)?.includes(id)) {return}- writePreviews(sid, [...list, { cwd, id: raw, label: previewName(raw), target: raw }].slice(-MAX_PER_SESSION))+ writePreviews(+ sid,+ [...list, { cwd, id, label: previewName(raw), target: raw, dismissalScope: scope }].slice(-MAX_PER_SESSION)+ )}export function dismissPreviewArtifact(sid: string, id: string, dismissalSid = sid) {+ dismissalKey(sid, dismissalSid) // reconcile an owner refined since the row mountedconst list = $previewStatusBySession.get()[sid]+ const scope = list?.find(item => item.id === id)?.dismissalScope ?? dismissalKey(sid, dismissalSid)if (list) {writePreviews(@@ -117,7 +328,7 @@ export function dismissPreviewArtifact(sid: string, id: string, dismissalSid = s}if (dismissalSid && id) {- rememberDismissedPreview(dismissalSid, id)+ rememberDismissedPreview(scope, id)}}diff --git a/apps/desktop/src/store/session-states.ts b/apps/desktop/src/store/session-states.tsindex cdcae439813..f64618c328e 100644--- a/apps/desktop/src/store/session-states.ts+++ b/apps/desktop/src/store/session-states.ts@@ -35,6 +35,7 @@ import { stableArray } from '@/lib/stable-array'import { readJson, writeJson } from '@/lib/storage'import type { SessionInfo } from '@/types/hermes'+import { dropPreviewArtifactsForProfile, migratePreviewArtifactsForProfile } from './preview-status'import { $activeGatewayProfile, normalizeProfileKey } from './profile'import { clearAllProviderWaits, clearSessionProviderWait } from './provider-wait'import {@@ -1943,6 +1944,7 @@ export function dropTilesForProfile(}const name = normalizeProfileKey(profile)+ dropPreviewArtifactsForProfile(name, route)// Route fields go through the SAME canonicalization as `name` below — a// source-scoped delete must not be defeated by stray whitespace around a// profile name that a non-route delete trims away.@@ -2078,6 +2080,7 @@ export function migrateTilesForProfile(oldProfile: string, newProfile: string):migrateTranscriptTailsForProfile(from, to)migrateRememberedNavigationForProfile(from, to)migrateSessionOwnerHintsForProfile(from, to)+ migratePreviewArtifactsForProfile(from, to)}/** ⌘⇧T — reopen the most recently closed tab where it was, then focus it.diff --git a/apps/shared/src/gateway-events.ts b/apps/shared/src/gateway-events.tsindex f4cab921695..617790a90a5 100644--- a/apps/shared/src/gateway-events.ts+++ b/apps/shared/src/gateway-events.ts@@ -34,6 +34,8 @@ export type GatewayEventName = keyof GatewayEventMap/** One `event` notification's `params`. */export interface GatewayEvent<K extends GatewayEventName = GatewayEventName> {+ /** Client-local: recovered/held during reconnect, not fresh user-facing work. */+ replayed?: boolean/** Registry connection whose socket delivered the event (renderer-side tag;* absent for the local/legacy primary path). */connectionId?: stringdiff --git a/apps/shared/src/json-rpc-gateway.ts b/apps/shared/src/json-rpc-gateway.tsindex fe8f5759b1a..676b8ab4319 100644--- a/apps/shared/src/json-rpc-gateway.ts+++ b/apps/shared/src/json-rpc-gateway.ts@@ -522,7 +522,7 @@ export class JsonRpcGatewayClient {continue}- this.dispatchIfNewer(event as GatewayEvent)+ this.dispatchIfNewer({ ...event, replayed: true } as GatewayEvent)}}} catch {@@ -584,7 +584,7 @@ export class JsonRpcGatewayClient {for (const parked of hold.values()) {for (const event of parked) {- this.dispatchIfNewer(event)+ this.dispatchIfNewer({ ...event, replayed: true })}}}diff --git a/website/docs/user-guide/desktop.md b/website/docs/user-guide/desktop.mdindex b32e569827f..7ac5fc47b7a 100644--- a/website/docs/user-guide/desktop.md+++ b/website/docs/user-guide/desktop.md@@ -114,6 +114,8 @@ Explore and preview the working directory without leaving the app — useful for### Artifacts+Preview links above the composer are session suggestions, not a task-completion checklist. Dismissing one keeps historical tool rows from bringing it back after navigation or reload. A new successful tool completion can offer the file again. Read-only file inspection and failed writes do not create suggestions. Files with the same name show enough directory context to distinguish them; dismissing a suggestion does not delete its file or transcript. Changing a `/goal` does not erase a conversation's artifacts.+When connected to a remote gateway, opening a file artifact downloads it through that gateway, using the artifact’s originating profile and session. Relative paths resolve against the session’s saved working directory; home-relative paths use the gateway’s home, never the Desktop machine’s home. Windows-style relative paths are recognized alongside forward-slash paths, and file URIs retain drive and network-share information for the gateway to interpret. Missing sessions or working directories produce an error rather than selecting a different local file.The **Artifacts** view collects what your sessions generate — **images, files, and links** — into one searchable, browsable gallery. Open it from the sidebar, the command palette (**Artifacts — Browse generated outputs**), or a `nav.artifacts` shortcut you bind yourself. It indexes recent session outputs automatically; every artifact shows which session produced it with a jump back to that chat, and images and files open in a preview with download / open-in-browser / copy actions.