Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 12 additions & 10 deletions docs/agents/index.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -63,16 +63,18 @@ Definitions larger than 1 MB are rejected at parse time. Filenames that don't ma

A plugin agent without any of those fields is read as a Claude Code or Cursor subagent. Both tools give such an agent every tool when it omits `tools`, so Xum maps it like this:

| Plugin field | Xum meaning |
| ---------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- |
| (always) | `base: exec`, `subagent.runnable: true`, `ui.hidden: true`, `prompt.append: false` |
| `name` omitted | The file name (agent id), as both tools do for plugin agents |
| `readonly: true` (Cursor) | `base: explore` and `prompt.append: true` (no file edits or task spawning; bash stays; Explore's prompt first) |
| `model` | `ai.model` for an alias or a known Claude ID. Other values use the inherited model. |
| `effort` (Claude Code) | `ai.thinkingLevel`, when it is a valid thinking level |
| `is_background`, `background` | Ignored. The `task` caller chooses `run_in_background`. |
| Other keys (`maxTurns`, `skills`, `memory`, `hooks`, `mcpServers`, `permissionMode`, `isolation`, `color`) | Ignored, as Xum ignores unknown keys. Claude Code also ignores `hooks`, `mcpServers` and `permissionMode` for plugin agents. |
| `tools`, `disallowedTools` as a list | Translated to Xum tool patterns, see [Claude Code tool lists](#claude-code-tool-lists) |
| Plugin field | Xum meaning |
| ---------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
| (always) | `base: exec`, `subagent.runnable: true`, `ui.hidden: true`, `prompt.append: false` |
| `name` omitted | The file name (agent id), as both tools do for plugin agents |
| `readonly: true` (Cursor) | `base: explore` and `prompt.append: true` (no file edits or task spawning; bash stays; Explore's prompt first) |
| `model` | `ai.model` for an alias or a known Claude ID. Other values except `fast` use the inherited model. |
| `model: fast` (Cursor) | `ai.settingsBase: explore`: the agent takes Explore's model, thinking level, reasoning mode and prompt cache from Settings, then Exec's |
| `effort` (Claude Code) | `ai.thinkingLevel`, when it is a valid thinking level |
| `is_background: true` (Cursor) | `subagent.background_hint: true`: the `task` tool lists the agent as meant to run in the background |
| `background` (Claude Code) | Ignored. The `task` caller chooses `run_in_background`. |
| Other keys (`maxTurns`, `skills`, `memory`, `hooks`, `mcpServers`, `permissionMode`, `isolation`, `color`) | Ignored, as Xum ignores unknown keys. Claude Code also ignores `hooks`, `mcpServers` and `permissionMode` for plugin agents. |
| `tools`, `disallowedTools` as a list | Translated to Xum tool patterns, see [Claude Code tool lists](#claude-code-tool-lists) |

So `task({ agentId: "<file name>" })` spawns the agent with Exec's tools, narrowed by any Claude Code tool list: without one, it can run shell commands and edit files. The body replaces Exec's prompt. Xum still adds its sub-agent instructions (commit the work so the parent can apply the patch, and report back), because the parent depends on them. The agent does not appear in the agent picker. This mapping applies only to plugin agents. A project or global agent file in the same format keeps the Xum defaults (not runnable, no tools).

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { useEffect, useRef } from "react";
import { useAgent } from "@/browser/contexts/AgentContext";
import { getAgentAiSettingsBases } from "@/common/utils/ai/agentAncestorLayers";
import { recordWorkspaceModelChange } from "@/browser/utils/modelChange";
import { getWorkspaceAiSelection } from "@/browser/utils/workspaceAiSettingsSync";
import { normalizeAgentId } from "@/common/utils/agentIds";
Expand All @@ -19,15 +20,15 @@
const previousAgentId = prevAgentIdRef.current;

const isExplicitAgentSwitch =
previousAgentId !== null &&

Check warning on line 23 in src/browser/components/WorkspaceModeAISync/WorkspaceModeAISync.tsx

View workflow job for this annotation

GitHub Actions / Quality / Mutation

Mutation survived: && -> ||

No unit test failed when WorkspaceModeAISync had && -> ||. Add a test that tells them apart, or say why they are equivalent.
prevWorkspaceIdRef.current === workspaceId &&

Check warning on line 24 in src/browser/components/WorkspaceModeAISync/WorkspaceModeAISync.tsx

View workflow job for this annotation

GitHub Actions / Quality / Mutation

Mutation survived: && -> ||

No unit test failed when WorkspaceModeAISync had && -> ||. Add a test that tells them apart, or say why they are equivalent.
previousAgentId !== normalizedAgentId;

// Update refs for the next run (even if no model changes).
prevAgentIdRef.current = normalizedAgentId;
prevWorkspaceIdRef.current = workspaceId;

const agentBaseById = new Map(agents.map((agent) => [agent.id, agent.base]));
const agentBaseById = getAgentAiSettingsBases(agents);
if (isExplicitAgentSwitch) {
// Each agent resolves its own model, so the switch itself is the explicit model change.
recordWorkspaceModelChange(
Expand Down
3 changes: 2 additions & 1 deletion src/browser/contexts/ThinkingContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import { KEYBINDS, matchesKeybind, paneHandlesKeyEvent } from "@/browser/utils/ui/keybinds";
import { useChatPaneScope } from "@/browser/contexts/ChatPaneScopeContext";
import { markAiSelectionIntent } from "@/browser/utils/aiSelectionIntent";
import { getAgentAiSettingsBases } from "@/common/utils/ai/agentAncestorLayers";
import { setAutoRoutingChoice } from "@/browser/utils/modelChange";
import { useScopedAiDefault, writeScopedAiDefault } from "@/browser/utils/scopedAiDefaults";

Expand Down Expand Up @@ -56,14 +57,14 @@
const { config: providersConfig } = useProvidersConfig();
const workspaceId = props.workspaceId;
const defaultModel = useDefaultModel();
const scopeId = props.scopeId ?? getScopeId(workspaceId, props.projectPath);

Check warning on line 60 in src/browser/contexts/ThinkingContext.tsx

View workflow job for this annotation

GitHub Actions / Quality / Mutation

Mutation survived: ?? -> ||

No unit test failed when ThinkingProvider had ?? -> ||. Add a test that tells them apart, or say why they are equivalent.
// Hooks run unconditionally; a workspace mount reads the resolver instead of scope defaults.
const defaultsScopeId = workspaceId != null ? GLOBAL_SCOPE_ID : scopeId;
const agentContext = useOptionalAgent();
const selection = useWorkspaceAiSelection(
scopeId,
agentContext?.agentId,
agentContext && new Map(agentContext.agents.map((agent) => [agent.id, agent.base]))
agentContext && getAgentAiSettingsBases(agentContext.agents)
);
const scopedModel = useScopedAiDefault(defaultsScopeId, "model");
const scopedThinkingLevel = useScopedAiDefault(defaultsScopeId, "thinkingLevel");
Expand All @@ -71,12 +72,12 @@
// normalizeSelectedModel (not normalizeToCanonical): explicit gateway identities must
// survive; thinking policy lookups resolve gateway-scoped strings themselves.
const model =
workspaceId != null ? selection.model : normalizeSelectedModel(scopedModel ?? defaultModel);

Check warning on line 75 in src/browser/contexts/ThinkingContext.tsx

View workflow job for this annotation

GitHub Actions / Quality / Mutation

Mutation survived: ?? -> ||

No unit test failed when ThinkingProvider had ?? -> ||. Add a test that tells them apart, or say why they are equivalent.
const thinkingLevel =
workspaceId != null ? selection.thinkingLevel : (scopedThinkingLevel ?? THINKING_LEVEL_OFF);

Check warning on line 77 in src/browser/contexts/ThinkingContext.tsx

View workflow job for this annotation

GitHub Actions / Quality / Mutation

Mutation survived: ?? -> ||

No unit test failed when ThinkingProvider had ?? -> ||. Add a test that tells them apart, or say why they are equivalent.
// useWorkspaceAiSelection re-renders this provider when a creation scope's pick changes.
const reasoningMode =
workspaceId != null ? selection.reasoningMode : getWorkspaceAiSelection(scopeId).reasoningMode;

Check warning on line 80 in src/browser/contexts/ThinkingContext.tsx

View workflow job for this annotation

GitHub Actions / Quality / Mutation

Mutation survived: != -> ==

No unit test failed when ThinkingProvider had != -> ==. Add a test that tells them apart, or say why they are equivalent.

const serviceTier = selection.serviceTier;
const setServiceTier = (tier: ServiceTier) => setWorkspaceServiceTier(api, scopeId, tier);
Expand Down Expand Up @@ -118,7 +119,7 @@
const isDecrease = matchesKeybind(e, KEYBINDS.DECREASE_THINKING);
// TOGGLE_THINKING is deprecated but still honored for muscle memory.
const isCycle = matchesKeybind(e, KEYBINDS.TOGGLE_THINKING);
if (!isIncrease && !isDecrease && !isCycle) {

Check warning on line 122 in src/browser/contexts/ThinkingContext.tsx

View workflow job for this annotation

GitHub Actions / Quality / Mutation

Mutation survived: delete !

No unit test failed when ThinkingProvider had delete !. Add a test that tells them apart, or say why they are equivalent.

Check warning on line 122 in src/browser/contexts/ThinkingContext.tsx

View workflow job for this annotation

GitHub Actions / Quality / Mutation

Mutation survived: delete !

No unit test failed when ThinkingProvider had delete !. Add a test that tells them apart, or say why they are equivalent.
return;
}

Expand All @@ -127,7 +128,7 @@
// Step only within levels at or above the model's minimum floor.
const minimum = getMinimum(model);
const allowed = getAvailableThinkingLevels(model, minimum, providersConfig);
if (allowed.length <= 1) {

Check warning on line 131 in src/browser/contexts/ThinkingContext.tsx

View workflow job for this annotation

GitHub Actions / Quality / Mutation

Mutation survived: <= -> <

No unit test failed when ThinkingProvider had <= -> <. Add a test that tells them apart, or say why they are equivalent.

Check warning on line 131 in src/browser/contexts/ThinkingContext.tsx

View workflow job for this annotation

GitHub Actions / Quality / Mutation

Mutation survived: 1 -> 0

No unit test failed when ThinkingProvider had 1 -> 0. Add a test that tells them apart, or say why they are equivalent.
return;
}

Expand Down
5 changes: 3 additions & 2 deletions src/browser/features/ChatInput/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@
import { setWorkspaceModelWithOrigin } from "@/browser/utils/modelChange";
import { readScopedAiDefault, writeScopedAiDefault } from "@/browser/utils/scopedAiDefaults";
import { resolveWorkspaceAiSettingsForAgent } from "@/browser/utils/workspaceModeAi";
import { getAgentAiSettingsBases } from "@/common/utils/ai/agentAncestorLayers";
import { getWorkspaceAiSelection } from "@/browser/utils/workspaceAiSettingsSync";
import {
getCreationDraftScopeId,
Expand Down Expand Up @@ -370,3408 +371,3408 @@
settled: boolean;
}

const ChatInputInner: React.FC<ChatInputProps> = (props) => {
const { api } = useAPI();
const liveApi = useLiveAPI();
// For refusals after an await: the send's closure holds the client from when it started.
const liveApiRef = useRef(liveApi);
useEffect(() => {
liveApiRef.current = liveApi;
}, [liveApi]);
const { variant } = props;
// A /side chat composer is mounted next to the main one. Window shortcuts act only in the pane
// that owns the focused element, and unscoped palette events (open model selector, voice, toasts)
// belong to the main composer so they fire once.
const paneScope = useChatPaneScope();
const { userProjects } = useProjectContext();
const creationScope =
variant === "creation"
? resolveWorkspaceCreationScope(props.projectPath, userProjects, props.pendingSubProjectPath)
: null;
const creationParentProjectPath = creationScope?.projectPath ?? "";
// The creation composer's AI choices belong to its draft (keyed by id, not project).
const creationDraftId = variant === "creation" ? (props.pendingDraftId ?? "") : "";
const creationSubProjectPath = creationScope?.subProjectPath ?? undefined;
const creationProject =
variant === "creation" ? userProjects.get(creationParentProjectPath) : undefined;
// A sub-project draft keeps its parent's route, so files, skills and agents come from the parent
// (as for main's sidebar New chat on a sub-project). Following the sub-project instead makes the
// agent list, its defaults and the agent resets disagree.
const atMentionProjectPath =
variant === "creation" && props.kind !== "scratch" ? props.projectPath : null;
const asyncCommandScopeRef = useRef<{ variant: typeof variant; workspaceId: string | null }>({
variant,
workspaceId: variant === "workspace" ? props.workspaceId : null,
});
const asyncCommandTokenRef = useRef(0);
const workspaceId = variant === "workspace" ? props.workspaceId : null;
// One controller covers all sends in a composer scope. Scope changes abort
// stale continuations; unmount does not, so submitted sends can still reach
// their captured workspace after navigation.
const sendResolutionAbortRef = useRef<AbortController | null>(null);

useEffect(() => {
asyncCommandScopeRef.current = { variant, workspaceId };
sendResolutionAbortRef.current?.abort();
sendResolutionAbortRef.current = null;
}, [variant, workspaceId]);

const store = useWorkspaceStoreRaw();
const workspaceSidebarState = useOptionalWorkspaceSidebarState(workspaceId);
const workspaceGoal = workspaceSidebarState?.goal ?? null;

// Lock the composer while a creation-flow staging + initial send is still in
// flight for this workspace (deferred runtimes can hold it for minutes), so a
// user send cannot leapfrog the initial message and a failure transfer cannot
// overwrite a freshly typed draft.
const initialStagingLocked = useSyncExternalStore(subscribeInitialStagingLock, () =>
variant === "workspace" ? isInitialStagingLocked(props.workspaceId) : false
);

// Extract workspace-specific props with defaults
const disabled = (props.disabled ?? false) || initialStagingLocked;
const editingMessage = variant === "workspace" ? props.editingMessage : undefined;
// Live edit target for callbacks that outlive the render they were created in (a transcript
// refresh outcome, the "Retry refresh" toast): they must not act on an edit the user has
// since cancelled or replaced.
const editingMessageIdRef = useRef<string | undefined>(editingMessage?.id);
// A failed conflict refresh keeps Send disabled (stale evidence is never re-sent blindly), so
// the retry must live in persistent edit-mode UI, not only in the dismissible toast.
const [editRefreshRetry, setEditRefreshRetry] = useState<{
editMessageId: string;
precondition: HistoryEditPrecondition;
} | null>(null);
// Assigned in a layout effect, not a passive one: a refresh that settles between a commit
// that changed the edit and a passive effect must already see the new edit as current.
// Layout effects run in the same task as the commit, so no callback can observe the gap.
useLayoutEffect(() => {
editingMessageIdRef.current = editingMessage?.id;
});
const [pendingBoundaryEditConfirmation, setPendingBoundaryEditConfirmation] =
useState<SendOverrides | null>(null);
// Hide edit-mode chrome as soon as an edit send starts so the input doesn't sit blank
// while the backend acknowledges the edit and begins the replacement stream.
const [optimisticallyDismissedEditId, setOptimisticallyDismissedEditId] = useState<string | null>(
null
);
const editingMessageForUi =
editingMessage?.id === optimisticallyDismissedEditId ? undefined : editingMessage;
const isTranscriptCaughtUp =
variant === "workspace" ? (props.isTranscriptCaughtUp ?? false) : false;
const isStreamStarting = variant === "workspace" ? (props.isStreamStarting ?? false) : false;
const isCompacting = variant === "workspace" ? (props.isCompacting ?? false) : false;
const [isMobileTouch, setIsMobileTouch] = useState(
() =>
typeof window !== "undefined" &&
window.matchMedia("(max-width: 768px) and (pointer: coarse)").matches
);
useEffect(() => {
if (typeof window === "undefined") return;

const mobileTouchMediaQuery = window.matchMedia("(max-width: 768px) and (pointer: coarse)");
const handleMobileTouchChange = () => {
setIsMobileTouch(mobileTouchMediaQuery.matches);
};

handleMobileTouchChange();
mobileTouchMediaQuery.addEventListener("change", handleMobileTouchChange);
return () => {
mobileTouchMediaQuery.removeEventListener("change", handleMobileTouchChange);
};
}, []);
useEffect(() => {
if (
optimisticallyDismissedEditId != null &&
editingMessage?.id !== optimisticallyDismissedEditId
) {
setOptimisticallyDismissedEditId(null);
}
}, [editingMessage?.id, optimisticallyDismissedEditId]);
// runtimeType for telemetry - defaults to "worktree" if not provided
const runtimeType = variant === "workspace" ? (props.runtimeType ?? "worktree") : "worktree";
const computerUse = useComputerUse(workspaceId);

// Callback for model changes (both variants support this)
const onModelChange = props.onModelChange;

// User request: keep creation runtime controls synced with Settings enablement toggles.
const rawRuntimeEnablement = useAppConfig((config) => config.runtimeEnablement);
const runtimeEnablement = normalizeRuntimeEnablement(rawRuntimeEnablement);

// Track concurrent sends with a counter (not boolean) to handle queued follow-ups correctly.
// When a follow-up is queued during stream-start, it resolves immediately but shouldn't
// clear the "in flight" state until all sends complete.
const [sendingCount, setSendingCount] = useState(0);
const sendModeMenuContainerRef = useRef<HTMLDivElement>(null);
const [hideReviewsDuringSend, setHideReviewsDuringSend] = useState(false);
const projectedWorkflowRunCardKeysRef = useRef(new Set<string>());
const workflowsRequestIdRef = useRef(0);
const [toast, setToast] = useState<Toast | null>(null);
// The alert an edit's `history-changed` refusal raised. That edit's successful re-send clears
// it (only while it is still the shown toast), as a successful refresh retry clears its own.
const editConflictToastRef = useRef<{ editMessageId: string; toast: Toast } | null>(null);
// State for destructive command confirmation modal (currently only /clear).
const [pendingDestructiveCommand, setPendingDestructiveCommand] = useState(false);
const pushToast = useCallback(
(nextToast: Omit<Toast, "id" | "type"> & { type: Toast["type"] | "info" }) => {
// Keep a dedicated "info" intent for callsites while rendering with the shared non-error toast style.
const type = nextToast.type === "info" ? "success" : nextToast.type;
setToast({ id: Date.now().toString(), ...nextToast, type });
},
[setToast]
);
// A draft transferred from a failed creation send may have resolved its
// slash skill against the project path; honor that choice on the retry.
// listener: true keeps this in sync when the transfer lands after mount and
// when a successful send clears the key, so the skill descriptor list below
// reloads under the matching discovery target.
const [transferredDraftProjectDiscovery] = usePersistedState<boolean>(
variant === "workspace" && workspaceId
? getPendingDraftSkillDiscoveryKey(workspaceId)
: "__unused__",
false,
{ listener: true }
);

// Subscribe to pending send errors from creation flow. Uses listener: true so
// late failures (e.g., slow devcontainer startup) still surface a toast.
const pendingErrorKey =
variant === "workspace" && workspaceId ? getPendingWorkspaceSendErrorKey(workspaceId) : null;
// Typed as unknown: localStorage can hold anything (another build, a hand edit), and an
// invalid error used to crash the workspace view in createErrorToast (#5007).
const [pendingError, setPendingError] = usePersistedState<unknown>(
pendingErrorKey ?? "__unused__",
null,
{ listener: true }
);
useEffect(() => {
if (!pendingErrorKey || pendingError == null) return;
const parsed = SendMessageErrorSchema.safeParse(pendingError);
if (parsed.success) {
setToast(createErrorToast(parsed.data));
} else {
// Self-heal: drop the malformed value (cleared below) instead of throwing.
console.warn("Dropping malformed pending send error:", parsed.error);
}
setPendingError(null);
}, [pendingErrorKey, pendingError, setPendingError]);

const handleToastDismiss = () => {
setToast(null);
};

const draft = useComposerDraft({
variant,
workspaceId,
pendingDraftId: creationDraftId,
attachedReviews: variant === "workspace" ? (props.attachedReviews ?? []) : [],
pushToast,
});
const { input, setInput, attachments, setAttachments, draftReviews, setDraftReviews } = draft;
const { getDraft, setDraft } = draft;
const { reviewOverrideActive, reviewData, reviewIdsForCheck, reviewPanelItems } = draft;
const { removeDraftReview, updateDraftReviewNote, draftScope, latestInputValueRef } = draft;
const {
processingAttachmentCount,
handlePaste,
handleAttachFiles,
handleDragOver,
handleDrop,
handleRemoveAttachment,
} = useComposerAttachments({
variant,
workspaceId,
setAttachments,
editingMessage: editingMessageForUi != null,
pushToast,
});
const workspaceIdForComposerClear = variant === "workspace" ? props.workspaceId : null;
const onDetachAllReviewsForComposerClear =
variant === "workspace" ? props.onDetachAllReviews : undefined;
const onAddReviewForRestore = variant === "workspace" ? props.onAddReview : undefined;
const onAcceptRestoredHeldInputs =
variant === "workspace" ? props.onAcceptRestoredHeldInputs : undefined;

// Creation sends can resolve after navigation; guard draft clears on unmounted inputs.
const isMountedRef = useRef(true);
useEffect(() => {
return () => {
isMountedRef.current = false;
};
}, []);
const inputRef = useRef<HTMLTextAreaElement>(null);
// #6585: edits other than typing at the end stop a send in flight from cutting its text.
const sendMarkEdits = useSendMarkEditTracking(inputRef, draftScope);
const modelSelectorRef = useRef<ModelSelectorRef>(null);
const powerMode = usePowerMode();
const handleInputChange = useCallback(
(next: string, caretFromEvent?: number) => {
if (powerMode.enabled) {
const prev = latestInputValueRef.current;
const delta = next.length - prev.length;

if (next !== prev) {
// Power Mode positioning depends on the textarea's post-layout size/position.
// On backspace/delete the textarea can shrink (auto-resize) which shifts the caret
// downward; if we measure immediately we can get a stale bounding rect and the
// fireworks appear out-of-sync with the cursor.
const intensity = delta > 0 ? Math.min(6, delta) : delta < 0 ? Math.min(6, -delta) : 1;
const kind = delta < 0 ? "delete" : "insert";
// Capture the caret index now (before rAF) so bursts queued within the same frame
// don't all measure the latest caret position and appear "ahead" during fast typing.
const caretIndex = caretFromEvent ?? inputRef.current?.selectionStart ?? next.length;

requestAnimationFrame(() => {
const el = inputRef.current;
if (!el) {
return;
}

const emit = () => powerMode.burstFromTextarea(el, intensity, kind, caretIndex);

// When the textarea is scrollable, scrollTop may settle one frame after
// the layout shift, so defer measurement to a second rAF.
if (el.scrollHeight > el.clientHeight) {
requestAnimationFrame(emit);
return;
}

emit();
});
}
}

// Auto-convert a backslash symbol command (e.g. "\alpha" -> α, "\leq" -> ≤).
// Eager path fires only for unambiguous names; the terminator path accepts
// a completed name when a space/punctuation follows (e.g. "\in " -> "∈ ").
// Both only act at the caret, so partial/mid-word edits are left untouched.
const caret = caretFromEvent ?? inputRef.current?.selectionStart ?? next.length;
const converted =
convertSymbolCommandAtCursor(next, caret) ?? convertTerminatedSymbolCommand(next, caret);
if (converted) {
// #6944: commit the converted text now and put the caret after the symbol before the
// next key. Writing the value moves the caret to the end; a frame later was too late for
// a fast next key, which then landed at the end.
flushSync(() => setInput(converted.text));
const el = inputRef.current;
if (el && !el.disabled) {
el.selectionStart = converted.cursor;
el.selectionEnd = converted.cursor;
}
return { text: converted.text, cursor: converted.cursor };
}

setInput(next);
return { text: next, cursor: caret };
},
[latestInputValueRef, powerMode, setInput]
);

const { open } = useSettings();
const { selectedWorkspace, beginWorkspaceCreation, workspaceMetadata } = useWorkspaceContext();
const { agentId, currentAgent, agents, loaded: agentsLoaded } = useAgent();

// Use current agent's uiColor, or neutral border until agents load
const agentColor = currentAgent?.uiColor ?? "var(--color-border-light)";
const composerSurfaceStyle: React.CSSProperties & { "--composer-focus-border": string } = {
"--composer-focus-border": agentColor,
};
const { models, hiddenModelsForSelector, ensureModelInSettings, defaultModel, setDefaultModel } =
useModelsFromSettings();

const agentAiDefaults = useAgentAiDefaults();
const telemetry = useTelemetry();
const vimEnabled = useUserPreferences(
(preferences) => preferences.appearance?.vimEnabled === true
);
const { startSequence: startTutorial } = useTutorial();

// Track transcription provider prerequisites from Settings → Providers.
const [openAIKeySet, setOpenAIKeySet] = useState(false);
const [openAIProviderEnabled, setOpenAIProviderEnabled] = useState(true);
const isTranscriptionAvailable = openAIProviderEnabled && openAIKeySet;

// Voice input - appends transcribed text to input
const voiceInput = useVoiceInput({
onTranscript: (text) => {
setInput((prev) => {
const separator = prev.length > 0 && !prev.endsWith(" ") ? " " : "";
return prev + separator + text;
});
},
onError: (error) => {
pushToast({ type: "error", message: error });
},
onSend: () => void handleSend(),
isTranscriptionAvailable,
useRecordingKeybinds: true,
api: liveApi,
});

const voiceInputUnavailableMessage =
"Voice input requires an enabled OpenAI provider with an API key. Configure in Settings → Providers.";

// Start creation tutorial when entering creation mode
useEffect(() => {
if (variant === "creation") {
// Small delay to ensure UI is rendered
const timer = setTimeout(() => {
startTutorial("creation");
}, 600);
return () => clearTimeout(timer);
}
}, [variant, startTutorial]);

// Get current send message options from shared hook (must be at component top level)
// For creation variant, use project-scoped key; for workspace, use workspace ID
const sendOptionsScopeId =
variant === "workspace" ? props.workspaceId : getCreationDraftScopeId(creationDraftId);
const sendMessageOptions = useSendMessageOptions(sendOptionsScopeId);
const autoModelRoutingEnabled = useExperimentValue(EXPERIMENT_IDS.AUTO_MODEL_ROUTING);
const [autoModelRoutingActive, setAutoModelRoutingActive] = useAutoRoutingSelection(
sendOptionsScopeId,
"model"
);
const [autoThinkingLevelActive, setAutoThinkingLevelActive] = useAutoRoutingSelection(
sendOptionsScopeId,
"thinkingLevel"
);
const composerSuggestions = useComposerSuggestions({
input,
setInput,
inputRef,
variant,
workspaceId,
projectPath: atMentionProjectPath,
});
const { agentSkillDescriptors, handleInputCaretChange, mcpPromptDescriptors } =
composerSuggestions;
const handleComposerInputChange = (next: string, caret?: number) => {
// Feed the suggestion seam the applied text/cursor: symbol auto-conversion
// can rewrite both, and caret state keyed to the pre-conversion text would
// fall back to end-of-input over the converted draft.
const applied = handleInputChange(next, caret);
handleInputCaretChange(applied.cursor, applied.text);
};
const additionalSystemContext = useAdditionalSystemContextSnapshot(
variant === "workspace" ? props.workspaceId : ""
);
const additionalSystemContextHydrated = useAdditionalSystemContextHydrated(
variant === "workspace" ? props.workspaceId : ""
);
// Extract models for convenience (don't create separate state - use hook as single source of truth)
// - preferredModel: selected model used for backend routing, preserving explicit gateway choices
// - baseModel: canonical format for UI display and policy checks (e.g., ThinkingSelector)
const preferredModel = sendMessageOptions.model;
const baseModel = sendMessageOptions.baseModel;

// Context usage indicator data (workspace variant only)
const workspaceIdForUsage = variant === "workspace" ? props.workspaceId : "";
const usage = useWorkspaceUsage(workspaceIdForUsage);
const { has1MContext } = useProviderOptions();
const { config: providersConfig } = useProvidersConfig();
const lastUsage = usage?.liveUsage ?? usage?.lastContextUsage;
// Token counts come from usage metadata, but context limits/1M eligibility should
// follow the currently selected model unless a stream is actively running.
const activeUsageModel = usage?.liveUsage?.model ?? null;
const contextDisplayModel = activeUsageModel ?? baseModel;
const use1M = has1MContext(contextDisplayModel);
const contextUsageData = useMemo(() => {
return lastUsage
? calculateTokenMeterData(lastUsage, contextDisplayModel, use1M, false, providersConfig)
: { segments: [], totalTokens: 0, totalPercentage: 0 };
}, [lastUsage, contextDisplayModel, use1M, providersConfig]);
const autoCompactionSettings = useAutoCompactionSettings(
workspaceIdForUsage,
contextDisplayModel
);
const autoCompactionProps = {
...autoCompactionSettings,
modelContextLimit: contextUsageData.maxTokens,
};

// Idle compaction settings (per-project, persisted to backend for idleCompactionService)
const { hours: idleCompactionHours, setHours: setIdleCompactionHours } = useIdleCompactionHours({
projectPath: selectedWorkspace?.projectPath ?? null,
});
const idleCompactionProps = {
hours: idleCompactionHours,
setHours: setIdleCompactionHours,
};

const setPreferredModel = (model: string) => {
const selectedModel = normalizeSelectedModel(model);
if (
variant === "workspace" &&
hasBudgetedResumableGoal(workspaceGoal) &&
!modelHasPricingData(selectedModel, providersConfig)
) {
setToast({
id: Date.now().toString(),
type: "error",
message: UNPRICED_TARGET_MODEL_GOAL_MESSAGE,
});
return;
}

ensureModelInSettings(selectedModel); // Ensure model exists in Settings
// A concrete pick (selector, /model, or the cycle shortcut) always leaves Auto.
setAutoModelRoutingActive(false);

if (onModelChange) {
// Notify parent of model change (for context switch warning + persisted model metadata).
// Called before early returns so warnings work even offline or with custom agents.
onModelChange(selectedModel);
} else {
const scopeId =
variant === "creation" ? getCreationDraftScopeId(creationDraftId) : workspaceId;
if (scopeId) {
setWorkspaceModelWithOrigin(scopeId, selectedModel, "user");
}
}

// Marked after onModelChange so its explicit-switch record still sees the previous model;
// this also pins a same-model pick on a sub-agent once a message sends it.
if (variant === "workspace" && workspaceId) {
markAiSelectionIntent(workspaceId, "model", selectedModel);
}
};

// Model cycling candidates: all visible models (custom + built-in, minus hidden).
const cycleModels = models;

const cycleToNextModel = () => {
if (cycleModels.length < 2) {
return;
}

const currentIndex = cycleModels.indexOf(baseModel);
const nextIndex = currentIndex === -1 ? 0 : (currentIndex + 1) % cycleModels.length;
const nextModel = cycleModels[nextIndex];
if (nextModel) {
setPreferredModel(nextModel);
}
};

// The global shortcut listener reads the latest handler through a ref so it isn't
// re-subscribed whenever the model list or selection changes.
const cycleToNextModelRef = useRef(cycleToNextModel);
useLayoutEffect(() => {
cycleToNextModelRef.current = cycleToNextModel;
});

const openModelSelector = useCallback(() => {
modelSelectorRef.current?.open();
}, []);
// Keep workspace creation in sync with Settings → Runtimes project overrides.
const creationRuntimeEnablement =
variant === "creation"
? projectRuntimeEnablement(creationProject, runtimeEnablement)
: runtimeEnablement;
// Compiler-memoized in its own module; see useCreationProjectChangeHandler for why.
const changeCreationProject = useCreationProjectChangeHandler(
creationDraftId,
userProjects,
rawRuntimeEnablement,
beginWorkspaceCreation
);
const [hasAttemptedCreateSend, setHasAttemptedCreateSend] = useState(false);

// Creation-specific state (hook always called, but only used when variant === "creation")
// This avoids conditional hook calls which violate React rules
const creationNameMessage =
variant === "creation"
? (() => {
const parsedCreationCommand = parseCommand(input.trim());
if (parsedCreationCommand?.type === "goal-set") {
return parsedCreationCommand.objective;
}
if (input.trim().length === 0 && attachments.length > 0) {
const filenames = attachments
.map((attachment) => attachment.filename)
.filter((filename): filename is string => typeof filename === "string");
return filenames.length > 0 ? `Attached files: ${filenames.join(", ")}` : "";
}
return input;
})()
: "";
const creationState = useCreationWorkspace(
variant === "creation"
? {
kind: props.kind,
projectPath: creationParentProjectPath,
subProjectPath: creationSubProjectPath,
onWorkspaceCreated: props.onWorkspaceCreated,
message: creationNameMessage,
draftId: props.pendingDraftId,
userModel: preferredModel,
agentBaseById: new Map(agents.map((agent) => [agent.id, agent.base])),
agentBaseById: getAgentAiSettingsBases(agents),
}
: {
// Dummy values for workspace variant (never used)
projectPath: "",
// eslint-disable-next-line @typescript-eslint/no-empty-function
onWorkspaceCreated: () => {},
message: "",
}
);

// Creation sends also pass through the async resolution phase guarded by
// sendingCount, so include it alongside the creation-specific flag.
// A send whose acceptance is unresolved (the receiver answered unknown, or the lookup failed)
// keeps the composer in this same sending state while DraftStore retries it (idempotent sends).
const isSending = sendingCount > 0 || draft.unresolvedSendCount > 0;
const isSendInFlight = variant === "creation" ? creationState.isSending || isSending : isSending;
const sendInFlightBlocksInput =
variant === "workspace" ? isSendInFlight && !isStreamStarting : isSendInFlight;
// #6259: typing stays on once a send has taken its draft; submission waits for it to settle.
const typingLock = useComposerTypingLock({
variant,
sendingCount,
isStreamStarting,
creationLocksTyping: sendInFlightBlocksInput,
inputRef,
});
const sendLocksTyping = typingLock.locksTyping;
// A creation Send takes one snapshot of the draft: a file still being read, or speech still
// being transcribed, would land after it.
const isProcessingAttachments =
processingAttachmentCount > 0 || (variant === "creation" && voiceInput.state !== "idle");
// Moving to or from Scratch opens another page (a new composer), which would drop a file read
// or a recording still in progress, so the project waits for them.
const creationProjectLocked = isSendInFlight || isProcessingAttachments;

// Coder workspace state - config is owned by selectedRuntime.coder, this hook manages async data
const currentRuntime = creationState.selectedRuntime;
const coderRuntimeHost = currentRuntime.mode === "ssh" ? currentRuntime.host : null;
const setCreationSelectedRuntime = creationState.setSelectedRuntime;
// Compiler-memoized in its own module; see useCoderConfigChangeHandler for why.
const handleCoderConfigChange = useCoderConfigChangeHandler(
coderRuntimeHost,
setCreationSelectedRuntime
);
const coderState = useCoderWorkspace({
coderConfig: currentRuntime.mode === "ssh" ? (currentRuntime.coder ?? null) : null,
onCoderConfigChange: handleCoderConfigChange,
coderInfoRefreshPolicy: variant === "creation" ? "mount-and-focus" : "mount-only",
});

const creationRuntimeError =
variant === "creation" && props.kind !== "scratch"
? validateCreationRuntime(creationState.selectedRuntime, coderState.presets.length)
: null;

const runtimeFieldError =
variant === "creation" && hasAttemptedCreateSend ? (creationRuntimeError?.mode ?? null) : null;

const creationControlsProps =
variant === "creation" && props.kind !== "scratch"
? ({
branches: creationState.branches,
branchLoad: creationState.branchLoad,
trunkBranch: creationState.trunkBranch,
onTrunkBranchChange: creationState.setTrunkBranch,
selectedRuntime: creationState.selectedRuntime,
coderConfigFallback: creationState.coderConfigFallback,
sshHostFallback: creationState.sshHostFallback,
defaultRuntimeMode: creationState.defaultRuntimeMode,
onSelectedRuntimeChange: creationState.setSelectedRuntime,
disabled: isSendInFlight,
projectPath: creationParentProjectPath,
// Surface the actually-targeted project (possibly a sub-project) to
// the dropdown so the trigger label reflects what the user picked,
// while runtime/settings scoping stays on the parent above. When
// creating from the sidebar's "+ New chat" on a sub-project header,
// the URL/route is the parent project and the sub-project comes via
// the draft (pendingSubProjectPath / creationSubProjectPath); both
// routes (deep link to a sub-project, or sidebar "+") collapse here.
selectedProjectPath: creationSubProjectPath ?? props.projectPath,
userProjects,
onSelectedProjectPathChange: changeCreationProject,
projectSelectDisabled: creationProjectLocked,
projectName: props.projectName,
nameState: creationState.nameState,
runtimeAvailabilityState: creationState.runtimeAvailabilityState,
runtimeEnablement: creationRuntimeEnablement,
coderInfo: coderState.coderInfo,
runtimeFieldError,
// Pass coderProps when CLI is available/outdated, Coder is enabled, or still checking (so "Checking…" UI renders)
coderProps:
coderState.coderInfo === null ||
coderState.enabled ||
coderState.coderInfo?.state !== "unavailable"
? {
enabled: coderState.enabled,
onEnabledChange: coderState.setEnabled,
coderInfo: coderState.coderInfo,
coderConfig: coderState.coderConfig,
onCoderConfigChange: coderState.setCoderConfig,
templates: coderState.templates,
templatesError: coderState.templatesError,
presets: coderState.presets,
presetsError: coderState.presetsError,
existingWorkspaces: coderState.existingWorkspaces,
workspacesError: coderState.workspacesError,
loadingTemplates: coderState.loadingTemplates,
loadingPresets: coderState.loadingPresets,
loadingWorkspaces: coderState.loadingWorkspaces,
}
: undefined,
} satisfies React.ComponentProps<typeof CreationControls>)
: null;
const hasTypedText = input.trim().length > 0;
const hasImages = attachments.length > 0;
const hasReviews = reviewData !== undefined;
// Disable send while Coder presets are loading (user could bypass preset validation)
const coderPresetsLoading =
coderState.enabled && !coderState.coderConfig?.existingWorkspace && coderState.loadingPresets;
// #6033: the trunk branch stays empty until the branch list loads, and the backend refuses
// every runtime except local without one, so a creation send must wait for the list. A failed
// list keeps it closed too (#6055).
const creationBranchesLoading =
variant === "creation" &&
props.kind !== "scratch" &&
creationState.branchLoad !== "loaded" &&
creationState.selectedRuntime.mode !== RUNTIME_MODE.LOCAL;
const creationDraftNotSaved = variant === "creation" && draft.saveError !== null;
// #6423: the same blockers as canSend below, so "Run /init" is off whenever Send is.
useReportCreationSendBlocked(
{
disabled,
sendInFlight: sendInFlightBlocksInput,
processingAttachments: isProcessingAttachments,
coderPresetsLoading,
branchesNotLoaded: creationBranchesLoading,
draftNotSaved: creationDraftNotSaved,
},
props
);
const hasSendableDraft = hasTypedText || hasImages || hasReviews;
// Workspace sends/edits mutate history relative to the visible transcript, so they wait for
// the onChat replay to finish; the creation composer has no transcript to catch up with.
// Goal and settings commands act on backend/local state by id and stay usable meanwhile
// (a /goal with attachments becomes a message send, so it does not bypass).
const draftBypassesTranscriptBarrier =
hasTypedText &&
!hasImages &&
!hasReviews &&
commandBypassesTranscriptBarrier(parseCommand(input.trim()));
const transcriptBlocksSend =
variant === "workspace" && !isTranscriptCaughtUp && !draftBypassesTranscriptBarrier;
// A refused edit stays in edit mode with Send disabled until the transcript refresh hands
// back a fresh candidate (or the user leaves edit mode); nothing is re-sent automatically.
const editPreconditionInvalidated = editingMessageForUi?.preconditionInvalidated === true;
const canSend =
hasSendableDraft &&
!disabled &&
!sendInFlightBlocksInput &&
!isProcessingAttachments &&
!coderPresetsLoading &&
!creationBranchesLoading &&
!creationDraftNotSaved &&
!transcriptBlocksSend &&
!editPreconditionInvalidated;
const runningGoalActive =
variant === "workspace" && isGoalRunning(workspaceGoal?.status ?? "paused");

// Send defaults to tool-end on click; advanced dispatch modes remain available via
// right-click and touch long-press whenever there's a sendable workspace draft.
const canChooseDispatchMode = variant === "workspace" && canSend;
const sendModeMenu = useContextMenuPosition({
longPress: true,
canOpen: () => canChooseDispatchMode,
});
const {
isOpen: isSendModeMenuOpen,
onContextMenu: openSendModeMenuFromContext,
touchHandlers: sendModeMenuTouchHandlers,
suppressClickIfLongPress: suppressSendClickIfLongPress,
close: closeSendModeMenu,
} = sendModeMenu;

useEffect(() => {
if (canChooseDispatchMode) {
return;
}

closeSendModeMenu();
}, [canChooseDispatchMode, closeSendModeMenu]);

useEffect(() => {
if (!isSendModeMenuOpen) {
return;
}

const handleClickOutside = (event: MouseEvent) => {
if (sendModeMenuContainerRef.current?.contains(event.target as Node)) {
return;
}
closeSendModeMenu();
};

const handleEscape = (event: KeyboardEvent) => {
if (event.key !== "Escape") {
return;
}

// Mark Escape as handled so global interrupt listeners do not cancel the stream
// when users are only dismissing this inline send-mode menu.
event.preventDefault();
event.stopPropagation();
closeSendModeMenu();
};

document.addEventListener("mousedown", handleClickOutside);
document.addEventListener("keydown", handleEscape);
return () => {
document.removeEventListener("mousedown", handleClickOutside);
document.removeEventListener("keydown", handleEscape);
};
}, [closeSendModeMenu, isSendModeMenuOpen]);

// User request: this sync effect runs on mount and when defaults/config change.
// Only treat *real* agent changes as explicit (origin "agent"); everything else is "sync".
const prevCreationAgentIdRef = useRef<string | null>(null);
const prevCreationScopeIdRef = useRef<string | null>(null);
const prevCreationProjectRef = useRef<string | null>(null);
// Creation variant: keep the project-scoped model/thinking in sync with global agent defaults
// so switching agents uses the configured defaults (and respects "inherit" semantics).
useEffect(() => {
if (variant !== "creation") {
// Reset tracking on variant transitions so creation entry never counts as an explicit switch.
prevCreationAgentIdRef.current = null;
prevCreationScopeIdRef.current = null;
return;
}

const scopeId = getCreationDraftScopeId(creationDraftId);

const fallbackModel = defaultModel;

const normalizedAgentId = normalizeAgentId(agentId, "exec");

// Defaults come from the agent's base chain, which needs the list.
if (!agentsLoaded) return;
const isFirstSync = prevCreationScopeIdRef.current !== scopeId;
// A project change resets the agent automatically: that is no pick of the user's.
const isExplicitAgentSwitch =
!isFirstSync &&
prevCreationProjectRef.current === creationParentProjectPath &&
prevCreationAgentIdRef.current !== normalizedAgentId;

// Update refs for the next run (even if no model changes).
prevCreationAgentIdRef.current = normalizedAgentId;
prevCreationScopeIdRef.current = scopeId;
prevCreationProjectRef.current = creationParentProjectPath;
// The draft owns its choices: after the composer seeds them, only the user's agent pick applies
// agent defaults over them (not a move, its agent reset or an agent list reload).
if (!isFirstSync && !isExplicitAgentSwitch) return;

const existingModel = readScopedAiDefault(scopeId, "model") ?? fallbackModel;
const existingThinking = readScopedAiDefault(scopeId, "thinkingLevel") ?? "off";
// Configured defaults (direct or base-chain, field-wise) must reach the
// first turn of a new workspace too, not just post-creation agent syncs:
// a custom agent inheriting model/thinking/pro from its base would
// otherwise send the first prompt with the ambient model and Pro gated off
// until WorkspaceModeAISync corrects the workspace.
const existingReasoning = getWorkspaceAiSelection(scopeId).reasoningMode;
const agentBaseById = new Map(agents.map((agent) => [agent.id, agent.base]));
const agentBaseById = getAgentAiSettingsBases(agents);
const {
resolvedModel,
resolvedThinking,
resolvedReasoningMode: resolvedReasoning,
} = resolveWorkspaceAiSettingsForAgent({
agentId: normalizedAgentId,
agentAiDefaults,
fallbackModel,
existingModel,
existingThinking,
existingReasoningMode: existingReasoning,
agentBaseById,
});
if (existingModel !== resolvedModel) {
setWorkspaceModelWithOrigin(scopeId, resolvedModel, isExplicitAgentSwitch ? "agent" : "sync");
}

if (existingThinking !== resolvedThinking) {
writeScopedAiDefault(scopeId, "thinkingLevel", resolvedThinking);
}

if (existingReasoning !== resolvedReasoning) {
markAiSelectionIntent(scopeId, "reasoningMode", resolvedReasoning);
}
}, [
agentAiDefaults,
agentId,
agents,
agentsLoaded,
creationDraftId,
creationParentProjectPath,
defaultModel,
variant,
]);

const chatDockColumnWidthClass = useChatDockColumnWidthClass();

// Expose ChatInput auto-focus completion for Storybook/tests.
const chatInputSectionRef = useRef<HTMLDivElement | null>(null);
const setChatInputAutoFocusState = useCallback((state: "pending" | "done") => {
chatInputSectionRef.current?.setAttribute("data-autofocus-state", state);
}, []);

const focusMessageInput = useCallback(() => {
const element = inputRef.current;
if (!element || element.disabled) {
return;
}

element.focus();

requestAnimationFrame(() => {
const cursor = element.value.length;
element.selectionStart = cursor;
element.selectionEnd = cursor;
// Skip the resize dance when empty: reading scrollHeight after a height write
// forces a synchronous reflow, and this rAF fires right after a workspace
// switch while the freshly mounted transcript is still dirty — laying out the
// whole document before first paint. Empty composers are sized by CSS alone
// (rows=1 + min-height; see useAutoResizeTextarea).
if (element.value !== "") {
element.style.height = "auto";
element.style.height = Math.min(element.scrollHeight, window.innerHeight * 0.5) + "px";
}
});
}, []);

const applyDraftFromPending = useCallback(
(pending: PendingUserMessage, attachmentKeyPrefix: string) => {
setDraft({
text: pending.content,
attachments: pendingChatAttachments(pending, attachmentKeyPrefix),
});
},
[setDraft]
);

// Restore a full pending draft (text + attachments + reviews), e.g. queued message edits.
const restoreDraft = useCallback(
(pending: PendingUserMessage, options?: { retainedSendIds?: string[] }) => {
const retained = getDraftStore().getPendingSendIds(draftScope);
const sendIds = options?.retainedSendIds ?? [];
const retainedSendIds = sendIds.filter((id) => retained.has(id));
if (retainedSendIds.length === 0) {
applyDraftFromPending(pending, `restored-${Date.now()}`);
} else {
// The draft still retains these sends: they come back as not accepted (prepended to the
// composer text) once the backend no longer holds them. Inserting them here too would
// show them twice, so only the rest of the queued input (sends the draft does not
// retain, e.g. a backend-minted one) is inserted now.
if (draftScope.kind === "workspace") {
getDraftStore().triggerSendResolution(draftScope.workspaceId);
}
if (retainedSendIds.length < sendIds.length) {
const { text: restText, ...rest } = getDraftStore().withoutRetainedSends(
draftScope,
retainedSendIds,
{ ...pending, text: pending.content }
);
// Merged in front, never replacing: the composer may already show a resolved send.
setInput((current) => joinDraftText(restText, current));
const restAttachments = pendingChatAttachments(
{ ...rest, content: restText },
`restored-${Date.now()}`
);
if (restAttachments.length > 0) {
setAttachments((current) => [...restAttachments, ...current]);
}
}
}
setDraftReviews(pending.reviews);
focusMessageInput();
},
[
applyDraftFromPending,
draftScope,
focusMessageInput,
setAttachments,
setDraftReviews,
setInput,
]
);

// The latest edit's session. Settled explicitly: the edit target also leaves the live
// transcript when the accepted edit replaces it (possibly before the send returns), and that
// is not a cancel.
const editSessionRef = useRef<EditSession | null>(null);
// Live review override for completions that settle after the render they started in.
const draftReviewsRef = useRef(draftReviews);
useLayoutEffect(() => {
draftReviewsRef.current = draftReviews;
});
const restorePreEditDraft = () => {
const session = editSessionRef.current;
if (!session || session.settled || session.id !== editingMessageIdRef.current) return;
session.settled = true;
setDraft(session.preEditDraft);
setDraftReviews(session.preEditReviews);
};

// Completing an edit sends the edited message; the unsent draft from before the edit comes
// back as on cancel, so typed input is never lost (#5155). Functional updates keep anything
// typed while the send was in flight, after the restored draft; restored notes join notes
// attached meanwhile. Not for an edit the user cancelled meanwhile: it got its draft back. No
// edit starts while the send is pending (#5226). `dropEditReviews`: an editing command's send
// leaves the edit's own notes in the composer; they are replaced, not merged.
const restorePreEditDraftAfterSend = (
session: EditSession | null,
dropEditReviews = false
): boolean => {
if (!session || session.settled) return false;
session.settled = true;
const { preEditDraft, preEditReviews } = session;
if (dropEditReviews) setDraftReviews(null);
setInput((current) => joinDraftText(preEditDraft.text, current));
if (preEditDraft.attachments.length > 0) {
setAttachments((current) => [...preEditDraft.attachments, ...current]);
}
if (preEditReviews !== null) {
if ((dropEditReviews || draftReviewsRef.current === null) && onAddReviewForRestore) {
// The notes in effect live in the review store: add the restored ones there too.
for (const review of preEditReviews) onAddReviewForRestore(review);
} else {
setDraftReviews((current) => [...preEditReviews, ...(current ?? [])]);
}
}
return true;
};
// By identity, not row id: a row reopened after a cancel is a new edit.
const isOpenEditOrNone = (session: EditSession | null) =>
editingMessageIdRef.current === undefined || editSessionRef.current === session;

// Method to restore text to input (used by compaction cancel)
const restoreText = useCallback(
(text: string) => {
// #6866: a replace is not typing, even when its text starts with the sent text: a send not
// yet taken removes nothing from it.
getDraftStore().markSendEdited(draftScope);
setInput(() => text);
focusMessageInput();
},
[draftScope, focusMessageInput, setInput]
);

// Method to append text to input (used by Code Review notes)
const appendText = useCallback(
(text: string) => {
setInput((prev) => {
// Add blank line before if there's existing content
const separator = prev.trim() ? "\n\n" : "";
return prev + separator + text;
});
// Don't focus - user wants to keep reviewing
},
[setInput]
);

// Method to prepend text to input (used by manual compact trigger)
const prependText = useCallback(
(text: string) => {
setInput((prev) => text + prev);
focusMessageInput();
},
[focusMessageInput, setInput]
);

const handleSendRef = useRef<() => Promise<void>>(() => Promise.resolve());
const send = useCallback(() => {
return handleSendRef.current();
}, []);

const onReady = props.onReady;

// Provide API to parent via callback. Latest-ref wrappers (see handleSendRef)
// keep the handed-out object stable even though the draft helpers are not
// identity-stable without manual memoization; re-invoking onReady per render
// would churn parent state.
const composerApiRef = useRef({ restoreText, restoreDraft, appendText, prependText });
useEffect(() => {
composerApiRef.current = { restoreText, restoreDraft, appendText, prependText };
});
useEffect(() => {
if (onReady) {
onReady({
focus: focusMessageInput,
send,
restoreText: (text) => composerApiRef.current.restoreText(text),
restoreDraft: (pending, options) => composerApiRef.current.restoreDraft(pending, options),
appendText: (text) => composerApiRef.current.appendText(text),
prependText: (text) => composerApiRef.current.prependText(text),
});
}
}, [onReady, focusMessageInput, send]);

// The creation composer shows the focus-chat hint too, but the only handler lived in the
// workspace view (useAIViewKeybinds), so the shortcut did nothing here (#5687). Same rules as
// there: capture phase, works from inputs, yields to remote desktops and open dialogs.
useEffect(() => {
if (variant !== "creation") return;
const handleFocusChat = (event: KeyboardEvent) => {
if (!matchesKeybind(event, KEYBINDS.FOCUS_CHAT) || isDesktopViewportFocused(event.target)) {
return;
}
event.preventDefault();
if (!isDialogOpen() && !isCommandPaletteTarget(event.target)) focusMessageInput();
};
window.addEventListener("keydown", handleFocusChat, { capture: true });
return () => window.removeEventListener("keydown", handleFocusChat, { capture: true });
}, [variant, focusMessageInput]);

useEffect(() => {
const handleGlobalKeyDown = (event: KeyboardEvent) => {
if (isEditableElement(event.target) || !paneHandlesKeyEvent(paneScope, event.target)) {
return;
}

if (matchesKeybind(event, KEYBINDS.FOCUS_INPUT_I)) {
event.preventDefault();
focusMessageInput();
return;
}

if (matchesKeybind(event, KEYBINDS.FOCUS_INPUT_A)) {
event.preventDefault();
focusMessageInput();
return;
}

if (matchesKeybind(event, KEYBINDS.CYCLE_MODEL)) {
event.preventDefault();
focusMessageInput();
cycleToNextModelRef.current();
}
};

window.addEventListener("keydown", handleGlobalKeyDown);
return () => {
window.removeEventListener("keydown", handleGlobalKeyDown);
};
}, [focusMessageInput, openModelSelector, paneScope]);

// When entering editing mode, save current draft and populate with message content.
// Runs once per edit target: the draft callbacks change identity as the user types, and
// re-applying would clobber the in-progress edit text. The applied-id ref makes that
// explicit instead of hiding the callbacks from the dependency list.
const appliedEditIdRef = useRef<string | null>(null);
const draftPayloadsLoaded = draft.payloadsLoaded;
useEffect(() => {
if (!editingMessage) {
appliedEditIdRef.current = null;
return;
}
if (appliedEditIdRef.current === editingMessage.id) return;
if (!draftPayloadsLoaded) {
// Hydrated attachments have no payloads yet (the draft shows none). Snapshotting now would
// save an attachment-less draft on cancel, and the edit's full replacement would end the
// load. Enter edit mode once they load (re-requested here in case an earlier load failed).
getDraftStore()
.ensurePayloads(draftScope)
.catch((error: unknown) => console.warn("Failed to load draft attachments:", error));
return;
}
appliedEditIdRef.current = editingMessage.id;
editSessionRef.current = {
id: editingMessage.id,
preEditDraft: getDraft(),
preEditReviews: draftReviews,
settled: false,
};
applyDraftFromPending(editingMessage.pending, `edit-${editingMessage.id}`);
setDraftReviews(editingMessage.pending.reviews);
// Auto-resize textarea and focus
setTimeout(() => {
if (inputRef.current) {
inputRef.current.style.height = "auto";
inputRef.current.style.height =
Math.min(inputRef.current.scrollHeight, window.innerHeight * 0.5) + "px";
inputRef.current.focus();
}
}, 0);
}, [
editingMessage,
draftPayloadsLoaded,
draftScope,
getDraft,
draftReviews,
applyDraftFromPending,
setDraftReviews,
]);

// Project live workflow run cards for foreground slash invocations after reloads.
useEffect(() => {
let isMounted = true;
const requestId = ++workflowsRequestIdRef.current;

const loadWorkflows = async () => {
if (!api) {
return;
}

await runWithCatch(
async () => {
const discoveryWorkspaceId = variant === "workspace" && workspaceId ? workspaceId : null;
const runs =
discoveryWorkspaceId != null && isTranscriptCaughtUp
? await api.workflows.listRuns({ workspaceId: discoveryWorkspaceId })
: [];
if (!isMounted || workflowsRequestIdRef.current !== requestId) {
return;
}
if (discoveryWorkspaceId == null) {
return;
}
const muxMessages = store.getWorkspaceState(discoveryWorkspaceId).muxMessages;
for (const run of runs) {
const projection = getWorkflowRunCardProjection(muxMessages, run);
if (!projection.shouldProject) {
continue;
}
const cardKey = `${discoveryWorkspaceId}:${run.id}:${run.updatedAt}:${run.status}`;
if (projectedWorkflowRunCardKeysRef.current.has(cardKey)) {
continue;
}
projectedWorkflowRunCardKeysRef.current.add(cardKey);
addWorkflowRunCardMessageForRun(discoveryWorkspaceId, run, {
existingMessage: projection.existingMessage,
});
}
},
(error) => {
console.error("Failed to project workflow run cards:", error);
}
);
};

void loadWorkflows();

return () => {
isMounted = false;
};
}, [api, variant, workspaceId, atMentionProjectPath, isTranscriptCaughtUp, store]);

// Voice input: track transcription provider availability (subscribe to provider config changes)
useEffect(() => {
if (!api) return;

const abortController = new AbortController();
const { signal } = abortController;

// Set by forEachProviderConfigChange; returned on cleanup.
let iterator: AsyncIterator<unknown> | null = null;

const checkTranscriptionConfig = () =>
runWithCatch(
async () => {
const config = await api.providers.getConfig();
if (!signal.aborted) {
// VoiceService resolves keys from config, key files and env vars alike. Codex OAuth
// alone cannot transcribe, so isConfigured is not enough.
setOpenAIKeySet(hasOpenAIApiKey(config?.openai));
setOpenAIProviderEnabled(config?.openai?.isEnabled ?? true);
}
},
() => {
// Ignore errors fetching config
}
);

// Initial fetch
void checkTranscriptionConfig();

// Subscribe to provider config changes via oRPC
void forEachProviderConfigChange(
api,
signal,
(subscribedIterator) => {
iterator = subscribedIterator;
},
() => void checkTranscriptionConfig()
);

return () => {
abortController.abort();
void iterator?.return?.();
};
}, [api]);

// Allow external components (e.g., CommandPalette, Queued message edits) to insert text
useEffect(() => {
type UpdateDetail = CustomEventPayloads[typeof CUSTOM_EVENTS.UPDATE_CHAT_INPUT];
const handler = (e: Event) => {
const detail = (e as CustomEvent<UpdateDetail>).detail;
if (detail.workspaceId != null && workspaceIdForComposerClear !== detail.workspaceId) {
return;
}
// Unscoped updates come from the palette / main UI; the side composer only takes updates
// addressed to its own workspace so text is never inserted into both composers.
if (detail.workspaceId == null && paneScope !== "main") {
return;
}
const { inputs } = detail;
if (detail.mode !== "restore" || inputs == null) {
applyUpdate(detail);
return;
}
// Idempotent sends: a restored send whose id the draft still retains (pendingSends) is not
// inserted again: once its held input is released, its entry resolves as not accepted and
// its text becomes visible from the draft. An id-less (foreign) input is inserted once, as
// before.
const retained = getDraftStore().getPendingSendIds(draftScope);
const parts = inputs.map((restored) => {
const retainedIds = restored.sendIds.filter((id) => retained.has(id));
if (retainedIds.length === 0) return { restored, insert: restored, hasRetained: false };
if (retainedIds.length === restored.sendIds.length) {
return { restored, insert: null, hasRetained: true };
}
// One input can join a retained send with one the draft does not retain (e.g. a
// backend-minted one): insert only the latter's part.
const rest = getDraftStore().withoutRetainedSends(draftScope, retainedIds, {
text: restored.text,
fileParts: restored.fileParts ?? [],
});
const insert = {
text: rest.text,
fileParts: rest.fileParts,
sendIds: restored.sendIds.filter((id) => !retained.has(id)),
};
return { restored, insert, hasRetained: true };
});
// An input with ids the draft no longer retains may be a late copy of a send the backend
// already accepted (e.g. two windows re-sent it after a restart): ask before inserting it,
// so accepted text never comes back to be sent again. A failed lookup inserts it (a
// visible duplicate beats a loss).
const restoreParts = (accepted: ReadonlySet<string>) => {
const isAcceptedCopy = (insert: { sendIds: string[] }) =>
insert.sendIds.length > 0 && insert.sendIds.every((id) => accepted.has(id));
const inserted = parts.flatMap(({ insert }) =>
insert && !isAcceptedCopy(insert) ? [insert] : []
);
// Notes come back per input: none for an input dropped as an accepted copy (they were
// sent). A retained send's notes do come back here: its draft entry keeps only its text
// and attachments.
const reviews = parts.flatMap(({ restored, insert, hasRetained }) =>
!hasRetained && insert && isAcceptedCopy(insert) ? [] : (restored.reviews ?? [])
);
applyUpdate({
...detail,
inputs: undefined,
text: inserted
.map((restored) => restored.text)
.filter((part) => part.length > 0)
.join("\n"),
fileParts: inserted.flatMap((restored) => restored.fileParts ?? []),
reviews: reviews.length > 0 ? reviews : undefined,
});
};
const askIds = parts.flatMap(({ insert }) => insert?.sendIds ?? []);
if (askIds.length === 0 || workspaceIdForComposerClear == null || api == null) {
restoreParts(new Set());
return;
}
acceptedSendIds(api, workspaceIdForComposerClear, askIds)
.catch(() => new Set<string>())
.then(restoreParts)
.catch((error: unknown) => console.error("Failed to restore queued input:", error));
};
const applyUpdate = (detail: UpdateDetail) => {
const { text, mode = "append", fileParts, reviews } = detail;
const restoredIdPrefix = `restored-${Date.now()}`;
const restoredPending = buildPendingFromRestoredInput({
content: text,
fileParts: fileParts ?? [],
reviews: reviews ?? [],
idPrefix: restoredIdPrefix,
});
const hasFileParts = restoredPending.fileParts.length > 0;
const hasStagedAttachments = restoredPending.stagedAttachments.length > 0;
const hasReviews = restoredPending.reviews.length > 0;

if (mode === "restore") {
// A queued message returned by Stop (#4431). It must not destroy a newer draft the user
// typed while it waited, so it goes in front of whatever the composer holds: it was
// written, and would have been sent, first. An empty composer ends up with exactly the
// restored message, as the old replace did. Functional updates merge with the current
// draft rather than the one this listener was registered with.
// Like "replace", never inject into a historical-message edit (e.g. canceling compaction
// enters edit mode before its interrupt restores the queue).
if (editingMessageForUi) {
return;
}
const restoredAttachments = pendingChatAttachments(restoredPending, restoredIdPrefix);
// Merged from the stored draft, exactly as a functional setInput would, so the
// acknowledgement below can check that this exact value landed.
const mergedText = [restoredPending.content, getDraftStore().getText(draftScope)]
.filter((part) => part.trim().length > 0)
.join("\n\n");
setInput(mergedText);
if (restoredAttachments.length > 0) {
setAttachments((current) => [...restoredAttachments, ...current]);
}
// Ids the review store added; null when the notes went to the memory-only override.
let restoredReviewIds: string[] | null = [];
if (restoredPending.reviews.length > 0) {
if (draftReviews === null && onAddReviewForRestore) {
// The draft's notes live in the review store: add the restored ones there too, as
// new attached notes. A detached copy in the override would hide later store
// changes, and a send in flight checks off only the notes it captured, not these.
// Called here, not in a state updater, which may run more than once.
restoredReviewIds = restoredPending.reviews.map(
(review) => onAddReviewForRestore(review).id
);
} else {
// An active override (e.g. a queued-message edit) owns the composer's notes.
setDraftReviews((current) => [...restoredPending.reviews, ...(current ?? [])]);
restoredReviewIds = null;
}
}
// The backend keeps this input as held input until a composer takes it (#4448). Release
// that copy only once every restored part is durable; otherwise the "Not sent" banner
// stays next to the composer's copy: a visible duplicate beats a loss. Edit mode (above)
// takes nothing.
const heldInputIds = detail.heldInputIds ?? [];
if (heldInputIds.length > 0 && workspaceIdForComposerClear != null) {
// The backend copy is released only after the backend confirmed the restored draft
// write; a failed write keeps (and shows) the held input.
const draftDurable = isRestoredDraftDurable({
draftStore: getDraftStore(),
draftScope,
restoredAttachmentIds: restoredAttachments.map(({ id }) => id),
restoredReviewIds,
});
// Restored notes live in the backend review-state store: require its
// server-acknowledged copy too. A failed flush leaves the input held (fail closed; a
// visible duplicate beats a loss).
const durable =
restoredReviewIds !== null && restoredReviewIds.length > 0
? Promise.all([
draftDurable,
getReviewStateStore()
.areReviewsDurable(workspaceIdForComposerClear, restoredReviewIds)
.catch(() => false),
]).then(([draftOk, reviewsOk]) => draftOk && reviewsOk)
: draftDurable;
onAcceptRestoredHeldInputs?.(heldInputIds, durable);
}
focusMessageInput();
} else if (mode === "replace") {
if (editingMessageForUi) {
return;
}
// #6866: a replace is not typing (see restoreText), with or without files.
getDraftStore().markSendEdited(draftScope);
if (hasFileParts || hasStagedAttachments || hasReviews) {
restoreDraft(restoredPending);
} else {
restoreText(restoredPending.content);
}
} else if (hasFileParts || hasStagedAttachments || hasReviews) {
const currentText = getDraft().text;
const separator = currentText.trim() ? "\n\n" : "";
applyDraftFromPending(
{
...restoredPending,
content: currentText + separator + restoredPending.content,
},
restoredIdPrefix
);
} else {
appendText(restoredPending.content);
}
};
window.addEventListener(CUSTOM_EVENTS.UPDATE_CHAT_INPUT, handler as EventListener);
return () =>
window.removeEventListener(CUSTOM_EVENTS.UPDATE_CHAT_INPUT, handler as EventListener);
}, [
appendText,
restoreText,
restoreDraft,
applyDraftFromPending,
getDraft,
editingMessageForUi,
workspaceIdForComposerClear,
setInput,
setAttachments,
draftReviews,
setDraftReviews,
onAddReviewForRestore,
onAcceptRestoredHeldInputs,
draftScope,
focusMessageInput,
api,
paneScope,
]);

useEffect(() => {
const handler = (event: CustomEvent<{ workspaceId: string }>) => {
if (workspaceIdForComposerClear !== event.detail.workspaceId) {
return;
}

setInput("");
setAttachments([]);
setDraftReviews(null);
onDetachAllReviewsForComposerClear?.();
if (inputRef.current) {
inputRef.current.style.height = "";
}
};

window.addEventListener(CUSTOM_EVENTS.CLEAR_CHAT_COMPOSER, handler as EventListener);
return () =>
window.removeEventListener(CUSTOM_EVENTS.CLEAR_CHAT_COMPOSER, handler as EventListener);
}, [
onDetachAllReviewsForComposerClear,
setAttachments,
setDraftReviews,
setInput,
workspaceIdForComposerClear,
]);

// Allow external components to open the Model Selector
useEffect(() => {
// Unscoped palette event: the main composer owns it (see paneScope).
if (paneScope !== "main") return;
const handler = () => {
// Open the inline ModelSelector and let it take focus itself
modelSelectorRef.current?.open();
};
window.addEventListener(CUSTOM_EVENTS.OPEN_MODEL_SELECTOR, handler as EventListener);
return () =>
window.removeEventListener(CUSTOM_EVENTS.OPEN_MODEL_SELECTOR, handler as EventListener);
}, [paneScope]);

// Show toast when thinking level is changed via command palette (workspace only)
useEffect(() => {
if (variant !== "workspace") return;

const handler = (event: Event) => {
const detail = (event as CustomEvent<{ workspaceId: string; level: ThinkingLevel }>).detail;
if (detail?.workspaceId !== props.workspaceId || !detail.level) {
return;
}

const level = detail.level;
const levelDescriptions: Record<ThinkingLevel, string> = {
off: "Off — fastest responses",
low: "Low — adds light reasoning",
medium: "Medium — balanced reasoning",
high: "High — maximum reasoning depth",
xhigh: "Max — deepest possible reasoning",
max: "Max — deepest possible reasoning",
};

pushToast({
type: "success",
message: `Thinking effort set to ${levelDescriptions[level]}`,
});
};

window.addEventListener(CUSTOM_EVENTS.THINKING_LEVEL_TOAST, handler as EventListener);
return () =>
window.removeEventListener(CUSTOM_EVENTS.THINKING_LEVEL_TOAST, handler as EventListener);
}, [variant, props, pushToast]);

useChatErrorToasts(workspaceId, toast?.message ?? null, pushToast);

// Show toast feedback for analytics rebuild command palette action.
useEffect(() => {
// Unscoped palette event: the main composer owns it so the toast shows once.
if (paneScope !== "main") return;
const handler = (event: Event) => {
const detail = (
event as CustomEvent<CustomEventPayloads[typeof CUSTOM_EVENTS.ANALYTICS_REBUILD_TOAST]>
).detail;

if (!detail || (detail.type !== "success" && detail.type !== "error")) {
return;
}

pushToast({
type: detail.type,
title: detail.title,
message: detail.message,
copyText: detail.copyText,
duration: detail.duration,
});
};

window.addEventListener(CUSTOM_EVENTS.ANALYTICS_REBUILD_TOAST, handler as EventListener);
return () =>
window.removeEventListener(CUSTOM_EVENTS.ANALYTICS_REBUILD_TOAST, handler as EventListener);
}, [pushToast, paneScope]);

// Voice input: command palette toggle + global recording keybinds
useEffect(() => {
// Unscoped palette event: only the main composer starts recording (see paneScope).
if (!voiceInput.shouldShowUI || paneScope !== "main") return;

const handleToggle = () => {
if (!voiceInput.isAvailable) {
pushToast({
type: "error",
message: voiceInputUnavailableMessage,
});
return;
}
voiceInput.toggle();
};

window.addEventListener(CUSTOM_EVENTS.TOGGLE_VOICE_INPUT, handleToggle as EventListener);
return () => {
window.removeEventListener(CUSTOM_EVENTS.TOGGLE_VOICE_INPUT, handleToggle as EventListener);
};
}, [voiceInput, pushToast, voiceInputUnavailableMessage, paneScope]);

useWorkspaceSwitchAutoFocus({
workspaceId: variant === "workspace" ? props.workspaceId : null,
inputRef,
sectionRef: chatInputSectionRef,
focusInput: focusMessageInput,
setAutoFocusState: setChatInputAutoFocusState,
});

// Shared slash command execution for creation + workspace inputs.
const commandWorkspaceId = variant === "workspace" ? props.workspaceId : undefined;
const commandProjectPath =
variant === "creation" ? props.projectPath : (selectedWorkspace?.projectPath ?? null);
const commandOnCancelEdit = variant === "workspace" ? props.onCancelEdit : undefined;

// Keep this helper as a plain function so command wiring stays readable without a giant
// dependency list; the React Compiler already handles memoization.
/**
* The composer's review notes for a send. Attached notes live in the backend review-state
* store; a send racing its hydration waits for it (normally already done) and reads them from
* the store, so neither a command (e.g. /compact's follow-up) nor a normal send is built from
* the empty loading view. After a failed subscription the store retries it (bounded, #5011);
* if the notes still cannot be read, none are included and `unavailable` is set, so the send
* path can say so (see warnIfReviewsUnavailable).
*/
const readReviewsForSend = async (): Promise<ReviewsForSend> => {
const renderTime: ReviewsForSend = { data: reviewData, ids: reviewIdsForCheck };
if (variant !== "workspace" || !workspaceId || reviewOverrideActive) return renderTime;
const reviewStateStore = getReviewStateStore();
// Without an API client (backend reconnecting) hydration cannot finish, and waiting would
// hold this send in flight and fire it after reconnect; let the send path report
// "Not connected to server" instead.
if (!liveApi || reviewStateStore.isHydrated(workspaceId)) return renderTime;
const attached = await reviewStateStore.readAttachedReviewsForSend(workspaceId);
if (attached === null) {
// The render-time notes may be a stale cache; send none rather than a possibly wrong set.
return { data: undefined, ids: [], unavailable: true };
}
return {
data: attached.length > 0 ? attached.map((review) => review.data) : undefined,
ids: attached.map((review) => review.id),
};
};

/**
* Called only once a message that would carry the notes was accepted (a normal send, or
* /compact's check-reviews action), so a failed send or a command like /vim never shows it.
*/
const warnIfReviewsUnavailable = (reviews: ReviewsForSend) => {
if (!reviews.unavailable) return;
pushToast({
type: "error",
message:
"Review notes could not be loaded, so none were attached. They are kept; send them once they load.",
});
};

const executeParsedCommand = async (
parsed: ParsedCommand | null,
restoreInput: string,
options: {
inlineRefs: SlashCommandInlineRefs;
skipConfirmation?: boolean;
queueDispatchMode?: QueueDispatchMode;
goalInterventionPolicy?: GoalInterventionPolicy;
/** Hydrated review notes read by the send path; defaults to the render-time notes. */
reviews?: ReviewsForSend;
}
): Promise<boolean> => {
if (!parsed) {
return false;
}

// /<model-alias> ... is a *send modifier* (one-shot model override), not a command with its own
// side effects. Let the normal send flow handle it so post-send behavior can't drift.
if (parsed.type === "model-oneshot") {
if (variant !== "workspace") {
setToast({
id: Date.now().toString(),
type: "error",
message: "Model one-shot is only available in workspace view",
});
return true;
}
return false;
}

const isDestructive = parsed.type === "clear" && parsed.mode === "hard";
if (isDestructive && variant === "workspace" && !options.skipConfirmation) {
setPendingDestructiveCommand(true);
return true;
}

// Pending files block every command (even /compact) because command sends
// never stage them, so they'd be silently dropped.
if (
getPendingFileAttachments(attachments).length > 0 ||
(getStagedAttachments(attachments).length > 0 && parsed.type !== "compact")
) {
setToast({
id: Date.now().toString(),
type: "error",
message: "This command cannot include staged files. Remove them or send a normal message.",
});
return true;
}

const reviewsData = options.reviews ? options.reviews.data : reviewData;
const dispatchMode = options.queueDispatchMode ?? "tool-end";
// Thread dispatch mode into send options so queued command sends stay in sync with normal sends.
const commandSendMessageOptions: SendMessageOptions = {
...sendMessageOptions,
...(options.goalInterventionPolicy
? { goalInterventionPolicy: options.goalInterventionPolicy }
: {}),
...(dispatchMode === "tool-end" ? {} : { queueDispatchMode: dispatchMode }),
};
// Prepare file parts for commands that need to send messages with attachments
const commandFileParts = chatAttachmentsToFileParts(attachments, { validate: true });
const asyncCommandToken = ++asyncCommandTokenRef.current;
const commandEnv: SlashCommandEnv = {
// Commands report "Not connected to server" themselves when there is no live client.
api: liveApi,
inlineRefs: options.inlineRefs,
aiScopeId: sendOptionsScopeId,
variant,
workspaceId: commandWorkspaceId,
projectPath: commandProjectPath,
rawInput: restoreInput,
currentModel: workspaceSidebarState?.currentModel ?? null,
sendMessageOptions: commandSendMessageOptions,
resetContext: variant === "workspace" ? props.onResetContext : undefined,
truncateHistory: variant === "workspace" ? props.onTruncateHistory : undefined,
editMessageId: editingMessageForUi?.id,
historyEditPrecondition: editingMessageForUi
? getEditSendPrecondition(editingMessageForUi)
: undefined,
reviews: reviewsData,
attachments,
fileParts: commandFileParts.length > 0 ? commandFileParts : undefined,
attachedReviewIds: options.reviews ? options.reviews.ids : reviewIdsForCheck,
isSideChat:
commandWorkspaceId != null &&
workspaceMetadata.get(commandWorkspaceId)?.sideChatParentWorkspaceId != null,
isCurrent: () => {
const scope = asyncCommandScopeRef.current;
return (
asyncCommandToken === asyncCommandTokenRef.current &&
scope.variant === "workspace" &&
scope.workspaceId === commandWorkspaceId
);
},
};

// A completed edit restored its pre-edit draft, review notes included: keep them.
let restoredPreEditDraft = false;
const commandEditSession =
commandEnv.editMessageId !== undefined &&
editSessionRef.current?.id === commandEnv.editMessageId
? editSessionRef.current
: null;
// An editing command whose edit gave its draft back (the user cancelled it) or is no longer
// the open edit: the composer holds another draft, so the command's clears must not touch it.
const editCancelled = () =>
commandEditSession?.settled === true || !isOpenEditOrNone(commandEditSession);
// Command actions stop at the caller's UI boundary; creation mode intentionally has its own applier.
const applyCommandActions = (actions: CommandAction[]) => {
for (const action of actions) {
switch (action.type) {
case "clear-input":
if (!editCancelled()) setInput("");
break;
case "reset-input-height":
if (inputRef.current) inputRef.current.style.height = "";
break;
case "show-toast":
setToast(action.toast);
break;
case "set-preferred-model":
setPreferredModel(action.model);
break;
case "toggle-vim":
updateUserPreferences({
appearance: { vimEnabled: getUserPreferences().appearance?.vimEnabled !== true },
});
break;
case "set-sending":
setSendingCount((count) => count + (action.sending ? 1 : -1));
break;
case "clear-attachments":
if (!editCancelled()) setAttachments([]);
break;
case "detach-reviews":
if (variant === "workspace") props.onDetachAllReviews?.();
break;
case "check-reviews":
if (variant === "workspace" && action.reviewIds.length > 0) {
props.onCheckReviews?.(action.reviewIds);
}
// Emitted once the command's message was accepted (/compact).
if (options.reviews) warnIfReviewsUnavailable(options.reviews);
break;
case "message-sent":
if (variant === "workspace") props.onMessageSent?.(action.dispatchMode);
break;
case "cancel-edit":
// Emitted once an editing command (/compact) was accepted: the edit is complete.
restoredPreEditDraft = restorePreEditDraftAfterSend(commandEditSession, true);
if (isOpenEditOrNone(commandEditSession)) commandOnCancelEdit?.();
break;
case "edit-history-changed":
startEditTranscriptRefresh(action.editMessageId, action.precondition);
break;
}
}
};

let result = await processSlashCommand(parsed, commandEnv);
while (result.kind === "phase") {
applyCommandActions(result.actions);
result = await result.continue();
}
applyCommandActions(result.actions);
if (result.backgroundTask) {
void result.backgroundTask().then(applyCommandActions);
}

switch (result.inputDisposition) {
case "consume":
// Commands clear the composer through their own clear-input actions;
// clearing again here would wipe a draft typed while phases ran.
if (!restoredPreEditDraft) setDraftReviews(null);
break;
case "restore":
setInput(restoreInput);
break;
case "restore-if-empty":
// Async phases can outlive the invoking render, so check the live
// draft: the getDraft closure captured here still reports
// this render's input and would refuse to restore over a newer draft.
if (draft.getLiveText().trim().length === 0) {
setInput(restoreInput);
} else {
setDraftReviews(null);
}
break;
}

return true;
};

// Handle destructive command confirmation (currently only /clear).
const handleDestructiveCommandConfirm = async () => {
if (!pendingDestructiveCommand || variant !== "workspace") return;

const parsedCommand: ParsedCommand = { type: "clear", mode: "hard" };

setPendingDestructiveCommand(false);
await executeParsedCommand(parsedCommand, input, {
inlineRefs: NO_INLINE_REFS,
skipConfirmation: true,
});
};

const handleDestructiveCommandCancel = useCallback(() => {
setPendingDestructiveCommand(false);
}, []);

/**
* Conflict recovery after a `history-changed` refusal: one logical transcript refresh whose
* outcome updates the parent-owned editing state. Nothing here re-sends — the user's next
* explicit Send carries the refreshed candidate unchanged. Escape (cancel editing) stays
* available throughout and cancels the request through the editing-state owner.
*/
const startEditTranscriptRefresh = (
editMessageId: string,
precondition: HistoryEditPrecondition
): void => {
if (variant !== "workspace") return;
const targetWorkspaceId = props.workspaceId;
const onEditingMessageChange = props.onEditingMessageChange;
const onCancelEdit = props.onCancelEdit;
const patchEditing = (
patch: Pick<EditingMessageState, "preconditionInvalidated" | "pendingReconfirmation">
) =>
onEditingMessageChange?.((current) =>
current.id === editMessageId ? { ...current, ...patch } : current
);

// Every outcome and the retry affordance are scoped to THIS edit: once the user cancels it
// or edits another row, a late outcome or a stale toast must not touch the new edit.
const isSameEdit = () => editingMessageIdRef.current === editMessageId;

patchEditing({ preconditionInvalidated: true, pendingReconfirmation: undefined });
setEditRefreshRetry(null);
store
.requestTranscriptRefresh(targetWorkspaceId, {
throughSequence: precondition.rangeStartHistorySequence,
editMessageId,
})
.then((outcome) => {
// The editing state lives in the parent, so its updates apply even if this composer
// instance remounted meanwhile; only this instance's toasts need the mount guard.
switch (outcome.kind) {
case "refreshed":
patchEditing({
preconditionInvalidated: false,
pendingReconfirmation: outcome.candidate,
});
return;
case "target-not-found":
if (!isSameEdit()) return;
// Leave edit mode without restoring the pre-edit draft: the typed text stays in
// the composer as a normal draft.
onCancelEdit?.();
if (isMountedRef.current) {
pushToast({ type: "error", message: EDIT_TARGET_GONE_MESSAGE });
}
return;
case "failed":
// Draft and invalidated state stay; a failure is never read as exhausted history.
if (!isMountedRef.current || !isSameEdit()) return;
setEditRefreshRetry({ editMessageId, precondition });
setToast({
id: Date.now().toString(),
type: "error",
title: "Transcript refresh failed",
message: outcome.error,
solution: (
<button
type="button"
onClick={() => {
// The toast belongs to the failed attempt: clear it before retrying so a
// successful retry does not leave a stale failure (and its retry button)
// behind. It can also outlive the edit; a click then only clears it.
setToast(null);
if (!isSameEdit()) return;
startEditTranscriptRefresh(editMessageId, precondition);
}}
className="text-muted hover:text-accent-text cursor-pointer border-0 bg-transparent p-0 text-[10px] underline transition-colors"
>
{EDIT_RETRY_REFRESH_LABEL}
</button>
),
});
return;
case "superseded":
case "cancelled":
return;
}
})
.catch((error: unknown) => {
if (!isMountedRef.current) return;
console.error("Transcript refresh failed:", error);
setToast(
createErrorToast({
type: "unknown",
raw: error instanceof Error ? error.message : "Transcript refresh failed",
})
);
});
};

// An edit send and a new edit never overlap (#5226): the transcript refuses to start an edit
// until the edit send settles, successfully or not.
const handleSend = async (overrides?: InternalSendOverrides) => {
const onEditSendPendingChange =
variant === "workspace" && editingMessageForUi ? props.onEditSendPendingChange : undefined;
onEditSendPendingChange?.(true);
// #6405: the composer stays on from Enter for a plain message.
const releaseTyping = typingLock.keepTypingOn(input);
await runWithFinally(
() => sendComposerInput(overrides),
() => {
releaseTyping();
onEditSendPendingChange?.(false);
}
);
};
const sendComposerInput = async (overrides?: InternalSendOverrides) => {
// Checked before `canSend` (which also carries the barrier) so a refused Enter on a real
// draft explains itself instead of silently doing nothing. Reads the live store rather
// than the render-time prop so a keybind racing a workspace switch sees current state.
// Slash commands (/clear, /reset, /compact, edits) all enter through here as well.
if (
variant === "workspace" &&
hasSendableDraft &&
!draftBypassesTranscriptBarrier &&
!isTranscriptMutationAllowed(props.workspaceId)
) {
pushToast({ type: "error", message: transcriptBarrierMessage(liveApiRef.current == null) });
return;
}
if (!canSend) {
return;
}
if (!draft.payloadsLoaded) {
// Hydrated drafts carry attachment metadata only; sending now would drop the attachments.
pushToast({ type: "info", message: "Draft attachments are still loading. Try again." });
getDraftStore()
.ensurePayloads(draftScope)
.catch((error: unknown) => console.warn("Failed to load draft attachments:", error));
return;
}

closeSendModeMenu();
// #6405: past the send gate only, so a refused Enter never moves the mark of a send in flight.
getDraftStore().markSendStart(draftScope, input);

const trimmedInput = input.trim();
// #5695: a plain message keeps its first line's indentation (pasted code). Only leading
// blank lines and trailing whitespace go. Slash commands keep the fully trimmed text, so
// their parsing and stored rawCommand do not change.
const messageText = trimmedInput.startsWith("/")
? trimmedInput
: input.replace(/^(?:[^\S\r\n]*\r?\n)+/, "").trimEnd();
const skillDiscovery: SkillResolutionTarget | null =
variant === "creation"
? atMentionProjectPath
? { kind: "project", projectPath: atMentionProjectPath }
: null
: variant === "workspace" && workspaceId
? {
kind: "workspace",
workspaceId,
disableWorkspaceAgents: transferredDraftProjectDiscovery,
}
: null;
// Captured before command resolution so the row the new workspace opens with shows what was
// typed (skill sends are rewritten below) and is stamped with the Send time. Same routing as
// the creation branch below: an initial /goal without attachments sets a goal instead of
// sending a user turn, so it gets no row.
const creationFileParts = variant === "creation" ? chatAttachmentsToFileParts(attachments) : [];
const creationPendingUserMessage: PendingInitialUserMessage | null =
variant === "creation" &&
!(parseCommand(messageText)?.type === "goal-set" && attachments.length === 0)
? {
content: messageText.length > 0 ? messageText : creationNameMessage,
fileParts: creationFileParts.length > 0 ? creationFileParts : undefined,
timestamp: Date.now(),
}
: null;
// Resolving commands/references can include cold MCP server startup and
// prompt discovery; mark the send in flight so a second Enter cannot start
// a duplicate send against the same captured draft.
setSendingCount((c) => c + 1);
const resolutionController = sendResolutionAbortRef.current ?? new AbortController();
sendResolutionAbortRef.current = resolutionController;
const resolutionSignal = resolutionController.signal;
const isSendScopeCurrent = () =>
!resolutionSignal.aborted &&
asyncCommandScopeRef.current.variant === variant &&
asyncCommandScopeRef.current.workspaceId === workspaceId;
const resolved = await runWithFinally(
async () => {
const resolution = await parseCommandWithSkillInvocation({
messageText,
agentSkillDescriptors,
mcpPromptDescriptors,
api: liveApi,
discovery: skillDiscovery,
signal: resolutionSignal,
});
if (!isSendScopeCurrent()) return null;
if (resolution.error) {
pushToast({ type: "error", message: resolution.error });
return null;
}
const inlineReferenceCandidates = extractInlineSkillReferenceCandidates(messageText);
const [skillRefs, mcpPromptRefs] = await Promise.all([
resolveInlineSkillRefsForSend({
messageText,
slashInvocation: resolution.skillInvocation,
agentSkillDescriptors,
api: liveApi,
discovery: skillDiscovery,
candidates: inlineReferenceCandidates,
}),
resolveMcpPromptRefsForSend({
messageText,
slashInvocation: resolution.mcpPromptInvocation,
descriptors: mcpPromptDescriptors,
api: liveApi,
discovery: skillDiscovery,
candidates: inlineReferenceCandidates,
signal: resolutionSignal,
}),
]);
if (!isSendScopeCurrent()) return null;
if (mcpPromptRefs.error) {
pushToast({ type: "error", message: mcpPromptRefs.error });
return null;
}
// Before any command runs, so commands and normal sends both get hydrated notes; inside
// this in-flight window so a second Enter cannot start a duplicate send meanwhile.
const reviewsForSend = await readReviewsForSend();
if (!isSendScopeCurrent()) return null;
return {
reviewsForSend,
parsed: resolution.parsed,
skillInvocation: resolution.skillInvocation,
mcpPromptInvocation: resolution.mcpPromptInvocation,
combinedSkillRefs: skillRefs,
combinedMcpPromptRefs: mcpPromptRefs.refs,
};
},
() => setSendingCount((c) => c - 1)
);
if (!resolved) return;
const {
reviewsForSend,
parsed,
skillInvocation,
mcpPromptInvocation,
combinedSkillRefs,
combinedMcpPromptRefs,
} = resolved;
const inlineRefs: SlashCommandInlineRefs = {
agentSkillRefs: combinedSkillRefs,
mcpPromptRefs: combinedMcpPromptRefs,
};

// The barrier is re-checked here, after the resolution awaits and before any command runs:
// a reconnect can close it meanwhile, and handled commands (/compact, /fork, workflow
// starts, refinement actions) return before the plain-send re-check further down. Same
// bypass rule as the render-time term, evaluated on the RESOLVED command.
const refusal = sendRefusalToast({
parsed,
workspaceVariant: variant === "workspace",
// Only a workspace composer has a transcript (and a workspaceId) to wait for.
transcriptAllowed: variant !== "workspace" || isTranscriptMutationAllowed(props.workspaceId),
offline: liveApiRef.current == null,
attachmentCount: attachments.length,
skillRefs: combinedSkillRefs,
});
if (refusal) {
pushToast(refusal);
return;
}

// Route to creation handler for creation variant
if (variant === "creation") {
// The initial /goal path sets a goal without sending a user message, so
// attachments would be silently dropped. With attachments present, skip
// command processing and send the raw text as a normal message instead.
const goalCommandBypassedForAttachments =
parsed?.type === "goal-set" && attachments.length > 0;
const initialSlashCommand =
parsed?.type === "goal-set" && !goalCommandBypassedForAttachments
? { ...parsed, typedText: messageText }
: undefined;
if (
!initialSlashCommand &&
!goalCommandBypassedForAttachments &&
parsed?.type !== "workflow-run"
) {
const commandHandled = await executeParsedCommand(parsed, input, { inlineRefs });
if (commandHandled) {
return;
}
}

let creationMessageTextForSend =
initialSlashCommand?.type === "goal-set" ? initialSlashCommand.objective : messageText;
let creationOptionsOverride: Partial<SendMessageOptions> | undefined;

if (skillInvocation) {
if (!liveApi) {
pushToast({ type: "error", message: "Not connected to server" });
return;
}

creationMessageTextForSend = skillInvocation.userText;
}

if (combinedSkillRefs.length > 0) {
const baseMetadata = skillInvocation
? buildSkillInvocationMetadata(
messageText,
skillInvocation.descriptor,
skillInvocation.argumentText
)
: undefined;
const muxMetadata = withAgentSkillRefs(baseMetadata, combinedSkillRefs);
if (!muxMetadata) {
throw new Error("Expected skill metadata when skill refs are present");
}

creationOptionsOverride = {
muxMetadata,
// In the creation flow, project-scoped skills may not exist in the new worktree.
// Force project-path discovery for this send so resolution matches suggestions.
...(hasProjectScopedSkillRef(combinedSkillRefs) ? { disableWorkspaceAgents: true } : {}),
};
}

setHasAttemptedCreateSend(true);

if (props.kind !== "scratch") {
const runtimeError = validateCreationRuntime(
creationState.selectedRuntime,
coderState.presets.length
);
if (runtimeError) {
return;
}
}

// Creation variant: simple message send + workspace creation
const creationPendingFiles = getPendingFileAttachments(attachments);
const creationResult = await creationState.handleSend(
creationMessageTextForSend,
creationFileParts.length > 0 ? creationFileParts : undefined,
creationOptionsOverride,
initialSlashCommand,
creationPendingFiles.length > 0 ? creationPendingFiles : undefined,
creationPendingUserMessage ?? undefined
);

if (creationResult.success) {
if (isMountedRef.current) {
setInput("");
setAttachments([]);
// Height is managed by VimTextArea's useLayoutEffect - clear inline style
// to let CSS min-height take over
if (inputRef.current) {
inputRef.current.style.height = "";
}
}
}
return;
}

// Workspace variant: full command handling + message send
if (variant !== "workspace") return; // Type guard

if (
editingMessageForUi?.isBeforeLatestContextBoundary === true &&
overrides?.skipBoundaryEditConfirmation !== true
) {
// Re-enable the old pre-compaction edit flow, but confirm at send time because
// the backend truncates through the context boundary and discards its summary.
setPendingBoundaryEditConfirmation({
...(overrides?.queueDispatchMode ? { queueDispatchMode: overrides.queueDispatchMode } : {}),
...(overrides?.goalInterventionPolicy
? { goalInterventionPolicy: overrides.goalInterventionPolicy }
: {}),
});
return;
}

const runWorkspaceSend = async () => {
const modelOneShot = parsed?.type === "model-oneshot" ? parsed : null;
// Mirror the creation-composer /goal bypass: with attachments present,
// send the raw text as a normal message instead of processing the
// command, which would drop the files. Transferred staging-failure
// drafts (raw /goal text + staged/pending chips) retry through here.
const goalCommandBypassedForAttachments =
parsed?.type === "goal-set" && attachments.length > 0;
const commandHandled =
modelOneShot || goalCommandBypassedForAttachments
? false
: await executeParsedCommand(parsed, input, {
inlineRefs,
goalInterventionPolicy: overrides?.goalInterventionPolicy,
queueDispatchMode: overrides?.queueDispatchMode,
reviews: reviewsForSend,
});
if (commandHandled) {
return;
}

// A normal workspace send supersedes any pending asynchronous slash
// command completion. If that older command fails after this send clears
// the composer, it must not restore stale command text over the newer turn.
asyncCommandTokenRef.current++;

const modelOverride = modelOneShot?.modelString;

// Regular message (or /<model-alias> one-shot override) - send directly via API
const messageTextForSend =
modelOneShot?.message ??
skillInvocation?.userText ??
mcpPromptInvocation?.userText ??
messageText;

if (!liveApi) {
pushToast({ type: "error", message: "Not connected to server" });
return;
}
setSendingCount((c) => c + 1);

// Pending files only reach workspace composers via transferred creation
// drafts; stage them before the notice is built.
let sendAttachments = attachments;
const pendingFilesForSend = getPendingFileAttachments(attachments);
if (pendingFilesForSend.length > 0) {
const stagingOutcome = await stagePendingFiles(
liveApi,
props.workspaceId,
pendingFilesForSend
);
if (stagingOutcome.staged.length > 0) {
sendAttachments = replacePendingFilesWithStaged(attachments, stagingOutcome.staged);
// Swap staged chips into the composer so a later failure or retry
// can't re-stage duplicate copies.
setAttachments(sendAttachments);
}
if (stagingOutcome.failures.length > 0) {
setToast(
createErrorToast({
type: "unknown",
raw: formatPendingFileStagingError(stagingOutcome.failures),
})
);
setSendingCount((c) => c - 1);
return;
}
}

const skillMuxMetadata = skillInvocation
? buildSkillInvocationMetadata(
appendStagedAttachmentNotice(messageText, sendAttachments),
skillInvocation.descriptor,
skillInvocation.argumentText
)
: undefined;
const promptMuxMetadata: MuxMessageMetadata | undefined = mcpPromptInvocation
? {
type: "normal",
// Include the staged-attachment notice so edit restoration and
// compact-and-retry (which prefer rawCommand) keep the attached files.
rawCommand: appendStagedAttachmentNotice(messageText, sendAttachments),
commandPrefix: `/${mcpPromptInvocation.descriptor.commandKey}`,
}
: undefined;

const policyModel = modelOverride ?? baseModel;

// Preflight: if the message includes PDFs, ensure the selected model can accept them.
const pdfAttachments = attachments.filter(isPdfAttachment);
if (pdfAttachments.length > 0) {
const caps = getModelCapabilitiesResolved(policyModel, providersConfig);
if (caps && !caps.supportsPdfInput) {
const pdfCapableKnownModels = Object.values(KNOWN_MODELS)
.map((m) => m.id)
.filter((model) => getModelCapabilities(model)?.supportsPdfInput);
const pdfCapableExamples = pdfCapableKnownModels.slice(0, 3);
const examplesSuffix =
pdfCapableKnownModels.length > pdfCapableExamples.length ? ", and others." : ".";

pushToast({
type: "error",
title: "PDF not supported",
message:
`Model ${policyModel} does not support PDF input.` +
(pdfCapableExamples.length > 0
? ` Try e.g.: ${pdfCapableExamples.join(", ")}${examplesSuffix}`
: " Choose a model with PDF support."),
});
setSendingCount((c) => c - 1);
return;
}

if (caps?.maxPdfSizeMb !== undefined) {
const maxBytes = caps.maxPdfSizeMb * 1024 * 1024;
for (const attachment of pdfAttachments) {
const bytes = estimateBase64DataUrlBytes(attachment.url);
if (bytes !== null && bytes > maxBytes) {
const actualMb = (bytes / (1024 * 1024)).toFixed(1);
pushToast({
type: "error",
title: "PDF too large",
message: `${attachment.filename ?? "PDF"} is ${actualMb}MB, but ${policyModel} allows up to ${caps.maxPdfSizeMb}MB per PDF.`,
});
setSendingCount((c) => c - 1);
return;
}
}
}
}
// What this send took out of the composer, until it settles. A failed send puts it back
// merged with what the composer holds by then, never replacing it: text another window
// typed or a restore put in meanwhile stays (#5226 item 12).
// Null when the send failed before taking anything (nothing to put back) or succeeded.
let taken: { text: string } | null = null;
let releaseTakenDraft: () => void = () => undefined;
const putBackTaken = () => {
if (taken === null) return;
const { text } = taken;
taken = null;
// Put the text back unless the composer holds it again as a whole block: the clear can
// miss (the draft was replaced while the send was prepared), or the text can come back
// after it (another window that still held it saved it, #5501). A match inside a longer
// line is the user's own text, so the sent text comes back beside it: a duplicate
// beats a loss.
setInput((current) =>
hasDraftBlock(current, text) ? current : joinDraftText(text, current)
);
// On an id match the sent copy wins: it may be the staged version of a file that
// another window saved again as pending (#5501), and a retry must not stage it twice.
setAttachments((current) => {
const sentById = new Map(
sendAttachments.map((attachment) => [attachment.id, attachment])
);
const currentIds = new Set(current.map(({ id }) => id));
const missing = sendAttachments.filter(({ id }) => !currentIds.has(id));
const merged = current.map((attachment) => sentById.get(attachment.id) ?? attachment);
const changed = merged.some((attachment, index) => attachment !== current[index]);
return missing.length > 0 || changed ? [...missing, ...merged] : current;
});
};
const preSendReviews = draftReviews;
const editMessageForSend = editingMessageForUi;
const editSessionForSend =
editMessageForSend && editSessionRef.current?.id === editMessageForSend.id
? editSessionRef.current
: null;

const sendPreparedMessage = async () => {
// Prepare file parts if any
const fileParts = chatAttachmentsToFileParts(sendAttachments, { validate: true });

// Review notes as hydrated by readReviewsForSend.
const reviewsData = reviewsForSend.data;
const reviewIdsToCheck = reviewsForSend.ids;

const preparedMessage = prepareMessagePayload({
messageText,
messageTextForSend,
attachments: sendAttachments,
fileParts,
reviews: reviewsData,
reviewIds: reviewIdsToCheck,
editMessageId: editMessageForSend?.id,
// The refreshed candidate is sent exactly as handed back; nothing is re-captured here.
historyEditPrecondition: editMessageForSend
? getEditSendPrecondition(editMessageForSend)
: undefined,
baseMetadata: skillMuxMetadata ?? promptMuxMetadata,
agentSkillRefs: combinedSkillRefs,
mcpPromptRefs: combinedMcpPromptRefs,
sendMessageOptions,
modelOneShot,
policyModel,
transferredDraftProjectDiscovery,
additionalSystemContextHydrated,
additionalSystemContext,
goalInterventionPolicy: overrides?.goalInterventionPolicy,
queueDispatchMode: overrides?.queueDispatchMode,
});
const finalMessageText = preparedMessage.message;
const effectiveModel = preparedMessage.effectiveModel;
// Attach deliberate picks only while the sent values still equal them; the backend
// pins those fields on sub-agents so later reawakenings keep the user's choice.
const intentAgentId =
preparedMessage.options.agentId ?? agentId ?? WORKSPACE_DEFAULTS.agentId;
const aiSelection = getAiSelectionIntentForSendOptions(
props.workspaceId,
intentAgentId,
preparedMessage.options
);
const sendOptions = aiSelection.intent
? { ...preparedMessage.options, aiSelectionIntent: aiSelection.intent }
: preparedMessage.options;
const sentReviewIds = preparedMessage.sentReviewIds;

// The backend reads this model's auto-compaction threshold from persisted user
// preferences when the stream starts, and the slider write reaches config.json
// asynchronously. Wait for the backend to accept that write so a send right after a
// slider change is not ordered ahead of it; a rejected save refuses the send visibly
// and leaves the draft untouched. (Since #4444 a failed disk write rejects too, so
// acceptance also means the preference landed.)
const preferencePersisted = await runWithCatch(
async () => {
await flushUserPreferences();
return true;
},
(error) => {
if (isSendScopeCurrent()) {
setToast(
createErrorToast({
type: "unknown",
raw: error instanceof Error ? error.message : "Settings could not be saved",
})
);
}
return false;
}
);
if (!preferencePersisted || !isSendScopeCurrent()) return;

// Last re-check before anything is cleared or sent: command/skill/MCP resolution and
// the persistence wait above are async, and the transcript can stop being current in
// the meantime (switch, reconnect). Draft, attachments and edit state stay intact; the
// outer `finally` releases sendingCount.
if (!isTranscriptMutationAllowed(props.workspaceId)) {
pushToast({
type: "error",
message: transcriptBarrierMessage(liveApiRef.current == null),
});
return;
}

// Idempotent sends: every send carries an id minted here; a retry reuses it with the same
// request, so the backend never appends it twice. Not covered (they carry no client id; the
// backend mints one): chatCommands.ts sends (/compact and friends) and the creation flow.
const sendId = createSendId();
// An edit keeps today's put-back: its pre-edit draft lives only in memory, so it gets no
// pending-send entry. Every other send keeps its text and attachments in the durable
// draft until the backend answers for its id.
const tracksSend = editMessageForSend == null;
const sendScope = { kind: "workspace" as const, workspaceId: props.workspaceId };
if (tracksSend) {
// The exact request, for retries (also after a reload); file parts are rebuilt from
// the retained attachments, so they are not stored twice.
const {
fileParts: _fileParts,
editMessageId: _editMessageId,
historyEditPrecondition: _historyEditPrecondition,
unfencedEdit: _unfencedEdit,
sendId: _sendId,
...requestOptions
} = sendOptions;
try {
// The one durable draft write before the send: the composer hides what it took,
// and the draft keeps it until the backend answers for the id.
await getDraftStore().beginSend(sendScope, {
sendId,
text: input,
attachments: sendAttachments,
request: { message: finalMessageText, options: requestOptions },
});
} catch (error) {
// Nothing was taken or sent: the draft is as it was.
setToast(
createErrorToast({
type: "unknown",
raw: error instanceof Error ? error.message : "The draft could not be saved",
})
);
return;
}
}

if (editMessageForSend) {
setOptimisticallyDismissedEditId(editMessageForSend.id);
}

// Clear input, images, and hide reviews immediately for responsive UI
// Text/images are restored if send fails; reviews remain "attached" in state
// so they'll reappear naturally on failure (we only call onCheckReviews on success)
// Clear only what this send took: a draft restored meanwhile (an edit completing while
// this send resolved its options) stays in the composer (#5226).
const sentAttachmentIds = new Set([...attachments, ...sendAttachments].map(({ id }) => id));
if (!tracksSend) {
// An edit send has no beginSend, which takes the mark of every other send (#6729).
// Read before the update below: takeSendMark ends the mark.
const take = getDraftStore().takeSendMark(draftScope, input);
setInput((current) => takeSentText(current, input, take));
taken = { text: input };
}
// Likewise for notes: drop the override this send captured, keeping notes an edit's
// completion put into it meanwhile.
setDraftReviews((current) => {
if (current === null || current === preSendReviews) return null;
const remaining = current.filter((review) => !preSendReviews?.includes(review));
return remaining.length > 0 ? remaining : null;
});
if (!tracksSend) {
setAttachments((current) => current.filter(({ id }) => !sentAttachmentIds.has(id)));
}
setHideReviewsDuringSend(true);
// Clear inline height style - VimTextArea's useLayoutEffect will handle sizing
if (inputRef.current) {
inputRef.current.style.height = "";
}
// The draft is out of the composer: typing can resume (#6259).
releaseTakenDraft = typingLock.markDraftTaken(input);

props.onMessageSendStarted?.(overrides?.queueDispatchMode ?? "tool-end");

let result: Awaited<ReturnType<typeof liveApi.workspace.sendMessage>> | undefined;
let thrown: unknown;
try {
result = await liveApi.workspace.sendMessage({
workspaceId: props.workspaceId,
message: finalMessageText,
options: { ...sendOptions, sendId },
});
} catch (error) {
thrown = error;
}
// A failed reply does not mean the backend did not take the message: only the
// backend's answer for the id decides. Never inferred from the transcript text.
let accepted = result?.success === true;
if (tracksSend) {
// Resolves the draft entry too: accepted drops the retained text, not accepted makes it
// visible again, pending (queued or held) keeps it until its row.
const outcome = await getDraftStore()
.settleSend(sendScope, sendId)
.catch((): SendOutcome => "unresolved");
// A lost reply of a send the backend queued or runs is its send all the same. (An Ok
// reply stays a sent message even when the queue was cleared before the lookup: the
// clear restored it with its notes, a queue edit or Stop restore, so the notes this
// send took are checked off as for any queued send; its text comes back through its
// draft entry.)
if (outcome === "accepted" || outcome === "pending") accepted = true;
} else if (!accepted) {
accepted = await isEditSendAccepted(liveApi, props.workspaceId, sendId);
}

if (!accepted) {
if (result === undefined) throw thrown;
assert(!result.success, "a successful send counts as accepted");
// Log error for debugging
console.error("Failed to send message:", result.error);
// Show error using enhanced toast
const failureToast = createErrorToast(result.error);
setToast(failureToast);
// Restore draft on error so user can try again (a tracked send's text comes back
// through its draft entry instead)
setOptimisticallyDismissedEditId(null);
putBackTaken();
setDraftReviews(preSendReviews);
// The rows this edit would delete changed after its evidence was captured. Stay in
// edit mode with the draft, block Send, and re-read the transcript so the user can
// review it and send again explicitly (never automatically).
if (
result.error.type === "history-changed" &&
editMessageForSend &&
sendOptions.historyEditPrecondition
) {
editConflictToastRef.current = {
editMessageId: editMessageForSend.id,
toast: failureToast,
};
startEditTranscriptRefresh(editMessageForSend.id, sendOptions.historyEditPrecondition);
}
} else {
// The backend took the text: nothing to put back.
taken = null;
const conflictToast = editConflictToastRef.current;
if (editMessageForSend && conflictToast?.editMessageId === editMessageForSend.id) {
editConflictToastRef.current = null;
setToast((current) => (current === conflictToast.toast ? null : current));
}
consumeAiSelectionIntent(props.workspaceId, intentAgentId, aiSelection);
// Track telemetry for successful message send
telemetry.messageSent(
props.workspaceId,
effectiveModel,
sendMessageOptions.agentId ?? agentId ?? WORKSPACE_DEFAULTS.agentId,
finalMessageText.length,
runtimeType,
sendMessageOptions.thinkingLevel ?? "off"
);

if (modelOneShot) {
trackCommandUsed("model");
}

// Mark workspace as read after sending a message.
// This prevents the unread indicator from showing when the user
// just interacted with the workspace (their own message bumps recencyTimestamp,
// but since they initiated it, they've "read" the workspace).
updatePersistedState(getWorkspaceLastReadKey(props.workspaceId), Date.now());

if (transferredDraftProjectDiscovery) {
// The transferred creation draft has been sent; later sends use
// normal workspace skill discovery again.
updatePersistedState(getPendingDraftSkillDiscoveryKey(props.workspaceId), undefined);
}

// Mark attached reviews as completed (checked)
if (sentReviewIds.length > 0) {
props.onCheckReviews?.(sentReviewIds);
}
warnIfReviewsUnavailable(reviewsForSend);

// Exit editing mode if we were editing
restorePreEditDraftAfterSend(editSessionForSend);
if (editMessageForSend && props.onCancelEdit && isOpenEditOrNone(editSessionForSend)) {
props.onCancelEdit();
} else if (editMessageForSend) {
setOptimisticallyDismissedEditId(null);
}
props.onMessageSent?.(overrides?.queueDispatchMode ?? "tool-end");
}
};
const restoreDraftOnError = (error: unknown) => {
// Handle unexpected errors
console.error("Unexpected error sending message:", error);
setToast(
createErrorToast({
type: "unknown",
raw: error instanceof Error ? error.message : "Failed to send message",
})
);
// Restore draft on error
setOptimisticallyDismissedEditId(null);
putBackTaken();
setDraftReviews(preSendReviews);
};
await runWithCatchFinally(sendPreparedMessage, restoreDraftOnError, () => {
setSendingCount((c) => c - 1);
releaseTakenDraft();
setHideReviewsDuringSend(false);
});
};
await runWithFinally(runWorkspaceSend, () => {
// /side may have handed focus to another composer while this command completed.
// Keep that handoff instead of pulling typing back into the main chat.
setTimeout(() => {
if (paneHandlesKeyEvent(paneScope, document.activeElement)) inputRef.current?.focus();
}, 0);
});
};

const handleBoundaryEditConfirm = async () => {
const pendingOverrides = pendingBoundaryEditConfirmation;
const pendingEdit = editingMessageForUi;
if (!pendingOverrides || variant !== "workspace" || !pendingEdit) {
setPendingBoundaryEditConfirmation(null);
return;
}

setPendingBoundaryEditConfirmation(null);
await handleSend({ ...pendingOverrides, skipBoundaryEditConfirmation: true });
};

const handleBoundaryEditCancel = () => {
setPendingBoundaryEditConfirmation(null);
};

// Keep the imperative API pointing at the latest send handler. A layout effect (not a
// render-time write, which React Compiler rejects) updates it in the commit's own task.
useLayoutEffect(() => {
handleSendRef.current = handleSend;
});

// Handler for Escape in vim normal mode - cancels edit if editing
const handleEscapeInNormalMode = () => {
if (variant === "workspace" && editingMessageForUi && props.onCancelEdit) {
restorePreEditDraft();
props.onCancelEdit();
inputRef.current?.blur();
}
};

const handleKeyDown = (e: React.KeyboardEvent) => {
// Handle voice input toggle (Ctrl+D / Cmd+D)
if (matchesKeybind(e, KEYBINDS.TOGGLE_VOICE_INPUT) && voiceInput.shouldShowUI) {
e.preventDefault();
if (!voiceInput.isAvailable) {
pushToast({
type: "error",
message: voiceInputUnavailableMessage,
});
return;
}
voiceInput.toggle();
return;
}

// Space on empty input starts voice recording (ignore key repeat from holding)
if (
e.key === " " &&
!e.repeat &&
input.trim() === "" &&
voiceInput.shouldShowUI &&
voiceInput.isAvailable &&
voiceInput.state === "idle"
) {
e.preventDefault();
voiceInput.start();
return;
}

// Cycle models (Ctrl+/)
if (matchesKeybind(e, KEYBINDS.CYCLE_MODEL)) {
e.preventDefault();
cycleToNextModel();
return;
}

// Handle cancel edit (Escape) - workspace only
// In vim mode, escape first goes to normal mode; escapeInNormalMode callback handles cancel
// In non-vim mode, escape directly cancels edit
if (matchesKeybind(e, KEYBINDS.CANCEL_EDIT)) {
if (variant === "workspace" && editingMessageForUi && props.onCancelEdit && !vimEnabled) {
e.preventDefault();
stopKeyboardPropagation(e);
restorePreEditDraft();
props.onCancelEdit();
const isFocused = document.activeElement === inputRef.current;
if (isFocused) {
inputRef.current?.blur();
}
return;
}
}

// Handle up arrow on empty input - edit last user message (workspace only)
if (
variant === "workspace" &&
e.key === "ArrowUp" &&
!editingMessageForUi &&
input.trim() === "" &&
props.onEditLastUserMessage
) {
e.preventDefault();
props.onEditLastUserMessage();
return;
}

// Note: ESC handled by VimTextArea (for mode transitions) and CommandSuggestions (for dismissal)

if (composerSuggestions.isVisible && COMMAND_SUGGESTION_KEYS.includes(e.key)) {
return;
}

const hasOnlyQueuedMessage =
variant === "workspace" &&
!editingMessageForUi &&
props.queuedMessage != null &&
input.trim() === "" &&
attachments.length === 0 &&
reviewPanelItems.length === 0;

// Held-input shortcuts, like the queued ones, apply only from an empty composer (never while
// typing), and always to the oldest held input so the target is deterministic.
const heldInputId = variant === "workspace" ? props.heldInputId : undefined;
const heldAction = matchesKeybind(e, KEYBINDS.SEND_HELD_INPUT)
? "send"
: matchesKeybind(e, KEYBINDS.DISCARD_HELD_INPUT)
? "discard"
: null;
if (
heldAction != null &&
heldInputId != null &&
workspaceIdForComposerClear != null &&
!editingMessageForUi &&
input.trim() === "" &&
attachments.length === 0 &&
reviewPanelItems.length === 0
) {
e.preventDefault();
stopKeyboardPropagation(e);
if (e.repeat) return;
window.dispatchEvent(
createCustomEvent(CUSTOM_EVENTS.HELD_INPUT_ACTION, {
workspaceId: workspaceIdForComposerClear,
heldInputId,
action: heldAction,
})
);
return;
}

// Existing send keybinds edit the queued boundary when the composer itself is empty.
if (hasOnlyQueuedMessage && matchesKeybind(e, KEYBINDS.SEND_QUEUED_MESSAGE_NOW)) {
if (!props.onSendQueuedImmediately || e.repeat) return;
e.preventDefault();
stopKeyboardPropagation(e);
props.onSendQueuedImmediately().catch((error: unknown) => {
props.onQueuedActionError?.(error);
});
return;
}

if (matchesKeybind(e, KEYBINDS.SEND_MESSAGE_AFTER_TURN)) {
e.preventDefault();
if (hasOnlyQueuedMessage && props.onQueuedDispatchModeChange) {
stopKeyboardPropagation(e);
props.onQueuedDispatchModeChange("turn-end").catch((error: unknown) => {
props.onQueuedActionError?.(error);
});
} else {
void handleSend({ queueDispatchMode: "turn-end" });
}
return;
}

if (matchesKeybind(e, KEYBINDS.SEND_MESSAGE)) {
// Mobile keyboards should keep Enter for newlines; sending remains button-driven.
if (isMobileTouch) {
return;
}
if (hasOnlyQueuedMessage && props.onQueuedDispatchModeChange && !e.repeat) {
e.preventDefault();
stopKeyboardPropagation(e);
props.onQueuedDispatchModeChange("tool-end").catch((error: unknown) => {
props.onQueuedActionError?.(error);
});
return;
}
e.preventDefault();
void handleSend();
}
};

const interruptKeybind = vimEnabled
? KEYBINDS.INTERRUPT_STREAM_VIM
: KEYBINDS.INTERRUPT_STREAM_NORMAL;

// Build placeholder text based on current state
const placeholder = (() => {
// Creation view keeps the onboarding prompt; workspace stays concise for the inline hints.
if (variant === "creation") {
return props.kind === "scratch"
? "Describe your goals to start a scratch chat..."
: "Describe your goals to create a workspace...";
}

// Workspace variant placeholders
if (editingMessageForUi) {
if (isMobileTouch) {
return "Edit your message...";
}
const cancelHint = vimEnabled
? `${formatKeybind(KEYBINDS.CANCEL_EDIT)}×2 to cancel`
: `${formatKeybind(KEYBINDS.CANCEL_EDIT)} to cancel`;
return `Edit your message... (${cancelHint}, ${formatKeybind(KEYBINDS.SEND_MESSAGE)} to send)`;
}
if (disabled) {
if (initialStagingLocked) {
return "Sending attached files...";
}
const disabledReason = props.disabledReason;
if (typeof disabledReason === "string" && disabledReason.trim().length > 0) {
return disabledReason;
}
}
if (isCompacting) {
if (isMobileTouch) {
return "Compacting...";
}
return `Compacting... (${formatKeybind(interruptKeybind)} cancel | ${formatKeybind(KEYBINDS.SEND_MESSAGE)} to queue)`;
}

// Tip carousel: rotates the placeholder through a curated list of
// slash-command and capability tips on a wall-clock bucket so switching
// workspaces mid-bucket doesn't reroll the visible tip. See placeholderTips.ts.
//
if (isMobileTouch || props.kind === "scratch") {
return "Type a message...";
}
return getPlaceholderTip();
})();

const activeToast = toast ?? (variant === "creation" ? creationState.toast : null);

// No wrapper needed - parent controls layout for both variants
const Wrapper = React.Fragment;
const wrapperProps = {};

return (
<Wrapper {...wrapperProps}>
{creationState.trustDialog}

{/* Input section - centered card for creation, bottom bar for workspace */}
<div
ref={chatInputSectionRef}
className={cn(
"relative flex flex-col gap-1",
variant === "creation"
? `w-full ${CREATION_COLUMN_MAX_WIDTH_CLASS}`
: // WorkspaceFooterBar owns the bottom safe-area inset.
`bg-surface-primary pb-2 ${CHAT_DOCK_GUTTER_CLASS}`
)}
data-component="ChatInputSection"
data-autofocus-state="done"
>
<div className={cn(variant === "creation" ? "w-full" : chatDockColumnWidthClass)}>
{/* Toasts (overlay) */}
<div className="pointer-events-none absolute right-[15px] bottom-full left-[15px] z-[1000] mb-2 flex flex-col gap-2 [&>*]:pointer-events-auto">
<ConnectionStatusToast wrap={false} />
<ChatInputToast
toast={activeToast}
wrap={false}
onDismiss={() => {
handleToastDismiss();
if (variant === "creation") {
creationState.setToast(null);
}
}}
/>
</div>

{/* Attached reviews preview - show styled blocks with remove/edit buttons */}
{/* Hide during send to avoid duplicate display with the sent message */}
{variant === "workspace" && !hideReviewsDuringSend && (
<AttachedReviewsPanel
reviews={reviewPanelItems}
onDetachAll={
reviewOverrideActive
? () =>
setDraftReviews((prev) => (prev === null || prev.length === 0 ? prev : []))
: props.onDetachAllReviews
}
onDetach={reviewOverrideActive ? removeDraftReview : props.onDetachReview}
onCheck={reviewOverrideActive ? removeDraftReview : props.onCheckReview}
onDelete={reviewOverrideActive ? removeDraftReview : props.onDeleteReview}
onUpdateNote={reviewOverrideActive ? updateDraftReviewNote : props.onUpdateReviewNote}
/>
)}

{/* Creation header controls - shown above textarea for creation variant */}
{creationControlsProps && <CreationControls {...creationControlsProps} />}
{creationDraftNotSaved && (
<div role="alert" className="text-error mb-2 text-xs">
Not saved: {draft.saveError}. Keep this window open.
</div>
)}

{/* Scratch chats have no CreationControls, but mobile users still
need the current scope visible and a way to reach a project's
creation page: on narrow viewports the sidebar auto-collapses
after opening the scratch page from it. */}
{variant === "creation" && props.kind === "scratch" && (
<div className="mb-3 flex items-center" data-component="ScratchProjectGroup">
<CreationProjectSelect
selected={SCRATCH_PROJECT_CONFIG_KEY}
userProjects={userProjects}
onChange={changeCreationProject}
disabled={creationProjectLocked}
/>
</div>
)}

<CommandSuggestions
suggestions={composerSuggestions.suggestions}
onSelectSuggestion={composerSuggestions.select}
onDismiss={composerSuggestions.dismiss}
isVisible={composerSuggestions.isVisible}
ariaLabel={composerSuggestions.ariaLabel}
listId={composerSuggestions.listId}
anchorRef={variant === "creation" ? inputRef : undefined}
highlightQuery={composerSuggestions.highlightQuery}
isFileSuggestion={composerSuggestions.isFileSuggestion}
selectedIndex={composerSuggestions.selectedIndex}
onSelectedIndexChange={composerSuggestions.setSelectedIndex}
/>

{/* Scope the focus border to the textarea so sibling controls do not trigger it. */}
<div
className={cn(
"rounded-md border p-2",
editingMessageForUi
? "bg-editing-mode-alpha border-editing-mode"
: "border-border-light has-[textarea:focus]:border-[var(--composer-focus-border)]"
)}
style={composerSurfaceStyle}
data-component="ChatInputSurface"
>
<div className="relative flex items-end pb-1" data-component="ChatInputControls">
{/* Recording/transcribing overlay - replaces textarea when active */}
{voiceInput.state !== "idle" ? (
<RecordingOverlay
state={voiceInput.state}
agentColor={agentColor}
mediaRecorder={voiceInput.mediaRecorder}
onStop={voiceInput.toggle}
/>
) : (
<>
<VimTextArea
ref={inputRef}
data-escape-interrupts-stream="true"
value={input}
ghostHint={composerSuggestions.ghostHint}
onChange={handleComposerInputChange}
// Write the draft when focus leaves instead of after the debounce; a failure
// keeps the change in the draft store, which retries it.
onBlur={() => {
draft
.flush()
.catch((error: unknown) =>
console.warn("Failed to save the draft:", error)
);
}}
onKeyDown={handleKeyDown}
onPaste={handlePaste}
onKeyUp={composerSuggestions.handleCursorActivity}
onMouseUp={composerSuggestions.handleCursorActivity}
onSelect={composerSuggestions.handleCursorActivity}
onDragOver={handleDragOver}
onDrop={handleDrop}
onEscapeInNormalMode={handleEscapeInNormalMode}
onKeyEdit={sendMarkEdits.onKeyEdit}
suppressKeys={
composerSuggestions.isVisible ? COMMAND_SUGGESTION_KEYS : undefined
}
placeholder={placeholder}
disabled={!editingMessageForUi && (disabled || sendLocksTyping)}
aria-label={editingMessageForUi ? "Edit message" : "Message"}
// No aria-expanded: the textbox role does not allow it (#5951), and a
// textarea cannot take role="combobox" without screen readers treating
// the multi-line composer as a single-line field.
aria-autocomplete="list"
aria-controls={
composerSuggestions.isVisible ? composerSuggestions.listId : undefined
}
// Creation favors prompt space; workspaces keep a one-line floor because the
// user asked for a shorter chat box. Workspaces hide the shortcut hints, so a
// taller floor reserved for them would only be dead space. Long placeholders
// (tips, edit/compacting hints) stay on that one line instead of wrapping into
// a second line the empty one-line box would clip.
className={variant === "creation" ? "min-h-36" : "min-h-9 placeholder:truncate"}
/>
{/* Shortcut hints only show in creation, which has room below the prompt. */}
{variant === "creation" && input.trim() === "" && (
<div className="mobile-hide-shortcut-hints text-muted @container pointer-events-none absolute right-2 bottom-3 left-2 flex flex-nowrap items-center gap-4 overflow-hidden text-[11px] whitespace-nowrap">
<span className="shrink-0">
<span className="font-mono">{formatKeybind(KEYBINDS.FOCUS_CHAT)}</span>
<span> - focus chat</span>
</span>
<span className="shrink-0 [@container(max-width:520px)]:hidden">
<span className="font-mono">{formatKeybind(KEYBINDS.CYCLE_MODEL)}</span>
<span> - change model</span>
</span>
<span className="shrink-0 [@container(max-width:640px)]:hidden">
<span className="font-mono">{formatKeybind(KEYBINDS.CYCLE_AGENT)}</span>
<span> - change agent</span>
</span>
</div>
)}
</>
)}
</div>

<ChatAttachments attachments={attachments} onRemove={handleRemoveAttachment} />

<div className="flex flex-col gap-0.5" data-component="ChatModeToggles">
{/* Editing indicator - workspace only */}
{variant === "workspace" && editingMessageForUi && (
<div className="text-edit-mode text-[11px] font-medium">
{/* Send is disabled while a history-changed refresh is pending or failed;
say why here since the toast can be dismissed — and after a failure keep
the retry here too, so the edit is never stuck once the toast is gone. */}
{editPreconditionInvalidated
? editRefreshRetry?.editMessageId === editingMessageForUi.id
? "Editing message — history changed, transcript refresh failed"
: "Editing message — history changed, refreshing transcript"
: "Editing message"}{" "}
{editPreconditionInvalidated &&
editRefreshRetry?.editMessageId === editingMessageForUi.id && (
<button
type="button"
onClick={() => {
setToast(null);
startEditTranscriptRefresh(
editRefreshRetry.editMessageId,
editRefreshRetry.precondition
);
}}
className="cursor-pointer border-0 bg-transparent p-0 underline"
>
{EDIT_RETRY_REFRESH_LABEL}
</button>
)}{" "}
{/* Escape is the only other way out, and touch screens have no Escape key (its
hint is hidden there): keep a visible Cancel on every viewport. */}
{props.onCancelEdit && (
<button
type="button"
onClick={() => {
restorePreEditDraft();
props.onCancelEdit?.();
}}
className="cursor-pointer border-0 bg-transparent p-0 underline"
>
Cancel
</button>
)}{" "}
<span className="mobile-hide-shortcut-hints">
({formatKeybind(KEYBINDS.CANCEL_EDIT)}
{vimEnabled ? "×2" : ""} to cancel)
</span>
</div>
)}

{/* 320px is a container breakpoint, not a minimum width. The row must shrink to
keep trailing controls inside narrow composers. */}
<div
className="@container flex flex-nowrap items-center gap-1.5"
data-component="ComposerControlRow"
>
<div className="flex min-w-0 flex-1 items-center gap-1.5">
<div
className="min-w-0 [@container(max-width:320px)]:hidden"
data-tutorial="mode-selector"
>
<AgentModePicker
className="min-w-0"
iconOnlyHideClassName={
variant === "workspace"
? COMPOSER_WORKSPACE_ICON_ONLY_HIDE_CLASS
: COMPOSER_ICON_ONLY_HIDE_CLASS
}
onComplete={() => inputRef.current?.focus()}
computerUse={
workspaceId == null
? undefined
: {
...computerUse,
runtimeEligible:
runtimeType === "local" || runtimeType === "worktree",
}
}
/>
</div>

{/* Inset outlines preserve the boundary over hover backgrounds and in forced colors. */}
<div
className={cn(
"outline-border-light flex min-w-0 items-center gap-1.5 rounded-md px-1.5 outline-1 -outline-offset-1",
COMPOSER_CONTROL_HEIGHT_CLASS
)}
data-component="ModelSelectorGroup"
data-tutorial="model-selector"
>
<ModelSelector
ref={modelSelectorRef}
value={baseModel}
onChange={setPreferredModel}
models={models}
onComplete={() => inputRef.current?.focus()}
defaultModel={defaultModel}
onSetDefaultModel={setDefaultModel}
hiddenModels={hiddenModelsForSelector}
onOpenSettings={() => {
// The dropdown's focused input unmounts; hand focus to the composer (as
// onComplete does) so closing settings returns there.
inputRef.current?.focus();
open("models");
}}
className="h-full max-w-[8rem] min-w-0"
autoRouting={
autoModelRoutingEnabled
? {
active: autoModelRoutingActive,
onSelect: () => setAutoModelRoutingActive(true),
}
: undefined
}
tooltipExtraContent={
<>
<strong>Click to edit</strong>
<br />
<strong>{formatKeybind(KEYBINDS.CYCLE_MODEL)}</strong> to cycle models
<br />
<br />
<strong>Abbreviations:</strong>
{MODEL_ABBREVIATION_EXAMPLES.map((ex) => (
<React.Fragment key={ex.abbrev}>
<br />• <code>/model {ex.abbrev}</code> - {ex.displayName}
</React.Fragment>
))}
<br />
<br />
<strong>Full format:</strong>
<br />
<code>/model provider:model-name</code>
<br />
(e.g., <code>/model anthropic:claude-sonnet-4-5</code>)
</>
}
/>
<span className="bg-border-light h-3.5 w-px shrink-0" aria-hidden="true" />

<div
className="flex shrink-0 items-center"
data-component="ThinkingSelectorGroup"
>
<ThinkingSelector
modelString={baseModel}
autoRouting={
autoModelRoutingEnabled
? {
active: autoThinkingLevelActive,
onSelect: () => setAutoThinkingLevelActive(true),
}
: undefined
}
/>
</div>
</div>

{variant === "workspace" && (
<ContextUsageIndicatorButton
data={contextUsageData}
autoCompaction={autoCompactionProps}
idleCompaction={idleCompactionProps}
model={contextDisplayModel}
historyLoaded={isTranscriptCaughtUp}
/>
)}
</div>

<div
className="flex shrink-0 items-center justify-end gap-1"
data-component="ModelControls"
>
{/* Attach and voice sit below the textarea rather than in an absolute overlay so
they can never visually intersect typed or wrapped text. */}
<div
className="flex shrink-0 items-center gap-0"
data-component="InputMethodGroup"
>
<AttachFileButton
onFiles={handleAttachFiles}
disabled={disabled || sendLocksTyping || !!editingMessageForUi}
/>
<VoiceInputButton
state={voiceInput.state}
isAvailable={voiceInput.isAvailable}
shouldShowUI={voiceInput.shouldShowUI}
requiresSecureContext={voiceInput.requiresSecureContext}
onToggle={voiceInput.toggle}
disabled={disabled || sendLocksTyping}
agentColor={agentColor}
/>
</div>

<div ref={sendModeMenuContainerRef} className="relative">
<Tooltip>
<TooltipTrigger asChild>
<Button
type="button"
onClick={() => {
if (suppressSendClickIfLongPress()) {
return;
}

void handleSend();
}}
onContextMenu={openSendModeMenuFromContext}
onTouchStart={sendModeMenuTouchHandlers.onTouchStart}
onTouchEnd={sendModeMenuTouchHandlers.onTouchEnd}
onTouchMove={sendModeMenuTouchHandlers.onTouchMove}
onTouchCancel={sendModeMenuTouchHandlers.onTouchEnd}
disabled={!canSend}
aria-label="Send message"
aria-expanded={canChooseDispatchMode ? isSendModeMenuOpen : undefined}
aria-haspopup={canChooseDispatchMode ? "menu" : undefined}
size="xs"
variant="ghost"
className={cn(
// Keep the filled action compact so it reads as an icon button, not a
// second bordered control competing with the picker groups.
"inline-flex h-7 w-7 items-center justify-center rounded-full p-0 font-medium transition-colors duration-200",
// Pin text colors because the ghost variant otherwise overrides the glyph.
canSend
? "bg-composer-send hover:bg-composer-send text-composer-send-foreground hover:text-composer-send-foreground hover:opacity-90"
: "bg-surface-secondary text-composer-send-foreground",
"[@media(hover:none)_and_(pointer:coarse)]:h-9 [@media(hover:none)_and_(pointer:coarse)]:w-9 [@media(hover:none)_and_(pointer:coarse)]:text-sm"
)}
>
<SendHorizontal className="h-3.5 w-3.5" strokeWidth={2.5} />
</Button>
</TooltipTrigger>
<TooltipContent align="start" className="max-w-80 whitespace-normal">
<strong>Send message ({formatKeybind(KEYBINDS.SEND_MESSAGE)})</strong>
{variant === "workspace" && (
<>
<br />
<br />
<strong>Right-click or long-press for advanced send modes:</strong>
{runningGoalActive && !editingMessageForUi && (
<>
<br />
Manual sends pause the current goal; use Resume to continue it.
</>
)}
{SEND_DISPATCH_MODES.map((entry) => (
<React.Fragment key={entry.mode}>
<br />
{entry.label}: <kbd>{formatKeybind(entry.keybind)}</kbd>
</React.Fragment>
))}
</>
)}
</TooltipContent>
</Tooltip>

{canChooseDispatchMode && isSendModeMenuOpen && (
<div className="bg-separator border-border-light absolute right-0 bottom-full z-[1020] mb-1 min-w-[12.5rem] rounded-md border p-1.5 shadow-md">
{SEND_DISPATCH_MODES.map((entry) => (
<button
key={entry.mode}
type="button"
className="hover:bg-hover focus-visible:bg-hover text-foreground flex w-full items-center justify-between gap-2 rounded-sm px-2.5 py-1 text-left text-xs"
onClick={() => {
closeSendModeMenu();
void handleSend(
entry.mode === "tool-end"
? undefined
: { queueDispatchMode: entry.mode }
);
}}
>
<span className="whitespace-nowrap">{entry.label}</span>
<kbd className="bg-background-secondary text-foreground border-border-medium rounded border px-1.5 py-px font-mono text-[10px] whitespace-nowrap">
{formatKeybind(entry.keybind)}
</kbd>
</button>
))}
</div>
)}
</div>
</div>
</div>
</div>
</div>
</div>
</div>

<ConfirmationModal
isOpen={pendingBoundaryEditConfirmation !== null}
title="Edit Message Before Context Boundary?"
description="Sending this edit will discard the latest compaction or reset summary and every message after the edited one, then continue from the rewritten history."
warning="This action cannot be undone."
confirmLabel="Edit and Send"
onConfirm={handleBoundaryEditConfirm}
onCancel={handleBoundaryEditCancel}
/>

{/* Confirmation modal for destructive commands (currently only /clear). */}
<ConfirmationModal
isOpen={pendingDestructiveCommand}
title="Clear Chat History?"
description="This will remove all messages from the conversation."
warning="This action cannot be undone."
confirmLabel="Clear"
onConfirm={handleDestructiveCommandConfirm}
onCancel={handleDestructiveCommandCancel}
/>
</Wrapper>
);
};

Check warning on line 3775 in src/browser/features/ChatInput/index.tsx

View workflow job for this annotation

GitHub Actions / Quality / CRAP

CRAP crap-tax (warning)

src/browser/features/ChatInput/index.tsx:374-3775 ChatInputInner: touched hotspot, CC 712 unchanged: consider shrinking it

export const ChatInput = React.memo(ChatInputInner);
ChatInput.displayName = "ChatInput";
18 changes: 12 additions & 6 deletions src/browser/features/Settings/Sections/TasksSection.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import { getDefaultModel, useModelsFromSettings } from "@/browser/hooks/useModelsFromSettings";
import { EXPERIMENT_IDS } from "@/common/constants/experiments";
import { useWorkspaceAiSelection } from "@/browser/utils/workspaceAiSettingsSync";
import { resolveInheritedLayerModel } from "@/browser/utils/workspaceModeAi";
import {
getAppConfigStore,
updateUserPreferences,
Expand Down Expand Up @@ -48,7 +49,11 @@
type ThinkingLevel,
} from "@/common/types/thinking";
import { normalizeModelInput } from "@/common/utils/ai/normalizeModelInput";
import { collectDeclaredAncestorLayers } from "@/common/utils/ai/agentAncestorLayers";
import {
aiSettingsBaseOf,
collectDeclaredAncestorLayers,
getAgentAiSettingsBases,
} from "@/common/utils/ai/agentAncestorLayers";
import { CacheTtlSchema } from "@/common/config/schemas/providersConfig";
import type { AnthropicCacheTtl } from "@/common/utils/ai/cacheStrategy";
import { resolveAgentCacheTtl } from "@/common/utils/ai/resolveAgentAiSettings";
Expand Down Expand Up @@ -465,7 +470,7 @@
input.listedAgents.map((agent) => [
agent.id,
{
base: agent.base,
base: aiSettingsBaseOf(agent),
// A resolved agent's aiDefaults merge its bases' frontmatter, which the backend
// ranks below those bases' Settings, so the walk takes only its own layer.
definitionAiDefaults: agent.aiLayers
Expand Down Expand Up @@ -577,877 +582,878 @@
);
}

export function TasksSection() {
const { api } = useAPI();
// The autosave sends only through a live client. Offline it keeps the change pending and says
// so: the reload after the reconnect keeps a pending change, and the autosave sends it then.
const liveApi = useLiveAPI();
const liveApiRef = useRef(liveApi);
useEffect(() => {
liveApiRef.current = liveApi;
}, [liveApi]);
const { selectedWorkspace, pendingNewWorkspaceProject } = useWorkspaceContext();
// Settings opened over a project page has no workspace; list that project's agents so its
// overrides reach the cards (the Prompt cache Inherit label included). Scratch is no project.
const agentsProjectPath =
selectedWorkspace?.projectPath ??
(pendingNewWorkspaceProject !== SCRATCH_PROJECT_CONFIG_KEY
? (pendingNewWorkspaceProject ?? undefined)
: undefined);
const agentsWorkspaceId = selectedWorkspace?.workspaceId;

const agentsScopeRef = useRef({ projectPath: agentsProjectPath, workspaceId: agentsWorkspaceId });
useEffect(() => {
agentsScopeRef.current = { projectPath: agentsProjectPath, workspaceId: agentsWorkspaceId };
}, [agentsProjectPath, agentsWorkspaceId]);

const [taskSettings, setTaskSettings] = useState<TaskSettings>(DEFAULT_TASK_SETTINGS);
const [agentAiDefaults, setAgentAiDefaults] = useState<AgentAiDefaults>({});

const [agents, setAgents] = useState<AgentDefinitionDescriptor[]>([]);
const [enabledAgentIds, setEnabledAgentIds] = useState<string[]>([]);
const [agentsLoaded, setAgentsLoaded] = useState(false);
const [agentsLoadFailed, setAgentsLoadFailed] = useState(false);

const [loaded, setLoaded] = useState(false);
const [loadFailed, setLoadFailed] = useState(false);
const [saveError, setSaveError] = useState<string | null>(null);

const saveTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const savingRef = useRef(false);
const pendingSaveRef = useRef<TasksSectionSavePayload | null>(null);

const { models, hiddenModelsForSelector } = useModelsFromSettings();
const { config: providersConfig } = useProvidersConfig();
const newWorkspaceDefaultAgentId = coerceAgentId(
useUserPreferences((preferences) => preferences.ai?.globalDefaults?.agentId)
);
const portableDesktopEnabled = useExperimentValue(EXPERIMENT_IDS.PORTABLE_DESKTOP);
const autoModelRoutingEnabled = useExperimentValue(EXPERIMENT_IDS.AUTO_MODEL_ROUTING);
// Dream only runs when both flags are on (see memoryConsolidationService);
// mirror that gate for its Settings card.
const memoryEnabled = useExperimentValue(EXPERIMENT_IDS.MEMORY);
const memoryConsolidationFlag = useExperimentValue(EXPERIMENT_IDS.MEMORY_CONSOLIDATION);
const memoryConsolidationEnabled = memoryEnabled && memoryConsolidationFlag;
const statusPageAgentEnabled = useStatusPageAgentEnabled();

// Resolve the workspace's active model so that when a sub-agent's model is
// "Inherit", we show thinking levels for the workspace model (falling back to
// the global default). This mirrors the workspace model resolution chain used when sending messages.
const selectedWorkspaceId = selectedWorkspace?.workspaceId ?? "";
const workspaceModel = useWorkspaceAiSelection(selectedWorkspaceId).model;
const inheritedEffectiveModel = selectedWorkspaceId ? workspaceModel : getDefaultModel();

const lastSyncedTaskSettingsRef = useRef<TaskSettings | null>(null);
const lastSyncedAgentAiDefaultsRef = useRef<AgentAiDefaults | null>(null);
const shownAgentsScopeRef = useRef<string | null>(null);

useEffect(() => {
if (!api) return;

setLoaded(false);
setLoadFailed(false);
setSaveError(null);

void api.config
.getConfig()
.then((cfg) => {
// A reload after a reconnect keeps values the user changed and not yet saved: the
// autosave sends them through the new client once `loaded` is back.
if (pendingSaveRef.current != null || savingRef.current) {
setLoaded(true);
return;
}
const normalizedTaskSettings = normalizeTaskSettings(cfg.taskSettings);
setTaskSettings(normalizedTaskSettings);
const normalizedAgentDefaults = normalizeAgentAiDefaults(cfg.agentAiDefaults);
setAgentAiDefaults(normalizedAgentDefaults);

setLoadFailed(false);
lastSyncedTaskSettingsRef.current = normalizedTaskSettings;
lastSyncedAgentAiDefaultsRef.current = normalizedAgentDefaults;

setLoaded(true);
})
.catch((error: unknown) => {
// A lost connection is no load failure: the reconnect loads again.
if (isConnectionLostError(error)) return;
setSaveError(getErrorMessage(error));
setLoadFailed(true);
setLoaded(true);
});
}, [api]);

useEffect(() => {
if (!api) return;

const projectPath = agentsProjectPath;
const workspaceId = agentsWorkspaceId;
if (!projectPath) {
setAgents([]);
setEnabledAgentIds(FALLBACK_AGENTS.map((agent) => agent.id));
setAgentsLoaded(true);
setAgentsLoadFailed(false);
return;
}

let cancelled = false;
// Only a new scope shows "Loading agents…": a new client (reconnect) reloads the same
// scope behind the shown list.
const scope = JSON.stringify([projectPath, workspaceId]);
if (shownAgentsScopeRef.current !== scope) {
shownAgentsScopeRef.current = scope;
setAgentsLoaded(false);
setAgentsLoadFailed(false);
}

void Promise.all([
api.agents.list({ projectPath, workspaceId }),
api.agents.list({ projectPath, workspaceId, includeDisabled: true }),
])
.then(([enabled, all]) => {
if (cancelled) return;
setAgents(all);
setEnabledAgentIds(enabled.map((agent) => agent.id));
setAgentsLoadFailed(false);
setAgentsLoaded(true);
})
.catch((error: unknown) => {
if (cancelled || isConnectionLostError(error)) return;
setAgents([]);
setEnabledAgentIds(FALLBACK_AGENTS.map((agent) => agent.id));
setAgentsLoadFailed(true);
setAgentsLoaded(true);
});

return () => {
cancelled = true;
};
}, [api, agentsProjectPath, agentsWorkspaceId]);

useEffect(() => {
if (!loaded) return;
if (loadFailed) return;

pendingSaveRef.current = {
taskSettings,
agentAiDefaults,
};
const lastTaskSettings = lastSyncedTaskSettingsRef.current;
const lastAgentDefaults = lastSyncedAgentAiDefaultsRef.current;

if (
lastTaskSettings &&
lastAgentDefaults &&
areTaskSettingsEqual(lastTaskSettings, taskSettings) &&
areAgentAiDefaultsEqual(lastAgentDefaults, agentAiDefaults)
) {
pendingSaveRef.current = null;
clearSaveTimer(saveTimerRef);
return;
}

if (!liveApi) {
// Offline: the change stays pending (the reload after the reconnect keeps it) and the
// autosave sends it once this effect runs with the new client.
clearSaveTimer(saveTimerRef);
setSaveError(OFFLINE_SAVE_MESSAGE);
return;
}

// Readers of the shared store see the edit before the debounced save lands.
getAppConfigStore().updateOptimistically({ agentAiDefaults });

clearSaveTimer(saveTimerRef);

saveTimerRef.current = setTimeout(() => {
const flush = () => {
if (savingRef.current) return;
// The live client now, not this effect's: a retry after a lost connection must not take
// the pending change while offline (it would fail again and lose it).
const client = liveApiRef.current;
if (!client) return;

const payload = pendingSaveRef.current;
if (!payload) return;

pendingSaveRef.current = null;
savingRef.current = true;
void client.config
.saveConfig(payload)
.then(() => {
const previousAgentDefaults = lastSyncedAgentAiDefaultsRef.current;
const agentDefaultsChanged =
!previousAgentDefaults ||
!areAgentAiDefaultsEqual(previousAgentDefaults, payload.agentAiDefaults);

lastSyncedTaskSettingsRef.current = payload.taskSettings;
lastSyncedAgentAiDefaultsRef.current = payload.agentAiDefaults;
setSaveError(null);

if (agentDefaultsChanged) {
window.dispatchEvent(createCustomEvent(CUSTOM_EVENTS.AGENTS_REFRESH_REQUESTED));

const { projectPath, workspaceId } = agentsScopeRef.current;
if (!projectPath) {
return;
}

// Refresh in the background so enablement inheritance stays accurate after saving
// defaults, but keep the existing list rendered to avoid a "Loading agents…" flash
// while the user tweaks values.
setAgentsLoadFailed(false);
void Promise.all([
client.agents.list({ projectPath, workspaceId }),
client.agents.list({ projectPath, workspaceId, includeDisabled: true }),
])
.then(([enabled, all]) => {
setAgents(all);
setEnabledAgentIds(enabled.map((agent) => agent.id));
setAgentsLoadFailed(false);
setAgentsLoaded(true);
})
.catch(() => {
setAgents([]);
setEnabledAgentIds(FALLBACK_AGENTS.map((agent) => agent.id));
setAgentsLoadFailed(true);
setAgentsLoaded(true);
});
}
})
.catch((error: unknown) => {
setSaveError(getErrorMessage(error));
})
.finally(() => {
savingRef.current = false;
flush();
});
};

flush();
}, 400);

return () => {
clearSaveTimer(saveTimerRef);
};
}, [liveApi, agentAiDefaults, loaded, loadFailed, taskSettings]);

usePendingSaveFlush({
api: loaded && !loadFailed ? api : null,
saveTimerRef,
savingRef,
pendingSaveRef,
});

// TaskLimitInput decides when a typed value is ready (#6384); this clamps and saves it.
const setMaxParallelAgentTasks = (value: number) => {
setTaskSettings((prev) => normalizeTaskSettings({ ...prev, maxParallelAgentTasks: value }));
};

// TaskLimitInput decides when a typed value is ready (#6384); this clamps and saves it.
const setMaxTaskNestingDepth = (value: number) => {
setTaskSettings((prev) => normalizeTaskSettings({ ...prev, maxTaskNestingDepth: value }));
};

const setProposePlanImplementReplacesChatHistory = (value: boolean) => {
setTaskSettings((prev) =>
normalizeTaskSettings({ ...prev, proposePlanImplementReplacesChatHistory: value })
);
};

const setNewWorkspaceDefaultAgentId = (agentId: string) => {
updateUserPreferences({ ai: { globalDefaults: { agentId: coerceAgentId(agentId) } } });
};

const setAgentModel = (agentId: string, value: string) => {
setAgentAiDefaults((prev) =>
updateAgentDefaultEntry(prev, agentId, (updated) => {
// Any non-Auto model selection exits Auto.
delete updated.autoModelRouting;
if (value === INHERIT || value.trim().length === 0) {
delete updated.modelString;
} else {
updated.modelString = value;
}
})
);
};

const setAgentThinking = (agentId: string, value: string) => {
setAgentAiDefaults((prev) =>
updateAgentDefaultEntry(prev, agentId, (updated) => {
delete updated.autoThinkingLevel;
if (value === INHERIT) {
// The Inherit row resets the whole reasoning config: a retained
// reasoning override would be invisible (explicit "standard" renders
// identically to absent) with no other way to remove it.
delete updated.thinkingLevel;
delete updated.reasoningMode;
return;
}

updated.thinkingLevel = value as ThinkingLevel;
})
);
};

// Selecting Auto keeps any concrete value as the routing fallback.
const setAgentAutoRouting = (agentId: string, flag: "autoModelRouting" | "autoThinkingLevel") => {
setAgentAiDefaults((prev) =>
updateAgentDefaultEntry(prev, agentId, (updated) => {
updated[flag] = true;
})
);
};

// Unknown IDs may be UI agents defined elsewhere, so keep stored Auto flags clearable.
// Delegated and internal agents never route prompts.
const getAutoRoutingProps = (
agentId: string,
entry: AgentAiDefaultsEntry | undefined
): Pick<AiDefaultsControlsProps, "modelAutoRouting" | "thinkingAutoRouting"> =>
autoModelRoutingEnabled
? {
modelAutoRouting: {
active: entry?.autoModelRouting === true,
onSelect: () => setAgentAutoRouting(agentId, "autoModelRouting"),
},
thinkingAutoRouting: {
active: entry?.autoThinkingLevel === true,
onSelect: () => setAgentAutoRouting(agentId, "autoThinkingLevel"),
},
}
: {};

// Mirrors resolveAgentAiSettings' field-wise base-chain walk (ACP
// resolution): agents without their own default inherit each field from the
// closest ancestor that sets it, so the card must display and gate against
// the same inherited model/mode the backend resolves.
const resolveBaseChainDefaults = (
agentId: string
): { modelString?: string; reasoningMode?: OpenAIReasoningMode } => {
const agentsById = new Map(listedAgents.map((agent) => [agent.id, agent]));
const aiSettingsBases = getAgentAiSettingsBases(listedAgents);
const visited = new Set<string>([agentId]);
let cursor = agentId;
let modelString: string | undefined;
let reasoningMode: OpenAIReasoningMode | undefined;
while (modelString === undefined || reasoningMode === undefined) {
const base = agentsById.get(cursor)?.base ?? (cursor === "plan" ? "plan" : "exec");
const base = aiSettingsBases.get(cursor) ?? (cursor === "plan" ? "plan" : "exec");
Comment thread
ThomasK33 marked this conversation as resolved.
Resolved
if (base === cursor || visited.has(base)) {
break;
}
const inherited = agentAiDefaults[base];
modelString ??= inherited?.modelString;
reasoningMode ??= inherited?.reasoningMode;
visited.add(base);
cursor = base;
}
return { modelString, reasoningMode };
};

const baseChainSuppliesNonStandardMode = (agentId: string): boolean => {
const inherited = resolveBaseChainDefaults(agentId).reasoningMode;
return inherited !== undefined && inherited !== "standard";
};

// Definitions may pin ai.model (possibly an alias like "sonnet"); ACP/task
// resolution slots it below Settings overrides and above the ambient
// fallback (resolveAgentAiSettings), so display gating must match.
const resolveDefinitionModel = (agent: AgentDefinitionDescriptor): string | undefined =>
normalizeModelInput(agent.aiDefaults?.model).model ?? undefined;

const setAgentReasoningMode = (agentId: string, mode: OpenAIReasoningMode) => {
// "standard" is the wire default; keep entries sparse by only persisting
// non-standard modes, unless a base agent supplies one, where deleting the
// override would silently fall back to it.
const inheritsNonStandard = baseChainSuppliesNonStandardMode(agentId);
setAgentAiDefaults((prev) =>
updateAgentDefaultEntry(prev, agentId, (updated) => {
if (mode !== "standard") {
updated.reasoningMode = mode;
} else if (inheritsNonStandard) {
updated.reasoningMode = "standard";
} else {
delete updated.reasoningMode;
}
})
);
};

const setSubagentModel = (agentId: string, value: string) => {
setAgentAiDefaults((prev) =>
updateAgentSubagentProfile(prev, agentId, (profile) => {
if (value === INHERIT || value.trim().length === 0) {
delete profile.modelString;
} else {
profile.modelString = value;
}
})
);
};

const setSubagentThinking = (agentId: string, value: string) => {
setAgentAiDefaults((prev) =>
updateAgentSubagentProfile(prev, agentId, (profile) => {
if (value === INHERIT) {
// Clear the reasoning override too (same rationale as setAgentThinking).
delete profile.thinkingLevel;
delete profile.reasoningMode;
return;
}

profile.thinkingLevel = value as ThinkingLevel;
})
);
};

const setSubagentReasoningMode = (agentId: string, mode: OpenAIReasoningMode) => {
// The calling chat is unknown here: Standard must remain explicit even if
// global Exec is Standard, or a Pro calling chat would override the choice.
setAgentAiDefaults((prev) =>
updateAgentSubagentProfile(prev, agentId, (profile) => {
profile.reasoningMode = mode;
})
);
};

const setAgentEnabled = (agentId: string, value: boolean) => {
setAgentAiDefaults((prev) =>
updateAgentDefaultEntry(prev, agentId, (updated) => {
updated.enabled = value;
})
);
};

const getCacheTtlProps = (agentId: string, definition: AgentDefinitionDescriptor | undefined) =>
buildPromptCacheTtlProps({
agentId,
definition,
listedAgents,
agentAiDefaults,
providersConfig,
onChange: (value) => setAgentAiDefaults((prev) => withAgentCacheTtl(prev, agentId, value)),
});

const resetAgentEnabled = (agentId: string) => {
setAgentAiDefaults((prev) =>
updateAgentDefaultEntry(prev, agentId, (updated) => {
delete updated.enabled;
})
);
};

const listedAgents = agents.length > 0 ? agents : FALLBACK_AGENTS;
const enabledAgentIdSet = new Set(enabledAgentIds);

const { uiAgents, subagents, internalAgents, unknownAgentIds } = useMemo(
() =>
deriveTasksSectionAgentGroups({
listedAgents,
agentAiDefaults,
portableDesktopEnabled,
memoryConsolidationEnabled,
statusPageAgentEnabled,
}),
[
agentAiDefaults,
listedAgents,
portableDesktopEnabled,
memoryConsolidationEnabled,
statusPageAgentEnabled,
]
);
const execSubagentAgent = listedAgents.find(
(agent) => agent.id === "exec" && agent.subagentRunnable && agent.uiSelectable
);

const newWorkspaceDefaultAgentOptions = useMemo(() => {
const options = uiAgents.map((agent) => ({
id: agent.id,
label: agent.name,
}));

if (!options.some((option) => option.id === newWorkspaceDefaultAgentId)) {
options.unshift({
id: newWorkspaceDefaultAgentId,
label: `${newWorkspaceDefaultAgentId} (unavailable)`,
});
}

return options;
}, [newWorkspaceDefaultAgentId, uiAgents]);

const renderAgentDefaults = (agent: AgentDefinitionDescriptor) => {
const entry = agentAiDefaults[agent.id];
const modelValue = entry?.modelString ?? INHERIT;
const thinkingValue = entry?.thinkingLevel ?? INHERIT;
const enabledOverride = entry?.enabled;

const enablementLocked =
agent.id === "exec" || agent.id === "plan" || agent.id === "compact" || agent.id === "mux";

const enabledValue = enablementLocked
? true
: typeof enabledOverride === "boolean"
? enabledOverride
: enabledAgentIdSet.has(agent.id);

const enablementTitle = enablementLocked
? "Core agent. Can't be disabled."
: enabledOverride === undefined
? enabledValue
? "Enabled by agent definition."
: "Disabled by agent definition."
: enabledOverride
? "Enabled (local override)."
: "Disabled (local override).";

const enablementHint =
!enablementLocked && enabledOverride === undefined && !enabledValue
? "Disabled by default"
: null;
// When model is "Inherit", resolve the effective model so the dropdown
// shows the correct thinking levels (e.g. "max" for Opus 4.6, not "xhigh")
// and Pro gating matches ACP resolution: the agent's own definition model
// precedes ancestor configuration (resolveAgentAiSettings tier order), and
// a base-chain model wins over the ambient default (otherwise an agent
// inheriting GPT-5.6+pro from its base would hide the Pro toggle whenever
// the ambient model isn't pro-capable).
const inheritedDefaults = resolveBaseChainDefaults(agent.id);
const effectiveModel =
modelValue !== INHERIT
? modelValue
: (resolveDefinitionModel(agent) ??
inheritedDefaults.modelString ??
: ((agent.aiLayers
? resolveInheritedLayerModel(agent.id, agent.aiLayers, agentAiDefaults)
: (resolveDefinitionModel(agent) ?? inheritedDefaults.modelString)) ??
inheritedEffectiveModel);

const agentDefinitionPath = getAgentDefinitionPath(agent);
const scopeNode = agentDefinitionPath ? (
<Tooltip>
<TooltipTrigger asChild>
<button
type="button"
className="hover:text-foreground cursor-copy bg-transparent p-0 underline decoration-dotted underline-offset-2"
onClick={(e) => {
e.stopPropagation();
void copyToClipboard(agentDefinitionPath);
}}
>
{agent.scope}
</button>
</TooltipTrigger>
<TooltipContent align="start" className="max-w-80 whitespace-normal">
<div className="font-medium">Agent file</div>
<div className="mt-1">
<code>{agentDefinitionPath}</code>
</div>
<div className="text-muted mt-2 text-xs">Click to copy</div>
</TooltipContent>
</Tooltip>
) : (
<span>{agent.scope}</span>
);

return (
<div
key={agent.id}
className="border-border-medium bg-background-secondary rounded-md border p-3"
>
<div className="flex items-start justify-between gap-3">
<div className="min-w-0 flex-1">
<div className="text-foreground text-sm font-medium">{agent.name}</div>
<div className="text-muted text-xs">
{agent.id} • {scopeNode} • {renderPolicySummary(agent)}
{agent.uiSelectable && agent.subagentRunnable ? (
<>
{" "}
•{" "}
<Tooltip>
<TooltipTrigger asChild>
<span className="cursor-help underline decoration-dotted underline-offset-2">
sub-agent
</span>
</TooltipTrigger>
<TooltipContent align="start" className="max-w-80 whitespace-normal">
Can be invoked as a sub-agent.
</TooltipContent>
</Tooltip>
</>
) : null}
</div>

{agent.description ? (
<div className="text-muted mt-1 text-xs">{agent.description}</div>
) : null}
</div>

<div className="flex shrink-0 flex-col items-end gap-2">
<div className="flex items-center gap-3">
{enablementHint ? <div className="text-muted text-xs">{enablementHint}</div> : null}
<Tooltip>
<TooltipTrigger asChild>
<div className="flex items-center gap-2">
<div className="text-muted text-xs">Enabled</div>
<Switch
checked={enabledValue}
disabled={enablementLocked}
onCheckedChange={(checked) => setAgentEnabled(agent.id, checked)}
aria-label={`Toggle ${agent.id} enabled`}
/>
</div>
</TooltipTrigger>
<TooltipContent>{enablementTitle}</TooltipContent>
</Tooltip>
{enabledOverride !== undefined ? (
<Button
type="button"
variant="ghost"
size="sm"
className="px-2"
onClick={() => resetAgentEnabled(agent.id)}
>
Reset
</Button>
) : null}
</div>
</div>
</div>

<AiDefaultsControls
modelValue={modelValue}
thinkingValue={thinkingValue}
reasoningModeValue={entry?.reasoningMode ?? inheritedDefaults.reasoningMode ?? "standard"}
allowReasoningModes={!HEADLESS_REASONING_AGENT_IDS.has(agent.id)}
showReasoning={!NO_REASONING_AGENT_IDS.has(agent.id)}
effectiveModel={effectiveModel}
models={models}
hiddenModelsForSelector={hiddenModelsForSelector}
{...(agent.uiSelectable ? getAutoRoutingProps(agent.id, entry) : {})}
cacheTtl={getCacheTtlProps(agent.id, agent)}
onModelChange={(value) => setAgentModel(agent.id, value)}
onThinkingChange={(value) => setAgentThinking(agent.id, value)}
onReasoningModeChange={(mode) => setAgentReasoningMode(agent.id, mode)}
/>
</div>
);
};

const renderExecSubagentDefaults = (agent: AgentDefinitionDescriptor) => {
const entry = agentAiDefaults.exec?.subagent;
const modelValue = entry?.modelString ?? INHERIT;
const thinkingValue = entry?.thinkingLevel ?? INHERIT;

return (
<div
key="exec-subagent"
role="group"
aria-label="Exec defaults"
className="border-border-medium bg-background-secondary rounded-md border p-3"
>
<div className="min-w-0 flex-1">
<div className="text-foreground text-sm font-medium">Exec</div>
<div className="text-muted text-xs">
{agent.id} • {agent.scope} • {renderPolicySummary(agent)}
</div>
<div className="text-muted mt-1 text-xs">
Unset fields use the calling chat’s Exec settings at task creation, falling back to UI
Exec defaults when no chat selection exists. Model capabilities are enforced at launch.
Enabled settings stay shared with UI Exec.
</div>
</div>

<AiDefaultsControls
modelValue={modelValue}
thinkingValue={thinkingValue}
reasoningModeValue={entry?.reasoningMode ?? "standard"}
reasoningModeInherited={entry?.reasoningMode === undefined}
modelCapabilitiesDeferred={entry?.modelString === undefined}
effectiveModel={entry?.modelString}
models={models}
hiddenModelsForSelector={hiddenModelsForSelector}
inheritLabel="Use calling chat’s Exec"
showThinkingResetButton
onModelChange={(value) => setSubagentModel("exec", value)}
onThinkingChange={(value) => setSubagentThinking("exec", value)}
onReasoningModeChange={(mode) => setSubagentReasoningMode("exec", mode)}
/>
</div>
);
};

const renderUnknownAgentDefaults = (agentId: string) => {
const entry = agentAiDefaults[agentId];
const modelValue = entry?.modelString ?? INHERIT;
const thinkingValue = entry?.thinkingLevel ?? INHERIT;
// Base-chain model wins over the ambient default (see renderAgentDefaults).
const inheritedDefaults = resolveBaseChainDefaults(agentId);
const effectiveModel =
modelValue !== INHERIT
? modelValue
: (inheritedDefaults.modelString ?? inheritedEffectiveModel);

return (
<div
key={agentId}
className="border-border-medium bg-background-secondary rounded-md border p-3"
>
<div className="flex items-start justify-between gap-3">
<div>
<div className="text-foreground text-sm font-medium">{agentId}</div>
<div className="text-muted text-xs">Not discovered in the current workspace</div>
</div>
</div>

<AiDefaultsControls
modelValue={modelValue}
thinkingValue={thinkingValue}
reasoningModeValue={entry?.reasoningMode ?? inheritedDefaults.reasoningMode ?? "standard"}
effectiveModel={effectiveModel}
models={models}
hiddenModelsForSelector={hiddenModelsForSelector}
{...getAutoRoutingProps(agentId, entry)}
cacheTtl={getCacheTtlProps(agentId, undefined)}
onModelChange={(value) => setAgentModel(agentId, value)}
onThinkingChange={(value) => setAgentThinking(agentId, value)}
onReasoningModeChange={(mode) => setAgentReasoningMode(agentId, mode)}
/>
</div>
);
};

return (
// Offline every control is disabled: an edit kept only in this section's state is lost when
// the user leaves the section before the reconnect. Until a load answers, too: the autosave
// does not track an edit made then, so the answer would replace it.
<fieldset disabled={areControlsLocked(liveApi == null, loaded)} className="min-w-0 space-y-6">
<div>
<h3 className="text-foreground mb-4 text-sm font-medium">Task Settings</h3>
<div className="space-y-4">
<div className="flex items-center justify-between gap-4">
<div className="flex-1">
<div className="text-foreground text-sm">Default new-workspace agent</div>
<div className="text-muted text-xs">New chats start with this agent.</div>
</div>
<Select
value={newWorkspaceDefaultAgentId}
onValueChange={setNewWorkspaceDefaultAgentId}
>
<SelectTrigger className="border-border-medium bg-background-secondary h-9 w-56">
<SelectValue placeholder="Select agent" />
</SelectTrigger>
<SelectContent>
{newWorkspaceDefaultAgentOptions.map((option) => (
<SelectItem key={option.id} value={option.id}>
{option.label}
</SelectItem>
))}
</SelectContent>
</Select>
</div>

<div className="flex items-center justify-between gap-4">
<div className="flex-1">
<div className="text-foreground text-sm">Max Parallel Agent Tasks</div>
<div className="text-muted text-xs">
Default {TASK_SETTINGS_LIMITS.maxParallelAgentTasks.default}, range{" "}
{TASK_SETTINGS_LIMITS.maxParallelAgentTasks.min}–
{TASK_SETTINGS_LIMITS.maxParallelAgentTasks.max}
</div>
</div>
<TaskLimitInput
label="Max Parallel Agent Tasks"
value={taskSettings.maxParallelAgentTasks}
min={TASK_SETTINGS_LIMITS.maxParallelAgentTasks.min}
max={TASK_SETTINGS_LIMITS.maxParallelAgentTasks.max}
onCommit={setMaxParallelAgentTasks}
/>
</div>

<div className="flex items-center justify-between gap-4">
<div className="flex-1">
<div className="text-foreground text-sm">Max Task Nesting Depth</div>
<div className="text-muted text-xs">
Default {TASK_SETTINGS_LIMITS.maxTaskNestingDepth.default}, range{" "}
{TASK_SETTINGS_LIMITS.maxTaskNestingDepth.min}–
{TASK_SETTINGS_LIMITS.maxTaskNestingDepth.max}
</div>
</div>
<TaskLimitInput
label="Max Task Nesting Depth"
value={taskSettings.maxTaskNestingDepth}
min={TASK_SETTINGS_LIMITS.maxTaskNestingDepth.min}
max={TASK_SETTINGS_LIMITS.maxTaskNestingDepth.max}
onCommit={setMaxTaskNestingDepth}
/>
</div>

<div className="flex items-center justify-between gap-4">
<div className="flex-1">
<div className="text-foreground text-sm">
Plan: Implement replaces conversation with plan
</div>
<div className="text-muted text-xs">
When enabled, clicking Implement on a plan proposal clears previous messages and
shows the plan before switching to Exec.
</div>
</div>
<Switch
checked={taskSettings.proposePlanImplementReplacesChatHistory ?? false}
onCheckedChange={setProposePlanImplementReplacesChatHistory}
aria-label="Toggle plan Implement replaces conversation with plan"
/>
</div>
</div>

{saveError ? <div className="text-danger-light mt-4 text-xs">{saveError}</div> : null}
</div>

<AgentResourceLimitsSettings />

<div>
<h3 className="text-foreground mb-1 text-sm font-medium">Agent Defaults</h3>
<div className="text-muted text-xs">
Defaults apply globally. Changing model/reasoning in a workspace creates a workspace
override.
</div>
{agentsLoadFailed ? (
<div className="text-danger-light mt-3 text-xs">
Failed to load agent definitions for this workspace.
</div>
) : null}
{!agentsLoaded ? <div className="text-muted mt-3 text-xs">Loading agents…</div> : null}
</div>

{uiAgents.length > 0 ? (
<div>
<h4 className="text-foreground mb-3 text-sm font-medium">UI agents</h4>
<div className="space-y-4">{uiAgents.map(renderAgentDefaults)}</div>
</div>
) : null}

{subagents.length > 0 || execSubagentAgent ? (
<div>
<h4 className="text-foreground mb-3 text-sm font-medium">Sub-agents</h4>
<div className="space-y-4">
{execSubagentAgent ? renderExecSubagentDefaults(execSubagentAgent) : null}
{subagents.map(renderAgentDefaults)}
</div>
</div>
) : null}

{internalAgents.length > 0 ? (
<div>
<h4 className="text-foreground mb-3 text-sm font-medium">Internal</h4>
<div className="space-y-4">{internalAgents.map(renderAgentDefaults)}</div>
</div>
) : null}

{unknownAgentIds.length > 0 ? (
<div>
<h4 className="text-foreground mb-3 text-sm font-medium">Unknown agents</h4>
<div className="space-y-4">{unknownAgentIds.map(renderUnknownAgentDefaults)}</div>
</div>
) : null}
</fieldset>
);
}

Check warning on line 1459 in src/browser/features/Settings/Sections/TasksSection.tsx

View workflow job for this annotation

GitHub Actions / Quality / CRAP

CRAP crap-tax (warning)

src/browser/features/Settings/Sections/TasksSection.tsx:585-1459 TasksSection: touched hotspot, CC 123 unchanged: consider shrinking it
33 changes: 33 additions & 0 deletions src/browser/features/Settings/Sections/TasksSection.ui.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -754,6 +754,39 @@ describe("TasksSection Exec subagent defaults", () => {
expect(card.querySelector('[data-component="ProModeToggle"]')).not.toBeNull();
});

test("gates Pro on the settings base's model, not a base pin the settings base replaced", async () => {
// A Cursor `model: fast` agent on Exec, where a project exec.md pins a pro-capable model. A
// run resolves [ci-watcher, explore, exec], so Explore's Settings model outranks that pin,
// while the base-merged aiDefaults still carry it.
const view = renderTasksSection({
agents: [
{
id: "ci-watcher",
scope: "global",
name: "CI Watcher",
uiSelectable: false,
subagentRunnable: true,
base: "exec",
aiSettingsBase: "explore",
aiDefaults: { model: "openai:gpt-6-luna", settingsBase: "explore" },
aiLayers: {
ancestors: [
{ agentId: "explore", definitionAiDefaults: { cacheTtl: "5m" } },
{ agentId: "exec", definitionAiDefaults: { model: "openai:gpt-6-luna" } },
],
},
},
],
agentAiDefaults: { explore: { modelString: "anthropic:foo" } },
});

await view.findByText("CI Watcher");
const card = getAgentCardByName(view, "CI Watcher");
fireEvent.click(within(card).getByRole("button", { name: "Reasoning" }));
expect(within(card).getByRole("listbox", { name: "Reasoning effort" })).toBeTruthy();
expect(card.querySelector('[data-component="ProModeToggle"]')).toBeNull();
});

test("hides the Pro mode toggle on the Name Workspace card even for pro-capable models", async () => {
// Name generation runs raw streamText (workspaceTitleGenerator) and never
// applies reasoningMode, same headless class as Dream.
Expand Down
9 changes: 3 additions & 6 deletions src/browser/hooks/useSendMessageOptions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { EXPERIMENT_IDS } from "@/common/constants/experiments";
import { useAutoRouting, useWorkspaceAiSelection } from "@/browser/utils/workspaceAiSettingsSync";
import { setAutoRoutingChoice } from "@/browser/utils/modelChange";
import type { AutoRoutingDimension } from "@/browser/utils/aiSelectionIntent";
import { getAgentAiSettingsBases } from "@/common/utils/ai/agentAncestorLayers";

/**
* Extended send options that includes both the canonical model used for backend routing
Expand All @@ -26,11 +27,7 @@ export function useAutoRoutingSelection(
): [active: boolean, setActive: (active: boolean) => void] {
const experimentEnabled = useExperimentValue(EXPERIMENT_IDS.AUTO_MODEL_ROUTING);
const agents = useOptionalAgent()?.agents ?? [];
const active = useAutoRouting(
workspaceId,
dimension,
new Map(agents.map((agent) => [agent.id, agent.base]))
);
const active = useAutoRouting(workspaceId, dimension, getAgentAiSettingsBases(agents));
return [
experimentEnabled && active,
(next) => setAutoRoutingChoice(workspaceId, dimension, next),
Expand All @@ -50,7 +47,7 @@ export function useSendMessageOptions(workspaceId: string): SendMessageOptionsWi
const { model: baseModel, serviceTier } = useWorkspaceAiSelection(
workspaceId,
agentId,
new Map(agents.map((agent) => [agent.id, agent.base]))
getAgentAiSettingsBases(agents)
);

const [autoModelRouting] = useAutoRoutingSelection(workspaceId, "model");
Expand Down
8 changes: 6 additions & 2 deletions src/browser/utils/aiSelectionIntent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,10 @@ import assert from "@/common/utils/assert";
import { WORKSPACE_DEFAULTS } from "@/constants/workspaceDefaults";
import { getUserPreferences } from "@/browser/stores/AppConfigStore";
import { getCreationDraftStore } from "@/browser/stores/CreationDraftStore";
import {
getAgentAiSettingsBases,
type ListedAgentAiAncestry,
} from "@/common/utils/ai/agentAncestorLayers";
import { parseCreationDraftScopeId } from "@/common/constants/storage";
import { CreationDraftSchema } from "@/common/orpc/schemas/drafts";

Expand Down Expand Up @@ -144,10 +148,10 @@ function getSavedRevision(workspaceId: string): number {
*/
export function setAgentBases(
scopeId: string,
agents: ReadonlyArray<{ id: string; base?: string; scope?: AgentDefinitionScope }>
agents: ReadonlyArray<ListedAgentAiAncestry & { scope?: AgentDefinitionScope }>
): void {
agentScopesByScope.set(scopeId, new Map(agents.map((agent) => [agent.id, agent.scope])));
const bases = new Map(agents.map((agent) => [agent.id, agent.base]));
const bases = getAgentAiSettingsBases(agents);
const previous = agentBasesByScope.get(scopeId);
if (previous != null && JSON.stringify([...previous]) === JSON.stringify([...bases])) return;
agentBasesByScope.set(scopeId, bases);
Expand Down
12 changes: 10 additions & 2 deletions src/browser/utils/workspaceAiSettingsSync.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,8 @@ interface WorkspaceAiSelectionInput {
defaultModel: string;
agentAiDefaults: AgentAiDefaults;
agentBaseById?: ReadonlyMap<string, string | undefined>;
/** Hooks pass the AI-selection store version (see useAutoRouting). */
selectionVersion?: number;
}

/**
Expand Down Expand Up @@ -152,7 +154,7 @@ export function useWorkspaceAiSelection(
agentId?: string,
agentBaseById?: ReadonlyMap<string, string | undefined>
): WorkspaceAiSelection {
useSyncExternalStore(subscribeAiSelection, getAiSelectionVersion);
const selectionVersion = useSyncExternalStore(subscribeAiSelection, getAiSelectionVersion);
const selectedAgentId = useScopedAiDefault(workspaceId, "agentId");
// Subscribed for creation scopes, which resolve like getWorkspaceAiSelection.
const scopedModel = useScopedAiDefault(workspaceId, "model");
Expand All @@ -177,6 +179,7 @@ export function useWorkspaceAiSelection(
defaultModel,
agentAiDefaults,
agentBaseById,
selectionVersion,
});
}

Expand All @@ -187,6 +190,8 @@ function resolveAutoRouting(input: {
agentId: string;
agentAiDefaults: AgentAiDefaults;
agentBaseById?: ReadonlyMap<string, string | undefined>;
/** Hooks pass the AI-selection store version (see useAutoRouting). */
selectionVersion?: number;
}): boolean {
const agentId = normalizeAgentId(input.agentId, WORKSPACE_DEFAULTS.agentId);
const flag = AUTO_ROUTING_FLAG[input.dimension];
Expand Down Expand Up @@ -223,7 +228,9 @@ export function useAutoRouting(
dimension: AutoRoutingDimension,
agentBaseById?: ReadonlyMap<string, string | undefined>
): boolean {
useSyncExternalStore(subscribeAiSelection, getAiSelectionVersion);
// The result reads module-level picks, so the React Compiler must see the store version as an
// input: otherwise it reuses the result while the arguments stay the same (a memoized map).
const selectionVersion = useSyncExternalStore(subscribeAiSelection, getAiSelectionVersion);
const agentId = useScopeAgentId(scopeId);
const agentAiDefaults = useAgentAiDefaults();
return resolveAutoRouting({
Expand All @@ -232,5 +239,6 @@ export function useAutoRouting(
agentId,
agentAiDefaults,
agentBaseById,
selectionVersion,
});
}
Loading
Loading