Files
multica/packages/views/issues/components/comment-input.tsx
Naiyuan Qing b7857a6aa3 feat(chat): workspace-scoped attachment binding + fire-and-forget send (#4249)
* feat(chat): workspace-scoped attachment binding + fire-and-forget send

Uploads are now workspace-scoped: the chat session is created and
attachments are bound to the message at send time, so a paste/drop no
longer creates an empty session the user never sends.

- LinkAttachmentsToChatMessage returns the ids it actually bound; the
  client diffs requested-vs-bound and warns on partial bind, replacing
  an extra listChatMessagesPage fetch.
- Cancelling an empty chat task detaches attachments before deleting the
  user message (attachment FK is ON DELETE CASCADE) and returns them via
  cancelled_chat_message.attachments, so a restored draft can re-bind.
- SendChatMessageResponse.attachment_ids has no omitempty: "requested but
  bound zero" serializes [] so the client can tell it apart from an older
  server and still warn.
- Send is fire-and-forget: it no longer steals focus when the user has
  navigated to another session (guarded on the live store + new-chat agent
  id); the reply surfaces via the unread dot. commitInput gets clearEditor
  so a navigated-away commit doesn't wipe the editor now showing another
  session, while still clearing the sent draft's data.
- Draft restore is session-aware so a failed fire-and-forget send restores
  into the session it was sent from, never the one the user moved to.
- Removed the now-unreferenced migrateInputDraft store action.

Verified: core/views typecheck, chat-input (15) / store (3) / api client
(24) unit tests, go build + vet, handler SendChatMessage + CancelTaskByUser
DB tests. Full make check / E2E left to CI.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* test(chat): guard attachment survival on empty-chat cancel

Cancelling an empty chat task deletes the user message, and
attachment.chat_message_id is ON DELETE CASCADE (migration 083), so the
detach-before-delete in finalizeCancelledChatMessage is the only thing
keeping the user's attachment from being silently destroyed. Nothing
covered it.

Add a DB regression test that binds an attachment to the cancelled user
message and asserts: the row survives the cascade (chat_message_id NULL,
chat_session_id retained), the cancel response returns it via
cancelled_chat_message.attachments, and a resend re-binds it to the new
message. Verified red when the detach step is removed.

Related issue: MUL-3364

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* fix(comment): pessimistic submit for comment/reply composers

The comment and reply composers cleared the editor after `await onSubmit`
returned, with no in-flight lock. On a slow send the WS `comment:created`
event already dropped the real comment into the timeline while the box
still held the same text + spinner, so it read as two comments. And
because `submitComment`/`submitReply` swallow errors (toast, no rethrow),
a failed send still reached `clearContent` and silently discarded the
user's draft.

Recover the comment/reply portion of the closed #4236: make the submit
callback resolve a success boolean (true on success, false on the caught
failure), lock the editor while in flight (pointer-events-none + dimmed
wrapper + aria-busy, since ContentEditor can't toggle Tiptap `editable`
post-mount), keep the button spinning, and clear only on success — a
failed send keeps the draft. Chat composer is out of scope (already
reworked on this branch); attachment binding is untouched.

Adds two view tests (in-flight lock then clear-on-success; failed send
keeps the draft); both verified red against the un-fixed code.

Related issue: MUL-3364

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>
2026-06-18 09:40:38 +08:00

200 lines
8.2 KiB
TypeScript

"use client";
import { useRef, useState, useCallback, useEffect } from "react";
import { cn } from "@multica/ui/lib/utils";
import { ContentEditor, type ContentEditorRef, useFileDropZone, FileDropOverlay } from "../../editor";
import { FileUploadButton } from "@multica/ui/components/common/file-upload-button";
import { SubmitButton } from "@multica/ui/components/common/submit-button";
import { useFileUpload } from "@multica/core/hooks/use-file-upload";
import { api } from "@multica/core/api";
import type { Attachment } from "@multica/core/types";
import { contentReferencesAttachment } from "@multica/core/types";
import { enterKey, formatShortcut, modKey } from "@multica/core/platform";
import { useCommentDraftStore } from "@multica/core/issues/stores";
import { useT } from "../../i18n";
import { CommentTriggerChips } from "./comment-trigger-chips";
import { useCommentTriggerPreview } from "../hooks/use-comment-trigger-preview";
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[]) => Promise<boolean>;
}
function CommentInput({ issueId, onSubmit }: CommentInputProps) {
const { t } = useT("issues");
const editorRef = useRef<ContentEditorRef>(null);
// Read the persisted draft once on mount. ContentEditor only honors
// `defaultValue` at mount time, so this snapshot drives both the editor's
// initial content and the submit-button enable state — without this the
// button would be disabled even though the editor visibly contains text.
const draftKey = `new:${issueId}` as const;
const initialDraft = useCommentDraftStore.getState().getDraft(draftKey);
const [content, setContent] = useState(initialDraft ?? "");
const [isEmpty, setIsEmpty] = useState(() => !initialDraft?.trim());
const [submitting, setSubmitting] = useState(false);
const [suppressedAgentIds, setSuppressedAgentIds] = useState<Set<string>>(() => new Set());
const triggerPreview = useCommentTriggerPreview({ issueId, content });
// Attachments uploaded in this composer session. Drives both:
// - submit-time `attachment_ids` payload (filtered to URLs still in markdown)
// - the editor's AttachmentDownloadProvider, so file-card Eye buttons can
// resolve text/code/markdown previews that require the attachment id.
const [pendingAttachments, setPendingAttachments] = useState<Attachment[]>([]);
const { uploadWithToast } = useFileUpload(api);
const { isDragOver, dropZoneProps } = useFileDropZone({
onDrop: (files) => files.forEach((f) => editorRef.current?.uploadFile(f)),
});
// 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);
const clearDraft = useCommentDraftStore((s) => s.clearDraft);
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]);
const handleUpload = useCallback(async (file: File) => {
const result = await uploadWithToast(file, { issueId });
if (result) {
setPendingAttachments((prev) => [...prev, result]);
}
return result;
}, [uploadWithToast, issueId]);
useEffect(() => {
setSuppressedAgentIds(new Set());
}, [issueId]);
useEffect(() => {
const visible = new Set(triggerPreview.agents.map((agent) => agent.id));
setSuppressedAgentIds((prev) => {
const next = new Set([...prev].filter((id) => visible.has(id)));
return next.size === prev.size ? prev : next;
});
}, [triggerPreview.agents]);
const toggleSuppressedAgent = useCallback((agentId: string) => {
setSuppressedAgentIds((prev) => {
const next = new Set(prev);
if (next.has(agentId)) next.delete(agentId);
else next.add(agentId);
return next;
});
}, []);
const handleSubmit = async () => {
const content = editorRef.current?.getMarkdown()?.replace(/(\n\s*)+$/, "").trim();
if (!content || submitting) return;
// Track every attachment whose stable download URL OR legacy
// storage URL is referenced in the markdown body. Both shapes
// can appear in the same comment during the MUL-3130 rollout —
// see contentReferencesAttachment for the rationale.
const activeIds = pendingAttachments
.filter((a) => contentReferencesAttachment(content, a))
.map((a) => a.id);
const suppressAgentIds = triggerPreview.agents
.filter((agent) => suppressedAgentIds.has(agent.id))
.map((agent) => agent.id);
// Pessimistic submit: keep the text in place (the editor is locked and the
// button spins via `submitting`) until the server actually accepts it, then
// clear. Clearing only on success means a slow send no longer looks like
// "comment posted but the box is still full", and a failed send keeps the
// draft instead of silently dropping it.
setSubmitting(true);
try {
const ok = await onSubmit(
content,
activeIds.length > 0 ? activeIds : undefined,
suppressAgentIds.length > 0 ? suppressAgentIds : undefined,
);
if (ok) {
editorRef.current?.clearContent();
setContent("");
setIsEmpty(true);
setSuppressedAgentIds(new Set());
setPendingAttachments([]);
clearDraft(draftKey);
}
} finally {
setSubmitting(false);
}
};
return (
<div
{...dropZoneProps}
className="relative flex flex-col rounded-lg bg-card pb-8 ring-1 ring-border"
>
{/* 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. */}
<div
className={cn(
"flex-1 min-h-0 overflow-y-auto px-3 py-2",
submitting && "pointer-events-none opacity-60",
)}
aria-busy={submitting || undefined}
>
<ContentEditor
ref={editorRef}
defaultValue={initialDraft}
placeholder={t(($) => $.comment.leave_comment_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.
if (md.trim().length > 0) setDraft(draftKey, md);
else clearDraft(draftKey);
}}
onSubmit={handleSubmit}
onUploadFile={handleUpload}
debounceMs={100}
currentIssueId={issueId}
attachments={pendingAttachments}
enableSlashCommands
slashCommandMode="command"
/>
</div>
<div className="absolute bottom-1 left-2 right-28 min-w-0">
<CommentTriggerChips
agents={triggerPreview.agents}
suppressedAgentIds={suppressedAgentIds}
onToggle={toggleSuppressedAgent}
/>
</div>
<div className="absolute bottom-1 right-1.5 flex items-center gap-1">
<FileUploadButton
size="sm"
multiple
onSelect={(file) => editorRef.current?.uploadFile(file)}
/>
<SubmitButton
onClick={handleSubmit}
disabled={isEmpty}
loading={submitting}
tooltip={`${t(($) => $.comment.send_tooltip)} · ${formatShortcut(modKey, enterKey)}`}
/>
</div>
{isDragOver && <FileDropOverlay />}
</div>
);
}
export { CommentInput };