From 2dafe938f41edbb8ceb7c6a3655c9533bb50e47d Mon Sep 17 00:00:00 2001 From: soryu Date: Thu, 30 Apr 2026 15:48:26 +0100 Subject: fix(doc-mode): autosave robustness, draft→active flip, save-now, sidebar context menus (#108) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Stage 1 of the planned doc-mode revamp — bug fixes + UX polish ahead of the larger contract-revisioning architecture work. ## Backend: 'draft' included in goal-update status flip repository::update_directive_goal previously flipped only idle/paused → active on a goal save, leaving 'draft' alone. That meant brand-new directives got their goal persisted on save but never spawned a planner — exactly the "orchestrator never runs" report. Extended the CASE clause so 'draft' also flips to 'active' on save. The status remains visible to users; this just makes the implicit "first goal save = start" behaviour work end-to-end. ## Autosave robustness (DocumentEditor.tsx) The synchronous-write fix from the previous PR was correct in principle but not visible enough for users to confirm it was working, and could still drop the very last edit on an abrupt tab close. This change: - Adds beforeunload / pagehide / visibilitychange handlers that synchronously flush pendingGoalRef → localStorage (skipping if it matches the persisted value). Backed by a persistedGoalRef that tracks directive.goal in real time so the handler doesn't capture a stale closure. - Tracks the timestamp of every successful draft write (draftSavedAt) and surfaces it as a "Draft saved Ns ago" stamp in the bar — refreshed on a 1Hz ticker so users can SEE the autosave is alive. - Logs a console.warn on localStorage write failure (was silently swallowed) so quota / storage-disabled environments are diagnosable. ## Always-visible save bar + Save now button The bar now renders in every state (was hiding when idle/pending-with-time- remaining). Idle shows a quiet "Up to date." Pending outside the last 10s shows "Unsaved changes — auto-save soon." Save now is always present; disabled only when truly idle. ## EXEC and CONTRACTS hidden in document mode NavStrip filters Contracts and Exec links when settings.documentModeEnabled is true. Those areas are subsumed by the directive-document interface; the nav strip stops surfacing them so document mode users have one canonical place to work. ## Right-click context menus on sidebar Right-clicking a directive folder header opens DirectiveContextMenu with start / pause / archive / delete / Go-to-PR — same component the legacy list page uses. Right-clicking a task row inside the tasks/ subfolder opens a smaller TaskContextMenu with Interrupt (for orchestrator/completion/ running steps) and Mark complete / failed / skipped (for step rows). Step lifecycle calls require the directive_step.id, so FolderTaskRow now carries stepId alongside taskId. Co-authored-by: Claude Opus 4.7 (1M context) --- makima/frontend/src/components/NavStrip.tsx | 27 +- .../src/components/directives/DocumentEditor.tsx | 152 ++++++++--- makima/frontend/src/routes/document-directives.tsx | 286 ++++++++++++++++++++- makima/src/db/repository.rs | 10 +- 4 files changed, 435 insertions(+), 40 deletions(-) diff --git a/makima/frontend/src/components/NavStrip.tsx b/makima/frontend/src/components/NavStrip.tsx index 17013ac..a6e483d 100644 --- a/makima/frontend/src/components/NavStrip.tsx +++ b/makima/frontend/src/components/NavStrip.tsx @@ -1,5 +1,6 @@ import { useAuth } from "../contexts/AuthContext"; import { useSupervisorQuestions } from "../contexts/SupervisorQuestionsContext"; +import { useUserSettings } from "../hooks/useUserSettings"; import { RewriteLink } from "./RewriteLink"; interface NavLink { @@ -7,14 +8,30 @@ interface NavLink { href: string; requiresAuth?: boolean; external?: boolean; + /** + * When true the link is hidden once the user has flipped on the + * document-mode UI — those areas (Exec, Contracts) are subsumed by the + * directive-document interface and surfacing them just creates noise. + */ + hideInDocumentMode?: boolean; } const NAV_LINKS: NavLink[] = [ { label: "Listen", href: "/listen" }, { label: "Directives", href: "/directives", requiresAuth: true }, { label: "Orders", href: "/orders", requiresAuth: true }, - { label: "Contracts", href: "/contracts", requiresAuth: true }, - { label: "Exec", href: "/exec", requiresAuth: true }, + { + label: "Contracts", + href: "/contracts", + requiresAuth: true, + hideInDocumentMode: true, + }, + { + label: "Exec", + href: "/exec", + requiresAuth: true, + hideInDocumentMode: true, + }, { label: "Daemons", href: "/daemons", requiresAuth: true }, { label: "History", href: "/history", requiresAuth: true }, ]; @@ -22,6 +39,8 @@ const NAV_LINKS: NavLink[] = [ export function NavStrip() { const { isAuthenticated, isAuthConfigured, signOut, user } = useAuth(); const { pendingQuestions } = useSupervisorQuestions(); + const { settings } = useUserSettings(); + const documentMode = settings?.documentModeEnabled ?? false; const directiveQuestionCount = pendingQuestions.filter(q => q.directiveId).length; const handleSignOut = async () => { @@ -41,7 +60,9 @@ export function NavStrip() { NAV//
- {NAV_LINKS.map((link) => ( + {NAV_LINKS.filter( + (link) => !(documentMode && link.hideInDocumentMode), + ).map((link) => ( Date.now()); + useEffect(() => { + const id = window.setInterval(() => setNow(Date.now()), 1000); + return () => window.clearInterval(id); + }, []); + if (draftSavedAt == null) return null; + const ageSec = Math.max(0, Math.floor((now - draftSavedAt) / 1000)); + if (ageSec > 60) return null; + if (ageSec < 2) return "Draft saved"; + return `Draft saved ${ageSec}s ago`; +} + // ============================================================================= // Floating formatting toolbar // @@ -669,6 +686,7 @@ interface SaveCountdownBarProps { remainingMs: number; liveStart: boolean; orchestratorRunning: boolean; + draftSavedAt: number | null; onSaveNow: () => void; onCancel: () => void; onToggleLiveStart: (next: boolean) => void; @@ -679,22 +697,14 @@ function SaveCountdownBar({ remainingMs, liveStart, orchestratorRunning, + draftSavedAt, onSaveNow, onCancel, onToggleLiveStart, }: SaveCountdownBarProps) { - // Visibility rules: - // - Always show when actually saving / saved / error (transient feedback). - // - Show when "dirty" if live-start is OFF (user must trigger save). - // - Show when "pending" only inside the last BAR_VISIBLE_MS so the user - // does not feel rushed during the long fresh countdown. - const visible = - state === "saving" || - state === "saved" || - state === "error" || - (state === "dirty" && !liveStart) || - (state === "pending" && remainingMs <= BAR_VISIBLE_MS); - if (!visible) return null; + // The bar is now ALWAYS visible. Users explicitly asked to be able to + // observe save state at all times — and to have a "Save now" button they + // can hit without waiting for the countdown. let label: string; let progressPct = 0; @@ -702,13 +712,19 @@ function SaveCountdownBar({ if (state === "pending") { const seconds = Math.max(0, Math.ceil(remainingMs / 1000)); - label = orchestratorRunning - ? `Replanning in ${seconds}s — Esc/Undo cancels.` - : `Saving goal in ${seconds}s — Esc/Undo cancels.`; - progressPct = Math.max( - 0, - Math.min(100, (1 - remainingMs / BAR_VISIBLE_MS) * 100), - ); + // Show ticking countdown in the last 10s, otherwise a quieter label. + if (remainingMs <= BAR_VISIBLE_MS) { + label = orchestratorRunning + ? `Replanning in ${seconds}s — Esc/Undo cancels.` + : `Saving in ${seconds}s — Esc/Undo cancels.`; + progressPct = Math.max( + 0, + Math.min(100, (1 - remainingMs / BAR_VISIBLE_MS) * 100), + ); + } else { + label = "Unsaved changes — auto-save soon."; + progressPct = 0; + } } else if (state === "dirty") { label = orchestratorRunning ? "Unsaved changes — saving will replan the directive." @@ -722,12 +738,23 @@ function SaveCountdownBar({ label = "Saved"; progressPct = 100; tone = "border-emerald-700 text-emerald-300"; - } else { + } else if (state === "error") { label = "Save failed — try again."; progressPct = 100; tone = "border-red-700 text-red-300"; + } else { + label = "Up to date."; + progressPct = 0; + tone = "border-[rgba(117,170,252,0.2)] text-[#7788aa]"; } + // Right-side "Draft saved Xs ago" stamp — re-renders on a 1Hz ticker so + // the user can see drafts being captured. We only ever surface this when + // a write has happened in the last minute; otherwise we hide it. + const draftLabel = useDraftFreshnessLabel(draftSavedAt); + + const dirtyish = state === "dirty" || state === "pending"; + return (
{label} + {draftLabel && ( + + {draftLabel} + + )} + {/* Live-start toggle is always shown so users can flip it from the bar. */} - {(state === "dirty" || state === "pending") && ( - - )} - {(state === "dirty" || state === "pending") && ( + {/* "Save now" is always available when there are unsaved edits, so + users don't have to wait for the auto-save countdown. */} + + {dirtyish && ( + )} + {(showComplete || showFail || showSkip) &&
} + {showComplete && ( + + )} + {showFail && ( + + )} + {showSkip && ( + + )} +
+ ); +} + function slugify(title: string, fallback: string): string { const slug = title .trim() @@ -196,6 +335,8 @@ function DirectiveFolder({ onSelect, pendingTaskIds, hasPendingForDirective, + onDirectiveContextMenu, + onTaskContextMenu, }: { directive: DirectiveSummary; open: boolean; @@ -206,6 +347,8 @@ function DirectiveFolder({ pendingTaskIds: Set; /** Whether any pending question is associated with this directive. */ hasPendingForDirective: boolean; + onDirectiveContextMenu: (e: React.MouseEvent, d: DirectiveSummary) => void; + onTaskContextMenu: (e: React.MouseEvent, t: FolderTaskRow, directiveId: string) => void; }) { const dotColor = STATUS_DOT[directive.status] ?? STATUS_DOT.draft; const fileName = `${slugify(directive.title, directive.id.slice(0, 8))}.md`; @@ -228,6 +371,7 @@ function DirectiveFolder({
); } diff --git a/makima/src/db/repository.rs b/makima/src/db/repository.rs index ca07d92..cec9a82 100644 --- a/makima/src/db/repository.rs +++ b/makima/src/db/repository.rs @@ -5625,8 +5625,12 @@ pub async fn check_directive_idle( } /// Update a directive's goal and bump goal_updated_at. -/// Reactivates idle/paused directives and clears any stale orchestrator task -/// so that replanning triggers on the next tick. +/// Reactivates draft/idle/paused directives and clears any stale orchestrator +/// task so that planning/replanning triggers on the next reconciler tick. +/// +/// `draft` is included in the flip set because the document-mode UI treats +/// the first goal save as the implicit "start" — without this, a brand-new +/// directive's goal save would persist but never spawn a planner. pub async fn update_directive_goal( pool: &PgPool, owner_id: Uuid, @@ -5638,7 +5642,7 @@ pub async fn update_directive_goal( UPDATE directives SET goal = $3, goal_updated_at = NOW(), - status = CASE WHEN status IN ('idle', 'paused') THEN 'active' ELSE status END, + status = CASE WHEN status IN ('draft', 'idle', 'paused') THEN 'active' ELSE status END, orchestrator_task_id = NULL, updated_at = NOW(), version = version + 1 -- cgit v1.2.3