返回 DeepSeek-Reasonix
Composer.tsx
根目录 / desktop / frontend / src / components / Composer.tsx
1 import { clipboardFiles, clipboardHasImageHint, isPasteShortcut, dataURLHash, cutUnchangedComposerText } from "../lib/composerClipboard";
2 import { composerDraftFingerprint, emptyComposerDraft, persistentComposerDraft, persistentSnapshot } from "./composerDraftState";
3 import { SessionInputRecovery } from "./SessionInputRecovery";
4 import { recoveryStatusText, type RecoveryRetry } from "../lib/recoveryStatus";
5 import { useRuntimeSession } from "../lib/useRuntimeState";
6 import { isCompactCommand } from "../lib/sessionMaintenanceOperation";
7 import { pendingFollowups, confirmFollowup, followupNotSubmitted, followupSessionKey, queuedFollowupOutcome, type PendingFollowup } from "../lib/pendingFollowup";
8 import { useAppNavigationStore } from "../store/appNavigation";
9 import { lazy, Suspense, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
10 import type { CSSProperties, ClipboardEvent, DragEvent, KeyboardEvent, MouseEvent as ReactMouseEvent, PointerEvent as ReactPointerEvent } from "react";
11 import { ArrowRight, ArrowUp, Brain, Check, CornerDownRight, Eye, FileText, Folder, Lightbulb, List, MessageSquare, Plus, Search, Square, Target, Trash2, X } from "lucide-react";
12 import { asArray } from "../lib/array";
13 import { filterAtMatches } from "../lib/atMatches";
14 import { DedupIndex, sha256, ordinaryFileSource } from "../lib/attachDedup";
15 import { splitOversizeAttachments } from "../lib/attachmentLimits";
16 import { app, onFilesDropped } from "../lib/bridge";
17 import { attachmentExt, attachmentName, baseName, formatAttachmentDisplayReference, hasImageAttachments, sortComposerAttachments, type Attachment } from "../lib/composerAttachments";
18 import type { PastedBlock, PersistentComposerDraft, PersistentComposerTarget, WorkspaceReference } from "../lib/composerDraftTypes";
19 import { sendPersistedComposer, useSessionComposerPersistence } from "../lib/sessionComposerPersistence";
20 import { ComposerModelApplicationRecovery } from "./ModelApplicationRecovery";
21 import { definitelyNotAccepted, modelApplicationError, type ModelApplicationDetails, type ModelApplicationChoice } from "../lib/modelApplication";
22 import type { SessionRef } from "../lib/sessionRef";
23 import type { SessionIdentity } from "../lib/sessionIdentity";
24 import type { ComposerTarget } from "../generated/desktopContract.generated";
25 import { desktopHost } from "../lib/desktopHost";
26 import { steerInboxItemForActiveTurn } from "../lib/inboxSubmit";
27 import { formatInboxError, isInboxItemMissing } from "../lib/inboxError";
28 import { captureStableInboxTarget, createTransientGuidance } from "../lib/transientComposerGuidance";
29 import { inboxScopeKey } from "../lib/composerInboxQueue";
30 import { useComposerInboxRefresh } from "../lib/useComposerInboxRefresh";
31 import { useComposerImeGuard } from "../lib/useComposerImeGuard";
32 import { useComposerCommandCatalog } from "../lib/useComposerCommandCatalog";
33 import { guidanceIsInFlight, guidanceNeedsRetry, guidanceTextMatches, kickIdleGuidance, markGuidanceQueued } from "../lib/composerGuidance";
34 import { createGuidanceReceiptTracker, type GuidanceReceiptTracker } from "../lib/composerGuidanceReceipt";
35 import { canUsePromptHistory, composerEnterAction, composerEscapeAction, composerMenuKeyAction, insertComposerNewline, isFnKeyEvent, isImeKeyEvent, promptHistoryDirectionFromEvent } from "../lib/composerKeyboard";
36 import { cacheGeneration, loadOlder } from "../lib/composerHistory";
37 import { sessionTurnsLabel } from "../lib/sessionTurnsPresentation";
38 import { useI18n, type Translator } from "../lib/i18n";
39 import { detectShortcutPlatform, formatShortcutCombo, matchesShortcut, useShortcutComboLabel } from "../lib/keyboardShortcuts";
40 import { writeClipboardText } from "../lib/clipboard";
41 import {
42 commandAvailableAtSlashPosition,
43 commandUsesStructuredInvocation,
44 invocationRequests,
45 replaceInvocationTextRange,
46 serializeInvocationSubmit,
47 typedStructuredInvocationDraft,
48 trimInvocationDraft,
49 type ComposerInvocation,
50 type StructuredInvocationSubmit,
51 } from "../lib/invocationDisplay";
52 import { formatTokens, formatTps } from "../lib/format";
53 import { formatElapsedMs, turnMetrics } from "../lib/turnMetrics";
54 import { useLiveTurnMetrics } from "../lib/useLiveTurnMetrics";
55 import type { CancelOutcome } from "../lib/inboxCancel";
56 import type { ControllerLiveStore } from "../lib/useController";
57 import { clearLayoutSize, loadOptionalLayoutSize, saveLayoutSize } from "../lib/layoutPreferences";
58 import { createRafResizeUpdater } from "../lib/resizeDrag";
59 import { observeComposerMenuViewport } from "../lib/composerMenuViewport";
60 import { resolveComposerContentSizing } from "../lib/composerSizing";
61 import { useToast } from "../lib/toast";
62 import { readStatusLabel, turnPhaseStatusLabel } from "../lib/readStatus";
63 import { fullAccessProjectConfirmationKey } from "../lib/fullAccessConfirmation";
64 import { normalizeToolApprovalMode, type CollaborationMode, type CommandInfo, type ComposerInsertRequest, type ContextInfo, type DirEntry, type EffortInfo, type GoalLifecycleView, type GoalRuntime, type HistoryMessage, type Mode, type PromptHistoryEntry, type SessionMeta, type SessionReference, type SlashArgItem, type SlashArgsResult, type TabMeta, type ToolApprovalMode, type BalanceInfo, type WireReadStatus } from "../lib/types";
65 import { ComposerPinnedFilesShelf } from "./ComposerPinnedFilesShelf";
66 import type { ComposerWorkspaceContext } from "./ComposerWorkspaceContextBar";
67 import {
68 formatWorkspaceReference,
69 parseWorkspaceReference,
70 readWorkspaceReferenceDrag,
71 WORKSPACE_REF_DRAG_TYPE,
72 } from "../lib/workspaceDrag";
73 import { SlashMenu, sortSlashCommandsForMenu } from "./SlashMenu";
74 import { ArgMenu } from "./ArgMenu";
75 import { ANCHORED_POPOVER_CLOSE_MS, AnchoredPopover } from "./AnchoredPopover";
76 import { ComposerChoice } from "./ComposerChoice";
77 import { PermissionPresetChoice } from "./PermissionPresetChoice";
78 const ModelSwitcher = lazy(() => import("./ModelSwitcher").then((module) => ({ default: module.ModelSwitcher })));
79 const ComposerWorkspaceContextBar = lazy(() => import("./ComposerWorkspaceContextBar"));
80 import { Tooltip } from "./Tooltip";
81 const RecoveryWaitBanner = lazy(() => import("./RecoveryWaitBanner").then((module) => ({ default: module.RecoveryWaitBanner })));
82 const AuthenticationRecoveryActions = lazy(() => import("./AuthenticationRecoveryActions").then((module) => ({ default: module.AuthenticationRecoveryActions })));
83 import { ComposerContextCard } from "./ComposerContextCard";
84 import { Markdown } from "./Markdown";
85 import { CodeViewer } from "./CodeViewer";
86 import { ContextWindowRing } from "./ContextWindowRing";
87 import { ImageViewer } from "./ImageViewer";
88 import type { PendingGuidance } from "./ComposerGuidanceShelf";
89 import {
90 RichComposerInput,
91 slashQueryAt,
92 type RichComposerChangeOrigin,
93 type RichComposerInputHandle,
94 type RichComposerSelection,
95 type RichSlashQuery,
96 } from "./RichComposerInput";
97 import { VirtualMenu } from "./VirtualMenu";
98 import { activeFileReferenceToken, dirEntryMenuLabel, dirEntrySubmitPath } from "./FileReferenceMenu";
99 import { activeRefTokenRe, escapeRefPath, unescapeRefPath } from "../lib/refToken";
100 import { ContextMenu, contextMenuPointFromEvent, type ContextMenuItem, type ContextMenuPoint } from "./ContextMenu";
101 import {
102 formatSelectedTextContext,
103 formatSelectionLabel,
104 languageFor,
105 normalizeSelectedText,
106 selectedTextSnippet,
107 type SelectedTextInsertRequest,
108 type SelectedTextReference,
109 } from "../lib/selectedTextContext";
110 import { formatGoalWorkTime } from "../lib/goalRuntime";
111 import { ComposerContentMenuActions } from "./ComposerContentMenuActions";
112 import { GoalLifecycleActions } from "./GoalLifecycleActions";
113
114 export type { PersistentComposerDraft } from "../lib/composerDraftTypes";
115
116 interface AttachmentDedupKey {
117 hash: string;
118 source: string;
119 }
120
121 const LONG_PASTE_MIN_CHARS = 2000;
122 const LONG_PASTE_MIN_LINES = 20;
123 const COMPOSER_MIN_HEIGHT = 104;
124 const COMPOSER_DEFAULT_HEIGHT = 140;
125 const COMPOSER_MAX_HEIGHT = 360;
126 // Height reserved for the in-card run strip while a turn runs; applied via a
127 // CSS calc so --composer-height always stays in "logical height" space.
128 const COMPOSER_RUN_STRIP_RESERVED = 30;
129 const COMPOSER_MAX_VIEWPORT_RATIO = 0.4;
130 const COMPOSER_AUTO_RESERVED_HEIGHT = 58;
131 const PROMPT_HISTORY_PREFETCH_REMAINING = 3;
132 const FILE_REF_SEARCH_CACHE_TTL_MS = 5000;
133 const ComposerGuidanceShelf = lazy(() => import("./ComposerGuidanceShelf").then((module) => ({ default: module.ComposerGuidanceShelf })));
134 const ComposerInboxQueue = lazy(() => import("./ComposerInboxQueue").then(module => ({ default: module.ComposerInboxQueue })));
135 const loadAttachmentSubmit = () => import("../lib/attachmentSubmit");
136 // Resolve functional updates synchronously, outside React's deferred updater.
137 // The store receives only the field changed by the event, never an old snapshot.
138 function useComposerField<K extends keyof PersistentComposerDraft>(key: K, initial: PersistentComposerDraft[K], owner: { current: PersistentComposerTarget | undefined }, restoring: { current: boolean }) {
139 const [value, setValue] = useState(initial);
140 const latest = useRef(initial);
141 const set = (update: PersistentComposerDraft[K] | ((previous: PersistentComposerDraft[K]) => PersistentComposerDraft[K])) => {
142 const target = owner.current;
143 if (!restoring.current && target?.canEdit && !target.canEdit(target.draftId, target.generation)) return;
144 const next = typeof update === "function" ? update(latest.current) : update;
145 latest.current = next;
146 setValue(next);
147 if (!restoring.current && target) {
148 if (target.onPatch) target.onPatch(target.draftId, target.generation, { [key]: next });
149 else {
150 const content = { ...target.initial, [key]: next };
151 owner.current = { ...target, initial: content };
152 target.onChange(target.draftId, target.generation, content);
153 }
154 }
155 };
156 return [value, set] as const;
157 }
158
159 type FileRefSearchCacheEntry = {
160 entries: DirEntry[];
161 cachedAt: number;
162 };
163
164 export type ComposerDraft = {
165 text: string;
166 invocations: ComposerInvocation[];
167 attachments: Attachment[];
168 workspaceRefs: WorkspaceReference[];
169 pastedBlocks: PastedBlock[];
170 openPastedLabels: string[];
171 sessionRefs: SessionReference[];
172 selectedTextRefs: SelectedTextReference[];
173 attachmentDedupKeys: Record<string, AttachmentDedupKey>;
174 nextPasteId: number;
175 historyIndex: number;
176 savedText: string;
177 pendingGuidance: PendingGuidance[];
178 guidanceExpanded: boolean;
179 guidanceSendingId: string | null;
180 pendingPaste: number;
181 submitting: false | "message" | "compact";
182 };
183
184 type ComposerEditSnapshot = {
185 text: string;
186 invocations: ComposerInvocation[];
187 pastedBlocks: PastedBlock[];
188 openPastedLabels: string[];
189 nextPasteId: number;
190 selection: RichComposerSelection;
191 };
192
193 type ComposerEditTransaction = {
194 before: ComposerEditSnapshot;
195 after: ComposerEditSnapshot;
196 nativeBarrierBefore: boolean;
197 nativeBarrierAfter: boolean;
198 };
199
200 type ComposerEditHistory = {
201 undo: ComposerEditTransaction[];
202 redo: ComposerEditTransaction[];
203 undoNativeBarrier: boolean;
204 redoNativeBarrier: boolean;
205 };
206
207 type WebkitFileEntry = {
208 isDirectory?: boolean;
209 };
210
211 const DEFAULT_COMPOSER_DRAFT_KEY = "__default_composer_draft__";
212 const MAX_COMPOSER_EDIT_HISTORY = 50;
213
214 function lineCount(s: string): number {
215 if (s === "") return 0;
216 return s.split(/\r\n|\r|\n/).length;
217 }
218
219 function shouldFoldPaste(s: string): boolean {
220 return s.length >= LONG_PASTE_MIN_CHARS || lineCount(s) >= LONG_PASTE_MIN_LINES;
221 }
222
223 function renderPastedBlock(block: PastedBlock): string {
224 return `${block.label}\n\n--- Begin ${block.label} ---\n${block.text}\n--- End ${block.label} ---`;
225 }
226
227 function workspaceReferenceKey(ref: WorkspaceReference): string {
228 return `${ref.isDir ? "dir" : "file"}:${ref.path}`;
229 }
230
231 type PastChatToken = {
232 from: number;
233 query: string;
234 };
235
236 function activePastChatToken(text: string): PastChatToken | null {
237 const queryText = text.replace(/[\r\n]+$/u, "");
238 const match = /(?:^|\s)#([^\s#]*)$/u.exec(queryText);
239 if (!match) return null;
240 return { from: match.index, query: match[1] };
241 }
242
243 export function composerPickFileEntry(
244 text: string,
245 atRaw: string | null,
246 atDir: string,
247 entry: DirEntry,
248 ): { text: string; workspaceRef?: WorkspaceReference } {
249 const queryText = text.replace(/[\r\n]+$/u, "");
250 const atPos = queryText.length - (atRaw?.length ?? 0) - 1; // index of '@'
251 const prefix = queryText.slice(0, Math.max(0, atPos));
252 const refPath = dirEntrySubmitPath(entry, atDir);
253 if (entry.path || entry.displayPath) {
254 return { text: prefix, workspaceRef: { path: refPath, isDir: entry.isDir, displayPath: entry.displayPath } };
255 }
256 // Inline fallback: escape whitespace so the ref survives @-token parsing.
257 return { text: prefix + "@" + escapeRefPath(refPath) + (entry.isDir ? "/" : " ") };
258 }
259
260 function cloneComposerDraft(draft: ComposerDraft): ComposerDraft {
261 return {
262 text: draft.text,
263 invocations: draft.invocations.map((invocation) => ({ ...invocation, command: { ...invocation.command } })),
264 attachments: [...draft.attachments],
265 workspaceRefs: [...draft.workspaceRefs],
266 pastedBlocks: [...draft.pastedBlocks],
267 openPastedLabels: [...draft.openPastedLabels],
268 sessionRefs: [...draft.sessionRefs],
269 selectedTextRefs: draft.selectedTextRefs.map((reference) => ({ ...reference })),
270 attachmentDedupKeys: { ...draft.attachmentDedupKeys },
271 nextPasteId: draft.nextPasteId,
272 historyIndex: draft.historyIndex,
273 savedText: draft.savedText,
274 pendingGuidance: draft.pendingGuidance.map((item) => ({ ...item })),
275 guidanceExpanded: draft.guidanceExpanded,
276 guidanceSendingId: draft.guidanceSendingId,
277 pendingPaste: draft.pendingPaste,
278 submitting: draft.submitting,
279 };
280 }
281
282 function attachmentDedupFromKeys(keys: Record<string, AttachmentDedupKey>): DedupIndex {
283 const index = new DedupIndex();
284 for (const key of Object.values(keys)) {
285 index.add(key.hash, key.source);
286 }
287 return index;
288 }
289
290 function draftHasAttachmentDedupKey(draft: ComposerDraft, key: AttachmentDedupKey): boolean {
291 return Object.values(draft.attachmentDedupKeys).some((existing) => existing.hash === key.hash && existing.source === key.source);
292 }
293
294 function composerMaxHeight(): number {
295 if (typeof window === "undefined") return COMPOSER_MAX_HEIGHT;
296 return Math.max(COMPOSER_MIN_HEIGHT, Math.min(COMPOSER_MAX_HEIGHT, Math.floor(window.innerHeight * COMPOSER_MAX_VIEWPORT_RATIO)));
297 }
298
299 // Hero (creation) input cap: the old 96px hard cap clipped longer drafts
300 // before the card autosize took over; give the hero min(30vh, 160px) so a
301 // visible scrollbar takes over instead (#8494/#8742/#9019).
302 function composerHeroInputMaxHeight(): number {
303 if (typeof window === "undefined") return 160;
304 return Math.min(Math.floor(window.innerHeight * 0.3), 160);
305 }
306
307 // The rendered card includes the run strip while a turn runs; subtract it to
308 // recover the user's logical height when measuring from the DOM.
309 function composerLogicalHeight(card: HTMLElement): number {
310 const strip = card.querySelector(".composer-run-strip");
311 const stripHeight = strip ? strip.getBoundingClientRect().height : 0;
312 return card.getBoundingClientRect().height - stripHeight;
313 }
314
315 function clampComposerHeight(height: number): number {
316 return Math.min(Math.max(Math.round(height), COMPOSER_MIN_HEIGHT), composerMaxHeight());
317 }
318
319 function loadComposerHeight(): number | null {
320 return loadOptionalLayoutSize("composerHeight", clampComposerHeight) ?? clampComposerHeight(COMPOSER_DEFAULT_HEIGHT);
321 }
322
323 // --- past:chats hover preview helpers (PR-C2) ---
324 // Pure formatting helpers used by the past:chats list tooltip. They never read
325 // from disk, never call PreviewSession — they only shape the data that already
326 // lives in the SessionMeta snapshot we fetched on entry.
327 const PAST_CHAT_PREVIEW_MAX = 200;
328
329 function truncatePreview(value?: string, max = PAST_CHAT_PREVIEW_MAX): string {
330 const text = (value || "").trim();
331 if (text.length <= max) return text;
332 return `${text.slice(0, max)}...`;
333 }
334
335 function fmtSessionTime(value?: number): string {
336 if (!value) return "";
337 const d = new Date(value);
338 if (Number.isNaN(d.getTime())) return "";
339 const yyyy = d.getFullYear();
340 const mm = String(d.getMonth() + 1).padStart(2, "0");
341 const dd = String(d.getDate()).padStart(2, "0");
342 const hh = String(d.getHours()).padStart(2, "0");
343 const mi = String(d.getMinutes()).padStart(2, "0");
344 return `${yyyy}-${mm}-${dd} ${hh}:${mi}`;
345 }
346
347 function pastChatTitle(session: SessionMeta): string {
348 return session.title || session.topicTitle || session.preview || "Untitled";
349 }
350
351 function useTick(on: boolean): number {
352 const [, setN] = useState(0);
353 useEffect(() => {
354 if (!on) return;
355 const id = window.setInterval(() => setN((n) => n + 1), 1000);
356 return () => window.clearInterval(id);
357 }, [on]);
358 return Date.now();
359 }
360
361 // --- past:chats session reference → prompt context (PR-B) ---
362 // Send-side helpers for "@past:chats" session references. PR-A wired the menu and
363 // the composer-context card; this layer reads each referenced session through the
364 // existing PreviewSession API and prepends a compact user/assistant transcript to
365 // submitText so the model sees the referenced chat as background context.
366 const SESSION_REF_MAX_MESSAGES = 30;
367 const SESSION_REF_MAX_CHARS = 20_000;
368 const PAST_CHATS_MENU_ITEM = "past:chats";
369
370 // limitSessionMessages keeps the most recent useful messages within a char budget.
371 // Walks from the end so the truncation is always "drop the oldest", which matches
372 // the intuition that the latest turns are the relevant ones for follow-up.
373 function limitSessionMessages(
374 messages: HistoryMessage[],
375 maxMessages = SESSION_REF_MAX_MESSAGES,
376 maxChars = SESSION_REF_MAX_CHARS,
377 ): { messages: HistoryMessage[]; truncated: boolean } {
378 const useful = messages
379 .filter(
380 (m) =>
381 (m.role === "user" || m.role === "assistant") &&
382 typeof m.content === "string" &&
383 m.content.trim().length > 0,
384 )
385 .slice(-maxMessages);
386 const result: HistoryMessage[] = [];
387 let total = 0;
388 let truncated = useful.length >= maxMessages;
389 for (let i = useful.length - 1; i >= 0; i--) {
390 const msg = useful[i];
391 const content = msg.content.trim();
392 if (total + content.length > maxChars) {
393 truncated = true;
394 break;
395 }
396 result.unshift({ ...msg, content });
397 total += content.length;
398 }
399 if (result.length < useful.length) truncated = true;
400 return { messages: result, truncated };
401 }
402
403 // formatSessionContext renders one referenced session as a labelled transcript.
404 // Falls back to a "no usable messages" note when filtering empties the list so
405 // the model still sees that something was referenced.
406 function formatSessionContext(
407 ref: SessionReference,
408 messages: HistoryMessage[],
409 truncated: boolean,
410 t: Translator,
411 ): string {
412 const body = messages
413 .map((m) => `${m.role === "user" ? t("composer.sessionContextUser") : t("composer.sessionContextAssistant")}: ${m.content.trim()}`)
414 .join("\n\n");
415 return [
416 `[${t("composer.sessionContextSession", { title: ref.title })}]`,
417 truncated ? t("composer.sessionContextTruncated") : "",
418 body || t("composer.sessionContextEmpty"),
419 ]
420 .filter(Boolean)
421 .join("\n");
422 }
423
424 // buildSessionContext reads each referenced session, formats the most recent
425 // slice, and joins them with a separator. A single failed read must not block
426 // the others; a localized read-failure note marks the bad one and the
427 // remaining refs still flow through.
428 async function buildSessionContext(refs: SessionReference[], t: Translator): Promise<string> {
429 if (refs.length === 0) return "";
430 let context = `${t("composer.sessionContextHeader")}\n\n`;
431 for (const ref of refs) {
432 try {
433 const raw = await app.PreviewSession(ref.path);
434 const limited = limitSessionMessages(asArray(raw));
435 context += `${formatSessionContext(ref, limited.messages, limited.truncated, t)}\n\n---\n\n`;
436 } catch (error) {
437 console.error("[past:chats] failed to preview session", ref.path, error);
438 context += `[${t("composer.sessionContextSession", { title: ref.title })}]\n${t("composer.sessionContextReadFailed")}\n\n---\n\n`;
439 }
440 }
441 context += `${t("composer.sessionContextFooter")}\n`;
442 return context;
443 }
444
445 export function Composer({
446 running,
447 collaborationMode,
448 toolApprovalMode,
449 turnPhase,
450 readStatuses,
451 goal,
452 goalStatus,
453 goalView,
454 goalRuntime,
455 cwd,
456 workspaceRoot,
457 modelLabel,
458 commandCatalog,
459 imageInputEnabled = true,
460 imageUnderstandingEnabled = false,
461 attachmentInputEnabled = true,
462 tabId, turnId,
463 effort,
464 onSend,
465 onSteer,
466 localDurableGuidance = true,
467 onCancel,
468 onCycleMode,
469 onSetMode,
470 onSetCollaborationMode: setCollaborationMode,
471 onSetToolApprovalMode,
472 onClearGoal,
473 onEditGoal,
474 onPauseGoal,
475 onResumeGoal,
476 onSwitchModel,
477 onSetEffort,
478 insertRequest,
479 selectedTextRequest,
480 disabled,
481 submitDisabled = false,
482 submitDisabledReason,
483 authentication,
484 readOnly = false,
485 decisionPending = false,
486 ready,
487 turnStartAt,
488 turnDoneAt,
489 lastTurnOutputTokens,
490 lastTurnWaitAccumMs,
491 turnWaitAccumMs = 0,
492 promptWaitStartedAt,
493 turnTokens,
494 turnOutputTokens,
495 turnOutputCharsAtUsage,
496 turnModelActiveAt,
497 turnModelActiveMs = 0,
498 turnRateOutputQuarters,
499 liveStore,
500 turnArgChars = 0,
501 turnOutputEstimated,
502 lastTurnOutputEstimated,
503 retry,
504 suspendedByDecision = false,
505 pendingApprovalLabel,
506 pendingAsk = false,
507 transientDismissSignal,
508 sessionKey,
509 inboxSessionPath,
510 inboxHostId,
511 inboxWorkspace,
512 workspaceScopeKey,
513 fileRefRefreshKey,
514 guidanceConsumedKey,
515 guidanceConsumedItemId,
516 guidanceConsumedText,
517 guidanceQueuePreviewItems,
518 showContextWindowRing = false,
519 heroMode = false,
520 context,
521 turnCost,
522 turnRateBand,
523 currency,
524 cacheHitTokens,
525 cacheMissTokens,
526 balance,
527 pinnedFiles,
528 workspaceContext,
529 onInvocationMetadataChange,
530 onCaptureSubmit,
531 onReleaseSubmit,
532 onPrepareSubmit,
533 persistentDraft: legacyPersistentDraft,
534 formalSessionRef,
535 sessionIdentity,
536 composerTarget,
537 }: {
538 running: boolean;
539 collaborationMode: CollaborationMode;
540 toolApprovalMode: ToolApprovalMode;
541 /** Host turn phase: working | checking | verifying | reviewing */
542 turnPhase?: string;
543 /** Live read progress keyed by read id; rendered as one status line. */
544 readStatuses?: Record<string, WireReadStatus>;
545 goal?: string;
546 goalStatus?: string;
547 goalView?: GoalLifecycleView;
548 goalRuntime?: GoalRuntime;
549 cwd?: string;
550 workspaceRoot?: string;
551 modelLabel: string;
552 commandCatalog?: readonly CommandInfo[];
553 imageInputEnabled?: boolean;
554 /** True when text-only image turns are preprocessed by a configured vision model. */
555 imageUnderstandingEnabled?: boolean;
556 /** False for remote sessions because local filesystem paths are not portable to Serve. */
557 attachmentInputEnabled?: boolean;
558 tabId?: string; turnId?: string;
559 effort?: EffortInfo;
560 onSend: (displayText: string, submitText?: string, tabId?: string, structured?: StructuredInvocationSubmit, capture?: unknown, submissionId?: string) => void | Promise<void>;
561 onCaptureSubmit?: (content: PersistentComposerDraft) => unknown;
562 onReleaseSubmit?: (capture: unknown) => void;
563 onPrepareSubmit?: (capture: unknown) => Promise<void>;
564 onInvocationMetadataChange?: (metadata: Record<string, { kind: "skill" | "subagent"; color?: string }>) => void;
565 onSteer?: (submitText: string, tabId?: string) => void | Promise<void>;
566 /** False when the owning surface provides its own durable remote inbox. */
567 localDurableGuidance?: boolean;
568 // Returns the un-sent text plus the exact durable queue IDs the backend
569 // confirmed were withdrawn and are therefore safe to restore.
570 onCancel: (queuedItemIDs?: string[]) => Promise<CancelOutcome>;
571 onCycleMode: () => void;
572 onSetMode: (mode: Mode) => void;
573 onSetCollaborationMode: (mode: CollaborationMode) => void;
574 onSetToolApprovalMode: (mode: ToolApprovalMode) => void;
575 onClearGoal: () => void;
576 onEditGoal: (objective: string, maxGoalRounds: number | null) => void;
577 onPauseGoal: () => void;
578 onResumeGoal: () => void;
579 onSwitchModel: (name: string) => boolean | Promise<boolean>;
580 onSetEffort: (level: string) => void;
581 insertRequest?: ComposerInsertRequest | null;
582 selectedTextRequest?: SelectedTextInsertRequest | null;
583 disabled?: boolean;
584 submitDisabled?: boolean;
585 submitDisabledReason?: string;
586 authentication?: TabMeta["authentication"];
587 readOnly?: boolean;
588 decisionPending?: boolean;
589 // ready/cwd/running/workspaceScopeKey re-trigger the command fetch: Commands() returns only
590 // built-ins until boot.Build finishes (the controller, hence skills/custom/MCP,
591 // is nil before then), the available set changes when the workspace switches,
592 // and a completed turn may have installed skills or MCP prompts.
593 ready?: boolean;
594 turnStartAt?: number;
595 turnDoneAt?: number;
596 lastTurnOutputTokens?: number;
597 lastTurnWaitAccumMs?: number;
598 // Tab-scoped user-wait from the controller (approval/ask). Counts while the
599 // tab is in the background so Composer does not invent a wait start on focus.
600 turnWaitAccumMs?: number;
601 promptWaitStartedAt?: number;
602 turnTokens?: number;
603 // Completion + reasoning tokens accumulated this turn — feeds the streaming
604 // TPS readout in the run ticker (composer-run-strip).
605 turnOutputTokens?: number;
606 // Live text+reasoning characters already covered by turnOutputTokens.
607 turnOutputCharsAtUsage?: number;
608 // Active provider-output time for the current turn; excludes tool gaps.
609 turnModelActiveAt?: number;
610 turnModelActiveMs?: number;
611 turnRateOutputQuarters?: number;
612 // Live-stream subscription for the character-density TPS fallback (see
613 // lib/turnMetrics) when the provider does not emit per-chunk usage events
614 // with token counts during streaming. Subscribing here keeps text deltas off
615 // the main state tree — only the composer re-renders, matching the
616 // controller's live-store contract (pure stream deltas must not re-render the
617 // controller owner).
618 liveStore?: ControllerLiveStore;
619 // Streaming argument characters provide estimated progress before usage arrives.
620 turnArgChars?: number;
621 // Whether the provider flagged this turn's usage as reconstructed.
622 turnOutputEstimated?: boolean;
623 lastTurnOutputEstimated?: boolean;
624 retry?: RecoveryRetry;
625 // True while a footer decision surface (approval / ask / clear context) owns
626 // the UI. Pauses the model-work ticker without rendering a "waiting approval"
627 // run strip (the decision card already conveys that state).
628 suspendedByDecision?: boolean;
629 // Legacy strip labels kept for isolated unit tests; App prefers
630 // suspendedByDecision so the decision card is not duplicated in the strip.
631 pendingApprovalLabel?: string | null;
632 pendingAsk?: boolean;
633 transientDismissSignal?: number;
634 sessionKey?: string;
635 inboxSessionPath?: string;
636 inboxHostId?: string;
637 inboxWorkspace?: string;
638 workspaceScopeKey?: string;
639 fileRefRefreshKey?: number | string;
640 guidanceConsumedKey?: string;
641 guidanceConsumedItemId?: string;
642 guidanceConsumedText?: string;
643 guidanceQueuePreviewItems?: readonly string[];
644 showContextWindowRing?: boolean;
645 // Creation empty-session hero: slim centered composer under the welcome
646 // headline (hides task/approval chrome; keeps model + effort).
647 heroMode?: boolean;
648 context?: ContextInfo;
649 turnCost?: number;
650 turnRateBand?: string;
651 currency?: string;
652 cacheHitTokens?: number;
653 cacheMissTokens?: number;
654 balance?: BalanceInfo;
655 pinnedFiles?: import("../lib/pinnedContextBridge").PinnedFileInfo[];
656 workspaceContext?: ComposerWorkspaceContext;
657 persistentDraft?: PersistentComposerTarget;
658 formalSessionRef?: SessionRef;
659 sessionIdentity?: SessionIdentity;
660 composerTarget?: ComposerTarget;
661 }) {
662 const { t, locale } = useI18n();
663 const { showToast } = useToast();
664 const shortcutPlatform = useMemo(() => detectShortcutPlatform(), []);
665 const sendComboLabel = useShortcutComboLabel("composer.send");
666 const undoComboLabel = useShortcutComboLabel("composer.undo");
667 const redoComboLabel = useShortcutComboLabel("composer.redo");
668 const permissionPreset = normalizeToolApprovalMode(toolApprovalMode);
669 const fullAccessConfirmationKey = fullAccessProjectConfirmationKey({
670 workspacePath: workspaceRoot || inboxWorkspace || cwd,
671 remoteHostId: inboxHostId,
672 });
673 const savedInput = useSessionComposerPersistence(legacyPersistentDraft ? undefined : formalSessionRef, tabId);
674 const persistentDraft = legacyPersistentDraft ?? savedInput.target;
675 if (savedInput.blocked) disabled = true;
676 const onSetCollaborationMode = (mode: CollaborationMode) => {
677 savedInput.setGoalDraft(mode === "goal");
678 setCollaborationMode(mode);
679 };
680 useEffect(() => {
681 if (savedInput.goalDraft === true && !savedInput.blocked && !goal?.trim() && collaborationMode !== "goal") setCollaborationMode("goal");
682 }, [formalSessionRef?.sessionId, savedInput.goalDraft, savedInput.blocked]);
683 const draftKey = sessionKey || tabId || DEFAULT_COMPOSER_DRAFT_KEY;
684 const bridgeTarget = useMemo(() => composerTarget?.kind === "draft"
685 ? { kind: "draft", draftId: composerTarget.draftId, tabId: "", generation: persistentDraft?.generation ?? composerTarget.generation ?? 0 }
686 : { kind: "session", draftId: "", tabId: composerTarget?.tabId ?? tabId ?? "", session: formalSessionRef },
687 [composerTarget?.kind, composerTarget?.kind === "draft" ? composerTarget.draftId : composerTarget?.tabId, persistentDraft?.generation, tabId, formalSessionRef?.hostId, formalSessionRef?.sessionId]);
688 const bridgeTargetKey = `${bridgeTarget.kind}:${bridgeTarget.draftId}:${bridgeTarget.tabId}:${bridgeTarget.generation ?? 0}`;
689 const runtimeState = useRuntimeSession(tabId, sessionIdentity ?? inboxSessionPath);
690 const finishing = runtimeState.finishing;
691 const maintenanceActive = Boolean(runtimeState.state?.maintenance);
692 const [queueEditingScope, setQueueEditingScope] = useState<string | null>(null);
693 if (runtimeState.known) running = runtimeState.running ?? running;
694 if (runtimeState.unknown) disabled = true;
695 const pendingKey = followupSessionKey(inboxSessionPath, inboxHostId, inboxWorkspace);
696 const pendingKeyRef = useRef(pendingKey);
697 pendingKeyRef.current = pendingKey;
698 const pendingFollowup = useSyncExternalStore(pendingFollowups.subscribe, () => pendingFollowups.get(pendingKey));
699 useEffect(() => {
700 if (pendingFollowup && savedInput.settledId === pendingFollowup.key) pendingFollowups.clear(pendingKey, pendingFollowup);
701 }, [pendingFollowup, pendingKey, savedInput.settledId]);
702 const inboxSessionKey = [pendingKey, inboxScopeKey(inboxSessionPath, workspaceScopeKey)].filter(Boolean).join("\u0000");
703 const now = useTick(running);
704 const persistentOwner = useRef(persistentDraft);
705 persistentOwner.current = persistentDraft;
706 const restoringContent = useRef(false);
707 const [text, setText] = useComposerField("text", "", persistentOwner, restoringContent);
708 const [attachments, setAttachments] = useComposerField("attachments", [], persistentOwner, restoringContent);
709 const [imageViewer, setImageViewer] = useState<{ open: boolean; url: string; name: string }>({ open: false, url: "", name: "" });
710 const openComposerImageViewer = useCallback((url: string, name: string) => {
711 setImageViewer({ open: true, url, name });
712 }, []);
713
714 const closeComposerImageViewer = useCallback(() => {
715 setImageViewer((prev) => (prev.open ? { ...prev, open: false } : prev));
716 }, []);
717
718 const [workspaceRefs, setWorkspaceRefs] = useComposerField("workspaceRefs", [], persistentOwner, restoringContent);
719 const [invocations, setInvocations] = useComposerField("invocations", [], persistentOwner, restoringContent);
720 const [plainSelection, setPlainSelection] = useState<RichComposerSelection>({ start: 0, end: 0 });
721 const [richSelection, setRichSelection] = useState<RichComposerSelection>({ start: 0, end: 0 });
722 const [richSlashQuery, setRichSlashQuery] = useState<RichSlashQuery | null>(null);
723 const [pastedBlocks, setPastedBlocks] = useComposerField("pastedBlocks", [], persistentOwner, restoringContent);
724 const [openPastedLabels, setOpenPastedLabels] = useComposerField("openPastedLabels", [], persistentOwner, restoringContent);
725 const [pendingPaste, setPendingPaste] = useState(0);
726 const pendingPasteRef = useRef(0);
727 const pastedBlocksRef = useRef<PastedBlock[]>([]);
728 const nextPasteId = useRef(1);
729 const nextInvocationId = useRef(1);
730 const [active, setActive] = useState(0);
731 const [dismissed, setDismissed] = useState(false);
732 const [dragOver, setDragOver] = useState(false);
733 // A saved manual height is a floor, not a hard cap: longer drafts may grow
734 // above it and return to it when their content shrinks.
735 const [composerHeight, setComposerHeight] = useState<number | null>(loadComposerHeight);
736 const [composerResizing, setComposerResizing] = useState(false);
737 const [textareaAutoHeight, setTextareaAutoHeight] = useState<number | null>(null);
738 const [textareaAutoOverflow, setTextareaAutoOverflow] = useState(false);
739 const [intentMenuOpen, setIntentMenuOpen] = useState(false);
740 const [intentMenuClosing, setIntentMenuClosing] = useState(false);
741 const [contentMenuOpen, setContentMenuOpen] = useState(false);
742 const [showPastChats, setShowPastChats] = useState(false);
743 const [directPastChats, setDirectPastChats] = useState(false);
744 const [pastChats, setPastChats] = useState<SessionMeta[]>([]);
745 const [pastChatQuery, setPastChatQuery] = useState("");
746 const [sessionRefs, setSessionRefs] = useComposerField("sessionRefs", [], persistentOwner, restoringContent);
747 const [selectedTextRefs, setSelectedTextRefs] = useComposerField("selectedTextRefs", [], persistentOwner, restoringContent);
748 const [pendingGuidance, setPendingGuidance] = useState<PendingGuidance[]>([]);
749 const [guidanceExpanded, setGuidanceExpanded] = useState(false);
750 const [guidanceSendingId, setGuidanceSendingId] = useState<string | null>(null);
751 const [guidanceRetryNonce, setGuidanceRetryNonce] = useState(0);
752 const [guidanceDraftKey, setGuidanceDraftKey] = useState(draftKey);
753 const pendingGuidanceRef = useRef<PendingGuidance[]>([]);
754 const guidanceExpandedRef = useRef(false);
755 const guidanceSendingIdRef = useRef<string | null>(null);
756 const [loadingPastChats, setLoadingPastChats] = useState(false);
757 const [submission, setSubmission] = useState<false | "message" | "compact">(false);
758 const cancelSettlingDraftsRef = useRef(new Set<string>());
759 const [, setCancelSettlingRevision] = useState(0);
760 const [inputMenuPoint, setInputMenuPoint] = useState<ContextMenuPoint | null>(null);
761 const [composerPrompt, setComposerPrompt] = useState<string | null>(null);
762 // Prompt history navigation (plain ↑/↓)
763 // Use refs for values read inside async closures to avoid stale captures
764 // on rapid key presses (the React closure trap).
765 const historyIndexRef = useRef(-1);
766 const historyEntriesRef = useRef<PromptHistoryEntry[]>([]);
767 const historyLoadRef = useRef<Promise<void> | null>(null);
768 const historyGenerationRef = useRef(cacheGeneration());
769 // historyIndex state is written (via setHistoryIndex) for potential future
770 // UI feedback (e.g. "3/200" indicator); currently unused in render.
771 const [, setHistoryIndex] = useState(-1);
772 const savedTextRef = useRef("");
773 const taRef = useRef<HTMLTextAreaElement>(null);
774 const measureTaRef = useRef<HTMLTextAreaElement>(null);
775 const richInputRef = useRef<RichComposerInputHandle>(null);
776 const fileInputRef = useRef<HTMLInputElement>(null);
777 const editHistoryByDraftRef = useRef<Record<string, ComposerEditHistory>>({});
778 const pendingNativeInputTypeRef = useRef<string | undefined>(undefined);
779 const composerCardRef = useRef<HTMLDivElement>(null);
780 const composerWrapRef = useRef<HTMLDivElement>(null);
781 const contentMenuAnchorRef = useRef<HTMLButtonElement>(null);
782 const intentMenuAnchorRef = useRef<HTMLButtonElement>(null);
783 const intentCloseTimerRef = useRef<number | null>(null);
784 // Creation chrome: hover-open task menus (same pattern as ContextWindowRing).
785 const intentHoverTimerRef = useRef<number | null>(null);
786 const creationChrome = showContextWindowRing;
787 const wasRunningByDraftRef = useRef<Record<string, boolean>>({ [draftKey]: running });
788 const pastChatSearchComposingRef = useRef(false);
789 const pastChatSearchLastCompositionEndAt = useRef(0);
790 const lastSelectionRef = useRef({ start: 0, end: 0 });
791 const consumedInsertIdByDraftRef = useRef<Record<string, number>>({});
792 const consumedSelectedTextIdByDraftRef = useRef<Record<string, number>>({});
793 const lastTransientDismissSignal = useRef(transientDismissSignal);
794 const lastGuidanceConsumedKeyByDraftRef = useRef<Record<string, string | undefined>>(
795 guidanceConsumedKey ? { [draftKey]: guidanceConsumedKey } : {},
796 );
797 const guidanceReceiptTrackerRef = useRef<GuidanceReceiptTracker | null>(null);
798 guidanceReceiptTrackerRef.current ??= createGuidanceReceiptTracker();
799 // Messages held behind a transient target fence, keyed by follow-up key so a
800 // dismissal or a second send can cancel the pending retry loop.
801 const transientRetriesRef = useRef(new Map<string, { cancelled: boolean }>());
802 const selfDispatchedGuidanceByDraftRef = useRef<Record<string, string[]>>({});
803 const submittingRef = useRef<false | "message" | "compact">(false);
804 const nativeClipboardPasteTimerRef = useRef<number | null>(null);
805 const nativeClipboardPasteCompletionRef = useRef<(() => void) | null>(null);
806 // Snapshot of the current cwd so async callbacks (openPastChats) can detect
807 // workspace switches and discard stale responses (issue #3601).
808 const cwdRef = useRef(cwd);
809 cwdRef.current = cwd;
810 const attachmentDedupRef = useRef(new DedupIndex());
811 const attachmentDedupKeysRef = useRef<Record<string, AttachmentDedupKey>>({});
812 const guidanceQueuePreviewKey = (guidanceQueuePreviewItems ?? []).map((item) => item.trim()).filter(Boolean).join("\n");
813 const draftsBySessionRef = useRef<Record<string, ComposerDraft>>(
814 persistentDraft ? { [draftKey]: persistentComposerDraft(persistentDraft.initial) } : {},
815 );
816 const persistentTargetsByDraftRef = useRef<Record<string, PersistentComposerTarget | undefined>>({});
817 const bridgeTargetsByDraftRef = useRef<Record<string, typeof bridgeTarget>>({});
818 persistentTargetsByDraftRef.current[draftKey] = persistentDraft;
819 bridgeTargetsByDraftRef.current[draftKey] = bridgeTarget;
820 const activeDraftKeyRef = useRef(draftKey);
821 const [remoteApplication, setRemoteApplication] = useState<{key:string; text:string; details:ModelApplicationDetails}|undefined>();
822 const draftActivationEpochRef = useRef(0);
823 const textRef = useRef(text);
824 const invocationsRef = useRef(invocations);
825 const attachmentsRef = useRef(attachments);
826 const workspaceRefsRef = useRef(workspaceRefs);
827 const openPastedLabelsRef = useRef(openPastedLabels);
828 const sessionRefsRef = useRef(sessionRefs);
829 const selectedTextRefsRef = useRef(selectedTextRefs);
830 // Plain-textarea IME freeze: while a composition is active the textarea
831 // renders uncontrolled so no re-render can cancel it (#8593/#8409); the
832 // hook owns the composition lifecycle, resync, and force-sync semantics.
833 const { composingRef, lastCompositionEndAt, trackImeInputChange } = useComposerImeGuard({
834 taRef,
835 text,
836 invocationCount: invocations.length,
837 textRef,
838 lastSelectionRef,
839 setText,
840 setPlainSelection,
841 });
842 textRef.current = text;
843 invocationsRef.current = invocations;
844 attachmentsRef.current = attachments;
845 workspaceRefsRef.current = workspaceRefs;
846 pastedBlocksRef.current = pastedBlocks;
847 openPastedLabelsRef.current = openPastedLabels;
848 sessionRefsRef.current = sessionRefs;
849 selectedTextRefsRef.current = selectedTextRefs;
850 pendingGuidanceRef.current = pendingGuidance;
851 guidanceExpandedRef.current = guidanceExpanded;
852 guidanceSendingIdRef.current = guidanceSendingId;
853 pendingPasteRef.current = pendingPaste;
854 submittingRef.current = submission;
855
856 const snapshotComposerDraft = (): ComposerDraft => ({
857 text: textRef.current,
858 invocations: invocationsRef.current.map((invocation) => ({ ...invocation, command: { ...invocation.command } })),
859 attachments: [...attachmentsRef.current],
860 workspaceRefs: [...workspaceRefsRef.current],
861 pastedBlocks: [...pastedBlocksRef.current],
862 openPastedLabels: [...openPastedLabelsRef.current],
863 sessionRefs: [...sessionRefsRef.current],
864 selectedTextRefs: selectedTextRefsRef.current.map((reference) => ({ ...reference })),
865 attachmentDedupKeys: { ...attachmentDedupKeysRef.current },
866 nextPasteId: nextPasteId.current,
867 historyIndex: historyIndexRef.current,
868 savedText: savedTextRef.current,
869 pendingGuidance: pendingGuidanceRef.current.map((item) => ({ ...item })),
870 guidanceExpanded: guidanceExpandedRef.current,
871 guidanceSendingId: guidanceSendingIdRef.current,
872 pendingPaste: pendingPasteRef.current,
873 submitting: submittingRef.current,
874 });
875
876 const restoreComposerDraft = (draft: ComposerDraft) => {
877 restoringContent.current = true;
878 const next = cloneComposerDraft(draft);
879 textRef.current = next.text;
880 invocationsRef.current = next.invocations;
881 attachmentsRef.current = next.attachments;
882 workspaceRefsRef.current = next.workspaceRefs;
883 openPastedLabelsRef.current = next.openPastedLabels;
884 sessionRefsRef.current = next.sessionRefs;
885 selectedTextRefsRef.current = next.selectedTextRefs;
886 setText(next.text);
887 setInvocations(next.invocations);
888 setAttachments(next.attachments);
889 setWorkspaceRefs(next.workspaceRefs);
890 pastedBlocksRef.current = next.pastedBlocks;
891 setPastedBlocks(next.pastedBlocks);
892 setOpenPastedLabels(next.openPastedLabels);
893 setSessionRefs(next.sessionRefs);
894 setSelectedTextRefs(next.selectedTextRefs);
895 restoringContent.current = false;
896 attachmentDedupKeysRef.current = next.attachmentDedupKeys;
897 attachmentDedupRef.current = attachmentDedupFromKeys(next.attachmentDedupKeys);
898 nextPasteId.current = next.nextPasteId;
899 historyIndexRef.current = next.historyIndex;
900 savedTextRef.current = next.savedText;
901 pendingGuidanceRef.current = next.pendingGuidance;
902 guidanceExpandedRef.current = next.guidanceExpanded;
903 guidanceSendingIdRef.current = next.guidanceSendingId;
904 pendingPasteRef.current = next.pendingPaste;
905 submittingRef.current = next.submitting;
906 setPendingGuidance(next.pendingGuidance);
907 setGuidanceExpanded(next.guidanceExpanded);
908 setGuidanceSendingId(next.guidanceSendingId);
909 setPendingPaste(next.pendingPaste);
910 setSubmission(next.submitting);
911 setHistoryIndex(next.historyIndex);
912 const restoredSelection = { start: next.text.length, end: next.text.length };
913 lastSelectionRef.current = restoredSelection;
914 setPlainSelection(restoredSelection);
915 setRichSelection(restoredSelection);
916 setRichSlashQuery(
917 next.invocations.length > 0
918 ? slashQueryAt(next.text, restoredSelection)
919 : null,
920 );
921 setComposerPrompt(null);
922 setShowPastChats(false);
923 setDirectPastChats(false);
924 setContentMenuOpen(false);
925 setPastChatQuery("");
926 setLoadingPastChats(false);
927 setActive(0);
928 setInputMenuPoint(null);
929 setDragOver(false);
930 setImageViewer((current) => current.open ? { ...current, open: false } : current);
931 setIntentMenuOpen(false);
932 setIntentMenuClosing(false);
933 };
934
935 const composerEditSnapshot = (
936 targetDraftKey: string,
937 selection?: RichComposerSelection,
938 ): ComposerEditSnapshot => {
939 if (targetDraftKey === activeDraftKeyRef.current) {
940 return {
941 text: textRef.current,
942 invocations: invocationsRef.current.map((invocation) => ({ ...invocation, command: { ...invocation.command } })),
943 pastedBlocks: [...pastedBlocksRef.current],
944 openPastedLabels: [...openPastedLabelsRef.current],
945 nextPasteId: nextPasteId.current,
946 selection: selection ?? getComposerSelection(),
947 };
948 }
949 const draft = draftsBySessionRef.current[targetDraftKey] ?? emptyComposerDraft();
950 const start = Math.min(selection?.start ?? draft.text.length, draft.text.length);
951 return {
952 text: draft.text,
953 invocations: draft.invocations.map((invocation) => ({ ...invocation, command: { ...invocation.command } })),
954 pastedBlocks: [...draft.pastedBlocks],
955 openPastedLabels: [...draft.openPastedLabels],
956 nextPasteId: draft.nextPasteId,
957 selection: {
958 start,
959 end: Math.min(selection?.end ?? start, draft.text.length),
960 afterInvocationId: selection?.afterInvocationId,
961 },
962 };
963 };
964
965 const composerEditStateMatches = (left: ComposerEditSnapshot, right: ComposerEditSnapshot): boolean =>
966 left.text === right.text
967 && left.nextPasteId === right.nextPasteId
968 && JSON.stringify(left.invocations) === JSON.stringify(right.invocations)
969 && JSON.stringify(left.pastedBlocks) === JSON.stringify(right.pastedBlocks);
970
971 const editHistoryForDraft = (targetDraftKey: string): ComposerEditHistory => {
972 const existing = editHistoryByDraftRef.current[targetDraftKey];
973 if (existing) return existing;
974 const created: ComposerEditHistory = {
975 undo: [],
976 redo: [],
977 undoNativeBarrier: false,
978 redoNativeBarrier: false,
979 };
980 editHistoryByDraftRef.current[targetDraftKey] = created;
981 return created;
982 };
983
984 const clearComposerEditHistory = (targetDraftKey: string) => {
985 delete editHistoryByDraftRef.current[targetDraftKey];
986 };
987
988 const syncComposerNativeHistory = (targetDraftKey: string, inputType?: string) => {
989 const history = editHistoryByDraftRef.current[targetDraftKey];
990 if (!history) return;
991 const current = composerEditSnapshot(targetDraftKey);
992 const undoTransaction = history.undo[history.undo.length - 1];
993 const redoTransaction = history.redo[history.redo.length - 1];
994
995 if (inputType === "historyUndo") {
996 history.undoNativeBarrier = Boolean(
997 undoTransaction && !composerEditStateMatches(current, undoTransaction.after),
998 );
999 // The browser has just created at least one native redo unit. Keep it
1000 // ahead of any older custom redo transaction until historyRedo reaches
1001 // that transaction's boundary again.
1002 history.redoNativeBarrier = history.undo.length > 0 || history.redo.length > 0;
1003 return;
1004 }
1005
1006 if (inputType === "historyRedo") {
1007 history.undoNativeBarrier = Boolean(
1008 undoTransaction && !composerEditStateMatches(current, undoTransaction.after),
1009 );
1010 if (redoTransaction) {
1011 history.redoNativeBarrier = !composerEditStateMatches(current, redoTransaction.before);
1012 } else if (undoTransaction) {
1013 history.redoNativeBarrier = !composerEditStateMatches(current, undoTransaction.after);
1014 } else {
1015 history.redoNativeBarrier = false;
1016 }
1017 return;
1018 }
1019
1020 // A new browser edit sits above the latest custom transaction even when
1021 // its net text later returns to the same value (type then Backspace).
1022 history.undoNativeBarrier = history.undo.length > 0;
1023 history.redo = [];
1024 history.redoNativeBarrier = false;
1025 };
1026
1027 const recordComposerEdit = (
1028 targetDraftKey: string,
1029 before: ComposerEditSnapshot,
1030 after: ComposerEditSnapshot,
1031 ) => {
1032 if (composerEditStateMatches(before, after)) return;
1033 const history = editHistoryForDraft(targetDraftKey);
1034 const previous = history.undo[history.undo.length - 1];
1035 const nativeBarrierBefore = Boolean(
1036 previous
1037 && (
1038 history.undoNativeBarrier
1039 || !composerEditStateMatches(before, previous.after)
1040 ),
1041 );
1042 history.undo.push({
1043 before,
1044 after,
1045 nativeBarrierBefore,
1046 nativeBarrierAfter: false,
1047 });
1048 if (history.undo.length > MAX_COMPOSER_EDIT_HISTORY) history.undo.shift();
1049 history.redo = [];
1050 history.undoNativeBarrier = false;
1051 history.redoNativeBarrier = false;
1052 };
1053
1054 const restoreComposerEdit = (targetDraftKey: string, snapshot: ComposerEditSnapshot) => {
1055 const invocations = snapshot.invocations.map((invocation) => ({ ...invocation, command: { ...invocation.command } }));
1056 const pastedBlocks = [...snapshot.pastedBlocks];
1057 const openPastedLabels = [...snapshot.openPastedLabels];
1058 if (targetDraftKey !== activeDraftKeyRef.current) {
1059 const draft = cloneComposerDraft(draftsBySessionRef.current[targetDraftKey] ?? emptyComposerDraft());
1060 draft.text = snapshot.text;
1061 draft.invocations = invocations;
1062 draft.pastedBlocks = pastedBlocks;
1063 draft.openPastedLabels = openPastedLabels;
1064 draft.nextPasteId = snapshot.nextPasteId;
1065 draftsBySessionRef.current[targetDraftKey] = draft;
1066 return;
1067 }
1068 textRef.current = snapshot.text;
1069 invocationsRef.current = invocations;
1070 pastedBlocksRef.current = pastedBlocks;
1071 openPastedLabelsRef.current = openPastedLabels;
1072 nextPasteId.current = snapshot.nextPasteId;
1073 setText(snapshot.text);
1074 setInvocations(invocations);
1075 setPastedBlocks(pastedBlocks);
1076 setOpenPastedLabels(openPastedLabels);
1077 setComposerPrompt(null);
1078 resetPromptHistoryNavigation();
1079 setComposerSelection(
1080 snapshot.selection.start,
1081 snapshot.selection.end,
1082 snapshot.selection.afterInvocationId,
1083 );
1084 };
1085
1086 const canUndoComposerEdit = (targetDraftKey: string): boolean => {
1087 const history = editHistoryByDraftRef.current[targetDraftKey];
1088 if (!history || history.undoNativeBarrier) return false;
1089 const transaction = history.undo[history.undo.length - 1];
1090 return Boolean(
1091 transaction
1092 && composerEditStateMatches(composerEditSnapshot(targetDraftKey), transaction.after),
1093 );
1094 };
1095
1096 const undoComposerEdit = (targetDraftKey: string): boolean => {
1097 const history = editHistoryByDraftRef.current[targetDraftKey];
1098 if (!history || !canUndoComposerEdit(targetDraftKey)) return false;
1099 const transaction = history.undo.pop();
1100 if (!transaction) return false;
1101 transaction.nativeBarrierAfter = history.redoNativeBarrier;
1102 history.redo.push(transaction);
1103 restoreComposerEdit(targetDraftKey, transaction.before);
1104 const previous = history.undo[history.undo.length - 1];
1105 history.undoNativeBarrier = Boolean(previous && transaction.nativeBarrierBefore);
1106 history.redoNativeBarrier = false;
1107 return true;
1108 };
1109
1110 const canRedoComposerEdit = (targetDraftKey: string): boolean => {
1111 const history = editHistoryByDraftRef.current[targetDraftKey];
1112 if (!history || history.redoNativeBarrier) return false;
1113 const transaction = history.redo[history.redo.length - 1];
1114 return Boolean(
1115 transaction
1116 && composerEditStateMatches(composerEditSnapshot(targetDraftKey), transaction.before),
1117 );
1118 };
1119
1120 const redoComposerEdit = (targetDraftKey: string): boolean => {
1121 const history = editHistoryByDraftRef.current[targetDraftKey];
1122 if (!history || !canRedoComposerEdit(targetDraftKey)) return false;
1123 const transaction = history.redo.pop();
1124 if (!transaction) return false;
1125 history.undo.push(transaction);
1126 restoreComposerEdit(targetDraftKey, transaction.after);
1127 history.undoNativeBarrier = false;
1128 const next = history.redo[history.redo.length - 1];
1129 history.redoNativeBarrier = transaction.nativeBarrierAfter
1130 || Boolean(next && next.nativeBarrierBefore);
1131 return true;
1132 };
1133
1134 const updatePendingGuidanceForDraft = (
1135 targetDraftKey: string,
1136 update: (items: PendingGuidance[]) => PendingGuidance[],
1137 ) => {
1138 if (targetDraftKey === activeDraftKeyRef.current) {
1139 const next = update(pendingGuidanceRef.current);
1140 pendingGuidanceRef.current = next;
1141 setPendingGuidance(next);
1142 return;
1143 }
1144 const draft = cloneComposerDraft(draftsBySessionRef.current[targetDraftKey] ?? emptyComposerDraft());
1145 draft.pendingGuidance = update(draft.pendingGuidance);
1146 draftsBySessionRef.current[targetDraftKey] = draft;
1147 };
1148
1149 const updateGuidanceSendingIdForDraft = (targetDraftKey: string, next: string | null) => {
1150 if (targetDraftKey === activeDraftKeyRef.current) {
1151 guidanceSendingIdRef.current = next;
1152 setGuidanceSendingId(next);
1153 return;
1154 }
1155 const draft = cloneComposerDraft(draftsBySessionRef.current[targetDraftKey] ?? emptyComposerDraft());
1156 draft.guidanceSendingId = next;
1157 draftsBySessionRef.current[targetDraftKey] = draft;
1158 };
1159
1160 const updatePendingPasteForDraft = (targetDraftKey: string, delta: number) => {
1161 if (targetDraftKey === activeDraftKeyRef.current) {
1162 const next = Math.max(0, pendingPasteRef.current + delta);
1163 pendingPasteRef.current = next;
1164 setPendingPaste(next);
1165 return;
1166 }
1167 const draft = cloneComposerDraft(draftsBySessionRef.current[targetDraftKey] ?? emptyComposerDraft());
1168 draft.pendingPaste = Math.max(0, draft.pendingPaste + delta);
1169 draftsBySessionRef.current[targetDraftKey] = draft;
1170 };
1171
1172 const updateSubmittingForDraft = (targetDraftKey: string, next: boolean, kind: "message" | "compact" = "message") => {
1173 if (targetDraftKey === activeDraftKeyRef.current) {
1174 submittingRef.current = next ? kind : false;
1175 setSubmission(next ? kind : false);
1176 return;
1177 }
1178 const draft = cloneComposerDraft(draftsBySessionRef.current[targetDraftKey] ?? emptyComposerDraft());
1179 draft.submitting = next ? kind : false;
1180 draftsBySessionRef.current[targetDraftKey] = draft;
1181 };
1182
1183 const draftIsSubmitting = (targetDraftKey: string): boolean =>
1184 targetDraftKey === activeDraftKeyRef.current
1185 ? Boolean(submittingRef.current)
1186 : Boolean(draftsBySessionRef.current[targetDraftKey]?.submitting);
1187
1188 const draftHasPendingPaste = (targetDraftKey: string): boolean =>
1189 targetDraftKey === activeDraftKeyRef.current
1190 ? pendingPasteRef.current > 0
1191 : (draftsBySessionRef.current[targetDraftKey]?.pendingPaste ?? 0) > 0;
1192
1193 useLayoutEffect(() => {
1194 const previousKey = activeDraftKeyRef.current;
1195 if (previousKey === draftKey) return;
1196 draftsBySessionRef.current[previousKey] = snapshotComposerDraft();
1197 draftActivationEpochRef.current += 1;
1198 activeDraftKeyRef.current = draftKey;
1199 setGuidanceDraftKey(draftKey);
1200 restoreComposerDraft(draftsBySessionRef.current[draftKey] ?? emptyComposerDraft());
1201 }, [draftKey]);
1202
1203 const loadedPersistentDraftIdentityRef = useRef<string | null>(null);
1204 const persistedSnapshotByDraftRef = useRef<Record<string, string>>({});
1205 useLayoutEffect(() => {
1206 if (!persistentDraft) return;
1207 const identity = `${draftKey}:${persistentDraft.draftId}:${persistentDraft.generation}`;
1208 if (loadedPersistentDraftIdentityRef.current === identity) {
1209 // The external store may add a background attachment or regenerated
1210 // preview. Project fields without resetting cursor/menu/IME state.
1211 if (!persistentDraft.onPatch || JSON.stringify(persistentSnapshot(snapshotComposerDraft())) === JSON.stringify(persistentDraft.initial)) return;
1212 const content = persistentDraft.initial;
1213 restoringContent.current = true;
1214 textRef.current = content.text; setText(content.text);
1215 invocationsRef.current = content.invocations; setInvocations(content.invocations);
1216 attachmentsRef.current = content.attachments; setAttachments(content.attachments);
1217 workspaceRefsRef.current = content.workspaceRefs; setWorkspaceRefs(content.workspaceRefs);
1218 pastedBlocksRef.current = content.pastedBlocks; setPastedBlocks(content.pastedBlocks);
1219 openPastedLabelsRef.current = content.openPastedLabels; setOpenPastedLabels(content.openPastedLabels);
1220 sessionRefsRef.current = content.sessionRefs; setSessionRefs(content.sessionRefs);
1221 selectedTextRefsRef.current = content.selectedTextRefs; setSelectedTextRefs(content.selectedTextRefs);
1222 restoringContent.current = false;
1223 return;
1224 }
1225 loadedPersistentDraftIdentityRef.current = identity;
1226 const next = persistentComposerDraft(persistentDraft.initial);
1227 draftsBySessionRef.current[draftKey] = next;
1228 persistedSnapshotByDraftRef.current[draftKey] = JSON.stringify(persistentSnapshot(next));
1229 restoreComposerDraft(next);
1230 }, [draftKey, persistentDraft?.draftId, persistentDraft?.generation, persistentDraft?.initial]);
1231
1232 const persistentSnapshotForDraft = (targetDraftKey: string): PersistentComposerDraft => (
1233 targetDraftKey === activeDraftKeyRef.current
1234 ? persistentSnapshot(snapshotComposerDraft())
1235 : persistentSnapshot(draftsBySessionRef.current[targetDraftKey] ?? emptyComposerDraft())
1236 );
1237
1238 const publishPersistentDraft = (targetDraftKey: string) => {
1239 const target = persistentTargetsByDraftRef.current[targetDraftKey];
1240 if (!target || target.onPatch) return;
1241 const snapshot = persistentSnapshotForDraft(targetDraftKey);
1242 const serialized = JSON.stringify(snapshot);
1243 if (persistedSnapshotByDraftRef.current[targetDraftKey] === serialized) return;
1244 persistedSnapshotByDraftRef.current[targetDraftKey] = serialized;
1245 target.onChange(target.draftId, target.generation, snapshot);
1246 };
1247
1248 const trackPersistentTask = <T,>(targetDraftKey: string, promise: Promise<T>): Promise<T> => {
1249 const target = persistentTargetsByDraftRef.current[targetDraftKey];
1250 return target?.trackTask ? target.trackTask(target.draftId, target.generation, promise) : promise;
1251 };
1252
1253 const trackInputTask = <T,>(targetDraftKey: string, promise: Promise<T>): Promise<T> => {
1254 // Cover the whole accepted operation, including target capture, clipboard
1255 // reads and native fallback timers, before any async result can yield to send.
1256 updatePendingPasteForDraft(targetDraftKey, 1);
1257 const task = promise.finally(() => updatePendingPasteForDraft(targetDraftKey, -1));
1258 const target = persistentTargetsByDraftRef.current[targetDraftKey];
1259 return target?.trackTask ? target.trackTask(target.draftId, target.generation, task, true) : task;
1260 };
1261
1262 const applyInboxQueue = useCallback((items: PendingGuidance[]) => updatePendingGuidanceForDraft(draftKey, () => items), [draftKey]);
1263 const collapseInboxQueue = useCallback(() => setGuidanceExpanded(false), []);
1264 const refreshInboxQueue = useCallback(() => setGuidanceRetryNonce((value) => value + 1), []);
1265 const { snapshot: inboxSnapshot, acceptSnapshot: acceptInboxSnapshot } = useComposerInboxRefresh(tabId, draftKey, guidanceDraftKey, inboxSessionKey, guidanceQueuePreviewKey, guidanceRetryNonce, running, applyInboxQueue, collapseInboxQueue, refreshInboxQueue, runtimeState.state?.revision);
1266 const queueScope = JSON.stringify([draftKey, pendingKey]);
1267 const queueEditing = queueEditingScope === queueScope;
1268 const onQueueEditingChange = useCallback((active: boolean) => setQueueEditingScope(active ? queueScope : null), [queueScope]);
1269
1270 useEffect(() => {
1271 return () => {
1272 draftsBySessionRef.current[activeDraftKeyRef.current] = snapshotComposerDraft();
1273 };
1274 }, []);
1275
1276 const clearNativeClipboardPasteTimer = () => {
1277 if (nativeClipboardPasteTimerRef.current === null) return;
1278 window.clearTimeout(nativeClipboardPasteTimerRef.current);
1279 nativeClipboardPasteTimerRef.current = null;
1280 nativeClipboardPasteCompletionRef.current?.();
1281 nativeClipboardPasteCompletionRef.current = null;
1282 };
1283
1284 useEffect(() => () => clearNativeClipboardPasteTimer(), []);
1285
1286 useEffect(() => {
1287 const wasRunning = wasRunningByDraftRef.current[draftKey] ?? running;
1288 if (wasRunning && !running) {
1289 setGuidanceExpanded(false);
1290 if (text.trim() === "") {
1291 pastedBlocksRef.current = [];
1292 setPastedBlocks([]);
1293 setOpenPastedLabels([]);
1294 }
1295 }
1296 wasRunningByDraftRef.current[draftKey] = running;
1297 }, [draftKey, running, text]);
1298
1299 // Legacy/local preview items still need the frontend-owned send path; durable items
1300 // are dispatched and acknowledged exactly once by the Controller after TurnDone.
1301 // The draft-key guard prevents this compatibility path from using a newly selected session's onSend.
1302 useEffect(() => {
1303 // Never auto-send guidance while a decision surface owns the footer —
1304 // the draft must stay intact until the user finishes the decision.
1305 if (guidanceDraftKey !== draftKey || running || submitDisabled || suspendedByDecision) return;
1306 const next = pendingGuidance[0];
1307 if (next?.id.startsWith("local-")) void sendQueuedGuidance(next, draftKey);
1308 }, [draftKey, guidanceDraftKey, guidanceRetryNonce, running, submitDisabled, pendingGuidance, suspendedByDecision]);
1309
1310 useEffect(() => {
1311 if (guidanceExpanded && pendingGuidance.length <= 2) setGuidanceExpanded(false);
1312 }, [guidanceExpanded, pendingGuidance.length]);
1313
1314 // --- slash commands ---
1315 const commands = useComposerCommandCatalog(commandCatalog, ready ?? false, cwd, running, workspaceScopeKey ?? "");
1316 useEffect(() => {
1317 onInvocationMetadataChange?.(Object.fromEntries(
1318 commands
1319 .filter(commandUsesStructuredInvocation)
1320 .map((command) => [command.name, {
1321 kind: command.kind === "subagent" ? "subagent" : "skill",
1322 color: command.color,
1323 }]),
1324 ));
1325 }, [commands, onInvocationMetadataChange]);
1326
1327 const slashText = useMemo(() => text.replace(/[\r\n]+$/u, ""), [text]);
1328 const plainSlashQuery = useMemo(() => slashQueryAt(slashText, {
1329 start: Math.min(plainSelection.start, slashText.length),
1330 end: Math.min(plainSelection.end, slashText.length),
1331 }), [plainSelection, slashText]);
1332 const activeSlashQuery = invocations.length > 0 ? richSlashQuery : plainSlashQuery;
1333 const slashQuery = activeSlashQuery?.query ?? null;
1334 const slashMatches = useMemo(
1335 () => slashQuery === null
1336 ? []
1337 : sortSlashCommandsForMenu(commands.filter((c) => c.name.toLowerCase().includes(slashQuery))),
1338 [slashQuery, commands],
1339 );
1340 const slashCommandAtStart = Boolean(
1341 activeSlashQuery
1342 && invocations.length === 0
1343 && slashText.slice(0, activeSlashQuery.from).trim() === "",
1344 );
1345 const slashCommandDisabled = useCallback(
1346 (command: CommandInfo) => !commandAvailableAtSlashPosition(command, slashCommandAtStart),
1347 [slashCommandAtStart],
1348 );
1349 const slashSelectableIndices = useMemo(
1350 () => slashMatches.flatMap((command, index) => slashCommandDisabled(command) ? [] : [index]),
1351 [slashCommandDisabled, slashMatches],
1352 );
1353 const slashQueryKey = activeSlashQuery
1354 ? `${activeSlashQuery.from}:${activeSlashQuery.to}:${activeSlashQuery.query}`
1355 : "";
1356
1357 // --- slash argument completion ("/cmd <args>") --- mirrors the CLI: once past
1358 // the command word, the backend suggests sub-commands (/skill → list/show/…,
1359 // /mcp → add/remove, /model → refs). Fetched from app.SlashArgs. Debounced
1360 // by 120ms so rapid typing doesn't flood the backend with IPC calls — the
1361 // menu only updates after the user pauses.
1362 const [argRes, setArgRes] = useState<SlashArgsResult | null>(null);
1363 const debounceRef = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
1364 useEffect(() => {
1365 if (invocations.length > 0 || !slashText.startsWith("/") || !/\s/.test(slashText)) {
1366 setArgRes(null);
1367 return;
1368 }
1369 let live = true;
1370 clearTimeout(debounceRef.current);
1371 debounceRef.current = setTimeout(() => {
1372 app
1373 .SlashArgs(slashText)
1374 .then((r) => {
1375 if (!live) return;
1376 // Drop suggestions that wouldn't change the input — the token is already
1377 // fully typed (e.g. "/skill list" offering "list"). Otherwise the menu
1378 // lingers on a complete command and Enter keeps "accepting" a no-op
1379 // instead of sending. (Defense-in-depth: the backend filters these too.)
1380 // r.items can arrive as null (an empty Go slice serializes to JSON null),
1381 // so guard before filtering — otherwise the throw is swallowed and the
1382 // stale menu from the previous keystroke lingers (the /skill list bug).
1383 const items = asArray(r?.items);
1384 const from = r?.from ?? 0;
1385 const useful = items.filter((it) => slashText.slice(0, from) + it.insert !== slashText);
1386 setArgRes(useful.length > 0 ? { items: useful, from } : null);
1387 setActive(0);
1388 })
1389 .catch(() => {});
1390 }, 120);
1391 return () => {
1392 live = false;
1393 clearTimeout(debounceRef.current);
1394 };
1395 }, [invocations.length, slashText]);
1396
1397 // --- @ file references (token at the end of the text) ---
1398 // atRaw is everything after a trailing "@token"; atDir is its path up to the
1399 // last "/", atFrag the part after. The menu lists one directory level (atDir)
1400 // and filters by atFrag — descending one level per pick.
1401 const activeAtToken = useMemo(() => activeFileReferenceToken(text), [text]);
1402 const atRaw = activeAtToken?.raw ?? null;
1403 const atDir = activeAtToken?.dir ?? "";
1404 const atFrag = activeAtToken?.frag ?? "";
1405 const pastChatToken = useMemo(() => activePastChatToken(text), [text]);
1406 const pastChatTokenQuery = pastChatToken?.query ?? null;
1407
1408 const [entries, setEntries] = useState<DirEntry[]>([]);
1409 const [searchEntries, setSearchEntries] = useState<DirEntry[]>([]);
1410 const dirCache = useRef<Record<string, DirEntry[]>>({});
1411 const searchCache = useRef<Record<string, FileRefSearchCacheEntry>>({});
1412 const fileRefTabId = tabId ?? "";
1413 const fileRefScopeKey = workspaceScopeKey ?? `${fileRefTabId}\u0000${cwd ?? ""}`;
1414
1415 const clearFileRefState = useCallback(() => {
1416 dirCache.current = {};
1417 searchCache.current = {};
1418 setEntries([]);
1419 setSearchEntries([]);
1420 setShowPastChats(false);
1421 setPastChats([]);
1422 setPastChatQuery("");
1423 setLoadingPastChats(false);
1424 setActive(0);
1425 setDismissed(false);
1426 }, []);
1427
1428 // Controller/session changes invalidate @ mention state even when tab and
1429 // workspace identities stay the same (saved-session rebinds and rebuilds).
1430 const prevFileRefScopeRef = useRef(fileRefScopeKey);
1431 useEffect(() => {
1432 if (prevFileRefScopeRef.current === fileRefScopeKey) return;
1433 prevFileRefScopeRef.current = fileRefScopeKey;
1434 clearFileRefState();
1435 }, [clearFileRefState, fileRefScopeKey]);
1436
1437 const prevFileRefRefreshKeyRef = useRef(fileRefRefreshKey);
1438 useEffect(() => {
1439 if (prevFileRefRefreshKeyRef.current === fileRefRefreshKey) return;
1440 prevFileRefRefreshKeyRef.current = fileRefRefreshKey;
1441 clearFileRefState();
1442 }, [clearFileRefState, fileRefRefreshKey]);
1443
1444 useEffect(() => {
1445 if (atRaw === null) return;
1446 const cached = dirCache.current[atDir];
1447 if (cached) {
1448 setEntries(cached);
1449 } else {
1450 setEntries([]);
1451 }
1452 let live = true;
1453 app
1454 .ListDirForTarget(bridgeTarget, unescapeRefPath(atDir))
1455 .then((es) => {
1456 const list = asArray(es);
1457 if (!live) return;
1458 dirCache.current[atDir] = list;
1459 setEntries(list);
1460 })
1461 .catch(() => {});
1462 return () => {
1463 live = false;
1464 };
1465 // Re-fetch when the menu opens, the directory level changes, or the
1466 // workspace tree refreshes; cached data is only a fast first paint.
1467 }, [atRaw === null, atDir, fileRefRefreshKey, fileRefScopeKey, bridgeTargetKey]);
1468 useEffect(() => {
1469 if (atRaw === null || atDir !== "" || atFrag === "") {
1470 setSearchEntries([]);
1471 return;
1472 }
1473 const cached = searchCache.current[atFrag];
1474 if (cached) {
1475 setSearchEntries(cached.entries);
1476 if (Date.now() - cached.cachedAt < FILE_REF_SEARCH_CACHE_TTL_MS) return;
1477 } else {
1478 setSearchEntries([]);
1479 }
1480 let live = true;
1481 app
1482 .SearchFileRefsForTarget(bridgeTarget, atFrag)
1483 .then((es) => {
1484 const list = asArray(es);
1485 if (!live) return;
1486 searchCache.current[atFrag] = { entries: list, cachedAt: Date.now() };
1487 setSearchEntries(list);
1488 })
1489 .catch(() => {});
1490 return () => {
1491 live = false;
1492 };
1493 }, [atRaw === null, atDir, atFrag, fileRefRefreshKey, fileRefScopeKey, bridgeTargetKey]);
1494 const atMatches = useMemo(
1495 () => {
1496 if (atRaw === null) return [];
1497 return filterAtMatches(entries, searchEntries, atFrag);
1498 },
1499 [atRaw, atFrag, entries, searchEntries],
1500 );
1501
1502 // Unified menu item model for the @ menu. "past:chats" is a real selectable
1503 // item (kind "pastChats"), not an active===0 special case.
1504 type AtMenuItem =
1505 | { kind: "pastChats" }
1506 | { kind: "file"; entry: DirEntry };
1507
1508 const includePastChatsItem = atRaw !== null && atDir === "" && (atFrag === "" || PAST_CHATS_MENU_ITEM.startsWith(atFrag));
1509
1510 const atMenuItems = useMemo<AtMenuItem[]>(
1511 () => [
1512 ...(includePastChatsItem ? [{ kind: "pastChats" as const }] : []),
1513 ...atMatches.map((entry) => ({ kind: "file" as const, entry })),
1514 ],
1515 [includePastChatsItem, atMatches],
1516 );
1517 const atMenuItemKey = useCallback(
1518 (item: AtMenuItem) => item.kind === "pastChats" ? "past:chats" : (item.entry.isDir ? "d:" : "f:") + (item.entry.path || item.entry.name),
1519 [],
1520 );
1521
1522 // --- which menu (if any) is open --- (slash command names win; then slash
1523 // arguments; then @-refs — they're rarely valid at once)
1524 const menuMode: "slash" | "slasharg" | "at" | "pastChats" | null =
1525 directPastChats
1526 ? "pastChats"
1527 : slashMatches.length > 0 && !dismissed
1528 ? "slash"
1529 : argRes && argRes.items.length > 0 && !dismissed
1530 ? "slasharg"
1531 : atRaw !== null && !dismissed
1532 ? "at"
1533 : null;
1534 const menuOpen = menuMode !== null;
1535 useLayoutEffect(() => {
1536 if (!menuOpen) return;
1537 const anchor = composerWrapRef.current;
1538 if (!anchor) return;
1539 return observeComposerMenuViewport(anchor);
1540 }, [menuOpen]);
1541 const countBase =
1542 menuMode === "slash"
1543 ? slashMatches.length
1544 : menuMode === "slasharg"
1545 ? argRes!.items.length
1546 : menuMode === "at"
1547 ? atMenuItems.length
1548 : menuMode === "pastChats"
1549 ? pastChats.length
1550 : 0;
1551
1552 // Reset highlight + un-dismiss whenever the active query changes.
1553 useEffect(() => {
1554 setActive(0);
1555 setDismissed(false);
1556 }, [slashQueryKey, atRaw, pastChatTokenQuery]);
1557
1558 useEffect(() => {
1559 if (transientDismissSignal === undefined || transientDismissSignal === lastTransientDismissSignal.current) return;
1560 lastTransientDismissSignal.current = transientDismissSignal;
1561 setDismissed(true);
1562 }, [transientDismissSignal]);
1563
1564 const takeSelfDispatchedGuidance = useCallback((text: string, targetDraftKey: string): boolean => {
1565 const selfDispatched = selfDispatchedGuidanceByDraftRef.current[targetDraftKey] ?? [];
1566 const idx = selfDispatched.findIndex((queued) => guidanceTextMatches(queued, text));
1567 if (idx < 0) return false;
1568 selfDispatched.splice(idx, 1);
1569 if (selfDispatched.length === 0) delete selfDispatchedGuidanceByDraftRef.current[targetDraftKey];
1570 return true;
1571 }, []);
1572
1573 useEffect(() => {
1574 if (guidanceDraftKey !== draftKey || !guidanceConsumedKey) return;
1575 if (guidanceConsumedKey === lastGuidanceConsumedKeyByDraftRef.current[draftKey]) return;
1576 lastGuidanceConsumedKeyByDraftRef.current[draftKey] = guidanceConsumedKey;
1577 const consumed = (guidanceConsumedText ?? "").trim();
1578 if (guidanceConsumedItemId) {
1579 guidanceReceiptTrackerRef.current?.recordConsumed(draftKey, guidanceConsumedItemId);
1580 }
1581 if (!guidanceConsumedItemId && consumed && takeSelfDispatchedGuidance(consumed, draftKey)) return;
1582 updatePendingGuidanceForDraft(draftKey, (items) => {
1583 if (items.length === 0) return items;
1584 const byID = guidanceConsumedItemId
1585 ? items.findIndex((item) => item.id === guidanceConsumedItemId)
1586 : -1;
1587 const idx = guidanceConsumedItemId ? byID : consumed
1588 ? items.findIndex((item) => guidanceTextMatches(item.submitText, consumed) || guidanceTextMatches(item.text, consumed))
1589 : -1;
1590 // Only remove on a real match. Steer notices also fire for guidance this
1591 // client never queued (another window, bot bridge, turn-end flush) —
1592 // falling back to dropping items[0] silently deleted unrelated queued
1593 // guidance (#6238).
1594 if (idx < 0) return items;
1595 return items.filter((_, index) => index !== idx);
1596 });
1597 }, [draftKey, guidanceDraftKey, guidanceConsumedKey, guidanceConsumedItemId, guidanceConsumedText, takeSelfDispatchedGuidance]);
1598
1599 // When the @ trigger disappears (user deleted the @), close the past:chats
1600 // sub-menu and reset related state. Without this, showPastChats can outlive
1601 // the @ token and leave the session list visible with no way to dismiss it.
1602 useEffect(() => {
1603 if (menuMode !== "at" && menuMode !== "pastChats" && showPastChats) {
1604 setShowPastChats(false);
1605 setPastChatQuery("");
1606 setActive(0);
1607 }
1608 }, [menuMode]);
1609
1610 useEffect(() => {
1611 if (menuMode && menuMode !== "pastChats") setContentMenuOpen(false);
1612 }, [menuMode]);
1613
1614 // A starting run closes the transient content surfaces. Without this the
1615 // popover state survives the run (its open prop gates on !running) and the
1616 // menu would pop back unprompted the moment the turn finishes.
1617 useEffect(() => {
1618 if (!running) return;
1619 setContentMenuOpen(false);
1620 setDirectPastChats(false);
1621 setShowPastChats(false);
1622 setPastChatQuery("");
1623 if (pastChatToken) setDismissed(true);
1624 }, [pastChatToken, running]);
1625
1626 const resetPromptHistoryNavigation = () => {
1627 if (historyIndexRef.current === -1) return;
1628 historyIndexRef.current = -1;
1629 setHistoryIndex(-1);
1630 };
1631
1632 const syncPromptHistoryGeneration = () => {
1633 const nextGeneration = cacheGeneration();
1634 if (historyGenerationRef.current === nextGeneration) return;
1635 historyGenerationRef.current = nextGeneration;
1636 historyEntriesRef.current = [];
1637 historyLoadRef.current = null;
1638 historyIndexRef.current = -1;
1639 setHistoryIndex(-1);
1640 };
1641
1642 const ensurePromptHistoryIndex = async (index: number): Promise<boolean> => {
1643 if (index < historyEntriesRef.current.length) return true;
1644 if (historyLoadRef.current) await historyLoadRef.current;
1645 while (index >= historyEntriesRef.current.length) {
1646 let loaded = 0;
1647 const task = loadOlder().then((entries) => {
1648 loaded = entries.length;
1649 if (loaded > 0) {
1650 historyEntriesRef.current = historyEntriesRef.current.concat(entries);
1651 }
1652 });
1653 historyLoadRef.current = task;
1654 await task;
1655 historyLoadRef.current = null;
1656 if (loaded === 0) return index < historyEntriesRef.current.length;
1657 }
1658 return true;
1659 };
1660
1661 const prefetchPromptHistoryTail = () => {
1662 if (historyLoadRef.current) return;
1663 void ensurePromptHistoryIndex(historyEntriesRef.current.length);
1664 };
1665
1666 const focusComposerInput = () => {
1667 if (invocationsRef.current.length > 0) richInputRef.current?.focus();
1668 else taRef.current?.focus();
1669 };
1670
1671 const requestActiveDraftFrame = (callback: () => void) => {
1672 const activationEpoch = draftActivationEpochRef.current;
1673 requestAnimationFrame(() => {
1674 if (draftActivationEpochRef.current !== activationEpoch) return;
1675 callback();
1676 });
1677 };
1678
1679 const getComposerSelection = () => {
1680 if (invocationsRef.current.length > 0) return richInputRef.current?.getSelection() ?? richSelection;
1681 const ta = taRef.current;
1682 const start = ta?.selectionStart ?? textRef.current.length;
1683 const end = ta?.selectionEnd ?? start;
1684 return { start: Math.min(start, end), end: Math.max(start, end) };
1685 };
1686
1687 const setComposerSelection = (start: number, end = start, afterInvocationId?: string) => {
1688 const nextSelection = { start, end, afterInvocationId };
1689 lastSelectionRef.current = { start, end };
1690 if (invocationsRef.current.length === 0) setPlainSelection(nextSelection);
1691 requestActiveDraftFrame(() => {
1692 if (invocationsRef.current.length > 0) {
1693 richInputRef.current?.setSelectionRange(start, end, afterInvocationId);
1694 return;
1695 }
1696 const ta = taRef.current;
1697 if (!ta) return;
1698 ta.focus();
1699 ta.setSelectionRange(start, end);
1700 });
1701 };
1702
1703 const focusComposerFromContentBlank = (event: ReactMouseEvent<HTMLDivElement>) => {
1704 if (event.target !== event.currentTarget || disabled || readOnly) return;
1705 event.preventDefault();
1706 setComposerSelection(textRef.current.length);
1707 };
1708
1709 const setTextCaretEnd = (next: string, trackEdit = true) => {
1710 const targetDraftKey = activeDraftKeyRef.current;
1711 const beforeEdit = trackEdit ? composerEditSnapshot(targetDraftKey) : null;
1712 textRef.current = next;
1713 setText(next);
1714 setComposerSelection(next.length);
1715 if (beforeEdit) {
1716 recordComposerEdit(
1717 targetDraftKey,
1718 beforeEdit,
1719 composerEditSnapshot(targetDraftKey, { start: next.length, end: next.length }),
1720 );
1721 }
1722 };
1723
1724 const setTextForDraft = (targetDraftKey: string, next: string) => {
1725 if (targetDraftKey === activeDraftKeyRef.current) {
1726 setTextCaretEnd(next);
1727 return;
1728 }
1729 const draft = cloneComposerDraft(draftsBySessionRef.current[targetDraftKey] ?? emptyComposerDraft());
1730 draft.text = next;
1731 draftsBySessionRef.current[targetDraftKey] = draft;
1732 };
1733
1734 const rememberCaret = () => {
1735 if (invocationsRef.current.length > 0) {
1736 const selection = richInputRef.current?.getSelection();
1737 if (selection) lastSelectionRef.current = { start: selection.start, end: selection.end };
1738 return;
1739 }
1740 const ta = taRef.current;
1741 if (!ta) return;
1742 const nextSelection = { start: ta.selectionStart ?? text.length, end: ta.selectionEnd ?? text.length };
1743 lastSelectionRef.current = nextSelection;
1744 setPlainSelection(nextSelection);
1745 };
1746
1747 const insertNewlineAtCaret = () => {
1748 const selection = getComposerSelection();
1749 const targetDraftKey = activeDraftKeyRef.current;
1750 const beforeEdit = composerEditSnapshot(targetDraftKey, selection);
1751 const updated = insertComposerNewline(textRef.current, invocationsRef.current, selection);
1752 textRef.current = updated.text;
1753 invocationsRef.current = updated.invocations;
1754 setText(updated.text);
1755 setInvocations(updated.invocations);
1756 const caret = selection.start + 1;
1757 setComposerSelection(caret);
1758 recordComposerEdit(
1759 targetDraftKey,
1760 beforeEdit,
1761 composerEditSnapshot(targetDraftKey, { start: caret, end: caret }),
1762 );
1763 };
1764
1765 const insertTextAtCaret = (snippet: string) => {
1766 const selection = getComposerSelection();
1767 const targetDraftKey = activeDraftKeyRef.current;
1768 const beforeEdit = composerEditSnapshot(targetDraftKey, selection);
1769 const start = selection.start;
1770 const end = selection.end;
1771 const current = textRef.current;
1772 const before = current.slice(0, start);
1773 const after = current.slice(end);
1774 const leading = before.length === 0 || before.endsWith("\n\n") ? "" : before.endsWith("\n") ? "\n" : "\n\n";
1775 const body = snippet.trimEnd();
1776 const trailing = after.length === 0 ? "\n" : after.startsWith("\n") ? "" : "\n\n";
1777 const inserted = leading + body + trailing;
1778 const pos = before.length + inserted.length;
1779 const updated = replaceInvocationTextRange(current, invocationsRef.current, start, end, inserted);
1780 textRef.current = updated.text;
1781 invocationsRef.current = updated.invocations;
1782 setText(updated.text);
1783 setInvocations(updated.invocations);
1784 setComposerSelection(pos);
1785 recordComposerEdit(
1786 targetDraftKey,
1787 beforeEdit,
1788 composerEditSnapshot(targetDraftKey, { start: pos, end: pos }),
1789 );
1790 };
1791
1792 const replaceComposerText = (next: string) => {
1793 clearComposerEditHistory(activeDraftKeyRef.current);
1794 clearAttachments();
1795 setWorkspaceRefs([]);
1796 setSessionRefs([]);
1797 selectedTextRefsRef.current = [];
1798 setSelectedTextRefs([]);
1799 pastedBlocksRef.current = [];
1800 setPastedBlocks([]);
1801 setOpenPastedLabels([]);
1802 setTextCaretEnd(next, false);
1803 };
1804
1805 const addWorkspaceReference = (ref: WorkspaceReference) => {
1806 setWorkspaceRefs((prev) => {
1807 const key = workspaceReferenceKey(ref);
1808 if (prev.some((item) => workspaceReferenceKey(item) === key)) return prev;
1809 const next = [...prev, ref];
1810 workspaceRefsRef.current = next;
1811 return next;
1812 });
1813 requestActiveDraftFrame(focusComposerInput);
1814 };
1815
1816 useEffect(() => {
1817 if (!insertRequest || insertRequest.id === consumedInsertIdByDraftRef.current[draftKey]) return;
1818 consumedInsertIdByDraftRef.current[draftKey] = insertRequest.id;
1819 if (insertRequest.mode === "replace") {
1820 replaceComposerText(insertRequest.text);
1821 return;
1822 }
1823 if (insertRequest.mode === "prefix") {
1824 const prefix = `${insertRequest.text.trimEnd()} `;
1825 const current = textRef.current;
1826 setTextCaretEnd(current ? prefix + current : prefix);
1827 return;
1828 }
1829 const ref = parseWorkspaceReference(insertRequest.text);
1830 if (ref) {
1831 if (!attachmentInputEnabled) return;
1832 addWorkspaceReference(ref);
1833 return;
1834 }
1835 insertTextAtCaret(insertRequest.text);
1836 }, [draftKey, insertRequest]);
1837
1838 useEffect(() => {
1839 if (!selectedTextRequest || selectedTextRequest.id === consumedSelectedTextIdByDraftRef.current[draftKey]) return;
1840 consumedSelectedTextIdByDraftRef.current[draftKey] = selectedTextRequest.id;
1841 const normalized = normalizeSelectedText(selectedTextRequest.text);
1842 if (!normalized.text) return;
1843 if (normalized.truncated) showToast(t("composer.selectedTextTruncated"), "warn");
1844 const path = selectedTextRequest.path;
1845 const source = selectedTextRequest.source;
1846 const duplicate = selectedTextRefsRef.current.some(
1847 (reference) => reference.text === normalized.text
1848 && (reference.path ?? "") === (path ?? "")
1849 && (reference.source ?? "") === (source ?? ""),
1850 );
1851 if (!duplicate) {
1852 const next = [
1853 ...selectedTextRefsRef.current,
1854 {
1855 id: `${path ? "code" : source === "terminal" ? "terminal" : "chat"}-selection-${selectedTextRequest.id}`,
1856 text: normalized.text,
1857 ...(path ? { path } : {}),
1858 ...(source ? { source } : {}),
1859 },
1860 ];
1861 selectedTextRefsRef.current = next;
1862 setSelectedTextRefs(next);
1863 }
1864 requestActiveDraftFrame(focusComposerInput);
1865 }, [draftKey, selectedTextRequest, showToast, t]);
1866
1867 const expandPastedBlocks = (displayText: string, blocks = pastedBlocksRef.current): string => {
1868 let expanded = displayText;
1869 for (const block of blocks) {
1870 if (expanded.includes(block.label)) {
1871 expanded = expanded.split(block.label).join(renderPastedBlock(block));
1872 }
1873 }
1874 return expanded;
1875 };
1876
1877 const rememberAttachment = (path: string, key: AttachmentDedupKey) => {
1878 attachmentDedupRef.current.add(key.hash, key.source);
1879 attachmentDedupKeysRef.current[path] = key;
1880 };
1881
1882 const forgetAttachment = (path: string) => {
1883 const key = attachmentDedupKeysRef.current[path];
1884 if (key) {
1885 attachmentDedupRef.current.forget(key.hash, key.source);
1886 delete attachmentDedupKeysRef.current[path];
1887 }
1888 };
1889
1890 const clearAttachments = () => {
1891 attachmentsRef.current = [];
1892 setAttachments([]);
1893 attachmentDedupRef.current.clear();
1894 attachmentDedupKeysRef.current = {};
1895 };
1896
1897 const removeAttachment = (path: string) => {
1898 forgetAttachment(path);
1899 setAttachments(attachmentsRef.current.filter((x) => x.path !== path));
1900 requestActiveDraftFrame(focusComposerInput);
1901 };
1902
1903 const attachmentSeenInDraft = (targetDraftKey: string, key: AttachmentDedupKey): boolean => {
1904 if (targetDraftKey === activeDraftKeyRef.current) return attachmentDedupRef.current.seen(key.hash, key.source);
1905 const draft = draftsBySessionRef.current[targetDraftKey];
1906 return draft ? draftHasAttachmentDedupKey(draft, key) : false;
1907 };
1908
1909 const addAttachmentToDraft = (targetDraftKey: string, attachment: Attachment, key: AttachmentDedupKey, owner?: PersistentComposerTarget): boolean => {
1910 if (owner?.isCurrent && !owner.isCurrent(owner.draftId, owner.generation)) return false;
1911 if (owner?.onPatch) {
1912 owner.onPatch(owner.draftId, owner.generation, content => ({ ...content, attachments: content.attachments.some(item => item.path === attachment.path) ? content.attachments : [...content.attachments, attachment] }));
1913 if (targetDraftKey === activeDraftKeyRef.current) rememberAttachment(attachment.path, key);
1914 return true;
1915 }
1916 if (targetDraftKey === activeDraftKeyRef.current) {
1917 if (attachmentDedupRef.current.seen(key.hash, key.source)) return false;
1918 rememberAttachment(attachment.path, key);
1919 const next = [...attachmentsRef.current, attachment];
1920 attachmentsRef.current = next;
1921 setAttachments(next);
1922 queueMicrotask(() => publishPersistentDraft(targetDraftKey));
1923 return true;
1924 }
1925 const draft = cloneComposerDraft(draftsBySessionRef.current[targetDraftKey] ?? emptyComposerDraft());
1926 if (draftHasAttachmentDedupKey(draft, key)) return false;
1927 draft.attachmentDedupKeys[attachment.path] = key;
1928 draft.attachments = [...draft.attachments, attachment];
1929 draftsBySessionRef.current[targetDraftKey] = draft;
1930 publishPersistentDraft(targetDraftKey);
1931 return true;
1932 };
1933
1934 const addWorkspaceReferenceToDraft = (targetDraftKey: string, ref: WorkspaceReference, owner?: PersistentComposerTarget) => {
1935 if (owner?.isCurrent && !owner.isCurrent(owner.draftId, owner.generation)) return;
1936 if (owner?.onPatch) {
1937 owner.onPatch(owner.draftId, owner.generation, content => ({ ...content, workspaceRefs: content.workspaceRefs.some(item => workspaceReferenceKey(item) === workspaceReferenceKey(ref)) ? content.workspaceRefs : [...content.workspaceRefs, ref] }));
1938 return;
1939 }
1940 if (targetDraftKey === activeDraftKeyRef.current) {
1941 addWorkspaceReference(ref);
1942 queueMicrotask(() => publishPersistentDraft(targetDraftKey));
1943 return;
1944 }
1945 const draft = cloneComposerDraft(draftsBySessionRef.current[targetDraftKey] ?? emptyComposerDraft());
1946 const key = workspaceReferenceKey(ref);
1947 if (draft.workspaceRefs.some((item) => workspaceReferenceKey(item) === key)) return;
1948 draft.workspaceRefs = [...draft.workspaceRefs, ref];
1949 draftsBySessionRef.current[targetDraftKey] = draft;
1950 publishPersistentDraft(targetDraftKey);
1951 };
1952
1953 const clearSubmittedDraft = (targetDraftKey: string) => {
1954 clearComposerEditHistory(targetDraftKey);
1955 if (targetDraftKey === activeDraftKeyRef.current) {
1956 textRef.current = "";
1957 setText("");
1958 invocationsRef.current = [];
1959 setInvocations([]);
1960 setRichSlashQuery(null);
1961 historyIndexRef.current = -1;
1962 setHistoryIndex(-1);
1963 clearAttachments();
1964 workspaceRefsRef.current = [];
1965 setWorkspaceRefs([]);
1966 sessionRefsRef.current = [];
1967 setSessionRefs([]);
1968 selectedTextRefsRef.current = [];
1969 setSelectedTextRefs([]);
1970 pastedBlocksRef.current = [];
1971 setPastedBlocks([]);
1972 openPastedLabelsRef.current = [];
1973 setOpenPastedLabels([]);
1974 savedTextRef.current = "";
1975 return;
1976 }
1977 const draft = cloneComposerDraft(draftsBySessionRef.current[targetDraftKey] ?? emptyComposerDraft());
1978 draft.text = "";
1979 draft.invocations = [];
1980 draft.attachments = [];
1981 draft.workspaceRefs = [];
1982 draft.pastedBlocks = [];
1983 draft.openPastedLabels = [];
1984 draft.sessionRefs = [];
1985 draft.selectedTextRefs = [];
1986 draft.attachmentDedupKeys = {};
1987 draft.historyIndex = -1;
1988 draft.savedText = "";
1989 draftsBySessionRef.current[targetDraftKey] = draft;
1990 };
1991
1992 const clearIntentCloseTimer = useCallback(() => {
1993 if (intentCloseTimerRef.current === null) return;
1994 window.clearTimeout(intentCloseTimerRef.current);
1995 intentCloseTimerRef.current = null;
1996 }, []);
1997
1998 // Hover timers only touch refs — no useCallback cross-deps (avoids TDZ on HMR).
1999 const clearHoverTimer = (timerRef: { current: number | null }) => {
2000 if (timerRef.current == null) return;
2001 window.clearTimeout(timerRef.current);
2002 timerRef.current = null;
2003 };
2004
2005 const closeIntentMenu = useCallback((afterClose?: () => void) => {
2006 clearIntentCloseTimer();
2007 clearHoverTimer(intentHoverTimerRef);
2008 setIntentMenuClosing(true);
2009 window.requestAnimationFrame(() => setIntentMenuOpen(false));
2010 const reduceMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
2011 intentCloseTimerRef.current = window.setTimeout(() => {
2012 intentCloseTimerRef.current = null;
2013 setIntentMenuClosing(false);
2014 afterClose?.();
2015 }, reduceMotion ? 0 : ANCHORED_POPOVER_CLOSE_MS);
2016 }, [clearIntentCloseTimer]);
2017
2018 useEffect(() => () => {
2019 clearIntentCloseTimer();
2020 clearHoverTimer(intentHoverTimerRef);
2021 }, [clearIntentCloseTimer]);
2022
2023 const onIntentHoverLeave = useCallback(() => {
2024 if (!creationChrome) return;
2025 clearHoverTimer(intentHoverTimerRef);
2026 if (!intentMenuOpen && !intentMenuClosing) return;
2027 intentHoverTimerRef.current = window.setTimeout(() => {
2028 intentHoverTimerRef.current = null;
2029 closeIntentMenu();
2030 }, 140);
2031 }, [closeIntentMenu, creationChrome, intentMenuClosing, intentMenuOpen]);
2032
2033 const onIntentPopoverEnter = useCallback(() => {
2034 if (!creationChrome) return;
2035 clearHoverTimer(intentHoverTimerRef);
2036 }, [creationChrome]);
2037
2038 const fileDedupKey = async (file: File): Promise<AttachmentDedupKey> => ({
2039 hash: await sha256(file),
2040 source: `file:${file.name}:${file.size}:${file.lastModified}`,
2041 });
2042
2043 const planModeOn = collaborationMode === "plan";
2044 const activeGoal = (goal ?? "").trim();
2045 const goalModeOn = collaborationMode === "goal";
2046 const warnImageInputFallback = useCallback((message?: string) => {
2047 const text = message ?? t("composer.imageInputUnsupported");
2048 showToast(text, "warn");
2049 }, [showToast, t]);
2050
2051 const followupDraftFingerprint = (key: string): string => composerDraftFingerprint(
2052 key === activeDraftKeyRef.current ? snapshotComposerDraft() : draftsBySessionRef.current[key] ?? emptyComposerDraft(),
2053 );
2054
2055 const submit = (guideCurrent = false) => trackPersistentTask(activeDraftKeyRef.current, performSubmit(guideCurrent));
2056 const performSubmit = async (guideCurrent = false, modelChoice?:ModelApplicationChoice) => {
2057 if (queueEditing) return;
2058 const queueOnly = running && (!guideCurrent || finishing || maintenanceActive);
2059 const submitDraftKey = activeDraftKeyRef.current;
2060 const submitPendingKey = pendingKey;
2061 const submitTabId = tabId;
2062 const ownsDraft = () => activeDraftKeyRef.current !== submitDraftKey || pendingKeyRef.current === submitPendingKey;
2063 if (draftIsSubmitting(submitDraftKey)) return;
2064 const unresolved = pendingFollowups.get(submitPendingKey);
2065 if (unresolved) {
2066 updateSubmittingForDraft(submitDraftKey, true);
2067 try {
2068 await confirmFollowup(app, unresolved);
2069 if (savedInput.target) await savedInput.settleSubmission(unresolved.key);
2070 if (ownsDraft() && pendingFollowups.get(submitPendingKey) === unresolved && followupDraftFingerprint(submitDraftKey) === unresolved.draft) clearSubmittedDraft(submitDraftKey);
2071 pendingFollowups.clear(submitPendingKey, unresolved);
2072 setGuidanceRetryNonce(value => value + 1);
2073 } catch {
2074 showToast(t("runtime.unconfirmed"), "warn");
2075 } finally {
2076 updateSubmittingForDraft(submitDraftKey, false);
2077 }
2078 return;
2079 }
2080 if (disabled || (!running && submitDisabled) || readOnly) return;
2081 const currentText = textRef.current;
2082 const rawDraft = trimInvocationDraft(currentText, invocationsRef.current);
2083 const typedGoalDraft = goalModeOn && !activeGoal && rawDraft.invocations.length === 0
2084 ? typedStructuredInvocationDraft(rawDraft.text, commands)
2085 : null;
2086 const trimmedDraft = typedGoalDraft ?? rawDraft;
2087 const trimmedText = trimmedDraft.text;
2088 if (draftHasPendingPaste(submitDraftKey)) return;
2089 if (!attachmentInputEnabled && (attachmentsRef.current.length > 0 || workspaceRefsRef.current.length > 0)) return;
2090 if (!imageInputEnabled && !imageUnderstandingEnabled && hasImageAttachments(attachmentsRef.current)) {
2091 warnImageInputFallback();
2092 }
2093 const currentAttachments = attachmentsRef.current;
2094 const currentWorkspaceRefs = workspaceRefsRef.current;
2095 const inlineInvocationCount = trimmedDraft.invocations.filter((invocation) => invocation.command.kind === "skill").length;
2096 const subagentInvocationCount = trimmedDraft.invocations.filter((invocation) => invocation.command.kind === "subagent").length;
2097 if (goalModeOn && !activeGoal && trimmedDraft.invocations.length > 0 && !trimmedText) {
2098 // Goal setup still needs task text when a structured invocation is
2099 // present. Attachments and workspace refs remain valid task-only input.
2100 setComposerPrompt(t("composer.goalInputRequired"));
2101 requestActiveDraftFrame(focusComposerInput);
2102 return;
2103 }
2104 if (!trimmedText && currentAttachments.length === 0 && currentWorkspaceRefs.length === 0 && inlineInvocationCount === 0) {
2105 if (goalModeOn && !activeGoal) {
2106 setComposerPrompt(t("composer.goalInputRequired"));
2107 requestActiveDraftFrame(focusComposerInput);
2108 } else if (subagentInvocationCount > 0) {
2109 setComposerPrompt(t("composer.subagentTaskRequired"));
2110 requestActiveDraftFrame(focusComposerInput);
2111 }
2112 return;
2113 }
2114 setComposerPrompt(null);
2115 const submittedDraft = followupDraftFingerprint(submitDraftKey);
2116 const currentSessionRefs = sessionRefsRef.current;
2117 const currentSelectedTextRefs = selectedTextRefsRef.current;
2118 const currentPastedBlocks = [...pastedBlocksRef.current];
2119 updateSubmittingForDraft(submitDraftKey, true,
2120 !goalModeOn && trimmedDraft.invocations.length === 0 && currentSessionRefs.length === 0 && isCompactCommand(expandPastedBlocks(trimmedText, currentPastedBlocks)) ? "compact" : "message");
2121 let submissionCapture: unknown;
2122 let submissionAttachmentTarget: string | undefined;
2123 let attachmentSubmissionId: string | undefined;
2124 let attachmentSubmit: Awaited<ReturnType<typeof loadAttachmentSubmit>> | undefined;
2125 // Captured for the outer catch: a transient submit failure still holds the
2126 // exact message (display and submit text) the user typed.
2127 let submittedDisplayText = "";
2128 let submittedSubmitText = "";
2129 let submittedStructured: StructuredInvocationSubmit | undefined;
2130 const holdTransientGuidance = createTransientGuidance({
2131 app, transientRetriesRef, pendingKeyRef, submitPendingKey, submitDraftKey, submitTabId,
2132 inboxSessionPath, submittedDraft, queueOnly, followupDraftFingerprint, clearSubmittedDraft,
2133 setGuidanceRetryNonce, showToast, t, locale,
2134 });
2135 try {
2136 submissionCapture = onCaptureSubmit?.(persistentSnapshot(snapshotComposerDraft()));
2137 if (onCaptureSubmit && !submissionCapture) return;
2138 await onPrepareSubmit?.(submissionCapture);
2139 if (bridgeTarget.kind === "session" && currentWorkspaceRefs.length > 0) {
2140 const { restoreExternalFolderReferences } = await loadAttachmentSubmit();
2141 await restoreExternalFolderReferences(app, bridgeTarget, currentWorkspaceRefs);
2142 }
2143 if (queueOnly && !submitPendingKey) throw new Error("reasonix_error:inbox_not_submitted");
2144 const target = running ? await captureStableInboxTarget(app, submitTabId || "", inboxSessionPath || "") : undefined;
2145 const orderedAttachments = sortComposerAttachments(currentAttachments);
2146 const refs = [
2147 ...currentWorkspaceRefs.map((ref) => formatWorkspaceReference(ref.path, ref.isDir)),
2148 ...orderedAttachments.map((a) => `@${a.path}`),
2149 ].join(" ");
2150 const displayRefs = [
2151 ...currentWorkspaceRefs.map((ref) => formatWorkspaceReference(ref.displayPath || ref.path, ref.isDir)),
2152 ...orderedAttachments.map(formatAttachmentDisplayReference),
2153 ...currentSelectedTextRefs.map(formatSelectionLabel),
2154 ].join(" ");
2155 const displayText = [trimmedText, displayRefs].filter(Boolean).join(trimmedText && displayRefs ? " " : "");
2156 submittedDisplayText = displayText;
2157 // PR-B: when past:chats refs are attached, prepend their formatted transcript
2158 // to submitText only (displayText stays unchanged so the user still sees their
2159 // original prompt in the input preview). With no refs we keep the original
2160 // submitText verbatim — no header, no rewording, byte-identical to pre-PR-B.
2161 const sessionContext = currentSessionRefs.length === 0 ? "" : await buildSessionContext(currentSessionRefs, t);
2162 const selectedTextContext = formatSelectedTextContext(currentSelectedTextRefs);
2163 const invocationText = serializeInvocationSubmit(trimmedText, trimmedDraft.invocations);
2164 const baseSubmitText = [expandPastedBlocks(invocationText, currentPastedBlocks), refs].filter(Boolean).join(" ");
2165 const submitBase = sessionContext ? `${sessionContext}${baseSubmitText}` : baseSubmitText;
2166 const submitText = [submitBase, selectedTextContext].filter(Boolean).join("\n\n");
2167 submittedSubmitText = submitText;
2168 const structuredInput = [expandPastedBlocks(trimmedText, currentPastedBlocks), refs].filter(Boolean).join(" ");
2169 let structured: StructuredInvocationSubmit | undefined = trimmedDraft.invocations.length > 0 ? {
2170 display: [invocationText, displayRefs].filter(Boolean).join(invocationText && displayRefs ? " " : ""),
2171 input: [sessionContext ? `${sessionContext}${structuredInput}` : structuredInput, selectedTextContext].filter(Boolean).join("\n\n"),
2172 invocations: invocationRequests(trimmedDraft.invocations),
2173 } satisfies StructuredInvocationSubmit : undefined;
2174 const stagedImages = orderedAttachments.filter((item) => item.draftId || item.recoveryPath);
2175 if (stagedImages.length > 0 && bridgeTarget.kind === "session") {
2176 attachmentSubmit = await loadAttachmentSubmit();
2177 const prepared = await attachmentSubmit.prepareImageSubmission(app, bridgeTarget, submitDraftKey, submittedDraft, stagedImages, structured, displayText, submitText);
2178 submissionAttachmentTarget = prepared.token;
2179 attachmentSubmissionId = prepared.submissionId;
2180 structured = prepared.structured;
2181 }
2182 submittedStructured = structured;
2183 // Repeated compaction asks the owner for its current operation receipt;
2184 // queueing it would unexpectedly start another compaction after this one.
2185 if (running && !(maintenanceActive && !structured && isCompactCommand(submitText))) {
2186 // An entity-only submit has an empty displayText (entities live
2187 // outside the text model); fall back to the serialized slash form so
2188 // the queue shows the invocation instead of silently dropping it
2189 // while clearSubmittedDraft wipes the composer.
2190 const guidanceText = displayText.trim() || (structured?.display.trim() ?? "");
2191 const guidanceSubmitText = submitText.trim();
2192 if (guidanceText) {
2193 if (!queueOnly && !localDurableGuidance && !target && onSteer) {
2194 try {
2195 await onSteer(guidanceSubmitText, submitTabId);
2196 clearSubmittedDraft(submitDraftKey);
2197 } catch (error) {
2198 showToast(formatInboxError(error, locale), "warn");
2199 }
2200 return;
2201 }
2202 // Durable follow-up: only clear the composer after a durable receipt.
2203 const receiptTracker = guidanceReceiptTrackerRef.current;
2204 receiptTracker?.start(submitDraftKey);
2205 let unresolvedRequest: PendingFollowup | undefined;
2206 let enqueueAttempted = false;
2207 try {
2208 const { enqueueComposerGuidance } = await import("../lib/inboxGuidanceSubmit");
2209 const request: PendingFollowup = { key: structured?.attachmentSubmissionId || `followup-${crypto.randomUUID()}`, target,
2210 tabId: submitTabId || "", display: guidanceText, submit: guidanceSubmitText, structured, draft: submittedDraft };
2211 if (queueOnly || target) {
2212 unresolvedRequest = request;
2213 pendingFollowups.set(submitPendingKey, request);
2214 }
2215 const enqueue = async () => {
2216 enqueueAttempted = true;
2217 const receipt = await enqueueComposerGuidance(app, request, queueOnly, turnId);
2218 if (receipt?.error) throw new Error(receipt.error);
2219 if (!receipt?.itemId) throw new Error("Follow-up receipt unconfirmed");
2220 return receipt;
2221 };
2222 const receipt = savedInput.target && submitTabId
2223 ? await sendPersistedComposer(submitTabId, guidanceText, guidanceSubmitText, request.key, enqueue, savedInput.target.revision, savedInput.target.draftId, "guidance")
2224 : await enqueue();
2225 const consumedBeforeReceipt = receiptTracker?.takeConsumed(submitDraftKey, receipt.itemId) ?? false;
2226 if (!consumedBeforeReceipt && !queueOnly && (receipt.disposition === "steer_accepted" || receipt.disposition === "queued_followup")) {
2227 updatePendingGuidanceForDraft(submitDraftKey, (items) => {
2228 const next = items.map((item) => receipt.paused ? { ...item, paused: true } : item);
2229 if (next.some((item) => item.id === receipt.itemId)) return next;
2230 return [...next, {
2231 id: receipt.itemId,
2232 text: guidanceText.slice(0, 120),
2233 submitText: "",
2234 intent: receipt.disposition === "steer_accepted" ? "steer" : "followup",
2235 state: receipt.disposition === "steer_accepted" ? "steer_accepted" : "queued",
2236 source: "desktop",
2237 paused: Boolean(receipt.paused),
2238 structured,
2239 }];
2240 });
2241 }
2242 if (ownsDraft() && (!queueOnly || pendingFollowups.get(submitPendingKey) === request) && followupDraftFingerprint(submitDraftKey) === submittedDraft) clearSubmittedDraft(submitDraftKey);
2243 if (queueOnly || target) {
2244 pendingFollowups.clear(submitPendingKey, request);
2245 setGuidanceRetryNonce(value => value + 1);
2246 }
2247 if (queueOnly || receipt.disposition === "queued_followup") showToast(t("runtime.queued"), "info");
2248 } catch (error) {
2249 // A transient fence keeps the pending request and retries it
2250 // briefly: the message stays visibly pending instead of surfacing
2251 // an error the user cannot act on.
2252 if (holdTransientGuidance(error, { display: guidanceText, submit: guidanceSubmitText, structured, turnId })) return;
2253 if (followupNotSubmitted(error)) attachmentSubmit?.settleImageSubmission(submitDraftKey, attachmentSubmissionId);
2254 // Registration still needs reconciliation, but no inbox receipt exists before enqueue starts.
2255 if (unresolvedRequest && (!enqueueAttempted || followupNotSubmitted(error))) pendingFollowups.clear(submitPendingKey, unresolvedRequest);
2256 showToast(formatInboxError(error, locale), "warn");
2257 // Keep draft on durable failure.
2258 } finally {
2259 receiptTracker?.finish(submitDraftKey);
2260 }
2261 }
2262 return;
2263 }
2264 if(modelChoice) structured={...(structured ?? {display:displayText,input:submitText,invocations:[]}),modelApplicationChoice:modelChoice};
2265 if (savedInput.target && submitTabId) {
2266 const submissionId = attachmentSubmissionId || `composer-${crypto.randomUUID()}`;
2267 await sendPersistedComposer(submitTabId, displayText, submitText, submissionId,
2268 () => onSend(displayText, submitText, submitTabId, structured, submissionCapture, submissionId), savedInput.target.revision, savedInput.target.draftId);
2269 } else await onSend(displayText, submitText, submitTabId, structured, submissionCapture);
2270 attachmentSubmit?.settleImageSubmission(submitDraftKey, attachmentSubmissionId);
2271 if (!persistentDraft && followupDraftFingerprint(submitDraftKey) === submittedDraft) clearSubmittedDraft(submitDraftKey);
2272 } catch (error) {
2273 // A submit that raced a session switch is refused by the serve's
2274 // expected-session fence. Hold it visibly and retry once the route
2275 // settles instead of reporting a failure the user cannot act on.
2276 if (holdTransientGuidance(error, {
2277 display: submittedDisplayText || trimmedText,
2278 submit: submittedSubmitText || trimmedText,
2279 structured: submittedStructured,
2280 })) return;
2281 // A busy-window submit was durably queued instead of starting a turn:
2282 // show the queue entry immediately and confirm the message left the
2283 // composer, rather than reporting a conflict.
2284 const queued = queuedFollowupOutcome(error);
2285 if (queued) {
2286 updatePendingGuidanceForDraft(submitDraftKey, (items) => items.some((item) => item.id === queued.itemId) ? items : [...items, {
2287 id: queued.itemId,
2288 text: trimmedText.slice(0, 120),
2289 submitText: "",
2290 intent: "followup",
2291 state: "queued",
2292 source: "desktop",
2293 paused: queued.paused,
2294 }]);
2295 if (ownsDraft() && followupDraftFingerprint(submitDraftKey) === submittedDraft) clearSubmittedDraft(submitDraftKey);
2296 setGuidanceRetryNonce((value) => value + 1);
2297 showToast(t("runtime.queued"), "info");
2298 return;
2299 }
2300 if (definitelyNotAccepted(error) || followupNotSubmitted(error)) attachmentSubmit?.settleImageSubmission(submitDraftKey, attachmentSubmissionId);
2301 if (savedInput.target && modelApplicationError(error)) savedInput.reportSubmissionError(error);
2302 else if (savedInput.target) showToast(formatInboxError(error, locale), "warn");
2303 else if (modelApplicationError(error)) setRemoteApplication({key:submitDraftKey,text:submittedDraft,details:modelApplicationError(error)!});
2304 else if (persistentDraft?.onTaskError) persistentDraft.onTaskError(persistentDraft.draftId, persistentDraft.generation, formatInboxError(error, locale));
2305 else showToast(formatInboxError(error, locale), "warn");
2306 } finally {
2307 if (submissionAttachmentTarget) await app.ReleaseAttachmentTarget?.(submissionAttachmentTarget);
2308 onReleaseSubmit?.(submissionCapture);
2309 updateSubmittingForDraft(submitDraftKey, false);
2310 }
2311 };
2312
2313 const sendQueuedGuidance = async (
2314 item: PendingGuidance,
2315 targetDraftKey = activeDraftKeyRef.current,
2316 targetTabId = tabId,
2317 ) => {
2318 if (targetDraftKey !== activeDraftKeyRef.current || disabled || readOnly || guidanceSendingIdRef.current !== null) return;
2319 const durable = !item.id.startsWith("local-");
2320 if (running && item.structured) return;
2321 updateGuidanceSendingIdForDraft(targetDraftKey, item.id);
2322 try {
2323 if (durable && guidanceNeedsRetry(item.state)) {
2324 await app.RetryInboxItem(targetTabId || "", item.id);
2325 updatePendingGuidanceForDraft(targetDraftKey, (items) => markGuidanceQueued(items, item.id));
2326 setGuidanceRetryNonce((value) => value + 1);
2327 // Idle retries dispatch a new turn in the Controller. Busy retries are
2328 // requeued first, then admitted to the active turn below.
2329 if (!running || item.structured) return;
2330 }
2331 if (durable && !running) return await kickIdleGuidance(app.SetInboxPaused, targetTabId || "", () => setGuidanceRetryNonce((value) => value + 1));
2332 if (running && durable) {
2333 const receipt = await steerInboxItemForActiveTurn(app, targetTabId || "", item.id, turnId);
2334 if (receipt?.error) throw new Error(receipt.error);
2335 if (receipt?.disposition === "steer_accepted") {
2336 updatePendingGuidanceForDraft(targetDraftKey, (items) => items.filter((queued) => queued.id !== item.id));
2337 } else {
2338 // Rejected steers remain the same durable follow-up item. The
2339 // Controller owns its later FIFO dispatch.
2340 updatePendingGuidanceForDraft(targetDraftKey, (items) =>
2341 items.map((queued) => queued.id === item.id
2342 ? { ...queued, intent: "followup", state: "queued" }
2343 : queued),
2344 );
2345 setGuidanceRetryNonce((value) => value + 1);
2346 }
2347 return;
2348 }
2349 if (durable) return;
2350 // Prefer durable inbox paths: load body by id only when needed.
2351 let displayText = item.text.trim();
2352 let submitText = item.submitText.trim();
2353 if (!submitText || submitText === displayText) {
2354 try {
2355 const env = await app.ReadInboxItem(targetTabId || "", item.id);
2356 displayText = (env.displayText || env.submitText || displayText).trim();
2357 submitText = (env.submitText || displayText).trim();
2358 } catch {
2359 // Fall back to preview-only shelf text.
2360 }
2361 }
2362 if (!displayText || !submitText) return;
2363 const attemptedSteer = running && onSteer !== undefined;
2364 const selfDispatched = selfDispatchedGuidanceByDraftRef.current[targetDraftKey] ?? [];
2365 selfDispatched.push(submitText);
2366 selfDispatchedGuidanceByDraftRef.current[targetDraftKey] = selfDispatched;
2367 if (attemptedSteer) {
2368 await onSteer(submitText, targetTabId);
2369 updatePendingGuidanceForDraft(targetDraftKey, (items) => items.filter((queued) => queued.id !== item.id));
2370 } else {
2371 await onSend(displayText, submitText, targetTabId, item.structured);
2372 updatePendingGuidanceForDraft(targetDraftKey, (items) => items.filter((queued) => queued.id !== item.id));
2373 }
2374 window.setTimeout(() => {
2375 takeSelfDispatchedGuidance(submitText, targetDraftKey);
2376 }, 5000);
2377 } catch (error) {
2378 showToast(formatInboxError(error, locale), "warn");
2379 } finally {
2380 const current = targetDraftKey === activeDraftKeyRef.current
2381 ? guidanceSendingIdRef.current
2382 : draftsBySessionRef.current[targetDraftKey]?.guidanceSendingId;
2383 if (current === item.id) updateGuidanceSendingIdForDraft(targetDraftKey, null);
2384 }
2385 };
2386
2387 const dismissQueuedGuidance = async (item: PendingGuidance) => {
2388 const targetDraftKey = activeDraftKeyRef.current;
2389 const targetTabId = tabId || "";
2390 try {
2391 if (!item.id.startsWith("local-")) {
2392 await app.DeleteInboxItem(targetTabId, item.id);
2393 }
2394 updatePendingGuidanceForDraft(
2395 targetDraftKey,
2396 (items) => items.filter((queued) => queued.id !== item.id),
2397 );
2398 } catch (error) {
2399 if (isInboxItemMissing(error)) {
2400 updatePendingGuidanceForDraft(
2401 targetDraftKey,
2402 (items) => items.filter((queued) => queued.id !== item.id),
2403 );
2404 return;
2405 }
2406 showToast(formatInboxError(error, locale), "warn");
2407 }
2408 };
2409
2410 const editQueuedGuidance = async (item: PendingGuidance, nextText: string) => {
2411 const text = nextText.trim();
2412 if (!text || item.id.startsWith("local-")) return;
2413 const targetDraftKey = activeDraftKeyRef.current;
2414 const targetTabId = tabId || "";
2415 try {
2416 await app.UpdateInboxItem(targetTabId, item.id, text, text);
2417 updatePendingGuidanceForDraft(targetDraftKey, (items) =>
2418 items.map((queued) => queued.id === item.id ? { ...queued, text, submitText: text } : queued),
2419 );
2420 } catch (error) {
2421 showToast(formatInboxError(error, locale), "warn");
2422 throw error;
2423 }
2424 };
2425
2426 const attachImageFiles = async (files: File[], sourceDraftKey: string) => {
2427 const owner = persistentTargetsByDraftRef.current[sourceDraftKey];
2428 if (!attachmentInputEnabled) return;
2429 const sourceBridgeTarget = bridgeTargetsByDraftRef.current[sourceDraftKey] ?? bridgeTarget;
2430 const images = files.filter((f) => f.type.startsWith("image/"));
2431 if (images.length === 0) return;
2432 // Capability validation happens synchronously inside captureImageTarget,
2433 // before hashing or FileReader starts work for this owner.
2434 const attachmentSubmit = await loadAttachmentSubmit();
2435 const target = await attachmentSubmit.captureImageTarget(app, sourceBridgeTarget);
2436 try {
2437 for (const file of images) {
2438 try {
2439 const key = await fileDedupKey(file);
2440 if (attachmentSeenInDraft(sourceDraftKey, key)) continue;
2441 const staged = await attachmentSubmit.stageImageFile(app, target, `${sourceDraftKey}:${key.hash}:${key.source}`, file, sourceBridgeTarget.kind === "session" && sourceBridgeTarget.session ? sourceBridgeTarget : undefined);
2442 addAttachmentToDraft(sourceDraftKey, {
2443 path: staged.path, previewUrl: staged.previewUrl, displayName: file.name,
2444 draftId: staged.draftId, recoveryPath: staged.recoveryPath, clientAttachmentId: crypto.randomUUID(),
2445 }, key, owner);
2446 } catch (error) {
2447 console.warn("[composer] failed to attach pasted image", error);
2448 if (owner?.onTaskError) owner.onTaskError(owner.draftId, owner.generation, t("composer.attachImageFailed"));
2449 else if (sourceDraftKey === activeDraftKeyRef.current) showToast(t("composer.attachImageFailed"), "warn");
2450 // non-fatal: a failed image attach must not block normal text input
2451 }
2452 }
2453 } finally {
2454 await app.ReleaseAttachmentTarget?.(target);
2455 }
2456 };
2457
2458 const attachOtherFiles = async (files: File[], sourceDraftKey: string) => {
2459 const owner = persistentTargetsByDraftRef.current[sourceDraftKey];
2460 if (!attachmentInputEnabled) return;
2461 const sourceBridgeTarget = bridgeTargetsByDraftRef.current[sourceDraftKey] ?? bridgeTarget;
2462 const others = files.filter((f) => !f.type.startsWith("image/"));
2463 if (others.length === 0) return;
2464 const attachmentSubmit = await loadAttachmentSubmit();
2465 const target = await attachmentSubmit.captureAttachmentTarget(app, sourceBridgeTarget, []);
2466 try {
2467 for (const file of others) {
2468 try {
2469 const nativePath = desktopHost().native.getPathForFile?.(file) || "";
2470 const key = { hash: "", source: ordinaryFileSource(file, nativePath) };
2471 if (attachmentSeenInDraft(sourceDraftKey, key)) continue;
2472 const item = await attachmentSubmit.attachOrdinaryFile(app, target, file, () => nativePath);
2473 if (item.kind === "workspace") {
2474 addWorkspaceReferenceToDraft(sourceDraftKey, { path: item.path, isDir: item.isDir, displayPath: item.displayPath }, owner);
2475 } else {
2476 addAttachmentToDraft(sourceDraftKey, { path: item.path, displayName: file.name }, key, owner);
2477 }
2478 } catch (error) {
2479 console.warn("[composer] failed to attach pasted file");
2480 const message = attachmentSubmit.attachmentUploadFailure(error, t("composer.attachFileFailed"), bytes => t("composer.attachTooLarge", { name: file.name, limit: String(bytes / (1024 * 1024)) }));
2481 if (sourceDraftKey === activeDraftKeyRef.current && attachmentSubmit.isAttachmentUploadLimitError(error)) showToast(message, "warn", { summary: message });
2482 else if (owner?.onTaskError) owner.onTaskError(owner.draftId, owner.generation, message);
2483 else if (sourceDraftKey === activeDraftKeyRef.current) showToast(message, "warn");
2484 }
2485 }
2486 } finally {
2487 await app.ReleaseAttachmentTarget?.(target);
2488 }
2489 };
2490
2491 const attachFiles = (files: File[]) => {
2492 if (!attachmentInputEnabled) return;
2493 const sourceDraftKey = activeDraftKeyRef.current;
2494 const target = persistentTargetsByDraftRef.current[sourceDraftKey];
2495 if (target?.canEdit && !target.canEdit(target.draftId, target.generation)) return;
2496 const notify = (message: string) => target?.onTaskError ? target.onTaskError(target.draftId, target.generation, message) : showToast(message, "warn");
2497 const { accepted, oversize } = splitOversizeAttachments(files);
2498 for (const { file, limitMiB } of oversize) notify(t("composer.attachTooLarge", { name: file.name, limit: String(limitMiB) }));
2499 for (const [attach, failure] of [[attachImageFiles, "composer.attachImageFailed"], [attachOtherFiles, "composer.attachFileFailed"]] as const) {
2500 void trackInputTask(sourceDraftKey, attach(accepted, sourceDraftKey)).catch((error) => {
2501 console.warn("[composer] attachment capability unavailable", error);
2502 notify(t(failure));
2503 });
2504 }
2505 };
2506
2507 const attachNativeClipboardImage = (notifyOnError: boolean, sourceDraftKey: string, owner = persistentTargetsByDraftRef.current[sourceDraftKey]) => {
2508 const sourceBridgeTarget = bridgeTargetsByDraftRef.current[sourceDraftKey] ?? bridgeTarget;
2509 const task = (async () => {
2510 if (!attachmentInputEnabled) return;
2511 if (owner?.isCurrent && !owner.isCurrent(owner.draftId, owner.generation)) return;
2512 const attachmentSubmit = await loadAttachmentSubmit();
2513 const target = await attachmentSubmit.captureAttachmentTarget(app, sourceBridgeTarget, ["SaveClipboardImageForTarget", "AttachmentDataURLForTarget"]);
2514 try {
2515 const path = await app.SaveClipboardImageForTarget!(target);
2516 const previewUrl = await app.AttachmentDataURLForTarget!(target, path);
2517 const key = { hash: await dataURLHash(previewUrl), source: `native-clipboard:${path}` };
2518 if (attachmentSeenInDraft(sourceDraftKey, key)) return;
2519 addAttachmentToDraft(sourceDraftKey, { path, previewUrl }, key, owner);
2520 } catch (error) {
2521 console.warn("[composer] failed to read native clipboard image", error);
2522 if (notifyOnError) {
2523 if (owner?.onTaskError) owner.onTaskError(owner.draftId, owner.generation, t("composer.pasteImageFailed"));
2524 else if (sourceDraftKey === activeDraftKeyRef.current) showToast(t("composer.pasteImageFailed"), "warn");
2525 }
2526 } finally {
2527 await app.ReleaseAttachmentTarget?.(target);
2528 }
2529 })();
2530 return trackInputTask(sourceDraftKey, task).catch((error) => {
2531 console.warn("[composer] native clipboard attachment unavailable", error);
2532 if (notifyOnError) {
2533 if (owner?.onTaskError) owner.onTaskError(owner.draftId, owner.generation, t("composer.pasteImageFailed"));
2534 else showToast(t("composer.pasteImageFailed"), "warn");
2535 }
2536 });
2537 };
2538
2539 // OS file drops arrive as absolute paths through the native bridge (the webview
2540 // withholds them from the HTML drop event); the kernel resolves each into a
2541 // workspace @reference or a stored attachment.
2542 const attachDroppedPaths = (paths: string[], sourceDraftKey = activeDraftKeyRef.current) => {
2543 const owner = persistentTargetsByDraftRef.current[sourceDraftKey];
2544 if (owner?.canEdit && !owner.canEdit(owner.draftId, owner.generation)) return Promise.resolve();
2545 const sourceBridgeTarget = bridgeTargetsByDraftRef.current[sourceDraftKey] ?? bridgeTarget;
2546 const task = (async () => {
2547 setDragOver(false);
2548 if (!attachmentInputEnabled) return;
2549 const attachmentSubmit = await loadAttachmentSubmit();
2550 const target = await attachmentSubmit.captureAttachmentTarget(app, sourceBridgeTarget, ["AttachDroppedForTarget"]);
2551 try {
2552 for (const path of paths) {
2553 try {
2554 const key = { hash: "", source: `path:${path}` };
2555 if (attachmentSeenInDraft(sourceDraftKey, key)) continue;
2556 const item = await app.AttachDroppedForTarget!(target, path);
2557 if (item.kind === "workspace") {
2558 addWorkspaceReferenceToDraft(sourceDraftKey, { path: item.path, isDir: item.isDir, displayPath: item.displayPath }, owner);
2559 } else {
2560 addAttachmentToDraft(sourceDraftKey, { path: item.path, previewUrl: item.previewUrl, displayName: baseName(path) }, key, owner);
2561 }
2562 } catch {
2563 console.warn("[composer] failed to attach dropped file");
2564 if (owner?.onTaskError) owner.onTaskError(owner.draftId, owner.generation, t("composer.attachDropFailed"));
2565 else if (sourceDraftKey === activeDraftKeyRef.current) showToast(t("composer.attachDropFailed"), "warn");
2566 }
2567 }
2568 } finally {
2569 await app.ReleaseAttachmentTarget?.(target);
2570 }
2571 })();
2572 return trackInputTask(sourceDraftKey, task).catch((error) => {
2573 console.warn("[composer] dropped attachment capability unavailable", error);
2574 if (owner?.onTaskError) owner.onTaskError(owner.draftId, owner.generation, t("composer.attachDropFailed"));
2575 else showToast(t("composer.attachDropFailed"), "warn");
2576 });
2577 };
2578
2579 useEffect(() => {
2580 if (!attachmentInputEnabled) return;
2581 return onFilesDropped((paths) => void attachDroppedPaths(paths, activeDraftKeyRef.current));
2582 }, [attachmentInputEnabled, bridgeTargetKey]);
2583
2584 const onPaste = (e: ClipboardEvent<HTMLTextAreaElement | HTMLDivElement>) => {
2585 clearNativeClipboardPasteTimer();
2586 const owner = persistentTargetsByDraftRef.current[activeDraftKeyRef.current];
2587 if (owner?.canEdit && !owner.canEdit(owner.draftId, owner.generation)) { e.preventDefault(); return; }
2588 const files = clipboardFiles(e.clipboardData);
2589 if (files.length > 0) {
2590 e.preventDefault();
2591 if (attachmentInputEnabled) attachFiles(files);
2592 return;
2593 }
2594
2595 const pasted = e.clipboardData.getData("text");
2596 const hasImageHint = clipboardHasImageHint(e.clipboardData);
2597 if (hasImageHint || pasted === "") {
2598 e.preventDefault();
2599 if (attachmentInputEnabled) void attachNativeClipboardImage(hasImageHint, activeDraftKeyRef.current);
2600 return;
2601 }
2602
2603 // Always prevent the browser default paste so React's controlled-input
2604 // reconciliation cannot race with the native DOM update and lose the
2605 // pasted content (WebView2 / Windows). We insert the text manually below.
2606 e.preventDefault();
2607 const selection = getComposerSelection();
2608 const start = selection.start;
2609 const end = selection.end;
2610 const sourceDraftKey = activeDraftKeyRef.current;
2611 const beforeEdit = composerEditSnapshot(sourceDraftKey, selection);
2612
2613 // Normalize CRLF from Windows clipboard so caret offsets match the
2614 // textarea's normalized value. The raw text (with CRLF) is preserved
2615 // in the PastedBlock for long pastes so block content is lossless.
2616 const normalizedPasted = pasted.replace(/\r\n/g, "\n");
2617 let caret: number;
2618
2619 if (shouldFoldPaste(pasted)) {
2620 // Long paste: fold into a collapsible block so the composer stays compact.
2621 const id = nextPasteId.current++;
2622 const lines = lineCount(pasted);
2623 const label = t("composer.pastedLabel", { id, lines });
2624 const block: PastedBlock = { label, text: pasted }; // keep raw text (CRLF preserved)
2625 const next = replaceInvocationTextRange(
2626 textRef.current,
2627 invocationsRef.current,
2628 start,
2629 end,
2630 label,
2631 selection.afterInvocationId,
2632 );
2633 pastedBlocksRef.current = [...pastedBlocksRef.current, block];
2634 setPastedBlocks((prev) => [...prev, block]);
2635 textRef.current = next.text;
2636 invocationsRef.current = next.invocations;
2637 setText(next.text);
2638 setInvocations(next.invocations);
2639 caret = start + label.length;
2640 setComposerSelection(caret);
2641 } else {
2642 // The paste event is intentionally prevented above, so the browser
2643 // cannot add this edit to its native undo history. Record the complete
2644 // programmatic edit below while leaving ordinary typing in the native
2645 // history.
2646 resetPromptHistoryNavigation();
2647 const next = replaceInvocationTextRange(
2648 textRef.current,
2649 invocationsRef.current,
2650 start,
2651 end,
2652 normalizedPasted,
2653 selection.afterInvocationId,
2654 );
2655 textRef.current = next.text;
2656 invocationsRef.current = next.invocations;
2657 setText(next.text);
2658 setInvocations(next.invocations);
2659 caret = start + normalizedPasted.length;
2660 setComposerSelection(caret);
2661 }
2662 recordComposerEdit(
2663 sourceDraftKey,
2664 beforeEdit,
2665 composerEditSnapshot(sourceDraftKey, { start: caret, end: caret }),
2666 );
2667 };
2668
2669 const getInputSelection = () => {
2670 const selection = getComposerSelection();
2671 const start = selection.start;
2672 const end = selection.end;
2673 const from = Math.min(start, end);
2674 const to = Math.max(start, end);
2675 return {
2676 from,
2677 to,
2678 selected: textRef.current.slice(from, to),
2679 afterInvocationId: start === end ? selection.afterInvocationId : undefined,
2680 };
2681 };
2682
2683 const focusInputRange = (start: number, end = start, afterInvocationId?: string) => {
2684 setComposerSelection(start, end, afterInvocationId);
2685 };
2686
2687 const replaceInputRange = (
2688 value: string,
2689 start: number,
2690 end: number,
2691 targetDraftKey = activeDraftKeyRef.current,
2692 afterInvocationId?: string,
2693 ) => {
2694 if (targetDraftKey === activeDraftKeyRef.current) {
2695 const current = textRef.current;
2696 const next = replaceInvocationTextRange(
2697 current,
2698 invocationsRef.current,
2699 start,
2700 end,
2701 value,
2702 afterInvocationId,
2703 );
2704 textRef.current = next.text;
2705 invocationsRef.current = next.invocations;
2706 setText(next.text);
2707 setInvocations(next.invocations);
2708 focusInputRange(start + value.length);
2709 return;
2710 }
2711 const draft = cloneComposerDraft(draftsBySessionRef.current[targetDraftKey] ?? emptyComposerDraft());
2712 const next = replaceInvocationTextRange(
2713 draft.text,
2714 draft.invocations,
2715 start,
2716 end,
2717 value,
2718 afterInvocationId,
2719 );
2720 draft.text = next.text;
2721 draft.invocations = next.invocations;
2722 draftsBySessionRef.current[targetDraftKey] = draft;
2723 };
2724
2725 const insertPastedText = (
2726 pasted: string,
2727 start: number,
2728 end: number,
2729 targetDraftKey = activeDraftKeyRef.current,
2730 afterInvocationId?: string,
2731 owner?: PersistentComposerTarget,
2732 ) => {
2733 if (owner?.isCurrent && !owner.isCurrent(owner.draftId, owner.generation)) return;
2734 const normalizedPasted = pasted.replace(/\r\n/g, "\n");
2735 if (owner?.onPatch) {
2736 let caret = start;
2737 owner.onPatch(owner.draftId, owner.generation, (current) => {
2738 // Clipboard reads may finish after further typing or navigation. Merge
2739 // into the owner's latest fields; never restore a cached Composer copy.
2740 const unchanged = current.text === owner.initial.text;
2741 const from = unchanged ? Math.min(start, current.text.length) : current.text.length;
2742 const to = unchanged ? Math.min(end, current.text.length) : from;
2743 let inserted = normalizedPasted;
2744 let blocks = current.pastedBlocks;
2745 if (shouldFoldPaste(pasted)) {
2746 do { inserted = t("composer.pastedLabel", { id: nextPasteId.current++, lines: lineCount(pasted) }); }
2747 while (blocks.some((block) => block.label === inserted));
2748 blocks = [...blocks, { label: inserted, text: pasted }];
2749 }
2750 const next = replaceInvocationTextRange(current.text, current.invocations, from, to, inserted, unchanged ? afterInvocationId : undefined);
2751 caret = from + inserted.length;
2752 return { ...current, text: next.text, invocations: next.invocations, pastedBlocks: blocks };
2753 });
2754 if (targetDraftKey === activeDraftKeyRef.current) focusInputRange(caret);
2755 return;
2756 }
2757 const beforeEdit = composerEditSnapshot(targetDraftKey, { start, end, afterInvocationId });
2758 let caret: number;
2759 if (targetDraftKey !== activeDraftKeyRef.current) {
2760 const draft = cloneComposerDraft(draftsBySessionRef.current[targetDraftKey] ?? emptyComposerDraft());
2761 let inserted: string;
2762 if (shouldFoldPaste(pasted)) {
2763 const id = draft.nextPasteId++;
2764 const lines = lineCount(pasted);
2765 const label = t("composer.pastedLabel", { id, lines });
2766 draft.pastedBlocks = [...draft.pastedBlocks, { label, text: pasted }];
2767 inserted = label;
2768 caret = start + label.length;
2769 } else {
2770 draft.historyIndex = -1;
2771 inserted = normalizedPasted;
2772 caret = start + normalizedPasted.length;
2773 }
2774 const next = replaceInvocationTextRange(
2775 draft.text,
2776 draft.invocations,
2777 start,
2778 end,
2779 inserted,
2780 afterInvocationId,
2781 );
2782 draft.text = next.text;
2783 draft.invocations = next.invocations;
2784 draftsBySessionRef.current[targetDraftKey] = draft;
2785 owner?.onPatch?.(owner.draftId, owner.generation, { text: draft.text, invocations: draft.invocations, pastedBlocks: draft.pastedBlocks });
2786 recordComposerEdit(targetDraftKey, beforeEdit, composerEditSnapshot(targetDraftKey, { start: caret, end: caret }));
2787 publishPersistentDraft(targetDraftKey);
2788 return;
2789 }
2790
2791 if (shouldFoldPaste(pasted)) {
2792 const id = nextPasteId.current++;
2793 const lines = lineCount(pasted);
2794 const label = t("composer.pastedLabel", { id, lines });
2795 const block: PastedBlock = { label, text: pasted };
2796 const next = replaceInvocationTextRange(
2797 textRef.current,
2798 invocationsRef.current,
2799 start,
2800 end,
2801 label,
2802 afterInvocationId,
2803 );
2804 pastedBlocksRef.current = [...pastedBlocksRef.current, block];
2805 setPastedBlocks((prev) => [...prev, block]);
2806 textRef.current = next.text;
2807 invocationsRef.current = next.invocations;
2808 setText(next.text);
2809 setInvocations(next.invocations);
2810 caret = start + label.length;
2811 focusInputRange(caret);
2812 } else {
2813 resetPromptHistoryNavigation();
2814 const next = replaceInvocationTextRange(
2815 textRef.current,
2816 invocationsRef.current,
2817 start,
2818 end,
2819 normalizedPasted,
2820 afterInvocationId,
2821 );
2822 textRef.current = next.text;
2823 invocationsRef.current = next.invocations;
2824 setText(next.text);
2825 setInvocations(next.invocations);
2826 caret = start + normalizedPasted.length;
2827 focusInputRange(caret);
2828 }
2829 recordComposerEdit(targetDraftKey, beforeEdit, composerEditSnapshot(targetDraftKey, { start: caret, end: caret }));
2830 queueMicrotask(() => publishPersistentDraft(targetDraftKey));
2831 };
2832
2833 const copyComposerSelection = async (cut = false) => {
2834 const selection = getInputSelection();
2835 const sourceDraftKey = activeDraftKeyRef.current;
2836 const owner = persistentTargetsByDraftRef.current[sourceDraftKey];
2837 if (cut && owner?.canEdit && !owner.canEdit(owner.draftId, owner.generation)) return;
2838 const beforeEdit = composerEditSnapshot(sourceDraftKey, { start: selection.from, end: selection.to });
2839 setInputMenuPoint(null);
2840 if (!selection.selected) {
2841 focusInputRange(selection.from, selection.to, selection.afterInvocationId);
2842 return;
2843 }
2844 const task = (async () => {
2845 if (!await writeClipboardText(selection.selected)) {
2846 // Never delete content that did not reach the clipboard.
2847 if (sourceDraftKey === activeDraftKeyRef.current) {
2848 focusInputRange(selection.from, selection.to, selection.afterInvocationId);
2849 }
2850 return;
2851 }
2852 if (cut) {
2853 if (owner?.isCurrent && !owner.isCurrent(owner.draftId, owner.generation)) return;
2854 let afterEdit: ComposerEditSnapshot | undefined;
2855 if (owner?.onPatch) {
2856 owner.onPatch(owner.draftId, owner.generation, current => {
2857 const next = cutUnchangedComposerText(current, beforeEdit, selection);
2858 if (next) afterEdit = { ...beforeEdit, text: next.text, invocations: next.invocations, selection: { start: selection.from, end: selection.from } };
2859 return next ?? current;
2860 });
2861 if (!afterEdit) return;
2862 if (sourceDraftKey === activeDraftKeyRef.current) focusInputRange(selection.from);
2863 } else {
2864 if (!composerEditStateMatches(beforeEdit, composerEditSnapshot(sourceDraftKey))) return;
2865 replaceInputRange("", selection.from, selection.to, sourceDraftKey, selection.afterInvocationId);
2866 afterEdit = composerEditSnapshot(sourceDraftKey, { start: selection.from, end: selection.from });
2867 publishPersistentDraft(sourceDraftKey);
2868 }
2869 if (sourceDraftKey === activeDraftKeyRef.current) resetPromptHistoryNavigation();
2870 recordComposerEdit(sourceDraftKey, beforeEdit, afterEdit);
2871 } else if (sourceDraftKey === activeDraftKeyRef.current) {
2872 focusInputRange(selection.from, selection.to, selection.afterInvocationId);
2873 }
2874 })();
2875 return cut ? trackInputTask(sourceDraftKey, task) : task;
2876 };
2877
2878 const pasteIntoComposer = () => {
2879 const selection = getInputSelection();
2880 const sourceDraftKey = activeDraftKeyRef.current;
2881 const owner = persistentTargetsByDraftRef.current[sourceDraftKey];
2882 if (owner?.canEdit && !owner.canEdit(owner.draftId, owner.generation)) return Promise.resolve();
2883 setInputMenuPoint(null);
2884 return trackInputTask(sourceDraftKey, (async () => {
2885
2886 // Try reading clipboard items for image detection (no event in menu path)
2887 try {
2888 const items = await navigator.clipboard.read();
2889 if (owner?.isCurrent && !owner.isCurrent(owner.draftId, owner.generation)) return;
2890 if (attachmentInputEnabled && items.some((item) => item.types.some((t) => t.startsWith("image/")))) {
2891 void attachNativeClipboardImage(true, sourceDraftKey);
2892 return;
2893 }
2894 } catch {
2895 /* clipboard.read() not supported or permission denied; fall through */
2896 }
2897
2898 if (!navigator.clipboard?.readText) {
2899 if (sourceDraftKey === activeDraftKeyRef.current) {
2900 focusInputRange(selection.from, selection.to, selection.afterInvocationId);
2901 }
2902 return;
2903 }
2904 try {
2905 const pasted = await navigator.clipboard.readText();
2906 if (owner?.isCurrent && !owner.isCurrent(owner.draftId, owner.generation)) return;
2907 if (pasted === "") {
2908 // Match the keyboard paste handler: an empty text read means "nothing
2909 // to insert" (empty clipboard, files, or unsupported types) — never
2910 // replace the current selection with nothing. An image may still be
2911 // attachable through the native clipboard path.
2912 if (sourceDraftKey === activeDraftKeyRef.current) {
2913 focusInputRange(selection.from, selection.to, selection.afterInvocationId);
2914 }
2915 if (attachmentInputEnabled) void attachNativeClipboardImage(false, sourceDraftKey);
2916 return;
2917 }
2918 insertPastedText(
2919 pasted,
2920 selection.from,
2921 selection.to,
2922 sourceDraftKey,
2923 selection.afterInvocationId,
2924 owner,
2925 );
2926 } catch {
2927 if (sourceDraftKey === activeDraftKeyRef.current) {
2928 focusInputRange(selection.from, selection.to, selection.afterInvocationId);
2929 }
2930 }
2931 })());
2932 };
2933
2934 const selectAllComposerText = () => {
2935 setInputMenuPoint(null);
2936 focusInputRange(0, text.length);
2937 };
2938
2939 const openInputMenu = (event: ReactMouseEvent<HTMLElement>) => {
2940 event.preventDefault();
2941 event.stopPropagation();
2942 rememberCaret();
2943 setInputMenuPoint(contextMenuPointFromEvent(event));
2944 };
2945
2946 const hasWorkspaceReferenceDrag = (dataTransfer: DataTransfer): boolean =>
2947 Array.from(dataTransfer.types).includes(WORKSPACE_REF_DRAG_TYPE);
2948
2949 const hasFileDrag = (dataTransfer: DataTransfer): boolean =>
2950 Array.from(dataTransfer.items).some((it) => it.kind === "file") || dataTransfer.files.length > 0;
2951
2952 const fileDragItems = (dataTransfer: DataTransfer): DataTransferItem[] =>
2953 Array.from(dataTransfer.items).filter((item) => item.kind === "file");
2954
2955 const getWebkitFileEntry = (item: DataTransferItem): WebkitFileEntry | null => {
2956 const getAsEntry = (item as DataTransferItem & { webkitGetAsEntry?: () => WebkitFileEntry | null }).webkitGetAsEntry;
2957 return typeof getAsEntry === "function" ? getAsEntry.call(item) : null;
2958 };
2959
2960 const hasPathlessFileDrop = (dataTransfer: DataTransfer): boolean => {
2961 const items = fileDragItems(dataTransfer);
2962 if (items.length === 0) return dataTransfer.files.length > 0;
2963 return items.some((item) => getWebkitFileEntry(item) === null);
2964 };
2965
2966 const stopNativeFileDrop = (e: DragEvent<HTMLDivElement>) => {
2967 e.preventDefault();
2968 e.stopPropagation();
2969 e.nativeEvent.stopImmediatePropagation();
2970 };
2971
2972 const onFileDropCapture = (e: DragEvent<HTMLDivElement>) => {
2973 if (hasWorkspaceReferenceDrag(e.dataTransfer) || !hasFileDrag(e.dataTransfer)) return;
2974 e.preventDefault();
2975 if (!attachmentInputEnabled) {
2976 stopNativeFileDrop(e);
2977 setDragOver(false);
2978 return;
2979 }
2980 if (!hasPathlessFileDrop(e.dataTransfer)) return;
2981 const files = Array.from(e.dataTransfer.files);
2982 if (files.length === 0) return;
2983 stopNativeFileDrop(e);
2984 setDragOver(false);
2985 attachFiles(files);
2986 };
2987
2988 const onDrop = (e: DragEvent<HTMLDivElement>) => {
2989 const droppedWorkspaceRef = readWorkspaceReferenceDrag(e.dataTransfer);
2990 if (droppedWorkspaceRef) {
2991 e.preventDefault();
2992 setDragOver(false);
2993 if (!attachmentInputEnabled) return;
2994 addWorkspaceReference(droppedWorkspaceRef);
2995 return;
2996 }
2997
2998 // OS file drops deliver no usable bytes/paths here; the native bridge
2999 // (onFilesDropped -> AttachDropped) handles them. Prevent webview navigation.
3000 if (hasFileDrag(e.dataTransfer)) {
3001 e.preventDefault();
3002 setDragOver(false);
3003 }
3004 };
3005
3006 const onDragOver = (e: DragEvent<HTMLDivElement>) => {
3007 if (!hasWorkspaceReferenceDrag(e.dataTransfer) && !hasFileDrag(e.dataTransfer)) return;
3008 e.preventDefault(); // required for the drop event to fire
3009 e.dataTransfer.dropEffect = attachmentInputEnabled ? "copy" : "none";
3010 setDragOver(attachmentInputEnabled);
3011 };
3012
3013 const onDragLeave = () => setDragOver(false);
3014 // handleCancel stops the in-flight turn; if it was cancelled before the server
3015 // replied, the just-sent text is handed back so we drop it back into the input.
3016 const handleCancel = async () => {
3017 if (finishing || runtimeState.unknown || runtimeState.cancellable === false) return;
3018 const targetDraftKey = activeDraftKeyRef.current;
3019 if (cancelSettlingDraftsRef.current.has(targetDraftKey)) return;
3020 cancelSettlingDraftsRef.current.add(targetDraftKey);
3021 setCancelSettlingRevision((value) => value + 1);
3022 // The durable queue has its own pause/delete controls. Stopping the current
3023 // task must not discard pending messages or restore truncated previews.
3024 const ownedGuidance = typeof app.InboxQueueForTarget === "function" ? [] : pendingGuidanceRef.current.filter((item) => item.id.startsWith("local-") || item.source === "desktop");
3025 const durableItemIDs = maintenanceActive ? [] : ownedGuidance
3026 .map((item) => item.id)
3027 .filter((id) => !id.startsWith("local-"));
3028 if (!maintenanceActive && goalModeOn && activeGoal) onClearGoal();
3029 try {
3030 const outcome = (await onCancel(durableItemIDs)) ?? { discardedItemIds: [] };
3031 const discarded = new Set(outcome.discardedItemIds);
3032 const restorable = maintenanceActive ? [] : ownedGuidance.filter((item) => item.id.startsWith("local-") || discarded.has(item.id));
3033 const queued = restorable
3034 .map((item) => item.structured?.display ?? item.text)
3035 .filter((part) => part.trim() !== "");
3036 const restoredIDs = new Set(restorable.map((item) => item.id));
3037 if (restoredIDs.size > 0) {
3038 updatePendingGuidanceForDraft(targetDraftKey, (items) => items.filter((item) => !restoredIDs.has(item.id)));
3039 }
3040 const draftText = targetDraftKey === activeDraftKeyRef.current
3041 ? textRef.current
3042 : (draftsBySessionRef.current[targetDraftKey]?.text ?? "");
3043 const currentDraft = outcome.restoredText?.trim() === draftText.trim() ? "" : draftText;
3044 const nextText = [outcome.restoredText, currentDraft, ...queued]
3045 .filter((part): part is string => Boolean(part?.trim()))
3046 .join("\n");
3047 if (nextText) setTextForDraft(targetDraftKey, nextText);
3048 if (targetDraftKey === activeDraftKeyRef.current && restorable.length > 0) setGuidanceExpanded(false);
3049 } finally {
3050 cancelSettlingDraftsRef.current.delete(targetDraftKey);
3051 setCancelSettlingRevision((value) => value + 1);
3052 }
3053 };
3054
3055 const pickCommand = (c: CommandInfo) => {
3056 const query = activeSlashQuery;
3057 if (!query || slashCommandDisabled(c)) return;
3058 if (!commandUsesStructuredInvocation(c)) {
3059 if (invocationsRef.current.length > 0 && richSlashQuery) {
3060 richInputRef.current?.replaceRange(`/${c.name} `, richSlashQuery.from, richSlashQuery.to);
3061 } else {
3062 const targetDraftKey = activeDraftKeyRef.current;
3063 const beforeEdit = composerEditSnapshot(targetDraftKey, { start: query.from, end: query.to });
3064 const next = replaceInvocationTextRange(
3065 textRef.current,
3066 invocationsRef.current,
3067 query.from,
3068 query.to,
3069 `/${c.name} `,
3070 );
3071 const caret = query.from + c.name.length + 2;
3072 textRef.current = next.text;
3073 setText(next.text);
3074 setComposerSelection(caret);
3075 recordComposerEdit(
3076 targetDraftKey,
3077 beforeEdit,
3078 composerEditSnapshot(targetDraftKey, { start: caret, end: caret }),
3079 );
3080 }
3081 return;
3082 }
3083 if (invocationsRef.current.length > 0 && richSlashQuery) {
3084 richInputRef.current?.insertInvocation(c, richSlashQuery);
3085 setRichSlashQuery(null);
3086 return;
3087 }
3088 const targetDraftKey = activeDraftKeyRef.current;
3089 const beforeEdit = composerEditSnapshot(targetDraftKey, { start: query.from, end: query.to });
3090 const invocation: ComposerInvocation = {
3091 id: `composer-invocation-${nextInvocationId.current++}`,
3092 offset: query.from,
3093 command: c,
3094 };
3095 const next = replaceInvocationTextRange(
3096 textRef.current,
3097 invocationsRef.current,
3098 query.from,
3099 query.to,
3100 "",
3101 );
3102 textRef.current = next.text;
3103 invocationsRef.current = [invocation];
3104 setText(next.text);
3105 setInvocations([invocation]);
3106 setRichSlashQuery(null);
3107 recordComposerEdit(
3108 targetDraftKey,
3109 beforeEdit,
3110 composerEditSnapshot(targetDraftKey, {
3111 start: query.from,
3112 end: query.from,
3113 afterInvocationId: invocation.id,
3114 }),
3115 );
3116 requestActiveDraftFrame(() => richInputRef.current?.setSelectionRange(
3117 query.from,
3118 query.from,
3119 invocation.id,
3120 ));
3121 };
3122
3123 const activePastedBlocks = pastedBlocks.filter((block) => text.includes(block.label));
3124 const shellModeActive = text.trimStart().startsWith("!");
3125
3126 const removeWorkspaceReference = (target: WorkspaceReference) => {
3127 const key = workspaceReferenceKey(target);
3128 setWorkspaceRefs((prev) => prev.filter((ref) => workspaceReferenceKey(ref) !== key));
3129 requestActiveDraftFrame(focusComposerInput);
3130 };
3131
3132 const togglePastedPreview = (label: string) => {
3133 setOpenPastedLabels((prev) => {
3134 const next = prev.includes(label) ? prev.filter((x) => x !== label) : [...prev, label];
3135 openPastedLabelsRef.current = next;
3136 return next;
3137 });
3138 };
3139
3140 const replacePastedBlockLabel = (block: PastedBlock, replacement: string): number | null => {
3141 const current = textRef.current;
3142 const start = current.indexOf(block.label);
3143 if (start < 0) return null;
3144 const next = replaceInvocationTextRange(
3145 current,
3146 invocationsRef.current,
3147 start,
3148 start + block.label.length,
3149 replacement,
3150 );
3151 textRef.current = next.text;
3152 invocationsRef.current = next.invocations;
3153 setText(next.text);
3154 setInvocations(next.invocations);
3155 setComposerSelection(next.text.length);
3156 return next.text.length;
3157 };
3158
3159 const removePastedBlock = (block: PastedBlock) => {
3160 const targetDraftKey = activeDraftKeyRef.current;
3161 const beforeEdit = composerEditSnapshot(targetDraftKey);
3162 const nextBlocks = pastedBlocksRef.current.filter((x) => x.label !== block.label);
3163 const nextOpenLabels = openPastedLabelsRef.current.filter((x) => x !== block.label);
3164 pastedBlocksRef.current = nextBlocks;
3165 openPastedLabelsRef.current = nextOpenLabels;
3166 setPastedBlocks(nextBlocks);
3167 setOpenPastedLabels(nextOpenLabels);
3168 const caret = replacePastedBlockLabel(block, "");
3169 if (caret !== null) {
3170 recordComposerEdit(
3171 targetDraftKey,
3172 beforeEdit,
3173 composerEditSnapshot(targetDraftKey, { start: caret, end: caret }),
3174 );
3175 }
3176 };
3177
3178 const expandPastedBlock = (block: PastedBlock) => {
3179 const targetDraftKey = activeDraftKeyRef.current;
3180 const beforeEdit = composerEditSnapshot(targetDraftKey);
3181 const nextBlocks = pastedBlocksRef.current.filter((x) => x.label !== block.label);
3182 const nextOpenLabels = openPastedLabelsRef.current.filter((x) => x !== block.label);
3183 pastedBlocksRef.current = nextBlocks;
3184 openPastedLabelsRef.current = nextOpenLabels;
3185 setPastedBlocks(nextBlocks);
3186 setOpenPastedLabels(nextOpenLabels);
3187 const caret = replacePastedBlockLabel(block, block.text);
3188 if (caret !== null) {
3189 recordComposerEdit(
3190 targetDraftKey,
3191 beforeEdit,
3192 composerEditSnapshot(targetDraftKey, { start: caret, end: caret }),
3193 );
3194 }
3195 };
3196
3197 useEffect(() => {
3198 const onResize = () => setComposerHeight((height) => (height === null ? null : clampComposerHeight(height)));
3199 window.addEventListener("resize", onResize);
3200 return () => window.removeEventListener("resize", onResize);
3201 }, []);
3202
3203 const measureTextareaAutoHeight = useCallback(() => {
3204 // Creation empty hero starts single-line but must grow so multi-line drafts
3205 // stay readable before send (review: fixed 20px + overflow:hidden clipped).
3206 if (heroMode) {
3207 const measureNode = measureTaRef.current;
3208 if (!measureNode) {
3209 setTextareaAutoHeight(20);
3210 setTextareaAutoOverflow(false);
3211 return;
3212 }
3213 const scrollHeight = measureNode.scrollHeight || 20;
3214 const maxHeight = composerHeroInputMaxHeight();
3215 const nextHeight = Math.min(Math.max(scrollHeight, 20), maxHeight);
3216 const nextOverflow = scrollHeight > maxHeight + 1;
3217 setTextareaAutoHeight((current) => (current === nextHeight ? current : nextHeight));
3218 setTextareaAutoOverflow((current) => (current === nextOverflow ? current : nextOverflow));
3219 return;
3220 }
3221 const richHeight = invocationsRef.current.length > 0 ? richInputRef.current?.scrollHeight() : 0;
3222 const scrollHeight = richHeight || measureTaRef.current?.scrollHeight || 0;
3223 if (!scrollHeight) return;
3224 const sizing = resolveComposerContentSizing({
3225 contentHeight: scrollHeight,
3226 manualLogicalHeight: composerHeight,
3227 maxLogicalHeight: composerMaxHeight(),
3228 reservedHeight: COMPOSER_AUTO_RESERVED_HEIGHT,
3229 });
3230 setTextareaAutoHeight((current) => (current === sizing.inputHeight ? current : sizing.inputHeight));
3231 setTextareaAutoOverflow((current) => (current === sizing.overflow ? current : sizing.overflow));
3232 }, [composerHeight, heroMode, invocations.length]);
3233
3234 useLayoutEffect(() => {
3235 measureTextareaAutoHeight();
3236 }, [text, measureTextareaAutoHeight]);
3237
3238 useEffect(() => {
3239 let frame = 0;
3240 const update = () => {
3241 if (frame) window.cancelAnimationFrame(frame);
3242 frame = window.requestAnimationFrame(() => {
3243 frame = 0;
3244 measureTextareaAutoHeight();
3245 });
3246 };
3247 window.addEventListener("resize", update);
3248 const observer = new MutationObserver(update);
3249 observer.observe(document.documentElement, {
3250 attributes: true,
3251 attributeFilter: ["data-text-size", "data-font-family", "data-mono-font-family", "style"],
3252 });
3253 return () => {
3254 if (frame) window.cancelAnimationFrame(frame);
3255 window.removeEventListener("resize", update);
3256 observer.disconnect();
3257 };
3258 }, [composerHeight, measureTextareaAutoHeight]);
3259
3260 const saveComposerHeight = (height: number) => {
3261 saveLayoutSize("composerHeight", height, clampComposerHeight);
3262 };
3263
3264 const resetComposerHeight = () => {
3265 setComposerHeight(clampComposerHeight(COMPOSER_DEFAULT_HEIGHT));
3266 clearLayoutSize("composerHeight");
3267 };
3268
3269 const onComposerResizeStart = (e: ReactPointerEvent<HTMLButtonElement>) => {
3270 if (e.button !== 0) return;
3271 const card = composerCardRef.current;
3272 if (!card) return;
3273
3274 e.preventDefault();
3275 const startY = e.clientY;
3276 const startHeight = Math.max(composerHeight ?? COMPOSER_MIN_HEIGHT, composerLogicalHeight(card));
3277 let nextHeight = clampComposerHeight(startHeight);
3278 let moved = false;
3279 card.style.setProperty("--composer-height", `${nextHeight}px`);
3280 e.currentTarget.setAttribute("aria-valuenow", String(nextHeight));
3281 const liveResize = createRafResizeUpdater({
3282 target: card,
3283 separator: e.currentTarget,
3284 cssVar: "--composer-height",
3285 });
3286 setComposerResizing(true);
3287 document.body.classList.add("composer-resizing");
3288
3289 const onMove = (event: PointerEvent) => {
3290 moved = true;
3291 nextHeight = clampComposerHeight(startHeight + startY - event.clientY);
3292 liveResize.schedule(nextHeight);
3293 };
3294 const onUp = () => {
3295 liveResize.flush();
3296 setComposerResizing(false);
3297 document.body.classList.remove("composer-resizing");
3298 if (moved) {
3299 setComposerHeight(nextHeight);
3300 saveComposerHeight(nextHeight);
3301 }
3302 document.removeEventListener("pointermove", onMove);
3303 document.removeEventListener("pointerup", onUp);
3304 document.removeEventListener("pointercancel", onUp);
3305 };
3306
3307 document.addEventListener("pointermove", onMove);
3308 document.addEventListener("pointerup", onUp);
3309 document.addEventListener("pointercancel", onUp);
3310 };
3311
3312 const onComposerResizeKeyDown = (e: KeyboardEvent<HTMLButtonElement>) => {
3313 const card = composerCardRef.current;
3314 const current = Math.max(
3315 composerHeight ?? COMPOSER_MIN_HEIGHT,
3316 card ? composerLogicalHeight(card) : COMPOSER_MIN_HEIGHT,
3317 );
3318 const step = e.shiftKey ? 32 : 16;
3319 let next: number | null = null;
3320 if (e.key === "ArrowUp" || e.key === "PageUp") next = current + step;
3321 else if (e.key === "ArrowDown" || e.key === "PageDown") next = current - step;
3322 else if (e.key === "Home") next = COMPOSER_MIN_HEIGHT;
3323 else if (e.key === "End") next = composerMaxHeight();
3324 if (next === null) return;
3325 e.preventDefault();
3326 const height = clampComposerHeight(next);
3327 setComposerHeight(height);
3328 saveComposerHeight(height);
3329 };
3330
3331 const pickEntry = (e: DirEntry) => {
3332 const picked = composerPickFileEntry(text, atRaw, atDir, e);
3333 if (picked.workspaceRef) {
3334 setTextCaretEnd(picked.text);
3335 addWorkspaceReference(picked.workspaceRef);
3336 return;
3337 }
3338 // A directory keeps the menu open (trailing "/"); a file completes it (space).
3339 setTextCaretEnd(picked.text);
3340 };
3341
3342 // --- past:chats session reference ---
3343 const openPastChats = useCallback(async (initialQuery = "") => {
3344 const snapshotCwd = cwdRef.current;
3345 const sourceDraftKey = activeDraftKeyRef.current;
3346 setShowPastChats(true);
3347 setActive(0);
3348 setPastChatQuery(initialQuery);
3349 setLoadingPastChats(true);
3350 try {
3351 const sessions = await app.ListSessions();
3352 // Discard stale response if workspace changed while the request was in-flight.
3353 if (cwdRef.current !== snapshotCwd || activeDraftKeyRef.current !== sourceDraftKey) return;
3354 const sorted = asArray(sessions)
3355 .filter((s) => !s.current)
3356 .sort((a, b) => {
3357 const at = a.lastActivityAt || a.modTime || a.createdAt || 0;
3358 const bt = b.lastActivityAt || b.modTime || b.createdAt || 0;
3359 return bt - at;
3360 })
3361 .slice(0, 50);
3362 setPastChats(sorted);
3363 } catch {
3364 if (cwdRef.current !== snapshotCwd || activeDraftKeyRef.current !== sourceDraftKey) return;
3365 setPastChats([]);
3366 } finally {
3367 if (cwdRef.current === snapshotCwd && activeDraftKeyRef.current === sourceDraftKey) setLoadingPastChats(false);
3368 }
3369 }, []);
3370
3371 useEffect(() => {
3372 if (!pastChatToken || directPastChats || dismissed || running || disabled || readOnly) return;
3373 setDirectPastChats(true);
3374 void openPastChats(pastChatToken.query);
3375 }, [directPastChats, disabled, dismissed, openPastChats, pastChatToken, readOnly, running]);
3376
3377 const clearDirectPastChatToken = () => {
3378 const current = textRef.current;
3379 const token = activePastChatToken(current);
3380 if (!token) return current.length;
3381 const next = replaceInvocationTextRange(current, invocationsRef.current, token.from, current.length, "");
3382 textRef.current = next.text;
3383 invocationsRef.current = next.invocations;
3384 setText(next.text);
3385 setInvocations(next.invocations);
3386 return token.from;
3387 };
3388
3389 const dismissDirectPastChats = () => {
3390 // Keep the literal token text — "#6310" may be an issue number or a
3391 // heading, not a session query. Dismissing only closes the panel;
3392 // `dismissed` suppresses reopening until the query changes, the same
3393 // contract as the slash and @ menus. Selecting a session (pickSession)
3394 // is the only path that consumes the token.
3395 setDismissed(true);
3396 setDirectPastChats(false);
3397 setShowPastChats(false);
3398 setPastChatQuery("");
3399 setActive(0);
3400 requestActiveDraftFrame(focusComposerInput);
3401 };
3402
3403 // The typed panel follows the live token: typing in the composer extends
3404 // the query, and deleting the token (or ending it with whitespace) closes
3405 // the panel instead of leaving it open on a stale query.
3406 useEffect(() => {
3407 if (!directPastChats) return;
3408 if (pastChatTokenQuery === null) {
3409 setDirectPastChats(false);
3410 setShowPastChats(false);
3411 setPastChatQuery("");
3412 setActive(0);
3413 return;
3414 }
3415 setPastChatQuery(pastChatTokenQuery);
3416 }, [directPastChats, pastChatTokenQuery]);
3417
3418 const insertContentTrigger = (trigger: "@" | "#" | "/") => {
3419 const selection = getInputSelection();
3420 const targetDraftKey = activeDraftKeyRef.current;
3421 const beforeEdit = composerEditSnapshot(targetDraftKey, {
3422 start: selection.from,
3423 end: selection.to,
3424 afterInvocationId: selection.afterInvocationId,
3425 });
3426 const current = textRef.current;
3427 const needsSpace = selection.from > 0 && !/\s/.test(current.charAt(selection.from - 1));
3428 const value = `${needsSpace ? " " : ""}${trigger}`;
3429 setContentMenuOpen(false);
3430 setDirectPastChats(false);
3431 setShowPastChats(false);
3432 setDismissed(false);
3433 replaceInputRange(
3434 value,
3435 selection.from,
3436 selection.to,
3437 targetDraftKey,
3438 selection.afterInvocationId,
3439 );
3440 const caret = selection.from + value.length;
3441 recordComposerEdit(
3442 targetDraftKey,
3443 beforeEdit,
3444 composerEditSnapshot(targetDraftKey, { start: caret, end: caret }),
3445 );
3446 if (trigger === "#") {
3447 setDirectPastChats(true);
3448 void openPastChats();
3449 }
3450 };
3451
3452 const openContentMenu = () => {
3453 if (intentMenuOpen || intentMenuClosing) closeIntentMenu();
3454 setDirectPastChats(false);
3455 setShowPastChats(false);
3456 setDismissed(true);
3457 setContentMenuOpen(true);
3458 };
3459
3460 const chooseAttachmentFiles = () => {
3461 setContentMenuOpen(false);
3462 if (!attachmentInputEnabled) return;
3463 fileInputRef.current?.click();
3464 };
3465
3466 // PR-C1: client-side filter for the past:chats list. Matches against the
3467 // human-visible fields (title, topic, preview, path, workspace) so users
3468 // can narrow long session lists without a backend round-trip. Lowercased
3469 // substring match keeps the behaviour predictable across locales.
3470 const filteredPastChats = useMemo(() => {
3471 const q = pastChatQuery.trim().toLowerCase();
3472 if (!q) return pastChats;
3473 return pastChats.filter((session) =>
3474 [
3475 session.title,
3476 session.topicTitle,
3477 session.preview,
3478 session.path,
3479 session.workspaceRoot,
3480 ]
3481 .map((value) => String(value ?? "").toLowerCase())
3482 .some((value) => value.includes(q)),
3483 );
3484 }, [pastChats, pastChatQuery]);
3485
3486 // Final menu item count: when the past:chats list is open, count the
3487 // filtered sessions instead of file entries + the "past:chats" row.
3488 const count = (menuMode === "at" && showPastChats) || menuMode === "pastChats"
3489 ? filteredPastChats.length
3490 : countBase;
3491
3492 // Clamp active index when the menu item count changes (e.g. switching
3493 // between file list and past:chats list, or filtering sessions).
3494 useEffect(() => {
3495 if (menuMode === "slash") {
3496 if (!slashSelectableIndices.includes(active)) {
3497 setActive(slashSelectableIndices[0] ?? 0);
3498 }
3499 return;
3500 }
3501 const maxIdx = Math.max(0, count - 1);
3502 setActive((prev) => (prev > maxIdx ? 0 : prev));
3503 }, [active, count, menuMode, slashSelectableIndices]);
3504
3505 const removeAtToken = (value: string) => {
3506 return value.replace(/[\r\n]+$/u, "").replace(activeRefTokenRe, "").trimEnd();
3507 };
3508
3509 const pickSession = (session: SessionMeta) => {
3510 setSessionRefs((prev) => {
3511 if (prev.some((x) => x.path === session.path)) {
3512 return prev;
3513 }
3514 return [
3515 ...prev,
3516 {
3517 path: session.path,
3518 title: session.title || session.topicTitle || session.preview || "Untitled",
3519 preview: session.preview,
3520 turns: session.turns,
3521 turnsState: session.turnsState,
3522 createdAt: session.createdAt,
3523 lastActivityAt: session.lastActivityAt,
3524 },
3525 ];
3526 });
3527 const caret = directPastChats ? clearDirectPastChatToken() : null;
3528 if (!directPastChats) setText((prev) => removeAtToken(prev));
3529 setDirectPastChats(false);
3530 setPastChatQuery("");
3531 setShowPastChats(false);
3532 setActive(0);
3533 setComposerSelection(caret ?? textRef.current.length);
3534 };
3535
3536 const removeSessionRef = (path: string) => {
3537 setSessionRefs((prev) => prev.filter((ref) => ref.path !== path));
3538 };
3539
3540 // pickArg replaces just the current token with the suggestion. A "descend" item
3541 // (e.g. "/skill show ") ends with a space, so the effect re-fetches the next
3542 // level; a terminal item leaves the menu (next fetch returns nothing).
3543 const pickArg = (it: SlashArgItem) => {
3544 if (!argRes) return;
3545 setTextCaretEnd(slashText.slice(0, argRes.from) + it.insert);
3546 };
3547
3548 const pickActive = () => {
3549 if (menuMode === "slash") {
3550 const item = slashMatches[active];
3551 if (item && !slashCommandDisabled(item)) pickCommand(item);
3552 return;
3553 }
3554 if (menuMode === "slasharg" && argRes) {
3555 const item = argRes.items[active];
3556 if (item) pickArg(item);
3557 return;
3558 }
3559 if (menuMode === "at" || menuMode === "pastChats") {
3560 if (showPastChats) {
3561 const session = filteredPastChats[active];
3562 if (session) pickSession(session);
3563 return;
3564 }
3565 if (menuMode === "pastChats") return;
3566 const item = atMenuItems[active];
3567 if (!item) return;
3568 if (item.kind === "pastChats") {
3569 void openPastChats();
3570 return;
3571 }
3572 pickEntry(item.entry);
3573 }
3574 };
3575
3576 const onKeyDown = (e: KeyboardEvent<HTMLTextAreaElement | HTMLDivElement>) => {
3577 const composing = isImeKeyEvent(e.nativeEvent, composingRef.current, lastCompositionEndAt.current);
3578 const native = e.nativeEvent as globalThis.KeyboardEvent & {
3579 keyCode?: number;
3580 which?: number;
3581 code?: string;
3582 };
3583 const fnKey = isFnKeyEvent(native);
3584 const historyDirection = promptHistoryDirectionFromEvent({
3585 key: e.key,
3586 code: native.code,
3587 keyCode: native.keyCode,
3588 which: native.which,
3589 });
3590
3591 if (e.key === "Enter" && composing) return;
3592 if (fnKey) return;
3593
3594 if (attachmentInputEnabled && isPasteShortcut(e) && !composing) {
3595 clearNativeClipboardPasteTimer();
3596 const sourceDraftKey = activeDraftKeyRef.current;
3597 const owner = persistentTargetsByDraftRef.current[sourceDraftKey];
3598 if (owner?.canEdit && !owner.canEdit(owner.draftId, owner.generation)) { e.preventDefault(); return; }
3599 let settle!: () => void;
3600 const task = new Promise<void>(resolve => { settle = resolve; });
3601 nativeClipboardPasteCompletionRef.current = settle;
3602 void trackInputTask(sourceDraftKey, task);
3603 nativeClipboardPasteTimerRef.current = window.setTimeout(() => {
3604 nativeClipboardPasteTimerRef.current = null;
3605 nativeClipboardPasteCompletionRef.current = null;
3606 void attachNativeClipboardImage(false, sourceDraftKey, owner).finally(settle);
3607 }, 160);
3608 }
3609
3610 // Shift+Tab toggles plan mode only. Tool access is deliberately changed via
3611 // the access menu so keyboard cycling never crosses a permission boundary.
3612 if (e.key === "Tab" && e.shiftKey && !composing) {
3613 e.preventDefault();
3614 onCycleMode();
3615 return;
3616 }
3617
3618 syncPromptHistoryGeneration();
3619
3620 const inputSelection = getComposerSelection();
3621 const inputValue = textRef.current;
3622
3623 const canUseCurrentPromptHistory = () => canUsePromptHistory({
3624 direction: historyDirection,
3625 menuOpen: Boolean(menuMode),
3626 composing,
3627 altKey: e.altKey,
3628 ctrlKey: e.ctrlKey,
3629 metaKey: e.metaKey,
3630 shiftKey: e.shiftKey,
3631 fnKey,
3632 value: inputValue,
3633 selectionStart: inputSelection.start,
3634 selectionEnd: inputSelection.end,
3635 historyIndex: historyIndexRef.current,
3636 }) && invocationsRef.current.length === 0;
3637
3638 // Prompt history navigation: plain ↑/↓ only. Fn/Page/Home/End are left to
3639 // the native textarea/OS so macOS dictation and text navigation keep working.
3640
3641 // When navigating history, any other key (letter, Backspace, etc.) resets
3642 // back to the saved draft when another key is used.
3643 if (historyIndexRef.current !== -1 && !canUseCurrentPromptHistory()) {
3644 historyIndexRef.current = -1;
3645 setHistoryIndex(-1);
3646 }
3647
3648 if (canUseCurrentPromptHistory()) {
3649 e.preventDefault();
3650 const sourceDraftKey = activeDraftKeyRef.current;
3651 void (async () => {
3652 // Keep the navigation result with the draft where the key was pressed;
3653 // loading older history may outlive a tab switch.
3654 if (historyIndexRef.current === -1) {
3655 savedTextRef.current = text; // save current draft
3656 }
3657 const sourceIndex = historyIndexRef.current;
3658 const target =
3659 historyDirection === "up"
3660 ? sourceIndex + 1
3661 : historyDirection === "down"
3662 ? sourceIndex - 1
3663 : sourceIndex;
3664 if (target >= historyEntriesRef.current.length && !(await ensurePromptHistoryIndex(target))) {
3665 return;
3666 }
3667 const next =
3668 historyDirection === "up"
3669 ? Math.min(target, historyEntriesRef.current.length - 1)
3670 : historyDirection === "down"
3671 ? Math.max(target, -1)
3672 : sourceIndex;
3673 const historyText = next === -1 ? null : historyEntriesRef.current[next]?.text ?? "";
3674 if (sourceDraftKey === activeDraftKeyRef.current) {
3675 historyIndexRef.current = next;
3676 setHistoryIndex(next);
3677 setTextCaretEnd(historyText ?? savedTextRef.current);
3678 } else {
3679 const beforeEdit = composerEditSnapshot(sourceDraftKey);
3680 const draft = cloneComposerDraft(draftsBySessionRef.current[sourceDraftKey] ?? emptyComposerDraft());
3681 draft.historyIndex = next;
3682 draft.text = historyText ?? draft.savedText;
3683 draftsBySessionRef.current[sourceDraftKey] = draft;
3684 recordComposerEdit(
3685 sourceDraftKey,
3686 beforeEdit,
3687 composerEditSnapshot(sourceDraftKey, { start: draft.text.length, end: draft.text.length }),
3688 );
3689 }
3690 if (historyDirection === "up" && historyEntriesRef.current.length - 1 - next <= PROMPT_HISTORY_PREFETCH_REMAINING) {
3691 prefetchPromptHistoryTail();
3692 }
3693 })();
3694 return;
3695 }
3696
3697 if (menuMode && !composing) {
3698 if (e.key === "ArrowDown" && count > 0) {
3699 e.preventDefault();
3700 if (menuMode === "slash") {
3701 if (slashSelectableIndices.length > 0) {
3702 setActive((current) => {
3703 const currentPosition = slashSelectableIndices.indexOf(current);
3704 return slashSelectableIndices[(currentPosition + 1) % slashSelectableIndices.length];
3705 });
3706 }
3707 } else {
3708 setActive((i) => (i + 1) % count);
3709 }
3710 return;
3711 }
3712 if (e.key === "ArrowUp" && count > 0) {
3713 e.preventDefault();
3714 if (menuMode === "slash") {
3715 if (slashSelectableIndices.length > 0) {
3716 setActive((current) => {
3717 const currentPosition = slashSelectableIndices.indexOf(current);
3718 const previousPosition = currentPosition < 0 ? 0 : currentPosition - 1;
3719 return slashSelectableIndices[
3720 (previousPosition + slashSelectableIndices.length) % slashSelectableIndices.length
3721 ];
3722 });
3723 }
3724 } else {
3725 setActive((i) => (i - 1 + count) % count);
3726 }
3727 return;
3728 }
3729 if (e.key === "Enter" || e.key === "Tab") {
3730 e.preventDefault();
3731 pickActive();
3732 return;
3733 }
3734 if (e.key === "Escape") {
3735 e.preventDefault();
3736 if (menuMode === "pastChats") {
3737 dismissDirectPastChats();
3738 } else if (showPastChats) {
3739 setPastChatQuery("");
3740 setShowPastChats(false);
3741 setActive(0);
3742 } else {
3743 setDismissed(true);
3744 }
3745 return;
3746 }
3747 }
3748
3749 // The send chord (default Enter) sends and the newline chord (default
3750 // Shift+Enter) breaks the line — both configurable in Settings →
3751 // Shortcuts. The default send layout retains legacy modified-Enter send
3752 // aliases; explicit custom bindings are exact. `composing` guards IME confirms.
3753 if (e.key === "Enter" && !composing) {
3754 const enterAction = composerEnterAction(e.nativeEvent, shortcutPlatform);
3755 if (enterAction === "newline-insert") {
3756 e.preventDefault();
3757 insertNewlineAtCaret();
3758 return;
3759 }
3760 if (enterAction === "send") {
3761 e.preventDefault();
3762 submit();
3763 return;
3764 }
3765 if (enterAction !== "newline-native") {
3766 e.preventDefault();
3767 return;
3768 }
3769 // "newline-native" falls through so the input inserts the break itself.
3770 }
3771 // Esc interrupts the in-flight turn (matches the Stop button's hint), and
3772 // restores the text if the server hadn't replied yet.
3773 if (composerEscapeAction(e.nativeEvent, running, composing) === "cancel") {
3774 e.preventDefault();
3775 void handleCancel();
3776 }
3777
3778 // Browser undo owns ordinary DOM edits, while programmatic composer edits
3779 // live in the per-draft transaction stacks. Native barriers preserve the
3780 // real ordering even when later browser edits happen to return to the same
3781 // text (for example type then Backspace).
3782 const undoShortcut = matchesShortcut(e.nativeEvent, "composer.undo", shortcutPlatform);
3783 const redoShortcut = matchesShortcut(e.nativeEvent, "composer.redo", shortcutPlatform)
3784 || (
3785 shortcutPlatform !== "darwin"
3786 && e.ctrlKey
3787 && !e.metaKey
3788 && !e.altKey
3789 && !e.shiftKey
3790 && e.key.toLowerCase() === "y"
3791 );
3792 if (!composing && (undoShortcut || redoShortcut)) {
3793 const targetDraftKey = activeDraftKeyRef.current;
3794 const history = editHistoryForDraft(targetDraftKey);
3795 const current = composerEditSnapshot(targetDraftKey);
3796
3797 if (undoShortcut) {
3798 const transaction = history.undo[history.undo.length - 1];
3799 if (history.undoNativeBarrier) return;
3800 if (!transaction) return;
3801 if (!composerEditStateMatches(current, transaction.after)) {
3802 // A programmatic owner changed state without joining either history.
3803 // Do not let a stale browser entry mutate that unknown boundary.
3804 e.preventDefault();
3805 return;
3806 }
3807 e.preventDefault();
3808 undoComposerEdit(targetDraftKey);
3809 return;
3810 }
3811
3812 const transaction = history.redo[history.redo.length - 1];
3813 if (history.redoNativeBarrier) return;
3814 if (!transaction) {
3815 // A custom edit is a new branch and invalidates native redo entries
3816 // that the browser cannot see. With no custom history, native redo
3817 // remains fully browser-owned.
3818 if (history.undo.length > 0) e.preventDefault();
3819 return;
3820 }
3821 if (!composerEditStateMatches(current, transaction.before)) {
3822 e.preventDefault();
3823 return;
3824 }
3825 e.preventDefault();
3826 redoComposerEdit(targetDraftKey);
3827 }
3828 };
3829
3830 // Keydown handler for the past:chats search <input>. The search input is a
3831 // sibling of the <textarea>, so keyboard events never reach the textarea's
3832 // onKeyDown. We intercept navigation keys here and delegate to the same
3833 // menu logic. Regular typing keys (letters, Backspace, etc.) pass through
3834 // so the user can type a search query.
3835 const onPastChatSearchKeyDown = (e: KeyboardEvent<HTMLInputElement>) => {
3836 const composing = isImeKeyEvent(
3837 e.nativeEvent,
3838 pastChatSearchComposingRef.current,
3839 pastChatSearchLastCompositionEndAt.current,
3840 );
3841 if (composerMenuKeyAction(e.nativeEvent, composing) === "handle") {
3842 e.preventDefault();
3843 e.stopPropagation();
3844 if (e.key === "ArrowDown" && count > 0) {
3845 setActive((i) => (i + 1) % count);
3846 } else if (e.key === "ArrowUp" && count > 0) {
3847 setActive((i) => (i - 1 + count) % count);
3848 } else if (e.key === "Enter" || e.key === "Tab") {
3849 pickActive();
3850 } else if (e.key === "Escape") {
3851 if (menuMode === "pastChats") dismissDirectPastChats();
3852 else {
3853 setPastChatQuery("");
3854 setShowPastChats(false);
3855 setActive(0);
3856 }
3857 }
3858 }
3859 };
3860
3861 // When the run strip is visible inside a user-resized card, the card grows
3862 // by the strip's reserved height so the meta row stays fully visible.
3863 // --composer-height stays in logical card-height space. It may be the saved
3864 // manual floor or a larger content-derived height; the run-strip reservation
3865 // remains separate so the live resize writer uses the same coordinate space.
3866 const waitingPrompt = suspendedByDecision
3867 ? null
3868 : pendingApprovalLabel
3869 ? "approval"
3870 : pendingAsk
3871 ? "ask"
3872 : null;
3873 // Ordinary work keeps the strip too: it carries the live token/throughput
3874 // readout, so it is no longer reserved for states the glow ring cannot name.
3875 // `!suspendedByDecision` mirrors the run-state chain, which yields no label
3876 // while a decision surface owns the footer; without it the reservation would
3877 // hold a strip's height open with nothing to draw in it.
3878 const compactSubmitting = submission === "compact" && !running;
3879 const showRunStrip = Boolean(compactSubmitting || (running && !suspendedByDecision) || retry || waitingPrompt || finishing || runtimeState.unknown || runtimeState.kind === "background_job" || runtimeState.kind === "cancelling");
3880 const effectiveComposerHeight = composerHeight === null
3881 ? null
3882 : resolveComposerContentSizing({
3883 contentHeight: textareaAutoHeight ?? 0,
3884 manualLogicalHeight: composerHeight,
3885 maxLogicalHeight: composerMaxHeight(),
3886 reservedHeight: COMPOSER_AUTO_RESERVED_HEIGHT,
3887 }).logicalHeight;
3888 const composerCardStyle = effectiveComposerHeight === null
3889 ? undefined
3890 : ({
3891 "--composer-height": `${effectiveComposerHeight}px`,
3892 "--composer-run-strip-reserved": `${showRunStrip ? COMPOSER_RUN_STRIP_RESERVED : 0}px`,
3893 } as CSSProperties);
3894 const textareaStyle = !composerResizing && textareaAutoHeight !== null
3895 ? ({ height: `${textareaAutoHeight}px`, overflowY: textareaAutoOverflow ? "auto" : "hidden" } as CSSProperties)
3896 : undefined;
3897 const composerAutoExpanded = composerHeight === null && textareaAutoHeight !== null && textareaAutoHeight > 40;
3898 // Autosize mode flips overflow-y to auto once content exceeds the max
3899 // height; the card modifier restores a thin scrollbar for exactly that
3900 // state so long drafts expose their scrollability (#8494/#8742/#9019).
3901 const composerAutoOverflow = composerHeight === null && textareaAutoOverflow;
3902 const composerResizeValue = effectiveComposerHeight ?? clampComposerHeight((textareaAutoHeight ?? 0) + COMPOSER_AUTO_RESERVED_HEIGHT);
3903 void onSetMode;
3904 const chooseApprovalMode = (nextMode: ToolApprovalMode) => {
3905 onSetToolApprovalMode(nextMode);
3906 requestActiveDraftFrame(focusComposerInput);
3907 };
3908 const chooseTaskMode = (nextMode: CollaborationMode) => {
3909 setContentMenuOpen(false);
3910 closeIntentMenu(() => {
3911 if (nextMode !== collaborationMode) onSetCollaborationMode(nextMode);
3912 requestActiveDraftFrame(focusComposerInput);
3913 });
3914 };
3915 const stopGoalMode = () => {
3916 setContentMenuOpen(false);
3917 closeIntentMenu(() => {
3918 savedInput.setGoalDraft(false);
3919 onClearGoal();
3920 requestActiveDraftFrame(focusComposerInput);
3921 });
3922 };
3923 const taskModeShortKey = collaborationMode === "plan"
3924 ? "composer.taskModePlanShort"
3925 : collaborationMode === "goal"
3926 ? "composer.taskModeGoalShort"
3927 : "composer.taskModeDirectShort";
3928 const TaskModeIcon = collaborationMode === "plan" ? Lightbulb : collaborationMode === "goal" ? Target : ArrowRight;
3929 const taskModeTriggerLabel = `${t("common.close")} ${t(taskModeShortKey)}`;
3930 const taskModeTooltipLabel = taskModeTriggerLabel;
3931 const effortOptions = asArray(effort?.options);
3932 const effortLabel = (id: string) => id === "auto" ? t("common.auto") : effortOptions.find((option) => option.id === id)?.name || id;
3933 const effortLevels = effort?.options ? ["auto", ...effortOptions.map((option) => option.id)] : asArray(effort?.levels);
3934 const currentEffort = effort?.current || "auto";
3935 const hasEffort = Boolean(effort?.supported && effortLevels.length > 0);
3936 const chooseEffortLevel = (level: string) => {
3937 if (level !== currentEffort) onSetEffort(level);
3938 };
3939 // Run-strip state machine: retry > waiting-approval > waiting-ask > streaming.
3940 // Decision surfaces own the "waiting on user" UI; while suspendedByDecision
3941 // is true we still pause the work clock but do not render a waiting strip.
3942 const pauseWorkClock = suspendedByDecision || Boolean(waitingPrompt);
3943 // Decision surfaces hide the whole composer, so mode controls stay disabled.
3944 // Legacy tests that pass pendingApprovalLabel without suspendedByDecision
3945 // still keep the approval bar usable mid-prompt.
3946 const approvalBarDisabled = Boolean(disabled) && !(pendingApprovalLabel && !suspendedByDecision);
3947 // Waiting on the user is not model work. Approval/ask wait is owned by the
3948 // per-tab controller (turnWaitAccumMs + promptWaitStartedAt) so background
3949 // tabs keep accumulating. Composer only tracks local pauses for surfaces the
3950 // controller does not know about (clear-context, legacy strip tests).
3951 const controllerTracksWait = typeof promptWaitStartedAt === "number" && promptWaitStartedAt > 0;
3952 const controllerWaitMs = Math.max(0, turnWaitAccumMs || 0)
3953 + (controllerTracksWait ? Math.max(0, now - promptWaitStartedAt) : 0);
3954 const trackLocalPause = pauseWorkClock && !controllerTracksWait;
3955 const [localWaitAccumMs, setLocalWaitAccumMs] = useState(0);
3956 const localPauseSinceRef = useRef<number | null>(null);
3957 useEffect(() => {
3958 localPauseSinceRef.current = null;
3959 setLocalWaitAccumMs(0);
3960 if (trackLocalPause) localPauseSinceRef.current = Date.now();
3961 // trackLocalPause is read from the render that changed draft/turn.
3962 // eslint-disable-next-line react-hooks/exhaustive-deps -- intentional scope-only reset
3963 }, [draftKey, turnStartAt]);
3964 useEffect(() => {
3965 if (trackLocalPause) {
3966 if (localPauseSinceRef.current == null) localPauseSinceRef.current = Date.now();
3967 return;
3968 }
3969 if (localPauseSinceRef.current == null) return;
3970 const delta = Date.now() - localPauseSinceRef.current;
3971 localPauseSinceRef.current = null;
3972 if (delta > 0) setLocalWaitAccumMs((total) => total + delta);
3973 }, [trackLocalPause]);
3974 const localOpenWaitMs = localPauseSinceRef.current != null
3975 ? Math.max(0, now - localPauseSinceRef.current)
3976 : 0;
3977 const waitAccumMs = controllerWaitMs + localWaitAccumMs + localOpenWaitMs;
3978 // Close menus/popovers while a decision surface owns the footer.
3979 useEffect(() => {
3980 if (!suspendedByDecision) return;
3981 setDismissed(true);
3982 setContentMenuOpen(false);
3983 setDirectPastChats(false);
3984 setShowPastChats(false);
3985 closeIntentMenu();
3986 }, [suspendedByDecision, closeIntentMenu]);
3987 const { liveOutput, liveModelActiveAt, liveRateOutputQuarters } = useLiveTurnMetrics(liveStore, tabId);
3988 const turnPhaseLabel = turnPhaseStatusLabel(turnPhase, t);
3989 const readStatusText = readStatusLabel(readStatuses, t);
3990 const runStateText = runtimeState.unknown ? t("runtime.unknown") : compactSubmitting ? t("compaction.preparing") : runtimeState.kind === "maintenance_finalizing" ? t("compaction.saving") : runtimeState.kind === "maintenance_cancelling" ? t("compaction.stopping") : runtimeState.kind === "maintenance_running" ? t("compaction.working") : finishing ? t("runtime.finishing") : runtimeState.kind === "cancelling" ? t("status.jobStopping") : runtimeState.kind === "background_job" ? t("runtime.background", { count: runtimeState.state?.backgroundJobs ?? 0 }) : retry
3991 ? recoveryStatusText(t, retry, now)
3992 : waitingPrompt === "approval"
3993 ? t("composer.runWaitingApproval", { tool: pendingApprovalLabel ?? "" })
3994 : waitingPrompt === "ask"
3995 ? t("composer.runWaitingAsk")
3996 : running && !suspendedByDecision
3997 ? turnPhaseLabel
3998 : null;
3999 // Second-quantized: the run strip has no sub-second resolution, and `now` is
4000 // a fresh Date.now() every render, so keying the memo on it would never hit.
4001 const metricsTick = Math.floor(now / 1000);
4002 const runMetrics = useMemo(() => {
4003 const metrics = turnMetrics({
4004 now, turnStartAt, turnDoneAt, running: running && !maintenanceActive, waitAccumMs, lastTurnWaitAccumMs,
4005 turnTokens, turnOutputTokens, lastTurnOutputTokens, turnOutputCharsAtUsage,
4006 turnArgChars, turnModelActiveMs, turnModelActiveAt, liveModelActiveAt,
4007 turnRateOutputQuarters: liveRateOutputQuarters ?? turnRateOutputQuarters,
4008 live: liveOutput, turnOutputEstimated, lastTurnOutputEstimated,
4009 });
4010 if (!metrics) return null;
4011 // The parenthesised group reads as a subordinate clause, so the state word
4012 // keeps its own sentence. Elapsed leads because the strip's real job is
4013 // answering "is this stuck?". Only the token reading carries the estimate
4014 // cue: the clock is exact, and throughput is derived from it. The popover
4015 // keeps a per-value cue because it also shows settled, exact readings.
4016 const estimate = metrics.estimated ? "≈" : "";
4017 const live = metrics.tokens > 0 && !turnDoneAt;
4018 // Punctuation is not what groups these: the readings are pinned right and
4019 // dimmed, so a long state word ellipsises instead of cutting them. The
4020 // throughput is returned apart because it is the one reading the strip may
4021 // shed whole when the composer is narrow.
4022 const stripParts = live
4023 ? [formatElapsedMs(metrics.elapsedMs),
4024 `${estimate}${formatTokens(metrics.tokens)} ${t("status.tokens")}`]
4025 : [];
4026 const stripSpeed = live && (liveModelActiveAt ?? turnModelActiveAt) && metrics.tps !== null
4027 ? formatTps(metrics.tps)
4028 : "";
4029 return {
4030 elapsed: formatElapsedMs(metrics.elapsedMs),
4031 tokens: metrics.tokens > 0
4032 ? `${metrics.estimated ? "≈" : ""}${formatTokens(metrics.tokens)} ${t("status.tokens")}`
4033 : null,
4034 tps: formatTps(metrics.tps, metrics.estimated || (liveRateOutputQuarters ?? turnRateOutputQuarters) !== undefined),
4035 stripParts,
4036 stripSpeed,
4037 };
4038 }, [metricsTick, running, maintenanceActive, turnStartAt, turnDoneAt, waitAccumMs, lastTurnWaitAccumMs,
4039 turnTokens, turnOutputTokens, lastTurnOutputTokens, turnOutputCharsAtUsage, turnArgChars,
4040 turnModelActiveMs, turnModelActiveAt, liveModelActiveAt, liveOutput, turnOutputEstimated,
4041 turnRateOutputQuarters, liveRateOutputQuarters,
4042 lastTurnOutputEstimated, t]);
4043 // The strip's own sr-only sibling keeps announcing the stable state alone, so
4044 // these churning numbers stay out of the live region.
4045 const runStrip = runMetrics?.stripParts.length ? runMetrics : null;
4046 const submitEmpty = !text.trim() && attachments.length === 0 && workspaceRefs.length === 0 &&
4047 !invocations.some((invocation) => invocation.command.kind === "skill");
4048 const submitBlocked = queueEditing || Boolean(submission) || (!pendingFollowup && (pendingPaste > 0 || (submitEmpty && !(goalModeOn && !activeGoal)) || disabled || (!running && submitDisabled) || readOnly));
4049 const submitUnavailableHint = !running && submitDisabled ? submitDisabledReason : undefined;
4050 const submitTooltip = pendingFollowup ? t("runtime.checkReceipt") : running
4051 ? t("composer.queueGuidance", { combo: sendComboLabel })
4052 : t("composer.send", { combo: sendComboLabel });
4053 const composerPlaceholder = readOnly
4054 ? t("composer.readOnlyChannel")
4055 : disabled
4056 ? t("common.loading")
4057 : running
4058 ? t("composer.steerPlaceholder", { combo: sendComboLabel })
4059 : goalModeOn && !activeGoal
4060 ? t("composer.goalInputPlaceholder")
4061 : planModeOn
4062 ? t("composer.planInputPlaceholder")
4063 : t("composer.placeholder");
4064 const composerMetaClass = [
4065 "composer-meta composer-meta--unified",
4066 hasEffort ? "composer-meta--has-effort" : "composer-meta--no-effort",
4067 ].join(" ");
4068
4069 const inputSelection = getInputSelection();
4070 const hasInputSelection = inputSelection.from !== inputSelection.to;
4071 // Platform-correct hint: ⌘ on macOS, Ctrl elsewhere — same formatter the
4072 // shortcut settings UI uses.
4073 const editMenuShortcut = (key: string) =>
4074 formatShortcutCombo(
4075 shortcutPlatform === "darwin" ? { key, meta: true } : { key, ctrl: true },
4076 shortcutPlatform,
4077 );
4078 const inputMenuItems: ContextMenuItem[] = [
4079 {
4080 key: "undo",
4081 label: t("shortcuts.action.composerUndo"),
4082 shortcut: undoComboLabel,
4083 disabled: disabled || !canUndoComposerEdit(activeDraftKeyRef.current),
4084 onSelect: () => {
4085 setInputMenuPoint(null);
4086 undoComposerEdit(activeDraftKeyRef.current);
4087 },
4088 },
4089 {
4090 key: "redo",
4091 label: t("shortcuts.action.composerRedo"),
4092 shortcut: redoComboLabel,
4093 disabled: disabled || !canRedoComposerEdit(activeDraftKeyRef.current),
4094 onSelect: () => {
4095 setInputMenuPoint(null);
4096 redoComposerEdit(activeDraftKeyRef.current);
4097 },
4098 },
4099 {
4100 type: "separator",
4101 key: "edit-history-separator",
4102 },
4103 {
4104 key: "cut",
4105 label: t("common.cut"),
4106 shortcut: editMenuShortcut("x"),
4107 disabled: disabled || !hasInputSelection,
4108 onSelect: () => void copyComposerSelection(true),
4109 },
4110 {
4111 key: "copy",
4112 label: t("common.copy"),
4113 shortcut: editMenuShortcut("c"),
4114 disabled: !hasInputSelection,
4115 onSelect: () => void copyComposerSelection(),
4116 },
4117 {
4118 key: "paste",
4119 label: t("common.paste"),
4120 shortcut: editMenuShortcut("v"),
4121 disabled,
4122 onSelect: () => void pasteIntoComposer(),
4123 },
4124 {
4125 key: "select-all",
4126 label: t("common.selectAll"),
4127 shortcut: editMenuShortcut("a"),
4128 disabled: text.length === 0,
4129 onSelect: selectAllComposerText,
4130 },
4131 ];
4132
4133 return (
4134 <div
4135 ref={composerWrapRef}
4136 data-queue-editing={queueEditing ? "true" : undefined}
4137 className={[
4138 "composer-wrap",
4139 decisionPending ? "composer-wrap--decision-pending" : "",
4140 heroMode ? "composer-wrap--hero" : "",
4141 ].filter(Boolean).join(" ")}
4142 data-native-drop-target={attachmentInputEnabled ? "" : undefined}
4143 onDropCapture={onFileDropCapture}
4144 >
4145 <ComposerModelApplicationRecovery tabId={tabId} local={savedInput} remote={remoteApplication} setRemote={setRemoteApplication} draftKey={draftKey} text={followupDraftFingerprint(draftKey)} running={running} onUseApplied={choice=>trackPersistentTask(activeDraftKeyRef.current,performSubmit(false,choice))}/>
4146 <SessionInputRecovery input={savedInput} />
4147 <input
4148 ref={fileInputRef}
4149 className="composer-content-file-input"
4150 type="file"
4151 multiple
4152 disabled={!attachmentInputEnabled}
4153 tabIndex={-1}
4154 aria-hidden="true"
4155 onChange={(event) => {
4156 const files = Array.from(event.currentTarget.files ?? []);
4157 event.currentTarget.value = "";
4158 if (files.length > 0) attachFiles(files);
4159 requestActiveDraftFrame(() => taRef.current?.focus());
4160 }}
4161 />
4162 {!heroMode && <AnchoredPopover
4163 open={(contentMenuOpen || intentMenuOpen) && !disabled && !readOnly && (!running || (goalModeOn && Boolean(activeGoal)))}
4164 anchorRef={contentMenuOpen ? contentMenuAnchorRef : intentMenuAnchorRef}
4165 onClose={() => { setContentMenuOpen(false); closeIntentMenu(); }}
4166 className="composer-access-menu composer-content-menu composer-intent-menu composer-menu-surface"
4167 align="start"
4168 >
4169 <ComposerContentMenuActions
4170 attachmentInputEnabled={attachmentInputEnabled}
4171 textPresent={text.trim().length > 0}
4172 onChooseAttachment={chooseAttachmentFiles}
4173 onInsertTrigger={insertContentTrigger}
4174 />
4175 <div
4176 className="composer-access-menu__section"
4177 role="menu"
4178 aria-label={t("composer.intentMenuTitle")}
4179 onMouseEnter={creationChrome ? onIntentPopoverEnter : undefined}
4180 onMouseLeave={creationChrome ? onIntentHoverLeave : undefined}
4181 >
4182 <div className="composer-access-menu__label">{t("composer.intentMenuTitle")}</div>
4183 <button
4184 type="button"
4185 role="menuitemradio"
4186 aria-checked={planModeOn}
4187 className={`composer-access-menu__item composer-intent-menu__item${planModeOn ? " composer-access-menu__item--active" : ""}`}
4188 onClick={() => chooseTaskMode(planModeOn ? "normal" : "plan")}
4189 disabled={disabled || running}
4190 >
4191 <List size={16} />
4192 <span className="composer-access-menu__copy">
4193 <span className="composer-access-menu__title">{t("composer.taskModePlan")}</span>
4194 </span>
4195 {planModeOn && <Check className="composer-intent-menu__check" size={16} aria-hidden="true" />}
4196 </button>
4197 <button
4198 type="button"
4199 role="menuitemradio"
4200 aria-checked={goalModeOn}
4201 className={`composer-access-menu__item composer-intent-menu__item${goalModeOn ? " composer-access-menu__item--active" : ""}`}
4202 onClick={() => chooseTaskMode(goalModeOn && !activeGoal ? "normal" : "goal")}
4203 disabled={disabled || running}
4204 title={activeGoal || undefined}
4205 >
4206 <Target size={16} />
4207 <span className="composer-access-menu__copy">
4208 <span className="composer-access-menu__title">{t("composer.taskModeGoal")}</span>
4209 </span>
4210 {goalModeOn && <Check className="composer-intent-menu__check" size={16} aria-hidden="true" />}
4211 </button>
4212 {goalModeOn && activeGoal && (
4213 <div className="composer-intent-menu__goal-actions">
4214 <div className="composer-intent-menu__goal-runtime">
4215 {goalView && (
4216 <span className="composer-intent-menu__goal-runtime-line">
4217 {goalView.phase === "active" && goalView.activation === "armed"
4218 ? running ? t("composer.goalRunning") : t("composer.goalWaitingNext")
4219 : goalView.phase === "active"
4220 ? t("composer.goalWaitingResume")
4221 : goalView.phase === "paused"
4222 ? t("composer.goalPaused")
4223 : goalView.phase === "blocked"
4224 ? t("composer.goalBlocked")
4225 : t("composer.goalComplete")}
4226 {goalView.blockedReason?.message ? ` — ${goalView.blockedReason.message}` : ""}
4227 </span>
4228 )}
4229 {goalRuntime && (
4230 <span className="composer-intent-menu__goal-runtime-line">
4231 {t("composer.goalRuntimeLine", {
4232 turnsUsed: goalRuntime.turnsUsed,
4233 tokensUsed: formatTokens(goalRuntime.tokensUsed),
4234 requestsUsed: goalRuntime.requestsUsed ?? 0,
4235 workTime: formatGoalWorkTime(goalRuntime.workDurationMs),
4236 })}
4237 </span>
4238 )}
4239 {!goalView && goalStatus === "blocked" && !goalRuntime?.stopCause && (
4240 <span className="composer-intent-menu__goal-runtime-line composer-intent-menu__goal-runtime-line--blocked">
4241 {t("composer.goalBlocked")}
4242 </span>
4243 )}
4244 {!goalView && goalStatus === "blocked" && goalRuntime?.stopCause && (
4245 <span className="composer-intent-menu__goal-runtime-line composer-intent-menu__goal-runtime-line--paused">
4246 {t("composer.goalPaused")}
4247 {goalRuntime.lastReason ? ` — ${goalRuntime.lastReason}` : ""}
4248 </span>
4249 )}
4250 </div>
4251 <GoalLifecycleActions
4252 goalView={goalView} goalStatus={goalStatus} disabled={disabled} running={running}
4253 onEditGoal={onEditGoal} onPauseGoal={onPauseGoal} onResumeGoal={onResumeGoal} onStopGoal={stopGoalMode}
4254 />
4255 </div>
4256 )}
4257 </div>
4258 </AnchoredPopover>}
4259 {menuMode === "slash" && (
4260 <SlashMenu
4261 items={slashMatches}
4262 activeIndex={active}
4263 onPick={pickCommand}
4264 onHover={setActive}
4265 isDisabled={slashCommandDisabled}
4266 disabledReason={t("slash.startOnly")}
4267 />
4268 )}
4269 {menuMode === "slasharg" && argRes && (
4270 <ArgMenu items={argRes.items} activeIndex={active} onPick={pickArg} onHover={setActive} />
4271 )}
4272 {(menuMode === "at" || menuMode === "pastChats") && (
4273 showPastChats ? (
4274 <div className="slashmenu" role="listbox">
4275 {loadingPastChats ? (
4276 <div className="slashmenu__item slashmenu__item--empty">
4277 <span className="slashmenu__name">{t("composer.pastChatsLoading")}</span>
4278 </div>
4279 ) : pastChats.length === 0 ? (
4280 <div className="slashmenu__item slashmenu__item--empty">
4281 <span className="slashmenu__name">{t("composer.pastChatsEmpty")}</span>
4282 </div>
4283 ) : (
4284 <>
4285 <div className="slashmenu__item slashmenu__item--search" onMouseDown={(ev) => ev.preventDefault()}>
4286 <Search size={13} className="filemenu__icon" />
4287 <input
4288 className="slashmenu__search"
4289 type="text"
4290 placeholder={t("composer.pastChatsSearch")}
4291 value={pastChatQuery}
4292 // In the token-driven flows (typed "#" or the content-menu
4293 // action) focus must stay in the composer: typing there
4294 // extends the token and filters the list, and stealing
4295 // focus mid-word hijacks ordinary "#123" text. Only the
4296 // @-flow subpanel, which has no composer token to type
4297 // into, moves focus here.
4298 autoFocus={!directPastChats}
4299 onChange={(ev) => {
4300 setPastChatQuery(ev.target.value);
4301 setActive(0);
4302 }}
4303 onCompositionStart={() => {
4304 pastChatSearchComposingRef.current = true;
4305 }}
4306 onCompositionEnd={() => {
4307 pastChatSearchComposingRef.current = false;
4308 pastChatSearchLastCompositionEndAt.current = Date.now();
4309 }}
4310 onBlur={() => {
4311 pastChatSearchComposingRef.current = false;
4312 }}
4313 onKeyDown={onPastChatSearchKeyDown}
4314 />
4315 </div>
4316 {filteredPastChats.length === 0 ? (
4317 <div className="slashmenu__item slashmenu__item--empty">
4318 <span className="slashmenu__name">{t("composer.pastChatsNoMatches")}</span>
4319 </div>
4320 ) : (
4321 filteredPastChats.map((session, i) => {
4322 // Hover preview stays on SessionMeta and never reads the transcript.
4323 const turnsLabel = sessionTurnsLabel(session, t);
4324 const ts = session.lastActivityAt || session.modTime || session.createdAt;
4325 const preview = truncatePreview(session.preview);
4326 const pathText = session.workspaceRoot || session.path;
4327 const tooltipLabel =
4328 turnsLabel || ts || preview || pathText ? (
4329 <div className="past-chat-hover">
4330 <div className="past-chat-hover__title">{pastChatTitle(session)}</div>
4331 {preview && <div className="past-chat-hover__preview">{preview}</div>}
4332 {(turnsLabel || ts) && (
4333 <div className="past-chat-hover__meta">
4334 {turnsLabel && <span>{turnsLabel}</span>}
4335 {ts && <span>· {fmtSessionTime(ts)}</span>}
4336 </div>
4337 )}
4338 {pathText && <div className="past-chat-hover__path">{pathText}</div>}
4339 </div>
4340 ) : null;
4341 return (
4342 <Tooltip key={session.path} block label={tooltipLabel}>
4343 <button
4344 className={`slashmenu__item ${i === active ? "slashmenu__item--active" : ""}`}
4345 onMouseDown={(ev) => {
4346 ev.preventDefault();
4347 pickSession(session);
4348 }}
4349 onMouseMove={() => setActive(i)}
4350 >
4351 <MessageSquare size={13} className="filemenu__icon" />
4352 <span className="slashmenu__name slashmenu__name--file">
4353 {pastChatTitle(session)}
4354 {turnsLabel ? ` (${turnsLabel})` : ""}
4355 </span>
4356 </button>
4357 </Tooltip>
4358 );
4359 })
4360 )}
4361 </>
4362 )}
4363 <button
4364 className="slashmenu__item slashmenu__item--back"
4365 onMouseDown={(ev) => {
4366 ev.preventDefault();
4367 if (menuMode === "pastChats") dismissDirectPastChats();
4368 else {
4369 setPastChatQuery("");
4370 setShowPastChats(false);
4371 setActive(0);
4372 }
4373 }}
4374 >
4375 <span className="slashmenu__name">
4376 {menuMode === "pastChats" ? t("composer.contentCloseSessions") : t("composer.backToFiles")}
4377 </span>
4378 </button>
4379 </div>
4380 ) : menuMode === "at" ? (
4381 <VirtualMenu
4382 items={atMenuItems}
4383 activeIndex={active}
4384 itemKey={atMenuItemKey}
4385 renderItem={(it, i) =>
4386 it.kind === "pastChats" ? (
4387 <button
4388 className={`slashmenu__item${i === active ? " slashmenu__item--active" : ""}`}
4389 onMouseDown={(ev) => {
4390 ev.preventDefault();
4391 void openPastChats();
4392 }}
4393 onMouseMove={() => setActive(i)}
4394 >
4395 <MessageSquare size={13} className="filemenu__icon" />
4396 <span className="slashmenu__name">{PAST_CHATS_MENU_ITEM}</span>
4397 </button>
4398 ) : (
4399 <button
4400 role="option"
4401 aria-selected={i === active}
4402 className={`slashmenu__item ${i === active ? "slashmenu__item--active" : ""}`}
4403 onMouseDown={(ev) => {
4404 ev.preventDefault();
4405 pickEntry(it.entry);
4406 }}
4407 onMouseMove={() => setActive(i)}
4408 >
4409 {it.entry.isDir ? (
4410 <Folder size={13} className="filemenu__icon filemenu__icon--dir" />
4411 ) : (
4412 <FileText size={13} className="filemenu__icon" />
4413 )}
4414 <span className="slashmenu__name slashmenu__name--file">
4415 {dirEntryMenuLabel(it.entry)}
4416 {it.entry.isDir ? "/" : ""}
4417 </span>
4418 </button>
4419 )
4420 }
4421 />
4422 ) : null
4423 )}
4424 {typeof app.InboxQueueForTarget === "function" ? <Suspense fallback={null}>
4425 <ComposerInboxQueue key={queueScope} scope={queueScope} tabId={tabId || ""} sessionPath={inboxSessionPath || ""}
4426 items={pendingGuidance} snapshot={inboxSnapshot} disabled={Boolean(disabled || readOnly)} running={running}
4427 onSnapshot={acceptInboxSnapshot} onRefresh={refreshInboxQueue}
4428 onEditingChange={onQueueEditingChange} turnId={turnId}
4429 onRestoreDraft={value => setTextCaretEnd([textRef.current, value].filter(Boolean).join("\n\n"))}
4430 onStop={!finishing && !runtimeState.unknown ? () => void handleCancel() : undefined}
4431 stopDisabled={runtimeState.cancellable === false || cancelSettlingDraftsRef.current.has(draftKey)} />
4432 </Suspense> : pendingGuidance.length > 0 && (
4433 <Suspense fallback={null}>
4434 <ComposerGuidanceShelf
4435 recovery={pendingGuidance[0]?.paused && !pendingGuidance.some((item) => guidanceIsInFlight(item.state)) ? {
4436 draftKey,
4437 tabId: tabId || "",
4438 count: pendingGuidance[0].recoveredCount || pendingGuidance.length,
4439 recovered: Boolean(pendingGuidance[0].recoveredCount),
4440 } : null}
4441 recoveryDisabled={Boolean(disabled || readOnly)}
4442 items={pendingGuidance}
4443 expanded={guidanceExpanded}
4444 running={running}
4445 disabled={Boolean(disabled)}
4446 readOnly={readOnly}
4447 sendingId={guidanceSendingId}
4448 onReview={() => setGuidanceExpanded(true)}
4449 onRecoveryResumed={() => setGuidanceRetryNonce((value) => value + 1)}
4450 onRecoveryError={(error) => showToast(formatInboxError(error, locale), "warn")}
4451 onToggleExpanded={() => setGuidanceExpanded((value) => !value)}
4452 onSend={(item) => void sendQueuedGuidance(item)}
4453 onDismiss={(item) => void dismissQueuedGuidance(item)}
4454 onEdit={(item, text) => editQueuedGuidance(item, text)}
4455 />
4456 </Suspense>
4457 )}
4458 <ComposerPinnedFilesShelf tabId={tabId || ""} pinnedFiles={pinnedFiles} />
4459 {(attachments.length > 0 || workspaceRefs.length > 0 || sessionRefs.length > 0 || selectedTextRefs.length > 0) && (
4460 <div className="composer-context" aria-label={t("composer.contextItems")}>
4461 {sortComposerAttachments(attachments).map((a) => {
4462 const imageOnly = Boolean(a.previewUrl) && attachments.every((item) => item.previewUrl) && workspaceRefs.length === 0 && sessionRefs.length === 0;
4463 return (
4464 <ComposerContextCard
4465 key={a.path}
4466 variant="attachment"
4467 tooltipLabel={a.previewUrl ? `${t("imageViewer.clickToPreview")} — ${a.path}` : a.path}
4468 removeLabel={t("composer.removeImage")}
4469 onRemove={() => removeAttachment(a.path)}
4470 previewUrl={a.previewUrl}
4471 onImageClick={a.previewUrl ? () => openComposerImageViewer(a.previewUrl!, attachmentName(a)) : undefined}
4472 imageOnly={imageOnly}
4473 name={attachmentName(a)}
4474 meta={attachmentExt(attachmentName(a)) || t("msg.fileAttachment")}
4475 />
4476 );
4477 })}
4478 {workspaceRefs.map((ref) => (
4479 <ComposerContextCard
4480 key={workspaceReferenceKey(ref)}
4481 variant="workspace"
4482 tooltipLabel={ref.displayPath ? formatWorkspaceReference(ref.displayPath, ref.isDir) : formatWorkspaceReference(ref.path, ref.isDir)}
4483 removeLabel={t("composer.removeReference")}
4484 onRemove={() => removeWorkspaceReference(ref)}
4485 folder={Boolean(ref.isDir)}
4486 label={ref.isDir ? `${baseName(ref.displayPath || ref.path)}/` : baseName(ref.displayPath || ref.path)}
4487 />
4488 ))}
4489 {sessionRefs.map((ref) => (
4490 <div
4491 className="composer-context__item composer-context__item--session"
4492 key={ref.path}
4493 >
4494 <Tooltip label={ref.preview || ref.title}>
4495 <span className="composer-context__label">
4496 <MessageSquare size={15} />
4497 <span>
4498 {ref.title}
4499 {sessionTurnsLabel(ref, t) ? ` (${sessionTurnsLabel(ref, t)})` : ""}
4500 </span>
4501 </span>
4502 </Tooltip>
4503 <Tooltip label={t("composer.removeSessionReference")}>
4504 <button
4505 type="button"
4506 onClick={() => removeSessionRef(ref.path)}
4507 >
4508 <X size={13} />
4509 </button>
4510 </Tooltip>
4511 </div>
4512 ))}
4513 {selectedTextRefs.map((reference) => (
4514 <ComposerContextCard
4515 key={reference.id}
4516 variant="selection"
4517 tooltipLabel={reference.path
4518 ? <CodeViewer value={reference.text} language={languageFor(reference.path)} maxHeight={240} />
4519 : reference.source === "terminal"
4520 ? <CodeViewer value={reference.text} language="console" maxHeight={240} />
4521 : <Markdown text={reference.text} />}
4522 removeLabel={t("composer.removeSelectedText")}
4523 onRemove={() => {
4524 const next = selectedTextRefsRef.current.filter((item) => item.id !== reference.id);
4525 selectedTextRefsRef.current = next;
4526 setSelectedTextRefs(next);
4527 requestActiveDraftFrame(focusComposerInput);
4528 }}
4529 name={reference.path ? reference.path.split("/").filter(Boolean).pop() ?? reference.path : selectedTextSnippet(reference.text)}
4530 meta={reference.path
4531 ? t("composer.selectedCode")
4532 : reference.source === "terminal"
4533 ? t("composer.selectedTerminal")
4534 : reference.source === "browser"
4535 ? (locale === "en" ? "Page element" : "页面元素")
4536 : t("composer.selectedText")}
4537 icon={reference.path
4538 ? <FileText size={20} />
4539 : <MessageSquare size={20} />}
4540 />
4541 ))}
4542 </div>
4543 )}
4544 <ImageViewer
4545 open={imageViewer.open}
4546 imageUrl={imageViewer.url}
4547 imageName={imageViewer.name}
4548 onClose={closeComposerImageViewer}
4549 />
4550 {activePastedBlocks.length > 0 && (
4551 <div className="composer__pasted">
4552 {activePastedBlocks.map((block) => {
4553 const open = openPastedLabels.includes(block.label);
4554 return (
4555 <div className="composer__pasted-block" key={block.label}>
4556 <div className="composer__pasted-head">
4557 <FileText size={15} />
4558 <span className="composer__pasted-label">{block.label}</span>
4559 <div className="composer__pasted-actions">
4560 <Tooltip label={t(open ? "composer.pastedHidePreview" : "composer.pastedShowPreview")}>
4561 <button type="button" onClick={() => togglePastedPreview(block.label)}>
4562 <Eye size={14} />
4563 </button>
4564 </Tooltip>
4565 <Tooltip label={t("composer.pastedExpand")}>
4566 <button type="button" onClick={() => expandPastedBlock(block)}>
4567 {t("composer.pastedExpand")}
4568 </button>
4569 </Tooltip>
4570 <Tooltip label={t("composer.pastedRemove")}>
4571 <button type="button" onClick={() => removePastedBlock(block)}>
4572 <Trash2 size={14} />
4573 </button>
4574 </Tooltip>
4575 </div>
4576 </div>
4577 {open && <pre className="composer__pasted-preview">{block.text}</pre>}
4578 </div>
4579 );
4580 })}
4581 </div>
4582 )}
4583 {retry?.recovery?.waiting && <Suspense fallback={null}><RecoveryWaitBanner retry={retry} now={now} onStop={() => void handleCancel()} stopDisabled={cancelSettlingDraftsRef.current.has(draftKey)} /></Suspense>}
4584 {pendingFollowup && <div className="composer-guidance-item" role="status">
4585 <span className="composer-guidance-item__text" title={pendingFollowup.display}>{pendingFollowup.display}</span>
4586 <span>{t("runtime.unconfirmed")}</span>
4587 </div>}
4588 <div className={`composer-workspace-frame${workspaceContext ? " composer-workspace-frame--context" : " composer-workspace-frame--plain"}`}>
4589 {workspaceContext && running && !waitingPrompt && !retry?.recovery?.waiting && !finishing && !runtimeState.unknown ? (
4590 <span className="composer-glowring" aria-hidden="true"><i /></span>
4591 ) : null}
4592 {workspaceContext ? (
4593 <Suspense fallback={<div className="composer-workspace-bar-fallback" aria-hidden="true" />}>
4594 <ComposerWorkspaceContextBar context={workspaceContext} />
4595 </Suspense>
4596 ) : null}
4597 <div
4598 className={`composer-card${composerHeight !== null || composerResizing ? " composer-card--resized" : ""}${composerAutoExpanded ? " composer-card--autosized" : ""}${composerAutoOverflow ? " composer-card--auto-overflow" : ""}${composerResizing ? " composer-card--resizing" : ""}${running && !finishing && !runtimeState.unknown ? (waitingPrompt ? " composer-card--waiting" : " composer-card--running") : ""}`}
4599 ref={composerCardRef}
4600 style={composerCardStyle}
4601 >
4602 {!workspaceContext && running && !waitingPrompt && !retry?.recovery?.waiting && (
4603 <span className="composer-glowring" aria-hidden="true"><i /></span>
4604 )}
4605 <button
4606 className="composer-resize-handle"
4607 type="button"
4608 role="separator"
4609 aria-orientation="horizontal"
4610 aria-label={t("composer.resize")}
4611 aria-valuemin={COMPOSER_MIN_HEIGHT}
4612 aria-valuemax={composerMaxHeight()}
4613 aria-valuenow={composerResizeValue}
4614 title={t("composer.resize")}
4615 onPointerDown={onComposerResizeStart}
4616 onKeyDown={onComposerResizeKeyDown}
4617 onDoubleClick={resetComposerHeight}
4618 />
4619 {(readStatusText || (showRunStrip && runStateText)) && (
4620 <div className={`composer-run-strip${waitingPrompt ? " composer-run-strip--waiting" : ""}`}>
4621 {!finishing && !runtimeState.unknown && <span className="composer-run-strip__dot" aria-hidden="true" />}
4622 <span className="composer-run-strip__text">
4623 <span className="composer-run-strip__state">{readStatusText || runStateText}</span>
4624 {runStrip && !compactSubmitting && !maintenanceActive && (
4625 <span className="composer-run-strip__metrics">
4626 {runStrip.stripParts.map((part) => (
4627 <span className="composer-run-strip__metric" key={part}>{` ${part}`}</span>
4628 ))}
4629 {runStrip.stripSpeed && (
4630 <span className="composer-run-strip__metric composer-run-strip__metric--optional">{` ${runStrip.stripSpeed}`}</span>
4631 )}
4632 </span>
4633 )}
4634 </span>
4635 </div>
4636 )}
4637 <span className="sr-only" role="status">{readStatusText || runStateText}</span>
4638 <div
4639 className={`composer${invocations.length > 0 ? " composer--has-invocation" : ""}${dragOver ? " composer--dragover" : ""}${disabled || readOnly ? " composer--disabled" : ""}${shellModeActive ? " composer--shell" : ""}`}
4640 onDrop={onDrop}
4641 onDragOver={onDragOver}
4642 onDragLeave={onDragLeave}
4643 >
4644 <div className="composer__input-row">
4645 <span className="composer__caret">{shellModeActive ? "$" : "›"}</span>
4646 <div className="composer__content" onMouseDown={focusComposerFromContentBlank}>
4647 {invocations.length > 0 ? (
4648 <RichComposerInput
4649 ref={richInputRef}
4650 text={text}
4651 invocations={invocations}
4652 placeholder={composerPlaceholder}
4653 disabled={disabled || readOnly}
4654 style={textareaStyle}
4655 onChange={(
4656 nextText,
4657 nextInvocations,
4658 origin: RichComposerChangeOrigin,
4659 ) => {
4660 const targetDraftKey = activeDraftKeyRef.current;
4661 const beforeEdit = origin.source === "programmatic"
4662 ? composerEditSnapshot(targetDraftKey, origin.beforeSelection)
4663 : null;
4664 resetPromptHistoryNavigation();
4665 const hadInvocations = invocationsRef.current.length > 0;
4666 textRef.current = nextText;
4667 invocationsRef.current = nextInvocations;
4668 setText(nextText);
4669 setInvocations(nextInvocations);
4670 if (beforeEdit) {
4671 recordComposerEdit(
4672 targetDraftKey,
4673 beforeEdit,
4674 composerEditSnapshot(targetDraftKey, origin.afterSelection),
4675 );
4676 } else {
4677 syncComposerNativeHistory(targetDraftKey, origin.inputType);
4678 }
4679 if (composerPrompt) setComposerPrompt(null);
4680 if (hadInvocations && nextInvocations.length === 0) {
4681 // Removing the last entity unmounts the rich input and
4682 // swaps the plain textarea back in; without an explicit
4683 // handoff the focused editable disappears and the next
4684 // keystrokes land on <body>. RichComposerInput reports
4685 // the removal caret through onSelectionChange before
4686 // this onChange fires.
4687 setComposerSelection(Math.min(lastSelectionRef.current.start, nextText.length));
4688 }
4689 }}
4690 onSelectionChange={(selection, query) => {
4691 setRichSelection(selection);
4692 setRichSlashQuery(query);
4693 lastSelectionRef.current = { start: selection.start, end: selection.end };
4694 }}
4695 onKeyDown={onKeyDown}
4696 onContextMenu={openInputMenu}
4697 onPaste={onPaste}
4698 onCompositionStart={() => {
4699 composingRef.current = true;
4700 }}
4701 onCompositionEnd={() => {
4702 composingRef.current = false;
4703 lastCompositionEndAt.current = Date.now();
4704 }}
4705 />
4706 ) : (
4707 <>
4708 <textarea
4709 id="composer-input"
4710 ref={taRef}
4711 className="composer__input"
4712 aria-label={t("composer.placeholder")} spellCheck={false} autoCorrect="off" autoCapitalize="off"
4713 value={composingRef.current ? undefined : text}
4714 onInputCapture={(e) => {
4715 pendingNativeInputTypeRef.current = (e.nativeEvent as InputEvent).inputType;
4716 }}
4717 onChange={(e) => {
4718 const targetDraftKey = activeDraftKeyRef.current;
4719 const inputType = (e.nativeEvent as InputEvent).inputType
4720 || pendingNativeInputTypeRef.current;
4721 pendingNativeInputTypeRef.current = undefined;
4722 trackImeInputChange(e.nativeEvent as InputEvent, inputType, e.target.value);
4723 resetPromptHistoryNavigation();
4724 textRef.current = e.target.value;
4725 setText(e.target.value);
4726 const nextSelection = {
4727 start: e.target.selectionStart ?? e.target.value.length,
4728 end: e.target.selectionEnd ?? e.target.value.length,
4729 };
4730 lastSelectionRef.current = nextSelection;
4731 setPlainSelection(nextSelection);
4732 syncComposerNativeHistory(targetDraftKey, inputType);
4733 if (composerPrompt) setComposerPrompt(null);
4734 }}
4735 onSelect={rememberCaret}
4736 onClick={rememberCaret}
4737 onKeyUp={rememberCaret}
4738 onFocus={rememberCaret}
4739 onContextMenu={openInputMenu}
4740 onPaste={onPaste}
4741 onKeyDown={onKeyDown}
4742 style={textareaStyle}
4743 placeholder={composerPlaceholder}
4744 rows={1}
4745 disabled={disabled || readOnly}
4746 />
4747 <textarea
4748 ref={measureTaRef} className="composer__input composer__input--measure"
4749 value={text} readOnly aria-hidden="true" tabIndex={-1}
4750 />
4751 </>
4752 )}
4753 </div>
4754 {composerPrompt && (
4755 <span className="composer__prompt" role="status">
4756 {composerPrompt}
4757 </span>
4758 )}
4759 </div>
4760 </div>
4761 <ContextMenu
4762 open={inputMenuPoint !== null}
4763 point={inputMenuPoint}
4764 items={inputMenuItems}
4765 className="context-menu--composer-input"
4766 minWidth={64}
4767 ariaLabel={t("composer.inputActions")}
4768 onClose={() => setInputMenuPoint(null)}
4769 />
4770 <div className={composerMetaClass}>
4771 <div className="composer-meta__params">
4772 {!heroMode && (
4773 <div className="composer-meta__control composer-meta__control--content">
4774 <Tooltip label={t("composer.contentMenuTitle")} disabled={contentMenuOpen}>
4775 <button
4776 ref={contentMenuAnchorRef}
4777 type="button"
4778 className={`composer-content-trigger${contentMenuOpen ? " composer-content-trigger--open" : ""}`}
4779 onClick={() => (contentMenuOpen ? setContentMenuOpen(false) : openContentMenu())}
4780 disabled={disabled || readOnly || (running && !(goalModeOn && activeGoal))}
4781 aria-haspopup="menu"
4782 aria-expanded={contentMenuOpen}
4783 aria-label={t("composer.contentMenuTitle")}
4784 >
4785 <Plus size={17} strokeWidth={1.8} aria-hidden="true" />
4786 </button>
4787 </Tooltip>
4788 </div>
4789 )}
4790 {!heroMode && <div className="composer-meta__control composer-meta__control--approval">
4791 <PermissionPresetChoice
4792 key={`approval-${tabId}`}
4793 value={permissionPreset}
4794 disabled={approvalBarDisabled} dismissSignal={transientDismissSignal}
4795 scopeKey={`${tabId ?? ""}:${sessionKey ?? ""}:${workspaceScopeKey ?? ""}`}
4796 projectConfirmationKey={fullAccessConfirmationKey}
4797 onPick={chooseApprovalMode}
4798 />
4799 </div>}
4800 {!heroMode && collaborationMode !== "normal" && (
4801 <div className="composer-meta__control composer-meta__control--intent">
4802 <Tooltip label={taskModeTooltipLabel} disabled={intentMenuOpen || intentMenuClosing}>
4803 <button
4804 ref={intentMenuAnchorRef}
4805 type="button"
4806 className="composer-task-mode-trigger composer-task-mode-trigger--removable"
4807 onClick={() => { if (goalModeOn && activeGoal) stopGoalMode(); else chooseTaskMode("normal"); }}
4808 disabled={disabled || running}
4809 aria-label={taskModeTriggerLabel}
4810 title={intentMenuOpen || intentMenuClosing || creationChrome ? undefined : taskModeTriggerLabel}
4811 >
4812 <span className="composer-task-mode-trigger__icon"><TaskModeIcon size={16} aria-hidden="true" /><X className="composer-task-mode-trigger__remove" size={14} aria-hidden="true" /></span>
4813 <span className="composer-task-mode-trigger__value">{t(taskModeShortKey)}</span>
4814 </button>
4815 </Tooltip>
4816 </div>
4817 )}
4818 <div className="composer-meta__control composer-meta__control--model">
4819 {!heroMode && (
4820 <ContextWindowRing
4821 enabled={!suspendedByDecision}
4822 turnMetrics={runMetrics ?? undefined}
4823 context={context}
4824 tabId={tabId}
4825 turnCost={turnCost}
4826 turnRateBand={turnRateBand}
4827 currency={currency}
4828 cacheHitTokens={cacheHitTokens}
4829 cacheMissTokens={cacheMissTokens}
4830 balance={balance} dismissSignal={transientDismissSignal}
4831 />
4832 )}
4833 <Suspense fallback={<span className="modelsw__label">{modelLabel}</span>}><ModelSwitcher composerMenu label={modelLabel} tabId={tabId} draftId={bridgeTarget.kind === "draft" ? bridgeTarget.draftId : undefined} ready={ready} sessionKey={sessionKey} disabled={disabled || suspendedByDecision} dismissSignal={transientDismissSignal} onPick={onSwitchModel} onManage={() => {
4834 useAppNavigationStore.getState().setSettingsFocus({ target: "model-access" });
4835 useAppNavigationStore.getState().setSettingsTarget("models");
4836 }} /></Suspense>
4837 {hasEffort && !heroMode && <div className="composer-effort-control">
4838 <ComposerChoice key={`effort-${tabId}`} label={effortLabel(currentEffort)}
4839 ariaLabel={`${t("status.effortTitle")}: ${effortLabel(currentEffort)}`}
4840 icon={<Brain size={16} />} showChevron
4841 value={currentEffort} disabled={disabled || readOnly || running} dismissSignal={transientDismissSignal}
4842 onPick={chooseEffortLevel}
4843 options={effortLevels.map(level => ({ value: level, label: effortLabel(level) }))} />
4844 </div>}
4845 </div>
4846 <div className={`composer-toolbar-send${submitUnavailableHint ? " composer-toolbar-send--unavailable" : ""}`}>
4847 {running && !finishing && !runtimeState.unknown && (
4848 <Tooltip label={t("composer.stop")}>
4849 <button
4850 className="composer__btn composer__btn--stop"
4851 type="button"
4852 onClick={() => void handleCancel()}
4853 disabled={runtimeState.cancellable === false || cancelSettlingDraftsRef.current.has(draftKey)}
4854 aria-label={t("composer.stop")}
4855 >
4856 <Square size={12} fill="currentColor" />
4857 </button>
4858 </Tooltip>
4859 )}
4860 <Tooltip label={submitUnavailableHint || submitTooltip}>
4861 <button
4862 className={`composer__btn composer__btn--send${running ? " composer__btn--steer" : ""}`}
4863 onClick={() => void submit()}
4864 disabled={submitBlocked}
4865 aria-label={submitTooltip}
4866 >
4867 {pendingFollowup ? <Search size={16} /> : running ? <CornerDownRight size={16} /> : <ArrowUp size={16} />}
4868 </button>
4869 </Tooltip>
4870 {running && !finishing && !maintenanceActive && <button type="button" className="btn btn--small composer__queue-steer" disabled={submitBlocked || Boolean(pendingFollowup)} onClick={() => void submit(true)}>{locale.startsWith("zh") ? "引导当前轮" : "Guide current turn"}</button>}
4871 {submitUnavailableHint && <span className="composer-toolbar-send__hint">{submitUnavailableHint}</span>}
4872 {authentication && authentication.status !== "ready" && <Suspense fallback={null}>
4873 <AuthenticationRecoveryActions
4874 authentication={authentication}
4875 tabId={tabId}
4876 />
4877 </Suspense>}
4878 </div>
4879 </div>
4880 </div>
4881 </div>
4882 </div>
4883 </div>
4884 );
4885 }
4886
4886 lines Plain Text