mirror of
https://github.com/siteboon/claudecodeui.git
synced 2026-05-01 18:28:38 +00:00
GET /api/projects used to scan ~/.claude/projects/ on every request, derive each project's identity from the encoded folder name, and re-parse JSONL files to build session lists. Using the folder-derived name as the project identifier leaked the Claude CLI's on-disk encoding into every API route, forced every downstream endpoint to re-resolve a real path via JSONL 'cwd' inspection, and made the project list endpoint O(projects x sessions) on disk I/O. This change switches the entire API surface to identify projects by the stable primary key from the 'projects' table and drives the listing straight from the DB: - Add projectsDb.getProjectPathById as the canonical projectId -> path resolver so routes no longer need to touch the filesystem to figure out where a project lives. - Rewrite getProjects so it reads the project list from the 'projects' table and the per-project session list from the 'sessions' table (one SELECT per project). No filesystem scanning happens for this endpoint anymore, which removes the dependency on ~/.claude/projects existing, on Cursor's MD5-hashed chat folders being discoverable, and on Codex's JSONL history being on disk. Per the migration spec each session now exposes 'summary' sourced from sessions.custom_name, 'messageCount' = 0 (message counting is not implemented), and sessionMeta.hasMore is pinned to false since this endpoint doesn't drive session pagination. - Introduce id-based wrappers (getSessionsById, renameProjectById, deleteSessionById, deleteProjectById, getProjectTaskMasterById) so every caller can pass projectId and resolve the real path through the DB. renameProjectById also writes to projects.custom_project_name so the DB-driven getProjects response reflects renames immediately; it keeps project-config.json in sync for any legacy reader that still consults the JSON file. - Migrate every /api/projects/:projectName route in server/index.js, server/routes/taskmaster.js, and server/routes/messages.js to :projectId, and change server/routes/git.js so the 'project' query/body parameter carries a projectId that is resolved through the DB before any git command runs. TaskMaster WebSocket broadcasts emit 'projectId' for the same reason so the frontend can match notifications against its current selection without another lookup. - Delete helpers that existed only to feed the old getProjects path (getCursorSessions, getGeminiCliSessions, getProjectTaskMaster) along with their unused imports (better-sqlite3's Database, applyCustomSessionNames). The legacy folder-name helpers (getSessions, renameProject, deleteSession, deleteProject, extractProjectDirectory) are kept as internal implementation details of the id-based wrappers and of destructive cleanup / conversation search, but they are no longer re-exported. - searchConversations still walks JSONL to produce match snippets (that data doesn't live in the DB), but it now includes the resolved projectId in each result so the sidebar can cross-reference hits with its already loaded project list without a second round-trip. Frontend migration: - Project.name is replaced by Project.projectId in src/types/app.ts, and ProjectSession.__projectName becomes __projectId so session tagging and sidebar state keys stay aligned with the backend identifier. Settings continues to use SettingsProject.name for legacy consumers, but it is populated from projectId by normalizeProjectForSettings. - All places that previously indexed per-project state by project.name (sidebar expanded/starred/loading/deletingProjects sets, additionalSessions map, projectHasMoreOverrides, starredProjects localStorage, command history and draft-input localStorage, TaskMaster caches) now key on projectId so state survives display-name edits and is consistent across the app. - src/utils/api.js renames every endpoint parameter to projectId, the unified messages endpoint takes projectId in its query string, and useSessionStore forwards projectId on fetchFromServer / fetchMore / refreshFromServer. Git panel, file tree, code editor, PRD editor, plugins context, MCP server flows and TaskMaster hooks are all updated to pass projectId. - DEFAULT_PROJECT_FOR_EMPTY_SHELL is updated to carry a 'default' projectId sentinel so the empty-shell placeholder still satisfies the Project contract. Bug fix bundled in: - sessionsDb.setName no longer bumps updated_at when a row already exists. Renaming is a label change, not activity, so there is no reason for it to reset 'last activity' in the sidebar. It also no longer relies on SQLite's CURRENT_TIMESTAMP, which stores a naive 'YYYY-MM-DD HH:MM:SS' value that JavaScript parses as local time and caused renamed sessions to appear shifted backwards by the client's UTC offset. When an INSERT actually happens it now writes ISO-8601 UTC with a 'Z' suffix. - buildSessionsByProviderFromDb normalizes any legacy naive timestamps in the sessions table to ISO-8601 UTC on the way out so rows written before this change also render correctly on the client. Other cleanup: - Removed the filesystem-first project-discovery comment block at the top of server/projects.js and replaced it with a short note that describes the new DB-driven flow and lists the few remaining filesystem-dependent helpers (message reads, search, destructive delete, manual project registration). - server/modules/providers/index.ts is added as a small barrel so the providers module exposes a stable public surface. Made-with: Cursor
283 lines
8.6 KiB
TypeScript
283 lines
8.6 KiB
TypeScript
import path from 'node:path';
|
|
|
|
import { getConnection } from '@/modules/database/connection.js';
|
|
import { projectsDb } from '@/modules/database/repositories/projects.db.js';
|
|
|
|
type SessionNameLookupRow = {
|
|
session_id: string;
|
|
custom_name: string;
|
|
};
|
|
|
|
type SessionRow = {
|
|
session_id: string;
|
|
provider: string;
|
|
project_path: string | null;
|
|
jsonl_path: string | null;
|
|
custom_name: string | null;
|
|
created_at: string;
|
|
updated_at: string;
|
|
};
|
|
|
|
type SessionMetadataLookupRow = Pick<
|
|
SessionRow,
|
|
'session_id' | 'provider' | 'project_path' | 'jsonl_path' | 'custom_name' | 'created_at' | 'updated_at'
|
|
>;
|
|
|
|
type LegacySessionSummary = {
|
|
id: string;
|
|
summary?: string;
|
|
};
|
|
|
|
function normalizeTimestamp(value?: string): string | null {
|
|
if (!value) return null;
|
|
|
|
const parsed = new Date(value);
|
|
if (Number.isNaN(parsed.getTime())) {
|
|
return null;
|
|
}
|
|
|
|
return parsed.toISOString();
|
|
}
|
|
|
|
function normalizeCodexProjectPath(projectPath: string): string {
|
|
const trimmedPath = projectPath.trim();
|
|
if (!trimmedPath) {
|
|
return projectPath;
|
|
}
|
|
|
|
if (process.platform !== 'win32') {
|
|
return path.normalize(trimmedPath);
|
|
}
|
|
|
|
let strippedPath = trimmedPath;
|
|
if (strippedPath.startsWith('\\\\?\\UNC\\')) {
|
|
strippedPath = `\\\\${strippedPath.slice('\\\\?\\UNC\\'.length)}`;
|
|
} else if (strippedPath.startsWith('\\\\?\\')) {
|
|
strippedPath = strippedPath.slice('\\\\?\\'.length);
|
|
}
|
|
|
|
return path.win32.normalize(strippedPath);
|
|
}
|
|
|
|
function normalizeProjectPathForProvider(provider: string, projectPath: string): string {
|
|
if (provider !== 'codex') {
|
|
return projectPath;
|
|
}
|
|
|
|
return normalizeCodexProjectPath(projectPath);
|
|
}
|
|
|
|
export const sessionsDb = {
|
|
createSession(
|
|
sessionId: string,
|
|
provider: string,
|
|
projectPath: string,
|
|
customName?: string,
|
|
createdAt?: string,
|
|
updatedAt?: string,
|
|
jsonlPath?: string | null
|
|
): void {
|
|
const db = getConnection();
|
|
const createdAtValue = normalizeTimestamp(createdAt);
|
|
const updatedAtValue = normalizeTimestamp(updatedAt);
|
|
const normalizedProjectPath = normalizeProjectPathForProvider(provider, projectPath);
|
|
|
|
// First, ensure the project path is recorded in the projects table,
|
|
// since it's a foreign key in the sessions table.
|
|
projectsDb.createProjectPath(normalizedProjectPath);
|
|
|
|
db.prepare(
|
|
`INSERT INTO sessions (session_id, provider, custom_name, project_path, jsonl_path, created_at, updated_at)
|
|
VALUES (?, ?, ?, ?, ?, COALESCE(?, CURRENT_TIMESTAMP), COALESCE(?, CURRENT_TIMESTAMP))
|
|
ON CONFLICT(session_id, provider) DO UPDATE SET
|
|
updated_at = excluded.updated_at,
|
|
project_path = excluded.project_path,
|
|
jsonl_path = excluded.jsonl_path,
|
|
custom_name = COALESCE(excluded.custom_name, sessions.custom_name)`
|
|
).run(
|
|
sessionId,
|
|
provider,
|
|
customName ?? null,
|
|
normalizedProjectPath,
|
|
jsonlPath ?? null,
|
|
createdAtValue,
|
|
updatedAtValue
|
|
);
|
|
},
|
|
|
|
updateSessionCustomName(sessionId: string, customName: string): void {
|
|
const db = getConnection();
|
|
db.prepare(
|
|
`UPDATE sessions
|
|
SET custom_name = ?
|
|
WHERE session_id = ?`
|
|
).run(customName, sessionId);
|
|
},
|
|
|
|
createSessionName(sessionId: string, provider: string, customName: string): void {
|
|
const db = getConnection();
|
|
db.prepare(
|
|
`UPDATE sessions
|
|
SET custom_name = ?
|
|
WHERE session_id = ? AND provider = ?`
|
|
).run(customName, sessionId, provider);
|
|
},
|
|
|
|
getSessionById(sessionId: string): SessionMetadataLookupRow | null {
|
|
const db = getConnection();
|
|
const row = db
|
|
.prepare(
|
|
`SELECT session_id, provider, project_path, jsonl_path, custom_name, created_at, updated_at
|
|
FROM sessions
|
|
WHERE session_id = ?
|
|
ORDER BY updated_at DESC
|
|
LIMIT 1`
|
|
)
|
|
.get(sessionId) as SessionMetadataLookupRow | undefined;
|
|
|
|
return row ?? null;
|
|
},
|
|
|
|
getAllSessions(): SessionRow[] {
|
|
const db = getConnection();
|
|
return db
|
|
.prepare(
|
|
`SELECT session_id, provider, project_path, jsonl_path, custom_name, created_at, updated_at
|
|
FROM sessions`
|
|
)
|
|
.all() as SessionRow[];
|
|
},
|
|
|
|
getSessionsByProjectPath(projectPath: string): SessionRow[] {
|
|
const db = getConnection();
|
|
return db
|
|
.prepare(
|
|
`SELECT session_id, provider, project_path, jsonl_path, custom_name, created_at, updated_at
|
|
FROM sessions
|
|
WHERE project_path = ?`
|
|
)
|
|
.all(projectPath) as SessionRow[];
|
|
},
|
|
|
|
getSessionName(sessionId: string, provider: string): string | null {
|
|
const db = getConnection();
|
|
const row = db
|
|
.prepare(
|
|
`SELECT custom_name
|
|
FROM sessions
|
|
WHERE session_id = ? AND provider = ?`
|
|
)
|
|
.get(sessionId, provider) as { custom_name: string | null } | undefined;
|
|
|
|
return row?.custom_name ?? null;
|
|
},
|
|
|
|
getSessionNames(sessionIds: string[], provider: string): Map<string, string> {
|
|
if (sessionIds.length === 0) return new Map();
|
|
|
|
const db = getConnection();
|
|
const placeholders = sessionIds.map(() => '?').join(',');
|
|
const rows = db
|
|
.prepare(
|
|
`SELECT session_id, custom_name
|
|
FROM sessions
|
|
WHERE session_id IN (${placeholders})
|
|
AND provider = ?
|
|
AND custom_name IS NOT NULL`
|
|
)
|
|
.all(...sessionIds, provider) as SessionNameLookupRow[];
|
|
|
|
return new Map(rows.map((row) => [row.session_id, row.custom_name]));
|
|
},
|
|
|
|
/**
|
|
* Legacy-compatibility method kept for parity with `server/database/db.js`.
|
|
*
|
|
* Renaming a session is a metadata-only change — it's not actual activity,
|
|
* so existing rows intentionally keep their `updated_at` untouched. This
|
|
* prevents the sidebar's "last activity" timestamp from jumping around when
|
|
* a user simply edits a session's label.
|
|
*
|
|
* When the row doesn't exist yet we still have to seed `created_at`/
|
|
* `updated_at`; we write ISO-8601 UTC (with the `Z` suffix) rather than
|
|
* rely on SQLite's `CURRENT_TIMESTAMP`, which stores a naive
|
|
* `"YYYY-MM-DD HH:MM:SS"` value that JavaScript's `new Date(...)` parses as
|
|
* local time and displays with the wrong offset.
|
|
*
|
|
* TODO: Remove after all legacy imports are migrated to the new repository API.
|
|
*/
|
|
setName(sessionId: string, provider: string, customName: string): void {
|
|
const db = getConnection();
|
|
const nowIso = new Date().toISOString();
|
|
db.prepare(
|
|
`INSERT INTO sessions (session_id, provider, custom_name, created_at, updated_at)
|
|
VALUES (?, ?, ?, ?, ?)
|
|
ON CONFLICT(session_id, provider) DO UPDATE SET
|
|
custom_name = excluded.custom_name`
|
|
).run(sessionId, provider, customName, nowIso, nowIso);
|
|
},
|
|
|
|
/**
|
|
* Legacy-compatibility method kept for parity with `server/database/db.js`.
|
|
* TODO: Remove after all legacy imports are migrated to the new repository API.
|
|
*/
|
|
getName(sessionId: string, provider: string): string | null {
|
|
return sessionsDb.getSessionName(sessionId, provider);
|
|
},
|
|
|
|
/**
|
|
* Legacy-compatibility method kept for parity with `server/database/db.js`.
|
|
* TODO: Remove after all legacy imports are migrated to the new repository API.
|
|
*/
|
|
getNames(sessionIds: string[], provider: string): Map<string, string> {
|
|
return sessionsDb.getSessionNames(sessionIds, provider);
|
|
},
|
|
|
|
/**
|
|
* Legacy-compatibility method kept for parity with `server/database/db.js`.
|
|
* TODO: Remove after all legacy imports are migrated to the new repository API.
|
|
*/
|
|
deleteName(sessionId: string, provider: string): boolean {
|
|
const db = getConnection();
|
|
return (
|
|
db
|
|
.prepare(
|
|
`DELETE FROM sessions
|
|
WHERE session_id = ? AND provider = ?`
|
|
)
|
|
.run(sessionId, provider).changes > 0
|
|
);
|
|
},
|
|
|
|
deleteSession(sessionId: string): void {
|
|
const db = getConnection();
|
|
db.prepare('DELETE FROM sessions WHERE session_id = ?').run(sessionId);
|
|
},
|
|
};
|
|
|
|
/**
|
|
* Legacy-compatibility helper kept for parity with `server/database/db.js`.
|
|
* TODO: Remove after all legacy imports are migrated to the new repository API.
|
|
*/
|
|
export function applyCustomSessionNames(
|
|
sessions: LegacySessionSummary[] | null | undefined,
|
|
provider: string
|
|
): void {
|
|
if (!sessions?.length) return;
|
|
|
|
try {
|
|
const sessionIds = sessions.map((session) => session.id);
|
|
const customNames = sessionsDb.getNames(sessionIds, provider);
|
|
|
|
for (const session of sessions) {
|
|
const customName = customNames.get(session.id);
|
|
if (customName) {
|
|
session.summary = customName;
|
|
}
|
|
}
|
|
} catch (error) {
|
|
const message = error instanceof Error ? error.message : String(error);
|
|
console.warn(`[DB] Failed to apply custom session names for ${provider}:`, message);
|
|
}
|
|
}
|