Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(chat): change a wakeup's timing from the Wakeups panel (MUL-10021) (#11415)
Multica Eve147b8ed873c3
diff --git a/apps/docs/content/docs/chat.fr.mdx b/apps/docs/content/docs/chat.fr.mdxindex 32634b1691..b0582da2a1 100644--- a/apps/docs/content/docs/chat.fr.mdx+++ b/apps/docs/content/docs/chat.fr.mdx@@ -110,7 +110,7 @@ Cette fonction concerne les conversations Chat directes sur les clients web, deDemandez à l'agent de revenir avec un résultat, par exemple « Préviens-moi quand cette tâche est prête à être revue » ou « Rappelle-le-moi dans deux heures ». Il peut créer un réveil qui lance une nouvelle exécution dans cette conversation lorsqu'une tâche atteint un statut, que des sous-tâches se terminent, qu'une PR GitHub est fusionnée ou fermée, que ses vérifications se terminent, qu'une exécution se termine ou qu'un membre commente une tâche. Il peut aussi revenir à une heure précise ou vérifier périodiquement.-Sur le web et sur desktop, une carte sous la réponse indique le suivi prévu. Le bandeau au-dessus de la saisie indique ce que l'agent attend et l'échéance. Ouvrez ce bandeau ou le bouton horloge de l'en-tête pour voir les **Réveils**, y compris ceux terminés au cours des 7 derniers jours. **Annuler le réveil** arrête l'attente ; si l'exécution du compte rendu échoue ou est annulée, choisissez **Réessayer**.+Sur le web et sur desktop, une carte sous la réponse indique le suivi prévu. Le bandeau au-dessus de la saisie indique ce que l'agent attend et l'échéance. Ouvrez ce bandeau ou le bouton horloge de l'en-tête pour voir les **Réveils**, y compris ceux terminés au cours des 7 derniers jours. **Annuler le réveil** arrête l'attente ; si l'exécution du compte rendu échoue ou est annulée, choisissez **Réessayer**. Pour changer l'horaire d'un réveil actif sans le demander à l'agent, utilisez **Modifier l'horaire** : déplacer un rappel, changer la fréquence d'une vérification ou fixer une nouvelle échéance. Si une vérification plus fréquente dépasse 100 passages, l'échéance est avancée.Les conditions et les vérifications périodiques attendent 24 heures par défaut, 7 jours au maximum. Si l'échéance arrive d'abord, l'agent dispose d'une dernière exécution pour faire le point. Un rappel ponctuel peut être prévu jusqu'à 30 jours à l'avance. Une conversation peut avoir au maximum 10 réveils actifs. Archiver la conversation les annule ; perdre l'accès à l'agent ou au travail surveillé peut aussi les terminer.diff --git a/apps/docs/content/docs/chat.ja.mdx b/apps/docs/content/docs/chat.ja.mdxindex 26bf2aad83..bece07a668 100644--- a/apps/docs/content/docs/chat.ja.mdx+++ b/apps/docs/content/docs/chat.ja.mdx@@ -110,7 +110,7 @@ Multica で作成したダイレクトチャットを読めるのは作成者だ「このタスクがレビュー待ちになったら教えて」「2 時間後にリマインドして」のように依頼できます。エージェントはウェイクアップを作成し、タスクが指定の状態になったとき、サブタスクの完了、GitHub PR のマージやクローズ、チェックの終了、実行の終了、メンバーによるタスクへのコメントに合わせて、同じ会話で新しい実行を開始できます。指定時刻のリマインダーや定期的な確認も可能です。-Web とデスクトップでは、返信の下のカードに予定が表示されます。入力欄の上には、待っている内容と期限が表示されます。その表示か会話ヘッダーの時計ボタンをクリックすると、過去 7 日以内に終了したものも含めた**ウェイクアップ**一覧を開けます。**ウェイクアップをキャンセル**で待機を終了できます。報告の実行が失敗またはキャンセルされた場合は、**再試行**を選べます。+Web とデスクトップでは、返信の下のカードに予定が表示されます。入力欄の上には、待っている内容と期限が表示されます。その表示か会話ヘッダーの時計ボタンをクリックすると、過去 7 日以内に終了したものも含めた**ウェイクアップ**一覧を開けます。**ウェイクアップをキャンセル**で待機を終了できます。報告の実行が失敗またはキャンセルされた場合は、**再試行**を選べます。エージェントに頼まずに時間を変えるには、進行中のウェイクアップの**時間を変更**を使います。通知時刻、チェック間隔、期限を変更できます。間隔を短くしてチェックが 100 回を超える場合は、期限が早まります。条件待ちと定期確認は既定で 24 時間、最長 7 日間です。先に期限が来た場合、エージェントは最後にもう一度実行して現状を報告します。単発のリマインダーは 30 日先まで設定できます。会話ごとに有効なウェイクアップは最大 10 件です。会話をアーカイブすると有効なウェイクアップはキャンセルされます。エージェントや対象の作業へのアクセス権を失った場合も終了することがあります。diff --git a/apps/docs/content/docs/chat.ko.mdx b/apps/docs/content/docs/chat.ko.mdxindex fdd914068d..bcae1ddbd5 100644--- a/apps/docs/content/docs/chat.ko.mdx+++ b/apps/docs/content/docs/chat.ko.mdx@@ -110,7 +110,7 @@ Multica에서 만든 직접 대화는 만든 사람만 읽을 수 있고, 다른"이 태스크가 검토 준비되면 알려 줘" 또는 "두 시간 뒤에 알려 줘"처럼 요청할 수 있습니다. 에이전트는 웨이크업을 만들어 태스크가 지정한 상태에 도달하거나 하위 태스크가 완료될 때, GitHub PR이 병합되거나 닫힐 때, 검사가 끝날 때, 실행이 끝나거나 멤버가 태스크에 댓글을 달 때 같은 대화에서 새 실행을 시작할 수 있습니다. 지정 시각에 알리거나 주기적으로 확인할 수도 있습니다.-웹과 데스크톱에서는 답변 아래 카드에 후속 작업이 표시됩니다. 입력란 위에는 기다리는 내용과 기한이 표시됩니다. 이 표시나 대화 헤더의 시계 버튼을 누르면 최근 7일 안에 종료된 항목을 포함한 **웨이크업** 목록을 볼 수 있습니다. **웨이크업 취소**로 대기를 끝낼 수 있으며, 결과를 보고하는 실행이 실패하거나 취소되면 **다시 시도**할 수 있습니다.+웹과 데스크톱에서는 답변 아래 카드에 후속 작업이 표시됩니다. 입력란 위에는 기다리는 내용과 기한이 표시됩니다. 이 표시나 대화 헤더의 시계 버튼을 누르면 최근 7일 안에 종료된 항목을 포함한 **웨이크업** 목록을 볼 수 있습니다. **웨이크업 취소**로 대기를 끝낼 수 있으며, 결과를 보고하는 실행이 실패하거나 취소되면 **다시 시도**할 수 있습니다. 에이전트에게 다시 묻지 않고 시간을 바꾸려면 진행 중인 웨이크업의 **시간 변경**을 사용하세요. 알림 시각, 확인 간격, 기한을 바꿀 수 있습니다. 간격을 줄여 확인이 100회를 넘게 되면 기한이 앞당겨집니다.조건 대기와 주기적 확인은 기본 24시간, 최대 7일 동안 유지됩니다. 기한이 먼저 오면 에이전트가 마지막으로 한 번 더 실행되어 현재 상황을 알려 줍니다. 일회성 알림은 최대 30일 뒤까지 예약할 수 있습니다. 대화마다 활성 웨이크업은 최대 10개입니다. 대화를 보관하면 활성 웨이크업이 취소됩니다. 에이전트나 확인 중인 작업에 대한 접근 권한을 잃어도 종료될 수 있습니다.diff --git a/apps/docs/content/docs/chat.mdx b/apps/docs/content/docs/chat.mdxindex ae14f35043..4e7e2884e1 100644--- a/apps/docs/content/docs/chat.mdx+++ b/apps/docs/content/docs/chat.mdx@@ -110,7 +110,7 @@ Steering applies to direct Chat sessions on updated web, desktop, and mobile cliAsk the agent to report back when something happens, for example, "Tell me when this issue is ready for review" or "Remind me in two hours." It can create a wakeup that starts another run in this conversation when an issue reaches a status, sub-issues finish, a GitHub PR merges or closes, its checks finish, a run ends, or a member comments on an issue. It can also return at a set time or check periodically.-On web and desktop, a card under the reply records the follow-up. The strip above the input shows what the agent is waiting for and its deadline. Open the strip or the clock button in the conversation header to see **Wakeups**, including those that ended in the past 7 days. Use **Cancel wakeup** to stop waiting; if a report run fails or is cancelled, use **Retry** to request it again.+On web and desktop, a card under the reply records the follow-up. The strip above the input shows what the agent is waiting for and its deadline. Open the strip or the clock button in the conversation header to see **Wakeups**, including those that ended in the past 7 days. Use **Cancel wakeup** to stop waiting; if a report run fails or is cancelled, use **Retry** to request it again. To change when an active wakeup runs without asking the agent, use **Change timing**: move a reminder, change how often a check runs, or set a new deadline. If a faster check would run more than 100 times, the deadline moves earlier.Conditions and periodic checks wait 24 hours by default, at most 7 days. If the deadline arrives first, the agent gets one final turn to report where things stand. One-time reminders can be scheduled up to 30 days ahead. A conversation can have at most 10 active wakeups. Archiving the conversation cancels its active wakeups; losing access to the agent or watched work can also end them.diff --git a/apps/docs/content/docs/chat.zh-Hant.mdx b/apps/docs/content/docs/chat.zh-Hant.mdxindex 0702d85f74..560a17611d 100644--- a/apps/docs/content/docs/chat.zh-Hant.mdx+++ b/apps/docs/content/docs/chat.zh-Hant.mdx@@ -110,7 +110,7 @@ AI 代理執行時,介面會顯示當前階段和工具活動。展開**檢視可以請 AI 代理在有結果時回來回報,例如「任務可以審查時告訴我」或「兩小時後提醒我」。它可以建立喚醒,在任務到達指定狀態、子任務完成、GitHub PR 合併或關閉、其檢查結束、執行結束或成員在任務下評論時,在原對話中啟動新的執行;也可以按指定時間提醒或定期檢查。-在網頁和桌面端,回覆下方的卡片會記錄這次跟進。輸入框上方的提示列顯示正在等待的事項和截止時間。點選提示列或對話標題列的時鐘按鈕,開啟**喚醒**清單,也能查看過去 7 天內結束的記錄。點選**取消喚醒**可停止等待;回報執行失敗或被取消時,可以點選**重試**。+在網頁和桌面端,回覆下方的卡片會記錄這次跟進。輸入框上方的提示列顯示正在等待的事項和截止時間。點選提示列或對話標題列的時鐘按鈕,開啟**喚醒**清單,也能查看過去 7 天內結束的記錄。點選**取消喚醒**可停止等待;回報執行失敗或被取消時,可以點選**重試**。想改時間又不想再問 AI 代理,可以點選進行中喚醒旁的**修改時間**:調整提醒時間、檢查間隔或截止時間。加快檢查後如果會超過 100 次,截止時間會相應提前。條件等待和定期檢查預設持續 24 小時,最長 7 天。到期仍未等到結果時,AI 代理會再執行一次,回報目前進展。單次提醒最遠可安排在 30 天後。每個對話最多有 10 個有效喚醒。封存對話會取消其有效喚醒;失去對 AI 代理或所關注工作的存取權限,也可能讓喚醒結束。diff --git a/apps/docs/content/docs/chat.zh.mdx b/apps/docs/content/docs/chat.zh.mdxindex 552c65fdc2..bbd4871c63 100644--- a/apps/docs/content/docs/chat.zh.mdx+++ b/apps/docs/content/docs/chat.zh.mdx@@ -110,7 +110,7 @@ import { ChatDemo } from "@/components/demos/chat-demo";可以让智能体在有结果时回来汇报,例如"任务可以评审时告诉我"或"两小时后提醒我"。它可以创建唤醒,在任务到达指定状态、子任务完成、GitHub PR 合并或关闭、其检查结束、运行结束或成员在任务下评论时,在原对话中启动新的运行;也可以按指定时间提醒或定期检查。-在网页和桌面端,回复下方的卡片会记录这次跟进。输入框上方的提示条显示正在等待的事项和截止时间。点击提示条或对话标题栏的时钟按钮,打开**唤醒**列表,也能查看过去 7 天内结束的记录。点击**取消唤醒**可停止等待;汇报运行失败或被取消时,可以点击**重试**。+在网页和桌面端,回复下方的卡片会记录这次跟进。输入框上方的提示条显示正在等待的事项和截止时间。点击提示条或对话标题栏的时钟按钮,打开**唤醒**列表,也能查看过去 7 天内结束的记录。点击**取消唤醒**可停止等待;汇报运行失败或被取消时,可以点击**重试**。想改时间又不想再问智能体,可以点击进行中唤醒旁的**修改时间**:调整提醒时间、检查间隔或截止时间。加快检查后如果会超过 100 次,截止时间会相应提前。条件等待和定期检查默认持续 24 小时,最长 7 天。到期仍未等到结果时,智能体会再运行一次,汇报当前进展。单次提醒最远可安排在 30 天后。每个对话最多有 10 个有效唤醒。归档对话会取消其有效唤醒;失去对智能体或所关注工作的访问权限,也可能让唤醒结束。diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex 57e01a39bc..fc15444bf0 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -139,6 +139,7 @@ import type {ChatMessagesPage,ChatDraftRestoresResponse,ChatWakeup,+ ChatWakeupTiming,ChatPendingTask,PrioritizeQueuedChatTaskResponse,PendingChatTasksResponse,@@ -4760,6 +4761,13 @@ export class ApiClient {});}+ async rescheduleChatWakeup(sessionId: string, wakeupId: string, timing: ChatWakeupTiming): Promise<void> {+ await this.fetch(`/api/chat/sessions/${sessionId}/wakeups/${wakeupId}`, {+ method: "PATCH",+ body: JSON.stringify(timing),+ });+ }+async cancelChatWakeup(sessionId: string, wakeupId: string): Promise<void> {await this.fetch(`/api/chat/sessions/${sessionId}/wakeups/${wakeupId}/cancel`, {method: "POST",diff --git a/packages/core/chat/mutations.ts b/packages/core/chat/mutations.tsindex 42bba7bf20..3ed0e27ed5 100644--- a/packages/core/chat/mutations.ts+++ b/packages/core/chat/mutations.ts@@ -7,6 +7,7 @@ import type {ChatSession,ChatPinnedAgent,ChatWakeup,+ ChatWakeupTiming,ChatDraftRestoresResponse,ChatQuickActionsPendingState,} from "../types";@@ -84,6 +85,27 @@ export function useCancelChatWakeup() {});}+/**+ * Change when an active wakeup runs. Not optimistic: the server applies the+ * limits, and chat:wakeup_changed plus the refetch bring the new timing.+ */+export function useRescheduleChatWakeup() {+ const qc = useQueryClient();+ const wsId = useWorkspaceId();++ return useMutation({+ mutationFn: ({ sessionId, wakeupId, timing }: { sessionId: string; wakeupId: string; timing: ChatWakeupTiming }) =>+ api.rescheduleChatWakeup(sessionId, wakeupId, timing),+ onError: (err, { sessionId }) => {+ logger.warn("rescheduleChatWakeup.error", { sessionId, err });+ },+ onSettled: (_data, _err, { sessionId }) => {+ qc.invalidateQueries({ queryKey: chatKeys.wakeups(sessionId) });+ qc.invalidateQueries({ queryKey: chatKeys.myWakeups(wsId) });+ },+ });+}+/*** Re-run a wakeup whose report turn failed. The new turn arrives through* chat:wakeup_changed like any other wakeup turn.diff --git a/packages/core/types/chat.ts b/packages/core/types/chat.tsindex 5f155b36a4..c5e33ee3e1 100644--- a/packages/core/types/chat.ts+++ b/packages/core/types/chat.ts@@ -325,6 +325,18 @@ export interface ChatPendingTask {}export type ChatWakeupKind = "condition" | "at" | "check";++/**+ * A member's change to an active wakeup's timing (PATCH …/wakeups/{id}). A+ * reminder takes `at`; a check `interval_seconds` and/or `expires_at`; a+ * condition `expires_at`. What is left out keeps its current value.+ */+export interface ChatWakeupTiming {+ at?: string;+ interval_seconds?: number;+ expires_at?: string;+}+export type ChatWakeupStatus =| "active"| "fired"diff --git a/packages/core/types/index.ts b/packages/core/types/index.tsindex 7c2b487ac7..82c557151f 100644--- a/packages/core/types/index.ts+++ b/packages/core/types/index.ts@@ -207,6 +207,7 @@ export type {ChatDraftRestoresResponse,ChatWakeup,ChatWakeupKind,+ ChatWakeupTiming,ChatWakeupStatus,} from "./chat";export type { StorageAdapter } from "./storage";diff --git a/packages/views/chat/components/chat-wakeup-timing-editor.test.tsx b/packages/views/chat/components/chat-wakeup-timing-editor.test.tsxnew file mode 100644index 0000000000..0d5eaee343--- /dev/null+++ b/packages/views/chat/components/chat-wakeup-timing-editor.test.tsx@@ -0,0 +1,139 @@+import { fireEvent, render, screen, waitFor } from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { I18nProvider } from "@multica/core/i18n/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import type { ChatWakeup } from "@multica/core/types";+import enChat from "../../locales/en/chat.json";+import enCommon from "../../locales/en/common.json";+import enInbox from "../../locales/en/inbox.json";++const reschedule = vi.hoisted(() => vi.fn());+const toastError = vi.hoisted(() => vi.fn());++vi.mock("@multica/core/api", async (original) => ({+ ...(await original<typeof import("@multica/core/api")>()),+ api: { rescheduleChatWakeup: reschedule },+}));+vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "workspace-1" }));+vi.mock("sonner", () => ({ toast: { error: toastError } }));++import { ChatWakeupHeaderButton } from "./chat-wakeups";++const MINUTE = 60_000;+const HOUR = 60 * MINUTE;+const NOW = new Date(2026, 10, 24, 10, 10).getTime();++function check(overrides: Partial<ChatWakeup> = {}): ChatWakeup {+ return {+ id: "check-1",+ chat_session_id: "session-1",+ agent_id: "agent-1",+ title: "Watch the staging deploy",+ instruction: "Report the deploy result",+ kind: "check",+ condition: null,+ interval_seconds: 1800,+ fire_at: null,+ next_eval_at: new Date(NOW + 30 * MINUTE).toISOString(),+ expires_at: new Date(NOW + 23 * HOUR + 50 * MINUTE).toISOString(),+ status: "active",+ end_reason: null,+ ended_at: null,+ check_count: 6,+ last_check_note: null,+ last_checked_at: null,+ last_task_id: null,+ last_fired_at: null,+ last_error: null,+ source_message_id: null,+ source_task_id: "task-1",+ created_at: new Date(NOW - 10 * MINUTE).toISOString(),+ updated_at: new Date(NOW).toISOString(),+ ...overrides,+ };+}++function renderPanel(wakeups: ChatWakeup[]) {+ const client = new QueryClient({ defaultOptions: { mutations: { retry: false } } });+ const invalidate = vi.spyOn(client, "invalidateQueries");+ render(+ <QueryClientProvider client={client}>+ <I18nProvider locale="en" resources={{ en: { chat: enChat, common: enCommon, inbox: enInbox } }}>+ <ChatWakeupHeaderButton sessionId="session-1" wakeups={wakeups} />+ </I18nProvider>+ </QueryClientProvider>,+ );+ fireEvent.click(screen.getByRole("button", { name: "Wakeups" }));+ return { invalidate };+}++describe("Wakeup timing editor", () => {+ beforeEach(() => {+ vi.useFakeTimers({ toFake: ["Date"] });+ vi.setSystemTime(NOW);+ reschedule.mockReset();+ toastError.mockReset();+ });+ afterEach(() => vi.useRealTimers());++ it("moves the deadline earlier when a faster interval would pass the check limit, and saves both", async () => {+ reschedule.mockResolvedValue(undefined);+ const { invalidate } = renderPanel([check()]);++ fireEvent.click(await screen.findByRole("button", { name: "Change timing" }));+ expect(screen.getByRole("button", { name: "30 minutes" })).toHaveAttribute("aria-pressed", "true");+ expect(screen.getByRole("button", { name: "No change" })).toHaveAttribute("aria-pressed", "true");+ expect(screen.getByRole("button", { name: "Save" })).toBeDisabled();++ fireEvent.click(screen.getByRole("button", { name: "10 minutes" }));+ // 23h50m of 10-minute checks is 143; the deadline ends at the 100th instead.+ expect(screen.queryByRole("button", { name: "No change" })).toBeNull();+ expect(screen.getByRole("button", { name: /tomorrow/i })).toHaveAttribute("aria-pressed", "true");++ fireEvent.click(screen.getByRole("button", { name: "Save" }));+ await waitFor(() => expect(screen.queryByRole("button", { name: "Save" })).toBeNull());+ expect(reschedule).toHaveBeenCalledWith("session-1", "check-1", {+ interval_seconds: 600,+ expires_at: new Date(NOW + 100 * 10 * MINUTE).toISOString(),+ });+ expect(invalidate).toHaveBeenCalled();+ });++ it("keeps the editor open and says so when the change fails", async () => {+ reschedule.mockRejectedValue(new Error("offline"));+ renderPanel([check({ kind: "condition", interval_seconds: null, condition: { type: "issue" } })]);++ fireEvent.click(await screen.findByRole("button", { name: "Change timing" }));+ expect(screen.queryByRole("group", { name: "Every" })).toBeNull();+ fireEvent.click(screen.getByRole("button", { name: "in 4 hours" }));+ fireEvent.click(screen.getByRole("button", { name: "Save" }));++ await waitFor(() => expect(toastError).toHaveBeenCalledWith("Couldn't change the timing"));+ expect(reschedule).toHaveBeenCalledWith("session-1", "check-1", {+ expires_at: new Date(NOW + 4 * HOUR).toISOString(),+ });+ expect(screen.getByRole("button", { name: "Save" })).toBeEnabled();+ });++ it("offers later reminder times, not only earlier ones", async () => {+ reschedule.mockResolvedValue(undefined);+ renderPanel([+ check({+ kind: "at",+ interval_seconds: null,+ fire_at: new Date(NOW + 2 * HOUR).toISOString(),+ expires_at: new Date(NOW + 2 * HOUR).toISOString(),+ }),+ ]);++ fireEvent.click(await screen.findByRole("button", { name: "Change timing" }));+ fireEvent.click(screen.getByRole("button", { name: /tomorrow/i }));+ fireEvent.click(screen.getByRole("button", { name: "Save" }));++ await waitFor(() =>+ expect(reschedule).toHaveBeenCalledWith("session-1", "check-1", {+ at: new Date(2026, 10, 25, 9).toISOString(),+ }),+ );+ });+});diff --git a/packages/views/chat/components/chat-wakeup-timing-editor.tsx b/packages/views/chat/components/chat-wakeup-timing-editor.tsxnew file mode 100644index 0000000000..9025d38435--- /dev/null+++ b/packages/views/chat/components/chat-wakeup-timing-editor.tsx@@ -0,0 +1,236 @@+"use client";++import { useEffect, useRef, useState, type ReactNode } from "react";+import { toast } from "sonner";+import { CalendarDays, TriangleAlert } from "@multica/ui/icons";+import { Button } from "@multica/ui/components/ui/button";+import { LazyCalendar } from "@multica/ui/components/ui/lazy-calendar";+import { TimeInput } from "@multica/ui/components/ui/time-input";+import { Tooltip, TooltipContent, TooltipTrigger } from "@multica/ui/components/ui/tooltip";+import { useRescheduleChatWakeup } from "@multica/core/chat/mutations";+import type { ChatWakeup } from "@multica/core/types";+import { useLocale, useT } from "../../i18n";+import { formatSnoozeTime } from "../../inbox/components/inbox-snooze-time";+import {+ INTERVAL_PRESETS_S,+ KEEP,+ WAKEUP_MAX_CHECKS,+ WAKEUP_MAX_REMINDER_MS,+ WAKEUP_MAX_WAIT_MS,+ checkTiming,+ deadlinePresets,+ reminderPresets,+ timingChange,+ type TimingChoice,+} from "./chat-wakeup-timing";++const HOUR_MS = 3_600_000;++function intervalLabel(locale: string, seconds: number): string {+ const [value, unit] = seconds % 3600 === 0 ? [seconds / 3600, "hour"] : [Math.round(seconds / 60), "minute"];+ return new Intl.NumberFormat(locale, { style: "unit", unit, unitDisplay: "long" }).format(value);+}++function inLabel(locale: string, ms: number): string {+ const rtf = new Intl.RelativeTimeFormat(locale, { numeric: "always" });+ return ms % (24 * HOUR_MS) === 0 ? rtf.format(ms / (24 * HOUR_MS), "day") : rtf.format(ms / HOUR_MS, "hour");+}++function startOfDay(at: number): Date {+ const d = new Date(at);+ return new Date(d.getFullYear(), d.getMonth(), d.getDate());+}++function hhmm(at: number): string {+ const d = new Date(at);+ return `${String(d.getHours()).padStart(2, "0")}:${String(d.getMinutes()).padStart(2, "0")}`;+}++/** The picked day and time, or null when it is not within (now, now + max]. */+function pickedTime(day: Date, time: string, now: number, maxMs: number): number | null {+ const [hours, minutes] = time.split(":").map(Number);+ if (!Number.isInteger(hours) || !Number.isInteger(minutes)) return null;+ const at = new Date(day.getFullYear(), day.getMonth(), day.getDate(), hours, minutes).getTime();+ return at > now && at <= now + maxMs ? at : null;+}++function Choice({+ selected,+ onClick,+ children,+}: {+ selected: boolean;+ onClick: () => void;+ children: ReactNode;+}) {+ return (+ <Button type="button" size="xs" variant={selected ? "brand" : "outline"} aria-pressed={selected} onClick={onClick}>+ {children}+ </Button>+ );+}++function Line({ label, children }: { label: string; children: ReactNode }) {+ return (+ <div role="group" aria-label={label} className="grid grid-cols-[auto_1fr] items-start gap-x-2">+ <span aria-hidden className="min-w-7 text-caption leading-6 text-muted-foreground">{label}</span>+ <div className="flex min-w-0 flex-wrap gap-1">{children}</div>+ </div>+ );+}++/**+ * Change an active wakeup's timing in place, under its row in the Wakeups+ * panel: one-click choices, a date and time for anything else, and the same+ * limits the server applies, so a choice that would break one is adjusted+ * before it is saved rather than refused after.+ */+export function WakeupTimingEditor({+ wakeup,+ sessionId,+ onClose,+}: {+ wakeup: ChatWakeup;+ sessionId: string;+ onClose: () => void;+}) {+ const { t } = useT("chat");+ const { t: common } = useT("common");+ const { t: inbox } = useT("inbox");+ const locale = useLocale();+ const reschedule = useRescheduleChatWakeup();+ const [now] = useState(() => Date.now());+ const isReminder = wakeup.kind === "at";+ const current = Date.parse((isReminder ? wakeup.fire_at : wakeup.expires_at) ?? "");+ const maxMs = isReminder ? WAKEUP_MAX_REMINDER_MS : WAKEUP_MAX_WAIT_MS;++ const [interval, setIntervalChoice] = useState<number | null>(null);+ const [preset, setPreset] = useState<TimingChoice>(KEEP);+ const [custom, setCustom] = useState<{ day: Date; time: string } | null>(null);++ const customAt = custom ? pickedTime(custom.day, custom.time, now, maxMs) : null;+ const choice: TimingChoice | null = custom ? (customAt === null ? null : { kind: "at", at: customAt }) : preset;+ const check = wakeup.kind === "check" && choice ? checkTiming(wakeup, interval, choice, now) : null;+ const change = choice+ ? timingChange(wakeup, { interval, deadline: isReminder ? KEEP : choice, reminder: isReminder ? choice : KEEP }, now)+ : null;++ // The panel is short: opening the calendar brings its time field and Save+ // into view.+ const footerRef = useRef<HTMLDivElement>(null);+ const customOpen = custom !== null;+ useEffect(() => {+ if (customOpen) footerRef.current?.scrollIntoView?.({ block: "nearest" });+ }, [customOpen]);++ const pick = (next: TimingChoice) => {+ setCustom(null);+ setPreset(next);+ };+ const openCustom = () => {+ const start = Number.isNaN(current) || current <= now ? now + HOUR_MS : current;+ setCustom({ day: startOfDay(start), time: hhmm(start) });+ };+ const save = () => {+ if (!change || reschedule.isPending) return;+ reschedule.mutateAsync({ sessionId, wakeupId: wakeup.id, timing: change }).then(onClose, () => {+ toast.error(t(($) => $.wakeup.timing_failed));+ });+ };++ const intervals: number[] = [...INTERVAL_PRESETS_S];+ if (wakeup.interval_seconds && !intervals.includes(wakeup.interval_seconds)) {+ intervals.unshift(wakeup.interval_seconds);+ }+ const effectiveInterval = interval ?? wakeup.interval_seconds;+ const presets = isReminder ? reminderPresets(now) : deadlinePresets(now);+ const limited = check?.limited ?? false;+ const today = startOfDay(now);+ const lastDay = startOfDay(now + maxMs);++ return (+ <div data-slot="chat-wakeup-timing" className="flex flex-col gap-2 pt-1 pb-1 pl-[22px]">+ {wakeup.kind === "check" && (+ <Line label={t(($) => $.wakeup.timing_interval)}>+ {intervals.map((seconds) => (+ <Choice+ key={seconds}+ selected={effectiveInterval === seconds}+ onClick={() => setIntervalChoice(seconds === wakeup.interval_seconds ? null : seconds)}+ >+ {intervalLabel(locale, seconds)}+ </Choice>+ ))}+ </Line>+ )}+ <Line label={isReminder ? t(($) => $.wakeup.timing_reminder) : t(($) => $.wakeup.timing_deadline)}>+ {!isReminder && !limited && (+ <Choice selected={!custom && preset.kind === "keep"} onClick={() => pick(KEEP)}>+ {t(($) => $.wakeup.timing_keep)}+ </Choice>+ )}+ {limited && check && (+ <Tooltip>+ <TooltipTrigger+ render={<Button type="button" size="xs" variant="brand" aria-pressed />}+ >+ <TriangleAlert aria-hidden />+ {formatSnoozeTime(new Date(check.deadline), new Date(now), locale)}+ </TooltipTrigger>+ <TooltipContent side="bottom">{t(($) => $.wakeup.timing_check_limit, { max: WAKEUP_MAX_CHECKS })}</TooltipContent>+ </Tooltip>+ )}+ {presets.map(({ at, inMs }) => (+ <Choice+ key={at}+ selected={!limited && !custom && preset.kind === "at" && preset.at === at}+ onClick={() => pick({ kind: "at", at })}+ >+ {inMs ? inLabel(locale, inMs) : formatSnoozeTime(new Date(at), new Date(now), locale)}+ </Choice>+ ))}+ <Choice selected={!!custom && !limited} onClick={openCustom}>+ <CalendarDays aria-hidden />+ {t(($) => $.wakeup.timing_custom)}+ </Choice>+ </Line>+ {custom && (+ <div className="flex flex-col rounded-md border border-surface-border bg-surface">+ <LazyCalendar+ mode="single"+ required+ selected={custom.day}+ defaultMonth={custom.day}+ onSelect={(day: Date) => setCustom({ ...custom, day })}+ startMonth={today}+ endMonth={lastDay}+ disabled={[{ before: today }, { after: lastDay }]}+ className="bg-transparent"+ />+ <div className="flex items-center justify-end border-t border-surface-border px-2 py-1.5">+ <TimeInput+ value={custom.time}+ onChange={(time) => setCustom({ ...custom, time })}+ hourLabel={inbox(($) => $.snooze.picker_hour)}+ minuteLabel={inbox(($) => $.snooze.picker_minute)}+ />+ </div>+ </div>+ )}+ <div ref={footerRef} className="flex justify-end gap-1.5">+ <Button type="button" size="xs" variant="ghost" onClick={onClose}>+ {common(($) => $.cancel)}+ </Button>+ <Button+ type="button"+ size="xs"+ disabled={!change || reschedule.isPending}+ aria-busy={reschedule.isPending}+ onClick={save}+ >+ {common(($) => $.save)}+ </Button>+ </div>+ </div>+ );+}diff --git a/packages/views/chat/components/chat-wakeup-timing.test.ts b/packages/views/chat/components/chat-wakeup-timing.test.tsnew file mode 100644index 0000000000..c8a7bf92d7--- /dev/null+++ b/packages/views/chat/components/chat-wakeup-timing.test.ts@@ -0,0 +1,87 @@+// @vitest-environment node+import { describe, expect, it } from "vitest";+import { KEEP, checkTiming, reminderPresets, timingChange } from "./chat-wakeup-timing";++const MINUTE = 60_000;+const HOUR = 60 * MINUTE;+const NOW = new Date(2026, 10, 24, 10, 10).getTime();+const iso = (at: number) => new Date(at).toISOString();++describe("checkTiming", () => {+ // A check every 30 minutes until tomorrow 10:00, as an agent creates it.+ const check = { interval_seconds: 1800, expires_at: iso(NOW + 23 * HOUR + 50 * MINUTE) };++ it("keeps a schedule within the check limit", () => {+ expect(checkTiming(check, 900, KEEP, NOW)).toEqual({+ intervalSeconds: 900,+ deadline: NOW + 23 * HOUR + 50 * MINUTE,+ limited: false,+ });+ });++ it("ends a schedule over 100 checks at the last deadline the limit allows", () => {+ // Every 10 minutes for 23h50m would be 143 checks.+ expect(checkTiming(check, 600, KEEP, NOW)).toEqual({+ intervalSeconds: 600,+ deadline: NOW + 100 * 10 * MINUTE,+ limited: true,+ });+ // A longer deadline at the current interval is limited the same way.+ expect(checkTiming(check, null, { kind: "at", at: NOW + 3 * 24 * HOUR }, NOW).limited).toBe(true);+ });+});++describe("timingChange", () => {+ const check = {+ kind: "check" as const,+ interval_seconds: 1800,+ expires_at: iso(NOW + 23 * HOUR + 50 * MINUTE),+ };++ it("sends only what changed", () => {+ expect(timingChange(check, { interval: null, deadline: KEEP, reminder: KEEP }, NOW)).toBeNull();+ expect(timingChange(check, { interval: 1800, deadline: KEEP, reminder: KEEP }, NOW)).toBeNull();+ expect(timingChange(check, { interval: 900, deadline: KEEP, reminder: KEEP }, NOW)).toEqual({ interval_seconds: 900 });+ expect(+ timingChange(check, { interval: null, deadline: { kind: "at", at: NOW + 4 * HOUR }, reminder: KEEP }, NOW),+ ).toEqual({ expires_at: iso(NOW + 4 * HOUR) });+ });++ it("sends the earlier deadline when the check limit moves it", () => {+ expect(timingChange(check, { interval: 600, deadline: KEEP, reminder: KEEP }, NOW)).toEqual({+ interval_seconds: 600,+ expires_at: iso(NOW + 1000 * MINUTE),+ });+ });++ it("takes a time for a reminder and a deadline for a condition", () => {+ const reminder = { kind: "at" as const, interval_seconds: null, expires_at: iso(NOW + 2 * HOUR) };+ const at = NOW + 20 * HOUR;+ expect(timingChange(reminder, { interval: null, deadline: KEEP, reminder: { kind: "at", at } }, NOW)).toEqual({+ at: iso(at),+ });+ const condition = { kind: "condition" as const, interval_seconds: null, expires_at: iso(NOW + 20 * HOUR) };+ expect(timingChange(condition, { interval: null, deadline: { kind: "at", at }, reminder: KEEP }, NOW)).toEqual({+ expires_at: iso(at),+ });+ expect(timingChange(condition, { interval: null, deadline: KEEP, reminder: KEEP }, NOW)).toBeNull();+ });+});++describe("reminderPresets", () => {+ it("offers this evening only while it is more than three hours away", () => {+ const morning = reminderPresets(NOW).map((p) => p.at);+ expect(morning).toEqual([+ NOW + HOUR,+ NOW + 3 * HOUR,+ new Date(2026, 10, 24, 18).getTime(),+ new Date(2026, 10, 25, 9).getTime(),+ ]);+ const afternoon = new Date(2026, 10, 24, 16).getTime();+ expect(reminderPresets(afternoon).map((p) => p.at)).toEqual([+ afternoon + HOUR,+ afternoon + 3 * HOUR,+ new Date(2026, 10, 25, 9).getTime(),+ ]);+ });+});diff --git a/packages/views/chat/components/chat-wakeup-timing.ts b/packages/views/chat/components/chat-wakeup-timing.tsnew file mode 100644index 0000000000..fc52297174--- /dev/null+++ b/packages/views/chat/components/chat-wakeup-timing.ts@@ -0,0 +1,97 @@+import type { ChatWakeup, ChatWakeupTiming } from "@multica/core/types";++const MINUTE_MS = 60_000;+const HOUR_MS = 60 * MINUTE_MS;+const DAY_MS = 24 * HOUR_MS;++// The server's limits for chat wakeups (server/internal/service/chat_wakeup.go).+// The editor applies them before saving so a choice never fails on submit.+export const WAKEUP_MAX_CHECKS = 100;+export const WAKEUP_MAX_WAIT_MS = 7 * DAY_MS;+export const WAKEUP_MAX_REMINDER_MS = 30 * DAY_MS;++export const INTERVAL_PRESETS_S = [600, 900, 1800, 3600] as const;+export const DEADLINE_PRESETS_MS = [4 * HOUR_MS, DAY_MS, 3 * DAY_MS] as const;++/** A deadline or reminder choice: kept as it is, or a time picked in the editor. */+export type TimingChoice = { kind: "keep" } | { kind: "at"; at: number };++export const KEEP: TimingChoice = { kind: "keep" };++/** A one-click time: a distance from now ("in 4 hours") or a clock time. */+export interface TimingPreset {+ at: number;+ inMs?: number;+}++export function deadlinePresets(now: number): TimingPreset[] {+ return DEADLINE_PRESETS_MS.map((inMs) => ({ at: now + inMs, inMs }));+}++/**+ * One-click reminder times: an hour and three hours out, this evening while it+ * is still afternoon, and tomorrow morning.+ */+export function reminderPresets(now: number): TimingPreset[] {+ const today = new Date(now);+ const evening = new Date(today.getFullYear(), today.getMonth(), today.getDate(), 18).getTime();+ const morning = new Date(today.getFullYear(), today.getMonth(), today.getDate() + 1, 9).getTime();+ const presets: TimingPreset[] = [+ { at: now + HOUR_MS, inMs: HOUR_MS },+ { at: now + 3 * HOUR_MS, inMs: 3 * HOUR_MS },+ ];+ if (evening - now > 3 * HOUR_MS) presets.push({ at: evening });+ presets.push({ at: morning });+ return presets;+}++export interface CheckTiming {+ intervalSeconds: number;+ deadline: number;+ /** The deadline was moved earlier to stay within the check limit. */+ limited: boolean;+}++/**+ * What a check would run as with the editor's choices. A schedule that needs+ * more than WAKEUP_MAX_CHECKS checks ends early instead, at the last deadline+ * the limit allows, the same count the server applies.+ */+export function checkTiming(+ wakeup: Pick<ChatWakeup, "interval_seconds" | "expires_at">,+ interval: number | null,+ deadline: TimingChoice,+ now: number,+): CheckTiming {+ const intervalSeconds = interval ?? wakeup.interval_seconds ?? INTERVAL_PRESETS_S[0];+ const chosen = deadline.kind === "at" ? deadline.at : Date.parse(wakeup.expires_at);+ const limit = now + WAKEUP_MAX_CHECKS * intervalSeconds * 1000;+ return chosen > limit+ ? { intervalSeconds, deadline: limit, limited: true }+ : { intervalSeconds, deadline: chosen, limited: false };+}++/**+ * The PATCH body for the editor's choices, or null when nothing changed. Only+ * what the member changed is sent; the server keeps the rest.+ */+export function timingChange(+ wakeup: Pick<ChatWakeup, "kind" | "interval_seconds" | "expires_at">,+ choice: { interval: number | null; deadline: TimingChoice; reminder: TimingChoice },+ now: number,+): ChatWakeupTiming | null {+ switch (wakeup.kind) {+ case "at":+ return choice.reminder.kind === "at" ? { at: new Date(choice.reminder.at).toISOString() } : null;+ case "condition":+ return choice.deadline.kind === "at" ? { expires_at: new Date(choice.deadline.at).toISOString() } : null;+ case "check": {+ const interval = choice.interval !== null && choice.interval !== wakeup.interval_seconds ? choice.interval : null;+ const plan = checkTiming(wakeup, interval, choice.deadline, now);+ const change: ChatWakeupTiming = {};+ if (interval !== null) change.interval_seconds = interval;+ if (choice.deadline.kind === "at" || plan.limited) change.expires_at = new Date(plan.deadline).toISOString();+ return Object.keys(change).length > 0 ? change : null;+ }+ }+}diff --git a/packages/views/chat/components/chat-wakeups.tsx b/packages/views/chat/components/chat-wakeups.tsxindex bc5dc1f5b3..a42b28dcb5 100644--- a/packages/views/chat/components/chat-wakeups.tsx+++ b/packages/views/chat/components/chat-wakeups.tsx@@ -3,9 +3,10 @@import { useEffect, useMemo, useState } from "react";import { useQuery } from "@tanstack/react-query";import { toast } from "sonner";-import { AlarmClock, RotateCcw, X } from "@multica/ui/icons";+import { AlarmClock, Clock, RotateCcw, X } from "@multica/ui/icons";import { IconButton } from "@multica/ui/components/common/icon-button";import { Button } from "@multica/ui/components/ui/button";+import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@multica/ui/components/ui/collapsible";import { Popover, PopoverContent, PopoverTrigger } from "@multica/ui/components/ui/popover";import { cn } from "@multica/ui/lib/utils";import { chatWakeupsOptions } from "@multica/core/chat/queries";@@ -13,6 +14,7 @@ import { useCancelChatWakeup, useRetryChatWakeup } from "@multica/core/chat/mutaimport type { ChatMessage, ChatWakeup } from "@multica/core/types";import { useLocale, useT } from "../../i18n";import { CHAT_COLUMN, CHAT_GUTTER } from "./chat-column";+import { WakeupTimingEditor } from "./chat-wakeup-timing-editor";const EMPTY: ChatWakeup[] = [];const MINUTE = 60_000;@@ -161,7 +163,19 @@ function RetryButton({ wakeup, sessionId }: { wakeup: ChatWakeup; sessionId: str);}-function WakeupRow({ wakeup, sessionId, now }: { wakeup: ChatWakeup; sessionId: string; now: number }) {+function WakeupRow({+ wakeup,+ sessionId,+ now,+ editing = false,+ onEditingChange,+}: {+ wakeup: ChatWakeup;+ sessionId: string;+ now: number;+ editing?: boolean;+ onEditingChange?: (editing: boolean) => void;+}) {const text = useWakeupText();const cancel = useCancel(sessionId);const urgent = isWakeupRunningOut(wakeup, now);@@ -169,52 +183,80 @@ function WakeupRow({ wakeup, sessionId, now }: { wakeup: ChatWakeup; sessionId:const report = wakeupReportState(wakeup);const failure = text.failure(wakeup);const details = [text.kind(wakeup), text.timing(wakeup, now), text.nextCheck(wakeup, now)].filter(Boolean);+ const isEditing = editing && active;return (- <div data-slot="chat-wakeup-row" className="flex min-w-0 items-start gap-2 rounded-md px-2 py-1.5">- <AlarmClock- aria-hidden- className={cn("mt-0.5 size-3.5 shrink-0", active ? "text-brand" : "text-faint-foreground")}- />- <div className="min-w-0 flex-1">- <div className={cn("truncate text-body", !active && "text-muted-foreground")}>{wakeup.title}</div>- <div- className={cn(- "text-caption text-muted-foreground",- urgent && "text-warning",- report === "failed" && "text-destructive",+ <Collapsible+ data-slot="chat-wakeup-row"+ open={isEditing}+ onOpenChange={(open) => onEditingChange?.(open)}+ className={cn("rounded-md px-2 py-1.5 transition-colors", isEditing && "bg-surface-hover")}+ >+ <div className="flex min-w-0 items-start gap-2">+ <AlarmClock+ aria-hidden+ className={cn("mt-0.5 size-3.5 shrink-0", active ? "text-brand" : "text-faint-foreground")}+ />+ <div className="min-w-0 flex-1">+ <div className={cn("truncate text-body", !active && "text-muted-foreground")}>{wakeup.title}</div>+ <div+ className={cn(+ "text-caption text-muted-foreground",+ urgent && "text-warning",+ report === "failed" && "text-destructive",+ )}+ >+ {active ? details.join(" · ") : text.status(wakeup)}+ </div>+ {wakeup.last_check_note && active && (+ <div className="truncate text-caption text-muted-foreground">+ {text.t(($) => $.wakeup.last_check, { note: wakeup.last_check_note })}+ </div>)}- >- {active ? details.join(" · ") : text.status(wakeup)}+ {failure && <div className="truncate text-caption text-destructive">{failure}</div>}</div>- {wakeup.last_check_note && active && (- <div className="truncate text-caption text-muted-foreground">- {text.t(($) => $.wakeup.last_check, { note: wakeup.last_check_note })}- </div>+ {report === "failed" && <RetryButton wakeup={wakeup} sessionId={sessionId} />}+ {active && onEditingChange && (+ <CollapsibleTrigger+ render={+ <IconButton+ variant="ghost"+ size="icon-xs"+ className="shrink-0 text-muted-foreground aria-expanded:bg-surface-selected aria-expanded:text-foreground"+ label={text.t(($) => $.wakeup.change_timing)}+ />+ }+ >+ <Clock aria-hidden />+ </CollapsibleTrigger>+ )}+ {active && (+ <IconButton+ variant="ghost"+ size="icon-xs"+ className="shrink-0 text-muted-foreground"+ label={text.t(($) => $.wakeup.cancel)}+ onClick={() => cancel(wakeup.id)}+ >+ <X aria-hidden />+ </IconButton>)}- {failure && <div className="truncate text-caption text-destructive">{failure}</div>}</div>- {report === "failed" && <RetryButton wakeup={wakeup} sessionId={sessionId} />}- {active && (- <IconButton- variant="ghost"- size="icon-xs"- className="shrink-0 text-muted-foreground"- label={text.t(($) => $.wakeup.cancel)}- onClick={() => cancel(wakeup.id)}- >- <X aria-hidden />- </IconButton>+ {active && onEditingChange && (+ <CollapsibleContent>+ <WakeupTimingEditor wakeup={wakeup} sessionId={sessionId} onClose={() => onEditingChange(false)} />+ </CollapsibleContent>)}- </div>+ </Collapsible>);}-/** Every wakeup of the conversation, plus the limits that bound them. */+/** Every wakeup of the conversation; an active one can change its timing in place. */function WakeupPanel({ wakeups, sessionId }: { wakeups: ChatWakeup[]; sessionId: string }) {const { t } = useT("chat");const now = useNow();const active = activeFirst(wakeups);const ended = wakeups.filter((w) => w.status !== "active");+ const [editingId, setEditingId] = useState<string | null>(null);return (<><div className="shrink-0 px-2 py-1.5 text-caption font-medium text-muted-foreground">@@ -224,7 +266,16 @@ function WakeupPanel({ wakeups, sessionId }: { wakeups: ChatWakeup[]; sessionId:{wakeups.length === 0 && (<div className="px-2 py-1.5 text-caption text-muted-foreground">{t(($) => $.wakeup.panel_empty)}</div>)}- {active.map((w) => <WakeupRow key={w.id} wakeup={w} sessionId={sessionId} now={now} />)}+ {active.map((w) => (+ <WakeupRow+ key={w.id}+ wakeup={w}+ sessionId={sessionId}+ now={now}+ editing={editingId === w.id}+ onEditingChange={(editing) => setEditingId(editing ? w.id : null)}+ />+ ))}{ended.length > 0 && (<div className="border-t border-surface-border pt-1"><div className="px-2 py-1 text-caption text-muted-foreground">{t(($) => $.wakeup.panel_ended)}</div>@@ -232,9 +283,6 @@ function WakeupPanel({ wakeups, sessionId }: { wakeups: ChatWakeup[]; sessionId:</div>)}</div>- <p className="shrink-0 border-t border-surface-border px-2 pt-2 pb-1 text-caption text-muted-foreground">- {t(($) => $.wakeup.limits_hint)}- </p></>);}diff --git a/packages/views/layout/panels/inbox-section.test.tsx b/packages/views/layout/panels/inbox-section.test.tsxindex c281cb260a..c58d5fdd47 100644--- a/packages/views/layout/panels/inbox-section.test.tsx+++ b/packages/views/layout/panels/inbox-section.test.tsx@@ -820,7 +820,8 @@ describe("InboxSection", () => {fireEvent.click(screen.getByRole("tab", { name: /^Snoozed/ }));expect(await screen.findByRole("link", { name: /^Ship the release notes/ })).toBeInTheDocument();expect(document.querySelector('[data-inbox-snoozed-row] [data-mc="status-icon"]')).not.toBeNull();- expect(apiMock.getIssue).not.toHaveBeenCalled();+ // The unread row above is warmed once idle; the snoozed issue itself is never fetched.+ expect(apiMock.getIssue.mock.calls.flat()).not.toContain("issue-z");});it("loads the archive when its tab is pointed at, so the click renders from cache", async () => {diff --git a/packages/views/locales/en/chat.json b/packages/views/locales/en/chat.jsonindex dc25adc1f3..8148ae33d6 100644--- a/packages/views/locales/en/chat.json+++ b/packages/views/locales/en/chat.json@@ -277,7 +277,6 @@"panel_title": "Wakeups","panel_empty": "No wakeups in this conversation","panel_ended": "Ended recently",- "limits_hint": "Every wakeup ends: waits last 24 hours by default and 7 days at most. If the deadline comes first, the agent comes back once to tell you where things stand.","strip_waiting": "Waiting: {{title}}","card": "Will report back: {{title}}","ends": "ends {{relative}}",@@ -288,6 +287,14 @@"cancel_failed": "Couldn't cancel the wakeup","retry": "Retry","retry_failed": "Couldn't retry the wakeup",+ "change_timing": "Change timing",+ "timing_interval": "Every",+ "timing_deadline": "Until",+ "timing_reminder": "Remind",+ "timing_keep": "No change",+ "timing_custom": "Custom",+ "timing_check_limit": "At most {{max}} checks",+ "timing_failed": "Couldn't change the timing","status": {"active": "Waiting","fired": "Reported back",diff --git a/packages/views/locales/es/chat.json b/packages/views/locales/es/chat.jsonindex 7d856eefea..b8c2fb4ed7 100644--- a/packages/views/locales/es/chat.json+++ b/packages/views/locales/es/chat.json@@ -277,7 +277,6 @@"panel_title": "Recordatorios","panel_empty": "No hay recordatorios en esta conversación","panel_ended": "Terminados recientemente",- "limits_hint": "Todo recordatorio termina: la espera dura 24 horas por defecto y 7 días como máximo. Si el plazo llega antes, el agente vuelve una vez para contarte cómo va todo.","strip_waiting": "Esperando: {{title}}","card": "Volverá a informar: {{title}}","ends": "termina {{relative}}",@@ -288,6 +287,14 @@"cancel_failed": "No se pudo cancelar el recordatorio","retry": "Reintentar","retry_failed": "No se pudo reintentar el aviso",+ "change_timing": "Cambiar horario",+ "timing_interval": "Cada",+ "timing_deadline": "Hasta",+ "timing_reminder": "Recordar",+ "timing_keep": "Sin cambios",+ "timing_custom": "Personalizado",+ "timing_check_limit": "Máximo {{max}} comprobaciones",+ "timing_failed": "No se pudo cambiar el horario","status": {"active": "Esperando","fired": "Informado",diff --git a/packages/views/locales/fr/chat.json b/packages/views/locales/fr/chat.jsonindex d81f05b736..488fcbbb25 100644--- a/packages/views/locales/fr/chat.json+++ b/packages/views/locales/fr/chat.json@@ -277,7 +277,6 @@"panel_title": "Réveils","panel_empty": "Aucun réveil dans cette conversation","panel_ended": "Terminés récemment",- "limits_hint": "Chaque réveil a une fin : l'attente dure 24 heures par défaut et 7 jours au maximum. Si l'échéance arrive d'abord, l'agent revient une fois pour vous dire où en sont les choses.","strip_waiting": "En attente : {{title}}","card": "Reviendra faire le point : {{title}}","ends": "se termine {{relative}}",@@ -288,6 +287,14 @@"cancel_failed": "Impossible d'annuler le réveil","retry": "Réessayer","retry_failed": "Impossible de relancer le réveil",+ "change_timing": "Modifier l'horaire",+ "timing_interval": "Toutes les",+ "timing_deadline": "Jusqu'à",+ "timing_reminder": "Rappel",+ "timing_keep": "Inchangé",+ "timing_custom": "Personnalisé",+ "timing_check_limit": "{{max}} vérifications au maximum",+ "timing_failed": "Impossible de modifier l'horaire","status": {"active": "En attente","fired": "Point fait",diff --git a/packages/views/locales/ja/chat.json b/packages/views/locales/ja/chat.jsonindex e63c1aaa44..7a2c6dfff4 100644--- a/packages/views/locales/ja/chat.json+++ b/packages/views/locales/ja/chat.json@@ -272,7 +272,6 @@"panel_title": "ウェイクアップ","panel_empty": "この会話にウェイクアップはありません","panel_ended": "最近終了",- "limits_hint": "ウェイクアップには必ず期限があります。待機は既定で 24 時間、最長 7 日です。先に期限が来た場合、エージェントは一度戻って現状を報告します。","strip_waiting": "待機中:{{title}}","card": "あとで報告:{{title}}","ends": "{{relative}}に期限",@@ -283,6 +282,14 @@"cancel_failed": "ウェイクアップをキャンセルできませんでした","retry": "再試行","retry_failed": "ウェイクアップを再試行できませんでした",+ "change_timing": "時間を変更",+ "timing_interval": "間隔",+ "timing_deadline": "期限",+ "timing_reminder": "通知",+ "timing_keep": "変更しない",+ "timing_custom": "カスタム",+ "timing_check_limit": "チェックは最大 {{max}} 回",+ "timing_failed": "時間を変更できませんでした","status": {"active": "待機中","fired": "報告済み",diff --git a/packages/views/locales/ko/chat.json b/packages/views/locales/ko/chat.jsonindex e2eddddf2f..54953ca0b0 100644--- a/packages/views/locales/ko/chat.json+++ b/packages/views/locales/ko/chat.json@@ -272,7 +272,6 @@"panel_title": "웨이크업","panel_empty": "이 대화에는 웨이크업이 없습니다","panel_ended": "최근 종료됨",- "limits_hint": "모든 웨이크업에는 끝이 있습니다. 기본 대기 시간은 24시간, 최대 7일입니다. 기한이 먼저 오면 에이전트가 한 번 돌아와 현재 상황을 알려 드립니다.","strip_waiting": "대기 중: {{title}}","card": "나중에 보고: {{title}}","ends": "{{relative}} 만료",@@ -283,6 +282,14 @@"cancel_failed": "웨이크업을 취소하지 못했습니다","retry": "다시 시도","retry_failed": "웨이크업을 다시 시도하지 못했습니다",+ "change_timing": "시간 변경",+ "timing_interval": "간격",+ "timing_deadline": "기한",+ "timing_reminder": "알림",+ "timing_keep": "변경 안 함",+ "timing_custom": "직접 지정",+ "timing_check_limit": "최대 {{max}}회 확인",+ "timing_failed": "시간을 변경하지 못했습니다","status": {"active": "대기 중","fired": "보고함",diff --git a/packages/views/locales/ru/chat.json b/packages/views/locales/ru/chat.jsonindex 6a0aa6796f..5d02cb26cc 100644--- a/packages/views/locales/ru/chat.json+++ b/packages/views/locales/ru/chat.json@@ -287,7 +287,6 @@"panel_title": "Напоминания","panel_empty": "В этом чате нет напоминаний","panel_ended": "Недавно завершённые",- "limits_hint": "У каждого напоминания есть срок: ожидание длится 24 часа по умолчанию и не дольше 7 дней. Если срок наступит раньше, агент вернётся один раз и расскажет, как обстоят дела.","strip_waiting": "Ожидание: {{title}}","card": "Вернётся с отчётом: {{title}}","ends": "истекает {{relative}}",@@ -298,6 +297,14 @@"cancel_failed": "Не удалось отменить напоминание","retry": "Повторить","retry_failed": "Не удалось повторить пробуждение",+ "change_timing": "Изменить время",+ "timing_interval": "Интервал",+ "timing_deadline": "До",+ "timing_reminder": "Напомнить",+ "timing_keep": "Без изменений",+ "timing_custom": "Своё время",+ "timing_check_limit": "Не больше {{max}} проверок",+ "timing_failed": "Не удалось изменить время","status": {"active": "Ожидание","fired": "Отчёт отправлен",diff --git a/packages/views/locales/zh-Hans/chat.json b/packages/views/locales/zh-Hans/chat.jsonindex d399ffb218..c377fcfd6f 100644--- a/packages/views/locales/zh-Hans/chat.json+++ b/packages/views/locales/zh-Hans/chat.json@@ -272,7 +272,6 @@"panel_title": "唤醒","panel_empty": "这个对话没有唤醒","panel_ended": "最近结束",- "limits_hint": "每个唤醒都会结束:等待默认 24 小时,最长 7 天。到期时如果还没等到,智能体会回来一次,告诉你目前的进展。","strip_waiting": "等待中:{{title}}","card": "会回来汇报:{{title}}","ends": "{{relative}}到期",@@ -283,6 +282,14 @@"cancel_failed": "无法取消唤醒","retry": "重试","retry_failed": "无法重试该唤醒",+ "change_timing": "修改时间",+ "timing_interval": "间隔",+ "timing_deadline": "截止",+ "timing_reminder": "提醒",+ "timing_keep": "不变",+ "timing_custom": "自定义",+ "timing_check_limit": "最多检查 {{max}} 次",+ "timing_failed": "无法修改时间","status": {"active": "等待中","fired": "已汇报",diff --git a/packages/views/locales/zh-Hant/chat.json b/packages/views/locales/zh-Hant/chat.jsonindex c470ac6111..543c122f6e 100644--- a/packages/views/locales/zh-Hant/chat.json+++ b/packages/views/locales/zh-Hant/chat.json@@ -272,7 +272,6 @@"panel_title": "喚醒","panel_empty": "這個對話沒有喚醒","panel_ended": "最近結束",- "limits_hint": "每個喚醒都會結束:等待預設 24 小時,最長 7 天。到期時如果還沒等到,Agent 會回來一次,告訴你目前的進展。","strip_waiting": "等待中:{{title}}","card": "會回來匯報:{{title}}","ends": "{{relative}}到期",@@ -283,6 +282,14 @@"cancel_failed": "無法取消喚醒","retry": "重試","retry_failed": "無法重試此喚醒",+ "change_timing": "修改時間",+ "timing_interval": "間隔",+ "timing_deadline": "截止",+ "timing_reminder": "提醒",+ "timing_keep": "不變",+ "timing_custom": "自訂",+ "timing_check_limit": "最多檢查 {{max}} 次",+ "timing_failed": "無法修改時間","status": {"active": "等待中","fired": "已回報",diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex 6d3c050326..a7c352a84f 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -2805,6 +2805,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busr.Get("/draft-restores", h.ListChatDraftRestores)r.Delete("/draft-restores/{restoreId}", h.ConsumeChatDraftRestore)r.Get("/wakeups", h.ListChatSessionWakeups)+ r.Patch("/wakeups/{wakeupId}", h.RescheduleChatSessionWakeup)r.Post("/wakeups/{wakeupId}/cancel", h.CancelChatSessionWakeup)r.Post("/wakeups/{wakeupId}/retry", h.RetryChatSessionWakeup)})diff --git a/server/internal/handler/chat_wakeup.go b/server/internal/handler/chat_wakeup.goindex 4adde89895..20c5d4bdd0 100644--- a/server/internal/handler/chat_wakeup.go+++ b/server/internal/handler/chat_wakeup.go@@ -313,6 +313,26 @@ func (h *Handler) CancelChatSessionWakeup(w http.ResponseWriter, r *http.RequestwriteJSON(w, http.StatusOK, chatWakeupToResponse(ended))}+// RescheduleChatSessionWakeup changes when an active wakeup runs: a reminder's+// time, a check's interval or deadline, or a condition's deadline.+func (h *Handler) RescheduleChatSessionWakeup(w http.ResponseWriter, r *http.Request) {+ sessionID, id, ok := h.chatSessionWakeupForUser(w, r)+ if !ok {+ return+ }+ var timing service.ChatWakeupTiming+ if err := json.NewDecoder(r.Body).Decode(&timing); err != nil {+ writeError(w, http.StatusBadRequest, "invalid request body")+ return+ }+ updated, err := h.chatWakeups().Reschedule(r.Context(), sessionID, id, timing)+ if err != nil {+ chatWakeupError(w, err)+ return+ }+ writeJSON(w, http.StatusOK, chatWakeupToResponse(updated))+}+// RetryChatSessionWakeup re-runs a wakeup whose report turn failed.func (h *Handler) RetryChatSessionWakeup(w http.ResponseWriter, r *http.Request) {sessionID, id, ok := h.chatSessionWakeupForUser(w, r)diff --git a/server/internal/handler/chat_wakeup_test.go b/server/internal/handler/chat_wakeup_test.goindex 0990ecfb31..901f93ce30 100644--- a/server/internal/handler/chat_wakeup_test.go+++ b/server/internal/handler/chat_wakeup_test.go@@ -66,6 +66,42 @@ func TestCancelChatSessionWakeup_RequesterOrSessionOwner(t *testing.T) {}}+// Changing a wakeup's timing follows the cancel rule: the requester or the+// session's owner, nobody else, and only while it is active.+func TestRescheduleChatSessionWakeup(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ agentID := createHandlerTestAgent(t, "ChatWakeupRescheduleAgent", []byte("[]"))+ sessionID := createHandlerTestChatSession(t, agentID)+ suffix := time.Now().UnixNano()+ requester := createWorkspaceMemberUser(t, "Reschedule requester", fmt.Sprintf("reschedule-requester-%[email protected]", suffix))+ bystander := createWorkspaceMemberUser(t, "Reschedule bystander", fmt.Sprintf("reschedule-bystander-%[email protected]", suffix))+ wakeupID := seedChatWakeup(t, sessionID, agentID, requester)++ reschedule := func(userID string, body map[string]any) *testutil.Response {+ t.Helper()+ req := newRequestAs(userID, http.MethodPatch, "/api/chat/sessions/"+sessionID+"/wakeups/"+wakeupID, body)+ req = withURLParams(req, "sessionId", sessionID, "wakeupId", wakeupID)+ return testutil.Call(t, testHandler.RescheduleChatSessionWakeup, withChatTestWorkspaceCtx(t, req))+ }+ at := time.Now().UTC().Truncate(time.Second).Add(3 * time.Hour)+ reschedule(bystander, map[string]any{"at": at}).Want(http.StatusForbidden)+ reschedule(requester, map[string]any{"at": time.Now().Add(-time.Minute)}).Want(http.StatusBadRequest)+ reschedule(requester, map[string]any{"interval_seconds": 900}).Want(http.StatusBadRequest)+ for i, userID := range []string{requester, testUserID} {+ want := at.Add(time.Duration(i) * time.Hour)+ var updated ChatWakeupResponse+ reschedule(userID, map[string]any{"at": want}).Want(http.StatusOK).JSON(&updated)+ got, err := time.Parse(time.RFC3339, *updated.FireAt)+ if updated.Title != "Release shipped" || err != nil || !got.Equal(want) {+ t.Fatalf("rescheduled reminder = %+v, want fire_at %v", updated, want)+ }+ }+ cancelChatWakeupAs(t, testUserID, sessionID, wakeupID)+ reschedule(requester, map[string]any{"at": at}).Want(http.StatusConflict)+}+// chat_wakeup has no chat_session FK, so DeleteChatSession prunes it.func TestDeleteChatSession_PrunesChatWakeups(t *testing.T) {if testHandler == nil {diff --git a/server/internal/service/chat_wakeup.go b/server/internal/service/chat_wakeup.goindex 19b3f0c140..5cad6a0636 100644--- a/server/internal/service/chat_wakeup.go+++ b/server/internal/service/chat_wakeup.go@@ -416,6 +416,105 @@ func (s *ChatWakeupService) Update(ctx context.Context, task db.AgentTaskQueue,return updated, nil}+// ChatWakeupTiming is a member's change to when an active wakeup runs. A+// reminder takes At; a check IntervalSeconds and/or ExpiresAt; a condition+// ExpiresAt. A field left out keeps its current value.+type ChatWakeupTiming struct {+ At *time.Time `json:"at,omitempty"`+ IntervalSeconds int64 `json:"interval_seconds,omitempty"`+ ExpiresAt *time.Time `json:"expires_at,omitempty"`+}++// input merges the change into the wakeup's current timing, so the agent's+// limits in plan apply to the result unchanged.+func (t ChatWakeupTiming) input(current db.ChatWakeup) (ChatWakeupInput, error) {+ in := ChatWakeupInput{ExpiresAt: t.ExpiresAt}+ switch current.Kind {+ case "at":+ if t.At == nil || t.IntervalSeconds != 0 || t.ExpiresAt != nil {+ return in, chatWakeupInputError("a reminder takes a new time and nothing else")+ }+ in.At = t.At+ case "check":+ if t.At != nil || (t.IntervalSeconds == 0 && t.ExpiresAt == nil) {+ return in, chatWakeupInputError("a check takes a new interval, a new deadline, or both")+ }+ in.IntervalSeconds = t.IntervalSeconds+ if in.IntervalSeconds == 0 {+ in.IntervalSeconds = current.IntervalSeconds.Int64+ }+ case "condition":+ if t.At != nil || t.IntervalSeconds != 0 || t.ExpiresAt == nil {+ return in, chatWakeupInputError("a condition takes a new deadline and nothing else")+ }+ in.Condition = current.Condition+ default:+ return in, chatWakeupInputError("this wakeup's timing cannot be changed")+ }+ if current.Kind != "at" && in.ExpiresAt == nil {+ deadline := current.ExpiresAt.Time+ in.ExpiresAt = &deadline+ }+ return in, nil+}++// Reschedule changes when an active wakeup runs without a turn of the agent.+// The title, instruction, condition, its baseline and the check history stay+// as they are.+func (s *ChatWakeupService) Reschedule(ctx context.Context, sessionID, id pgtype.UUID, timing ChatWakeupTiming) (db.ChatWakeup, error) {+ now := s.clock()+ var updated db.ChatWakeup+ err := s.inTx(ctx, func(_ pgx.Tx, qtx *db.Queries) error {+ current, err := qtx.LockChatWakeupInSession(ctx, db.LockChatWakeupInSessionParams{ID: id, ChatSessionID: sessionID})+ if errors.Is(err, pgx.ErrNoRows) {+ return ErrChatWakeupNotFound+ }+ if err != nil {+ return err+ }+ if current.Status != "active" {+ return ErrChatWakeupEnded+ }+ in, err := timing.input(current)+ if err != nil {+ return err+ }+ plan, err := in.plan(now)+ if err != nil {+ return err+ }+ next := plan.nextEval+ if current.Kind == "condition" || (current.Kind == "check" && timing.IntervalSeconds == 0) {+ // Only the deadline moved: the next evaluation stays where it was,+ // unless the new deadline comes first.+ next = current.NextEvalAt.Time+ if next.After(plan.expiresAt) {+ next = plan.expiresAt+ }+ }+ updated, err = qtx.UpdateChatWakeupConfig(ctx, db.UpdateChatWakeupConfigParams{+ ID: id,+ Title: current.Title,+ Instruction: current.Instruction,+ Condition: current.Condition,+ ConditionState: current.ConditionState,+ IntervalSeconds: plan.interval,+ FireAt: plan.fireAt,+ NextEvalAt: pgtype.Timestamptz{Time: next, Valid: true},+ ExpiresAt: pgtype.Timestamptz{Time: plan.expiresAt, Valid: true},+ })+ if errors.Is(err, pgx.ErrNoRows) {+ return ErrChatWakeupEnded+ }+ return err+ })+ if err != nil {+ return db.ChatWakeup{}, err+ }+ s.publish(ctx, updated, pgtype.UUID{})+ return updated, nil+}+// Cancel ends an active wakeup. by is "user" or "agent".func (s *ChatWakeupService) Cancel(ctx context.Context, sessionID, id pgtype.UUID, by string) (db.ChatWakeup, error) {return s.end(ctx, sessionID, id, "cancelled", "cancelled_by_"+by)diff --git a/server/internal/service/chat_wakeup_test.go b/server/internal/service/chat_wakeup_test.goindex 0a9ea0f0f0..f5de560976 100644--- a/server/internal/service/chat_wakeup_test.go+++ b/server/internal/service/chat_wakeup_test.go@@ -582,3 +582,95 @@ func TestChatWakeupFinishedCheckWhoseReportFailedCanRetry(t *testing.T) {t.Fatalf("retry of a finished check must ask for the report, not another check:\n%s", input.Content)}}++func TestChatWakeupRescheduleCheckKeepsWhatItDoesNotChange(t *testing.T) {+ f := newChatWakeupFixture(t)+ ctx := t.Context()+ w := f.create(t, ChatWakeupInput{IntervalSeconds: 1800, ExpiresInSeconds: 6 * 3600})+ f.fx.Exec(t, "UPDATE chat_wakeup SET check_count = 6, last_check_note = 'Still building' WHERE id = $1", w.ID)+ // Postgres keeps microseconds; Linux clocks carry nanoseconds.+ f.at(f.clock.Add(321 * time.Nanosecond))+ near := func(got, want time.Time) bool { return got.Sub(want).Abs() < time.Millisecond }++ // Interval only: the deadline stays, the next check restarts from now.+ f.at(f.clock.Add(5 * time.Minute))+ updated, err := f.svc.Reschedule(ctx, w.ChatSessionID, w.ID, ChatWakeupTiming{IntervalSeconds: 600})+ if err != nil {+ t.Fatal(err)+ }+ if updated.IntervalSeconds.Int64 != 600 || !near(updated.ExpiresAt.Time, w.ExpiresAt.Time) ||+ !near(updated.NextEvalAt.Time, f.clock.Add(10*time.Minute)) ||+ updated.CheckCount != 6 || updated.LastCheckNote.String != "Still building" || updated.Title != w.Title {+ t.Fatalf("interval change: %+v", updated)+ }++ // Deadline only: the next check stays where it was.+ deadline := f.clock.Add(2 * time.Hour)+ updated, err = f.svc.Reschedule(ctx, w.ChatSessionID, w.ID, ChatWakeupTiming{ExpiresAt: &deadline})+ if err != nil {+ t.Fatal(err)+ }+ if updated.IntervalSeconds.Int64 != 600 || !near(updated.ExpiresAt.Time, deadline) || !near(updated.NextEvalAt.Time, f.clock.Add(10*time.Minute)) {+ t.Fatalf("deadline change: %+v", updated)+ }++ // The agent's limits apply: 10-minute checks for a day is 144 checks.+ far := f.clock.Add(24 * time.Hour)+ if _, err := f.svc.Reschedule(ctx, w.ChatSessionID, w.ID, ChatWakeupTiming{ExpiresAt: &far}); !errors.Is(err, ErrChatWakeupInput) {+ t.Fatalf("schedule over the check limit: %v", err)+ }+ if _, err := f.svc.Reschedule(ctx, w.ChatSessionID, w.ID, ChatWakeupTiming{IntervalSeconds: 60}); !errors.Is(err, ErrChatWakeupInput) {+ t.Fatalf("interval under the minimum: %v", err)+ }+ reminder := f.clock.Add(time.Hour)+ if _, err := f.svc.Reschedule(ctx, w.ChatSessionID, w.ID, ChatWakeupTiming{At: &reminder}); !errors.Is(err, ErrChatWakeupInput) {+ t.Fatalf("reminder time on a check: %v", err)+ }+ if len(f.events) == 0 || f.events[len(f.events)-1].WakeupID != util.UUIDToString(w.ID) {+ t.Fatalf("reschedule was not published: %+v", f.events)+ }+}++func TestChatWakeupRescheduleReminderAndCondition(t *testing.T) {+ f := newChatWakeupFixture(t)+ ctx := t.Context()+ // Postgres keeps microseconds; Linux clocks carry nanoseconds.+ f.at(f.clock.Add(321 * time.Nanosecond))+ near := func(got, want time.Time) bool { return got.Sub(want).Abs() < time.Millisecond }++ at := f.clock.Add(2 * time.Hour)+ reminder := f.create(t, ChatWakeupInput{At: &at})+ later := f.clock.Add(20 * time.Hour)+ updated, err := f.svc.Reschedule(ctx, reminder.ChatSessionID, reminder.ID, ChatWakeupTiming{At: &later})+ if err != nil {+ t.Fatal(err)+ }+ if !near(updated.FireAt.Time, later) || !near(updated.NextEvalAt.Time, later) || !near(updated.ExpiresAt.Time, later) {+ t.Fatalf("moved reminder: %+v", updated)+ }+ past := f.clock.Add(-time.Minute)+ if _, err := f.svc.Reschedule(ctx, reminder.ChatSessionID, reminder.ID, ChatWakeupTiming{At: &past}); !errors.Is(err, ErrChatWakeupInput) {+ t.Fatalf("reminder in the past: %v", err)+ }++ issue := f.fx.Issue(t, "Watch the release")+ cond, _ := json.Marshal(map[string]any{"type": "issue", "issue_id": issue, "state": "done"})+ watch := f.create(t, ChatWakeupInput{Condition: cond})+ f.fx.Exec(t, "UPDATE chat_wakeup SET condition_state = 'baseline' WHERE id = $1", watch.ID)+ deadline := f.clock.Add(3 * 24 * time.Hour)+ updated, err = f.svc.Reschedule(ctx, watch.ChatSessionID, watch.ID, ChatWakeupTiming{ExpiresAt: &deadline})+ if err != nil {+ t.Fatal(err)+ }+ if string(updated.Condition) != string(watch.Condition) || updated.ConditionState != "baseline" ||+ !updated.NextEvalAt.Time.Equal(watch.NextEvalAt.Time) || !near(updated.ExpiresAt.Time, deadline) {+ t.Fatalf("condition deadline change: %+v", updated)+ }+ tooFar := f.clock.Add(8 * 24 * time.Hour)+ if _, err := f.svc.Reschedule(ctx, watch.ChatSessionID, watch.ID, ChatWakeupTiming{ExpiresAt: &tooFar}); !errors.Is(err, ErrChatWakeupInput) {+ t.Fatalf("wait past 7 days: %v", err)+ }+ if _, err := f.svc.Reschedule(ctx, watch.ChatSessionID, watch.ID, ChatWakeupTiming{IntervalSeconds: 900}); !errors.Is(err, ErrChatWakeupInput) {+ t.Fatalf("interval on a condition: %v", err)+ }+}