Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

fix(agents): stop review-note sends from flushing the queue twice (#6710)

Wolf Mermelsteinf26da864e946
diff --git a/apps/web/src/features/agent-changes/primitives/create-agent-changes.ts b/apps/web/src/features/agent-changes/primitives/create-agent-changes.ts
index 389d60ced2..231b0ad869 100644
--- a/apps/web/src/features/agent-changes/primitives/create-agent-changes.ts
+++ b/apps/web/src/features/agent-changes/primitives/create-agent-changes.ts
@@ -30,6 +30,12 @@ export type AgentChangesController = {
setDiffStyle: (style: DiffStyle) => void;
/** Post every queued note to the agent as one prompt. */
sendQueuedNotes: () => void;
+ /**
+ * Take queued notes off the dock as the markdown a composer send should
+ * carry, and mark them sent. Empty when there is nothing to take — so a
+ * second send in the same tick cannot post the same notes again.
+ */
+ consumeSendableNotes: () => string;
/** The handoff card was dismissed for the changeset on screen. */
handoffDismissed: Accessor<boolean>;
dismissHandoff: () => void;
@@ -80,6 +86,14 @@ export function createAgentChanges(options: {
);
};
+ const consumeSendableNotes = () => {
+ const queued = sendableNotes(review.notes());
+ if (queued.length === 0) return '';
+ const markdown = formatNotesForAgent(queued);
+ review.markQueuedSent();
+ return markdown;
+ };
+
return {
context: options.context,
available: () => host.canHaveChanges?.() ?? true,
@@ -91,15 +105,15 @@ export function createAgentChanges(options: {
sendQueuedNotes: () => {
const agent = host.agent;
if (!agent) return;
- const queued = sendableNotes(review.notes());
- if (queued.length === 0) return;
+ if (sendableNotes(review.notes()).length === 0) return;
if (!agent.canSend()) {
host.notify('The agent cannot take a prompt right now.', 'failure');
return;
}
- agent.send(formatNotesForAgent(queued));
- review.markQueuedSent();
+ const markdown = consumeSendableNotes();
+ if (markdown) agent.send(markdown);
},
+ consumeSendableNotes,
handoffDismissed: () => {
const id = model.changeset()?.id;
return id !== undefined && dismissed() === id;
diff --git a/apps/web/src/features/agents-view/components/ChatComposer.tsx b/apps/web/src/features/agents-view/components/ChatComposer.tsx
index 3e11ec9431..7857d22886 100644
--- a/apps/web/src/features/agents-view/components/ChatComposer.tsx
+++ b/apps/web/src/features/agents-view/components/ChatComposer.tsx
@@ -69,7 +69,7 @@ export function ChatComposer(props: {
const disabled = () => !!props.blockedReason || props.session?.disabled;
const canSendNext = () =>
!hasContent() &&
- !props.session?.stopPending &&
+ !props.session?.sendNextHeld &&
props.session?.hasQueuedMessages &&
props.session.onStop &&
!disabled();
diff --git a/apps/web/src/features/block-agent/agent-session-provider.tsx b/apps/web/src/features/block-agent/agent-session-provider.tsx
index b2ed564d32..417d2ea9c5 100644
--- a/apps/web/src/features/block-agent/agent-session-provider.tsx
+++ b/apps/web/src/features/block-agent/agent-session-provider.tsx
@@ -6,10 +6,7 @@ import { isCursorBotId } from '@core/constant/cursorAgent';
import { useUserId } from '@core/context/user';
import { idToDisplayName } from '@core/user/util';
import { useAgentSessionExternalUrlQuery } from '@queries/agent-session/session';
-import type {
- AgentAction,
- AgentSessionResponse,
-} from '@service-agent-harness/generated/schemas';
+import type { AgentSessionResponse } from '@service-agent-harness/generated/schemas';
import {
type Accessor,
createEffect,
@@ -23,6 +20,7 @@ import {
type QueueController,
} from './context/create-queue-controller';
import { resolveSessionId } from './context/resolve-session-id';
+import { createSendNext } from './context/send-next';
import { createInteractionController } from './primitives/create-interaction-controller';
import type { QuoteInsert } from './ui';
@@ -59,20 +57,13 @@ export function AgentSessionProvider(
return served.remove(actionId);
},
};
- const sendNext = () => {
- const head = queue.entries()[0];
- if (!head) return;
- const action: AgentAction | undefined =
- head.kind === 'prompt' && head.prompt != null
- ? { type: 'prompt', prompt: head.prompt }
- : head.kind === 'compact'
- ? { type: 'compact' }
- : undefined;
- void live.issue({ type: 'stop' })?.then((result) => {
- if (result.isErr()) live.retract(head.actionId);
- });
- if (action) live.expect(head.actionId, action);
- };
+ const sendNext = createSendNext({
+ currentTurn: live.currentTurn,
+ entries: queue.entries,
+ issue: live.issue,
+ expect: live.expect,
+ retract: live.retract,
+ });
const interactions = createInteractionController({
sessionId,
pending: () => live.metadata()?.pendingInteractions ?? [],
diff --git a/apps/web/src/features/block-agent/component/AgentComposer.tsx b/apps/web/src/features/block-agent/component/AgentComposer.tsx
index 1f8efe75bf..3210d8e5da 100644
--- a/apps/web/src/features/block-agent/component/AgentComposer.tsx
+++ b/apps/web/src/features/block-agent/component/AgentComposer.tsx
@@ -5,6 +5,7 @@
* marks — so the composer keeps no state of its own.
*/
+import { useOptionalAgentChanges } from '@app/features/agent-changes/context/agent-changes-controller';
import {
createInputAttachmentTracker,
type InputAttachmentData,
@@ -53,6 +54,7 @@ export function AgentComposer(props: {
turn,
registerQuoteInsert,
} = useAgentSession();
+ const changes = useOptionalAgentChanges();
// The fold speculates the action the moment it is issued, so success is
// observed there; only a refusal needs saying here.
@@ -104,7 +106,14 @@ export function AgentComposer(props: {
// the text: issued once, speculated by the fold, and queued server-side
// behind a running turn with the files still on them.
const send = (markdown: string, attachments: InputAttachmentData[]) => {
- act(promptActionOf(markdown, attachments), 'The message could not be sent');
+ // Queued review notes ride this send: taking them here marks them sent
+ // before the prompt is issued, so a second Enter cannot post them again
+ // as their own queued prompt (which would then stop-and-flush).
+ const notes = changes?.consumeSendableNotes() ?? '';
+ const prompt = [markdown, notes]
+ .filter((part) => part.length > 0)
+ .join('\n\n');
+ act(promptActionOf(prompt, attachments), 'The message could not be sent');
attachmentTracker.clearAttachments();
};
@@ -168,12 +177,16 @@ export function AgentComposer(props: {
autofocus={props.autofocus}
busy={busy()}
hasQueuedMessages={queuedItems().length > 0}
- // The fold's own answer to "a stop is already working on this turn",
- // which holds from the moment the stop is folded until the turn
- // actually ends. `pending` alone clears as soon as the log confirms
- // the cancel, which is well before the runtime winds the turn down -
- // and every Enter in that gap posted another cancel.
- stopPending={turn() === 'stopping'}
+ // Read off the fold's turn discriminant, never `pending`, which
+ // clears as soon as the log confirms a cancel - well before the
+ // runtime winds the turn down, and every Enter in that gap posted
+ // another cancel. `stopping` is a stop already working on this turn.
+ // `starting` is the prompt the last advance showed as sent, still
+ // unconfirmed: the server has not dispatched it, so a stop now would
+ // end the turn already ending and the server would dispatch *that*
+ // head - the next one would sit as a sent-looking bubble while it
+ // waits. Enter is admitted again once the log confirms the head.
+ sendNextHeld={turn() === 'stopping' || turn() === 'starting'}
// Prompts go straight to the service, so sending needs a session to
// post to — a block whose create is still on the wire can be typed
// into, but not sent from, until the id lands.
diff --git a/apps/web/src/features/block-agent/context/AgentSessionContext.tsx b/apps/web/src/features/block-agent/context/AgentSessionContext.tsx
index 1c52a414d9..ffcbfd041d 100644
--- a/apps/web/src/features/block-agent/context/AgentSessionContext.tsx
+++ b/apps/web/src/features/block-agent/context/AgentSessionContext.tsx
@@ -63,7 +63,10 @@ export type AgentSessionState = {
* Send the next queued message now: stop the running turn, and show the
* queue head as sent under the id the server already holds it by. The
* server dispatches it when the turn actually ends, and that row promotes
- * the speculation in place. No-op with nothing queued.
+ * the speculation in place. No-op with nothing queued, and while the head
+ * a previous call showed as sent is still unconfirmed (`turn` reads
+ * `starting`): a stop posted then would end the turn already ending, and
+ * the server would dispatch that head, not the next one.
*/
sendNext: () => void;
/** The live requests, and the action that answers each one. */
diff --git a/apps/web/src/features/block-agent/context/create-agent-session.ts b/apps/web/src/features/block-agent/context/create-agent-session.ts
index b8203d1c55..fb9c83dccf 100644
--- a/apps/web/src/features/block-agent/context/create-agent-session.ts
+++ b/apps/web/src/features/block-agent/context/create-agent-session.ts
@@ -21,6 +21,7 @@ import type {
FoldedMessage,
FoldedStreamEvent,
SessionMetadata,
+ TurnState,
} from '@service-agent-fold/generated/types';
import { agentHarnessServiceClient } from '@service-agent-harness/client';
import type {
@@ -63,6 +64,13 @@ export type AgentSessionHandle = {
expect: (actionId: string, action: AgentAction) => void;
/** Take a speculation back. See {@link AgentSession.retract}. */
retract: (actionId: string) => void;
+ /**
+ * The session's own turn state, read at call time - not reactive. It is
+ * ahead of `metadata().turn` by the worker round trip: a prompt just
+ * issued or expected reads `starting` here before the fold has reported
+ * it. See {@link AgentSession.currentTurn}.
+ */
+ currentTurn: () => TurnState;
/**
* Adopt a newer snapshot of this session (the bounded external-url poll).
* No-op when the payload is for a different session.
@@ -287,6 +295,7 @@ export function createAgentSession(
expect: (actionId, action) =>
live()?.expect(actionId, action, { userId: options.userId() }),
retract: (actionId) => live()?.retract(actionId),
+ currentTurn: () => untrack(live)?.currentTurn() ?? 'idle',
applySnapshot: (snapshot) => {
if (sessionId() !== snapshot.id) return;
mutate(snapshot);
diff --git a/apps/web/src/features/block-agent/context/send-next.ts b/apps/web/src/features/block-agent/context/send-next.ts
new file mode 100644
index 0000000000..2e8b13bb6b
--- /dev/null
+++ b/apps/web/src/features/block-agent/context/send-next.ts
@@ -0,0 +1,49 @@
+/**
+ * "Send the next queued message now": stop the running turn, and show the
+ * queue head as sent under the id the server already holds it by. The
+ * server dispatches the head when the turn actually ends, and that row
+ * promotes the speculation in place.
+ */
+
+import type { IssueResult } from '@core/agent-session/AgentSession';
+import type { TurnState } from '@service-agent-fold/generated/types';
+import type {
+ AgentAction,
+ QueuedActionDto,
+} from '@service-agent-harness/generated/schemas';
+
+export function createSendNext(session: {
+ /**
+ * The session's turn as it stands at call time, including what it has
+ * just speculated: the fold's reactive report lags by the worker round
+ * trip, and two presses inside it must not both pass.
+ */
+ currentTurn: () => TurnState;
+ /** The queue as the composer shows it: the server's entries minus any the fold already shows. */
+ entries: () => QueuedActionDto[];
+ issue: (action: AgentAction) => Promise<IssueResult> | undefined;
+ expect: (actionId: string, action: AgentAction) => void;
+ retract: (actionId: string) => void;
+}): () => void {
+ return () => {
+ // The head a previous send-next showed as sent is still on its way: the
+ // server has not dispatched it, so a stop posted now lands on the turn
+ // that is already ending and the server dispatches *that* head when it
+ // does - not this one. Speculating this one anyway would show it as sent
+ // while it waits in the queue, behind a turn the server is only now
+ // starting. The next press is admitted once the log confirms the head.
+ if (session.currentTurn() === 'starting') return;
+ const head = session.entries()[0];
+ if (!head) return;
+ const action: AgentAction | undefined =
+ head.kind === 'prompt' && head.prompt != null
+ ? { type: 'prompt', prompt: head.prompt }
+ : head.kind === 'compact'
+ ? { type: 'compact' }
+ : undefined;
+ void session.issue({ type: 'stop' })?.then((result) => {
+ if (result.isErr()) session.retract(head.actionId);
+ });
+ if (action) session.expect(head.actionId, action);
+ };
+}
diff --git a/apps/web/src/features/block-agent/ui/AgentInput.tsx b/apps/web/src/features/block-agent/ui/AgentInput.tsx
index 1c3f3c2887..3889cad07e 100644
--- a/apps/web/src/features/block-agent/ui/AgentInput.tsx
+++ b/apps/web/src/features/block-agent/ui/AgentInput.tsx
@@ -45,10 +45,14 @@ export interface AgentInputProps {
*/
hasQueuedMessages?: boolean;
/**
- * A stop is already on its way. The queue advances when the turn it ends
- * actually ends, so a second stop does nothing but post again.
+ * Advancing the queue would not advance it right now, so Enter and the
+ * button stay inert (the control reads Stop). Either a stop is already on
+ * its way - the queue advances when the turn it ends actually ends, so a
+ * second stop does nothing but post again - or the prompt that last
+ * advanced is still unconfirmed, so there is no turn the server has opened
+ * for a stop to end.
*/
- stopPending?: boolean;
+ sendNextHeld?: boolean;
/**
* Enter or the send button with an empty input and a queued message. Falls
* back to `onStop`, which is the mechanism: the queue advances when the
@@ -153,14 +157,14 @@ export function AgentInput(props: AgentInputProps) {
// Deliberately not gated on `busy`. A speculated stop reads as done
// everywhere else, so `busy` is already false while the runtime is still
// winding the turn down - and that is exactly when a waiting message is
- // most worth advancing. What does gate it is a stop already in flight:
- // repeating it just posts another cancel for the same turn. Attached files
- // are something to send in their own right, so they hold it back too.
+ // most worth advancing. What does gate it is `sendNextHeld`: a stop already
+ // in flight, or a previous advance the log has not confirmed yet. Attached
+ // files are something to send in their own right, so they hold it back too.
const canSendNext = () =>
markdown().trim().length === 0 &&
attachments().length === 0 &&
props.hasQueuedMessages === true &&
- !props.stopPending &&
+ !props.sendNextHeld &&
!props.disabled &&
props.onStop !== undefined;
diff --git a/apps/web/src/lib/core/agent-session/AgentSession.ts b/apps/web/src/lib/core/agent-session/AgentSession.ts
index d55c5e9460..654a13c63a 100644
--- a/apps/web/src/lib/core/agent-session/AgentSession.ts
+++ b/apps/web/src/lib/core/agent-session/AgentSession.ts
@@ -261,6 +261,18 @@ export class AgentSession {
void this.enqueue({ kind: 'retracted', actionId });
}
+ /**
+ * Where the turn stands as this class knows it right now: the fold's last
+ * report, or `starting` from the moment {@link issue} or {@link expect}
+ * folded a prompt - ahead of the fold's own answer by the worker round
+ * trip. What a caller reads to decide whether an action posted now would
+ * reach a turn the server has opened; the listener-fed metadata lags by
+ * that round trip, and two actions inside it would both read the old state.
+ */
+ currentTurn(): TurnState {
+ return this.turn;
+ }
+
/**
* Whether this action reaches the runtime now, rather than waiting in the
* server's queue.
diff --git a/docs/AGENT_GUIDE/ai-chat.md b/docs/AGENT_GUIDE/ai-chat.md
index d1c6b27bcb..b5f138d351 100644
--- a/docs/AGENT_GUIDE/ai-chat.md
+++ b/docs/AGENT_GUIDE/ai-chat.md
@@ -456,8 +456,10 @@ review note for the agent (`aria-label="Review note"`; `Cmd/Ctrl+Enter` adds,
The chip's count row expands (`aria-expanded`) to show each queued note's
file, line, and text so the reviewer can read or edit them before sending;
**Send to agent** then posts one prompt listing every non-empty note by file
-and line and marks them "sent to agent". Clicking a note's path opens that
-file in the Changes pane. Notes never go to GitHub. Collapsed files and
+and line and marks them "sent to agent". Sending a typed composer message
+while notes are queued includes those notes in the same prompt and marks them
+sent — a second Enter does not post them again. Clicking a note's path opens
+that file in the Changes pane. Notes never go to GitHub. Collapsed files and
unsent notes persist per session in localStorage; a new capture expands all
files.
@@ -537,7 +539,12 @@ must stay hidden; subsequent live messages must still appear.
walks back and past the bottom row returns to the input. When the composer is empty
and a prompt is queued, its action becomes `Send next queued message` (an Enter
symbol); pressing Enter or clicking that button cancels the current turn so the next
- queued prompt starts immediately. Typed composer text still takes priority and Enter
+ queued prompt starts immediately. The advance is held — the control reads `Stop` and
+ Enter is inert — while a stop is already in flight or while the prompt the last
+ advance sent is still unconfirmed (it shows as a pending bubble); once the server
+ confirms that prompt as the running turn, Enter advances the queue again. Two rapid
+ Enters therefore advance one entry, not two: each advance ends the turn the server is
+ actually running. Typed composer text still takes priority and Enter
queues that new prompt normally.
- The stop button cancels only the **current** turn. The queue keeps draining: the next
queued prompt starts a new turn. To fully quiesce a session, remove the queued