Files
kandev/apps/web/hooks/use-file-save-delete.ts
T
José Almeida 214a8f5cce fix: scope multi-repo file editor open/save to the right repo (#1382)
* fix: scope multi-repo file editor open/save to the right repo

The editor open/save/sync/delete chain dropped the repository_name in
multi-repo task workspaces, so the backend resolved paths against the
bare task root and failed with "file not found". Thread the repo
subpath through openFile, save, sync, and delete, and store it on
FileEditorState.

* fix: pass repo from diff Edit button to multi-repo file editor

The diff/changes "Edit" button opened files without their repository
scope, so multi-repo files resolved against the bare task root and
failed with "file not found". Thread repository_name through the diff
and review toolbars into onOpenFile.

* fix: preserve repo across tab restore and stale syncs

Address review feedback: persisted file tabs dropped the repo subpath,
so a multi-repo file reopened against the bare task root after a browser
refresh. Persist and restore `repo` on StoredFileTab. Also guard the
workspace sync against a tab being swapped to a different repo mid-fetch,
and widen the remaining onOpenFile type declarations to carry repo.

* fix: thread repo into editor panel fallback fetch

Address review feedback: FileEditorPanel's useFileLoader fallback fetch
(triggered when the open-files map is transiently empty, e.g. after a
session switch) called requestFileContent without the repo subpath,
re-introducing the multi-repo "file not found" failure. Record repo on
the panel params and forward it through useFileLoader. Also assert the
full restored-tab shape in the local-storage round-trip test.

* fix: guard editor fetches against stale session/repo races

Address review feedback: file open and the panel fallback fetch could
apply a late response after the user navigated away. openFile now drops
the result if the active session changed mid-fetch (via fetchFileEditorState),
and the panel loader keys its in-flight guard by session+path+repo so a
changed target re-fetches and stale responses are discarded.
2026-06-15 17:59:05 +01:00

171 lines
5.9 KiB
TypeScript

"use client";
import { useCallback } from "react";
import { useDockviewStore, type FileEditorState } from "@/lib/state/dockview-store";
import { getWebSocketClient } from "@/lib/ws/connection";
import { updateFileContent, deleteFile } from "@/lib/ws/workspace-files";
import { generateUnifiedDiff, calculateHash } from "@/lib/utils/file-diff";
import type { useToast } from "@/components/toast-provider";
import { PREVIEW_FILE_EDITOR_ID } from "@/lib/state/dockview-panel-actions";
/** Read openFiles from the store without subscribing to changes. */
function getOpenFiles() {
return useDockviewStore.getState().openFiles;
}
/** Update dockview panel dirty state after a successful save. */
export function updatePanelAfterSave(path: string, name: string) {
const dockApi = useDockviewStore.getState().api;
const panel =
dockApi?.getPanel(`file:${path}`) ??
(() => {
const preview = dockApi?.getPanel(PREVIEW_FILE_EDITOR_ID);
return (preview?.params as Record<string, unknown> | undefined)?.previewItemId === path
? preview
: undefined;
})();
if (panel) {
panel.api.updateParameters({ ...(panel.params ?? {}), isDirty: false });
panel.setTitle(name);
}
}
/** Close the pinned (or preview) editor panel for a path after a remote delete. */
function closeFileEditorPanel(path: string) {
const dockApi = useDockviewStore.getState().api;
const pinned = dockApi?.getPanel(`file:${path}`);
if (pinned) {
dockApi?.removePanel(pinned);
return;
}
const preview = dockApi?.getPanel(PREVIEW_FILE_EDITOR_ID);
if (preview && (preview.params as Record<string, unknown>)?.previewItemId === path) {
dockApi?.removePanel(preview);
}
}
export type SaveDeleteParams = {
activeSessionIdRef: React.MutableRefObject<string | null>;
updateFileState: (path: string, updates: Partial<FileEditorState>) => void;
setSavingFiles: React.Dispatch<React.SetStateAction<Set<string>>>;
toast: ReturnType<typeof useToast>["toast"];
};
async function performSaveFile(path: string, params: SaveDeleteParams) {
const file = getOpenFiles().get(path);
if (!file || !file.isDirty) return;
const client = getWebSocketClient();
const currentSessionId = params.activeSessionIdRef.current;
if (!client || !currentSessionId) return;
params.setSavingFiles((prev) => new Set(prev).add(path));
try {
const diff = generateUnifiedDiff(file.originalContent, file.content, file.path);
const response = await updateFileContent(client, currentSessionId, {
path,
diff,
originalHash: file.originalHash,
desiredContent: file.content,
repo: file.repo,
});
if (response.success && response.new_hash) {
// Re-read current state: user may have typed more while the save was
// in flight. Only mark clean if content still matches what was saved.
const current = getOpenFiles().get(path);
const stillClean = current?.content === file.content;
params.updateFileState(path, {
originalContent: file.content,
originalHash: response.new_hash,
isDirty: !stillClean,
hasRemoteUpdate: false,
remoteContent: undefined,
remoteOriginalHash: undefined,
});
if (stillClean) updatePanelAfterSave(path, file.name);
if (response.resolution === "overwritten") {
params.toast({
title: "File saved (overwritten)",
description: "The file was modified externally. Your version was saved.",
variant: "default",
});
}
} else {
params.toast({
title: "Save failed",
description: response.error || "Failed to save file",
variant: "error",
});
}
} catch (error) {
params.toast({
title: "Save failed",
description:
error instanceof Error ? error.message : "An error occurred while saving the file",
variant: "error",
});
} finally {
params.setSavingFiles((prev) => {
const next = new Set(prev);
next.delete(path);
return next;
});
}
}
export function useSaveDeleteActions(params: SaveDeleteParams) {
const { activeSessionIdRef, updateFileState, toast } = params;
const saveFile = useCallback((path: string) => performSaveFile(path, params), [params]);
const deleteFileAction = useCallback(
async (path: string) => {
const client = getWebSocketClient();
const currentSessionId = activeSessionIdRef.current;
if (!client || !currentSessionId) return;
try {
const repo = getOpenFiles().get(path)?.repo;
const response = await deleteFile(client, currentSessionId, path, repo);
if (!response.success) {
toast({
title: "Delete failed",
description: response.error || "Failed to delete file",
variant: "error",
});
return;
}
} catch (error) {
toast({
title: "Delete failed",
description:
error instanceof Error ? error.message : "An error occurred while deleting the file",
variant: "error",
});
return;
}
// Close the panel only after the remote delete succeeds.
closeFileEditorPanel(path);
},
[activeSessionIdRef, toast],
);
const applyRemoteUpdate = useCallback(
async (path: string) => {
const file = getOpenFiles().get(path);
if (!file || !file.hasRemoteUpdate || file.remoteContent === undefined) return;
const remoteHash = file.remoteOriginalHash ?? (await calculateHash(file.remoteContent));
updateFileState(path, {
content: file.remoteContent,
originalContent: file.remoteContent,
originalHash: remoteHash,
isDirty: false,
hasRemoteUpdate: false,
remoteContent: undefined,
remoteOriginalHash: undefined,
});
updatePanelAfterSave(path, file.name);
},
[updateFileState],
);
return { saveFile, deleteFileAction, applyRemoteUpdate };
}