A local-first multi-agent app development platform, built on PenguinHarness
fix(web): a channel keeps the message you have not sent (#810)
lmlihengdbd0c255d620
diff --git a/changelog/unreleased/2026-10-14-channel-draft.md b/changelog/unreleased/2026-10-14-channel-draft.mdnew file mode 100644index 00000000..a33f7694--- /dev/null+++ b/changelog/unreleased/2026-10-14-channel-draft.md@@ -0,0 +1,17 @@+# A channel keeps the message you have not sent++- **Date:** 2026-10-14+- **Type:** fix+- **Scope:** `web`++[中文版](2026-10-14-channel-draft.zh.md)++Ported from upstream PenguinHarness (#810, commit `7ecb60e1`).++Text typed into a channel's composer and not sent used to live only in the open view: opening+another channel, a desk or any other page — or reloading — threw it away. It is now kept per+user, Project, organization and channel in the browser (`penguin.channelDraft.…`), the way a+conversation's unsent input already was: coming back to the channel finds the text where it+was left, another channel does not inherit it, and sending the message (or emptying the box)+is what ends it. Nothing on disk or on the server changes, and the new key is classified as+install-scoped beside the chat drafts.diff --git a/changelog/unreleased/2026-10-14-channel-draft.zh.md b/changelog/unreleased/2026-10-14-channel-draft.zh.mdnew file mode 100644index 00000000..06828705--- /dev/null+++ b/changelog/unreleased/2026-10-14-channel-draft.zh.md@@ -0,0 +1,11 @@+# 频道保留你还没发出的消息++- **Date:** 2026-10-14+- **Type:** fix+- **Scope:** `web`++[English](2026-10-14-channel-draft.md)++移植自上游 PenguinHarness(#810,提交 `7ecb60e1`)。++在频道输入框里写了还没发出的文字,过去只活在当前视图里:打开另一个频道、某个工位、任何别的页面——或刷新——都会把它丢掉。现在它按用户、项目、组织与频道保存在浏览器里(`penguin.channelDraft.…`),与对话里未发送的输入同一口径:回到该频道,文字还在原处;别的频道不会继承它;发出消息(或清空输入框)才会结束它。磁盘与服务端什么都不变,新键与对话草稿并列归为 install 作用域。diff --git a/packages/web/e2e/company.spec.mjs b/packages/web/e2e/company.spec.mjsindex 3b286f73..09ba8b2d 100644--- a/packages/web/e2e/company.spec.mjs+++ b/packages/web/e2e/company.spec.mjs@@ -396,6 +396,26 @@ test("company mode: create the organization, meet the CEO, see the board and theexpect(siteDay.messages.some((m) => m.text.includes("站点频道成立"))).toBe(true);expect(siteDay.messages.some((m) => m.mentions.includes(`agent:${ORG}_ceo`))).toBe(true);+ // An unsent draft stays with its channel: leaving does not lose it, another channel does not+ // inherit it, a reload keeps it, and sending is what ends it.+ await siteInput.fill("还没写完的一句");+ await page+ .getByRole("link", { name: /^全员频道/ })+ .first()+ .click();+ await expect(page).toHaveURL(/channels\/default_channel/);+ await expect(page.getByRole("textbox", { name: /输入消息/ })).toHaveValue("");+ await page.getByRole("link", { name: /^Site launch/ }).click();+ await expect(page).toHaveURL(/channels\/site/);+ await expect(page.getByRole("textbox", { name: /输入消息/ })).toHaveValue("还没写完的一句");+ await page.reload();+ await expect(page.getByRole("textbox", { name: /输入消息/ })).toHaveValue("还没写完的一句");+ await page.getByRole("textbox", { name: /输入消息/ }).press("Enter");+ await expect(page.getByText("还没写完的一句").first()).toBeVisible();+ await expect(page.getByRole("textbox", { name: /输入消息/ })).toHaveValue("");+ await page.reload();+ await expect(page.getByRole("textbox", { name: /输入消息/ })).toHaveValue("");+// The overview shows the organization, its mission on screen.await page.goto(`/org/${projectId}/${ORG}/overview`);await expect(page.getByText("Plugin Marketplace").first()).toBeVisible();diff --git a/packages/web/src/features/company/channel-composer.tsx b/packages/web/src/features/company/channel-composer.tsxindex 1ede470a..837fbcb5 100644--- a/packages/web/src/features/company/channel-composer.tsx+++ b/packages/web/src/features/company/channel-composer.tsx@@ -33,6 +33,10 @@* the browser's own, and so does its undo step. A cut deletes its selection itself, natively,* since writing the clipboard means cancelling the browser's cut.*+ * The unsent text is the caller's to keep (channel-draft.ts): the box starts from+ * `initialText` and reports every edit, so leaving the channel does not lose what was typed.+ * The caller remounts the composer per channel, which is what makes `initialText` apply.+ ** The keys are named in the placeholder and nothing is rendered under the box, the way* development mode's chat input reads: a line of hint below the composer is read once and* then costs a row of the stream on every later visit.@@ -106,16 +110,29 @@ function kindTitle(kind: MentionKind): string {export function ChannelComposer({candidates,names,+ initialText = "",+ onTextChange,onSend,}: {candidates: readonly MentionCandidate[];names: ReadonlyMap<string, string>;+ /** The draft this channel was left with. Read once, at mount. */+ initialText?: string;+ /** Every change of the box's text, the clearing after a send included. */+ onTextChange?: (text: string) => void;/** Sends the draft; resolves true once it is in the stream (the draft is then cleared). */onSend: (text: string) => Promise<boolean>;}) {- const [draft, setDraft] = useState(EMPTY_DRAFT);+ const [draft, setDraftState] = useState<MentionDraft>(() => ({+ text: initialText,+ mentions: [],+ }));const text = draft.text;- const [caret, setCaret] = useState(0);+ const [caret, setCaret] = useState(initialText.length);+ const setDraft = (next: MentionDraft) => {+ setDraftState(next);+ onTextChange?.(draftWireText(next));+ };const [highlight, setHighlight] = useState(0);/** The `start:query` token Escape dismissed the panel for; typing on changes the token and reopens it. */const [dismissed, setDismissed] = useState<string | null>(null);diff --git a/packages/web/src/features/company/channel-draft.ts b/packages/web/src/features/company/channel-draft.tsnew file mode 100644index 00000000..67f8694c--- /dev/null+++ b/packages/web/src/features/company/channel-draft.ts@@ -0,0 +1,98 @@+/**+ * A channel composer's unsent text, kept across leaving the channel and reloading the page.+ *+ * Cached in localStorage per "user × Project × organization × channel" — the user dimension+ * for the same reason the chat drafts carry it (draft-cache.ts): two accounts on one browser+ * must not read each other's unsent words. The storage helpers are the chat drafts' own; a+ * channel draft is their `text` field and nothing else.+ *+ * The write strategy is the session composer's (use-session-draft.ts): typing is debounced, an+ * edit still waiting for its timer is flushed when the channel changes or the view unmounts,+ * an emptied box deletes the key rather than leaving a shell per channel, and a successful+ * send cancels the pending write first — otherwise it would put the sent text back.+ */+import { useCallback, useEffect, useMemo, useRef } from "react";+import { useAuth } from "../../state/auth";+import { clearDraft, loadDraft, saveDraft } from "../chat/draft-cache";+import type { DraftStorage } from "../chat/draft-cache";++const SAVE_DEBOUNCE_MS = 300;++export const channelDraftKey = (+ userId: string,+ projectId: string,+ orgId: string,+ channelId: string,+): string => `penguin.channelDraft.${userId}.${projectId}.${orgId}.${channelId}`;++export function loadChannelDraft(key: string, storage?: DraftStorage): string {+ return loadDraft(key, storage).text ?? "";+}++/** Writes the text, or deletes the key when there is nothing left to keep. */+export function storeChannelDraft(key: string, text: string, storage?: DraftStorage): void {+ if (text === "") clearDraft(key, storage);+ else saveDraft(key, { text }, storage);+}++export function useChannelDraft(+ projectId: string,+ orgId: string,+ channelId: string,+): {+ /** Identifies the draft: the composer remounts on it, so it starts from `initial`. */+ key: string | null;+ initial: string;+ onTextChange: (text: string) => void;+ /** Drops the draft after a successful send. */+ discard: () => void;+} {+ // No user (should not happen under RequireAuth) disables the cache: never an account-less key.+ const userId = useAuth().user?.userId ?? null;+ const key = userId === null ? null : channelDraftKey(userId, projectId, orgId, channelId);+ const initial = useMemo(() => (key === null ? "" : loadChannelDraft(key)), [key]);++ const textRef = useRef(initial);+ const timer = useRef<number | null>(null);++ const cancelPending = useCallback(() => {+ if (timer.current !== null) {+ window.clearTimeout(timer.current);+ timer.current = null;+ }+ }, []);++ const persistNow = useCallback(() => {+ cancelPending();+ if (key !== null) storeChannelDraft(key, textRef.current);+ }, [cancelPending, key]);++ // Another channel, or leaving: the cleanup flushes the old channel's pending edit (its+ // closure still holds the old key), then setup starts from the new channel's draft.+ useEffect(() => {+ textRef.current = initial;+ return () => {+ if (timer.current !== null) persistNow();+ };+ }, [initial, persistNow]);++ const onTextChange = useCallback(+ (text: string) => {+ textRef.current = text;+ cancelPending();+ timer.current = window.setTimeout(() => {+ timer.current = null;+ persistNow();+ }, SAVE_DEBOUNCE_MS);+ },+ [cancelPending, persistNow],+ );++ const discard = useCallback(() => {+ cancelPending();+ textRef.current = "";+ if (key !== null) clearDraft(key);+ }, [cancelPending, key]);++ return { key, initial, onTextChange, discard };+}diff --git a/packages/web/src/features/company/channel-view.tsx b/packages/web/src/features/company/channel-view.tsxindex fc59a673..2c05993b 100644--- a/packages/web/src/features/company/channel-view.tsx+++ b/packages/web/src/features/company/channel-view.tsx@@ -65,6 +65,7 @@ import { useOrg } from "./org-layout";import { principalLabel } from "./shared";import { orgKey } from "./company-nav";import { ChannelComposer } from "./channel-composer";+import { useChannelDraft } from "./channel-draft";import { ChannelHeader } from "./channel-header";import { ChannelMessageBody, ChannelReaderProvider, MentionChip } from "./channel-markdown";import { noticeText } from "./channel-notices";@@ -353,9 +354,13 @@ export function ChannelView() {syncScrollState();};+ // The unsent text outlives the view: leaving a channel (or reloading) must not lose it.+ const draft = useChannelDraft(projectId, orgId, channelId);+const send = async (text: string): Promise<boolean> => {try {const msg = await api.sendOrgChannelMessage(projectId, orgId, channelId, { text });+ draft.discard();follow.resume();setDays((prev) =>prev === null ? prev : appendMessage(prev, meta?.today ?? msg.time.slice(0, 10), msg),@@ -668,7 +673,15 @@ export function ChannelView() {</div><div className="mx-auto w-full max-w-5xl">{canPost ? (- <ChannelComposer candidates={candidates} names={names} onSend={send} />+ <ChannelComposer+ // Remounted per draft: the box starts from the text this channel was left with.+ key={draft.key ?? channelId}+ candidates={candidates}+ names={names}+ initialText={draft.initial}+ onTextChange={draft.onTextChange}+ onSend={send}+ />) : detail !== null && detail.archived ? (<NoticeStriptone="neutral"diff --git a/packages/web/src/lib/install-scope.ts b/packages/web/src/lib/install-scope.tsindex e6aedbbd..b74fb039 100644--- a/packages/web/src/lib/install-scope.ts+++ b/packages/web/src/lib/install-scope.ts@@ -247,6 +247,12 @@ export const KEY_RULES: readonly KeyRule[] = [scope: "install",why: "Parked draft conversations — the same contents as an active draft, kept as a list.",},+ {+ kind: "family",+ key: "penguin.channelDraft.",+ scope: "install",+ why: "A channel composer's unsent text, keyed by user, Project, organization and channel — all four name things that live in one data root.",+ },{kind: "family",key: "penguin.sidebarWorkspaces.",diff --git a/packages/web/test/channel-draft.test.ts b/packages/web/test/channel-draft.test.tsnew file mode 100644index 00000000..b32ceda1--- /dev/null+++ b/packages/web/test/channel-draft.test.ts@@ -0,0 +1,59 @@+/**+ * A channel composer's draft storage: one key per user × Project × organization × channel,+ * the text and nothing else, and no empty shells left behind.+ */+import { describe, expect, it } from "vitest";+import {+ channelDraftKey,+ loadChannelDraft,+ storeChannelDraft,+} from "../src/features/company/channel-draft";+import type { DraftStorage } from "../src/features/chat/draft-cache";++/** In-memory storage (vitest runs in a Node environment, no localStorage). */+function memStorage(): DraftStorage & { map: Map<string, string> } {+ const map = new Map<string, string>();+ return {+ map,+ getItem: (k) => map.get(k) ?? null,+ setItem: (k, v) => void map.set(k, v),+ removeItem: (k) => void map.delete(k),+ };+}++describe("channel drafts", () => {+ it("keeps a draft per user, Project, organization and channel", () => {+ const keys = new Set([+ channelDraftKey("alice", "p1", "acme", "dev"),+ channelDraftKey("bob", "p1", "acme", "dev"),+ channelDraftKey("alice", "p2", "acme", "dev"),+ channelDraftKey("alice", "p1", "other", "dev"),+ channelDraftKey("alice", "p1", "acme", "ops"),+ ]);+ expect(keys.size).toBe(5);+ });++ it("gives back what was stored, and nothing for a channel never typed in", () => {+ const storage = memStorage();+ const key = channelDraftKey("alice", "p1", "acme", "dev");+ expect(loadChannelDraft(key, storage)).toBe("");+ storeChannelDraft(key, "@ceo 先看一下\nsecond line", storage);+ expect(loadChannelDraft(key, storage)).toBe("@ceo 先看一下\nsecond line");+ expect(loadChannelDraft(channelDraftKey("alice", "p1", "acme", "ops"), storage)).toBe("");+ });++ it("deletes the key when the box is emptied, rather than storing an empty draft", () => {+ const storage = memStorage();+ const key = channelDraftKey("alice", "p1", "acme", "dev");+ storeChannelDraft(key, "half a sentence", storage);+ storeChannelDraft(key, "", storage);+ expect(storage.map.size).toBe(0);+ });++ it("reads an unreadable entry as no draft", () => {+ const storage = memStorage();+ const key = channelDraftKey("alice", "p1", "acme", "dev");+ storage.setItem(key, "{not json");+ expect(loadChannelDraft(key, storage)).toBe("");+ });+});