fix(dashboard): stop Planning Mode retry loop, make AI sessions multi-tab (#2101)
## Problem Reported: planning gets stuck in a cycle of retrying and regenerating after a response was already supplied. After the user answers a planning question, `submitResponse` pushed the answer to history but left `session.currentQuestion` pointing at the just-answered question for the whole next generation. The planning SSE route's catch-up path re-emits `currentQuestion` to every fresh connection — and each FN-7946 auto-retry (#2073) opens a fresh connection. So after any generation error: 1. Auto-retry connects a fresh stream → the server re-emits the **already-answered** question. 2. The client treats any question event as progress: it **resets the 3-attempt auto-retry budget** and re-shows the answered question. 3. The retry regenerates; if it errors again the cycle repeats with a fresh budget — an unbounded retry/regenerate loop. Re-answering the stale question also 409-collided with the in-flight generation, feeding the same loop. ## Fix Invariant: `currentQuestion` is only set while the session is genuinely awaiting user input. - `submitResponse` clears it the moment an answer is accepted (normal turns and the deepening checkpoint), while preserving the legacy 200 respond contract on generation failure (the modal ignores the body and lets the SSE error drive recovery). - `retrySession` scrubs stale questions persisted by pre-fix builds before regenerating. - `buildSessionFromRow` only restores a question when the persisted row is `awaiting_input`. - `didSubmitSameAnswer` now compares against the last history entry so the duplicate-submit 409 message survives. - Agent onboarding gets the same fix (its SSE route also re-emits `currentQuestion` on connect); retry now asks the next question instead of re-asking the answered one. Surface enumeration: mission and milestone interviews keep questions the same way but their SSE routes never re-emit on connect, and the auto-retry budget machinery is Planning-Mode-only — planning + onboarding were the two affected surfaces. ## Symptom Verification - **Original symptom:** after answering a question, Planning Mode loops between "Retrying…" and regenerating, re-showing the already-answered question, with the auto-retry budget never exhausting. - **Exact reproduction:** answer a question, have the next generation fail (stuck watchdog/provider error), let the client auto-retry open a fresh SSE connection. - **Assertion it is gone:** new regression suite `planning-answered-question-reemit.test.ts` asserts `currentQuestion` is cleared mid-generation, on generation failure, on retry, and on restore from non-`awaiting_input` rows — so the SSE catch-up path has nothing stale to re-emit. All 5 tests fail against pre-fix code and pass with the fix; an onboarding regression test covers the sibling surface. ## Verification - New regression tests: 5/5 fail on pre-fix code, pass with the fix (plus 1 onboarding test). - Existing suites: 137 planning server tests pass (3 failures in `routes-planning.test.ts` fail identically without this change — pre-existing on the branch); all 69 `PlanningModeModal.planning-flow` client tests pass; `tsc --noEmit` clean; `pnpm check:changesets` passes. 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Made Planning Mode (and related planning controls) lock-free and multi-tab—no more take-over/active-in-another-tab lock overlays. * **Bug Fixes** * Fixed Planning Mode retry/generation flows where already-answered questions could reappear. * Ensured answered questions clear immediately and aren’t re-emitted during session recovery/SSE catch-up. * Improved session restoration and preserved legacy recovery behavior when generation fails after an answer. * **Tests** * Added regression coverage for the answered-question invariant and updated existing tests to reflect lock-free behavior. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --- ## Follow-up: Planning Mode is now multi-tab via DB state (lock-free) Second commit removes all cross-tab coordination from planning — the persisted session row is the single source of truth and multiple tabs can read and interact with the same session: - **Server:** `/planning/*` routes no longer run `checkSessionLock` or parse `tabId`; a stale `tabId` from an older client is ignored instead of 409'd. Subtask/mission interview routes keep their existing lock behavior. - **Client:** `PlanningModeModal` drops `useSessionLock`, the `useAiSessionSync` BroadcastChannel broadcasts, `sessionTabId`/`lockSessionId` state, and the "Take Control" overlay. Tabs stay current via the per-session SSE stream plus the global `ai_session:updated` events `useBackgroundSessions` already consumes; concurrent writes resolve via the server's generation-in-progress guard (409). - **API client:** planning functions lose their `tabId` params. - **Fix uncovered by the refactor:** the 8s stuck-poll now resolves the session id inside each tick — the removed lock state was what previously re-armed the poll after Start Planning resolved the session id. - Also fixes a pre-existing PG-cutover break in `planning-generation-cancellation.test.ts` (`getSession` is async). Verification: 144 client planning tests and 137 server planning tests pass (the 3 remaining `routes-planning.test.ts` failures are pre-existing on the branch and fail identically without these changes); `tsc --noEmit` and eslint clean on changed files; `pnpm check:changesets` passes. Lock-conflict route tests were rewritten to assert lock-free semantics, plus a new modal test proving a session stays fully interactive with no lock acquisition even when another tab is active. --- ## Follow-up 2: the per-tab session lock is gone entirely Third commit extends the multi-tab model from planning to **every** AI interview surface (planning, subtask breakdown, mission interview, milestone/slice interview) and deletes the lock machinery root and branch. **Server** - Deleted the `/ai-sessions/:id/lock`, `/lock/force`, and `/lock/beacon` routes. - Dropped `checkSessionLock` from every planning/subtask/mission/milestone route (both copies — `routes.ts` and `mission-routes.ts`). A `tabId` from an older client is ignored, never 409'd; all `tabId` body parsing is gone. - Dropped `acquireLock` / `releaseLock` / `forceAcquireLock` / `getLockHolder` / `releaseStaleLocks` from `AiSessionStore`, plus the `@fusion/core` async helpers (`acquireAiSessionLock` et al) and core's re-exports. - Removed `lockedByTab`/`lockedAt` from `AiSessionRow`/`AiSessionSummary`, the upsert SQL, and all four session producers. **Client** - Deleted `useSessionLock` and the now-orphaned `getSessionTabId` util. - Removed the Take Control overlay, the "active in another tab" banners, and `BackgroundTasksIndicator`'s active-elsewhere gate (the confirm prompt and lock badge — sessions now just open). - Reduced `useAiSessionSync` to what its own comments already called it — a low-latency *status* supplement to SSE: no `activeTabMap`, `broadcastLock/Unlock/Heartbeat`, `owningTabId`, `tab:*` messages, or stale-heartbeat sweep. - Dropped `tabId` from every session API client function; removed the lock CSS. **Deliberately kept: the two DB columns.** `ai_sessions.locked_by_tab` / `locked_at` remain as dead, always-NULL columns with a deprecation note. Dropping them is an irreversible migration, and released binaries still name those columns explicitly in their upsert — an older install pointed at the same database would fail every session write. They can be dropped once no such binary can reach it. No code reads or writes them. **Verification**: 397 client tests and 137 server planning tests pass (the same 3 `routes-planning.test.ts` failures are pre-existing — verified identical on a clean stash); `tsc --noEmit` clean for `@fusion/core` and `@fusion/dashboard`; eslint clean on all changed files; the 30 PG `schema-applier` tests pass (they exercise the retained columns); `pnpm check:changesets` passes. The lock-conflict route tests and both modal lock tests were rewritten to assert the inverse: routes and modals stay fully interactive while another tab "holds" a lock, and the lock API is never called. --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
@@ -4087,11 +4087,10 @@ export function respondToPlanning(
|
||||
sessionId: string,
|
||||
responses: Record<string, unknown>,
|
||||
projectId?: string,
|
||||
tabId?: string,
|
||||
): Promise<PlanningSession> {
|
||||
return api<PlanningSession>(withProjectId("/planning/respond", projectId), {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ sessionId, responses, tabId }),
|
||||
body: JSON.stringify({ sessionId, responses }),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -4099,13 +4098,11 @@ export function respondToPlanning(
|
||||
export function rewindPlanningSession(
|
||||
sessionId: string,
|
||||
projectId?: string,
|
||||
tabId?: string,
|
||||
): Promise<{ currentQuestion: PlanningQuestion; history: Array<{ question: PlanningQuestion; response: unknown; thinkingOutput?: string }> }> {
|
||||
return api<{ currentQuestion: PlanningQuestion; history: Array<{ question: PlanningQuestion; response: unknown; thinkingOutput?: string }> }>(
|
||||
withProjectId(`/planning/${encodeURIComponent(sessionId)}/back`, projectId),
|
||||
{
|
||||
method: "POST",
|
||||
...(tabId ? { body: JSON.stringify({ tabId }) } : {}),
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -4114,13 +4111,11 @@ export function rewindPlanningSession(
|
||||
export function retryPlanningSession(
|
||||
sessionId: string,
|
||||
projectId?: string,
|
||||
tabId?: string,
|
||||
): Promise<{ success: boolean; sessionId: string }> {
|
||||
return api<{ success: boolean; sessionId: string }>(
|
||||
withProjectId(`/planning/${encodeURIComponent(sessionId)}/retry`, projectId),
|
||||
{
|
||||
method: "POST",
|
||||
...(tabId ? { body: JSON.stringify({ tabId }) } : {}),
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -4129,22 +4124,20 @@ export function retryPlanningSession(
|
||||
export function stopPlanningGeneration(
|
||||
sessionId: string,
|
||||
projectId?: string,
|
||||
tabId?: string,
|
||||
): Promise<{ success: boolean }> {
|
||||
return api<{ success: boolean }>(
|
||||
withProjectId(`/planning/${encodeURIComponent(sessionId)}/stop`, projectId),
|
||||
{
|
||||
method: "POST",
|
||||
...(tabId ? { body: JSON.stringify({ tabId }) } : {}),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/** Cancel an active planning session */
|
||||
export function cancelPlanning(sessionId: string, projectId?: string, tabId?: string): Promise<void> {
|
||||
export function cancelPlanning(sessionId: string, projectId?: string): Promise<void> {
|
||||
return api<void>(withProjectId("/planning/cancel", projectId), {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ sessionId, tabId }),
|
||||
body: JSON.stringify({ sessionId }),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -6186,14 +6179,10 @@ export function startSubtaskBreakdown(description: string, projectId?: string):
|
||||
export function retrySubtaskSession(
|
||||
sessionId: string,
|
||||
projectId?: string,
|
||||
tabId?: string,
|
||||
): Promise<{ success: boolean; sessionId: string }> {
|
||||
return api<{ success: boolean; sessionId: string }>(
|
||||
withProjectId(`/subtasks/${encodeURIComponent(sessionId)}/retry`, projectId),
|
||||
{
|
||||
method: "POST",
|
||||
...(tabId ? { body: JSON.stringify({ tabId }) } : {}),
|
||||
},
|
||||
{ method: "POST" },
|
||||
);
|
||||
}
|
||||
|
||||
@@ -6318,10 +6307,10 @@ export function createTasksFromBreakdown(
|
||||
});
|
||||
}
|
||||
|
||||
export function cancelSubtaskBreakdown(sessionId: string, projectId?: string, tabId?: string): Promise<void> {
|
||||
export function cancelSubtaskBreakdown(sessionId: string, projectId?: string): Promise<void> {
|
||||
return api<void>(withProjectId("/subtasks/cancel", projectId), {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ sessionId, tabId }),
|
||||
body: JSON.stringify({ sessionId }),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -8833,11 +8822,10 @@ export function respondToMissionInterview(
|
||||
sessionId: string,
|
||||
responses: Record<string, unknown>,
|
||||
projectId?: string,
|
||||
tabId?: string,
|
||||
): Promise<MissionInterviewResponse> {
|
||||
return api<MissionInterviewResponse>(withProjectId("/missions/interview/respond", projectId), {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ sessionId, responses, tabId }),
|
||||
body: JSON.stringify({ sessionId, responses }),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -8845,22 +8833,18 @@ export function respondToMissionInterview(
|
||||
export function retryMissionInterviewSession(
|
||||
sessionId: string,
|
||||
projectId?: string,
|
||||
tabId?: string,
|
||||
): Promise<{ success: boolean; sessionId: string }> {
|
||||
return api<{ success: boolean; sessionId: string }>(
|
||||
withProjectId(`/missions/interview/${encodeURIComponent(sessionId)}/retry`, projectId),
|
||||
{
|
||||
method: "POST",
|
||||
...(tabId ? { body: JSON.stringify({ tabId }) } : {}),
|
||||
},
|
||||
{ method: "POST" },
|
||||
);
|
||||
}
|
||||
|
||||
/** Cancel an active mission interview session */
|
||||
export function cancelMissionInterview(sessionId: string, projectId?: string, tabId?: string): Promise<void> {
|
||||
export function cancelMissionInterview(sessionId: string, projectId?: string): Promise<void> {
|
||||
return api<void>(withProjectId("/missions/interview/cancel", projectId), {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ sessionId, tabId }),
|
||||
body: JSON.stringify({ sessionId }),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -8873,14 +8857,10 @@ export async function fetchMissionInterviewDrafts(projectId?: string): Promise<M
|
||||
export function discardMissionInterviewDraft(
|
||||
sessionId: string,
|
||||
projectId?: string,
|
||||
tabId?: string,
|
||||
): Promise<{ removed: boolean }> {
|
||||
return api<{ removed: boolean }>(
|
||||
withProjectId(`/missions/interview/drafts/${encodeURIComponent(sessionId)}/discard`, projectId),
|
||||
{
|
||||
method: "POST",
|
||||
body: JSON.stringify({ tabId }),
|
||||
},
|
||||
{ method: "POST" },
|
||||
);
|
||||
}
|
||||
|
||||
@@ -9090,11 +9070,10 @@ export function respondToMilestoneInterview(
|
||||
sessionId: string,
|
||||
responses: Record<string, unknown>,
|
||||
projectId?: string,
|
||||
tabId?: string,
|
||||
): Promise<TargetInterviewResponse> {
|
||||
return api<TargetInterviewResponse>(buildMilestoneInterviewUrl(sessionId, "/respond", projectId), {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ sessionId, responses, tabId }),
|
||||
body: JSON.stringify({ sessionId, responses }),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -9226,11 +9205,10 @@ export function respondToSliceInterview(
|
||||
sessionId: string,
|
||||
responses: Record<string, unknown>,
|
||||
projectId?: string,
|
||||
tabId?: string,
|
||||
): Promise<TargetInterviewResponse> {
|
||||
return api<TargetInterviewResponse>(buildSliceInterviewUrl(sessionId, "/respond", projectId), {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ sessionId, responses, tabId }),
|
||||
body: JSON.stringify({ sessionId, responses }),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -9470,7 +9448,6 @@ export interface AiSessionSummary {
|
||||
/** Server-derived preview of the in-progress initialPlan; only set for draft planning sessions. */
|
||||
preview?: string;
|
||||
projectId: string | null;
|
||||
lockedByTab: string | null;
|
||||
updatedAt: string;
|
||||
archived?: boolean;
|
||||
}
|
||||
@@ -9489,7 +9466,6 @@ export interface AiSessionDetail extends AiSessionSummary {
|
||||
thinkingOutput: string;
|
||||
error: string | null;
|
||||
createdAt: string;
|
||||
lockedAt: string | null;
|
||||
}
|
||||
|
||||
export function parseConversationHistory(raw: string): ConversationHistoryEntry[] {
|
||||
@@ -9540,37 +9516,12 @@ export async function fetchAiSession(id: string): Promise<AiSessionDetail | null
|
||||
return res.json();
|
||||
}
|
||||
|
||||
export async function acquireSessionLock(
|
||||
sessionId: string,
|
||||
tabId: string,
|
||||
): Promise<{ acquired: boolean; currentHolder: string | null }> {
|
||||
const result = await api<{ acquired: boolean; currentHolder?: string | null }>(
|
||||
`/ai-sessions/${encodeURIComponent(sessionId)}/lock`,
|
||||
{
|
||||
method: "POST",
|
||||
body: JSON.stringify({ tabId }),
|
||||
},
|
||||
);
|
||||
|
||||
return {
|
||||
acquired: result.acquired,
|
||||
currentHolder: result.currentHolder ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
export function releaseSessionLock(sessionId: string, tabId: string): Promise<void> {
|
||||
return api<void>(`/ai-sessions/${encodeURIComponent(sessionId)}/lock`, {
|
||||
method: "DELETE",
|
||||
body: JSON.stringify({ tabId }),
|
||||
});
|
||||
}
|
||||
|
||||
export function forceAcquireSessionLock(sessionId: string, tabId: string): Promise<void> {
|
||||
return api<void>(`/ai-sessions/${encodeURIComponent(sessionId)}/lock/force`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ tabId }),
|
||||
});
|
||||
}
|
||||
/*
|
||||
FNXC:PlanningMultiTab 2026-07-14-00:00:
|
||||
acquireSessionLock / releaseSessionLock / forceAcquireSessionLock were removed with the rest of
|
||||
the per-tab session lock; their routes no longer exist. AI interview sessions are multi-tab —
|
||||
the persisted session row is the shared source of truth and any tab may read and interact.
|
||||
*/
|
||||
|
||||
export async function deleteAiSession(id: string): Promise<void> {
|
||||
const url = buildApiUrl(`/ai-sessions/${encodeURIComponent(id)}`);
|
||||
|
||||
Reference in New Issue
Block a user