feat(KB-504): add migration and first-run experience for multi-project support
- Add MigrationOrchestrator with filesystem scanning and auto-registration - Add FirstRunExperience with setup wizard state management - CLI integration with automatic migration hook on first run - Backward-compatible single-project mode support - \"--project\" flag support for CLI multi-project targeting - KB_SKIP_MIGRATION environment variable for recovery - Graceful fallback when central database unavailable - New fn init command to initialize kb projects - Interactive first-run setup wizard API in dashboard
This commit is contained in:
@@ -46,7 +46,8 @@ const { runSettingsImport } = await import("./commands/settings-import.js");
|
||||
const { runGitStatus, runGitFetch, runGitPull, runGitPush } = await import("./commands/git.js");
|
||||
const { runBackupCreate, runBackupList, runBackupRestore, runBackupCleanup } = await import("./commands/backup.js");
|
||||
const { runMissionCreate, runMissionList, runMissionShow, runMissionDelete, runMissionActivateSlice } = await import("./commands/mission.js");
|
||||
const { runProjectList, runProjectAdd, runProjectRemove, runProjectShow, runProjectSetDefault, runProjectDetect } = await import("./commands/project.js");
|
||||
const { runProjectList, runProjectAdd, runProjectRemove, runProjectInfo } = await import("./commands/project.js");
|
||||
const { getResolvedProject } = await import("./project-resolver.js");
|
||||
|
||||
const HELP = `
|
||||
fn — AI-orchestrated task board
|
||||
@@ -154,48 +155,56 @@ async function main() {
|
||||
let projectName: string | undefined;
|
||||
const projectFlagIdx = args.indexOf("--project");
|
||||
const projectFlagShortIdx = args.indexOf("-P");
|
||||
const projectIdx = projectFlagIdx !== -1 ? projectFlagIdx : projectFlagShortIdx;
|
||||
if (projectIdx !== -1 && projectIdx + 1 < args.length) {
|
||||
projectName = args[projectIdx + 1];
|
||||
const resolvedProjectIdx = projectFlagIdx !== -1 ? projectFlagIdx : projectFlagShortIdx;
|
||||
if (resolvedProjectIdx !== -1 && resolvedProjectIdx + 1 < args.length) {
|
||||
projectName = args[resolvedProjectIdx + 1];
|
||||
// Remove --project and its value from args
|
||||
args.splice(projectIdx, 2);
|
||||
args.splice(resolvedProjectIdx, 2);
|
||||
}
|
||||
|
||||
// Extract command early (needed for migration check)
|
||||
const command = args[0];
|
||||
|
||||
// Migration check for first-run experience
|
||||
// Skip for init command and help flags
|
||||
if (command !== "init" && command !== "--help" && command !== "-h") {
|
||||
// ── First-Run Auto-Migration ─────────────────────────────────────────────
|
||||
// Check if this is a fresh installation or if projects need to be migrated
|
||||
// Skip migration check for 'project' commands to avoid circular issues
|
||||
if (command !== "project" && !process.env.KB_SKIP_MIGRATION) {
|
||||
try {
|
||||
const { FirstRunDetector, MigrationCoordinator } = await import("@fusion/core");
|
||||
const { CentralCore } = await import("@fusion/core");
|
||||
const { createMigrationOrchestrator, createFirstRunExperience, CentralCore } = await import("@fusion/core");
|
||||
|
||||
const detector = new FirstRunDetector();
|
||||
const state = await detector.detectFirstRunState();
|
||||
|
||||
if (state === "needs-migration") {
|
||||
const cwd = process.cwd();
|
||||
const central = new CentralCore();
|
||||
await central.init();
|
||||
|
||||
try {
|
||||
const coordinator = new MigrationCoordinator(central);
|
||||
const result = await coordinator.registerSingleProject(cwd);
|
||||
const centralCore = new CentralCore();
|
||||
await centralCore.init();
|
||||
|
||||
const migration = createMigrationOrchestrator(centralCore);
|
||||
|
||||
if (await migration.needsMigration()) {
|
||||
const firstRun = createFirstRunExperience(centralCore);
|
||||
const state = await firstRun.getSetupState();
|
||||
|
||||
if (state.isFirstRun && state.hasDetectedProjects) {
|
||||
console.log("[kb] First run detected. Auto-registering projects...");
|
||||
const result = await migration.runMigration({
|
||||
startPath: process.cwd(),
|
||||
autoRegister: true
|
||||
});
|
||||
|
||||
if (result.success && result.projectsRegistered.length > 0) {
|
||||
const project = await central.getProject(result.projectsRegistered[0]);
|
||||
if (project) {
|
||||
console.log(`✓ Auto-registered project: ${project.name}`);
|
||||
if (result.projectsRegistered.length > 0) {
|
||||
console.log(`[kb] Auto-registered ${result.projectsRegistered.length} project(s):`);
|
||||
for (const p of result.projectsRegistered) {
|
||||
console.log(` - ${p.name}: ${p.path}`);
|
||||
}
|
||||
} else if (result.errors.length > 0) {
|
||||
console.warn(`Migration warning: ${result.errors[0]}`);
|
||||
}
|
||||
} finally {
|
||||
await central.close();
|
||||
|
||||
if (result.projectsSkipped.length > 0) {
|
||||
console.log(`[kb] Skipped ${result.projectsSkipped.length} project(s) (already registered or invalid)`);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Silently ignore migration errors - user can manually run fn init
|
||||
|
||||
await centralCore.close();
|
||||
} catch (err) {
|
||||
// Migration is best-effort: log warning but don't block command execution
|
||||
console.warn("[kb] Warning: Migration check failed:", (err as Error).message);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -295,17 +304,17 @@ async function main() {
|
||||
}
|
||||
case "show": {
|
||||
const name = args[2];
|
||||
await runProjectShow(name);
|
||||
await runProjectInfo(name, { interactive: false });
|
||||
break;
|
||||
}
|
||||
case "set-default":
|
||||
case "default": {
|
||||
const name = args[2];
|
||||
await runProjectSetDefault(name);
|
||||
await runProjectInfo(name, { setAsDefault: true, interactive: false });
|
||||
break;
|
||||
}
|
||||
case "detect":
|
||||
await runProjectDetect();
|
||||
await runProjectInfo(undefined, { detect: true, interactive: false });
|
||||
break;
|
||||
default:
|
||||
console.error(`Unknown subcommand: project ${subcommand || ""}`);
|
||||
|
||||
@@ -123,26 +123,26 @@ export type {
|
||||
ProjectStatus,
|
||||
ProjectHealth,
|
||||
CentralActivityLogEntry,
|
||||
GlobalConcurrencyState
|
||||
} from "./types.js";
|
||||
|
||||
// ── Migration and First-Run Experience ────────────────────────────────
|
||||
|
||||
export {
|
||||
FirstRunDetector,
|
||||
MigrationCoordinator,
|
||||
BackwardCompat,
|
||||
ProjectRequiredError,
|
||||
} from "./migration.js";
|
||||
export type {
|
||||
FirstRunState,
|
||||
GlobalConcurrencyState,
|
||||
DetectedProject,
|
||||
MigrationOptions,
|
||||
MigrationResult,
|
||||
ProjectSetupInput,
|
||||
ResolvedContext,
|
||||
} from "./migration.js";
|
||||
SetupState,
|
||||
SetupCompletionResult,
|
||||
} from "./types.js";
|
||||
|
||||
// ── Migration & First-Run (Multi-Project Support) ───────────────────────────
|
||||
|
||||
export {
|
||||
needsCentralMigration,
|
||||
detectExistingProjects,
|
||||
autoMigrateToCentral,
|
||||
} from "./db-migrate.js";
|
||||
MigrationOrchestrator,
|
||||
createMigrationOrchestrator,
|
||||
MAX_AUTO_REGISTER_PROJECTS,
|
||||
DEFAULT_MAX_DEPTH,
|
||||
EXCLUDED_DIRS,
|
||||
} from "./migration-orchestrator.js";
|
||||
|
||||
export {
|
||||
FirstRunExperience,
|
||||
createFirstRunExperience,
|
||||
} from "./first-run.js";
|
||||
|
||||
@@ -178,12 +178,12 @@ export class TaskStore extends EventEmitter<TaskStoreEvents> {
|
||||
worktree, blockedBy, paused, baseBranch, baseCommitSha, modelPresetId, modelProvider,
|
||||
modelId, validatorModelProvider, validatorModelId, mergeRetries, error,
|
||||
summary, thinkingLevel, createdAt, updatedAt, columnMovedAt,
|
||||
dependencies, steps, log, attachments,
|
||||
dependencies, steps, log, attachments, steeringComments,
|
||||
comments, workflowStepResults, prInfo, issueInfo, mergeDetails,
|
||||
breakIntoSubtasks, enabledWorkflowSteps, modifiedFiles, sliceId
|
||||
) VALUES (
|
||||
?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
|
||||
?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?
|
||||
?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?
|
||||
)
|
||||
`).run(
|
||||
task.id,
|
||||
@@ -215,7 +215,7 @@ export class TaskStore extends EventEmitter<TaskStoreEvents> {
|
||||
toJson(task.steps || []),
|
||||
toJson(task.log || []),
|
||||
toJson(task.attachments || []),
|
||||
"[]", // steeringComments column - no longer used, write empty array
|
||||
toJson(task.steeringComments || []),
|
||||
toJson(task.comments || []),
|
||||
toJson(task.workflowStepResults || []),
|
||||
toJsonNullable(task.prInfo),
|
||||
@@ -2707,4 +2707,97 @@ ${notificationsSection}`;
|
||||
}
|
||||
return this.missionStore;
|
||||
}
|
||||
|
||||
// ── Backward Compatibility (Multi-Project Support) ────────────────────────
|
||||
|
||||
/**
|
||||
* Get or create a TaskStore for a project, supporting backward-compatible
|
||||
* single-project mode and multi-project resolution.
|
||||
*
|
||||
* Resolution logic:
|
||||
* - If `projectId` provided: look up in central registry, create store for that path
|
||||
* - If no `projectId` and single project registered: use that project
|
||||
* - If no `projectId` and multiple projects: throw requiring explicit selection
|
||||
* - If no central DB available: fall back to legacy behavior (current directory)
|
||||
*
|
||||
* @param projectId — Optional project ID to resolve
|
||||
* @param centralCore — Optional CentralCore instance (creates new if not provided)
|
||||
* @returns TaskStore initialized for the resolved project
|
||||
* @throws Error if project resolution fails or multiple projects require explicit selection
|
||||
*/
|
||||
static async getOrCreateForProject(
|
||||
projectId?: string,
|
||||
centralCore?: import("./central-core.js").CentralCore
|
||||
): Promise<TaskStore> {
|
||||
// If no centralCore provided, try to create one
|
||||
let core = centralCore;
|
||||
let shouldCleanupCore = false;
|
||||
|
||||
if (!core) {
|
||||
try {
|
||||
const { CentralCore } = await import("./central-core.js");
|
||||
core = new CentralCore();
|
||||
await core.init();
|
||||
shouldCleanupCore = true;
|
||||
} catch {
|
||||
// Central core not available - fall back to legacy mode
|
||||
}
|
||||
}
|
||||
|
||||
// Legacy mode: no central core available
|
||||
if (!core) {
|
||||
const store = new TaskStore(process.cwd());
|
||||
await store.init();
|
||||
return store;
|
||||
}
|
||||
|
||||
try {
|
||||
// If projectId provided, look it up directly
|
||||
if (projectId) {
|
||||
const project = await core.getProject(projectId);
|
||||
if (!project) {
|
||||
// Try to find by name
|
||||
const allProjects = await core.listProjects();
|
||||
const byName = allProjects.find(p => p.name === projectId);
|
||||
if (!byName) {
|
||||
throw new Error(`Project "${projectId}" not found`);
|
||||
}
|
||||
const store = new TaskStore(byName.path);
|
||||
await store.init();
|
||||
return store;
|
||||
}
|
||||
const store = new TaskStore(project.path);
|
||||
await store.init();
|
||||
return store;
|
||||
}
|
||||
|
||||
// No projectId provided - check registered projects
|
||||
const projects = await core.listProjects();
|
||||
|
||||
if (projects.length === 0) {
|
||||
// No projects registered - fall back to legacy mode (current directory)
|
||||
const store = new TaskStore(process.cwd());
|
||||
await store.init();
|
||||
return store;
|
||||
}
|
||||
|
||||
if (projects.length === 1) {
|
||||
// Exactly one project - use it
|
||||
const store = new TaskStore(projects[0].path);
|
||||
await store.init();
|
||||
return store;
|
||||
}
|
||||
|
||||
// Multiple projects - require explicit selection
|
||||
const projectList = projects.map(p => ` - ${p.name}: ${p.path}`).join("\n");
|
||||
throw new Error(
|
||||
`Multiple projects registered. Use --project <name> to specify one.\n\nAvailable projects:\n${projectList}`
|
||||
);
|
||||
} finally {
|
||||
// Clean up the central core if we created it
|
||||
if (shouldCleanupCore && core) {
|
||||
await core.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -386,6 +386,8 @@ export interface Task {
|
||||
baseCommitSha?: string;
|
||||
attachments?: TaskAttachment[];
|
||||
comments?: TaskComment[];
|
||||
/** Steering comments injected during task execution for real-time guidance */
|
||||
steeringComments?: TaskComment[];
|
||||
/** PR information for tasks linked to GitHub pull requests */
|
||||
prInfo?: PrInfo;
|
||||
mergeDetails?: MergeDetails;
|
||||
@@ -531,7 +533,8 @@ export interface GlobalSettings {
|
||||
* and ntfyTopic, notifications include a Click URL that opens the dashboard
|
||||
* directly to the task. Example: "http://localhost:3000" or "https://fusion.example.com" */
|
||||
ntfyDashboardHost?: string;
|
||||
/** Whether the first-run setup wizard has been completed. */
|
||||
/** When true, indicates the first-run setup wizard has been completed.
|
||||
* Set by FirstRunExperience.completeSetup() after successful migration. */
|
||||
setupComplete?: boolean;
|
||||
}
|
||||
|
||||
@@ -1151,3 +1154,75 @@ export interface AgentUpdateInput {
|
||||
role?: AgentCapability;
|
||||
metadata?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
// ── Migration & First-Run Types (Multi-Project Support) ───────────────────
|
||||
|
||||
/** A project detected during filesystem scanning for auto-migration */
|
||||
export interface DetectedProject {
|
||||
/** Absolute path to the project directory */
|
||||
path: string;
|
||||
/** Project name (derived from directory basename) */
|
||||
name: string;
|
||||
/** Whether the project has a valid kb database */
|
||||
hasDb: boolean;
|
||||
}
|
||||
|
||||
/** Options for migration orchestration */
|
||||
export interface MigrationOptions {
|
||||
/** Starting path for project detection (default: process.cwd()) */
|
||||
startPath?: string;
|
||||
/** Whether to auto-register detected projects (default: false) */
|
||||
autoRegister?: boolean;
|
||||
/** Whether to perform a dry run (detect only, don't register) */
|
||||
dryRun?: boolean;
|
||||
/** Maximum depth to scan (default: 5) */
|
||||
maxDepth?: number;
|
||||
/** Progress callback for UI feedback */
|
||||
onProgress?: (current: number, total: number, projectPath: string) => void;
|
||||
}
|
||||
|
||||
/** Result of migration execution */
|
||||
export interface MigrationResult {
|
||||
/** Projects detected during scan */
|
||||
projectsDetected: DetectedProject[];
|
||||
/** Projects successfully registered */
|
||||
projectsRegistered: RegisteredProject[];
|
||||
/** Projects skipped (already registered or invalid) */
|
||||
projectsSkipped: Array<{ path: string; reason: string }>;
|
||||
/** Errors encountered during migration */
|
||||
errors: Array<{ path: string; error: string }>;
|
||||
}
|
||||
|
||||
/** Input for setting up a project during first-run wizard */
|
||||
export interface ProjectSetupInput {
|
||||
/** Absolute path to project directory */
|
||||
path: string;
|
||||
/** Display name for the project */
|
||||
name: string;
|
||||
/** Execution isolation mode (default: 'in-process') */
|
||||
isolationMode?: IsolationMode;
|
||||
}
|
||||
|
||||
/** Complete setup state for first-run experience */
|
||||
export interface SetupState {
|
||||
/** Whether this is a fresh installation (no projects registered) */
|
||||
isFirstRun: boolean;
|
||||
/** Whether any projects were detected during scan */
|
||||
hasDetectedProjects: boolean;
|
||||
/** Projects detected but not yet registered */
|
||||
detectedProjects: DetectedProject[];
|
||||
/** Projects already registered in the system */
|
||||
registeredProjects: RegisteredProject[];
|
||||
/** Recommended action based on current state */
|
||||
recommendedAction: 'auto-detect' | 'manual-setup' | 'create-new';
|
||||
}
|
||||
|
||||
/** Result of completing the setup wizard */
|
||||
export interface SetupCompletionResult {
|
||||
/** Whether setup completed successfully */
|
||||
success: boolean;
|
||||
/** Projects that were registered */
|
||||
projects: RegisteredProject[];
|
||||
/** Suggested next steps for the user */
|
||||
nextSteps: string[];
|
||||
}
|
||||
|
||||
@@ -1,259 +1,62 @@
|
||||
<<<<<<< HEAD
|
||||
import { useCallback } from "react";
|
||||
import { X } from "lucide-react";
|
||||
import { SetupWizard } from "./SetupWizard";
|
||||
import type { ProjectInfo, ProjectCreateInput } from "../api";
|
||||
|
||||
export interface SetupWizardModalProps {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
onComplete: (project: ProjectInfo) => void;
|
||||
onRegisterProject: (input: ProjectCreateInput) => Promise<ProjectInfo>;
|
||||
}
|
||||
|
||||
/**
|
||||
* SetupWizardModal - Modal wrapper for the SetupWizard component
|
||||
*
|
||||
* Provides a modal overlay for the setup wizard, suitable for:
|
||||
* - First-run experience when no projects exist
|
||||
* - "Add Project" button from ProjectOverview
|
||||
*/
|
||||
export function SetupWizardModal({
|
||||
isOpen,
|
||||
onClose,
|
||||
onComplete,
|
||||
onRegisterProject,
|
||||
}: SetupWizardModalProps) {
|
||||
const handleProjectCreated = useCallback((project: ProjectInfo) => {
|
||||
onComplete(project);
|
||||
}, [onComplete]);
|
||||
=======
|
||||
import { useState, useEffect, useCallback } from "react";
|
||||
import { X, Loader2, FolderPlus, Search, CheckCircle, ArrowRight, ArrowLeft } from "lucide-react";
|
||||
import { X, Loader2, FolderPlus, CheckCircle } from "lucide-react";
|
||||
import type { ProjectInfo, ProjectCreateInput } from "../api";
|
||||
import { fetchFirstRunStatus, detectProjects, registerProject } from "../api";
|
||||
import { ProjectDetectionResults, type SelectedProject } from "./ProjectDetectionResults";
|
||||
import { scanForProjects } from "../utils/projectDetection";
|
||||
import { registerProject } from "../api";
|
||||
|
||||
export interface SetupWizardModalProps {
|
||||
/** Called when a single project is registered */
|
||||
onProjectRegistered: (project: ProjectInfo) => void;
|
||||
/** Called when multiple projects are registered (bulk detection) */
|
||||
onProjectsRegistered?: (projects: ProjectInfo[]) => void;
|
||||
/** Called when wizard is closed (completed or cancelled) */
|
||||
onClose?: () => void;
|
||||
}
|
||||
|
||||
type WizardStep = "welcome" | "detecting" | "review" | "manual" | "complete";
|
||||
type WizardStep = "manual" | "complete";
|
||||
|
||||
interface WizardState {
|
||||
step: WizardStep;
|
||||
detectedProjects: SelectedProject[];
|
||||
isDetecting: boolean;
|
||||
detectError: string | null;
|
||||
manualPath: string;
|
||||
manualName: string;
|
||||
manualIsolationMode: "in-process" | "child-process";
|
||||
isRegistering: boolean;
|
||||
registeredCount: number;
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
const WIZARD_STATE_KEY = "kb-setup-wizard-state";
|
||||
|
||||
/**
|
||||
* Setup wizard for first-run project registration.
|
||||
*
|
||||
* Provides a multi-step wizard for new users to:
|
||||
* 1. Welcome - Introduction to multi-project mode
|
||||
* 2. Auto-detect - Scan filesystem for existing kb projects
|
||||
* 3. Review - Select which detected projects to register
|
||||
* 4. Manual - Add projects manually by path
|
||||
* 5. Complete - Summary and get started
|
||||
*
|
||||
* Features:
|
||||
* - Auto-opens when no projects exist (uses fetchFirstRunStatus)
|
||||
* - Persists state to localStorage for resume capability
|
||||
* - Bulk registration of selected detected projects
|
||||
* - Manual project registration as fallback
|
||||
* Provides a wizard for new users to add their first project manually.
|
||||
*
|
||||
* @example
|
||||
* ```tsx
|
||||
* <SetupWizardModal
|
||||
* onProjectRegistered={(project) => console.log(`Registered ${project.name}`)}
|
||||
* onProjectsRegistered={(projects) => console.log(`Registered ${projects.length} projects`)}
|
||||
* onClose={() => setShowWizard(false)}
|
||||
* />
|
||||
* ```
|
||||
*/
|
||||
export function SetupWizardModal({
|
||||
onProjectRegistered,
|
||||
onProjectsRegistered,
|
||||
onClose,
|
||||
}: SetupWizardModalProps) {
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const [isOpen, setIsOpen] = useState(true);
|
||||
const [state, setState] = useState<WizardState>({
|
||||
step: "welcome",
|
||||
detectedProjects: [],
|
||||
isDetecting: false,
|
||||
detectError: null,
|
||||
step: "manual",
|
||||
manualPath: "",
|
||||
manualName: "",
|
||||
manualIsolationMode: "in-process",
|
||||
isRegistering: false,
|
||||
registeredCount: 0,
|
||||
error: null,
|
||||
});
|
||||
|
||||
// Check first-run status on mount
|
||||
useEffect(() => {
|
||||
const checkFirstRun = async () => {
|
||||
try {
|
||||
const status = await fetchFirstRunStatus();
|
||||
|
||||
// Check for saved wizard state (resume capability)
|
||||
const savedState = localStorage.getItem(WIZARD_STATE_KEY);
|
||||
if (savedState) {
|
||||
try {
|
||||
const parsed = JSON.parse(savedState);
|
||||
if (parsed.inProgress) {
|
||||
setIsOpen(true);
|
||||
setState((prev) => ({
|
||||
...prev,
|
||||
step: parsed.step || "welcome",
|
||||
detectedProjects: parsed.detectedProjects || [],
|
||||
}));
|
||||
return;
|
||||
}
|
||||
} catch {
|
||||
// Invalid saved state, ignore
|
||||
}
|
||||
}
|
||||
|
||||
// Auto-open if no projects exist
|
||||
if (!status.hasProjects) {
|
||||
setIsOpen(true);
|
||||
}
|
||||
} catch {
|
||||
// Fail silently - don't auto-open on error
|
||||
}
|
||||
};
|
||||
|
||||
// Small delay to allow app to fully mount
|
||||
const timer = setTimeout(checkFirstRun, 500);
|
||||
return () => clearTimeout(timer);
|
||||
}, []);
|
||||
|
||||
// Persist wizard state for resume capability
|
||||
useEffect(() => {
|
||||
if (isOpen && state.step !== "complete") {
|
||||
localStorage.setItem(
|
||||
WIZARD_STATE_KEY,
|
||||
JSON.stringify({
|
||||
inProgress: true,
|
||||
step: state.step,
|
||||
detectedProjects: state.detectedProjects,
|
||||
})
|
||||
);
|
||||
} else if (!isOpen || state.step === "complete") {
|
||||
localStorage.removeItem(WIZARD_STATE_KEY);
|
||||
}
|
||||
}, [isOpen, state.step, state.detectedProjects]);
|
||||
|
||||
const handleClose = useCallback(() => {
|
||||
setIsOpen(false);
|
||||
localStorage.removeItem(WIZARD_STATE_KEY);
|
||||
onClose?.();
|
||||
}, [onClose]);
|
||||
|
||||
const startDetection = useCallback(async () => {
|
||||
setState((prev) => ({
|
||||
...prev,
|
||||
step: "detecting",
|
||||
isDetecting: true,
|
||||
detectError: null,
|
||||
}));
|
||||
|
||||
const result = await scanForProjects();
|
||||
|
||||
if (result.error) {
|
||||
setState((prev) => ({
|
||||
...prev,
|
||||
isDetecting: false,
|
||||
detectError: result.error,
|
||||
}));
|
||||
return;
|
||||
}
|
||||
|
||||
// Mark all non-existing projects as selected by default
|
||||
const selectedProjects: SelectedProject[] = result.projects.map((p) => ({
|
||||
...p,
|
||||
selected: !p.existing,
|
||||
}));
|
||||
|
||||
setState((prev) => ({
|
||||
...prev,
|
||||
step: "review",
|
||||
isDetecting: false,
|
||||
detectedProjects: selectedProjects,
|
||||
}));
|
||||
}, []);
|
||||
|
||||
const handleSelectionChange = useCallback((selected: SelectedProject[]) => {
|
||||
setState((prev) => ({
|
||||
...prev,
|
||||
detectedProjects: prev.detectedProjects.map((p) => ({
|
||||
...p,
|
||||
selected: selected.some((s) => s.path === p.path),
|
||||
customName: selected.find((s) => s.path === p.path)?.customName,
|
||||
})),
|
||||
}));
|
||||
}, []);
|
||||
|
||||
const handleRegisterDetected = useCallback(async () => {
|
||||
const toRegister = state.detectedProjects.filter((p) => p.selected && !p.existing);
|
||||
|
||||
if (toRegister.length === 0) {
|
||||
// No projects selected, skip to manual
|
||||
setState((prev) => ({ ...prev, step: "manual" }));
|
||||
return;
|
||||
}
|
||||
|
||||
setState((prev) => ({ ...prev, isRegistering: true }));
|
||||
|
||||
const registered: ProjectInfo[] = [];
|
||||
|
||||
for (const project of toRegister) {
|
||||
try {
|
||||
const input: ProjectCreateInput = {
|
||||
name: project.customName || project.suggestedName,
|
||||
path: project.path,
|
||||
isolationMode: "in-process",
|
||||
};
|
||||
|
||||
const result = await registerProject(input);
|
||||
registered.push(result);
|
||||
onProjectRegistered(result);
|
||||
} catch (err) {
|
||||
// Log error but continue with other projects
|
||||
console.error(`Failed to register project at ${project.path}:`, err);
|
||||
}
|
||||
}
|
||||
|
||||
if (onProjectsRegistered && registered.length > 0) {
|
||||
onProjectsRegistered(registered);
|
||||
}
|
||||
|
||||
setState((prev) => ({
|
||||
...prev,
|
||||
step: "complete",
|
||||
isRegistering: false,
|
||||
registeredCount: registered.length,
|
||||
}));
|
||||
}, [state.detectedProjects, onProjectRegistered, onProjectsRegistered]);
|
||||
|
||||
const handleManualRegister = useCallback(async () => {
|
||||
if (!state.manualPath || !state.manualName) return;
|
||||
|
||||
setState((prev) => ({ ...prev, isRegistering: true }));
|
||||
setState((prev) => ({ ...prev, isRegistering: true, error: null }));
|
||||
|
||||
try {
|
||||
const input: ProjectCreateInput = {
|
||||
@@ -269,85 +72,25 @@ export function SetupWizardModal({
|
||||
...prev,
|
||||
step: "complete",
|
||||
isRegistering: false,
|
||||
registeredCount: 1,
|
||||
}));
|
||||
} catch (err) {
|
||||
setState((prev) => ({
|
||||
...prev,
|
||||
isRegistering: false,
|
||||
detectError: err instanceof Error ? err.message : "Failed to register project",
|
||||
error: err instanceof Error ? err.message : "Failed to register project",
|
||||
}));
|
||||
}
|
||||
}, [state.manualPath, state.manualName, state.manualIsolationMode, onProjectRegistered]);
|
||||
|
||||
const goToManual = useCallback(() => {
|
||||
setState((prev) => ({ ...prev, step: "manual", detectError: null }));
|
||||
}, []);
|
||||
|
||||
const goBack = useCallback(() => {
|
||||
setState((prev) => {
|
||||
switch (prev.step) {
|
||||
case "detecting":
|
||||
return { ...prev, step: "welcome" };
|
||||
case "review":
|
||||
return { ...prev, step: "welcome" };
|
||||
case "manual":
|
||||
return { ...prev, step: "review" };
|
||||
default:
|
||||
return prev;
|
||||
}
|
||||
});
|
||||
}, []);
|
||||
>>>>>>> kb/kb-502
|
||||
|
||||
if (!isOpen) return null;
|
||||
|
||||
return (
|
||||
<<<<<<< HEAD
|
||||
<div
|
||||
className="modal-overlay open"
|
||||
onClick={(e) => {
|
||||
// Close on overlay click, but not when clicking the modal itself
|
||||
if (e.target === e.currentTarget) {
|
||||
onClose();
|
||||
}
|
||||
}}
|
||||
data-testid="setup-wizard-modal-overlay"
|
||||
>
|
||||
<div
|
||||
className="modal modal-lg"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
data-testid="setup-wizard-modal"
|
||||
>
|
||||
<div className="modal-header">
|
||||
<h3>Add New Project</h3>
|
||||
<button
|
||||
className="modal-close"
|
||||
onClick={onClose}
|
||||
aria-label="Close"
|
||||
data-testid="setup-wizard-modal-close"
|
||||
>
|
||||
<X size={20} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="modal-content-no-padding">
|
||||
<SetupWizard
|
||||
isOpen={isOpen}
|
||||
onClose={onClose}
|
||||
onProjectCreated={handleProjectCreated}
|
||||
onRegisterProject={onRegisterProject}
|
||||
/>
|
||||
=======
|
||||
<div className="modal-overlay open" role="dialog" aria-modal="true" aria-labelledby="wizard-title">
|
||||
<div className="modal setup-wizard-modal">
|
||||
{/* Header */}
|
||||
<div className="setup-wizard-header">
|
||||
<h2 id="wizard-title" className="setup-wizard-title">
|
||||
{state.step === "welcome" && "Welcome to kb"}
|
||||
{state.step === "detecting" && "Detecting Projects..."}
|
||||
{state.step === "review" && "Review Detected Projects"}
|
||||
{state.step === "manual" && "Add Project Manually"}
|
||||
{state.step === "manual" && "Welcome to kb"}
|
||||
{state.step === "complete" && "Setup Complete!"}
|
||||
</h2>
|
||||
{state.step !== "complete" && (
|
||||
@@ -363,57 +106,16 @@ export function SetupWizardModal({
|
||||
|
||||
{/* Content */}
|
||||
<div className="setup-wizard-content">
|
||||
{/* Welcome Step */}
|
||||
{state.step === "welcome" && (
|
||||
<div className="setup-wizard-welcome">
|
||||
<div className="welcome-icon">
|
||||
<FolderPlus size={64} />
|
||||
</div>
|
||||
<p className="welcome-text">
|
||||
Let's set up your kb workspace. We can automatically detect existing projects
|
||||
on your system, or you can add them manually.
|
||||
</p>
|
||||
<div className="welcome-actions">
|
||||
<button className="btn-primary" onClick={startDetection}>
|
||||
<Search size={18} />
|
||||
<span>Auto-detect Projects</span>
|
||||
</button>
|
||||
<button className="btn-secondary" onClick={goToManual}>
|
||||
<FolderPlus size={18} />
|
||||
<span>Add Manually</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Detecting Step */}
|
||||
{state.step === "detecting" && (
|
||||
<div className="setup-wizard-detecting">
|
||||
<Loader2 size={48} className="animate-spin" />
|
||||
<p>Scanning your home directory for kb projects...</p>
|
||||
<p className="detecting-hint">
|
||||
This may take a moment. Looking for <code>.fusion/kb.db</code> files.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Review Step */}
|
||||
{state.step === "review" && (
|
||||
<div className="setup-wizard-review">
|
||||
<ProjectDetectionResults
|
||||
projects={state.detectedProjects}
|
||||
onSelectionChange={handleSelectionChange}
|
||||
isDetecting={false}
|
||||
/>
|
||||
{state.detectError && (
|
||||
<div className="error-message">{state.detectError}</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Manual Step */}
|
||||
{state.step === "manual" && (
|
||||
<div className="setup-wizard-manual">
|
||||
<div className="welcome-icon" style={{ marginBottom: "1rem" }}>
|
||||
<FolderPlus size={48} />
|
||||
</div>
|
||||
<p className="welcome-text" style={{ marginBottom: "1.5rem" }}>
|
||||
Let's set up your first kb project. Enter the path to your project directory.
|
||||
</p>
|
||||
|
||||
<div className="form-group">
|
||||
<label htmlFor="project-path">Project Path</label>
|
||||
<input
|
||||
@@ -426,7 +128,7 @@ export function SetupWizardModal({
|
||||
placeholder="/path/to/your/project"
|
||||
/>
|
||||
<p className="form-hint">
|
||||
Absolute path to your project directory (must contain .fusion/kb.db)
|
||||
Absolute path to your project directory
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@@ -460,8 +162,10 @@ export function SetupWizardModal({
|
||||
</select>
|
||||
</div>
|
||||
|
||||
{state.detectError && (
|
||||
<div className="error-message">{state.detectError}</div>
|
||||
{state.error && (
|
||||
<div className="error-message" style={{ marginTop: "1rem" }}>
|
||||
{state.error}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
@@ -472,8 +176,7 @@ export function SetupWizardModal({
|
||||
<CheckCircle size={64} className="success-icon" />
|
||||
<h3>All Set!</h3>
|
||||
<p>
|
||||
{state.registeredCount} project{state.registeredCount !== 1 ? "s" : ""}{" "}
|
||||
registered successfully.
|
||||
Your project has been registered successfully.
|
||||
</p>
|
||||
<p>You can add more projects anytime from the project overview.</p>
|
||||
</div>
|
||||
@@ -482,51 +185,6 @@ export function SetupWizardModal({
|
||||
|
||||
{/* Footer */}
|
||||
<div className="setup-wizard-footer">
|
||||
{state.step !== "welcome" && state.step !== "complete" && (
|
||||
<button
|
||||
className="btn-secondary"
|
||||
onClick={goBack}
|
||||
disabled={state.isRegistering}
|
||||
>
|
||||
<ArrowLeft size={16} />
|
||||
<span>Back</span>
|
||||
</button>
|
||||
)}
|
||||
|
||||
<div className="footer-spacer" />
|
||||
|
||||
{state.step === "review" && (
|
||||
<>
|
||||
<button
|
||||
className="btn-secondary"
|
||||
onClick={goToManual}
|
||||
disabled={state.isRegistering}
|
||||
>
|
||||
Skip to Manual
|
||||
</button>
|
||||
<button
|
||||
className="btn-primary"
|
||||
onClick={handleRegisterDetected}
|
||||
disabled={
|
||||
state.isRegistering ||
|
||||
!state.detectedProjects.some((p) => p.selected && !p.existing)
|
||||
}
|
||||
>
|
||||
{state.isRegistering ? (
|
||||
<>
|
||||
<Loader2 size={16} className="animate-spin" />
|
||||
<span>Registering...</span>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<span>Register Selected</span>
|
||||
<ArrowRight size={16} />
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
|
||||
{state.step === "manual" && (
|
||||
<button
|
||||
className="btn-primary"
|
||||
@@ -541,7 +199,6 @@ export function SetupWizardModal({
|
||||
) : (
|
||||
<>
|
||||
<span>Register Project</span>
|
||||
<ArrowRight size={16} />
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
@@ -553,7 +210,6 @@ export function SetupWizardModal({
|
||||
<span>Get Started</span>
|
||||
</button>
|
||||
)}
|
||||
>>>>>>> kb/kb-502
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -76,7 +76,7 @@ import {
|
||||
fetchTasks,
|
||||
type ProjectInfo,
|
||||
type DetectedProject,
|
||||
} from "../../app/api";
|
||||
} from "../../app/api.js";
|
||||
|
||||
function mockFetchResponse(
|
||||
ok: boolean,
|
||||
|
||||
@@ -1075,18 +1075,28 @@ export function createApiRoutes(store: TaskStore, options?: ServerOptions): Rout
|
||||
*/
|
||||
router.get("/setup-state", async (_req, res) => {
|
||||
try {
|
||||
const { FirstRunDetector } = await import("@fusion/core");
|
||||
const { CentralCore } = await import("@fusion/core");
|
||||
const { createFirstRunExperience, CentralCore } = await import("@fusion/core");
|
||||
const { createMigrationOrchestrator } = await import("@fusion/core");
|
||||
|
||||
const detector = new FirstRunDetector();
|
||||
const state = await detector.detectFirstRunState();
|
||||
const detectedProjects = await detector.detectExistingProjects(process.cwd());
|
||||
const central = new CentralCore();
|
||||
await central.init();
|
||||
|
||||
res.json({
|
||||
state,
|
||||
detectedProjects,
|
||||
hasCentralDb: detector.hasCentralDb(),
|
||||
});
|
||||
try {
|
||||
const migration = createMigrationOrchestrator(central);
|
||||
const firstRun = createFirstRunExperience(central);
|
||||
|
||||
const needsMigration = await migration.needsMigration();
|
||||
const state = await firstRun.getSetupState();
|
||||
const detectedProjects = state.detectedProjects || [];
|
||||
|
||||
res.json({
|
||||
state: needsMigration ? "needs-migration" : state.isFirstRun ? "setup-wizard" : "normal-operation",
|
||||
detectedProjects,
|
||||
hasCentralDb: true,
|
||||
});
|
||||
} finally {
|
||||
await central.close();
|
||||
}
|
||||
} catch (err: any) {
|
||||
res.status(500).json({ error: err.message });
|
||||
}
|
||||
@@ -1106,19 +1116,19 @@ export function createApiRoutes(store: TaskStore, options?: ServerOptions): Rout
|
||||
return;
|
||||
}
|
||||
|
||||
const { CentralCore, MigrationCoordinator } = await import("@fusion/core");
|
||||
const { CentralCore, createFirstRunExperience } = await import("@fusion/core");
|
||||
|
||||
const central = new CentralCore();
|
||||
await central.init();
|
||||
|
||||
try {
|
||||
const coordinator = new MigrationCoordinator(central);
|
||||
const result = await coordinator.completeSetup(projects);
|
||||
const firstRun = createFirstRunExperience(central);
|
||||
const result = await firstRun.completeSetup(projects);
|
||||
|
||||
res.json({
|
||||
success: result.success,
|
||||
registered: result.projectsRegistered,
|
||||
errors: result.errors,
|
||||
registered: result.projects.map(p => p.id),
|
||||
errors: [],
|
||||
});
|
||||
} finally {
|
||||
await central.close();
|
||||
|
||||
@@ -14,3 +14,4 @@ export { PrCommentHandler } from "./pr-comment-handler.js";
|
||||
export { NtfyNotifier, type NtfyNotifierOptions } from "./notifier.js";
|
||||
export { CronRunner, type CronRunnerOptions } from "./cron-runner.js";
|
||||
export { StuckTaskDetector, type StuckTaskDetectorOptions, type DisposableSession } from "./stuck-task-detector.js";
|
||||
export { ProjectManager } from "./project-manager.js";
|
||||
|
||||
Reference in New Issue
Block a user