Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-7994: send chat conversation starters on click (#9220)
Multica Evec73ea81ed12c
diff --git a/docs/assets/mul-7994/starter-after.png b/docs/assets/mul-7994/starter-after.pngnew file mode 100644index 0000000000..69ca991439Binary files /dev/null and b/docs/assets/mul-7994/starter-after.png differdiff --git a/docs/assets/mul-7994/starter-before.png b/docs/assets/mul-7994/starter-before.pngnew file mode 100644index 0000000000..9ae2a7ca28Binary files /dev/null and b/docs/assets/mul-7994/starter-before.png differdiff --git a/docs/assets/mul-7994/starter-draft-preserved.png b/docs/assets/mul-7994/starter-draft-preserved.pngnew file mode 100644index 0000000000..fef450154bBinary files /dev/null and b/docs/assets/mul-7994/starter-draft-preserved.png differdiff --git a/docs/assets/mul-7994/starter-upload-feedback.png b/docs/assets/mul-7994/starter-upload-feedback.pngnew file mode 100644index 0000000000..c470a7a7d6Binary files /dev/null and b/docs/assets/mul-7994/starter-upload-feedback.png differdiff --git a/packages/views/chat/chat-page.tsx b/packages/views/chat/chat-page.tsxindex b84b2fddbc..1f9878e34c 100644--- a/packages/views/chat/chat-page.tsx+++ b/packages/views/chat/chat-page.tsx@@ -298,7 +298,7 @@ export function ChatPage() {<EmptyStateagent={c.activeAgent}hasSessions={c.sessions.length > 0}- onPickPrompt={c.prefillConversationStarter}+ onPickPrompt={c.sendConversationStarter}customizeHref={c.customizeConversationStartersHref}/>)}diff --git a/packages/views/chat/components/chat-input-draft-isolation.test.tsx b/packages/views/chat/components/chat-input-draft-isolation.test.tsxindex ffb0da1387..e639713f5e 100644--- a/packages/views/chat/components/chat-input-draft-isolation.test.tsx+++ b/packages/views/chat/components/chat-input-draft-isolation.test.tsx@@ -288,6 +288,40 @@ describe("ChatInput draft isolation across a composer switch (real debounce)", (vi.useRealTimers();});+ it("preserves unflushed typing when a starter is clicked inside the debounce window", async () => {+ const onSend = vi.fn().mockResolvedValue(false);+ const { rerender } = render(element({ onSend }));+ type("unfinished local text");+ const prompt = "Review the release pull request.";++ rerender(element({ onSend, conversationStarterRequest: { id: 1, content: prompt } }));+ await act(async () => {});+ expect(onSend).not.toHaveBeenCalled();+ expect(editorState.markdown).toBe("unfinished local text");++ act(() => { vi.advanceTimersByTime(1000); });+ expect(store().inputDrafts["__new__"]).toBe("unfinished local text");+ expect(onSend).not.toHaveBeenCalled();+ });++ it("allows a starter after the user clears the draft before its debounce fires", async () => {+ mockSetContent.mockImplementationOnce((markdown: string) => {+ editorState.markdown = markdown;+ });+ const onSend = vi.fn().mockResolvedValue(false);+ const { rerender } = render(element({ onSend }));+ type("unfinished local text");+ act(() => { vi.advanceTimersByTime(1000); });+ expect(store().inputDrafts["__new__"]).toBe("unfinished local text");+ type("");+ const prompt = "Review the release pull request.";++ rerender(element({ onSend, conversationStarterRequest: { id: 1, content: prompt } }));+ await act(async () => {});+ expect(onSend).toHaveBeenCalledWith(prompt, undefined, expect.any(Function), []);+ expect(store().inputDrafts["__new__"]).toBe(prompt);+ });+it("files unflushed keystrokes under the session they were typed in, never the one switched to", () => {store().activeSessionId = "session-a";const { rerender } = render(element());diff --git a/packages/views/chat/components/chat-input.test.tsx b/packages/views/chat/components/chat-input.test.tsxindex 2f0b1e0b45..59a9213906 100644--- a/packages/views/chat/components/chat-input.test.tsx+++ b/packages/views/chat/components/chat-input.test.tsx@@ -13,6 +13,10 @@ import enEditor from "../../locales/en/editor.json";// mocking that call; it resolves a server Attachment row (makeUpload's extra// link/markdownLink fields are ignored by the engine, which re-derives them).const mockApiUploadFile = vi.hoisted(() => vi.fn());+const mockToastInfo = vi.hoisted(() => vi.fn());+vi.mock("sonner", () => ({+ toast: Object.assign(vi.fn(), { info: mockToastInfo, error: vi.fn(), success: vi.fn() }),+}));// Observability for the write-back insert path: a settle whose mount died// delivers into the live editor through this method.const insertMarkdownSpy = vi.hoisted(() => vi.fn());@@ -353,6 +357,7 @@ beforeEach(() => {delete state.inputDraftAttachments[key];});mockApiUploadFile.mockReset();+ mockToastInfo.mockClear();mockApiUploadFile.mockImplementation(async () =>makeUpload({ id: "att-1", link: "https://cdn.example/att-1.png", filename: "img.png" }),);@@ -501,16 +506,15 @@ describe("ChatInput focusRequest", () => {});});-describe("ChatInput conversation starter prefill", () => {- it("replaces live editor text and the stored draft", () => {+describe("ChatInput conversation starter send", () => {+ it("sends the chosen prompt immediately from an empty draft", async () => {+ const onSend = vi.fn().mockResolvedValue(false);const onConversationStarterApplied = vi.fn();- const { rerender } = renderInput();+ const { rerender } = renderInput({ onSend });- fireEvent.change(screen.getByTestId("editor"), {- target: { value: "unfinished local text" },- });rerender(element({+ onSend,conversationStarterRequest: {id: 1,content: "Review the release pull request.",@@ -525,18 +529,127 @@ describe("ChatInput conversation starter prefill", () => {);expect(editorState.adopted).toEqual(["Review the release pull request."]);expect(onConversationStarterApplied).toHaveBeenCalledTimes(1);+ await waitFor(() => expect(onSend).toHaveBeenCalledTimes(1));+ expect(onSend).toHaveBeenCalledWith(+ "Review the release pull request.",+ undefined,+ expect.any(Function),+ [],+ );+ });++ it("preserves an existing draft and explains why the starter was not sent", async () => {+ const onSend = vi.fn().mockResolvedValue(true);+ const { rerender } = renderInput({ onSend });+ fireEvent.change(screen.getByTestId("editor"), {+ target: { value: "unfinished local text" },+ });+ rerender(element({ onSend, conversationStarterRequest: { id: 1, content: "Deploy the release." } }));++ await act(async () => {});+ expect(onSend).not.toHaveBeenCalled();+ expect(editorState.adopted).toEqual([]);+ expect(useChatStore.getState().inputDrafts["__draft_new__"]).toBe("unfinished local text");+ expect(mockToastInfo).toHaveBeenCalledWith("Send or clear your draft before using a starter.");+ });++ it("preserves staged attachments even when the draft text is empty", async () => {+ const attachment = makeUpload({ id: "att-1", link: "https://cdn.example/att-1.png", filename: "image.png" });+ const staged = { clientUploadId: "upload-1", status: "uploaded", filename: "image.png", size: 1, attachment } as DraftUpload;+ useChatStore.getState().setInputDraftAttachments("__draft_new__", [staged]);+ const { onSend } = renderInput({ conversationStarterRequest: { id: 1, content: "Deploy the release." } });++ await act(async () => {});+ expect(onSend).not.toHaveBeenCalled();+ expect(useChatStore.getState().inputDraftAttachments["__draft_new__"]).toEqual([staged]);+ expect(mockToastInfo).toHaveBeenCalledWith("Send or clear your draft before using a starter.");});- it("applies each request only once", () => {+ it("sends each request only once across rerenders", async () => {+ const onSend = vi.fn().mockResolvedValue(false);const request = {id: 1,content: "Review the release pull request.",};- const { rerender } = renderInput({ conversationStarterRequest: request });+ const { rerender } = renderInput({ onSend, conversationStarterRequest: request });- rerender(element({ conversationStarterRequest: request }));+ rerender(element({ onSend, conversationStarterRequest: request }));expect(editorState.adopted).toEqual([request.content]);+ await waitFor(() => expect(onSend).toHaveBeenCalledTimes(1));+ });++ it("keeps a rejected starter in the draft for manual retry", async () => {+ const onSend = vi.fn().mockResolvedValueOnce(false).mockResolvedValueOnce(true);+ const request = { id: 1, content: "Review the release pull request." };+ renderInput({ onSend, conversationStarterRequest: request });++ await waitFor(() => expect(onSend).toHaveBeenCalledTimes(1));+ const sendButton = screen.getByRole("button", { name: "Send" });+ await waitFor(() => expect(sendButton).toBeEnabled());+ expect(useChatStore.getState().inputDrafts["__draft_new__"]).toBe(request.content);+ expect(editorState.cleared).toBe(0);++ fireEvent.click(sendButton);+ await waitFor(() => expect(editorState.cleared).toBe(1));+ expect(onSend).toHaveBeenCalledTimes(2);+ expect(useChatStore.getState().inputDrafts["__draft_new__"]).toBeUndefined();+ });++ it("ignores another starter while a send is pending", async () => {+ let finishSend!: (accepted: boolean) => void;+ const onSend = vi.fn(() => new Promise<boolean>((resolve) => { finishSend = resolve; }));+ const first = { id: 1, content: "Review the release pull request." };+ const second = { id: 2, content: "Deploy the release." };+ const { rerender } = renderInput({ onSend, conversationStarterRequest: first });++ await waitFor(() => expect(onSend).toHaveBeenCalledTimes(1));+ rerender(element({ onSend, conversationStarterRequest: second }));+ expect(editorState.adopted).toEqual([first.content]);+ expect(useChatStore.getState().inputDrafts["__draft_new__"]).toBe(first.content);++ await act(async () => finishSend(true));+ expect(onSend).toHaveBeenCalledTimes(1);+ expect(editorState.cleared).toBe(1);+ });++ it.each([+ { disabled: true },+ { noAgent: true },+ { isRunning: true, allowSubmitWhileRunning: false },+ ])("does not replace a draft or defer a send when unavailable: %j", async (guard) => {+ const onSend = vi.fn().mockResolvedValue(true);+ const request = { id: 1, content: "Deploy the release." };+ useChatStore.getState().setInputDraft("__draft_new__", "unfinished local text");+ const { rerender } = renderInput({ onSend, conversationStarterRequest: request, ...guard });++ expect(onSend).not.toHaveBeenCalled();+ expect(editorState.adopted).toEqual([]);+ expect(useChatStore.getState().inputDrafts["__draft_new__"]).toBe("unfinished local text");+ rerender(element({ onSend, conversationStarterRequest: request }));+ await act(async () => {});+ expect(onSend).not.toHaveBeenCalled();+ });++ it("does not defer a starter until an active upload finishes", async () => {+ let finishUpload!: (result: UploadResult) => void;+ mockApiUploadFile.mockImplementationOnce(() => new Promise<UploadResult>((resolve) => {+ finishUpload = resolve;+ }));+ const onSend = vi.fn().mockResolvedValue(true);+ const { rerender } = renderInput({ onSend });+ act(() => dropHandlers.onDrop?.([new File(["x"], "image.png", { type: "image/png" })]));+ const request = { id: 1, content: "Deploy the release." };+ rerender(element({ onSend, conversationStarterRequest: request }));++ expect(onSend).not.toHaveBeenCalled();+ expect(editorState.adopted).toEqual([]);+ expect(mockToastInfo).toHaveBeenCalledWith("Wait for uploads to finish before using a starter.");+ await act(async () => finishUpload(makeUpload({+ id: "att-1", link: "https://cdn.example/att-1.png", filename: "image.png",+ })));+ expect(onSend).not.toHaveBeenCalled();+ expect(useChatStore.getState().inputDrafts["__draft_new__"]).toContain("att-1.png");});});diff --git a/packages/views/chat/components/chat-input.tsx b/packages/views/chat/components/chat-input.tsxindex 6391f1af2c..84144d8fc9 100644--- a/packages/views/chat/components/chat-input.tsx+++ b/packages/views/chat/components/chat-input.tsx@@ -3,6 +3,7 @@import type { ReactNode } from "react";import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";import { TriangleAlert } from "lucide-react";+import { toast } from "sonner";import { cn } from "@multica/ui/lib/utils";import {ContentEditor,@@ -73,14 +74,14 @@ interface ChatInputProps {*/sessionId?: string;} | null;- /** Explicit replacement requested by a conversation-starter button. Unlike a- * synchronized draft write, this may intentionally replace dirty editor- * content, so ChatInput adopts it after cancelling any pending debounce. */+ /** One-click send requested by a conversation-starter button. ChatInput+ * adopts the prompt only when there is no draft in progress, then uses the+ * regular submit path for pending state, single-flight and failure recovery. */conversationStarterRequest?: {id: number;content: string;} | null;- /** Fired after the request has replaced both the stored and live draft. */+ /** Consumes the request even when the composer cannot send right now. */onConversationStarterApplied?: () => void;/*** Fired when — and only when — the restore's content/attachments were written@@ -377,32 +378,6 @@ export function ChatInput({editorRef.current?.focus();}, [focusRequest]);- // A conversation-starter click is an explicit replacement, not an ordinary- // external store sync. ContentEditor deliberately rejects external values- // while it has dirty local text, so adopting here prevents the old text's- // pending debounce from winning the race and overwriting the chosen prompt.- // Wait out active uploads: adopting content while an upload node is present- // would strand its completion callback.- useLayoutEffect(() => {- if (!conversationStarterRequest) return;- if (appliedConversationStarterIdRef.current === conversationStarterRequest.id) return;- if (editorDraftKeyRef.current !== draftKey) return;- if (editorRef.current?.hasActiveUploads() === true) return;-- editorRef.current?.flushPendingUpdate();- appliedConversationStarterIdRef.current = conversationStarterRequest.id;- commitDraft(draftKey, conversationStarterRequest.content);- editorRef.current?.adoptContent(conversationStarterRequest.content);- setIsEmpty(!conversationStarterRequest.content.trim());- onConversationStarterApplied?.();- }, [- commitDraft,- draftKey,- onConversationStarterApplied,- conversationStarterRequest,- uploadGate.uploading,- ]);-useEffect(() => {if (!restoreDraftRequest) {appliedRestoreIdRef.current = null;@@ -578,6 +553,56 @@ export function ChatInput({},});+ // Consume each click once, including clicks while sending or uploading:+ // replaying later could send after the user switches session or agent.+ // Keep existing text and attachments intact. Flush first so the draft check+ // sees typing still in the debounce window. A rejected send keeps the+ // starter prompt in the draft for manual retry.+ useLayoutEffect(() => {+ if (!conversationStarterRequest) return;+ if (appliedConversationStarterIdRef.current === conversationStarterRequest.id) return;+ appliedConversationStarterIdRef.current = conversationStarterRequest.id;+ onConversationStarterApplied?.();+ if (+ submitting || disabled || noAgent ||+ (isRunning && !allowSubmitWhileRunning) ||+ editorDraftKeyRef.current !== draftKey+ ) return;+ if (gate.isBlocked()) {+ toast.info(t(($) => $.conversation_starters.uploading));+ return;+ }++ const pending = editorRef.current?.flushPendingUpdate();+ if (pending != null) commitDraft(draftKey, pending);+ const draft = useChatStore.getState();+ if (+ editorRef.current?.getMarkdown().trim() ||+ (draft.inputDrafts[draftKey] ?? "").trim() ||+ (draft.inputDraftAttachments[draftKey]?.length ?? 0) > 0+ ) {+ toast.info(t(($) => $.conversation_starters.draft_in_progress));+ return;+ }+ commitDraft(draftKey, conversationStarterRequest.content);+ editorRef.current?.adoptContent(conversationStarterRequest.content);+ setIsEmpty(!conversationStarterRequest.content.trim());+ void submit();+ }, [+ allowSubmitWhileRunning,+ commitDraft,+ conversationStarterRequest,+ disabled,+ draftKey,+ gate,+ isRunning,+ noAgent,+ onConversationStarterApplied,+ submit,+ submitting,+ t,+ ]);+const placeholder = agentAccessRevoked? t(($) => $.input.placeholder_access_revoked): noAgentdiff --git a/packages/views/chat/components/chat-window.tsx b/packages/views/chat/components/chat-window.tsxindex 57d649160b..adf89d3502 100644--- a/packages/views/chat/components/chat-window.tsx+++ b/packages/views/chat/components/chat-window.tsx@@ -195,7 +195,7 @@ export function ChatWindow() {content: string;} | null>(null);const nextConversationStarterRequestIdRef = useRef(0);- const prefillConversationStarter = useCallback(+ const sendConversationStarter = useCallback((prompt: string) => {setConversationStarterRequest({id: ++nextConversationStarterRequestIdRef.current,@@ -954,7 +954,7 @@ export function ChatWindow() {<EmptyStateagent={activeAgent}hasSessions={sessions.length > 0}- onPickPrompt={prefillConversationStarter}+ onPickPrompt={sendConversationStarter}customizeHref={customizeConversationStartersHref}/>)}diff --git a/packages/views/chat/components/use-chat-controller.ts b/packages/views/chat/components/use-chat-controller.tsindex 8ecf5bfd54..d32d9f8deb 100644--- a/packages/views/chat/components/use-chat-controller.ts+++ b/packages/views/chat/components/use-chat-controller.ts@@ -284,7 +284,7 @@ export function useChatController(opts?: { isActive?: boolean }) {content: string;} | null>(null);const nextConversationStarterRequestIdRef = useRef(0);- const prefillConversationStarter = useCallback(+ const sendConversationStarter = useCallback((prompt: string) => {setConversationStarterRequest({id: ++nextConversationStarterRequestIdRef.current,@@ -871,7 +871,7 @@ export function useChatController(opts?: { isActive?: boolean }) {focusInputRequest,conversationStarterRequest,handleConversationStarterApplied,- prefillConversationStarter,+ sendConversationStarter,// actionshandleSend,handleStop,diff --git a/packages/views/locales/en/chat.json b/packages/views/locales/en/chat.jsonindex 3f1a19429d..93baadea55 100644--- a/packages/views/locales/en/chat.json+++ b/packages/views/locales/en/chat.json@@ -168,7 +168,9 @@"label": "Recommend an action","prompt": "Review what you know about my workspace and recommend a useful first action."},- "customize": "Customize starters"+ "customize": "Customize starters",+ "uploading": "Wait for uploads to finish before using a starter.",+ "draft_in_progress": "Send or clear your draft before using a starter."},"onboarding_cards": {"aria_label": "Ways to start",diff --git a/packages/views/locales/fr/chat.json b/packages/views/locales/fr/chat.jsonindex d9f9ca0d09..eac139f26c 100644--- a/packages/views/locales/fr/chat.json+++ b/packages/views/locales/fr/chat.json@@ -168,7 +168,9 @@"label": "Recommander une action","prompt": "Examinez ce que vous savez de mon espace de travail et recommandez une première action utile."},- "customize": "Personnaliser les amorces"+ "customize": "Personnaliser les amorces",+ "uploading": "Attendez la fin des téléversements avant d’utiliser une amorce.",+ "draft_in_progress": "Envoyez ou effacez votre brouillon avant d’utiliser une amorce."},"onboarding_cards": {"aria_label": "Façons de démarrer",diff --git a/packages/views/locales/ja/chat.json b/packages/views/locales/ja/chat.jsonindex c8d221f716..f86a0e4bf4 100644--- a/packages/views/locales/ja/chat.json+++ b/packages/views/locales/ja/chat.json@@ -164,7 +164,9 @@"label": "アクションを提案","prompt": "私のワークスペースについて知っていることを踏まえ、最初に役立つアクションを提案してください。"},- "customize": "開始例をカスタマイズ"+ "customize": "開始例をカスタマイズ",+ "uploading": "アップロードが完了してから開始例を使用してください。",+ "draft_in_progress": "開始例を使う前に、下書きを送信するか消去してください。"},"onboarding_cards": {"aria_label": "はじめ方",diff --git a/packages/views/locales/ko/chat.json b/packages/views/locales/ko/chat.jsonindex 0e64492af1..8a966ba846 100644--- a/packages/views/locales/ko/chat.json+++ b/packages/views/locales/ko/chat.json@@ -164,7 +164,9 @@"label": "작업 추천","prompt": "내 워크스페이스에 대해 알고 있는 내용을 바탕으로 유용한 첫 작업을 추천해 주세요."},- "customize": "시작 예시 편집"+ "customize": "시작 예시 편집",+ "uploading": "업로드가 완료된 후 대화 시작 예시를 사용해 주세요.",+ "draft_in_progress": "대화 시작 예시를 사용하려면 먼저 초안을 보내거나 지워 주세요."},"onboarding_cards": {"aria_label": "시작 방법",diff --git a/packages/views/locales/zh-Hans/chat.json b/packages/views/locales/zh-Hans/chat.jsonindex 598feaf651..e7f78fb076 100644--- a/packages/views/locales/zh-Hans/chat.json+++ b/packages/views/locales/zh-Hans/chat.json@@ -164,7 +164,9 @@"label": "推荐一个操作","prompt": "根据你对我的工作区的了解,推荐一个有用的初始操作。"},- "customize": "自定义开场建议"+ "customize": "自定义开场建议",+ "uploading": "请等待附件上传完成后再使用开场建议。",+ "draft_in_progress": "请先发送或清空草稿,再使用开场建议。"},"onboarding_cards": {"aria_label": "开始方式",