Skip to content

A desktop coding agent with free access to frontier models.

TypeScript

fix: safer editor saves and review

ogsamrat1045ac6a20be
diff --git a/apps/app/src/react-app/domains/session/chat/session-page.tsx b/apps/app/src/react-app/domains/session/chat/session-page.tsx
index 72b72441..9cab2535 100644
--- a/apps/app/src/react-app/domains/session/chat/session-page.tsx
+++ b/apps/app/src/react-app/domains/session/chat/session-page.tsx
@@ -789,6 +789,18 @@ export function SessionPage(props: SessionPageProps) {
const closeRightPane = useCallback(() => {
setCurrentSidePanel(null);
}, [setCurrentSidePanel]);
+ // The editor stays open when the chat changes (a new chat starting, another chat picked):
+ // a chat that never had a side panel of its own gets the editor the last one had.
+ const lastSidePanel = useRef<{ key: string; panel: SidePanelItem | null }>({ key: sidePanelSessionKey, panel: sessionSidePanel });
+ useEffect(() => {
+ const last = lastSidePanel.current;
+ if (last.key !== sidePanelSessionKey && last.panel === "editor") {
+ const own = useUiStateStore.getState().sidePanelState[sidePanelSessionKey];
+ if (own === undefined) setSidePanelState(sidePanelSessionKey, "editor");
+ }
+ lastSidePanel.current = { key: sidePanelSessionKey, panel: useUiStateStore.getState().sidePanelState[sidePanelSessionKey] ?? (last.key !== sidePanelSessionKey && last.panel === "editor" ? "editor" : null) };
+ }, [sessionSidePanel, setSidePanelState, sidePanelSessionKey]);
+
// Cmd/Ctrl+Shift+E toggles the editor; Cmd/Ctrl+P opens it with quick open (use-shell-shortcuts.ts).
const editorShowRequest = useEditorStore((state) => state.showRequest);
const editorToggleRequest = useEditorStore((state) => state.toggleRequest);
@@ -2065,7 +2077,7 @@ export function SessionPage(props: SessionPageProps) {
<ResizableHandle className="hidden bg-transparent lg:flex" />
<ResizablePanel
panelRef={browserPanelRef}
- defaultSize={`${activeSidePanel === "extensions" ? Math.max(browserPanelDefaultWidth, 480) : activeSidePanel === "editor" ? Math.max(browserPanelDefaultWidth, 640) : browserPanelDefaultWidth}px`}
+ defaultSize={`${activeSidePanel === "extensions" ? Math.max(browserPanelDefaultWidth, 480) : activeSidePanel === "editor" ? Math.max(browserPanelDefaultWidth, 560) : browserPanelDefaultWidth}px`}
minSize={activeSidePanel === "extensions" ? "420px" : activeSidePanel === "editor" ? "420px" : "320px"}
maxSize="70%"
className="min-h-0 overflow-hidden pl-2 lg:flex lg:flex-col"
diff --git a/apps/app/src/react-app/domains/session/editor/editor-models.ts b/apps/app/src/react-app/domains/session/editor/editor-models.ts
index 3a7eb26d..cadcc5a0 100644
--- a/apps/app/src/react-app/domains/session/editor/editor-models.ts
+++ b/apps/app/src/react-app/domains/session/editor/editor-models.ts
@@ -18,6 +18,8 @@ export type FileDoc = {
savedVersion: number;
/** The file changed on disk while this document had unsaved changes. */
conflict: boolean;
+ /** The file is gone from disk (deleted since it was opened, or an agent deletion under review). */
+ missing: boolean;
};
export type OpenResult =
@@ -67,7 +69,7 @@ export class EditorDocuments {
if (file.binary) return { ok: false, reason: "binary", message: "This file is binary and cannot be edited here." };
if (file.tooLarge || file.content === null) return { ok: false, reason: "too_large", message: "This file is too large to open in the editor (over 5 MB)." };
const model = this.monaco.editor.createModel(file.content, languageForPath(path), this.uri(path));
- const doc: FileDoc = { path, model, updatedAt: file.updatedAt, savedVersion: model.getAlternativeVersionId(), conflict: false };
+ const doc: FileDoc = { path, model, updatedAt: file.updatedAt, savedVersion: model.getAlternativeVersionId(), conflict: false, missing: false };
this.docs.set(path, doc);
this.track(doc);
return { ok: true, doc };
@@ -88,7 +90,7 @@ export class EditorDocuments {
const existing = this.docs.get(path);
if (existing) return existing;
const model = this.monaco.editor.createModel("", languageForPath(path), this.uri(path));
- const doc: FileDoc = { path, model, updatedAt: null, savedVersion: model.getAlternativeVersionId(), conflict: false };
+ const doc: FileDoc = { path, model, updatedAt: null, savedVersion: model.getAlternativeVersionId(), conflict: false, missing: true };
this.docs.set(path, doc);
this.track(doc);
return doc;
@@ -110,6 +112,7 @@ export class EditorDocuments {
doc.updatedAt = result.updatedAt;
doc.savedVersion = version;
doc.conflict = false;
+ doc.missing = false;
useEditorStore.getState().setDirty(this.workspaceId, path, this.isDirty(doc));
return { ok: true };
} catch (error) {
@@ -128,6 +131,7 @@ export class EditorDocuments {
const doc = this.docs.get(path);
if (doc) {
doc.updatedAt = null;
+ doc.missing = true;
doc.savedVersion = doc.model.getAlternativeVersionId();
useEditorStore.getState().setDirty(this.workspaceId, path, false);
}
@@ -148,17 +152,32 @@ export class EditorDocuments {
try {
file = await this.client.editorReadFile(this.workspaceId, doc.path);
} catch (error) {
- if ((error as { status?: number }).status === 404 && doc.updatedAt !== null && !this.isDirty(doc)) {
+ // Deleted on disk: a clean document empties and says so; a dirty one keeps the user's text.
+ if ((error as { status?: number }).status === 404 && !doc.missing) {
+ if (this.isDirty(doc)) {
+ doc.conflict = true;
+ return;
+ }
+ if (doc.model.getValueLength() > 0) doc.model.pushEditOperations([], [{ range: doc.model.getFullModelRange(), text: "" }], () => null);
doc.updatedAt = null;
+ doc.missing = true;
+ doc.savedVersion = doc.model.getAlternativeVersionId();
+ useEditorStore.getState().setDirty(this.workspaceId, doc.path, false);
}
return;
}
- if (file.content === null || file.updatedAt === doc.updatedAt) return;
+ if (file.content === null) return;
const current = doc.model.getValue(this.monaco.editor.EndOfLinePreference.TextDefined);
+ doc.missing = false;
if (current === file.content) {
+ // Same text as on disk: the document is clean (also after a discard).
doc.updatedAt = file.updatedAt;
+ doc.conflict = false;
+ doc.savedVersion = doc.model.getAlternativeVersionId();
+ useEditorStore.getState().setDirty(this.workspaceId, doc.path, false);
return;
}
+ if (file.updatedAt === doc.updatedAt) return;
if (this.isDirty(doc)) {
doc.conflict = true;
return;
@@ -192,6 +211,26 @@ export class EditorDocuments {
return model;
}
+ /** Closes clean documents nobody shows (no tab, not under review), so a long session does not keep every file it touched. */
+ evict(keep: ReadonlySet<string>): void {
+ for (const [path, doc] of this.docs) {
+ if (keep.has(path) || this.isDirty(doc) || doc.conflict) continue;
+ doc.model.dispose();
+ this.docs.delete(path);
+ }
+ }
+
+ /** Review "before" models of reviews other than these keys. */
+ disposeReviewModels(keepKeys: ReadonlySet<string>): void {
+ for (const model of this.monaco.editor.getModels()) {
+ const uri = model.uri;
+ if (uri.scheme !== "omnirush-base" || !uri.path.startsWith("/review/")) continue;
+ if (uri.authority !== this.uri("x").authority) continue;
+ const key = uri.path.slice("/review/".length).split("/")[0] ?? "";
+ if (!keepKeys.has(key) && !model.isAttachedToEditor()) model.dispose();
+ }
+ }
+
dispose(): void {
for (const doc of this.docs.values()) doc.model.dispose();
for (const model of this.baselines.values()) model.dispose();
diff --git a/apps/app/src/react-app/domains/session/editor/editor-panel.tsx b/apps/app/src/react-app/domains/session/editor/editor-panel.tsx
index 6508cc58..1e68eb04 100644
--- a/apps/app/src/react-app/domains/session/editor/editor-panel.tsx
+++ b/apps/app/src/react-app/domains/session/editor/editor-panel.tsx
@@ -65,6 +65,8 @@ const EMPTY_FILES: string[] = [];
type ReviewFile = TurnFileChange & {
/** The file before the reviewed turns; null when the turns created it; undefined when it could not be worked out. */
baseline: string | null | undefined;
+ /** The file on disk when the review loaded (null: not there), for files without an open document. */
+ current: string | null;
};
type ReviewData = { key: string; turns: number; files: ReviewFile[] };
@@ -105,14 +107,21 @@ async function loadAgentChanges(input: {
if (scope === "turn") break;
}
const paths = [...new Set(turns.flat().map((change) => change.path))].slice(0, MAX_REVIEW_FILES);
+ // "Before" is worked out from the text on disk, never from an open buffer (it may hold unsaved
+ // edits, or the text from before the turn until it refreshes).
const current = new Map<string, string | null>();
const unreadable = new Set<string>();
await Promise.all(paths.map(async (path) => {
- const opened = await docs.open(path);
- if (opened.ok) current.set(path, opened.doc.model.getValue());
- else if (opened.reason === "missing") current.set(path, null);
- else unreadable.add(path);
+ try {
+ const file = await docs.client.editorReadFile(docs.workspaceId, path);
+ if (file.content === null) unreadable.add(path);
+ else current.set(path, file.content);
+ } catch (error) {
+ if ((error as { status?: number }).status === 404) current.set(path, null);
+ else unreadable.add(path);
+ }
}));
+ await docs.refresh(paths.filter((path) => docs.get(path)));
const baselines = baselinesForTurns(turns, (path) => current.get(path) ?? null);
// Binary or very large files are listed without a review diff.
for (const path of unreadable) baselines.set(path, undefined);
@@ -128,6 +137,7 @@ async function loadAgentChanges(input: {
additions: (previous?.additions ?? 0) + change.additions,
deletions: (previous?.deletions ?? 0) + change.deletions,
baseline: baselines.get(change.path),
+ current: current.get(change.path) ?? null,
});
}
}
@@ -231,8 +241,12 @@ function FilesView(props: {
unsafeCSS: TREE_CSS,
});
const search = useFileTreeSearch(model);
- useEffect(() => model.resetPaths(props.files), [model, props.files]);
- useEffect(() => model.setGitStatus(treeGitStatus(props.git)), [model, props.git, props.files]);
+ useEffect(() => {
+ model.resetPaths(props.files);
+ }, [model, props.files]);
+ useEffect(() => {
+ model.setGitStatus(treeGitStatus(props.git));
+ }, [model, props.git, props.files]);
useEffect(() => {
if (!props.selected) return;
const item = model.getItem(props.selected);
@@ -302,9 +316,9 @@ function ChangesView(props: {
key={scope}
type="button"
onClick={() => props.onScope(scope)}
- className={cn("rounded-md px-2 py-0.5", props.scope === scope ? "bg-background text-foreground shadow-sm" : "text-muted-foreground")}
+ className={cn("whitespace-nowrap rounded-md px-1.5 py-0.5", props.scope === scope ? "bg-background text-foreground shadow-sm" : "text-muted-foreground")}
>
- {scope === "turn" ? "Last turn" : "Whole chat"}
+ {scope === "turn" ? "Last turn" : "All turns"}
</button>
))}
</div>
@@ -399,7 +413,7 @@ function GitView(props: {
className="opacity-60 group-hover:opacity-100"
aria-label={isStaged ? `Unstage ${file.path}` : `Stage ${file.path}`}
disabled={props.busy}
- onClick={() => props.onStage([file.path], !isStaged)}
+ onClick={() => props.onStage(isStaged && file.from ? [file.path, file.from] : [file.path], !isStaged)}
>
{isStaged ? <Minus /> : <Plus />}
</Button>
@@ -450,7 +464,7 @@ function GitView(props: {
<div className="min-h-0 flex-1 overflow-y-auto px-1 pb-2">
<div className="flex items-center px-2 pt-1 pb-0.5 text-[10.5px] font-medium uppercase tracking-wide text-muted-foreground">
<span className="flex-1">Staged ({staged.length})</span>
- {staged.length ? <button type="button" className="hover:text-foreground" onClick={() => props.onStage(staged.map((file) => file.path), false)}>Unstage all</button> : null}
+ {staged.length ? <button type="button" className="hover:text-foreground" onClick={() => props.onStage(staged.flatMap((file) => (file.from ? [file.path, file.from] : [file.path])), false)}>Unstage all</button> : null}
</div>
{staged.map((file) => row(file, true))}
<div className="flex items-center px-2 pt-2 pb-0.5 text-[10.5px] font-medium uppercase tracking-wide text-muted-foreground">
@@ -488,7 +502,7 @@ export default function EditorPanel(props: EditorPanelProps) {
const treeQuery = useQuery({
queryKey: ["editor-tree", workspaceId] as const,
queryFn: () => client.editorTree(workspaceId),
- staleTime: 15_000,
+ staleTime: 30_000,
refetchOnWindowFocus: true,
});
const gitQuery = useQuery({
@@ -523,33 +537,62 @@ export default function EditorPanel(props: EditorPanelProps) {
// Back in the window: files may have changed outside the app.
useEffect(() => {
- const onFocus = () => void docs.refresh();
+ let last = 0;
+ const onFocus = () => {
+ // At most every 5 s: switching windows quickly must not re-read every open file each time.
+ if (Date.now() - last < 5_000) return;
+ last = Date.now();
+ void docs.refresh();
+ };
window.addEventListener("focus", onFocus);
return () => window.removeEventListener("focus", onFocus);
}, [docs]);
// ── review state ───────────────────────────────────────────────────────
const reviewKey = review?.key ?? null;
+ // Older reviews' "before" models and documents nobody shows are let go when a new review loads.
+ const recentReviewKeys = useRef<string[]>([]);
+ useEffect(() => {
+ if (!reviewKey) return;
+ recentReviewKeys.current = [reviewKey, ...recentReviewKeys.current.filter((key) => key !== reviewKey)].slice(0, 2);
+ docs.disposeReviewModels(new Set(recentReviewKeys.current));
+ const keep = new Set<string>([
+ ...useEditorStore.getState().byWorkspace[workspaceId]?.tabs.map((tab) => tab.path) ?? [],
+ ...(review?.files.map((file) => file.path) ?? []),
+ ]);
+ docs.evict(keep);
+ }, [docs, review, reviewKey, workspaceId]);
const baselineModel = useCallback((file: ReviewFile) => {
// Created once per review (key + path): accepting a hunk edits it, and a refetch must not undo that.
const uri = docs.uri(`review/${reviewKey}/${file.path}`, "omnirush-base");
const existing = monaco.editor.getModel(uri);
if (existing) return existing;
// A file fully reviewed before a restart stays reviewed while its text is the one that was reviewed.
- const current = docs.get(file.path)?.model.getValue() ?? null;
+ const current = docs.get(file.path)?.model.getValue() ?? file.current;
const reviewed = current !== null && reviewKey !== null && isReviewed(reviewKey, file.path, current);
return monaco.editor.createModel(reviewed ? current : file.baseline ?? "", languageForPath(file.path), uri);
}, [docs, monaco, reviewKey]);
const modifiedFor = useCallback((file: ReviewFile): FileDoc => {
return docs.get(file.path) ?? docs.openMissing(file.path);
}, [docs]);
+ /** The file's document, read from disk first when it is not open yet (an agent deletion: an empty one). */
+ const loadModified = useCallback(async (file: ReviewFile): Promise<FileDoc | null> => {
+ const existing = docs.get(file.path);
+ if (existing) return existing;
+ if (file.current === null) return docs.openMissing(file.path);
+ const opened = await docs.open(file.path);
+ if (opened.ok) return opened.doc;
+ toast.error(opened.message);
+ return null;
+ }, [docs]);
+ /** The file's text now: its document when open, else the disk text the review loaded with. */
+ const textNow = useCallback((file: ReviewFile) => docs.get(file.path)?.model.getValue() ?? file.current ?? "", [docs]);
const isPending = useCallback((file: ReviewFile) => {
if (file.baseline === undefined) return false;
const base = baselineModel(file).getValue();
- const now = docs.get(file.path)?.model.getValue() ?? "";
- return base !== now;
+ return base !== textNow(file);
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [baselineModel, docs, reviewTick]);
+ }, [baselineModel, textNow, reviewTick]);
// Remembers files whose review is finished (before === now), so a restart does not ask again.
useEffect(() => {
@@ -558,8 +601,8 @@ export default function EditorPanel(props: EditorPanelProps) {
if (file.baseline === undefined) continue;
const uri = docs.uri(`review/${reviewKey}/${file.path}`, "omnirush-base");
const base = monaco.editor.getModel(uri)?.getValue();
- const now = docs.get(file.path)?.model.getValue();
- if (base !== undefined && now !== undefined && base === now) markReviewed(reviewKey, file.path, now);
+ const now = docs.get(file.path)?.model.getValue() ?? file.current ?? "";
+ if (base !== undefined && base === now) markReviewed(reviewKey, file.path, now);
}
}, [docs, monaco, reviewFiles, reviewKey, reviewTick]);
@@ -590,35 +633,61 @@ export default function EditorPanel(props: EditorPanelProps) {
setLines(base, acceptHunk(base.getLinesContent(), doc.model.getLinesContent(), hunk), false);
reportReview(file.path, "accept", hunkCounts(hunk), "hunk");
setReviewTick((value) => value + 1);
+ return true;
}, [baselineModel, modifiedFor, reportReview]);
+ /** Rejecting writes the file: not while the agent works on it, and not over the user's unsaved edits. */
+ const canReject = useCallback((doc: FileDoc) => {
+ if (sessionBusy) {
+ toast("Wait for the agent's turn to finish before rejecting changes.");
+ return false;
+ }
+ if (docs.isDirty(doc)) {
+ toast(`${doc.path} has unsaved edits: save or discard them first.`);
+ return false;
+ }
+ return true;
+ }, [docs, sessionBusy]);
+
const rejectOne = useCallback((file: ReviewFile, hunk: LineHunk) => {
const base = baselineModel(file);
const doc = modifiedFor(file);
+ if (!canReject(doc)) return false;
setLines(doc.model, rejectHunk(base.getLinesContent(), doc.model.getLinesContent(), hunk), true);
reportReview(file.path, "reject", hunkCounts(hunk), "hunk");
setReviewTick((value) => value + 1);
void writeReviewed(file, doc);
- }, [baselineModel, modifiedFor, reportReview, writeReviewed]);
+ return true;
+ }, [baselineModel, canReject, modifiedFor, reportReview, writeReviewed]);
- const acceptFiles = useCallback((list: ReviewFile[]) => {
+ const acceptFiles = useCallback(async (list: ReviewFile[]) => {
for (const file of list) {
+ const doc = await loadModified(file);
+ if (!doc) return;
const base = baselineModel(file);
- base.setValue(modifiedFor(file).model.getValue());
+ base.setValue(doc.model.getValue());
reportReview(file.path, "accept", { added: file.additions, removed: file.deletions }, "file");
}
setReviewTick((value) => value + 1);
- }, [baselineModel, modifiedFor, reportReview]);
+ }, [baselineModel, loadModified, reportReview]);
const rejectFiles = useCallback(async (list: ReviewFile[]) => {
for (const file of list) {
- const doc = modifiedFor(file);
+ const doc = await loadModified(file);
+ if (!doc || !canReject(doc)) return;
doc.model.pushEditOperations([], [{ range: doc.model.getFullModelRange(), text: baselineModel(file).getValue() }], () => null);
reportReview(file.path, "reject", { added: file.additions, removed: file.deletions }, "file");
await writeReviewed(file, doc);
}
setReviewTick((value) => value + 1);
- }, [baselineModel, modifiedFor, reportReview, writeReviewed]);
+ }, [baselineModel, canReject, loadModified, reportReview, writeReviewed]);
+
+ const reviewFilesRef = useRef(reviewFiles);
+ reviewFilesRef.current = reviewFiles;
+ const acceptRef = useRef(acceptOne);
+ acceptRef.current = acceptOne;
+ const rejectRef = useRef(rejectOne);
+ rejectRef.current = rejectOne;
// ── tabs ───────────────────────────────────────────────────────────────
const openFile = useCallback((path: string) => {
@@ -661,6 +730,11 @@ export default function EditorPanel(props: EditorPanelProps) {
setTabError(opened.message);
return;
}
+ if (opened.doc.missing && !docs.isDirty(opened.doc)) {
+ setSurface(null);
+ setTabError("This file was deleted.");
+ return;
+ }
setSurface({ kind: "file", key, doc: opened.doc });
return;
}
@@ -676,12 +750,15 @@ export default function EditorPanel(props: EditorPanelProps) {
const opened = file.status === "deleted" ? null : await docs.open(file.path);
if (cancelled) return;
const doc = opened && opened.ok ? opened.doc : docs.openMissing(file.path);
+ const path = file.path;
+ // Through refs: the bars outlive this render, and must act on the newest review data.
+ const current = () => reviewFilesRef.current.find((item) => item.path === path) ?? file;
setSurface({
kind: "diff",
key: `${key}:${reviewKey}`,
original: baselineModel(file),
modified: doc.model,
- review: { onAccept: (hunk) => acceptOne(file, hunk), onReject: (hunk) => rejectOne(file, hunk) },
+ review: { onAccept: (hunk) => acceptRef.current(current(), hunk), onReject: (hunk) => rejectRef.current(current(), hunk) },
});
return;
}
@@ -765,7 +842,8 @@ export default function EditorPanel(props: EditorPanelProps) {
if (!mod || event.altKey) return;
const key = event.key.toLowerCase();
// Cmd/Ctrl+S outside Monaco (tab strip, tree) still saves the active file.
- if (key === "s" && !event.shiftKey && panelRef.current?.contains(document.activeElement)) {
+ const inMonaco = event.target instanceof Element && Boolean(event.target.closest(".monaco-editor"));
+ if (key === "s" && !event.shiftKey && !inMonaco && panelRef.current?.contains(document.activeElement)) {
event.preventDefault();
void save();
}
@@ -774,6 +852,11 @@ export default function EditorPanel(props: EditorPanelProps) {
return () => window.removeEventListener("keydown", onKey, true);
}, [save]);
+ useEffect(() => {
+ if (!state.activeId) return;
+ panelRef.current?.querySelector(`[data-editor-tab="${CSS.escape(state.activeId)}"]`)?.scrollIntoView({ block: "nearest", inline: "nearest" });
+ }, [state.activeId]);
+
const activePath = activeTab?.path ?? null;
const activeDirty = activeTab && dirty?.[activeTab.path];
const activeDoc = activePath ? docs.get(activePath) : null;
@@ -808,7 +891,7 @@ export default function EditorPanel(props: EditorPanelProps) {
selected={activeTab?.kind === "review" ? activeTab.path : null}
onScope={(scope) => useEditorStore.getState().setReviewScope(scope)}
onOpen={openReview}
- onAcceptAll={acceptFiles}
+ onAcceptAll={(list) => void acceptFiles(list)}
onRejectAll={(list) => void rejectFiles(list)}
onRefresh={() => void changesQuery.refetch()}
/>
@@ -918,12 +1001,12 @@ export default function EditorPanel(props: EditorPanelProps) {
</div>
</div>
<div className="flex h-6 shrink-0 items-center gap-3 overflow-hidden whitespace-nowrap border-t border-border px-3 text-[11px] text-muted-foreground" data-editor-status>
- {branch ? <span className="flex items-center gap-1"><GitBranch className="size-3" />{branch}</span> : null}
- {gitQuery.data?.repo ? <span>{gitQuery.data.files.length} changed</span> : null}
+ {branch ? <span className="flex min-w-0 items-center gap-1 truncate"><GitBranch className="size-3 shrink-0" />{branch}</span> : null}
+ {gitQuery.data?.repo ? <span className="shrink-0">{gitQuery.data.files.length} changed</span> : null}
<span className="flex-1" />
- {cursor && activeTab ? <span>Ln {cursor.line}, Col {cursor.column}</span> : null}
- {activePath ? <span>{languageForPath(activePath)}</span> : null}
- {activeTab?.kind === "file" ? <span data-editor-saved={activeDirty ? "0" : "1"}>{activeDirty ? "Unsaved" : "Saved"}</span> : null}
+ {cursor && activeTab ? <span className="shrink-0 max-[1100px]:hidden">Ln {cursor.line}, Col {cursor.column}</span> : null}
+ {activePath ? <span className="shrink-0 max-[1250px]:hidden">{languageForPath(activePath)}</span> : null}
+ {activeTab?.kind === "file" ? <span className="shrink-0" data-editor-saved={activeDirty ? "0" : "1"}>{activeDirty ? "Unsaved" : "Saved"}</span> : null}
</div>
</div>
);
diff --git a/apps/app/src/react-app/domains/session/editor/editor-surface.tsx b/apps/app/src/react-app/domains/session/editor/editor-surface.tsx
index c96f718c..14f5986d 100644
--- a/apps/app/src/react-app/domains/session/editor/editor-surface.tsx
+++ b/apps/app/src/react-app/domains/session/editor/editor-surface.tsx
@@ -21,8 +21,9 @@ export type SurfaceDoc =
modified: MonacoApi.editor.ITextModel;
/** Review tabs: per-hunk decisions. Git tabs have none. */
review?: {
- onAccept: (hunk: LineHunk) => void;
- onReject: (hunk: LineHunk) => void;
+ /** Applies the decision; false when it was refused (nothing changed). */
+ onAccept: (hunk: LineHunk) => boolean;
+ onReject: (hunk: LineHunk) => boolean;
};
readOnlyModified?: boolean;
};
@@ -189,7 +190,36 @@ export function EditorSurface({ monaco, surface, onSave, onCursor, onHunks, navi
const diff = diffRef.current;
if (!diff || !surface || surface.kind !== "diff") return;
const modifiedEditor = diff.getModifiedEditor();
+ // After a decision the bars' line numbers are stale until the diff is computed again:
+ // they take no clicks until then, and a hunk is applied only if the diff still has it.
+ let locked = false;
+ let unlockTimer: ReturnType<typeof setTimeout> | null = null;
+ const setLocked = (value: boolean) => {
+ locked = value;
+ for (const widget of overlays.current) widget.getDomNode().classList.toggle("omnirush-hunk-bar-busy", value);
+ };
+ const decide = (apply: (hunk: LineHunk) => boolean) => (hunk: LineHunk) => {
+ if (locked) return false;
+ const still = (diff.getLineChanges() ?? []).some((change) =>
+ change.originalStartLineNumber === hunk.originalStartLineNumber
+ && change.originalEndLineNumber === hunk.originalEndLineNumber
+ && change.modifiedStartLineNumber === hunk.modifiedStartLineNumber
+ && change.modifiedEndLineNumber === hunk.modifiedEndLineNumber);
+ if (!still) return false;
+ setLocked(true);
+ const applied = apply(hunk);
+ if (!applied) setLocked(false);
+ else {
+ if (unlockTimer) clearTimeout(unlockTimer);
+ unlockTimer = setTimeout(() => setLocked(false), 3_000);
+ }
+ return applied;
+ };
+ const review = surface.review
+ ? { onAccept: decide(surface.review.onAccept), onReject: decide(surface.review.onReject) }
+ : null;
const render = () => {
+ setLocked(false);
const changes = (diff.getLineChanges() ?? []).map((change) => ({
originalStartLineNumber: change.originalStartLineNumber,
originalEndLineNumber: change.originalEndLineNumber,
@@ -205,13 +235,13 @@ export function EditorSurface({ monaco, surface, onSave, onCursor, onHunks, navi
modifiedEditor.changeViewZones((accessor) => {
for (const id of zoneIds.current) accessor.removeZone(id);
zoneIds.current = [];
- if (!surface.review) return;
+ if (!review) return;
const layout = modifiedEditor.getLayoutInfo();
const left = layout.contentLeft;
const width = Math.max(120, layout.width - layout.contentLeft - layout.verticalScrollbarWidth - 8);
changes.forEach((hunk, index) => {
const after = hunk.modifiedEndLineNumber === 0 ? hunk.modifiedStartLineNumber : hunk.modifiedStartLineNumber - 1;
- const bar = hunkBar(hunk, index, changes.length, surface.review!);
+ const bar = hunkBar(hunk, index, changes.length, review);
bar.style.position = "absolute";
bar.style.left = `${left}px`;
bar.style.width = `${width}px`;
@@ -249,6 +279,7 @@ export function EditorSurface({ monaco, surface, onSave, onCursor, onHunks, navi
const layout = modifiedEditor.onDidLayoutChange(() => render());
render();
return () => {
+ if (unlockTimer) clearTimeout(unlockTimer);
subscription.dispose();
scroll.dispose();
layout.dispose();
diff --git a/apps/app/src/react-app/domains/session/editor/editor.css b/apps/app/src/react-app/domains/session/editor/editor.css
index 903be99d..e77a2d52 100644
--- a/apps/app/src/react-app/domains/session/editor/editor.css
+++ b/apps/app/src/react-app/domains/session/editor/editor.css
@@ -26,3 +26,4 @@
.omnirush-hunk-btn:hover { background: var(--muted); }
.omnirush-hunk-btn-primary { background: var(--primary); border-color: var(--primary); color: var(--primary-foreground, #fff); }
.omnirush-hunk-btn-primary:hover { background: color-mix(in srgb, var(--primary) 88%, black); }
+.omnirush-hunk-bar-busy { opacity: 0.55; pointer-events: none; }
diff --git a/apps/app/src/react-app/shell/use-shell-shortcuts.ts b/apps/app/src/react-app/shell/use-shell-shortcuts.ts
index 9c564443..f32c38a6 100644
--- a/apps/app/src/react-app/shell/use-shell-shortcuts.ts
+++ b/apps/app/src/react-app/shell/use-shell-shortcuts.ts
@@ -182,7 +182,9 @@ export function useShellShortcuts(input: UseShellShortcutsInput) {
}
return;
}
- if (key === "p" && isElectronRuntime()) {
+ // In the terminal Ctrl+P is the shell's (previous command); Cmd+P on macOS still opens quick open.
+ const inTerminal = Boolean(target?.closest?.(".xterm"));
+ if (key === "p" && isElectronRuntime() && !(inTerminal && !isMac)) {
// Quick open: shows the editor (session-page) with its file finder.
event.preventDefault();
const editor = useEditorStore.getState();
diff --git a/apps/server/src/editor-routes.e2e.test.ts b/apps/server/src/editor-routes.e2e.test.ts
index 5d9c5c59..0f818845 100644
--- a/apps/server/src/editor-routes.e2e.test.ts
+++ b/apps/server/src/editor-routes.e2e.test.ts
@@ -126,6 +126,44 @@ describe("editor routes", () => {
expect((await call("GET", "/file?path=link/secret.txt")).status).toBe(400);
expect((await call("PUT", "/file", { path: "link/evil.txt", content: "x" })).status).toBe(400);
expect((await call("PUT", "/file", { path: ".git/config", content: "x" })).status).toBe(400);
+ expect((await call("PUT", "/file", { path: ".GIT/config", content: "x" })).status).toBe(400);
+ expect((await call("PUT", "/file", { path: "sub/.git/hooks/pre-commit", content: "x" })).status).toBe(400);
+ expect((await call("PUT", "/file", { path: "/etc/passwd", content: "x" })).status).toBe(400);
+ await symlink(join(root, ".git"), join(root, "gitlink"));
+ expect((await call("PUT", "/file", { path: "gitlink/config", content: "x" })).status).toBe(400);
+ });
+
+ test("paths are never rewritten: workspace/ prefixes are real folders", async () => {
+ const root = await project();
+ await mkdir(join(root, "workspace"), { recursive: true });
+ await mkdir(join(root, "workspaces", "app", "src"), { recursive: true });
+ await writeFile(join(root, "workspace", "foo.ts"), "inner\n", "utf8");
+ await writeFile(join(root, "foo.ts"), "outer\n", "utf8");
+ const call = await serve(root);
+ expect((await call("GET", "/file?path=workspace/foo.ts")).body.content).toBe("inner\n");
+ await call("PUT", "/file", { path: "workspaces/app/src/index.ts", content: "deep\n" });
+ expect(await readFile(join(root, "workspaces", "app", "src", "index.ts"), "utf8")).toBe("deep\n");
+ expect(await readFile(join(root, "foo.ts"), "utf8")).toBe("outer\n");
+ });
+
+ test("a save keeps the file mode and leaves no temporary file", async () => {
+ const root = await project();
+ const script = join(root, "run.sh");
+ await writeFile(script, "echo a\n", { mode: 0o755 });
+ const call = await serve(root);
+ await call("PUT", "/file", { path: "run.sh", content: "echo b\n" });
+ const { stat: statFile, readdir: list } = await import("node:fs/promises");
+ expect((await statFile(script)).mode & 0o777).toBe(0o755);
+ expect((await list(root)).filter((name) => name.includes(".tmp-"))).toEqual([]);
+ });
+
+ test("stage takes paths literally, not as globs", async () => {
+ const root = await project();
+ await writeFile(join(root, "[ab].ts"), "x\n", "utf8");
+ await writeFile(join(root, "a.ts"), "a\n", "utf8");
+ const call = await serve(root);
+ const staged = await call("POST", "/git/stage", { paths: ["[ab].ts"] });
+ expect(staged.body.files.map((file: any) => `${file.index}${file.worktree} ${file.path}`)).toEqual(["A [ab].ts", "?? a.ts"]);
});
test("git panel: status, stage, unstage, commit, original text", async () => {
diff --git a/apps/server/src/routes/editor.ts b/apps/server/src/routes/editor.ts
index c9e3ed28..2bb5a2a6 100644
--- a/apps/server/src/routes/editor.ts
+++ b/apps/server/src/routes/editor.ts
@@ -10,13 +10,12 @@
* without one, or for a chat that is not tracked, reports nothing.
*/
import { spawn } from "node:child_process";
-import { chmod, readdir, readFile, realpath, rename, rm, stat, writeFile } from "node:fs/promises";
+import { readdir, readFile, realpath, rm, stat, writeFile } from "node:fs/promises";
import { dirname, join, relative, resolve, sep } from "node:path";
import { ApiError } from "../errors.js";
import { ignoredByRules, parseGitignoreRules, scopedIgnoreRules } from "../session-uploader.js";
import type { ApprovalRequest, ServerConfig, TokenScope, WorkspaceInfo } from "../types.js";
-import { ensureDir, shortId } from "../utils.js";
-import { normalizeWorkspaceRelativePath } from "./files.js";
+import { ensureDir } from "../utils.js";
import { addRoute, type RequestContext, type Route } from "./registry.js";
/** The largest file the editor opens or saves. */
@@ -25,7 +24,9 @@ export const EDITOR_MAX_FILE_BYTES = 5_000_000;
export const EDITOR_MAX_TREE_FILES = 200_000;
const GIT_TIMEOUT_MS = 20_000;
const GIT_MAX_OUTPUT_BYTES = 64 * 1024 * 1024;
-const WALK_SKIPPED_DIRECTORIES = new Set([".git", "node_modules"]);
+const WALK_SKIPPED_DIRECTORIES = new Set([".git", "node_modules", ".venv", "venv", "__pycache__", ".cache", ".next", ".turbo", ".gradle", ".npm", ".pnpm-store"]);
+/** A folder that is not a repository is walked for at most this long (a home folder can hold millions of files). */
+const WALK_TIME_LIMIT_MS = 8_000;
const COMMIT_MESSAGE_MAX = 20_000;
const MAX_PATHS_PER_CALL = 5_000;
@@ -67,10 +68,14 @@ export function runEditorGit(root: string, args: string[], options: { input?: st
return new Promise((resolvePromise) => {
let child;
try {
- child = spawn("git", ["-c", "core.quotePath=false", "-c", "color.ui=false", ...args], {
+ // No inherited GIT_* settings (a GIT_DIR or GIT_WORK_TREE from the app's own environment
+ // would point git elsewhere); paths are literal, never globs; no fsmonitor program.
+ const env: NodeJS.ProcessEnv = {};
+ for (const [key, value] of Object.entries(process.env)) if (!key.startsWith("GIT_")) env[key] = value;
+ child = spawn("git", ["-c", "core.quotePath=false", "-c", "color.ui=false", "-c", "core.fsmonitor=false", ...args], {
cwd: root,
stdio: ["pipe", "pipe", "pipe"],
- env: { ...process.env, GIT_TERMINAL_PROMPT: "0", GIT_OPTIONAL_LOCKS: "0", LC_ALL: "C" },
+ env: { ...env, GIT_TERMINAL_PROMPT: "0", GIT_OPTIONAL_LOCKS: "0", GIT_LITERAL_PATHSPECS: "1", LC_ALL: "C" },
windowsHide: true,
});
} catch (error) {
@@ -115,10 +120,30 @@ function splitNul(buffer: Buffer): string[] {
}
/** The workspace-relative path, checked (no `..`, no absolute paths, no reserved names). */
-function editorPath(input: unknown): string {
- const path = normalizeWorkspaceRelativePath(String(input ?? ""), { allowSubdirs: true });
- if (path === ".git" || path.startsWith(".git/")) throw new ApiError(400, "invalid_path", "The .git folder is not editable");
- return path;
+const WINDOWS_RESERVED_NAME = /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\..*)?$/i;
+
+function isGitComponent(part: string): boolean {
+ return part.toLowerCase() === ".git";
+}
+
+/**
+ * The workspace-relative path, checked strictly and never rewritten: no
+ * absolute paths, no `..`, no NUL, no `.git` folder at any depth (any case).
+ */
+export function editorPath(input: unknown): string {
+ const raw = String(input ?? "").replace(/\\/g, "/");
+ const invalid = (message: string) => new ApiError(400, "invalid_path", message);
+ if (!raw.trim()) throw invalid("A path is required");
+ if (raw.includes("\0")) throw invalid("Invalid path");
+ if (raw.startsWith("/") || /^[A-Za-z]:/.test(raw)) throw invalid("Path must be relative to the workspace");
+ const parts = raw.split("/").filter((part) => part !== "" && part !== ".");
+ if (parts.length === 0) throw invalid("A path is required");
+ if (parts.some((part) => part === "..")) throw invalid("Path traversal is not allowed");
+ if (parts.some(isGitComponent)) throw invalid("The .git folder is not editable");
+ if (process.platform === "win32" && parts.some((part) => part.includes(":") || WINDOWS_RESERVED_NAME.test(part) || /[. ]$/.test(part))) {
+ throw invalid("This name is not valid on Windows");
+ }
+ return parts.join("/");
}
/** The file's absolute path inside the workspace; a symlinked folder that leads out of it is refused. */
@@ -137,6 +162,10 @@ async function resolveInside(root: string, relativePath: string): Promise<string
if (real !== rootReal && !real.startsWith(rootReal + sep)) {
throw new ApiError(400, "invalid_path", "Path leads outside the workspace");
}
+ // A symlink into a .git folder is refused like the folder itself.
+ if (relative(rootReal, real).split(sep).some(isGitComponent)) {
+ throw new ApiError(400, "invalid_path", "The .git folder is not editable");
+ }
break;
}
const parent = dirname(probe);
@@ -180,8 +209,13 @@ async function gitTree(root: string): Promise<string[] | null> {
async function walkTree(root: string, limit: number): Promise<{ files: string[]; truncated: boolean }> {
const files: string[] = [];
let truncated = false;
+ const deadline = Date.now() + WALK_TIME_LIMIT_MS;
const walk = async (dir: string, rules: string[]) => {
if (truncated) return;
+ if (Date.now() > deadline) {
+ truncated = true;
+ return;
+ }
const rel = relative(root, dir).replace(/\\/g, "/");
const local = await readFile(join(dir, ".gitignore"), "utf8").then(parseGitignoreRules).catch(() => [] as string[]);
const scoped = [...rules, ...scopedIgnoreRules(rel, local)];
@@ -191,7 +225,7 @@ async function walkTree(root: string, limit: number): Promise<{ files: string[];
if (truncated) return;
const path = rel ? `${rel}/${entry.name}` : entry.name;
if (entry.isDirectory()) {
- if (WALK_SKIPPED_DIRECTORIES.has(entry.name) || ignoredByRules(`${path}/`, scoped)) continue;
+ if (WALK_SKIPPED_DIRECTORIES.has(entry.name) || isGitComponent(entry.name) || ignoredByRules(`${path}/`, scoped)) continue;
await walk(join(dir, entry.name), scoped);
} else if (entry.isFile() || entry.isSymbolicLink()) {
if (ignoredByRules(path, scoped)) continue;
@@ -320,6 +354,11 @@ export function registerEditorRoutes(options: RegisterEditorRoutesOptions): void
addRoute(routes, "PUT", "/workspace/:id/editor/file", "client", async (ctx) => {
ensureWritable(config);
requireClientScope(ctx, "collaborator");
+ // JSON-escaped text can be up to 6 bytes per byte; anything larger is refused before it is read.
+ const declared = Number(ctx.request.headers.get("content-length") ?? "0");
+ if (Number.isFinite(declared) && declared > EDITOR_MAX_FILE_BYTES * 6 + 64 * 1024) {
+ throw new ApiError(413, "file_too_large", "File exceeds size limit", { maxBytes: EDITOR_MAX_FILE_BYTES });
+ }
const workspace = await resolveWorkspace(config, ctx.params.id);
const body = await readJsonBody(ctx.request);
const path = editorPath(body.path);
@@ -351,11 +390,10 @@ export function registerEditorRoutes(options: RegisterEditorRoutesOptions): void
if (remove) {
await rm(absolute, { force: true });
} else {
+ // In place: no temporary file appears in the project (the session uploader watches it),
+ // and the file keeps its mode, hard links and symlink.
await ensureDir(dirname(absolute));
- const tmp = `${absolute}.tmp-${shortId()}`;
- await writeFile(tmp, content, "utf8");
- if (current) await chmod(tmp, current.mode & 0o7777).catch(() => undefined);
- await rename(tmp, absolute);
+ await writeFile(absolute, content, "utf8");
}
const after = remove ? null : await stat(absolute);
// A file whose old text could not be read (binary, too large) is not reported.
@@ -371,6 +409,8 @@ export function registerEditorRoutes(options: RegisterEditorRoutesOptions): void
});
addRoute(routes, "POST", "/workspace/:id/editor/review", "client", async (ctx) => {
+ ensureWritable(config);
+ requireClientScope(ctx, "collaborator");
const workspace = await resolveWorkspace(config, ctx.params.id);
const body = await readJsonBody(ctx.request);
const sessionId = sessionIdOf(body.sessionId);