mirror of
https://github.com/Ark0N/Codeman.git
synced 2026-11-18 20:29:33 +01:00
Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
08de6667ab | ||
|
|
d27f8e77f7 | ||
|
|
e248cd8bcf | ||
|
|
73d81afd4d |
No files matched your search
@@ -1,5 +1,14 @@
|
|||||||
# aicodeman
|
# aicodeman
|
||||||
|
|
||||||
|
## 0.6.11
|
||||||
|
|
||||||
|
### Patch Changes
|
||||||
|
|
||||||
|
- Resume Conversation: fixes and folder drill-down.
|
||||||
|
- **fix(history)**: `decodeProjectKey()` now uses longest-join-first backtracking with on-disk validation, so sibling directories sharing a prefix (e.g. `diary/` vs `diary-app/`) resolve to the correct path. Previously the greedy shortest-match decoder picked the shorter name and bailed, surfacing `$HOME` in the Resume Conversation list and resuming into the wrong folder. Greedy decode is kept as a fallback so history for deleted projects still resolves. (#92)
|
||||||
|
- **fix(tabs)**: Drop the client-side resurrection of ended-session tabs. The old code cached open tabs in `localStorage` and rebuilt them as grayed-out stubs whenever the server no longer knew them, which left phantom tabs after closing a session on another device. The server is now the single source of truth; legacy `localStorage` keys are purged on init. Net -44 / +6 lines. (#93)
|
||||||
|
- **feat(history)**: New "View all in this folder" drill-down on Resume Conversation. `GET /api/history/sessions` accepts `projectKey` (validated against `^[A-Za-z0-9_-]+$` before any filesystem access), `offset`, and `limit`; single-folder mode bypasses the 50-cap and returns `{ sessions, total }`. Frontend adds a modal listing 20 sessions per page with a "Show more" pagination button. Modal items omit their own "View all" button to prevent recursive entry points. (#94)
|
||||||
|
|
||||||
## 0.6.10
|
## 0.6.10
|
||||||
|
|
||||||
### Patch Changes
|
### Patch Changes
|
||||||
|
|||||||
@@ -56,7 +56,7 @@ When user says "COM":
|
|||||||
|
|
||||||
CI runs `npm run check:lockfile` on every push/PR, so lockfile drift fails the build even if the `version-packages` script is bypassed.
|
CI runs `npm run check:lockfile` on every push/PR, so lockfile drift fails the build even if the `version-packages` script is bypassed.
|
||||||
|
|
||||||
**Version**: 0.6.10 (must match `package.json`)
|
**Version**: 0.6.11 (must match `package.json`)
|
||||||
|
|
||||||
## Project Overview
|
## Project Overview
|
||||||
|
|
||||||
|
|||||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
|||||||
{
|
{
|
||||||
"name": "aicodeman",
|
"name": "aicodeman",
|
||||||
"version": "0.6.10",
|
"version": "0.6.11",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "aicodeman",
|
"name": "aicodeman",
|
||||||
"version": "0.6.10",
|
"version": "0.6.11",
|
||||||
"hasInstallScript": true,
|
"hasInstallScript": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"workspaces": [
|
"workspaces": [
|
||||||
|
|||||||
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "aicodeman",
|
"name": "aicodeman",
|
||||||
"version": "0.6.10",
|
"version": "0.6.11",
|
||||||
"description": "The missing control plane for AI coding agents - run 20 autonomous agents with real-time monitoring and session persistence",
|
"description": "The missing control plane for AI coding agents - run 20 autonomous agents with real-time monitoring and session persistence",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"main": "dist/index.js",
|
"main": "dist/index.js",
|
||||||
|
|||||||
+6
-42
@@ -1794,8 +1794,10 @@ class CodemanApp {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// Restore tabs that were open before refresh but are no longer on the server
|
// Server is source of truth for open sessions — don't resurrect stale tabs
|
||||||
this._restoreEndedTabs();
|
// from localStorage (would show phantom "ended" tabs when a session was closed
|
||||||
|
// on another device).
|
||||||
|
try { localStorage.removeItem('codeman-tab-meta'); } catch {}
|
||||||
|
|
||||||
// Sync sessionOrder with current sessions (preserve order, add new, remove stale)
|
// Sync sessionOrder with current sessions (preserve order, add new, remove stale)
|
||||||
this.syncSessionOrder();
|
this.syncSessionOrder();
|
||||||
@@ -2117,8 +2119,7 @@ class CodemanApp {
|
|||||||
const tallTabsEnabled = this._tallTabsEnabled ?? false;
|
const tallTabsEnabled = this._tallTabsEnabled ?? false;
|
||||||
const showFolder = tallTabsEnabled && session.name && folderName && folderName !== name;
|
const showFolder = tallTabsEnabled && session.name && folderName && folderName !== name;
|
||||||
|
|
||||||
const endedAttr = session._ended ? ' data-ended="1"' : '';
|
parts.push(`<div class="session-tab ${isActive ? 'active' : ''}${alertClass}" data-id="${id}" data-color="${color}" onclick="app.selectSession('${escapeHtml(id)}')" oncontextmenu="event.preventDefault(); app.startInlineRename('${escapeHtml(id)}')" tabindex="0" role="tab" aria-selected="${isActive ? 'true' : 'false'}" aria-label="${escapeHtml(name)} session" ${session.workingDir ? `title="${escapeHtml(session.workingDir)}"` : ''}>
|
||||||
parts.push(`<div class="session-tab ${isActive ? 'active' : ''}${alertClass}" data-id="${id}" data-color="${color}"${endedAttr} onclick="app.selectSession('${escapeHtml(id)}')" oncontextmenu="event.preventDefault(); app.startInlineRename('${escapeHtml(id)}')" tabindex="0" role="tab" aria-selected="${isActive ? 'true' : 'false'}" aria-label="${escapeHtml(name)} session" ${session.workingDir ? `title="${escapeHtml(session.workingDir)}"` : ''}>
|
|
||||||
${_tabIdx < 9 ? '<span class="tab-number">' + (_tabIdx + 1) + '</span>' : ''}
|
${_tabIdx < 9 ? '<span class="tab-number">' + (_tabIdx + 1) + '</span>' : ''}
|
||||||
<span class="tab-status ${status}" aria-hidden="true"></span>
|
<span class="tab-status ${status}" aria-hidden="true"></span>
|
||||||
<span class="tab-info">
|
<span class="tab-info">
|
||||||
@@ -2138,9 +2139,6 @@ class CodemanApp {
|
|||||||
|
|
||||||
container.innerHTML = parts.join('');
|
container.innerHTML = parts.join('');
|
||||||
|
|
||||||
// Persist tab metadata for refresh recovery
|
|
||||||
this._saveTabMetadata();
|
|
||||||
|
|
||||||
// Set up drag-and-drop handlers for tab reordering
|
// Set up drag-and-drop handlers for tab reordering
|
||||||
this.setupTabDragHandlers();
|
this.setupTabDragHandlers();
|
||||||
|
|
||||||
@@ -2240,33 +2238,6 @@ class CodemanApp {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Save tab metadata to localStorage so ended sessions can be restored after refresh
|
|
||||||
_saveTabMetadata() {
|
|
||||||
try {
|
|
||||||
const meta = {};
|
|
||||||
for (const [id, s] of this.sessions) {
|
|
||||||
if (s._ended) continue; // Don't persist ended stubs back
|
|
||||||
meta[id] = { id, name: s.name || '', workingDir: s.workingDir || '', mode: s.mode || 'claude', color: s.color || 'default' };
|
|
||||||
}
|
|
||||||
localStorage.setItem('codeman-tab-meta', JSON.stringify(meta));
|
|
||||||
} catch { /* ignore */ }
|
|
||||||
}
|
|
||||||
|
|
||||||
// Restore tabs that were open before refresh but are no longer on the server
|
|
||||||
_restoreEndedTabs() {
|
|
||||||
try {
|
|
||||||
const saved = localStorage.getItem('codeman-tab-meta');
|
|
||||||
if (!saved) return;
|
|
||||||
const meta = JSON.parse(saved);
|
|
||||||
for (const [id, info] of Object.entries(meta)) {
|
|
||||||
if (!this.sessions.has(id)) {
|
|
||||||
// Add a stub session so the tab renders
|
|
||||||
this.sessions.set(id, { id, name: info.name, workingDir: info.workingDir, mode: info.mode, color: info.color, status: 'ended', _ended: true });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch { /* ignore */ }
|
|
||||||
}
|
|
||||||
|
|
||||||
// Set up drag-and-drop handlers on tab elements
|
// Set up drag-and-drop handlers on tab elements
|
||||||
setupTabDragHandlers() {
|
setupTabDragHandlers() {
|
||||||
const container = this.$('sessionTabs');
|
const container = this.$('sessionTabs');
|
||||||
@@ -2546,16 +2517,9 @@ class CodemanApp {
|
|||||||
// Check if this is a restored session that needs to be attached
|
// Check if this is a restored session that needs to be attached
|
||||||
const session = this.sessions.get(sessionId);
|
const session = this.sessions.get(sessionId);
|
||||||
|
|
||||||
// Ended tabs (restored from localStorage, no longer on server) — show message, skip buffer load
|
|
||||||
if (session?._ended) {
|
|
||||||
this.terminal.clear();
|
|
||||||
this.terminal.write('\r\n \x1b[2mSession ended. Close tab or click to reopen.\x1b[0m\r\n');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Track working directory for path normalization in Project Insights
|
// Track working directory for path normalization in Project Insights
|
||||||
this.currentSessionWorkingDir = session?.workingDir || null;
|
this.currentSessionWorkingDir = session?.workingDir || null;
|
||||||
if (session && session.pid === null && !session._ended) {
|
if (session && session.pid === null) {
|
||||||
// Session has no PTY attached — either restored after server restart
|
// Session has no PTY attached — either restored after server restart
|
||||||
// or detached for some other reason. Re-attach regardless of status.
|
// or detached for some other reason. Re-attach regardless of status.
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -293,7 +293,6 @@ body {
|
|||||||
}
|
}
|
||||||
.session-tab .tab-status.error { background: var(--red); }
|
.session-tab .tab-status.error { background: var(--red); }
|
||||||
.session-tab .tab-status.ended { background: var(--text-muted); opacity: 0.5; }
|
.session-tab .tab-status.ended { background: var(--text-muted); opacity: 0.5; }
|
||||||
.session-tab[data-ended] { opacity: 0.55; }
|
|
||||||
|
|
||||||
/* Session color coding - left border indicator */
|
/* Session color coding - left border indicator */
|
||||||
.session-tab[data-color="red"] { border-left: 3px solid var(--session-red); }
|
.session-tab[data-color="red"] { border-left: 3px solid var(--session-red); }
|
||||||
@@ -2370,6 +2369,56 @@ body {
|
|||||||
color: var(--text);
|
color: var(--text);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.history-detail-actions {
|
||||||
|
margin-top: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.history-view-all-btn {
|
||||||
|
width: 100%;
|
||||||
|
padding: 0.45rem 0.75rem;
|
||||||
|
background: rgba(99, 179, 237, 0.08);
|
||||||
|
border: 1px solid rgba(99, 179, 237, 0.25);
|
||||||
|
border-radius: 6px;
|
||||||
|
color: rgba(99, 179, 237, 0.95);
|
||||||
|
font-size: 0.78rem;
|
||||||
|
font-weight: 500;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: background var(--transition-smooth), border-color var(--transition-smooth);
|
||||||
|
}
|
||||||
|
|
||||||
|
.history-view-all-btn:hover {
|
||||||
|
background: rgba(99, 179, 237, 0.15);
|
||||||
|
border-color: rgba(99, 179, 237, 0.5);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Folder history modal */
|
||||||
|
.folder-history-modal .modal-body {
|
||||||
|
padding: 0.75rem 1rem 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.folder-history-subtitle {
|
||||||
|
color: var(--text-muted);
|
||||||
|
font-size: 0.78rem;
|
||||||
|
font-family: 'SF Mono', Menlo, Consolas, monospace;
|
||||||
|
word-break: break-all;
|
||||||
|
margin-bottom: 0.75rem;
|
||||||
|
padding-bottom: 0.5rem;
|
||||||
|
border-bottom: 1px solid rgba(255, 255, 255, 0.06);
|
||||||
|
}
|
||||||
|
|
||||||
|
.folder-history-list {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.folder-history-empty {
|
||||||
|
padding: 2rem 0.5rem;
|
||||||
|
text-align: center;
|
||||||
|
color: var(--text-muted);
|
||||||
|
font-size: 0.85rem;
|
||||||
|
}
|
||||||
|
|
||||||
.welcome-hint {
|
.welcome-hint {
|
||||||
color: var(--text-muted);
|
color: var(--text-muted);
|
||||||
font-size: 0.8rem;
|
font-size: 0.8rem;
|
||||||
|
|||||||
@@ -444,7 +444,6 @@ Object.assign(CodemanApp.prototype, {
|
|||||||
if (
|
if (
|
||||||
activeResizeSession &&
|
activeResizeSession &&
|
||||||
activeResizeSession.mode !== 'shell' &&
|
activeResizeSession.mode !== 'shell' &&
|
||||||
!activeResizeSession._ended &&
|
|
||||||
this.terminal &&
|
this.terminal &&
|
||||||
this.isTerminalAtBottom()
|
this.isTerminalAtBottom()
|
||||||
) {
|
) {
|
||||||
@@ -918,8 +917,15 @@ Object.assign(CodemanApp.prototype, {
|
|||||||
.replace(/^\/Users\/[^/]+\//, '~/');
|
.replace(/^\/Users\/[^/]+\//, '~/');
|
||||||
},
|
},
|
||||||
|
|
||||||
/** Build a single history item DOM element */
|
/**
|
||||||
_buildHistoryItem(s, cases) {
|
* Build a single history item DOM element.
|
||||||
|
* @param {object} s session record
|
||||||
|
* @param {Array} cases linked cases (for #caseName label)
|
||||||
|
* @param {object} [options]
|
||||||
|
* @param {boolean} [options.showViewAll=true] show "View all in folder" button in detail panel
|
||||||
|
*/
|
||||||
|
_buildHistoryItem(s, cases, options) {
|
||||||
|
const showViewAll = options?.showViewAll !== false;
|
||||||
const size =
|
const size =
|
||||||
s.sizeBytes < 1024
|
s.sizeBytes < 1024
|
||||||
? `${s.sizeBytes}B`
|
? `${s.sizeBytes}B`
|
||||||
@@ -1001,6 +1007,21 @@ Object.assign(CodemanApp.prototype, {
|
|||||||
|
|
||||||
detail.append(promptRow, pathRow, metaRow);
|
detail.append(promptRow, pathRow, metaRow);
|
||||||
|
|
||||||
|
if (showViewAll && s.projectKey) {
|
||||||
|
const actionRow = document.createElement('div');
|
||||||
|
actionRow.className = 'history-detail-row history-detail-actions';
|
||||||
|
const viewAllBtn = document.createElement('button');
|
||||||
|
viewAllBtn.type = 'button';
|
||||||
|
viewAllBtn.className = 'history-view-all-btn';
|
||||||
|
viewAllBtn.textContent = 'View all in this folder';
|
||||||
|
viewAllBtn.addEventListener('click', (ev) => {
|
||||||
|
ev.stopPropagation();
|
||||||
|
this.openFolderHistoryModal(s.projectKey, s.workingDir, cases);
|
||||||
|
});
|
||||||
|
actionRow.appendChild(viewAllBtn);
|
||||||
|
detail.appendChild(actionRow);
|
||||||
|
}
|
||||||
|
|
||||||
expandBtn.addEventListener('click', (ev) => {
|
expandBtn.addEventListener('click', (ev) => {
|
||||||
ev.stopPropagation();
|
ev.stopPropagation();
|
||||||
const expanded = item.classList.toggle('expanded');
|
const expanded = item.classList.toggle('expanded');
|
||||||
@@ -1064,9 +1085,144 @@ Object.assign(CodemanApp.prototype, {
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
|
/** Page size for the folder history modal */
|
||||||
|
_FOLDER_HISTORY_PAGE_SIZE: 20,
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Open a modal showing all history sessions in a single folder.
|
||||||
|
* Paginated by FOLDER_HISTORY_PAGE_SIZE; "Show more" loads next page.
|
||||||
|
*/
|
||||||
|
openFolderHistoryModal(projectKey, workingDir, cases) {
|
||||||
|
// Close any existing instance first
|
||||||
|
this._closeFolderHistoryModal();
|
||||||
|
|
||||||
|
const modal = document.createElement('div');
|
||||||
|
modal.className = 'modal active folder-history-modal';
|
||||||
|
modal.id = 'folderHistoryModal';
|
||||||
|
|
||||||
|
const backdrop = document.createElement('div');
|
||||||
|
backdrop.className = 'modal-backdrop';
|
||||||
|
backdrop.addEventListener('click', () => this._closeFolderHistoryModal());
|
||||||
|
|
||||||
|
const content = document.createElement('div');
|
||||||
|
content.className = 'modal-content modal-lg';
|
||||||
|
|
||||||
|
const header = document.createElement('div');
|
||||||
|
header.className = 'modal-header';
|
||||||
|
const title = document.createElement('h3');
|
||||||
|
title.textContent = 'Folder History';
|
||||||
|
const subtitle = document.createElement('div');
|
||||||
|
subtitle.className = 'folder-history-subtitle';
|
||||||
|
subtitle.textContent = this._shortenHomePath(workingDir);
|
||||||
|
const closeBtn = document.createElement('button');
|
||||||
|
closeBtn.className = 'modal-close';
|
||||||
|
closeBtn.setAttribute('aria-label', 'Close');
|
||||||
|
closeBtn.innerHTML = '×';
|
||||||
|
closeBtn.addEventListener('click', () => this._closeFolderHistoryModal());
|
||||||
|
header.append(title, closeBtn);
|
||||||
|
|
||||||
|
const body = document.createElement('div');
|
||||||
|
body.className = 'modal-body';
|
||||||
|
const list = document.createElement('div');
|
||||||
|
list.className = 'folder-history-list';
|
||||||
|
list.setAttribute('data-loading', 'true');
|
||||||
|
list.textContent = 'Loading...';
|
||||||
|
body.append(subtitle, list);
|
||||||
|
|
||||||
|
content.append(header, body);
|
||||||
|
modal.append(backdrop, content);
|
||||||
|
document.body.appendChild(modal);
|
||||||
|
|
||||||
|
// Track state for pagination
|
||||||
|
this._folderHistoryState = {
|
||||||
|
projectKey,
|
||||||
|
workingDir,
|
||||||
|
cases: cases || [],
|
||||||
|
offset: 0,
|
||||||
|
total: null,
|
||||||
|
list,
|
||||||
|
};
|
||||||
|
|
||||||
|
// ESC to close
|
||||||
|
this._folderHistoryEscHandler = (ev) => {
|
||||||
|
if (ev.key === 'Escape') this._closeFolderHistoryModal();
|
||||||
|
};
|
||||||
|
document.addEventListener('keydown', this._folderHistoryEscHandler);
|
||||||
|
|
||||||
|
this._loadFolderHistoryPage();
|
||||||
|
},
|
||||||
|
|
||||||
|
async _loadFolderHistoryPage() {
|
||||||
|
const state = this._folderHistoryState;
|
||||||
|
if (!state) return;
|
||||||
|
const { projectKey, cases, list } = state;
|
||||||
|
const limit = this._FOLDER_HISTORY_PAGE_SIZE;
|
||||||
|
const offset = state.offset;
|
||||||
|
|
||||||
|
// Remove existing "Show more" button while loading
|
||||||
|
const existingMore = list.querySelector('.folder-history-more');
|
||||||
|
if (existingMore) existingMore.remove();
|
||||||
|
|
||||||
|
// First page: clear loading placeholder
|
||||||
|
if (offset === 0) {
|
||||||
|
list.replaceChildren();
|
||||||
|
list.removeAttribute('data-loading');
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const url = `/api/history/sessions?projectKey=${encodeURIComponent(projectKey)}&offset=${offset}&limit=${limit}`;
|
||||||
|
const res = await fetch(url);
|
||||||
|
const data = await res.json();
|
||||||
|
const sessions = data.sessions || [];
|
||||||
|
state.total = typeof data.total === 'number' ? data.total : sessions.length + offset;
|
||||||
|
|
||||||
|
if (offset === 0 && sessions.length === 0) {
|
||||||
|
const empty = document.createElement('div');
|
||||||
|
empty.className = 'folder-history-empty';
|
||||||
|
empty.textContent = 'No conversations found in this folder.';
|
||||||
|
list.appendChild(empty);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const s of sessions) {
|
||||||
|
list.appendChild(this._buildHistoryItem(s, cases, { showViewAll: false }));
|
||||||
|
}
|
||||||
|
|
||||||
|
state.offset = offset + sessions.length;
|
||||||
|
|
||||||
|
// Add "Show more" if there are more sessions
|
||||||
|
if (state.offset < state.total) {
|
||||||
|
const remaining = state.total - state.offset;
|
||||||
|
const moreBtn = document.createElement('button');
|
||||||
|
moreBtn.className = 'history-show-more folder-history-more';
|
||||||
|
moreBtn.textContent = `Show ${Math.min(limit, remaining)} more (${remaining} remaining)`;
|
||||||
|
moreBtn.addEventListener('click', () => this._loadFolderHistoryPage());
|
||||||
|
list.appendChild(moreBtn);
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.error('[loadFolderHistoryPage]', err);
|
||||||
|
const errorEl = document.createElement('div');
|
||||||
|
errorEl.className = 'folder-history-empty';
|
||||||
|
errorEl.textContent = 'Failed to load folder history.';
|
||||||
|
list.appendChild(errorEl);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
_closeFolderHistoryModal() {
|
||||||
|
const modal = document.getElementById('folderHistoryModal');
|
||||||
|
if (modal) modal.remove();
|
||||||
|
if (this._folderHistoryEscHandler) {
|
||||||
|
document.removeEventListener('keydown', this._folderHistoryEscHandler);
|
||||||
|
this._folderHistoryEscHandler = null;
|
||||||
|
}
|
||||||
|
this._folderHistoryState = null;
|
||||||
|
},
|
||||||
|
|
||||||
async resumeHistorySession(sessionId, workingDir) {
|
async resumeHistorySession(sessionId, workingDir) {
|
||||||
// Close the run mode menu if open
|
// Close the run mode menu if open
|
||||||
document.getElementById('runModeMenu')?.classList.remove('active');
|
document.getElementById('runModeMenu')?.classList.remove('active');
|
||||||
|
// Close folder history modal if open
|
||||||
|
this._closeFolderHistoryModal();
|
||||||
try {
|
try {
|
||||||
this.terminal.clear();
|
this.terminal.clear();
|
||||||
this.terminal.writeln(`\x1b[1;32m Resuming conversation ${sessionId.slice(0, 8)}...\x1b[0m`);
|
this.terminal.writeln(`\x1b[1;32m Resuming conversation ${sessionId.slice(0, 8)}...\x1b[0m`);
|
||||||
|
|||||||
@@ -1324,42 +1324,76 @@ export function registerSessionRoutes(
|
|||||||
* Claude CLI encodes both '/' and '_' as '-', so each '-' in the key could be
|
* Claude CLI encodes both '/' and '_' as '-', so each '-' in the key could be
|
||||||
* any of: '/' (path separator), '_' (underscore), or '-' (literal dash).
|
* any of: '/' (path separator), '_' (underscore), or '-' (literal dash).
|
||||||
*
|
*
|
||||||
* Strategy: look-ahead matching. At each '-', try consuming multiple segments
|
* Strategy: recursive backtracking with longest-match-first preference.
|
||||||
* joined by '_' or '-' to find an existing child directory, then recurse.
|
* At each segment boundary, try joining as many segments as possible (with '_'
|
||||||
* E.g. for segments [AI, project, Mirror] inside /Workspace:
|
* or '-') into a single existing directory name. If a shorter match leads to a
|
||||||
* try /Workspace/AI (no) -> /Workspace/AI_project (yes!) -> continue with [Mirror]
|
* dead end, backtrack and try the next-shorter candidate.
|
||||||
|
*
|
||||||
|
* Why backtracking: when both `diary/` and `diary-app/` exist as siblings, the
|
||||||
|
* naive shortest-match would pick `diary` and then fail to find `app` inside,
|
||||||
|
* leaving the rest of the key unresolved. Longest-first picks `diary-app`.
|
||||||
*/
|
*/
|
||||||
async function decodeProjectKey(projKey: string): Promise<string> {
|
async function decodeProjectKey(projKey: string): Promise<string> {
|
||||||
const encoded = projKey.startsWith('-') ? projKey.slice(1) : projKey;
|
const encoded = projKey.startsWith('-') ? projKey.slice(1) : projKey;
|
||||||
const segments = encoded.split('-');
|
const segments = encoded.split('-');
|
||||||
|
|
||||||
const isDir = async (p: string): Promise<boolean> =>
|
const isDirCache = new Map<string, boolean>();
|
||||||
fs
|
const isDir = async (p: string): Promise<boolean> => {
|
||||||
|
const cached = isDirCache.get(p);
|
||||||
|
if (cached !== undefined) return cached;
|
||||||
|
const result = await fs
|
||||||
.stat(p)
|
.stat(p)
|
||||||
.then((s) => s.isDirectory())
|
.then((s) => s.isDirectory())
|
||||||
.catch(() => false);
|
.catch(() => false);
|
||||||
|
isDirCache.set(p, result);
|
||||||
|
return result;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Recursive backtracking: returns the deepest valid path that consumes all
|
||||||
|
// segments. Tries the longest segment-join first at each step so that
|
||||||
|
// dash-containing directory names win over shorter same-prefix siblings.
|
||||||
|
async function tryDecode(idx: number, current: string): Promise<string | null> {
|
||||||
|
if (idx >= segments.length) return current;
|
||||||
|
const maxLook = Math.min(idx + 4, segments.length);
|
||||||
|
// Longest first: end = maxLook-1 down to idx
|
||||||
|
for (let end = maxLook - 1; end >= idx; end--) {
|
||||||
|
const candidates: string[] = [];
|
||||||
|
if (end === idx) {
|
||||||
|
candidates.push(segments[idx]);
|
||||||
|
} else {
|
||||||
|
candidates.push(segments.slice(idx, end + 1).join('-'));
|
||||||
|
candidates.push(segments.slice(idx, end + 1).join('_'));
|
||||||
|
}
|
||||||
|
for (const child of candidates) {
|
||||||
|
const candidate = current + '/' + child;
|
||||||
|
if (await isDir(candidate)) {
|
||||||
|
const result = await tryDecode(end + 1, candidate);
|
||||||
|
if (result) return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const decoded = await tryDecode(0, '');
|
||||||
|
if (decoded) return decoded;
|
||||||
|
|
||||||
|
// Fallback: greedy shortest-match (original behavior) — best effort when
|
||||||
|
// no fully-valid path exists (e.g. directory was deleted after the
|
||||||
|
// conversation was recorded).
|
||||||
let current = '';
|
let current = '';
|
||||||
let i = 0;
|
let i = 0;
|
||||||
|
|
||||||
while (i < segments.length) {
|
while (i < segments.length) {
|
||||||
// Try progressively longer child names by joining segments with '_' or '-'
|
|
||||||
let matched = false;
|
let matched = false;
|
||||||
// Limit look-ahead to avoid excessive fs checks (max 4 segments per component)
|
|
||||||
const maxLook = Math.min(i + 4, segments.length);
|
const maxLook = Math.min(i + 4, segments.length);
|
||||||
for (let end = i; end < maxLook; end++) {
|
for (let end = i; end < maxLook; end++) {
|
||||||
// Build candidate child name from segments[i..end]
|
|
||||||
// Try all separator combinations: for 2+ segments, try '_' first then '-'
|
|
||||||
const candidates: string[] = [];
|
const candidates: string[] = [];
|
||||||
if (end === i) {
|
if (end === i) {
|
||||||
candidates.push(segments[i]);
|
candidates.push(segments[i]);
|
||||||
} else {
|
} else {
|
||||||
// Build with underscores between joined segments
|
|
||||||
candidates.push(segments.slice(i, end + 1).join('_'));
|
candidates.push(segments.slice(i, end + 1).join('_'));
|
||||||
// Build with dashes (literal)
|
|
||||||
candidates.push(segments.slice(i, end + 1).join('-'));
|
candidates.push(segments.slice(i, end + 1).join('-'));
|
||||||
}
|
}
|
||||||
|
|
||||||
for (const child of candidates) {
|
for (const child of candidates) {
|
||||||
const candidate = current + '/' + child;
|
const candidate = current + '/' + child;
|
||||||
if (await isDir(candidate)) {
|
if (await isDir(candidate)) {
|
||||||
@@ -1372,12 +1406,10 @@ export function registerSessionRoutes(
|
|||||||
if (matched) break;
|
if (matched) break;
|
||||||
}
|
}
|
||||||
if (!matched) {
|
if (!matched) {
|
||||||
// No directory match found — append as-is and move on
|
|
||||||
current = current + '/' + segments[i];
|
current = current + '/' + segments[i];
|
||||||
i++;
|
i++;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const finalExists = await fs
|
const finalExists = await fs
|
||||||
.access(current)
|
.access(current)
|
||||||
.then(() => true)
|
.then(() => true)
|
||||||
@@ -1416,96 +1448,104 @@ export function registerSessionRoutes(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
app.get('/api/history/sessions', async () => {
|
type HistorySession = {
|
||||||
|
sessionId: string;
|
||||||
|
workingDir: string;
|
||||||
|
projectKey: string;
|
||||||
|
sizeBytes: number;
|
||||||
|
lastModified: string;
|
||||||
|
firstPrompt?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Scan a single project directory and return all valid history sessions in it.
|
||||||
|
// Reused by both the global overview and the single-folder drill-down.
|
||||||
|
async function scanProjectDir(projPath: string, projDir: string, headBuf: Buffer): Promise<HistorySession[]> {
|
||||||
|
const out: HistorySession[] = [];
|
||||||
|
const stat = await fs.stat(projPath).catch(() => null);
|
||||||
|
if (!stat?.isDirectory()) return out;
|
||||||
|
|
||||||
|
const workingDir = await decodeProjectKey(projDir);
|
||||||
|
const entries = await fs.readdir(projPath).catch(() => [] as string[]);
|
||||||
|
|
||||||
|
for (const entry of entries) {
|
||||||
|
if (!entry.endsWith('.jsonl')) continue;
|
||||||
|
const sessionId = entry.replace('.jsonl', '');
|
||||||
|
if (!/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(sessionId)) continue;
|
||||||
|
|
||||||
|
const filePath = join(projPath, entry);
|
||||||
|
const fileStat = await fs.stat(filePath).catch(() => null);
|
||||||
|
if (!fileStat) continue;
|
||||||
|
if (fileStat.size < 4000) continue;
|
||||||
|
|
||||||
|
let firstPrompt: string | undefined;
|
||||||
|
const head = await readFileHead(filePath, headBuf);
|
||||||
|
const hasConversation = (text: string) =>
|
||||||
|
text.includes('"type":"user"') || text.includes('"type":"assistant"') || text.includes('"type":"summary"');
|
||||||
|
|
||||||
|
let foundContent = head ? hasConversation(head) : false;
|
||||||
|
let tail: string | null = null;
|
||||||
|
if (!foundContent && fileStat.size > 16384) {
|
||||||
|
const tailBuf = Buffer.alloc(32768);
|
||||||
|
tail = await readFileTail(filePath, tailBuf, fileStat.size);
|
||||||
|
if (tail) foundContent = hasConversation(tail);
|
||||||
|
}
|
||||||
|
if (!foundContent) continue;
|
||||||
|
|
||||||
|
if (head) firstPrompt = extractFirstUserPrompt(head);
|
||||||
|
if (!firstPrompt && fileStat.size > 65536) {
|
||||||
|
if (!tail) {
|
||||||
|
const tailBuf = Buffer.alloc(32768);
|
||||||
|
tail = await readFileTail(filePath, tailBuf, fileStat.size);
|
||||||
|
}
|
||||||
|
if (tail) firstPrompt = extractFirstUserPrompt(tail);
|
||||||
|
}
|
||||||
|
|
||||||
|
out.push({
|
||||||
|
sessionId,
|
||||||
|
workingDir,
|
||||||
|
projectKey: projDir,
|
||||||
|
sizeBytes: fileStat.size,
|
||||||
|
lastModified: fileStat.mtime.toISOString(),
|
||||||
|
firstPrompt,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
app.get('/api/history/sessions', async (req) => {
|
||||||
|
const query = req.query as { projectKey?: string; offset?: string; limit?: string };
|
||||||
const projectsDir = join(process.env.HOME || '/tmp', '.claude', 'projects');
|
const projectsDir = join(process.env.HOME || '/tmp', '.claude', 'projects');
|
||||||
const results: Array<{
|
|
||||||
sessionId: string;
|
|
||||||
workingDir: string;
|
|
||||||
projectKey: string;
|
|
||||||
sizeBytes: number;
|
|
||||||
lastModified: string;
|
|
||||||
firstPrompt?: string;
|
|
||||||
}> = [];
|
|
||||||
const headBuf = Buffer.alloc(16384);
|
const headBuf = Buffer.alloc(16384);
|
||||||
|
|
||||||
|
// Single-folder drill-down: when projectKey is provided, scan only that
|
||||||
|
// directory, bypass the 50-cap, and honor offset/limit pagination.
|
||||||
|
if (query.projectKey) {
|
||||||
|
// Validate projectKey format to prevent path traversal
|
||||||
|
if (!/^[A-Za-z0-9_-]+$/.test(query.projectKey)) {
|
||||||
|
return { sessions: [], total: 0 };
|
||||||
|
}
|
||||||
|
const offset = Math.max(0, parseInt(query.offset || '0', 10) || 0);
|
||||||
|
const limit = Math.min(100, Math.max(1, parseInt(query.limit || '20', 10) || 20));
|
||||||
|
const projPath = join(projectsDir, query.projectKey);
|
||||||
|
const all = await scanProjectDir(projPath, query.projectKey, headBuf);
|
||||||
|
all.sort((a, b) => new Date(b.lastModified).getTime() - new Date(a.lastModified).getTime());
|
||||||
|
return { sessions: all.slice(offset, offset + limit), total: all.length };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Global overview: scan all projects, return up to 50 most-recent sessions.
|
||||||
|
const results: HistorySession[] = [];
|
||||||
try {
|
try {
|
||||||
const projectDirs = await fs.readdir(projectsDir);
|
const projectDirs = await fs.readdir(projectsDir);
|
||||||
for (const projDir of projectDirs) {
|
for (const projDir of projectDirs) {
|
||||||
const projPath = join(projectsDir, projDir);
|
const projPath = join(projectsDir, projDir);
|
||||||
const stat = await fs.stat(projPath).catch(() => null);
|
const list = await scanProjectDir(projPath, projDir, headBuf);
|
||||||
if (!stat?.isDirectory()) continue;
|
results.push(...list);
|
||||||
|
|
||||||
// Decode project key to working dir. Claude CLI encodes '/' as '-',
|
|
||||||
// but path components may also contain '-' (e.g. "AI_project" vs "AI-project").
|
|
||||||
// Use recursive backtracking: try each '-' as either '/' or literal '-',
|
|
||||||
// verify which decoded path actually exists on disk.
|
|
||||||
const workingDir = await decodeProjectKey(projDir);
|
|
||||||
|
|
||||||
const entries = await fs.readdir(projPath);
|
|
||||||
for (const entry of entries) {
|
|
||||||
if (!entry.endsWith('.jsonl')) continue;
|
|
||||||
const sessionId = entry.replace('.jsonl', '');
|
|
||||||
// Only valid UUIDs
|
|
||||||
if (!/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(sessionId)) continue;
|
|
||||||
|
|
||||||
const filePath = join(projPath, entry);
|
|
||||||
const fileStat = await fs.stat(filePath).catch(() => null);
|
|
||||||
if (!fileStat) continue;
|
|
||||||
// Skip files too small to contain real conversation (metadata-only sessions
|
|
||||||
// like file-history-snapshot entries are typically < 4KB)
|
|
||||||
if (fileStat.size < 4000) continue;
|
|
||||||
|
|
||||||
// Quick content check: verify actual conversation data exists.
|
|
||||||
// Sessions with only file-history-snapshot or hook_progress entries have
|
|
||||||
// no "user"/"assistant" messages and will fail claude --resume.
|
|
||||||
// Read first 16KB to check content and extract first user prompt.
|
|
||||||
let firstPrompt: string | undefined;
|
|
||||||
const head = await readFileHead(filePath, headBuf);
|
|
||||||
const hasConversation = (text: string) =>
|
|
||||||
text.includes('"type":"user"') || text.includes('"type":"assistant"') || text.includes('"type":"summary"');
|
|
||||||
|
|
||||||
let foundContent = head ? hasConversation(head) : false;
|
|
||||||
|
|
||||||
// For large files, head may not contain user messages (e.g. /init followed
|
|
||||||
// by large system entries). Check the tail as well.
|
|
||||||
let tail: string | null = null;
|
|
||||||
if (!foundContent && fileStat.size > 16384) {
|
|
||||||
const tailBuf = Buffer.alloc(32768);
|
|
||||||
tail = await readFileTail(filePath, tailBuf, fileStat.size);
|
|
||||||
if (tail) foundContent = hasConversation(tail);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!foundContent) continue; // No conversation content — skip
|
|
||||||
|
|
||||||
if (head) firstPrompt = extractFirstUserPrompt(head);
|
|
||||||
|
|
||||||
// If head scan found no usable prompt (e.g. session started with /init),
|
|
||||||
// try reading the tail for a recent user message.
|
|
||||||
if (!firstPrompt && fileStat.size > 65536) {
|
|
||||||
if (!tail) {
|
|
||||||
const tailBuf = Buffer.alloc(32768);
|
|
||||||
tail = await readFileTail(filePath, tailBuf, fileStat.size);
|
|
||||||
}
|
|
||||||
if (tail) firstPrompt = extractFirstUserPrompt(tail);
|
|
||||||
}
|
|
||||||
|
|
||||||
results.push({
|
|
||||||
sessionId,
|
|
||||||
workingDir,
|
|
||||||
projectKey: projDir,
|
|
||||||
sizeBytes: fileStat.size,
|
|
||||||
lastModified: fileStat.mtime.toISOString(),
|
|
||||||
firstPrompt,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
} catch {
|
} catch {
|
||||||
// Projects dir may not exist
|
// Projects dir may not exist
|
||||||
}
|
}
|
||||||
|
|
||||||
// Sort by lastModified descending
|
|
||||||
results.sort((a, b) => new Date(b.lastModified).getTime() - new Date(a.lastModified).getTime());
|
results.sort((a, b) => new Date(b.lastModified).getTime() - new Date(a.lastModified).getTime());
|
||||||
|
|
||||||
return { sessions: results.slice(0, 50) };
|
return { sessions: results.slice(0, 50) };
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
Reference in new issue
Block a user