async function api(path,opts={}){ // Strip leading slash so URL resolves relative to location.href (supports subpath mounts) const rel = path.startsWith('/') ? path.slice(1) : path; const url=new URL(rel,document.baseURI||location.href); const timeoutMs=Object.prototype.hasOwnProperty.call(opts,'timeoutMs')?opts.timeoutMs:30000; const timeoutToast=opts.timeoutToast!==false; // Retry up to 2 times on network errors (e.g. stale keep-alive after long idle). // Server errors (4xx/5xx) and client-side timeouts are NOT retried. let lastErr; for(let attempt=0;attempt<3;attempt++){ let controller=null; let timeoutId=null; let didTimeout=false; let upstreamSignal=null; let upstreamAbort=null; try{ const fetchOpts={...opts}; delete fetchOpts.timeoutMs; delete fetchOpts.timeoutToast; const useTimeout=Number.isFinite(Number(timeoutMs))&&Number(timeoutMs)>0; if(useTimeout&&typeof AbortController!=='undefined'){ controller=new AbortController(); upstreamSignal=fetchOpts.signal||null; if(upstreamSignal){ upstreamAbort=()=>controller.abort(upstreamSignal.reason); if(upstreamSignal.aborted) upstreamAbort(); else upstreamSignal.addEventListener('abort',upstreamAbort,{once:true}); } fetchOpts.signal=controller.signal; } const requestPromise=(async()=>{ const res=await fetch(url.href,{credentials:'include',headers:{'Content-Type':'application/json'},...fetchOpts}); if(!res.ok){ // 401 means the auth session expired. Redirect to login so the user can // re-authenticate. This is especially important for iOS PWA (standalone mode) // and for subpath mounts like /hermes/, where /login escapes to the site root. if(res.status===401){window.location.href='login?next='+encodeURIComponent(window.location.pathname+window.location.search);return;} const text=await res.text(); // Parse JSON error body and surface the human-readable message, // rather than showing raw JSON like {"error":"Profile 'x' does not exist."} let message=text; try{const j=JSON.parse(text);message=j.error||j.message||text;}catch(e){} // Attach the raw HTTP context so callers can branch on status (404 stale-session // cleanup, 401 redirect, 503 retry, etc.) without re-parsing the message string. const err=new Error(message); err.status=res.status; err.statusText=res.statusText; err.body=text; throw err; } const ct=res.headers.get('content-type')||''; return ct.includes('application/json')?await res.json():await res.text(); })(); return useTimeout?await Promise.race([ requestPromise, new Promise((_,reject)=>{ timeoutId=setTimeout(()=>{ didTimeout=true; if(controller) controller.abort(); const err=new Error('Request timed out. Please try again.'); err.name='TimeoutError'; err.timeout=true; reject(err); },Number(timeoutMs)); }) ]):await requestPromise; }catch(e){ lastErr=e; const isTimeout=didTimeout||(e&&(e.timeout===true||e.name==='TimeoutError')); if(isTimeout){ const err=(e&&e.name==='TimeoutError')?e:new Error('Request timed out. Please try again.'); err.name='TimeoutError'; err.timeout=true; if(timeoutToast&&typeof showToast==='function') showToast('Request timed out. Please try again.',5000,'error'); throw err; } // Only retry on network errors (TypeError from fetch), not on HTTP errors // that were already thrown above. Re-throw 401 redirects immediately. if(e.message&&/401/.test(e.message)) throw e; if(attempt<2 && e instanceof TypeError) continue; throw e; }finally{ if(timeoutId) clearTimeout(timeoutId); if(upstreamSignal&&upstreamAbort) upstreamSignal.removeEventListener('abort',upstreamAbort); } } throw lastErr; } function recordClientSSEError(source, details={}){ try{ const payload={ event:'sse_error', source:String(source||'unknown'), ready_state:details.ready_state, session_id:details.session_id||null, stream_id:details.stream_id||null, visibility_state:(typeof document!=='undefined'&&document.visibilityState)||'unknown', online:(typeof navigator!=='undefined'&&typeof navigator.onLine==='boolean')?navigator.onLine:null, url_path:(typeof location!=='undefined'&&location.pathname)||'/', reason:details.reason||'EventSource.onerror', }; void api('/api/client-events/log',{method:'POST',body:JSON.stringify(payload),timeoutMs:3000,timeoutToast:false}).catch(()=>{}); }catch(_){} } // Persist/restore expanded directory state per workspace in localStorage function _wsExpandKey(){ const ws=S.session&&S.session.workspace; return ws?'hermes-webui-expanded:'+ws:null; } function _saveExpandedDirs(){ const key=_wsExpandKey();if(!key)return; try{localStorage.setItem(key,JSON.stringify([...(S._expandedDirs||new Set())]));}catch(e){} } function _restoreExpandedDirs(){ const key=_wsExpandKey(); if(!key){S._expandedDirs=new Set();return;} try{ const raw=localStorage.getItem(key); S._expandedDirs=raw?new Set(JSON.parse(raw)):new Set(); }catch(e){S._expandedDirs=new Set();} } let _workspacePanelActiveTab = 'files'; let _renderSessionArtifactsTimer = null; function _setWorkspacePanelTabDataset(){ const panel = document.querySelector('.rightpanel'); if(panel) panel.dataset.activeTab = _workspacePanelActiveTab; } function scheduleRenderSessionArtifacts(){ if(_renderSessionArtifactsTimer) clearTimeout(_renderSessionArtifactsTimer); _renderSessionArtifactsTimer = setTimeout(()=>{ _renderSessionArtifactsTimer = null; renderSessionArtifacts(); }, 100); } if(typeof document !== 'undefined'){ if(document.readyState === 'loading') document.addEventListener('DOMContentLoaded', _setWorkspacePanelTabDataset, {once:true}); else _setWorkspacePanelTabDataset(); } function switchWorkspacePanelTab(tab){ _workspacePanelActiveTab = tab === 'artifacts' ? 'artifacts' : 'files'; _setWorkspacePanelTabDataset(); const filesTab = $('workspaceFilesTab'); const artifactsTab = $('workspaceArtifactsTab'); if(filesTab){ filesTab.classList.toggle('active', _workspacePanelActiveTab === 'files'); filesTab.setAttribute('aria-selected', _workspacePanelActiveTab === 'files' ? 'true' : 'false'); } if(artifactsTab){ artifactsTab.classList.toggle('active', _workspacePanelActiveTab === 'artifacts'); artifactsTab.setAttribute('aria-selected', _workspacePanelActiveTab === 'artifacts' ? 'true' : 'false'); } const artifacts = $('workspaceArtifacts'); if(artifacts) artifacts.hidden = _workspacePanelActiveTab !== 'artifacts'; if(_workspacePanelActiveTab === 'artifacts') renderSessionArtifacts(); } const ARTIFACT_IGNORE_RE = /(^|\/)(?:\.git|\.hg|\.svn|node_modules|\.venv|venv|__pycache__|dist|build|\.next|\.cache)(?:\/|$)/; // Canonical Hermes mutators plus MCP filesystem aliases that can create/edit files. const ARTIFACT_MUTATION_TOOLS = new Set(['write_file','patch','edit_file','create_file','mcp_filesystem_write_file','mcp_filesystem_edit_file']); function _normalizeArtifactPath(path){ if(!path) return ''; path = String(path).trim().replace(/[\`"'<>),.;:]+$/g,'').replace(/^[\`"'(<]+/g,''); if(!path || path.length > 240 || path.includes('://')) return ''; // Canonicalize workspace-relative prefixes so a file-tree open ("foo.md") and a // tool arg recorded as "./foo.md" or "~/foo.md" compare equal for mutation // tracking; otherwise an agent edit via a ./-prefixed path leaves the open // preview stale (#3262 / pre-release regression-gate finding). path = path.replace(/^~\//,'').replace(/^(?:\.\/)+/,''); if(!path) return ''; if(ARTIFACT_IGNORE_RE.test(path)) return ''; if(!/[./]/.test(path)) return ''; return path; } function _artifactCandidatesFromText(text){ if(!text || typeof text !== 'string') return []; const out = []; const seen = new Set(); const add = (path) => { path = _normalizeArtifactPath(path); if(!path || seen.has(path)) return; seen.add(path); out.push({path, kind:'diff'}); }; // Fallback text mining is intentionally narrow: only diff/patch fences imply // the session changed a file. Prose mentions such as "edited package.json" are // too noisy for an Artifacts list that should track write/edit outputs. const fenced = /```(?:diff|patch)\s*\n[\s\S]*?```/gi; let m; while((m = fenced.exec(text))){ const block = m[0]; const fm = block.match(/(?:^|\n)(?:\+\+\+|---)\s+(?:[ab]\/)?([^\n\t]+)/); if(fm) add(fm[1].trim()); } return out; } function _artifactCandidatesFromToolCall(tc){ if(!tc) return []; const name = String(tc.name || '').replace(/^functions\./,''); const args = tc.arguments || tc.args || tc.input || {}; const result = tc.result || tc.output || tc.snippet || ''; const out = []; const add = (path, source=name || 'tool') => { path = _normalizeArtifactPath(path); if(path) out.push({path, kind:source}); }; if(ARTIFACT_MUTATION_TOOLS.has(name) && args && typeof args === 'object'){ for(const key of ['path','file_path','source','destination']) add(args[key]); if(Array.isArray(args.paths)) args.paths.forEach(p=>add(p)); if(Array.isArray(args.edits)) args.edits.forEach(e=>add(e&&e.path)); } const resultText = typeof result === 'string' ? result : (result ? JSON.stringify(result) : ''); // Tool results may include unified diffs from patch-style tools; scan those // narrowly after structured args so diff headers can still contribute paths. for(const a of _artifactCandidatesFromText(resultText)) out.push(a); if(!out.length && ARTIFACT_MUTATION_TOOLS.has(name)){ const argsText = typeof args === 'string' ? args : JSON.stringify(args || {}); for(const a of _artifactCandidatesFromText(argsText)) out.push(a); } return out; } const _turnMutatedPreviewPaths = new Set(); function resetTurnWorkspaceMutations(){ _turnMutatedPreviewPaths.clear(); } function noteWorkspaceMutationsFromToolCall(tc){ for(const a of _artifactCandidatesFromToolCall(tc)){ const path=_normalizeArtifactPath(a.path); if(path) _turnMutatedPreviewPaths.add(path); } } function noteWorkspaceMutationsFromToolCalls(toolCalls){ if(!Array.isArray(toolCalls)) return; for(const tc of toolCalls) noteWorkspaceMutationsFromToolCall(tc); } function _isOpenPreviewPathMutated(){ if(!_previewCurrentPath) return false; const current=_normalizeArtifactPath(_previewCurrentPath); return !!(current&&_turnMutatedPreviewPaths.has(current)); } async function refreshOpenPreviewIfMutated(){ if(typeof _previewDirty!=='undefined'&&_previewDirty) return; if(!_isOpenPreviewPathMutated()) return; if(!_previewCurrentPath||!S.session) return; await openFile(_previewCurrentPath, { bustCache: true }); } function collectSessionArtifacts(){ const items = []; const seen = new Set(); const push = (path, source) => { path = _normalizeArtifactPath(path); if(!path || seen.has(path)) return; seen.add(path); items.push({path, source}); }; // Source 1: session-level tool call summaries (may be empty when messages // carry their own tool metadata — see _syncToolCallsForLoadedMessages). for(const tc of (S.toolCalls || [])){ for(const a of _artifactCandidatesFromToolCall(tc)) push(a.path, a.kind || tc.name || 'tool'); } // Source 2 & 3: message-level data — both text-mined diffs and structured // tool_calls / tool_use content blocks that survive the S.toolCalls clear. for(const msg of (S.messages || [])){ if(!msg) continue; const text = msg.content || msg.text || msg.message || ''; // Text-mined diff/patch fences (existing path). if(typeof text === 'string'){ for(const a of _artifactCandidatesFromText(text)) push(a.path, a.kind); } // Structured tool_calls array (OpenAI format: {function:{name,arguments}}). if(Array.isArray(msg.tool_calls)){ for(const tc of msg.tool_calls){ if(!tc || typeof tc !== 'object') continue; const fn = (tc.function && typeof tc.function === 'object') ? tc.function : tc; const name = fn.name || tc.name || ''; let args = fn.arguments || tc.arguments || tc.args || tc.input || {}; if(typeof args === 'string'){ try{ args = JSON.parse(args); }catch(_){} } const fakeTc = {name, args, result: tc.result || tc.output || ''}; for(const a of _artifactCandidatesFromToolCall(fakeTc)) push(a.path, a.kind || name || 'tool'); } } // Structured content array with tool_use blocks (Anthropic format). if(Array.isArray(msg.content)){ for(const block of msg.content){ if(!block || block.type !== 'tool_use') continue; let inp = block.input || {}; if(typeof inp === 'string'){ try{ inp = JSON.parse(inp); }catch(_){} } const fakeTc = {name: block.name || '', args: inp, result: block.result || ''}; for(const a of _artifactCandidatesFromToolCall(fakeTc)) push(a.path, a.kind || block.name || 'tool'); } } } return items.slice(0, 50); } function renderSessionArtifacts(){ const root = $('workspaceArtifacts'); const count = $('workspaceArtifactsCount'); if(!root) return; const items = collectSessionArtifacts(); if(count) count.textContent = String(items.length); if(!S.session){ root.innerHTML = '
, so a previously-previewed code file leaves e.g.
// "language-css" on #previewCode. A subsequent plain-text file builds a
// class-less , and Prism walks up to that stale ancestor class and
// mis-highlights prose. Strip any inherited language-* token from the
// before each render so highlighting never leaks across files.
pre.className=pre.className.replace(/\blanguage-\S+/g,'').replace(/\s+/g,' ').trim();
pre.appendChild(codeEl);
// Only invoke Prism when we actually assigned a language; otherwise the
// class-less would inherit any ancestor language-* class.
if(lang&&typeof Prism!=='undefined'&&typeof Prism.highlightElement==='function'){
Prism.highlightElement(codeEl);
}
}catch(e){
// If it's a 400/too-large error, offer download instead
downloadFile(path);
}
}
}
function downloadFile(path){
if(!S.session)return;
// Trigger browser download via the raw file endpoint with content-disposition attachment
const url=`api/file/raw?session_id=${encodeURIComponent(S.session.session_id)}&path=${encodeURIComponent(path)}&download=1`;
const filename=path.split('/').pop();
const a=document.createElement('a');
a.href=url;a.download=filename;
document.body.appendChild(a);a.click();
setTimeout(()=>document.body.removeChild(a),100);
showToast(t('downloading',filename),2000);
}
// ── Render breadcrumb for file preview mode ──────────────────────────────────
function renderFileBreadcrumb(filePath) {
const bar = $('breadcrumbBar');
if (!bar) return;
bar.style.display = 'flex';
const upBtn = $('btnUpDir');
if (upBtn) upBtn.style.display = '';
bar.innerHTML = '';
// Root
const root = document.createElement('span');
root.className = 'breadcrumb-seg breadcrumb-link';
root.textContent = '~';
root.onclick = () => { loadDir('.'); };
bar.appendChild(root);
const parts = filePath.split('/');
let accumulated = '';
for (let i = 0; i < parts.length; i++) {
const sep = document.createElement('span');
sep.className = 'breadcrumb-sep';
sep.textContent = '/';
bar.appendChild(sep);
accumulated += (accumulated ? '/' : '') + parts[i];
const seg = document.createElement('span');
seg.textContent = parts[i];
if (i < parts.length - 1) {
seg.className = 'breadcrumb-seg breadcrumb-link';
const target = accumulated;
seg.onclick = () => { loadDir(target); };
} else {
seg.className = 'breadcrumb-seg breadcrumb-current';
}
bar.appendChild(seg);
}
}
function openInBrowser(){
if(!_previewCurrentPath||!S.session) return;
const url=`api/file/raw?session_id=${encodeURIComponent(S.session.session_id)}&path=${encodeURIComponent(_previewCurrentPath)}&inline=1`;
window.open(url,'_blank','noopener');
}
// ── Workspace upload ──────────────────────────────────────────────────
function triggerWorkspaceUpload() {
const input = $('workspaceFileInput');
if (!input) return;
input.value = '';
input.onchange = async () => {
const files = input.files;
if (!files || !files.length) return;
for (const file of files) {
await uploadToWorkspace(file, S.currentDir || '.');
}
if (S.session) loadDir(S.currentDir);
};
input.click();
}
async function uploadToWorkspace(file, dir) {
if (!S.session) return;
const formData = new FormData();
formData.append('session_id', S.session.session_id);
formData.append('path', dir || '.');
formData.append('file', file, file.name);
try {
showToast(t('uploading') || 'Uploading\u2026', 2000);
const data = await api('/api/workspace/upload', {
method: 'POST',
body: formData,
headers: {},
timeoutMs: 120000,
});
if (data && data.error) {
showToast(data.error, 5000, 'error');
} else if (data && (data.extract_error || (Array.isArray(data.files) && data.files.some(function(f){return f && f.extract_error;})))) {
// Archive was rejected (zip-slip / zip-bomb / corrupt / too-many-members):
// the file uploaded but extraction failed. Surface it as an error instead
// of a misleading "Uploaded" success toast.
var msg = data.extract_error
|| (data.files.find(function(f){return f && f.extract_error;}) || {}).extract_error
|| 'Archive extraction failed';
showToast(msg, 5000, 'error');
} else {
showToast(t('uploaded') || ('Uploaded ' + (data.filename || file.name)), 2000);
}
} catch (e) {
showToast(t('upload_failed') || ('Upload failed: ' + e.message), 5000, 'error');
}
}
function _isOsFilesDrag(e) {
return !!(e.dataTransfer && e.dataTransfer.types && e.dataTransfer.types.includes('Files'));
}
function _joinWorkspacePath(base, rel) {
const b = base || '.';
const r = (rel || '').replace(/^\/+|\/+$/g, '');
if (!r) return b;
return b === '.' ? r : `${b}/${r}`;
}
function _targetDirForRelDir(destDir, relDir) {
const dirPart = (relDir || '').replace(/\/+$/, '');
if (!dirPart) return destDir || '.';
return _joinWorkspacePath(destDir, dirPart);
}
async function _readAllDirectoryEntries(reader) {
const entries = [];
while (true) {
const batch = await new Promise((resolve, reject) => {
reader.readEntries(resolve, reject);
});
if (!batch.length) break;
entries.push(...batch);
}
return entries;
}
async function _collectFilesFromEntry(entry, relPrefix) {
if (entry.isFile) {
const file = await new Promise((resolve, reject) => {
entry.file(resolve, reject);
});
return [{ file, relDir: relPrefix || '' }];
}
if (!entry.isDirectory) return [];
const reader = entry.createReader();
const children = await _readAllDirectoryEntries(reader);
const dirPrefix = `${relPrefix || ''}${entry.name}/`;
let out = [];
for (const child of children) {
out = out.concat(await _collectFilesFromEntry(child, dirPrefix));
}
return out;
}
async function _collectOsDropUploads(dataTransfer) {
const out = [];
const items = dataTransfer.items ? [...dataTransfer.items] : [];
if (items.length && typeof items[0].webkitGetAsEntry === 'function') {
for (const item of items) {
if (item.kind !== 'file') continue;
const entry = item.webkitGetAsEntry();
if (!entry) continue;
out.push(...await _collectFilesFromEntry(entry, ''));
}
if (out.length) return out;
}
for (const file of dataTransfer.files) {
out.push({ file, relDir: '' });
}
return out;
}
async function uploadOsDropToWorkspace(dataTransfer, destDir) {
if (!S.session || !dataTransfer) return;
const uploads = await _collectOsDropUploads(dataTransfer);
for (const { file, relDir } of uploads) {
await uploadToWorkspace(file, _targetDirForRelDir(destDir, relDir));
}
if (S.session) await loadDir(S.currentDir);
}
function _clearWorkspaceOsUploadDragOver() {
document.querySelectorAll('.file-item.drag-over-upload,.breadcrumb-seg.drag-over-upload').forEach((el) => {
el.classList.remove('drag-over-upload');
});
}
function _bindWorkspaceOsUploadDropTarget(el, destDir) {
// Use addEventListener (not on-property assignment) so these OS-upload
// handlers COMPOSE with the workspace tree-MOVE handlers bound by
// _bindWorkspaceMoveDropTarget() on the same element. A property assignment
// for the drop handler here would overwrite the move handler, and a
// workspace-file drag would fall through to the document drop (inserting
// @path into the composer) instead of moving the file. Each handler gates on
// its own drag type (_isOsFilesDrag vs _isWorkspaceTreeMoveDrag), so only the
// matching one acts.
el.addEventListener('dragenter', (e) => {
if (!_isOsFilesDrag(e)) return;
e.preventDefault();
e.stopPropagation();
el.classList.add('drag-over-upload');
});
el.addEventListener('dragover', (e) => {
if (!_isOsFilesDrag(e)) return;
e.preventDefault();
e.stopPropagation();
e.dataTransfer.dropEffect = 'copy';
el.classList.add('drag-over-upload');
});
el.addEventListener('dragleave', (e) => {
if (el.contains(e.relatedTarget)) return;
el.classList.remove('drag-over-upload');
});
el.addEventListener('drop', async (e) => {
if (!_isOsFilesDrag(e)) return;
e.preventDefault();
e.stopPropagation();
el.classList.remove('drag-over-upload');
await uploadOsDropToWorkspace(e.dataTransfer, destDir);
});
}
// Drag-and-drop files onto workspace file tree
if (typeof document !== 'undefined') {
const _wsUploadInit = () => {
const tree = $('fileTree');
if (!tree) return;
tree.addEventListener('dragenter', (e) => {
if (e.dataTransfer && e.dataTransfer.types && e.dataTransfer.types.includes('Files')) {
e.preventDefault();
e.stopPropagation();
}
});
tree.addEventListener('dragover', (e) => {
if (e.dataTransfer && e.dataTransfer.types && e.dataTransfer.types.includes('Files')) {
e.preventDefault();
e.stopPropagation();
if (e.target.closest('.file-item[data-ws-type="dir"],.breadcrumb-seg')) return;
e.dataTransfer.dropEffect = 'copy';
tree.classList.add('drag-over-upload');
}
});
tree.addEventListener('dragleave', (e) => {
if (tree.contains(e.relatedTarget)) return;
tree.classList.remove('drag-over-upload');
});
tree.addEventListener('drop', async (e) => {
tree.classList.remove('drag-over-upload');
if (!e.dataTransfer || !e.dataTransfer.types || !e.dataTransfer.types.includes('Files')) return;
if (e.target.closest('.file-item[data-ws-type="dir"],.breadcrumb-seg')) return;
e.preventDefault();
e.stopPropagation();
await uploadOsDropToWorkspace(e.dataTransfer, S.currentDir || '.');
});
};
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', _wsUploadInit, {once: true});
} else {
_wsUploadInit();
}
}