From 1e27c5857ef56e4b5e7f6ea45ae4222a40277d13 Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Fri, 27 Nov 2026 05:49:50 +0000 Subject: [PATCH 01/13] wip: scope a kept new chat's draft key --- components/AppShell.tsx | 2 ++ components/ChatWindow.tsx | 7 +++++-- hooks/useAgentSession.rpc.test.mjs | 9 ++++----- hooks/useAgentSession.ts | 7 ++++--- lib/project-ordering.test.mjs | 8 ++++++++ 5 files changed, 23 insertions(+), 10 deletions(-) diff --git a/components/AppShell.tsx b/components/AppShell.tsx index 5840bcc5..11bcb7b4 100644 --- a/components/AppShell.tsx +++ b/components/AppShell.tsx @@ -3089,6 +3089,7 @@ export function AppShell({ appName }: { appName: string }) { void; /** The chat's host from the `hosts` channel: the source of truth until a * `host_status` frame reports a change, and for a chat opened mid-outage. */ @@ -396,7 +398,7 @@ const CommittedTranscript = memo(function CommittedTranscript({ ); }); -export function ChatWindow({ session, newSessionCwd, newSessionHostId, newSessionCreationId, newSessionPoolId, newSessionProjectId, newSessionInitialization, onNewSessionInitialization, hostStatus: channelHostStatus, hostLabel, newSessionWorkspace, headerActions, toolCallsDefaultCollapsed = true, hideToolActivity = true, neverFoldActivity = false, showToolCallsUnfolded = false, expandThinkingByDefault = false, hideThinkingBlock = false, onAgentEnd, onSessionCreated, onSent, onSessionForked, modelsRefreshKey, chatInputRef, sessionInfoContainer, onBranchDataChange, onSystemPromptChange, onSystemPromptLoaderChange, onSessionStatsChange, onSessionStatsPanelOpen, onGenerationSpeedChange, onOpenFile: onOpenWorkspaceFile, onOpenUrl, onOpenProviders, searchQuery = "", searchTarget = null, onSearchTargetHandled, covered = false }: Props) { +export function ChatWindow({ session, newSessionCwd, newSessionHostId, newSessionCreationId, newSessionPoolId, newSessionProjectId, newSessionInitialization, draftScope, onNewSessionInitialization, hostStatus: channelHostStatus, hostLabel, newSessionWorkspace, headerActions, toolCallsDefaultCollapsed = true, hideToolActivity = true, neverFoldActivity = false, showToolCallsUnfolded = false, expandThinkingByDefault = false, hideThinkingBlock = false, onAgentEnd, onSessionCreated, onSent, onSessionForked, modelsRefreshKey, chatInputRef, sessionInfoContainer, onBranchDataChange, onSystemPromptChange, onSystemPromptLoaderChange, onSessionStatsChange, onSessionStatsPanelOpen, onGenerationSpeedChange, onOpenFile: onOpenWorkspaceFile, onOpenUrl, onOpenProviders, searchQuery = "", searchTarget = null, onSearchTargetHandled, covered = false }: Props) { const { t, tn } = useI18n(); const fileSource = useMemo(() => ({ hostId: session?.hostId ?? newSessionHostId ?? "local", @@ -554,7 +556,8 @@ export function ChatWindow({ session, newSessionCwd, newSessionHostId, newSessio // top, load another page while keeping the scroll position stable. const [visibleCount, setVisibleCount] = useState(VISIBLE_PAGE_SIZE); const prevSessionKeyForPagingRef = useRef(null); - const draftKey = session?.id ?? (newSessionPoolId && newSessionProjectId ? `new:pool:${newSessionPoolId}:${newSessionProjectId}` : newSessionCwd ? newChatDraftKey(newSessionCwd, newSessionHostId) : undefined); + const baseDraftKey = session?.id ?? (newSessionPoolId && newSessionProjectId ? `new:pool:${newSessionPoolId}:${newSessionProjectId}` : newSessionCwd ? newChatDraftKey(newSessionCwd, newSessionHostId) : undefined); + const draftKey = session?.id ?? (baseDraftKey && draftScope ? `${baseDraftKey}#${draftScope}` : baseDraftKey); const sessionKeyForPaging = draftKey ?? "empty"; useEffect(() => { if (prevSessionKeyForPagingRef.current !== sessionKeyForPaging) { diff --git a/hooks/useAgentSession.rpc.test.mjs b/hooks/useAgentSession.rpc.test.mjs index a67b1a51..3ba25c7a 100644 --- a/hooks/useAgentSession.rpc.test.mjs +++ b/hooks/useAgentSession.rpc.test.mjs @@ -5137,7 +5137,7 @@ test("a rejected saved launch configuration is shown on a fresh chat and leaves const w = await mountSession(null, undefined, { newSessionCwd: "/workspace" }); let receipt; await act(async () => { receipt = await w.latest.handleSend("keep this draft"); }); - assert.deepEqual(receipt, { status: "rejected", recoveryKey: "new:/workspace" }); + assert.deepEqual(receipt, { status: "rejected", recoveryKey: undefined }); assert.ok(w.latest.notices.some((notice) => notice.type === "error" && notice.message.includes(translate("errors.stored_reserved_launch_arg")))); assert.equal(world.calls.some((call) => call.body?.type === "prompt"), false); }); @@ -5152,8 +5152,7 @@ test("a fresh chat on a remote host creates its session there and toasts when th const w = await mountSession(null, undefined, { newSessionCwd: "/remote/work", newSessionHostId: "h1" }); let receipt; await act(async () => { receipt = await w.latest.handleSend("first"); await sleep(30); }); - // Drafts for one path on two hosts must not share a composer key. - assert.deepEqual(receipt, { status: "rejected", recoveryKey: "new:h1:/remote/work" }); + assert.deepEqual(receipt, { status: "rejected", recoveryKey: undefined }); assert.deepEqual(callsTo("POST", "/api/agent/new").map((call) => [call.body.cwd, call.body.hostId]), [["/remote/work", "h1"]]); assert.equal(toastCalls[0]?.[0], "error"); assert.equal(w.latest.notices.length, 0); @@ -6229,7 +6228,7 @@ test("workspace file search stays in its source session rather than a same-path view.unmount(); }); -test("a fresh local chat sends no host id and keeps the pre-hosts draft key", async () => { +test("a fresh local chat sends no host id and leaves a failed send to the composer's own draft key", async () => { resetWorld(); world.holds.push({ match: (method, url) => method === "POST" && url === "/api/agent/new", @@ -6239,7 +6238,7 @@ test("a fresh local chat sends no host id and keeps the pre-hosts draft key", as let receipt; await act(async () => { receipt = await w.latest.handleSend("first"); await sleep(30); }); assert.equal("hostId" in callsTo("POST", "/api/agent/new")[0].body, false); - assert.deepEqual(receipt, { status: "rejected", recoveryKey: "new:/workspace" }); + assert.deepEqual(receipt, { status: "rejected", recoveryKey: undefined }); }); for (const [name, method, mode, message] of [ diff --git a/hooks/useAgentSession.ts b/hooks/useAgentSession.ts index 770c690c..bdabaa0a 100644 --- a/hooks/useAgentSession.ts +++ b/hooks/useAgentSession.ts @@ -25,7 +25,7 @@ import type { ThinkingModelMeta } from "@/lib/thinking-levels"; import { HostOfflineError, getOutboxScope, rememberOutboxScope, sendAgentCommand } from "@/lib/agent-client"; import type { HostStatus } from "@/lib/hosts/host"; import type { WorkspaceFileSource } from "@/lib/workspace-types"; -import { newChatDraftKey, remoteHostId } from "@/lib/project-ordering"; +import { remoteHostId } from "@/lib/project-ordering"; import { recoverDraft, setDraft } from "@/lib/draft-store"; import { formatExitedSessionNotice, translate } from "@/lib/i18n"; import { formatApiError } from "@/lib/i18n/api-error"; @@ -3073,7 +3073,8 @@ export function useAgentSession(opts: UseAgentSessionOptions) { // not a request to stop following the response that this prompt starts. userScrollIntentUntilRef.current = 0; - let recoveryKey = sessionIdRef.current ?? (pooled ? `new:pool:${newSessionPoolId}:${newSessionProjectId}` : newSessionCwd ? newChatDraftKey(newSessionCwd, newSessionHostId) : undefined); + // Unset until a session exists: a failed first send goes back to the composer's own draft key. + let recoveryKey: string | undefined = sessionIdRef.current ?? undefined; // Set just before the prompt goes out: a lost reply from any earlier command (get_state, set_model) ran no prompt. let promptIssued = false; try { @@ -3160,7 +3161,7 @@ export function useAgentSession(opts: UseAgentSessionOptions) { dispatch({ type: "end" }); return mayHaveRun ? { status: "accepted" } : { status: "rejected", recoveryKey: sessionIdRef.current ?? recoveryKey }; } - }, [catchUp, eventCoalescer, isNew, pooled, newSessionPoolId, newSessionProjectId, newSessionCwd, newSessionHostId, newSessionModel, session, ensureNewSession, ensureEventsConnected, promoteNewSession, onSessionCreated, waitForPromptSettlement, addNotice, refreshSubagentRoster, clearLiveToolResults, clearTerminalReconcileTimer, snapshotRunEntries, holdMessage]); + }, [catchUp, eventCoalescer, isNew, newSessionModel, session, ensureNewSession, ensureEventsConnected, promoteNewSession, onSessionCreated, waitForPromptSettlement, addNotice, refreshSubagentRoster, clearLiveToolResults, clearTerminalReconcileTimer, snapshotRunEntries, holdMessage]); const executeBash = useCallback(async (command: string, excludeFromContext: boolean) => { if (bashRunningRef.current || editInFlightRef.current) return; diff --git a/lib/project-ordering.test.mjs b/lib/project-ordering.test.mjs index 8cf66770..ae87b855 100644 --- a/lib/project-ordering.test.mjs +++ b/lib/project-ordering.test.mjs @@ -6,6 +6,7 @@ const { groupProjectsByHost, groupSessionsByProject, hostProjectKey, + newChatDraftKey, projectActivityCounts, nextPinOrder, orderProjects, @@ -315,3 +316,10 @@ test("last updated sorts a host's project by that host's sessions only", () => { ]; assert.deepEqual(orderProjects(projects, "updated", sessions, (p) => p.path).map((p) => p.hostId), ["h1", "local"]); }); + +test("a fresh chat's draft key keeps the pre-hosts form here and names the host elsewhere", () => { + assert.equal(newChatDraftKey("/workspace", undefined), "new:/workspace"); + assert.equal(newChatDraftKey("/workspace", "local"), "new:/workspace"); + // Drafts for one path on two hosts must not share a composer key. + assert.equal(newChatDraftKey("/remote/work", "h1"), "new:h1:/remote/work"); +}); From 6d3470f23ca26c72df29c22485788df6b7df5ad1 Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Fri, 27 Nov 2026 05:57:32 +0000 Subject: [PATCH 02/13] fix(tabs): give a kept new chat a draft of its own --- AGENTS.md | 2 +- components/AppShell.tsx | 19 +++++++++++++------ components/ChatInput.tsx | 23 ++++++++++++++++++----- components/ChatWindow.tsx | 3 ++- hooks/useAgentSession.rpc.test.mjs | 9 +++++++++ lib/draft-store.test.mjs | 16 +++++++++++++++- lib/draft-store.ts | 8 ++++++++ 7 files changed, 66 insertions(+), 14 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index e2be2024..7661b50e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -370,7 +370,7 @@ Browser keys use `tau-` / `tau:` (`tau-theme`, the `tau-theme-color` cookie, `ta - Prefill only the selected message's text, never its images. Preserve drafts, newer typing and attachments through pending edits, cancellation, errors and navigation. `submissionBlocked` keeps asynchronous dictation from submitting or clearing the composer. `session_history_changed` carries the leaf marker; the initiating tab deduplicates its own echo. Editing does not undo tool side effects. - Draft text survives reload via sessionStorage; attachment payloads stay in memory. - Event connections own their readiness waits: replacement and unmount settle the old wait as closed and close its observer; stale continuations must not attach streams or authorize operations. A new chat's first prompt is the exception: when its chat unmounts while pi spawns, `handleSend` still sends it and returns `accepted`. A new chat left for another group's chat stays mounted there instead; its session then replaces its tab in place without being selected (`handleSessionCreated`). Existing sessions' messages go through the outbox. - - `ChatInput.onSend` returns `Promise` (`accepted` / `rejected` / `superseded`). With `outbox` the composer clears only once the message is stored in the browser's outbox and only if it still holds what was sent. For a new chat only rejection restores the draft (`recoverDraft`; the composer owns recovery); superseded failures never reinsert a processed turn. + - `ChatInput.onSend` returns `Promise` (`accepted` / `rejected` / `superseded`). With `outbox` the composer clears only once the message is stored in the browser's outbox and only if it still holds what was sent. For a new chat only rejection restores the draft (`recoverDraft`; the composer owns recovery) to the key the draft store's submission names, so it follows the chat when its composer remounts or the chat gets a draft of its own; superseded failures never reinsert a processed turn. A new chat that sent and moved to a tab of its own (`DraftChat.scope`) keeps its draft under `new:…#` (`continueDraft`), so the new chat opened after it has the workspace's draft to itself. - **In-session branch** (Continue / BranchNavigator): a read-only historical view of the entry tree through `/api/sessions/[id]/context?leafId=` (`handleLeafChange`); it does not change the live agent. Never implement Edit with it. ### ToolCall field normalization diff --git a/components/AppShell.tsx b/components/AppShell.tsx index 11bcb7b4..fa8dd04e 100644 --- a/components/AppShell.tsx +++ b/components/AppShell.tsx @@ -128,7 +128,9 @@ const OPEN_URL_AUTOMATICALLY_STORAGE_KEY = "tau:open-url-automatically"; /** The transient tab of a chat not yet sent (no session yet). */ const NEW_CHAT_TAB_ID = "chat:new"; /** An unsent new chat's target, as it was last shown. */ -type DraftChat = { cwd: string | null; hostId?: string; project: ManagedProject | null; creationId?: string; initialization?: string }; +/** `scope`: set once the chat sent something and moved to a tab of its own, which gives it a composer draft of its + * own (ChatWindow's `draftScope`): the new chat that opens after it has the workspace's. */ +type DraftChat = { cwd: string | null; hostId?: string; project: ManagedProject | null; creationId?: string; initialization?: string; scope?: string }; const chatTabId = (session: SessionInfo) => `chat:${remoteHostId(session.hostId) ?? LOCAL_HOST_ID}:${session.id}`; /** The strips kept across reloads of this browser tab (sessionStorage: another window keeps its own). */ const WORKBENCH_STORAGE_KEY = "tau:workbench"; @@ -198,6 +200,8 @@ export function AppShell({ appName }: { appName: string }) { // New chats that sent something, moved out of the new chat's tab: each keeps a tab of its own, and its mount, until // the tab closes or the chat's session takes the tab over. const [draftTabs, setDraftTabs] = useState<{ id: string; draft: DraftChat }[]>([]); + // The shown new chat's DraftChat.scope. + const [newChatScope, setNewChatScope] = useState(undefined); const draftTabSeqRef = useRef(0); // Mount keys of the new chats that began a send which can create their session. Never cleared: a key names one // mount, and a sent chat stays sent. @@ -220,7 +224,8 @@ export function AppShell({ appName }: { appName: string }) { return; } const id = `${DRAFT_TAB_PREFIX}${++draftTabSeqRef.current}`; - setDraftTabs((tabs) => [...tabs, { id, draft }]); + setDraftTabs((tabs) => [...tabs, { id, draft: { ...draft, scope: draft.scope ?? id } }]); + setNewChatScope(undefined); setTabLayout((layout) => replaceTab(layout, NEW_CHAT_TAB_ID, id)); setChatMounts((mounts) => moveChatMount(mounts, NEW_CHAT_TAB_ID, id)); }, []); @@ -1461,6 +1466,7 @@ export function AppShell({ appName }: { appName: string }) { }, [router, isMobile, activeCwd, activePoolProject, dropKeptDraft]); const takeUpDraft = useCallback((draft: DraftChat) => { handleNewSession(draft.creationId ?? "", draft.cwd, draft.hostId, draft.project ?? undefined, draft.initialization); + setNewChatScope(draft.scope); }, [handleNewSession]); // ---- In-app Navigate back / forward over visited chat views ---- @@ -1609,6 +1615,7 @@ export function AppShell({ appName }: { appName: string }) { // Called by ChatWindow when a new session gets its real id from pi const handleSessionCreated = useCallback((session: SessionInfo) => { setDraftChat(null); + setNewChatScope(undefined); if (!draftShownRef.current && draftChatRef.current) { setNewSessionCwd(null); setNewSessionPoolProject(null); @@ -2180,8 +2187,8 @@ export function AppShell({ appName }: { appName: string }) { const draftTabShown = showChat && !selectedSession; draftShownRef.current = draftTabShown; useEffect(() => { - if (draftTabShown) setDraftChat({ cwd: effectiveNewSessionCwd, hostId: newSessionHost, project: effectivePoolProject, creationId: newSessionCreation.id, initialization: newSessionCreation.initialization }); - }, [draftTabShown, effectiveNewSessionCwd, newSessionHost, effectivePoolProject, newSessionCreation.id, newSessionCreation.initialization]); + if (draftTabShown) setDraftChat({ cwd: effectiveNewSessionCwd, hostId: newSessionHost, project: effectivePoolProject, creationId: newSessionCreation.id, initialization: newSessionCreation.initialization, scope: newChatScope }); + }, [draftTabShown, effectiveNewSessionCwd, newSessionHost, effectivePoolProject, newSessionCreation.id, newSessionCreation.initialization, newChatScope]); const tabGroups = groupsOf(tabLayout); // The new chat a group shows keeps its tab while the selected chat is not in that group (a chat selected into // the new chat's own group replaces it, as before). @@ -3089,7 +3096,7 @@ export function AppShell({ appName }: { appName: string }) { Promise; onAudioUnlock?: () => void; draftKey?: string; + /** The key `draftKey` replaces for the same chat (a new chat given a draft of its own): a change from it keeps the + * composer's content and moves its pending recoveries along, instead of loading another draft. */ + draftKeyContinues?: string; /** Owning host for file uploads and the @ file index (this machine when absent). */ uploadHostId?: string; /** Lazily bind a pool's real owner before staging any file bytes. Failure never falls back locally. */ @@ -302,6 +305,7 @@ export const ChatInput = memo(forwardRef(function ChatIn generationSpeed, onClearQueuedMessages, draftKey = "new:unassigned", + draftKeyContinues, uploadHostId = LOCAL_HOST_ID, resolveUploadHost, cwd, @@ -956,6 +960,12 @@ export const ChatInput = memo(forwardRef(function ChatIn useLayoutEffect(() => { const previousDraftKey = draftKeyRef.current; if (previousDraftKey === draftKey) return; + if (previousDraftKey && draftKey && previousDraftKey === draftKeyContinues) { + continueDraft(previousDraftKey, draftKey, captureDraft()); + draftKeyRef.current = draftKey; + draftRecoveryIdentityRef.current = { key: draftKey }; + return; + } // Invalidate any attachment reads still in flight for the old session so // they cannot append onto the new session's composer, and drop any stale @@ -990,7 +1000,7 @@ export const ChatInput = memo(forwardRef(function ChatIn for (const upload of prev) if (upload.previewUrl) URL.revokeObjectURL(upload.previewUrl); return draftUploadsToAttachedUploads(draft?.uploads); }); - }, [draftKey, setPromptOnly, captureDraft]); + }, [draftKey, draftKeyContinues, setPromptOnly, captureDraft]); useLayoutEffect(() => subscribeDraftRecovery((key, recovery) => { if (draftKeyRef.current !== key) return; @@ -1121,7 +1131,6 @@ export const ChatInput = memo(forwardRef(function ChatIn } if (submissionBlockedRef.current) return; if (rejectsOversizedPrompt(composedMessage, attachedImagesRef.current)) return; - const key = draftKeyRef.current; const images = attachedImagesRef.current.length ? attachedImagesRef.current : undefined; const recovery = { text: msg, images: images?.map(imageToDraftImage), files: files.length ? files.map(textFileToDraftFile) : undefined, ...(promptOnlyRef.current ? { promptOnly: true } : {}), ...uploadRecovery(attachedUploadsRef.current) }; const stored = outbox && !shellCommand ? clearOnceStored(raw) : undefined; @@ -1147,16 +1156,20 @@ export const ChatInput = memo(forwardRef(function ChatIn } return; } + // Owned by the store, not this mount: the chat's composer may remount, or move to a key of its own, meanwhile. + const submission = beginDraftSubmission(draftKeyRef.current); clearInput(); try { const result = await pending; if (result.status === "rejected") { - const destination = result.recoveryKey ?? key; + const destination = result.recoveryKey ?? submission.key; if (destination) recoverDraft(destination, recovery); } } catch (error) { - if (key) recoverDraft(key, recovery); + if (submission.key) recoverDraft(submission.key, recovery); throw error; + } finally { + endDraftSubmission(submission); } }, [value, isStreaming, onBuiltinCommand, onSend, outbox, clearInput, clearOnceStored, onAudioUnlock, rejectsOversizedPrompt, rejectsPendingUploads, runBuiltinCommand, sendSideQuestion]); const { diff --git a/components/ChatWindow.tsx b/components/ChatWindow.tsx index d2b03624..050904ce 100644 --- a/components/ChatWindow.tsx +++ b/components/ChatWindow.tsx @@ -53,7 +53,7 @@ interface Props { newSessionPoolId?: string; newSessionProjectId?: string; newSessionInitialization?: string; - /** Set for a new chat that is not the strip's own new chat: its draft is its own, not the workspace's. */ + /** A new chat's draft of its own (DraftChat.scope in AppShell); without it the chat has the workspace's. */ draftScope?: string; onNewSessionInitialization?: (body: string) => void; /** The chat's host from the `hosts` channel: the source of truth until a @@ -970,6 +970,7 @@ export function ChatWindow({ session, newSessionCwd, newSessionHostId, newSessio onBuiltinCommand={handleBuiltinSlashCommand} onAudioUnlock={unlockAudio} draftKey={draftKey} + draftKeyContinues={draftScope ? baseDraftKey : undefined} uploadHostId={session ? session.hostId : newSessionHostId} resolveUploadHost={!session && newSessionPoolId ? resolveUploadHost : undefined} cwd={!session && newSessionPoolId ? null : session?.cwd ?? newSessionCwd} diff --git a/hooks/useAgentSession.rpc.test.mjs b/hooks/useAgentSession.rpc.test.mjs index 3ba25c7a..e2e82c53 100644 --- a/hooks/useAgentSession.rpc.test.mjs +++ b/hooks/useAgentSession.rpc.test.mjs @@ -6123,6 +6123,15 @@ test("a kept chat whose session cannot be created keeps its tab and shows the er h.view.unmount(); }); +test("a kept chat whose send fails gets its text back in its own composer, not the fresh new chat's", async (t) => { + const h = await sentBesideFreshChat(t, { status: 500, value: { error: "spawn failed" } }); + await act(async () => { fireEvent.change(h.composerIn(h.other), { target: { value: "fresh idea" } }); await sleep(60); }); + await act(async () => { h.release(); await sleep(300); }); + assert.equal(h.composerIn(h.draftGroup).value, "hello there", "the kept chat has its prompt back"); + assert.equal(h.composerIn(h.other).value, "fresh idea", "the fresh new chat keeps only its own text"); + h.view.unmount(); +}); + test("another new chat replaces an unsent kept one and opens fresh in the focused group", async (t) => { const h = await draftInItsOwnGroup(t); await act(async () => { fireEvent.change(h.draftComposer, { target: { value: "unsent idea" } }); await sleep(60); }); diff --git a/lib/draft-store.test.mjs b/lib/draft-store.test.mjs index 72ece312..3c0e8bd3 100644 --- a/lib/draft-store.test.mjs +++ b/lib/draft-store.test.mjs @@ -1,7 +1,7 @@ import assert from "node:assert/strict"; import { spawnSync } from "node:child_process"; import test from "node:test"; -import { clearDraft, consumeDraft, getDraft, getDraftRevision, getDraftSummary, markDraftEdited, mergeRecoveredText, recoverDraft, setDraft, subscribeDraftConsumption, subscribeDraftRecovery } from "./draft-store.ts"; +import { beginDraftSubmission, clearDraft, consumeDraft, continueDraft, endDraftSubmission, getDraft, getDraftRevision, getDraftSummary, markDraftEdited, mergeRecoveredText, recoverDraft, setDraft, subscribeDraftConsumption, subscribeDraftRecovery } from "./draft-store.ts"; test("outbox consumption notifies matching drafts without clearing newer text, equal-text retypes or attachment payloads", () => { const key = "outbox-consumption"; @@ -312,3 +312,17 @@ test("a later recovery merges with an earlier one in order, unless the draft no assert.equal(mergeRecoveredText("B\n\ntyping", { text: "A\n\nB", replace }), "A\n\nB\n\ntyping"); assert.equal(mergeRecoveredText("edited", { text: "A\n\nB", replace }), "A\n\nedited", "never re-adds text the user removed"); }); + +test("a continued draft moves its content and its submissions in flight to the new key, and nothing else", () => { + setDraft("new:/w", { value: "typed after sending", images: [], files: [] }); + const moving = beginDraftSubmission("new:/w"); + const other = beginDraftSubmission("new:/other"); + continueDraft("new:/w", "new:/w#chat:draft:1", { value: "typed after sending", images: [], files: [] }); + assert.equal(getDraft("new:/w"), null, "the workspace's draft is free for the next new chat"); + assert.equal(getDraft("new:/w#chat:draft:1")?.value, "typed after sending"); + assert.equal(moving.key, "new:/w#chat:draft:1", "a failed send recovers to the chat's own key"); + assert.equal(other.key, "new:/other"); + endDraftSubmission(moving); + endDraftSubmission(other); + clearDraft("new:/w#chat:draft:1"); +}); diff --git a/lib/draft-store.ts b/lib/draft-store.ts index 02605825..3a116165 100644 --- a/lib/draft-store.ts +++ b/lib/draft-store.ts @@ -296,3 +296,11 @@ export function clearDraft(key: string): void { for (const listener of listeners) listener(); } } + +/** The same chat continues under `to` (a new chat given a draft of its own): `draft` (the composer's current one) + * is stored there, `from` is cleared, and submissions still in flight from `from` recover to `to`. */ +export function continueDraft(from: string, to: string, draft: ChatDraft): void { + clearDraft(from); + setDraft(to, draft); + for (const submission of submissions) if (submission.key === from) submission.key = to; +} From 5cda910ebce12f98717f3f63bbe3ec453fe2a9c9 Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Fri, 27 Nov 2026 06:19:22 +0000 Subject: [PATCH 03/13] fix(tabs): move a kept chat's draft before the next new chat renders; fold it back when it ends --- AGENTS.md | 2 +- components/AppShell.tsx | 33 ++++++++++++++--- components/ChatInput.tsx | 18 +++++++--- components/ChatWindow.tsx | 11 +++--- hooks/useAgentSession.rpc.test.mjs | 58 ++++++++++++++++++++++++++++++ lib/draft-store.test.mjs | 28 +++++++++++---- lib/draft-store.ts | 41 ++++++++++++++++----- lib/project-ordering.ts | 8 +++++ 8 files changed, 170 insertions(+), 29 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 7661b50e..d87c392d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -370,7 +370,7 @@ Browser keys use `tau-` / `tau:` (`tau-theme`, the `tau-theme-color` cookie, `ta - Prefill only the selected message's text, never its images. Preserve drafts, newer typing and attachments through pending edits, cancellation, errors and navigation. `submissionBlocked` keeps asynchronous dictation from submitting or clearing the composer. `session_history_changed` carries the leaf marker; the initiating tab deduplicates its own echo. Editing does not undo tool side effects. - Draft text survives reload via sessionStorage; attachment payloads stay in memory. - Event connections own their readiness waits: replacement and unmount settle the old wait as closed and close its observer; stale continuations must not attach streams or authorize operations. A new chat's first prompt is the exception: when its chat unmounts while pi spawns, `handleSend` still sends it and returns `accepted`. A new chat left for another group's chat stays mounted there instead; its session then replaces its tab in place without being selected (`handleSessionCreated`). Existing sessions' messages go through the outbox. - - `ChatInput.onSend` returns `Promise` (`accepted` / `rejected` / `superseded`). With `outbox` the composer clears only once the message is stored in the browser's outbox and only if it still holds what was sent. For a new chat only rejection restores the draft (`recoverDraft`; the composer owns recovery) to the key the draft store's submission names, so it follows the chat when its composer remounts or the chat gets a draft of its own; superseded failures never reinsert a processed turn. A new chat that sent and moved to a tab of its own (`DraftChat.scope`) keeps its draft under `new:…#` (`continueDraft`), so the new chat opened after it has the workspace's draft to itself. + - `ChatInput.onSend` returns `Promise` (`accepted` / `rejected` / `superseded`). With `outbox` the composer clears only once the message is stored in the browser's outbox and only if it still holds what was sent. For a new chat only rejection restores the draft (`recoverDraft`; the composer owns recovery) to the key the draft store's submission names, so it follows the chat when its composer remounts or the chat gets a draft of its own; superseded failures never reinsert a processed turn. A new chat that sent and moved to a tab of its own (`DraftChat.scope`) keeps its draft under `new:…#`, a key of this page only (`continueDraft`, before the next new chat renders; its composer moves its own sends in flight, `moveDraftSubmissions` with ChatWindow's `draftOwner`), so the new chat opened after it has the workspace's draft to itself. That key ends, and its draft and sends in flight go back to the workspace's (`foldDraft`), when its tab closes, its chat is replaced or forgotten, or its composer leaves the key (its session, another workspace). - **In-session branch** (Continue / BranchNavigator): a read-only historical view of the entry tree through `/api/sessions/[id]/context?leafId=` (`handleLeafChange`); it does not change the live agent. Never implement Edit with it. ### ToolCall field normalization diff --git a/components/AppShell.tsx b/components/AppShell.tsx index fa8dd04e..d7b52024 100644 --- a/components/AppShell.tsx +++ b/components/AppShell.tsx @@ -45,13 +45,13 @@ import type { WorkspaceFileSource } from "@/lib/workspace-types"; import { buildAtMentionText, buildFileAtMentionsText, buildFileLineMentionText } from "@/lib/file-fuzzy"; import { findSessionTarget, getInitialNavigation, sameSessionTarget, sessionNavigationUrl } from "@/lib/initial-navigation"; import { comparableProjectPath } from "@/lib/comparable-path"; -import { foldedHostProjectKey, hostProjectKey, LOCAL_HOST_ID, remoteHostId, projectIdentity, projectTargetId } from "@/lib/project-ordering"; +import { foldedHostProjectKey, freshChatDraftKey, hostProjectKey, LOCAL_HOST_ID, scopedDraftKey, remoteHostId, projectIdentity, projectTargetId } from "@/lib/project-ordering"; import { isClusterTarget } from "@/lib/hosts/cluster"; import { useHostRows } from "@/hooks/useHostRows"; import { isRecord } from "@/lib/type-guards"; import { LocalDaemonBanner } from "./LocalDaemonBanner"; import { hostName, hostUnavailableReason } from "./host-status"; -import { clearDraft } from "@/lib/draft-store"; +import { clearDraft, continueDraft, foldDraft } from "@/lib/draft-store"; import { useNotifications } from "@/hooks/useNotifications"; import { APP_UPDATE_COMPLETED_RELOAD_MS, @@ -131,6 +131,15 @@ const NEW_CHAT_TAB_ID = "chat:new"; /** `scope`: set once the chat sent something and moved to a tab of its own, which gives it a composer draft of its * own (ChatWindow's `draftScope`): the new chat that opens after it has the workspace's. */ type DraftChat = { cwd: string | null; hostId?: string; project: ManagedProject | null; creationId?: string; initialization?: string; scope?: string }; +const draftKeyOf = (draft: DraftChat) => { + const fresh = freshChatDraftKey(draft.cwd, draft.hostId, draft.project?.poolId, draft.project?.projectId); + return fresh && draft.scope ? scopedDraftKey(fresh, draft.scope) : fresh; +}; +/** A closing new chat's draft of its own goes back to its workspace's (as an unsent one's stays there). */ +const foldScopedDraft = (draft: DraftChat) => { + const fresh = draftKeyOf({ ...draft, scope: undefined }); + if (fresh && draft.scope) foldDraft(scopedDraftKey(fresh, draft.scope), fresh); +}; const chatTabId = (session: SessionInfo) => `chat:${remoteHostId(session.hostId) ?? LOCAL_HOST_ID}:${session.id}`; /** The strips kept across reloads of this browser tab (sessionStorage: another window keeps its own). */ const WORKBENCH_STORAGE_KEY = "tau:workbench"; @@ -224,6 +233,9 @@ export function AppShell({ appName }: { appName: string }) { return; } const id = `${DRAFT_TAB_PREFIX}${++draftTabSeqRef.current}`; + const freshKey = draftKeyOf({ ...draft, scope: undefined }); + // Its draft moves before the new chat taking the workspace's renders (that one reads the store as it mounts). + if (!draft.scope && freshKey) continueDraft(freshKey, scopedDraftKey(freshKey, id)); setDraftTabs((tabs) => [...tabs, { id, draft: { ...draft, scope: draft.scope ?? id } }]); setNewChatScope(undefined); setTabLayout((layout) => replaceTab(layout, NEW_CHAT_TAB_ID, id)); @@ -1442,8 +1454,13 @@ export function AppShell({ appName }: { appName: string }) { }, [router, isMobile, selectedSession]); const handleNewSession = useCallback((creationId: string, cwd: string | null, hostId?: string, project?: ManagedProject, initialization?: string) => { - // Taking the kept new chat up again passes its own creation id. - if ((creationId || undefined) !== draftChatRef.current?.creationId) dropKeptDraft(); + // Taking the kept new chat up again passes its own creation id (takeUpDraft then sets its scope). + if ((creationId || undefined) !== draftChatRef.current?.creationId) { + // A shown new chat is replaced: a draft of its own goes back to its workspace's, for the chat that replaces it. + if (draftShownRef.current && draftChatRef.current) foldScopedDraft(draftChatRef.current); + dropKeptDraft(); + } + setNewChatScope(undefined); setSettingsTab(null); setFileShown(false); setSelectedSession(null); @@ -2198,7 +2215,10 @@ export function AppShell({ appName }: { appName: string }) { draftKeptRef.current = draftKept; // A new chat whose tab is gone (a chat selected into its group replaced it) is forgotten. useEffect(() => { - if (!draftTabOpen) setDraftChat(null); + if (draftTabOpen) return; + if (draftChatRef.current) foldScopedDraft(draftChatRef.current); + setDraftChat(null); + setNewChatScope(undefined); }, [draftTabOpen]); useEffect(() => { // A new chat's own tab is not saved (nor its chat): its id would name nothing after a reload. @@ -2377,8 +2397,11 @@ export function AppShell({ appName }: { appName: string }) { let selected: SessionInfo | undefined; if (id === NEW_CHAT_TAB_ID) { // Only another group's new chat closes (see draftKept); its draft stays in the store. + if (draftChat) foldScopedDraft(draftChat); setDraftChat(null); } else if (draftTabs.some((tab) => tab.id === id)) { + const closed = draftTabs.find((tab) => tab.id === id); + if (closed) foldScopedDraft(closed.draft); setDraftTabs((tabs) => tabs.filter((tab) => tab.id !== id)); } else if (!session) { handleCloseFileTab(id); diff --git a/components/ChatInput.tsx b/components/ChatInput.tsx index 2ec0ea7b..43ba95c2 100644 --- a/components/ChatInput.tsx +++ b/components/ChatInput.tsx @@ -15,7 +15,7 @@ import type { SttAfter } from "@/lib/stt"; import { formatCompactNumber, formatPercent } from "@/lib/format"; import { ContextDetailPanel } from "./ComposerPanels"; import { RecordingDeck } from "./RecordingDeck"; -import { beginDraftSubmission, clearDraft, consumeDraft, continueDraft, endDraftSubmission, getDraft, getDraftRevision, isSameDraft, markDraftEdited, mergeRecoveredText, recoverDraft, requiresPromptMode, setDraft, subscribeDraftConsumption, subscribeDraftRecovery, type ChatDraft } from "@/lib/draft-store"; +import { beginDraftSubmission, clearDraft, consumeDraft, foldDraft, moveDraftSubmissions, endDraftSubmission, getDraft, getDraftRevision, isSameDraft, markDraftEdited, mergeRecoveredText, recoverDraft, requiresPromptMode, setDraft, subscribeDraftConsumption, subscribeDraftRecovery, type ChatDraft } from "@/lib/draft-store"; import { expandWebSlashCommand } from "@/lib/web-slash-commands"; import { WorkspaceFileContext } from "@/lib/workspace-file-context"; import type { AttachedImage, AttachedTextFile } from "./ChatInput-draft-attachments"; @@ -184,6 +184,8 @@ interface Props { /** The key `draftKey` replaces for the same chat (a new chat given a draft of its own): a change from it keeps the * composer's content and moves its pending recoveries along, instead of loading another draft. */ draftKeyContinues?: string; + /** Identifies the chat across remounts of this composer (ChatWindow's): its sends move with it to a key of its own. */ + draftOwner?: object; /** Owning host for file uploads and the @ file index (this machine when absent). */ uploadHostId?: string; /** Lazily bind a pool's real owner before staging any file bytes. Failure never falls back locally. */ @@ -306,6 +308,7 @@ export const ChatInput = memo(forwardRef(function ChatIn onClearQueuedMessages, draftKey = "new:unassigned", draftKeyContinues, + draftOwner, uploadHostId = LOCAL_HOST_ID, resolveUploadHost, cwd, @@ -459,6 +462,8 @@ export const ChatInput = memo(forwardRef(function ChatIn }, [markInputEdited]); // Navigation starts a new identity, even when a draft key is later reused. const draftRecoveryIdentityRef = useRef({ key: draftKey }); + // The workspace key this composer's own key (`draftKey`) continues, while it has one. + const scopeBaseRef = useRef(draftKeyContinues); // Async dictation and slash-command completions must see the latest edit gate. const submissionBlockedRef = useRef(submissionBlocked); const valueRef = useRef(value); @@ -960,8 +965,11 @@ export const ChatInput = memo(forwardRef(function ChatIn useLayoutEffect(() => { const previousDraftKey = draftKeyRef.current; if (previousDraftKey === draftKey) return; + const leftBase = scopeBaseRef.current; + scopeBaseRef.current = draftKeyContinues; if (previousDraftKey && draftKey && previousDraftKey === draftKeyContinues) { - continueDraft(previousDraftKey, draftKey, captureDraft()); + // The same chat under a key of its own: AppShell moved its draft there (continueDraft); keep the composer as is. + moveDraftSubmissions(previousDraftKey, draftKey, draftOwner); draftKeyRef.current = draftKey; draftRecoveryIdentityRef.current = { key: draftKey }; return; @@ -978,6 +986,8 @@ export const ChatInput = memo(forwardRef(function ChatIn if (previousDraftKey) { setDraft(previousDraftKey, captureDraft()); + // A key of its own ends with the chat leaving it (its session, another workspace): its draft goes back. + if (leftBase) foldDraft(previousDraftKey, leftBase); } const draft = draftKey ? getDraft(draftKey) : null; @@ -1000,7 +1010,7 @@ export const ChatInput = memo(forwardRef(function ChatIn for (const upload of prev) if (upload.previewUrl) URL.revokeObjectURL(upload.previewUrl); return draftUploadsToAttachedUploads(draft?.uploads); }); - }, [draftKey, draftKeyContinues, setPromptOnly, captureDraft]); + }, [draftKey, draftKeyContinues, draftOwner, setPromptOnly, captureDraft]); useLayoutEffect(() => subscribeDraftRecovery((key, recovery) => { if (draftKeyRef.current !== key) return; @@ -1157,7 +1167,7 @@ export const ChatInput = memo(forwardRef(function ChatIn return; } // Owned by the store, not this mount: the chat's composer may remount, or move to a key of its own, meanwhile. - const submission = beginDraftSubmission(draftKeyRef.current); + const submission = beginDraftSubmission(draftKeyRef.current, draftOwner); clearInput(); try { const result = await pending; diff --git a/components/ChatWindow.tsx b/components/ChatWindow.tsx index 050904ce..c8d64047 100644 --- a/components/ChatWindow.tsx +++ b/components/ChatWindow.tsx @@ -39,7 +39,7 @@ import { } from "@/lib/chat-lazy-load"; import { getDraftSummary } from "@/lib/draft-store"; import { isLinkUp, type HostStatus } from "@/lib/hosts/host"; -import { newChatDraftKey } from "@/lib/project-ordering"; +import { freshChatDraftKey, scopedDraftKey } from "@/lib/project-ordering"; import { WorkspaceFileContext } from "@/lib/workspace-file-context"; import type { WorkspaceFileSource } from "@/lib/workspace-types"; import { getFileName } from "@/lib/file-paths"; @@ -556,8 +556,10 @@ export function ChatWindow({ session, newSessionCwd, newSessionHostId, newSessio // top, load another page while keeping the scroll position stable. const [visibleCount, setVisibleCount] = useState(VISIBLE_PAGE_SIZE); const prevSessionKeyForPagingRef = useRef(null); - const baseDraftKey = session?.id ?? (newSessionPoolId && newSessionProjectId ? `new:pool:${newSessionPoolId}:${newSessionProjectId}` : newSessionCwd ? newChatDraftKey(newSessionCwd, newSessionHostId) : undefined); - const draftKey = session?.id ?? (baseDraftKey && draftScope ? `${baseDraftKey}#${draftScope}` : baseDraftKey); + const freshDraftKey = freshChatDraftKey(newSessionCwd, newSessionHostId, newSessionPoolId, newSessionProjectId); + // This chat, across remounts of its composer. + const [draftOwner] = useState(() => ({})); + const draftKey = session?.id ?? (freshDraftKey && draftScope ? scopedDraftKey(freshDraftKey, draftScope) : freshDraftKey); const sessionKeyForPaging = draftKey ?? "empty"; useEffect(() => { if (prevSessionKeyForPagingRef.current !== sessionKeyForPaging) { @@ -970,7 +972,8 @@ export function ChatWindow({ session, newSessionCwd, newSessionHostId, newSessio onBuiltinCommand={handleBuiltinSlashCommand} onAudioUnlock={unlockAudio} draftKey={draftKey} - draftKeyContinues={draftScope ? baseDraftKey : undefined} + draftKeyContinues={!session && draftScope ? freshDraftKey : undefined} + draftOwner={draftOwner} uploadHostId={session ? session.hostId : newSessionHostId} resolveUploadHost={!session && newSessionPoolId ? resolveUploadHost : undefined} cwd={!session && newSessionPoolId ? null : session?.cwd ?? newSessionCwd} diff --git a/hooks/useAgentSession.rpc.test.mjs b/hooks/useAgentSession.rpc.test.mjs index e2e82c53..8f3d98ee 100644 --- a/hooks/useAgentSession.rpc.test.mjs +++ b/hooks/useAgentSession.rpc.test.mjs @@ -6132,6 +6132,64 @@ test("a kept chat whose send fails gets its text back in its own composer, not t h.view.unmount(); }); +test("text typed into a kept chat after it sent stays with it when another new chat opens", async (t) => { + let release; + const h = await draftInItsOwnGroup(t); + world.holds.push({ match: (method, url) => method === "POST" && url === "/api/agent/new", produce: () => new Promise((resolve) => { release = () => resolve({ status: 500, value: { error: "spawn failed" } }); }) }); + await act(async () => { fireEvent.change(h.draftComposer, { target: { value: "hello there" } }); await sleep(30); }); + await act(async () => { fireEvent.keyDown(h.draftComposer, { key: "Enter" }); await sleep(60); }); + await until(() => release, "the new chat is being created"); + await act(async () => { fireEvent.change(h.composerIn(h.draftGroup), { target: { value: "and more" } }); await sleep(60); }); + await act(async () => { fireEvent.pointerDown(h.composerIn(h.other)); await sleep(80); }); + await act(async () => { fireEvent.click(h.newSessionButton()); await sleep(120); }); + assert.equal(h.composerIn(h.other).value, "", "the fresh new chat starts empty"); + assert.equal(h.composerIn(h.draftGroup).value, "and more", "the kept chat keeps what was typed into it"); + // Closing the kept chat's tab gives its text and its failed prompt back to the workspace's new chat. + const kept = within(h.draftGroup).getByRole("tab", { name: translate("appShell.newSession") }); + await act(async () => { fireEvent.click(within(h.draftGroup).getByRole("button", { name: translate("tabBar.closeTab", { label: kept.textContent || translate("appShell.newSession") }) })); await sleep(120); }); + assert.match(h.composerIn(h.other).value, /and more/); + await act(async () => { release(); await sleep(300); }); + assert.match(h.composerIn(h.other).value, /hello there/, "a send that fails after its tab closed is not lost"); + // The workspace's draft outlives this view: leave it empty for the next test. + await act(async () => { fireEvent.change(h.composerIn(h.other), { target: { value: "" } }); await sleep(60); }); + h.view.unmount(); +}); + +test("two kept chats swapped in and out of the new chat's tab each keep their own draft", async (t) => { + let releaseB; + const h = await sentBesideFreshChat(t, { status: 500, value: { error: "spawn failed" } }); + // The fresh chat B sends too, then a third new chat opens: B moves to a tab of its own beside A's. + world.holds.push({ match: (method, url) => method === "POST" && url === "/api/agent/new", produce: () => new Promise((resolve) => { releaseB = () => resolve({ status: 500, value: { error: "spawn failed too" } }); }) }); + await act(async () => { fireEvent.change(h.composerIn(h.other), { target: { value: "second prompt" } }); await sleep(30); }); + await act(async () => { fireEvent.keyDown(h.composerIn(h.other), { key: "Enter" }); await sleep(60); }); + await until(() => releaseB, "B's session is being created"); + const tabA = within(h.draftGroup).getByRole("tab", { name: translate("appShell.newSession") }); + // Taking A up moves B to a tab of its own; taking B up again moves A back. + await act(async () => { fireEvent.click(tabA); await sleep(150); }); + const tabB = h.newChatTabs().find((tab) => tab !== tabA && h.other.contains(tab)) ?? h.newChatTabs().find((tab) => tab.getAttribute("aria-selected") !== "true"); + await act(async () => { fireEvent.click(tabB); await sleep(150); }); + await act(async () => { h.release(); releaseB(); await sleep(400); }); + const values = [h.composerIn(h.draftGroup).value, h.composerIn(h.other).value].sort(); + assert.deepEqual(values, ["hello there", "second prompt"], "each failed prompt is back in its own chat, once"); + for (const group of [h.draftGroup, h.other]) await act(async () => { fireEvent.change(h.composerIn(group), { target: { value: "" } }); await sleep(30); }); + h.view.unmount(); +}); + +test("a new chat that replaces a shown kept chat gets the workspace's draft, and that chat's failed prompt", async (t) => { + const h = await sentBesideFreshChat(t, { status: 500, value: { error: "spawn failed" } }); + await act(async () => { fireEvent.change(h.composerIn(h.other), { target: { value: "fresh idea" } }); await sleep(60); }); + // Taking the kept chat up closes the unsent fresh one; its draft stays with the workspace. + await act(async () => { fireEvent.click(within(h.draftGroup).getByRole("tab", { name: translate("appShell.newSession") })); await sleep(150); }); + await act(async () => { fireEvent.click(h.newSessionButton()); await sleep(150); }); + const shown = h.newChatTabs().find((tab) => tab.getAttribute("aria-selected") === "true" && h.groupOf(tab).querySelector('[data-group-focused="true"]')); + const composer = h.composerIn(h.groupOf(shown ?? h.newChatTab())); + assert.match(composer.value, /fresh idea/, "the workspace's draft, not a kept chat's key"); + await act(async () => { h.release(); await sleep(300); }); + assert.match(composer.value, /hello there/, "the replaced chat's failed prompt comes back there"); + await act(async () => { fireEvent.change(composer, { target: { value: "" } }); await sleep(30); }); + h.view.unmount(); +}); + test("another new chat replaces an unsent kept one and opens fresh in the focused group", async (t) => { const h = await draftInItsOwnGroup(t); await act(async () => { fireEvent.change(h.draftComposer, { target: { value: "unsent idea" } }); await sleep(60); }); diff --git a/lib/draft-store.test.mjs b/lib/draft-store.test.mjs index 3c0e8bd3..697ed908 100644 --- a/lib/draft-store.test.mjs +++ b/lib/draft-store.test.mjs @@ -1,7 +1,7 @@ import assert from "node:assert/strict"; import { spawnSync } from "node:child_process"; import test from "node:test"; -import { beginDraftSubmission, clearDraft, consumeDraft, continueDraft, endDraftSubmission, getDraft, getDraftRevision, getDraftSummary, markDraftEdited, mergeRecoveredText, recoverDraft, setDraft, subscribeDraftConsumption, subscribeDraftRecovery } from "./draft-store.ts"; +import { beginDraftSubmission, clearDraft, consumeDraft, continueDraft, endDraftSubmission, foldDraft, moveDraftSubmissions, getDraft, getDraftRevision, getDraftSummary, markDraftEdited, mergeRecoveredText, recoverDraft, setDraft, subscribeDraftConsumption, subscribeDraftRecovery } from "./draft-store.ts"; test("outbox consumption notifies matching drafts without clearing newer text, equal-text retypes or attachment payloads", () => { const key = "outbox-consumption"; @@ -313,16 +313,32 @@ test("a later recovery merges with an earlier one in order, unless the draft no assert.equal(mergeRecoveredText("edited", { text: "A\n\nB", replace }), "A\n\nedited", "never re-adds text the user removed"); }); -test("a continued draft moves its content and its submissions in flight to the new key, and nothing else", () => { +test("a continued draft moves its content and submissions to a key of this page only, and folds back when it ends", (t) => { + const stored = new Map(); + globalThis.sessionStorage = { getItem: (k) => stored.get(k) ?? null, setItem: (k, v) => { stored.set(k, String(v)); }, removeItem: (k) => { stored.delete(k); } }; + t.after(() => { delete globalThis.sessionStorage; }); setDraft("new:/w", { value: "typed after sending", images: [], files: [] }); - const moving = beginDraftSubmission("new:/w"); - const other = beginDraftSubmission("new:/other"); - continueDraft("new:/w", "new:/w#chat:draft:1", { value: "typed after sending", images: [], files: [] }); + const owner = {}; + const moving = beginDraftSubmission("new:/w", owner); + const other = beginDraftSubmission("new:/other", owner); + const earlier = beginDraftSubmission("new:/w", {}); + continueDraft("new:/w", "new:/w#chat:draft:1"); + moveDraftSubmissions("new:/w", "new:/w#chat:draft:1", owner); assert.equal(getDraft("new:/w"), null, "the workspace's draft is free for the next new chat"); assert.equal(getDraft("new:/w#chat:draft:1")?.value, "typed after sending"); + assert.equal(stored.has("tau-draft-new:/w#chat:draft:1"), false, "nothing reopens it after a reload"); + assert.equal(stored.has("tau-draft-new:/w"), false); assert.equal(moving.key, "new:/w#chat:draft:1", "a failed send recovers to the chat's own key"); assert.equal(other.key, "new:/other"); + assert.equal(earlier.key, "new:/w", "another chat's send in flight from the workspace's key stays there"); + setDraft("new:/w", { value: "fresh", images: [], files: [] }); + foldDraft("new:/w#chat:draft:1", "new:/w"); + assert.equal(getDraft("new:/w#chat:draft:1"), null); + assert.match(getDraft("new:/w")?.value ?? "", /fresh[\s\S]*typed after sending|typed after sending[\s\S]*fresh/, "both texts are kept"); + assert.equal(moving.key, "new:/w", "and its sends in flight recover there"); + assert.ok(stored.has("tau-draft-new:/w"), "the workspace's draft is kept across reloads again"); endDraftSubmission(moving); endDraftSubmission(other); - clearDraft("new:/w#chat:draft:1"); + endDraftSubmission(earlier); + clearDraft("new:/w"); }); diff --git a/lib/draft-store.ts b/lib/draft-store.ts index 3a116165..13c7dffd 100644 --- a/lib/draft-store.ts +++ b/lib/draft-store.ts @@ -54,6 +54,7 @@ declare global { var __tauChatDrafts: Map | undefined; var __tauChatDraftListeners: Set<() => void> | undefined; var __tauChatDraftRecoveryListeners: Set<(key: string, recovery: DraftRecovery) => void> | undefined; + var __tauChatDraftTransientKeys: Set | undefined; var __tauChatDraftConsumptionListeners: Set<(key: string, snapshot: ChatDraft) => void> | undefined; var __tauChatDraftRevisions: { byKey: Map; last: number } | undefined; var __tauChatDraftSubmissions: Set | undefined; @@ -151,12 +152,12 @@ export function markDraftEdited(key: string): void { /** A submission waiting for its durable commit, owned by this store (not by the composer mount that sent it, which may * be gone by the time the commit lands). `edited` records any edit since it was sent. */ -export interface DraftSubmission { key: string | undefined; snapshot: ChatDraft | null; revision: number; edited: boolean } +export interface DraftSubmission { key: string | undefined; snapshot: ChatDraft | null; revision: number; edited: boolean; owner?: object } /** Starts tracking the draft at `key`. Every submission MUST be ended (`endDraftSubmission`) once its commit settles, * whether it was stored, refused or failed. */ -export function beginDraftSubmission(key: string | undefined): DraftSubmission { - const submission: DraftSubmission = { key, snapshot: key ? getDraft(key) : null, revision: key ? getDraftRevision(key) : -1, edited: false }; +export function beginDraftSubmission(key: string | undefined, owner?: object): DraftSubmission { + const submission: DraftSubmission = { key, snapshot: key ? getDraft(key) : null, revision: key ? getDraftRevision(key) : -1, edited: false, owner }; submissions.add(submission); return submission; } @@ -267,7 +268,7 @@ export function setDraft(key: string, draft: ChatDraft): void { markSubmissionsEdited(key); } drafts.set(key, next); - try { + if (!transientKeys.has(key)) try { // Persist only text: attachment payloads can exhaust the tab's storage quota. // Mark prompt provenance before publishing its text; never restore that text as a shell command after reload. if (next.promptOnly) sessionStorage.setItem(PROMPT_STORAGE_PREFIX + key, "1"); @@ -297,10 +298,32 @@ export function clearDraft(key: string): void { } } -/** The same chat continues under `to` (a new chat given a draft of its own): `draft` (the composer's current one) - * is stored there, `from` is cleared, and submissions still in flight from `from` recover to `to`. */ -export function continueDraft(from: string, to: string, draft: ChatDraft): void { +/** Keys of drafts that live only as long as this page (`continueDraft`): kept out of sessionStorage, since nothing + * reopens them after a reload. */ +const transientKeys = (globalThis.__tauChatDraftTransientKeys ??= new Set()); + +/** Submissions in flight from `from` (only `owner`'s, when given) recover to `to` from now on. */ +export function moveDraftSubmissions(from: string, to: string, owner?: object): void { + for (const submission of submissions) if (submission.key === from && (!owner || submission.owner === owner)) submission.key = to; +} + +/** The same chat continues under `to`, a key of its own for this page only (a new chat that sent and moved to a tab of + * its own): `from`'s draft moves there. Call it before the chat that takes `from` over renders; that chat's composer + * moves its own submissions (`moveDraftSubmissions`). */ +export function continueDraft(from: string, to: string): void { + transientKeys.add(to); + const draft = getDraft(from); + clearDraft(from); + if (draft) setDraft(to, draft); + else clearDraft(to); +} + +/** `continueDraft` undone once that key ends (its tab closed, its chat left it): what it holds is recovered into + * `to`, as into any composer, and its submissions in flight recover there too. */ +export function foldDraft(from: string, to: string): void { + const draft = getDraft(from); clearDraft(from); - setDraft(to, draft); - for (const submission of submissions) if (submission.key === from) submission.key = to; + transientKeys.delete(from); + moveDraftSubmissions(from, to); + if (draft) recoverDraft(to, { text: draft.value, images: draft.images.length ? draft.images : undefined, files: draft.files.length ? draft.files : undefined, uploads: draft.uploads, ...(draft.promptOnly ? { promptOnly: true } : {}) }); } diff --git a/lib/project-ordering.ts b/lib/project-ordering.ts index 32a1c54d..4a9fc58f 100644 --- a/lib/project-ordering.ts +++ b/lib/project-ordering.ts @@ -36,6 +36,14 @@ export function newChatDraftKey(cwd: string, hostId: string | undefined): string return `new:${hostProjectKey(hostId, cwd)}`; } +/** Composer draft key of a new chat (ChatWindow's): a pool project's, else its workspace's. */ +export function freshChatDraftKey(cwd: string | null | undefined, hostId: string | undefined, poolId?: string, projectId?: string): string | undefined { + return poolId && projectId ? `new:pool:${poolId}:${projectId}` : cwd ? newChatDraftKey(cwd, hostId) : undefined; +} + +/** A new chat's draft key of its own (AppShell's DraftChat.scope) over its workspace's. */ +export const scopedDraftKey = (freshKey: string, scope: string) => `${freshKey}#${scope}`; + /** `hostProjectKey` over the case-folded comparable path (how sessions find their project). */ export function foldedHostProjectKey(hostId: string | undefined, path: string): string { return path.startsWith("pool:") ? path : hostProjectKey(hostId, comparableProjectPath(path)); From d3c219145aa1cb04a5b08a1372beeaf0a22f9665 Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Fri, 27 Nov 2026 06:27:34 +0000 Subject: [PATCH 04/13] fix(tabs): keep a kept chat's draft across reloads and workspace changes; move its sends with its draft --- components/AppShell.tsx | 32 +++++++++++++---------- components/ChatInput.tsx | 13 +++++----- components/ChatWindow.tsx | 14 +++++----- hooks/useAgentSession.rpc.test.mjs | 3 +++ lib/draft-store.test.mjs | 12 ++++----- lib/draft-store.ts | 41 +++++++++++++++++++++--------- lib/project-ordering.test.mjs | 12 +++++++++ lib/project-ordering.ts | 8 ++++-- 8 files changed, 87 insertions(+), 48 deletions(-) diff --git a/components/AppShell.tsx b/components/AppShell.tsx index d7b52024..3fd75aab 100644 --- a/components/AppShell.tsx +++ b/components/AppShell.tsx @@ -45,7 +45,7 @@ import type { WorkspaceFileSource } from "@/lib/workspace-types"; import { buildAtMentionText, buildFileAtMentionsText, buildFileLineMentionText } from "@/lib/file-fuzzy"; import { findSessionTarget, getInitialNavigation, sameSessionTarget, sessionNavigationUrl } from "@/lib/initial-navigation"; import { comparableProjectPath } from "@/lib/comparable-path"; -import { foldedHostProjectKey, freshChatDraftKey, hostProjectKey, LOCAL_HOST_ID, scopedDraftKey, remoteHostId, projectIdentity, projectTargetId } from "@/lib/project-ordering"; +import { effectiveDraftKey, foldedHostProjectKey, freshChatDraftKey, hostProjectKey, LOCAL_HOST_ID, scopedDraftBase, scopedDraftKey, remoteHostId, projectIdentity, projectTargetId } from "@/lib/project-ordering"; import { isClusterTarget } from "@/lib/hosts/cluster"; import { useHostRows } from "@/hooks/useHostRows"; import { isRecord } from "@/lib/type-guards"; @@ -128,17 +128,13 @@ const OPEN_URL_AUTOMATICALLY_STORAGE_KEY = "tau:open-url-automatically"; /** The transient tab of a chat not yet sent (no session yet). */ const NEW_CHAT_TAB_ID = "chat:new"; /** An unsent new chat's target, as it was last shown. */ -/** `scope`: set once the chat sent something and moved to a tab of its own, which gives it a composer draft of its - * own (ChatWindow's `draftScope`): the new chat that opens after it has the workspace's. */ +/** `scope`: the composer draft key of its own (`scopedDraftKey`) a chat gets once it sent something and moved to a tab + * of its own (ChatWindow's `draftScope`): the new chat that opens after it has the workspace's. */ type DraftChat = { cwd: string | null; hostId?: string; project: ManagedProject | null; creationId?: string; initialization?: string; scope?: string }; -const draftKeyOf = (draft: DraftChat) => { - const fresh = freshChatDraftKey(draft.cwd, draft.hostId, draft.project?.poolId, draft.project?.projectId); - return fresh && draft.scope ? scopedDraftKey(fresh, draft.scope) : fresh; -}; +const freshKeyOf = (draft: DraftChat) => freshChatDraftKey(draft.cwd, draft.hostId, draft.project?.poolId, draft.project?.projectId); /** A closing new chat's draft of its own goes back to its workspace's (as an unsent one's stays there). */ const foldScopedDraft = (draft: DraftChat) => { - const fresh = draftKeyOf({ ...draft, scope: undefined }); - if (fresh && draft.scope) foldDraft(scopedDraftKey(fresh, draft.scope), fresh); + if (draft.scope) foldDraft(draft.scope, scopedDraftBase(draft.scope)); }; const chatTabId = (session: SessionInfo) => `chat:${remoteHostId(session.hostId) ?? LOCAL_HOST_ID}:${session.id}`; /** The strips kept across reloads of this browser tab (sessionStorage: another window keeps its own). */ @@ -233,10 +229,15 @@ export function AppShell({ appName }: { appName: string }) { return; } const id = `${DRAFT_TAB_PREFIX}${++draftTabSeqRef.current}`; - const freshKey = draftKeyOf({ ...draft, scope: undefined }); - // Its draft moves before the new chat taking the workspace's renders (that one reads the store as it mounts). - if (!draft.scope && freshKey) continueDraft(freshKey, scopedDraftKey(freshKey, id)); - setDraftTabs((tabs) => [...tabs, { id, draft: { ...draft, scope: draft.scope ?? id } }]); + const freshKey = freshKeyOf(draft); + let scope = effectiveDraftKey(freshKey, draft.scope); + if (freshKey && scope === freshKey) { + // Its draft and its sends in flight move before the new chat taking the workspace's renders (that one reads the + // store as it mounts). + scope = scopedDraftKey(freshKey, id); + continueDraft(freshKey, scope, key); + } + setDraftTabs((tabs) => [...tabs, { id, draft: { ...draft, scope } }]); setNewChatScope(undefined); setTabLayout((layout) => replaceTab(layout, NEW_CHAT_TAB_ID, id)); setChatMounts((mounts) => moveChatMount(mounts, NEW_CHAT_TAB_ID, id)); @@ -2396,7 +2397,8 @@ export function AppShell({ appName }: { appName: string }) { const session = chatTabById(id); let selected: SessionInfo | undefined; if (id === NEW_CHAT_TAB_ID) { - // Only another group's new chat closes (see draftKept); its draft stays in the store. + // Only another group's new chat closes (see draftKept); its draft stays in the store (folded back into its + // workspace's when it had one of its own). if (draftChat) foldScopedDraft(draftChat); setDraftChat(null); } else if (draftTabs.some((tab) => tab.id === id)) { @@ -3120,6 +3122,7 @@ export function AppShell({ appName }: { appName: string }) { key={key ?? undefined} session={null} draftScope={draft.scope} + draftOwner={key ?? undefined} newSessionCwd={draft.cwd} newSessionHostId={draft.hostId} newSessionCreationId={draft.project?.poolId ? draft.creationId : undefined} @@ -3299,6 +3302,7 @@ export function AppShell({ appName }: { appName: string }) { key={chatKey ?? undefined} session={selectedSession} draftScope={newChatScope} + draftOwner={chatKey ?? undefined} headerActions={chatPill} newSessionCwd={effectiveNewSessionCwd} newSessionHostId={newSessionHost} diff --git a/components/ChatInput.tsx b/components/ChatInput.tsx index 43ba95c2..2b139a80 100644 --- a/components/ChatInput.tsx +++ b/components/ChatInput.tsx @@ -15,7 +15,7 @@ import type { SttAfter } from "@/lib/stt"; import { formatCompactNumber, formatPercent } from "@/lib/format"; import { ContextDetailPanel } from "./ComposerPanels"; import { RecordingDeck } from "./RecordingDeck"; -import { beginDraftSubmission, clearDraft, consumeDraft, foldDraft, moveDraftSubmissions, endDraftSubmission, getDraft, getDraftRevision, isSameDraft, markDraftEdited, mergeRecoveredText, recoverDraft, requiresPromptMode, setDraft, subscribeDraftConsumption, subscribeDraftRecovery, type ChatDraft } from "@/lib/draft-store"; +import { beginDraftSubmission, clearDraft, consumeDraft, foldDraft, endDraftSubmission, getDraft, getDraftRevision, isSameDraft, markDraftEdited, mergeRecoveredText, recoverDraft, requiresPromptMode, setDraft, subscribeDraftConsumption, subscribeDraftRecovery, type ChatDraft } from "@/lib/draft-store"; import { expandWebSlashCommand } from "@/lib/web-slash-commands"; import { WorkspaceFileContext } from "@/lib/workspace-file-context"; import type { AttachedImage, AttachedTextFile } from "./ChatInput-draft-attachments"; @@ -184,8 +184,8 @@ interface Props { /** The key `draftKey` replaces for the same chat (a new chat given a draft of its own): a change from it keeps the * composer's content and moves its pending recoveries along, instead of loading another draft. */ draftKeyContinues?: string; - /** Identifies the chat across remounts of this composer (ChatWindow's): its sends move with it to a key of its own. */ - draftOwner?: object; + /** Identifies the chat across remounts of this composer (AppShell's mount key): its sends move with its draft. */ + draftOwner?: string; /** Owning host for file uploads and the @ file index (this machine when absent). */ uploadHostId?: string; /** Lazily bind a pool's real owner before staging any file bytes. Failure never falls back locally. */ @@ -968,9 +968,10 @@ export const ChatInput = memo(forwardRef(function ChatIn const leftBase = scopeBaseRef.current; scopeBaseRef.current = draftKeyContinues; if (previousDraftKey && draftKey && previousDraftKey === draftKeyContinues) { - // The same chat under a key of its own: AppShell moved its draft there (continueDraft); keep the composer as is. - moveDraftSubmissions(previousDraftKey, draftKey, draftOwner); + // The same chat under a key of its own: AppShell moved its draft and sends there (continueDraft); keep the + // composer as is, with any edit of this commit. draftKeyRef.current = draftKey; + setDraft(draftKey, captureDraft()); draftRecoveryIdentityRef.current = { key: draftKey }; return; } @@ -1010,7 +1011,7 @@ export const ChatInput = memo(forwardRef(function ChatIn for (const upload of prev) if (upload.previewUrl) URL.revokeObjectURL(upload.previewUrl); return draftUploadsToAttachedUploads(draft?.uploads); }); - }, [draftKey, draftKeyContinues, draftOwner, setPromptOnly, captureDraft]); + }, [draftKey, draftKeyContinues, setPromptOnly, captureDraft]); useLayoutEffect(() => subscribeDraftRecovery((key, recovery) => { if (draftKeyRef.current !== key) return; diff --git a/components/ChatWindow.tsx b/components/ChatWindow.tsx index c8d64047..2a401c6b 100644 --- a/components/ChatWindow.tsx +++ b/components/ChatWindow.tsx @@ -39,7 +39,7 @@ import { } from "@/lib/chat-lazy-load"; import { getDraftSummary } from "@/lib/draft-store"; import { isLinkUp, type HostStatus } from "@/lib/hosts/host"; -import { freshChatDraftKey, scopedDraftKey } from "@/lib/project-ordering"; +import { effectiveDraftKey, freshChatDraftKey } from "@/lib/project-ordering"; import { WorkspaceFileContext } from "@/lib/workspace-file-context"; import type { WorkspaceFileSource } from "@/lib/workspace-types"; import { getFileName } from "@/lib/file-paths"; @@ -53,8 +53,10 @@ interface Props { newSessionPoolId?: string; newSessionProjectId?: string; newSessionInitialization?: string; - /** A new chat's draft of its own (DraftChat.scope in AppShell); without it the chat has the workspace's. */ + /** A new chat's draft key of its own (DraftChat.scope in AppShell); without it the chat has the workspace's. */ draftScope?: string; + /** This chat across remounts (AppShell's mount key): its sends in flight move with its draft. */ + draftOwner?: string; onNewSessionInitialization?: (body: string) => void; /** The chat's host from the `hosts` channel: the source of truth until a * `host_status` frame reports a change, and for a chat opened mid-outage. */ @@ -398,7 +400,7 @@ const CommittedTranscript = memo(function CommittedTranscript({ ); }); -export function ChatWindow({ session, newSessionCwd, newSessionHostId, newSessionCreationId, newSessionPoolId, newSessionProjectId, newSessionInitialization, draftScope, onNewSessionInitialization, hostStatus: channelHostStatus, hostLabel, newSessionWorkspace, headerActions, toolCallsDefaultCollapsed = true, hideToolActivity = true, neverFoldActivity = false, showToolCallsUnfolded = false, expandThinkingByDefault = false, hideThinkingBlock = false, onAgentEnd, onSessionCreated, onSent, onSessionForked, modelsRefreshKey, chatInputRef, sessionInfoContainer, onBranchDataChange, onSystemPromptChange, onSystemPromptLoaderChange, onSessionStatsChange, onSessionStatsPanelOpen, onGenerationSpeedChange, onOpenFile: onOpenWorkspaceFile, onOpenUrl, onOpenProviders, searchQuery = "", searchTarget = null, onSearchTargetHandled, covered = false }: Props) { +export function ChatWindow({ session, newSessionCwd, newSessionHostId, newSessionCreationId, newSessionPoolId, newSessionProjectId, newSessionInitialization, draftScope, draftOwner, onNewSessionInitialization, hostStatus: channelHostStatus, hostLabel, newSessionWorkspace, headerActions, toolCallsDefaultCollapsed = true, hideToolActivity = true, neverFoldActivity = false, showToolCallsUnfolded = false, expandThinkingByDefault = false, hideThinkingBlock = false, onAgentEnd, onSessionCreated, onSent, onSessionForked, modelsRefreshKey, chatInputRef, sessionInfoContainer, onBranchDataChange, onSystemPromptChange, onSystemPromptLoaderChange, onSessionStatsChange, onSessionStatsPanelOpen, onGenerationSpeedChange, onOpenFile: onOpenWorkspaceFile, onOpenUrl, onOpenProviders, searchQuery = "", searchTarget = null, onSearchTargetHandled, covered = false }: Props) { const { t, tn } = useI18n(); const fileSource = useMemo(() => ({ hostId: session?.hostId ?? newSessionHostId ?? "local", @@ -557,9 +559,7 @@ export function ChatWindow({ session, newSessionCwd, newSessionHostId, newSessio const [visibleCount, setVisibleCount] = useState(VISIBLE_PAGE_SIZE); const prevSessionKeyForPagingRef = useRef(null); const freshDraftKey = freshChatDraftKey(newSessionCwd, newSessionHostId, newSessionPoolId, newSessionProjectId); - // This chat, across remounts of its composer. - const [draftOwner] = useState(() => ({})); - const draftKey = session?.id ?? (freshDraftKey && draftScope ? scopedDraftKey(freshDraftKey, draftScope) : freshDraftKey); + const draftKey = session?.id ?? effectiveDraftKey(freshDraftKey, draftScope); const sessionKeyForPaging = draftKey ?? "empty"; useEffect(() => { if (prevSessionKeyForPagingRef.current !== sessionKeyForPaging) { @@ -972,7 +972,7 @@ export function ChatWindow({ session, newSessionCwd, newSessionHostId, newSessio onBuiltinCommand={handleBuiltinSlashCommand} onAudioUnlock={unlockAudio} draftKey={draftKey} - draftKeyContinues={!session && draftScope ? freshDraftKey : undefined} + draftKeyContinues={!session && draftKey !== freshDraftKey ? freshDraftKey : undefined} draftOwner={draftOwner} uploadHostId={session ? session.hostId : newSessionHostId} resolveUploadHost={!session && newSessionPoolId ? resolveUploadHost : undefined} diff --git a/hooks/useAgentSession.rpc.test.mjs b/hooks/useAgentSession.rpc.test.mjs index 8f3d98ee..4f71e0ca 100644 --- a/hooks/useAgentSession.rpc.test.mjs +++ b/hooks/useAgentSession.rpc.test.mjs @@ -6144,6 +6144,9 @@ test("text typed into a kept chat after it sent stays with it when another new c await act(async () => { fireEvent.click(h.newSessionButton()); await sleep(120); }); assert.equal(h.composerIn(h.other).value, "", "the fresh new chat starts empty"); assert.equal(h.composerIn(h.draftGroup).value, "and more", "the kept chat keeps what was typed into it"); + assert.equal(window.sessionStorage.getItem("tau-draft-new:pool:workers:app#chat:draft:1"), null, "its own key is not reopened after a reload"); + window.dispatchEvent(new Event("pagehide")); + assert.match(window.sessionStorage.getItem("tau-draft-new:pool:workers:app") ?? "", /and more/, "a reload finds its text in the workspace's draft"); // Closing the kept chat's tab gives its text and its failed prompt back to the workspace's new chat. const kept = within(h.draftGroup).getByRole("tab", { name: translate("appShell.newSession") }); await act(async () => { fireEvent.click(within(h.draftGroup).getByRole("button", { name: translate("tabBar.closeTab", { label: kept.textContent || translate("appShell.newSession") }) })); await sleep(120); }); diff --git a/lib/draft-store.test.mjs b/lib/draft-store.test.mjs index 697ed908..be63e83a 100644 --- a/lib/draft-store.test.mjs +++ b/lib/draft-store.test.mjs @@ -1,7 +1,7 @@ import assert from "node:assert/strict"; import { spawnSync } from "node:child_process"; import test from "node:test"; -import { beginDraftSubmission, clearDraft, consumeDraft, continueDraft, endDraftSubmission, foldDraft, moveDraftSubmissions, getDraft, getDraftRevision, getDraftSummary, markDraftEdited, mergeRecoveredText, recoverDraft, setDraft, subscribeDraftConsumption, subscribeDraftRecovery } from "./draft-store.ts"; +import { beginDraftSubmission, clearDraft, consumeDraft, continueDraft, endDraftSubmission, foldDraft, getDraft, getDraftRevision, getDraftSummary, markDraftEdited, mergeRecoveredText, recoverDraft, setDraft, subscribeDraftConsumption, subscribeDraftRecovery } from "./draft-store.ts"; test("outbox consumption notifies matching drafts without clearing newer text, equal-text retypes or attachment payloads", () => { const key = "outbox-consumption"; @@ -318,12 +318,10 @@ test("a continued draft moves its content and submissions to a key of this page globalThis.sessionStorage = { getItem: (k) => stored.get(k) ?? null, setItem: (k, v) => { stored.set(k, String(v)); }, removeItem: (k) => { stored.delete(k); } }; t.after(() => { delete globalThis.sessionStorage; }); setDraft("new:/w", { value: "typed after sending", images: [], files: [] }); - const owner = {}; - const moving = beginDraftSubmission("new:/w", owner); - const other = beginDraftSubmission("new:/other", owner); - const earlier = beginDraftSubmission("new:/w", {}); - continueDraft("new:/w", "new:/w#chat:draft:1"); - moveDraftSubmissions("new:/w", "new:/w#chat:draft:1", owner); + const moving = beginDraftSubmission("new:/w", "chat:new"); + const other = beginDraftSubmission("new:/other", "chat:new"); + const earlier = beginDraftSubmission("new:/w", "chat:new~1"); + continueDraft("new:/w", "new:/w#chat:draft:1", "chat:new"); assert.equal(getDraft("new:/w"), null, "the workspace's draft is free for the next new chat"); assert.equal(getDraft("new:/w#chat:draft:1")?.value, "typed after sending"); assert.equal(stored.has("tau-draft-new:/w#chat:draft:1"), false, "nothing reopens it after a reload"); diff --git a/lib/draft-store.ts b/lib/draft-store.ts index 13c7dffd..ecb5f802 100644 --- a/lib/draft-store.ts +++ b/lib/draft-store.ts @@ -54,7 +54,8 @@ declare global { var __tauChatDrafts: Map | undefined; var __tauChatDraftListeners: Set<() => void> | undefined; var __tauChatDraftRecoveryListeners: Set<(key: string, recovery: DraftRecovery) => void> | undefined; - var __tauChatDraftTransientKeys: Set | undefined; + var __tauChatDraftTransientKeys: Map | undefined; + var __tauChatDraftPagehide: boolean | undefined; var __tauChatDraftConsumptionListeners: Set<(key: string, snapshot: ChatDraft) => void> | undefined; var __tauChatDraftRevisions: { byKey: Map; last: number } | undefined; var __tauChatDraftSubmissions: Set | undefined; @@ -152,11 +153,11 @@ export function markDraftEdited(key: string): void { /** A submission waiting for its durable commit, owned by this store (not by the composer mount that sent it, which may * be gone by the time the commit lands). `edited` records any edit since it was sent. */ -export interface DraftSubmission { key: string | undefined; snapshot: ChatDraft | null; revision: number; edited: boolean; owner?: object } +export interface DraftSubmission { key: string | undefined; snapshot: ChatDraft | null; revision: number; edited: boolean; owner?: string } /** Starts tracking the draft at `key`. Every submission MUST be ended (`endDraftSubmission`) once its commit settles, * whether it was stored, refused or failed. */ -export function beginDraftSubmission(key: string | undefined, owner?: object): DraftSubmission { +export function beginDraftSubmission(key: string | undefined, owner?: string): DraftSubmission { const submission: DraftSubmission = { key, snapshot: key ? getDraft(key) : null, revision: key ? getDraftRevision(key) : -1, edited: false, owner }; submissions.add(submission); return submission; @@ -298,24 +299,40 @@ export function clearDraft(key: string): void { } } -/** Keys of drafts that live only as long as this page (`continueDraft`): kept out of sessionStorage, since nothing - * reopens them after a reload. */ -const transientKeys = (globalThis.__tauChatDraftTransientKeys ??= new Set()); +/** Keys of drafts that live only as long as this page (`continueDraft`), with the key each continues: kept out of + * sessionStorage, where their text is added to that key's as the page is hidden (a reload reopens no such key). */ +const transientKeys = (globalThis.__tauChatDraftTransientKeys ??= new Map()); +if (typeof window !== "undefined" && !globalThis.__tauChatDraftPagehide) { + globalThis.__tauChatDraftPagehide = true; + window.addEventListener("pagehide", () => { + const texts = new Map(); + for (const [key, base] of transientKeys) { + const text = drafts.get(key)?.value; + if (text) texts.set(base, mergeRecoveredText(texts.get(base) ?? drafts.get(base)?.value ?? "", { text })); + } + try { + for (const [base, text] of texts) sessionStorage.setItem(STORAGE_PREFIX + base, text); + } catch { + // Storage may be unavailable. + } + }); +} /** Submissions in flight from `from` (only `owner`'s, when given) recover to `to` from now on. */ -export function moveDraftSubmissions(from: string, to: string, owner?: object): void { - for (const submission of submissions) if (submission.key === from && (!owner || submission.owner === owner)) submission.key = to; +function moveDraftSubmissions(from: string, to: string, owner?: string): void { + for (const submission of submissions) if (submission.key === from && (owner === undefined || submission.owner === owner)) submission.key = to; } /** The same chat continues under `to`, a key of its own for this page only (a new chat that sent and moved to a tab of - * its own): `from`'s draft moves there. Call it before the chat that takes `from` over renders; that chat's composer - * moves its own submissions (`moveDraftSubmissions`). */ -export function continueDraft(from: string, to: string): void { - transientKeys.add(to); + * its own): `from`'s draft moves there, and so do the sends in flight that `owner`'s composer began. Call it before + * the chat that takes `from` over renders. */ +export function continueDraft(from: string, to: string, owner: string | undefined): void { + transientKeys.set(to, from); const draft = getDraft(from); clearDraft(from); if (draft) setDraft(to, draft); else clearDraft(to); + if (owner !== undefined) moveDraftSubmissions(from, to, owner); } /** `continueDraft` undone once that key ends (its tab closed, its chat left it): what it holds is recovered into diff --git a/lib/project-ordering.test.mjs b/lib/project-ordering.test.mjs index ae87b855..0c4694f3 100644 --- a/lib/project-ordering.test.mjs +++ b/lib/project-ordering.test.mjs @@ -7,6 +7,9 @@ const { groupSessionsByProject, hostProjectKey, newChatDraftKey, + effectiveDraftKey, + scopedDraftBase, + scopedDraftKey, projectActivityCounts, nextPinOrder, orderProjects, @@ -323,3 +326,12 @@ test("a fresh chat's draft key keeps the pre-hosts form here and names the host // Drafts for one path on two hosts must not share a composer key. assert.equal(newChatDraftKey("/remote/work", "h1"), "new:h1:/remote/work"); }); + +test("a new chat's draft key of its own holds only while its workspace is the one it continues", () => { + const scope = scopedDraftKey("new:/a#1", "chat:draft:1"); + assert.equal(scopedDraftBase(scope), "new:/a#1", "a `#` in the path stays in the base"); + assert.equal(effectiveDraftKey("new:/a#1", scope), scope); + assert.equal(effectiveDraftKey("new:/b", scope), "new:/b", "another workspace has its own draft"); + assert.equal(effectiveDraftKey("new:/a#1", undefined), "new:/a#1"); + assert.equal(effectiveDraftKey(undefined, scope), undefined); +}); diff --git a/lib/project-ordering.ts b/lib/project-ordering.ts index 4a9fc58f..b443c205 100644 --- a/lib/project-ordering.ts +++ b/lib/project-ordering.ts @@ -41,8 +41,12 @@ export function freshChatDraftKey(cwd: string | null | undefined, hostId: string return poolId && projectId ? `new:pool:${poolId}:${projectId}` : cwd ? newChatDraftKey(cwd, hostId) : undefined; } -/** A new chat's draft key of its own (AppShell's DraftChat.scope) over its workspace's. */ -export const scopedDraftKey = (freshKey: string, scope: string) => `${freshKey}#${scope}`; +/** A new chat's draft key of its own (AppShell's DraftChat.scope) over its workspace's `freshKey`; `tag` has no `#`. */ +export const scopedDraftKey = (freshKey: string, tag: string) => `${freshKey}#${tag}`; +/** The workspace key a `scopedDraftKey` continues. */ +export const scopedDraftBase = (scoped: string) => scoped.slice(0, scoped.lastIndexOf("#")); +/** `scope` when it continues `freshKey` (it does not once the chat's workspace changed), else `freshKey`. */ +export const effectiveDraftKey = (freshKey: string | undefined, scope: string | undefined) => freshKey && scope && scopedDraftBase(scope) === freshKey ? scope : freshKey; /** `hostProjectKey` over the case-folded comparable path (how sessions find their project). */ export function foldedHostProjectKey(hostId: string | undefined, path: string): string { From 2732a7cf39f8a89994f691c23350b153589b9931 Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Fri, 27 Nov 2026 06:45:22 +0000 Subject: [PATCH 05/13] fix(chat): a new chat that sent has a draft of its own; its failed prompt follows it --- AGENTS.md | 2 +- components/AppShell.tsx | 56 ++++----------------- components/ChatInput.tsx | 40 ++++----------- components/ChatWindow.tsx | 26 ++++++---- hooks/useAgentSession.rpc.test.mjs | 63 ++++++++++++----------- hooks/useAgentSession.ts | 7 ++- lib/draft-store.test.mjs | 36 +++++-------- lib/draft-store.ts | 81 +++++++++++------------------- lib/project-ordering.test.mjs | 20 -------- lib/project-ordering.ts | 12 ----- 10 files changed, 115 insertions(+), 228 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index d87c392d..65dde0a6 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -370,7 +370,7 @@ Browser keys use `tau-` / `tau:` (`tau-theme`, the `tau-theme-color` cookie, `ta - Prefill only the selected message's text, never its images. Preserve drafts, newer typing and attachments through pending edits, cancellation, errors and navigation. `submissionBlocked` keeps asynchronous dictation from submitting or clearing the composer. `session_history_changed` carries the leaf marker; the initiating tab deduplicates its own echo. Editing does not undo tool side effects. - Draft text survives reload via sessionStorage; attachment payloads stay in memory. - Event connections own their readiness waits: replacement and unmount settle the old wait as closed and close its observer; stale continuations must not attach streams or authorize operations. A new chat's first prompt is the exception: when its chat unmounts while pi spawns, `handleSend` still sends it and returns `accepted`. A new chat left for another group's chat stays mounted there instead; its session then replaces its tab in place without being selected (`handleSessionCreated`). Existing sessions' messages go through the outbox. - - `ChatInput.onSend` returns `Promise` (`accepted` / `rejected` / `superseded`). With `outbox` the composer clears only once the message is stored in the browser's outbox and only if it still holds what was sent. For a new chat only rejection restores the draft (`recoverDraft`; the composer owns recovery) to the key the draft store's submission names, so it follows the chat when its composer remounts or the chat gets a draft of its own; superseded failures never reinsert a processed turn. A new chat that sent and moved to a tab of its own (`DraftChat.scope`) keeps its draft under `new:…#`, a key of this page only (`continueDraft`, before the next new chat renders; its composer moves its own sends in flight, `moveDraftSubmissions` with ChatWindow's `draftOwner`), so the new chat opened after it has the workspace's draft to itself. That key ends, and its draft and sends in flight go back to the workspace's (`foldDraft`), when its tab closes, its chat is replaced or forgotten, or its composer leaves the key (its session, another workspace). + - `ChatInput.onSend` returns `Promise` (`accepted` / `rejected` / `superseded`). With `outbox` the composer clears only once the message is stored in the browser's outbox and only if it still holds what was sent. For a new chat only rejection restores the draft (`recoverDraft`; the composer owns recovery), into the draft its chat shows when the reply comes (`draftOwner`, `holdDraftOwner`), else the key captured at the send; superseded failures never reinsert a processed turn. A new chat that sent has a draft of its own, `#sent:`, for this page only (`transientDraftKey`), until its session takes over: another new chat on the workspace, which may open meanwhile (a kept chat's draft tab), has the workspace's. - **In-session branch** (Continue / BranchNavigator): a read-only historical view of the entry tree through `/api/sessions/[id]/context?leafId=` (`handleLeafChange`); it does not change the live agent. Never implement Edit with it. ### ToolCall field normalization diff --git a/components/AppShell.tsx b/components/AppShell.tsx index 3fd75aab..5840bcc5 100644 --- a/components/AppShell.tsx +++ b/components/AppShell.tsx @@ -45,13 +45,13 @@ import type { WorkspaceFileSource } from "@/lib/workspace-types"; import { buildAtMentionText, buildFileAtMentionsText, buildFileLineMentionText } from "@/lib/file-fuzzy"; import { findSessionTarget, getInitialNavigation, sameSessionTarget, sessionNavigationUrl } from "@/lib/initial-navigation"; import { comparableProjectPath } from "@/lib/comparable-path"; -import { effectiveDraftKey, foldedHostProjectKey, freshChatDraftKey, hostProjectKey, LOCAL_HOST_ID, scopedDraftBase, scopedDraftKey, remoteHostId, projectIdentity, projectTargetId } from "@/lib/project-ordering"; +import { foldedHostProjectKey, hostProjectKey, LOCAL_HOST_ID, remoteHostId, projectIdentity, projectTargetId } from "@/lib/project-ordering"; import { isClusterTarget } from "@/lib/hosts/cluster"; import { useHostRows } from "@/hooks/useHostRows"; import { isRecord } from "@/lib/type-guards"; import { LocalDaemonBanner } from "./LocalDaemonBanner"; import { hostName, hostUnavailableReason } from "./host-status"; -import { clearDraft, continueDraft, foldDraft } from "@/lib/draft-store"; +import { clearDraft } from "@/lib/draft-store"; import { useNotifications } from "@/hooks/useNotifications"; import { APP_UPDATE_COMPLETED_RELOAD_MS, @@ -128,14 +128,7 @@ const OPEN_URL_AUTOMATICALLY_STORAGE_KEY = "tau:open-url-automatically"; /** The transient tab of a chat not yet sent (no session yet). */ const NEW_CHAT_TAB_ID = "chat:new"; /** An unsent new chat's target, as it was last shown. */ -/** `scope`: the composer draft key of its own (`scopedDraftKey`) a chat gets once it sent something and moved to a tab - * of its own (ChatWindow's `draftScope`): the new chat that opens after it has the workspace's. */ -type DraftChat = { cwd: string | null; hostId?: string; project: ManagedProject | null; creationId?: string; initialization?: string; scope?: string }; -const freshKeyOf = (draft: DraftChat) => freshChatDraftKey(draft.cwd, draft.hostId, draft.project?.poolId, draft.project?.projectId); -/** A closing new chat's draft of its own goes back to its workspace's (as an unsent one's stays there). */ -const foldScopedDraft = (draft: DraftChat) => { - if (draft.scope) foldDraft(draft.scope, scopedDraftBase(draft.scope)); -}; +type DraftChat = { cwd: string | null; hostId?: string; project: ManagedProject | null; creationId?: string; initialization?: string }; const chatTabId = (session: SessionInfo) => `chat:${remoteHostId(session.hostId) ?? LOCAL_HOST_ID}:${session.id}`; /** The strips kept across reloads of this browser tab (sessionStorage: another window keeps its own). */ const WORKBENCH_STORAGE_KEY = "tau:workbench"; @@ -205,8 +198,6 @@ export function AppShell({ appName }: { appName: string }) { // New chats that sent something, moved out of the new chat's tab: each keeps a tab of its own, and its mount, until // the tab closes or the chat's session takes the tab over. const [draftTabs, setDraftTabs] = useState<{ id: string; draft: DraftChat }[]>([]); - // The shown new chat's DraftChat.scope. - const [newChatScope, setNewChatScope] = useState(undefined); const draftTabSeqRef = useRef(0); // Mount keys of the new chats that began a send which can create their session. Never cleared: a key names one // mount, and a sent chat stays sent. @@ -229,16 +220,7 @@ export function AppShell({ appName }: { appName: string }) { return; } const id = `${DRAFT_TAB_PREFIX}${++draftTabSeqRef.current}`; - const freshKey = freshKeyOf(draft); - let scope = effectiveDraftKey(freshKey, draft.scope); - if (freshKey && scope === freshKey) { - // Its draft and its sends in flight move before the new chat taking the workspace's renders (that one reads the - // store as it mounts). - scope = scopedDraftKey(freshKey, id); - continueDraft(freshKey, scope, key); - } - setDraftTabs((tabs) => [...tabs, { id, draft: { ...draft, scope } }]); - setNewChatScope(undefined); + setDraftTabs((tabs) => [...tabs, { id, draft }]); setTabLayout((layout) => replaceTab(layout, NEW_CHAT_TAB_ID, id)); setChatMounts((mounts) => moveChatMount(mounts, NEW_CHAT_TAB_ID, id)); }, []); @@ -1455,13 +1437,8 @@ export function AppShell({ appName }: { appName: string }) { }, [router, isMobile, selectedSession]); const handleNewSession = useCallback((creationId: string, cwd: string | null, hostId?: string, project?: ManagedProject, initialization?: string) => { - // Taking the kept new chat up again passes its own creation id (takeUpDraft then sets its scope). - if ((creationId || undefined) !== draftChatRef.current?.creationId) { - // A shown new chat is replaced: a draft of its own goes back to its workspace's, for the chat that replaces it. - if (draftShownRef.current && draftChatRef.current) foldScopedDraft(draftChatRef.current); - dropKeptDraft(); - } - setNewChatScope(undefined); + // Taking the kept new chat up again passes its own creation id. + if ((creationId || undefined) !== draftChatRef.current?.creationId) dropKeptDraft(); setSettingsTab(null); setFileShown(false); setSelectedSession(null); @@ -1484,7 +1461,6 @@ export function AppShell({ appName }: { appName: string }) { }, [router, isMobile, activeCwd, activePoolProject, dropKeptDraft]); const takeUpDraft = useCallback((draft: DraftChat) => { handleNewSession(draft.creationId ?? "", draft.cwd, draft.hostId, draft.project ?? undefined, draft.initialization); - setNewChatScope(draft.scope); }, [handleNewSession]); // ---- In-app Navigate back / forward over visited chat views ---- @@ -1633,7 +1609,6 @@ export function AppShell({ appName }: { appName: string }) { // Called by ChatWindow when a new session gets its real id from pi const handleSessionCreated = useCallback((session: SessionInfo) => { setDraftChat(null); - setNewChatScope(undefined); if (!draftShownRef.current && draftChatRef.current) { setNewSessionCwd(null); setNewSessionPoolProject(null); @@ -2205,8 +2180,8 @@ export function AppShell({ appName }: { appName: string }) { const draftTabShown = showChat && !selectedSession; draftShownRef.current = draftTabShown; useEffect(() => { - if (draftTabShown) setDraftChat({ cwd: effectiveNewSessionCwd, hostId: newSessionHost, project: effectivePoolProject, creationId: newSessionCreation.id, initialization: newSessionCreation.initialization, scope: newChatScope }); - }, [draftTabShown, effectiveNewSessionCwd, newSessionHost, effectivePoolProject, newSessionCreation.id, newSessionCreation.initialization, newChatScope]); + if (draftTabShown) setDraftChat({ cwd: effectiveNewSessionCwd, hostId: newSessionHost, project: effectivePoolProject, creationId: newSessionCreation.id, initialization: newSessionCreation.initialization }); + }, [draftTabShown, effectiveNewSessionCwd, newSessionHost, effectivePoolProject, newSessionCreation.id, newSessionCreation.initialization]); const tabGroups = groupsOf(tabLayout); // The new chat a group shows keeps its tab while the selected chat is not in that group (a chat selected into // the new chat's own group replaces it, as before). @@ -2216,10 +2191,7 @@ export function AppShell({ appName }: { appName: string }) { draftKeptRef.current = draftKept; // A new chat whose tab is gone (a chat selected into its group replaced it) is forgotten. useEffect(() => { - if (draftTabOpen) return; - if (draftChatRef.current) foldScopedDraft(draftChatRef.current); - setDraftChat(null); - setNewChatScope(undefined); + if (!draftTabOpen) setDraftChat(null); }, [draftTabOpen]); useEffect(() => { // A new chat's own tab is not saved (nor its chat): its id would name nothing after a reload. @@ -2397,13 +2369,9 @@ export function AppShell({ appName }: { appName: string }) { const session = chatTabById(id); let selected: SessionInfo | undefined; if (id === NEW_CHAT_TAB_ID) { - // Only another group's new chat closes (see draftKept); its draft stays in the store (folded back into its - // workspace's when it had one of its own). - if (draftChat) foldScopedDraft(draftChat); + // Only another group's new chat closes (see draftKept); its draft stays in the store. setDraftChat(null); } else if (draftTabs.some((tab) => tab.id === id)) { - const closed = draftTabs.find((tab) => tab.id === id); - if (closed) foldScopedDraft(closed.draft); setDraftTabs((tabs) => tabs.filter((tab) => tab.id !== id)); } else if (!session) { handleCloseFileTab(id); @@ -3121,8 +3089,6 @@ export function AppShell({ appName }: { appName: string }) { Promise; onAudioUnlock?: () => void; draftKey?: string; - /** The key `draftKey` replaces for the same chat (a new chat given a draft of its own): a change from it keeps the - * composer's content and moves its pending recoveries along, instead of loading another draft. */ - draftKeyContinues?: string; - /** Identifies the chat across remounts of this composer (AppShell's mount key): its sends move with its draft. */ + /** Identifies the chat across remounts of this composer (ChatWindow's): a failed send's text comes back to the draft + * this chat shows while it is mounted, whatever key it has moved to meanwhile. */ draftOwner?: string; /** Owning host for file uploads and the @ file index (this machine when absent). */ uploadHostId?: string; @@ -307,7 +305,6 @@ export const ChatInput = memo(forwardRef(function ChatIn generationSpeed, onClearQueuedMessages, draftKey = "new:unassigned", - draftKeyContinues, draftOwner, uploadHostId = LOCAL_HOST_ID, resolveUploadHost, @@ -462,8 +459,6 @@ export const ChatInput = memo(forwardRef(function ChatIn }, [markInputEdited]); // Navigation starts a new identity, even when a draft key is later reused. const draftRecoveryIdentityRef = useRef({ key: draftKey }); - // The workspace key this composer's own key (`draftKey`) continues, while it has one. - const scopeBaseRef = useRef(draftKeyContinues); // Async dictation and slash-command completions must see the latest edit gate. const submissionBlockedRef = useRef(submissionBlocked); const valueRef = useRef(value); @@ -965,16 +960,6 @@ export const ChatInput = memo(forwardRef(function ChatIn useLayoutEffect(() => { const previousDraftKey = draftKeyRef.current; if (previousDraftKey === draftKey) return; - const leftBase = scopeBaseRef.current; - scopeBaseRef.current = draftKeyContinues; - if (previousDraftKey && draftKey && previousDraftKey === draftKeyContinues) { - // The same chat under a key of its own: AppShell moved its draft and sends there (continueDraft); keep the - // composer as is, with any edit of this commit. - draftKeyRef.current = draftKey; - setDraft(draftKey, captureDraft()); - draftRecoveryIdentityRef.current = { key: draftKey }; - return; - } // Invalidate any attachment reads still in flight for the old session so // they cannot append onto the new session's composer, and drop any stale @@ -987,8 +972,6 @@ export const ChatInput = memo(forwardRef(function ChatIn if (previousDraftKey) { setDraft(previousDraftKey, captureDraft()); - // A key of its own ends with the chat leaving it (its session, another workspace): its draft goes back. - if (leftBase) foldDraft(previousDraftKey, leftBase); } const draft = draftKey ? getDraft(draftKey) : null; @@ -1011,7 +994,9 @@ export const ChatInput = memo(forwardRef(function ChatIn for (const upload of prev) if (upload.previewUrl) URL.revokeObjectURL(upload.previewUrl); return draftUploadsToAttachedUploads(draft?.uploads); }); - }, [draftKey, draftKeyContinues, setPromptOnly, captureDraft]); + }, [draftKey, setPromptOnly, captureDraft]); + + useLayoutEffect(() => (draftOwner && draftKey ? holdDraftOwner(draftOwner, draftKey) : undefined), [draftOwner, draftKey]); useLayoutEffect(() => subscribeDraftRecovery((key, recovery) => { if (draftKeyRef.current !== key) return; @@ -1142,6 +1127,7 @@ export const ChatInput = memo(forwardRef(function ChatIn } if (submissionBlockedRef.current) return; if (rejectsOversizedPrompt(composedMessage, attachedImagesRef.current)) return; + const key = draftKeyRef.current; const images = attachedImagesRef.current.length ? attachedImagesRef.current : undefined; const recovery = { text: msg, images: images?.map(imageToDraftImage), files: files.length ? files.map(textFileToDraftFile) : undefined, ...(promptOnlyRef.current ? { promptOnly: true } : {}), ...uploadRecovery(attachedUploadsRef.current) }; const stored = outbox && !shellCommand ? clearOnceStored(raw) : undefined; @@ -1167,22 +1153,18 @@ export const ChatInput = memo(forwardRef(function ChatIn } return; } - // Owned by the store, not this mount: the chat's composer may remount, or move to a key of its own, meanwhile. - const submission = beginDraftSubmission(draftKeyRef.current, draftOwner); clearInput(); try { const result = await pending; if (result.status === "rejected") { - const destination = result.recoveryKey ?? submission.key; - if (destination) recoverDraft(destination, recovery); + const destination = result.recoveryKey ?? key; + if (destination) recoverDraft(destination, recovery, draftOwner); } } catch (error) { - if (submission.key) recoverDraft(submission.key, recovery); + if (key) recoverDraft(key, recovery, draftOwner); throw error; - } finally { - endDraftSubmission(submission); } - }, [value, isStreaming, onBuiltinCommand, onSend, outbox, clearInput, clearOnceStored, onAudioUnlock, rejectsOversizedPrompt, rejectsPendingUploads, runBuiltinCommand, sendSideQuestion]); + }, [value, isStreaming, draftOwner, onBuiltinCommand, onSend, outbox, clearInput, clearOnceStored, onAudioUnlock, rejectsOversizedPrompt, rejectsPendingUploads, runBuiltinCommand, sendSideQuestion]); const { isRecording, isPaused, diff --git a/components/ChatWindow.tsx b/components/ChatWindow.tsx index 2a401c6b..463a593d 100644 --- a/components/ChatWindow.tsx +++ b/components/ChatWindow.tsx @@ -37,9 +37,9 @@ import { restoreScrollTop, VISIBLE_PAGE_SIZE, } from "@/lib/chat-lazy-load"; -import { getDraftSummary } from "@/lib/draft-store"; +import { getDraftSummary, transientDraftKey } from "@/lib/draft-store"; import { isLinkUp, type HostStatus } from "@/lib/hosts/host"; -import { effectiveDraftKey, freshChatDraftKey } from "@/lib/project-ordering"; +import { newChatDraftKey } from "@/lib/project-ordering"; import { WorkspaceFileContext } from "@/lib/workspace-file-context"; import type { WorkspaceFileSource } from "@/lib/workspace-types"; import { getFileName } from "@/lib/file-paths"; @@ -53,10 +53,6 @@ interface Props { newSessionPoolId?: string; newSessionProjectId?: string; newSessionInitialization?: string; - /** A new chat's draft key of its own (DraftChat.scope in AppShell); without it the chat has the workspace's. */ - draftScope?: string; - /** This chat across remounts (AppShell's mount key): its sends in flight move with its draft. */ - draftOwner?: string; onNewSessionInitialization?: (body: string) => void; /** The chat's host from the `hosts` channel: the source of truth until a * `host_status` frame reports a change, and for a chat opened mid-outage. */ @@ -400,7 +396,7 @@ const CommittedTranscript = memo(function CommittedTranscript({ ); }); -export function ChatWindow({ session, newSessionCwd, newSessionHostId, newSessionCreationId, newSessionPoolId, newSessionProjectId, newSessionInitialization, draftScope, draftOwner, onNewSessionInitialization, hostStatus: channelHostStatus, hostLabel, newSessionWorkspace, headerActions, toolCallsDefaultCollapsed = true, hideToolActivity = true, neverFoldActivity = false, showToolCallsUnfolded = false, expandThinkingByDefault = false, hideThinkingBlock = false, onAgentEnd, onSessionCreated, onSent, onSessionForked, modelsRefreshKey, chatInputRef, sessionInfoContainer, onBranchDataChange, onSystemPromptChange, onSystemPromptLoaderChange, onSessionStatsChange, onSessionStatsPanelOpen, onGenerationSpeedChange, onOpenFile: onOpenWorkspaceFile, onOpenUrl, onOpenProviders, searchQuery = "", searchTarget = null, onSearchTargetHandled, covered = false }: Props) { +export function ChatWindow({ session, newSessionCwd, newSessionHostId, newSessionCreationId, newSessionPoolId, newSessionProjectId, newSessionInitialization, onNewSessionInitialization, hostStatus: channelHostStatus, hostLabel, newSessionWorkspace, headerActions, toolCallsDefaultCollapsed = true, hideToolActivity = true, neverFoldActivity = false, showToolCallsUnfolded = false, expandThinkingByDefault = false, hideThinkingBlock = false, onAgentEnd, onSessionCreated, onSent, onSessionForked, modelsRefreshKey, chatInputRef, sessionInfoContainer, onBranchDataChange, onSystemPromptChange, onSystemPromptLoaderChange, onSessionStatsChange, onSessionStatsPanelOpen, onGenerationSpeedChange, onOpenFile: onOpenWorkspaceFile, onOpenUrl, onOpenProviders, searchQuery = "", searchTarget = null, onSearchTargetHandled, covered = false }: Props) { const { t, tn } = useI18n(); const fileSource = useMemo(() => ({ hostId: session?.hostId ?? newSessionHostId ?? "local", @@ -437,6 +433,17 @@ export function ChatWindow({ session, newSessionCwd, newSessionHostId, newSessio onAgentEnd?.(); }, [onAgentEnd]); + // This chat across remounts of its composer (ChatInput's draftOwner). + const [draftOwner] = useState(() => Math.random().toString(36).slice(2, 12) + Date.now().toString(36)); + // Once a new chat sent, its draft is its own until its session takes over: another new chat on the workspace (it + // may open while this one's session is created) has the workspace's. + const [sentAsNew, setSentAsNew] = useState(false); + const freshDraftKey = newSessionPoolId && newSessionProjectId ? `new:pool:${newSessionPoolId}:${newSessionProjectId}` : newSessionCwd ? newChatDraftKey(newSessionCwd, newSessionHostId) : undefined; + const draftKey = session?.id ?? (freshDraftKey && sentAsNew ? transientDraftKey(`${freshDraftKey}#sent:${draftOwner}`) : freshDraftKey); + const handleSent = useCallback(() => { + setSentAsNew(true); + onSent?.(); + }, [onSent]); const { loading, error, messages, entryIds, showPreCompactionHistory, streamState, agentRunning, bashRunning, pendingBash, deferredBash, modelNames, modelList, modelsLoading, modelError, modelThinkingLevels, modelThinkingLevelMaps, thinkingLevel, @@ -464,7 +471,7 @@ export function ChatWindow({ session, newSessionCwd, newSessionHostId, newSessio resolveUploadHost, sessionHostId, } = useAgentSession({ - session, newSessionCwd, newSessionHostId, newSessionCreationId, newSessionPoolId, newSessionProjectId, newSessionInitialization, onNewSessionInitialization, onAgentEnd: wrappedOnAgentEnd, onSessionCreated, onSent, onSessionForked, + session, newSessionCwd, newSessionHostId, newSessionCreationId, newSessionPoolId, newSessionProjectId, newSessionInitialization, onNewSessionInitialization, onAgentEnd: wrappedOnAgentEnd, onSessionCreated, onSent: handleSent, onSessionForked, modelsRefreshKey, chatInputRef: composerRef, onBranchDataChange, onSystemPromptChange, onSystemPromptLoaderChange, onSessionStatsPanelOpen, onOpenFile: onOpenWorkspaceFile, onOpenUrl, }); @@ -558,8 +565,6 @@ export function ChatWindow({ session, newSessionCwd, newSessionHostId, newSessio // top, load another page while keeping the scroll position stable. const [visibleCount, setVisibleCount] = useState(VISIBLE_PAGE_SIZE); const prevSessionKeyForPagingRef = useRef(null); - const freshDraftKey = freshChatDraftKey(newSessionCwd, newSessionHostId, newSessionPoolId, newSessionProjectId); - const draftKey = session?.id ?? effectiveDraftKey(freshDraftKey, draftScope); const sessionKeyForPaging = draftKey ?? "empty"; useEffect(() => { if (prevSessionKeyForPagingRef.current !== sessionKeyForPaging) { @@ -972,7 +977,6 @@ export function ChatWindow({ session, newSessionCwd, newSessionHostId, newSessio onBuiltinCommand={handleBuiltinSlashCommand} onAudioUnlock={unlockAudio} draftKey={draftKey} - draftKeyContinues={!session && draftKey !== freshDraftKey ? freshDraftKey : undefined} draftOwner={draftOwner} uploadHostId={session ? session.hostId : newSessionHostId} resolveUploadHost={!session && newSessionPoolId ? resolveUploadHost : undefined} diff --git a/hooks/useAgentSession.rpc.test.mjs b/hooks/useAgentSession.rpc.test.mjs index 4f71e0ca..266030be 100644 --- a/hooks/useAgentSession.rpc.test.mjs +++ b/hooks/useAgentSession.rpc.test.mjs @@ -5137,7 +5137,7 @@ test("a rejected saved launch configuration is shown on a fresh chat and leaves const w = await mountSession(null, undefined, { newSessionCwd: "/workspace" }); let receipt; await act(async () => { receipt = await w.latest.handleSend("keep this draft"); }); - assert.deepEqual(receipt, { status: "rejected", recoveryKey: undefined }); + assert.deepEqual(receipt, { status: "rejected", recoveryKey: "new:/workspace" }); assert.ok(w.latest.notices.some((notice) => notice.type === "error" && notice.message.includes(translate("errors.stored_reserved_launch_arg")))); assert.equal(world.calls.some((call) => call.body?.type === "prompt"), false); }); @@ -5152,7 +5152,8 @@ test("a fresh chat on a remote host creates its session there and toasts when th const w = await mountSession(null, undefined, { newSessionCwd: "/remote/work", newSessionHostId: "h1" }); let receipt; await act(async () => { receipt = await w.latest.handleSend("first"); await sleep(30); }); - assert.deepEqual(receipt, { status: "rejected", recoveryKey: undefined }); + // Drafts for one path on two hosts must not share a composer key. + assert.deepEqual(receipt, { status: "rejected", recoveryKey: "new:h1:/remote/work" }); assert.deepEqual(callsTo("POST", "/api/agent/new").map((call) => [call.body.cwd, call.body.hostId]), [["/remote/work", "h1"]]); assert.equal(toastCalls[0]?.[0], "error"); assert.equal(w.latest.notices.length, 0); @@ -6132,32 +6133,6 @@ test("a kept chat whose send fails gets its text back in its own composer, not t h.view.unmount(); }); -test("text typed into a kept chat after it sent stays with it when another new chat opens", async (t) => { - let release; - const h = await draftInItsOwnGroup(t); - world.holds.push({ match: (method, url) => method === "POST" && url === "/api/agent/new", produce: () => new Promise((resolve) => { release = () => resolve({ status: 500, value: { error: "spawn failed" } }); }) }); - await act(async () => { fireEvent.change(h.draftComposer, { target: { value: "hello there" } }); await sleep(30); }); - await act(async () => { fireEvent.keyDown(h.draftComposer, { key: "Enter" }); await sleep(60); }); - await until(() => release, "the new chat is being created"); - await act(async () => { fireEvent.change(h.composerIn(h.draftGroup), { target: { value: "and more" } }); await sleep(60); }); - await act(async () => { fireEvent.pointerDown(h.composerIn(h.other)); await sleep(80); }); - await act(async () => { fireEvent.click(h.newSessionButton()); await sleep(120); }); - assert.equal(h.composerIn(h.other).value, "", "the fresh new chat starts empty"); - assert.equal(h.composerIn(h.draftGroup).value, "and more", "the kept chat keeps what was typed into it"); - assert.equal(window.sessionStorage.getItem("tau-draft-new:pool:workers:app#chat:draft:1"), null, "its own key is not reopened after a reload"); - window.dispatchEvent(new Event("pagehide")); - assert.match(window.sessionStorage.getItem("tau-draft-new:pool:workers:app") ?? "", /and more/, "a reload finds its text in the workspace's draft"); - // Closing the kept chat's tab gives its text and its failed prompt back to the workspace's new chat. - const kept = within(h.draftGroup).getByRole("tab", { name: translate("appShell.newSession") }); - await act(async () => { fireEvent.click(within(h.draftGroup).getByRole("button", { name: translate("tabBar.closeTab", { label: kept.textContent || translate("appShell.newSession") }) })); await sleep(120); }); - assert.match(h.composerIn(h.other).value, /and more/); - await act(async () => { release(); await sleep(300); }); - assert.match(h.composerIn(h.other).value, /hello there/, "a send that fails after its tab closed is not lost"); - // The workspace's draft outlives this view: leave it empty for the next test. - await act(async () => { fireEvent.change(h.composerIn(h.other), { target: { value: "" } }); await sleep(60); }); - h.view.unmount(); -}); - test("two kept chats swapped in and out of the new chat's tab each keep their own draft", async (t) => { let releaseB; const h = await sentBesideFreshChat(t, { status: 500, value: { error: "spawn failed" } }); @@ -6193,6 +6168,34 @@ test("a new chat that replaces a shown kept chat gets the workspace's draft, and h.view.unmount(); }); +test("a kept chat's failed prompt goes to the workspace's new chat once the kept chat's tab is closed", async (t) => { + const h = await sentBesideFreshChat(t, { status: 500, value: { error: "spawn failed" } }); + const kept = within(h.draftGroup).getByRole("tab", { name: translate("appShell.newSession") }); + await act(async () => { fireEvent.click(within(h.draftGroup).getByRole("button", { name: translate("tabBar.closeTab", { label: kept.textContent || translate("appShell.newSession") }) })); await sleep(120); }); + await act(async () => { h.release(); await sleep(300); }); + assert.match(h.composerIn(h.other).value, /hello there/, "a send that fails after its tab closed is not lost"); + await act(async () => { fireEvent.change(h.composerIn(h.other), { target: { value: "" } }); await sleep(60); }); + h.view.unmount(); +}); + +test("text typed into a kept chat after it sent stays with it when another new chat opens", async (t) => { + let release; + const h = await draftInItsOwnGroup(t); + world.holds.push({ match: (method, url) => method === "POST" && url === "/api/agent/new", produce: () => new Promise((resolve) => { release = () => resolve({ status: 500, value: { error: "spawn failed" } }); }) }); + await act(async () => { fireEvent.change(h.draftComposer, { target: { value: "hello there" } }); await sleep(30); }); + await act(async () => { fireEvent.keyDown(h.draftComposer, { key: "Enter" }); await sleep(60); }); + await until(() => release, "the new chat is being created"); + await act(async () => { fireEvent.change(h.composerIn(h.draftGroup), { target: { value: "and more" } }); await sleep(60); }); + await act(async () => { fireEvent.pointerDown(h.composerIn(h.other)); await sleep(80); }); + await act(async () => { fireEvent.click(h.newSessionButton()); await sleep(120); }); + assert.equal(h.composerIn(h.other).value, "", "the fresh new chat starts empty"); + assert.equal(h.composerIn(h.draftGroup).value, "and more", "the kept chat keeps what was typed into it"); + await act(async () => { release(); await sleep(300); }); + assert.match(h.composerIn(h.draftGroup).value, /and more[\s\S]*hello there|hello there[\s\S]*and more/, "and gets its failed prompt back beside it"); + assert.equal(h.composerIn(h.other).value, ""); + h.view.unmount(); +}); + test("another new chat replaces an unsent kept one and opens fresh in the focused group", async (t) => { const h = await draftInItsOwnGroup(t); await act(async () => { fireEvent.change(h.draftComposer, { target: { value: "unsent idea" } }); await sleep(60); }); @@ -6298,7 +6301,7 @@ test("workspace file search stays in its source session rather than a same-path view.unmount(); }); -test("a fresh local chat sends no host id and leaves a failed send to the composer's own draft key", async () => { +test("a fresh local chat sends no host id and keeps the pre-hosts draft key", async () => { resetWorld(); world.holds.push({ match: (method, url) => method === "POST" && url === "/api/agent/new", @@ -6308,7 +6311,7 @@ test("a fresh local chat sends no host id and leaves a failed send to the compos let receipt; await act(async () => { receipt = await w.latest.handleSend("first"); await sleep(30); }); assert.equal("hostId" in callsTo("POST", "/api/agent/new")[0].body, false); - assert.deepEqual(receipt, { status: "rejected", recoveryKey: undefined }); + assert.deepEqual(receipt, { status: "rejected", recoveryKey: "new:/workspace" }); }); for (const [name, method, mode, message] of [ diff --git a/hooks/useAgentSession.ts b/hooks/useAgentSession.ts index bdabaa0a..770c690c 100644 --- a/hooks/useAgentSession.ts +++ b/hooks/useAgentSession.ts @@ -25,7 +25,7 @@ import type { ThinkingModelMeta } from "@/lib/thinking-levels"; import { HostOfflineError, getOutboxScope, rememberOutboxScope, sendAgentCommand } from "@/lib/agent-client"; import type { HostStatus } from "@/lib/hosts/host"; import type { WorkspaceFileSource } from "@/lib/workspace-types"; -import { remoteHostId } from "@/lib/project-ordering"; +import { newChatDraftKey, remoteHostId } from "@/lib/project-ordering"; import { recoverDraft, setDraft } from "@/lib/draft-store"; import { formatExitedSessionNotice, translate } from "@/lib/i18n"; import { formatApiError } from "@/lib/i18n/api-error"; @@ -3073,8 +3073,7 @@ export function useAgentSession(opts: UseAgentSessionOptions) { // not a request to stop following the response that this prompt starts. userScrollIntentUntilRef.current = 0; - // Unset until a session exists: a failed first send goes back to the composer's own draft key. - let recoveryKey: string | undefined = sessionIdRef.current ?? undefined; + let recoveryKey = sessionIdRef.current ?? (pooled ? `new:pool:${newSessionPoolId}:${newSessionProjectId}` : newSessionCwd ? newChatDraftKey(newSessionCwd, newSessionHostId) : undefined); // Set just before the prompt goes out: a lost reply from any earlier command (get_state, set_model) ran no prompt. let promptIssued = false; try { @@ -3161,7 +3160,7 @@ export function useAgentSession(opts: UseAgentSessionOptions) { dispatch({ type: "end" }); return mayHaveRun ? { status: "accepted" } : { status: "rejected", recoveryKey: sessionIdRef.current ?? recoveryKey }; } - }, [catchUp, eventCoalescer, isNew, newSessionModel, session, ensureNewSession, ensureEventsConnected, promoteNewSession, onSessionCreated, waitForPromptSettlement, addNotice, refreshSubagentRoster, clearLiveToolResults, clearTerminalReconcileTimer, snapshotRunEntries, holdMessage]); + }, [catchUp, eventCoalescer, isNew, pooled, newSessionPoolId, newSessionProjectId, newSessionCwd, newSessionHostId, newSessionModel, session, ensureNewSession, ensureEventsConnected, promoteNewSession, onSessionCreated, waitForPromptSettlement, addNotice, refreshSubagentRoster, clearLiveToolResults, clearTerminalReconcileTimer, snapshotRunEntries, holdMessage]); const executeBash = useCallback(async (command: string, excludeFromContext: boolean) => { if (bashRunningRef.current || editInFlightRef.current) return; diff --git a/lib/draft-store.test.mjs b/lib/draft-store.test.mjs index be63e83a..3b2e3f6b 100644 --- a/lib/draft-store.test.mjs +++ b/lib/draft-store.test.mjs @@ -1,7 +1,7 @@ import assert from "node:assert/strict"; import { spawnSync } from "node:child_process"; import test from "node:test"; -import { beginDraftSubmission, clearDraft, consumeDraft, continueDraft, endDraftSubmission, foldDraft, getDraft, getDraftRevision, getDraftSummary, markDraftEdited, mergeRecoveredText, recoverDraft, setDraft, subscribeDraftConsumption, subscribeDraftRecovery } from "./draft-store.ts"; +import { clearDraft, consumeDraft, holdDraftOwner, transientDraftKey, getDraft, getDraftRevision, getDraftSummary, markDraftEdited, mergeRecoveredText, recoverDraft, setDraft, subscribeDraftConsumption, subscribeDraftRecovery } from "./draft-store.ts"; test("outbox consumption notifies matching drafts without clearing newer text, equal-text retypes or attachment payloads", () => { const key = "outbox-consumption"; @@ -313,30 +313,20 @@ test("a later recovery merges with an earlier one in order, unless the draft no assert.equal(mergeRecoveredText("edited", { text: "A\n\nB", replace }), "A\n\nedited", "never re-adds text the user removed"); }); -test("a continued draft moves its content and submissions to a key of this page only, and folds back when it ends", (t) => { +test("a recovery follows its chat to the draft that chat shows now, and a page-only key is never stored", (t) => { const stored = new Map(); globalThis.sessionStorage = { getItem: (k) => stored.get(k) ?? null, setItem: (k, v) => { stored.set(k, String(v)); }, removeItem: (k) => { stored.delete(k); } }; t.after(() => { delete globalThis.sessionStorage; }); - setDraft("new:/w", { value: "typed after sending", images: [], files: [] }); - const moving = beginDraftSubmission("new:/w", "chat:new"); - const other = beginDraftSubmission("new:/other", "chat:new"); - const earlier = beginDraftSubmission("new:/w", "chat:new~1"); - continueDraft("new:/w", "new:/w#chat:draft:1", "chat:new"); - assert.equal(getDraft("new:/w"), null, "the workspace's draft is free for the next new chat"); - assert.equal(getDraft("new:/w#chat:draft:1")?.value, "typed after sending"); - assert.equal(stored.has("tau-draft-new:/w#chat:draft:1"), false, "nothing reopens it after a reload"); - assert.equal(stored.has("tau-draft-new:/w"), false); - assert.equal(moving.key, "new:/w#chat:draft:1", "a failed send recovers to the chat's own key"); - assert.equal(other.key, "new:/other"); - assert.equal(earlier.key, "new:/w", "another chat's send in flight from the workspace's key stays there"); - setDraft("new:/w", { value: "fresh", images: [], files: [] }); - foldDraft("new:/w#chat:draft:1", "new:/w"); - assert.equal(getDraft("new:/w#chat:draft:1"), null); - assert.match(getDraft("new:/w")?.value ?? "", /fresh[\s\S]*typed after sending|typed after sending[\s\S]*fresh/, "both texts are kept"); - assert.equal(moving.key, "new:/w", "and its sends in flight recover there"); - assert.ok(stored.has("tau-draft-new:/w"), "the workspace's draft is kept across reloads again"); - endDraftSubmission(moving); - endDraftSubmission(other); - endDraftSubmission(earlier); + const own = transientDraftKey("new:/w#sent:a"); + const release = holdDraftOwner("a", own); + recoverDraft("new:/w", { text: "failed prompt" }, "a"); + assert.equal(getDraft(own)?.value, "failed prompt", "into the chat's own draft"); + assert.equal(getDraft("new:/w"), null, "not the workspace's, which another new chat may show"); + assert.equal(stored.has("tau-draft-" + own), false, "nothing reopens a page-only key after a reload"); + release(); + recoverDraft("new:/w", { text: "after it closed" }, "a"); + assert.equal(getDraft("new:/w")?.value, "after it closed", "a chat no longer shown gives it to the workspace's draft"); + assert.ok(stored.has("tau-draft-new:/w")); + clearDraft(own); clearDraft("new:/w"); }); diff --git a/lib/draft-store.ts b/lib/draft-store.ts index ecb5f802..6a5e624b 100644 --- a/lib/draft-store.ts +++ b/lib/draft-store.ts @@ -53,9 +53,9 @@ export function mergeRecoveredText(current: string, { text, replace }: DraftReco declare global { var __tauChatDrafts: Map | undefined; var __tauChatDraftListeners: Set<() => void> | undefined; + var __tauChatDraftOwners: Map | undefined; + var __tauChatDraftTransientKeys: Set | undefined; var __tauChatDraftRecoveryListeners: Set<(key: string, recovery: DraftRecovery) => void> | undefined; - var __tauChatDraftTransientKeys: Map | undefined; - var __tauChatDraftPagehide: boolean | undefined; var __tauChatDraftConsumptionListeners: Set<(key: string, snapshot: ChatDraft) => void> | undefined; var __tauChatDraftRevisions: { byKey: Map; last: number } | undefined; var __tauChatDraftSubmissions: Set | undefined; @@ -153,12 +153,12 @@ export function markDraftEdited(key: string): void { /** A submission waiting for its durable commit, owned by this store (not by the composer mount that sent it, which may * be gone by the time the commit lands). `edited` records any edit since it was sent. */ -export interface DraftSubmission { key: string | undefined; snapshot: ChatDraft | null; revision: number; edited: boolean; owner?: string } +export interface DraftSubmission { key: string | undefined; snapshot: ChatDraft | null; revision: number; edited: boolean } /** Starts tracking the draft at `key`. Every submission MUST be ended (`endDraftSubmission`) once its commit settles, * whether it was stored, refused or failed. */ -export function beginDraftSubmission(key: string | undefined, owner?: string): DraftSubmission { - const submission: DraftSubmission = { key, snapshot: key ? getDraft(key) : null, revision: key ? getDraftRevision(key) : -1, edited: false, owner }; +export function beginDraftSubmission(key: string | undefined): DraftSubmission { + const submission: DraftSubmission = { key, snapshot: key ? getDraft(key) : null, revision: key ? getDraftRevision(key) : -1, edited: false }; submissions.add(submission); return submission; } @@ -227,8 +227,31 @@ export function getDraft(key: string): ChatDraft | null { return draft ? cloneDraft(draft) : null; } -export function recoverDraft(key: string, recovery: DraftRecovery): void { +/** The draft key each chat's mounted composer shows (`holdDraftOwner`), by chat. */ +const liveOwners = (globalThis.__tauChatDraftOwners ??= new Map()); + +/** Records that `owner`'s composer shows `key` until the returned release runs. */ +export function holdDraftOwner(owner: string, key: string): () => void { + liveOwners.set(owner, key); + return () => { + if (liveOwners.get(owner) === key) liveOwners.delete(owner); + }; +} + +/** Keys of drafts that live only as long as this page (`transientDraftKey`). */ +const transientKeys = (globalThis.__tauChatDraftTransientKeys ??= new Set()); + +/** `key`, as a draft key of this page only: kept out of sessionStorage, since nothing reopens it after a reload. */ +export function transientDraftKey(key: string): string { + transientKeys.add(key); + return key; +} + +/** Recovers into `key`'s draft or, when `owner`'s composer is mounted, into the draft it shows now: a new chat that + * sent moves to a key of its own, and another chat may have its old one. */ +export function recoverDraft(key: string, recovery: DraftRecovery, owner?: string): void { if (!recovery.text && !recovery.images?.length && !recovery.files?.length && !recovery.uploads?.length) return; + key = (owner && liveOwners.get(owner)) || key; if (key) { const draft = getDraft(key) ?? { value: "", images: [], files: [] }; setDraft(key, { @@ -298,49 +321,3 @@ export function clearDraft(key: string): void { for (const listener of listeners) listener(); } } - -/** Keys of drafts that live only as long as this page (`continueDraft`), with the key each continues: kept out of - * sessionStorage, where their text is added to that key's as the page is hidden (a reload reopens no such key). */ -const transientKeys = (globalThis.__tauChatDraftTransientKeys ??= new Map()); -if (typeof window !== "undefined" && !globalThis.__tauChatDraftPagehide) { - globalThis.__tauChatDraftPagehide = true; - window.addEventListener("pagehide", () => { - const texts = new Map(); - for (const [key, base] of transientKeys) { - const text = drafts.get(key)?.value; - if (text) texts.set(base, mergeRecoveredText(texts.get(base) ?? drafts.get(base)?.value ?? "", { text })); - } - try { - for (const [base, text] of texts) sessionStorage.setItem(STORAGE_PREFIX + base, text); - } catch { - // Storage may be unavailable. - } - }); -} - -/** Submissions in flight from `from` (only `owner`'s, when given) recover to `to` from now on. */ -function moveDraftSubmissions(from: string, to: string, owner?: string): void { - for (const submission of submissions) if (submission.key === from && (owner === undefined || submission.owner === owner)) submission.key = to; -} - -/** The same chat continues under `to`, a key of its own for this page only (a new chat that sent and moved to a tab of - * its own): `from`'s draft moves there, and so do the sends in flight that `owner`'s composer began. Call it before - * the chat that takes `from` over renders. */ -export function continueDraft(from: string, to: string, owner: string | undefined): void { - transientKeys.set(to, from); - const draft = getDraft(from); - clearDraft(from); - if (draft) setDraft(to, draft); - else clearDraft(to); - if (owner !== undefined) moveDraftSubmissions(from, to, owner); -} - -/** `continueDraft` undone once that key ends (its tab closed, its chat left it): what it holds is recovered into - * `to`, as into any composer, and its submissions in flight recover there too. */ -export function foldDraft(from: string, to: string): void { - const draft = getDraft(from); - clearDraft(from); - transientKeys.delete(from); - moveDraftSubmissions(from, to); - if (draft) recoverDraft(to, { text: draft.value, images: draft.images.length ? draft.images : undefined, files: draft.files.length ? draft.files : undefined, uploads: draft.uploads, ...(draft.promptOnly ? { promptOnly: true } : {}) }); -} diff --git a/lib/project-ordering.test.mjs b/lib/project-ordering.test.mjs index 0c4694f3..8cf66770 100644 --- a/lib/project-ordering.test.mjs +++ b/lib/project-ordering.test.mjs @@ -6,10 +6,6 @@ const { groupProjectsByHost, groupSessionsByProject, hostProjectKey, - newChatDraftKey, - effectiveDraftKey, - scopedDraftBase, - scopedDraftKey, projectActivityCounts, nextPinOrder, orderProjects, @@ -319,19 +315,3 @@ test("last updated sorts a host's project by that host's sessions only", () => { ]; assert.deepEqual(orderProjects(projects, "updated", sessions, (p) => p.path).map((p) => p.hostId), ["h1", "local"]); }); - -test("a fresh chat's draft key keeps the pre-hosts form here and names the host elsewhere", () => { - assert.equal(newChatDraftKey("/workspace", undefined), "new:/workspace"); - assert.equal(newChatDraftKey("/workspace", "local"), "new:/workspace"); - // Drafts for one path on two hosts must not share a composer key. - assert.equal(newChatDraftKey("/remote/work", "h1"), "new:h1:/remote/work"); -}); - -test("a new chat's draft key of its own holds only while its workspace is the one it continues", () => { - const scope = scopedDraftKey("new:/a#1", "chat:draft:1"); - assert.equal(scopedDraftBase(scope), "new:/a#1", "a `#` in the path stays in the base"); - assert.equal(effectiveDraftKey("new:/a#1", scope), scope); - assert.equal(effectiveDraftKey("new:/b", scope), "new:/b", "another workspace has its own draft"); - assert.equal(effectiveDraftKey("new:/a#1", undefined), "new:/a#1"); - assert.equal(effectiveDraftKey(undefined, scope), undefined); -}); diff --git a/lib/project-ordering.ts b/lib/project-ordering.ts index b443c205..32a1c54d 100644 --- a/lib/project-ordering.ts +++ b/lib/project-ordering.ts @@ -36,18 +36,6 @@ export function newChatDraftKey(cwd: string, hostId: string | undefined): string return `new:${hostProjectKey(hostId, cwd)}`; } -/** Composer draft key of a new chat (ChatWindow's): a pool project's, else its workspace's. */ -export function freshChatDraftKey(cwd: string | null | undefined, hostId: string | undefined, poolId?: string, projectId?: string): string | undefined { - return poolId && projectId ? `new:pool:${poolId}:${projectId}` : cwd ? newChatDraftKey(cwd, hostId) : undefined; -} - -/** A new chat's draft key of its own (AppShell's DraftChat.scope) over its workspace's `freshKey`; `tag` has no `#`. */ -export const scopedDraftKey = (freshKey: string, tag: string) => `${freshKey}#${tag}`; -/** The workspace key a `scopedDraftKey` continues. */ -export const scopedDraftBase = (scoped: string) => scoped.slice(0, scoped.lastIndexOf("#")); -/** `scope` when it continues `freshKey` (it does not once the chat's workspace changed), else `freshKey`. */ -export const effectiveDraftKey = (freshKey: string | undefined, scope: string | undefined) => freshKey && scope && scopedDraftBase(scope) === freshKey ? scope : freshKey; - /** `hostProjectKey` over the case-folded comparable path (how sessions find their project). */ export function foldedHostProjectKey(hostId: string | undefined, path: string): string { return path.startsWith("pool:") ? path : hostProjectKey(hostId, comparableProjectPath(path)); From 6e19919378308b5aa8f928ca287738930d449800 Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Fri, 27 Nov 2026 06:59:22 +0000 Subject: [PATCH 06/13] fix(chat): carry a sent new chat's draft to its session; fold it back when the chat goes away or the page reloads --- AGENTS.md | 2 +- components/ChatInput.tsx | 28 +++++++++++++++++++------ components/ChatWindow.tsx | 21 +++++++++++++++---- hooks/useAgentSession.rpc.test.mjs | 24 ++++++++++++++++++++++ lib/draft-store.test.mjs | 33 ++++++++++++++++++++++-------- lib/draft-store.ts | 28 +++++++++++++++++-------- 6 files changed, 108 insertions(+), 28 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 65dde0a6..269b4352 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -370,7 +370,7 @@ Browser keys use `tau-` / `tau:` (`tau-theme`, the `tau-theme-color` cookie, `ta - Prefill only the selected message's text, never its images. Preserve drafts, newer typing and attachments through pending edits, cancellation, errors and navigation. `submissionBlocked` keeps asynchronous dictation from submitting or clearing the composer. `session_history_changed` carries the leaf marker; the initiating tab deduplicates its own echo. Editing does not undo tool side effects. - Draft text survives reload via sessionStorage; attachment payloads stay in memory. - Event connections own their readiness waits: replacement and unmount settle the old wait as closed and close its observer; stale continuations must not attach streams or authorize operations. A new chat's first prompt is the exception: when its chat unmounts while pi spawns, `handleSend` still sends it and returns `accepted`. A new chat left for another group's chat stays mounted there instead; its session then replaces its tab in place without being selected (`handleSessionCreated`). Existing sessions' messages go through the outbox. - - `ChatInput.onSend` returns `Promise` (`accepted` / `rejected` / `superseded`). With `outbox` the composer clears only once the message is stored in the browser's outbox and only if it still holds what was sent. For a new chat only rejection restores the draft (`recoverDraft`; the composer owns recovery), into the draft its chat shows when the reply comes (`draftOwner`, `holdDraftOwner`), else the key captured at the send; superseded failures never reinsert a processed turn. A new chat that sent has a draft of its own, `#sent:`, for this page only (`transientDraftKey`), until its session takes over: another new chat on the workspace, which may open meanwhile (a kept chat's draft tab), has the workspace's. + - `ChatInput.onSend` returns `Promise` (`accepted` / `rejected` / `superseded`). With `outbox` the composer clears only once the message is stored in the browser's outbox and only if it still holds what was sent. For a new chat only rejection restores the draft (`recoverDraft`; the composer owns recovery), into the draft its chat shows when the reply comes (`draftOwner`, `holdDraftOwner`; a session id the hook names wins), else the key captured at the send; superseded failures never reinsert a processed turn. A new chat that sent has a draft of its own, `#sent:` (`sentDraftKey`, set from the hook's `onSent`), until its session takes over: another new chat on the workspace, which may open meanwhile (a kept chat's draft tab), has the workspace's. Moving to that key keeps the composer's content (`draftKeyContinues`); leaving it (the session, another workspace) carries the content to the next key; a chat that goes away, and a reload, fold it back into the workspace's (`foldSentDraft`). - **In-session branch** (Continue / BranchNavigator): a read-only historical view of the entry tree through `/api/sessions/[id]/context?leafId=` (`handleLeafChange`); it does not change the live agent. Never implement Edit with it. ### ToolCall field normalization diff --git a/components/ChatInput.tsx b/components/ChatInput.tsx index 19db667c..ad20d57e 100644 --- a/components/ChatInput.tsx +++ b/components/ChatInput.tsx @@ -15,7 +15,7 @@ import type { SttAfter } from "@/lib/stt"; import { formatCompactNumber, formatPercent } from "@/lib/format"; import { ContextDetailPanel } from "./ComposerPanels"; import { RecordingDeck } from "./RecordingDeck"; -import { beginDraftSubmission, clearDraft, consumeDraft, endDraftSubmission, getDraft, getDraftRevision, holdDraftOwner, isSameDraft, markDraftEdited, mergeRecoveredText, recoverDraft, requiresPromptMode, setDraft, subscribeDraftConsumption, subscribeDraftRecovery, type ChatDraft } from "@/lib/draft-store"; +import { beginDraftSubmission, clearDraft, consumeDraft, endDraftSubmission, getDraft, getDraftRevision, holdDraftOwner, isSameDraft, isSentDraftKey, markDraftEdited, mergeRecoveredText, recoverDraft, requiresPromptMode, setDraft, subscribeDraftConsumption, subscribeDraftRecovery, type ChatDraft } from "@/lib/draft-store"; import { expandWebSlashCommand } from "@/lib/web-slash-commands"; import { WorkspaceFileContext } from "@/lib/workspace-file-context"; import type { AttachedImage, AttachedTextFile } from "./ChatInput-draft-attachments"; @@ -184,6 +184,9 @@ interface Props { /** Identifies the chat across remounts of this composer (ChatWindow's): a failed send's text comes back to the draft * this chat shows while it is mounted, whatever key it has moved to meanwhile. */ draftOwner?: string; + /** The workspace key `draftKey` continues when it is the chat's own (a new chat that sent): moving to it keeps the + * composer and what it holds. */ + draftKeyContinues?: string; /** Owning host for file uploads and the @ file index (this machine when absent). */ uploadHostId?: string; /** Lazily bind a pool's real owner before staging any file bytes. Failure never falls back locally. */ @@ -306,6 +309,7 @@ export const ChatInput = memo(forwardRef(function ChatIn onClearQueuedMessages, draftKey = "new:unassigned", draftOwner, + draftKeyContinues, uploadHostId = LOCAL_HOST_ID, resolveUploadHost, cwd, @@ -960,6 +964,17 @@ export const ChatInput = memo(forwardRef(function ChatIn useLayoutEffect(() => { const previousDraftKey = draftKeyRef.current; if (previousDraftKey === draftKey) return; + if (previousDraftKey && draftKey && previousDraftKey === draftKeyContinues) { + // A new chat moving to its own key as it sends: the composer, and what it still holds (a command kept after a + // failure), go along; the workspace's key is left for the next new chat. + draftKeyRef.current = draftKey; + draftRecoveryIdentityRef.current = { key: draftKey }; + setDraft(draftKey, captureDraft()); + clearDraft(previousDraftKey); + return; + } + // Leaving the chat's own key (its session, another workspace): what it holds goes to the next key, never stays behind. + const carried = previousDraftKey && isSentDraftKey(previousDraftKey) ? captureDraft() : null; // Invalidate any attachment reads still in flight for the old session so // they cannot append onto the new session's composer, and drop any stale @@ -970,9 +985,8 @@ export const ChatInput = memo(forwardRef(function ChatIn setAttachNotice(null); setQueuedDeleteTarget(null); - if (previousDraftKey) { - setDraft(previousDraftKey, captureDraft()); - } + if (carried) clearDraft(previousDraftKey!); + else if (previousDraftKey) setDraft(previousDraftKey, captureDraft()); const draft = draftKey ? getDraft(draftKey) : null; draftKeyRef.current = draftKey; @@ -994,7 +1008,8 @@ export const ChatInput = memo(forwardRef(function ChatIn for (const upload of prev) if (upload.previewUrl) URL.revokeObjectURL(upload.previewUrl); return draftUploadsToAttachedUploads(draft?.uploads); }); - }, [draftKey, setPromptOnly, captureDraft]); + if (carried && draftKey) recoverDraft(draftKey, { text: carried.value, images: carried.images.length ? carried.images : undefined, files: carried.files.length ? carried.files : undefined, uploads: carried.uploads, ...(carried.promptOnly ? { promptOnly: true } : {}) }); + }, [draftKey, draftKeyContinues, setPromptOnly, captureDraft]); useLayoutEffect(() => (draftOwner && draftKey ? holdDraftOwner(draftOwner, draftKey) : undefined), [draftOwner, draftKey]); @@ -1158,7 +1173,8 @@ export const ChatInput = memo(forwardRef(function ChatIn const result = await pending; if (result.status === "rejected") { const destination = result.recoveryKey ?? key; - if (destination) recoverDraft(destination, recovery, draftOwner); + // A session id the hook names is the chat's; otherwise the chat's draft now, wherever it moved. + if (destination) recoverDraft(destination, recovery, destination === key ? draftOwner : undefined); } } catch (error) { if (key) recoverDraft(key, recovery, draftOwner); diff --git a/components/ChatWindow.tsx b/components/ChatWindow.tsx index 463a593d..dbf9c8dd 100644 --- a/components/ChatWindow.tsx +++ b/components/ChatWindow.tsx @@ -37,7 +37,7 @@ import { restoreScrollTop, VISIBLE_PAGE_SIZE, } from "@/lib/chat-lazy-load"; -import { getDraftSummary, transientDraftKey } from "@/lib/draft-store"; +import { foldSentDraft, getDraftSummary, isSentDraftKey, sentDraftKey } from "@/lib/draft-store"; import { isLinkUp, type HostStatus } from "@/lib/hosts/host"; import { newChatDraftKey } from "@/lib/project-ordering"; import { WorkspaceFileContext } from "@/lib/workspace-file-context"; @@ -437,13 +437,25 @@ export function ChatWindow({ session, newSessionCwd, newSessionHostId, newSessio const [draftOwner] = useState(() => Math.random().toString(36).slice(2, 12) + Date.now().toString(36)); // Once a new chat sent, its draft is its own until its session takes over: another new chat on the workspace (it // may open while this one's session is created) has the workspace's. - const [sentAsNew, setSentAsNew] = useState(false); + // Held for the workspace key it sent on: another workspace's draft is that workspace's again. const freshDraftKey = newSessionPoolId && newSessionProjectId ? `new:pool:${newSessionPoolId}:${newSessionProjectId}` : newSessionCwd ? newChatDraftKey(newSessionCwd, newSessionHostId) : undefined; - const draftKey = session?.id ?? (freshDraftKey && sentAsNew ? transientDraftKey(`${freshDraftKey}#sent:${draftOwner}`) : freshDraftKey); + const [sentOn, setSentOn] = useState(undefined); + const ownDraft = !session && freshDraftKey !== undefined && sentOn === freshDraftKey; + const draftKey = session?.id ?? (ownDraft ? sentDraftKey(freshDraftKey, draftOwner) : freshDraftKey); + const freshDraftKeyRef = useRef(freshDraftKey); + freshDraftKeyRef.current = freshDraftKey; + const draftKeyRef = useRef(draftKey); + draftKeyRef.current = draftKey; const handleSent = useCallback(() => { - setSentAsNew(true); + setSentOn(freshDraftKeyRef.current); onSent?.(); }, [onSent]); + // A chat that goes away (its tab closed, another new chat replacing it) leaves its own draft to its workspace's, as + // a send still in flight does. + useEffect(() => () => { + const key = draftKeyRef.current; + if (key && isSentDraftKey(key)) foldSentDraft(key); + }, []); const { loading, error, messages, entryIds, showPreCompactionHistory, streamState, agentRunning, bashRunning, pendingBash, deferredBash, modelNames, modelList, modelsLoading, modelError, modelThinkingLevels, modelThinkingLevelMaps, thinkingLevel, @@ -978,6 +990,7 @@ export function ChatWindow({ session, newSessionCwd, newSessionHostId, newSessio onAudioUnlock={unlockAudio} draftKey={draftKey} draftOwner={draftOwner} + draftKeyContinues={ownDraft ? freshDraftKey : undefined} uploadHostId={session ? session.hostId : newSessionHostId} resolveUploadHost={!session && newSessionPoolId ? resolveUploadHost : undefined} cwd={!session && newSessionPoolId ? null : session?.cwd ?? newSessionCwd} diff --git a/hooks/useAgentSession.rpc.test.mjs b/hooks/useAgentSession.rpc.test.mjs index 266030be..60eb386e 100644 --- a/hooks/useAgentSession.rpc.test.mjs +++ b/hooks/useAgentSession.rpc.test.mjs @@ -6196,6 +6196,30 @@ test("text typed into a kept chat after it sent stays with it when another new c h.view.unmount(); }); +test("text typed into a new chat while its session is created stays in that chat once the session takes over", async (t) => { + const h = await sentBesideFreshChat(t); + world.sessions.set("created", { leafId: null, messages: [], entryIds: [] }); + await act(async () => { fireEvent.change(h.composerIn(h.draftGroup), { target: { value: "typed while spawning" } }); await sleep(60); }); + await act(async () => { h.release(); await sleep(300); }); + assert.ok(within(h.draftGroup).queryByRole("tab", { name: "hello there" }), "the session took the kept chat's tab"); + assert.equal(h.composerIn(h.draftGroup).value, "typed while spawning", "its composer keeps the text"); + assert.equal(h.composerIn(h.other).value, "", "the fresh new chat does not get it"); + await act(async () => { fireEvent.change(h.composerIn(h.draftGroup), { target: { value: "" } }); await sleep(30); }); + h.view.unmount(); +}); + +test("a failed kept chat replaced by another new chat leaves its text to the workspace's draft", async (t) => { + const h = await sentBesideFreshChat(t, { status: 500, value: { error: "spawn failed" } }); + await act(async () => { h.release(); await sleep(300); }); + assert.equal(h.composerIn(h.draftGroup).value, "hello there"); + await act(async () => { fireEvent.click(within(h.draftGroup).getByRole("tab", { name: translate("appShell.newSession") })); await sleep(150); }); + await act(async () => { fireEvent.click(h.newSessionButton()); await sleep(150); }); + const composers = [...h.view.container.querySelectorAll("textarea")].map((area) => area.value); + assert.ok(composers.some((value) => value === "hello there"), `the new chat shows it: ${JSON.stringify(composers)}`); + for (const area of h.view.container.querySelectorAll("textarea")) await act(async () => { fireEvent.change(area, { target: { value: "" } }); await sleep(20); }); + h.view.unmount(); +}); + test("another new chat replaces an unsent kept one and opens fresh in the focused group", async (t) => { const h = await draftInItsOwnGroup(t); await act(async () => { fireEvent.change(h.draftComposer, { target: { value: "unsent idea" } }); await sleep(60); }); diff --git a/lib/draft-store.test.mjs b/lib/draft-store.test.mjs index 3b2e3f6b..689d8f88 100644 --- a/lib/draft-store.test.mjs +++ b/lib/draft-store.test.mjs @@ -1,7 +1,7 @@ import assert from "node:assert/strict"; import { spawnSync } from "node:child_process"; import test from "node:test"; -import { clearDraft, consumeDraft, holdDraftOwner, transientDraftKey, getDraft, getDraftRevision, getDraftSummary, markDraftEdited, mergeRecoveredText, recoverDraft, setDraft, subscribeDraftConsumption, subscribeDraftRecovery } from "./draft-store.ts"; +import { clearDraft, consumeDraft, foldSentDraft, holdDraftOwner, isSentDraftKey, sentDraftKey, getDraft, getDraftRevision, getDraftSummary, markDraftEdited, mergeRecoveredText, recoverDraft, setDraft, subscribeDraftConsumption, subscribeDraftRecovery } from "./draft-store.ts"; test("outbox consumption notifies matching drafts without clearing newer text, equal-text retypes or attachment payloads", () => { const key = "outbox-consumption"; @@ -313,20 +313,35 @@ test("a later recovery merges with an earlier one in order, unless the draft no assert.equal(mergeRecoveredText("edited", { text: "A\n\nB", replace }), "A\n\nedited", "never re-adds text the user removed"); }); -test("a recovery follows its chat to the draft that chat shows now, and a page-only key is never stored", (t) => { - const stored = new Map(); - globalThis.sessionStorage = { getItem: (k) => stored.get(k) ?? null, setItem: (k, v) => { stored.set(k, String(v)); }, removeItem: (k) => { stored.delete(k); } }; - t.after(() => { delete globalThis.sessionStorage; }); - const own = transientDraftKey("new:/w#sent:a"); +test("a recovery follows its chat to the draft that chat shows now, and a chat's own draft folds back into its workspace's", () => { + const own = sentDraftKey("new:/w", "a"); + assert.equal(own, "new:/w#sent:a"); + assert.ok(isSentDraftKey(own)); const release = holdDraftOwner("a", own); recoverDraft("new:/w", { text: "failed prompt" }, "a"); assert.equal(getDraft(own)?.value, "failed prompt", "into the chat's own draft"); assert.equal(getDraft("new:/w"), null, "not the workspace's, which another new chat may show"); - assert.equal(stored.has("tau-draft-" + own), false, "nothing reopens a page-only key after a reload"); release(); recoverDraft("new:/w", { text: "after it closed" }, "a"); assert.equal(getDraft("new:/w")?.value, "after it closed", "a chat no longer shown gives it to the workspace's draft"); - assert.ok(stored.has("tau-draft-new:/w")); - clearDraft(own); + foldSentDraft(own); + assert.equal(getDraft(own), null); + assert.equal(getDraft("new:/w")?.value, "failed prompt\n\nafter it closed", "its own draft joins the workspace's (recovered text leads)"); clearDraft("new:/w"); }); + +test("a reload folds a chat's own drafts into their workspaces' drafts", () => { + const script = ` + const stored = new Map([["tau-draft-new:/w", "kept"], ["tau-draft-new:/w#sent:a", "own text"], ["tau-prompt-draft-new:/w#sent:a", "1"]]); + globalThis.sessionStorage = { get length() { return stored.size; }, key: (i) => [...stored.keys()][i] ?? null, getItem: (k) => stored.get(k) ?? null, setItem: (k, v) => { stored.set(k, String(v)); }, removeItem: (k) => { stored.delete(k); } }; + const { getDraft } = await import("./lib/draft-store.ts"); + console.log(JSON.stringify({ draft: getDraft("new:/w"), own: getDraft("new:/w#sent:a"), keys: [...stored.keys()].sort() })); + `; + const run = spawnSync(process.execPath, ["-e", script], { cwd: new URL("..", import.meta.url).pathname, encoding: "utf8" }); + assert.equal(run.status, 0, run.stderr); + const result = JSON.parse(run.stdout.trim().split("\n").at(-1)); + assert.equal(result.own, null); + assert.equal(result.draft.value, "own text\n\nkept"); + assert.equal(result.draft.promptOnly, true, "a prompt-only draft stays one"); + assert.deepEqual(result.keys, ["tau-draft-new:/w", "tau-prompt-draft-new:/w"]); +}); diff --git a/lib/draft-store.ts b/lib/draft-store.ts index 6a5e624b..045219a6 100644 --- a/lib/draft-store.ts +++ b/lib/draft-store.ts @@ -54,7 +54,6 @@ declare global { var __tauChatDrafts: Map | undefined; var __tauChatDraftListeners: Set<() => void> | undefined; var __tauChatDraftOwners: Map | undefined; - var __tauChatDraftTransientKeys: Set | undefined; var __tauChatDraftRecoveryListeners: Set<(key: string, recovery: DraftRecovery) => void> | undefined; var __tauChatDraftConsumptionListeners: Set<(key: string, snapshot: ChatDraft) => void> | undefined; var __tauChatDraftRevisions: { byKey: Map; last: number } | undefined; @@ -238,13 +237,23 @@ export function holdDraftOwner(owner: string, key: string): () => void { }; } -/** Keys of drafts that live only as long as this page (`transientDraftKey`). */ -const transientKeys = (globalThis.__tauChatDraftTransientKeys ??= new Set()); +const SENT_KEY_MARK = "#sent:"; -/** `key`, as a draft key of this page only: kept out of sessionStorage, since nothing reopens it after a reload. */ -export function transientDraftKey(key: string): string { - transientKeys.add(key); - return key; +/** A new chat's draft key of its own once it sent, over its workspace's `base`, until its session takes over. */ +export function sentDraftKey(base: string, chat: string): string { + return `${base}${SENT_KEY_MARK}${chat}`; +} + +export function isSentDraftKey(key: string): boolean { + return key.includes(SENT_KEY_MARK); +} + +/** A `sentDraftKey`'s draft goes back to its workspace's (its chat is gone, or the page was reloaded): recovered into + * it as into any composer, so a new chat showing it gets the text too. */ +export function foldSentDraft(key: string): void { + const draft = getDraft(key); + clearDraft(key); + if (draft) recoverDraft(key.slice(0, key.lastIndexOf(SENT_KEY_MARK)), { text: draft.value, images: draft.images.length ? draft.images : undefined, files: draft.files.length ? draft.files : undefined, uploads: draft.uploads, ...(draft.promptOnly ? { promptOnly: true } : {}) }); } /** Recovers into `key`'s draft or, when `owner`'s composer is mounted, into the draft it shows now: a new chat that @@ -292,7 +301,7 @@ export function setDraft(key: string, draft: ChatDraft): void { markSubmissionsEdited(key); } drafts.set(key, next); - if (!transientKeys.has(key)) try { + try { // Persist only text: attachment payloads can exhaust the tab's storage quota. // Mark prompt provenance before publishing its text; never restore that text as a shell command after reload. if (next.promptOnly) sessionStorage.setItem(PROMPT_STORAGE_PREFIX + key, "1"); @@ -321,3 +330,6 @@ export function clearDraft(key: string): void { for (const listener of listeners) listener(); } } + +// A reload reopens no chat's own key: their drafts are their workspaces' again. +for (const key of [...drafts.keys()]) if (isSentDraftKey(key)) foldSentDraft(key); From 232076d1daa1910dd46c104755d9424b226b0aa1 Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Fri, 27 Nov 2026 07:06:42 +0000 Subject: [PATCH 07/13] fix(chat): recognise a chat's own draft key by its shape; send it back to its workspace when nobody shows it --- components/ChatInput.tsx | 14 +++++++++----- components/ChatWindow.tsx | 3 ++- lib/draft-store.test.mjs | 18 +++++++++++------- lib/draft-store.ts | 21 +++++++++++++++++---- 4 files changed, 39 insertions(+), 17 deletions(-) diff --git a/components/ChatInput.tsx b/components/ChatInput.tsx index ad20d57e..e2bdb83c 100644 --- a/components/ChatInput.tsx +++ b/components/ChatInput.tsx @@ -15,7 +15,7 @@ import type { SttAfter } from "@/lib/stt"; import { formatCompactNumber, formatPercent } from "@/lib/format"; import { ContextDetailPanel } from "./ComposerPanels"; import { RecordingDeck } from "./RecordingDeck"; -import { beginDraftSubmission, clearDraft, consumeDraft, endDraftSubmission, getDraft, getDraftRevision, holdDraftOwner, isSameDraft, isSentDraftKey, markDraftEdited, mergeRecoveredText, recoverDraft, requiresPromptMode, setDraft, subscribeDraftConsumption, subscribeDraftRecovery, type ChatDraft } from "@/lib/draft-store"; +import { beginDraftSubmission, clearDraft, consumeDraft, endDraftSubmission, getDraft, getDraftRevision, foldSentDraft, holdDraftOwner, isSameDraft, isSentDraftKey, markDraftEdited, mergeRecoveredText, recoverDraft, requiresPromptMode, setDraft, subscribeDraftConsumption, subscribeDraftRecovery, type ChatDraft } from "@/lib/draft-store"; import { expandWebSlashCommand } from "@/lib/web-slash-commands"; import { WorkspaceFileContext } from "@/lib/workspace-file-context"; import type { AttachedImage, AttachedTextFile } from "./ChatInput-draft-attachments"; @@ -973,8 +973,10 @@ export const ChatInput = memo(forwardRef(function ChatIn clearDraft(previousDraftKey); return; } - // Leaving the chat's own key (its session, another workspace): what it holds goes to the next key, never stays behind. - const carried = previousDraftKey && isSentDraftKey(previousDraftKey) ? captureDraft() : null; + // Leaving the chat's own key: what it holds goes to its session's draft when the session takes over, else back to + // its workspace's (another workspace may be on another host, where its uploads are not). + const leavingOwn = previousDraftKey !== undefined && isSentDraftKey(previousDraftKey); + const carried = leavingOwn && draftKey && !draftKey.startsWith("new:") ? captureDraft() : null; // Invalidate any attachment reads still in flight for the old session so // they cannot append onto the new session's composer, and drop any stale @@ -985,8 +987,9 @@ export const ChatInput = memo(forwardRef(function ChatIn setAttachNotice(null); setQueuedDeleteTarget(null); + if (previousDraftKey) setDraft(previousDraftKey, captureDraft()); if (carried) clearDraft(previousDraftKey!); - else if (previousDraftKey) setDraft(previousDraftKey, captureDraft()); + else if (leavingOwn) foldSentDraft(previousDraftKey!); const draft = draftKey ? getDraft(draftKey) : null; draftKeyRef.current = draftKey; @@ -1201,7 +1204,8 @@ export const ChatInput = memo(forwardRef(function ChatIn seekPreview: seekPreviewDictation, confirmTranscribe: confirmTranscribeDictation, } = useDictation({ - scope: draftKey, + // A new chat's own key is its workspace's for dictation: a reload or another tab adopts its jobs from there. + scope: draftKeyContinues ?? draftKey, // `after` comes back with the transcript from the server job, so a send or // queue chosen before a session switch (which remounts this composer) holds. // The run may have started or ended since: queue while the agent runs diff --git a/components/ChatWindow.tsx b/components/ChatWindow.tsx index dbf9c8dd..bdc51112 100644 --- a/components/ChatWindow.tsx +++ b/components/ChatWindow.tsx @@ -434,7 +434,8 @@ export function ChatWindow({ session, newSessionCwd, newSessionHostId, newSessio }, [onAgentEnd]); // This chat across remounts of its composer (ChatInput's draftOwner). - const [draftOwner] = useState(() => Math.random().toString(36).slice(2, 12) + Date.now().toString(36)); + // At least 12 base36 characters: the shape `isSentDraftKey` recognizes. + const [draftOwner] = useState(() => Math.random().toString(36).slice(2, 12).padEnd(10, "0") + Date.now().toString(36)); // Once a new chat sent, its draft is its own until its session takes over: another new chat on the workspace (it // may open while this one's session is created) has the workspace's. // Held for the workspace key it sent on: another workspace's draft is that workspace's again. diff --git a/lib/draft-store.test.mjs b/lib/draft-store.test.mjs index 689d8f88..3beb2e06 100644 --- a/lib/draft-store.test.mjs +++ b/lib/draft-store.test.mjs @@ -314,15 +314,19 @@ test("a later recovery merges with an earlier one in order, unless the draft no }); test("a recovery follows its chat to the draft that chat shows now, and a chat's own draft folds back into its workspace's", () => { - const own = sentDraftKey("new:/w", "a"); - assert.equal(own, "new:/w#sent:a"); + const own = sentDraftKey("new:/w", "chat0000000a"); + assert.equal(own, "new:/w#sent:chat0000000a"); + assert.equal(isSentDraftKey("new:/home/u/a#sent:b"), false, "a workspace path with the mark in it is no chat's own key"); assert.ok(isSentDraftKey(own)); - const release = holdDraftOwner("a", own); - recoverDraft("new:/w", { text: "failed prompt" }, "a"); + const release = holdDraftOwner("chat0000000a", own); + recoverDraft("new:/w", { text: "failed prompt" }, "chat0000000a"); assert.equal(getDraft(own)?.value, "failed prompt", "into the chat's own draft"); assert.equal(getDraft("new:/w"), null, "not the workspace's, which another new chat may show"); release(); - recoverDraft("new:/w", { text: "after it closed" }, "a"); + recoverDraft(own, { text: "second send" }, "chat0000000a"); + assert.equal(getDraft("new:/w")?.value, "second send", "a chat's own key nobody shows gives way to its workspace's"); + clearDraft("new:/w"); + recoverDraft("new:/w", { text: "after it closed" }, "chat0000000a"); assert.equal(getDraft("new:/w")?.value, "after it closed", "a chat no longer shown gives it to the workspace's draft"); foldSentDraft(own); assert.equal(getDraft(own), null); @@ -332,10 +336,10 @@ test("a recovery follows its chat to the draft that chat shows now, and a chat's test("a reload folds a chat's own drafts into their workspaces' drafts", () => { const script = ` - const stored = new Map([["tau-draft-new:/w", "kept"], ["tau-draft-new:/w#sent:a", "own text"], ["tau-prompt-draft-new:/w#sent:a", "1"]]); + const stored = new Map([["tau-draft-new:/w", "kept"], ["tau-draft-new:/w#sent:chat0000000a", "own text"], ["tau-prompt-draft-new:/w#sent:chat0000000a", "1"]]); globalThis.sessionStorage = { get length() { return stored.size; }, key: (i) => [...stored.keys()][i] ?? null, getItem: (k) => stored.get(k) ?? null, setItem: (k, v) => { stored.set(k, String(v)); }, removeItem: (k) => { stored.delete(k); } }; const { getDraft } = await import("./lib/draft-store.ts"); - console.log(JSON.stringify({ draft: getDraft("new:/w"), own: getDraft("new:/w#sent:a"), keys: [...stored.keys()].sort() })); + console.log(JSON.stringify({ draft: getDraft("new:/w"), own: getDraft("new:/w#sent:chat0000000a"), keys: [...stored.keys()].sort() })); `; const run = spawnSync(process.execPath, ["-e", script], { cwd: new URL("..", import.meta.url).pathname, encoding: "utf8" }); assert.equal(run.status, 0, run.stderr); diff --git a/lib/draft-store.ts b/lib/draft-store.ts index 045219a6..baebc4ef 100644 --- a/lib/draft-store.ts +++ b/lib/draft-store.ts @@ -54,6 +54,7 @@ declare global { var __tauChatDrafts: Map | undefined; var __tauChatDraftListeners: Set<() => void> | undefined; var __tauChatDraftOwners: Map | undefined; + var __tauChatDraftsFolded: boolean | undefined; var __tauChatDraftRecoveryListeners: Set<(key: string, recovery: DraftRecovery) => void> | undefined; var __tauChatDraftConsumptionListeners: Set<(key: string, snapshot: ChatDraft) => void> | undefined; var __tauChatDraftRevisions: { byKey: Map; last: number } | undefined; @@ -240,12 +241,19 @@ export function holdDraftOwner(owner: string, key: string): () => void { const SENT_KEY_MARK = "#sent:"; /** A new chat's draft key of its own once it sent, over its workspace's `base`, until its session takes over. */ +function sentDraftBase(key: string): string { + return key.slice(0, key.lastIndexOf(SENT_KEY_MARK)); +} + export function sentDraftKey(base: string, chat: string): string { return `${base}${SENT_KEY_MARK}${chat}`; } +// The exact shape at the end of the key (a chat id is base36): `#` is legal in a workspace path. +const SENT_KEY_RE = /#sent:[0-9a-z]{12,}$/; + export function isSentDraftKey(key: string): boolean { - return key.includes(SENT_KEY_MARK); + return SENT_KEY_RE.test(key); } /** A `sentDraftKey`'s draft goes back to its workspace's (its chat is gone, or the page was reloaded): recovered into @@ -253,7 +261,7 @@ export function isSentDraftKey(key: string): boolean { export function foldSentDraft(key: string): void { const draft = getDraft(key); clearDraft(key); - if (draft) recoverDraft(key.slice(0, key.lastIndexOf(SENT_KEY_MARK)), { text: draft.value, images: draft.images.length ? draft.images : undefined, files: draft.files.length ? draft.files : undefined, uploads: draft.uploads, ...(draft.promptOnly ? { promptOnly: true } : {}) }); + if (draft) recoverDraft(sentDraftBase(key), { text: draft.value, images: draft.images.length ? draft.images : undefined, files: draft.files.length ? draft.files : undefined, uploads: draft.uploads, ...(draft.promptOnly ? { promptOnly: true } : {}) }); } /** Recovers into `key`'s draft or, when `owner`'s composer is mounted, into the draft it shows now: a new chat that @@ -261,6 +269,8 @@ export function foldSentDraft(key: string): void { export function recoverDraft(key: string, recovery: DraftRecovery, owner?: string): void { if (!recovery.text && !recovery.images?.length && !recovery.files?.length && !recovery.uploads?.length) return; key = (owner && liveOwners.get(owner)) || key; + // A chat's own key that no composer shows any more (its chat went away): its workspace's draft takes it. + if (isSentDraftKey(key) && ![...liveOwners.values()].includes(key)) key = sentDraftBase(key); if (key) { const draft = getDraft(key) ?? { value: "", images: [], files: [] }; setDraft(key, { @@ -331,5 +341,8 @@ export function clearDraft(key: string): void { } } -// A reload reopens no chat's own key: their drafts are their workspaces' again. -for (const key of [...drafts.keys()]) if (isSentDraftKey(key)) foldSentDraft(key); +// A reload reopens no chat's own key: their drafts are their workspaces' again (once per page, not per hot reload). +if (!globalThis.__tauChatDraftsFolded) { + globalThis.__tauChatDraftsFolded = true; + for (const key of [...drafts.keys()]) if (isSentDraftKey(key)) foldSentDraft(key); +} From 2721565ed066a399c986681b304151b78acac92e Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Fri, 27 Nov 2026 07:20:53 +0000 Subject: [PATCH 08/13] fix(chat): mark a chat's own draft key with NUL; recover only into the chat's own or session draft --- AGENTS.md | 2 +- components/ChatWindow.tsx | 3 +-- lib/draft-store.test.mjs | 15 +++++++++++---- lib/draft-store.ts | 13 +++++++------ 4 files changed, 20 insertions(+), 13 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 269b4352..2793478c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -370,7 +370,7 @@ Browser keys use `tau-` / `tau:` (`tau-theme`, the `tau-theme-color` cookie, `ta - Prefill only the selected message's text, never its images. Preserve drafts, newer typing and attachments through pending edits, cancellation, errors and navigation. `submissionBlocked` keeps asynchronous dictation from submitting or clearing the composer. `session_history_changed` carries the leaf marker; the initiating tab deduplicates its own echo. Editing does not undo tool side effects. - Draft text survives reload via sessionStorage; attachment payloads stay in memory. - Event connections own their readiness waits: replacement and unmount settle the old wait as closed and close its observer; stale continuations must not attach streams or authorize operations. A new chat's first prompt is the exception: when its chat unmounts while pi spawns, `handleSend` still sends it and returns `accepted`. A new chat left for another group's chat stays mounted there instead; its session then replaces its tab in place without being selected (`handleSessionCreated`). Existing sessions' messages go through the outbox. - - `ChatInput.onSend` returns `Promise` (`accepted` / `rejected` / `superseded`). With `outbox` the composer clears only once the message is stored in the browser's outbox and only if it still holds what was sent. For a new chat only rejection restores the draft (`recoverDraft`; the composer owns recovery), into the draft its chat shows when the reply comes (`draftOwner`, `holdDraftOwner`; a session id the hook names wins), else the key captured at the send; superseded failures never reinsert a processed turn. A new chat that sent has a draft of its own, `#sent:` (`sentDraftKey`, set from the hook's `onSent`), until its session takes over: another new chat on the workspace, which may open meanwhile (a kept chat's draft tab), has the workspace's. Moving to that key keeps the composer's content (`draftKeyContinues`); leaving it (the session, another workspace) carries the content to the next key; a chat that goes away, and a reload, fold it back into the workspace's (`foldSentDraft`). + - `ChatInput.onSend` returns `Promise` (`accepted` / `rejected` / `superseded`). With `outbox` the composer clears only once the message is stored in the browser's outbox and only if it still holds what was sent. For a new chat only rejection restores the draft (`recoverDraft`; the composer owns recovery), into the draft its chat shows when the reply comes (`draftOwner`, `holdDraftOwner`; a session id the hook names wins), else the key captured at the send; superseded failures never reinsert a processed turn. A new chat that sent has a draft of its own, `\0sent:` (NUL: no other key can look like it; `sentDraftKey`, set from the hook's `onSent`), until its session takes over: another new chat on the workspace, which may open meanwhile (a kept chat's draft tab), has the workspace's. Moving to that key keeps the composer's content (`draftKeyContinues`); leaving it (the session, another workspace) carries the content to the next key; a chat that goes away, and a reload, fold it back into the workspace's (`foldSentDraft`). - **In-session branch** (Continue / BranchNavigator): a read-only historical view of the entry tree through `/api/sessions/[id]/context?leafId=` (`handleLeafChange`); it does not change the live agent. Never implement Edit with it. ### ToolCall field normalization diff --git a/components/ChatWindow.tsx b/components/ChatWindow.tsx index bdc51112..dbf9c8dd 100644 --- a/components/ChatWindow.tsx +++ b/components/ChatWindow.tsx @@ -434,8 +434,7 @@ export function ChatWindow({ session, newSessionCwd, newSessionHostId, newSessio }, [onAgentEnd]); // This chat across remounts of its composer (ChatInput's draftOwner). - // At least 12 base36 characters: the shape `isSentDraftKey` recognizes. - const [draftOwner] = useState(() => Math.random().toString(36).slice(2, 12).padEnd(10, "0") + Date.now().toString(36)); + const [draftOwner] = useState(() => Math.random().toString(36).slice(2, 12) + Date.now().toString(36)); // Once a new chat sent, its draft is its own until its session takes over: another new chat on the workspace (it // may open while this one's session is created) has the workspace's. // Held for the workspace key it sent on: another workspace's draft is that workspace's again. diff --git a/lib/draft-store.test.mjs b/lib/draft-store.test.mjs index 3beb2e06..8495e5ab 100644 --- a/lib/draft-store.test.mjs +++ b/lib/draft-store.test.mjs @@ -315,13 +315,20 @@ test("a later recovery merges with an earlier one in order, unless the draft no test("a recovery follows its chat to the draft that chat shows now, and a chat's own draft folds back into its workspace's", () => { const own = sentDraftKey("new:/w", "chat0000000a"); - assert.equal(own, "new:/w#sent:chat0000000a"); - assert.equal(isSentDraftKey("new:/home/u/a#sent:b"), false, "a workspace path with the mark in it is no chat's own key"); + assert.equal(own, "new:/w\u0000sent:chat0000000a"); + assert.equal(isSentDraftKey("new:/home/u/a#sent:abcdefghijklmnop"), false, "a workspace path that looks like a mark is no chat's own key"); assert.ok(isSentDraftKey(own)); const release = holdDraftOwner("chat0000000a", own); recoverDraft("new:/w", { text: "failed prompt" }, "chat0000000a"); assert.equal(getDraft(own)?.value, "failed prompt", "into the chat's own draft"); assert.equal(getDraft("new:/w"), null, "not the workspace's, which another new chat may show"); + const other = holdDraftOwner("chat0000000a", "new:h2:/elsewhere"); + recoverDraft("new:/w", { text: "moved away", uploads: [{ id: "u1", name: "f", size: 1, hostId: "local" }] }, "chat0000000a"); + assert.equal(getDraft("new:h2:/elsewhere"), null, "never into another workspace's draft, maybe on another host"); + assert.equal(getDraft("new:/w")?.uploads?.[0]?.id, "u1", "the workspace it was sent on keeps it"); + clearDraft("new:/w"); + other(); + holdDraftOwner("chat0000000a", own)(); release(); recoverDraft(own, { text: "second send" }, "chat0000000a"); assert.equal(getDraft("new:/w")?.value, "second send", "a chat's own key nobody shows gives way to its workspace's"); @@ -336,10 +343,10 @@ test("a recovery follows its chat to the draft that chat shows now, and a chat's test("a reload folds a chat's own drafts into their workspaces' drafts", () => { const script = ` - const stored = new Map([["tau-draft-new:/w", "kept"], ["tau-draft-new:/w#sent:chat0000000a", "own text"], ["tau-prompt-draft-new:/w#sent:chat0000000a", "1"]]); + const stored = new Map([["tau-draft-new:/w", "kept"], ["tau-draft-new:/w\\u0000sent:chat0000000a", "own text"], ["tau-prompt-draft-new:/w\\u0000sent:chat0000000a", "1"]]); globalThis.sessionStorage = { get length() { return stored.size; }, key: (i) => [...stored.keys()][i] ?? null, getItem: (k) => stored.get(k) ?? null, setItem: (k, v) => { stored.set(k, String(v)); }, removeItem: (k) => { stored.delete(k); } }; const { getDraft } = await import("./lib/draft-store.ts"); - console.log(JSON.stringify({ draft: getDraft("new:/w"), own: getDraft("new:/w#sent:chat0000000a"), keys: [...stored.keys()].sort() })); + console.log(JSON.stringify({ draft: getDraft("new:/w"), own: getDraft("new:/w\\u0000sent:chat0000000a"), keys: [...stored.keys()].sort() })); `; const run = spawnSync(process.execPath, ["-e", script], { cwd: new URL("..", import.meta.url).pathname, encoding: "utf8" }); assert.equal(run.status, 0, run.stderr); diff --git a/lib/draft-store.ts b/lib/draft-store.ts index baebc4ef..af287a96 100644 --- a/lib/draft-store.ts +++ b/lib/draft-store.ts @@ -238,7 +238,8 @@ export function holdDraftOwner(owner: string, key: string): () => void { }; } -const SENT_KEY_MARK = "#sent:"; +// NUL: no workspace path, host id or session id holds one, so no other key can look like a chat's own. +const SENT_KEY_MARK = "\u0000sent:"; /** A new chat's draft key of its own once it sent, over its workspace's `base`, until its session takes over. */ function sentDraftBase(key: string): string { @@ -249,11 +250,8 @@ export function sentDraftKey(base: string, chat: string): string { return `${base}${SENT_KEY_MARK}${chat}`; } -// The exact shape at the end of the key (a chat id is base36): `#` is legal in a workspace path. -const SENT_KEY_RE = /#sent:[0-9a-z]{12,}$/; - export function isSentDraftKey(key: string): boolean { - return SENT_KEY_RE.test(key); + return key.includes(SENT_KEY_MARK); } /** A `sentDraftKey`'s draft goes back to its workspace's (its chat is gone, or the page was reloaded): recovered into @@ -268,7 +266,10 @@ export function foldSentDraft(key: string): void { * sent moves to a key of its own, and another chat may have its old one. */ export function recoverDraft(key: string, recovery: DraftRecovery, owner?: string): void { if (!recovery.text && !recovery.images?.length && !recovery.files?.length && !recovery.uploads?.length) return; - key = (owner && liveOwners.get(owner)) || key; + // The chat's draft now: its own key or its session's (same workspace, same host), never another workspace's, which + // may be on another host than the recovered uploads. + const shown = owner ? liveOwners.get(owner) : undefined; + if (shown && (!shown.startsWith("new:") || (isSentDraftKey(shown) && sentDraftBase(shown) === key))) key = shown; // A chat's own key that no composer shows any more (its chat went away): its workspace's draft takes it. if (isSentDraftKey(key) && ![...liveOwners.values()].includes(key)) key = sentDraftBase(key); if (key) { From 987d46d23bdfffe4f7e16203b42bebb4b7678d1d Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Fri, 27 Nov 2026 07:26:54 +0000 Subject: [PATCH 09/13] fix(chat): give a chat's own draft key a namespace of its own; recover into it only for the workspace it sent on --- AGENTS.md | 2 +- components/ChatInput.tsx | 2 +- lib/draft-store.test.mjs | 13 +++++++++---- lib/draft-store.ts | 25 +++++++++++++------------ 4 files changed, 24 insertions(+), 18 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 2793478c..61a080ff 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -370,7 +370,7 @@ Browser keys use `tau-` / `tau:` (`tau-theme`, the `tau-theme-color` cookie, `ta - Prefill only the selected message's text, never its images. Preserve drafts, newer typing and attachments through pending edits, cancellation, errors and navigation. `submissionBlocked` keeps asynchronous dictation from submitting or clearing the composer. `session_history_changed` carries the leaf marker; the initiating tab deduplicates its own echo. Editing does not undo tool side effects. - Draft text survives reload via sessionStorage; attachment payloads stay in memory. - Event connections own their readiness waits: replacement and unmount settle the old wait as closed and close its observer; stale continuations must not attach streams or authorize operations. A new chat's first prompt is the exception: when its chat unmounts while pi spawns, `handleSend` still sends it and returns `accepted`. A new chat left for another group's chat stays mounted there instead; its session then replaces its tab in place without being selected (`handleSessionCreated`). Existing sessions' messages go through the outbox. - - `ChatInput.onSend` returns `Promise` (`accepted` / `rejected` / `superseded`). With `outbox` the composer clears only once the message is stored in the browser's outbox and only if it still holds what was sent. For a new chat only rejection restores the draft (`recoverDraft`; the composer owns recovery), into the draft its chat shows when the reply comes (`draftOwner`, `holdDraftOwner`; a session id the hook names wins), else the key captured at the send; superseded failures never reinsert a processed turn. A new chat that sent has a draft of its own, `\0sent:` (NUL: no other key can look like it; `sentDraftKey`, set from the hook's `onSent`), until its session takes over: another new chat on the workspace, which may open meanwhile (a kept chat's draft tab), has the workspace's. Moving to that key keeps the composer's content (`draftKeyContinues`); leaving it (the session, another workspace) carries the content to the next key; a chat that goes away, and a reload, fold it back into the workspace's (`foldSentDraft`). + - `ChatInput.onSend` returns `Promise` (`accepted` / `rejected` / `superseded`). With `outbox` the composer clears only once the message is stored in the browser's outbox and only if it still holds what was sent. For a new chat only rejection restores the draft (`recoverDraft`; the composer owns recovery), into the draft its chat shows when the reply comes (`draftOwner`, `holdDraftOwner`: only the chat's own key on the workspace it sent on; a session id the hook names wins), else the key captured at the send; superseded failures never reinsert a processed turn. A new chat that sent has a draft of its own, `sent::` (a namespace no workspace or session key can enter; `sentDraftKey`, set from the hook's `onSent`), until its session takes over: another new chat on the workspace, which may open meanwhile (a kept chat's draft tab), has the workspace's. Moving to that key keeps the composer's content (`draftKeyContinues`); leaving it (the session, another workspace) carries the content to the next key; a chat that goes away, and a reload, fold it back into the workspace's (`foldSentDraft`). - **In-session branch** (Continue / BranchNavigator): a read-only historical view of the entry tree through `/api/sessions/[id]/context?leafId=` (`handleLeafChange`); it does not change the live agent. Never implement Edit with it. ### ToolCall field normalization diff --git a/components/ChatInput.tsx b/components/ChatInput.tsx index e2bdb83c..2e1aa1b2 100644 --- a/components/ChatInput.tsx +++ b/components/ChatInput.tsx @@ -976,7 +976,7 @@ export const ChatInput = memo(forwardRef(function ChatIn // Leaving the chat's own key: what it holds goes to its session's draft when the session takes over, else back to // its workspace's (another workspace may be on another host, where its uploads are not). const leavingOwn = previousDraftKey !== undefined && isSentDraftKey(previousDraftKey); - const carried = leavingOwn && draftKey && !draftKey.startsWith("new:") ? captureDraft() : null; + const carried = leavingOwn && draftKey && !draftKey.startsWith("new:") && !isSentDraftKey(draftKey) ? captureDraft() : null; // Invalidate any attachment reads still in flight for the old session so // they cannot append onto the new session's composer, and drop any stale diff --git a/lib/draft-store.test.mjs b/lib/draft-store.test.mjs index 8495e5ab..5225db5c 100644 --- a/lib/draft-store.test.mjs +++ b/lib/draft-store.test.mjs @@ -315,7 +315,7 @@ test("a later recovery merges with an earlier one in order, unless the draft no test("a recovery follows its chat to the draft that chat shows now, and a chat's own draft folds back into its workspace's", () => { const own = sentDraftKey("new:/w", "chat0000000a"); - assert.equal(own, "new:/w\u0000sent:chat0000000a"); + assert.equal(own, "sent:chat0000000a:new:/w"); assert.equal(isSentDraftKey("new:/home/u/a#sent:abcdefghijklmnop"), false, "a workspace path that looks like a mark is no chat's own key"); assert.ok(isSentDraftKey(own)); const release = holdDraftOwner("chat0000000a", own); @@ -328,7 +328,12 @@ test("a recovery follows its chat to the draft that chat shows now, and a chat's assert.equal(getDraft("new:/w")?.uploads?.[0]?.id, "u1", "the workspace it was sent on keeps it"); clearDraft("new:/w"); other(); - holdDraftOwner("chat0000000a", own)(); + const session = holdDraftOwner("chat0000000a", "4f1c0de0-0000-4000-8000-000000000001"); + recoverDraft("new:/w", { text: "not its session" }, "chat0000000a"); + assert.equal(getDraft("4f1c0de0-0000-4000-8000-000000000001"), null, "a session the chat shows now is not proof the send created it"); + assert.equal(getDraft("new:/w")?.value, "not its session"); + clearDraft("new:/w"); + session(); release(); recoverDraft(own, { text: "second send" }, "chat0000000a"); assert.equal(getDraft("new:/w")?.value, "second send", "a chat's own key nobody shows gives way to its workspace's"); @@ -343,10 +348,10 @@ test("a recovery follows its chat to the draft that chat shows now, and a chat's test("a reload folds a chat's own drafts into their workspaces' drafts", () => { const script = ` - const stored = new Map([["tau-draft-new:/w", "kept"], ["tau-draft-new:/w\\u0000sent:chat0000000a", "own text"], ["tau-prompt-draft-new:/w\\u0000sent:chat0000000a", "1"]]); + const stored = new Map([["tau-draft-new:/w", "kept"], ["tau-draft-sent:chat0000000a:new:/w", "own text"], ["tau-prompt-draft-sent:chat0000000a:new:/w", "1"]]); globalThis.sessionStorage = { get length() { return stored.size; }, key: (i) => [...stored.keys()][i] ?? null, getItem: (k) => stored.get(k) ?? null, setItem: (k, v) => { stored.set(k, String(v)); }, removeItem: (k) => { stored.delete(k); } }; const { getDraft } = await import("./lib/draft-store.ts"); - console.log(JSON.stringify({ draft: getDraft("new:/w"), own: getDraft("new:/w\\u0000sent:chat0000000a"), keys: [...stored.keys()].sort() })); + console.log(JSON.stringify({ draft: getDraft("new:/w"), own: getDraft("sent:chat0000000a:new:/w"), keys: [...stored.keys()].sort() })); `; const run = spawnSync(process.execPath, ["-e", script], { cwd: new URL("..", import.meta.url).pathname, encoding: "utf8" }); assert.equal(run.status, 0, run.stderr); diff --git a/lib/draft-store.ts b/lib/draft-store.ts index af287a96..e91695ae 100644 --- a/lib/draft-store.ts +++ b/lib/draft-store.ts @@ -238,20 +238,21 @@ export function holdDraftOwner(owner: string, key: string): () => void { }; } -// NUL: no workspace path, host id or session id holds one, so no other key can look like a chat's own. -const SENT_KEY_MARK = "\u0000sent:"; - -/** A new chat's draft key of its own once it sent, over its workspace's `base`, until its session takes over. */ -function sentDraftBase(key: string): string { - return key.slice(0, key.lastIndexOf(SENT_KEY_MARK)); -} +// Its own namespace: a workspace's key starts with `new:` and a session's is its id, so neither can look like one. +const SENT_KEY_PREFIX = "sent:"; +/** A new chat's draft key of its own once it sent, over its workspace's `base`, until its session takes over. `chat` + * holds no `:`. */ export function sentDraftKey(base: string, chat: string): string { - return `${base}${SENT_KEY_MARK}${chat}`; + return `${SENT_KEY_PREFIX}${chat}:${base}`; } export function isSentDraftKey(key: string): boolean { - return key.includes(SENT_KEY_MARK); + return key.startsWith(SENT_KEY_PREFIX); +} + +function sentDraftBase(key: string): string { + return key.slice(key.indexOf(":", SENT_KEY_PREFIX.length) + 1); } /** A `sentDraftKey`'s draft goes back to its workspace's (its chat is gone, or the page was reloaded): recovered into @@ -266,10 +267,10 @@ export function foldSentDraft(key: string): void { * sent moves to a key of its own, and another chat may have its old one. */ export function recoverDraft(key: string, recovery: DraftRecovery, owner?: string): void { if (!recovery.text && !recovery.images?.length && !recovery.files?.length && !recovery.uploads?.length) return; - // The chat's draft now: its own key or its session's (same workspace, same host), never another workspace's, which - // may be on another host than the recovered uploads. + // The chat's own key over the workspace it sent on, while it shows it; never another draft, which may be another + // workspace's on another host than the recovered uploads (a session the send created comes as its own `key`). const shown = owner ? liveOwners.get(owner) : undefined; - if (shown && (!shown.startsWith("new:") || (isSentDraftKey(shown) && sentDraftBase(shown) === key))) key = shown; + if (shown && isSentDraftKey(shown) && sentDraftBase(shown) === key) key = shown; // A chat's own key that no composer shows any more (its chat went away): its workspace's draft takes it. if (isSentDraftKey(key) && ![...liveOwners.values()].includes(key)) key = sentDraftBase(key); if (key) { From 3eb33502d1e3c4b26a3618c118f6e01e747ef72d Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Fri, 27 Nov 2026 07:47:00 +0000 Subject: [PATCH 10/13] fix(chat): keep owner routing on a retry's workspace recovery; move a command in flight with its draft --- components/ChatInput.tsx | 8 +++++--- hooks/useAgentSession.rpc.test.mjs | 18 ++++++++++++++++++ lib/draft-store.test.mjs | 12 +++++++++++- lib/draft-store.ts | 5 +++++ 4 files changed, 39 insertions(+), 4 deletions(-) diff --git a/components/ChatInput.tsx b/components/ChatInput.tsx index 2e1aa1b2..0fce11fb 100644 --- a/components/ChatInput.tsx +++ b/components/ChatInput.tsx @@ -15,7 +15,7 @@ import type { SttAfter } from "@/lib/stt"; import { formatCompactNumber, formatPercent } from "@/lib/format"; import { ContextDetailPanel } from "./ComposerPanels"; import { RecordingDeck } from "./RecordingDeck"; -import { beginDraftSubmission, clearDraft, consumeDraft, endDraftSubmission, getDraft, getDraftRevision, foldSentDraft, holdDraftOwner, isSameDraft, isSentDraftKey, markDraftEdited, mergeRecoveredText, recoverDraft, requiresPromptMode, setDraft, subscribeDraftConsumption, subscribeDraftRecovery, type ChatDraft } from "@/lib/draft-store"; +import { beginDraftSubmission, clearDraft, consumeDraft, endDraftSubmission, moveDraftSubmissions, getDraft, getDraftRevision, foldSentDraft, holdDraftOwner, isSameDraft, isSentDraftKey, markDraftEdited, mergeRecoveredText, recoverDraft, requiresPromptMode, setDraft, subscribeDraftConsumption, subscribeDraftRecovery, type ChatDraft } from "@/lib/draft-store"; import { expandWebSlashCommand } from "@/lib/web-slash-commands"; import { WorkspaceFileContext } from "@/lib/workspace-file-context"; import type { AttachedImage, AttachedTextFile } from "./ChatInput-draft-attachments"; @@ -971,6 +971,8 @@ export const ChatInput = memo(forwardRef(function ChatIn draftRecoveryIdentityRef.current = { key: draftKey }; setDraft(draftKey, captureDraft()); clearDraft(previousDraftKey); + // A command in flight (`/name` sends before it clears) clears the moved draft once it is stored. + moveDraftSubmissions(previousDraftKey, draftKey); return; } // Leaving the chat's own key: what it holds goes to its session's draft when the session takes over, else back to @@ -1176,8 +1178,8 @@ export const ChatInput = memo(forwardRef(function ChatIn const result = await pending; if (result.status === "rejected") { const destination = result.recoveryKey ?? key; - // A session id the hook names is the chat's; otherwise the chat's draft now, wherever it moved. - if (destination) recoverDraft(destination, recovery, destination === key ? draftOwner : undefined); + // Into the chat's own draft when it shows one over the destination workspace; a session id stays as named. + if (destination) recoverDraft(destination, recovery, draftOwner); } } catch (error) { if (key) recoverDraft(key, recovery, draftOwner); diff --git a/hooks/useAgentSession.rpc.test.mjs b/hooks/useAgentSession.rpc.test.mjs index 60eb386e..aebd2ef5 100644 --- a/hooks/useAgentSession.rpc.test.mjs +++ b/hooks/useAgentSession.rpc.test.mjs @@ -6108,6 +6108,9 @@ test("a kept chat that sent a builtin command creating its session keeps a tab o const h = await sentBesideFreshChat(t, undefined, "/name Early"); assert.equal(h.newChatTabs().length, 2, "the kept chat has a tab of its own"); assert.equal(h.chatView(h.draftGroup), h.sending, "on its mount"); + world.sessions.set("created", { leafId: null, messages: [], entryIds: [] }); + await act(async () => { h.release(); await sleep(400); }); + assert.equal([...h.view.container.querySelectorAll("textarea")].some((area) => area.value.includes("/name Early")), false, "the command, once run, is cleared from the draft it moved to"); h.view.unmount(); }); @@ -6220,6 +6223,21 @@ test("a failed kept chat replaced by another new chat leaves its text to the wor h.view.unmount(); }); +test("a kept chat whose retry fails too gets its prompt back in its own composer", async (t) => { + let releaseRetry; + const h = await sentBesideFreshChat(t, { status: 500, value: { error: "spawn failed" } }); + await act(async () => { h.release(); await sleep(300); }); + world.holds.push({ match: (method, url) => method === "POST" && url === "/api/agent/new", produce: () => new Promise((resolve) => { releaseRetry = () => resolve({ status: 500, value: { error: "spawn failed again" } }); }) }); + const kept = h.composerIn(h.draftGroup); + await act(async () => { fireEvent.keyDown(kept, { key: "Enter" }); await sleep(60); }); + await until(() => releaseRetry, "the retry is sent"); + await act(async () => { releaseRetry(); await sleep(300); }); + assert.equal(h.composerIn(h.draftGroup).value, "hello there", "back where it was sent from"); + assert.equal(h.composerIn(h.other).value, "", "not in the fresh new chat"); + await act(async () => { fireEvent.change(h.composerIn(h.draftGroup), { target: { value: "" } }); await sleep(30); }); + h.view.unmount(); +}); + test("another new chat replaces an unsent kept one and opens fresh in the focused group", async (t) => { const h = await draftInItsOwnGroup(t); await act(async () => { fireEvent.change(h.draftComposer, { target: { value: "unsent idea" } }); await sleep(60); }); diff --git a/lib/draft-store.test.mjs b/lib/draft-store.test.mjs index 5225db5c..cd965eab 100644 --- a/lib/draft-store.test.mjs +++ b/lib/draft-store.test.mjs @@ -1,7 +1,7 @@ import assert from "node:assert/strict"; import { spawnSync } from "node:child_process"; import test from "node:test"; -import { clearDraft, consumeDraft, foldSentDraft, holdDraftOwner, isSentDraftKey, sentDraftKey, getDraft, getDraftRevision, getDraftSummary, markDraftEdited, mergeRecoveredText, recoverDraft, setDraft, subscribeDraftConsumption, subscribeDraftRecovery } from "./draft-store.ts"; +import { beginDraftSubmission, endDraftSubmission, moveDraftSubmissions, clearDraft, consumeDraft, foldSentDraft, holdDraftOwner, isSentDraftKey, sentDraftKey, getDraft, getDraftRevision, getDraftSummary, markDraftEdited, mergeRecoveredText, recoverDraft, setDraft, subscribeDraftConsumption, subscribeDraftRecovery } from "./draft-store.ts"; test("outbox consumption notifies matching drafts without clearing newer text, equal-text retypes or attachment payloads", () => { const key = "outbox-consumption"; @@ -361,3 +361,13 @@ test("a reload folds a chat's own drafts into their workspaces' drafts", () => { assert.equal(result.draft.promptOnly, true, "a prompt-only draft stays one"); assert.deepEqual(result.keys, ["tau-draft-new:/w", "tau-prompt-draft-new:/w"]); }); + +test("a submission in flight moves with its chat's draft, and others stay", () => { + const moving = beginDraftSubmission("new:/w"); + const other = beginDraftSubmission("new:/other"); + moveDraftSubmissions("new:/w", "sent:chat0000000a:new:/w"); + assert.equal(moving.key, "sent:chat0000000a:new:/w"); + assert.equal(other.key, "new:/other"); + endDraftSubmission(moving); + endDraftSubmission(other); +}); diff --git a/lib/draft-store.ts b/lib/draft-store.ts index e91695ae..e0613a57 100644 --- a/lib/draft-store.ts +++ b/lib/draft-store.ts @@ -167,6 +167,11 @@ export function endDraftSubmission(submission: DraftSubmission): void { submissions.delete(submission); } +/** Submissions in flight from `from` settle against `to` (the same chat's draft moved there). */ +export function moveDraftSubmissions(from: string, to: string): void { + for (const submission of submissions) if (submission.key === from) submission.key = to; +} + function markSubmissionsEdited(key: string): void { for (const submission of submissions) if (submission.key === key) submission.edited = true; } From d2ee7145236c2e0e88bd67beb3cdb7f7ea7f1b11 Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Fri, 27 Nov 2026 07:53:18 +0000 Subject: [PATCH 11/13] fix(chat): move only this composer's command in flight with its draft, at the moved draft's revision --- components/ChatInput.tsx | 15 +++++++++++---- hooks/useAgentSession.rpc.test.mjs | 2 ++ lib/draft-store.test.mjs | 14 ++++++++------ lib/draft-store.ts | 8 +++++--- 4 files changed, 26 insertions(+), 13 deletions(-) diff --git a/components/ChatInput.tsx b/components/ChatInput.tsx index 0fce11fb..b24f1788 100644 --- a/components/ChatInput.tsx +++ b/components/ChatInput.tsx @@ -15,7 +15,7 @@ import type { SttAfter } from "@/lib/stt"; import { formatCompactNumber, formatPercent } from "@/lib/format"; import { ContextDetailPanel } from "./ComposerPanels"; import { RecordingDeck } from "./RecordingDeck"; -import { beginDraftSubmission, clearDraft, consumeDraft, endDraftSubmission, moveDraftSubmissions, getDraft, getDraftRevision, foldSentDraft, holdDraftOwner, isSameDraft, isSentDraftKey, markDraftEdited, mergeRecoveredText, recoverDraft, requiresPromptMode, setDraft, subscribeDraftConsumption, subscribeDraftRecovery, type ChatDraft } from "@/lib/draft-store"; +import { beginDraftSubmission, clearDraft, consumeDraft, endDraftSubmission, moveDraftSubmission, getDraft, type DraftSubmission, getDraftRevision, foldSentDraft, holdDraftOwner, isSameDraft, isSentDraftKey, markDraftEdited, mergeRecoveredText, recoverDraft, requiresPromptMode, setDraft, subscribeDraftConsumption, subscribeDraftRecovery, type ChatDraft } from "@/lib/draft-store"; import { expandWebSlashCommand } from "@/lib/web-slash-commands"; import { WorkspaceFileContext } from "@/lib/workspace-file-context"; import type { AttachedImage, AttachedTextFile } from "./ChatInput-draft-attachments"; @@ -463,6 +463,8 @@ export const ChatInput = memo(forwardRef(function ChatIn }, [markInputEdited]); // Navigation starts a new identity, even when a draft key is later reused. const draftRecoveryIdentityRef = useRef({ key: draftKey }); + // This composer's submissions in flight (clearOnceStored), which move with its draft. + const ownSubmissionsRef = useRef(new Set()); // Async dictation and slash-command completions must see the latest edit gate. const submissionBlockedRef = useRef(submissionBlocked); const valueRef = useRef(value); @@ -935,8 +937,10 @@ export const ChatInput = memo(forwardRef(function ChatIn // Dictation can submit before the layout persistence effect sees its inserted text. if (key) setDraft(key, captureDraft()); const pending = beginDraftSubmission(draftKeyRef.current); + ownSubmissionsRef.current.add(pending); const commit = () => { endDraftSubmission(pending); + ownSubmissionsRef.current.delete(pending); // Only the sent draft itself is ever consumed: an edit since it was sent keeps it. if (pending.edited) return; if (composerAliveRef.current && draftKeyRef.current === pending.key @@ -946,7 +950,10 @@ export const ChatInput = memo(forwardRef(function ChatIn else if (pending.key && pending.snapshot) consumeDraft(pending.key, pending.snapshot, pending.revision); }; /** The submission settled without a commit (refused or failed): stop tracking it. */ - commit.release = () => endDraftSubmission(pending); + commit.release = () => { + endDraftSubmission(pending); + ownSubmissionsRef.current.delete(pending); + }; return commit; }, [clearInput, captureDraft]); @@ -971,8 +978,8 @@ export const ChatInput = memo(forwardRef(function ChatIn draftRecoveryIdentityRef.current = { key: draftKey }; setDraft(draftKey, captureDraft()); clearDraft(previousDraftKey); - // A command in flight (`/name` sends before it clears) clears the moved draft once it is stored. - moveDraftSubmissions(previousDraftKey, draftKey); + // This composer's command in flight (`/name` sends before it clears) clears the moved draft once it is stored. + for (const submission of ownSubmissionsRef.current) if (submission.key === previousDraftKey) moveDraftSubmission(submission, draftKey); return; } // Leaving the chat's own key: what it holds goes to its session's draft when the session takes over, else back to diff --git a/hooks/useAgentSession.rpc.test.mjs b/hooks/useAgentSession.rpc.test.mjs index aebd2ef5..186d1b3d 100644 --- a/hooks/useAgentSession.rpc.test.mjs +++ b/hooks/useAgentSession.rpc.test.mjs @@ -6111,6 +6111,8 @@ test("a kept chat that sent a builtin command creating its session keeps a tab o world.sessions.set("created", { leafId: null, messages: [], entryIds: [] }); await act(async () => { h.release(); await sleep(400); }); assert.equal([...h.view.container.querySelectorAll("textarea")].some((area) => area.value.includes("/name Early")), false, "the command, once run, is cleared from the draft it moved to"); + const stored = Object.keys(window.sessionStorage).filter((key) => window.sessionStorage.getItem(key)?.includes("/name Early")); + assert.deepEqual(stored, [], "and from storage, where a reload would bring it back"); h.view.unmount(); }); diff --git a/lib/draft-store.test.mjs b/lib/draft-store.test.mjs index cd965eab..68697316 100644 --- a/lib/draft-store.test.mjs +++ b/lib/draft-store.test.mjs @@ -1,7 +1,7 @@ import assert from "node:assert/strict"; import { spawnSync } from "node:child_process"; import test from "node:test"; -import { beginDraftSubmission, endDraftSubmission, moveDraftSubmissions, clearDraft, consumeDraft, foldSentDraft, holdDraftOwner, isSentDraftKey, sentDraftKey, getDraft, getDraftRevision, getDraftSummary, markDraftEdited, mergeRecoveredText, recoverDraft, setDraft, subscribeDraftConsumption, subscribeDraftRecovery } from "./draft-store.ts"; +import { beginDraftSubmission, endDraftSubmission, moveDraftSubmission, clearDraft, consumeDraft, foldSentDraft, holdDraftOwner, isSentDraftKey, sentDraftKey, getDraft, getDraftRevision, getDraftSummary, markDraftEdited, mergeRecoveredText, recoverDraft, setDraft, subscribeDraftConsumption, subscribeDraftRecovery } from "./draft-store.ts"; test("outbox consumption notifies matching drafts without clearing newer text, equal-text retypes or attachment payloads", () => { const key = "outbox-consumption"; @@ -362,12 +362,14 @@ test("a reload folds a chat's own drafts into their workspaces' drafts", () => { assert.deepEqual(result.keys, ["tau-draft-new:/w", "tau-prompt-draft-new:/w"]); }); -test("a submission in flight moves with its chat's draft, and others stay", () => { +test("a submission in flight moves with its chat's draft and still consumes it there", () => { + setDraft("new:/w", { value: "/name X", images: [], files: [] }); const moving = beginDraftSubmission("new:/w"); - const other = beginDraftSubmission("new:/other"); - moveDraftSubmissions("new:/w", "sent:chat0000000a:new:/w"); + setDraft("sent:chat0000000a:new:/w", getDraft("new:/w")); + clearDraft("new:/w"); + moveDraftSubmission(moving, "sent:chat0000000a:new:/w"); assert.equal(moving.key, "sent:chat0000000a:new:/w"); - assert.equal(other.key, "new:/other"); + consumeDraft(moving.key, moving.snapshot, moving.revision); + assert.equal(getDraft("sent:chat0000000a:new:/w"), null, "the command that ran is not left in the moved draft"); endDraftSubmission(moving); - endDraftSubmission(other); }); diff --git a/lib/draft-store.ts b/lib/draft-store.ts index e0613a57..208c91fb 100644 --- a/lib/draft-store.ts +++ b/lib/draft-store.ts @@ -167,9 +167,11 @@ export function endDraftSubmission(submission: DraftSubmission): void { submissions.delete(submission); } -/** Submissions in flight from `from` settle against `to` (the same chat's draft moved there). */ -export function moveDraftSubmissions(from: string, to: string): void { - for (const submission of submissions) if (submission.key === from) submission.key = to; +/** A submission in flight settles against `to`, where its chat's draft just moved unchanged: it takes `to`'s + * revision, so its commit still consumes the draft it sent unless that is edited later. */ +export function moveDraftSubmission(submission: DraftSubmission, to: string): void { + submission.key = to; + submission.revision = getDraftRevision(to); } function markSubmissionsEdited(key: string): void { From b010d05af2cfbb0a800603937622b8a9750256eb Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Fri, 27 Nov 2026 07:53:54 +0000 Subject: [PATCH 12/13] test(drafts): import the store by URL in the reload child, as the other child tests do --- lib/draft-store.test.mjs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/draft-store.test.mjs b/lib/draft-store.test.mjs index 68697316..adc323af 100644 --- a/lib/draft-store.test.mjs +++ b/lib/draft-store.test.mjs @@ -350,10 +350,10 @@ test("a reload folds a chat's own drafts into their workspaces' drafts", () => { const script = ` const stored = new Map([["tau-draft-new:/w", "kept"], ["tau-draft-sent:chat0000000a:new:/w", "own text"], ["tau-prompt-draft-sent:chat0000000a:new:/w", "1"]]); globalThis.sessionStorage = { get length() { return stored.size; }, key: (i) => [...stored.keys()][i] ?? null, getItem: (k) => stored.get(k) ?? null, setItem: (k, v) => { stored.set(k, String(v)); }, removeItem: (k) => { stored.delete(k); } }; - const { getDraft } = await import("./lib/draft-store.ts"); + const { getDraft } = await import(${JSON.stringify(new URL("./draft-store.ts", import.meta.url).href)}); console.log(JSON.stringify({ draft: getDraft("new:/w"), own: getDraft("sent:chat0000000a:new:/w"), keys: [...stored.keys()].sort() })); `; - const run = spawnSync(process.execPath, ["-e", script], { cwd: new URL("..", import.meta.url).pathname, encoding: "utf8" }); + const run = spawnSync(process.execPath, ["-e", script], { encoding: "utf8" }); assert.equal(run.status, 0, run.stderr); const result = JSON.parse(run.stdout.trim().split("\n").at(-1)); assert.equal(result.own, null); From f1337e531a593696d72fe25fcddd32de4897c012 Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Fri, 27 Nov 2026 08:08:16 +0000 Subject: [PATCH 13/13] fix(chat): a moved composer's command clear leaves the workspace's draft alone --- components/ChatInput.tsx | 5 ++++- hooks/useAgentSession.rpc.test.mjs | 3 +++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/components/ChatInput.tsx b/components/ChatInput.tsx index b24f1788..eb72a131 100644 --- a/components/ChatInput.tsx +++ b/components/ChatInput.tsx @@ -913,7 +913,10 @@ export const ChatInput = memo(forwardRef(function ChatIn setAtQuery(null); setSlashMatch(null); setHistoryMenuOpen(false); - if (draftKey) clearDraft(draftKey); + // A composer that moved to its own sent key since (a command clearing once stored) left the workspace's key to the + // next new chat: it never clears that one. + const movedToOwn = draftKeyRef.current !== draftKey && draftKeyRef.current !== undefined && isSentDraftKey(draftKeyRef.current); + if (draftKey && !movedToOwn) clearDraft(draftKey); if (draftKeyRef.current && draftKeyRef.current !== draftKey) clearDraft(draftKeyRef.current); clearImages(); clearTextFiles(); diff --git a/hooks/useAgentSession.rpc.test.mjs b/hooks/useAgentSession.rpc.test.mjs index 186d1b3d..140a648d 100644 --- a/hooks/useAgentSession.rpc.test.mjs +++ b/hooks/useAgentSession.rpc.test.mjs @@ -6109,10 +6109,13 @@ test("a kept chat that sent a builtin command creating its session keeps a tab o assert.equal(h.newChatTabs().length, 2, "the kept chat has a tab of its own"); assert.equal(h.chatView(h.draftGroup), h.sending, "on its mount"); world.sessions.set("created", { leafId: null, messages: [], entryIds: [] }); + await act(async () => { fireEvent.change(h.composerIn(h.other), { target: { value: "fresh idea" } }); await sleep(60); }); await act(async () => { h.release(); await sleep(400); }); assert.equal([...h.view.container.querySelectorAll("textarea")].some((area) => area.value.includes("/name Early")), false, "the command, once run, is cleared from the draft it moved to"); const stored = Object.keys(window.sessionStorage).filter((key) => window.sessionStorage.getItem(key)?.includes("/name Early")); assert.deepEqual(stored, [], "and from storage, where a reload would bring it back"); + assert.equal(window.sessionStorage.getItem("tau-draft-new:pool:workers:app"), "fresh idea", "the fresh new chat's stored draft is not cleared with it"); + await act(async () => { fireEvent.change(h.composerIn(h.other), { target: { value: "" } }); await sleep(30); }); h.view.unmount(); });