Skip to content

The agent that grows with you

fix(desktop): prevent preview saves crossing connection boundaries

FroRaut6e5013f343fd
diff --git a/apps/desktop/src/app/chat/right-rail/preview-file-save-scope.test.tsx b/apps/desktop/src/app/chat/right-rail/preview-file-save-scope.test.tsx
new file mode 100644
index 00000000000..2468e84efdf
--- /dev/null
+++ b/apps/desktop/src/app/chat/right-rail/preview-file-save-scope.test.tsx
@@ -0,0 +1,198 @@
+import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import path from 'node:path'
+
+import { EditorView } from '@codemirror/view'
+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { expect, it, vi } from 'vitest'
+
+import { setApiRequestConnection, setApiRequestProfile } from '@/api/client'
+import type { HermesApiRequest, HermesConnection } from '@/global'
+import { $connection } from '@/store/session'
+
+import { LocalFilePreview } from './preview-file'
+
+vi.mock('@/components/chat/shiki-highlighter', () => ({
+ LazyShiki: ({ code }: { code: string }) => <pre>{code}</pre>
+}))
+
+it.each(['connection', 'profile', 'local', 'api-route'] as const)(
+ 'never retargets a pending preview save after a %s switch and permits retry on its owner',
+ async destination => {
+ const directory = await mkdtemp(path.join(tmpdir(), 'hermes-save-scope-'))
+ const originFile = path.join(directory, 'origin.txt')
+ const otherFile = path.join(directory, 'other.txt')
+ const logicalPath = '/workspace/note.txt'
+ const origin = { connectionId: 'gateway-a', mode: 'remote', profile: 'default' } as HermesConnection
+
+ const other = {
+ connectionId:
+ destination === 'connection' || destination === 'api-route'
+ ? 'gateway-b'
+ : destination === 'local'
+ ? 'local'
+ : 'gateway-a',
+ mode: destination === 'local' ? 'local' : 'remote',
+ profile: destination === 'profile' ? 'other' : 'default'
+ } as HermesConnection
+
+ const rangeDescriptors = Object.getOwnPropertyDescriptors(Range.prototype)
+ let releaseRead!: () => void
+
+ const pendingRead = new Promise<void>(resolve => {
+ releaseRead = resolve
+ })
+
+ let originReads = 0
+ let validationStarted!: () => void
+
+ const started = new Promise<void>(resolve => {
+ validationStarted = resolve
+ })
+
+ const writes: string[] = []
+
+ const read = async (file: string) => ({
+ path: logicalPath,
+ text: await readFile(file, 'utf8'),
+ binary: false,
+ truncated: false
+ })
+
+ const write = async (file: string, content: string) => {
+ writes.push(file)
+ await writeFile(file, content)
+
+ return { path: logicalPath }
+ }
+
+ const activate = (connection: HermesConnection) => {
+ $connection.set(connection)
+ setApiRequestConnection(connection.connectionId ?? null)
+ setApiRequestProfile(connection.profile ?? null)
+ }
+
+ try {
+ await writeFile(originFile, 'origin baseline')
+ await writeFile(otherFile, 'unrelated valuable contents')
+ vi.stubGlobal('hermesDesktop', {
+ api: async (request: HermesApiRequest) => {
+ const file =
+ request.connectionId === origin.connectionId && request.profile === origin.profile ? originFile : otherFile
+
+ if (request.path.startsWith('/api/fs/read-text?')) {
+ const snapshot = await read(file)
+
+ if (file === originFile && ++originReads === 2) {
+ validationStarted()
+ await pendingRead
+ }
+
+ return snapshot
+ }
+
+ if (request.path === '/api/fs/write-text') {
+ return write(file, (request.body as { content: string }).content)
+ }
+
+ if (request.path.startsWith('/api/fs/git-root?')) {
+ return { root: null }
+ }
+
+ throw new Error(`Unexpected request: ${request.path}`)
+ },
+ readFileText: () => read(otherFile),
+ writeTextFile: (_file: string, content: string) => write(otherFile, content)
+ })
+ Object.defineProperties(Range.prototype, {
+ getClientRects: { configurable: true, value: () => [] },
+ getBoundingClientRect: { configurable: true, value: () => new DOMRect() }
+ })
+ activate(origin)
+
+ const rendered = render(
+ <LocalFilePreview
+ reloadKey={0}
+ target={{
+ kind: 'file',
+ label: 'note.txt',
+ path: logicalPath,
+ previewKind: 'text',
+ source: logicalPath,
+ url: `file://${logicalPath}`
+ }}
+ />
+ )
+
+ fireEvent.click(await screen.findByRole('button', { name: 'Edit' }))
+ const editor = EditorView.findFromDOM(rendered.container.querySelector('.cm-content')!)!
+ act(() => editor.dispatch({ changes: { from: 0, to: editor.state.doc.length, insert: 'draft for origin' } }))
+ fireEvent.click(screen.getByRole('button', { name: /Save/ }))
+ await started
+
+ await act(async () => {
+ if (destination === 'api-route') {
+ setApiRequestConnection(other.connectionId ?? null)
+ } else {
+ activate(other)
+ }
+
+ releaseRead()
+ })
+ await waitFor(() =>
+ expect(
+ screen.queryByRole('button', { name: 'Edit' }) || screen.queryByText(/original connection/)
+ ).not.toBeNull()
+ )
+ expect(await readFile(otherFile, 'utf8')).toBe('unrelated valuable contents')
+ expect(writes).toEqual([])
+ expect(editor.dom.isConnected).toBe(true)
+ expect(editor.state.doc.toString()).toBe('draft for origin')
+
+ // Save is still refused when invoked after the switch.
+ fireEvent.click(screen.getByRole('button', { name: /Save/ }))
+ await screen.findByText(/original connection/)
+ expect(writes).toEqual([])
+
+ await act(async () => activate(origin))
+
+ if (destination === 'connection') {
+ // An Overwrite decision belongs to the same owner as the conflict.
+ await writeFile(originFile, 'external edit at origin')
+ fireEvent.click(screen.getByRole('button', { name: /Save/ }))
+ await screen.findByRole('button', { name: /Overwrite/ })
+ await act(async () => activate(other))
+ fireEvent.click(screen.getByRole('button', { name: /Overwrite/ }))
+ await screen.findByText(/original connection/)
+ expect(writes).toEqual([])
+ expect(await readFile(otherFile, 'utf8')).toBe('unrelated valuable contents')
+ await act(async () => activate(origin))
+ fireEvent.click(screen.getByRole('button', { name: /Overwrite/ }))
+ } else {
+ fireEvent.click(screen.getByRole('button', { name: /Save/ }))
+ }
+
+ await screen.findByRole('button', { name: 'Edit' })
+ expect(writes).toEqual([originFile])
+ expect(await readFile(originFile, 'utf8')).toBe('draft for origin')
+ expect(await readFile(otherFile, 'utf8')).toBe('unrelated valuable contents')
+ } finally {
+ releaseRead()
+ cleanup()
+ vi.unstubAllGlobals()
+ $connection.set(null)
+ setApiRequestConnection(null)
+ setApiRequestProfile(null)
+
+ for (const key of ['getClientRects', 'getBoundingClientRect']) {
+ if (rangeDescriptors[key]) {
+ Object.defineProperty(Range.prototype, key, rangeDescriptors[key])
+ } else {
+ Reflect.deleteProperty(Range.prototype, key)
+ }
+ }
+
+ await rm(directory, { recursive: true, force: true })
+ }
+ }
+)
diff --git a/apps/desktop/src/app/chat/right-rail/preview-file.tsx b/apps/desktop/src/app/chat/right-rail/preview-file.tsx
index c686da01340..7eac4a8b737 100644
--- a/apps/desktop/src/app/chat/right-rail/preview-file.tsx
+++ b/apps/desktop/src/app/chat/right-rail/preview-file.tsx
@@ -10,6 +10,7 @@ import type {
import { createContext, Fragment, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react'
import { defaultRehypePlugins, defaultRemarkPlugins, Streamdown } from 'streamdown'
+import { getApiRequestConnection } from '@/api/client'
import { requestComposerFocus, requestComposerInsertRefs } from '@/app/chat/composer/focus'
import { droppedFileInlineRef } from '@/app/chat/composer/inline-refs'
import { HERMES_PATHS_MIME } from '@/app/chat/hooks/use-composer-actions'
@@ -190,6 +191,12 @@ function isTypableElement(el: Element | null): boolean {
return tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT' || (el as HTMLElement).isContentEditable
}
+function fileEditScopeKey(fsKey = desktopFsCacheKey()) {
+ // The REST wrapper has its own routing authority. Include it while the
+ // resolved connection descriptor is catching up with an activation.
+ return JSON.stringify([fsKey, getApiRequestConnection()])
+}
+
function filePathForTarget(target: PreviewTarget) {
if (target.path) {
return target.path
@@ -768,6 +775,7 @@ export function LocalFilePreview({
const [editing, setEditing] = useState(false)
const draftRef = useRef('')
const baselineRef = useRef('')
+ const editorScopeRef = useRef('')
const [dirty, setDirty] = useState(false)
const [editorKey, setEditorKey] = useState(0)
const [saving, setSaving] = useState(false)
@@ -958,6 +966,7 @@ export function LocalFilePreview({
const beginEdit = () => {
const text = state.text ?? ''
+ editorScopeRef.current = fileEditScopeKey(fsCacheKey)
baselineRef.current = text
draftRef.current = text
setDirty(false)
@@ -1027,7 +1036,19 @@ export function LocalFilePreview({
setSaving(true)
setSaveError(null)
+ // Keep the edit's owner across awaits: the FS facade routes each call via
+ // the window's current connection, which can change while validation waits.
+ const saveScope = editorScopeRef.current
+
+ const requireEditorOwner = () => {
+ if (fileEditScopeKey() !== saveScope) {
+ throw new Error(t.preview.saveScopeChanged)
+ }
+ }
+
try {
+ requireEditorOwner()
+
// Stale-on-disk guard: re-read what's on disk now and compare to the
// snapshot the user started from. If something changed underneath (an
// agent edit, an external save), don't clobber it silently — surface the
@@ -1047,6 +1068,9 @@ export function LocalFilePreview({
}
}
+ // Also guards Overwrite: bypassing a content conflict never authorizes
+ // writing the same path on another connection/profile or this device.
+ requireEditorOwner()
await writeDesktopFileText(filePath, draftRef.current)
baselineRef.current = draftRef.current
setDirty(false)
diff --git a/apps/desktop/src/i18n/ar_artifacts.ts b/apps/desktop/src/i18n/ar_artifacts.ts
index 52abede1439..9876dc7c0e2 100644
--- a/apps/desktop/src/i18n/ar_artifacts.ts
+++ b/apps/desktop/src/i18n/ar_artifacts.ts
@@ -88,6 +88,7 @@ export const arArtifacts = {
editing: 'جار التحرير',
unsavedChanges: 'تغييرات غير محفوظة',
saveFailed: message => `تعذّر الحفظ: ${message}`,
+ saveScopeChanged: 'عُد إلى الاتصال والملف الشخصي الأصليين لحفظ هذه المسودة.',
diskChangedTitle: 'تغيّر الملف على القرص',
diskChangedBody: 'تغيّر هذا الملف منذ أن فتحته. هل تريد الكتابة فوقه بنسختك، أم تجاهل تعديلاتك وإعادة التحميل؟',
overwrite: 'الكتابة فوقه',
diff --git a/apps/desktop/src/i18n/de.ts b/apps/desktop/src/i18n/de.ts
index f52a8662469..a094cff2270 100644
--- a/apps/desktop/src/i18n/de.ts
+++ b/apps/desktop/src/i18n/de.ts
@@ -5274,6 +5274,8 @@ export const deOverrides = {
editing: 'Wird bearbeitet',
unsavedChanges: 'Nicht gespeicherte Änderungen',
saveFailed: message => `Speichern fehlgeschlagen: ${message}`,
+ saveScopeChanged:
+ 'Wechsle zur ursprünglichen Verbindung und zum ursprünglichen Profil zurück, um diesen Entwurf zu speichern.',
diskChangedTitle: 'Datei auf der Festplatte geändert',
diskChangedBody:
'Diese Datei wurde geändert, seit Sie sie geöffnet haben. Mit Ihrer Version überschreiben oder Ihre Änderungen verwerfen und neu laden?',
diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.ts
index 3bbcd5643a9..753cd043a9c 100644
--- a/apps/desktop/src/i18n/en.ts
+++ b/apps/desktop/src/i18n/en.ts
@@ -4894,6 +4894,7 @@ export const en: Translations = {
editing: 'Editing',
unsavedChanges: 'Unsaved changes',
saveFailed: message => `Couldn't save: ${message}`,
+ saveScopeChanged: 'Switch back to the original connection and profile to save this draft.',
diskChangedTitle: 'File changed on disk',
diskChangedBody:
'This file changed since you opened it. Overwrite it with your version, or discard your edits and reload?',
diff --git a/apps/desktop/src/i18n/es.ts b/apps/desktop/src/i18n/es.ts
index c9d1255b526..eeb2f49701e 100644
--- a/apps/desktop/src/i18n/es.ts
+++ b/apps/desktop/src/i18n/es.ts
@@ -5265,6 +5265,7 @@ export const esOverrides = {
editing: 'Edición',
unsavedChanges: 'Cambios no guardados',
saveFailed: message => `No se pudo guardar: ${message}`,
+ saveScopeChanged: 'Vuelve a la conexión y al perfil originales para guardar este borrador.',
diskChangedTitle: 'Archivo cambiado en el disco',
diskChangedBody:
'Este archivo cambió desde que lo abriste. ¿Quieres sobrescribirlo con tu versión o descartar tus cambios y recargar?',
diff --git a/apps/desktop/src/i18n/fr.ts b/apps/desktop/src/i18n/fr.ts
index d4d5f5a2682..0b5b9a72fb1 100644
--- a/apps/desktop/src/i18n/fr.ts
+++ b/apps/desktop/src/i18n/fr.ts
@@ -5288,6 +5288,7 @@ export const frOverrides = {
editing: 'Modification',
unsavedChanges: 'Modifications non enregistrées',
saveFailed: message => `Impossible d'enregistrer : ${message}`,
+ saveScopeChanged: 'Revenez à la connexion et au profil d’origine pour enregistrer ce brouillon.',
diskChangedTitle: 'Fichier modifié sur le disque',
diskChangedBody:
"Ce fichier a changé depuis que vous l'avez ouvert. L'écraser avec votre version, ou abandonner vos modifications et recharger ?",
diff --git a/apps/desktop/src/i18n/ja.ts b/apps/desktop/src/i18n/ja.ts
index 1ee3f9e64ce..69db7e9af4a 100644
--- a/apps/desktop/src/i18n/ja.ts
+++ b/apps/desktop/src/i18n/ja.ts
@@ -3616,6 +3616,7 @@ export const ja = defineLocale({
editing: '編集中',
unsavedChanges: '未保存の変更',
saveFailed: message => `保存できませんでした:${message}`,
+ saveScopeChanged: 'この下書きを保存するには、元の接続とプロファイルに戻ってください。',
diskChangedTitle: 'ファイルがディスク上で変更されました',
diskChangedBody:
'このファイルは開いてから変更されています。あなたの版で上書きするか、編集を破棄して再読み込みしますか?',
diff --git a/apps/desktop/src/i18n/ru.ts b/apps/desktop/src/i18n/ru.ts
index 32024b2d0c9..3d1274cfc24 100644
--- a/apps/desktop/src/i18n/ru.ts
+++ b/apps/desktop/src/i18n/ru.ts
@@ -3835,6 +3835,7 @@ export const ru = defineLocale({
editing: 'Изменение',
unsavedChanges: 'Несохранённые изменения',
saveFailed: message => `Не удалось сохранить: ${message}`,
+ saveScopeChanged: 'Чтобы сохранить этот черновик, вернитесь к исходному подключению и профилю.',
diskChangedTitle: 'Файл изменился на диске',
diskChangedBody:
'Этот файл изменился с момента открытия. Перезаписать его вашей версией или сбросить правки и перезагрузить?',
diff --git a/apps/desktop/src/i18n/types.ts b/apps/desktop/src/i18n/types.ts
index c53afa4a6d7..9b7ab4c2e1d 100644
--- a/apps/desktop/src/i18n/types.ts
+++ b/apps/desktop/src/i18n/types.ts
@@ -4142,6 +4142,7 @@ export interface Translations {
editing: string
unsavedChanges: string
saveFailed: (message: string) => string
+ saveScopeChanged: string
diskChangedTitle: string
diskChangedBody: string
overwrite: string
diff --git a/apps/desktop/src/i18n/zh-hant_artifacts.ts b/apps/desktop/src/i18n/zh-hant_artifacts.ts
index 40225d354ff..a8928fd8809 100644
--- a/apps/desktop/src/i18n/zh-hant_artifacts.ts
+++ b/apps/desktop/src/i18n/zh-hant_artifacts.ts
@@ -90,6 +90,7 @@ export const zhHantArtifacts = {
editing: '編輯中',
unsavedChanges: '未儲存的變更',
saveFailed: message => `無法儲存:${message}`,
+ saveScopeChanged: '請切換回原本的連線和設定檔以儲存此草稿。',
diskChangedTitle: '檔案已在磁碟上變更',
diskChangedBody: '此檔案自開啟以來已變更。用你的版本覆寫,還是放棄你的編輯並重新載入?',
overwrite: '覆寫',
diff --git a/apps/desktop/src/i18n/zh.ts b/apps/desktop/src/i18n/zh.ts
index fc9f55d5674..5ba2a7f8268 100644
--- a/apps/desktop/src/i18n/zh.ts
+++ b/apps/desktop/src/i18n/zh.ts
@@ -4588,6 +4588,7 @@ export const zh = defineLocale({
editing: '编辑中',
unsavedChanges: '未保存的更改',
saveFailed: message => `无法保存:${message}`,
+ saveScopeChanged: '请切换回原来的连接和配置文件以保存此草稿。',
diskChangedTitle: '文件已在磁盘上更改',
diskChangedBody: '此文件自打开以来已更改。用你的版本覆盖,还是放弃你的编辑并重新加载?',
overwrite: '覆盖',