From 80085c7cfa9d679ed3e3fd54a7d55fa8ab1addef Mon Sep 17 00:00:00 2001 From: soryu Date: Fri, 1 May 2026 18:06:38 +0100 Subject: feat(doc-mode): unified surface — ephemeral tasks, tmp/, /exec redirect, palette, SWR (#117) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Phases 1-3 of the unified-surface plan, bundled per the user's request. The directive document/folder UI is now the canonical place to interact with makima; legacy /exec is subsumed by routing redirects, /contracts is already hidden in nav, and orphan tasks surface under a top-level tmp/ pseudo-folder. Phase 4 (porting contract-only features) was confirmed out of scope; Phase 5 (deleting the contracts code) is a follow-up. ## Backend - New migration `20260501000000_archive_existing_contracts.sql` flips every legacy contract to `archived` so /contracts is read-only history. - New endpoint `POST /api/v1/directives/{id}/tasks` creates an ephemeral task — `directive_id` set, `directive_step_id` NULL, repo/branch inherited from the directive. Reuses `create_task_for_owner`. - New endpoint `GET /api/v1/directives/{id}/tasks` lists ephemeral tasks attached to a directive (drives the per-folder ephemeral group). - `GET /api/v1/mesh/tasks?orphan=true` returns top-level tasks with no `directive_id` AND no `parent_task_id` — backs the sidebar's tmp/. - New repo helpers `list_ephemeral_directive_tasks_for_owner` and `list_orphan_tasks_for_owner`. - The existing `mesh_merge` endpoints are reused as-is for ephemeral task merge (no new merge logic needed). ## Frontend ### Sticky composer + auto-scroll fix (`DocumentTaskStream.tsx`) - Sticky comment composer pinned to viewport bottom; padding compensates so the last entry isn't hidden behind it. - `autoScroll` now resumes when the user scrolls back within 80px of the bottom (previously stuck off forever after a single scroll-up). - Floating "↓ Jump to latest" chip when the user has scrolled away. - Action header strip: explicit Stop / Send / Open-in-task-page + conditional "Merge to base ↗" button on ephemeral terminal tasks. - Module-level cache of historical entries by taskId so re-selecting a task you've viewed renders instantly while a fresh fetch runs. ### Sidebar (`document-directives.tsx`) - Top-level `tmp/` folder: orphan tasks, polled every 5s. - Per-directive `tasks/` subfolder now also surfaces ephemeral tasks (lazily fetched on folder open) with a distinct asterisk-on-terminal icon (`EphemeralTaskIcon`). - Inline hover-action chips on each directive folder header: Start / Pause / PR / +New task. Right-click menu still works as a power-user fallback. - "Now executing" amber strip in the editor pane: surfaces the live orchestrator/completion/running-step task with a one-click jump. - Inline `+ New task` modal (name + plan); on submit calls `createDirectiveTask` and navigates into the freshly-spawned task. - New `EphemeralAwareTaskStream` wrapper passes `ephemeral` and `status` to `DocumentTaskStream` so the merge button only shows when the selected task is genuinely an ephemeral spinoff in a terminal state. Step-spawned tasks merge via the directive's PR completion. ### SWR cache (`useDirectives.ts`) - Module-level `listCache` and per-id `detailCache` (mirrors the pattern in `useUserSettings.ts`). Mounting the hook renders the cache value immediately if present and kicks a background refresh; subscribers see the new value when it lands. Cuts perceived navigation latency to near-zero on warm cache hits. ### QuickSwitcher (`QuickSwitcher.tsx`, new) - IntelliJ-style double-Shift command palette mounted at app root. - Listens at the document level for two `Shift` keydowns within 300ms with no other key in between; ignores while focus is in an input/textarea so capitalising letters doesn't pop the palette. - Searches across directives + their tasks (orchestrator/completion/ steps/ephemerals) + orphan tmp tasks. Fuzzy matches on title. - Eagerly loads task details for the first 20 directives on open so searches don't block on per-directive fetches. ### Routing (`main.tsx` + `exec-redirect.tsx` + `tmp.tsx`) - New `ExecRedirect` wrapper at `/exec/:id`: when documentMode is on AND the task has a `directiveId`, replaces the URL with `/directives/?task=`. Otherwise renders the legacy `MeshPage` as before. - New `/tmp/:taskId` route renders `DocumentTaskStream` standalone for orphan tasks, with the masthead and a `tmp / ` breadcrumb. Co-authored-by: Claude Opus 4.7 (1M context) --- makima/frontend/src/components/QuickSwitcher.tsx | 314 ++++++++++++ .../components/directives/DocumentTaskStream.tsx | 248 +++++++-- makima/frontend/src/hooks/useDirectives.ts | 178 ++++++- makima/frontend/src/lib/api.ts | 59 +++ makima/frontend/src/main.tsx | 14 +- makima/frontend/src/routes/document-directives.tsx | 555 ++++++++++++++++++++- makima/frontend/src/routes/exec-redirect.tsx | 59 +++ makima/frontend/src/routes/tmp.tsx | 93 ++++ .../20260501000000_archive_existing_contracts.sql | 18 + makima/src/db/repository.rs | 65 +++ makima/src/server/handlers/directives.rs | 161 ++++++ makima/src/server/handlers/mesh.rs | 25 +- makima/src/server/mod.rs | 4 + makima/src/server/openapi.rs | 3 + 14 files changed, 1705 insertions(+), 91 deletions(-) create mode 100644 makima/frontend/src/components/QuickSwitcher.tsx create mode 100644 makima/frontend/src/routes/exec-redirect.tsx create mode 100644 makima/frontend/src/routes/tmp.tsx create mode 100644 makima/migrations/20260501000000_archive_existing_contracts.sql diff --git a/makima/frontend/src/components/QuickSwitcher.tsx b/makima/frontend/src/components/QuickSwitcher.tsx new file mode 100644 index 0000000..8fe1d4a --- /dev/null +++ b/makima/frontend/src/components/QuickSwitcher.tsx @@ -0,0 +1,314 @@ +/** + * QuickSwitcher — IntelliJ-style "double Shift" command palette. + * + * Listens at the document level for two `Shift` keydowns within ~300ms with + * no other key in between. Single-Shift presses (capitalising letters etc.) + * are pass-through. The palette pulls directives + their tasks (orchestrator, + * completion, started steps, ephemerals) + orphan tasks, fuzzy-matches on + * the typed query, arrows navigate, Enter selects, Esc dismisses. + * + * The directive list comes straight from `useDirectives()` (now backed by + * the SWR cache) so the palette opens instantly when the cache is warm. + * Tasks per-directive are fetched eagerly into the cache when the palette + * opens so subsequent searches don't block on a network round-trip. + */ +import { useCallback, useEffect, useMemo, useRef, useState } from "react"; +import { useNavigate } from "react-router"; +import { useDirectives } from "../hooks/useDirectives"; +import { + getDirective, + listDirectiveEphemeralTasks, + listOrphanTasks, + type DirectiveWithSteps, + type TaskSummary, +} from "../lib/api"; + +interface PaletteEntry { + id: string; + label: string; + /** Subtitle shown to the right (status, parent context). */ + hint: string; + /** Where to navigate on selection. */ + href: string; + kind: "directive" | "task" | "orphan"; +} + +const DOUBLE_SHIFT_WINDOW_MS = 300; + +export function QuickSwitcher() { + const navigate = useNavigate(); + const { directives } = useDirectives(); + const [open, setOpen] = useState(false); + const [query, setQuery] = useState(""); + const [activeIdx, setActiveIdx] = useState(0); + const inputRef = useRef(null); + + // ---- Double-shift detection ----------------------------------------------- + useEffect(() => { + let lastShift = 0; + let dirty = false; + const onKey = (e: KeyboardEvent) => { + if (e.key === "Shift") { + const now = Date.now(); + if (!dirty && now - lastShift < DOUBLE_SHIFT_WINDOW_MS) { + // Don't open if we're typing in an input — otherwise typing a + // capital letter via Shift triggers the palette unexpectedly. + const target = e.target as HTMLElement | null; + const tag = target?.tagName?.toUpperCase(); + const editable = target?.isContentEditable; + if ( + tag !== "INPUT" && + tag !== "TEXTAREA" && + tag !== "SELECT" && + !editable + ) { + setOpen(true); + setQuery(""); + setActiveIdx(0); + } + lastShift = 0; + } else { + lastShift = now; + dirty = false; + } + } else { + // Any other keydown invalidates the in-flight shift sequence. + dirty = true; + } + }; + document.addEventListener("keydown", onKey); + return () => document.removeEventListener("keydown", onKey); + }, []); + + // ---- Eager-load tasks per directive on open ------------------------------ + const [directiveTasks, setDirectiveTasks] = useState< + Map + >(new Map()); + const [orphanTasks, setOrphanTasks] = useState([]); + + useEffect(() => { + if (!open) return; + let cancelled = false; + // Orphan tasks + listOrphanTasks() + .then((res) => { + if (!cancelled) setOrphanTasks(res.tasks); + }) + .catch(() => { + /* swallow */ + }); + // Per-directive details + ephemeral tasks. We only fetch the first + // ~20 directives to keep the open-time bounded; the rest still appear + // in the palette (just without their tasks expanded). + const slice = directives.slice(0, 20); + Promise.all( + slice.map(async (d): Promise<[string, { detail: DirectiveWithSteps | null; ephemeral: TaskSummary[] }]> => { + try { + const [detail, ephRes] = await Promise.all([ + getDirective(d.id).catch(() => null), + listDirectiveEphemeralTasks(d.id).catch(() => ({ tasks: [] as TaskSummary[], total: 0 })), + ]); + return [d.id, { detail, ephemeral: ephRes.tasks }]; + } catch { + return [d.id, { detail: null, ephemeral: [] as TaskSummary[] }]; + } + }), + ).then((entries) => { + if (!cancelled) setDirectiveTasks(new Map(entries)); + }); + return () => { + cancelled = true; + }; + }, [open, directives]); + + // ---- Build the searchable entry list ------------------------------------- + const allEntries: PaletteEntry[] = useMemo(() => { + const out: PaletteEntry[] = []; + for (const d of directives) { + out.push({ + id: `dir:${d.id}`, + label: d.title, + hint: `contract · ${d.status}`, + href: `/directives/${d.id}`, + kind: "directive", + }); + const td = directiveTasks.get(d.id); + if (td) { + if (td.detail?.orchestratorTaskId) { + out.push({ + id: `task:${td.detail.orchestratorTaskId}`, + label: `${d.title} › orchestrator`, + hint: "task · running", + href: `/directives/${d.id}?task=${td.detail.orchestratorTaskId}`, + kind: "task", + }); + } + if (td.detail?.completionTaskId) { + out.push({ + id: `task:${td.detail.completionTaskId}`, + label: `${d.title} › completion`, + hint: "task · running", + href: `/directives/${d.id}?task=${td.detail.completionTaskId}`, + kind: "task", + }); + } + if (td.detail) { + for (const step of td.detail.steps) { + if (!step.taskId) continue; + out.push({ + id: `task:${step.taskId}`, + label: `${d.title} › ${step.name}`, + hint: `step · ${step.status}`, + href: `/directives/${d.id}?task=${step.taskId}`, + kind: "task", + }); + } + } + for (const t of td.ephemeral) { + out.push({ + id: `task:${t.id}`, + label: `${d.title} › ${t.name}`, + hint: `ephemeral · ${t.status}`, + href: `/directives/${d.id}?task=${t.id}`, + kind: "task", + }); + } + } + } + for (const t of orphanTasks) { + out.push({ + id: `orphan:${t.id}`, + label: t.name, + hint: `tmp · ${t.status}`, + href: `/tmp/${t.id}`, + kind: "orphan", + }); + } + return out; + }, [directives, directiveTasks, orphanTasks]); + + // ---- Fuzzy filter -------------------------------------------------------- + const filtered = useMemo(() => { + const q = query.trim().toLowerCase(); + if (!q) return allEntries.slice(0, 50); + return allEntries + .filter((e) => fuzzyContains(e.label.toLowerCase(), q)) + .slice(0, 50); + }, [allEntries, query]); + + useEffect(() => { + setActiveIdx(0); + }, [query]); + + useEffect(() => { + if (open) inputRef.current?.focus(); + }, [open]); + + const close = useCallback(() => setOpen(false), []); + const select = useCallback( + (entry: PaletteEntry) => { + navigate(entry.href); + setOpen(false); + }, + [navigate], + ); + + if (!open) return null; + + return ( +
+
e.stopPropagation()} + > + setQuery(e.target.value)} + onKeyDown={(e) => { + if (e.key === "Escape") { + close(); + } else if (e.key === "ArrowDown") { + e.preventDefault(); + setActiveIdx((i) => Math.min(i + 1, filtered.length - 1)); + } else if (e.key === "ArrowUp") { + e.preventDefault(); + setActiveIdx((i) => Math.max(i - 1, 0)); + } else if (e.key === "Enter") { + e.preventDefault(); + const entry = filtered[activeIdx]; + if (entry) select(entry); + } + }} + placeholder="Jump to a contract or task…" + className="bg-transparent border-b border-dashed border-[rgba(117,170,252,0.3)] px-4 py-3 text-[14px] text-white placeholder-[#445566] outline-none font-mono" + /> +
    + {filtered.length === 0 ? ( +
  • + No matches. +
  • + ) : ( + filtered.map((entry, idx) => ( +
  • setActiveIdx(idx)} + onClick={() => select(entry)} + className={`px-4 py-2 font-mono text-[12px] cursor-pointer flex items-center gap-3 ${ + idx === activeIdx + ? "bg-[rgba(117,170,252,0.15)] text-white" + : "text-[#dbe7ff] hover:bg-[rgba(117,170,252,0.06)]" + }`} + > + + {entry.label} + + {entry.hint} + +
  • + )) + )} +
+
+ ↑↓ navigate + ↵ open + Esc close + Shift Shift to reopen +
+
+
+ ); +} + +function KindBadge({ kind }: { kind: PaletteEntry["kind"] }) { + const map: Record = { + directive: { label: "DOC", tone: "text-[#75aafc] border-[#3f6fb3]" }, + task: { label: "TASK", tone: "text-emerald-300 border-emerald-700/60" }, + orphan: { label: "TMP", tone: "text-[#7788aa] border-[#2a3a5a]" }, + }; + const m = map[kind]; + return ( + + {m.label} + + ); +} + +/** + * Crude fuzzy match: every char of `q` appears in `s` in order. Good enough + * for the typical "fold-by-substring" feel of an IntelliJ palette without + * pulling in a fuzzy library. + */ +function fuzzyContains(s: string, q: string): boolean { + let i = 0; + for (const c of s) { + if (c === q[i]) i++; + if (i === q.length) return true; + } + return i === q.length; +} diff --git a/makima/frontend/src/components/directives/DocumentTaskStream.tsx b/makima/frontend/src/components/directives/DocumentTaskStream.tsx index 62c1a52..b718ae4 100644 --- a/makima/frontend/src/components/directives/DocumentTaskStream.tsx +++ b/makima/frontend/src/components/directives/DocumentTaskStream.tsx @@ -5,39 +5,88 @@ * Key differences from TaskOutput: * - Document typography (serif-ish paragraphs, not monospace logs). * - Interleaved with subtle marginalia for tool calls and results. - * - "Comment" footer interrupts the running task via sendTaskMessage — - * same backend wire as the existing input bar, just framed as a comment. + * - Sticky comment composer at the bottom that's always in view. + * - Header strip with explicit Stop / Send / Open-in-task-page buttons so + * primary task controls don't require a right-click discovery step. + * - Module-level cache of historical entries per taskId so re-selecting a + * task you've already viewed renders instantly while a fresh fetch + * refreshes in the background. */ import { useCallback, useEffect, useRef, useState } from "react"; +import { useNavigate } from "react-router"; import { SimpleMarkdown } from "../SimpleMarkdown"; import { useTaskSubscription, type TaskOutputEvent, } from "../../hooks/useTaskSubscription"; -import { getTaskOutput, sendTaskMessage } from "../../lib/api"; +import { getTaskOutput, sendTaskMessage, stopTask } from "../../lib/api"; interface DocumentTaskStreamProps { taskId: string; /** Human label used as the document header (e.g. "orchestrator", step name) */ label: string; + /** + * When this task is ephemeral (spawned via the directive's "+ New task" + * action) AND has reached a terminal state, surface a "Merge to base" + * affordance that navigates the user to the standalone task page where + * the existing merge UI handles the actual merge / conflict flow. + * + * Step-spawned tasks have their own merge path (the directive's PR), so + * this affordance is intentionally off by default. + */ + ephemeral?: boolean; + /** Current status of the task; drives whether merge button is enabled. */ + status?: string; } -export function DocumentTaskStream({ taskId, label }: DocumentTaskStreamProps) { - const [entries, setEntries] = useState([]); - const [loading, setLoading] = useState(true); +// ============================================================================= +// Module-level cache for historical task entries. +// +// Switching between tasks you've already viewed used to re-fire +// getTaskOutput and show "Loading transcript…" for the duration of the +// network round-trip. We now keep the entries cached per taskId; on +// re-selection we render the cache immediately and refetch in the +// background. The WS subscription continues to handle live deltas. +// ============================================================================= +const entriesCache = new Map(); + +export function DocumentTaskStream({ + taskId, + label, + ephemeral, + status, +}: DocumentTaskStreamProps) { + const navigate = useNavigate(); + const [entries, setEntries] = useState( + () => entriesCache.get(taskId) ?? [], + ); + const [loading, setLoading] = useState(!entriesCache.has(taskId)); const [isStreaming, setIsStreaming] = useState(false); const [comment, setComment] = useState(""); const [sending, setSending] = useState(false); const [sendError, setSendError] = useState(null); + const [stopping, setStopping] = useState(false); const containerRef = useRef(null); - const [autoScroll, setAutoScroll] = useState(true); + const composerRef = useRef(null); + // autoScroll lives in a ref so the scroll handler reads the latest value + // synchronously without re-creating the effect. + const autoScrollRef = useRef(true); + const [showResumeScroll, setShowResumeScroll] = useState(false); - // Load historical output when the selected task changes. + // Load historical output when the selected task changes. Render the cache + // immediately if we have it; refetch in the background regardless. useEffect(() => { let cancelled = false; - setLoading(true); - setEntries([]); + const cached = entriesCache.get(taskId); + if (cached) { + setEntries(cached); + setLoading(false); + } else { + setEntries([]); + setLoading(true); + } setIsStreaming(false); + getTaskOutput(taskId) .then((res) => { if (cancelled) return; @@ -52,6 +101,7 @@ export function DocumentTaskStream({ taskId, label }: DocumentTaskStreamProps) { durationMs: e.durationMs, isPartial: false, })); + entriesCache.set(taskId, mapped); setEntries(mapped); }) .catch((err) => { @@ -67,17 +117,27 @@ export function DocumentTaskStream({ taskId, label }: DocumentTaskStreamProps) { }; }, [taskId]); - const handleOutput = useCallback((event: TaskOutputEvent) => { - if (event.isPartial) return; - setEntries((prev) => [...prev, event]); - setIsStreaming(true); - }, []); + const handleOutput = useCallback( + (event: TaskOutputEvent) => { + if (event.isPartial) return; + setEntries((prev) => { + const next = [...prev, event]; + entriesCache.set(taskId, next); + return next; + }); + setIsStreaming(true); + }, + [taskId], + ); const handleUpdate = useCallback((event: { status: string }) => { if ( event.status === "completed" || event.status === "failed" || - event.status === "cancelled" + event.status === "cancelled" || + event.status === "interrupted" || + event.status === "merged" || + event.status === "done" ) { setIsStreaming(false); } else if (event.status === "running") { @@ -92,18 +152,32 @@ export function DocumentTaskStream({ taskId, label }: DocumentTaskStreamProps) { onUpdate: handleUpdate, }); - // Auto-scroll while at bottom. + // Auto-scroll while at bottom. The previous version only flipped autoScroll + // off and never resumed; now a scroll back into the bottom 80px reactivates + // it so a brief read-up doesn't permanently freeze the stream at the top. + useEffect(() => { + if (autoScrollRef.current && containerRef.current) { + containerRef.current.scrollTop = containerRef.current.scrollHeight; + } + }, [entries]); + + // After loading the initial transcript, snap to the bottom unconditionally + // so users see the latest output, not the start. useEffect(() => { - if (autoScroll && containerRef.current) { + if (!loading && containerRef.current) { containerRef.current.scrollTop = containerRef.current.scrollHeight; + autoScrollRef.current = true; + setShowResumeScroll(false); } - }, [entries, autoScroll]); + }, [loading, taskId]); const handleScroll = useCallback(() => { if (!containerRef.current) return; const { scrollTop, scrollHeight, clientHeight } = containerRef.current; - const atBottom = scrollHeight - scrollTop - clientHeight < 80; - setAutoScroll(atBottom); + const distanceFromBottom = scrollHeight - scrollTop - clientHeight; + const atBottom = distanceFromBottom < 80; + autoScrollRef.current = atBottom; + setShowResumeScroll(!atBottom); }, []); const submitComment = useCallback( @@ -114,15 +188,19 @@ export function DocumentTaskStream({ taskId, label }: DocumentTaskStreamProps) { setSending(true); setSendError(null); // Show the comment immediately as a user-input entry. - setEntries((prev) => [ - ...prev, - { - taskId, - messageType: "user_input", - content: trimmed, - isPartial: false, - }, - ]); + setEntries((prev) => { + const next: TaskOutputEvent[] = [ + ...prev, + { + taskId, + messageType: "user_input", + content: trimmed, + isPartial: false, + }, + ]; + entriesCache.set(taskId, next); + return next; + }); try { await sendTaskMessage(taskId, trimmed); setComment(""); @@ -138,15 +216,94 @@ export function DocumentTaskStream({ taskId, label }: DocumentTaskStreamProps) { [comment, sending, taskId], ); + const handleStop = useCallback(async () => { + if (stopping || !isStreaming) return; + if (!window.confirm("Stop this task? It will be marked failed.")) return; + setStopping(true); + try { + await stopTask(taskId); + } catch (err) { + // eslint-disable-next-line no-console + console.error("Failed to stop task", err); + } finally { + setStopping(false); + } + }, [taskId, stopping, isStreaming]); + + const focusComposer = useCallback(() => { + const input = composerRef.current?.querySelector("textarea"); + input?.focus(); + }, []); + + const resumeScroll = useCallback(() => { + if (!containerRef.current) return; + containerRef.current.scrollTop = containerRef.current.scrollHeight; + autoScrollRef.current = true; + setShowResumeScroll(false); + }, []); + return ( -
+
+ {/* Action header strip — explicit Stop / Send / Open-in-task-page so + users don't have to right-click to discover task controls. */} +
+ + Task actions + + + + + {/* Manual merge affordance — visible only on ephemeral tasks that + have reached a terminal state. Navigates to the standalone task + page where the existing mesh_merge UI drives the real merge / + conflict resolution flow. The user explicitly asked for this to + be a manual button press for safety. */} + {ephemeral && isTerminalStatus(status) && ( + + )} + + +
+ {/* Document body */}
-
+

{label} @@ -183,8 +340,23 @@ export function DocumentTaskStream({ taskId, label }: DocumentTaskStreamProps) {

- {/* Comment / interrupt footer */} -
+ {/* "Resume auto-scroll" floating chip when the user has scrolled up. */} + {showResumeScroll && ( + + )} + + {/* Sticky comment composer — always pinned to the viewport bottom so + users can interact with the task no matter where they've scrolled. */} +
{sendError && (
{sendError} @@ -192,7 +364,7 @@ export function DocumentTaskStream({ taskId, label }: DocumentTaskStreamProps) { )}
Comment @@ -325,6 +497,12 @@ function DocumentEntry({ entry }: { entry: TaskOutputEvent }) { } } +/** Terminal task statuses where the merge button is meaningful. */ +function isTerminalStatus(status?: string): boolean { + if (!status) return false; + return ["done", "completed", "merged"].includes(status); +} + function firstLineOfInput(input?: Record): string { if (!input) return ""; // Common shapes — show the most informative single value. diff --git a/makima/frontend/src/hooks/useDirectives.ts b/makima/frontend/src/hooks/useDirectives.ts index 898f671..8104de0 100644 --- a/makima/frontend/src/hooks/useDirectives.ts +++ b/makima/frontend/src/hooks/useDirectives.ts @@ -24,28 +24,111 @@ import { createDirectivePR, } from "../lib/api"; +// ============================================================================= +// Stale-while-revalidate cache +// +// Switching between directives in the document-mode sidebar used to feel +// noticeably laggy because every navigation re-fired the GET request and +// blocked the UI on it. We now keep a process-wide cache (mirrors the +// pattern in `useUserSettings.ts`) and use the cache as the immediate +// render value; a fresh fetch fires in the background and notifies all +// subscribed hook instances when it lands. +// +// Mutations (start/pause/etc.) push their result back into the cache so +// successive reads are also instant. Hard `refresh()` calls bypass the +// cache age check and refetch. +// ============================================================================= + +let listCache: DirectiveSummary[] | null = null; +let listInflight: Promise | null = null; +const listSubscribers = new Set<(d: DirectiveSummary[]) => void>(); + +const detailCache = new Map(); +const detailInflight = new Map>(); +const detailSubscribers = new Map void>>(); + +function notifyList(value: DirectiveSummary[]) { + for (const sub of listSubscribers) sub(value); +} + +function notifyDetail(id: string, value: DirectiveWithSteps) { + const subs = detailSubscribers.get(id); + if (!subs) return; + for (const sub of subs) sub(value); +} + +function fetchList(): Promise { + if (listInflight) return listInflight; + listInflight = listDirectives() + .then((res) => { + listCache = res.directives; + notifyList(res.directives); + return res.directives; + }) + .finally(() => { + listInflight = null; + }); + return listInflight; +} + +function fetchDetail(id: string): Promise { + const existing = detailInflight.get(id); + if (existing) return existing; + const p = getDirective(id) + .then((d) => { + detailCache.set(id, d); + notifyDetail(id, d); + return d; + }) + .finally(() => { + detailInflight.delete(id); + }); + detailInflight.set(id, p); + return p; +} + export function useDirectives() { - const [directives, setDirectives] = useState([]); - const [loading, setLoading] = useState(true); + const [directives, setDirectives] = useState( + () => listCache ?? [], + ); + const [loading, setLoading] = useState(listCache === null); const [error, setError] = useState(null); + useEffect(() => { + let mounted = true; + const sub = (value: DirectiveSummary[]) => { + if (!mounted) return; + setDirectives(value); + setLoading(false); + }; + listSubscribers.add(sub); + + // Always kick a background fetch on mount so we don't ship stale data; + // subscribers see the new value when it lands. UI shows the cached + // value immediately if there is one. + fetchList().catch((e) => { + if (!mounted) return; + setError(e instanceof Error ? e.message : "Failed to load directives"); + setLoading(false); + }); + + return () => { + mounted = false; + listSubscribers.delete(sub); + }; + }, []); + const refresh = useCallback(async () => { try { - setLoading(true); - setError(null); const res = await listDirectives(); - setDirectives(res.directives); + listCache = res.directives; + notifyList(res.directives); + setError(null); } catch (e) { setError(e instanceof Error ? e.message : "Failed to load directives"); - } finally { - setLoading(false); } }, []); - useEffect(() => { - refresh(); - }, [refresh]); - const create = useCallback(async (req: CreateDirectiveRequest) => { const d = await createDirective(req); await refresh(); @@ -54,6 +137,7 @@ export function useDirectives() { const remove = useCallback(async (id: string) => { await deleteDirective(id); + detailCache.delete(id); await refresh(); }, [refresh]); @@ -61,8 +145,12 @@ export function useDirectives() { } export function useDirective(id: string | undefined) { - const [directive, setDirective] = useState(null); - const [loading, setLoading] = useState(true); + const [directive, setDirective] = useState( + () => (id ? detailCache.get(id) ?? null : null), + ); + const [loading, setLoading] = useState( + id !== undefined && !detailCache.has(id), + ); const [error, setError] = useState(null); // Silently refresh without setting loading state (for polls) @@ -70,35 +158,73 @@ export function useDirective(id: string | undefined) { if (!id) return; try { const d = await getDirective(id); - setDirective(d); + detailCache.set(id, d); + notifyDetail(id, d); setError(null); - } catch (e) { + } catch { // Don't overwrite existing data on poll failure } }, [id]); - // Full refresh with loading state (for initial load / explicit refresh) + // Full refresh with loading state (for explicit refresh) const refresh = useCallback(async () => { if (!id) return; try { - setLoading(true); setError(null); const d = await getDirective(id); - setDirective(d); + detailCache.set(id, d); + notifyDetail(id, d); } catch (e) { setError(e instanceof Error ? e.message : "Failed to load directive"); - } finally { - setLoading(false); } }, [id]); - // Reset state and fetch when ID changes + // Subscribe to detail updates for this id; render cached value + // immediately and kick a background fetch if the cache is missing. useEffect(() => { - setDirective(null); - setError(null); - setLoading(true); - refresh(); - }, [id]); // eslint-disable-line react-hooks/exhaustive-deps + if (!id) { + setDirective(null); + setLoading(false); + setError(null); + return; + } + + let mounted = true; + const sub = (value: DirectiveWithSteps) => { + if (!mounted) return; + setDirective(value); + setLoading(false); + }; + + let subs = detailSubscribers.get(id); + if (!subs) { + subs = new Set(); + detailSubscribers.set(id, subs); + } + subs.add(sub); + + const cached = detailCache.get(id); + if (cached) { + setDirective(cached); + setLoading(false); + } else { + setDirective(null); + setLoading(true); + } + + // Always kick a fresh fetch so polling-driven UIs see updates. + fetchDetail(id).catch((e) => { + if (!mounted) return; + setError(e instanceof Error ? e.message : "Failed to load directive"); + setLoading(false); + }); + + return () => { + mounted = false; + subs!.delete(sub); + if (subs!.size === 0) detailSubscribers.delete(id); + }; + }, [id]); // Auto-poll while directive is active, has an orchestrator task, or has a completion task useEffect(() => { diff --git a/makima/frontend/src/lib/api.ts b/makima/frontend/src/lib/api.ts index 3fcd728..4d664cf 100644 --- a/makima/frontend/src/lib/api.ts +++ b/makima/frontend/src/lib/api.ts @@ -3509,6 +3509,65 @@ export async function newDirectiveDraft( return res.json(); } +/** + * Request body for spawning an ephemeral task under a directive. The task is + * not part of the DAG — it lives alongside the directive's planned steps but + * the orchestrator ignores it. + */ +export interface CreateDirectiveTaskRequest { + name: string; + plan: string; + /** Override the directive's repository_url; defaults to the directive's. */ + repositoryUrl?: string; + /** Override the directive's base_branch; defaults to the directive's. */ + baseBranch?: string; +} + +/** + * List ephemeral tasks (directive_id set, directive_step_id NULL) attached + * to a directive. Backs the "spinoff" group inside each directive folder + * in the document-mode sidebar. + */ +export async function listDirectiveEphemeralTasks( + directiveId: string, +): Promise { + const res = await authFetch(`${API_BASE}/api/v1/directives/${directiveId}/tasks`); + if (!res.ok) { + throw new Error(`Failed to list directive tasks: ${res.statusText}`); + } + return res.json(); +} + +export async function createDirectiveTask( + directiveId: string, + req: CreateDirectiveTaskRequest, +): Promise { + const res = await authFetch( + `${API_BASE}/api/v1/directives/${directiveId}/tasks`, + { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(req), + }, + ); + if (!res.ok) { + throw new Error(`Failed to create directive task: ${res.statusText}`); + } + return res.json(); +} + +/** + * List tasks not attached to any directive (and not subtasks). Backs the + * `tmp/` pseudo-folder in the document-mode sidebar. + */ +export async function listOrphanTasks(): Promise { + const res = await authFetch(`${API_BASE}/api/v1/mesh/tasks?orphan=true`); + if (!res.ok) { + throw new Error(`Failed to list orphan tasks: ${res.statusText}`); + } + return res.json(); +} + export async function createDirectivePR(id: string): Promise { const res = await authFetch(`${API_BASE}/api/v1/directives/${id}/create-pr`, { method: "POST" }); if (!res.ok) throw new Error(`Failed to create PR: ${res.statusText}`); diff --git a/makima/frontend/src/main.tsx b/makima/frontend/src/main.tsx index 4f7c525..bbb72f3 100644 --- a/makima/frontend/src/main.tsx +++ b/makima/frontend/src/main.tsx @@ -7,6 +7,7 @@ import { SupervisorQuestionsProvider } from "./contexts/SupervisorQuestionsConte import { GridOverlay } from "./components/GridOverlay"; import { SupervisorQuestionNotification } from "./components/SupervisorQuestionNotification"; import { PhaseConfirmationNotification } from "./components/PhaseConfirmationNotification"; +import { QuickSwitcher } from "./components/QuickSwitcher"; import { ProtectedRoute } from "./components/ProtectedRoute"; import HomePage from "./routes/_index"; import ListenPage from "./routes/listen"; @@ -21,6 +22,8 @@ import SettingsPage from "./routes/settings"; import ContractFilePage from "./routes/contract-file"; import SpeakPage from "./routes/speak"; import DirectivesPage from "./routes/directives"; +import ExecRedirect from "./routes/exec-redirect"; +import TmpTaskPage from "./routes/tmp"; createRoot(document.getElementById("root")!).render( @@ -30,6 +33,7 @@ createRoot(document.getElementById("root")!).render( + } /> } /> @@ -109,7 +113,15 @@ createRoot(document.getElementById("root")!).render( path="/exec/:id" element={ - + + + } + /> + + } /> diff --git a/makima/frontend/src/routes/document-directives.tsx b/makima/frontend/src/routes/document-directives.tsx index ffd2a8b..7b0a89b 100644 --- a/makima/frontend/src/routes/document-directives.tsx +++ b/makima/frontend/src/routes/document-directives.tsx @@ -23,12 +23,16 @@ import { cleanupDirective, pickUpOrders, sendTaskMessage, + listDirectiveEphemeralTasks, + createDirectiveTask, + listOrphanTasks, } from "../lib/api"; import type { DirectiveStatus, DirectiveSummary, DirectiveWithSteps, DirectiveRevision, + TaskSummary, } from "../lib/api"; // Status dot color, matching the existing tabular UI's badge palette so the @@ -124,6 +128,26 @@ function TaskIcon() { ); } +/** Asterisk-on-terminal icon for ephemeral spinoff tasks — visually + distinct from the plain TaskIcon used for step-spawned execution tasks + so users can tell at a glance which tasks are part of the DAG vs which + are user-spun side quests. */ +function EphemeralTaskIcon() { + return ( + + + + + + ); +} + /** PR-bracket icon for the completion task. */ function CompletionIcon() { return ( @@ -160,6 +184,31 @@ function PinIcon() { ); } +/** Tiny chip used for the inline directive-folder hover actions. */ +function FolderActionButton({ + children, + title, + onClick, +}: { + children: React.ReactNode; + title: string; + onClick: () => void; +}) { + return ( + + ); +} + function Caret({ open }: { open: boolean }) { return ( void; -} - /** * Per-directive folder. Renders the directive as a collapsible folder whose * body is the pinned document entry (always first) followed by a `tasks/` @@ -380,6 +422,8 @@ function DirectiveFolder({ hasPendingForDirective, onDirectiveContextMenu, onTaskContextMenu, + onCreateTask, + onQuickAction, }: { directive: DirectiveSummary; open: boolean; @@ -392,6 +436,10 @@ function DirectiveFolder({ hasPendingForDirective: boolean; onDirectiveContextMenu: (e: React.MouseEvent, d: DirectiveSummary) => void; onTaskContextMenu: (e: React.MouseEvent, t: FolderTaskRow, directiveId: string) => void; + /** Open the inline "+ New task" form for this directive. */ + onCreateTask: (d: DirectiveSummary) => void; + /** Trigger a quick action (start/pause/PR) on the directive. */ + onQuickAction: (d: DirectiveSummary, action: "start" | "pause" | "pr") => void; }) { const dotColor = STATUS_DOT[directive.status] ?? STATUS_DOT.draft; const fileName = `${slugify(directive.title, directive.id.slice(0, 8))}.md`; @@ -402,8 +450,31 @@ function DirectiveFolder({ const docSelected = selection?.directiveId === directive.id && selection.taskId === null; + // Ephemeral tasks attached to this directive (no directive_step_id). Fetched + // lazily when the folder opens; refetched whenever a poll lands on the + // directive's detail (poll-driven freshness). + const [ephemeralTasks, setEphemeralTasks] = useState([]); + useEffect(() => { + if (!open) return; + let cancelled = false; + listDirectiveEphemeralTasks(directive.id) + .then((res) => { + if (!cancelled) setEphemeralTasks(res.tasks); + }) + .catch((err) => { + // eslint-disable-next-line no-console + console.warn("[makima] failed to load ephemeral tasks", err); + }); + return () => { + cancelled = true; + }; + }, [open, directive.id, directive.updatedAt]); + // Collect the tasks to surface in the folder body. - const tasks = useMemo(() => collectTasks(detailed, directive), [detailed, directive]); + const tasks = useMemo( + () => collectTasks(detailed, directive, ephemeralTasks), + [detailed, directive, ephemeralTasks], + ); const orchestratorRunning = !!directive.orchestratorTaskId; // Tasks subfolder open state — independent of the directive folder. @@ -430,18 +501,76 @@ function DirectiveFolder({ }; }, [open, directive.id, directive.prUrl]); + // Inline action buttons on the folder header — visible on hover (and when + // the folder is open) so users don't have to right-click to discover the + // primary directive controls. Mirrors a code-editor sidebar's affordance. + const showStart = + directive.status === "draft" || + directive.status === "paused" || + directive.status === "idle" || + directive.status === "inactive"; + const showPause = directive.status === "active"; + return ( -
- + + {/* Hover/open-only action chips — discoverable replacement for the + right-click menu. Right-click still works as a power-user fallback. */} +
+ {showStart && ( + onQuickAction(directive, "start")} + > + ▶ + + )} + {showPause && ( + onQuickAction(directive, "pause")} + > + ❚❚ + + )} + {directive.prUrl && ( + + window.open(directive.prUrl ?? "", "_blank", "noreferrer") + } + > + ↗ + + )} + onCreateTask(directive)} + > + + + +
+ {/* Status dot — RIGHT side only. Glows when this directive has a pending user question, or pulses when the orchestrator is live. */} - +
{open && (
    @@ -504,7 +633,11 @@ function DirectiveFolder({ t.status === "running" || t.kind === "orchestrator-active"; const glow = pendingTaskIds.has(t.taskId); const Icon = - t.kind === "completion" ? CompletionIcon : TaskIcon; + t.kind === "completion" + ? CompletionIcon + : t.kind === "ephemeral" + ? EphemeralTaskIcon + : TaskIcon; return (
  • + {tmpOpen && ( +
      + {orphanTasks.length === 0 ? ( +
    • + No orphan tasks +
    • + ) : ( + orphanTasks.map((t) => { + const tdot = + STEP_STATUS_DOT[t.status] ?? STEP_STATUS_DOT.pending; + const live = t.status === "running"; + return ( +
    • + +
    • + ); + }) + )} +
    + )} +
+ {loading && directives.length === 0 ? (
Loading... @@ -923,6 +1154,8 @@ function DocumentSidebar({ hasPendingForDirective={directivesWithPending.has(d.id)} onDirectiveContextMenu={onDirectiveContextMenu} onTaskContextMenu={onTaskContextMenu} + onCreateTask={onCreateTask} + onQuickAction={onQuickAction} /> )) )} @@ -936,6 +1169,63 @@ function DocumentSidebar({ // and loading states. // ============================================================================= +/** + * Wraps DocumentTaskStream with ephemeral-aware metadata. Determines whether + * the selected task is part of the directive's DAG (orchestrator/completion/ + * steps) or an ephemeral spinoff, and looks up its current status from the + * ephemeral list — that decides whether the "Merge to base" affordance + * should appear in the stream's action header. + */ +function EphemeralAwareTaskStream({ + taskId, + label, + directive, +}: { + taskId: string; + label: string; + directive: DirectiveWithSteps; +}) { + const isStepBound = + taskId === directive.orchestratorTaskId || + taskId === directive.completionTaskId || + directive.steps.some((s) => s.taskId === taskId); + + // Status lookup for ephemeral tasks. We poll the ephemeral list lazily — + // this is a lightweight call and only triggers when the user is viewing a + // task in the editor pane. + const [ephemeralStatus, setEphemeralStatus] = useState(); + useEffect(() => { + if (isStepBound) return; + let cancelled = false; + const load = () => { + listDirectiveEphemeralTasks(directive.id) + .then((res) => { + if (cancelled) return; + const match = res.tasks.find((t) => t.id === taskId); + setEphemeralStatus(match?.status); + }) + .catch(() => { + /* non-blocking */ + }); + }; + load(); + const interval = setInterval(load, 5000); + return () => { + cancelled = true; + clearInterval(interval); + }; + }, [taskId, directive.id, isStepBound]); + + return ( + + ); +} + interface EditorShellProps { selectedId: string | undefined; selectedTaskId: string | null; @@ -1011,6 +1301,23 @@ function EditorShell({ ? "revision" : null; + // "Now executing" strip — surfaces what's live when looking at the + // contract editor, so users don't have to scan the sidebar to find it. + const liveTask = (() => { + if (selectedTaskId) return null; // already viewing a task; strip is redundant + if (directive.orchestratorTaskId) { + return { id: directive.orchestratorTaskId, name: "orchestrator" }; + } + if (directive.completionTaskId) { + return { id: directive.completionTaskId, name: "completion" }; + } + const runningStep = directive.steps.find((s) => s.status === "running"); + if (runningStep && runningStep.taskId) { + return { id: runningStep.taskId, name: runningStep.name }; + } + return null; + })(); + return (
{/* Contract header — breadcrumb-like, mirrors a code editor's tab bar */} @@ -1032,21 +1339,37 @@ function EditorShell({ )} - {!selectedTaskId && !!directive.orchestratorTaskId && ( - - - orchestrator running - - )}
+ {/* Now-executing strip — only when viewing the contract doc itself. + Click to jump into the live task transcript. */} + {liveTask && ( + + )} + {revisionId ? ( ) : realTaskId ? ( - ) : ( setContextMenu(null), []); + // Inline "+ New task" form state. When set, we render a small modal-ish + // overlay anchored to the directive folder; submitting calls the + // ephemeral-task endpoint. + const [newTaskFor, setNewTaskFor] = useState(null); + + const onCreateTask = useCallback((d: DirectiveSummary) => { + setNewTaskFor(d); + }, []); + + const handleSubmitNewTask = useCallback( + async (name: string, plan: string) => { + if (!newTaskFor) return; + try { + const task = await createDirectiveTask(newTaskFor.id, { name, plan }); + // Navigate the user into the freshly-spawned task's transcript. + navigate(`/directives/${newTaskFor.id}?task=${task.id}`); + setNewTaskFor(null); + } catch (err) { + // eslint-disable-next-line no-console + console.error("[makima] failed to create ephemeral task", err); + alert( + err instanceof Error + ? `Failed to create task: ${err.message}` + : "Failed to create task", + ); + } + }, + [newTaskFor, navigate], + ); + + const onQuickAction = useCallback( + async (d: DirectiveSummary, action: "start" | "pause" | "pr") => { + try { + if (action === "start") { + await startDirective(d.id); + } else if (action === "pause") { + await pauseDirective(d.id); + } else if (action === "pr") { + await createDirectivePR(d.id); + } + await refreshList(); + } catch (err) { + // eslint-disable-next-line no-console + console.error(`[makima] quick action ${action} failed`, err); + } + }, + [refreshList], + ); + + const onSelectOrphan = useCallback( + (taskId: string) => { + navigate(`/tmp/${taskId}`); + }, + [navigate], + ); + if (authLoading) { return (
@@ -1166,6 +1545,9 @@ export default function DocumentDirectivesPage() { onSelect={onSelect} onDirectiveContextMenu={onDirectiveContextMenu} onTaskContextMenu={onTaskContextMenu} + onCreateTask={onCreateTask} + onQuickAction={onQuickAction} + onSelectOrphan={onSelectOrphan} />
@@ -1304,6 +1686,125 @@ export default function DocumentDirectivesPage() { }} /> )} + + {newTaskFor && ( + setNewTaskFor(null)} + onSubmit={handleSubmitNewTask} + /> + )} +
+ ); +} + +/** + * Inline "+ New task" form for spawning an ephemeral task under a + * directive. Surfaced as a centered modal, dismissible with Esc / click-out. + */ +function NewTaskModal({ + directive, + onClose, + onSubmit, +}: { + directive: DirectiveSummary; + onClose: () => void; + onSubmit: (name: string, plan: string) => Promise; +}) { + const [name, setName] = useState(""); + const [plan, setPlan] = useState(""); + const [submitting, setSubmitting] = useState(false); + const nameRef = useRef(null); + + useEffect(() => { + nameRef.current?.focus(); + const onKey = (e: KeyboardEvent) => { + if (e.key === "Escape") onClose(); + }; + document.addEventListener("keydown", onKey); + return () => document.removeEventListener("keydown", onKey); + }, [onClose]); + + const submit = async (e: React.FormEvent) => { + e.preventDefault(); + const trimmedName = name.trim(); + const trimmedPlan = plan.trim(); + if (!trimmedName || !trimmedPlan || submitting) return; + setSubmitting(true); + try { + await onSubmit(trimmedName, trimmedPlan); + } finally { + setSubmitting(false); + } + }; + + return ( +
+ e.stopPropagation()} + className="w-[480px] max-w-[90vw] bg-[#0a1628] border border-[rgba(117,170,252,0.4)] shadow-xl flex flex-col" + > +
+

+ New task in +

+

+ {directive.title} +

+
+
+
+ + setName(e.target.value)} + placeholder="e.g. Investigate flaky test in auth.test.ts" + className="w-full bg-transparent border border-[rgba(117,170,252,0.2)] focus:border-[#75aafc] outline-none px-3 py-2 text-[13px] text-[#dbe7ff] placeholder-[#445566]" + /> +
+
+ +