From 6a29f29adbb7da53f3fb676e0a476b7ecd1dc48e Mon Sep 17 00:00:00 2001 From: Jinjing <6427696+AmethystLiang@users.noreply.github.com> Date: Sun, 21 Jun 2026 02:52:51 -0700 Subject: [PATCH] Fix folder workspace file connection resolution (#5973) --- .../components/editor/CombinedDiffViewer.tsx | 4 +- .../editor/editor-autosave-controller.test.ts | 59 +++++++++++++++++++ .../editor/editor-autosave-controller.ts | 5 +- .../src/lib/connection-context.test.ts | 56 ++++++++++++++++++ src/renderer/src/lib/connection-context.ts | 20 +++++-- .../runtime/mobile-markdown-bridge.test.ts | 2 +- .../src/runtime/mobile-markdown-bridge.ts | 4 +- 7 files changed, 137 insertions(+), 13 deletions(-) diff --git a/src/renderer/src/components/editor/CombinedDiffViewer.tsx b/src/renderer/src/components/editor/CombinedDiffViewer.tsx index 1a09dc27e..0cb35eab6 100644 --- a/src/renderer/src/components/editor/CombinedDiffViewer.tsx +++ b/src/renderer/src/components/editor/CombinedDiffViewer.tsx @@ -11,7 +11,7 @@ import { useAppStore } from '@/store' import { joinPath } from '@/lib/path' import { detectLanguage } from '@/lib/language-detect' import { setWithLRU } from '@/lib/scroll-cache' -import { getConnectionId } from '@/lib/connection-context' +import { getConnectionId, getConnectionIdForFile } from '@/lib/connection-context' import { findWorktreeById } from '@/store/slices/worktree-helpers' import { writeRuntimeFile } from '@/runtime/runtime-file-client' import { settingsForRuntimeOwner } from '@/runtime/runtime-rpc-client' @@ -974,7 +974,7 @@ export default function CombinedDiffViewer({ const content = modifiedEditor?.getValue() ?? section.modifiedContent const absolutePath = joinPath(file.filePath, section.path) try { - const connectionId = getConnectionId(file.worktreeId) ?? undefined + const connectionId = getConnectionIdForFile(file.worktreeId, absolutePath) ?? undefined const state = useAppStore.getState() const worktree = file.worktreeId ? findWorktreeById(state.worktreesByRepo, file.worktreeId) diff --git a/src/renderer/src/components/editor/editor-autosave-controller.test.ts b/src/renderer/src/components/editor/editor-autosave-controller.test.ts index bf72600a8..8493536a2 100644 --- a/src/renderer/src/components/editor/editor-autosave-controller.test.ts +++ b/src/renderer/src/components/editor/editor-autosave-controller.test.ts @@ -17,6 +17,15 @@ import { type RuntimeEnvironmentCallRequest } from '@/runtime/runtime-compatibility-test-fixture' import { clearRuntimeCompatibilityCacheForTests } from '@/runtime/runtime-rpc-client' +import { folderWorkspaceKey } from '../../../../shared/workspace-scope' + +const mocks = vi.hoisted(() => ({ + getConnectionIdForFile: vi.fn() +})) + +vi.mock('@/lib/connection-context', () => ({ + getConnectionIdForFile: mocks.getConnectionIdForFile +})) type WindowStub = { addEventListener: Window['addEventListener'] @@ -127,6 +136,8 @@ function makeSessionReadyState(): Partial { describe('attachEditorAutosaveController', () => { beforeEach(() => { vi.useFakeTimers() + mocks.getConnectionIdForFile.mockReset() + mocks.getConnectionIdForFile.mockReturnValue(undefined) }) afterEach(() => { @@ -177,6 +188,54 @@ describe('attachEditorAutosaveController', () => { } }) + it('saves folder workspace files through the path-specific SSH connection', async () => { + const writeFile = vi.fn().mockResolvedValue(undefined) + const eventTarget = new EventTarget() + vi.stubGlobal('window', { + addEventListener: eventTarget.addEventListener.bind(eventTarget), + removeEventListener: eventTarget.removeEventListener.bind(eventTarget), + dispatchEvent: eventTarget.dispatchEvent.bind(eventTarget), + setTimeout: globalThis.setTimeout.bind(globalThis), + clearTimeout: globalThis.clearTimeout.bind(globalThis), + api: { + fs: { + writeFile + } + } + } satisfies WindowStub) + + const store = createEditorStore() + const workspaceKey = folderWorkspaceKey('folder-workspace-1') + mocks.getConnectionIdForFile.mockReturnValue('ssh-1') + store.getState().openFile({ + filePath: '/home/neil/platform/api/src/file.ts', + relativePath: 'api/src/file.ts', + worktreeId: workspaceKey, + language: 'typescript', + mode: 'edit' + }) + store.getState().setEditorDraft('/home/neil/platform/api/src/file.ts', 'edited') + store.getState().markFileDirty('/home/neil/platform/api/src/file.ts', true) + + const cleanup = attachEditorAutosaveController(store) + try { + await requestDirtyFileSave() + + expect(mocks.getConnectionIdForFile).toHaveBeenCalledWith( + workspaceKey, + '/home/neil/platform/api/src/file.ts' + ) + expect(writeFile).toHaveBeenCalledWith({ + filePath: '/home/neil/platform/api/src/file.ts', + content: 'edited', + connectionId: 'ssh-1' + }) + expect(store.getState().openFiles[0]?.isDirty).toBe(false) + } finally { + cleanup() + } + }) + it('saves remote files through the owning runtime environment', async () => { clearRuntimeCompatibilityCacheForTests() const writeFile = vi.fn().mockResolvedValue(undefined) diff --git a/src/renderer/src/components/editor/editor-autosave-controller.ts b/src/renderer/src/components/editor/editor-autosave-controller.ts index d67975db4..23de3fecd 100644 --- a/src/renderer/src/components/editor/editor-autosave-controller.ts +++ b/src/renderer/src/components/editor/editor-autosave-controller.ts @@ -4,7 +4,7 @@ avoids split-brain saves across visible and hidden editors. */ import type { StoreApi } from 'zustand' import type { AppState } from '@/store' import type { OpenFile } from '@/store/slices/editor' -import { getConnectionId } from '@/lib/connection-context' +import { getConnectionIdForFile } from '@/lib/connection-context' import { buildWorkspaceSessionPayload, shouldPersistWorkspaceSession @@ -81,7 +81,8 @@ export function attachEditorAutosaveController(store: AppStoreApi): () => void { } const contentToSave = state.editorDrafts[file.id] ?? fallbackContent - const connectionId = getConnectionId(liveFile.worktreeId) ?? undefined + const connectionId = + getConnectionIdForFile(liveFile.worktreeId, liveFile.filePath) ?? undefined const worktree = liveFile.worktreeId ? findWorktreeById(state.worktreesByRepo ?? {}, liveFile.worktreeId) : null diff --git a/src/renderer/src/lib/connection-context.test.ts b/src/renderer/src/lib/connection-context.test.ts index bfcff5a1a..225ea00fd 100644 --- a/src/renderer/src/lib/connection-context.test.ts +++ b/src/renderer/src/lib/connection-context.test.ts @@ -316,4 +316,60 @@ describe('getConnectionId', () => { expect(getConnectionId(folderWorkspaceKey('folder-workspace-1'))).toBe('ssh-1') }) + + it('keeps normalized same-path folder repo ambiguity when resolving files', () => { + const workspaceKey = folderWorkspaceKey('folder-workspace-1') + useAppStore.setState({ + folderWorkspaces: [ + { + id: 'folder-workspace-1', + projectGroupId: 'group-1', + name: 'Platform workspace', + folderPath: '/home/neil/platform', + linkedTask: null, + comment: '', + isArchived: false, + isUnread: false, + isPinned: false, + sortOrder: 1, + lastActivityAt: 0, + createdAt: 1, + updatedAt: 1 + } + ], + projectGroups: [ + { + id: 'group-1', + name: 'Platform', + parentPath: '/home/neil/platform', + parentGroupId: null, + createdFrom: 'folder-scan', + tabOrder: 0, + isCollapsed: false, + color: null, + createdAt: 1, + updatedAt: 1 + } + ], + repos: [ + makeRepo({ + id: 'repo-ssh-1', + path: '/home/neil/platform/api', + projectGroupId: 'group-1', + connectionId: 'ssh-1' + }), + makeRepo({ + id: 'repo-ssh-2', + path: '/home/neil/platform/api/', + projectGroupId: 'group-1', + connectionId: 'ssh-2' + }) + ], + worktreesByRepo: {} + }) + + expect( + getConnectionIdForFile(workspaceKey, '/home/neil/platform/api/src/index.ts') + ).toBeUndefined() + }) }) diff --git a/src/renderer/src/lib/connection-context.ts b/src/renderer/src/lib/connection-context.ts index 8a4083e1c..ea8303b00 100644 --- a/src/renderer/src/lib/connection-context.ts +++ b/src/renderer/src/lib/connection-context.ts @@ -1,7 +1,10 @@ import { useAppStore } from '@/store' import { getRepoIdFromWorktreeId } from '../../../shared/worktree-id' import { parseWorkspaceKey } from '../../../shared/workspace-scope' -import { isPathInsideOrEqual } from '../../../shared/cross-platform-path' +import { + isPathInsideOrEqual, + normalizeRuntimePathForComparison +} from '../../../shared/cross-platform-path' import { getFolderWorkspaceCandidateRepos, getFolderWorkspaceConnectionId @@ -64,12 +67,17 @@ function resolveConnectionIdForRepoPath( ): string | null | undefined { const matchingRepos = repos .filter((repo) => isPathInsideOrEqual(repo.path, filePath)) - .sort((a, b) => b.path.length - a.path.length) - const longestPath = matchingRepos[0]?.path - if (!longestPath) { + .map((repo) => ({ repo, normalizedPath: normalizeRuntimePathForComparison(repo.path) })) + .sort((a, b) => b.normalizedPath.length - a.normalizedPath.length) + const longestPathLength = matchingRepos[0]?.normalizedPath.length + if (!longestPathLength) { return undefined } - const bestMatches = matchingRepos.filter((repo) => repo.path.length === longestPath.length) - const connectionIds = new Set(bestMatches.map((repo) => repo.connectionId ?? null)) + // Why: containment normalizes separators/trailing slashes; ambiguity checks + // need the same representation or equal repo roots can be hidden. + const bestMatches = matchingRepos.filter( + (candidate) => candidate.normalizedPath.length === longestPathLength + ) + const connectionIds = new Set(bestMatches.map(({ repo }) => repo.connectionId ?? null)) return connectionIds.size === 1 ? ([...connectionIds][0] ?? null) : undefined } diff --git a/src/renderer/src/runtime/mobile-markdown-bridge.test.ts b/src/renderer/src/runtime/mobile-markdown-bridge.test.ts index 5e7b71b3d..3db4c3201 100644 --- a/src/renderer/src/runtime/mobile-markdown-bridge.test.ts +++ b/src/renderer/src/runtime/mobile-markdown-bridge.test.ts @@ -15,7 +15,7 @@ vi.mock('@/components/tab-bar/group-tab-order', () => ({ })) vi.mock('@/lib/connection-context', () => ({ - getConnectionId: () => null + getConnectionIdForFile: () => null })) type WindowStub = { diff --git a/src/renderer/src/runtime/mobile-markdown-bridge.ts b/src/renderer/src/runtime/mobile-markdown-bridge.ts index a54cd6932..6f9303224 100644 --- a/src/renderer/src/runtime/mobile-markdown-bridge.ts +++ b/src/renderer/src/runtime/mobile-markdown-bridge.ts @@ -6,7 +6,7 @@ import { type EditorFileSavedDetail } from '@/components/editor/editor-autosave' import { flushPendingEditorChange } from '@/components/editor/editor-pending-flush' -import { getConnectionId } from '@/lib/connection-context' +import { getConnectionIdForFile } from '@/lib/connection-context' import { useAppStore } from '@/store' import type { OpenFile } from '@/store/slices/editor' import { readRuntimeFileContent } from './runtime-file-client' @@ -239,7 +239,7 @@ async function readCurrentContent( } async function readFileContent(file: OpenFile): Promise { - const connectionId = getConnectionId(file.worktreeId) ?? undefined + const connectionId = getConnectionIdForFile(file.worktreeId, file.filePath) ?? undefined const state = useAppStore.getState() const result = (await readRuntimeFileContent({ settings: settingsForRuntimeOwner(state.settings, file.runtimeEnvironmentId),