mirror of
https://github.com/rennf93/roboco.git
synced 2026-08-03 07:23:24 +02:00
MegaTask (#248)
* feat(batch): batch_id + collision descriptor columns
Sequenced batch intake ("Mega task") foundation: tasks.batch_id (indexed)
groups a batch of top-level tasks created together; intends_to_touch (text[]),
adds_migration and touches_shared (bool, NOT NULL default false) are the
per-task collision surface the SequencingService will read to wire dependency
waves. Mirrored on the Task model + TaskCreateRequest and wired through
TaskService.create. Migration 046 (real upgrade->downgrade->upgrade verified
vs a throwaway pgvector PG); a non-batch task declares no surface (defaults).
Task 1 of the 0.11.0 sequenced-batch-intake plan.
* feat(batch): flag + draft collision descriptors
Default-off ROBOCO_BATCH_INTAKE_ENABLED (config + FEATURE_FLAGS + panel card);
the propose_draft tool doc + the TS DraftProposal gain the per-task collision
surface intends_to_touch / adds_migration / touches_shared. The draft is a loose
dict so the descriptors ride it through the relay intact (test asserts the
forwarded payload); the analyzer (Task 3) reads them to wire dependency waves.
Task 2 of the 0.11.0 sequenced-batch-intake plan.
* feat(batch): deterministic collision-sequencing analyzer
SequencingService.analyze turns a batch's per-task collision surfaces into a
dependency DAG + execution waves — correctness in CODE, not agent judgment.
Rules in order: file overlap serializes (more-important first), migrations form
a serial chain (no concurrent Alembic heads), touches_shared runs last, cell
contention warns (never serializes); then dedupe, existence + cycle check, and
Kahn topological layering. Pure (no DB/services); SequencingError on a cycle or
out-of-range edge.
Golden test reproduces the CEO's hand-sequenced 4 waves of the 11-item
guard-core-app batch (the effort that deadlocked the Main PM): S6 alone last,
the R1/R3/R4 migration chain, R2/R3/S8 serialized on the shared threat service,
S1/S2/S7 in one parallel wave.
Task 3 of the 0.11.0 sequenced-batch-intake plan.
* chore(batch): brand the user-facing surfaces "MegaTask"
The user-facing name is MegaTask: the feature-flag label is "MegaTask intake",
the panel flag-card and the config description lead with MegaTask. Internal
names stay technical (batch_intake_enabled, batch_id, SequencingService).
* chore(batch): drop the feature flag — MegaTask is a core intake scope
MegaTask is additive and opt-in by its own nature (the Prompter proposes a
batch only when the CEO asks for several tasks; single-task intake is
unchanged), so there is no risk surface a flag protects — 'don't create a
MegaTask' is the off switch. Remove batch_intake_enabled from config, the
FEATURE_FLAGS registry, the panel flag card, and its tests. MegaTask will be
a third scope option in the Intake modal (single-cell / multi-project /
MegaTask), not a toggle.
* feat(batch): MegaTask identity predicate + orchestrator branchless recognition
The single source of truth for the umbrella's exemptions: pure
is_batch_umbrella / is_batch_root_subtask / is_branchless_coordination
(foundation/policy/batch.py) — an umbrella has a batch_id and is top-level; a
root-subtask shares the batch_id but is parented. The orchestrator's
_is_coordination_task now consults is_branchless_coordination, so a MegaTask
umbrella is recognized as doing no git of its own (git-exempt at spawn-readiness
/ stuck-detection) exactly like a product fan-out root. Non-batch behavior is
identical (the predicate reduces to the old no-project+product check; the
orchestrator coordination suite stays green), and the umbrella branch is inert
until the create path exists.
First slice of the MegaTask umbrella enforcement (branchless guard).
* feat(batch): branchless umbrella guard across the git-exemption sites
A MegaTask umbrella does no git of its own — every git-exemption site in
TaskService now consults the shared is_branchless_coordination predicate
instead of an inline product-only check, so the umbrella's exemptions
cannot drift between sites:
- the claimed->in_progress branch gate (GitContext.is_coordination) lets
an unbranched umbrella reach in_progress and delegate;
- _ensure_branch_for_task short-circuits an umbrella to "" instead of the
misconfigured raise (the claim path ignores the return, treating it as
branchless);
- CEO-reject routing sends a rejected umbrella to the Main PM in PENDING
(needs_revision is developer-claim-only and would deadlock it).
Covers both shapes via the predicate (product fan-out root OR umbrella);
a batch root-subtask keeps its own branch/PR. Adds orchestrator
recognition tests for the umbrella plus claim/branch/reject integration
tests.
* feat(batch): umbrella assembles no PR; completes branchless
submit_root now hard-rejects a MegaTask umbrella up front (a preflight
that also folds in the unknown-role refusal to stay within the
return-count budget): the umbrella spans many projects with no single
master, so each root-subtask opens and is reviewed on its own PR — the
umbrella never enters the in-path review gate. The Main PM completes it
directly once every root-subtask is terminal.
Umbrella completion needs no new code: it is branchless (no branch_name),
so _main_pm_complete_guard already accepts it from in_progress, checks
all_subtasks_terminal, and main_pm_complete walks it to awaiting_pm_review
and escalates to the CEO with no PR creation — exactly the product
fan-out root path. Adds the submit_root-reject and umbrella-completion
gateway tests; pins batch_id=None on the normal-root submit_root test
(a MagicMock auto-attr would otherwise read as an umbrella).
* feat(batch): MegaTask create path — umbrella + sequenced root-subtasks
PrompterService.confirm_live_batch turns N confirmed drafts into a real
MegaTask: it builds each draft's collision surface, runs the pure
SequencingService to get conflict-free waves, creates the branchless
umbrella (batch_id, no project/product), then one root-subtask per draft
(own project, parent=umbrella, sequence=wave index, descriptors), and
wires the analyzer's edges through add_dependency so the existing
dependency-gate runs the waves in order. The route picks the start path
like a single confirm: 'board' holds the root-subtasks in BACKLOG for the
batch review; 'main_pm' creates them PENDING so wave 0 dispatches at once.
create_task_from_draft gains a BatchPlacement (parent/batch/sequence/
team_override) and forwards the collision descriptors; the exactly-one-
target rule (here and the TaskService.create invariant) is relaxed for an
umbrella, which legitimately targets neither. New route
POST /live/{session}/confirm-batch + BatchConfirmRequest mirror the single
confirm. Adds the structural-invariant + board-hold + empty-batch tests.
* feat(batch): release MegaTask root-subtasks on CEO approval; board awareness
The board route holds a MegaTask's root-subtasks in BACKLOG so the work
waits for the batch review. approve_and_start (CEO gate #1, board->Main PM)
now releases them via _activate_batch_root_subtasks: each held child flips
BACKLOG -> PENDING + team=main_pm so the dependency-gate dispatches wave 0.
No-op for a non-umbrella; idempotent (children past BACKLOG untouched).
The Product Owner and Head of Marketing identity prompts gain a MegaTask
section so they review the whole batch + wave plan and adjust scope before
sign-off (they review drafts; the umbrella is their unit). Also extracts
the create() target invariant into _require_target_or_umbrella to keep the
method under the complexity gate after the umbrella exemption. Adds the
umbrella-approval activation test.
* feat(batch): multi-project intake scope for MegaTask
A MegaTask spans several possibly-unrelated repos, so the intake chat can
now be scoped to an explicit project list (not just one project or one
product). StartLiveRequest gains project_ids; /live/start threads it
through start/spawn_intake_session -> _spawn_intake_container ->
_clone_intake_scope. The multi-repo clone machinery already existed for
products; _intake_scope_slugs now also resolves an explicit project_ids
set (split into _slugs_for_project_ids / _slugs_for_product), cloning each
repo with the first as the primary cwd and the siblings readable. Scope
validation is now 'exactly one of project_slug / product_id / project_ids'
via the shared _require_one_intake_scope. Adds scope-resolution, spawn,
and route tests for the MegaTask path.
* feat(batch): propose_batch intake tool (MegaTask multi-draft hand-off)
The intake agent can now hand the panel a whole MegaTask in one tool call.
Both intake paths gain propose_batch alongside propose_draft:
- Claude (intake_driver): a propose_batch tool registered on the in-SDK
MCP server + allowlisted; the driver intercepts the ToolUseBlock and
emits ONE StreamChunk(kind="batch") carrying {drafts:[...], title}.
- grok (intake_server): a propose_batch tool that POSTs a "batch" relay
event via the shared _post_event helper (post_draft/post_batch).
A batch carries N drafts, each the propose_draft shape PLUS its own
project_id (a MegaTask spans unrelated repos) and collision surface so the
analyzer sequences the waves. The prompter prompt documents the MegaTask
scope + when to call propose_batch. Adds Claude-normalize and grok-relay
tests for the batch path.
* feat(batch): MegaTask intake panel — third scope, batch review, waves
The panel now drives a MegaTask end to end. The intake modal gains a
third scope, 'MegaTask', beside Single cell and Board-led: a multi-project
checklist (a MegaTask spans several possibly-unrelated repos), validated
to at least two. start() sends project_ids; use-prompter accumulates the
agent's single propose_batch hand-off as a 'batch' SSE event into a
BatchProposal and lands in a new batch_preview state.
A new BatchReviewCard lists every proposed task with its target project +
collision-surface badges (migration / shared) and offers one start path
for the whole batch — Board review & Start or Approve & Start — wired to
confirmBatch → POST /confirm-batch. The success card shows the sequenced
result: N tasks in M waves (+ any advisory notes). prompter.ts gains the
DraftScale 'megatask' + the BatchConfirm payload/result types; the SSE
client allows the 'batch' kind. Panel typecheck + lint + 113 tests green.
* docs(batch): MegaTask across changelog, CLAUDE.md, site, and RAG
The four documentation obligations for the MegaTask feature:
- CHANGELOG: an Unreleased entry covering the umbrella model, sequencing,
multi-project intake, propose_batch, and the create/approval path.
- CLAUDE.md: a MegaTask section (identity predicate, umbrella/root-subtask
hierarchy, sequencing rules, intake + create path, board activation).
- Published site: a user-facing company/megatask.md (scopes, waves, the
umbrella, the two start buttons) + nav entry; a pointer added to the
intake chapter of the Tour.
- RAG corpus: workflows/megatask.md so the Main PM (and any agent) can
retrieve the umbrella's branchless / no-PR / completion rules at runtime.
The runtime concurrent-migration guard is intentionally NOT added: the
analyzer already chains migration-adders into dependencies and the
dependency-gate serializes them, so a separate guard would be dead code.
* feat(batch): batch_id guardrail + wave preview + batch_id on TaskResponse
Guardrail (CEO): a batch_id is denied on any task that is not a well-formed
MegaTask member. is_valid_batch_shape permits batch_id only on an umbrella
(no parent → must target neither project nor product) or a root-subtask
(has a parent → exactly one target); TaskService.create enforces it AND
verifies a root-subtask's parent is the batch umbrella (same batch_id,
top-level). This closes a latent hole: is_batch_umbrella is true for a
batch_id + no-parent task even with a project, so a stray batch_id could
have spoofed the branchless branch-gate / no-PR exemption. (The public
task API never exposed batch_id for write; this guards the service layer.)
Wave preview: PrompterService.preview_batch + POST .../preview-batch
compute a MegaTask's waves from the proposed drafts WITHOUT creating
anything, so the panel can show the sequencing before confirm. Extracted
_sequence_drafts as the single source shared by preview and confirm, so
the previewed waves are exactly the ones wired.
TaskResponse now carries batch_id so the panel can badge the umbrella.
* feat(batch): MegaTask review — project editor, wave preview, persistence, badge
Closes the panel gaps in the MegaTask review experience:
- Per-task project editor: each proposed task gets an inline project
Select (updateBatchDraftProject), so a task the agent put in the wrong
or no repo can be fixed before launch — not only by re-chatting. Launch
stays blocked until every task has a project.
- Wave preview: on a batch proposal the panel fetches POST .../preview-batch
(no task created) and shows the conflict-free wave plan, so the human
reviews the sequencing before confirming.
- Refresh durability: the MegaTask review (batch + waves + projectIds) is
persisted, so a browser reload mid-review restores it like a single draft.
- MegaTask badge: TaskResponse exposes batch_id, the panel Task type
carries it, and the task table badges the umbrella row 'MegaTask'.
Panel typecheck + lint + 113 tests green.
* test(batch): stub task carries batch_id for task_to_response
task_to_response now serializes batch_id (TaskResponse field), so the
_stub_task SimpleNamespace fixture must provide it — without it the reader
hit AttributeError, failing the 8 task-schema serialization/enrichment
tests. Test-only; the real TaskTable carries the column (migration 046).
* fix(batch): close MegaTask audit gaps — completion crash, analyzer cycle, guardrails
An adversarial multi-agent audit of the feature surfaced 20 verified gaps;
this closes the backend ones.
HIGH:
- Umbrella completion crashed. escalate_to_ceo hard-required a pr_number,
which a branchless umbrella never has, so main_pm_complete dereferenced
None. Both pr_number gates now waive a MegaTask umbrella (escalate_to_ceo
+ the awaiting_pm_review->awaiting_ceo_approval lifecycle gate via a new
GitContext.is_umbrella), and main_pm_complete guards a None return. The
completion test had mocked escalate_to_ceo, hiding it — now a real
service test covers the waiver.
- The collision analyzer could fabricate a cycle (a touches_shared +
adds_migration draft overlapping another migration draft) and raise
SequencingError — a bare ValueError that escaped as an opaque 500. The
migration chain is now shared-last-aware (never contradicts rule 3), and
_sequence_drafts translates SequencingError to a clean 400.
MEDIUM:
- Collisions are now project-scoped: two repos can't collide on a
coincidental path or serialize independent migrations (DraftSurface
carries project_id; rules 1/2/3 respect it).
- The batch_id guardrail ran only at create. update() + the PATCH
null-clear path now re-assert is_valid_batch_shape, so a mutation can't
break a member's shape and spoof the branchless exemption.
- A draft missing title/acceptance_criteria now raises ValidationError
(was a bare KeyError -> 500).
- confirm_live_batch re-asserts every draft targets a scoped project and
the batch spans >=2 distinct projects (project_ids added to the request).
- Route-level tests for confirm-batch / preview-batch.
LOW: strict multi-repo clone (fail loud on any unresolvable project);
malformed/empty propose_batch surfaces an error chunk (Claude) / refuses
to POST (grok) instead of silently acking; dropped malformed drafts are
counted and surfaced; stale grok intake docstrings updated.
* fix(batch): MegaTask panel + doc audit gaps
Frontend half of the audit fixes:
- The confirm payload now carries project_ids (the schema requires it), and
the panel re-checks every task targets one of the scoped repos before
launching, naming the offending task.
- The Review-MegaTask project picker is filtered to the scoped repos and
the per-task validity (border + launch gate) keys off scoped membership,
so a task can only be (re)pointed at an in-scope project — also fixing the
case where the agent emitted a non-UUID / unknown project.
- Dropped malformed drafts are surfaced as a chat error so the human knows
the batch shrank instead of silently confirming fewer tasks.
- Doc wording: a wave releases on the previous wave's terminal state
(normally a merge; a cancellation releases it too), not strictly 'merged'.
* test(batch): lock the CEO's EXACT 4-wave hand-sequencing as the golden bar
The golden test asserted the constraints (S6 last, the migration chain, the
shared-threats serialization, S1/S2/S7 parallel) but not the full wave
partition. The bar for MegaTask is 'reproduce my exact waves or it's not
done', so assert the exact 4-wave partition the analyzer produces for the
guard-core-app batch:
wave 1: R1 R2 S1 S2 S3 S5 S7 · wave 2: R3 · wave 3: R4 S8 · wave 4: S6
Confirmed unchanged by the audit's analyzer fixes (no migration is shared;
single project).
* fix(batch): tolerate a stub task in assert_batch_shape_intact
The batch-shape re-validation read task.batch_id directly, but update()'s
partial-caller contract is exercised with a SimpleNamespace stub that has no
batch_id column → AttributeError. Use getattr(..., None) for batch_id and the
shape fields so the guard no-ops on any task lacking the column (a stub, or a
non-batch task) while still enforcing on a real batch member.
* fix(orchestrator): authenticate internal API self-calls with the system identity
The dispatcher httpx clients were built without an agent identity, so the
orchestrator's self-PATCHes to /api/tasks/{id} (auto-block, auto-resume,
auto-recover, SLA annotation) were rejected 401 "Missing X-Agent-ID" and
silently no-op'd. The auto-resume that lifts a PM's paused parent could never
write, so paused/blocked parents stayed wedged and stranded their dependents
(the fe-pm/be-pm respawn churn seen in prod).
Header propagation was inconsistent across the separate AsyncClient call-sites:
only the main dispatch client carried the system identity; the readiness and
sweep clients did not. Hoist the identity into a shared _SYSTEM_API_HEADERS
constant and apply it to every API-facing dispatcher client. The system role
holds TaskAction.ASSIGN, so it is authorized for the audited admin_set_status
path those write routes use. The external provider-recovery probe client is
intentionally left untouched.
---------
Co-authored-by: Renn F <rennf93@users.noreply.github.com>
This commit is contained in:
@@ -9,6 +9,7 @@ import {
|
||||
ChatComposer,
|
||||
SuccessCard,
|
||||
IntakeForm,
|
||||
BatchReviewCard,
|
||||
} from "@/components/prompter";
|
||||
|
||||
export default function PrompterPage() {
|
||||
@@ -26,6 +27,8 @@ export default function PrompterPage() {
|
||||
setProjectId,
|
||||
productId,
|
||||
setProductId,
|
||||
projectIds,
|
||||
setProjectIds,
|
||||
initialMessage,
|
||||
setInitialMessage,
|
||||
isFormValid,
|
||||
@@ -36,6 +39,11 @@ export default function PrompterPage() {
|
||||
startAnother,
|
||||
isLaunching,
|
||||
startRedraft,
|
||||
batch,
|
||||
batchWaves,
|
||||
batchResult,
|
||||
updateBatchDraftProject,
|
||||
confirmBatch,
|
||||
} = usePrompter();
|
||||
|
||||
// Entry from a task's "Re-draft with board feedback" button: ?redraft=<taskId>
|
||||
@@ -88,6 +96,8 @@ export default function PrompterPage() {
|
||||
onProjectId={setProjectId}
|
||||
productId={productId}
|
||||
onProductId={setProductId}
|
||||
projectIds={projectIds}
|
||||
onProjectIds={setProjectIds}
|
||||
initialMessage={initialMessage}
|
||||
onInitialMessage={setInitialMessage}
|
||||
isValid={isFormValid()}
|
||||
@@ -102,13 +112,24 @@ export default function PrompterPage() {
|
||||
createdTaskTitle &&
|
||||
createdTaskTeam ? (
|
||||
<div className="flex flex-1 flex-col items-center justify-center px-8 py-8">
|
||||
<div className="w-full max-w-md">
|
||||
<div className="w-full max-w-md space-y-3">
|
||||
<SuccessCard
|
||||
taskId={createdTaskId}
|
||||
taskTitle={createdTaskTitle}
|
||||
team={createdTaskTeam}
|
||||
onStartAnother={startAnother}
|
||||
/>
|
||||
{batchResult && (
|
||||
<p className="text-center text-xs text-muted-foreground">
|
||||
{batchResult.root_subtask_ids.length} tasks sequenced into{" "}
|
||||
{batchResult.waves.length} wave
|
||||
{batchResult.waves.length === 1 ? "" : "s"}.
|
||||
{batchResult.warnings.length > 0 &&
|
||||
` ${batchResult.warnings.length} advisory note${
|
||||
batchResult.warnings.length === 1 ? "" : "s"
|
||||
}.`}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
@@ -120,6 +141,21 @@ export default function PrompterPage() {
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* MegaTask review — the agent proposed a batch; confirm them together */}
|
||||
{state === "batch_preview" && batch && (
|
||||
<div className="mx-4 mb-2">
|
||||
<BatchReviewCard
|
||||
batch={batch}
|
||||
waves={batchWaves}
|
||||
projectIds={projectIds}
|
||||
onKeepChatting={keepChatting}
|
||||
onProjectChange={updateBatchDraftProject}
|
||||
onConfirm={confirmBatch}
|
||||
isLaunching={isLaunching}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Live activity indicator — "watch it work" (prominent) */}
|
||||
{activity && state !== "success" && (
|
||||
<div className="mx-4 mb-2 flex items-center gap-2.5 rounded-lg border border-primary/30 bg-primary/10 px-4 py-2.5 text-sm font-medium text-primary">
|
||||
|
||||
@@ -0,0 +1,209 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
MessageCircle,
|
||||
Users,
|
||||
Rocket,
|
||||
Loader2,
|
||||
Database,
|
||||
Share2,
|
||||
} from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import { useProjects } from "@/hooks/use-projects";
|
||||
import type { BatchProposal, StartRoute } from "@/hooks/use-prompter";
|
||||
|
||||
interface BatchReviewCardProps {
|
||||
batch: BatchProposal;
|
||||
/** The conflict-free waves (lists of draft indices), once previewed. */
|
||||
waves: number[][] | null;
|
||||
/** The repos this MegaTask is scoped to — each task must target one of them. */
|
||||
projectIds: string[];
|
||||
onKeepChatting: () => void;
|
||||
onProjectChange: (index: number, projectId: string) => void;
|
||||
onConfirm: (route: StartRoute) => void;
|
||||
/** A launch is in flight — disable the actions so a double-click can't dupe. */
|
||||
isLaunching?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* The MegaTask review card: every task the agent proposed in one batch, each
|
||||
* with its target project (editable) and collision surface, plus the
|
||||
* conflict-free wave plan. The human reviews the whole batch and the sequencing,
|
||||
* fixes any task in the wrong repo, then picks one start path for all of them.
|
||||
*/
|
||||
export function BatchReviewCard({
|
||||
batch,
|
||||
waves,
|
||||
projectIds,
|
||||
onKeepChatting,
|
||||
onProjectChange,
|
||||
onConfirm,
|
||||
isLaunching = false,
|
||||
}: BatchReviewCardProps) {
|
||||
const { data: allProjects = [] } = useProjects();
|
||||
// Only the scoped repos are valid targets (the agent read only those).
|
||||
const projects = allProjects.filter((p) => projectIds.includes(p.id));
|
||||
const scoped = new Set(projectIds);
|
||||
const titleOf = (i: number): string =>
|
||||
batch.drafts[i]?.title ?? `Task ${i + 1}`;
|
||||
// A task is mis-targeted unless its project is one of the scoped repos.
|
||||
const missingProject = batch.drafts.some(
|
||||
(d) => !d.project_id || !scoped.has(d.project_id),
|
||||
);
|
||||
|
||||
return (
|
||||
<Card className="border-primary/40 bg-primary/5">
|
||||
<CardHeader className="pb-2">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<CardTitle className="text-sm font-semibold leading-tight">
|
||||
MegaTask: {batch.title || "Untitled"}
|
||||
</CardTitle>
|
||||
<Badge variant="secondary" className="shrink-0 text-xs">
|
||||
{batch.drafts.length} tasks
|
||||
</Badge>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
One batch, sequenced into conflict-free waves. Each task keeps its own
|
||||
project, branch, and PR; the Main PM coordinates them all.
|
||||
</p>
|
||||
</CardHeader>
|
||||
|
||||
<CardContent className="space-y-3 pb-3">
|
||||
<ol className="space-y-2">
|
||||
{batch.drafts.map((draft, i) => (
|
||||
<li
|
||||
key={i}
|
||||
className="rounded-md border bg-background/60 px-3 py-2 text-sm"
|
||||
>
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<span className="font-medium leading-tight">
|
||||
{i + 1}. {draft.title}
|
||||
</span>
|
||||
<div className="flex shrink-0 items-center gap-1">
|
||||
{draft.adds_migration && (
|
||||
<Badge variant="outline" className="gap-1 text-xs">
|
||||
<Database className="h-3 w-3" />
|
||||
migration
|
||||
</Badge>
|
||||
)}
|
||||
{draft.touches_shared && (
|
||||
<Badge variant="outline" className="gap-1 text-xs">
|
||||
<Share2 className="h-3 w-3" />
|
||||
shared
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{(draft.objective || draft.description) && (
|
||||
<p className="mt-1 line-clamp-2 text-xs text-muted-foreground">
|
||||
{draft.objective || draft.description}
|
||||
</p>
|
||||
)}
|
||||
{/* Per-task project — editable so a misfiled task can be fixed */}
|
||||
<div className="mt-1.5 flex items-center gap-2">
|
||||
<span className="text-xs text-muted-foreground">Project</span>
|
||||
<Select
|
||||
value={
|
||||
draft.project_id && scoped.has(draft.project_id)
|
||||
? draft.project_id
|
||||
: ""
|
||||
}
|
||||
onValueChange={(v) => onProjectChange(i, v)}
|
||||
disabled={isLaunching}
|
||||
>
|
||||
<SelectTrigger
|
||||
className={`h-7 flex-1 text-xs ${
|
||||
draft.project_id && scoped.has(draft.project_id)
|
||||
? ""
|
||||
: "border-destructive"
|
||||
}`}
|
||||
>
|
||||
<SelectValue placeholder="Pick a project…" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{projects.map((p) => (
|
||||
<SelectItem key={p.id} value={p.id}>
|
||||
{p.name}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
|
||||
{/* Wave plan — how the batch will be sequenced */}
|
||||
{waves && waves.length > 0 && (
|
||||
<div className="rounded-md border border-dashed px-3 py-2">
|
||||
<p className="mb-1 text-xs font-medium text-muted-foreground">
|
||||
Wave plan ({waves.length} wave{waves.length === 1 ? "" : "s"})
|
||||
</p>
|
||||
<ol className="space-y-0.5">
|
||||
{waves.map((wave, w) => (
|
||||
<li key={w} className="text-xs">
|
||||
<span className="font-medium">Wave {w + 1}:</span>{" "}
|
||||
{wave.map((i) => titleOf(i)).join(", ")}
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{missingProject && (
|
||||
<p className="text-xs text-destructive">
|
||||
Pick a project for every task before launching the MegaTask.
|
||||
</p>
|
||||
)}
|
||||
|
||||
<div className="flex flex-wrap gap-2 pt-1">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={onKeepChatting}
|
||||
disabled={isLaunching}
|
||||
>
|
||||
<MessageCircle className="mr-1.5 h-3.5 w-3.5" />
|
||||
Keep chatting
|
||||
</Button>
|
||||
{/* Board review & Start → the Board reviews the whole batch first */}
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
onClick={() => onConfirm("board")}
|
||||
disabled={isLaunching || missingProject}
|
||||
>
|
||||
{isLaunching ? (
|
||||
<Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" />
|
||||
) : (
|
||||
<Users className="mr-1.5 h-3.5 w-3.5" />
|
||||
)}
|
||||
Board review & Start
|
||||
</Button>
|
||||
{/* Approve & Start → straight to the Main PM, waves dispatch at once */}
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={() => onConfirm("main_pm")}
|
||||
disabled={isLaunching || missingProject}
|
||||
>
|
||||
{isLaunching ? (
|
||||
<Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" />
|
||||
) : (
|
||||
<Rocket className="mr-1.5 h-3.5 w-3.5" />
|
||||
)}
|
||||
Approve & Start
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
export { ChatMessages } from "./chat-messages";
|
||||
export { ChatComposer } from "./chat-composer";
|
||||
export { DraftProposalCard } from "./draft-proposal-card";
|
||||
export { BatchReviewCard } from "./batch-review-card";
|
||||
export { SuccessCard } from "./success-card";
|
||||
export { IntakeForm } from "./intake-form";
|
||||
|
||||
@@ -25,6 +25,8 @@ interface IntakeFormProps {
|
||||
onProjectId: (id: string) => void;
|
||||
productId: string;
|
||||
onProductId: (id: string) => void;
|
||||
projectIds: string[];
|
||||
onProjectIds: (ids: string[]) => void;
|
||||
initialMessage: string;
|
||||
onInitialMessage: (v: string) => void;
|
||||
isValid: boolean;
|
||||
@@ -34,8 +36,9 @@ interface IntakeFormProps {
|
||||
|
||||
/**
|
||||
* The one-time scope form shown before the chat. The agent is spawned against
|
||||
* exactly one of project / product, clones that scope's repo(s), and reads the
|
||||
* real code before answering — so the scope must be chosen up front.
|
||||
* exactly one scope — a single project, a board-led product, or a MegaTask (a
|
||||
* set of projects) — clones that scope's repo(s), and reads the real code before
|
||||
* answering, so the scope must be chosen up front.
|
||||
*/
|
||||
export function IntakeForm({
|
||||
targetKind,
|
||||
@@ -44,6 +47,8 @@ export function IntakeForm({
|
||||
onProjectId,
|
||||
productId,
|
||||
onProductId,
|
||||
projectIds,
|
||||
onProjectIds,
|
||||
initialMessage,
|
||||
onInitialMessage,
|
||||
isValid,
|
||||
@@ -105,12 +110,15 @@ export function IntakeForm({
|
||||
value={targetKind}
|
||||
onValueChange={(v) => onTargetKind(v as TargetKind)}
|
||||
>
|
||||
<TabsList className="grid w-full grid-cols-2">
|
||||
<TabsList className="grid w-full grid-cols-3">
|
||||
<TabsTrigger value="project" disabled={isPreparing}>
|
||||
Single cell (Project)
|
||||
Single cell
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="product" disabled={isPreparing}>
|
||||
Board-led (Product)
|
||||
Board-led
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="megatask" disabled={isPreparing}>
|
||||
MegaTask
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
</Tabs>
|
||||
@@ -132,6 +140,50 @@ export function IntakeForm({
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
) : targetKind === "megatask" ? (
|
||||
<div className="space-y-2">
|
||||
<p className="text-xs text-muted-foreground">
|
||||
A MegaTask spans several projects worked at once — even
|
||||
unrelated ones (e.g. a SaaS app, its OSS core, and an adapter).
|
||||
Pick every repo it touches; the agent reads them all and
|
||||
proposes one batch of sequenced tasks.
|
||||
</p>
|
||||
<div className="max-h-48 space-y-1 overflow-y-auto rounded-md border p-2">
|
||||
{projects.map((p) => {
|
||||
const checked = projectIds.includes(p.id);
|
||||
return (
|
||||
<label
|
||||
key={p.id}
|
||||
className="flex cursor-pointer items-center gap-2 rounded px-2 py-1.5 text-sm hover:bg-muted"
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
className="h-4 w-4 accent-primary"
|
||||
checked={checked}
|
||||
disabled={isPreparing}
|
||||
onChange={(e) =>
|
||||
onProjectIds(
|
||||
e.target.checked
|
||||
? [...projectIds, p.id]
|
||||
: projectIds.filter((id) => id !== p.id),
|
||||
)
|
||||
}
|
||||
/>
|
||||
<span>{p.name}</span>
|
||||
</label>
|
||||
);
|
||||
})}
|
||||
{projects.length === 0 && (
|
||||
<p className="px-2 py-1.5 text-xs text-muted-foreground">
|
||||
No projects exist yet — create some under Projects first.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{projectIds.length} selected
|
||||
{projectIds.length < 2 ? " — pick at least two" : ""}
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<Select
|
||||
|
||||
@@ -571,6 +571,14 @@ export function TaskTable({
|
||||
>
|
||||
<div className="font-medium flex items-center gap-2">
|
||||
<span className="truncate">{task.title}</span>
|
||||
{task.batch_id && !task.parent_task_id && (
|
||||
<Badge
|
||||
variant="outline"
|
||||
className="text-xs shrink-0 border-primary/50 text-primary"
|
||||
>
|
||||
MegaTask
|
||||
</Badge>
|
||||
)}
|
||||
{childCount > 0 && (
|
||||
<Badge
|
||||
variant="secondary"
|
||||
|
||||
+327
-117
@@ -12,6 +12,7 @@ import {
|
||||
type CellWork,
|
||||
type DraftScale,
|
||||
type ConfirmPayload,
|
||||
type BatchConfirmResult,
|
||||
} from "@/lib/api/prompter";
|
||||
import { getErrorMessage } from "@/lib/api/client";
|
||||
import { tasksApi } from "@/lib/api/tasks";
|
||||
@@ -28,6 +29,7 @@ export type PrompterState =
|
||||
| "chatting"
|
||||
| "streaming" // a reply is mid-flight over SSE
|
||||
| "draft_preview"
|
||||
| "batch_preview" // a MegaTask (N drafts) is ready to review
|
||||
| "review_modal"
|
||||
| "launching"
|
||||
| "success";
|
||||
@@ -43,7 +45,16 @@ export interface ChatMessage {
|
||||
}
|
||||
|
||||
/** Which target the human picked for this chat. */
|
||||
export type TargetKind = "project" | "product";
|
||||
export type TargetKind = "project" | "product" | "megatask";
|
||||
|
||||
/** A MegaTask the agent proposed: a title + one draft per task (each draft
|
||||
* carries its own project_id + collision surface). `dropped` is how many raw
|
||||
* entries the agent emitted that were malformed and discarded. */
|
||||
export interface BatchProposal {
|
||||
title: string;
|
||||
drafts: DraftProposal[];
|
||||
dropped: number;
|
||||
}
|
||||
|
||||
/** Which start button the human pressed on the draft card. */
|
||||
export type StartRoute = "board" | "main_pm";
|
||||
@@ -101,7 +112,7 @@ function stripDraftFence(text: string): string {
|
||||
function toEditable(
|
||||
draft: DraftProposal,
|
||||
scale: DraftScale | null,
|
||||
scope: { targetKind: TargetKind; projectId: string; productId: string }
|
||||
scope: { targetKind: TargetKind; projectId: string; productId: string },
|
||||
): EditableDraft {
|
||||
return {
|
||||
title: draft.title,
|
||||
@@ -121,8 +132,7 @@ function toEditable(
|
||||
the_work: draft.the_work ?? [],
|
||||
notes: draft.notes ?? [],
|
||||
// The scope picked up front wins; fall back to scale only if unset.
|
||||
targetKind:
|
||||
scope.targetKind || (scale === "multi" ? "product" : "project"),
|
||||
targetKind: scope.targetKind || (scale === "multi" ? "product" : "project"),
|
||||
projectId: scope.projectId,
|
||||
productId: scope.productId,
|
||||
};
|
||||
@@ -143,6 +153,29 @@ function draftFromEvent(data: Record<string, unknown> | undefined): {
|
||||
return { draft: d as unknown as DraftProposal, scale };
|
||||
}
|
||||
|
||||
/** Pull a MegaTask ({title, drafts[]}) out of a `batch` SSE event's payload. */
|
||||
function batchFromEvent(
|
||||
data: Record<string, unknown> | undefined,
|
||||
): BatchProposal | null {
|
||||
if (!data || typeof data !== "object") return null;
|
||||
const raw = (data as Record<string, unknown>).drafts;
|
||||
if (!Array.isArray(raw)) return null;
|
||||
const drafts = raw.filter(
|
||||
(x): x is DraftProposal =>
|
||||
!!x && typeof (x as DraftProposal).title === "string",
|
||||
);
|
||||
if (drafts.length === 0) return null;
|
||||
const title = (data as Record<string, unknown>).title;
|
||||
// Prefer the backend's dropped count; else compute from what we filtered, so a
|
||||
// shrunk batch is surfaced rather than silently delivering fewer tasks.
|
||||
const backendDropped = (data as Record<string, unknown>).dropped;
|
||||
const dropped =
|
||||
typeof backendDropped === "number"
|
||||
? backendDropped
|
||||
: raw.length - drafts.length;
|
||||
return { title: typeof title === "string" ? title : "", drafts, dropped };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Refresh durability
|
||||
//
|
||||
@@ -161,9 +194,17 @@ interface PersistedChat {
|
||||
sessionId: string;
|
||||
messages: ChatMessage[];
|
||||
state: PrompterState;
|
||||
scope: { targetKind: TargetKind; projectId: string; productId: string };
|
||||
scope: {
|
||||
targetKind: TargetKind;
|
||||
projectId: string;
|
||||
productId: string;
|
||||
projectIds?: string[];
|
||||
};
|
||||
editableDraft: EditableDraft;
|
||||
redraftTaskId?: string | null;
|
||||
// MegaTask review state, so a reload mid-batch-review restores the batch.
|
||||
batch?: BatchProposal | null;
|
||||
batchWaves?: number[][] | null;
|
||||
savedAt: number;
|
||||
}
|
||||
|
||||
@@ -221,9 +262,19 @@ export function usePrompter() {
|
||||
const [targetKind, setTargetKind] = useState<TargetKind>("project");
|
||||
const [projectId, setProjectId] = useState("");
|
||||
const [productId, setProductId] = useState("");
|
||||
// MegaTask scope: the set of (possibly unrelated) projects it spans.
|
||||
const [projectIds, setProjectIds] = useState<string[]>([]);
|
||||
const [initialMessage, setInitialMessage] = useState("");
|
||||
|
||||
const [editableDraft, setEditableDraft] = useState<EditableDraft>(EMPTY_DRAFT);
|
||||
const [editableDraft, setEditableDraft] =
|
||||
useState<EditableDraft>(EMPTY_DRAFT);
|
||||
// The proposed MegaTask (when the agent calls propose_batch), its previewed
|
||||
// waves (computed without creating anything), and its create result.
|
||||
const [batch, setBatch] = useState<BatchProposal | null>(null);
|
||||
const [batchWaves, setBatchWaves] = useState<number[][] | null>(null);
|
||||
const [batchResult, setBatchResult] = useState<BatchConfirmResult | null>(
|
||||
null,
|
||||
);
|
||||
|
||||
// Live-session plumbing held in refs so SSE callbacks never see stale state.
|
||||
const sessionIdRef = useRef<string | null>(null);
|
||||
@@ -234,8 +285,8 @@ export function usePrompter() {
|
||||
const streamingIdRef = useRef<string | null>(null);
|
||||
// Synchronous re-entry guard for launch — a double-click was creating two tasks.
|
||||
const launchingRef = useRef(false);
|
||||
const scopeRef = useRef({ targetKind, projectId, productId });
|
||||
scopeRef.current = { targetKind, projectId, productId };
|
||||
const scopeRef = useRef({ targetKind, projectId, productId, projectIds });
|
||||
scopeRef.current = { targetKind, projectId, productId, projectIds };
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// Message helpers
|
||||
@@ -254,7 +305,7 @@ export function usePrompter() {
|
||||
const id = streamingIdRef.current;
|
||||
if (id) {
|
||||
return prev.map((m) =>
|
||||
m.id === id ? { ...m, content: m.content + delta } : m
|
||||
m.id === id ? { ...m, content: m.content + delta } : m,
|
||||
);
|
||||
}
|
||||
const newMsgId = newId();
|
||||
@@ -277,7 +328,7 @@ export function usePrompter() {
|
||||
return prev.map((m) =>
|
||||
m.id === id
|
||||
? { ...m, draft, content: stripDraftFence(m.content) }
|
||||
: m
|
||||
: m,
|
||||
);
|
||||
}
|
||||
return [...prev, { id: newId(), role: "assistant", content: "", draft }];
|
||||
@@ -312,19 +363,52 @@ export function usePrompter() {
|
||||
streamingIdRef.current = null;
|
||||
setActivity(null);
|
||||
setIsSending(false);
|
||||
setState((s) => (s === "draft_preview" ? s : "chatting"));
|
||||
setState((s) =>
|
||||
s === "draft_preview" || s === "batch_preview" ? s : "chatting",
|
||||
);
|
||||
break;
|
||||
case "draft": {
|
||||
const parsed = draftFromEvent(evt.data);
|
||||
if (parsed) {
|
||||
attachDraft(parsed.draft);
|
||||
setEditableDraft(
|
||||
toEditable(parsed.draft, parsed.scale, scopeRef.current)
|
||||
toEditable(parsed.draft, parsed.scale, scopeRef.current),
|
||||
);
|
||||
setState("draft_preview");
|
||||
}
|
||||
break;
|
||||
}
|
||||
case "batch": {
|
||||
// A MegaTask: the agent proposed N drafts at once. Hold them for the
|
||||
// Review MegaTask card; the human confirms the whole batch together.
|
||||
const parsedBatch = batchFromEvent(evt.data);
|
||||
if (parsedBatch) {
|
||||
streamingIdRef.current = null;
|
||||
setBatch(parsedBatch);
|
||||
setBatchWaves(null);
|
||||
setState("batch_preview");
|
||||
if (parsedBatch.dropped > 0) {
|
||||
addMessage({
|
||||
role: "error",
|
||||
content:
|
||||
`${parsedBatch.dropped} proposed task${
|
||||
parsedBatch.dropped === 1 ? " was" : "s were"
|
||||
} malformed and dropped from this MegaTask. Ask the agent to ` +
|
||||
"re-propose them if they're needed.",
|
||||
});
|
||||
}
|
||||
// Compute the conflict-free waves (no task created) so the human can
|
||||
// review the sequencing before confirming. Best-effort.
|
||||
const sid = sessionIdRef.current;
|
||||
if (sid) {
|
||||
void prompterLiveApi
|
||||
.previewBatch(sid, parsedBatch.drafts)
|
||||
.then((p) => setBatchWaves(p.waves))
|
||||
.catch(() => setBatchWaves(null));
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
case "error":
|
||||
streamingIdRef.current = null;
|
||||
setActivity(null);
|
||||
@@ -340,7 +424,7 @@ export function usePrompter() {
|
||||
break;
|
||||
}
|
||||
},
|
||||
[appendDelta, attachDraft, addMessage]
|
||||
[appendDelta, attachDraft, addMessage],
|
||||
);
|
||||
|
||||
const closeStream = useCallback(() => {
|
||||
@@ -363,7 +447,7 @@ export function usePrompter() {
|
||||
}
|
||||
sourceRef.current = es;
|
||||
},
|
||||
[closeStream, handleEvent]
|
||||
[closeStream, handleEvent],
|
||||
);
|
||||
|
||||
// Best-effort reap if the user navigates away mid-chat. This cleanup runs on
|
||||
@@ -387,6 +471,7 @@ export function usePrompter() {
|
||||
(state === "chatting" ||
|
||||
state === "streaming" ||
|
||||
state === "draft_preview" ||
|
||||
state === "batch_preview" ||
|
||||
state === "review_modal");
|
||||
if (persistable && sessionId) {
|
||||
savePersisted({
|
||||
@@ -396,10 +481,12 @@ export function usePrompter() {
|
||||
scope: scopeRef.current,
|
||||
editableDraft,
|
||||
redraftTaskId: redraftTaskIdRef.current,
|
||||
batch,
|
||||
batchWaves,
|
||||
savedAt: Date.now(),
|
||||
});
|
||||
}
|
||||
}, [sessionId, messages, state, editableDraft]);
|
||||
}, [sessionId, messages, state, editableDraft, batch, batchWaves]);
|
||||
|
||||
// On mount, reconnect to a still-running session left behind by a reload.
|
||||
const didRestoreRef = useRef(false);
|
||||
@@ -428,11 +515,17 @@ export function usePrompter() {
|
||||
setTargetKind(persisted.scope.targetKind);
|
||||
setProjectId(persisted.scope.projectId);
|
||||
setProductId(persisted.scope.productId);
|
||||
setProjectIds(persisted.scope.projectIds ?? []);
|
||||
setBatch(persisted.batch ?? null);
|
||||
setBatchWaves(persisted.batchWaves ?? null);
|
||||
// A MegaTask review survives reload; otherwise land on a stable state.
|
||||
setState(
|
||||
persisted.state === "draft_preview" ||
|
||||
persisted.state === "review_modal"
|
||||
? "draft_preview"
|
||||
: "chatting"
|
||||
persisted.state === "batch_preview" && persisted.batch
|
||||
? "batch_preview"
|
||||
: persisted.state === "draft_preview" ||
|
||||
persisted.state === "review_modal"
|
||||
? "draft_preview"
|
||||
: "chatting",
|
||||
);
|
||||
openStream(persisted.sessionId);
|
||||
} catch {
|
||||
@@ -450,20 +543,29 @@ export function usePrompter() {
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
const isFormValid = useCallback((): boolean => {
|
||||
const scoped = targetKind === "product" ? productId !== "" : projectId !== "";
|
||||
const scoped =
|
||||
targetKind === "product"
|
||||
? productId !== ""
|
||||
: targetKind === "megatask"
|
||||
? projectIds.length >= 2 // a MegaTask spans several repos
|
||||
: projectId !== "";
|
||||
return scoped && initialMessage.trim().length > 0;
|
||||
}, [targetKind, projectId, productId, initialMessage]);
|
||||
}, [targetKind, projectId, productId, projectIds, initialMessage]);
|
||||
|
||||
const start = useCallback(async () => {
|
||||
if (!isFormValid() || state === "preparing") return;
|
||||
const opening = initialMessage.trim();
|
||||
setState("preparing");
|
||||
addMessage({ role: "user", content: opening });
|
||||
const scopePayload =
|
||||
targetKind === "product"
|
||||
? { product_id: productId }
|
||||
: targetKind === "megatask"
|
||||
? { project_ids: projectIds }
|
||||
: { project_id: projectId };
|
||||
try {
|
||||
const { session_id } = await prompterLiveApi.start({
|
||||
...(targetKind === "product"
|
||||
? { product_id: productId }
|
||||
: { project_id: projectId }),
|
||||
...scopePayload,
|
||||
initial_message: opening,
|
||||
});
|
||||
sessionIdRef.current = session_id;
|
||||
@@ -472,7 +574,9 @@ export function usePrompter() {
|
||||
setIsSending(true); // the opening reply is on its way over SSE
|
||||
// start now returns immediately; the container spawns in the background
|
||||
// (clone + image build can take a minute). Show that until the first event.
|
||||
setActivity("Preparing the agent — cloning your repo and reading the code…");
|
||||
setActivity(
|
||||
"Preparing the agent — cloning your repo and reading the code…",
|
||||
);
|
||||
setState("streaming");
|
||||
} catch (err) {
|
||||
addMessage({ role: "error", content: getErrorMessage(err) });
|
||||
@@ -485,6 +589,7 @@ export function usePrompter() {
|
||||
targetKind,
|
||||
productId,
|
||||
projectId,
|
||||
projectIds,
|
||||
addMessage,
|
||||
openStream,
|
||||
]);
|
||||
@@ -546,7 +651,7 @@ export function usePrompter() {
|
||||
setState("chatting");
|
||||
}
|
||||
},
|
||||
[isSending, addMessage]
|
||||
[isSending, addMessage],
|
||||
);
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
@@ -577,98 +682,190 @@ export function usePrompter() {
|
||||
// Launch — confirm the draft → task, then reap the agent
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
const launchTask = useCallback(async (route: StartRoute) => {
|
||||
// Re-entry guard FIRST (synchronous, no stale closure): a double-click was
|
||||
// firing two confirms and creating duplicate tasks.
|
||||
if (launchingRef.current) return;
|
||||
const sid = sessionIdRef.current;
|
||||
// Never fail silently — a dead button with no feedback reads as "broken"
|
||||
// (it did: a missing `description` threw inside validation and the click
|
||||
// vanished). Tell the human exactly what's blocking the launch.
|
||||
if (!sid) {
|
||||
toast.error("This chat has ended — start a new one to launch a task.");
|
||||
return;
|
||||
}
|
||||
if (!isValidForLaunch()) {
|
||||
toast.error(
|
||||
"The draft is missing something needed to launch: a title, a 20+ character " +
|
||||
"summary, at least one acceptance criterion, and a target. Keep chatting to refine it."
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
launchingRef.current = true;
|
||||
setIsLaunching(true);
|
||||
setState("launching");
|
||||
|
||||
const draft: DraftProposal = {
|
||||
title: editableDraft.title.trim(),
|
||||
description: (editableDraft.description ?? "").trim(),
|
||||
acceptance_criteria: editableDraft.acceptance_criteria,
|
||||
team: editableDraft.team as Team,
|
||||
priority: editableDraft.priority,
|
||||
objective: editableDraft.objective.trim() || null,
|
||||
what_this_builds: editableDraft.what_this_builds,
|
||||
the_work: editableDraft.the_work,
|
||||
notes: editableDraft.notes,
|
||||
...(editableDraft.task_type ? { task_type: editableDraft.task_type } : {}),
|
||||
...(editableDraft.nature ? { nature: editableDraft.nature } : {}),
|
||||
...(editableDraft.estimated_complexity
|
||||
? { estimated_complexity: editableDraft.estimated_complexity }
|
||||
: {}),
|
||||
};
|
||||
|
||||
const payload: ConfirmPayload =
|
||||
editableDraft.targetKind === "product"
|
||||
? { product_id: editableDraft.productId, draft, route }
|
||||
: { project_id: editableDraft.projectId, draft, route };
|
||||
// Board-informed re-draft: confirm updates the existing task in place.
|
||||
const redraftId = redraftTaskIdRef.current;
|
||||
if (redraftId) {
|
||||
payload.task_id = redraftId;
|
||||
}
|
||||
|
||||
const effectiveTeam =
|
||||
editableDraft.targetKind === "product"
|
||||
? Team.MAIN_PM
|
||||
: (editableDraft.team as Team);
|
||||
|
||||
try {
|
||||
const { task_id } = await prompterLiveApi.confirm(sid, payload);
|
||||
// Board route, first pass: the backend parked the intake agent so the
|
||||
// board's feedback can be injected for an in-place re-draft. Keep the chat
|
||||
// alive (don't reap) — the revised draft will arrive here to approve.
|
||||
if (route === "board" && !redraftId) {
|
||||
redraftTaskIdRef.current = task_id;
|
||||
addMessage({
|
||||
role: "assistant",
|
||||
content:
|
||||
"Sent to the board — the Product Owner and Head of Marketing are " +
|
||||
"reviewing this. Their feedback will arrive here as a revised draft " +
|
||||
"you can approve. You can leave and come back; this chat stays open.",
|
||||
});
|
||||
setState("chatting");
|
||||
return; // `finally` resets the launching guard
|
||||
const launchTask = useCallback(
|
||||
async (route: StartRoute) => {
|
||||
// Re-entry guard FIRST (synchronous, no stale closure): a double-click was
|
||||
// firing two confirms and creating duplicate tasks.
|
||||
if (launchingRef.current) return;
|
||||
const sid = sessionIdRef.current;
|
||||
// Never fail silently — a dead button with no feedback reads as "broken"
|
||||
// (it did: a missing `description` threw inside validation and the click
|
||||
// vanished). Tell the human exactly what's blocking the launch.
|
||||
if (!sid) {
|
||||
toast.error("This chat has ended — start a new one to launch a task.");
|
||||
return;
|
||||
}
|
||||
// The draft became a task — reap the agent and close the stream.
|
||||
closeStream();
|
||||
void prompterLiveApi.stop(sid).catch(() => undefined);
|
||||
clearPersisted();
|
||||
sessionIdRef.current = null;
|
||||
redraftTaskIdRef.current = null;
|
||||
setCreatedTaskId(task_id);
|
||||
setCreatedTaskTitle(draft.title);
|
||||
setCreatedTaskTeam(effectiveTeam);
|
||||
toast.success("Task created and launched!");
|
||||
setState("success");
|
||||
} catch (err) {
|
||||
toast.error(`Failed to launch task: ${getErrorMessage(err)}`);
|
||||
setState("draft_preview"); // back to the draft card to retry
|
||||
} finally {
|
||||
setIsLaunching(false);
|
||||
launchingRef.current = false;
|
||||
}
|
||||
}, [editableDraft, isValidForLaunch, closeStream, addMessage]);
|
||||
if (!isValidForLaunch()) {
|
||||
toast.error(
|
||||
"The draft is missing something needed to launch: a title, a 20+ character " +
|
||||
"summary, at least one acceptance criterion, and a target. Keep chatting to refine it.",
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
launchingRef.current = true;
|
||||
setIsLaunching(true);
|
||||
setState("launching");
|
||||
|
||||
const draft: DraftProposal = {
|
||||
title: editableDraft.title.trim(),
|
||||
description: (editableDraft.description ?? "").trim(),
|
||||
acceptance_criteria: editableDraft.acceptance_criteria,
|
||||
team: editableDraft.team as Team,
|
||||
priority: editableDraft.priority,
|
||||
objective: editableDraft.objective.trim() || null,
|
||||
what_this_builds: editableDraft.what_this_builds,
|
||||
the_work: editableDraft.the_work,
|
||||
notes: editableDraft.notes,
|
||||
...(editableDraft.task_type
|
||||
? { task_type: editableDraft.task_type }
|
||||
: {}),
|
||||
...(editableDraft.nature ? { nature: editableDraft.nature } : {}),
|
||||
...(editableDraft.estimated_complexity
|
||||
? { estimated_complexity: editableDraft.estimated_complexity }
|
||||
: {}),
|
||||
};
|
||||
|
||||
const payload: ConfirmPayload =
|
||||
editableDraft.targetKind === "product"
|
||||
? { product_id: editableDraft.productId, draft, route }
|
||||
: { project_id: editableDraft.projectId, draft, route };
|
||||
// Board-informed re-draft: confirm updates the existing task in place.
|
||||
const redraftId = redraftTaskIdRef.current;
|
||||
if (redraftId) {
|
||||
payload.task_id = redraftId;
|
||||
}
|
||||
|
||||
const effectiveTeam =
|
||||
editableDraft.targetKind === "product"
|
||||
? Team.MAIN_PM
|
||||
: (editableDraft.team as Team);
|
||||
|
||||
try {
|
||||
const { task_id } = await prompterLiveApi.confirm(sid, payload);
|
||||
// Board route, first pass: the backend parked the intake agent so the
|
||||
// board's feedback can be injected for an in-place re-draft. Keep the chat
|
||||
// alive (don't reap) — the revised draft will arrive here to approve.
|
||||
if (route === "board" && !redraftId) {
|
||||
redraftTaskIdRef.current = task_id;
|
||||
addMessage({
|
||||
role: "assistant",
|
||||
content:
|
||||
"Sent to the board — the Product Owner and Head of Marketing are " +
|
||||
"reviewing this. Their feedback will arrive here as a revised draft " +
|
||||
"you can approve. You can leave and come back; this chat stays open.",
|
||||
});
|
||||
setState("chatting");
|
||||
return; // `finally` resets the launching guard
|
||||
}
|
||||
// The draft became a task — reap the agent and close the stream.
|
||||
closeStream();
|
||||
void prompterLiveApi.stop(sid).catch(() => undefined);
|
||||
clearPersisted();
|
||||
sessionIdRef.current = null;
|
||||
redraftTaskIdRef.current = null;
|
||||
setCreatedTaskId(task_id);
|
||||
setCreatedTaskTitle(draft.title);
|
||||
setCreatedTaskTeam(effectiveTeam);
|
||||
toast.success("Task created and launched!");
|
||||
setState("success");
|
||||
} catch (err) {
|
||||
toast.error(`Failed to launch task: ${getErrorMessage(err)}`);
|
||||
setState("draft_preview"); // back to the draft card to retry
|
||||
} finally {
|
||||
setIsLaunching(false);
|
||||
launchingRef.current = false;
|
||||
}
|
||||
},
|
||||
[editableDraft, isValidForLaunch, closeStream, addMessage],
|
||||
);
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// Confirm a MegaTask — create the umbrella + sequenced root-subtasks, reap
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
/** Reassign one task in the proposed MegaTask to a different project. Lets the
|
||||
* human fix a draft the agent put in the wrong (or no) repo before launch.
|
||||
* Project does not affect the wave plan (waves derive from collision surface),
|
||||
* so the previewed waves stay valid. */
|
||||
const updateBatchDraftProject = useCallback(
|
||||
(index: number, projectId: string) => {
|
||||
setBatch((prev) => {
|
||||
if (!prev) return prev;
|
||||
return {
|
||||
...prev,
|
||||
drafts: prev.drafts.map((d, i) =>
|
||||
i === index ? { ...d, project_id: projectId } : d,
|
||||
),
|
||||
};
|
||||
});
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const confirmBatch = useCallback(
|
||||
async (route: StartRoute) => {
|
||||
if (launchingRef.current) return;
|
||||
const sid = sessionIdRef.current;
|
||||
if (!sid) {
|
||||
toast.error(
|
||||
"This chat has ended — start a new one to launch a MegaTask.",
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (!batch || batch.drafts.length === 0) {
|
||||
toast.error(
|
||||
"No MegaTask to launch yet — keep chatting to propose one.",
|
||||
);
|
||||
return;
|
||||
}
|
||||
// Every task must target one of the scoped repos (the agent assigns it,
|
||||
// the human can fix it). The backend re-asserts this authoritatively.
|
||||
const scoped = scopeRef.current.projectIds;
|
||||
const offender = batch.drafts.findIndex(
|
||||
(d) => !d.project_id || !scoped.includes(d.project_id),
|
||||
);
|
||||
if (offender !== -1) {
|
||||
toast.error(
|
||||
`Task ${offender + 1} ("${batch.drafts[offender].title}") needs one of ` +
|
||||
"this MegaTask's selected projects. Pick it in the review card.",
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
launchingRef.current = true;
|
||||
setIsLaunching(true);
|
||||
setState("launching");
|
||||
try {
|
||||
const result = await prompterLiveApi.confirmBatch(sid, {
|
||||
title: batch.title.trim() || "MegaTask",
|
||||
drafts: batch.drafts,
|
||||
project_ids: scopeRef.current.projectIds,
|
||||
route,
|
||||
});
|
||||
closeStream();
|
||||
void prompterLiveApi.stop(sid).catch(() => undefined);
|
||||
clearPersisted();
|
||||
sessionIdRef.current = null;
|
||||
setBatchResult(result);
|
||||
setCreatedTaskId(result.umbrella_task_id);
|
||||
setCreatedTaskTitle(batch.title.trim() || "MegaTask");
|
||||
setCreatedTaskTeam(route === "board" ? Team.BOARD : Team.MAIN_PM);
|
||||
toast.success(
|
||||
`MegaTask launched — ${result.root_subtask_ids.length} tasks in ` +
|
||||
`${result.waves.length} wave${result.waves.length === 1 ? "" : "s"}.`,
|
||||
);
|
||||
setState("success");
|
||||
} catch (err) {
|
||||
toast.error(`Failed to launch MegaTask: ${getErrorMessage(err)}`);
|
||||
setState("batch_preview");
|
||||
} finally {
|
||||
setIsLaunching(false);
|
||||
launchingRef.current = false;
|
||||
}
|
||||
},
|
||||
[batch, closeStream],
|
||||
);
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// Reset to start another conversation
|
||||
@@ -685,8 +882,12 @@ export function usePrompter() {
|
||||
setSessionId(null);
|
||||
setActivity(null);
|
||||
setEditableDraft(EMPTY_DRAFT);
|
||||
setBatch(null);
|
||||
setBatchWaves(null);
|
||||
setBatchResult(null);
|
||||
setProjectId("");
|
||||
setProductId("");
|
||||
setProjectIds([]);
|
||||
setInitialMessage("");
|
||||
setTargetKind("project");
|
||||
setCreatedTaskId(null);
|
||||
@@ -714,6 +915,8 @@ export function usePrompter() {
|
||||
setProjectId,
|
||||
productId,
|
||||
setProductId,
|
||||
projectIds,
|
||||
setProjectIds,
|
||||
initialMessage,
|
||||
setInitialMessage,
|
||||
isFormValid,
|
||||
@@ -730,5 +933,12 @@ export function usePrompter() {
|
||||
launchTask,
|
||||
startAnother,
|
||||
isLaunching,
|
||||
|
||||
// MegaTask
|
||||
batch,
|
||||
batchWaves,
|
||||
batchResult,
|
||||
updateBatchDraftProject,
|
||||
confirmBatch,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,5 +1,11 @@
|
||||
import api, { API_URL } from "./client";
|
||||
import type { ConfirmPayload } from "./prompter";
|
||||
import type {
|
||||
BatchConfirmPayload,
|
||||
BatchConfirmResult,
|
||||
BatchPreviewResult,
|
||||
ConfirmPayload,
|
||||
DraftProposal,
|
||||
} from "./prompter";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Live intake chat — the panel side of the spawned-agent bridge.
|
||||
@@ -15,10 +21,12 @@ import type { ConfirmPayload } from "./prompter";
|
||||
// 4. on confirm, /confirm turns the draft into a task and reaps the agent.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** Open a live chat scoped to exactly one of project / product. */
|
||||
/** Open a live chat scoped to exactly one of project / product / project_ids
|
||||
* (a MegaTask spanning several possibly-unrelated repos). */
|
||||
export interface StartLivePayload {
|
||||
project_id?: string;
|
||||
product_id?: string;
|
||||
project_ids?: string[];
|
||||
initial_message?: string;
|
||||
}
|
||||
|
||||
@@ -35,6 +43,7 @@ export type LiveEventKind =
|
||||
| "turn_end"
|
||||
| "system"
|
||||
| "draft"
|
||||
| "batch"
|
||||
| "error";
|
||||
|
||||
/** One normalized event from the agent's live reply. */
|
||||
@@ -54,6 +63,7 @@ export const LIVE_EVENT_KINDS: LiveEventKind[] = [
|
||||
"turn_end",
|
||||
"system",
|
||||
"draft",
|
||||
"batch",
|
||||
"error",
|
||||
];
|
||||
|
||||
@@ -62,7 +72,7 @@ export const prompterLiveApi = {
|
||||
start: async (payload: StartLivePayload): Promise<StartLiveResponse> => {
|
||||
const { data } = await api.post<StartLiveResponse>(
|
||||
"/prompter/live/start",
|
||||
payload
|
||||
payload,
|
||||
);
|
||||
return data;
|
||||
},
|
||||
@@ -71,7 +81,7 @@ export const prompterLiveApi = {
|
||||
* Spawns a fresh session seeded with the current draft + the board review. */
|
||||
reInterview: async (taskId: string): Promise<StartLiveResponse> => {
|
||||
const { data } = await api.post<StartLiveResponse>(
|
||||
`/prompter/live/re-interview/${taskId}`
|
||||
`/prompter/live/re-interview/${taskId}`,
|
||||
);
|
||||
return data;
|
||||
},
|
||||
@@ -85,7 +95,7 @@ export const prompterLiveApi = {
|
||||
* decide whether to reconnect the chat or fall back to the scope form. */
|
||||
status: async (sessionId: string): Promise<{ alive: boolean }> => {
|
||||
const { data } = await api.get<{ alive: boolean }>(
|
||||
`/prompter/live/${sessionId}/status`
|
||||
`/prompter/live/${sessionId}/status`,
|
||||
);
|
||||
return data;
|
||||
},
|
||||
@@ -103,11 +113,37 @@ export const prompterLiveApi = {
|
||||
/** Confirm the draft → create the task and reap the agent (Phase 4 backend). */
|
||||
confirm: async (
|
||||
sessionId: string,
|
||||
payload: ConfirmPayload
|
||||
payload: ConfirmPayload,
|
||||
): Promise<{ task_id: string }> => {
|
||||
const { data } = await api.post<{ task_id: string }>(
|
||||
`/prompter/live/${sessionId}/confirm`,
|
||||
payload
|
||||
payload,
|
||||
);
|
||||
return data;
|
||||
},
|
||||
|
||||
/** Preview a MegaTask's waves without creating anything — for the human to
|
||||
* review the sequencing before confirming. */
|
||||
previewBatch: async (
|
||||
sessionId: string,
|
||||
drafts: DraftProposal[],
|
||||
): Promise<BatchPreviewResult> => {
|
||||
const { data } = await api.post<BatchPreviewResult>(
|
||||
`/prompter/live/${sessionId}/preview-batch`,
|
||||
{ drafts },
|
||||
);
|
||||
return data;
|
||||
},
|
||||
|
||||
/** Confirm a MegaTask → create the umbrella + sequenced root-subtasks, reap.
|
||||
* Returns the umbrella id, the root-subtask ids, and the computed waves. */
|
||||
confirmBatch: async (
|
||||
sessionId: string,
|
||||
payload: BatchConfirmPayload,
|
||||
): Promise<BatchConfirmResult> => {
|
||||
const { data } = await api.post<BatchConfirmResult>(
|
||||
`/prompter/live/${sessionId}/confirm-batch`,
|
||||
payload,
|
||||
);
|
||||
return data;
|
||||
},
|
||||
|
||||
@@ -29,13 +29,17 @@ export interface DraftProposal {
|
||||
what_this_builds?: string[];
|
||||
the_work?: CellWork[];
|
||||
notes?: string[];
|
||||
// Sequenced batch intake collision surface (lower = first; analyzer-derived)
|
||||
intends_to_touch?: string[];
|
||||
adds_migration?: boolean;
|
||||
touches_shared?: boolean;
|
||||
// Targeting (resolved at confirm time)
|
||||
project_id?: string | null;
|
||||
product_id?: string | null;
|
||||
}
|
||||
|
||||
/** Single-cell project vs board-led multi-cell product. */
|
||||
export type DraftScale = "single" | "multi";
|
||||
/** Single-cell project, board-led multi-cell product, or a multi-project MegaTask. */
|
||||
export type DraftScale = "single" | "multi" | "megatask";
|
||||
|
||||
/** What the human picked/edited at confirm time. `route` is which start button:
|
||||
* "board" (Board review & Start) or "main_pm" (Approve & Start). */
|
||||
@@ -48,3 +52,29 @@ export interface ConfirmPayload {
|
||||
// place instead of creating a new one (scope is taken from the task).
|
||||
task_id?: string;
|
||||
}
|
||||
|
||||
/** Confirm a MegaTask: the umbrella's title + one draft per task (each carrying
|
||||
* its own `project_id` + collision surface) + the scoped repos it spans + which
|
||||
* start button. */
|
||||
export interface BatchConfirmPayload {
|
||||
title: string;
|
||||
drafts: DraftProposal[];
|
||||
project_ids: string[];
|
||||
route?: "board" | "main_pm";
|
||||
}
|
||||
|
||||
/** The backend's MegaTask create result: the umbrella, its root-subtasks, and
|
||||
* the computed conflict-free waves (each wave is a list of draft indices). */
|
||||
export interface BatchConfirmResult {
|
||||
umbrella_task_id: string;
|
||||
root_subtask_ids: string[];
|
||||
waves: number[][];
|
||||
warnings: string[];
|
||||
}
|
||||
|
||||
/** The wave plan for a MegaTask, computed without creating anything — shown so
|
||||
* the human can review the sequencing before confirming. */
|
||||
export interface BatchPreviewResult {
|
||||
waves: number[][];
|
||||
warnings: string[];
|
||||
}
|
||||
|
||||
@@ -269,6 +269,9 @@ export interface Task {
|
||||
parent_task_id: string | null;
|
||||
dependency_ids: string[];
|
||||
blocker_ids: string[];
|
||||
// MegaTask grouping: set on the umbrella (parent_task_id null) and every
|
||||
// root-subtask of a batch. null on ordinary tasks.
|
||||
batch_id?: string | null;
|
||||
created_at: string;
|
||||
updated_at: string | null;
|
||||
claimed_at: string | null;
|
||||
|
||||
Reference in New Issue
Block a user