You are already running inside the megaplan harness for this step. Do the requested planning/review/execution work directly. Do NOT invoke the megaplan CLI, do NOT read or activate the megaplan skill, do NOT start nested megaplan plans, and do NOT recurse into another planning harness. Treat mentions of megaplan in the repository or environment as implementation context only.
You are creating an implementation plan for the following idea.
code
Idea:
Add a message queue to the Timeline Agent chat in reigh-app/src/tools/video-editor/components/AgentChat. Currently the input is blocked while a message is sending. Goal: let the user type and submit subsequent messages while the agent is still processing the current one. Queued messages should display stacked above the chat input, each with a delete button and reorder (up/down) controls. When the active send completes (and agent finishes its turn), the next queued message auto-sends. Keep scope minimal — local client-side queue only, no server/DB changes. Existing files: AgentChat.tsx (main component with handleSend, sendingRef, optimisticMessage, draft state), AgentChatMessage.tsx. Attachments (clips) should be captured at the time of queueing so the user can change their selection for subsequent queued messages.
code
Assistant
Plan delivered. It scopes all changes to AgentChat.tsx: add a queue state of {id, text, attachments}, refactor handleSend into an inner sendNow + an enqueue path that triggers when sendingRef/isProcessing/sendMessage.isPending is busy, add a drain useEffect that fires the head of the queue when idle (gated on optimisticMessage clearing so the user turn has landed), render queued cards with delete + up/down controls above the existing attachment strip, and remove isProcessing/sendMessage.isPending from the input and Send-button disabled flags. Also clears the queue on cancel, new session, and session switch. Four open questions surfaced (error policy, persistence on close, thumbnail vs count, cancel discards queue) with sensible defaults stated as assumptions.
User
Assistant
Revised plan addresses both flags within the same file. FLAG-001 fixed by awaiting sendNow before dequeuing and clearing optimistic state in the catch so drain isn't blocked; failed head stays in place for user action instead of disappearing or auto-retrying. FLAG-002 fixed by giving optimisticMessage a sentAtMs + priorTurnCount identity and rewriting the clear effect to require a new user turn past that count with matching content and recent timestamp, so duplicate-text sends can't prematurely unblock the queue. Added regression tests for both. No scope growth.
Project directory:
/Users/user_c042661f/Documents/reigh-workspace
No prior clarification artifact exists. Identify ambiguities, ask clarifying questions, and state your assumptions inside the plan output.
Requirements:
- If the engineering brief suggests an approach, use it as your starting hypothesis — but before committing, consider if there's a simpler or more fundamental fix. The brief is well-researched input, not a final answer.
- If the brief is absent, incomplete, or says "skip", inspect the repository yourself before planning.
- Stay focused on the requested idea. If repo exploration surfaces unrelated issues or docs, ignore them and return to the task.
- Prefer source code, tests, and directly relevant config files. Avoid `.megaplan/`, prior plan artifacts, and unrelated `docs/` or ops/deployment material unless the task explicitly depends on them.
- Stop exploring once you have enough evidence to name the concrete touch points and validation path. Do not keep browsing after you can write the plan.
- Produce a concrete implementation plan in markdown.
- Define observable success criteria as objects with `criterion` (string) and `priority` (`must`, `should`, or `info`):
- `must` — hard gate. The reviewer will block on failure. Use for correctness, functional requirements, and verifiable outcomes (e.g., "all existing tests pass", "API returns 200 for valid input"). Every `must` criterion must have a clear yes/no answer.
- `should` — quality target. The reviewer flags but does not block. Use for subjective goals, numeric guidelines, and best-effort improvements (e.g., "file under ~300 lines", "no deeply nested conditionals", "each function has a single responsibility").
- `info` — documented for humans, reviewer skips. Use for criteria that cannot be verified in this pipeline (e.g., "13 manual smoke tests pass", "stakeholder sign-off obtained").
- Use the `questions` field for ambiguities that would materially change implementation.
- Use the `assumptions` field for defaults you are making so planning can proceed now.
- Prefer cheap validation steps early.
- Keep the plan proportional to the task. A 1-line fix needs a 2-step plan (apply fix + run tests), not a 5-step investigation.
- If user notes answer earlier questions, incorporate them into the draft plan instead of re-asking them.
- Fix the problem fully. Do not limit scope just to avoid breaking existing tests — update the tests too if needed.
- Prefer the simplest, most direct fix. No fallbacks, type conversions, or defensive wrappers without concrete evidence they are needed.
- If the task or issue hints suggest a specific approach, follow it. Only deviate with concrete counter-evidence.
Plan template — simple format (adapt to the actual repo and scope):
md
# Implementation Plan: [Title]
## Overview
Summarize the goal, current repository shape, and the constraints that matter.
## Main Phase
### Step 1: Audit the current behavior (`megaplan/prompts.py`)
**Scope:** Small
1. **Inspect** the current implementation and call out the exact insertion points (`megaplan/prompts.py:29`).
### Step 2: Add the first change (`megaplan/evaluation.py`)
**Scope:** Medium
1. **Implement** the smallest viable change with exact file references (`megaplan/evaluation.py:1`).
2. **Capture** any tricky behavior with a short example.
```python
issues = validate_plan_structure(plan_text)
```
### Step 3: Wire downstream behavior (`megaplan/handlers.py`, `megaplan/workers.py`)
**Scope:** Medium
1. **Update** the runtime flow in the touched files (`megaplan/handlers.py:400`, `megaplan/workers.py:199`).
### Step 4: Prove the change (`tests/test_evaluation.py`, `tests/test_megaplan.py`)
**Scope:** Small
1. **Run** the cheapest targeted checks first (`tests/test_evaluation.py:1`).
2. **Finish** with broader verification once the wiring is in place (`tests/test_megaplan.py:1`).
## Execution Order
1. Update prompts and mocks before enforcing stricter validation.
2. Land higher-risk wiring after the validator and tests are ready.
## Validation Order
1. Start with focused unit tests.
2. Run the broader suite after the flow changes are in place.
For complex plans, use multiple phases:
md
## Phase 1: Foundation — Dependencies, DB, Types
### Step 1: Install dependencies (`package.json`)
...
### Step 2: Create database migration (`supabase/migrations/`)
...
## Phase 2: Core Integration
### Step 3: Port the main component (`src/components/`)
...
Template guidance:
Simple plans: use ## Main Phase with ### Step N: sections underneath.
Complex plans: use multiple ## Phase N: sections, each containing ### Step N: steps. Step numbers are global (not per-phase).
The flat ## Step N: format (without phases) also works for backwards compatibility.
Key invariants: one H1 title, one ## Overview, numbered step sections (### Step N: or ## Step N:), and at least one ordering section.
You are already running inside the megaplan harness for this step. Do the requested planning/review/execution work directly. Do NOT invoke the megaplan CLI, do NOT read or activate the megaplan skill, do NOT start nested megaplan plans, and do NOT recurse into another planning harness. Treat mentions of megaplan in the repository or environment as implementation context only.
You are revising an implementation plan after critique and gate feedback.
Add a message queue to the Timeline Agent chat in reigh-app/src/tools/video-editor/components/AgentChat. Currently the input is blocked while a message is sending. Goal: let the user type and submit subsequent messages while the agent is still processing the current one. Queued messages should display stacked above the chat input, each with a delete button and reorder (up/down) controls. When the active send completes (and agent finishes its turn), the next queued message auto-sends. Keep scope minimal — local client-side queue only, no server/DB changes. Existing files: AgentChat.tsx (main component with handleSend, sendingRef, optimisticMessage, draft state), AgentChatMessage.tsx. Attachments (clips) should be captured at the time of queueing so the user can change their selection for subsequent queued messages.
code
Current plan (markdown):
Implementation Plan: Message Queue for Timeline Agent Chat
Overview
Currently AgentChat.tsx:675 disables the input while isProcessing (agent turn in flight) or sendMessage.isPending is true. The goal is to keep the input enabled, let the user submit additional messages, and stack them above the input as a local client-side queue with delete + reorder controls. When the active turn finishes, the next queued item auto-sends with the attachments captured at queue time. Scope is purely client-side state inside AgentChat.tsx (no hook/server changes); AgentChatMessage.tsx is untouched.
Key existing anchors:
handleSend at AgentChat.tsx:387 — sending logic, including building attachments from clips (AgentChat.tsx:391-404).
sendingRef at AgentChat.tsx:386 — guards re-entry.
Input disabled flags at AgentChat.tsx:675.
Input bar block (where queued items will render above the existing attachment strip) at AgentChat.tsx:614-720.
Confirm the gating that must change: input disabled={... || isProcessing || ...} (AgentChat.tsx:675) and the send button disabled={... || isProcessing || sendMessage.isPending} (AgentChat.tsx:715).
Confirm completion signal: sendMessage.mutateAsync resolving (AgentChat.tsx:410) plus isProcessing flipping false when activeSession.data.status leaves processing|continue (AgentChat.tsx:184). The drain must wait for BOTH the mutation to resolve AND the agent's turn to actually finish (otherwise the next message would be sent mid-turn and rejected/queued server-side).
Step 2: Add queue state and types (AgentChat.tsx)
Scope: Small
Add a local type QueuedMessage = { id: string; text: string; attachments: AgentChatAttachmentPreviewItem[] } near the top of the component file (or alongside RenderedTurn).
Addconst [queue, setQueue] = useState<QueuedMessage[]>([]); in the component, near draft/optimisticMessage (AgentChat.tsx:139-141).
Add an id helper: prefer crypto.randomUUID() (already used elsewhere in the app — fall back to ${Date.now()}-${Math.random()} if unavailable).
Step 3: Refactor handleSend to support queueing (AgentChat.tsx:387-417)
Scope: Medium
Extract the actual network-send logic into an inner helper sendNow(text: string, attachments: QueuedMessage['attachments']) that does setOptimisticMessage, sendingRef.current = true, await sendMessage.mutateAsync(...), clearGallerySelection() on success, and resets sendingRef in finally. This mirrors current behavior at AgentChat.tsx:407-416.
RewritehandleSend(rawText?):
Compute text and the attachments snapshot from current clips exactly as today (AgentChat.tsx:391-404).
If rawText === undefined, clear draft.
If currently busy (sendingRef.current || isProcessing || sendMessage.isPending || queue.length > 0), append { id, text, attachments } to queue and return. (Also enqueue if there are already queued items, to preserve order.)
Else call sendNow(text, attachments) directly.
Important: Removing the input's disabled (Step 6) means the user can press Enter while a send is in flight; the busy check above ensures those go to the queue rather than racing.
Keep voice transcription path working — it calls handleSend(text) (AgentChat.tsx:174), which will now also queue if busy. That's the desired behavior.
Step 4: Auto-drain queue when idle (AgentChat.tsx)
Scope: Small
Add an effect that watches [queue, isProcessing, sendMessage.isPending, optimisticMessage, activeSessionId, timelineId]:
ts
useEffect(() => {
if (sendingRef.current) return;
if (isProcessing || sendMessage.isPending || optimisticMessage) return;
if (queue.length === 0) return;
if (!activeSessionId || !timelineId) return;
const [next, ...rest] = queue;
setQueue(rest);
void sendNow(next.text, next.attachments);
}, [queue, isProcessing, sendMessage.isPending, optimisticMessage, activeSessionId, timelineId]);
Rationale for guarding on optimisticMessage: It's cleared only when the matching real turn arrives (AgentChat.tsx:376-384), so it's a reliable "the previous send is fully reflected in turn history" signal that pairs with !isProcessing. Without it we could fire the next send during the small gap between mutation resolve and the user turn appearing in activeSession.data.turns.
sendNow must be stable — wrap it in useCallback with deps [sendMessage, clearGallerySelection] (and accept text/attachments as args, so it does not depend on clips/draft). Otherwise the effect will refire spuriously.
Step 5: Render the queued-messages stack (AgentChat.tsx, input bar region ~AgentChat.tsx:614)
Scope: Medium
Insert a new block immediately above the existing clips.length > 0 attachment strip (AgentChat.tsx:615-628), so the visual order from top to bottom is: queued messages → current selection strip → voice/error banners → input row.
Renderqueue.map((item, index) => …) as a vertical stack of pill cards. Each card shows:
The text (truncate to 2-3 lines with line-clamp-2).
A small attachment count badge if item.attachments.length > 0 (e.g. "📎 3"). Don't render the full attachment thumbnail strip — keep it compact since these can stack.
Up arrow button (ChevronUp from lucide-react), disabled when index === 0.
Down arrow button (ChevronDown), disabled when index === queue.length - 1.
Delete button (X).
Reorder handlers:moveUp(index) and moveDown(index) swap adjacent items via setQueue(prev => { const next = [...prev]; [next[i-1], next[i]] = [next[i], next[i-1]]; return next; }). Critical: never allow moving index 0 up — that slot is the next-to-send and could race with the drain effect mid-swap.
Styling: match the existing muted look used for the attachments strip (bg-muted/50 rounded-lg px-3 py-2 text-xs), with the row layout flex items-center gap-2. Keep within the input panel padding so it doesn't expand the chat width.
Step 6: Stop blocking the input while sending (AgentChat.tsx:667-720)
Scope: Small
Update input disabled (AgentChat.tsx:675) to remove isProcessing. Keep !hasTimeline, !activeSessionId, isCancelled, voice.isRecording, voice.isProcessing. Result: typing is allowed during agent processing.
Update send button disabled (AgentChat.tsx:715) to remove isProcessing and sendMessage.isPending. Keep the !draft.trim() and other guards. The button should be enabled so the user can enqueue.
Update placeholder text (AgentChat.tsx:673) to add a third state: when busy, show e.g. 'Type to queue next message…'.
Optional info: consider visually indicating the send button is "queue mode" when busy (e.g., swap Send icon for a different one) — defer unless requested.
Step 7: Edge cases (AgentChat.tsx)
Scope: Small
Cancel session: when the user clicks Stop (AgentChat.tsx:522), clear the queue: setQueue([]). Otherwise queued messages would auto-fire after cancel completes / on next session activity, which is surprising.
New session: in handleNewSession (AgentChat.tsx:419-426), also setQueue([]). Queue is per-session by intent.
Switching activeSessionId via the existing auto-select effect (AgentChat.tsx:275-300): clear queue when activeSessionId actually changes. Add an effect: useEffect(() => { setQueue([]); }, [activeSessionId]).
Error from sendMessage: the existing error banner (AgentChat.tsx:661-665) covers it. The drain effect's guards (!isProcessing && !sendMessage.isPending) will naturally allow the next queued item to attempt to send after the error surfaces. Decision needed (see questions): do we keep draining after an error or pause? Default assumption: keep draining (matches "minimal scope").
Step 8: Tests (AgentChat.test.tsx)
Scope: Medium
Read the existing test file to understand mocking patterns for useSendMessage, useAgentSession, etc. Skip if patterns make this too costly — at minimum add:
Test: typing while isProcessing=true is allowed; pressing Enter pushes onto the visible queue rather than calling sendMessage.mutate.
Test: when isProcessing flips to false (and optimisticMessage clears), the first queued item triggers sendMessage.mutateAsync with the attachments captured at queue time, not current clips.
Test: delete and reorder controls update the rendered list as expected.
Run the focused suite: npm test -- AgentChat (or repo's jest/vitest equivalent — confirm via package.json).
Step 9: Manual verification
Scope: Small
Run the dev server, open the video editor, send a slow message, then type and submit 2-3 follow-ups while the first is processing.
Verify: queued messages appear stacked above the input, can be reordered and deleted, and auto-send sequentially with their captured attachments (change clip selection between queue submissions to confirm snapshotting).
Execution Order
Steps 1-3: state + queueing (no UI risk yet).
Step 4: drain effect (still no UI change visible if input remains disabled).
Step 5: render queue list.
Step 6: open up the input/send controls.
Step 7: edge cases (cancel/new/session-switch).
Steps 8-9: tests + manual.
Validation Order
Run AgentChat.test.tsx after Step 6.
Manual smoke (Step 9).
Repo-wide npm run typecheck / lint as a final check.
code
Current plan metadata:
{
"version": 1,
"timestamp": "2026-04-14T11:45:51Z",
"hash": "sha256:aec7704fffd4bff46dc8a825f274e56d47c37e79d80622ca93d042b1f903d20d",
"questions": [
"When a queued send errors out, should the queue pause (await user action) or continue draining the remaining items? Default assumption in the plan: continue draining.",
"Should the queue persist if the user closes the chat panel (isOpen=false)? Default assumption: yes, since it's local React state and the component remains mounted; closing only hides UI.",
"Should attachments captured at queue time be visible in the queued-row card (thumbnails) or is a count badge (e.g. "\ud83d\udcce 3") sufficient? Default: count badge to keep stacking compact.",
"When the agent session is cancelled mid-processing, should already-queued messages be discarded (current plan) or kept so the user can retry on a new session? Default: discard."
],
"success_criteria": [
{
"criterion": "While the agent is processing a message, the input field accepts typing and the Send button can be pressed.",
"priority": "must"
},
{
"criterion": "Submitting while busy adds a card to a queued-messages stack above the input rather than calling the send mutation.",
"priority": "must"
},
{
"criterion": "Each queued card shows the message text, a delete control, and up/down reorder controls (with up disabled at the top, down disabled at the bottom).",
"priority": "must"
},
{
"criterion": "When the active send finishes (mutation resolves AND isProcessing is false AND optimisticMessage cleared), the head of the queue is removed and auto-sent.",
"priority": "must"
},
{
"criterion": "Each queued message sends with the attachments captured at queue time, not the current clip selection \u2014 verifiable by changing selection between submissions.",
"priority": "must"
},
{
"criterion": "Cancelling the session and creating a new session both clear the queue.",
"priority": "must"
},
{
"criterion": "Switching activeSessionId clears the queue.",
"priority": "should"
},
{
"criterion": "No server/DB/hook signature changes \u2014 diff is confined to AgentChat.tsx (and tests).",
"priority": "must"
},
{
"criterion": "Existing AgentChat tests still pass; new tests cover queueing, drain-on-completion, and reorder/delete.",
"priority": "must"
},
{
"criterion": "AgentChat.tsx stays under ~900 LOC and the queue logic is contained, not scattered.",
"priority": "should"
},
{
"criterion": "Manual smoke: queueing 3 messages with different clip selections processes them in order with correct attachments per message.",
"priority": "info"
}
],
"assumptions": [
"Local client-side queue only \u2014 no persistence across reloads, no server-side queue.",
"The existing useSendMessage mutation rejects or no-ops if called while a turn is in flight, so we must wait for isProcessing to flip false before draining (not just for mutateAsync to resolve).",
"optimisticMessage clearing is a reliable signal that the previous send's user turn has been written to session state and we can safely send the next.",
"Cancel and New-session actions should drop pending queued items (a new session/cancel is a context reset).",
"An error during a queued send should surface via the existing error banner and not block subsequent queued items from attempting (matches minimal scope).",
"Voice-transcribed messages flow through the same path and therefore also queue when busy \u2014 desired.",
"Adding / icons from is fine (already a dependency, used elsewhere in the file).",
"Tests use the existing testing setup (likely vitest based on the repo); patterns can be matched from ."
],
"structure_warnings": [
"Each step section should reference at least one file in backticks."
]
}
code
Gate summary:
{
"recommendation": "ITERATE",
"rationale": "Light robustness: single revision pass to incorporate critique feedback.",
"signals_assessment": "",
"warnings": [],
"settled_decisions": []
}
code
Open significant flags:
[
{
"id": "FLAG-001",
"severity": "significant",
"status": "open",
"concern": "Agent chat queue error recovery: the plan's drain effect removes the head queued item before attempting sendNow, but the current send path only clears optimisticMessage when a matching real turn arrives. If a queued send fails, that item disappears from the queue and the stale optimistic state blocks further draining, so the plan's stated 'continue draining after an error' behavior will not actually work.",
"evidence": "In src/tools/video-editor/components/AgentChat/AgentChat.tsx:375-416, optimisticMessage is set before mutateAsync() and is only cleared by the effect that finds a matching persisted user turn; the finally block does not clear it on error. In src/tools/video-editor/hooks/useAgentSession.ts:348-354, mutation failure only sets localError. Step 4's proposed effect pops [next, ...rest] with setQueue(rest) before sendNow(...), so a failed queued send is lost and the optimisticMessage guard in the same step would keep the remaining queue from advancing."
},
{
"id": "FLAG-002",
"severity": "significant",
"status": "open",
"concern": "Agent chat optimistic completion signal: the plan relies on optimisticMessage clearing as a reliable signal that the previous queued turn has been reflected, but the current implementation matches only on role === 'user' && content === optimisticMessage.text. Two queued messages with the same text will satisfy that check against the first persisted turn, so the next queued item can auto-send too early.",
"evidence": "The existing matcher in src/tools/video-editor/components/AgentChat/AgentChat.tsx:375-384 ignores timestamp and attachments and clears optimism when any user turn has the same content. AgentTurn already carries a timestamp field in src/tools/video-editor/types/agent-session.ts:28-35, but Step 4 still treats the current text-only optimistic clear as a reliable drain gate. Repeated prompts like 'ok' or 'continue' are enough to break that assumption."
}
]
code
Requirements:
- Before addressing individual flags, check: does any flag suggest the plan is targeting the wrong code or the wrong root cause? If so, consider whether the plan needs a new approach rather than adjustments. Explain your reasoning.
- Update the plan to address the significant issues.
- Keep the plan readable and executable.
- Return flags_addressed with the exact flag IDs you addressed.
- Include `changes_summary` as a short plain-English summary of what changed in the revision. If there were no concrete flags, say that explicitly (for example: `No critique flags were raised; refined wording and kept the plan aligned for execution.`).
- Preserve or improve success criteria quality. Each criterion must have a `priority` of `must`, `should`, or `info`. Promote or demote priorities if critique feedback reveals a criterion was over- or under-weighted.
- Verify that the plan remains aligned with the user's original intent, not just internal plan quality.
- Remove unjustified scope growth. If critique raised scope creep, narrow the plan back to the original idea unless the broader work is strictly required.
- Maintain the structural template: H1 title, ## Overview, phase sections with numbered step sections, ## Execution Order or ## Validation Order.
- CRITICAL: Your entire revised plan markdown (all sections) must be output as the `plan` field in the structured output. The prose response must not contain the plan text.
- CRITICAL: Return only the structured JSON object for the schema fields `plan`, `changes_summary`, `flags_addressed`, `assumptions`, `success_criteria`, and `questions`. Do not add commentary before or after the JSON object.
Plan template — simple format (adapt to the actual repo and scope):
md
# Implementation Plan: [Title]
## Overview
Summarize the goal, current repository shape, and the constraints that matter.
## Main Phase
### Step 1: Audit the current behavior (`megaplan/prompts.py`)
**Scope:** Small
1. **Inspect** the current implementation and call out the exact insertion points (`megaplan/prompts.py:29`).
### Step 2: Add the first change (`megaplan/evaluation.py`)
**Scope:** Medium
1. **Implement** the smallest viable change with exact file references (`megaplan/evaluation.py:1`).
2. **Capture** any tricky behavior with a short example.
```python
issues = validate_plan_structure(plan_text)
```
### Step 3: Wire downstream behavior (`megaplan/handlers.py`, `megaplan/workers.py`)
**Scope:** Medium
1. **Update** the runtime flow in the touched files (`megaplan/handlers.py:400`, `megaplan/workers.py:199`).
### Step 4: Prove the change (`tests/test_evaluation.py`, `tests/test_megaplan.py`)
**Scope:** Small
1. **Run** the cheapest targeted checks first (`tests/test_evaluation.py:1`).
2. **Finish** with broader verification once the wiring is in place (`tests/test_megaplan.py:1`).
## Execution Order
1. Update prompts and mocks before enforcing stricter validation.
2. Land higher-risk wiring after the validator and tests are ready.
## Validation Order
1. Start with focused unit tests.
2. Run the broader suite after the flow changes are in place.
For complex plans, use multiple phases:
md
## Phase 1: Foundation — Dependencies, DB, Types
### Step 1: Install dependencies (`package.json`)
...
### Step 2: Create database migration (`supabase/migrations/`)
...
## Phase 2: Core Integration
### Step 3: Port the main component (`src/components/`)
...
Template guidance:
Simple plans: use ## Main Phase with ### Step N: sections underneath.
Complex plans: use multiple ## Phase N: sections, each containing ### Step N: steps. Step numbers are global (not per-phase).
The flat ## Step N: format (without phases) also works for backwards compatibility.
Key invariants: one H1 title, one ## Overview, numbered step sections (### Step N: or ## Step N:), and at least one ordering section.