Adds a singleton, ephemeral 'settings' pane kind to the workspace. Opened via a new bottom-pinned button in ProjectSidebar (emits an open_settings_pane event when a session is mounted; navigates to /settings otherwise). Pane has three sections — Session, Project, Theme — and a maximize toggle that hides sibling pane columns via display:none on desktop only. Settings panes don't count toward MAX_PANES and are filtered out of the localStorage persistence layer so reload always restores a clean workspace. Schema (additive): - projects.default_system_prompt TEXT NOT NULL DEFAULT '' - projects.default_web_search_enabled BOOLEAN NOT NULL DEFAULT false - sessions.web_search_enabled BOOLEAN (nullable; null = inherit) Inference resolves user_prompt = session.system_prompt.trim() || project.default_system_prompt.trim() — empty/whitespace at either layer means "no override". Keeps the columns NOT NULL and matches the existing inherit semantics. Server routes: - GET /api/projects/:id (new; settings pane refetches on project_updated) - PATCH /api/projects/:id accepts default_system_prompt, default_web_search_enabled - PATCH /api/sessions/:id accepts web_search_enabled (tri-state) - POST /api/projects/:id/sessions/archive-all + GET /api/projects/:id/sessions/open-count - POST /api/sessions/:id/chats/archive-all + GET /api/sessions/:id/chats/open-count - PATCH /api/sessions/:id now broadcasts session_updated on every successful PATCH (was rename-only). Lets SettingsPane open in another tab pick up edits without a refetch. Bulk-archive publishes one session_archived / chat_archived frame per affected id so useSidebar's existing reducer cases handle them incrementally — no new frame type, no payload widening. ModelPicker refactored: shared ModelList inside a responsive shell. Desktop = labeled trigger + DropdownMenu, mobile = icon-only Cpu button + BottomSheet. Header in Session.tsx drops the pill wrap on mobile since the new trigger is the visual. ChatInput gains an icon-only '+' DropdownMenu next to AgentPicker when sessionId + webSearchEnabled props are provided. One item for now — Web search — with a checkmark reflecting the stored value (true), not the effective one. Click PATCHes the override; to restore inherit-from-project the user opens SettingsPane. ThemePicker lifted out of pages/Settings.tsx into a reusable component. The standalone /settings route is now a thin wrapper that mounts <ThemePicker /> with a Back button on top (navigate(-1) with fallback to '/'); the SettingsPane Theme tab renders the same picker bare. Project section delete-flow removed (button + confirm dialog + handler). Replaced with "Archive all sessions" using the same two-step count → confirm → fire pattern as "Archive all chats" in the Session section. api.projects.remove() stays in the client because useProjects.ts still uses it. Hand-rolled Switch primitive in SettingsPane (no shadcn switch in the project; spec said no new deps). Section nav is plain buttons (no shadcn Tabs). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
489 lines
16 KiB
TypeScript
489 lines
16 KiB
TypeScript
import type { FastifyInstance } from 'fastify';
|
|
import { z } from 'zod';
|
|
import { realpath, stat, readdir, access } from 'node:fs/promises';
|
|
import { basename, resolve, sep } from 'node:path';
|
|
import type { Sql } from '../db.js';
|
|
import type { Config } from '../config.js';
|
|
import type { Broker } from '../services/broker.js';
|
|
import type { Project, AvailableProject } from '../types/api.js';
|
|
import { resolveProjectRoot, PathScopeError } from '../services/path_guard.js';
|
|
import { listDir, viewFile } from '../services/file_ops.js';
|
|
import { getProjectFiles } from '../services/file_index.js';
|
|
import { getGitMeta } from '../services/git_meta.js';
|
|
import {
|
|
bootstrapProject,
|
|
BootstrapNameError,
|
|
BootstrapCollisionError,
|
|
BootstrapPathError,
|
|
} from '../services/project_bootstrap.js';
|
|
|
|
const AddProjectBody = z.object({
|
|
path: z.string().min(1),
|
|
name: z.string().min(1).optional(),
|
|
});
|
|
|
|
// v1.9: PATCH accepts the new per-project defaults. All fields optional so
|
|
// the existing rename-only callers keep working. Empty string on
|
|
// default_system_prompt is the "no override" sentinel — same convention as
|
|
// sessions.system_prompt.
|
|
const PatchProjectBody = z.object({
|
|
name: z.string().min(1).max(200).optional(),
|
|
default_system_prompt: z.string().max(8000).optional(),
|
|
default_web_search_enabled: z.boolean().optional(),
|
|
});
|
|
|
|
const CreateProjectBody = z.object({
|
|
name: z.string().min(1).max(64),
|
|
commit_message: z.string().min(1).max(200).optional(),
|
|
visibility: z.enum(['private', 'public']).optional(),
|
|
create_gitea_remote: z.boolean().optional(),
|
|
});
|
|
|
|
async function isDir(path: string): Promise<boolean> {
|
|
try {
|
|
const s = await stat(path);
|
|
return s.isDirectory();
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
export async function resolveProjectPath(
|
|
raw: string,
|
|
whitelist: string
|
|
): Promise<{ real: string; name: string } | { error: string }> {
|
|
if (!raw.startsWith('/')) return { error: 'path must be absolute' };
|
|
let real: string;
|
|
try {
|
|
real = await realpath(raw);
|
|
} catch {
|
|
return { error: 'path does not exist' };
|
|
}
|
|
const whitelistReal = await realpath(whitelist);
|
|
if (!real.startsWith(whitelistReal + sep)) {
|
|
return { error: `path must be under ${whitelist}` };
|
|
}
|
|
if (!(await isDir(real))) return { error: 'path is not a directory' };
|
|
return { real, name: basename(real) };
|
|
}
|
|
|
|
export function registerProjectRoutes(
|
|
app: FastifyInstance,
|
|
sql: Sql,
|
|
config: Config,
|
|
broker: Broker
|
|
): void {
|
|
app.get<{ Querystring: { status?: string } }>('/api/projects', async (req) => {
|
|
const status = req.query.status === 'archived' ? 'archived' : 'open';
|
|
const rows = await sql<Project[]>`
|
|
SELECT id, name, path, added_at, last_session_id, status, gitea_remote,
|
|
default_system_prompt, default_web_search_enabled
|
|
FROM projects
|
|
WHERE status = ${status}
|
|
ORDER BY added_at DESC
|
|
`;
|
|
return rows;
|
|
});
|
|
|
|
app.post('/api/projects/create', async (req, reply) => {
|
|
const parsed = CreateProjectBody.safeParse(req.body);
|
|
if (!parsed.success) {
|
|
reply.code(400);
|
|
return { error: 'invalid body', details: parsed.error.flatten() };
|
|
}
|
|
const visibility = parsed.data.visibility ?? 'private';
|
|
const createRemote = parsed.data.create_gitea_remote ?? true;
|
|
const commitMessage = parsed.data.commit_message ?? 'Initial commit';
|
|
|
|
let bootstrap;
|
|
try {
|
|
bootstrap = await bootstrapProject(config, app.log, {
|
|
name: parsed.data.name,
|
|
commitMessage,
|
|
visibility,
|
|
createGiteaRemote: createRemote,
|
|
});
|
|
} catch (err) {
|
|
if (err instanceof BootstrapNameError) {
|
|
reply.code(400);
|
|
return { error: `invalid project name: ${err.message}` };
|
|
}
|
|
if (err instanceof BootstrapCollisionError) {
|
|
reply.code(409);
|
|
return { error: err.message };
|
|
}
|
|
if (err instanceof BootstrapPathError) {
|
|
reply.code(400);
|
|
return { error: err.message };
|
|
}
|
|
app.log.error({ err }, 'bootstrap failed');
|
|
reply.code(500);
|
|
return { error: err instanceof Error ? err.message : 'bootstrap failed' };
|
|
}
|
|
|
|
// Insert into projects table only after bootstrap succeeded.
|
|
try {
|
|
const [row] = await sql<Project[]>`
|
|
INSERT INTO projects (name, path, gitea_remote)
|
|
VALUES (${parsed.data.name}, ${bootstrap.folder_real_path}, ${bootstrap.gitea_remote_url})
|
|
RETURNING id, name, path, added_at, last_session_id, status, gitea_remote,
|
|
default_system_prompt, default_web_search_enabled
|
|
`;
|
|
broker.publishUser('default', { type: 'project_created', project: row as unknown as Project });
|
|
reply.code(201);
|
|
return {
|
|
project: row,
|
|
bootstrap: {
|
|
folder_created: bootstrap.folder_created,
|
|
git_initialized: bootstrap.git_initialized,
|
|
first_commit: bootstrap.first_commit,
|
|
gitea_remote_created: bootstrap.gitea_remote_created,
|
|
gitea_pushed: bootstrap.gitea_pushed,
|
|
warnings: bootstrap.warnings,
|
|
},
|
|
};
|
|
} catch (err) {
|
|
app.log.error({ err, folder: bootstrap.folder_real_path }, 'project insert failed after bootstrap');
|
|
reply.code(500);
|
|
return {
|
|
error: 'project created on disk but DB insert failed',
|
|
folder: bootstrap.folder_real_path,
|
|
};
|
|
}
|
|
});
|
|
|
|
app.post('/api/projects', async (req, reply) => {
|
|
const parsed = AddProjectBody.safeParse(req.body);
|
|
if (!parsed.success) {
|
|
reply.code(400);
|
|
return { error: 'invalid body', details: parsed.error.flatten() };
|
|
}
|
|
const resolved = await resolveProjectPath(parsed.data.path, config.PROJECT_ROOT_WHITELIST);
|
|
if ('error' in resolved) {
|
|
reply.code(400);
|
|
return { error: resolved.error };
|
|
}
|
|
const name = parsed.data.name?.trim() || resolved.name;
|
|
|
|
// Pre-check the current row (if any) so we can distinguish three cases:
|
|
// - no row → INSERT fresh, 201, project_created
|
|
// - row archived → ON CONFLICT UPDATE flips to 'open', 200, project_unarchived
|
|
// - row already open → 409 (true duplicate)
|
|
const existing = await sql<{ status: string }[]>`
|
|
SELECT status FROM projects WHERE path = ${resolved.real}
|
|
`;
|
|
if (existing.length > 0 && existing[0]!.status === 'open') {
|
|
reply.code(409);
|
|
return { error: 'project already exists' };
|
|
}
|
|
|
|
const [row] = await sql<Project[]>`
|
|
INSERT INTO projects (name, path)
|
|
VALUES (${name}, ${resolved.real})
|
|
ON CONFLICT (path) DO UPDATE SET status = 'open'
|
|
RETURNING id, name, path, added_at, last_session_id, status, gitea_remote,
|
|
default_system_prompt, default_web_search_enabled
|
|
`;
|
|
|
|
if (existing.length === 0) {
|
|
broker.publishUser('default', { type: 'project_created', project: row as unknown as Project });
|
|
reply.code(201);
|
|
} else {
|
|
// existing.status was 'archived' — row has been restored.
|
|
broker.publishUser('default', { type: 'project_unarchived', project: row as unknown as Project });
|
|
reply.code(200);
|
|
}
|
|
return row;
|
|
});
|
|
|
|
// v1.9: single-project fetch so the settings pane can refetch on
|
|
// project_updated without pulling the whole project list.
|
|
app.get<{ Params: { id: string } }>('/api/projects/:id', async (req, reply) => {
|
|
const rows = await sql<Project[]>`
|
|
SELECT id, name, path, added_at, last_session_id, status, gitea_remote,
|
|
default_system_prompt, default_web_search_enabled
|
|
FROM projects WHERE id = ${req.params.id}
|
|
`;
|
|
if (rows.length === 0) {
|
|
reply.code(404);
|
|
return { error: 'not found' };
|
|
}
|
|
return rows[0];
|
|
});
|
|
|
|
app.patch<{ Params: { id: string } }>('/api/projects/:id', async (req, reply) => {
|
|
const parsed = PatchProjectBody.safeParse(req.body);
|
|
if (!parsed.success) {
|
|
reply.code(400);
|
|
return { error: 'invalid body', details: parsed.error.flatten() };
|
|
}
|
|
const { name, default_system_prompt, default_web_search_enabled } = parsed.data;
|
|
// v1.9: every field optional. COALESCE on the bind keeps the prior value
|
|
// when the caller omits it. Boolean has its own branch since COALESCE
|
|
// can't disambiguate "omitted" from "explicitly false" via a single
|
|
// nullable parameter.
|
|
const dwsProvided = default_web_search_enabled !== undefined;
|
|
const rows = await sql<Project[]>`
|
|
UPDATE projects
|
|
SET
|
|
name = COALESCE(${name ?? null}, name),
|
|
default_system_prompt = COALESCE(${default_system_prompt ?? null}, default_system_prompt),
|
|
default_web_search_enabled = CASE WHEN ${dwsProvided}
|
|
THEN ${default_web_search_enabled ?? false}
|
|
ELSE default_web_search_enabled END
|
|
WHERE id = ${req.params.id}
|
|
RETURNING id, name, path, added_at, last_session_id, status, gitea_remote,
|
|
default_system_prompt, default_web_search_enabled
|
|
`;
|
|
if (rows.length === 0) {
|
|
reply.code(404);
|
|
return { error: 'not found' };
|
|
}
|
|
const project = rows[0]!;
|
|
// v1.9: the project_updated frame still only carries id + name. Clients
|
|
// that need the new fields refetch via api.projects.list() — keeps the
|
|
// frame payload lean, per the locked recon decision (d).
|
|
broker.publishUser('default', {
|
|
type: 'project_updated',
|
|
project_id: project.id,
|
|
name: project.name,
|
|
});
|
|
return project;
|
|
});
|
|
|
|
app.post<{ Params: { id: string } }>('/api/projects/:id/archive', async (req, reply) => {
|
|
const result = await sql`
|
|
UPDATE projects SET status = 'archived'
|
|
WHERE id = ${req.params.id} AND status = 'open'
|
|
`;
|
|
if (result.count === 0) {
|
|
reply.code(404);
|
|
return { error: 'not found or already archived' };
|
|
}
|
|
broker.publishUser('default', { type: 'project_archived', project_id: req.params.id });
|
|
reply.code(204);
|
|
return null;
|
|
});
|
|
|
|
app.post<{ Params: { id: string } }>('/api/projects/:id/unarchive', async (req, reply) => {
|
|
const rows = await sql<Project[]>`
|
|
UPDATE projects SET status = 'open'
|
|
WHERE id = ${req.params.id} AND status = 'archived'
|
|
RETURNING id, name, path, added_at, last_session_id, status, gitea_remote,
|
|
default_system_prompt, default_web_search_enabled
|
|
`;
|
|
if (rows.length === 0) {
|
|
reply.code(404);
|
|
return { error: 'not found or not archived' };
|
|
}
|
|
const project = rows[0]!;
|
|
broker.publishUser('default', { type: 'project_unarchived', project });
|
|
return project;
|
|
});
|
|
|
|
app.delete<{ Params: { id: string } }>('/api/projects/:id', async (req, reply) => {
|
|
const id = req.params.id;
|
|
const result = await sql`DELETE FROM projects WHERE id = ${id}`;
|
|
if (result.count === 0) {
|
|
reply.code(404);
|
|
return { error: 'not found' };
|
|
}
|
|
broker.publishUser('default', { type: 'project_deleted', project_id: id });
|
|
reply.code(204);
|
|
return null;
|
|
});
|
|
|
|
app.get('/api/projects/available', async () => {
|
|
const whitelist = await realpath(config.PROJECT_ROOT_WHITELIST);
|
|
let entries: string[];
|
|
try {
|
|
entries = await readdir(whitelist);
|
|
} catch {
|
|
return [] as AvailableProject[];
|
|
}
|
|
|
|
// Only exclude paths registered with status='open'. Archived projects'
|
|
// folders should reappear as available so re-add via the picker restores
|
|
// the existing row (see POST /api/projects ON CONFLICT below).
|
|
const existing = await sql<{ path: string }[]>`
|
|
SELECT path FROM projects WHERE status = 'open'
|
|
`;
|
|
const existingSet = new Set(existing.map((r) => r.path));
|
|
|
|
const out: AvailableProject[] = [];
|
|
for (const entry of entries) {
|
|
const full = resolve(whitelist, entry);
|
|
let real: string;
|
|
try {
|
|
real = await realpath(full);
|
|
} catch {
|
|
continue;
|
|
}
|
|
if (real !== whitelist && !real.startsWith(whitelist + sep)) continue;
|
|
if (existingSet.has(real)) continue;
|
|
if (!(await isDir(real))) continue;
|
|
try {
|
|
await access(resolve(real, '.git'));
|
|
} catch {
|
|
continue;
|
|
}
|
|
out.push({ path: real, name: basename(real) });
|
|
}
|
|
out.sort((a, b) => a.name.localeCompare(b.name));
|
|
return out;
|
|
});
|
|
|
|
// GET /api/projects/:id/list_dir?path=<relpath>
|
|
app.get<{ Params: { id: string }; Querystring: { path?: string } }>(
|
|
'/api/projects/:id/list_dir',
|
|
async (req, reply) => {
|
|
const { id } = req.params;
|
|
const relPath = req.query.path ?? '.';
|
|
|
|
const rows = await sql<Project[]>`
|
|
SELECT id, name, path, added_at, last_session_id, status, gitea_remote
|
|
FROM projects WHERE id = ${id}
|
|
`;
|
|
if (rows.length === 0) {
|
|
reply.code(404);
|
|
return { error: 'not found' };
|
|
}
|
|
const project = rows[0]!;
|
|
let projectRoot: string;
|
|
try {
|
|
projectRoot = await resolveProjectRoot(project.path);
|
|
} catch (err) {
|
|
if (err instanceof PathScopeError) {
|
|
reply.code(404);
|
|
return { error: err.message };
|
|
}
|
|
throw err;
|
|
}
|
|
|
|
try {
|
|
const result = await listDir(projectRoot, relPath);
|
|
return result;
|
|
} catch (err) {
|
|
if (err instanceof PathScopeError) {
|
|
reply.code(400);
|
|
return { error: err.message };
|
|
}
|
|
throw err;
|
|
}
|
|
}
|
|
);
|
|
|
|
// GET /api/projects/:id/view_file?path=<relpath>
|
|
app.get<{ Params: { id: string }; Querystring: { path?: string } }>(
|
|
'/api/projects/:id/view_file',
|
|
async (req, reply) => {
|
|
const { id } = req.params;
|
|
const relPath = req.query.path;
|
|
|
|
if (!relPath) {
|
|
reply.code(400);
|
|
return { error: 'path is required' };
|
|
}
|
|
|
|
const rows = await sql<Project[]>`
|
|
SELECT id, name, path, added_at, last_session_id, status, gitea_remote
|
|
FROM projects WHERE id = ${id}
|
|
`;
|
|
if (rows.length === 0) {
|
|
reply.code(404);
|
|
return { error: 'not found' };
|
|
}
|
|
const project = rows[0]!;
|
|
let projectRoot: string;
|
|
try {
|
|
projectRoot = await resolveProjectRoot(project.path);
|
|
} catch (err) {
|
|
if (err instanceof PathScopeError) {
|
|
reply.code(404);
|
|
return { error: err.message };
|
|
}
|
|
throw err;
|
|
}
|
|
|
|
try {
|
|
const result = await viewFile(projectRoot, relPath);
|
|
return result;
|
|
} catch (err) {
|
|
if (err instanceof PathScopeError) {
|
|
reply.code(400);
|
|
return { error: err.message };
|
|
}
|
|
// File not found (pathGuard throws PathScopeError for non-existent paths)
|
|
if (err instanceof Error && err.message.includes('does not exist')) {
|
|
reply.code(404);
|
|
return { error: err.message };
|
|
}
|
|
throw err;
|
|
}
|
|
}
|
|
);
|
|
|
|
// GET /api/projects/:id/git
|
|
// v1.8 mobile-tabs: feeds the header branch indicator and is the same
|
|
// resolver the model's git_status tool uses. Returns 200 with branch=null
|
|
// for non-git directories (not 404) so the UI can degrade gracefully.
|
|
app.get<{ Params: { id: string } }>(
|
|
'/api/projects/:id/git',
|
|
async (req, reply) => {
|
|
const { id } = req.params;
|
|
const rows = await sql<Project[]>`
|
|
SELECT id, name, path, added_at, last_session_id, status, gitea_remote
|
|
FROM projects WHERE id = ${id}
|
|
`;
|
|
if (rows.length === 0) {
|
|
reply.code(404);
|
|
return { error: 'not found' };
|
|
}
|
|
const project = rows[0]!;
|
|
let projectRoot: string;
|
|
try {
|
|
projectRoot = await resolveProjectRoot(project.path);
|
|
} catch (err) {
|
|
if (err instanceof PathScopeError) {
|
|
reply.code(404);
|
|
return { error: err.message };
|
|
}
|
|
throw err;
|
|
}
|
|
const meta = await getGitMeta(projectRoot);
|
|
return meta ?? { branch: null, is_dirty: false, ahead: 0, behind: 0 };
|
|
}
|
|
);
|
|
|
|
// GET /api/projects/:id/files
|
|
app.get<{ Params: { id: string } }>(
|
|
'/api/projects/:id/files',
|
|
async (req, reply) => {
|
|
const { id } = req.params;
|
|
|
|
const rows = await sql<Project[]>`
|
|
SELECT id, name, path, added_at, last_session_id, status, gitea_remote
|
|
FROM projects WHERE id = ${id}
|
|
`;
|
|
if (rows.length === 0) {
|
|
reply.code(404);
|
|
return { error: 'not found' };
|
|
}
|
|
const project = rows[0]!;
|
|
let projectRoot: string;
|
|
try {
|
|
projectRoot = await resolveProjectRoot(project.path);
|
|
} catch (err) {
|
|
if (err instanceof PathScopeError) {
|
|
reply.code(404);
|
|
return { error: err.message };
|
|
}
|
|
throw err;
|
|
}
|
|
|
|
const files = await getProjectFiles(id, projectRoot);
|
|
return { files };
|
|
}
|
|
);
|
|
}
|