feat(dashboard): add draft planning sessions with debounced auto-creation
Introduce a draft lifecycle for planning sessions: typing into the PlanningModeModal textarea now creates a server-side draft after a 300ms debounce, persisted with status='draft' so the user's in-flight plan survives modal close/reopen and shows up immediately in the session list. - planning.ts: new createDraftSession path; persistSession status union widened to include 'draft'; Session gains an explicit title field so subsequent updates don't clobber it. - register-planning-subtask-routes.ts: wires the createPlanningDraft POST endpoint that the modal calls on debounce. - ai-session-store.ts: tracks the draft status across queries so the session list and locks behave the same as any active session. - legacy.ts: client wrapper for createPlanningDraft. - PlanningModeModal styling, tests, and ModalReentry coverage updated for the new flow. - docs/architecture.md notes the expanded ai_sessions.status lifecycle. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -2593,12 +2593,28 @@ export function startPlanning(
|
||||
});
|
||||
}
|
||||
|
||||
export function createPlanningDraft(
|
||||
initialPlan: string,
|
||||
projectId?: string,
|
||||
modelOverride?: { planningModelProvider?: string; planningModelId?: string },
|
||||
): Promise<{ sessionId: string; title: string }> {
|
||||
return api<{ sessionId: string; title: string }>(withProjectId("/planning/create-draft", projectId), {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
initialPlan,
|
||||
planningModelProvider: modelOverride?.planningModelProvider,
|
||||
planningModelId: modelOverride?.planningModelId,
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
/** Start a new planning session with AI streaming support */
|
||||
export function startPlanningStreaming(
|
||||
initialPlan: string,
|
||||
projectId?: string,
|
||||
modelOverride?: { planningModelProvider?: string; planningModelId?: string },
|
||||
planningOptions?: { planningDepth?: "small" | "medium" | "large"; customQuestionCount?: number },
|
||||
existingSessionId?: string,
|
||||
): Promise<{ sessionId: string }> {
|
||||
return api<{ sessionId: string }>(withProjectId("/planning/start-streaming", projectId), {
|
||||
method: "POST",
|
||||
@@ -2608,6 +2624,7 @@ export function startPlanningStreaming(
|
||||
planningModelId: modelOverride?.planningModelId,
|
||||
planningDepth: planningOptions?.planningDepth,
|
||||
customQuestionCount: planningOptions?.customQuestionCount,
|
||||
...(existingSessionId ? { existingSessionId } : {}),
|
||||
}),
|
||||
});
|
||||
}
|
||||
@@ -7100,7 +7117,7 @@ export function reorderTodoItems(listId: string, itemIds: string[], projectId?:
|
||||
export interface AiSessionSummary {
|
||||
id: string;
|
||||
type: "planning" | "subtask" | "mission_interview" | "milestone_interview" | "slice_interview";
|
||||
status: "generating" | "awaiting_input" | "complete" | "error";
|
||||
status: "draft" | "generating" | "awaiting_input" | "complete" | "error";
|
||||
title: string;
|
||||
projectId: string | null;
|
||||
lockedByTab: string | null;
|
||||
|
||||
@@ -93,25 +93,26 @@
|
||||
}
|
||||
|
||||
.planning-sidebar-header {
|
||||
padding: 12px;
|
||||
padding: var(--space-md);
|
||||
border-bottom: 1px solid var(--border);
|
||||
flex-shrink: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
gap: var(--space-sm);
|
||||
}
|
||||
|
||||
.planning-sidebar-footer {
|
||||
padding: 6px 12px 10px;
|
||||
padding: var(--space-sm) var(--space-md) var(--space-md);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.planning-sidebar-toggle-archived-link {
|
||||
font-size: 11px;
|
||||
font-size: calc(var(--space-sm) + var(--space-xs) * 0.75);
|
||||
color: var(--text-muted);
|
||||
text-decoration: none;
|
||||
cursor: pointer;
|
||||
transition: color var(--transition-fast);
|
||||
transition: color var(--transition-fast), box-shadow var(--transition-fast);
|
||||
border-radius: var(--radius-sm);
|
||||
}
|
||||
|
||||
.planning-sidebar-toggle-archived-link:hover {
|
||||
@@ -119,21 +120,26 @@
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.planning-sidebar-toggle-archived-link:focus-visible {
|
||||
outline: none;
|
||||
box-shadow: var(--focus-ring-strong);
|
||||
}
|
||||
|
||||
.planning-sidebar-new {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
gap: var(--space-sm);
|
||||
width: 100%;
|
||||
padding: 10px 12px;
|
||||
padding: var(--space-sm) var(--space-md);
|
||||
background: var(--surface);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-md);
|
||||
color: var(--text);
|
||||
font-size: 13px;
|
||||
font-size: calc(var(--space-sm) + var(--space-xs) * 1.25);
|
||||
font-weight: 500;
|
||||
cursor: pointer;
|
||||
transition: background var(--transition-fast), border-color var(--transition-fast);
|
||||
transition: background var(--transition-fast), border-color var(--transition-fast), box-shadow var(--transition-fast);
|
||||
}
|
||||
|
||||
.planning-sidebar-new:hover {
|
||||
@@ -147,14 +153,19 @@
|
||||
color: var(--todo);
|
||||
}
|
||||
|
||||
.planning-sidebar-new:focus-visible {
|
||||
outline: none;
|
||||
box-shadow: var(--focus-ring-strong);
|
||||
}
|
||||
|
||||
.planning-sidebar-list {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
overflow-y: auto;
|
||||
padding: 6px;
|
||||
padding: var(--space-sm);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
gap: var(--space-xs);
|
||||
}
|
||||
|
||||
.planning-sidebar-empty {
|
||||
@@ -181,7 +192,7 @@
|
||||
}
|
||||
|
||||
.planning-sidebar-item.pending-delete {
|
||||
background: color-mix(in srgb, var(--danger, #f85149) 15%, transparent);
|
||||
background: color-mix(in srgb, var(--color-error) 15%, transparent);
|
||||
}
|
||||
|
||||
.planning-sidebar-item-button {
|
||||
@@ -189,14 +200,20 @@
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 10px;
|
||||
padding: 10px 8px 10px 10px;
|
||||
gap: var(--space-sm);
|
||||
padding: var(--space-sm) var(--space-sm) var(--space-sm) var(--space-md);
|
||||
background: none;
|
||||
border: none;
|
||||
color: inherit;
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
font: inherit;
|
||||
border-radius: var(--radius-md);
|
||||
}
|
||||
|
||||
.planning-sidebar-item-button:focus-visible {
|
||||
outline: none;
|
||||
box-shadow: var(--focus-ring-strong);
|
||||
}
|
||||
|
||||
.planning-sidebar-item-body {
|
||||
@@ -234,8 +251,8 @@
|
||||
|
||||
.planning-sidebar-status-generating { color: var(--todo); }
|
||||
.planning-sidebar-status-awaiting { color: var(--triage); }
|
||||
.planning-sidebar-status-complete { color: var(--success, #3fb950); }
|
||||
.planning-sidebar-status-error { color: var(--danger, #f85149); }
|
||||
.planning-sidebar-status-complete { color: var(--color-success); }
|
||||
.planning-sidebar-status-error { color: var(--color-error); }
|
||||
|
||||
.planning-sidebar-item-actions {
|
||||
display: flex;
|
||||
@@ -245,7 +262,10 @@
|
||||
.planning-sidebar-item-delete,
|
||||
.planning-sidebar-item-archive {
|
||||
flex-shrink: 0;
|
||||
width: 32px;
|
||||
width: calc(var(--space-lg) + var(--space-xl));
|
||||
min-width: calc(var(--space-lg) + var(--space-xl));
|
||||
height: calc(var(--space-lg) + var(--space-xl));
|
||||
min-height: calc(var(--space-lg) + var(--space-xl));
|
||||
display: none;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
@@ -254,6 +274,7 @@
|
||||
color: var(--text-muted);
|
||||
cursor: pointer;
|
||||
border-radius: var(--radius-sm);
|
||||
transition: color var(--transition-fast), background var(--transition-fast), box-shadow var(--transition-fast);
|
||||
}
|
||||
|
||||
.planning-sidebar-item:hover .planning-sidebar-item-delete,
|
||||
@@ -264,8 +285,8 @@
|
||||
}
|
||||
|
||||
.planning-sidebar-item-delete:hover {
|
||||
color: var(--danger, #f85149);
|
||||
background: color-mix(in srgb, var(--danger, #f85149) 15%, transparent);
|
||||
color: var(--color-error);
|
||||
background: color-mix(in srgb, var(--color-error) 15%, transparent);
|
||||
}
|
||||
|
||||
.planning-sidebar-item-archive:hover {
|
||||
@@ -273,6 +294,12 @@
|
||||
background: color-mix(in srgb, var(--todo) 15%, transparent);
|
||||
}
|
||||
|
||||
.planning-sidebar-item-delete:focus-visible,
|
||||
.planning-sidebar-item-archive:focus-visible {
|
||||
outline: none;
|
||||
box-shadow: var(--focus-ring-strong);
|
||||
}
|
||||
|
||||
.planning-sidebar-item.archived .planning-sidebar-item-button {
|
||||
opacity: 0.6;
|
||||
}
|
||||
@@ -293,14 +320,20 @@
|
||||
border: none;
|
||||
color: var(--text);
|
||||
cursor: pointer;
|
||||
padding: 4px;
|
||||
padding: var(--space-xs);
|
||||
border-radius: var(--radius-sm);
|
||||
transition: background var(--transition-fast), box-shadow var(--transition-fast);
|
||||
}
|
||||
|
||||
.planning-mobile-back:hover {
|
||||
background: var(--card-hover);
|
||||
}
|
||||
|
||||
.planning-mobile-back:focus-visible {
|
||||
outline: none;
|
||||
box-shadow: var(--focus-ring-strong);
|
||||
}
|
||||
|
||||
/* Mobile: stack — only one pane visible at a time */
|
||||
@media (max-width: 720px) {
|
||||
/* Full-screen sheet — drop overlay padding so the modal fills the
|
||||
@@ -442,7 +475,7 @@
|
||||
.session-lock-overlay {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
background: rgba(0, 0, 0, 0.4);
|
||||
background: color-mix(in srgb, var(--bg) 55%, transparent);
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: center;
|
||||
@@ -459,7 +492,7 @@
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
|
||||
box-shadow: var(--shadow-md);
|
||||
}
|
||||
|
||||
.session-lock-take-control {
|
||||
@@ -589,7 +622,7 @@
|
||||
padding: 8px 14px;
|
||||
background: var(--card);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 999px;
|
||||
border-radius: var(--radius-pill);
|
||||
font-size: 12px;
|
||||
line-height: 1.4;
|
||||
color: var(--text-muted);
|
||||
@@ -649,7 +682,7 @@
|
||||
|
||||
.planning-progress-step {
|
||||
height: 4px;
|
||||
border-radius: 999px;
|
||||
border-radius: var(--radius-pill);
|
||||
background: var(--border);
|
||||
transition: background-color var(--transition-fast);
|
||||
}
|
||||
@@ -946,7 +979,7 @@
|
||||
padding: var(--space-sm) var(--space-md);
|
||||
background: var(--surface);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 999px;
|
||||
border-radius: var(--radius-pill);
|
||||
font-size: 12px;
|
||||
cursor: pointer;
|
||||
transition:
|
||||
@@ -1052,7 +1085,10 @@
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-md);
|
||||
cursor: pointer;
|
||||
transition: all 0.15s ease;
|
||||
transition:
|
||||
background var(--transition-fast),
|
||||
color var(--transition-fast),
|
||||
border-color var(--transition-fast);
|
||||
}
|
||||
|
||||
.planning-thinking-toggle:hover {
|
||||
@@ -1123,7 +1159,7 @@
|
||||
}
|
||||
|
||||
.subtask-item-drop-target {
|
||||
background: rgba(88, 166, 255, 0.08);
|
||||
background: color-mix(in srgb, var(--todo) 12%, transparent);
|
||||
border-color: var(--todo);
|
||||
}
|
||||
|
||||
|
||||
@@ -189,7 +189,7 @@ describe("ModalReentry", () => {
|
||||
expect(mockStartPlanningStreaming).toHaveBeenCalledWith("From prop", undefined, undefined, {
|
||||
planningDepth: "medium",
|
||||
customQuestionCount: undefined,
|
||||
});
|
||||
}, undefined);
|
||||
});
|
||||
|
||||
// localStorage should NOT be read since prop was provided
|
||||
|
||||
@@ -10,6 +10,7 @@ import type { Task, TaskDetail, PlanningQuestion, PlanningSummary, MergeResult }
|
||||
// Mock the API functions
|
||||
const mockStartPlanning = vi.fn();
|
||||
const mockStartPlanningStreaming = vi.fn();
|
||||
const mockCreatePlanningDraft = vi.fn();
|
||||
const mockConnectPlanningStream = vi.fn();
|
||||
const mockRespondToPlanning = vi.fn();
|
||||
const mockRetryPlanningSession = vi.fn();
|
||||
@@ -38,6 +39,7 @@ const mockRefineTask = vi.fn();
|
||||
vi.mock("../../api", () => ({
|
||||
startPlanning: (...args: any[]) => mockStartPlanning(...args),
|
||||
startPlanningStreaming: (...args: any[]) => mockStartPlanningStreaming(...args),
|
||||
createPlanningDraft: (...args: any[]) => mockCreatePlanningDraft(...args),
|
||||
connectPlanningStream: (...args: any[]) => mockConnectPlanningStream(...args),
|
||||
respondToPlanning: (...args: any[]) => mockRespondToPlanning(...args),
|
||||
retryPlanningSession: (...args: any[]) => mockRetryPlanningSession(...args),
|
||||
@@ -197,6 +199,7 @@ describe("PlanningModeModal", () => {
|
||||
|
||||
// Default mock for streaming
|
||||
mockStartPlanningStreaming.mockResolvedValue({ sessionId: "session-123" });
|
||||
mockCreatePlanningDraft.mockResolvedValue({ sessionId: "draft-123", title: "Test Plan" });
|
||||
mockRetryPlanningSession.mockResolvedValue({ success: true, sessionId: "session-123" });
|
||||
mockStartPlanningBreakdown.mockResolvedValue({ sessionId: "session-123", subtasks: [] });
|
||||
mockFetchAiSession.mockResolvedValue(null);
|
||||
@@ -384,7 +387,7 @@ describe("PlanningModeModal", () => {
|
||||
}, {
|
||||
planningDepth: "medium",
|
||||
customQuestionCount: undefined,
|
||||
});
|
||||
}, undefined);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -427,7 +430,7 @@ describe("PlanningModeModal", () => {
|
||||
expect(mockStartPlanningStreaming).toHaveBeenCalledWith("Build auth system", undefined, undefined, {
|
||||
planningDepth: "large",
|
||||
customQuestionCount: 7,
|
||||
});
|
||||
}, undefined);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -450,7 +453,51 @@ describe("PlanningModeModal", () => {
|
||||
expect(mockStartPlanningStreaming).toHaveBeenCalledWith("Build auth system", undefined, undefined, {
|
||||
planningDepth: "medium",
|
||||
customQuestionCount: undefined,
|
||||
});
|
||||
}, undefined);
|
||||
});
|
||||
});
|
||||
|
||||
it("auto-creates a draft after typing and reuses it when starting", async () => {
|
||||
render(
|
||||
<PlanningModeModal
|
||||
isOpen={true}
|
||||
onClose={mockOnClose}
|
||||
onTaskCreated={mockOnTaskCreated}
|
||||
onTasksCreated={vi.fn()}
|
||||
tasks={mockTasks}
|
||||
/>,
|
||||
);
|
||||
|
||||
const textarea = screen.getByPlaceholderText(/e.g., Build a user authentication/);
|
||||
fireEvent.change(textarea, { target: { value: "Build a detailed auth system plan" } });
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockCreatePlanningDraft).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
expect(mockCreatePlanningDraft).toHaveBeenCalledWith(
|
||||
"Build a detailed auth system plan",
|
||||
undefined,
|
||||
undefined,
|
||||
);
|
||||
|
||||
expect(screen.getByText("Test Plan")).toBeDefined();
|
||||
|
||||
fireEvent.change(textarea, { target: { value: "Build a detailed auth system plan with extras" } });
|
||||
await new Promise((resolve) => setTimeout(resolve, 350));
|
||||
expect(mockCreatePlanningDraft).toHaveBeenCalledTimes(1);
|
||||
|
||||
fireEvent.click(screen.getByText("Start Planning"));
|
||||
await waitFor(() => {
|
||||
expect(mockStartPlanningStreaming).toHaveBeenCalledWith(
|
||||
"Build a detailed auth system plan with extras",
|
||||
undefined,
|
||||
undefined,
|
||||
{
|
||||
planningDepth: "medium",
|
||||
customQuestionCount: undefined,
|
||||
},
|
||||
"draft-123",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -471,7 +518,7 @@ describe("PlanningModeModal", () => {
|
||||
expect(mockStartPlanningStreaming).toHaveBeenCalledWith("Build a login system from new task dialog", undefined, undefined, {
|
||||
planningDepth: "medium",
|
||||
customQuestionCount: undefined,
|
||||
});
|
||||
}, undefined);
|
||||
}, { timeout: 2000 });
|
||||
|
||||
// Should transition to question view
|
||||
@@ -497,7 +544,7 @@ describe("PlanningModeModal", () => {
|
||||
expect(mockStartPlanningStreaming).toHaveBeenCalledWith("Pre-filled plan from new task", undefined, undefined, {
|
||||
planningDepth: "medium",
|
||||
customQuestionCount: undefined,
|
||||
});
|
||||
}, undefined);
|
||||
}, { timeout: 2000 });
|
||||
});
|
||||
});
|
||||
@@ -554,7 +601,7 @@ describe("PlanningModeModal", () => {
|
||||
expect(mockStartPlanningStreaming).toHaveBeenCalledWith("Build auth system", undefined, undefined, {
|
||||
planningDepth: "medium",
|
||||
customQuestionCount: undefined,
|
||||
});
|
||||
}, undefined);
|
||||
});
|
||||
|
||||
// Should transition to question view via streaming
|
||||
|
||||
@@ -91,6 +91,25 @@ describe("AiSessionStore", () => {
|
||||
return entries;
|
||||
}
|
||||
|
||||
it("updateTitle updates title and emits ai_session:updated", () => {
|
||||
const row = makeRow("S-title", "draft");
|
||||
store.upsert(row);
|
||||
|
||||
const onUpdated = vi.fn();
|
||||
store.on("ai_session:updated", onUpdated);
|
||||
|
||||
const updated = store.updateTitle("S-title", "New Draft Title");
|
||||
|
||||
expect(updated).toBe(true);
|
||||
expect(store.get("S-title")?.title).toBe("New Draft Title");
|
||||
expect(onUpdated).toHaveBeenCalled();
|
||||
expect(onUpdated.mock.calls.at(-1)?.[0]).toMatchObject({
|
||||
id: "S-title",
|
||||
title: "New Draft Title",
|
||||
status: "draft",
|
||||
});
|
||||
});
|
||||
|
||||
it("cleanupOld removes only stale terminal sessions and emits deleted events", () => {
|
||||
const deletedIds: string[] = [];
|
||||
store.on("ai_session:deleted", (id) => deletedIds.push(id));
|
||||
|
||||
@@ -9,6 +9,8 @@ import { Database, TaskStore } from "@fusion/core";
|
||||
import {
|
||||
createSession,
|
||||
createSessionWithAgent,
|
||||
createDraftSession,
|
||||
startExistingSession,
|
||||
submitResponse,
|
||||
retrySession,
|
||||
cancelSession,
|
||||
@@ -760,6 +762,41 @@ describe("planning module", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("draft session helpers", () => {
|
||||
it("creates a draft session with draft status", async () => {
|
||||
const session = await createDraftSession(
|
||||
getUniqueIp(),
|
||||
"Draft plan text for the planning modal",
|
||||
TEST_ROOT_DIR,
|
||||
);
|
||||
|
||||
expect(session.sessionId).toBeDefined();
|
||||
expect(session.title).toBe("Draft plan text for the planning modal");
|
||||
expect(getSession(session.sessionId)?.id).toBe(session.sessionId);
|
||||
});
|
||||
|
||||
it("starts an existing draft session and moves it into active flow", async () => {
|
||||
setupMockStreamingAgent({ responses: STANDARD_QUESTION_RESPONSES });
|
||||
const draft = await createDraftSession(
|
||||
getUniqueIp(),
|
||||
"Draft plan reused by start",
|
||||
TEST_ROOT_DIR,
|
||||
);
|
||||
|
||||
await startExistingSession(draft.sessionId, TEST_ROOT_DIR);
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(getSession(draft.sessionId)?.currentQuestion?.id).toBe("q-scope");
|
||||
});
|
||||
});
|
||||
|
||||
it("throws when starting a missing draft session", async () => {
|
||||
await expect(startExistingSession("missing-session", TEST_ROOT_DIR)).rejects.toThrow(
|
||||
SessionNotFoundError,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("submitResponse", () => {
|
||||
it("processes response and returns next question", async () => {
|
||||
const mockIp = getUniqueIp();
|
||||
@@ -2388,6 +2425,113 @@ describe("planning routes lock enforcement", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("creates a draft planning session via route and persists draft status", async () => {
|
||||
const response = await request(
|
||||
app,
|
||||
"POST",
|
||||
"/api/planning/create-draft",
|
||||
JSON.stringify({ initialPlan: "Build a dashboard settings wizard with guided onboarding steps" }),
|
||||
{ "content-type": "application/json" },
|
||||
);
|
||||
|
||||
expect(response.status).toBe(201);
|
||||
expect(response.body).toMatchObject({
|
||||
sessionId: expect.any(String),
|
||||
title: "Build a dashboard settings wizard with guided onboarding steps",
|
||||
});
|
||||
expect(response.body.sessionId).toMatch(
|
||||
/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,
|
||||
);
|
||||
|
||||
const persisted = aiSessionStore.get(response.body.sessionId as string);
|
||||
expect(persisted?.status).toBe("draft");
|
||||
});
|
||||
|
||||
it("returns 400 for draft creation without non-empty initialPlan", async () => {
|
||||
const missing = await request(
|
||||
app,
|
||||
"POST",
|
||||
"/api/planning/create-draft",
|
||||
JSON.stringify({}),
|
||||
{ "content-type": "application/json" },
|
||||
);
|
||||
expect(missing.status).toBe(400);
|
||||
|
||||
const empty = await request(
|
||||
app,
|
||||
"POST",
|
||||
"/api/planning/create-draft",
|
||||
JSON.stringify({ initialPlan: "" }),
|
||||
{ "content-type": "application/json" },
|
||||
);
|
||||
expect(empty.status).toBe(400);
|
||||
});
|
||||
|
||||
it("returns 429 when draft creation rate limit is exceeded", async () => {
|
||||
for (let i = 0; i < 1000; i++) {
|
||||
const created = await request(
|
||||
app,
|
||||
"POST",
|
||||
"/api/planning/create-draft",
|
||||
JSON.stringify({ initialPlan: `Rate-limited draft ${i}` }),
|
||||
{ "content-type": "application/json" },
|
||||
);
|
||||
expect(created.status).toBe(201);
|
||||
}
|
||||
|
||||
const rateLimited = await request(
|
||||
app,
|
||||
"POST",
|
||||
"/api/planning/create-draft",
|
||||
JSON.stringify({ initialPlan: "This draft should hit the rate limit" }),
|
||||
{ "content-type": "application/json" },
|
||||
);
|
||||
|
||||
expect(rateLimited.status).toBe(429);
|
||||
expect(String(rateLimited.body?.error ?? "")).toContain("Rate limit exceeded");
|
||||
});
|
||||
|
||||
it("reuses existing draft session when starting streaming", async () => {
|
||||
const draft = await request(
|
||||
app,
|
||||
"POST",
|
||||
"/api/planning/create-draft",
|
||||
JSON.stringify({ initialPlan: "Plan draft to be reused by start-streaming" }),
|
||||
{ "content-type": "application/json" },
|
||||
);
|
||||
expect(draft.status).toBe(201);
|
||||
const draftSessionId = draft.body.sessionId as string;
|
||||
|
||||
const startExisting = await request(
|
||||
app,
|
||||
"POST",
|
||||
"/api/planning/start-streaming",
|
||||
JSON.stringify({
|
||||
initialPlan: "Plan draft to be reused by start-streaming",
|
||||
existingSessionId: draftSessionId,
|
||||
}),
|
||||
{ "content-type": "application/json" },
|
||||
);
|
||||
|
||||
expect(startExisting.status).toBe(201);
|
||||
expect(startExisting.body).toEqual({ sessionId: draftSessionId });
|
||||
expect(aiSessionStore.get(draftSessionId)?.status).toBe("awaiting_input");
|
||||
|
||||
const startNew = await request(
|
||||
app,
|
||||
"POST",
|
||||
"/api/planning/start-streaming",
|
||||
JSON.stringify({ initialPlan: "Plan without existing draft" }),
|
||||
{ "content-type": "application/json" },
|
||||
);
|
||||
|
||||
expect(startNew.status).toBe(201);
|
||||
expect(startNew.body.sessionId).toMatch(
|
||||
/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,
|
||||
);
|
||||
expect(startNew.body.sessionId).not.toBe(draftSessionId);
|
||||
});
|
||||
|
||||
it("keeps planning SSE stream read-only and unaffected by locks", async () => {
|
||||
const { sessionId } = await createSession(getUniqueIp(), "SSE lock check", taskStore, tmpRoot);
|
||||
await submitResponse(sessionId, { "q-scope": "small" }, tmpRoot);
|
||||
|
||||
@@ -17,7 +17,7 @@ import { createSessionDiagnostics } from "./ai-session-diagnostics.js";
|
||||
// ── Types ───────────────────────────────────────────────────────────────
|
||||
|
||||
export type AiSessionType = "planning" | "subtask" | "mission_interview" | "milestone_interview" | "slice_interview";
|
||||
export type AiSessionStatus = "generating" | "awaiting_input" | "complete" | "error";
|
||||
export type AiSessionStatus = "generating" | "awaiting_input" | "complete" | "error" | "draft";
|
||||
|
||||
export interface AiSessionRow {
|
||||
id: string;
|
||||
@@ -196,6 +196,29 @@ export class AiSessionStore extends EventEmitter<AiSessionStoreEvents> {
|
||||
return true;
|
||||
}
|
||||
|
||||
updateTitle(id: string, title: string): boolean {
|
||||
const now = new Date().toISOString();
|
||||
const result = this.db
|
||||
.prepare(
|
||||
`UPDATE ai_sessions
|
||||
SET title = ?, updatedAt = ?
|
||||
WHERE id = ?`,
|
||||
)
|
||||
.run(title, now, id) as { changes?: number };
|
||||
|
||||
const changed = Number(result.changes ?? 0) > 0;
|
||||
if (!changed) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const row = this.get(id);
|
||||
if (row) {
|
||||
this.emit("ai_session:updated", toSummary(row, row.updatedAt));
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Lightweight heartbeat for active sessions.
|
||||
* Updates only `updatedAt` and intentionally does NOT emit
|
||||
|
||||
@@ -19,7 +19,7 @@ import type {
|
||||
TaskStore,
|
||||
NtfyNotificationEvent,
|
||||
} from "@fusion/core";
|
||||
import { resolvePrompt, type PromptOverrideMap } from "@fusion/core";
|
||||
import { resolvePrompt, summarizeTitle, type PromptOverrideMap } from "@fusion/core";
|
||||
import type { SubtaskItem } from "./subtask-breakdown.js";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { EventEmitter } from "node:events";
|
||||
@@ -270,6 +270,7 @@ interface Session {
|
||||
id: string;
|
||||
ip: string;
|
||||
initialPlan: string;
|
||||
title: string;
|
||||
projectId?: string;
|
||||
ntfyConfig?: PlanningNtfyConfig;
|
||||
/** Last planning question notified via ntfy, keyed as `${sessionId}:${questionId}` for dedupe across reconnect/replay. */
|
||||
@@ -373,13 +374,13 @@ function cleanupInMemorySession(sessionId: string): boolean {
|
||||
}
|
||||
|
||||
/** Persist the current session state to SQLite (no-op if store not wired). */
|
||||
function persistSession(session: Session, status: "generating" | "awaiting_input" | "complete" | "error", error?: string): void {
|
||||
function persistSession(session: Session, status: "generating" | "awaiting_input" | "complete" | "error" | "draft", error?: string): void {
|
||||
if (!_aiSessionStore) return;
|
||||
const row: AiSessionRow = {
|
||||
id: session.id,
|
||||
type: "planning",
|
||||
status,
|
||||
title: session.initialPlan.slice(0, 120),
|
||||
title: session.title || session.initialPlan.slice(0, 120),
|
||||
inputPayload: JSON.stringify({ ip: session.ip, initialPlan: session.initialPlan }),
|
||||
conversationHistory: JSON.stringify(session.history),
|
||||
currentQuestion: session.currentQuestion ? JSON.stringify(session.currentQuestion) : null,
|
||||
@@ -432,6 +433,7 @@ function buildSessionFromRow(row: AiSessionRow): Session {
|
||||
id: row.id,
|
||||
ip: payload.ip ?? "",
|
||||
initialPlan: payload.initialPlan ?? row.title,
|
||||
title: row.title,
|
||||
projectId: row.projectId ?? undefined,
|
||||
history: safeParseJson<PlanningHistoryEntry[]>(
|
||||
row.conversationHistory,
|
||||
@@ -721,6 +723,7 @@ export async function createSession(
|
||||
id: sessionId,
|
||||
ip,
|
||||
initialPlan,
|
||||
title: initialPlan.slice(0, 120),
|
||||
history: [],
|
||||
thinkingOutput: "",
|
||||
lastGeneratedThinking: "",
|
||||
@@ -870,6 +873,75 @@ async function getFirstQuestionFromAgent(
|
||||
return parsed.data;
|
||||
}
|
||||
|
||||
export async function createDraftSession(
|
||||
ip: string,
|
||||
initialPlan: string,
|
||||
rootDir: string,
|
||||
modelProvider?: string,
|
||||
modelId?: string,
|
||||
_promptOverrides?: PromptOverrideMap,
|
||||
options?: { projectId?: string },
|
||||
): Promise<{ sessionId: string; title: string }> {
|
||||
if (!checkRateLimit(ip)) {
|
||||
const resetTime = getRateLimitResetTime(ip);
|
||||
throw new RateLimitError(
|
||||
`Rate limit exceeded. Maximum ${MAX_SESSIONS_PER_IP_PER_HOUR} planning sessions per hour. ` +
|
||||
`Reset at ${resetTime?.toISOString() || "unknown"}`,
|
||||
);
|
||||
}
|
||||
|
||||
const sessionId = randomUUID();
|
||||
const title = initialPlan.slice(0, 120);
|
||||
|
||||
const session: Session = {
|
||||
id: sessionId,
|
||||
ip,
|
||||
initialPlan,
|
||||
title,
|
||||
projectId: options?.projectId,
|
||||
history: [],
|
||||
thinkingOutput: "",
|
||||
lastGeneratedThinking: "",
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
};
|
||||
|
||||
sessions.set(sessionId, session);
|
||||
persistSession(session, "draft");
|
||||
|
||||
void (async () => {
|
||||
try {
|
||||
const generated = await summarizeTitle(initialPlan.trim(), rootDir, modelProvider, modelId);
|
||||
const finalTitle = generated ?? initialPlan.trim().slice(0, 60).trim();
|
||||
if (!finalTitle) {
|
||||
return;
|
||||
}
|
||||
session.title = finalTitle;
|
||||
_aiSessionStore?.updateTitle(sessionId, finalTitle);
|
||||
} catch {
|
||||
// Keep fallback title
|
||||
}
|
||||
})();
|
||||
|
||||
return { sessionId, title };
|
||||
}
|
||||
|
||||
export async function startExistingSession(
|
||||
sessionId: string,
|
||||
rootDir: string,
|
||||
modelProvider?: string,
|
||||
modelId?: string,
|
||||
promptOverrides?: PromptOverrideMap,
|
||||
): Promise<void> {
|
||||
const session = sessions.get(sessionId);
|
||||
if (!session) {
|
||||
throw new SessionNotFoundError(`Planning session ${sessionId} not found or expired`);
|
||||
}
|
||||
|
||||
persistSession(session, "generating");
|
||||
await initializeAgent(session, rootDir, modelProvider, modelId, promptOverrides);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new planning session with AI agent streaming.
|
||||
* This initializes an AI agent that will stream thinking output via SSE.
|
||||
@@ -911,6 +983,7 @@ export async function createSessionWithAgent(
|
||||
id: sessionId,
|
||||
ip,
|
||||
initialPlan,
|
||||
title: initialPlan.slice(0, 120),
|
||||
projectId: options?.projectId,
|
||||
ntfyConfig: options?.ntfyConfig
|
||||
? {
|
||||
|
||||
@@ -443,6 +443,58 @@ export function registerPlanningSubtaskRoutes(ctx: ApiRoutesContext, deps: Plann
|
||||
}
|
||||
});
|
||||
|
||||
router.post("/planning/create-draft", async (req, res) => {
|
||||
try {
|
||||
const { initialPlan, planningModelProvider, planningModelId } = req.body;
|
||||
|
||||
if (!initialPlan || typeof initialPlan !== "string" || initialPlan.trim().length === 0) {
|
||||
throw badRequest("initialPlan is required and must be a string");
|
||||
}
|
||||
|
||||
if (planningModelProvider !== undefined && typeof planningModelProvider !== "string") {
|
||||
throw badRequest("planningModelProvider must be a string when provided");
|
||||
}
|
||||
|
||||
if (planningModelId !== undefined && typeof planningModelId !== "string") {
|
||||
throw badRequest("planningModelId must be a string when provided");
|
||||
}
|
||||
|
||||
const { store: scopedStore, projectId } = await getProjectContext(req);
|
||||
const settings = await scopedStore.getSettings();
|
||||
const ip = req.ip || req.socket.remoteAddress || "unknown";
|
||||
const rootDir = scopedStore.getRootDir();
|
||||
|
||||
const resolvedPlanningSettings = resolvePlanningSettingsModel(settings);
|
||||
const resolvedPlanningProvider =
|
||||
(planningModelProvider && planningModelId ? planningModelProvider : undefined) ||
|
||||
resolvedPlanningSettings.provider;
|
||||
|
||||
const resolvedPlanningModelId =
|
||||
(planningModelProvider && planningModelId ? planningModelId : undefined) ||
|
||||
resolvedPlanningSettings.modelId;
|
||||
|
||||
const { createDraftSession } = await import("../planning.js");
|
||||
const draft = await createDraftSession(
|
||||
ip,
|
||||
initialPlan,
|
||||
rootDir,
|
||||
resolvedPlanningProvider,
|
||||
resolvedPlanningModelId,
|
||||
settings.promptOverrides,
|
||||
{ projectId },
|
||||
);
|
||||
res.status(201).json(draft);
|
||||
} catch (err: unknown) {
|
||||
if (err instanceof ApiError) {
|
||||
throw err;
|
||||
}
|
||||
if (err instanceof Error && err.name === "RateLimitError") {
|
||||
throw rateLimited(err.message);
|
||||
}
|
||||
rethrowAsApiError(err, "Failed to create planning draft");
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* POST /api/planning/start-streaming
|
||||
* Start a new planning session with AI agent streaming.
|
||||
@@ -462,6 +514,7 @@ export function registerPlanningSubtaskRoutes(ctx: ApiRoutesContext, deps: Plann
|
||||
planningModelId,
|
||||
planningDepth,
|
||||
customQuestionCount,
|
||||
existingSessionId,
|
||||
} = req.body;
|
||||
|
||||
if (!initialPlan || typeof initialPlan !== "string") {
|
||||
@@ -492,6 +545,10 @@ export function registerPlanningSubtaskRoutes(ctx: ApiRoutesContext, deps: Plann
|
||||
throw badRequest("customQuestionCount must be an integer between 1 and 20 when provided");
|
||||
}
|
||||
|
||||
if (existingSessionId !== undefined && typeof existingSessionId !== "string") {
|
||||
throw badRequest("existingSessionId must be a string when provided");
|
||||
}
|
||||
|
||||
const { store: scopedStore, projectId } = await getProjectContext(req);
|
||||
const settings = await scopedStore.getSettings();
|
||||
const ip = req.ip || req.socket.remoteAddress || "unknown";
|
||||
@@ -511,6 +568,19 @@ export function registerPlanningSubtaskRoutes(ctx: ApiRoutesContext, deps: Plann
|
||||
(planningModelProvider && planningModelId ? planningModelId : undefined) ||
|
||||
resolvedPlanningSettings.modelId;
|
||||
|
||||
if (existingSessionId) {
|
||||
const { startExistingSession } = await import("../planning.js");
|
||||
await startExistingSession(
|
||||
existingSessionId,
|
||||
rootDir,
|
||||
resolvedPlanningProvider,
|
||||
resolvedPlanningModelId,
|
||||
settings.promptOverrides,
|
||||
);
|
||||
res.status(201).json({ sessionId: existingSessionId });
|
||||
return;
|
||||
}
|
||||
|
||||
const { createSessionWithAgent, RateLimitError: _RateLimitError2 } = await import("../planning.js");
|
||||
const sessionId = await createSessionWithAgent(
|
||||
ip,
|
||||
|
||||
Reference in New Issue
Block a user