Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
"use client";
import { useRef, useState, useEffect, useMemo } from "react";
import { cn } from "@multica/ui/lib/utils";
import { Info } from "@multica/ui/icons";
import { useCurrentWorkspace } from "@multica/core/paths";
import { useIsGuest } from "@multica/core/permissions";
import { StorageLimitNotice } from "../../billing/storage-limit-notice";
import { ContentEditor, type ContentEditorRef, useFileDropZone, FileDropOverlay, useLazyEditor, useUploadGate, useComposerSubmit } from "../../editor";
import { SubmitButton } from "@multica/ui/components/common/submit-button";
import { Button } from "@multica/ui/components/ui/button";
import { contentReferencesAttachment, type AgentTask } from "@multica/core/types";
import { useShortcut } from "@multica/core/shortcuts";
import { ShortcutKeycaps } from "../../common/shortcut-keycaps";
import { useCommentDraftStore } from "@multica/core/issues/stores";
import { composeAnnotatedReply, hasReplyIntent } from "@multica/core/drafts/reply-annotation";
import { annotationsWithPending, type AnnotationComposerSlot } from "./annotation-composer";
import { ReplyAnnotations } from "./reply-annotations";
import { useT } from "../../i18n";
import {
useComposerVoice,
VoiceErrorRow,
VoiceHud,
VoiceSetupDialog,
} from "../../voice";
import { CommentTriggerChips } from "./comment-trigger-chips";
import {
ComposerToolbar,
ComposerTools,
QUIET_SEND_CLASS,
useComposerFocus,
} from "./composer-frame";
import { commentTriggerPreviewSignature, useCommentTriggerPreview } from "../hooks/use-comment-trigger-preview";
import { useRecipientActions } from "../hooks/use-recipient-actions";
import { SteerAttachmentNotice } from "./steer-attachment-notice";
import { useStopRunsBeforeSend } from "./use-stop-runs-before-send";
import { useCommentUploads } from "./use-comment-uploads";
import { useQuickActionMenu } from "../hooks/use-quick-action-menu";
import { useStickyComposer } from "../hooks/use-sticky-composer";
import { registerComposerFocus } from "./composer-focus";
interface CommentInputProps {
issueId: string;
/** Resolves true on success, false on failure. The composer keeps the text
* (editor locked + button spinning) until this settles, then clears only on
* success — a failed send must not silently discard the user's draft. */
onSubmit: (content: string, attachmentIds?: string[], suppressAgentIds?: string[], steerTaskIds?: string[]) => Promise<string | boolean>;
/** Called after the server accepts the comment and the composer is cleared. */
onAccepted?: (commentId: string) => void;
onEditAnnotation?: (id: string) => boolean;
annotationComposer?: AnnotationComposerSlot;
}
// A top-level comment belongs to no thread, so it takes a running turn by
// default only when that turn has no thread of its own (an assignment run).
function steerTopLevelByDefault(task: AgentTask): boolean {
return !task.trigger_comment_id;
}
function CommentInput({ issueId, onSubmit, onAccepted, onEditAnnotation, annotationComposer }: CommentInputProps) {
const { t } = useT("issues");
const { t: tEditor } = useT("editor");
const sendShortcut = useShortcut("send");
const editorRef = useRef<ContentEditorRef>(null);
// A guest (MUL-9420) comments and mentions people, nothing that runs agents.
const guest = useIsGuest(useCurrentWorkspace()?.id);
const placeholder = guest ? t(($) => $.comment.guest_placeholder) : t(($) => $.comment.leave_comment_placeholder);
// Sending mid-upload would strip the pending image's blob URL out of the
// markdown and bind no attachment id — the comment posts without the file.
const uploadGate = useUploadGate(editorRef);
// Subscribe to the persisted draft so text written into it from outside
// this composer shows up even while it is mounted.
const draftKey = `new:${issueId}` as const;
const [initialDraft] = useState(() =>
useCommentDraftStore.getState().getDraft(draftKey),
);
const persistedDraft = useCommentDraftStore((store) => store.getDraft(draftKey));
const [content, setContent] = useState(initialDraft ?? "");
const [isEmpty, setIsEmpty] = useState(() => !initialDraft?.trim());
const annotations = useCommentDraftStore((s) => s.getAnnotations(draftKey));
const previewAnnotations = useMemo(() => annotationsWithPending(annotations, annotationComposer?.pending), [annotations, annotationComposer?.pending]);
const composedContent = useMemo(() => composeAnnotatedReply(content, previewAnnotations), [content, previewAnnotations]);
const canSend = annotations.length ? hasReplyIntent(content, annotations) : !isEmpty;
const previewContent = canSend || annotationComposer?.pending.note.trim() ? composedContent : "";
const triggerPreview = useCommentTriggerPreview({ issueId, content: previewContent });
// Uploads for this composer session (MUL-5181). Owned by the module-level
// coordinator and persisted in the draft store, so closing/scrolling the
// composer away no longer drops an in-flight upload — its result lands in the
// draft. `attachments` (completed rows) drives both the submit `attachment_ids`
// payload and the editor's AttachmentDownloadProvider; `uploads` drives the
// status chips (uploading / failed / interrupted).
// `gate` widens the editor gate with coordinator-owned placeholders, so a
// composer reopened over a still-in-flight upload cannot send past it.
const { attachments: pendingAttachments, handleUpload, gate, storageRefusal, dismissStorageRefusal } =
useCommentUploads(draftKey, { issueId }, uploadGate, editorRef);
const hasAttachments = useMemo(
() => pendingAttachments.some((a) => contentReferencesAttachment(content, a)) || gate.uploading,
[pendingAttachments, content, gate.uploading],
);
const { recipients, attachmentsBlockSteer, routing, setAction, reset: resetRecipients } = useRecipientActions({
issueId,
agents: triggerPreview.agents,
allowSteer: true,
hasAttachments,
steerByDefault: steerTopLevelByDefault,
resetKey: issueId,
});
const stopRunsBeforeSend = useStopRunsBeforeSend(issueId);
// Readonly-first: the composer renders as a same-looking static shell until
// the user shows intent (click / keyboard / file drop). An unsent draft is
// standing intent — mount the real editor immediately so the draft is
// visible and editable, exactly like the pre-lazy behavior.
const lazy = useLazyEditor({
initialActive:
!!initialDraft?.trim() ||
useCommentDraftStore.getState().getUploads(draftKey).length > 0,
editorRef,
});
const activateRef = useRef(lazy.activate);
activateRef.current = lazy.activate;
useEffect(() => registerComposerFocus(issueId, () => activateRef.current()), [issueId]);
// Inactive shells must not mount query observers or duplicate cold reads.
const quickActionMenu = useQuickActionMenu(issueId, { enabled: lazy.active, triggerPreview, previewContent });
const { isDragOver, dropZoneProps } = useFileDropZone({
onDrop: lazy.uploadOrQueue,
});
// Sticky preference (Settings → Preferences): issue-detail pins this
// composer to the bottom of the scroll viewport when enabled. Shared with
// the host so the height cap below can never outlive the pinning.
const sticky = useStickyComposer();
// Draft persistence. Hydrate from store on mount via `defaultValue` above
// (ContentEditorRef has no setContent, so this is the only injection point).
// Flush on every onUpdate (debounced upstream) + visibilitychange/pagehide
// so tab close / mobile background doesn't lose work. Cleared on submit.
const setDraft = useCommentDraftStore((s) => s.setDraft);
useEffect(() => {
// Only an actual stored value is an external update. An absent entry is
// not a command to erase the editor: it is normal during the synchronous
// keystroke -> store handoff and after explicit submit cleanup.
if (persistedDraft === undefined) return;
const next = persistedDraft;
if (next === content) return;
setContent(next);
setIsEmpty(!next.trim());
if (next.trim()) lazy.activate();
}, [content, lazy, persistedDraft]);
useEffect(() => {
const flush = () => {
const md = editorRef.current?.getMarkdown();
if (md && md.trim().length > 0) setDraft(draftKey, md);
};
const onVis = () => { if (document.visibilityState === "hidden") flush(); };
document.addEventListener("visibilitychange", onVis);
window.addEventListener("pagehide", flush);
return () => {
document.removeEventListener("visibilitychange", onVis);
window.removeEventListener("pagehide", flush);
};
}, [draftKey, setDraft]);
// Await-then-render send (MUL-5181): the shared hook reads the markdown,
// guards empty/in-flight, re-checks the upload gate, locks + spins via
// `submitting`, and clears only once the server accepts — a failed send keeps
// the draft instead of silently dropping it.
// Stale-submit guard (MUL-5181 P0): if this composer unmounts mid-submit
// (issue detail closed) and the user reopens and types a new draft under the
// same key, the late success may only clear the draft it submitted.
const mountedRef = useRef(true);
useEffect(() => {
mountedRef.current = true;
return () => {
mountedRef.current = false;
};
}, []);
const submittedEntryRef = useRef<unknown>(null);
// Set by `onAccepted` only on the branch that actually wiped the editor; read
// back by `afterAccepted`. Bound this way because the stale-submit guard can
// leave a mid-flight draft in place: dropping the caret then would yank it
// out of the sentence the user is still typing.
const editorScrubbedRef = useRef(false);
const acceptedCommentIdRef = useRef<string | null>(null);
const { submitting, submit } = useComposerSubmit({
editorRef,
uploadGate: gate,
normalize: (raw) => {
const current = useCommentDraftStore.getState().getAnnotations(draftKey);
return hasReplyIntent(raw, current) ? composeAnnotatedReply(raw, current) : "";
},
// A top-level comment ends a turn: the caret is dropped rather than kept,
// so the composer stops reading as "still writing" once the comment is
// posted above it. Thread replies do the same — see ReplyInput.
afterAccepted: () => (editorScrubbedRef.current ? "blur" : "none"),
onSubmit: async (content) => {
editorScrubbedRef.current = false;
const { suppressAgentIds, steerTaskIds } = routing;
// A preview still catching up with an edited @mention can name a
// recipient this comment no longer addresses: never stop a run on it.
const previewMatches = triggerPreview.isCurrent && commentTriggerPreviewSignature(content) === commentTriggerPreviewSignature(composedContent);
const restartTaskIds = previewMatches ? routing.restartTaskIds : [];
if (!(await stopRunsBeforeSend(restartTaskIds))) return false;
// Flush the editor's pending debounce before snapshotting — a late flush
// of pre-submit typing must not read as an edit made during the request.
const pending = editorRef.current?.flushPendingUpdate?.();
if (pending != null) setDraft(draftKey, pending);
submittedEntryRef.current = useCommentDraftStore.getState().drafts[draftKey];
// Bind only uploads the BODY still references (MUL-5181): deleting an
// inline image really unbinds it. Uploads that finished after a close
// are written back into the body by the settle handler, so surviving
// files are referenced too — never silently attached.
const activeIds = pendingAttachments
.filter((a) => contentReferencesAttachment(content, a))
.map((a) => a.id);
return onSubmit(
content,
activeIds.length > 0 ? activeIds : undefined,
suppressAgentIds.length > 0 ? suppressAgentIds : undefined,
steerTaskIds.length > 0 ? steerTaskIds : undefined,
).then((commentId) => {
acceptedCommentIdRef.current = typeof commentId === "string" ? commentId : null;
return !!commentId;
});
},
onAccepted: () => {
// Success may only consume the entry it submitted (MUL-5181 P0): edits
// made while the request was in flight — or by a reopened composer after
// this one unmounted — survive both in the store and in the editor.
// Flush the pending debounce first so typing still inside the window is
// judged correctly (a no-op flush preserves entry identity).
const lateMd = editorRef.current?.flushPendingUpdate?.();
if (lateMd != null) setDraft(draftKey, lateMd);
const store = useCommentDraftStore.getState();
const live = store.drafts[draftKey];
const untouched = live === undefined || live === submittedEntryRef.current;
if (untouched) store.clearDraft(draftKey);
if (!mountedRef.current || !untouched) return;
editorRef.current?.clearContent();
setContent("");
setIsEmpty(true);
resetRecipients();
editorScrubbedRef.current = true;
if (acceptedCommentIdRef.current) onAccepted?.(acceptedCommentIdRef.current);
},
});
const voice = useComposerVoice({
insert: (text) => editorRef.current?.insertText(text) ?? false,
// Sending while a run would be restarted stays an explicit click on the
// destructive button.
submit: routing.restartTaskIds.length === 0 ? () => void submit() : undefined,
activate: () => lazy.activate(),
scope: issueId,
});
const { focused, focusProps } = useComposerFocus();
const showsTriggerChips = recipients.length > 0 || triggerPreview.blocked.length > 0 || triggerPreview.hasAllMembersMention;
return (<>
{annotationComposer?.render({
submit, submitting, uploading: gate.uploading, restart: routing.restartTaskIds.length > 0,
draftContent: content, annotations,
recipients: <CommentTriggerChips recipients={recipients} blocked={triggerPreview.blocked}
hasAllMembersMention={triggerPreview.hasAllMembersMention} draftContent={composedContent} onActionChange={setAction} />,
})}
<div
data-mc="comment-composer"
{...dropZoneProps}
{...focusProps}
className={cn(
"relative flex flex-col rounded-lg bg-card ring-1 transition-shadow",
focused ? "ring-foreground/25" : "ring-border",
)}
ref={voice.rootRef}
onFocusCapture={voice.onFocusCapture}
>
{attachmentsBlockSteer && <div className="px-3 pt-2">
<SteerAttachmentNotice />
</div>}
{annotations.length > 0 && <div className="px-3 pt-2">
<ReplyAnnotations draftKey={draftKey} annotations={annotations} disabled={submitting}
onEditAnnotation={onEditAnnotation} />
</div>}
{/* Lock the editor while the send is in flight. ContentEditor can't
toggle Tiptap's `editable` post-mount (see its docstring), so the
documented way to make it non-interactive is a pointer-events-none +
dimmed wrapper. */}
{lazy.active && (
<div
className={cn(
"flex-1 min-h-0 overflow-y-auto px-3 py-2",
// Pinned to the viewport bottom the composer grows upward; cap it
// so a long draft can't swallow the whole timeline (the editor
// area scrolls internally instead).
sticky && "max-h-[40vh]",
submitting && "pointer-events-none opacity-60",
!lazy.ready && "hidden",
)}
aria-busy={submitting || undefined}
>
<ContentEditor
ref={editorRef}
value={persistedDraft ?? content}
onReady={lazy.onReady}
placeholder={placeholder}
onUpdate={(md) => {
setContent(md);
setIsEmpty(!md.trim());
// Debounced upstream (debounceMs=100). Persist on every tick so a
// reload or scroll-out-of-viewport restores work to the keystroke.
// setDraft keeps any pending attachments and drops the entry only
// when text AND attachments are both empty.
setDraft(draftKey, md);
}}
onSubmit={submit}
onUploadFile={handleUpload}
onUploadingChange={uploadGate.onUploadingChange}
debounceMs={100}
currentIssueId={issueId}
attachments={pendingAttachments}
enableSlashCommands={!guest}
slashCommandMode="command"
quickActionMenu={quickActionMenu}
/>
</div>
)}
{/* Static shell — visually clones the empty single-line composer.
Real editor mounts (hidden) on first intent; shell stays visible
until it's ready so the card never blanks or shifts. */}
{!lazy.ready && (
<div
data-testid="comment-composer-shell"
role="button"
tabIndex={0}
aria-label={placeholder}
className="flex-1 min-h-0 cursor-text px-3 py-2"
onClick={() => lazy.activate()}
onKeyDown={(e) => {
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
lazy.activate();
}
}}
>
{/* rich-text-editor + <p>: the shell line inherits the editor's
exact type metrics (line-height 1.625 from prose.css), so the
shell→editor swap doesn't shift layout. */}
<div className="rich-text-editor text-body">
<p className="text-muted-foreground">{placeholder}</p>
</div>
</div>
)}
<VoiceHud voice={voice} />
<VoiceSetupDialog voice={voice} />
<VoiceErrorRow voice={voice} className="mx-2 mb-1" />
{storageRefusal && (
<StorageLimitNotice refusal={storageRefusal} onDismiss={dismissStorageRefusal} className="mx-2 mb-1" />
)}
<ComposerToolbar
className="px-1.5 pb-1"
voice={voice}
hasRecipients={guest || showsTriggerChips}
recipients={guest ? (
<p className="flex items-center gap-1.5 px-1.5 text-caption text-muted-foreground">
<Info className="size-3.5 shrink-0" aria-hidden="true" />
<span className="truncate">{t(($) => $.comment.guest_hint)}</span>
</p>
) : <CommentTriggerChips
recipients={recipients}
blocked={triggerPreview.blocked}
hasAllMembersMention={triggerPreview.hasAllMembersMention}
draftContent={composedContent}
onActionChange={setAction}
/>}
tools={guest ? null : <ComposerTools voice={voice} onAttach={(file) => lazy.uploadOrQueue([file])} />}
send={routing.restartTaskIds.length > 0 ? (
<Button
size="sm"
variant="destructive"
// eslint-disable-next-line no-restricted-syntax -- composer send button, the one round button
className="rounded-full px-3"
onClick={submit}
disabled={!canSend || submitting || gate.uploading}
>
{t(($) => $.comment.restart_send)}
</Button>
) : <SubmitButton
className={QUIET_SEND_CLASS}
onClick={submit}
disabled={!canSend}
loading={submitting}
busy={gate.uploading}
disabledReason={gate.uploading
? tEditor(($) => $.upload.in_progress)
: !canSend && annotations.length > 0
? t(($) => $.reply.annotations.intent_hint)
: undefined}
tooltip={sendShortcut
? (
<>
{t(($) => $.comment.send_tooltip)}
<ShortcutKeycaps shortcut={sendShortcut} decorative />
</>
)
: t(($) => $.comment.send_tooltip)}
ariaLabel={gate.uploading
? tEditor(($) => $.upload.in_progress)
: t(($) => $.comment.send_tooltip)}
/>}
/>
{isDragOver && <FileDropOverlay />}
</div>
</>);
}
export { CommentInput };