diff --git a/src/main/runtime/orca-runtime-files.test.ts b/src/main/runtime/orca-runtime-files.test.ts index 1ac31c38d..313b3a7bd 100644 --- a/src/main/runtime/orca-runtime-files.test.ts +++ b/src/main/runtime/orca-runtime-files.test.ts @@ -118,6 +118,7 @@ function mockLocalPathStats(entries: Record) { function createRuntimeFileCommands(options?: { path?: string + openFile?: ReturnType openDiff?: ReturnType resolveRuntimeGitTarget?: ReturnType }) { @@ -134,7 +135,7 @@ function createRuntimeFileCommands(options?: { path })), resolveRuntimeGitTarget: options?.resolveRuntimeGitTarget ?? vi.fn(), - openFile: vi.fn(), + openFile: options?.openFile ?? vi.fn(), ...(options?.openDiff ? { openDiff: options.openDiff } : {}) } as never) return { commands, store } @@ -187,7 +188,33 @@ describe('RuntimeFileCommands', () => { const result = await commands.openMobileDiff('id:wt-1', 'docs/readme.md', true) - expect(openDiff).toHaveBeenCalledWith('wt-1', '/repo/docs/readme.md', 'docs/readme.md', true) + expect(openDiff).toHaveBeenCalledWith( + 'wt-1', + '/repo/docs/readme.md', + 'docs/readme.md', + true, + 'runtime-1' + ) + expect(result).toEqual({ + worktree: 'wt-1', + relativePath: 'docs/readme.md', + kind: 'markdown', + opened: true + }) + }) + + it('opens text files through the renderer host with the runtime owner', async () => { + const openFile = vi.fn() + const { commands } = createRuntimeFileCommands({ openFile }) + + const result = await commands.openMobileFile('id:wt-1', 'docs/readme.md') + + expect(openFile).toHaveBeenCalledWith( + 'wt-1', + '/repo/docs/readme.md', + 'docs/readme.md', + 'runtime-1' + ) expect(result).toEqual({ worktree: 'wt-1', relativePath: 'docs/readme.md', diff --git a/src/main/runtime/orca-runtime-files.ts b/src/main/runtime/orca-runtime-files.ts index ecd8f98c3..dc5738a4e 100644 --- a/src/main/runtime/orca-runtime-files.ts +++ b/src/main/runtime/orca-runtime-files.ts @@ -120,8 +120,19 @@ export type RuntimeFileCommandHost = { resolveRuntimeGitTarget( selector: string ): Promise<{ worktree: ResolvedRuntimeFileWorktree; connectionId?: string }> - openFile(worktreeId: string, filePath: string, relativePath: string): void - openDiff(worktreeId: string, filePath: string, relativePath: string, staged: boolean): void + openFile( + worktreeId: string, + filePath: string, + relativePath: string, + runtimeEnvironmentId: string + ): void + openDiff( + worktreeId: string, + filePath: string, + relativePath: string, + staged: boolean, + runtimeEnvironmentId: string + ): void } export class RuntimeFileCommands { @@ -173,7 +184,7 @@ export class RuntimeFileCommands { return { worktree: worktree.id, relativePath, kind, opened: false } } const filePath = joinWorktreeRelativePath(worktree.path, relativePath) - this.host.openFile(worktree.id, filePath, relativePath) + this.host.openFile(worktree.id, filePath, relativePath, this.host.getRuntimeId()) return { worktree: worktree.id, relativePath, kind, opened: true } } @@ -192,7 +203,7 @@ export class RuntimeFileCommands { ? 'markdown' : 'text' const filePath = joinWorktreeRelativePath(worktree.path, relativePath) - this.host.openDiff(worktree.id, filePath, relativePath, staged) + this.host.openDiff(worktree.id, filePath, relativePath, staged, this.host.getRuntimeId()) return { worktree: worktree.id, relativePath, kind, opened: true } } diff --git a/src/main/runtime/orca-runtime.ts b/src/main/runtime/orca-runtime.ts index 4a3f80adc..b488e6f58 100644 --- a/src/main/runtime/orca-runtime.ts +++ b/src/main/runtime/orca-runtime.ts @@ -782,8 +782,19 @@ type RuntimeNotifier = { focusEditorTab?(tabId: string, worktreeId: string): void closeSessionTab?(tabId: string, worktreeId: string): void moveSessionTab?(worktreeId: string, move: RuntimeMobileSessionTabMove): void - openFile?(worktreeId: string, filePath: string, relativePath: string): void - openDiff?(worktreeId: string, filePath: string, relativePath: string, staged: boolean): void + openFile?( + worktreeId: string, + filePath: string, + relativePath: string, + runtimeEnvironmentId: string + ): void + openDiff?( + worktreeId: string, + filePath: string, + relativePath: string, + staged: boolean, + runtimeEnvironmentId: string + ): void readMobileMarkdownTab?(worktreeId: string, tabId: string): Promise saveMobileMarkdownTab?( worktreeId: string, @@ -2697,17 +2708,17 @@ export class OrcaRuntimeService { requireStore: () => this.requireStore(), resolveWorktreeSelector: (selector) => this.resolveWorktreeSelector(selector), resolveRuntimeGitTarget: (selector) => this.resolveRuntimeGitTarget(selector), - openFile: (worktreeId, filePath, relativePath) => { + openFile: (worktreeId, filePath, relativePath, runtimeEnvironmentId) => { if (!this.notifier?.openFile) { throw new Error('renderer_unavailable') } - this.notifier.openFile(worktreeId, filePath, relativePath) + this.notifier.openFile(worktreeId, filePath, relativePath, runtimeEnvironmentId) }, - openDiff: (worktreeId, filePath, relativePath, staged) => { + openDiff: (worktreeId, filePath, relativePath, staged, runtimeEnvironmentId) => { if (!this.notifier?.openDiff) { throw new Error('renderer_unavailable') } - this.notifier.openDiff(worktreeId, filePath, relativePath, staged) + this.notifier.openDiff(worktreeId, filePath, relativePath, staged, runtimeEnvironmentId) } }) diff --git a/src/main/window/attach-main-window-services.ts b/src/main/window/attach-main-window-services.ts index ca47dbb41..faf8f763f 100644 --- a/src/main/window/attach-main-window-services.ts +++ b/src/main/window/attach-main-window-services.ts @@ -365,10 +365,21 @@ function registerRuntimeWindowLifecycle( closeSessionTab: (tabId, worktreeId) => send('ui:closeSessionTab', { tabId, worktreeId }), moveSessionTab: (worktreeId: string, move: RuntimeMobileSessionTabMove) => send('ui:moveSessionTab', { worktreeId, ...move }), - openFile: (worktreeId, filePath, relativePath) => - send('ui:openFileFromMobile', { worktreeId, filePath, relativePath }), - openDiff: (worktreeId, filePath, relativePath, staged) => - send('ui:openDiffFromMobile', { worktreeId, filePath, relativePath, staged }), + openFile: (worktreeId, filePath, relativePath, runtimeEnvironmentId) => + send('ui:openFileFromMobile', { + worktreeId, + filePath, + relativePath, + runtimeEnvironmentId + }), + openDiff: (worktreeId, filePath, relativePath, staged, runtimeEnvironmentId) => + send('ui:openDiffFromMobile', { + worktreeId, + filePath, + relativePath, + staged, + runtimeEnvironmentId + }), readMobileMarkdownTab: (worktreeId, tabId) => requestMobileMarkdownFromRenderer(mainWindow, { operation: 'read', diff --git a/src/preload/api-types.ts b/src/preload/api-types.ts index 90fb1f3a1..0a735bc10 100644 --- a/src/preload/api-types.ts +++ b/src/preload/api-types.ts @@ -2163,7 +2163,12 @@ export type PreloadApi = { callback: (data: { worktreeId: string } & RuntimeMobileSessionTabMove) => void ) => () => void onOpenFileFromMobile: ( - callback: (data: { worktreeId: string; filePath: string; relativePath: string }) => void + callback: (data: { + worktreeId: string + filePath: string + relativePath: string + runtimeEnvironmentId: string + }) => void ) => () => void onOpenDiffFromMobile: ( callback: (data: { @@ -2171,6 +2176,7 @@ export type PreloadApi = { filePath: string relativePath: string staged: boolean + runtimeEnvironmentId: string }) => void ) => () => void onMobileMarkdownRequest: ( diff --git a/src/preload/index.ts b/src/preload/index.ts index 16fd77622..b968e9e66 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -2847,11 +2847,21 @@ const api = { return () => ipcRenderer.removeListener('ui:moveSessionTab', listener) }, onOpenFileFromMobile: ( - callback: (data: { worktreeId: string; filePath: string; relativePath: string }) => void + callback: (data: { + worktreeId: string + filePath: string + relativePath: string + runtimeEnvironmentId: string + }) => void ): (() => void) => { const listener = ( _event: Electron.IpcRendererEvent, - data: { worktreeId: string; filePath: string; relativePath: string } + data: { + worktreeId: string + filePath: string + relativePath: string + runtimeEnvironmentId: string + } ) => callback(data) ipcRenderer.on('ui:openFileFromMobile', listener) return () => ipcRenderer.removeListener('ui:openFileFromMobile', listener) @@ -2862,11 +2872,18 @@ const api = { filePath: string relativePath: string staged: boolean + runtimeEnvironmentId: string }) => void ): (() => void) => { const listener = ( _event: Electron.IpcRendererEvent, - data: { worktreeId: string; filePath: string; relativePath: string; staged: boolean } + data: { + worktreeId: string + filePath: string + relativePath: string + staged: boolean + runtimeEnvironmentId: string + } ) => callback(data) ipcRenderer.on('ui:openDiffFromMobile', listener) return () => ipcRenderer.removeListener('ui:openDiffFromMobile', listener) diff --git a/src/renderer/src/components/editor/editor-autosave-controller.ts b/src/renderer/src/components/editor/editor-autosave-controller.ts index a1b7ea008..5d5e170d8 100644 --- a/src/renderer/src/components/editor/editor-autosave-controller.ts +++ b/src/renderer/src/components/editor/editor-autosave-controller.ts @@ -89,7 +89,7 @@ export function attachEditorAutosaveController(store: AppStoreApi): () => void { // round-tripping back into a setContent that jumps the cursor to the // end (and, under round-trip drift, can drop keystrokes typed in the // debounce window). See editor-self-write-registry. - recordSelfWrite(liveFile.filePath, contentToSave) + recordSelfWrite(liveFile.filePath, contentToSave, liveFile.runtimeEnvironmentId) try { await writeRuntimeFile( { @@ -105,7 +105,7 @@ export function attachEditorAutosaveController(store: AppStoreApi): () => void { // Why: the self-write stamp is only valid if a disk write actually // happened. Clearing it on failure keeps the external watcher from // suppressing a real third-party update that lands during the TTL. - clearSelfWrite(liveFile.filePath) + clearSelfWrite(liveFile.filePath, liveFile.runtimeEnvironmentId) throw error } diff --git a/src/renderer/src/components/editor/editor-autosave.test.ts b/src/renderer/src/components/editor/editor-autosave.test.ts index 1157794b5..883978c79 100644 --- a/src/renderer/src/components/editor/editor-autosave.test.ts +++ b/src/renderer/src/components/editor/editor-autosave.test.ts @@ -193,4 +193,33 @@ describe('getOpenFilesForExternalFileChange', () => { ).map((file) => file.id) ).toEqual(['/repo/file.ts', 'markdown-preview::/repo/file.ts', 'wt-1::diff::unstaged::file.ts']) }) + + it('filters same-path matches by runtime owner when the watcher supplies one', () => { + const localEdit = makeOpenFile({ id: 'local-edit', runtimeEnvironmentId: null }) + const runtimeEdit = makeOpenFile({ id: 'runtime-edit', runtimeEnvironmentId: 'env-1' }) + const runtimeDiff = makeOpenFile({ + id: 'runtime-diff', + mode: 'diff', + diffSource: 'unstaged', + runtimeEnvironmentId: 'env-1' + }) + + expect( + getOpenFilesForExternalFileChange([localEdit, runtimeEdit, runtimeDiff], { + worktreeId: 'wt-1', + worktreePath: '/repo', + relativePath: 'file.ts', + runtimeEnvironmentId: null + }).map((file) => file.id) + ).toEqual(['local-edit']) + + expect( + getOpenFilesForExternalFileChange([localEdit, runtimeEdit, runtimeDiff], { + worktreeId: 'wt-1', + worktreePath: '/repo', + relativePath: 'file.ts', + runtimeEnvironmentId: 'env-1' + }).map((file) => file.id) + ).toEqual(['runtime-edit', 'runtime-diff']) + }) }) diff --git a/src/renderer/src/components/editor/editor-autosave.ts b/src/renderer/src/components/editor/editor-autosave.ts index 6985cf2ad..a1261ab45 100644 --- a/src/renderer/src/components/editor/editor-autosave.ts +++ b/src/renderer/src/components/editor/editor-autosave.ts @@ -19,6 +19,7 @@ export type EditorPathMutationTarget = { worktreeId: string worktreePath: string relativePath: string + runtimeEnvironmentId?: string | null } export type EditorSaveQuiesceTarget = { fileId: string } | EditorPathMutationTarget @@ -74,10 +75,18 @@ export function getOpenFilesForExternalFileChange( target: EditorPathMutationTarget ): OpenFile[] { const absolutePath = joinPath(target.worktreePath, target.relativePath) + const hasRuntimeOwnerFilter = Object.prototype.hasOwnProperty.call(target, 'runtimeEnvironmentId') + const targetRuntimeOwner = target.runtimeEnvironmentId?.trim() || null return openFiles.filter((file) => { if (file.worktreeId !== target.worktreeId) { return false } + if ( + hasRuntimeOwnerFilter && + (file.runtimeEnvironmentId?.trim() || null) !== targetRuntimeOwner + ) { + return false + } if (file.mode === 'edit' || file.mode === 'markdown-preview') { return file.filePath === absolutePath } diff --git a/src/renderer/src/components/editor/editor-self-write-registry.test.ts b/src/renderer/src/components/editor/editor-self-write-registry.test.ts index 8bc90df02..d05a98a40 100644 --- a/src/renderer/src/components/editor/editor-self-write-registry.test.ts +++ b/src/renderer/src/components/editor/editor-self-write-registry.test.ts @@ -38,6 +38,25 @@ describe('editor self-write registry', () => { expect(hasRecentSelfWrite('/repo/a.md')).toBe(false) }) + it('keeps same-path stamps isolated by runtime owner', () => { + recordSelfWrite('/repo/a.md', 'runtime save', 'env-1') + + expect(hasRecentSelfWrite('/repo/a.md', 'env-1')).toBe(true) + expect(hasRecentSelfWrite('/repo/a.md', null)).toBe(false) + + clearSelfWrite('/repo/a.md', null) + expect(hasRecentSelfWrite('/repo/a.md', 'env-1')).toBe(true) + + clearSelfWrite('/repo/a.md', 'env-1') + expect(hasRecentSelfWrite('/repo/a.md', 'env-1')).toBe(false) + }) + + it('trims runtime owner ids when matching stamps', () => { + recordSelfWrite('/repo/a.md', 'runtime save', ' env-1 ') + + expect(hasRecentSelfWrite('/repo/a.md', 'env-1')).toBe(true) + }) + it('prunes expired stamps when recording later writes', () => { recordSelfWrite('/repo/old.md') diff --git a/src/renderer/src/components/editor/editor-self-write-registry.ts b/src/renderer/src/components/editor/editor-self-write-registry.ts index 12829069e..561f4ec61 100644 --- a/src/renderer/src/components/editor/editor-self-write-registry.ts +++ b/src/renderer/src/components/editor/editor-self-write-registry.ts @@ -8,9 +8,9 @@ import { normalizeAbsolutePathForComparison } from '@/components/right-sidebar/f // getMarkdown() round-trip) can drift by a trailing newline or soft-break, // the reload can silently drop unsaved keystrokes as well. Stamping a path // right before writeFile lets the watch hook ignore the echo event without -// touching the editor at all. Keyed by normalized absolute path, bounded by -// a short TTL so a genuinely external edit that lands after the window still -// gets picked up. +// touching the editor at all. Keyed by runtime owner + normalized absolute +// path, bounded by a short TTL so a genuinely external edit that lands after +// the window still gets picked up. const SELF_WRITE_TTL_MS = 750 const SELF_WRITE_MAX_STAMPS = 256 @@ -24,6 +24,10 @@ type SelfWriteStamp = RecentSelfWrite & { const stamps = new Map() +function selfWriteKey(absolutePath: string, runtimeEnvironmentId?: string | null): string { + return `${runtimeEnvironmentId?.trim() || 'client'}::${normalizeAbsolutePathForComparison(absolutePath)}` +} + function pruneExpiredSelfWrites(now = Date.now()): void { for (const [key, stamp] of stamps) { if (now > stamp.expiresAt) { @@ -42,10 +46,14 @@ function enforceSelfWriteStampLimit(): void { } } -export function recordSelfWrite(absolutePath: string, content?: string): void { +export function recordSelfWrite( + absolutePath: string, + content?: string, + runtimeEnvironmentId?: string | null +): void { const now = Date.now() pruneExpiredSelfWrites(now) - const key = normalizeAbsolutePathForComparison(absolutePath) + const key = selfWriteKey(absolutePath, runtimeEnvironmentId) // Why: a missing watcher echo should not leave stale path/content stamps in // memory for the whole renderer session. stamps.delete(key) @@ -56,12 +64,15 @@ export function recordSelfWrite(absolutePath: string, content?: string): void { enforceSelfWriteStampLimit() } -export function clearSelfWrite(absolutePath: string): void { - stamps.delete(normalizeAbsolutePathForComparison(absolutePath)) +export function clearSelfWrite(absolutePath: string, runtimeEnvironmentId?: string | null): void { + stamps.delete(selfWriteKey(absolutePath, runtimeEnvironmentId)) } -export function getRecentSelfWrite(absolutePath: string): RecentSelfWrite | null { - const key = normalizeAbsolutePathForComparison(absolutePath) +export function getRecentSelfWrite( + absolutePath: string, + runtimeEnvironmentId?: string | null +): RecentSelfWrite | null { + const key = selfWriteKey(absolutePath, runtimeEnvironmentId) const stamp = stamps.get(key) if (!stamp) { return null @@ -73,8 +84,11 @@ export function getRecentSelfWrite(absolutePath: string): RecentSelfWrite | null return { content: stamp.content } } -export function hasRecentSelfWrite(absolutePath: string): boolean { - return getRecentSelfWrite(absolutePath) !== null +export function hasRecentSelfWrite( + absolutePath: string, + runtimeEnvironmentId?: string | null +): boolean { + return getRecentSelfWrite(absolutePath, runtimeEnvironmentId) !== null } export function __clearSelfWriteRegistryForTests(): void { diff --git a/src/renderer/src/components/right-sidebar/SourceControl.tsx b/src/renderer/src/components/right-sidebar/SourceControl.tsx index 44a420b44..83b057292 100644 --- a/src/renderer/src/components/right-sidebar/SourceControl.tsx +++ b/src/renderer/src/components/right-sidebar/SourceControl.tsx @@ -3857,13 +3857,16 @@ function SourceControlInner(): React.JSX.Element { if (!worktreePath || !activeWorktreeId) { return } + const runtimeEnvironmentId = + useAppStore.getState().settings?.activeRuntimeEnvironmentId?.trim() || null // Why: git discard replaces the working tree version of this file. Any // pending editor autosave must be quiesced first so it cannot recreate // the discarded edits after git restores the file. await requestEditorSaveQuiesce({ worktreeId: activeWorktreeId, worktreePath, - relativePath: filePath + relativePath: filePath, + runtimeEnvironmentId }) const connectionId = getConnectionId(activeWorktreeId ?? null) ?? undefined await discardRuntimeGitPath( @@ -3878,7 +3881,8 @@ function SourceControlInner(): React.JSX.Element { notifyEditorExternalFileChange({ worktreeId: activeWorktreeId, worktreePath, - relativePath: filePath + relativePath: filePath, + runtimeEnvironmentId }) }, [activeWorktreeId, worktreePath] @@ -3889,6 +3893,8 @@ function SourceControlInner(): React.JSX.Element { if (!worktreePath || !activeWorktreeId) { return } + const runtimeEnvironmentId = + useAppStore.getState().settings?.activeRuntimeEnvironmentId?.trim() || null // Why: bulk discard replaces many working-tree files at once. Quiesce // any matching editor autosaves before git mutates the files so a delayed // save cannot recreate edits after the restore. @@ -3897,7 +3903,8 @@ function SourceControlInner(): React.JSX.Element { requestEditorSaveQuiesce({ worktreeId: activeWorktreeId, worktreePath, - relativePath + relativePath, + runtimeEnvironmentId }) ) ) @@ -3915,7 +3922,8 @@ function SourceControlInner(): React.JSX.Element { notifyEditorExternalFileChange({ worktreeId: activeWorktreeId, worktreePath, - relativePath + relativePath, + runtimeEnvironmentId }) } }, diff --git a/src/renderer/src/hooks/useEditorExternalWatch-targets.test.ts b/src/renderer/src/hooks/useEditorExternalWatch-targets.test.ts index d6fc2c1c3..217015284 100644 --- a/src/renderer/src/hooks/useEditorExternalWatch-targets.test.ts +++ b/src/renderer/src/hooks/useEditorExternalWatch-targets.test.ts @@ -89,7 +89,7 @@ describe('getEditorExternalWatchTargets', () => { worktreeId: 'wt-1', worktreePath: '/repo-1/worktree', connectionId: undefined, - runtimeEnvironmentId: undefined + runtimeEnvironmentId: null } ]) }) @@ -123,7 +123,7 @@ describe('getEditorExternalWatchTargets', () => { worktreeId: 'wt-active-visible', worktreePath: '/repo-active-visible/worktree', connectionId: undefined, - runtimeEnvironmentId: undefined + runtimeEnvironmentId: null } ]) }) @@ -145,7 +145,7 @@ describe('getEditorExternalWatchTargets', () => { ).toEqual([]) }) - it('rebuilds targets when SSH connection or runtime environment identity changes', () => { + it('rebuilds ownerless targets when an SSH connection id hydrates', () => { const localRepo = makeRepo('repo-remote', null) const remoteRepo = makeRepo('repo-remote', 'ssh-1') const worktree = makeWorktree(localRepo.id, 'wt-remote') @@ -167,7 +167,81 @@ describe('getEditorExternalWatchTargets', () => { worktreeId: 'wt-remote', worktreePath: '/repo-remote/worktree', connectionId: 'ssh-1', - runtimeEnvironmentId: 'runtime-1' + runtimeEnvironmentId: null + } + ]) + }) + + it('creates separate watch targets for local and runtime-owned tabs in the same worktree', () => { + const repo = makeRepo('repo-mixed') + const worktree = makeWorktree(repo.id, 'wt-mixed') + const localFile = makeOpenFile(worktree.id) + const runtimeFile = { + ...makeOpenFile(worktree.id), + id: 'runtime-file', + runtimeEnvironmentId: 'env-1' + } + + expect( + getEditorExternalWatchTargets( + makeState({ + repo, + worktree, + openFiles: [localFile, runtimeFile], + runtimeEnvironmentId: null + }) + ).targets + ).toEqual([ + { + worktreeId: 'wt-mixed', + worktreePath: '/repo-mixed/worktree', + connectionId: undefined, + runtimeEnvironmentId: null + }, + { + worktreeId: 'wt-mixed', + worktreePath: '/repo-mixed/worktree', + connectionId: undefined, + runtimeEnvironmentId: 'env-1' + } + ]) + }) + + it('keeps restored ownerless tabs local when an active runtime is selected', () => { + const repo = makeRepo('repo-restored') + const worktree = makeWorktree(repo.id, 'wt-restored') + const restoredLocalFile = { + ...makeOpenFile(worktree.id), + id: 'restored-local-file', + runtimeEnvironmentId: undefined + } + const runtimeFile = { + ...makeOpenFile(worktree.id), + id: 'runtime-file', + runtimeEnvironmentId: 'env-1' + } + + expect( + getEditorExternalWatchTargets( + makeState({ + repo, + worktree, + openFiles: [restoredLocalFile, runtimeFile], + runtimeEnvironmentId: 'env-1' + }) + ).targets + ).toEqual([ + { + worktreeId: 'wt-restored', + worktreePath: '/repo-restored/worktree', + connectionId: undefined, + runtimeEnvironmentId: null + }, + { + worktreeId: 'wt-restored', + worktreePath: '/repo-restored/worktree', + connectionId: undefined, + runtimeEnvironmentId: 'env-1' } ]) }) diff --git a/src/renderer/src/hooks/useEditorExternalWatch.test.ts b/src/renderer/src/hooks/useEditorExternalWatch.test.ts index 61641c55e..c483d0c38 100644 --- a/src/renderer/src/hooks/useEditorExternalWatch.test.ts +++ b/src/renderer/src/hooks/useEditorExternalWatch.test.ts @@ -36,14 +36,14 @@ describe('getWatchedTargetKey', () => { worktreeId: 'wt-1', worktreePath: '/repo', connectionId: undefined, - runtimeEnvironmentId: undefined + runtimeEnvironmentId: null }) ).not.toBe( getWatchedTargetKey({ worktreeId: 'wt-1', worktreePath: '/repo', connectionId: 'conn-1', - runtimeEnvironmentId: undefined + runtimeEnvironmentId: null }) ) }) @@ -54,7 +54,7 @@ describe('getWatchedTargetKey', () => { worktreeId: 'wt-1', worktreePath: '/repo', connectionId: undefined, - runtimeEnvironmentId: undefined + runtimeEnvironmentId: null }) ).not.toBe( getWatchedTargetKey({ @@ -116,23 +116,70 @@ describe('getOverflowExternalReloadTargets', () => { { worktreeId: 'wt-1', worktreePath: '/repo', - relativePath: 'notes.md' + relativePath: 'notes.md', + runtimeEnvironmentId: null } ]) expect(setExternalMutation).toHaveBeenCalledWith('file-1', null) }) + + it('limits overflow reload targets to the matching runtime owner', () => { + vi.mocked(useAppStore.getState).mockReturnValue({ + openFiles: [ + { + id: 'local-file', + worktreeId: 'wt-1', + worktreePath: '/repo', + relativePath: 'local.md', + mode: 'edit', + isDirty: false, + externalMutation: 'deleted', + runtimeEnvironmentId: null + }, + { + id: 'runtime-file', + worktreeId: 'wt-1', + worktreePath: '/repo', + relativePath: 'runtime.md', + mode: 'edit', + isDirty: false, + externalMutation: 'deleted', + runtimeEnvironmentId: 'env-1' + } + ], + setExternalMutation + } as never) + + expect( + getOverflowExternalReloadTargets({ + worktreeId: 'wt-1', + worktreePath: '/repo', + runtimeEnvironmentId: 'env-1' + }) + ).toEqual([ + { + worktreeId: 'wt-1', + worktreePath: '/repo', + relativePath: 'runtime.md', + runtimeEnvironmentId: 'env-1' + } + ]) + expect(setExternalMutation).toHaveBeenCalledWith('runtime-file', null) + expect(setExternalMutation).not.toHaveBeenCalledWith('local-file', null) + }) }) describe('createExternalWatchEventHandler tombstone coalescing', () => { const setExternalMutation = vi.fn() const findTarget = ( - worktreePath: string + worktreePath: string, + runtimeEnvironmentId: string | null = null ): | { worktreeId: string worktreePath: string connectionId: string | undefined - runtimeEnvironmentId: string | undefined + runtimeEnvironmentId: string | null } | undefined => worktreePath === '/repo' @@ -140,7 +187,7 @@ describe('createExternalWatchEventHandler tombstone coalescing', () => { worktreeId: 'wt-1', worktreePath: '/repo', connectionId: undefined, - runtimeEnvironmentId: undefined + runtimeEnvironmentId } : undefined @@ -250,7 +297,8 @@ describe('createExternalWatchEventHandler tombstone coalescing', () => { expect(notifyEditorExternalFileChange).toHaveBeenCalledWith({ worktreeId: 'wt-win', worktreePath: 'C:\\Repo', - relativePath: 'notes.md' + relativePath: 'notes.md', + runtimeEnvironmentId: 'env-1' }) dispose() }) @@ -286,7 +334,8 @@ describe('createExternalWatchEventHandler tombstone coalescing', () => { expect(notifyEditorExternalFileChange).toHaveBeenCalledWith({ worktreeId: 'wt-unc', worktreePath: '//Server/Share/Repo', - relativePath: 'notes.md' + relativePath: 'notes.md', + runtimeEnvironmentId: 'env-1' }) dispose() }) @@ -308,7 +357,8 @@ describe('createExternalWatchEventHandler tombstone coalescing', () => { expect(notifyEditorExternalFileChange).toHaveBeenCalledWith({ worktreeId: 'wt-1', worktreePath: '/repo', - relativePath: 'notes.md' + relativePath: 'notes.md', + runtimeEnvironmentId: null }) dispose() }) @@ -330,4 +380,89 @@ describe('createExternalWatchEventHandler tombstone coalescing', () => { expect(notifyEditorExternalFileChange).not.toHaveBeenCalled() dispose() }) + + it('does not let a local self-write stamp suppress a runtime owner update', async () => { + const runtimeFile = { + ...fileNotes, + runtimeEnvironmentId: 'env-1' + } + vi.mocked(useAppStore.getState).mockReturnValue({ + openFiles: [runtimeFile], + setExternalMutation + } as never) + vi.mocked(getOpenFilesForExternalFileChange).mockReturnValue([runtimeFile] as never) + const readFile = vi.fn().mockResolvedValue({ content: 'local save', isBinary: false }) + vi.stubGlobal('window', { api: { fs: { readFile } } }) + const { handleFsChanged, dispose } = createExternalWatchEventHandler(findTarget) + + recordSelfWrite('/repo/notes.md', 'local save', null) + handleFsChanged(payload([{ kind: 'update', absolutePath: '/repo/notes.md' }]), 'env-1') + await vi.advanceTimersByTimeAsync(100) + + expect(notifyEditorExternalFileChange).toHaveBeenCalledWith({ + worktreeId: 'wt-1', + worktreePath: '/repo', + relativePath: 'notes.md', + runtimeEnvironmentId: 'env-1' + }) + dispose() + }) + + it('routes local and runtime watch events to the matching editor owner', () => { + const localFile = fileNotes + const runtimeFile = { + ...fileNotes, + id: 'runtime-notes', + runtimeEnvironmentId: 'env-1' + } + vi.mocked(useAppStore.getState).mockReturnValue({ + openFiles: [localFile, runtimeFile], + setExternalMutation + } as never) + vi.mocked(getOpenFilesForExternalFileChange).mockImplementation((_files, notification) => + notification.runtimeEnvironmentId === 'env-1' + ? ([runtimeFile] as never) + : ([localFile] as never) + ) + const { handleFsChanged, dispose } = createExternalWatchEventHandler(findTarget) + + handleFsChanged(payload([{ kind: 'update', absolutePath: '/repo/notes.md' }]), null) + handleFsChanged(payload([{ kind: 'update', absolutePath: '/repo/notes.md' }]), 'env-1') + vi.advanceTimersByTime(100) + + expect(notifyEditorExternalFileChange).toHaveBeenCalledWith({ + worktreeId: 'wt-1', + worktreePath: '/repo', + relativePath: 'notes.md', + runtimeEnvironmentId: null + }) + expect(notifyEditorExternalFileChange).toHaveBeenCalledWith({ + worktreeId: 'wt-1', + worktreePath: '/repo', + relativePath: 'notes.md', + runtimeEnvironmentId: 'env-1' + }) + dispose() + }) + + it('tombstones only the matching owner for same-path delete events', () => { + const localFile = fileNotes + const runtimeFile = { + ...fileNotes, + id: 'runtime-notes', + runtimeEnvironmentId: 'env-1' + } + vi.mocked(useAppStore.getState).mockReturnValue({ + openFiles: [localFile, runtimeFile], + setExternalMutation + } as never) + const { handleFsChanged, dispose } = createExternalWatchEventHandler(findTarget) + + handleFsChanged(payload([{ kind: 'delete', absolutePath: '/repo/notes.md' }]), 'env-1') + vi.advanceTimersByTime(200) + + expect(setExternalMutation).toHaveBeenCalledWith('runtime-notes', 'deleted') + expect(setExternalMutation).not.toHaveBeenCalledWith('file-notes', 'deleted') + dispose() + }) }) diff --git a/src/renderer/src/hooks/useEditorExternalWatch.ts b/src/renderer/src/hooks/useEditorExternalWatch.ts index a47b7b148..9e29725d0 100644 --- a/src/renderer/src/hooks/useEditorExternalWatch.ts +++ b/src/renderer/src/hooks/useEditorExternalWatch.ts @@ -45,8 +45,9 @@ function scheduleDebouncedExternalReload(notification: { worktreeId: string worktreePath: string relativePath: string + runtimeEnvironmentId: string | null }): void { - const key = `${notification.worktreeId}::${notification.relativePath}` + const key = `${notification.worktreeId}::${notification.runtimeEnvironmentId ?? 'client'}::${notification.relativePath}` const existing = pendingExternalReloadTimers.get(key) if (existing !== undefined) { globalThis.clearTimeout(existing) @@ -62,13 +63,14 @@ type WatchedTarget = { worktreeId: string worktreePath: string connectionId: string | undefined - runtimeEnvironmentId: string | undefined + runtimeEnvironmentId: string | null } type ExternalWatchNotification = { worktreeId: string worktreePath: string relativePath: string + runtimeEnvironmentId: string | null } type WatchedTargetsSnapshot = { @@ -103,6 +105,10 @@ export function getWatchedTargetKey(target: WatchedTarget): string { return `${target.worktreeId}::${target.worktreePath}::${target.connectionId ?? 'local'}::${target.runtimeEnvironmentId ?? 'client'}` } +function openFileRuntimeOwner(file: Pick): string | null { + return file.runtimeEnvironmentId?.trim() || null +} + export function getEditorExternalWatchTargets( state: EditorExternalWatchTargetState ): WatchedTargetsSnapshot { @@ -119,36 +125,55 @@ export function getEditorExternalWatchTargets( return cachedWatchedTargetsSnapshot } - const ids = new Set() - // Why: only the set of worktree IDs matters for watcher ownership. Dirty - // flags and editor metadata can churn while typing/saving, but should not - // re-render App or rebuild watch subscriptions. + const targetOwnersByWorktreeId = new Map>() + // Why: watcher ownership is scoped by both worktree and runtime owner. + // The same path can be open locally and in a runtime-backed workspace at + // once; reads/saves already route per tab owner, so live reloads must too. for (const f of state.openFiles) { - ids.add(f.worktreeId) + let owners = targetOwnersByWorktreeId.get(f.worktreeId) + if (!owners) { + owners = new Set() + targetOwnersByWorktreeId.set(f.worktreeId, owners) + } + // Why: persisted/restored local tabs may have runtimeEnvironmentId + // undefined. New openFile calls resolve active-runtime inheritance before + // storing the tab, so an ownerless stored tab must stay local here. + owners.add(openFileRuntimeOwner(f)) } if (state.activeWorktreeId && state.rightSidebarOpen && state.rightSidebarTab === 'explorer') { // Why: the right sidebar stays mounted while hidden; do not create a // worktree-level watcher just because the user clicked a workspace. // macOS can surface privacy prompts for those passive filesystem probes. - ids.add(state.activeWorktreeId) + let owners = targetOwnersByWorktreeId.get(state.activeWorktreeId) + if (!owners) { + owners = new Set() + targetOwnersByWorktreeId.set(state.activeWorktreeId, owners) + } + owners.add(runtimeEnvironmentId ?? null) } const nextTargets: WatchedTarget[] = [] const parts: string[] = [] - for (const id of Array.from(ids).sort()) { + const sortedWorktreeIds = Array.from(targetOwnersByWorktreeId.keys()).sort() + for (const id of sortedWorktreeIds) { const wt = findWorktreeById(state.worktreesByRepo, id) if (!wt) { continue } const repo = state.repos.find((r) => r.id === wt.repoId) - const target = { - worktreeId: id, - worktreePath: wt.path, - connectionId: repo?.connectionId ?? undefined, - runtimeEnvironmentId + const owners = Array.from(targetOwnersByWorktreeId.get(id) ?? []).sort((a, b) => + (a ?? '').localeCompare(b ?? '') + ) + for (const owner of owners) { + const target = { + worktreeId: id, + worktreePath: wt.path, + connectionId: repo?.connectionId ?? undefined, + runtimeEnvironmentId: owner + } + nextTargets.push(target) + parts.push(getWatchedTargetKey(target)) } - nextTargets.push(target) - parts.push(getWatchedTargetKey(target)) } const targetsKey = parts.join('|') @@ -174,8 +199,10 @@ export function getEditorExternalWatchTargets( // flickers struck-through for one render before the follow-up create clears // it. Debouncing just the 'deleted' signal — keyed by absolute path — lets a // same-path create in the next payload cancel the tombstone before it ever -// paints. A naked delete still resolves to 'deleted' after the window. The -// in-payload rename correlation is unchanged. +// paints. Key by owner as well as path so local/runtime tabs for the same +// worktree file cannot cancel each other's tombstones. A naked delete still +// resolves to 'deleted' after the window. The in-payload rename correlation +// is unchanged. const EXTERNAL_MUTATION_DEBOUNCE_MS = 75 type PendingDeleteTimer = { @@ -204,7 +231,9 @@ export function useEditorExternalWatch(): void { const latestTargetsRef = useRef(targets) latestTargetsRef.current = targets const remoteWatchUnsubsRef = useRef(new Map void>()) - const fsChangedHandlerRef = useRef<((payload: FsChangedPayload) => void) | null>(null) + const fsChangedHandlerRef = useRef< + ((payload: FsChangedPayload, runtimeEnvironmentId?: string | null) => void) | null + >(null) // Why: diff previous vs next targets so unchanged worktrees keep their // existing subscription. Tearing down every subscription on each targetsKey @@ -246,7 +275,7 @@ export function useEditorExternalWatch(): void { worktreePath: target.worktreePath, connectionId: target.connectionId }, - (payload) => fsChangedHandlerRef.current?.(payload), + (payload) => fsChangedHandlerRef.current?.(payload, target.runtimeEnvironmentId), (err) => warnExternalWatchFailure(target, err) ) .then((unsubscribe) => { @@ -292,14 +321,16 @@ export function useEditorExternalWatch(): void { // change (which would otherwise miss events fired during re-subscription). useEffect(() => { const remoteWatchUnsubs = remoteWatchUnsubsRef.current - const { handleFsChanged, dispose } = createExternalWatchEventHandler((worktreePath) => - targetsRef.current.find( - (t) => - normalizeRuntimePathForComparison(t.worktreePath) === - normalizeRuntimePathForComparison(worktreePath) - ) + const { handleFsChanged, dispose } = createExternalWatchEventHandler( + (worktreePath, runtimeEnvironmentId) => + targetsRef.current.find( + (t) => + normalizeRuntimePathForComparison(t.worktreePath) === + normalizeRuntimePathForComparison(worktreePath) && + t.runtimeEnvironmentId === runtimeEnvironmentId + ) ) - const unsubscribe = window.api.fs.onFsChanged(handleFsChanged) + const unsubscribe = window.api.fs.onFsChanged((payload) => handleFsChanged(payload, null)) fsChangedHandlerRef.current = handleFsChanged return () => { @@ -340,9 +371,12 @@ export function useEditorExternalWatch(): void { * `EXTERNAL_MUTATION_DEBOUNCE_MS` for the macOS atomic-write rationale. */ export function createExternalWatchEventHandler( - findTarget: (worktreePath: string) => WatchedTarget | undefined + findTarget: ( + worktreePath: string, + runtimeEnvironmentId: string | null + ) => WatchedTarget | undefined ): { - handleFsChanged: (payload: FsChangedPayload) => void + handleFsChanged: (payload: FsChangedPayload, runtimeEnvironmentId?: string | null) => void dispose: () => void } { // Why: coalesce 'deleted' tombstones across back-to-back payloads so a @@ -350,11 +384,17 @@ export function createExternalWatchEventHandler( // cancels the tombstone before the tab flashes. Keyed by normalized // absolute path, scoped per-target. See EXTERNAL_MUTATION_DEBOUNCE_MS. const pendingDeletes = new Map() - const pendingKey = (worktreeId: string, absolutePath: string): string => - `${worktreeId}::${absolutePath}` + const pendingKey = ( + worktreeId: string, + runtimeEnvironmentId: string | null, + absolutePath: string + ): string => `${worktreeId}::${runtimeEnvironmentId ?? 'client'}::${absolutePath}` - const handleFsChanged = (payload: FsChangedPayload): void => { - const target = findTarget(payload.worktreePath) + const handleFsChanged = ( + payload: FsChangedPayload, + runtimeEnvironmentId: string | null = null + ): void => { + const target = findTarget(payload.worktreePath, runtimeEnvironmentId) if (!target) { return } @@ -372,7 +412,7 @@ export function createExternalWatchEventHandler( } } for (const createdPath of createOrUpdatePaths) { - const key = pendingKey(target.worktreeId, createdPath) + const key = pendingKey(target.worktreeId, target.runtimeEnvironmentId, createdPath) const existing = pendingDeletes.get(key) if (existing) { clearTimeout(existing.timer) @@ -392,6 +432,7 @@ export function createExternalWatchEventHandler( const deletedOpenEditorIds = collectDeletedOpenEditorIds( payload, target.worktreeId, + target.runtimeEnvironmentId, openFilesAtStart ) // Why: correlate creates to deletes by basename OR parent directory to @@ -417,6 +458,7 @@ export function createExternalWatchEventHandler( const deletePathByFileId = buildDeletePathByFileId( payload, target.worktreeId, + target.runtimeEnvironmentId, deletedOpenEditorIds, openFilesAtStart ) @@ -425,7 +467,7 @@ export function createExternalWatchEventHandler( if (!absolutePath) { continue } - const key = pendingKey(target.worktreeId, absolutePath) + const key = pendingKey(target.worktreeId, target.runtimeEnvironmentId, absolutePath) const existing = pendingDeletes.get(key) if (existing) { clearTimeout(existing.timer) @@ -459,6 +501,7 @@ export function createExternalWatchEventHandler( for (const file of state.openFiles) { if ( file.worktreeId === target.worktreeId && + openFileRuntimeOwner(file) === target.runtimeEnvironmentId && (file.mode === 'edit' || file.mode === 'markdown-preview') && file.externalMutation && createOrUpdatePaths.has(normalizeRuntimePathForComparison(file.filePath)) @@ -520,7 +563,8 @@ export function createExternalWatchEventHandler( const notification = { worktreeId: target.worktreeId, worktreePath: target.worktreePath, - relativePath + relativePath, + runtimeEnvironmentId: target.runtimeEnvironmentId } const matching = getOpenFilesForExternalFileChange(openFilesSnapshot, notification) if (matching.length === 0) { @@ -530,7 +574,7 @@ export function createExternalWatchEventHandler( continue } const absolutePath = joinPath(notification.worktreePath, notification.relativePath) - const recentSelfWrite = getRecentSelfWrite(absolutePath) + const recentSelfWrite = getRecentSelfWrite(absolutePath, target.runtimeEnvironmentId) if (recentSelfWrite) { scheduleSelfWriteAwareExternalReload(target, notification, matching[0], recentSelfWrite) continue @@ -578,13 +622,13 @@ function scheduleSelfWriteAwareExternalReload( (result.isBinary || result.content !== recentSelfWrite.content) && hasCleanExternalReloadTarget(notification) ) { - clearSelfWrite(file.filePath) + clearSelfWrite(file.filePath, runtimeEnvironmentId) scheduleDebouncedExternalReload(notification) } }) .catch(() => { if (hasCleanExternalReloadTarget(notification)) { - clearSelfWrite(file.filePath) + clearSelfWrite(file.filePath, runtimeEnvironmentId) scheduleDebouncedExternalReload(notification) } }) @@ -596,7 +640,9 @@ function hasCleanExternalReloadTarget(notification: ExternalWatchNotification): } export function getOverflowExternalReloadTargets( - target: Pick + target: Pick & { + runtimeEnvironmentId?: string | null + } ): ExternalWatchNotification[] { const state = useAppStore.getState() const notifications: ExternalWatchNotification[] = [] @@ -604,6 +650,7 @@ export function getOverflowExternalReloadTargets( for (const file of state.openFiles) { if ( file.worktreeId !== target.worktreeId || + openFileRuntimeOwner(file) !== (target.runtimeEnvironmentId ?? null) || (file.mode !== 'edit' && file.mode !== 'markdown-preview') || file.isDirty ) { @@ -620,7 +667,8 @@ export function getOverflowExternalReloadTargets( notifications.push({ worktreeId: target.worktreeId, worktreePath: target.worktreePath, - relativePath: file.relativePath + relativePath: file.relativePath, + runtimeEnvironmentId: target.runtimeEnvironmentId ?? null }) } @@ -630,6 +678,7 @@ export function getOverflowExternalReloadTargets( function buildDeletePathByFileId( payload: FsChangedPayload, worktreeId: string, + runtimeEnvironmentId: string | null, deletedOpenEditorIds: string[], openFiles: OpenFile[] ): Map { @@ -645,7 +694,11 @@ function buildDeletePathByFileId( } const deletedIdSet = new Set(deletedOpenEditorIds) for (const file of openFiles) { - if (!deletedIdSet.has(file.id) || file.worktreeId !== worktreeId) { + if ( + !deletedIdSet.has(file.id) || + file.worktreeId !== worktreeId || + openFileRuntimeOwner(file) !== runtimeEnvironmentId + ) { continue } const normalized = normalizeRuntimePathForComparison(file.filePath) @@ -659,6 +712,7 @@ function buildDeletePathByFileId( function collectDeletedOpenEditorIds( payload: FsChangedPayload, worktreeId: string, + runtimeEnvironmentId: string | null, openFiles: OpenFile[] ): string[] { const deletePaths = new Set() @@ -674,6 +728,7 @@ function collectDeletedOpenEditorIds( for (const file of openFiles) { if ( file.worktreeId !== worktreeId || + openFileRuntimeOwner(file) !== runtimeEnvironmentId || (file.mode !== 'edit' && file.mode !== 'markdown-preview') ) { continue diff --git a/src/renderer/src/hooks/useIpcEvents.ts b/src/renderer/src/hooks/useIpcEvents.ts index ff3c097e5..2bfae42a0 100644 --- a/src/renderer/src/hooks/useIpcEvents.ts +++ b/src/renderer/src/hooks/useIpcEvents.ts @@ -1366,41 +1366,48 @@ export function useIpcEvents(): void { ) unsubs.push( - window.api.ui.onOpenFileFromMobile(({ worktreeId, filePath, relativePath }) => { - const store = useAppStore.getState() - const basename = relativePath.split(/[\\/]/).pop() || relativePath - store.setActiveWorktree(worktreeId) - store.markWorktreeVisited(worktreeId) - store.setActiveView('terminal') - // Why: mobile only sends a desktop-backed path. The renderer owns - // editor tab creation so grouped tab order and markdown bridges update - // through the same store path as desktop File Explorer. - store.openFile({ - filePath, - relativePath, - worktreeId, - language: detectLanguage(basename), - mode: 'edit' - }) - store.setActiveTabType('editor') - store.revealWorktreeInSidebar(worktreeId) - }) + window.api.ui.onOpenFileFromMobile( + ({ worktreeId, filePath, relativePath, runtimeEnvironmentId }) => { + const store = useAppStore.getState() + const basename = relativePath.split(/[\\/]/).pop() || relativePath + store.setActiveWorktree(worktreeId) + store.markWorktreeVisited(worktreeId) + store.setActiveView('terminal') + // Why: mobile only sends a desktop-backed path. The renderer owns + // editor tab creation so grouped tab order and markdown bridges update + // through the same store path as desktop File Explorer. + store.openFile({ + filePath, + relativePath, + worktreeId, + language: detectLanguage(basename), + runtimeEnvironmentId, + mode: 'edit' + }) + store.setActiveTabType('editor') + store.revealWorktreeInSidebar(worktreeId) + } + ) ) unsubs.push( - window.api.ui.onOpenDiffFromMobile(({ worktreeId, filePath, relativePath, staged }) => { - const store = useAppStore.getState() - const language = detectLanguage(relativePath) - store.setActiveWorktree(worktreeId) - store.markWorktreeVisited(worktreeId) - store.setActiveView('terminal') - // Why: mobile renders diff tabs from diff metadata. The desktop - // markdown Changes-mode shortcut is editor-local and would publish - // plain markdown content back to mobile. - store.openDiff(worktreeId, filePath, relativePath, language, staged) - store.setActiveTabType('editor') - store.revealWorktreeInSidebar(worktreeId) - }) + window.api.ui.onOpenDiffFromMobile( + ({ worktreeId, filePath, relativePath, staged, runtimeEnvironmentId }) => { + const store = useAppStore.getState() + const language = detectLanguage(relativePath) + store.setActiveWorktree(worktreeId) + store.markWorktreeVisited(worktreeId) + store.setActiveView('terminal') + // Why: mobile renders diff tabs from diff metadata. The desktop + // markdown Changes-mode shortcut is editor-local and would publish + // plain markdown content back to mobile. + store.openDiff(worktreeId, filePath, relativePath, language, staged, { + runtimeEnvironmentId + }) + store.setActiveTabType('editor') + store.revealWorktreeInSidebar(worktreeId) + } + ) ) unsubs.push( diff --git a/src/renderer/src/store/slices/editor.test.ts b/src/renderer/src/store/slices/editor.test.ts index 1d1c1bfae..d39c5d714 100644 --- a/src/renderer/src/store/slices/editor.test.ts +++ b/src/renderer/src/store/slices/editor.test.ts @@ -289,6 +289,26 @@ describe('createEditorSlice openDiff', () => { ]) }) + it('keeps local and runtime-owned diffs in separate tabs for the same path', () => { + const store = createEditorStore() + + store.getState().openDiff('wt-1', '/repo/file.ts', 'file.ts', 'typescript', false) + store.getState().openDiff('wt-1', '/repo/file.ts', 'file.ts', 'typescript', false, { + runtimeEnvironmentId: 'env-1' + }) + + expect(store.getState().openFiles).toEqual([ + expect.objectContaining({ + id: 'wt-1::diff::unstaged::file.ts', + runtimeEnvironmentId: undefined + }), + expect.objectContaining({ + id: 'editor-diff:wt-1:env-1:unstaged:file.ts', + runtimeEnvironmentId: 'env-1' + }) + ]) + }) + it('repairs an existing diff tab entry to the correct mode and staged state', () => { const store = createEditorStore() diff --git a/src/renderer/src/store/slices/editor.ts b/src/renderer/src/store/slices/editor.ts index 469f2c06a..bbac16559 100644 --- a/src/renderer/src/store/slices/editor.ts +++ b/src/renderer/src/store/slices/editor.ts @@ -204,6 +204,7 @@ const MAX_RECENT_CLOSED_EDITOR_TABS = 10 type EditorOpenTargetOptions = { targetGroupId?: string preview?: boolean + runtimeEnvironmentId?: string | null } export type PendingEditorReveal = { @@ -780,6 +781,19 @@ function buildOwnedEditorFileId( return `editor:${encodeURIComponent(worktreeId)}:${encodeURIComponent(runtimeKey)}:${encodeURIComponent(filePath)}` } +function buildDiffEditorFileId( + worktreeId: string, + diffSource: DiffSource, + relativePath: string, + runtimeEnvironmentId: string | null | undefined +): string { + const legacyId = `${worktreeId}::diff::${diffSource}::${relativePath}` + const runtimeKey = runtimeOwnerKey(runtimeEnvironmentId) + return runtimeKey + ? `editor-diff:${encodeURIComponent(worktreeId)}:${encodeURIComponent(runtimeKey)}:${encodeURIComponent(diffSource)}:${encodeURIComponent(relativePath)}` + : legacyId +} + function isEditorFileIdOccupiedByOtherOwner( file: Pick< OpenFile, @@ -2264,10 +2278,13 @@ export const createEditorSlice: StateCreator = (s openDiff: (worktreeId, filePath, relativePath, language, staged, options) => { const isPreview = options?.preview ?? false + const runtimeEnvironmentId = options?.runtimeEnvironmentId let editorItemTargetGroupId = options?.targetGroupId + let editorItemFileId = '' set((s) => { const diffSource: DiffSource = staged ? 'staged' : 'unstaged' - const id = `${worktreeId}::diff::${diffSource}::${relativePath}` + const id = buildDiffEditorFileId(worktreeId, diffSource, relativePath, runtimeEnvironmentId) + editorItemFileId = id const targetGroupId = resolveEditorOpenTargetGroupId(s, worktreeId, options?.targetGroupId) ?? undefined editorItemTargetGroupId = targetGroupId @@ -2277,7 +2294,8 @@ export const createEditorSlice: StateCreator = (s const needsUpdate = existing.mode !== 'diff' || existing.diffSource !== diffSource || - existing.isPreview !== updatedPreview + existing.isPreview !== updatedPreview || + existing.runtimeEnvironmentId !== runtimeEnvironmentId return { openFiles: needsUpdate ? s.openFiles.map((f) => @@ -2289,7 +2307,8 @@ export const createEditorSlice: StateCreator = (s conflict: undefined, skippedConflicts: undefined, conflictReview: undefined, - isPreview: updatedPreview + isPreview: updatedPreview, + runtimeEnvironmentId } : f ) @@ -2312,7 +2331,8 @@ export const createEditorSlice: StateCreator = (s conflict: undefined, skippedConflicts: undefined, conflictReview: undefined, - isPreview: isPreview || undefined + isPreview: isPreview || undefined, + runtimeEnvironmentId: options?.runtimeEnvironmentId } if (isPreview) { const replaceablePreviewId = getReplaceablePreviewFileId(s, worktreeId, targetGroupId) @@ -2342,7 +2362,7 @@ export const createEditorSlice: StateCreator = (s }) void openWorkspaceEditorItem( get(), - `${worktreeId}::diff::${staged ? 'staged' : 'unstaged'}::${relativePath}`, + editorItemFileId, worktreeId, relativePath, 'diff',