A local-first multi-agent app development platform, built on PenguinHarness
fix(web): 新对话的第一条消息发不出去时,原因留在输入卡下面,不再只活六秒
lmliheng7c14ffa22497
diff --git a/changelog/unreleased/2026-11-07-draft-send-refusal.md b/changelog/unreleased/2026-11-07-draft-send-refusal.mdnew file mode 100644index 00000000..911e2083--- /dev/null+++ b/changelog/unreleased/2026-11-07-draft-send-refusal.md@@ -0,0 +1,66 @@+# A draft's first message that could not go out says why under the input card, not in a six-second toast++- **Date:** 2026-11-07+- **Type:** fix+- **Scope:** `web`+- **Breaking:** no++[中文](2026-11-07-draft-send-refusal.zh.md)++The new-chat screen (a draft, before any Session exists) makes exactly one write: pressing Send+creates the Session and posts its first task. When either half is refused, nothing is persisted —+an empty Session the first half already created is deleted again — the message and the staged+files stay in the composer, and the Send button is the retry. What the reader got was a+notification over the card that dismissed itself after six seconds: afterwards the screen read+exactly as it had before the press, with the button back to normal and nothing saying why the+message never left.++That sentence now renders under the input card (`role="alert"`, danger colour, two lines, the+whole sentence on hover) and stays until the next attempt starts — the next press is the retry, and+it clears the sentence of the attempt before it.++## Whose words++The reason comes from the value the send threw, by the app-wide rule the confirmation dialogs'+refusal slots and 7.89–7.93 use:++- the server answered → `apiErrorText`, whose code carries the interface's own sentence, with the+ draft's model id for the one copy that needs it (`model_credential_missing` — the response body+ names no model);+- nothing answered (the connection dropped, the request never left) → `refusalText`' rule, keeping+ what the value itself has to say rather than flattening it to the generic text.++## Details++- `packages/web/src/features/chat/first-send-refusal.ts` (new): `sendRefusalReason(err, modelId)`+ picks the reason (the pure part, testable without the page) and `sendRefused(reason)` builds the+ sentence.+- `packages/web/src/features/chat/draft-view.tsx`: the page keeps `sendRefusal`; `onSend` clears it+ when an attempt starts and writes it in the catch instead of raising a toast, and the sentence is+ drawn between the input card and the ownership pills.+- `packages/web/src/lib/strings{,-en}.ts`: one new sentence, `chat.draftSendRefused(reason)`.++**Deliberately unchanged:** the thinking-level picker on the same page still reports a refused+write through a notification — it lives in the shared composer (`chat-input.tsx`) together with the+same family on a Session, so it wants its own round rather than this one. The success path (create,+post, navigate) is untouched, as is every other page's send.++## Tests++- `packages/web/test/first-send-refusal.test.ts` (new, 7 cases): a server answer reads through the+ code's sentence and never the English wire message; the model the draft was aimed at is named for+ a missing credential; a send that never reached the route keeps its own words; a value with+ nothing to say falls back to the generic text; the sentence speaks the active language.+- `packages/web/e2e/draft-send-refusal.spec.mjs` (new, real server + real browser, 2 cases, both+ writes stubbed to a 500 with a code the interface translates plus an English wire message): a+ refused session creation puts the sentence under the card, uses the interface's words, leaves the+ notification region out of it, keeps the composer's text and the Send button enabled — **seven+ seconds later** (past the six an error notification lives) it is still there, and a retry that+ lands navigates into the new conversation with the sentence gone. The second case refuses the+ first task after the Session was created: the same sentence, the draft still on `/chat/new`, and+ that empty Session gone (`GET` answers 404), so resending does not pile them up.++## Compatibility++No interface change, no new dependency, no Project config change. Only the failure path of the+draft's send is affected.diff --git a/changelog/unreleased/2026-11-07-draft-send-refusal.zh.md b/changelog/unreleased/2026-11-07-draft-send-refusal.zh.mdnew file mode 100644index 00000000..8923cc3d--- /dev/null+++ b/changelog/unreleased/2026-11-07-draft-send-refusal.zh.md@@ -0,0 +1,52 @@+# 新对话的第一条消息发不出去时,原因留在输入卡下面,不再只活六秒++- **日期:** 2026-11-07+- **类型:** 修复+- **范围:** `web`+- **破坏性:** 无++[English](2026-11-07-draft-send-refusal.md)++新建对话页(还没有 Session 的草稿)只做一次写入:按「发送」会建出这个 Session 并投出它的第一条+任务。这两半里任何一半被拒,什么都没落盘 —— 前一半已经建出来的空 Session 会被删掉 —— 消息与暂存+的文件仍留在输入框里,发送按钮就是重试。而读者拿到的是输入卡上方一条六秒后自己消失的通知:过了那+六秒,屏幕与按下之前一模一样,按钮恢复常态,却没说这条消息为什么没出去。++那句话现在画在**输入卡下面**(`role="alert"`、危险色、限两行、整句挂悬停),留到下一次尝试开始 ——+下一次按发送就是重试,它会把上一次的那句话清掉。++## 念的是谁的话++原因取自发送抛出的那个值,按全仓同一条规则(确认框的拒绝槽位与 7.89–7.93 用的就是它):++- 服务端答复了 → `apiErrorText`,由错误码给出界面自己的句子;唯一需要上下文的那条+ (`model_credential_missing`,响应体里没有模型名)由草稿选中的模型补上;+- 什么都没答复(连接断了、请求根本没发出去)→ `refusalText` 的规则,留着它自己要说的话,而不是+ 一律压成「未知错误」。++## 细节++- `packages/web/src/features/chat/first-send-refusal.ts`(新):`sendRefusalReason(err, modelId)`+ 挑出原因(纯逻辑,不依赖页面就能测),`sendRefused(reason)` 造出那句话。+- `packages/web/src/features/chat/draft-view.tsx`:页面多一个 `sendRefusal`;`onSend` 在尝试开始时+ 清掉它、失败时写上它(不再走通知),句子画在输入卡与归属药丸之间。+- `packages/web/src/lib/strings{,-en}.ts`:一条新文案 `chat.draftSendRefused(reason)`。++**有意不改的**:同一页的思考等级选择器写不进去时仍走通知 —— 它在共用的输入组件+(`chat-input.tsx`)里,与 Session 上同族的那一片是一件事,该单独一轮。成功那条路(建会话、发任务、+跳转)与其他页面的发送一个字没动。++## 测试++- `packages/web/test/first-send-refusal.test.ts`(新,7 条):服务端的答复念错误码自己的句子、绝不+ 念线上英文原文;缺密钥时点名草稿选中的模型;请求根本没到路由时留着它自己的话;什么都没说时退回+ 通用文案;句子跟着界面语言走。+- `packages/web/e2e/draft-send-refusal.spec.mjs`(新,真服务端 + 真浏览器,2 条,两处写入都桩成 500+ 并带一个界面有文案的错误码与一句英文原文):建会话被拒时句子出现在卡片下面、念的是界面的话、通知+ 区里没有它、输入框里的文字还在、发送按钮仍可用;**七秒后**(超过错误通知活着的 6 秒)仍在;放行后+ 重按落到新会话、句子消失。第二条:会话建出来、第一条任务被拒 —— 同一句话,仍停在草稿页,那个空+ Session 已被删掉(`GET` 答 404),重复发送不会把它们堆起来。++## 兼容性++不改接口、无新依赖、不动项目配置。只影响草稿页发送的失败路径。diff --git a/packages/web/e2e/draft-send-refusal.spec.mjs b/packages/web/e2e/draft-send-refusal.spec.mjsnew file mode 100644index 00000000..201b8d64--- /dev/null+++ b/packages/web/e2e/draft-send-refusal.spec.mjs@@ -0,0 +1,138 @@+/**+ * Regression: a draft's first message that does not go out keeps the reason under the input card+ * instead of in a notification that dismisses itself after six seconds.+ *+ * Sending from /chat/new is the page's only write: it creates the Session and posts its first+ * task, and when either half is refused nothing is persisted — an empty Session the first half+ * created is deleted again — while the text and the staged files stay in the composer, whose send+ * button is the retry. What used to be missing was the reason: it arrived as a toast over the+ * card, was gone six seconds later, and the screen then read exactly as it had before the press.+ * The sentence is drawn under the card now (`role="alert"`, danger colour, two lines, the whole+ * sentence on hover) and stays until the next attempt starts.+ *+ * Both writes are stubbed (a 500 carrying a code the interface has its own copy for, plus an+ * English wire message — that is how the tests tell the localized sentence from the raw one);+ * everything else stays real, including the Session the second case creates and deletes.+ */+import { test, expect } from "@playwright/test";+import { provisionAndLogin } from "./auth.mjs";++const BASE = process.env.BASE_URL;+const MOCK = process.env.MOCK_URL;++/** The refusal: a code the interface translates, plus a message that must not reach the page. */+const REFUSAL = { code: "internal", message: "RAW ENGLISH SERVER MESSAGE" };+/** The line the page draws for that code (S.errors.byCode), after what failed. */+const REASON = "服务器内部错误,请稍后重试。";+const MESSAGE = "第一条消息:这条发不出去";++const notifications = (page) => page.getByRole("region", { name: "通知" });+const refusalLine = (page) => page.getByRole("alert").filter({ hasText: "没能发出这条消息" });+const sendButton = (page) => page.getByRole("button", { name: "发送" });++/**+ * Provision a user, give the Project a model (without one the onboarding overlay covers the draft+ * page), and open /chat/new with a message typed into the composer. No model is ever called: the+ * writes measured here are stubbed.+ */+async function openDraft(page, userId) {+ await provisionAndLogin(page.request, userId, "password123");+ const projects = await (await page.request.get(`${BASE}/api/projects`)).json();+ const projectId = projects.projects[0].projectId;+ const models = await page.request.put(`${BASE}/api/projects/${projectId}/models`, {+ data: {+ defaultModel: { provider: "custom", modelId: "claude-4-8" },+ models: [+ {+ provider: "custom",+ modelId: "claude-4-8",+ apiKey: "sk-mock",+ baseUrl: MOCK,+ contextWindow: 200000,+ },+ ],+ },+ });+ expect(models.ok(), "put models").toBeTruthy();++ await page.goto(`${BASE}/chat/new`);+ const box = page.locator("textarea");+ await expect(box).toBeVisible();+ await box.fill(MESSAGE);+ return { projectId, box };+}++/** What one refusal looks like on the page, at the moment it lands and past the six seconds. */+async function expectRefusalKept(page) {+ const line = refusalLine(page);+ await expect(line).toBeVisible();+ await expect(line).toHaveText(`没能发出这条消息:${REASON}`);+ // The interface's own words for that code, never the server's English message.+ await expect(line).not.toContainText("RAW ENGLISH");+ // The reason is the card's, not a notification's.+ await expect(notifications(page)).not.toContainText("RAW ENGLISH");++ // Past the six seconds an error notification lived: the sentence is still under the card.+ await page.waitForTimeout(7000);+ await expect(line).toBeVisible();+ await expect(line).toHaveText(`没能发出这条消息:${REASON}`);+ return line;+}++test("a refused first send keeps the reason under the card, past six seconds", async ({ page }) => {+ const { box } = await openDraft(page, "draftsendrefusal");+ const writes = [];+ let refuse = true;+ await page.route("**/api/projects/*/agents/*/sessions", async (route) => {+ if (route.request().method() !== "POST") return route.fallback();+ writes.push(route.request().postDataJSON());+ if (!refuse) return route.fallback();+ return route.fulfill({+ status: 500,+ contentType: "application/json",+ body: JSON.stringify({ error: REFUSAL }),+ });+ });++ await sendButton(page).click();+ await expectRefusalKept(page);++ // Nothing was written, so the card still holds the message and the button that retries it.+ await expect(box).toHaveValue(MESSAGE);+ await expect(sendButton(page)).toBeEnabled();++ // The retry is the same button: the sentence of the attempt before it goes, and this one lands.+ refuse = false;+ await sendButton(page).click();+ await page.waitForURL(/\/chat\/session-/);+ await expect(page.getByRole("alert")).toHaveCount(0);+ expect(writes).toHaveLength(2);+});++test("a first message refused after the Session was created leaves the reason and no empty Session", async ({+ page,+}) => {+ const { box } = await openDraft(page, "draftsendrefusal2");+ let createdId = null;+ await page.route("**/api/sessions/*/tasks", async (route) => {+ if (route.request().method() !== "POST") return route.fallback();+ createdId = new URL(route.request().url()).pathname.split("/")[3];+ return route.fulfill({+ status: 500,+ contentType: "application/json",+ body: JSON.stringify({ error: REFUSAL }),+ });+ });++ await sendButton(page).click();+ await expectRefusalKept(page);+ await expect(box).toHaveValue(MESSAGE);++ // The Session the first half created is deleted again: resending must not pile up empty ones.+ await expect+ .poll(() => page.request.get(`${BASE}/api/sessions/${createdId}`).then((r) => r.status()))+ .toBe(404);+ // Still a draft: nobody was taken to a conversation that never got its message.+ await expect(page).toHaveURL(/\/chat\/new$/);+ await expect(sendButton(page)).toBeEnabled();+});diff --git a/packages/web/src/features/chat/draft-view.tsx b/packages/web/src/features/chat/draft-view.tsxindex 8d3dd12b..316d4535 100644--- a/packages/web/src/features/chat/draft-view.tsx+++ b/packages/web/src/features/chat/draft-view.tsx@@ -59,6 +59,7 @@ import { UNCONFINED, draftSandboxAfter } from "../../lib/permission-level";import type { PermissionPick } from "../../lib/permission-level";import { formatMonthDay } from "../../lib/format";import { apiErrorText } from "../../lib/api-error";+import { sendRefusalReason, sendRefused } from "./first-send-refusal";import { rememberSessionMachine } from "../../lib/session-machines";import { cachedMachineAgents, rememberMachineAgents } from "../../lib/machine-cache";import { useAuth } from "../../state/auth";@@ -93,6 +94,7 @@ import { effectiveThinkingLevel } from "./thinking-level";import { WorkspaceSelect, pillClass } from "./workspace-select";import { FilesPanelToggle } from "./dock-toggles";import { sameModelRef } from "../models/model-grouping";+import { toneInk } from "../../lib/tone";/** Coalescing window for writing body text to the cache: keystrokes are frequent, so a short batch accumulates before persisting (option changes are still written immediately). */const DRAFT_SAVE_DEBOUNCE_MS = 300;@@ -738,6 +740,13 @@ export function DraftView({// a racing navigation. A ref rather than state — the composer disables its own send button// off its `busy` state, and nothing else on this page renders differently mid-send.const sendingRef = useRef(false);+ /**+ * The reason this draft's last send did not go out. Sending is the page's only write, and a+ * refusal changes nothing else on screen: the text stays in the card, the send button is the+ * retry — so the sentence belongs right under the card instead of in a notification that lives+ * six seconds (first-send-refusal.ts). Cleared when the next attempt starts.+ */+ const [sendRefusal, setSendRefusal] = useState<string | null>(null);// Whether this draft's page is still the one open: the first send's round trips can outlast// it, and a new draft of the same Project would reuse its dock scope.const openRef = useRef(true);@@ -750,11 +759,14 @@ export function DraftView({// First message sent: only now is the Session created (Agent / Workspace / Model / approval// mode are all locked in together), then the route jumps once sent; returns false on any- // failure, so the input area keeps the draft and can resend.+ // failure, so the input area keeps the draft and can resend — with the reason left under the+ // card by the catch below.const onSend = useCallback(async (input: TaskInputPart[], goal: { budget: number } | null = null): Promise<boolean> => {if (!agentId || sendingRef.current) return false;sendingRef.current = true;+ // This attempt's own reason, not the one the attempt before it left (one attempt, one reason).+ setSendRefusal(null);// The draft's own docks, named now: the send takes round trips, and the user may be on// another conversation by the time it has a Session to hand them to.const dockScope = currentDockScope();@@ -802,7 +814,9 @@ export function DraftView({// this empty Session, otherwise every resend attempt would create another one, piling up// empty sessions with no messages in the sidebar (best-effort cleanup).if (createdId) void api.deleteSession(createdId).catch(() => undefined);- toastError(apiErrorText(e, modelRef ? { modelId: modelRef.modelId } : {}));+ // Nothing was written and the card still holds the message: the reason stays under it,+ // where the send button that retries is (see the `sendRefusal` state).+ setSendRefusal(sendRefused(sendRefusalReason(e, modelRef?.modelId)));return false;} finally {sendingRef.current = false;@@ -916,6 +930,21 @@ export function DraftView({onTextChange={onTextChange}/>+ {/* The first message did not go out: nothing was written (an empty Session is deleted+ again), the text and the staged files are still in the card above, and the send button+ is the retry — so the reason stays right here, under what it is about. */}+ {sendRefusal !== null && (+ <p+ role="alert"+ data-testid="draft-send-refusal"+ data-tooltip={sendRefusal}+ data-tooltip-content="text"+ className={`mt-2 line-clamp-2 break-words text-xs ${toneInk.danger}`}+ >+ {sendRefusal}+ </p>+ )}+{/* Ownership selection right below the card (small pill dropdowns, styled after ChatGPT's project picker button) */}<div className="mt-2 flex flex-wrap items-center gap-2"><AgentSelectdiff --git a/packages/web/src/features/chat/first-send-refusal.ts b/packages/web/src/features/chat/first-send-refusal.tsnew file mode 100644index 00000000..12e975b3--- /dev/null+++ b/packages/web/src/features/chat/first-send-refusal.ts@@ -0,0 +1,33 @@+/**+ * The first message a draft could not get out — the only write /chat/new makes — and the sentence+ * the page leaves under the input card afterwards.+ *+ * Sending from a draft creates the Session and posts its first task in one go. When either half+ * is refused nothing is persisted (an empty Session the first half created is deleted again), the+ * typed text and the staged files stay in the composer, and the send button is the retry. What the+ * reader used to get was a notification over the card that dismissed itself after six seconds:+ * afterwards the screen read exactly as it had before the press, with the words explaining why+ * gone.+ *+ * Whose words, when the send threw two different kinds of value:+ * - the server answered → `apiErrorText`, whose code carries the interface's own sentence, and+ * which needs the model the draft was aimed at for `model_credential_missing` (the body names+ * no model);+ * - nothing answered (the connection dropped, the request never left) → 7.19's rule, keeping what+ * the value itself has to say rather than flattening it to the generic text.+ * The same pair the confirmation dialogs' refusal slots and 7.89–7.93 use.+ */+import { ApiError } from "../../api/client";+import { apiErrorText, refusalText } from "../../lib/api-error";+import { S } from "../../lib/strings";++/** The reason out of whatever the send threw, with the model the draft was aimed at (if any). */+export function sendRefusalReason(err: unknown, modelId?: string): string {+ if (err instanceof ApiError) return apiErrorText(err, modelId !== undefined ? { modelId } : {});+ return refusalText(err);+}++/** The sentence: what could not be sent, then why. */+export function sendRefused(reason: string): string {+ return S.chat.draftSendRefused(reason);+}diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.tsindex a05711fa..57180279 100644--- a/packages/web/src/lib/strings-en.ts+++ b/packages/web/src/lib/strings-en.ts@@ -3426,6 +3426,8 @@ export const en: Strings = {machineTag: (machine: string) => `[SSH: ${machine}]`,newSessionInWorkspace: "New chat in this workspace",draftSubtitle: "The self-evolving agent that excels at AI development tasks",+ /** The draft's first message did not go out: nothing was written, the text is still in the card. */+ draftSendRefused: (reason: string) => `Could not send this message: ${reason}`,/** Second tooltip line on a shortcut row: the click fills the composer, it does not send. */shortcutFillHint: "Click to fill the composer — edit it if you like, then send",/** The draft screen's saved-prompt folder: prompts the user wrote and saved, stored per user on the server. */diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.tsindex b52b79e8..74f1c613 100644--- a/packages/web/src/lib/strings.ts+++ b/packages/web/src/lib/strings.ts@@ -3495,6 +3495,8 @@ export const zh = {machineTag: (machine: string) => `[SSH: ${machine}]`,newSessionInWorkspace: "在此工作区新建对话",draftSubtitle: "最擅长 AI 开发任务的自进化 Agent",+ /** The draft's first message did not go out: nothing was written, the text is still in the card. */+ draftSendRefused: (reason: string) => `没能发出这条消息:${reason}`,/** Second tooltip line on a shortcut row: the click fills the composer, it does not send. */shortcutFillHint: "点击填入输入框,可修改后自行发送",/** The draft screen's saved-prompt folder: prompts the user wrote and saved, stored per user on the server. */diff --git a/packages/web/test/first-send-refusal.test.ts b/packages/web/test/first-send-refusal.test.tsnew file mode 100644index 00000000..df65e06e--- /dev/null+++ b/packages/web/test/first-send-refusal.test.ts@@ -0,0 +1,68 @@+/**+ * A draft's first message that did not go out (src/features/chat/first-send-refusal.ts): which+ * words the sentence under the input card uses.+ *+ * The card keeps the message and its send button is the retry, so the sentence is what says why+ * the press changed nothing — after six seconds a notification would have said nothing at all.+ * Two things it must get right: a server answer speaks the interface's language (with the model's+ * name where the copy needs it), and a send that never reached the route keeps what it knows+ * instead of flattening to the generic text (7.19's rule).+ */+import { afterEach, describe, expect, it } from "vitest";+import { ApiError } from "../src/api/client";+import { en as EN } from "../src/lib/strings-en";+import { S, setActiveStrings, zh as ZH } from "../src/lib/strings";+import { sendRefusalReason, sendRefused } from "../src/features/chat/first-send-refusal";++afterEach(() => {+ setActiveStrings(ZH);+});++describe("sendRefusalReason", () => {+ it("reads a refusal through the code's own sentence, not the wire message", () => {+ // `no_default_model` has an interface sentence of its own; the English body must not reach it.+ const reason = sendRefusalReason(new ApiError(400, "no_default_model", "RAW ENGLISH"));+ expect(reason).toBe(S.errors.noDefaultModel);+ expect(reason).not.toContain("RAW ENGLISH");+ });++ it("names the model the draft was aimed at when the key is missing", () => {+ // The body of `model_credential_missing` carries no model id; the draft's own pick supplies it.+ const reason = sendRefusalReason(+ new ApiError(400, "model_credential_missing", "RAW ENGLISH"),+ "deepseek-flash",+ );+ expect(reason).toBe(S.errors.modelCredentialMissing("deepseek-flash"));+ expect(reason).toContain("deepseek-flash");+ });++ it("keeps what a send that never reached the route has to say", () => {+ expect(sendRefusalReason(new Error("Failed to fetch"))).toBe("Failed to fetch");+ });++ it("falls back to the generic text when the value has nothing to say", () => {+ expect(sendRefusalReason(undefined)).toBe(S.common.unknownError);+ expect(sendRefusalReason(new Error(" "))).toBe(S.common.unknownError);+ });++ it("speaks the active language", () => {+ setActiveStrings(EN);+ expect(sendRefusalReason(new ApiError(400, "no_default_model", "no default"))).toBe(+ EN.errors.noDefaultModel,+ );+ });+});++describe("sendRefused", () => {+ it("names what failed, then the reason", () => {+ const line = sendRefused("没有可用的默认模型。");+ expect(line).toBe(S.chat.draftSendRefused("没有可用的默认模型。"));+ expect(line.endsWith("没有可用的默认模型。")).toBe(true);+ });++ it("speaks the active language", () => {+ setActiveStrings(EN);+ expect(sendRefused("denied")).toBe(EN.chat.draftSendRefused("denied"));+ expect(sendRefused("denied")).toBe("Could not send this message: denied");+ });+});