Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat: default to non-interrupting Chat steering (MUL-9374) (#10715)
Bohan Jiangfd3aa99e5bea
diff --git a/apps/docs/components/demos/chat-queue-demo.tsx b/apps/docs/components/demos/chat-queue-demo.tsxdeleted file mode 100644index fd2d1e5fe1..0000000000--- a/apps/docs/components/demos/chat-queue-demo.tsx+++ /dev/null@@ -1,452 +0,0 @@-"use client";--import { type ReactNode, useEffect, useState } from "react";-import { CornerDownRight, Ellipsis, ListEnd, Loader2, Pencil, Square, Trash2 } from "@multica/ui/icons";-import {- CoachMark,- DemoAvatar,- DemoFrame,- DemoSendButton,- useDemoCopy,- useDemoTimers,- useStartWhenVisible,-} from "./demo-kit";--type Captions = {- idle: string;- opening: string;- ready: string;- queued: string;- menu: string;- steering: string;- steered: string;- clearing: string;- cleared: string;-};--const copy = {- en: {- title: "Chat · Ops helper",- agent: "Ops helper",- placeholder: "Message Ops helper…",- queueSend: "Queue message",- stop: "Stop",- typing: "Typing",- thinking: "Thinking",- repliedIn: (elapsed: string) => `Replied in ${elapsed}`,- replyTimes: ["14s", "11s"],- cancelled: "This reply was cancelled.",- queueTitle: "1 queued message",- steer: "Steer",- remove: "Remove queued message",- more: "More queue actions",- edit: "Edit queued message",- clear: "Clear all",- firstPrompt: "Draft an all-staff notice for next Wednesday's fire drill. Assembly point: the 1st-floor lobby.",- partial: [- "Hi all, we're holding a fire drill next Wednesday at 3 pm. ",- "When the alarm sounds, take the nearest emergency exit ",- ],- tail: "and gather in the 1st-floor lobby. Team leads, please count heads and report to the admin office.",- draft: "Change the assembly point to the B1 parking garage. The lobby is being renovated that day.",- steeredReply:- "Hi all, we're holding a fire drill next Wednesday at 3 pm. When the alarm sounds, take the nearest emergency exit and gather in the B1 parking garage (the lobby is closed for renovation that day). Team leads, please count heads and report to the admin office.",- captions: {- idle: "You've asked Ops helper to draft a notice.",- opening: "Ops helper is writing its reply. Then you remember the assembly point has to change.",- ready: "The agent is still replying, so the send button now queues the message. Click send.",- queued:- "The message waits in the queue until the current reply ends. Click Steer to have it handled now, or open ⋯ to clear the queue.",- menu: "Clear all withdraws every queued message; the current reply keeps going. Click Clear all.",- steering:- "Steer stopped the current reply and kept what it had written. The agent started on your new message right away.",- steered: "The notice is rewritten with the new location. Use Replay to watch again.",- clearing: "The queue is empty and that message won't reach the agent. The current reply continues.",- cleared: "The reply finished as first asked, still at the 1st-floor lobby. Use Replay and try Steer.",- } satisfies Captions,- },- zh: {- title: "聊天 · 运营助手",- agent: "运营助手",- placeholder: "给 运营助手 发消息...",- queueSend: "排队发送",- stop: "停止",- typing: "输入中",- thinking: "思考中",- repliedIn: (elapsed: string) => `${elapsed} 内回复`,- replyTimes: ["14s", "11s"],- cancelled: "这次回复已取消。",- queueTitle: "1 条排队消息",- steer: "引导",- remove: "移除排队消息",- more: "更多队列操作",- edit: "编辑排队消息",- clear: "全部清空",- firstPrompt: "起草一份下周三消防演练的全员通知,集合地点写 1 楼大厅。",- partial: ["各位同事:下周三下午 3 点进行消防演练,", "警报响起后请走最近的安全通道,"],- tail: "到 1 楼大厅集合,各部门负责人清点人数后报给行政部。",- draft: "集合地点改成 B1 停车场,1 楼大厅那天在装修。",- steeredReply:- "各位同事:下周三下午 3 点进行消防演练,警报响起后请走最近的安全通道,到 B1 停车场集合(1 楼大厅当天装修),各部门负责人清点人数后报给行政部。",- captions: {- idle: "你请 运营助手 起草一份通知。",- opening: "运营助手 正在写回复。这时你想起集合地点得改。",- ready: "智能体还在回复,发送按钮变成了\"排队发送\"。点击发送。",- queued: "消息进了队列,要等当前回复写完才处理。点击\"引导\"让它马上处理,或者点 ⋯ 清空队列。",- menu: "全部清空会撤回队列里的消息,当前回复不受影响。点击\"全部清空\"。",- steering: "引导停掉了当前回复,已写出的部分留在对话里。智能体马上开始处理你的新消息。",- steered: "通知按新地点重写好了。点右上角可以重新演示。",- clearing: "队列已清空,那条消息不会发给智能体。当前回复继续写。",- cleared: "回复按原来的要求写完,地点仍是 1 楼大厅。点右上角重新演示,可以试试\"引导\"。",- } satisfies Captions,- },- ja: {- title: "チャット · 運用アシスタント",- agent: "運用アシスタント",- placeholder: "運用アシスタント にメッセージ…",- queueSend: "キューに追加",- stop: "停止",- typing: "入力中",- thinking: "考え中",- repliedIn: (elapsed: string) => `${elapsed}で返信`,- replyTimes: ["14s", "11s"],- cancelled: "この返信はキャンセルされました。",- queueTitle: "キュー内のメッセージ 1 件",- steer: "指示",- remove: "キューから削除",- more: "その他のキュー操作",- edit: "キュー内のメッセージを編集",- clear: "すべて削除",- firstPrompt: "来週水曜の避難訓練について、全社員向けのお知らせを書いてください。集合場所は 1 階ロビーです。",- partial: ["皆さま、来週水曜の午後 3 時に避難訓練を行います。", "警報が鳴ったら最寄りの非常口から避難し、"],- tail: "1 階ロビーに集合してください。各部署の責任者は人数を確認し、総務部に報告してください。",- draft: "集合場所を地下 1 階の駐車場に変更してください。当日は 1 階ロビーが改装中です。",- steeredReply:- "皆さま、来週水曜の午後 3 時に避難訓練を行います。警報が鳴ったら最寄りの非常口から避難し、地下 1 階の駐車場に集合してください(当日は 1 階ロビーが改装中です)。各部署の責任者は人数を確認し、総務部に報告してください。",- captions: {- idle: "運用アシスタント にお知らせの下書きを頼みました。",- opening: "運用アシスタント が返信を書いています。そこで集合場所を変える必要を思い出しました。",- ready: "エージェントはまだ返信中なので、送信ボタンは「キューに追加」になっています。送信をクリックします。",- queued:- "メッセージはキューに入り、今の返信が終わるまで処理されません。「指示」をクリックするとすぐ処理されます。⋯ からキューを空にすることもできます。",- menu: "「すべて削除」はキュー内のメッセージを取り消します。今の返信はそのまま続きます。「すべて削除」をクリックします。",- steering: "「指示」で今の返信が止まり、書きかけの部分はチャットに残りました。エージェントはすぐ新しいメッセージに取りかかります。",- steered: "新しい集合場所でお知らせが書き直されました。「もう一度」で最初から見られます。",- clearing: "キューが空になり、あのメッセージはエージェントに届きません。今の返信は続きます。",- cleared: "返信は最初の依頼どおり 1 階ロビーのまま完成しました。「もう一度」で「指示」も試せます。",- } satisfies Captions,- },- ko: {- title: "채팅 · 운영 도우미",- agent: "운영 도우미",- placeholder: "운영 도우미에게 메시지 보내기…",- queueSend: "대기열에 추가",- stop: "중지",- typing: "입력 중",- thinking: "생각 중",- repliedIn: (elapsed: string) => `${elapsed} 만에 답변`,- replyTimes: ["14s", "11s"],- cancelled: "이 답변이 취소되었습니다.",- queueTitle: "대기 중인 메시지 1개",- steer: "지시",- remove: "대기열에서 삭제",- more: "추가 대기열 작업",- edit: "대기 중인 메시지 편집",- clear: "모두 지우기",- firstPrompt: "다음 주 수요일 소방 훈련 전 직원 공지를 작성해 주세요. 집결 장소는 1층 로비입니다.",- partial: ["여러분, 다음 주 수요일 오후 3시에 소방 훈련이 있습니다. ", "경보가 울리면 가장 가까운 비상구로 나와 "],- tail: "1층 로비에 모여 주세요. 각 팀장은 인원을 확인해 총무팀에 알려 주세요.",- draft: "집결 장소를 지하 1층 주차장으로 바꿔 주세요. 그날 1층 로비는 공사 중이에요.",- steeredReply:- "여러분, 다음 주 수요일 오후 3시에 소방 훈련이 있습니다. 경보가 울리면 가장 가까운 비상구로 나와 지하 1층 주차장에 모여 주세요(그날 1층 로비는 공사 중입니다). 각 팀장은 인원을 확인해 총무팀에 알려 주세요.",- captions: {- idle: "운영 도우미에게 공지 초안을 부탁했습니다.",- opening: "운영 도우미가 답변을 쓰는 중입니다. 그때 집결 장소를 바꿔야 한다는 게 떠오릅니다.",- ready: "에이전트가 아직 답변 중이라 보내기 버튼이 '대기열에 추가'로 바뀌었습니다. 보내기를 클릭하세요.",- queued:- "메시지는 대기열에 들어가 현재 답변이 끝난 뒤에 처리됩니다. '지시'를 클릭하면 바로 처리되고, ⋯에서 대기열을 비울 수도 있습니다.",- menu: "'모두 지우기'는 대기 중인 메시지를 취소하고, 현재 답변은 그대로 이어집니다. '모두 지우기'를 클릭하세요.",- steering: "'지시'로 현재 답변이 멈췄고, 이미 쓴 부분은 채팅에 남았습니다. 에이전트가 바로 새 메시지를 처리합니다.",- steered: "새 집결 장소로 공지가 다시 작성되었습니다. '다시 보기'로 다시 볼 수 있습니다.",- clearing: "대기열이 비었고, 그 메시지는 에이전트에게 전달되지 않습니다. 현재 답변은 계속됩니다.",- cleared: "답변은 처음 요청대로 1층 로비로 완성되었습니다. '다시 보기'로 '지시'도 해 보세요.",- } satisfies Captions,- },- fr: {- title: "Discussion · Assistant ops",- agent: "Assistant ops",- placeholder: "Écrire à Assistant ops…",- queueSend: "Mettre le message en file d'attente",- stop: "Arrêter",- typing: "Rédaction",- thinking: "Réflexion",- repliedIn: (elapsed: string) => `Réponse en ${elapsed}`,- replyTimes: ["14s", "11s"],- cancelled: "Cette réponse a été annulée.",- queueTitle: "1 message en file d'attente",- steer: "Réorienter",- remove: "Retirer le message de la file d'attente",- more: "Plus d'actions sur la file d'attente",- edit: "Modifier le message en file d'attente",- clear: "Tout effacer",- firstPrompt:- "Rédigez une note à tout le personnel pour l'exercice d'évacuation de mercredi prochain. Point de rassemblement : le hall du rez-de-chaussée.",- partial: [- "Bonjour à tous, un exercice d'évacuation aura lieu mercredi prochain à 15 h. ",- "Quand l'alarme retentit, sortez par l'issue de secours la plus proche ",- ],- tail: "et rejoignez le hall du rez-de-chaussée. Les responsables d'équipe comptent leurs effectifs et préviennent les services généraux.",- draft: "Changez le point de rassemblement pour le parking du sous-sol : le hall est en travaux ce jour-là.",- steeredReply:- "Bonjour à tous, un exercice d'évacuation aura lieu mercredi prochain à 15 h. Quand l'alarme retentit, sortez par l'issue de secours la plus proche et rejoignez le parking du sous-sol (le hall est en travaux ce jour-là). Les responsables d'équipe comptent leurs effectifs et préviennent les services généraux.",- captions: {- idle: "Vous avez demandé à Assistant ops de rédiger une note.",- opening: "Assistant ops rédige sa réponse. Vous vous rappelez alors que le point de rassemblement doit changer.",- ready:- "L'agent répond encore : le bouton d'envoi met donc le message en file d'attente. Cliquez sur envoyer.",- queued:- "Le message attend dans la file jusqu'à la fin de la réponse en cours. Cliquez sur Réorienter pour qu'il soit traité tout de suite, ou ouvrez ⋯ pour vider la file.",- menu: "Tout effacer retire tous les messages en attente ; la réponse en cours continue. Cliquez sur Tout effacer.",- steering:- "Réorienter a arrêté la réponse en cours, en gardant ce qui était déjà écrit. L'agent traite aussitôt votre nouveau message.",- steered: "La note est réécrite avec le nouveau lieu. Utilisez Rejouer pour revoir la démo.",- clearing: "La file est vide et ce message n'arrivera pas à l'agent. La réponse en cours continue.",- cleared:- "La réponse s'est terminée comme demandé au départ, toujours dans le hall. Utilisez Rejouer pour essayer Réorienter.",- } satisfies Captions,- },-};--type Phase = keyof Captions;--export function ChatQueueDemo() {- const t = useDemoCopy(copy);- const { after, clear } = useDemoTimers();- const [frameRef, visible] = useStartWhenVisible<HTMLElement>();- const [run, setRun] = useState(0);- const [phase, setPhase] = useState<Phase>("idle");- const [chunks, setChunks] = useState(0);- const [secondPill, setSecondPill] = useState<"thinking" | "typing">("thinking");-- // Opening: the first reply streams in, then the composer offers the follow-up.- useEffect(() => {- if (!visible) return;- clear();- setPhase("opening");- setChunks(1);- after(1000, () => setChunks(2));- after(1800, () => setPhase("ready"));- }, [visible, run, after, clear]);-- const queue = () => setPhase("queued");-- const steer = () => {- setPhase("steering");- setSecondPill("thinking");- after(1100, () => setSecondPill("typing"));- after(2600, () => setPhase("steered"));- };-- const clearQueue = () => {- setPhase("clearing");- after(1600, () => setPhase("cleared"));- };-- const replay = () => {- clear();- setChunks(0);- setSecondPill("thinking");- setPhase("idle");- setRun((r) => r + 1);- };-- const steered = phase === "steering" || phase === "steered";- const firstDone = phase === "cleared";- const firstRunning = !steered && !firstDone;- const queueShown = phase === "queued" || phase === "menu";- // While the first reply is still being written, an empty composer offers Stop.- const showStop = phase === "queued" || phase === "menu" || phase === "clearing" || phase === "steering";- const partial = t.partial.slice(0, chunks).join("");-- return (- <DemoFrame frameRef={frameRef} title={t.title} caption={t.captions[phase]} onReplay={replay}>- <div className="flex min-h-96 flex-col gap-3 p-4">- <div className="flex flex-col gap-3">- <UserMessage>{t.firstPrompt}</UserMessage>- {phase !== "idle" && (- <AgentMessage name={t.agent} meta={firstDone ? t.repliedIn(t.replyTimes[0]!) : undefined}>- <p className={steered ? "text-muted-foreground" : undefined}>- {firstDone ? `${t.partial.join("")}${t.tail}` : partial}- </p>- {steered && <p className="mt-1 text-caption text-muted-foreground">{t.cancelled}</p>}- </AgentMessage>- )}- {phase !== "idle" && firstRunning && <StatusPill label={t.typing} />}-- {steered && <UserMessage>{t.draft}</UserMessage>}- {phase === "steering" && <StatusPill label={secondPill === "thinking" ? t.thinking : t.typing} />}- {phase === "steered" && (- <AgentMessage name={t.agent} meta={t.repliedIn(t.replyTimes[1]!)}>- <p>{t.steeredReply}</p>- </AgentMessage>- )}- </div>-- <div className="mt-auto">- {queueShown && (- <section- aria-label={t.queueTitle}- className="relative z-0 mx-3 -mb-3 rounded-lg border bg-muted/40 px-2 pt-1 pb-4 motion-safe:animate-in motion-safe:fade-in motion-safe:slide-in-from-bottom-2"- >- <div className="flex min-h-7 min-w-0 items-center gap-2 px-1 py-0.5 text-caption">- <ListEnd aria-hidden className="size-3.5 shrink-0 text-muted-foreground" />- <span className="min-w-0 flex-1 truncate text-muted-foreground">{t.draft}</span>- <div className="flex shrink-0 items-center gap-0.5">- <CoachMark quiet active={phase === "queued"} ringClassName="rounded-md">- <button- type="button"- disabled={phase !== "queued"}- onClick={steer}- className="inline-flex h-6 items-center gap-1 rounded-md px-1.5 text-caption text-muted-foreground hover:bg-accent hover:text-foreground disabled:opacity-60 disabled:hover:bg-transparent"- >- <CornerDownRight aria-hidden className="size-3.5" />- {t.steer}- </button>- </CoachMark>- <IconButton label={t.remove} disabled>- <Trash2 aria-hidden className="size-3.5" />- </IconButton>- <span className="relative inline-flex">- <IconButton- label={t.more}- disabled={phase !== "queued"}- pressed={phase === "menu"}- onClick={() => setPhase("menu")}- >- <Ellipsis aria-hidden className="size-3.5" />- </IconButton>- {phase === "menu" && (- <div- role="menu"- aria-label={t.more}- className="absolute right-0 bottom-full z-20 mb-1.5 flex w-max flex-col rounded-lg border bg-popover p-1 text-popover-foreground shadow-md motion-safe:animate-in motion-safe:fade-in"- >- <button- type="button"- role="menuitem"- disabled- className="flex items-center gap-2 rounded-md px-2 py-1.5 text-caption opacity-50"- >- <Pencil aria-hidden className="size-3.5" />- {t.edit}- </button>- <div aria-hidden className="-mx-1 my-1 h-px bg-border" />- <CoachMark quiet active ringClassName="rounded-md" className="flex">- <button- type="button"- role="menuitem"- onClick={clearQueue}- className="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-caption text-destructive hover:bg-destructive/10"- >- <Trash2 aria-hidden className="size-3.5" />- {t.clear}- </button>- </CoachMark>- </div>- )}- </span>- </div>- </div>- </section>- )}-- <div className="relative z-10 rounded-lg border bg-background p-2">- <div className="min-h-10 px-1 text-body">- {phase === "ready" || phase === "opening" ? (- <span className="motion-safe:animate-in motion-safe:fade-in">{t.draft}</span>- ) : (- <span className="text-muted-foreground">{t.placeholder}</span>- )}- </div>- <div className="mt-1.5 flex items-center">- <span className="ml-auto" />- {showStop ? (- <button- type="button"- aria-label={t.stop}- disabled- className="inline-flex size-7 items-center justify-center rounded-full bg-foreground text-background opacity-40"- >- <Square aria-hidden className="size-3 fill-current" />- </button>- ) : (- <CoachMark active={phase === "ready"} side="left" ringClassName="rounded-full">- <DemoSendButton label={t.queueSend} disabled={phase !== "ready"} onClick={queue} />- </CoachMark>- )}- </div>- </div>- </div>- </div>- </DemoFrame>- );-}--function IconButton({- label,- disabled,- pressed,- onClick,- children,-}: {- label: string;- disabled?: boolean;- pressed?: boolean;- onClick?: () => void;- children: ReactNode;-}) {- return (- <button- type="button"- aria-label={label}- aria-expanded={pressed}- disabled={disabled}- onClick={onClick}- className="inline-flex size-6 items-center justify-center rounded-md text-muted-foreground hover:bg-accent hover:text-foreground disabled:opacity-60 disabled:hover:bg-transparent aria-expanded:bg-accent"- >- {children}- </button>- );-}--function UserMessage({ children }: { children: ReactNode }) {- return (- <div className="flex justify-end motion-safe:animate-in motion-safe:fade-in motion-safe:slide-in-from-bottom-1">- <div className="max-w-[85%] rounded-2xl bg-muted px-3 py-2 text-body break-words">{children}</div>- </div>- );-}--function AgentMessage({ name, meta, children }: { name: string; meta?: string; children: ReactNode }) {- return (- <div className="min-w-0 motion-safe:animate-in motion-safe:fade-in">- <div className="flex items-center gap-2">- <DemoAvatar name={name} agent />- <span className="text-label font-medium">{name}</span>- {meta && <span className="text-caption text-muted-foreground">{meta}</span>}- </div>- <div className="mt-1 pl-7 text-body break-words">{children}</div>- </div>- );-}--function StatusPill({ label }: { label: string }) {- return (- <div className="pl-7">- <span className="inline-flex items-center gap-1.5 rounded-full bg-muted px-2.5 py-1 text-caption text-muted-foreground motion-safe:animate-in motion-safe:fade-in">- <Loader2 aria-hidden className="size-3 text-brand motion-safe:animate-spin" />- {label}- </span>- </div>- );-}diff --git a/apps/docs/content/docs/chat.fr.mdx b/apps/docs/content/docs/chat.fr.mdxindex 042c57d512..fd331208c6 100644--- a/apps/docs/content/docs/chat.fr.mdx+++ b/apps/docs/content/docs/chat.fr.mdx@@ -6,7 +6,6 @@ description: "Conversation en tête-à-tête avec un agent, visible de vous seulimport { Callout } from "fumadocs-ui/components/callout";import { Step, Steps } from "fumadocs-ui/components/steps";import { ChatDemo } from "@/components/demos/chat-demo";-import { ChatQueueDemo } from "@/components/demos/chat-queue-demo";Discussion convient aux sujets qui n'ont pas encore pris la forme d'une tâche claire : clarifier des idées, faire le point sur l'espace de travail, discuter d'une approche, poser une question qui ne relève d'aucune tâche, ou confier d'abord un petit travail à un agent.@@ -97,22 +96,13 @@ Si l'agent n'avait encore rien produit, le message que vous venez d'envoyer est## Envoyer des messages pendant une réponse-Vous pouvez continuer à écrire pendant que l'agent répond. Dès que la zone de saisie contient du texte, le bouton d'envoi devient **Mettre le message en file d'attente**. Les messages en file n'interrompent pas la réponse en cours : ils attendent dans une file au-dessus de la zone de saisie et sont traités dans l'ordre une fois la réponse terminée.+Vous pouvez écrire pendant que l’agent répond. Si le runtime le permet, **Envoyer** ajoute un message texte à la réponse en cours sans arrêter l’exécution. L’agent le lit au prochain moment approprié et poursuit la tâche initiale. Mettez votre daemon à jour pour activer cette fonction.-| Action | Résultat |-|---|---|-| **Réorienter** | Place ce message en tête de file et arrête la réponse en cours. Ce que l'agent a déjà écrit reste dans la conversation, puis il traite ce message. |-| Retirer (icône corbeille) | Retire le message de la file ; il n'est jamais envoyé à l'agent. |-| **⋯ → Modifier le message en file d'attente** | Remet le message et ses pièces jointes dans la zone de saisie pour le modifier et le renvoyer. |-| **⋯ → Tout effacer** | Retire tous les messages en file. La réponse en cours continue. |--**Réorienter** n'est pas disponible tant que la réponse en cours n'a pas vraiment commencé (par exemple quand elle attend encore qu'un runtime la prenne en charge), ni si vous avez perdu la permission d'exécuter l'agent.+Pour attendre le prochain tour, utilisez **Mettre le message en file d’attente** à côté d’Envoyer. Les pièces jointes, les messages envoyés avant le début de la réponse et les runtimes incompatibles utilisent aussi la file. Un message non transmis avant la fin de la réponse rejoint automatiquement la file ; inutile de le renvoyer. Si vous arrêtez pendant la transmission, Chat attend son résultat avant de mettre les messages non transmis en file. En cas de nouvelle tentative automatique, les instructions supplémentaires restent associées à la demande initiale pour être traitées ensemble. Lors de la reprise de la même session, les instructions déjà transmises ne sont pas renvoyées.-<ChatQueueDemo />+La file apparaît au-dessus du champ de saisie et suit l’ordre des messages. Vous pouvez supprimer un message, le modifier via **⋯**, ou vider la file. **Envoyer maintenant (arrête la réponse)** place le message en tête et arrête la réponse en cours. Cette action nécessite une réponse démarrée et le droit d’exécuter l’agent.-<Callout>-Ici, **Réorienter** arrête d'abord la réponse en cours. Dans les commentaires d'une tâche, [Ajouter à l'exécution en cours](/mentioning-agents#réorienter-un-agent-en-cours-dexécution) fonctionne autrement : l'exécution n'est pas interrompue, l'agent lit le message à la fin de l'étape en cours et poursuit la tâche d'origine.-</Callout>+Cette fonction concerne les conversations Chat directes sur les clients web et de bureau à jour. Le mobile, les anciens clients et les conversations Slack et Lark conservent leur file habituelle.## Organiser la liste des conversationsdiff --git a/apps/docs/content/docs/chat.ja.mdx b/apps/docs/content/docs/chat.ja.mdxindex f50cc20345..fb6060a0be 100644--- a/apps/docs/content/docs/chat.ja.mdx+++ b/apps/docs/content/docs/chat.ja.mdx@@ -6,7 +6,6 @@ description: エージェントとの一対一の会話で、あなたにしかimport { Callout } from "fumadocs-ui/components/callout";import { Step, Steps } from "fumadocs-ui/components/steps";import { ChatDemo } from "@/components/demos/chat-demo";-import { ChatQueueDemo } from "@/components/demos/chat-queue-demo";チャットは、まだ明確なタスクになっていない作業に向いています。アイデアの整理、ワークスペースの状況確認、方針の議論、どのタスクにも属さない質問、あるいは小さな作業を先にエージェントに任せる、といった使い方です。@@ -97,22 +96,13 @@ Multica で作成したダイレクトチャットを読めるのは作成者だ## 返信中に続けてメッセージを送る-エージェントが返信している間も、次のメッセージを入力できます。入力欄に内容があると、送信ボタンは**キューに追加**に変わります。キューに入ったメッセージは今の返信を中断せず、入力欄の上のキューで待ち、返信が終わると順番に処理されます。+エージェントの返信中も入力できます。ランタイムが対応していれば、**送信**でテキストを現在の返信に追加できます。実行は停止せず、エージェントは次の安全なタイミングで読み取り、元のタスクを続けます。この機能には daemon の更新が必要です。-| 操作 | 結果 |-|---|---|-| **指示** | このメッセージを先頭に移し、今の返信を停止します。エージェントがすでに書いた内容は会話に残り、続けてこのメッセージを処理します。 |-| 削除(ゴミ箱アイコン) | メッセージをキューから外します。エージェントには送られません。 |-| **⋯ → キュー内のメッセージを編集** | メッセージを添付ファイルごと入力欄に戻します。直してから送り直せます。 |-| **⋯ → すべて削除** | キュー内のメッセージをすべて取り消します。今の返信はそのまま続きます。 |--今の返信が実際に始まるまで(たとえばランタイムに受け取られるのを待っている間)は**指示**を使えません。エージェントを実行する権限を失った場合も使えません。+次のターンに回すには、送信の横の**キューに追加**を使います。添付ファイル付きのメッセージ、返信開始前のメッセージ、非対応ランタイムへのメッセージもキューに入ります。返信終了までに追加メッセージが届かなかった場合は自動的にキューに戻るので、再送は不要です。配信中に停止した場合、配信結果を待ってから未配信のメッセージをキューに戻します。返信が自動再試行される場合、追加メッセージは元のリクエストと一緒に処理されます。同じセッションを再開する際は、配信済みの追加メッセージを再送しません。-<ChatQueueDemo />+キューは入力欄の上に表示され、順番に処理されます。削除、**⋯** からの編集や全消去も可能です。**今すぐ送信(現在の返信を停止)** はキュー内のメッセージを先頭に移し、現在の返信を停止します。返信が開始済みで、実行権限が必要です。-<Callout>-ここでの**指示**は、まず今の返信を止めます。タスクのコメントで使う[現在の実行に追加](/mentioning-agents#実行中のエージェントに割り込む)は別の動きで、実行を中断せず、エージェントは今のステップが終わったところでメッセージを読み、元のタスクを続けます。-</Callout>+対象は更新済みのウェブ版とデスクトップ版の通常の Chat です。モバイル、旧クライアント、Slack や Lark の会話は従来のキュー動作を維持します。## チャット一覧の整理diff --git a/apps/docs/content/docs/chat.ko.mdx b/apps/docs/content/docs/chat.ko.mdxindex 2b6ad343ea..6ce2f3236e 100644--- a/apps/docs/content/docs/chat.ko.mdx+++ b/apps/docs/content/docs/chat.ko.mdx@@ -6,7 +6,6 @@ description: 에이전트와 일대일로 나누는 대화로, 나만 볼 수import { Callout } from "fumadocs-ui/components/callout";import { Step, Steps } from "fumadocs-ui/components/steps";import { ChatDemo } from "@/components/demos/chat-demo";-import { ChatQueueDemo } from "@/components/demos/chat-queue-demo";대화는 아직 명확한 태스크가 되지 않은 작업에 적합합니다. 아이디어를 정리하고, 워크스페이스 상황을 조회하고, 방안을 논의하고, 어떤 태스크에도 속하지 않는 질문을 하거나, 에이전트에게 작은 작업을 먼저 맡길 수 있습니다.@@ -97,22 +96,13 @@ Multica에서 만든 직접 대화는 만든 사람만 읽을 수 있고, 다른## 답변 중에 메시지 이어서 보내기-에이전트가 답변하는 동안에도 다음 메시지를 입력할 수 있습니다. 입력란에 내용이 있으면 보내기 버튼이 **대기열에 추가**로 바뀝니다. 대기열에 들어간 메시지는 현재 답변을 끊지 않고 입력란 위의 대기열에서 기다리다가, 답변이 끝나면 순서대로 처리됩니다.+에이전트가 응답하는 동안에도 입력할 수 있습니다. 런타임이 지원하면 **보내기**로 텍스트 메시지를 현재 응답에 추가합니다. 실행을 중지하지 않으며 에이전트가 다음 안전한 시점에 읽고 원래 작업을 계속합니다. 사용하려면 daemon을 업그레이드하세요.-| 동작 | 결과 |-|---|---|-| **지시** | 이 메시지를 맨 앞으로 옮기고 현재 답변을 멈춥니다. 에이전트가 이미 쓴 내용은 대화에 남고, 이어서 이 메시지를 처리합니다. |-| 삭제(휴지통 아이콘) | 메시지를 대기열에서 뺍니다. 에이전트에게는 전달되지 않습니다. |-| **⋯ → 대기 중인 메시지 편집** | 메시지를 첨부 파일과 함께 입력란으로 되돌립니다. 고친 뒤 다시 보내면 됩니다. |-| **⋯ → 모두 지우기** | 대기 중인 메시지를 모두 취소합니다. 현재 답변은 그대로 이어집니다. |--현재 답변이 실제로 시작되기 전(예: 런타임이 가져가기를 기다리는 중)에는 **지시**를 쓸 수 없고, 에이전트를 실행할 권한을 잃은 뒤에도 쓸 수 없습니다.+다음 차례에 처리하려면 보내기 옆의 **대기열에 추가**를 사용하세요. 첨부 파일이 있는 메시지, 응답 시작 전의 메시지, 미지원 런타임에 보내는 메시지도 대기열에 들어갑니다. 현재 응답이 끝날 때까지 전달되지 않은 메시지는 자동으로 대기열로 이동하므로 다시 보낼 필요가 없습니다. 전달 중에 중지하면 전달 결과를 기다린 후 미전달 메시지를 대기열에 넣습니다. 응답을 자동으로 재시도하면 추가 메시지도 원래 요청과 함께 처리됩니다. 같은 세션을 재개할 때 이미 전달된 추가 메시지는 다시 보내지 않습니다.-<ChatQueueDemo />+대기열은 입력창 위에 표시되며 순서대로 처리됩니다. 삭제하거나 **⋯** 에서 편집 또는 전체 삭제할 수 있습니다. **지금 보내기 (현재 응답 중지)** 는 메시지를 맨 앞으로 옮기고 현재 응답을 중지합니다. 응답이 시작된 상태이고 에이전트 실행 권한이 있어야 합니다.-<Callout>-여기서 **지시**는 현재 답변부터 멈춥니다. 태스크 댓글의 [현재 실행에 추가](/mentioning-agents#실행-중인-에이전트에게-끼어들기)는 다르게 동작합니다. 실행을 끊지 않고, 에이전트가 현재 단계를 마친 뒤 메시지를 읽고 원래 태스크를 이어 갑니다.-</Callout>+업데이트된 웹 및 데스크톱 클라이언트의 일반 Chat에 적용됩니다. 모바일, 이전 클라이언트, Slack과 Lark 채널 대화는 기존 대기열 동작을 유지합니다.## 대화 목록 정리diff --git a/apps/docs/content/docs/chat.mdx b/apps/docs/content/docs/chat.mdxindex 9b46166245..a555840e22 100644--- a/apps/docs/content/docs/chat.mdx+++ b/apps/docs/content/docs/chat.mdx@@ -6,7 +6,6 @@ description: A one-to-one conversation with an agent that only you can see. Theimport { Callout } from "fumadocs-ui/components/callout";import { Step, Steps } from "fumadocs-ui/components/steps";import { ChatDemo } from "@/components/demos/chat-demo";-import { ChatQueueDemo } from "@/components/demos/chat-queue-demo";Chat fits work that hasn't become a clear issue yet: sorting out ideas, checking on the workspace, discussing an approach, asking a question that doesn't belong to any issue, or having an agent finish a small task first.@@ -97,22 +96,13 @@ If the agent hadn't produced anything yet, the message you just sent is taken ba## Send messages while a reply is in progress-You can keep typing while the agent is still replying. Once the input has content, the send button becomes **Queue message**. Queued messages don't interrupt the current reply; they wait in a queue above the input and are handled in order after the reply ends.+You can keep typing while the agent is replying. **Send** adds a plain text message to the current reply without stopping it, when the runtime supports steering. The agent reads it at its next safe boundary and continues the original task. Upgrade your daemon to enable this.-| Action | Result |-|---|---|-| **Steer** | Moves this message to the front and stops the current reply. What the agent already wrote stays in the conversation, and it handles this message next. |-| Remove (trash icon) | Takes the message out of the queue; it is never sent to the agent. |-| **⋯ → Edit queued message** | Puts the message and its attachments back in the input so you can change it and send it again. |-| **⋯ → Clear all** | Withdraws every queued message. The current reply keeps going. |--**Steer** is unavailable until the current reply has actually started (for example, while it still waits for a runtime to pick it up), and after you lose permission to run the agent.+Use **Queue message** beside Send to save a message for the next turn instead. Messages with attachments, and messages sent before a reply starts or to a runtime without steering support, also enter the queue. If guidance is not delivered before the reply ends, it automatically becomes a queued message; you do not need to resend it. If you stop while delivery is in progress, Chat waits for its result before queuing undelivered guidance. If the reply is retried automatically, guidance stays with the original request so both are processed together. When resuming the same session, guidance already delivered there is not sent again.-<ChatQueueDemo />+Queued messages appear above the input and run in order. You can remove them, use **⋯ → Edit queued message** to restore them to the input, or **⋯ → Clear all** to withdraw them. **Send now (stops current reply)** moves a queued message to the front and stops the current reply. It requires an active reply and permission to run the agent.-<Callout>-**Steer** here stops the current reply first. [Add to current run](/mentioning-agents#steer-a-running-agent) in issue comments works differently: it doesn't interrupt the run, and the agent reads the message after its current step and carries on with the original task.-</Callout>+Steering applies to direct Chat sessions on updated web and desktop clients. Mobile, older clients, and Slack and Lark channel conversations keep their existing queue behavior.## Organize the conversation listdiff --git a/apps/docs/content/docs/chat.zh-Hant.mdx b/apps/docs/content/docs/chat.zh-Hant.mdxindex 2f26cb71f9..494cecdf20 100644--- a/apps/docs/content/docs/chat.zh-Hant.mdx+++ b/apps/docs/content/docs/chat.zh-Hant.mdx@@ -6,7 +6,6 @@ description: 和 AI 代理一對一聊天,整段對話只有你能看到。AIimport { Callout } from "fumadocs-ui/components/callout";import { Step, Steps } from "fumadocs-ui/components/steps";import { ChatDemo } from "@/components/demos/chat-demo";-import { ChatQueueDemo } from "@/components/demos/chat-queue-demo";對話適合還沒有形成明確任務的工作:梳理想法、查詢工作區情況、討論方案、問一個不屬於任何任務的問題,或者先讓 AI 代理完成一個小任務。@@ -97,22 +96,13 @@ AI 代理執行時,介面會顯示當前階段和工具活動。展開**檢視## 回覆還沒結束時繼續發訊息-AI 代理還在回覆時,可以接著輸入下一條。輸入框有內容時,傳送按鈕變成**排隊傳送**。排隊的訊息不會打斷當前回覆,而是顯示在輸入框上方的佇列裡,等當前回覆結束後按順序處理。+智能體仍在回覆時,可以繼續輸入。執行階段支援插話時,按**傳送**會把純文字訊息加入目前回覆,不會停止執行;智能體在下一個安全時機讀到訊息,繼續完成原任務。需要升級 daemon 才能啟用。-| 操作 | 結果 |-|---|---|-| **引導** | 把這條訊息提到隊首,並停止當前回覆。已經寫出的內容留在對話裡,AI 代理緊接著處理這條訊息。 |-| 刪除(垃圾桶圖示) | 從佇列裡移除這條訊息,它不會發給 AI 代理。 |-| **⋯ → 編輯排隊訊息** | 把訊息連同附件放回輸入框,改完重新傳送。 |-| **⋯ → 全部清空** | 撤回佇列裡的所有訊息,當前回覆照常進行。 |--當前回覆還沒真正開始(例如還在等執行時領取)時,**引導**按鈕不可用;失去這名 AI 代理的執行權限後也不能引導。+想留到下一輪,按傳送旁的**排隊傳送**。含附件的訊息、回覆尚未開始時傳送的訊息,以及不支援插話的執行,都會進入佇列。插話若未在目前回覆結束前送達,會自動轉成排隊訊息,無需重送。投遞過程中按停止,會先等待投遞結果,再將未送達的插話排隊。如果回覆自動重試,插話會保留在原請求中,一起處理;恢復同一會話時,已送達的插話不會再次傳送。-<ChatQueueDemo />+佇列顯示在輸入框上方,依序處理。可以移除、透過 **⋯ → 編輯排隊訊息** 放回輸入框,或用 **⋯ → 全部清空** 撤回。**立即傳送(停止目前回覆)** 會將訊息移到最前並停止目前回覆;需要回覆已開始,且你有執行該智能體的權限。-<Callout>-這裡的**引導**會先停掉當前回覆。任務評論裡的[插話到當前執行](/mentioning-agents#給正在執行的 AI 代理插話)不一樣:它不中斷執行,AI 代理在當前步驟結束後讀到插話,然後繼續原來的任務。-</Callout>+插話適用於新版網頁和桌面用戶端的一般 Chat;行動版、舊版用戶端和 Slack、Lark 等渠道會話維持原有佇列行為。## 整理對話列表diff --git a/apps/docs/content/docs/chat.zh.mdx b/apps/docs/content/docs/chat.zh.mdxindex 29c6bb1aa1..d4ebe32a4a 100644--- a/apps/docs/content/docs/chat.zh.mdx+++ b/apps/docs/content/docs/chat.zh.mdx@@ -6,7 +6,6 @@ description: 和智能体一对一聊天,整段对话只有你能看到。智import { Callout } from "fumadocs-ui/components/callout";import { Step, Steps } from "fumadocs-ui/components/steps";import { ChatDemo } from "@/components/demos/chat-demo";-import { ChatQueueDemo } from "@/components/demos/chat-queue-demo";对话适合还没有形成明确任务的工作:梳理想法、查询工作区情况、讨论方案、问一个不属于任何任务的问题,或者先让智能体完成一个小任务。@@ -97,22 +96,13 @@ import { ChatQueueDemo } from "@/components/demos/chat-queue-demo";## 回复还没结束时继续发消息-智能体还在回复时,可以接着输入下一条。输入框有内容时,发送按钮变成**排队发送**。排队的消息不会打断当前回复,而是显示在输入框上方的队列里,等当前回复结束后按顺序处理。+智能体还在回复时,可以继续输入。运行时支持插话时,点**发送**会把纯文本消息插入当前回复,不会停止运行;智能体在下一个安全时机读到消息,继续完成原任务。需要升级 daemon 才能启用。-| 操作 | 结果 |-|---|---|-| **引导** | 把这条消息提到队首,并停止当前回复。已经写出的内容留在对话里,智能体紧接着处理这条消息。 |-| 删除(垃圾桶图标) | 从队列里移除这条消息,它不会发给智能体。 |-| **⋯ → 编辑排队消息** | 把消息连同附件放回输入框,改完重新发送。 |-| **⋯ → 全部清空** | 撤回队列里的所有消息,当前回复照常进行。 |--当前回复还没真正开始(例如还在等运行时领取)时,**引导**按钮不可用;失去这名智能体的运行权限后也不能引导。+想留到下一轮,点发送旁边的**排队发送**。带附件的消息、回复尚未开始时发送的消息,以及不支持插话的运行,都会进入队列。如果插话在当前回复结束前没送达,会自动转成排队消息,无需重发。投递过程中点停止,会先等待投递结果,再将未送达的插话排队。如果回复自动重试,插话会保留在原请求中,一起处理;恢复同一会话时,已送达的插话不会再次发送。-<ChatQueueDemo />+排队消息显示在输入框上方,按顺序处理。可以删除,通过 **⋯ → 编辑排队消息** 放回输入框,或用 **⋯ → 全部清空** 撤回。**立即发送(停止当前回复)** 会把排队消息提到队首,并停止当前回复;需要当前回复已开始,且你有运行该智能体的权限。-<Callout>-这里的**引导**会先停掉当前回复。任务评论里的[插话到当前运行](/mentioning-agents#给正在运行的智能体插话)不一样:它不中断运行,智能体在当前步骤结束后读到插话,然后继续原来的任务。-</Callout>+插话适用于新版网页和桌面客户端的普通 Chat;移动端、旧版客户端和 Slack、Lark 等渠道会话保持原有排队行为。## 整理对话列表diff --git a/apps/docs/content/docs/mentioning-agents.fr.mdx b/apps/docs/content/docs/mentioning-agents.fr.mdxindex b281b9f5e8..84d0f9bffb 100644--- a/apps/docs/content/docs/mentioning-agents.fr.mdx+++ b/apps/docs/content/docs/mentioning-agents.fr.mdx@@ -67,7 +67,7 @@ Après l'envoi, le commentaire affiche d'abord « En attente de lecture par …- Seul du texte peut rejoindre une exécution en cours. Un message avec des pièces jointes est traité après la fin de l'exécution.- La réorientation doit être prise en charge par l'outil de codage IA de l'agent. Sinon, « Ajouter à l'exécution en cours » n'est pas proposé.- Le choix par défaut se règle dans **Paramètres → Préférences**, sous **En répondant à un agent en cours d'exécution**. Vous pouvez toujours le modifier pour chaque message avant l'envoi.-- Dans le chat, **Réorienter** sur un message en file d'attente fonctionne autrement : la réponse en cours s'arrête d'abord ; voir [Chat](/chat#envoyer-des-messages-pendant-une-réponse).+- Dans un Chat compatible, envoyer un texte pendant une réponse l’ajoute à cette réponse sans l’arrêter. Utilisez **Mettre le message en file d’attente** pour le prochain tour ; voir [Chat](/chat#envoyer-des-messages-pendant-une-réponse).## Regroupement des commentaires consécutifsdiff --git a/apps/docs/content/docs/mentioning-agents.ja.mdx b/apps/docs/content/docs/mentioning-agents.ja.mdxindex 52c8c36618..012ba18309 100644--- a/apps/docs/content/docs/mentioning-agents.ja.mdx+++ b/apps/docs/content/docs/mentioning-agents.ja.mdx@@ -67,7 +67,7 @@ import { SteerDemo } from "@/components/demos/steer-demo";- 実行中に追加できるのはテキストだけです。ファイル付きのメッセージは、この実行の後に処理されます。- 割り込みには、エージェントが使う AI コーディングツールの対応が必要です。対応していない場合、「現在の実行に追加」は選択肢に表示されません。- 既定の選択肢は **設定 → 環境設定** の **実行中のエージェントに返信するとき** で変えられます。メッセージごとに送信前に変更することもできます。-- チャットでキュー内のメッセージに使う**指示**は動きが違い、現在の返信を先に止めます。[チャット](/chat#返信中に続けてメッセージを送る)を参照してください。+- 対応する Chat の返信中にテキストを送信すると、実行を止めずに現在の返信に追加します。次のターンに回すには**キューに追加**を使います。[チャット](/chat#返信中に続けてメッセージを送る)を参照してください。## 連続コメントの統合diff --git a/apps/docs/content/docs/mentioning-agents.ko.mdx b/apps/docs/content/docs/mentioning-agents.ko.mdxindex 20011404a5..4f42679f34 100644--- a/apps/docs/content/docs/mentioning-agents.ko.mdx+++ b/apps/docs/content/docs/mentioning-agents.ko.mdx@@ -67,7 +67,7 @@ import { SteerDemo } from "@/components/demos/steer-demo";- 실행 중에는 텍스트만 추가할 수 있습니다. 첨부 파일이 있는 메시지는 이번 실행이 끝난 뒤 처리됩니다.- 끼어들기는 에이전트가 쓰는 AI 코딩 도구가 지원해야 합니다. 지원하지 않으면 '현재 실행에 추가'가 옵션에 나오지 않습니다.- 기본 옵션은 **설정 → 환경설정**의 **실행 중인 에이전트에 답장할 때**에서 바꿀 수 있고, 메시지마다 보내기 전에 따로 바꿀 수도 있습니다.-- 채팅에서 대기 중인 메시지의 **지시**는 다르게 동작해 현재 답변을 먼저 멈춥니다. [채팅](/chat#답변-중에-메시지-이어서-보내기)을 참고하세요.+- 지원되는 Chat 응답 중에 텍스트를 보내면 실행을 중지하지 않고 현재 응답에 추가합니다. 다음 차례에 처리하려면 **대기열에 추가**를 사용하세요. [채팅](/chat#답변-중에-메시지-이어서-보내기)을 참고하세요.## 연속 댓글 합치기diff --git a/apps/docs/content/docs/mentioning-agents.mdx b/apps/docs/content/docs/mentioning-agents.mdxindex b4cf0ca77d..a3d27da0a8 100644--- a/apps/docs/content/docs/mentioning-agents.mdx+++ b/apps/docs/content/docs/mentioning-agents.mdx@@ -67,7 +67,7 @@ After you send, the comment shows "Waiting for … to read it", which changes to- Only text can join a running run. A message with attachments is handled after the run ends.- Steering needs support from the agent's AI coding tool. Without it, **Add to current run** isn't offered.- Set the default in **Settings → Preferences** under **When replying to a running agent**. You can still change it for any message before sending.-- In chat, **Steer** on a queued message works differently: it stops the current reply first; see [Chat](/chat#send-messages-while-a-reply-is-in-progress).+- In Chat, sending a text message during a supported reply steers that reply without stopping it. Use **Queue message** to wait for the next turn; see [Chat](/chat#send-messages-while-a-reply-is-in-progress).## Coalescing consecutive commentsdiff --git a/apps/docs/content/docs/mentioning-agents.zh-Hant.mdx b/apps/docs/content/docs/mentioning-agents.zh-Hant.mdxindex 174dc623c0..4c4257e4d5 100644--- a/apps/docs/content/docs/mentioning-agents.zh-Hant.mdx+++ b/apps/docs/content/docs/mentioning-agents.zh-Hant.mdx@@ -67,7 +67,7 @@ AI 代理做到一半、方向不對時,不必停下來重來。在評論框- 插話只支援文字。帶附件的訊息會在本輪結束後處理。- 插話需要 AI 代理使用的 AI 程式設計工具支援;不支援時,選項裡不會出現"插話到當前執行"。- 預設選項在設定的**回覆正在執行的 AI 代理時**中調整,每條訊息傳送前仍可單獨修改。-- 聊天裡排隊訊息的**引導**不一樣:它會先停掉當前回覆,見[聊天](/chat#回覆還沒結束時繼續發訊息)。+- 一般 Chat 支援插話時,回覆中直接傳送文字就會加入目前回覆,不會停止執行;也可以選擇**排隊傳送**留到下一輪,見[聊天](/chat#回覆還沒結束時繼續發訊息)。## 連續評論的合併diff --git a/apps/docs/content/docs/mentioning-agents.zh.mdx b/apps/docs/content/docs/mentioning-agents.zh.mdxindex 7e4be9618a..debc351293 100644--- a/apps/docs/content/docs/mentioning-agents.zh.mdx+++ b/apps/docs/content/docs/mentioning-agents.zh.mdx@@ -67,7 +67,7 @@ import { SteerDemo } from "@/components/demos/steer-demo";- 插话只支持文字。带附件的消息会在本轮结束后处理。- 插话需要智能体使用的 AI 编程工具支持;不支持时,选项里不会出现"插话到当前运行"。- 默认选项在设置的**回复正在运行的智能体时**中调整,每条消息发送前仍可单独修改。-- 聊天里排队消息的**引导**不一样:它会先停掉当前回复,见[聊天](/chat#回复还没结束时继续发消息)。+- 普通 Chat 支持插话时,回复中直接发送文本就会插入当前回复,不会停止运行;也可以选择**排队发送**留到下一轮,见[聊天](/chat#回复还没结束时继续发消息)。## 连续评论的合并diff --git a/packages/core/api/client.test.ts b/packages/core/api/client.test.tsindex f0f6bf1904..6d39bcd2a2 100644--- a/packages/core/api/client.test.ts+++ b/packages/core/api/client.test.ts@@ -2286,6 +2286,7 @@ describe("ApiClient", () => {const [, init] = fetchMock.mock.calls[0]!;expect(JSON.parse(init?.body as string)).toEqual({content: "hello",+ steer: true,attachment_ids: ["att-1", "att-2"],});});@@ -2305,8 +2306,17 @@ describe("ApiClient", () => {await client.sendChatMessage("session-1", "hello");await client.sendChatMessage("session-1", "again", []);- expect(JSON.parse(fetchMock.mock.calls[0]![1]?.body as string)).toEqual({ content: "hello" });- expect(JSON.parse(fetchMock.mock.calls[1]![1]?.body as string)).toEqual({ content: "again" });+ expect(JSON.parse(fetchMock.mock.calls[0]![1]?.body as string)).toEqual({ content: "hello", steer: true });+ expect(JSON.parse(fetchMock.mock.calls[1]![1]?.body as string)).toEqual({ content: "again", steer: true });+ });++ it("sendChatMessage explicitly opts out of steering for Queue message", async () => {+ const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify({+ message_id: "m1", task_id: "t1", created_at: "2026-08-01T00:00:00Z",+ }), { status: 201 }));+ vi.stubGlobal("fetch", fetchMock);+ await new ApiClient("https://api.example.test").sendChatMessage("session-1", "next turn", undefined, { queue: true });+ expect(JSON.parse(fetchMock.mock.calls[0]![1]?.body as string)).toEqual({ content: "next turn", steer: false });});it("sendChatMessage accepts the server's null attachment_ids for text-only sends", async () => {diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex 52492cc59b..0def60adba 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -4228,11 +4228,13 @@ export class ApiClient {sessionId: string,content: string,attachmentIds?: string[],+ options?: { queue?: boolean },): Promise<SendChatMessageResponse> {const body: {content: string;+ steer: boolean;attachment_ids?: string[];- } = { content };+ } = { content, steer: options?.queue !== true };if (attachmentIds && attachmentIds.length > 0) {body.attachment_ids = attachmentIds;}diff --git a/packages/core/api/schemas.test.ts b/packages/core/api/schemas.test.tsindex 5b0e658c51..4abc80e884 100644--- a/packages/core/api/schemas.test.ts+++ b/packages/core/api/schemas.test.ts@@ -931,6 +931,14 @@ describe("SendChatMessageResponseSchema", () => {it("ignores a malformed additive queue position without losing the accepted send", () => {expect(SendChatMessageResponseSchema.parse({ ...base, queued: "no" }).queued).toBeUndefined();});++ it("preserves steering acceptance and tolerates older or malformed metadata", () => {+ expect(SendChatMessageResponseSchema.parse({ ...base, steered: true }).steered).toBe(true);+ expect(SendChatMessageResponseSchema.parse({ ...base, steered: true, message_task_id: "root-task" }).message_task_id).toBe("root-task");+ expect(SendChatMessageResponseSchema.parse(base).steered).toBeUndefined();+ expect(SendChatMessageResponseSchema.parse({ ...base, steered: "yes", message_created_at: 42, message_task_id: 42 }))+ .toMatchObject({ ...base, steered: undefined, message_created_at: undefined, message_task_id: undefined });+ });});describe("PrioritizeQueuedChatTaskResponseSchema", () => {diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.tsindex 3b3dad2345..58cae25e9b 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -2625,6 +2625,9 @@ export const ChatPendingTaskSchema: z.ZodType<ChatPendingTask> = z.object({export const EMPTY_CHAT_PENDING_TASK: ChatPendingTask = {};export const SendChatMessageResponseSchema: z.ZodType<SendChatMessageResponse> = z.object({+ steered: z.boolean().optional().catch(undefined),+ message_created_at: z.string().optional().catch(undefined),+ message_task_id: z.string().optional().catch(undefined),message_id: z.string().min(1),task_id: z.string().min(1),supports_queue: z.boolean().optional(),diff --git a/packages/core/types/chat.ts b/packages/core/types/chat.tsindex b11f32f13f..76d2038959 100644--- a/packages/core/types/chat.ts+++ b/packages/core/types/chat.ts@@ -187,6 +187,11 @@ export interface ChatMessagesPage {}export interface SendChatMessageResponse {+ /** Accepted into the running reply without creating another turn. */+ steered?: boolean;+ message_created_at?: string;+ /** Input owner of the user message; may differ from the active retry. */+ message_task_id?: string;message_id: string;task_id: string;/** True when the server supports queued follow-up sends. */diff --git a/packages/views/chat/components/chat-input.test.tsx b/packages/views/chat/components/chat-input.test.tsxindex 14cadd7b3e..19bac4f08c 100644--- a/packages/views/chat/components/chat-input.test.tsx+++ b/packages/views/chat/components/chat-input.test.tsx@@ -994,7 +994,7 @@ describe("ChatInput project context", () => {expect(onProjectChange).toHaveBeenCalledWith(null);});- it("swaps Stop for Queue Send when the running composer has content", async () => {+ it("offers default Send and an explicit queue action while replying", async () => {const onSend = vi.fn<ChatInputOnSend>(async () => true);const onStop = vi.fn();renderInput({ isRunning: true, allowSubmitWhileRunning: true, onSend, onStop });@@ -1007,17 +1007,28 @@ describe("ChatInput project context", () => {});expect(screen.queryByRole("button", { name: "Stop" })).not.toBeInTheDocument();+ expect(screen.getByRole("button", { name: "Send" })).not.toBeDisabled();const queueButton = screen.getByRole("button", { name: "Queue message" });expect(queueButton).not.toBeDisabled();fireEvent.click(queueButton);await waitFor(() => expect(onSend).toHaveBeenCalledTimes(1));+ expect(onSend.mock.calls[0]?.[4]).toEqual({ queue: true });await waitFor(() => {expect(screen.getByRole("button", { name: "Stop" })).toBeInTheDocument();});expect(screen.queryByRole("button", { name: "Queue message" })).not.toBeInTheDocument();});+ it("sends guidance by default during a reply without forcing the queue", async () => {+ const onSend = vi.fn<ChatInputOnSend>(async () => true);+ renderInput({ isRunning: true, allowSubmitWhileRunning: true, onSend });+ fireEvent.change(screen.getByTestId("editor"), { target: { value: "use the new location" } });+ fireEvent.click(screen.getByRole("button", { name: "Send" }));+ await waitFor(() => expect(onSend).toHaveBeenCalledTimes(1));+ expect(onSend.mock.calls[0]?.[4]).toBeUndefined();+ });+it("keeps Stop available while queued content is uploading", async () => {let resolveUpload!: (value: UploadResult) => void;mockApiUploadFile.mockImplementation(diff --git a/packages/views/chat/components/chat-input.tsx b/packages/views/chat/components/chat-input.tsxindex 2cc7098b92..ec63390a72 100644--- a/packages/views/chat/components/chat-input.tsx+++ b/packages/views/chat/components/chat-input.tsx@@ -2,7 +2,7 @@import type { ReactNode } from "react";import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";-import { Scan, TriangleAlert, X } from "@multica/ui/icons";+import { ListEnd, Scan, TriangleAlert, X } from "@multica/ui/icons";import { IconButton } from "@multica/ui/components/common/icon-button";import { toast } from "sonner";import { cn } from "@multica/ui/lib/utils";@@ -76,6 +76,7 @@ interface ChatInputProps {attachmentIds: string[] | undefined,commitInput: (options?: { extraDraftKeys?: string[]; clearEditor?: boolean }) => void,draftAttachments: Attachment[],+ options?: { queue?: boolean },) => void | boolean | Promise<void | boolean>;restoreDraftRequest?: {id: string;@@ -493,6 +494,7 @@ export function ChatInput({// stale `true` behind for the next one.const editorScrubbedRef = useRef(false);+ const queueNextSendRef = useRef(false);const { submitting, submit } = useComposerSubmit({editorRef,uploadGate: gate,@@ -508,6 +510,8 @@ export function ChatInput({return hasReplyIntent(raw, current) ? composeAnnotatedReply(raw, current) : "";},onSubmit: async (content: string): Promise<boolean> => {+ const queue = queueNextSendRef.current;+ queueNextSendRef.current = false;editorScrubbedRef.current = false;// Same tick as `normalize`, so this is exactly what `content` quotes.const annotationKeyAtSend = annotationDraftKey;@@ -616,12 +620,15 @@ export function ChatInput({const sent = attachedPage? `[${escapeMarkdownLabel(attachedPage.label)}](mention://${attachedPage.type}/${attachedPage.id})\n\n${content}`: content;- const accepted = await onSend(+ const sendArgs = [sent,uniqueActiveIds.length > 0 ? uniqueActiveIds : undefined,commitInput,draftAttachments.filter((attachment) => uniqueActiveIds.includes(attachment.id)),- );+ ] as const;+ const accepted = queue+ ? await onSend(...sendArgs, { queue: true })+ : await onSend(...sendArgs);// Owner rejected the send (or threw, which useComposerSubmit also treats// as a rejection): the draft was never committed, so it stays put for// retry. Only a commit — here or by the owner — clears it.@@ -914,13 +921,26 @@ export function ChatInput({<Scan /></IconButton>)}+ {isRunning && allowSubmitWhileRunning && !hasNothingToSend && !gate.uploading && (+ <IconButton+ type="button"+ label={t(($) => $.input.queue_send_tooltip)}+ disabled={submitting || gate.uploading || !!disabled || !!noAgent}+ onClick={() => {+ queueNextSendRef.current = true;+ void submit().finally(() => { queueNextSendRef.current = false; });+ }}+ >+ <ListEnd />+ </IconButton>+ )}<SubmitButtononClick={submit}disabled={hasNothingToSend || submitting || !!disabled || !!noAgent}loading={submitting}busy={gate.uploading}// Queue-capable runs reuse this one action slot: an empty composer- // offers Stop, while live content swaps it to Queue Send. Older+ // offers Stop, while live content swaps it to Send. Older// servers cannot accept follow-ups, so they remain stop-only. An// upload blocks submit, so it also falls back to Stop rather than// removing chat's only cancellation path; the attachment node@@ -937,7 +957,7 @@ export function ChatInput({? placeholder: undefined}tooltip={isRunning- ? t(($) => $.input.queue_send_tooltip)+ ? t(($) => $.input.send_tooltip): sendShortcut? (<>@@ -948,8 +968,6 @@ export function ChatInput({: t(($) => $.input.send_tooltip)}ariaLabel={gate.uploading? tEditor(($) => $.upload.in_progress)- : isRunning- ? t(($) => $.input.queue_send_tooltip): t(($) => $.input.send_tooltip)}stopTooltip={t(($) => $.input.stop_tooltip)}stopAriaLabel={t(($) => $.input.stop_tooltip)}diff --git a/packages/views/chat/components/chat-queue.test.tsx b/packages/views/chat/components/chat-queue.test.tsxindex 11687a1fd7..9e09d0d193 100644--- a/packages/views/chat/components/chat-queue.test.tsx+++ b/packages/views/chat/components/chat-queue.test.tsx@@ -47,7 +47,7 @@ describe("ChatQueue", () => {expect(screen.queryByText("2 queued messages")).not.toBeInTheDocument();expect(screen.getByText("First follow-up")).toBeInTheDocument();expect(screen.getByText("Queued message")).toBeInTheDocument();- expect(screen.getAllByRole("button", { name: "Steer" })).toHaveLength(2);+ expect(screen.getAllByRole("button", { name: "Send now (stops current reply)" })).toHaveLength(2);expect(screen.getAllByLabelText("Remove queued message")).toHaveLength(2);expect(screen.getAllByLabelText("More queue actions")).toHaveLength(2);expect(screen.queryByRole("button", { name: "Clear all" })).not.toBeInTheDocument();@@ -70,7 +70,7 @@ describe("ChatQueue", () => {it("runs steer, remove, and overflow actions against the selected queue state", async () => {const actions = renderQueue();- fireEvent.click(screen.getAllByRole("button", { name: "Steer" })[1]!);+ fireEvent.click(screen.getAllByRole("button", { name: "Send now (stops current reply)" })[1]!);await waitFor(() => expect(actions.onSendNow).toHaveBeenCalledWith("task-3"));fireEvent.click(screen.getAllByLabelText("More queue actions")[0]!);@@ -89,7 +89,7 @@ describe("ChatQueue", () => {const actions = renderQueue("queued");const buttons = screen.getAllByRole("button", {- name: "Steer is available after the current reply starts",+ name: "Available after the current reply starts",});expect(buttons).toHaveLength(2);for (const button of buttons) expect(button).toBeDisabled();@@ -147,6 +147,6 @@ describe("ChatQueue send-now gating", () => {it("leaves Steer available when the head task is dispatchable and permitted", () => {renderQueue("running", false);- expect(screen.getAllByRole("button", { name: "Steer" })[0]!).not.toBeDisabled();+ expect(screen.getAllByRole("button", { name: "Send now (stops current reply)" })[0]!).not.toBeDisabled();});});diff --git a/packages/views/chat/components/use-chat-controller.test.tsx b/packages/views/chat/components/use-chat-controller.test.tsxindex 7aed14e877..a5531fc3d2 100644--- a/packages/views/chat/components/use-chat-controller.test.tsx+++ b/packages/views/chat/components/use-chat-controller.test.tsx@@ -1207,6 +1207,32 @@ describe("useChatController.handleSend — compose target tracking", () => {};}+ it("keeps the active retry and stores guidance under its root input owner", async () => {+ h.pendingTask = { task_id: "running-task", status: "running", supports_queue: true };+ vi.mocked(api.sendChatMessage).mockResolvedValue({+ message_id: "guidance", task_id: "running-task", message_task_id: "root-task", steered: true,+ created_at: "2026-01-01T00:00:00Z", message_created_at: "2026-01-01T00:01:00Z",+ });+ h.queryClient.setQueryData.mockClear();+ const { send, commitInput } = sendFrom("sA");+ await send();+ expect(h.queryClient.setQueryData.mock.calls.filter(([key]) =>+ JSON.stringify(key) === JSON.stringify(chatKeys.pendingTask("sA"))))+ .toHaveLength(0);+ const cacheWrite = h.queryClient.setQueryData.mock.calls.find(([key]) =>+ JSON.stringify(key) === JSON.stringify(chatKeys.messages("sA")));+ expect(cacheWrite).toBeDefined();+ expect(cacheWrite).toEqual([+ expect.objectContaining({+ id: "guidance",+ task_id: "root-task",+ created_at: "2026-01-01T00:01:00Z",+ }),+ ]);+ expect(commitInput).toHaveBeenCalled();+ expect(api.cancelTaskById).not.toHaveBeenCalled();+ });+it("scrubs the composer after a new chat's first send", async () => {const { commitInput, send } = sendFrom(null);await send();diff --git a/packages/views/chat/components/use-chat-controller.ts b/packages/views/chat/components/use-chat-controller.tsindex a16c4f9294..cb80eb241e 100644--- a/packages/views/chat/components/use-chat-controller.ts+++ b/packages/views/chat/components/use-chat-controller.ts@@ -471,6 +471,7 @@ export function useChatController(opts?: { isActive?: boolean }) {attachmentIds?: string[],commitInput?: (options?: { extraDraftKeys?: string[]; clearEditor?: boolean }) => void,draftAttachments: Attachment[] = [],+ options?: { queue?: boolean },): Promise<boolean> => {if (!activeAgent) {apiLogger.warn("sendChatMessage skipped: no active agent");@@ -551,7 +552,9 @@ export function useChatController(opts?: { isActive?: boolean }) {// the draft for retry (ChatInput never cleared it).let result;try {- result = await api.sendChatMessage(sessionId, finalContent, attachmentIds);+ result = options?.queue+ ? await api.sendChatMessage(sessionId, finalContent, attachmentIds, options)+ : await api.sendChatMessage(sessionId, finalContent, attachmentIds);} catch (err) {apiLogger.error("sendChatMessage.error", { sessionId, err });// Invoke permission can be revoked mid-session; the send is refused with@@ -588,8 +591,8 @@ export function useChatController(opts?: { isActive?: boolean }) {chat_session_id: sessionId,role: "user",content: finalContent,- task_id: result.task_id,- created_at: result.created_at,+ task_id: result.message_task_id ?? result.task_id,+ created_at: result.message_created_at ?? result.created_at,attachments: draftAttachments,};// Single door into the message caches (MUL-5711): idempotent by id, so@@ -597,14 +600,16 @@ export function useChatController(opts?: { isActive?: boolean }) {// arrival order, and this richer row (it carries the draft attachments)// is never downgraded by the echo, which has no attachments field.upsertChatMessageToCaches(qc, sessionId, sent, { seedIfMissing: true });- seedAcceptedPendingTask(qc, sessionId, {- task_id: result.task_id,- created_at: result.created_at,- message_id: result.message_id,- content: finalContent,- supports_queue: result.supports_queue,- queued: result.queued,- });+ if (result.steered !== true) {+ seedAcceptedPendingTask(qc, sessionId, {+ task_id: result.task_id,+ created_at: result.created_at,+ message_id: result.message_id,+ content: finalContent,+ supports_queue: result.supports_queue,+ queued: result.queued,+ });+ }// This send just committed the new session's server-derived title.if (sessionId !== activeSessionId) {void refetchChatSessionsAfterCommit(qc, chatKeys.sessions(wsId));diff --git a/packages/views/locales/en/chat.json b/packages/views/locales/en/chat.jsonindex 2fa8258c67..d9db237d3d 100644--- a/packages/views/locales/en/chat.json+++ b/packages/views/locales/en/chat.json@@ -55,10 +55,10 @@"title_one": "{{count}} queued message","title_other": "{{count}} queued messages","clear": "Clear all",- "steer": "Steer",- "steer_unavailable": "Steer is available after the current reply starts",+ "steer": "Send now (stops current reply)",+ "steer_unavailable": "Available after the current reply starts","steer_no_permission": "You no longer have permission to run this agent",- "steer_unavailable_toast": "Steer is unavailable. Refreshing the queue.",+ "steer_unavailable_toast": "Send now is unavailable. Refreshing the queue.","edit": "Edit queued message","remove": "Remove queued message","more": "More queue actions",diff --git a/packages/views/locales/es/chat.json b/packages/views/locales/es/chat.jsonindex dabfec9fca..67cd34000c 100644--- a/packages/views/locales/es/chat.json+++ b/packages/views/locales/es/chat.json@@ -55,10 +55,10 @@"title_one": "{{count}} mensaje en cola","title_other": "{{count}} mensajes en cola","clear": "Limpiar todo",- "steer": "Dirigir",- "steer_unavailable": "Dirigir está disponible cuando empiece la respuesta actual",+ "steer": "Enviar ahora (detiene la respuesta)",+ "steer_unavailable": "Disponible cuando comience la respuesta","steer_no_permission": "Ya no tienes permiso para ejecutar este agente",- "steer_unavailable_toast": "Dirigir no está disponible. Actualizando la cola.",+ "steer_unavailable_toast": "Envío inmediato no disponible. Actualizando la cola.","edit": "Editar mensaje en cola","remove": "Quitar mensaje en cola","more": "Más acciones de la cola",diff --git a/packages/views/locales/fr/chat.json b/packages/views/locales/fr/chat.jsonindex b7f79e1563..26b53651a8 100644--- a/packages/views/locales/fr/chat.json+++ b/packages/views/locales/fr/chat.json@@ -55,10 +55,10 @@"title_one": "{{count}} message en file d'attente","title_other": "{{count}} messages en file d'attente","clear": "Tout effacer",- "steer": "Réorienter",- "steer_unavailable": "La réorientation est possible une fois la réponse en cours démarrée",+ "steer": "Envoyer maintenant (arrête la réponse)",+ "steer_unavailable": "Disponible après le début de la réponse","steer_no_permission": "Vous n'avez plus l'autorisation d'exécuter cet agent",- "steer_unavailable_toast": "La réorientation est indisponible. Actualisation de la file d'attente.",+ "steer_unavailable_toast": "Envoi immédiat indisponible. Actualisation de la file.","edit": "Modifier le message en file d'attente","remove": "Retirer le message de la file d'attente","more": "Plus d'actions sur la file d'attente",diff --git a/packages/views/locales/ja/chat.json b/packages/views/locales/ja/chat.jsonindex 442feb605f..10072077ec 100644--- a/packages/views/locales/ja/chat.json+++ b/packages/views/locales/ja/chat.json@@ -52,10 +52,10 @@"queue": {"title_other": "キュー内のメッセージ {{count}} 件","clear": "すべて削除",- "steer": "指示",- "steer_unavailable": "現在の返信が開始されると指示できます",+ "steer": "今すぐ送信(現在の返信を停止)",+ "steer_unavailable": "現在の返信が開始すると利用できます","steer_no_permission": "このエージェントを実行する権限がありません",- "steer_unavailable_toast": "現在は指示できません。キューを更新しています。",+ "steer_unavailable_toast": "今すぐ送信できません。キューを更新しています。","edit": "キュー内のメッセージを編集","remove": "キューから削除","more": "その他のキュー操作",diff --git a/packages/views/locales/ko/chat.json b/packages/views/locales/ko/chat.jsonindex ab173202e9..b7c1da1976 100644--- a/packages/views/locales/ko/chat.json+++ b/packages/views/locales/ko/chat.json@@ -52,10 +52,10 @@"queue": {"title_other": "대기 중인 메시지 {{count}}개","clear": "모두 지우기",- "steer": "지시",- "steer_unavailable": "현재 답변이 시작되면 지시할 수 있습니다",+ "steer": "지금 보내기 (현재 응답 중지)",+ "steer_unavailable": "현재 응답이 시작되면 사용할 수 있습니다","steer_no_permission": "이 에이전트를 실행할 권한이 없습니다",- "steer_unavailable_toast": "현재는 지시할 수 없습니다. 대기열을 새로 고치는 중입니다.",+ "steer_unavailable_toast": "지금 보낼 수 없습니다. 대기열을 새로 고칩니다.","edit": "대기 중인 메시지 편집","remove": "대기열에서 삭제","more": "추가 대기열 작업",diff --git a/packages/views/locales/ru/chat.json b/packages/views/locales/ru/chat.jsonindex 22ad9f8f1a..0cfdf80070 100644--- a/packages/views/locales/ru/chat.json+++ b/packages/views/locales/ru/chat.json@@ -59,10 +59,10 @@"title_one": "{{count}} сообщение в очереди","title_other": "{{count}} сообщения в очереди","clear": "Очистить всё",- "steer": "Скорректировать",- "steer_unavailable": "Коррекция станет доступна после начала текущего ответа",+ "steer": "Отправить сейчас (остановит ответ)",+ "steer_unavailable": "Доступно после начала текущего ответа","steer_no_permission": "У вас больше нет прав на запуск этого агента",- "steer_unavailable_toast": "Коррекция недоступна. Обновляем очередь.",+ "steer_unavailable_toast": "Отправка сейчас недоступна. Обновляем очередь.","edit": "Изменить сообщение в очереди","remove": "Удалить сообщение из очереди","more": "Другие действия с очередью",diff --git a/packages/views/locales/zh-Hans/chat.json b/packages/views/locales/zh-Hans/chat.jsonindex f7dc5536f3..c6313ad6ab 100644--- a/packages/views/locales/zh-Hans/chat.json+++ b/packages/views/locales/zh-Hans/chat.json@@ -52,10 +52,10 @@"queue": {"title_other": "{{count}} 条排队消息","clear": "全部清空",- "steer": "引导",- "steer_unavailable": "当前回复开始后才能引导",+ "steer": "立即发送(停止当前回复)",+ "steer_unavailable": "当前回复开始后可立即发送","steer_no_permission": "你已没有运行该智能体的权限",- "steer_unavailable_toast": "暂时无法引导,正在刷新队列。",+ "steer_unavailable_toast": "暂时无法立即发送,正在刷新队列。","edit": "编辑排队消息","remove": "移除排队消息","more": "更多队列操作",diff --git a/packages/views/locales/zh-Hant/chat.json b/packages/views/locales/zh-Hant/chat.jsonindex 5a85e46c46..11bcc1cd9b 100644--- a/packages/views/locales/zh-Hant/chat.json+++ b/packages/views/locales/zh-Hant/chat.json@@ -52,10 +52,10 @@"queue": {"title_other": "{{count}} 條排隊訊息","clear": "全部清空",- "steer": "引導",- "steer_unavailable": "當前回覆開始後才能引導",+ "steer": "立即傳送(停止目前回覆)",+ "steer_unavailable": "目前回覆開始後可立即傳送","steer_no_permission": "你已沒有執行該 AI 代理的權限",- "steer_unavailable_toast": "暫時無法引導,正在重新整理佇列。",+ "steer_unavailable_toast": "暫時無法立即傳送,正在重新整理佇列。","edit": "編輯排隊訊息","remove": "移除排隊訊息","more": "更多佇列操作",diff --git a/server/cmd/migrate/main.go b/server/cmd/migrate/main.goindex c34c6f66c6..b93a5a1ed8 100644--- a/server/cmd/migrate/main.go+++ b/server/cmd/migrate/main.go@@ -140,6 +140,9 @@ var pgBigmOperatorClass = extensionOperatorClass{// they are still pending: a fresh self-hosted install, which is exactly where an// interrupted build would otherwise leave a permanently unusable index.var concurrentIndexCleanups = map[string]string{+ "662_chat_task_supplement_message": "uq_chat_task_supplement_message",+ "663_chat_task_supplement_task": "idx_chat_task_supplement_task",+ "664_chat_task_supplement_workspace": "idx_chat_task_supplement_workspace","654_chat_submission_receipt_key": "uq_chat_submission_receipt_key","655_chat_submission_receipt_workspace": "idx_chat_submission_receipt_workspace","651_task_context_receipt_issue_idx": "idx_task_context_receipt_issue",diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex 6e7bffa769..41f759267b 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -8919,7 +8919,7 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot itaskCapabilities = append(taskCapabilities, protocol.DaemonCapabilityMuseAppProcessCleanupV1)}var cursorHookCommand []string- supplementSupported := agent.SupportsTaskSupplement(provider, resolvedVersion) && task.IssueID != ""+ supplementSupported := agent.SupportsTaskSupplement(provider, resolvedVersion) && (task.IssueID != "" || task.ChatSessionID != "")if supplementSupported && provider == "cursor" {cursorHookCommand, supplementSupported = cursorSupplementHookCommand(env)}diff --git a/server/internal/daemon/prompt.go b/server/internal/daemon/prompt.goindex 2ab604043a..8f89891348 100644--- a/server/internal/daemon/prompt.go+++ b/server/internal/daemon/prompt.go@@ -867,7 +867,11 @@ func buildChatPrompt(task Task) string {}}}- fmt.Fprintf(&b, "User message:\n%s\n", task.ChatMessage)+ message := task.ChatMessage+ if task.PriorSessionID != "" && task.ChatResumeMessage != nil {+ message = *task.ChatResumeMessage+ }+ fmt.Fprintf(&b, "User message:\n%s\n", message)// List attachments by id + filename so the agent can fetch them via// the CLI. We deliberately do NOT inline the URL: chat attachments// live behind a signed CDN with a short TTL, so by the time the agentdiff --git a/server/internal/daemon/task_supplement_test.go b/server/internal/daemon/task_supplement_test.goindex 4f6e68a8f5..09440f206f 100644--- a/server/internal/daemon/task_supplement_test.go+++ b/server/internal/daemon/task_supplement_test.go@@ -214,3 +214,21 @@ func TestClaimTaskSupplementAdvertisesAuthorRendering(t *testing.T) {t.Fatalf("claim = %+v", supplement)}}++func TestChatSupplementRetryPromptUsesResumeInputOnlyWithPriorSession(t *testing.T) {+ resume := "original objective\n\npending guidance"+ task := Task{ChatSessionID: "chat", PriorSessionID: "provider-session", ChatMessage: resume + "\n\ndelivered guidance", ChatResumeMessage: &resume}+ if prompt := buildChatPrompt(task); strings.Contains(prompt, "delivered guidance") || !strings.Contains(prompt, "pending guidance") {+ t.Fatalf("resume prompt: %s", prompt)+ }+ // The same task can fall back to a fresh provider session inside the daemon.+ task.PriorSessionID = ""+ if prompt := buildChatPrompt(task); !strings.Contains(prompt, "delivered guidance") {+ t.Fatal("cold retry dropped guidance")+ }+ // A server without the optional field continues using its full input.+ task.PriorSessionID, task.ChatResumeMessage = "provider-session", nil+ if prompt := buildChatPrompt(task); !strings.Contains(prompt, "delivered guidance") {+ t.Fatal("legacy payload lost input")+ }+}diff --git a/server/internal/daemon/types.go b/server/internal/daemon/types.goindex 65c66b224c..6eb4447f36 100644--- a/server/internal/daemon/types.go+++ b/server/internal/daemon/types.go@@ -145,6 +145,7 @@ type Task struct {ChatType string `json:"chat_type,omitempty"` // "group" when the channel conversation is a shared room, "p2p" for a 1:1 with the bot. Empty for a web chat or an old server; the per-turn prompt then reports unknown rather than guessing 1:1ChatInThread bool `json:"chat_in_thread,omitempty"` // true when the latest @mention was a thread reply; selects which read command the prompt tells the agent to start withChatMessage string `json:"chat_message,omitempty"` // user message content for chat tasks+ ChatResumeMessage *string `json:"chat_resume_message,omitempty"` // input excluding guidance already in PriorSessionIDChatMessageAttachments []ChatAttachmentMeta `json:"chat_message_attachments,omitempty"` // attachments linked to the chat message; agent uses these to `multica attachment download <id>`ChatIntro bool `json:"chat_intro,omitempty"` // legacy compatibility for historical is_agent_intro sessions; new agent creation no longer creates these chatsRegenerateQuickActionsFor string `json:"regenerate_quick_actions_for,omitempty"` // set only by servers predating server-side quick-actions generation (MUL-5573). Read as a REFUSAL marker, never executed: see the guard in runTaskdiff --git a/server/internal/handler/agent.go b/server/internal/handler/agent.goindex 066b36509e..cf6b893330 100644--- a/server/internal/handler/agent.go+++ b/server/internal/handler/agent.go@@ -563,6 +563,7 @@ type AgentTaskResponse struct {ChatSource *protocol.ChatSource `json:"chat_source,omitempty"`ChatInThread bool `json:"chat_in_thread,omitempty"` // true when the latest @mention was a thread reply; tells the agent to start with `multica chat thread` vs `multica chat history`ChatMessage string `json:"chat_message,omitempty"` // user message for chat tasks+ ChatResumeMessage *string `json:"chat_resume_message,omitempty"` // excludes guidance already delivered to the resumed sessionChatMessageAttachments []ChatAttachmentMeta `json:"chat_message_attachments,omitempty"` // attachments on the user message — agent calls `multica attachment download <id>` per entryChatIntro bool `json:"chat_intro,omitempty"` // legacy compatibility for historical is_agent_intro sessions; new agent creation no longer creates these chatsAutopilotRunID string `json:"autopilot_run_id,omitempty"` // non-empty for autopilot-spawned tasksdiff --git a/server/internal/handler/chat.go b/server/internal/handler/chat.goindex 544902a29c..f954f45355 100644--- a/server/internal/handler/chat.go+++ b/server/internal/handler/chat.go@@ -729,6 +729,14 @@ func (h *Handler) DeleteChatSession(w http.ResponseWriter, r *http.Request) {return}+ if err := qtx.DeleteChatTaskSupplementsBySession(r.Context(), session.ID); err != nil {+ writeError(w, http.StatusInternalServerError, "failed to delete chat supplements")+ return+ }+ if err := qtx.DeleteChatSupplementCapabilitiesBySession(r.Context(), session.ID); err != nil {+ writeError(w, http.StatusInternalServerError, "failed to delete chat supplement capabilities")+ return+ }cancelled, err := qtx.CancelAgentTasksByChatSession(r.Context(), session.ID)if err != nil {writeError(w, http.StatusInternalServerError, "failed to cancel chat session tasks")@@ -822,6 +830,7 @@ func (h *Handler) DeleteChatSession(w http.ResponseWriter, r *http.Request) {// Chat Messagestype SendChatMessageRequest struct {+ Steer bool `json:"steer"`SubmissionID *string `json:"submission_id"`Content string `json:"content"`AttachmentIDs []string `json:"attachment_ids"`@@ -883,7 +892,7 @@ func (h *Handler) SendChatMessage(w http.ResponseWriter, r *http.Request) {h.writeDispatchBlocked(w, http.StatusForbidden, ReasonInvocationNotAllowed)return}- response, err := h.TaskService.LookupDirectChatSubmission(r.Context(), session, parseUUID(userID), req.Content, attachmentIDs, actorType, parseUUID(actorID), submissionID)+ response, err := h.TaskService.LookupDirectChatSubmission(r.Context(), session, parseUUID(userID), req.Content, attachmentIDs, actorType, parseUUID(actorID), submissionID, req.Steer)if err != nil {h.writeChatSubmissionError(w, err)return@@ -979,9 +988,9 @@ func (h *Handler) SendChatMessage(w http.ResponseWriter, r *http.Request) {// resolved above for the invoke gate.var sent *service.DirectChatSendResultif submissionID.Valid {- sent, err = h.TaskService.SendDirectChatMessageWithSubmission(r.Context(), session, agent, parseUUID(userID), req.Content, attachmentIDs, actorType, parseUUID(actorID), submissionID)+ sent, err = h.TaskService.SendDirectChatMessageWithSubmission(r.Context(), session, agent, parseUUID(userID), req.Content, attachmentIDs, actorType, parseUUID(actorID), submissionID, req.Steer)} else {- sent, err = h.TaskService.SendDirectChatMessage(r.Context(), session, agent, parseUUID(userID), req.Content, attachmentIDs, actorType, parseUUID(actorID))+ sent, err = h.TaskService.SendDirectChatMessage(r.Context(), session, agent, parseUUID(userID), req.Content, attachmentIDs, actorType, parseUUID(actorID), req.Steer)}if err != nil {switch {@@ -1007,6 +1016,9 @@ func (h *Handler) SendChatMessage(w http.ResponseWriter, r *http.Request) {}msg := sent.Messagetask := sent.Task+ if sent.Steered {+ h.notifyTaskSupplementAvailable(task)+ }currentTitle := session.Titleif sent.InitialTitle != "" {currentTitle = sent.InitialTitle@@ -1043,7 +1055,7 @@ func (h *Handler) SendChatMessage(w http.ResponseWriter, r *http.Request) {MessageID: uuidToString(msg.ID),Role: "user",Content: req.Content,- TaskID: uuidToString(task.ID),+ TaskID: uuidToString(msg.TaskID),CreatedAt: timestampToString(msg.CreatedAt),})@@ -1059,12 +1071,15 @@ func (h *Handler) SendChatMessage(w http.ResponseWriter, r *http.Request) {}writeJSON(w, http.StatusCreated, SendChatMessageResponse{- MessageID: uuidToString(msg.ID),- TaskID: uuidToString(task.ID),- SupportsQueue: true,- Queued: sent.Queued,- CreatedAt: timestampToString(task.CreatedAt),- AttachmentIDs: boundAttachmentIDs,+ MessageID: uuidToString(msg.ID),+ TaskID: uuidToString(task.ID),+ SupportsQueue: true,+ Queued: sent.Queued,+ Steered: sent.Steered,+ MessageTaskID: uuidToString(msg.TaskID),+ MessageCreatedAt: timestampToString(msg.CreatedAt),+ CreatedAt: timestampToString(task.CreatedAt),+ AttachmentIDs: boundAttachmentIDs,})}diff --git a/server/internal/handler/chat_supplement_test.go b/server/internal/handler/chat_supplement_test.gonew file mode 100644index 0000000000..8262303f85--- /dev/null+++ b/server/internal/handler/chat_supplement_test.go@@ -0,0 +1,561 @@+package handler++import (+ "net/http"+ "strings"+ "testing"++ "github.com/google/uuid"+ "github.com/multica-ai/multica/server/internal/service"+ "github.com/multica-ai/multica/server/internal/testutil"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++func newChatSupplementFixture(t *testing.T, negotiated bool) (string, string, string) {+ t.Helper()+ if testHandler == nil {+ t.Skip("database not available")+ }+ runtimeID := dbfx.Runtime(t, "chat-steering", testutil.Cols{"provider": "codex"})+ agentID := dbfx.Agent(t, "Chat steering "+uuid.NewString(), runtimeID)+ sessionID := dbfx.ChatSession(t, agentID)+ taskID := dbfx.Task(t, agentID, testutil.Cols{"runtime_id": runtimeID, "chat_session_id": sessionID, "issue_id": nil, "status": "dispatched"})+ dbfx.Exec(t, `UPDATE agent_task_queue SET chat_input_task_id=id WHERE id=$1`, taskID)+ dbfx.Insert(t, "chat_message", testutil.Cols{"chat_session_id": sessionID, "task_id": taskID, "role": "user", "content": "original objective"})+ if _, err := testHandler.TaskService.StartTask(t.Context(), parseUUID(taskID), service.TaskStartCapabilities{Supplement: negotiated}); err != nil {+ t.Fatal(err)+ }+ dbfx.Cleanup(t, `DELETE FROM chat_task_supplement WHERE chat_session_id=$1`, sessionID)+ dbfx.Cleanup(t, `DELETE FROM task_supplement_capability WHERE task_id=$1`, taskID)+ dbfx.Cleanup(t, `DELETE FROM agent_task_queue WHERE chat_session_id=$1 AND id<>$2`, sessionID, taskID)+ dbfx.Cleanup(t, `DELETE FROM task_supplement_capability WHERE task_id IN (SELECT id FROM agent_task_queue WHERE chat_session_id=$1)`, sessionID)+ return sessionID, taskID, agentID+}++func sendChatGuidance(t *testing.T, sessionID string, body map[string]any) SendChatMessageResponse {+ t.Helper()+ var response SendChatMessageResponse+ req := withURLParam(withChatTestWorkspaceCtx(t, newRequest(http.MethodPost, "/messages", body)), "sessionId", sessionID)+ testutil.Call(t, testHandler.SendChatMessage, req).Want(http.StatusCreated).JSON(&response)+ return response+}++func TestChatSupplementSendClaimAck(t *testing.T) {+ sessionID, taskID, _ := newChatSupplementFixture(t, true)+ key := uuid.NewString()+ body := map[string]any{"steer": true, "content": "use the new location", "submission_id": key}+ sent := sendChatGuidance(t, sessionID, body)+ replay := sendChatGuidance(t, sessionID, body)+ if !sent.Steered || sent.Queued || sent.TaskID != taskID || replay.MessageID != sent.MessageID {+ t.Fatalf("send=%+v replay=%+v", sent, replay)+ }+ if n := dbfx.Count(t, `SELECT count(*) FROM agent_task_queue WHERE chat_session_id=$1`, sessionID); n != 1 {+ t.Fatalf("steering created another run: %d", n)+ }+ var claim struct{ CommentID, Content string }+ // JSON wire names are intentionally shared with issue supplement delivery.+ var wire map[string]any+ req := withURLParam(newOwnerDaemonRequest(http.MethodPost, "/claim", nil), "taskId", taskID)+ testutil.Call(t, testHandler.ClaimTaskSupplement, req).Want(http.StatusOK).JSON(&wire)+ claim.CommentID, _ = wire["comment_id"].(string)+ claim.Content, _ = wire["content"].(string)+ if claim.CommentID != sent.MessageID || claim.Content != body["content"] || wire["author_type"] != "member" {+ t.Fatalf("wrong guidance: %+v", wire)+ }+ for range 2 {+ req = withURLParams(newOwnerDaemonRequest(http.MethodPost, "/ack", map[string]any{"delivered": true}), "taskId", taskID, "commentId", sent.MessageID)+ testutil.Call(t, testHandler.AckTaskSupplement, req).Want(http.StatusOK)+ }+ if w := completeTaskViaHandler(t, taskID, "updated reply"); w.Code != http.StatusOK {+ t.Fatalf("completion: %s", w.Body.String())+ }+ if n := dbfx.Count(t, `SELECT count(*) FROM agent_task_queue WHERE chat_session_id=$1`, sessionID); n != 1 {+ t.Fatal("delivered guidance ran twice")+ }+}++func TestChatSupplementFallbacks(t *testing.T) {+ for _, reason := range []string{"completed", "failed", "cancelled", "provider_rejected"} {+ t.Run(reason, func(t *testing.T) {+ sessionID, taskID, _ := newChatSupplementFixture(t, true)+ sent := sendChatGuidance(t, sessionID, map[string]any{"steer": true, "content": "never lose this"})+ if !sent.Steered {+ t.Fatal("not steered")+ }+ if reason == "provider_rejected" {+ if _, err := testHandler.Queries.ClaimNextChatTaskSupplement(t.Context(), parseUUID(taskID)); err != nil {+ t.Fatal(err)+ }+ req := withURLParams(newOwnerDaemonRequest(http.MethodPost, "/ack", map[string]any{"delivered": false}), "taskId", taskID, "commentId", sent.MessageID)+ testutil.Call(t, testHandler.AckTaskSupplement, req).Want(http.StatusOK)+ req = withURLParams(newOwnerDaemonRequest(http.MethodPost, "/ack", map[string]any{"delivered": false}), "taskId", taskID, "commentId", sent.MessageID)+ testutil.Call(t, testHandler.AckTaskSupplement, req).Want(http.StatusOK)+ } else {+ tx, err := testPool.Begin(t.Context())+ if err != nil {+ t.Fatal(err)+ }+ defer tx.Rollback(t.Context())+ q := testHandler.Queries.WithTx(tx)+ if _, err := tx.Exec(t.Context(), `UPDATE agent_task_queue SET status=$2 WHERE id=$1`, taskID, reason); err != nil {+ t.Fatal(err)+ }+ task, err := q.GetAgentTask(t.Context(), parseUUID(taskID))+ if err != nil {+ t.Fatal(err)+ }+ for range 2 {+ if err := service.SettleTerminalTaskState(t.Context(), q, task); err != nil {+ t.Fatal(err)+ }+ }+ if err := tx.Commit(t.Context()); err != nil {+ t.Fatal(err)+ }+ }+ var owner, status string+ if err := testPool.QueryRow(t.Context(), `SELECT m.task_id::text, t.status FROM chat_message m JOIN agent_task_queue t ON t.id=m.task_id WHERE m.id=$1`, sent.MessageID).Scan(&owner, &status); err != nil {+ t.Fatal(err)+ }+ if owner == taskID || status != "queued" {+ t.Fatalf("fallback owner=%s status=%s", owner, status)+ }+ inputs, err := testHandler.Queries.ListChatInputMessages(t.Context(), parseUUID(owner))+ if err != nil || len(inputs) != 1 || inputs[0].Content != "never lose this" {+ t.Fatalf("fallback input=%+v err=%v", inputs, err)+ }+ if n := dbfx.Count(t, `SELECT count(*) FROM agent_task_queue WHERE chat_session_id=$1`, sessionID); n != 2 {+ t.Fatalf("fallback created %d tasks", n)+ }+ })+ }+}++func TestChatSupplementQueueChoiceAndOldDaemon(t *testing.T) {+ for _, negotiated := range []bool{false, true} {+ sessionID, taskID, _ := newChatSupplementFixture(t, negotiated)+ sent := sendChatGuidance(t, sessionID, map[string]any{"content": "next turn", "steer": !negotiated})+ if sent.Steered || !sent.Queued || sent.TaskID == taskID {+ t.Fatalf("queue fallback: %+v", sent)+ }+ }+}++func TestChatSupplementLegacySendRemainsQueued(t *testing.T) {+ sessionID, taskID, _ := newChatSupplementFixture(t, true)+ sent := sendChatGuidance(t, sessionID, map[string]any{"content": "legacy queued message"})+ if sent.Steered || !sent.Queued || sent.TaskID == taskID {+ t.Fatalf("legacy send changed into guidance: %+v", sent)+ }+}++func TestChatSupplementTerminalFallbackBroadcastsQueued(t *testing.T) {+ for _, terminal := range []string{"completed", "failed", "cancelled"} {+ t.Run(terminal, func(t *testing.T) {+ sessionID, taskID, _ := newChatSupplementFixture(t, true)+ sent := sendChatGuidance(t, sessionID, map[string]any{"steer": true, "content": "next turn"})+ queued := subscribeChatTaskQueued(t, sessionID)+ switch terminal {+ case "completed":+ if w := completeTaskViaHandler(t, taskID, "done"); w.Code != http.StatusOK {+ t.Fatal(w.Body.String())+ }+ case "failed":+ if _, err := testHandler.TaskService.FailTask(t.Context(), parseUUID(taskID), "failed", "", "", "", "agent_error", false, "", ""); err != nil {+ t.Fatal(err)+ }+ case "cancelled":+ if _, err := testHandler.TaskService.CancelTask(t.Context(), parseUUID(taskID)); err != nil {+ t.Fatal(err)+ }+ }+ var owner string+ dbfx.QueryRow(t, `SELECT task_id::text FROM chat_message WHERE id=$1`, sent.MessageID).Scan(&owner)+ select {+ case id := <-queued:+ if id != owner {+ t.Fatalf("queued %s, want %s", id, owner)+ }+ default:+ t.Fatal("terminal fallback did not broadcast task:queued")+ }+ })+ }+}++func TestChatSupplementStopWaitsForDeliveryResult(t *testing.T) {+ for _, delivered := range []bool{false, true} {+ t.Run(map[bool]string{true: "delivered", false: "rejected"}[delivered], func(t *testing.T) {+ sessionID, taskID, _ := newChatSupplementFixture(t, true)+ first := sendChatGuidance(t, sessionID, map[string]any{"steer": true, "content": "first guidance"})+ if _, err := testHandler.Queries.ClaimNextChatTaskSupplement(t.Context(), parseUUID(taskID)); err != nil {+ t.Fatal(err)+ }+ sendChatGuidance(t, sessionID, map[string]any{"steer": true, "content": "second guidance"})+ queued := subscribeChatTaskQueued(t, sessionID)+ if _, err := testHandler.TaskService.CancelTask(t.Context(), parseUUID(taskID)); err != nil {+ t.Fatal(err)+ }+ if n := dbfx.Count(t, `SELECT count(*) FROM agent_task_queue WHERE chat_session_id=$1 AND status='queued'`, sessionID); n != 0 {+ t.Fatal("Stop requeued guidance before its delivery result")+ }+ for range 2 {+ req := withURLParams(newOwnerDaemonRequest(http.MethodPost, "/ack", map[string]any{"delivered": delivered}), "taskId", taskID, "commentId", first.MessageID)+ testutil.Call(t, testHandler.AckTaskSupplement, req).Want(http.StatusOK)+ }+ for range 2 {+ req := withURLParam(newOwnerDaemonRequest(http.MethodPost, "/cancel-ack", nil), "taskId", taskID)+ testutil.Call(t, testHandler.AckTaskCancelled, req).Want(http.StatusOK)+ }+ want := 1+ if !delivered {+ want+++ }+ if n := dbfx.Count(t, `SELECT count(*) FROM agent_task_queue WHERE chat_session_id=$1 AND status='queued'`, sessionID); n != want {+ t.Fatalf("queued %d turns, want %d", n, want)+ }+ if n := len(queued); n != want {+ t.Fatalf("queued events=%d, want %d", n, want)+ }+ if n := dbfx.Count(t, `SELECT count(*) FROM chat_message WHERE task_id=$1 AND role='assistant'`, taskID); n > 1 {+ t.Fatal("Stop wrote duplicate outcomes")+ }+ })+ }+}++func TestChatSupplementStopGraceRequeuesUnconfirmedGuidance(t *testing.T) {+ sessionID, taskID, _ := newChatSupplementFixture(t, true)+ sendChatGuidance(t, sessionID, map[string]any{"steer": true, "content": "delivery unconfirmed"})+ if _, err := testHandler.Queries.ClaimNextChatTaskSupplement(t.Context(), parseUUID(taskID)); err != nil {+ t.Fatal(err)+ }+ if _, err := testHandler.TaskService.CancelTask(t.Context(), parseUUID(taskID)); err != nil {+ t.Fatal(err)+ }+ // The existing sweeper invokes this finalizer when the daemon never acks.+ if !testHandler.TaskService.FinalizeDeferredCancelledChat(t.Context(), parseUUID(taskID)) {+ t.Fatal("unconfirmed guidance was stranded")+ }+ if testHandler.TaskService.FinalizeDeferredCancelledChat(t.Context(), parseUUID(taskID)) {+ t.Fatal("duplicate finalize changed state")+ }+ if n := dbfx.Count(t, `SELECT count(*) FROM agent_task_queue WHERE chat_session_id=$1 AND status='queued'`, sessionID); n != 1 {+ t.Fatalf("fallback created %d turns", n)+ }+}++func TestChatSupplementStopWithTranscriptSettlesDeliveryWithoutDuplicateOutcome(t *testing.T) {+ sessionID, taskID, _ := newChatSupplementFixture(t, true)+ sent := sendChatGuidance(t, sessionID, map[string]any{"steer": true, "content": "already injected"})+ if _, err := testHandler.Queries.ClaimNextChatTaskSupplement(t.Context(), parseUUID(taskID)); err != nil {+ t.Fatal(err)+ }+ dbfx.Exec(t, `INSERT INTO task_message (task_id,seq,type,content) VALUES ($1,1,'assistant','working')`, taskID)+ if _, err := testHandler.TaskService.CancelTaskWithResult(t.Context(), parseUUID(taskID), service.CancelTaskOptions{}); err != nil {+ t.Fatal(err)+ }+ req := withURLParams(newOwnerDaemonRequest(http.MethodPost, "/ack", map[string]any{"delivered": true}), "taskId", taskID, "commentId", sent.MessageID)+ testutil.Call(t, testHandler.AckTaskSupplement, req).Want(http.StatusOK)+ testHandler.TaskService.FinalizeDeferredCancelledChat(t.Context(), parseUUID(taskID))+ if n := dbfx.Count(t, `SELECT count(*) FROM chat_message WHERE task_id=$1 AND role='assistant'`, taskID); n != 1 {+ t.Fatalf("Stop outcomes=%d", n)+ }+ if n := dbfx.Count(t, `SELECT count(*) FROM agent_task_queue WHERE chat_session_id=$1`, sessionID); n != 1 {+ t.Fatal("acknowledged guidance ran again")+ }+}++func TestChatSupplementAccessRevocationWithdrawsGuidance(t *testing.T) {+ sessionID, taskID, _ := newChatSupplementFixture(t, true)+ sendChatGuidance(t, sessionID, map[string]any{"steer": true, "content": "in flight"})+ if _, err := testHandler.Queries.ClaimNextChatTaskSupplement(t.Context(), parseUUID(taskID)); err != nil {+ t.Fatal(err)+ }+ sendChatGuidance(t, sessionID, map[string]any{"steer": true, "content": "pending"})+ tx, err := testPool.Begin(t.Context())+ if err != nil {+ t.Fatal(err)+ }+ defer tx.Rollback(t.Context())+ q := testHandler.Queries.WithTx(tx)+ if _, err := q.LockChatSessionForTask(t.Context(), parseUUID(taskID)); err != nil {+ t.Fatal(err)+ }+ task, err := q.CancelAgentTask(t.Context(), parseUUID(taskID))+ if err != nil {+ t.Fatal(err)+ }+ if _, err := service.PrepareRuntimeAccessCancellation(t.Context(), q, []db.AgentTaskQueue{task}); err != nil {+ t.Fatal(err)+ }+ if err := tx.Commit(t.Context()); err != nil {+ t.Fatal(err)+ }+ testHandler.TaskService.FinalizeDeferredCancelledChat(t.Context(), task.ID)+ if n := dbfx.Count(t, `SELECT count(*) FROM agent_task_queue WHERE chat_session_id=$1`, sessionID); n != 1 {+ t.Fatal("revocation started more work")+ }+ if n := dbfx.Count(t, `SELECT count(*) FROM chat_task_supplement WHERE task_id=$1 AND status='withdrawn'`, taskID); n != 2 {+ t.Fatal("revocation left guidance deliverable")+ }+}++func TestChatSupplementRetryClaimKeepsColdInputAndOmitsResumedGuidance(t *testing.T) {+ for _, sameSession := range []bool{true, false} {+ t.Run(map[bool]string{true: "same provider session", false: "different provider session"}[sameSession], func(t *testing.T) {+ sessionID, taskID, _ := newChatSupplementFixture(t, true)+ sent := sendChatGuidance(t, sessionID, map[string]any{"steer": true, "content": "delivered guidance"})+ if _, err := testHandler.Queries.ClaimNextChatTaskSupplement(t.Context(), parseUUID(taskID)); err != nil {+ t.Fatal(err)+ }+ req := withURLParams(newOwnerDaemonRequest(http.MethodPost, "/ack", map[string]any{"delivered": true}), "taskId", taskID, "commentId", sent.MessageID)+ testutil.Call(t, testHandler.AckTaskSupplement, req).Want(http.StatusOK)+ sendChatGuidance(t, sessionID, map[string]any{"steer": true, "content": "pending guidance"})+ if _, err := testHandler.TaskService.FailTask(t.Context(), parseUUID(taskID), "connection reset", "provider-session", "/work", "", "agent_error.provider_network", false, "", ""); err != nil {+ t.Fatal(err)+ }+ if !sameSession {+ dbfx.Exec(t, `UPDATE chat_session SET session_id='other-session' WHERE id=$1`, sessionID)+ }+ var childID string+ dbfx.QueryRow(t, `SELECT id::text FROM agent_task_queue WHERE parent_task_id=$1`, taskID).Scan(&childID)+ child, err := testHandler.Queries.GetAgentTask(t.Context(), parseUUID(childID))+ if err != nil {+ t.Fatal(err)+ }+ runtime, err := testHandler.Queries.GetAgentRuntime(t.Context(), child.RuntimeID)+ if err != nil {+ t.Fatal(err)+ }+ resp, _, _, _, _, failure := testHandler.buildClaimedTaskResponse(newOwnerDaemonRequest(http.MethodPost, "/claim", nil), &child, runtime, uuidToString(child.RuntimeID), uuidToString(runtime.WorkspaceID))+ if failure != nil {+ t.Fatalf("claim failed: %+v", failure)+ }+ if !strings.Contains(resp.ChatMessage, "delivered guidance") || !strings.Contains(resp.ChatMessage, "pending guidance") {+ t.Fatalf("cold input lost guidance: %s", resp.ChatMessage)+ }+ if sameSession {+ if resp.ChatResumeMessage == nil || *resp.ChatResumeMessage != "original objective\n\npending guidance" {+ t.Fatalf("resumed input: %+v", resp.ChatResumeMessage)+ }+ } else if resp.ChatResumeMessage != nil {+ t.Fatal("omitted guidance from a different provider session")+ }+ })+ }+}++func TestChatSupplementRetryKeepsInputAndOrder(t *testing.T) {+ for _, onRetry := range []bool{false, true} {+ for _, delivered := range []bool{false, true} {+ name := map[bool]string{false: "root", true: "retry"}[onRetry] + "/" + map[bool]string{false: "pending", true: "delivered"}[delivered]+ t.Run(name, func(t *testing.T) {+ sessionID, rootID, _ := newChatSupplementFixture(t, true)+ activeID := rootID+ fail := func(taskID string) db.AgentTaskQueue {+ t.Helper()+ if _, err := testHandler.TaskService.FailTask(t.Context(), parseUUID(taskID), "connection reset", "", "", "", "agent_error.provider_network", false, "", ""); err != nil {+ t.Fatal(err)+ }+ var childID string+ if err := testPool.QueryRow(t.Context(), `SELECT id::text FROM agent_task_queue WHERE parent_task_id=$1`, taskID).Scan(&childID); err != nil {+ t.Fatal(err)+ }+ child, err := testHandler.Queries.GetAgentTask(t.Context(), parseUUID(childID))+ if err != nil {+ t.Fatal(err)+ }+ return child+ }+ if onRetry {+ child := fail(rootID)+ activeID = uuidToString(child.ID)+ dbfx.Exec(t, `UPDATE agent_task_queue SET status='dispatched' WHERE id=$1`, activeID)+ if _, err := testHandler.TaskService.StartTask(t.Context(), child.ID, service.TaskStartCapabilities{Supplement: true}); err != nil {+ t.Fatal(err)+ }+ }+ sent := sendChatGuidance(t, sessionID, map[string]any{"steer": true, "content": "keep guidance after the original objective"})+ if sent.TaskID != activeID || sent.MessageTaskID != rootID || !sent.Steered {+ t.Fatalf("send: %+v", sent)+ }+ if delivered {+ if _, err := testHandler.Queries.ClaimNextChatTaskSupplement(t.Context(), parseUUID(activeID)); err != nil {+ t.Fatal(err)+ }+ req := withURLParams(newOwnerDaemonRequest(http.MethodPost, "/ack", map[string]any{"delivered": true}), "taskId", activeID, "commentId", sent.MessageID)+ testutil.Call(t, testHandler.AckTaskSupplement, req).Want(http.StatusOK)+ }+ child := fail(activeID)+ if child.ChatInputTaskID != parseUUID(rootID) {+ t.Fatal("retry lost its root input owner")+ }+ if onRetry && child.Status != "deferred" {+ t.Fatalf("last network retry should retain its backoff: %s", child.Status)+ }+ inputs, err := testHandler.Queries.ListChatInputMessages(t.Context(), child.ChatInputTaskID)+ if err != nil || len(inputs) != 2 || inputs[0].Content != "original objective" || inputs[1].Content != "keep guidance after the original objective" {+ t.Fatalf("retry input order/content: %+v, %v", inputs, err)+ }+ wantTasks := 2+ if onRetry {+ wantTasks+++ }+ if n := dbfx.Count(t, `SELECT count(*) FROM agent_task_queue WHERE chat_session_id=$1`, sessionID); n != wantTasks {+ t.Fatalf("guidance created its own run ahead of retry: %d tasks, want %d", n, wantTasks)+ }+ })+ }+ }+}++func TestChatSupplementExhaustedRetryQueuesGuidance(t *testing.T) {+ sessionID, taskID, _ := newChatSupplementFixture(t, true)+ dbfx.Exec(t, `UPDATE agent_task_queue SET attempt=3 WHERE id=$1`, taskID)+ sent := sendChatGuidance(t, sessionID, map[string]any{"steer": true, "content": "next turn after the failure"})+ if _, err := testHandler.TaskService.FailTask(t.Context(), parseUUID(taskID), "connection reset", "", "", "", "agent_error.provider_network", false, "", ""); err != nil {+ t.Fatal(err)+ }+ var nextID string+ if err := testPool.QueryRow(t.Context(), `SELECT task_id::text FROM chat_message WHERE id=$1`, sent.MessageID).Scan(&nextID); err != nil {+ t.Fatal(err)+ }+ if nextID == taskID {+ t.Fatal("exhausted retry stranded guidance on the failed task")+ }+ inputs, err := testHandler.Queries.ListChatInputMessages(t.Context(), parseUUID(nextID))+ if err != nil || len(inputs) != 1 || inputs[0].Content != "next turn after the failure" {+ t.Fatalf("fallback input=%+v err=%v", inputs, err)+ }+}++func TestChatSupplementSubmissionReplayPreservesSendMode(t *testing.T) {+ sessionID, _, _ := newChatSupplementFixture(t, true)+ key := uuid.NewString()+ sendChatGuidance(t, sessionID, map[string]any{"content": "queued", "submission_id": key})+ req := withURLParam(withChatTestWorkspaceCtx(t, newRequest(http.MethodPost, "/messages", map[string]any{"content": "queued", "submission_id": key, "steer": true})), "sessionId", sessionID)+ testutil.Call(t, testHandler.SendChatMessage, req).Want(http.StatusConflict)+}++func TestChatSupplementDaemonRecoveryRetainsRetryInput(t *testing.T) {+ sessionID, taskID, _ := newChatSupplementFixture(t, true)+ sendChatGuidance(t, sessionID, map[string]any{"steer": true, "content": "guidance before daemon restart"})+ task, err := testHandler.Queries.GetAgentTask(t.Context(), parseUUID(taskID))+ if err != nil {+ t.Fatal(err)+ }+ failed, err := testHandler.TaskService.RecoverOrphanedTasksForRuntime(t.Context(), task.RuntimeID)+ if err != nil {+ t.Fatal(err)+ }+ var recovered bool+ for _, parent := range failed {+ if parent.ID != task.ID {+ continue+ }+ child, err := testHandler.TaskService.MaybeRetryFailedTask(t.Context(), parent)+ if err != nil || child == nil {+ t.Fatalf("recovery retry=%+v err=%v", child, err)+ }+ inputs, err := testHandler.Queries.ListChatInputMessages(t.Context(), child.ChatInputTaskID)+ if err != nil || len(inputs) != 2 || inputs[0].Content != "original objective" || inputs[1].Content != "guidance before daemon restart" {+ t.Fatalf("recovery input=%+v err=%v", inputs, err)+ }+ recovered = true+ }+ if !recovered {+ t.Fatal("fixture task was not recovered")+ }+ if n := dbfx.Count(t, `SELECT count(*) FROM agent_task_queue WHERE chat_session_id=$1`, sessionID); n != 2 {+ t.Fatalf("guidance escaped the retry batch: %d tasks", n)+ }+}++func TestChatSupplementDeliveredGuidanceSurvivesDraftRestore(t *testing.T) {+ sessionID, taskID, _ := newChatSupplementFixture(t, true)+ sent := sendChatGuidance(t, sessionID, map[string]any{"steer": true, "content": "keep this guidance in history"})+ if _, err := testHandler.Queries.ClaimNextChatTaskSupplement(t.Context(), parseUUID(taskID)); err != nil {+ t.Fatal(err)+ }+ req := withURLParams(newOwnerDaemonRequest(http.MethodPost, "/ack", map[string]any{"delivered": true}), "taskId", taskID, "commentId", sent.MessageID)+ testutil.Call(t, testHandler.AckTaskSupplement, req).Want(http.StatusOK)+ restored, err := testHandler.Queries.DeleteUserChatMessageByTask(t.Context(), parseUUID(taskID))+ if err != nil || restored.Content != "original objective" {+ t.Fatalf("restored the wrong draft: %+v, %v", restored, err)+ }+ if n := dbfx.Count(t, `SELECT count(*) FROM chat_message WHERE id=$1`, sent.MessageID); n != 1 {+ t.Fatal("draft restore deleted delivered guidance")+ }+}++func TestChatSupplementBulkStopDoesNotStartNewWork(t *testing.T) {+ for _, archive := range []bool{false, true} {+ t.Run(map[bool]string{false: "stop all", true: "archive"}[archive], func(t *testing.T) {+ sessionID, _, agentID := newChatSupplementFixture(t, true)+ sent := sendChatGuidance(t, sessionID, map[string]any{"steer": true, "content": "withdraw with all work"})+ var err error+ if archive {+ _, err = testHandler.TaskService.CancelTasksForArchivedAgent(t.Context(), parseUUID(agentID))+ } else {+ _, err = testHandler.TaskService.CancelTasksForAgent(t.Context(), parseUUID(agentID))+ }+ if err != nil {+ t.Fatal(err)+ }+ if n := dbfx.Count(t, `SELECT count(*) FROM agent_task_queue WHERE chat_session_id=$1 AND status='queued'`, sessionID); n != 0 {+ t.Fatal("bulk stop created a new run")+ }+ if n := dbfx.Count(t, `SELECT count(*) FROM chat_task_supplement WHERE message_id=$1 AND status='withdrawn'`, sent.MessageID); n != 1 {+ t.Fatal("guidance was not withdrawn")+ }+ })+ }+}++func TestChatSupplementRuntimeTeardownDoesNotStartNewWork(t *testing.T) {+ sessionID, taskID, _ := newChatSupplementFixture(t, true)+ sent := sendChatGuidance(t, sessionID, map[string]any{"steer": true, "content": "withdraw with runtime"})+ task, err := testHandler.Queries.GetAgentTask(t.Context(), parseUUID(taskID))+ if err != nil {+ t.Fatal(err)+ }+ tx, err := testPool.Begin(t.Context())+ if err != nil {+ t.Fatal(err)+ }+ defer tx.Rollback(t.Context())+ if _, err := service.TeardownRuntime(t.Context(), testHandler.Queries.WithTx(tx), task.RuntimeID, service.RuntimeTeardownOptions{CancelNonTerminalTasks: true}); err != nil {+ t.Fatal(err)+ }+ if err := tx.Commit(t.Context()); err != nil {+ t.Fatal(err)+ }+ if n := dbfx.Count(t, `SELECT count(*) FROM agent_task_queue WHERE chat_session_id=$1 AND status='queued'`, sessionID); n != 0 {+ t.Fatal("runtime teardown created new work")+ }+ if n := dbfx.Count(t, `SELECT count(*) FROM chat_task_supplement WHERE message_id=$1 AND status='withdrawn'`, sent.MessageID); n != 1 {+ t.Fatal("runtime teardown left guidance pending")+ }+}++func TestChatSupplementPermissionAndSessionDeletion(t *testing.T) {+ sessionID, taskID, agentID := newChatSupplementFixture(t, true)+ sent := sendChatGuidance(t, sessionID, map[string]any{"steer": true, "content": "pending"})+ dbfx.Exec(t, `UPDATE agent_runtime SET visibility='public' WHERE id=(SELECT runtime_id FROM agent WHERE id=$1)`, agentID)+ dbfx.Exec(t, `UPDATE agent SET permission_mode='private', owner_id=$2 WHERE id=$1`, agentID, dbfx.User(t, "Other", "other-"+uuid.NewString()+"@test.local"))+ req := withURLParam(withChatTestWorkspaceCtx(t, newRequest(http.MethodPost, "/messages", map[string]any{"steer": true, "content": "forbidden"})), "sessionId", sessionID)+ testutil.Call(t, testHandler.SendChatMessage, req).Want(http.StatusForbidden)+ if n := dbfx.Count(t, `SELECT count(*) FROM chat_task_supplement WHERE task_id=$1`, taskID); n != 1 {+ t.Fatal("revoked send mutated receipts")+ }+ dbfx.Exec(t, `UPDATE agent SET owner_id=$2 WHERE id=$1`, agentID, testUserID)+ req = withURLParam(withChatTestWorkspaceCtx(t, newRequest(http.MethodDelete, "/session", nil)), "sessionId", sessionID)+ testutil.Call(t, testHandler.DeleteChatSession, req).Want(http.StatusNoContent)+ if n := dbfx.Count(t, `SELECT count(*) FROM chat_task_supplement WHERE message_id=$1`, sent.MessageID); n != 0 {+ t.Fatal("deleted session retained guidance")+ }+ if _, err := testHandler.Queries.GetTaskSupplementCapability(t.Context(), parseUUID(taskID)); err == nil {+ t.Fatal("deleted session retained capability")+ }+}diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.goindex 88cd442b7c..8069a27c16 100644--- a/server/internal/handler/daemon.go+++ b/server/internal/handler/daemon.go@@ -3915,6 +3915,33 @@ func (h *Handler) buildClaimedTaskResponse(r *http.Request, task *db.AgentTaskQu}}resp.ChatMessage = strings.Join(parts, "\n\n")+ if task.RetryOfTaskID.Valid && resp.PriorSessionID != "" {+ // Keep the full input for cold starts and the daemon's local fresh+ // retry. Only a positively identified provider session can omit+ // guidance whose injection it already acknowledged.+ rows, err := h.Queries.ListChatGuidanceInProviderSession(r.Context(), db.ListChatGuidanceInProviderSessionParams{+ WorkspaceID: cs.WorkspaceID, MessageIds: messageIDs,+ SessionID: pgtype.Text{String: resp.PriorSessionID, Valid: true}, RuntimeID: task.RuntimeID,+ })+ if err != nil {+ return resp, deliveredCommentIDs, issueSnapshot, agentSkillCount, builtinSkillCount,+ h.rejectClaimSourceLoad(r.Context(), task, err, "chat guidance receipts", uuidToString(task.ID))+ }+ if len(rows) > 0 {+ delivered := make(map[pgtype.UUID]bool, len(rows))+ for _, id := range rows {+ delivered[id] = true+ }+ resumeParts := make([]string, 0, len(unanswered))+ for _, m := range unanswered {+ if !delivered[m.ID] && strings.TrimSpace(m.Content) != "" {+ resumeParts = append(resumeParts, m.Content)+ }+ }+ resume := strings.Join(resumeParts, "\n\n")+ resp.ChatResumeMessage = &resume+ }+ }// Fail closed: a task-owned direct task that resolves to no user text// (and is not the agent's proactive intro) must never dispatch andiff --git a/server/internal/handler/task_supplement.go b/server/internal/handler/task_supplement.goindex b578802bc6..74cb9293aa 100644--- a/server/internal/handler/task_supplement.go+++ b/server/internal/handler/task_supplement.go@@ -12,6 +12,7 @@ import ("github.com/go-chi/chi/v5""github.com/jackc/pgx/v5""github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/service"db "github.com/multica-ai/multica/server/pkg/db/generated""github.com/multica-ai/multica/server/pkg/protocol")@@ -22,7 +23,7 @@ func (h *Handler) hydrateTaskSupplementMetadata(ctx context.Context, r *http.Req}taskIDs := make([]pgtype.UUID, 0, len(tasks))for i := range tasks {- if tasks[i].IssueID.Valid {+ if tasks[i].IssueID.Valid || tasks[i].ChatSessionID.Valid {taskIDs = append(taskIDs, tasks[i].ID)}}@@ -467,7 +468,20 @@ type ackTaskSupplementRequest struct {func (h *Handler) ClaimTaskSupplement(w http.ResponseWriter, r *http.Request) {taskID := chi.URLParam(r, "taskId")- if _, ok := h.requireDaemonTaskAccess(w, r, taskID); !ok {+ task, ok := h.requireDaemonTaskAccess(w, r, taskID)+ if !ok {+ return+ }+ if task.ChatSessionID.Valid && !task.IssueID.Valid {+ row, err := h.Queries.ClaimNextChatTaskSupplement(r.Context(), task.ID)+ if errors.Is(err, pgx.ErrNoRows) {+ writeJSON(w, http.StatusOK, map[string]any{})+ } else if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to claim chat guidance")+ } else {+ // Keep the daemon wire contract: this opaque id names a chat message.+ writeJSON(w, http.StatusOK, map[string]any{"comment_id": uuidToString(row.MessageID), "author_type": "member", "author_name": row.AuthorName, "content": row.Content})+ }return}var req struct {@@ -497,7 +511,8 @@ func (h *Handler) ClaimTaskSupplement(w http.ResponseWriter, r *http.Request) {func (h *Handler) AckTaskSupplement(w http.ResponseWriter, r *http.Request) {taskID := chi.URLParam(r, "taskId")- if _, ok := h.requireDaemonTaskAccess(w, r, taskID); !ok {+ task, ok := h.requireDaemonTaskAccess(w, r, taskID)+ if !ok {return}commentID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "commentId"), "comment id")@@ -509,6 +524,10 @@ func (h *Handler) AckTaskSupplement(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusBadRequest, "invalid request body")return}+ if task.ChatSessionID.Valid && !task.IssueID.Valid {+ h.ackChatTaskSupplement(w, r, task, commentID, req.Delivered)+ return+ }var row db.TaskSupplementvar err errorif req.Delivered {@@ -534,6 +553,47 @@ func (h *Handler) AckTaskSupplement(w http.ResponseWriter, r *http.Request) {writeJSON(w, http.StatusOK, supplementReceipt(row))}+func (h *Handler) ackChatTaskSupplement(w http.ResponseWriter, r *http.Request, task db.AgentTaskQueue, messageID pgtype.UUID, delivered bool) {+ tx, err := h.TxStarter.Begin(r.Context())+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to acknowledge chat guidance")+ return+ }+ defer tx.Rollback(r.Context())+ q := h.Queries.WithTx(tx)+ if _, err = q.LockChatSessionForTask(r.Context(), task.ID); err != nil {+ writeError(w, http.StatusConflict, "chat session has ended")+ return+ }+ if _, err = q.LockTaskForSupplementBind(r.Context(), task.ID); err != nil {+ writeError(w, http.StatusConflict, "chat turn has ended")+ return+ }+ var queued []db.AgentTaskQueue+ if delivered {+ _, err = q.AckChatTaskSupplement(r.Context(), db.AckChatTaskSupplementParams{TaskID: task.ID, MessageID: messageID})+ } else {+ queued, err = service.RequeueChatTaskSupplements(r.Context(), q, task, messageID)+ }+ if err != nil {+ if errors.Is(err, pgx.ErrNoRows) {+ writeError(w, http.StatusConflict, "chat guidance is no longer deliverable")+ } else {+ writeError(w, http.StatusInternalServerError, "failed to acknowledge chat guidance")+ }+ return+ }+ if err := tx.Commit(r.Context()); err != nil {+ writeError(w, http.StatusInternalServerError, "failed to acknowledge chat guidance")+ return+ }+ for _, next := range queued {+ h.TaskService.BroadcastTaskQueued(r.Context(), next)+ h.TaskService.NotifyTaskEnqueued(r.Context(), next)+ }+ writeJSON(w, http.StatusOK, map[string]any{})+}+func stableTaskSupplementFailureReason(reason string) string {reason = strings.TrimSpace(sanitizeNullBytes(reason))switch reason {diff --git a/server/internal/handler/workspace.go b/server/internal/handler/workspace.goindex ef23a82fb8..affc6752da 100644--- a/server/internal/handler/workspace.go+++ b/server/internal/handler/workspace.go@@ -1281,6 +1281,10 @@ func (h *Handler) DeleteWorkspace(w http.ResponseWriter, r *http.Request) {return qtx.PrepareSeatCapacityMemberReleasesForWorkspaceDeletion(ctx, requester.WorkspaceID)},},+ {+ name: "delete chat supplements",+ run: func() error { return qtx.DeleteChatTaskSupplementsByWorkspace(ctx, requester.WorkspaceID) },+ },{name: "delete chat pins",run: func() error { return qtx.DeleteChatPinnedAgentsByWorkspace(ctx, requester.WorkspaceID) },diff --git a/server/internal/handler/workspace_delete_manifest_test.go b/server/internal/handler/workspace_delete_manifest_test.goindex c63245e7a3..e8add98f88 100644--- a/server/internal/handler/workspace_delete_manifest_test.go+++ b/server/internal/handler/workspace_delete_manifest_test.go@@ -138,6 +138,7 @@ var workspaceDeletionManifest = map[string]workspaceDeleteAction{"theme_store_download": workspaceDeleteKeep, // per registry theme, not workspace-owned"task_context_receipt": workspaceDelete,"task_message": workspaceDelete,+ "chat_task_supplement": workspaceDelete,"task_supplement": workspaceDelete,"task_supplement_capability": workspaceDelete,"task_token": workspaceDelete,diff --git a/server/internal/handler/workspace_revoke.go b/server/internal/handler/workspace_revoke.goindex 4874c82fa2..087a193e82 100644--- a/server/internal/handler/workspace_revoke.go+++ b/server/internal/handler/workspace_revoke.go@@ -117,6 +117,13 @@ func (h *Handler) revokeAndRemoveMember(ctx context.Context, workspaceID, userIDif err != nil {return empty, err}+ cancelledIDs := make([]pgtype.UUID, 0, len(result.CancelledTasks))+ for _, task := range result.CancelledTasks {+ cancelledIDs = append(cancelledIDs, task.ID)+ }+ if err = qtx.WithdrawChatTaskSupplementsByTasks(ctx, cancelledIDs); err != nil {+ return empty, err+ }if err = service.SettleTerminalTaskState(ctx, qtx, result.CancelledTasks...); err != nil {return empty, err}diff --git a/server/internal/service/chat_submission.go b/server/internal/service/chat_submission.goindex 2055b2b130..fe4974fbff 100644--- a/server/internal/service/chat_submission.go+++ b/server/internal/service/chat_submission.go@@ -22,10 +22,13 @@ var ErrChatSessionNotFound = errors.New("chat session not found")// ChatSubmissionResponse is the original acceptance snapshot. Cancellation,// queue edits and attachment deletion do not change what was accepted.type ChatSubmissionResponse struct {- MessageID string `json:"message_id"`- TaskID string `json:"task_id"`- SupportsQueue bool `json:"supports_queue"`- Queued bool `json:"queued"`+ MessageID string `json:"message_id"`+ TaskID string `json:"task_id"`+ SupportsQueue bool `json:"supports_queue"`+ Queued bool `json:"queued"`+ Steered bool `json:"steered,omitempty"`+ MessageCreatedAt string `json:"message_created_at,omitempty"`+ MessageTaskID string `json:"message_task_id,omitempty"`// AttachmentIDs are the attachment rows actually bound to this message by// the server. The client diffs these against the ids it requested so it// can warn the user when an attachment silently failed to bind — no extra@@ -49,7 +52,7 @@ type chatSubmission struct {fingerprint []byte}-func newChatSubmission(session db.ChatSession, userID pgtype.UUID, content string, attachmentIDs []pgtype.UUID, actorType string, actorID, submissionID pgtype.UUID) chatSubmission {+func newChatSubmission(session db.ChatSession, userID pgtype.UUID, content string, attachmentIDs []pgtype.UUID, actorType string, actorID, submissionID pgtype.UUID, steer ...bool) chatSubmission {ids := make([]string, 0, len(attachmentIDs))for _, id := range attachmentIDs {ids = append(ids, util.UUIDToString(id))@@ -60,7 +63,8 @@ func newChatSubmission(session db.ChatSession, userID pgtype.UUID, content strinpayload, _ := json.Marshal(struct {Content string `json:"content"`AttachmentIDs []string `json:"attachment_ids"`- }{content, ids})+ Steer bool `json:"steer,omitempty"`+ }{content, ids, len(steer) > 0 && steer[0]})hash := sha256.Sum256(payload)return chatSubmission{key: db.GetChatSubmissionReceiptParams{@@ -91,32 +95,32 @@ func (submission chatSubmission) lookup(ctx context.Context, q *db.Queries) (*Ch// LookupDirectChatSubmission must be called only after current authorization.// It intentionally avoids runtime readiness, overlays and provider lookups.-func (s *TaskService) LookupDirectChatSubmission(ctx context.Context, session db.ChatSession, userID pgtype.UUID, content string, attachmentIDs []pgtype.UUID, actorType string, actorID, submissionID pgtype.UUID) (*ChatSubmissionResponse, error) {- return newChatSubmission(session, userID, content, attachmentIDs, actorType, actorID, submissionID).lookup(ctx, s.Queries)+func (s *TaskService) LookupDirectChatSubmission(ctx context.Context, session db.ChatSession, userID pgtype.UUID, content string, attachmentIDs []pgtype.UUID, actorType string, actorID, submissionID pgtype.UUID, steer ...bool) (*ChatSubmissionResponse, error) {+ return newChatSubmission(session, userID, content, attachmentIDs, actorType, actorID, submissionID, steer...).lookup(ctx, s.Queries)}// SendDirectChatMessageWithSubmission requires a real transaction even for// callers which construct TaskService without its usual database wiring.-func (s *TaskService) SendDirectChatMessageWithSubmission(ctx context.Context, session db.ChatSession, agent db.Agent, userID pgtype.UUID, content string, attachmentIDs []pgtype.UUID, actorType string, actorID, submissionID pgtype.UUID) (*DirectChatSendResult, error) {+func (s *TaskService) SendDirectChatMessageWithSubmission(ctx context.Context, session db.ChatSession, agent db.Agent, userID pgtype.UUID, content string, attachmentIDs []pgtype.UUID, actorType string, actorID, submissionID pgtype.UUID, steer ...bool) (*DirectChatSendResult, error) {if !submissionID.Valid {return nil, errors.New("submission_id is required for keyed chat send")}if s.TxStarter == nil {return nil, errors.New("chat submission requires a transaction starter")}- submission := newChatSubmission(session, userID, content, attachmentIDs, actorType, actorID, submissionID)+ submission := newChatSubmission(session, userID, content, attachmentIDs, actorType, actorID, submissionID, steer...)if response, err := submission.lookup(ctx, s.Queries); err != nil {return nil, err} else if response != nil {return &DirectChatSendResult{Replayed: true, Acceptance: response}, nil}- return s.sendDirectChatMessage(ctx, session, agent, userID, content, attachmentIDs, actorType, actorID, &submission)+ return s.sendDirectChatMessage(ctx, session, agent, userID, content, attachmentIDs, actorType, actorID, &submission, len(steer) > 0 && steer[0])}func (submission chatSubmission) store(ctx context.Context, q *db.Queries, sent *DirectChatSendResult, attachmentsRequested bool) error {response := ChatSubmissionResponse{MessageID: util.UUIDToString(sent.Message.ID), TaskID: util.UUIDToString(sent.Task.ID),- SupportsQueue: true, Queued: sent.Queued, CreatedAt: util.TimestampToString(sent.Task.CreatedAt),+ SupportsQueue: true, Queued: sent.Queued, Steered: sent.Steered, MessageTaskID: util.UUIDToString(sent.Message.TaskID), MessageCreatedAt: util.TimestampToString(sent.Message.CreatedAt), CreatedAt: util.TimestampToString(sent.Task.CreatedAt),}if attachmentsRequested {response.AttachmentIDs = make([]string, 0, len(sent.BoundAttachmentIDs))diff --git a/server/internal/service/chat_supplement.go b/server/internal/service/chat_supplement.gonew file mode 100644index 0000000000..6413e9606d--- /dev/null+++ b/server/internal/service/chat_supplement.go@@ -0,0 +1,72 @@+package service++import (+ "context"+ "fmt"++ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/attribution"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+ "github.com/multica-ai/multica/server/pkg/dbid"+)++// RequeueChatTaskSupplements runs under the original turn's row lock, in the+// same transaction as completion or a failed delivery. Moving the existing+// message preserves its history while giving it a new immutable input owner.+// onlyMessage restricts a provider rejection to the message it rejected.+func RequeueChatTaskSupplements(ctx context.Context, q *db.Queries, task db.AgentTaskQueue, onlyMessage pgtype.UUID) ([]db.AgentTaskQueue, error) {+ return requeueChatTaskSupplements(ctx, q, task, onlyMessage, task.Status == "cancelled" && !onlyMessage.Valid)+}++func requeueChatTaskSupplements(ctx context.Context, q *db.Queries, task db.AgentTaskQueue, onlyMessage pgtype.UUID, waitForDelivery bool) ([]db.AgentTaskQueue, error) {+ rows, err := q.LockUndeliveredChatTaskSupplements(ctx, task.ID)+ if err != nil {+ return nil, fmt.Errorf("lock undelivered chat supplements: %w", err)+ }+ if waitForDelivery {+ for _, row := range rows {+ if row.Status == "delivering" {+ // The daemon joins injection and acknowledgement before cancel-ack.+ // Keep later guidance here too, so it cannot overtake this message.+ _, err := q.MarkChatFinalizeDeferred(ctx, task.ID)+ return nil, err+ }+ }+ }+ var queued []db.AgentTaskQueue+ for _, row := range rows {+ if onlyMessage.Valid && row.MessageID != onlyMessage {+ continue+ }+ attr := attribution.DirectHumanRun(row.AuthorID, attribution.EvidenceChat, row.ChatSessionID)+ source, _, evidenceKind, evidenceRef := attributionCreateParams(attr)+ next, err := q.CreateChatTask(ctx, db.CreateChatTaskParams{+ ID: dbid.NewV7(), AgentID: task.AgentID, RuntimeID: task.RuntimeID,+ Priority: 3, ChatSessionID: task.ChatSessionID, InitiatorUserID: row.AuthorID,+ OriginatorUserID: row.AuthorID, AccountableUserID: row.AuthorID,+ OriginatorSource: source, TriggerEvidenceKind: evidenceKind,+ TriggerEvidenceRefID: evidenceRef,+ ForceFreshSession: pgtype.Bool{Bool: false, Valid: true},+ RuntimeMcpOverlay: task.RuntimeMcpOverlay, RuntimeConnectedApps: task.RuntimeConnectedApps,+ })+ if err != nil {+ return nil, fmt.Errorf("requeue chat supplement: %w", err)+ }+ next, err = q.SetChatTaskInputOwnerSelf(ctx, next.ID)+ if err != nil {+ return nil, err+ }+ if err := q.RequeueChatTaskSupplement(ctx, db.RequeueChatTaskSupplementParams{MessageID: row.MessageID, NextTaskID: next.ID}); err != nil {+ return nil, err+ }+ queued = append(queued, next)+ }+ return queued, nil+}++func (s *TaskService) publishRequeuedChatTasks(ctx context.Context, tasks []db.AgentTaskQueue) {+ for _, task := range tasks {+ s.BroadcastTaskQueued(ctx, task)+ s.NotifyTaskEnqueued(ctx, task)+ }+}diff --git a/server/internal/service/runtime_access_cancellation.go b/server/internal/service/runtime_access_cancellation.goindex f75e5746ea..33adc800f5 100644--- a/server/internal/service/runtime_access_cancellation.go+++ b/server/internal/service/runtime_access_cancellation.go@@ -18,6 +18,15 @@ import (// after commit. That single idempotent finalizer owns transcript messages,// attachment detachment and persisted draft restores for disconnected clients.func PrepareRuntimeAccessCancellation(ctx context.Context, qtx *db.Queries, tasks []db.AgentTaskQueue) ([]pgtype.UUID, error) {+ taskIDs := make([]pgtype.UUID, 0, len(tasks))+ for _, task := range tasks {+ taskIDs = append(taskIDs, task.ID)+ }+ // Access revocation must not leave guidance able to create another run,+ // including when its delivery acknowledgement arrives after cancellation.+ if err := qtx.WithdrawChatTaskSupplementsByTasks(ctx, taskIDs); err != nil {+ return nil, err+ }if err := SettleTerminalTaskState(ctx, qtx, tasks...); err != nil {return nil, err}diff --git a/server/internal/service/runtime_teardown.go b/server/internal/service/runtime_teardown.goindex 719ab3f501..84acc181ab 100644--- a/server/internal/service/runtime_teardown.go+++ b/server/internal/service/runtime_teardown.go@@ -98,6 +98,11 @@ func TeardownRuntime(ctx context.Context, qtx *db.Queries, runtimeID pgtype.UUIDif err != nil {return out, fmt.Errorf("cancel tasks: %w", err)}+ // Task locks precede receipt locks, as in delivery acknowledgement.+ // Removing the runtime withdraws guidance rather than starting new work.+ if err := qtx.WithdrawChatTaskSupplementsByRuntime(ctx, runtimeID); err != nil {+ return out, err+ }if err := SettleTerminalTaskState(ctx, qtx, cancelled...); err != nil {return out, err}diff --git a/server/internal/service/task.go b/server/internal/service/task.goindex d172baea08..9188f804d0 100644--- a/server/internal/service/task.go+++ b/server/internal/service/task.go@@ -2376,6 +2376,7 @@ type DirectChatSendResult struct {Message db.ChatMessageBoundAttachmentIDs []pgtype.UUIDQueued bool+ Steered boolInitialTitle string}@@ -2401,8 +2402,9 @@ func (s *TaskService) SendDirectChatMessage(attachmentIDs []pgtype.UUID,uploaderType string,uploaderID pgtype.UUID,+ steer ...bool,) (*DirectChatSendResult, error) {- return s.sendDirectChatMessage(ctx, session, agent, initiatorUserID, content, attachmentIDs, uploaderType, uploaderID, nil)+ return s.sendDirectChatMessage(ctx, session, agent, initiatorUserID, content, attachmentIDs, uploaderType, uploaderID, nil, len(steer) > 0 && steer[0])}func (s *TaskService) sendDirectChatMessage(@@ -2415,6 +2417,7 @@ func (s *TaskService) sendDirectChatMessage(uploaderType string,uploaderID pgtype.UUID,submission *chatSubmission,+ steer bool,) (*DirectChatSendResult, error) {// Build the per-task Composio overlay before the transaction — it can do// network I/O and must not run with a DB transaction open.@@ -2492,30 +2495,44 @@ func (s *TaskService) sendDirectChatMessage(}out.Queued = queued- task, err := qtx.CreateChatTask(ctx, db.CreateChatTaskParams{- ID: dbid.NewV7(),- AgentID: session.AgentID,- RuntimeID: carrier.RuntimeID,- Priority: 2, // medium priority for chat; matches EnqueueChatTask- ChatSessionID: session.ID,- InitiatorUserID: initiatorUserID,- OriginatorUserID: attr.UserID,- AccountableUserID: attr.AccountableUserID,- ForceFreshSession: pgtype.Bool{Bool: false, Valid: true},- RuntimeMcpOverlay: overlay.Overlay,- RuntimeConnectedApps: overlay.ConnectedApps,- OriginatorSource: attrSource,- TriggerEvidenceKind: attrEvidenceKind,- TriggerEvidenceRefID: attrEvidenceRef,- })- if err != nil {- return fmt.Errorf("create direct chat task: %w", err)+ // Only plain human messages use the text-only supplement transport.+ // Locking the turn serializes the binding with every terminal transition.+ var task db.AgentTaskQueue+ if steer && uploaderType == "member" && len(attachmentIDs) == 0 {+ task, err = qtx.LockRunningChatTaskForSupplement(ctx, session.ID)+ if err != nil && !errors.Is(err, pgx.ErrNoRows) {+ return fmt.Errorf("find running chat turn: %w", err)+ }+ out.Steered = err == nil}- // Claim this task's own input batch (chat_input_task_id = id) in the same- // transaction, before the user message is written with task_id = task.id.- task, err = qtx.SetChatTaskInputOwnerSelf(ctx, task.ID)- if err != nil {- return fmt.Errorf("stamp direct chat input owner: %w", err)+ if out.Steered {+ out.Queued = false+ } else {+ task, err = qtx.CreateChatTask(ctx, db.CreateChatTaskParams{+ ID: dbid.NewV7(),+ AgentID: session.AgentID,+ RuntimeID: carrier.RuntimeID,+ Priority: 2, // medium priority for chat; matches EnqueueChatTask+ ChatSessionID: session.ID,+ InitiatorUserID: initiatorUserID,+ OriginatorUserID: attr.UserID,+ AccountableUserID: attr.AccountableUserID,+ ForceFreshSession: pgtype.Bool{Bool: false, Valid: true},+ RuntimeMcpOverlay: overlay.Overlay,+ RuntimeConnectedApps: overlay.ConnectedApps,+ OriginatorSource: attrSource,+ TriggerEvidenceKind: attrEvidenceKind,+ TriggerEvidenceRefID: attrEvidenceRef,+ })+ if err != nil {+ return fmt.Errorf("create direct chat task: %w", err)+ }+ // Claim this task's own input batch (chat_input_task_id = id) in the same+ // transaction, before the user message is written with task_id = task.id.+ task, err = qtx.SetChatTaskInputOwnerSelf(ctx, task.ID)+ if err != nil {+ return fmt.Errorf("stamp direct chat input owner: %w", err)+ }}out.Task = task@@ -2545,14 +2562,14 @@ func (s *TaskService) sendDirectChatMessage(}}- // Create the user message already owned by this task (task_id = task.id),- // so it belongs to this immutable input batch the instant it exists.+ // Bind guidance to the root input batch, including when it joins a retry.+ // The delivery receipt still names the exact running attempt.msg, err := qtx.CreateChatMessage(ctx, db.CreateChatMessageParams{ID: dbid.NewV7(),ChatSessionID: session.ID,Role: "user",Content: content,- TaskID: task.ID,+ TaskID: chatInputOwnerID(task),MessageKind: pgtype.Text{String: protocol.ChatMessageKindMessage, Valid: true},})if err != nil {@@ -2560,6 +2577,15 @@ func (s *TaskService) sendDirectChatMessage(}out.Message = msg+ if out.Steered {+ if err := qtx.CreateChatTaskSupplement(ctx, db.CreateChatTaskSupplementParams{+ TaskID: task.ID, MessageID: msg.ID, ChatSessionID: session.ID,+ WorkspaceID: session.WorkspaceID, AuthorID: initiatorUserID,+ }); err != nil {+ return fmt.Errorf("bind chat supplement: %w", err)+ }+ }+if len(attachmentIDs) > 0 {bound, err := qtx.LinkAttachmentsToChatMessage(ctx, db.LinkAttachmentsToChatMessageParams{ChatMessageID: msg.ID,@@ -2620,6 +2646,9 @@ func (s *TaskService) sendDirectChatMessage(if out.Replayed {return &out, nil}+ if out.Steered {+ return &out, nil+ }slog.Info("direct chat task enqueued","task_id", util.UUIDToString(out.Task.ID),"chat_session_id", util.UUIDToString(session.ID),@@ -2794,6 +2823,9 @@ func (s *TaskService) CancelTasksForAgent(ctx context.Context, agentID pgtype.UUif err != nil {return err}+ if err := qtx.WithdrawChatTaskSupplementsByAgent(ctx, agentID); err != nil {+ return err+ }return SettleTerminalTaskState(ctx, qtx, cancelled...)}); err != nil {return nil, err@@ -3028,6 +3060,7 @@ func (s *TaskService) CancelTaskWithResult(ctx context.Context, taskID pgtype.UUvar (task db.AgentTaskQueuecancelledChatMessage *CancelledChatMessageResult+ queuedChat []db.AgentTaskQueueerr error)if opts.QueuedOnly {@@ -3092,7 +3125,8 @@ func (s *TaskService) CancelTaskWithResult(ctx context.Context, taskID pgtype.UU}// CancelAgentTaskByUser appends the recovery receipt in the same// statement, so the returned row already carries it.- if err := SettleTerminalTaskState(ctx, qtx, cancelled); err != nil {+ queuedChat, err = settleTerminalTaskState(ctx, qtx, cancelled)+ if err != nil {return err}if !cancelled.ChatSessionID.Valid {@@ -3117,6 +3151,7 @@ func (s *TaskService) CancelTaskWithResult(ctx context.Context, taskID pgtype.UUslog.Info("task cancelled", "task_id", util.UUIDToString(task.ID), "issue_id", util.UUIDToString(task.IssueID))s.captureTaskCancelled(ctx, task)+ s.publishRequeuedChatTasks(ctx, queuedChat)if !opts.QueuedOnly {cancelledChatMessage = s.finalizeCancelledChatMessage(ctx, task, opts)}@@ -3338,6 +3373,11 @@ func (s *TaskService) finalizeCancelledChatMessage(ctx context.Context, task db.if err := lockChatSessionForTaskWrite(ctx, qtx, task.ID); err != nil {return err}+ if exists, err := qtx.HasChatTaskAssistantOutcome(ctx, task.ID); err != nil {+ return err+ } else if exists {+ return nil+ }hasMessages, err := qtx.HasTaskMessages(ctx, task.ID)if err != nil {return fmt.Errorf("list cancelled chat task messages: %w", err)@@ -3506,10 +3546,11 @@ func (s *TaskService) RetireCancelledTaskSession(ctx context.Context, taskID pgtfunc (s *TaskService) FinalizeDeferredCancelledChat(ctx context.Context, taskID pgtype.UUID) bool {var (- task db.AgentTaskQueue- payload protocol.ChatCancelFinalizedPayload- changed bool- settled bool+ task db.AgentTaskQueue+ payload protocol.ChatCancelFinalizedPayload+ changed bool+ settled bool+ queuedChat []db.AgentTaskQueue)if err := s.runInTx(ctx, func(qtx *db.Queries) error {// Lock the task's chat_session first. chat_draft_restore has no FK@@ -3552,6 +3593,17 @@ func (s *TaskService) FinalizeDeferredCancelledChat(ctx context.Context, taskIDif !claimed.ChatSessionID.Valid {return nil}+ queuedChat, err = requeueChatTaskSupplements(ctx, qtx, claimed, pgtype.UUID{}, false)+ if err != nil {+ return err+ }+ // A client requiring a synchronous Stop outcome may already have+ // finalized the transcript while injection was still in flight.+ if exists, err := qtx.HasChatTaskAssistantOutcome(ctx, claimed.ID); err != nil {+ return err+ } else if exists {+ return nil+ }settled = truepayload.ChatSessionID = util.UUIDToString(claimed.ChatSessionID)payload.TaskID = util.UUIDToString(claimed.ID)@@ -3642,6 +3694,7 @@ func (s *TaskService) FinalizeDeferredCancelledChat(ctx context.Context, taskID)return false}+ s.publishRequeuedChatTasks(ctx, queuedChat)if !settled || payload.Outcome == "" {return changed}@@ -4784,6 +4837,7 @@ func (s *TaskService) CompleteTaskWithTransition(ctx context.Context, taskID pgt// task inside the completion transaction below. It is broadcast (chat:done)// only after the transaction commits.var chatAssistantMsg *db.ChatMessage+ var queuedChat []db.AgentTaskQueueif err := s.runInTx(ctx, func(qtx *db.Queries) error {if err := lockChatSessionForTaskWrite(ctx, qtx, taskID); err != nil {return err@@ -4809,7 +4863,8 @@ func (s *TaskService) CompleteTaskWithTransition(ctx context.Context, taskID pgt// Atomic with the status flip: a crash between the two would leave a// finished obligation looking pending forever.- if err := SettleTerminalTaskState(ctx, qtx, t); err != nil {+ queuedChat, err = settleTerminalTaskState(ctx, qtx, t)+ if err != nil {return err}@@ -4894,6 +4949,7 @@ func (s *TaskService) CompleteTaskWithTransition(ctx context.Context, taskID pgt}s.publishQoderIssueChange(ctx, change)+ s.publishRequeuedChatTasks(ctx, queuedChat)slog.Info("task completed", "task_id", util.UUIDToString(task.ID), "issue_id", util.UUIDToString(task.IssueID))s.captureTaskCompleted(ctx, task)@@ -5278,6 +5334,7 @@ func (s *TaskService) FailTaskWithTransition(ctx context.Context, taskID pgtype.var task db.AgentTaskQueuevar retried *db.AgentTaskQueue+ var queuedChat []db.AgentTaskQueueif err := s.runInTx(ctx, func(qtx *db.Queries) error {if err := lockChatSessionForTaskWrite(ctx, qtx, taskID); err != nil {return err@@ -5305,14 +5362,6 @@ func (s *TaskService) FailTaskWithTransition(ctx context.Context, taskID pgtype.}task = t- // Atomic with the status flip, same as the completion path. A failed- // coordinator that already received the recovery comment has consumed- // the obligation: the pre-existing delivered_comment_ids coverage check- // never looked at the covering task's status either.- if err := SettleTerminalTaskState(ctx, qtx, t); err != nil {- return err- }-// Keep resume-unsafe sessions on the task row for observability, but// do not promote them to the chat-level resume pointer.//@@ -5465,6 +5514,22 @@ func (s *TaskService) FailTaskWithTransition(ctx context.Context, taskID pgtype.}}+ if retried != nil && t.ChatSessionID.Valid {+ // The retry reads guidance from the root input batch. Retire the old+ // attempt's delivery receipts instead of scheduling separate turns.+ if err := qtx.RetainChatTaskSupplementsForRetry(ctx, t.ID); err != nil {+ return err+ }+ }+ // Atomic with the status flip, same as the completion path. A failed+ // coordinator that already received the recovery comment has consumed+ // the obligation: the pre-existing delivered_comment_ids coverage check+ // never looked at the covering task's status either.+ queuedChat, err = settleTerminalTaskState(ctx, qtx, t)+ if err != nil {+ return err+ }+// A terminal non-retried chat failure is a visible assistant outcome.// Persist it while the session lock and failure transaction are still// held, then reanchor the next direct head. Otherwise the successor could@@ -5529,6 +5594,7 @@ func (s *TaskService) FailTaskWithTransition(ctx context.Context, taskID pgtype.slog.Warn("task failed", "task_id", util.UUIDToString(task.ID), "issue_id", util.UUIDToString(task.IssueID), "error", errMsg, "failure_reason", failureReason)s.captureTaskFailed(ctx, task)+ s.publishRequeuedChatTasks(ctx, queuedChat)// The auto-retry child (if any) was created inside the transaction above so// no newer chat task could jump ahead of it. Surface it now: broadcast@@ -6385,7 +6451,14 @@ func (s *TaskService) RecoverOrphanedTasksForRuntime(ctx context.Context, runtim// non-chat tasks keep their existing behavior.func (s *TaskService) CancelTasksForArchivedAgent(ctx context.Context, agentID pgtype.UUID) ([]db.AgentTaskQueue, error) {cancelled, err := s.terminateTasksInTx(ctx, func(qtx *db.Queries) ([]db.AgentTaskQueue, error) {- return qtx.CancelAgentTasksByAgent(ctx, agentID)+ tasks, err := qtx.CancelAgentTasksByAgent(ctx, agentID)+ if err != nil {+ return nil, err+ }+ if err := qtx.WithdrawChatTaskSupplementsByAgent(ctx, agentID); err != nil {+ return nil, err+ }+ return tasks, nil})if err != nil {return nil, err@@ -6401,6 +6474,7 @@ func (s *TaskService) CancelTasksForArchivedAgent(ctx context.Context, agentID pfunc (s *TaskService) terminateTasksInTx(ctx context.Context, fail func(*db.Queries) ([]db.AgentTaskQueue, error)) ([]db.AgentTaskQueue, error) {var failed []db.AgentTaskQueue+ var queuedChat []db.AgentTaskQueueif err := s.runInTx(ctx, func(qtx *db.Queries) error {var err errorfailed, err = fail(qtx)@@ -6427,10 +6501,22 @@ func (s *TaskService) terminateTasksInTx(ctx context.Context, fail func(*db.Querfailed[indices[task.ID]] = task}}- return SettleTerminalTaskState(ctx, qtx, failed...)+ // Infrastructure sweeps schedule their retries after this transaction.+ // Retain guidance in that same input batch instead of creating a turn+ // that could run before the original request's retry.+ for _, task := range failed {+ if task.ChatSessionID.Valid && task.Status == "failed" && retryEligible(task.FailureReason.String, task) {+ if err := qtx.RetainChatTaskSupplementsForRetry(ctx, task.ID); err != nil {+ return err+ }+ }+ }+ queuedChat, err = settleTerminalTaskState(ctx, qtx, failed...)+ return err}); err != nil {return nil, err}+ s.publishRequeuedChatTasks(ctx, queuedChat)return failed, nil}@@ -6567,8 +6653,15 @@ const (// task-row -> dependent-row lock order without making task status writes depend// on database trigger behavior.func SettleTerminalTaskState(ctx context.Context, q *db.Queries, tasks ...db.AgentTaskQueue) error {+ _, err := settleTerminalTaskState(ctx, q, tasks...)+ return err+}++// Callers that can requeue Chat guidance publish the returned tasks only after+// their terminal transaction commits.+func settleTerminalTaskState(ctx context.Context, q *db.Queries, tasks ...db.AgentTaskQueue) ([]db.AgentTaskQueue, error) {if len(tasks) == 0 {- return nil+ return nil, nil}taskIDs := make([]pgtype.UUID, 0, len(tasks))@@ -6576,9 +6669,19 @@ func SettleTerminalTaskState(ctx context.Context, q *db.Queries, tasks ...db.AgetaskIDs = append(taskIDs, task.ID)}if _, err := q.SettleTerminalTaskSupplements(ctx, taskIDs); err != nil {- return fmt.Errorf("settle terminal task supplements: %w", err)+ return nil, fmt.Errorf("settle terminal task supplements: %w", err)+ }+ var queued []db.AgentTaskQueue+ for _, task := range tasks {+ if task.ChatSessionID.Valid && (task.Status == "completed" || task.Status == "failed" || task.Status == "cancelled") {+ next, err := RequeueChatTaskSupplements(ctx, q, task, pgtype.UUID{})+ if err != nil {+ return nil, err+ }+ queued = append(queued, next...)+ }}- return SettleDeliveredDelegatedFailureRecoveries(ctx, q, tasks...)+ return queued, SettleDeliveredDelegatedFailureRecoveries(ctx, q, tasks...)}// SettleDeliveredDelegatedFailureRecoveries retires every delegated-failurediff --git a/server/migrations/661_chat_task_supplement.down.sql b/server/migrations/661_chat_task_supplement.down.sqlnew file mode 100644index 0000000000..95e3e70ed8--- /dev/null+++ b/server/migrations/661_chat_task_supplement.down.sql@@ -0,0 +1,4 @@+-- Drain active chat runs before downgrading the application or this schema.+DROP TABLE chat_task_supplement;+DELETE FROM task_supplement_capability WHERE issue_id IS NULL;+ALTER TABLE task_supplement_capability ALTER COLUMN issue_id SET NOT NULL;diff --git a/server/migrations/661_chat_task_supplement.up.sql b/server/migrations/661_chat_task_supplement.up.sqlnew file mode 100644index 0000000000..9e5ebe0196--- /dev/null+++ b/server/migrations/661_chat_task_supplement.up.sql@@ -0,0 +1,11 @@+ALTER TABLE task_supplement_capability ALTER COLUMN issue_id DROP NOT NULL;++CREATE TABLE chat_task_supplement (+ task_id UUID NOT NULL,+ message_id UUID NOT NULL,+ chat_session_id UUID NOT NULL,+ workspace_id UUID NOT NULL,+ author_id UUID NOT NULL,+ status TEXT NOT NULL CHECK (status IN ('pending', 'delivering', 'delivered', 'requeued', 'withdrawn')),+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()+);diff --git a/server/migrations/662_chat_task_supplement_message.down.sql b/server/migrations/662_chat_task_supplement_message.down.sqlnew file mode 100644index 0000000000..3478bfd78e--- /dev/null+++ b/server/migrations/662_chat_task_supplement_message.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS uq_chat_task_supplement_message;diff --git a/server/migrations/662_chat_task_supplement_message.up.sql b/server/migrations/662_chat_task_supplement_message.up.sqlnew file mode 100644index 0000000000..c0ad844793--- /dev/null+++ b/server/migrations/662_chat_task_supplement_message.up.sql@@ -0,0 +1 @@+CREATE UNIQUE INDEX CONCURRENTLY uq_chat_task_supplement_message ON chat_task_supplement (message_id);diff --git a/server/migrations/663_chat_task_supplement_task.down.sql b/server/migrations/663_chat_task_supplement_task.down.sqlnew file mode 100644index 0000000000..3aa4989d4c--- /dev/null+++ b/server/migrations/663_chat_task_supplement_task.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS idx_chat_task_supplement_task;diff --git a/server/migrations/663_chat_task_supplement_task.up.sql b/server/migrations/663_chat_task_supplement_task.up.sqlnew file mode 100644index 0000000000..b410d438d1--- /dev/null+++ b/server/migrations/663_chat_task_supplement_task.up.sql@@ -0,0 +1 @@+CREATE INDEX CONCURRENTLY idx_chat_task_supplement_task ON chat_task_supplement (task_id, created_at, message_id);diff --git a/server/migrations/664_chat_task_supplement_workspace.down.sql b/server/migrations/664_chat_task_supplement_workspace.down.sqlnew file mode 100644index 0000000000..d2aac98f37--- /dev/null+++ b/server/migrations/664_chat_task_supplement_workspace.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS idx_chat_task_supplement_workspace;diff --git a/server/migrations/664_chat_task_supplement_workspace.up.sql b/server/migrations/664_chat_task_supplement_workspace.up.sqlnew file mode 100644index 0000000000..752654b76a--- /dev/null+++ b/server/migrations/664_chat_task_supplement_workspace.up.sql@@ -0,0 +1 @@+CREATE INDEX CONCURRENTLY idx_chat_task_supplement_workspace ON chat_task_supplement (workspace_id, chat_session_id);diff --git a/server/pkg/db/generated/chat.sql.go b/server/pkg/db/generated/chat.sql.goindex 4b97c167eb..2162d97cea 100644--- a/server/pkg/db/generated/chat.sql.go+++ b/server/pkg/db/generated/chat.sql.go@@ -737,11 +737,17 @@ func (q *Queries) DeleteChatSession(ctx context.Context, arg DeleteChatSessionPa}const deleteUserChatMessageByTask = `-- name: DeleteUserChatMessageByTask :one-DELETE FROM chat_message-WHERE task_id = $1- AND role = 'user'- AND message_kind <> 'onboarding_kickoff'-RETURNING id, chat_session_id, role, content, task_id, created_at, failure_reason, elapsed_ms, message_kind, channel_media_pending_until, channel_ingested, quick_actions, channel_context_revision, channel_outbound_type, channel_outbound_installation_id, channel_outbound_chat_id, channel_outbound_message_ids, channel_typing_settled+DELETE FROM chat_message AS message+WHERE message.task_id = $1+ AND message.role = 'user'+ AND message.message_kind <> 'onboarding_kickoff'+ -- Guidance already accepted into a run is conversation history, not the+ -- original draft restored by Stop. A requeued message is editable normally.+ AND NOT EXISTS (+ SELECT 1 FROM chat_task_supplement s+ WHERE s.message_id = message.id AND s.status <> 'requeued'+ )+RETURNING message.id, message.chat_session_id, message.role, message.content, message.task_id, message.created_at, message.failure_reason, message.elapsed_ms, message.message_kind, message.channel_media_pending_until, message.channel_ingested, message.quick_actions, message.channel_context_revision, message.channel_outbound_type, message.channel_outbound_installation_id, message.channel_outbound_chat_id, message.channel_outbound_message_ids, message.channel_typing_settled`// Deletes the MEMBER-TYPED input of a cancelled/edited turn.diff --git a/server/pkg/db/generated/chat_supplement.sql.go b/server/pkg/db/generated/chat_supplement.sql.gonew file mode 100644index 0000000000..37423e146f--- /dev/null+++ b/server/pkg/db/generated/chat_supplement.sql.go@@ -0,0 +1,348 @@+// Code generated by sqlc. DO NOT EDIT.+// versions:+// sqlc v1.31.1+// source: chat_supplement.sql++package db++import (+ "context"++ "github.com/jackc/pgx/v5/pgtype"+)++const ackChatTaskSupplement = `-- name: AckChatTaskSupplement :one+UPDATE chat_task_supplement SET status = 'delivered'+WHERE task_id = $1 AND message_id = $2 AND status IN ('delivering', 'delivered')+RETURNING task_id, message_id, chat_session_id, workspace_id, author_id, status, created_at+`++type AckChatTaskSupplementParams struct {+ TaskID pgtype.UUID `json:"task_id"`+ MessageID pgtype.UUID `json:"message_id"`+}++func (q *Queries) AckChatTaskSupplement(ctx context.Context, arg AckChatTaskSupplementParams) (ChatTaskSupplement, error) {+ row := q.db.QueryRow(ctx, ackChatTaskSupplement, arg.TaskID, arg.MessageID)+ var i ChatTaskSupplement+ err := row.Scan(+ &i.TaskID,+ &i.MessageID,+ &i.ChatSessionID,+ &i.WorkspaceID,+ &i.AuthorID,+ &i.Status,+ &i.CreatedAt,+ )+ return i, err+}++const claimNextChatTaskSupplement = `-- name: ClaimNextChatTaskSupplement :one+WITH next AS MATERIALIZED (+ SELECT s.message_id FROM chat_task_supplement s+ JOIN agent_task_queue t ON t.id = s.task_id+ WHERE s.task_id = $1 AND s.status = 'pending' AND t.status = 'running'+ ORDER BY s.created_at, s.message_id+ LIMIT 1 FOR UPDATE OF s SKIP LOCKED+), claimed AS (+ UPDATE chat_task_supplement s SET status = 'delivering'+ FROM next WHERE s.message_id = next.message_id RETURNING s.task_id, s.message_id, s.chat_session_id, s.workspace_id, s.author_id, s.status, s.created_at+)+SELECT claimed.message_id, m.content, COALESCE(NULLIF(btrim(u.name), ''), 'a user')::text AS author_name+FROM claimed JOIN chat_message m ON m.id = claimed.message_id+LEFT JOIN "user" u ON u.id = claimed.author_id+`++type ClaimNextChatTaskSupplementRow struct {+ MessageID pgtype.UUID `json:"message_id"`+ Content string `json:"content"`+ AuthorName string `json:"author_name"`+}++func (q *Queries) ClaimNextChatTaskSupplement(ctx context.Context, taskID pgtype.UUID) (ClaimNextChatTaskSupplementRow, error) {+ row := q.db.QueryRow(ctx, claimNextChatTaskSupplement, taskID)+ var i ClaimNextChatTaskSupplementRow+ err := row.Scan(&i.MessageID, &i.Content, &i.AuthorName)+ return i, err+}++const createChatTaskSupplement = `-- name: CreateChatTaskSupplement :exec+INSERT INTO chat_task_supplement (task_id, message_id, chat_session_id, workspace_id, author_id, status)+VALUES ($1, $2, $3, $4, $5, 'pending')+`++type CreateChatTaskSupplementParams struct {+ TaskID pgtype.UUID `json:"task_id"`+ MessageID pgtype.UUID `json:"message_id"`+ ChatSessionID pgtype.UUID `json:"chat_session_id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ AuthorID pgtype.UUID `json:"author_id"`+}++func (q *Queries) CreateChatTaskSupplement(ctx context.Context, arg CreateChatTaskSupplementParams) error {+ _, err := q.db.Exec(ctx, createChatTaskSupplement,+ arg.TaskID,+ arg.MessageID,+ arg.ChatSessionID,+ arg.WorkspaceID,+ arg.AuthorID,+ )+ return err+}++const deleteChatSupplementCapabilitiesBySession = `-- name: DeleteChatSupplementCapabilitiesBySession :exec+DELETE FROM task_supplement_capability+WHERE task_id IN (SELECT id FROM agent_task_queue WHERE chat_session_id = $1)+`++func (q *Queries) DeleteChatSupplementCapabilitiesBySession(ctx context.Context, chatSessionID pgtype.UUID) error {+ _, err := q.db.Exec(ctx, deleteChatSupplementCapabilitiesBySession, chatSessionID)+ return err+}++const deleteChatTaskSupplementsBySession = `-- name: DeleteChatTaskSupplementsBySession :exec+DELETE FROM chat_task_supplement WHERE chat_session_id = $1+`++func (q *Queries) DeleteChatTaskSupplementsBySession(ctx context.Context, chatSessionID pgtype.UUID) error {+ _, err := q.db.Exec(ctx, deleteChatTaskSupplementsBySession, chatSessionID)+ return err+}++const deleteChatTaskSupplementsByWorkspace = `-- name: DeleteChatTaskSupplementsByWorkspace :exec+DELETE FROM chat_task_supplement WHERE workspace_id = $1+`++func (q *Queries) DeleteChatTaskSupplementsByWorkspace(ctx context.Context, workspaceID pgtype.UUID) error {+ _, err := q.db.Exec(ctx, deleteChatTaskSupplementsByWorkspace, workspaceID)+ return err+}++const hasChatTaskAssistantOutcome = `-- name: HasChatTaskAssistantOutcome :one+SELECT EXISTS (SELECT 1 FROM chat_message WHERE task_id = $1 AND role = 'assistant')+`++func (q *Queries) HasChatTaskAssistantOutcome(ctx context.Context, taskID pgtype.UUID) (bool, error) {+ row := q.db.QueryRow(ctx, hasChatTaskAssistantOutcome, taskID)+ var exists bool+ err := row.Scan(&exists)+ return exists, err+}++const listChatGuidanceInProviderSession = `-- name: ListChatGuidanceInProviderSession :many+SELECT s.message_id FROM chat_task_supplement s+JOIN agent_task_queue t ON t.id = s.task_id+WHERE s.workspace_id = $1 AND s.message_id = ANY($2::uuid[])+ AND s.status = 'delivered'+ AND t.session_id = $3 AND t.runtime_id = $4+`++type ListChatGuidanceInProviderSessionParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ MessageIds []pgtype.UUID `json:"message_ids"`+ SessionID pgtype.Text `json:"session_id"`+ RuntimeID pgtype.UUID `json:"runtime_id"`+}++func (q *Queries) ListChatGuidanceInProviderSession(ctx context.Context, arg ListChatGuidanceInProviderSessionParams) ([]pgtype.UUID, error) {+ rows, err := q.db.Query(ctx, listChatGuidanceInProviderSession,+ arg.WorkspaceID,+ arg.MessageIds,+ arg.SessionID,+ arg.RuntimeID,+ )+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []pgtype.UUID{}+ for rows.Next() {+ var message_id pgtype.UUID+ if err := rows.Scan(&message_id); err != nil {+ return nil, err+ }+ items = append(items, message_id)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const lockRunningChatTaskForSupplement = `-- name: LockRunningChatTaskForSupplement :one+SELECT t.id, t.agent_id, t.issue_id, t.status, t.priority, t.dispatched_at, t.started_at, t.completed_at, t.result, t.error, t.created_at, t.context, t.runtime_id, t.session_id, t.work_dir, t.trigger_comment_id, t.chat_session_id, t.autopilot_run_id, t.attempt, t.max_attempts, t.parent_task_id, t.failure_reason, t.trigger_summary, t.force_fresh_session, t.is_leader_task, t.wait_reason, t.initiator_user_id, t.handoff_note, t.prepare_lease_expires_at, t.squad_id, t.runtime_mcp_overlay, t.escalation_for_task_id, t.fire_at, t.originator_user_id, t.runtime_connected_apps, t.coalesced_comment_ids, t.delivered_comment_ids, t.chat_input_task_id, t.chat_finalize_deferred_at, t.originator_source, t.delegated_from_task_id, t.retry_of_task_id, t.rerun_of_task_id, t.rule_version_id, t.trigger_evidence_kind, t.trigger_evidence_ref_id, t.accountable_user_id, t.session_rollout_missing, t.retired_session_id, t.quick_actions_disabled, t.regenerate_quick_actions_for, t.branch_name, t.durable_work_dir, t.channel_context_revision, t.comment_thread_id, t.cancelled_by_type, t.cancelled_by_id, t.cancelled_by_name, t.issue_snapshot, t.workflow_step FROM agent_task_queue t+JOIN task_supplement_capability cap ON cap.task_id = t.id+WHERE t.chat_session_id = $1 AND t.status = 'running'+ AND t.regenerate_quick_actions_for IS NULL+ AND cap.capability = 'task-supplement-v1'+ AND NOT EXISTS (SELECT 1 FROM channel_chat_session_binding b WHERE b.chat_session_id = t.chat_session_id)+ORDER BY t.created_at, t.id+LIMIT 1+FOR UPDATE OF t+`++func (q *Queries) LockRunningChatTaskForSupplement(ctx context.Context, chatSessionID pgtype.UUID) (AgentTaskQueue, error) {+ row := q.db.QueryRow(ctx, lockRunningChatTaskForSupplement, chatSessionID)+ var i AgentTaskQueue+ err := row.Scan(+ &i.ID,+ &i.AgentID,+ &i.IssueID,+ &i.Status,+ &i.Priority,+ &i.DispatchedAt,+ &i.StartedAt,+ &i.CompletedAt,+ &i.Result,+ &i.Error,+ &i.CreatedAt,+ &i.Context,+ &i.RuntimeID,+ &i.SessionID,+ &i.WorkDir,+ &i.TriggerCommentID,+ &i.ChatSessionID,+ &i.AutopilotRunID,+ &i.Attempt,+ &i.MaxAttempts,+ &i.ParentTaskID,+ &i.FailureReason,+ &i.TriggerSummary,+ &i.ForceFreshSession,+ &i.IsLeaderTask,+ &i.WaitReason,+ &i.InitiatorUserID,+ &i.HandoffNote,+ &i.PrepareLeaseExpiresAt,+ &i.SquadID,+ &i.RuntimeMcpOverlay,+ &i.EscalationForTaskID,+ &i.FireAt,+ &i.OriginatorUserID,+ &i.RuntimeConnectedApps,+ &i.CoalescedCommentIds,+ &i.DeliveredCommentIds,+ &i.ChatInputTaskID,+ &i.ChatFinalizeDeferredAt,+ &i.OriginatorSource,+ &i.DelegatedFromTaskID,+ &i.RetryOfTaskID,+ &i.RerunOfTaskID,+ &i.RuleVersionID,+ &i.TriggerEvidenceKind,+ &i.TriggerEvidenceRefID,+ &i.AccountableUserID,+ &i.SessionRolloutMissing,+ &i.RetiredSessionID,+ &i.QuickActionsDisabled,+ &i.RegenerateQuickActionsFor,+ &i.BranchName,+ &i.DurableWorkDir,+ &i.ChannelContextRevision,+ &i.CommentThreadID,+ &i.CancelledByType,+ &i.CancelledByID,+ &i.CancelledByName,+ &i.IssueSnapshot,+ &i.WorkflowStep,+ )+ return i, err+}++const lockUndeliveredChatTaskSupplements = `-- name: LockUndeliveredChatTaskSupplements :many+SELECT s.task_id, s.message_id, s.chat_session_id, s.workspace_id, s.author_id, s.status, s.created_at FROM chat_task_supplement s+WHERE s.task_id = $1 AND s.status IN ('pending', 'delivering')+ORDER BY s.created_at, s.message_id FOR UPDATE+`++func (q *Queries) LockUndeliveredChatTaskSupplements(ctx context.Context, taskID pgtype.UUID) ([]ChatTaskSupplement, error) {+ rows, err := q.db.Query(ctx, lockUndeliveredChatTaskSupplements, taskID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []ChatTaskSupplement{}+ for rows.Next() {+ var i ChatTaskSupplement+ if err := rows.Scan(+ &i.TaskID,+ &i.MessageID,+ &i.ChatSessionID,+ &i.WorkspaceID,+ &i.AuthorID,+ &i.Status,+ &i.CreatedAt,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const requeueChatTaskSupplement = `-- name: RequeueChatTaskSupplement :exec+WITH moved AS (+ UPDATE chat_task_supplement SET status = 'requeued'+ WHERE message_id = $2 AND status IN ('pending', 'delivering')+ RETURNING message_id+)+UPDATE chat_message SET task_id = $1+WHERE id IN (SELECT message_id FROM moved)+`++type RequeueChatTaskSupplementParams struct {+ NextTaskID pgtype.UUID `json:"next_task_id"`+ MessageID pgtype.UUID `json:"message_id"`+}++func (q *Queries) RequeueChatTaskSupplement(ctx context.Context, arg RequeueChatTaskSupplementParams) error {+ _, err := q.db.Exec(ctx, requeueChatTaskSupplement, arg.NextTaskID, arg.MessageID)+ return err+}++const retainChatTaskSupplementsForRetry = `-- name: RetainChatTaskSupplementsForRetry :exec+UPDATE chat_task_supplement SET status = 'withdrawn'+WHERE task_id = $1 AND status IN ('pending', 'delivering')+`++// Retire delivery into the failed attempt. The message stays in the root+// input batch and reaches the retry as ordinary input, not another steer.+func (q *Queries) RetainChatTaskSupplementsForRetry(ctx context.Context, taskID pgtype.UUID) error {+ _, err := q.db.Exec(ctx, retainChatTaskSupplementsForRetry, taskID)+ return err+}++const withdrawChatTaskSupplementsByAgent = `-- name: WithdrawChatTaskSupplementsByAgent :exec+UPDATE chat_task_supplement SET status = 'withdrawn'+WHERE task_id IN (SELECT id FROM agent_task_queue WHERE agent_id = $1)+ AND status IN ('pending', 'delivering')+`++func (q *Queries) WithdrawChatTaskSupplementsByAgent(ctx context.Context, agentID pgtype.UUID) error {+ _, err := q.db.Exec(ctx, withdrawChatTaskSupplementsByAgent, agentID)+ return err+}++const withdrawChatTaskSupplementsByRuntime = `-- name: WithdrawChatTaskSupplementsByRuntime :exec+UPDATE chat_task_supplement SET status = 'withdrawn'+WHERE task_id IN (SELECT id FROM agent_task_queue WHERE runtime_id = $1)+ AND status IN ('pending', 'delivering')+`++func (q *Queries) WithdrawChatTaskSupplementsByRuntime(ctx context.Context, runtimeID pgtype.UUID) error {+ _, err := q.db.Exec(ctx, withdrawChatTaskSupplementsByRuntime, runtimeID)+ return err+}++const withdrawChatTaskSupplementsByTasks = `-- name: WithdrawChatTaskSupplementsByTasks :exec+UPDATE chat_task_supplement SET status = 'withdrawn'+WHERE task_id = ANY($1::uuid[]) AND status IN ('pending', 'delivering')+`++func (q *Queries) WithdrawChatTaskSupplementsByTasks(ctx context.Context, taskIds []pgtype.UUID) error {+ _, err := q.db.Exec(ctx, withdrawChatTaskSupplementsByTasks, taskIds)+ return err+}diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.goindex 6611c2d994..b38c154f82 100644--- a/server/pkg/db/generated/models.go+++ b/server/pkg/db/generated/models.go@@ -660,6 +660,16 @@ type ChatSubmissionReceipt struct {CreatedAt pgtype.Timestamptz `json:"created_at"`}+type ChatTaskSupplement struct {+ TaskID pgtype.UUID `json:"task_id"`+ MessageID pgtype.UUID `json:"message_id"`+ ChatSessionID pgtype.UUID `json:"chat_session_id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ AuthorID pgtype.UUID `json:"author_id"`+ Status string `json:"status"`+ CreatedAt pgtype.Timestamptz `json:"created_at"`+}+type ClientUsageDaily struct {UserID pgtype.UUID `json:"user_id"`ClientType string `json:"client_type"`diff --git a/server/pkg/db/generated/supplement.sql.go b/server/pkg/db/generated/supplement.sql.goindex 807a845695..295f2c34e8 100644--- a/server/pkg/db/generated/supplement.sql.go+++ b/server/pkg/db/generated/supplement.sql.go@@ -843,7 +843,7 @@ func (q *Queries) SettleTerminalTaskSupplements(ctx context.Context, taskIds []pconst startAgentTaskWithSupplement = `-- name: StartAgentTaskWithSupplement :oneWITH candidate AS MATERIALIZED (- SELECT t.id, t.issue_id, r.workspace_id, r.provider+ SELECT t.id, t.issue_id, t.chat_session_id, r.workspace_id, r.providerFROM agent_task_queue tJOIN agent_runtime r ON r.id = t.runtime_idWHERE t.id = $2@@ -855,7 +855,7 @@ WITH candidate AS MATERIALIZED (FROM candidateWHERE $3::booleanAND provider IN ('codex', 'claude', 'grok', 'cursor', 'kiro', 'pi')- AND issue_id IS NOT NULL+ AND (issue_id IS NOT NULL OR chat_session_id IS NOT NULL)ON CONFLICT DO NOTHINGRETURNING task_id)diff --git a/server/pkg/db/queries/chat.sql b/server/pkg/db/queries/chat.sqlindex a2967e485e..d5d09f0387 100644--- a/server/pkg/db/queries/chat.sql+++ b/server/pkg/db/queries/chat.sql@@ -781,11 +781,17 @@ RETURNING task.*;-- member the product's internal prompt as their restored draft, and silently-- drop what they actually typed. Callers release the kickoff separately-- (ReleaseOnboardingKickoffFromTask) so the next send re-adopts it.-DELETE FROM chat_message-WHERE task_id = $1- AND role = 'user'- AND message_kind <> 'onboarding_kickoff'-RETURNING *;+DELETE FROM chat_message AS message+WHERE message.task_id = $1+ AND message.role = 'user'+ AND message.message_kind <> 'onboarding_kickoff'+ -- Guidance already accepted into a run is conversation history, not the+ -- original draft restored by Stop. A requeued message is editable normally.+ AND NOT EXISTS (+ SELECT 1 FROM chat_task_supplement s+ WHERE s.message_id = message.id AND s.status <> 'requeued'+ )+RETURNING message.*;-- name: ReleaseOnboardingKickoffFromTask :exec-- Hands an adopted kickoff on to the session's next un-started turn when itsdiff --git a/server/pkg/db/queries/chat_supplement.sql b/server/pkg/db/queries/chat_supplement.sqlnew file mode 100644index 0000000000..c7f8a12d84--- /dev/null+++ b/server/pkg/db/queries/chat_supplement.sql@@ -0,0 +1,88 @@+-- name: LockRunningChatTaskForSupplement :one+SELECT t.* FROM agent_task_queue t+JOIN task_supplement_capability cap ON cap.task_id = t.id+WHERE t.chat_session_id = @chat_session_id AND t.status = 'running'+ AND t.regenerate_quick_actions_for IS NULL+ AND cap.capability = 'task-supplement-v1'+ AND NOT EXISTS (SELECT 1 FROM channel_chat_session_binding b WHERE b.chat_session_id = t.chat_session_id)+ORDER BY t.created_at, t.id+LIMIT 1+FOR UPDATE OF t;++-- name: CreateChatTaskSupplement :exec+INSERT INTO chat_task_supplement (task_id, message_id, chat_session_id, workspace_id, author_id, status)+VALUES (@task_id, @message_id, @chat_session_id, @workspace_id, @author_id, 'pending');++-- name: ClaimNextChatTaskSupplement :one+WITH next AS MATERIALIZED (+ SELECT s.message_id FROM chat_task_supplement s+ JOIN agent_task_queue t ON t.id = s.task_id+ WHERE s.task_id = @task_id AND s.status = 'pending' AND t.status = 'running'+ ORDER BY s.created_at, s.message_id+ LIMIT 1 FOR UPDATE OF s SKIP LOCKED+), claimed AS (+ UPDATE chat_task_supplement s SET status = 'delivering'+ FROM next WHERE s.message_id = next.message_id RETURNING s.*+)+SELECT claimed.message_id, m.content, COALESCE(NULLIF(btrim(u.name), ''), 'a user')::text AS author_name+FROM claimed JOIN chat_message m ON m.id = claimed.message_id+LEFT JOIN "user" u ON u.id = claimed.author_id;++-- name: AckChatTaskSupplement :one+UPDATE chat_task_supplement SET status = 'delivered'+WHERE task_id = @task_id AND message_id = @message_id AND status IN ('delivering', 'delivered')+RETURNING *;++-- name: LockUndeliveredChatTaskSupplements :many+SELECT s.* FROM chat_task_supplement s+WHERE s.task_id = @task_id AND s.status IN ('pending', 'delivering')+ORDER BY s.created_at, s.message_id FOR UPDATE;++-- name: RequeueChatTaskSupplement :exec+WITH moved AS (+ UPDATE chat_task_supplement SET status = 'requeued'+ WHERE message_id = @message_id AND status IN ('pending', 'delivering')+ RETURNING message_id+)+UPDATE chat_message SET task_id = @next_task_id+WHERE id IN (SELECT message_id FROM moved);++-- name: RetainChatTaskSupplementsForRetry :exec+-- Retire delivery into the failed attempt. The message stays in the root+-- input batch and reaches the retry as ordinary input, not another steer.+UPDATE chat_task_supplement SET status = 'withdrawn'+WHERE task_id = $1 AND status IN ('pending', 'delivering');++-- name: DeleteChatTaskSupplementsBySession :exec+DELETE FROM chat_task_supplement WHERE chat_session_id = $1;++-- name: HasChatTaskAssistantOutcome :one+SELECT EXISTS (SELECT 1 FROM chat_message WHERE task_id = $1 AND role = 'assistant');++-- name: ListChatGuidanceInProviderSession :many+SELECT s.message_id FROM chat_task_supplement s+JOIN agent_task_queue t ON t.id = s.task_id+WHERE s.workspace_id = @workspace_id AND s.message_id = ANY(@message_ids::uuid[])+ AND s.status = 'delivered'+ AND t.session_id = @session_id AND t.runtime_id = @runtime_id;++-- name: DeleteChatTaskSupplementsByWorkspace :exec+DELETE FROM chat_task_supplement WHERE workspace_id = $1;++-- name: DeleteChatSupplementCapabilitiesBySession :exec+DELETE FROM task_supplement_capability+WHERE task_id IN (SELECT id FROM agent_task_queue WHERE chat_session_id = $1);++-- name: WithdrawChatTaskSupplementsByRuntime :exec+UPDATE chat_task_supplement SET status = 'withdrawn'+WHERE task_id IN (SELECT id FROM agent_task_queue WHERE runtime_id = $1)+ AND status IN ('pending', 'delivering');++-- name: WithdrawChatTaskSupplementsByTasks :exec+UPDATE chat_task_supplement SET status = 'withdrawn'+WHERE task_id = ANY(@task_ids::uuid[]) AND status IN ('pending', 'delivering');++-- name: WithdrawChatTaskSupplementsByAgent :exec+UPDATE chat_task_supplement SET status = 'withdrawn'+WHERE task_id IN (SELECT id FROM agent_task_queue WHERE agent_id = $1)+ AND status IN ('pending', 'delivering');diff --git a/server/pkg/db/queries/supplement.sql b/server/pkg/db/queries/supplement.sqlindex e0ba571411..60d8f57e46 100644--- a/server/pkg/db/queries/supplement.sql+++ b/server/pkg/db/queries/supplement.sql@@ -3,7 +3,7 @@-- are one state transition. A missing row is the fail-closed value for old-- daemons, old servers, unsupported providers and application rollback.WITH candidate AS MATERIALIZED (- SELECT t.id, t.issue_id, r.workspace_id, r.provider+ SELECT t.id, t.issue_id, t.chat_session_id, r.workspace_id, r.providerFROM agent_task_queue tJOIN agent_runtime r ON r.id = t.runtime_idWHERE t.id = @task_id@@ -15,7 +15,7 @@ WITH candidate AS MATERIALIZED (FROM candidateWHERE @enable_task_supplement::booleanAND provider IN ('codex', 'claude', 'grok', 'cursor', 'kiro', 'pi')- AND issue_id IS NOT NULL+ AND (issue_id IS NOT NULL OR chat_session_id IS NOT NULL)ON CONFLICT DO NOTHINGRETURNING task_id)