Merge pull request #213 from Ark0N/feat/file-viewer-edit-mode

File Viewer: edit mode for text files (edit + save in the viewer)
This commit is contained in:
Ark0N
2026-08-05 09:00:22 +02:00
committed by GitHub
14 changed files with 1653 additions and 7 deletions
+152
View File
@@ -0,0 +1,152 @@
/**
* @fileoverview File Viewer edit-mode policy (issue #212).
*
* Pure, IO-free policy for which workspace files the in-viewer editor may read
* for editing and write back. Consumed by the `edit=1` branch of
* `GET /api/sessions/:id/file-content` and by `PUT /api/sessions/:id/file-content`
* in `src/web/routes/file-routes.ts`.
*
* Design (docs/file-viewer-edit-plan.md):
* - ALLOWLIST of text extensions/basenames, not a blocklist — matching the
* attachment-guard precedent. `svg` and `env` are deliberately absent: svg is
* treated as untrusted on the read side, and `.env` is sensitive-path blocked
* anyway; excluding them here keeps a single obvious refusal.
* - The `.git/` subtree is denied outright: `.git/hooks/*` is code execution and
* a corrupted index looks unrecoverable to a user who wanted to fix a typo.
* - EOL helpers exist because a browser <textarea> normalizes to LF; the server
* re-applies the file's original ending so a two-line edit of a CRLF file does
* not become a whole-file diff. Mixed-EOL files normalize to the dominant
* style (documented lossy edge).
*/
/** Hard cap for edit-mode reads AND writes (bytes of file content). */
export const MAX_EDITABLE_BYTES = 512 * 1024;
/** Lowercase extensions (no dot) the editor will open and save. */
export const EDITABLE_EXTENSIONS: ReadonlySet<string> = new Set([
// JS/TS ecosystem
'ts',
'tsx',
'js',
'jsx',
'mjs',
'cjs',
'json',
'jsonc',
// Docs / plain text
'md',
'mdx',
'txt',
'rst',
'adoc',
// Web
'css',
'scss',
'less',
'html',
'htm',
'xml',
// Config
'yml',
'yaml',
'toml',
'ini',
'cfg',
'conf',
'properties',
// Shell
'sh',
'bash',
'zsh',
'fish',
// Languages
'py',
'rb',
'go',
'rs',
'java',
'kt',
'swift',
'c',
'h',
'cpp',
'hpp',
'cc',
'cs',
'php',
'sql',
'graphql',
'proto',
'lua',
'pl',
'r',
'jl',
'tf',
'gradle',
// Data / misc text
'csv',
'tsv',
'log',
'diff',
'patch',
]);
/** Extensionless (or dot-led) file names that are still editable text. */
export const EDITABLE_BASENAMES: ReadonlySet<string> = new Set([
'dockerfile',
'makefile',
'license',
'readme',
'changelog',
'authors',
'codeowners',
'procfile',
'.gitignore',
'.gitattributes',
'.dockerignore',
'.prettierignore',
'.prettierrc',
'.editorconfig',
'.nvmrc',
'.npmrc',
'.eslintignore',
]);
/** Whether a file name (basename only) is eligible for in-viewer editing. */
export function isEditableFileName(fileName: string): boolean {
const lower = fileName.toLowerCase();
if (EDITABLE_BASENAMES.has(lower)) return true;
const dot = lower.lastIndexOf('.');
// No extension (or a bare dotfile like `.bashrc`): only the basename list applies.
if (dot <= 0) return false;
return EDITABLE_EXTENSIONS.has(lower.slice(dot + 1));
}
/**
* Whether a workspace-relative path is denied for editing regardless of its
* extension. Currently: anything inside a `.git` directory at any depth.
*/
export function isDeniedEditRelativePath(relativePath: string): boolean {
return relativePath.split('/').some((segment) => segment === '.git');
}
export type FileEol = 'lf' | 'crlf';
/** Dominant line-ending style of a text buffer (LF when tied or single-line). */
export function detectEol(text: string): FileEol {
let crlf = 0;
let lf = 0;
for (let i = 0; i < text.length; i++) {
if (text.charCodeAt(i) === 10) {
if (i > 0 && text.charCodeAt(i - 1) === 13) crlf++;
else lf++;
}
}
return crlf > lf ? 'crlf' : 'lf';
}
/** Normalize every line ending in `text` to the requested style. */
export function applyEol(text: string, eol: FileEol): string {
const normalized = text.replace(/\r\n/g, '\n');
return eol === 'crlf' ? normalized.replace(/\n/g, '\r\n') : normalized;
}
+16
View File
@@ -97,6 +97,22 @@ export interface FilesystemBrowseData {
truncated: boolean;
}
/** Response payload for `PUT /api/sessions/:id/file-content` (File Viewer edit mode). */
export interface FileWriteData {
/** Workspace-relative path as submitted */
path: string;
/** Size of the written content in bytes */
size: number;
/** mtime of the file after the write */
mtimeMs: number;
/** sha256 hex of the written bytes — the client's next baseHash */
hash: string;
/** Line count of the written content */
totalLines: number;
/** Line-ending style that was applied */
eol: 'lf' | 'crlf';
}
export type CleanupResourceType = 'timer' | 'interval' | 'watcher' | 'listener' | 'stream';
/**
+3
View File
@@ -601,6 +601,9 @@
'Select a run to view its agents': '选择一次运行以查看其智能体',
'Source type filter': '来源类型筛选',
'Copy content': '复制内容',
'Edit file': '编辑文件',
'Unsaved changes': '未保存的更改',
Saved: '已保存',
'Export as JSON': '导出为 JSON',
'Export as Markdown': '导出为 Markdown',
'Mark all read': '全部标为已读',
+7
View File
@@ -422,11 +422,18 @@
<div class="file-preview-header">
<span class="file-preview-title" id="filePreviewTitle">file.ts</span>
<div class="file-preview-actions">
<button class="btn-icon-sm file-preview-edit-btn" id="filePreviewEditBtn" onclick="app.enterFilePreviewEdit()" title="Edit file" aria-label="Edit file" hidden><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M17 3a2.85 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5z"/></svg></button>
<button class="btn-icon-sm" onclick="app.copyFilePreviewContent()" title="Copy content">&#x2398;</button>
<button class="btn-icon-sm" onclick="app.closeFilePreview()" title="Close">&times;</button>
</div>
</div>
<div class="file-preview-body" id="filePreviewBody"></div>
<div class="file-preview-editbar" id="filePreviewEditBar" hidden>
<span class="file-preview-dirty" id="filePreviewDirty" hidden>Unsaved changes</span>
<span class="file-preview-editbar-spacer"></span>
<button class="file-preview-editbar-btn" onclick="app.cancelFilePreviewEdit()">Cancel</button>
<button class="file-preview-editbar-btn file-preview-editbar-btn--save" id="filePreviewSaveBtn" onclick="app.saveFilePreviewEdit()" disabled>Save</button>
</div>
<div class="file-preview-footer" id="filePreviewFooter"></div>
</div>
</div>
+27
View File
@@ -1871,6 +1871,33 @@ html.mobile-init .file-browser-panel {
bottom: calc(44px + 2rem + var(--safe-area-bottom));
}
/* File preview window: full screen on phones. --app-height tracks the visual
viewport (KeyboardHandler), so the edit textarea + Save bar stay above the
OS keyboard instead of hiding behind it. Footer/edit bar pad for the home
indicator. */
.file-preview-window {
width: 100vw;
max-width: 100vw;
height: var(--app-height, 100vh);
max-height: var(--app-height, 100vh);
border-radius: 0;
border-left: none;
border-right: none;
}
.file-preview-editbar {
padding-bottom: calc(0.4rem + var(--safe-area-bottom));
}
.file-preview-overlay .file-preview-footer {
padding-bottom: calc(0.35rem + var(--safe-area-bottom));
}
/* >=16px or iOS Safari auto-zooms the page on focus */
.file-preview-body textarea.file-preview-editor {
font-size: 16px;
}
/* Notification drawer - full width on mobile, includes safe area padding */
.notification-drawer {
width: 100%;
+185 -2
View File
@@ -3200,6 +3200,9 @@ Object.assign(CodemanApp.prototype, {
if (!overlay || !bodyEl) return;
// Edit mode: reset any prior editor state whenever a preview (re)loads.
this._resetFilePreviewEdit();
// Show overlay with loading state
overlay.classList.add('visible');
titleEl.textContent = filePath;
@@ -3298,6 +3301,13 @@ Object.assign(CodemanApp.prototype, {
bodyEl.innerHTML = `<pre><code>${escapeHtml(data.content)}</code></pre>`;
const truncNote = data.truncated ? ` (showing 500/${data.totalLines} lines)` : '';
footerEl.textContent = `${data.totalLines} lines \u2022 ${this.formatFileSize(data.size)}${truncNote}`;
// Edit affordance only when the server says an edit=1 re-fetch would
// succeed (workspace text file inside the allowlist and size cap).
if (data.editable) {
this.filePreviewEditTarget = { sessionId, filePath };
const editBtn = this.$('filePreviewEditBtn');
if (editBtn) editBtn.hidden = false;
}
}
} catch (err) {
console.error('Failed to preview file:', err);
@@ -3306,6 +3316,8 @@ Object.assign(CodemanApp.prototype, {
},
closeFilePreview() {
if (this.filePreviewEdit?.dirty && !confirm('Discard unsaved changes?')) return;
this._resetFilePreviewEdit();
const overlay = this.$('filePreviewOverlay');
if (overlay) {
overlay.classList.remove('visible');
@@ -3313,6 +3325,172 @@ Object.assign(CodemanApp.prototype, {
this.filePreviewContent = '';
},
// ═══════════════════════════════════════════════════════════════
// File Viewer edit mode (issue #212 — docs/file-viewer-edit-plan.md)
// ═══════════════════════════════════════════════════════════════
_resetFilePreviewEdit() {
this.filePreviewEdit = null;
this.filePreviewEditTarget = null;
const editBtn = this.$('filePreviewEditBtn');
if (editBtn) editBtn.hidden = true;
const editBar = this.$('filePreviewEditBar');
if (editBar) editBar.hidden = true;
const dirtyEl = this.$('filePreviewDirty');
if (dirtyEl) dirtyEl.hidden = true;
const saveBtn = this.$('filePreviewSaveBtn');
if (saveBtn) {
saveBtn.disabled = true;
saveBtn.textContent = 'Save';
}
},
async enterFilePreviewEdit() {
const target = this.filePreviewEditTarget;
if (!target || this.filePreviewEdit) return;
const bodyEl = this.$('filePreviewBody');
const footerEl = this.$('filePreviewFooter');
if (!bodyEl) return;
// Always re-fetch with edit=1: the preview buffer may be line-truncated and
// a truncated buffer must never become an edit buffer. Parse the envelope
// even on non-ok responses so the specific refusal ("too large to edit
// here") reaches the toast instead of a generic failure.
let data;
try {
const res = await fetch(
`/api/sessions/${target.sessionId}/file-content?path=${encodeURIComponent(target.filePath)}&edit=1`
);
const result = await res.json().catch(() => null);
if (!result || result.success !== true) {
throw new Error(result?.error || `Failed to load file for editing (HTTP ${res.status})`);
}
data = result.data;
} catch (err) {
this.showToast(err.message, 'error');
return;
}
this.filePreviewEdit = {
sessionId: target.sessionId,
filePath: target.filePath,
baseHash: data.hash,
eol: data.eol,
original: data.content,
dirty: false,
saving: false,
};
const textarea = document.createElement('textarea');
textarea.className = 'file-preview-editor';
textarea.spellcheck = false;
textarea.setAttribute('autocapitalize', 'off');
textarea.setAttribute('autocorrect', 'off');
textarea.setAttribute('autocomplete', 'off');
textarea.wrap = 'off';
textarea.value = data.content;
textarea.addEventListener('input', () => this._onFilePreviewEditInput());
bodyEl.innerHTML = '';
bodyEl.appendChild(textarea);
// Deliberately no autofocus: on phones that would pop the OS keyboard
// before the user has scrolled to the line they want to change.
const editBtn = this.$('filePreviewEditBtn');
if (editBtn) editBtn.hidden = true;
const editBar = this.$('filePreviewEditBar');
if (editBar) editBar.hidden = false;
if (footerEl) {
const eolNote = data.eol === 'crlf' ? ' • CRLF' : '';
footerEl.textContent = `Editing • ${data.totalLines} lines • ${this.formatFileSize(data.size)}${eolNote}`;
}
},
_onFilePreviewEditInput() {
const edit = this.filePreviewEdit;
if (!edit) return;
const textarea = this.$('filePreviewBody')?.querySelector('textarea.file-preview-editor');
if (!textarea) return;
edit.dirty = textarea.value !== edit.original;
const dirtyEl = this.$('filePreviewDirty');
if (dirtyEl) dirtyEl.hidden = !edit.dirty;
const saveBtn = this.$('filePreviewSaveBtn');
if (saveBtn) saveBtn.disabled = !edit.dirty || edit.saving;
},
cancelFilePreviewEdit() {
const edit = this.filePreviewEdit;
if (!edit) return;
if (edit.dirty && !confirm('Discard unsaved changes?')) return;
const { sessionId, filePath } = edit;
this._resetFilePreviewEdit();
this.openFilePreview(filePath, sessionId);
},
async saveFilePreviewEdit(force = false) {
const edit = this.filePreviewEdit;
if (!edit || edit.saving) return;
const textarea = this.$('filePreviewBody')?.querySelector('textarea.file-preview-editor');
if (!textarea) return;
edit.saving = true;
const saveBtn = this.$('filePreviewSaveBtn');
if (saveBtn) {
saveBtn.disabled = true;
saveBtn.textContent = 'Saving…';
}
const restoreSaveState = () => {
edit.saving = false;
if (saveBtn) saveBtn.textContent = 'Save';
this._onFilePreviewEditInput();
};
let result = null;
let status = 0;
try {
const res = await fetch(`/api/sessions/${edit.sessionId}/file-content`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
path: edit.filePath,
content: textarea.value,
baseHash: edit.baseHash,
eol: edit.eol ?? undefined, // Zod .optional() rejects null
force: force || undefined,
}),
});
status = res.status;
result = await res.json().catch(() => null);
} catch (err) {
restoreSaveState();
this.showToast(`Save failed: ${err.message}`, 'error');
return;
}
if (status === 409 || result?.errorCode === 'CONFLICT') {
restoreSaveState();
if (
confirm(
'File changed on disk since you loaded it.\nOK overwrites it with your version; Cancel keeps your draft open.'
)
) {
this.saveFilePreviewEdit(true);
}
return;
}
if (!result || result.success !== true) {
restoreSaveState();
this.showToast(`Save failed: ${result?.error || `HTTP ${status}`}`, 'error');
return;
}
const { sessionId, filePath } = edit;
this._resetFilePreviewEdit();
this.showToast('Saved', 'success');
// Re-open in read mode — re-fetching shows the truth on disk (including the
// server-side EOL normalization) rather than trusting the local buffer.
this.openFilePreview(filePath, sessionId);
},
// ═══════════════════════════════════════════════════════════════
// Attachment Cards (detected documents/images)
// ═══════════════════════════════════════════════════════════════
@@ -3749,8 +3927,13 @@ Object.assign(CodemanApp.prototype, {
},
copyFilePreviewContent() {
if (this.filePreviewContent) {
navigator.clipboard.writeText(this.filePreviewContent).then(() => {
// While editing, copy the live editor buffer (not the stale preview text).
const editTextarea = this.filePreviewEdit
? this.$('filePreviewBody')?.querySelector('textarea.file-preview-editor')
: null;
const content = editTextarea ? editTextarea.value : this.filePreviewContent;
if (content) {
navigator.clipboard.writeText(content).then(() => {
this.showToast('Copied to clipboard', 'success');
}).catch(() => {
this.showToast('Failed to copy', 'error');
+78
View File
@@ -9430,6 +9430,84 @@ kbd {
flex-shrink: 0;
}
/* ---- File Viewer edit mode (issue #212) ---- */
.file-preview-body textarea.file-preview-editor {
display: block;
width: 100%;
height: 100%;
margin: 0;
padding: 0.75rem;
border: none;
outline: none;
resize: none;
background: var(--bg-dark);
color: var(--text);
font-family: var(--font-mono);
font-size: 0.8rem;
line-height: 1.5;
white-space: pre;
overflow-wrap: normal;
overflow: auto;
tab-size: 4;
}
.file-preview-editbar {
display: flex;
align-items: center;
gap: 0.5rem;
padding: 0.4rem 0.75rem;
border-top: 1px solid var(--border);
background: var(--bg-input);
flex-shrink: 0;
}
.file-preview-editbar[hidden] {
display: none;
}
.file-preview-editbar-spacer {
flex: 1;
}
.file-preview-dirty {
font-size: 0.7rem;
color: var(--warning, #e5c07b);
}
.file-preview-dirty::before {
content: '\25CF ';
}
.file-preview-editbar-btn {
padding: 0.3rem 0.9rem;
font-size: 0.75rem;
border-radius: 6px;
border: 1px solid var(--control-border);
background: var(--bg-input);
color: var(--text);
cursor: pointer;
}
.file-preview-editbar-btn:hover {
background: var(--bg-hover, rgba(255, 255, 255, 0.08));
}
.file-preview-editbar-btn--save {
background: var(--accent);
border-color: var(--accent);
color: #fff;
}
.file-preview-editbar-btn--save:hover {
background: var(--accent-hover);
}
.file-preview-editbar-btn--save:disabled {
opacity: 0.45;
cursor: default;
}
/* ========== Log Viewer Windows (Floating) ========== */
.log-viewer-window {
+261 -5
View File
@@ -1,12 +1,16 @@
/**
* @fileoverview File browser and streaming routes.
* Provides directory listing, file content preview, raw file serving, and tail streaming.
* Provides directory listing, file content preview, raw file serving, tail
* streaming, and the File Viewer edit-mode write path (edit=1 read +
* PUT /api/sessions/:id/file-content; policy in src/config/file-editing.ts,
* design in docs/file-viewer-edit-plan.md).
*/
import { FastifyInstance, type FastifyReply } from 'fastify';
import { basename as pathBasename, extname, isAbsolute, join, relative, resolve, sep } from 'node:path';
import { basename as pathBasename, dirname, extname, isAbsolute, join, relative, resolve, sep } from 'node:path';
import { createReadStream, realpathSync, type ReadStream } from 'node:fs';
import fs from 'node:fs/promises';
import { createHash, randomBytes } from 'node:crypto';
import { homedir } from 'node:os';
import type {
ApiResponse,
@@ -14,6 +18,7 @@ import type {
FilesystemBrowseEntry,
FilesystemBrowseRoot,
FilesystemPreviewKind,
FileWriteData,
} from '../../types.js';
import { ApiErrorCode, createErrorResponse, getErrorMessage } from '../../types.js';
import { fileStreamManager } from '../../file-stream-manager.js';
@@ -44,7 +49,14 @@ import type { SessionAttachmentHistoryItem, SessionState } from '../../types/ses
import { isSensitivePath } from '../sensitive-path.js';
import { SseEvent } from '../sse-events.js';
import type { ConfigPort, EventPort, SessionPort } from '../ports/index.js';
import { FilesystemBrowseQuerySchema, FilesystemPreviewQuerySchema } from '../schemas.js';
import { FilesystemBrowseQuerySchema, FilesystemPreviewQuerySchema, FileWriteSchema } from '../schemas.js';
import {
MAX_EDITABLE_BYTES,
applyEol,
detectEol,
isDeniedEditRelativePath,
isEditableFileName,
} from '../../config/file-editing.js';
const MIME_TYPES: Record<string, string> = {
png: 'image/png',
@@ -453,6 +465,71 @@ function appendDownloadFlag(url: string): string {
return `${url}${url.includes('?') ? '&' : '?'}download=true`;
}
// ===== File Viewer edit mode (issue #212) =====
// Policy lives in src/config/file-editing.ts; design in docs/file-viewer-edit-plan.md.
function sha256Hex(buf: Buffer): string {
return createHash('sha256').update(buf).digest('hex');
}
/** NUL byte in the first 8KB — same binary signal the plain read path uses. */
function sniffsBinary(buf: Buffer): boolean {
const sniffLength = Math.min(buf.length, 8192);
for (let i = 0; i < sniffLength; i++) {
if (buf[i] === 0) return true;
}
return false;
}
/**
* Structured-throw variant for the edit read/write paths. Identical mechanics to
* throwFilesystemPickerError (rendered by the central route error handler both
* in prod and in the app.inject() test harness); a separate name only so edit
* failures grep distinctly.
*/
function throwFileEditError(statusCode: number, code: ApiErrorCode, message: string): never {
throw Object.assign(new Error(message), {
statusCode,
body: createErrorResponse(code, message),
});
}
/**
* Gate a resolved workspace file for edit-mode read/write. Throws a structured
* error when the file may not be edited; returns void when it may. Order
* matters for the message a user sees: confinement (the caller's 404) →
* sensitive/blocked (403) → .git (403) → extension allowlist (400).
*/
function assertEditableTarget(resolvedPath: string, relativePath: string, blockedTrees: readonly string[]): void {
if (isSensitivePath(resolvedPath) || isBlockedAttachmentPath(resolvedPath, blockedTrees)) {
throwFileEditError(403, ApiErrorCode.FORBIDDEN, 'Editing this file is blocked');
}
if (isDeniedEditRelativePath(relativePath)) {
throwFileEditError(403, ApiErrorCode.FORBIDDEN, 'Files under .git cannot be edited');
}
if (!isEditableFileName(pathBasename(resolvedPath))) {
throwFileEditError(400, ApiErrorCode.INVALID_INPUT, 'This file type is not editable');
}
}
/**
* Decode a candidate edit buffer, refusing binary and non-UTF-8 content. The
* round-trip compare is what protects against silent corruption: decoding
* latin-1 (or any non-UTF-8) bytes yields U+FFFD replacements, and writing
* those back would destroy the original bytes. A UTF-8 BOM round-trips and is
* deliberately preserved.
*/
function decodeEditableText(buf: Buffer): string {
if (sniffsBinary(buf)) {
throwFileEditError(400, ApiErrorCode.INVALID_INPUT, 'Binary files cannot be edited');
}
const text = buf.toString('utf8');
if (!Buffer.from(text, 'utf8').equals(buf)) {
throwFileEditError(400, ApiErrorCode.INVALID_INPUT, 'Only UTF-8 text files can be edited');
}
return text;
}
function getSessionAttachmentHistory(
ctx: SessionPort & ConfigPort,
sessionId: string,
@@ -864,7 +941,12 @@ export function registerFileRoutes(app: FastifyInstance, ctx: SessionPort & Even
// Get file content for preview (File Browser)
app.get('/api/sessions/:id/file-content', async (req) => {
const { id } = req.params as { id: string };
const { path: filePath, lines, raw } = req.query as { path?: string; lines?: string; raw?: string };
const {
path: filePath,
lines,
raw,
edit,
} = req.query as { path?: string; lines?: string; raw?: string; edit?: string };
const session = findSessionOrFail(ctx, id, req);
if (!filePath) {
@@ -876,7 +958,52 @@ export function registerFileRoutes(app: FastifyInstance, ctx: SessionPort & Even
if (!validated) {
return createErrorResponse(ApiErrorCode.NOT_FOUND, 'File not found');
}
const { resolvedPath } = validated;
const { resolvedPath, relativePath } = validated;
// Read-for-edit: never truncated (a truncated buffer must never become an
// edit buffer), tighter size cap, full editability gate, and the hash/eol
// the client must echo back on PUT. Outside the shared try/catch below so
// its structured errors keep their status codes instead of collapsing into
// OPERATION_FAILED.
if (edit === '1' || edit === 'true') {
const guard = await loadAttachmentGuardConfig();
assertEditableTarget(resolvedPath, relativePath, guard.blockedTrees);
let editStat;
try {
editStat = await fs.stat(resolvedPath);
} catch {
throwFileEditError(404, ApiErrorCode.NOT_FOUND, 'File not found');
}
if (!editStat.isFile()) {
throwFileEditError(400, ApiErrorCode.INVALID_INPUT, 'Only regular files can be edited');
}
if (editStat.size > MAX_EDITABLE_BYTES) {
throwFileEditError(
413,
ApiErrorCode.INVALID_INPUT,
`File too large to edit here (${Math.ceil(editStat.size / 1024)}KB > ${MAX_EDITABLE_BYTES / 1024}KB limit)`
);
}
const editBuf = await fs.readFile(resolvedPath);
const editText = decodeEditableText(editBuf);
return {
success: true,
data: {
path: filePath,
content: editText,
size: editBuf.length,
mtimeMs: editStat.mtimeMs,
totalLines: editText.split('\n').length,
truncated: false,
extension: filePath.split('.').pop()?.toLowerCase() || '',
editable: true,
hash: sha256Hex(editBuf),
eol: detectEol(editText),
},
};
}
try {
const stat = await fs.stat(resolvedPath);
@@ -998,6 +1125,19 @@ export function registerFileRoutes(app: FastifyInstance, ctx: SessionPort & Even
const truncatedContent = allLines.length > maxLines;
const displayContent = truncatedContent ? allLines.slice(0, maxLines).join('\n') : content;
// Additive edit-mode advertisement: whether an edit=1 re-fetch would
// succeed. The UTF-8 round-trip compare is a cheap memcmp and mirrors
// decodeEditableText; no hash here — the Edit action re-fetches with
// edit=1, which is where the baseHash comes from.
const guard = await loadAttachmentGuardConfig();
const editable =
isEditableFileName(pathBasename(resolvedPath)) &&
!isDeniedEditRelativePath(relativePath) &&
!isSensitivePath(resolvedPath) &&
!isBlockedAttachmentPath(resolvedPath, guard.blockedTrees) &&
stat.size <= MAX_EDITABLE_BYTES &&
Buffer.from(content, 'utf8').equals(buf);
return {
success: true,
data: {
@@ -1007,6 +1147,7 @@ export function registerFileRoutes(app: FastifyInstance, ctx: SessionPort & Even
totalLines: allLines.length,
truncated: truncatedContent,
extension: ext,
editable,
},
};
} catch (err) {
@@ -1014,6 +1155,121 @@ export function registerFileRoutes(app: FastifyInstance, ctx: SessionPort & Even
}
});
// File Viewer edit mode: save a text file back into the session workspace.
// Edit-in-place ONLY — there is deliberately no O_CREAT path in this handler,
// so it can never create, and it never deletes. Confinement is identical to
// the read path (realpath + workspace boundary + ownership via
// findSessionOrFail), plus the sensitive-path/attachment-guard blocklists and
// the extension allowlist. Concurrency is optimistic: the client echoes the
// sha256 it loaded (baseHash) and a mismatch is a 409 unless force is set.
// bodyLimit: JSON escaping can expand content up to ~6x (each control char
// becomes \uXXXX), so the 512KB content cap needs headroom over Fastify's
// 1MB default.
app.put(
'/api/sessions/:id/file-content',
{ bodyLimit: 4 * 1024 * 1024 },
async (req): Promise<ApiResponse<FileWriteData>> => {
const { id } = req.params as { id: string };
const session = findSessionOrFail(ctx, id, req);
const body = parseBody(FileWriteSchema, req.body);
// Exact byte cap — the schema's .max() counts UTF-16 code units and is
// only a coarse pre-filter.
if (Buffer.byteLength(body.content, 'utf8') > MAX_EDITABLE_BYTES) {
throwFileEditError(413, ApiErrorCode.INVALID_INPUT, `Content too large (${MAX_EDITABLE_BYTES / 1024}KB limit)`);
}
const validated = validateSessionFilePath(session.workingDir, body.path);
if (!validated) {
// Covers missing files, traversal, and symlink escapes alike — a write
// target that fails confinement is reported identically to a missing
// one, matching the read route.
throwFileEditError(404, ApiErrorCode.NOT_FOUND, 'File not found');
}
const { resolvedPath, relativePath } = validated;
const guard = await loadAttachmentGuardConfig();
assertEditableTarget(resolvedPath, relativePath, guard.blockedTrees);
let stat;
try {
stat = await fs.stat(resolvedPath);
} catch {
throwFileEditError(404, ApiErrorCode.NOT_FOUND, 'File not found');
}
if (!stat.isFile()) {
throwFileEditError(400, ApiErrorCode.INVALID_INPUT, 'Only regular files can be edited');
}
if (stat.size > MAX_EDITABLE_BYTES) {
throwFileEditError(
413,
ApiErrorCode.INVALID_INPUT,
`File too large to edit here (${MAX_EDITABLE_BYTES / 1024}KB limit)`
);
}
const currentBuf = await fs.readFile(resolvedPath);
const currentText = decodeEditableText(currentBuf);
const currentHash = sha256Hex(currentBuf);
if (currentHash !== body.baseHash && !body.force) {
throwFileEditError(
409,
ApiErrorCode.CONFLICT,
'File changed on disk since it was loaded — reload it or overwrite'
);
}
// Re-apply the file's original line endings (a <textarea> normalizes to
// LF; without this a two-line edit of a CRLF file rewrites every line).
const eol = body.eol ?? detectEol(currentText);
const outText = applyEol(body.content, eol);
const outBuf = Buffer.from(outText, 'utf8');
if (outBuf.length > MAX_EDITABLE_BYTES) {
throwFileEditError(413, ApiErrorCode.INVALID_INPUT, `Content too large (${MAX_EDITABLE_BYTES / 1024}KB limit)`);
}
// Atomic replace: O_EXCL temp in the same directory, then rename.
// 'wx' cannot follow a pre-existing symlink and rename() replaces (not
// follows) a symlink in the final component, which closes the
// validate-then-write TOCTOU window. fchmod because open()'s mode is
// masked by the process umask; fsync so the rename never publishes a
// partially-durable file. Trade-off (same as vim's default): the inode
// changes, so hardlinks keep the old content.
const fileMode = stat.mode & 0o777;
const tmpPath = join(
dirname(resolvedPath),
`.${pathBasename(resolvedPath)}.codeman-tmp-${randomBytes(6).toString('hex')}`
);
let handle;
try {
handle = await fs.open(tmpPath, 'wx', fileMode);
await handle.chmod(fileMode);
await handle.writeFile(outBuf);
await handle.sync();
await handle.close();
handle = undefined;
await fs.rename(tmpPath, resolvedPath);
} catch (err) {
if (handle) await handle.close().catch(() => {});
await fs.unlink(tmpPath).catch(() => {});
throwFileEditError(500, ApiErrorCode.OPERATION_FAILED, `Failed to save file: ${getErrorMessage(err)}`);
}
const newStat = await fs.stat(resolvedPath).catch(() => undefined);
return {
success: true,
data: {
path: body.path,
size: outBuf.length,
mtimeMs: newStat?.mtimeMs ?? Date.now(),
hash: sha256Hex(outBuf),
totalLines: outText.split('\n').length,
eol,
},
};
}
);
// Serve raw file content (for images/binary files)
app.get('/api/sessions/:id/file-raw', async (req, reply) => {
const { id } = req.params as { id: string };
+25
View File
@@ -16,6 +16,7 @@ import {
MIN_TERMINAL_BUFFER_BYTES,
MIN_TERMINAL_SCROLLBACK_LINES,
} from '../config/terminal-history.js';
import { MAX_EDITABLE_BYTES } from '../config/file-editing.js';
// ========== Path Validation ==========
@@ -83,6 +84,30 @@ export const FilesystemPreviewQuerySchema = z.object({
.optional(),
});
/**
* Body validation for `PUT /api/sessions/:id/file-content` (File Viewer edit
* mode). `content.max()` counts UTF-16 code units, which for UTF-8 output is
* always <= the byte length, so it is a coarse pre-filter that never rejects
* valid content; the handler enforces the exact MAX_EDITABLE_BYTES byte cap.
* Workspace containment and symlink resolution are enforced by the route via
* validateSessionFilePath after parsing.
*/
export const FileWriteSchema = z
.object({
path: z
.string()
.min(1)
.max(4096)
.refine((p) => !p.includes('\0') && !p.includes('\n') && !p.includes('\r'), {
message: 'Invalid path',
}),
content: z.string().max(MAX_EDITABLE_BYTES),
baseHash: z.string().regex(/^[a-f0-9]{64}$/, 'baseHash must be a sha256 hex digest'),
eol: z.enum(['lf', 'crlf']).optional(),
force: z.boolean().optional(),
})
.strict();
// ========== Env Var Allowlist ==========
/** Allowlisted env var key prefixes */