fix(automations): unify chat replies and preserve explicit sends

This commit is contained in:
Xubin Ren committed 2026-10-07 01:12:23 +08:00
1 parent 5719ed6e16
commit ab614478a0
25 files changed
+474 -135

No files matched your search

@@ -39,14 +39,14 @@ export function AutomationChatBinding({ job, token, onSave, children }: {
children: (picker: ReactNode) => ReactNode;
}) {
const { t } = useTranslation();
const tx = (key: string) => t(`settings.automations.chat.${key}`);
const tx = (key: string, values?: Record<string, string>) => t(`settings.automations.chat.${key}`, values);
const [data, setData] = useState<AutomationChatsPayload | null>(null);
const [loadError, setLoadError] = useState(false);
const [reload, setReload] = useState(0);
const [draft, setDraft] = useState<{ target: AutomationChat; previousTitle: string; revision: string; message: string } | null>(null);
const [draft, setDraft] = useState<{ target: AutomationChat; previous: AutomationChat; revision: string; message: string } | null>(null);
const [saving, setSaving] = useState(false);
const [error, setError] = useState("");
const [saved, setSaved] = useState(false);
const [saved, setSaved] = useState<string | null>(null);
const heading = useRef<HTMLHeadingElement>(null);
const trigger = useRef<HTMLButtonElement>(null);
const returning = useRef(false);
@@ -77,21 +77,21 @@ export function AutomationChatBinding({ job, token, onSave, children }: {
disabled={pickerDisabled} onValueChange={id => {
const target = data?.chats.find(chat => chat.id === id);
if (!target || target.unavailable || id === current?.id) return;
setError(""); setSaved(false);
setError(""); setSaved(null);
setDraft(previous => previous ? { ...previous, target } : {
target, previousTitle: current?.title || fallback.title,
target, previous: current ?? fallback,
revision: job.chat_binding_revision!, message: job.payload.message,
});
}}>
<SelectTrigger ref={review ? undefined : trigger} aria-label={tx(review ? "new" : "label")}
className={`h-auto min-h-11 w-full py-2 [&>span:first-child]:min-w-0 [&>span:first-child]:flex-1 [&>span:first-child]:text-start ${review ? "" : "border-transparent bg-transparent hover:bg-muted/50"}`}>
className="h-auto min-h-11 w-full py-2 [&>span:first-child]:min-w-0 [&>span:first-child]:flex-1 [&>span:first-child]:text-start">
<SelectValue><ChatIdentity chat={(review ? draft?.target : current) ?? fallback} /></SelectValue>
</SelectTrigger>
<SelectContent>
{!current ? <SelectItem value="current" disabled><ChatIdentity chat={fallback} /></SelectItem> : null}
{data?.chats.map(chat => <SelectItem key={chat.id} value={chat.id} textValue={`${chat.title} ${chat.channel}`}
disabled={chat.unavailable || (review && chat.id === current?.id)}
className="h-auto min-h-11 py-2 [&>span:last-child]:min-w-0 [&>span:last-child]:max-w-[calc(100vw-5rem)] [&>span:last-child]:w-full"><ChatIdentity chat={chat} /></SelectItem>)}
className="h-auto min-h-11 py-2 [&>span:first-child]:min-w-0 [&>span:first-child]:max-w-[calc(100vw-5rem)] [&>span:first-child]:w-full"><ChatIdentity chat={chat} /></SelectItem>)}
</SelectContent>
</Select>;
const save = async () => {
@@ -100,7 +100,7 @@ export function AutomationChatBinding({ job, token, onSave, children }: {
try {
await onSave(job, { target_id: draft.target.id, revision: draft.revision, message: draft.message });
setData(previous => previous ? { ...previous, current: draft.target } : previous);
setSaved(true); back(); setReload(value => value + 1);
setSaved(draft.target.title); back(); setReload(value => value + 1);
} catch (cause) {
const reasons: Record<string, string> = {
automation_chat_conflict: "conflict", automation_chat_busy: "schedulerBusy",
@@ -109,33 +109,37 @@ export function AutomationChatBinding({ job, token, onSave, children }: {
setError(tx(cause instanceof Error ? reasons[cause.message] ?? "failed" : "failed"));
} finally { setSaving(false); }
};
if (!draft) return children(<div className="space-y-1">
<div className="grid min-w-0 grid-cols-1 items-start gap-1 py-1 min-[420px]:grid-cols-[6rem_minmax(0,1fr)] min-[420px]:gap-4">
<span className="text-[13px] text-muted-foreground min-[420px]:pt-3">{tx("label")}</span>
{picker(false)}
</div>
if (!draft) return children(<div className="space-y-2">
<p className="text-[13px] font-medium">{tx("label")}</p>
{picker(false)}
<p role={saved ? "status" : undefined} className="text-[12px] leading-5 text-muted-foreground">
{job.state.pending ? tx("busy") : saved ? tx("saved") : tx("hint")}
{job.state.pending ? tx("busy") : saved ? tx("saved", { chat: saved }) : tx("hint")}
</p>
{loadError ? <Button variant="link" size="sm" onClick={() => setReload(value => value + 1)}>{tx("retry")}</Button> : null}
{data && data.chats.length <= (current ? 1 : 0) ? <p className="text-[12px] leading-5 text-muted-foreground">{tx("available")}</p> : null}
</div>);
return <>
<DialogHeader className="shrink-0 px-6 pb-4 pr-12 pt-5 text-left">
<DialogTitle ref={heading} tabIndex={-1} className="text-lg font-medium leading-snug tracking-normal outline-none">{tx("change")}</DialogTitle>
<DialogTitle ref={heading} tabIndex={-1} className="break-words text-lg font-medium leading-snug tracking-normal outline-none">{tx("change")}</DialogTitle>
</DialogHeader>
<div className="min-h-0 space-y-4 overflow-y-auto overscroll-contain px-6">
<div className="space-y-2">
<div role="group" aria-label={tx("previous")} className="flex min-w-0 items-start gap-3 pb-1 text-muted-foreground">
<span className="shrink-0 text-[12px] leading-6">{tx("previous")}</span>
<ChatIdentity chat={draft.previous} />
</div>
<p className="text-[13px] font-medium">{tx("new")}</p>
{picker(true)}
<p className="text-[12px] leading-5 text-muted-foreground">{tx("previous")} {draft.previousTitle}</p>
</div>
<div className="space-y-1">
<p className="text-[13px] leading-5">{tx("effect")}</p>
<p className="text-[12px] leading-5 text-muted-foreground">{tx("history")}</p>
</div>
<label className="block space-y-2"><span className="text-[13px] font-medium">{tx("message")}</span>
<Textarea rows={3} value={draft.message} disabled={saving} onChange={event => setDraft({ ...draft, message: event.target.value })}
className="min-h-20 resize-y text-base leading-6 sm:text-[13px] sm:leading-5" />
</label>
<p className="text-[12px] leading-5 text-muted-foreground">{tx("review")}</p>
<p className="text-[12px] leading-5 text-muted-foreground">{tx("history")}</p>
{error || targetUnavailable ? <p role="alert" className="text-[12px] leading-5 text-destructive">{error || tx("unavailable")}</p> : null}
</div>
<DialogFooter className="shrink-0 flex-row justify-end gap-2 px-6 pb-5 pt-3">
+8 -8
View File
@@ -1398,19 +1398,19 @@
"conflict": "The task changed elsewhere. Your draft is kept. Reopen the task to review the latest settings.",
"unavailable": "This chat is no longer available with the same workspace and access mode. Select another chat.",
"schedulerBusy": "A task is running or queued. Wait for it to finish, then try again.",
"label": "Task chat",
"new": "New chat",
"label": "Run and reply in",
"new": "Change to",
"current": "Current chat",
"web": "Web chat",
"change": "Change chat",
"previous": "Previous chat:",
"hint": "Uses this chat’s history. Results return here by default.",
"effect": "Future runs will use the new chat’s history and send results there by default.",
"previous": "Now",
"hint": "The task runs in this chat and replies here by default.",
"effect": "From the next run, the task will use the new chat's messages and reply there.",
"message": "Task instructions",
"review": "Check for instructions that send to another chat. People in the new chat may see the task and its results.",
"history": "Old messages stay in the old chat. The schedule stays the same. This does not run the task.",
"review": "Check any recipients in the instructions. Changing the chat does not change them. People in the new chat can see the task and its results.",
"history": "Old messages stay where they are. The schedule does not change.",
"busy": "Cannot change while this task is running or queued.",
"saved": "Changed. Applies to future runs.",
"saved": "Changed to “{{chat}}”. Applies from the next run.",
"failed": "Could not confirm the change. Your draft is kept.",
"retry": "Retry loading chats",
"confirm": "Confirm change",
+8 -8
View File
@@ -1199,19 +1199,19 @@
"conflict": "La tarea cambió en otro lugar. Se conserva el borrador. Abre la tarea de nuevo para revisar los ajustes.",
"unavailable": "Este chat ya no está disponible con el mismo espacio de trabajo y modo de acceso. Elige otro chat.",
"schedulerBusy": "Hay una tarea en ejecución o en cola. Espera a que termine e inténtalo de nuevo.",
"label": "Chat de la tarea",
"new": "Nuevo chat",
"label": "Ejecutar y responder en",
"new": "Cambiar a",
"current": "Chat actual",
"web": "Chat web",
"change": "Cambiar chat",
"previous": "Chat anterior:",
"hint": "Usa el historial de este chat. Los resultados se envían aquí por defecto.",
"effect": "Las próximas ejecuciones usarán el historial del nuevo chat y enviarán allí los resultados por defecto.",
"previous": "Actual",
"hint": "La tarea se ejecuta en este chat y responde aquí de forma predeterminada.",
"effect": "A partir de la próxima ejecución, la tarea usará los mensajes del nuevo chat y responderá allí.",
"message": "Instrucciones de la tarea",
"review": "Revisa las instrucciones que envíen a otro chat. Los miembros del nuevo chat pueden ver la tarea y sus resultados.",
"history": "Los mensajes anteriores permanecen en el chat original. El horario no cambia. La tarea no se ejecuta ahora.",
"review": "Revisa los destinatarios de las instrucciones. Cambiar el chat no los modifica. Los miembros del nuevo chat pueden ver la tarea y sus resultados.",
"history": "Los mensajes anteriores no se trasladan. El horario no cambia.",
"busy": "No se puede cambiar mientras la tarea se ejecuta o espera en la cola.",
"saved": "Cambiado. Se aplica a las próximas ejecuciones.",
"saved": "Se cambió a «{{chat}}». Se aplica desde la próxima ejecución.",
"failed": "No se pudo confirmar el cambio. Se conserva el borrador.",
"retry": "Volver a cargar chats",
"confirm": "Confirmar cambio",
+8 -8
View File
@@ -1198,19 +1198,19 @@
"conflict": "La tâche a été modifiée ailleurs. Le brouillon est conservé. Rouvrez la tâche pour vérifier ses paramètres.",
"unavailable": "Cette discussion n’est plus disponible avec le même espace de travail et mode d’accès. Choisissez-en une autre.",
"schedulerBusy": "Une tâche est en cours ou en attente. Attendez la fin, puis réessayez.",
"label": "Discussion de la tâche",
"new": "Nouvelle discussion",
"label": "Exécuter et répondre dans",
"new": "Remplacer par",
"current": "Discussion actuelle",
"web": "Discussion web",
"change": "Changer de discussion",
"previous": "Ancienne discussion :",
"hint": "Utilise l’historique de cette discussion et y envoie les résultats par défaut.",
"effect": "Les prochaines exécutions utiliseront l’historique de la nouvelle discussion et y enverront les résultats par défaut.",
"previous": "Actuel",
"hint": "La tâche s'exécute dans cette discussion et y répond par défaut.",
"effect": "Dès la prochaine exécution, la tâche utilisera les messages de la nouvelle discussion et y répondra.",
"message": "Instructions de la tâche",
"review": "Vérifiez les instructions qui envoient vers une autre discussion. Les membres de la nouvelle discussion peuvent voir la tâche et ses résultats.",
"history": "Les anciens messages restent dans la discussion d’origine. L’horaire ne change pas. La tâche ne démarre pas maintenant.",
"review": "Vérifiez les destinataires dans les instructions. Changer de discussion ne les modifie pas. Les membres de la nouvelle discussion peuvent voir la tâche et ses résultats.",
"history": "Les anciens messages restent à leur place. L'horaire ne change pas.",
"busy": "Modification impossible si la tâche est en cours ou en attente.",
"saved": "Modifié. S’applique aux prochaines exécutions.",
"saved": "Discussion remplacée par « {{chat}} ». Applicable dès la prochaine exécution.",
"failed": "Impossible de confirmer la modification. Le brouillon est conservé.",
"retry": "Recharger les discussions",
"confirm": "Confirmer",
+8 -8
View File
@@ -1198,19 +1198,19 @@
"conflict": "Tugas diubah di tempat lain. Draf disimpan. Buka ulang tugas untuk memeriksa pengaturan terbaru.",
"unavailable": "Chat ini tidak tersedia lagi dengan ruang kerja dan mode akses yang sama. Pilih chat lain.",
"schedulerBusy": "Ada tugas berjalan atau mengantre. Tunggu hingga selesai, lalu coba lagi.",
"label": "Chat tugas",
"new": "Chat baru",
"label": "Jalankan dan balas di",
"new": "Ganti ke",
"current": "Chat saat ini",
"web": "Chat web",
"change": "Ganti chat",
"previous": "Chat sebelumnya:",
"hint": "Menggunakan riwayat chat ini. Hasil dikirim ke sini secara default.",
"effect": "Pelaksanaan berikutnya menggunakan riwayat chat baru dan mengirim hasil ke sana secara default.",
"previous": "Saat ini",
"hint": "Tugas berjalan di percakapan ini dan secara default membalas di sini.",
"effect": "Mulai eksekusi berikutnya, tugas akan menggunakan pesan dari percakapan baru dan membalas di sana.",
"message": "Instruksi tugas",
"review": "Periksa instruksi yang mengirim ke chat lain. Anggota chat baru mungkin dapat melihat tugas dan hasilnya.",
"history": "Pesan lama tetap di chat asal. Jadwal tidak berubah. Tugas tidak dijalankan sekarang.",
"review": "Periksa penerima dalam instruksi. Mengganti percakapan tidak mengubah penerima tersebut. Anggota percakapan baru dapat melihat tugas dan hasilnya.",
"history": "Pesan lama tetap di tempatnya. Jadwal tidak berubah.",
"busy": "Tidak dapat diganti saat tugas berjalan atau mengantre.",
"saved": "Diganti. Berlaku untuk pelaksanaan berikutnya.",
"saved": "Diubah ke “{{chat}}”. Berlaku mulai eksekusi berikutnya.",
"failed": "Perubahan belum dapat dikonfirmasi. Draf disimpan.",
"retry": "Muat ulang chat",
"confirm": "Konfirmasi perubahan",
+8 -8
View File
@@ -1198,19 +1198,19 @@
"conflict": "タスクが別の場所で変更されました。下書きは保持されています。タスクを開き直して最新の設定を確認してください。",
"unavailable": "このチャットは利用できないか、作業場所や権限が変わりました。別のチャットを選んでください。",
"schedulerBusy": "実行中または待機中のタスクがあります。完了後に再試行してください。",
"label": "タスクのチャット",
"new": "新しいチャット",
"label": "実行・返信先",
"new": "変更先",
"current": "現在のチャット",
"web": "Webチャット",
"change": "チャットを変更",
"previous": "変更前:",
"hint": "このチャットの履歴を使い、通常はここに結果を送ります。",
"effect": "今後の実行では新しいチャットの履歴を使い、通常はそこに結果を送ります。",
"previous": "現在",
"hint": "このチャットでタスクを実行し、既定ではここに結果を返信します。",
"effect": "次回から、新しいチャットの内容を参照してタスクを実行し、そこで返信します。",
"message": "タスクの指示",
"review": "別のチャットへの送信指示が残っていないか確認してください。新しいチャットの参加者にタスクと結果が見える場合があります。",
"history": "過去のメッセージは元のチャットに残ります。実行時刻は変わらず、今すぐ実行もしません。",
"review": "指示に含まれる宛先を確認してください。チャットを変更しても、その宛先は変わりません。新しいチャットのメンバーはタスクの内容と結果を見ることができます。",
"history": "以前のメッセージは移動しません。実行日時は変わりません。",
"busy": "実行中または待機中のタスクは変更できません。",
"saved": "変更しました。次回から適用されます。",
"saved": "「{{chat}}」に変更しました。次回から適用されます。",
"failed": "変更を確認できませんでした。下書きは保存されています。",
"retry": "チャットを再読込",
"confirm": "変更を確定",
+8 -8
View File
@@ -1198,19 +1198,19 @@
"conflict": "다른 곳에서 작업이 변경되었습니다. 초안은 유지됩니다. 작업을 다시 열어 최신 설정을 확인하세요.",
"unavailable": "이 채팅을 사용할 수 없거나 작업 공간 또는 권한이 변경되었습니다. 다른 채팅을 선택하세요.",
"schedulerBusy": "실행 중이거나 대기 중인 작업이 있습니다. 완료 후 다시 시도하세요.",
"label": "작업 채팅",
"new": "새 채팅",
"label": "실행 및 답장 위치",
"new": "변경할 채팅",
"current": "현재 채팅",
"web": "웹 채팅",
"change": "채팅 변경",
"previous": "이전 채팅:",
"hint": "이 채팅의 기록을 사용하며 결과도 기본적으로 여기로 보냅니다.",
"effect": "다음 실행부터 새 채팅의 기록을 사용하며 결과도 기본적으로 그곳으로 보냅니다.",
"previous": "현재",
"hint": "이 채팅에서 작업을 실행하고 기본적으로 여기에 결과를 보냅니다.",
"effect": "다음 실행부터 새 채팅의 메시지를 참고하고 해당 채팅에 답장합니다.",
"message": "작업 지침",
"review": "다른 채팅으로 보내라는 지침이 있는지 확인하세요. 새 채팅의 참여자가 작업 내용과 결과를 볼 수 있습니다.",
"history": "이전 메시지는 원래 채팅에 남습니다. 일정은 유지되며 지금 실행하지 않습니다.",
"review": "지침에 지정된 수신자를 확인하세요. 채팅을 변경해도 해당 수신자는 바뀌지 않습니다. 새 채팅의 구성원은 작업 내용과 결과를 볼 수 있습니다.",
"history": "이전 메시지는 이동하지 않습니다. 일정은 변경되지 않습니다.",
"busy": "작업이 실행 중이거나 대기 중이면 변경할 수 없습니다.",
"saved": "변경했습니다. 다음 실행부터 적용됩니다.",
"saved": "“{{chat}}”(으)로 변경했습니다. 다음 실행부터 적용됩니다.",
"failed": "변경을 확인하지 못했습니다. 초안은 유지됩니다.",
"retry": "채팅 다시 불러오기",
"confirm": "변경 확인",
+8 -8
View File
@@ -1212,19 +1212,19 @@
"conflict": "A tarefa foi alterada em outro lugar. O rascunho foi mantido. Abra a tarefa novamente para conferir os ajustes.",
"unavailable": "Esta conversa não está mais disponível com o mesmo espaço de trabalho e modo de acesso. Escolha outra conversa.",
"schedulerBusy": "Há uma tarefa em execução ou na fila. Aguarde a conclusão e tente novamente.",
"label": "Conversa da tarefa",
"new": "Nova conversa",
"label": "Executar e responder em",
"new": "Alterar para",
"current": "Conversa atual",
"web": "Conversa web",
"change": "Mudar conversa",
"previous": "Conversa anterior:",
"hint": "Usa o histórico desta conversa. Os resultados são enviados aqui por padrão.",
"effect": "As próximas execuções usarão o histórico da nova conversa e enviarão os resultados para lá por padrão.",
"previous": "Atual",
"hint": "A tarefa é executada nesta conversa e responde aqui por padrão.",
"effect": "A partir da próxima execução, a tarefa usará as mensagens da nova conversa e responderá nela.",
"message": "Instruções da tarefa",
"review": "Confira instruções que enviam para outra conversa. Os membros da nova conversa podem ver a tarefa e seus resultados.",
"history": "As mensagens antigas ficam na conversa original. O horário não muda. A tarefa não será executada agora.",
"review": "Confira os destinatários nas instruções. Mudar a conversa não altera esses destinatários. Os membros da nova conversa podem ver a tarefa e seus resultados.",
"history": "As mensagens anteriores ficam onde estão. O horário não muda.",
"busy": "Não é possível mudar enquanto a tarefa está em execução ou na fila.",
"saved": "Alterado. Vale para as próximas execuções.",
"saved": "Alterado para “{{chat}}”. Válido a partir da próxima execução.",
"failed": "Não foi possível confirmar a alteração. O rascunho foi mantido.",
"retry": "Recarregar conversas",
"confirm": "Confirmar alteração",
+8 -8
View File
@@ -1198,19 +1198,19 @@
"conflict": "Tác vụ đã được đổi ở nơi khác. Bản nháp được giữ lại. Mở lại tác vụ để kiểm tra cài đặt mới nhất.",
"unavailable": "Cuộc trò chuyện này không còn khả dụng với cùng không gian làm việc và quyền truy cập. Hãy chọn cuộc trò chuyện khác.",
"schedulerBusy": "Có tác vụ đang chạy hoặc chờ. Hãy đợi hoàn tất rồi thử lại.",
"label": "Cuộc trò chuyện của tác vụ",
"new": "Cuộc trò chuyện mới",
"label": "Chạy và trả lời trong",
"new": "Đổi sang",
"current": "Cuộc trò chuyện hiện tại",
"web": "Trò chuyện web",
"change": "Đổi cuộc trò chuyện",
"previous": "Cuộc trò chuyện cũ:",
"hint": "Dùng lịch sử trò chuyện này. Mặc định kết quả được gửi về đây.",
"effect": "Các lần chạy sau sẽ dùng lịch sử trò chuyện mới và mặc định gửi kết quả đến đó.",
"previous": "Hiện tại",
"hint": "Tác vụ chạy trong cuộc trò chuyện này và mặc định trả lời tại đây.",
"effect": "Từ lần chạy tiếp theo, tác vụ sẽ dùng tin nhắn trong cuộc trò chuyện mới và trả lời tại đó.",
"message": "Hướng dẫn tác vụ",
"review": "Kiểm tra hướng dẫn gửi đến cuộc trò chuyện khác. Thành viên trong cuộc trò chuyện mới có thể thấy tác vụ và kết quả.",
"history": "Tin nhắn cũ vẫn ở cuộc trò chuyện cũ. Lịch chạy không đổi. Tác vụ không chạy ngay.",
"review": "Kiểm tra người nhận trong chỉ dẫn. Đổi cuộc trò chuyện không thay đổi những người nhận này. Thành viên cuộc trò chuyện mới có thể xem tác vụ và kết quả.",
"history": "Tin nhắn cũ vẫn ở chỗ cũ. Lịch chạy không thay đổi.",
"busy": "Không thể đổi khi tác vụ đang chạy hoặc chờ trong hàng đợi.",
"saved": "Đã đổi. Áp dụng từ lần chạy tiếp theo.",
"saved": "Đã đổi sang “{{chat}}”. Áp dụng từ lần chạy tiếp theo.",
"failed": "Chưa thể xác nhận thay đổi. Bản nháp được giữ lại.",
"retry": "Tải lại cuộc trò chuyện",
"confirm": "Xác nhận thay đổi",
+8 -8
View File
@@ -1398,19 +1398,19 @@
"conflict": "任务已在别处修改,草稿已保留。请重新打开任务,核对最新设置后再更换。",
"unavailable": "这个聊天已不可用,或工作目录、权限已改变。请选择其他聊天。",
"schedulerBusy": "有任务正在执行或排队。请等任务结束后再试。",
"label": "任务所在聊天",
"new": "新聊天",
"label": "运行与回复",
"new": "更换为",
"current": "当前聊天",
"web": "网页聊天",
"change": "更换聊天",
"previous": "原聊天:",
"hint": "使用这里的聊天记录,结果也默认发到这里。",
"effect": "后续任务会使用新聊天的记录,结果也默认发到这里。",
"previous": "当前",
"hint": "任务在这个聊天中执行,结果默认发到这里。",
"effect": "从下次起,任务会参考新聊天的内容,并在该聊天回复。",
"message": "任务说明",
"review": "请检查并移除发往其他聊天的旧指令。新聊天的成员可能看到任务内容和结果。",
"history": "旧消息留在原聊天。执行时间不变,也不会立即运行。",
"review": "请检查说明中的收件人,更换聊天不会自动修改。新聊天的成员可见任务内容和结果。",
"history": "旧消息不会搬过去,执行时间不变。",
"busy": "任务正在执行或排队,暂时不能更换。",
"saved": "已更换,下次执行生效。",
"saved": "已更换为「{{chat}}」,下次执行生效。",
"failed": "未能确认更换成功,草稿已保留。",
"retry": "重新加载聊天",
"confirm": "确认并更换",
+8 -8
View File
@@ -1198,19 +1198,19 @@
"conflict": "任務已在別處修改,草稿已保留。請重新開啟任務,確認最新設定後再更換。",
"unavailable": "這個聊天已無法使用,或工作目錄、權限已變更。請選擇其他聊天。",
"schedulerBusy": "有任務正在執行或排隊。請等任務結束後再試。",
"label": "任務所在聊天",
"new": "新聊天",
"label": "執行與回覆",
"new": "更換為",
"current": "目前聊天",
"web": "網頁聊天",
"change": "更換聊天",
"previous": "原聊天:",
"hint": "使用這裡的聊天記錄,結果也預設傳到這裡。",
"effect": "之後的任務會使用新聊天的記錄,結果也預設傳到那裡。",
"previous": "目前",
"hint": "任務在這個聊天中執行,結果預設傳送到這裡。",
"effect": "從下次起,任務會參考新聊天的內容,並在該聊天回覆。",
"message": "任務說明",
"review": "請檢查並移除傳往其他聊天的舊指令。新聊天的成員可能看到任務內容和結果。",
"history": "舊訊息留在原聊天。執行時間不變,也不會立即執行。",
"review": "請檢查說明中的收件人,更換聊天不會自動修改。新聊天的成員可見任務內容和結果。",
"history": "舊訊息不會移過去,執行時間不變。",
"busy": "任務正在執行或排隊,暫時無法更換。",
"saved": "已更換,下次執行生效。",
"saved": "已更換為「{{chat}}」,下次執行生效。",
"failed": "無法確認更換成功,草稿已保留。",
"retry": "重新載入聊天",
"confirm": "確認並更換",
@@ -20,7 +20,7 @@ beforeEach(() => { vi.mocked(fetchAutomationChats).mockResolvedValue(choices); }
afterEach(() => { cleanup(); vi.clearAllMocks(); });
async function choose() {
const control = await screen.findByRole("combobox", { name: "Task chat" });
const control = await screen.findByRole("combobox", { name: "Run and reply in" });
await waitFor(() => expect(control).toBeEnabled());
fireEvent.keyDown(control, { key: "ArrowDown" });
fireEvent.click(await screen.findByRole("option", { name: /Product team/ }));
@@ -34,7 +34,7 @@ it("keeps the original route until acknowledgement and saves the reviewed prompt
const { rerender } = render(<AutomationDetailDialog {...props} job={job} onChangeChat={save} />);
await choose();
expect(save).not.toHaveBeenCalled();
expect(screen.getByText(/Previous chat:/)).toHaveTextContent("My planning");
expect(screen.getByRole("group", { name: "Now" })).toHaveTextContent("My planning");
await user.clear(screen.getByRole("textbox", { name: "Task instructions" }));
await user.type(screen.getByRole("textbox", { name: "Task instructions" }), "New instructions");
await user.click(screen.getByRole("button", { name: "Confirm change" }));
@@ -47,14 +47,29 @@ it("keeps the original route until acknowledgement and saves the reviewed prompt
rerender(<AutomationDetailDialog {...props} job={{ ...job, chat_binding_revision: "rev-2" }} onChangeChat={save} />);
finish();
});
expect(await screen.findByRole("status")).toHaveTextContent("Applies to future runs");
expect(screen.getByRole("combobox", { name: "Task chat" })).toHaveTextContent("Product team");
expect(screen.getByRole("combobox", { name: "Task chat" })).toBeDisabled();
expect(await screen.findByRole("status")).toHaveTextContent("Applies from the next run");
expect(screen.getByRole("combobox", { name: "Run and reply in" })).toHaveTextContent("Product team");
expect(screen.getByRole("combobox", { name: "Run and reply in" })).toBeDisabled();
await act(async () => refresh({ ...choices, current: target, revision: "rev-2" }));
expect(screen.getByRole("combobox", { name: "Task chat" })).toHaveFocus();
expect(screen.getByRole("combobox", { name: "Run and reply in" })).toHaveFocus();
expect(props.onAction).not.toHaveBeenCalled();
});
it("cancels a chat change without saving the edited instructions", async () => {
const user = userEvent.setup();
const save = vi.fn();
render(<AutomationDetailDialog {...props} job={job} onChangeChat={save} />);
await choose();
await user.clear(screen.getByRole("textbox", { name: "Task instructions" }));
await user.type(screen.getByRole("textbox", { name: "Task instructions" }), "Discard this draft");
await user.click(screen.getByRole("button", { name: "Cancel" }));
expect(save).not.toHaveBeenCalled();
expect(screen.getByRole("combobox", { name: "Run and reply in" })).toHaveTextContent("My planning");
expect(screen.getByRole("combobox", { name: "Run and reply in" })).toHaveFocus();
await choose();
expect(screen.getByRole("textbox", { name: "Task instructions" })).toHaveValue("Summarize the work.");
});
it("keeps a rejected draft and its original revision across polling", async () => {
const user = userEvent.setup();
const save = vi.fn().mockRejectedValue(new Error("automation_chat_conflict"));
@@ -67,7 +82,7 @@ it("keeps a rejected draft and its original revision across polling", async () =
expect(await screen.findByRole("alert")).toHaveTextContent("draft is kept");
expect(screen.getByRole("textbox", { name: "Task instructions" })).toHaveValue("Summarize the work. Reviewed");
await user.click(screen.getByRole("button", { name: "Cancel" }));
expect(screen.getByRole("combobox", { name: "Task chat" })).toHaveTextContent("My planning");
expect(screen.getByRole("combobox", { name: "Run and reply in" })).toHaveTextContent("My planning");
});
it("does not send the new request to an old host and locks a pending task", async () => {
@@ -76,7 +91,7 @@ it("does not send the new request to an old host and locks a pending task", asyn
expect(fetchAutomationChats).not.toHaveBeenCalled();
expect(screen.queryByRole("combobox")).not.toBeInTheDocument();
rerender(<AutomationDetailDialog {...props} job={{ ...job, state: { pending: true } }} onChangeChat={save} />);
expect(await screen.findByRole("combobox", { name: "Task chat" })).toBeDisabled();
expect(await screen.findByRole("combobox", { name: "Run and reply in" })).toBeDisabled();
expect(save).not.toHaveBeenCalled();
});
@@ -91,13 +106,13 @@ it("keeps the reviewed chat identity when refreshed choices no longer contain it
});
rerender(<AutomationDetailDialog {...props} job={{ ...job, chat_binding_revision: "rev-2" }} onChangeChat={save} />);
expect(await screen.findByRole("alert")).toHaveTextContent("no longer available");
expect(screen.getByRole("combobox", { name: "New chat" })).toHaveTextContent("Product team");
expect(screen.getByText(/Previous chat:/)).toHaveTextContent("My planning");
expect(screen.getByRole("combobox", { name: "Change to" })).toHaveTextContent("Product team");
expect(screen.getByRole("group", { name: "Now" })).toHaveTextContent("My planning");
expect(screen.getByRole("textbox", { name: "Task instructions" })).toHaveValue("Summarize the work. Reviewed");
expect(screen.getByRole("button", { name: "Confirm change" })).toBeDisabled();
expect(save).not.toHaveBeenCalled();
await user.click(screen.getByRole("button", { name: "Cancel" }));
expect(screen.getByRole("combobox", { name: "Task chat" })).toHaveTextContent("Renamed planning");
expect(screen.getByRole("combobox", { name: "Run and reply in" })).toHaveTextContent("Renamed planning");
});
it("keeps the current chat visible when discovery fails and permits a retry", async () => {
@@ -105,6 +120,6 @@ it("keeps the current chat visible when discovery fails and permits a retry", as
vi.mocked(fetchAutomationChats).mockRejectedValueOnce(new Error("offline"));
render(<AutomationDetailDialog {...props} job={job} onChangeChat={vi.fn()} />);
await user.click(await screen.findByRole("button", { name: "Retry loading chats" }));
await waitFor(() => expect(screen.getByRole("combobox", { name: "Task chat" })).toBeEnabled());
await waitFor(() => expect(screen.getByRole("combobox", { name: "Run and reply in" })).toBeEnabled());
expect(fetchAutomationChats).toHaveBeenCalledTimes(2);
});