diff --git a/AGENTS.md b/AGENTS.md index e2be2024..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); 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), 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 ca08ee83..eb72a131 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, isSameDraft, 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"; @@ -181,6 +181,12 @@ interface Props { onBuiltinCommand?: (message: string) => Promise; onAudioUnlock?: () => void; draftKey?: string; + /** 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. */ @@ -302,6 +308,8 @@ export const ChatInput = memo(forwardRef(function ChatIn generationSpeed, onClearQueuedMessages, draftKey = "new:unassigned", + draftOwner, + draftKeyContinues, uploadHostId = LOCAL_HOST_ID, resolveUploadHost, cwd, @@ -455,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); @@ -903,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(); @@ -927,8 +940,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 @@ -938,7 +953,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]); @@ -956,6 +974,21 @@ 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); + // 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 + // 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:") && !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 @@ -966,9 +999,9 @@ export const ChatInput = memo(forwardRef(function ChatIn setAttachNotice(null); setQueuedDeleteTarget(null); - if (previousDraftKey) { - setDraft(previousDraftKey, captureDraft()); - } + if (previousDraftKey) setDraft(previousDraftKey, captureDraft()); + if (carried) clearDraft(previousDraftKey!); + else if (leavingOwn) foldSentDraft(previousDraftKey!); const draft = draftKey ? getDraft(draftKey) : null; draftKeyRef.current = draftKey; @@ -990,7 +1023,10 @@ 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]); useLayoutEffect(() => subscribeDraftRecovery((key, recovery) => { if (draftKeyRef.current !== key) return; @@ -1152,13 +1188,14 @@ 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); + // 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); + if (key) recoverDraft(key, recovery, draftOwner); throw error; } - }, [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, @@ -1179,7 +1216,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 59d92acc..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 } 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"; @@ -433,6 +433,29 @@ 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. + // 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 [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(() => { + 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, @@ -460,7 +483,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, }); @@ -554,7 +577,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 draftKey = session?.id ?? (newSessionPoolId && newSessionProjectId ? `new:pool:${newSessionPoolId}:${newSessionProjectId}` : newSessionCwd ? newChatDraftKey(newSessionCwd, newSessionHostId) : undefined); const sessionKeyForPaging = draftKey ?? "empty"; useEffect(() => { if (prevSessionKeyForPagingRef.current !== sessionKeyForPaging) { @@ -967,6 +989,8 @@ export function ChatWindow({ session, newSessionCwd, newSessionHostId, newSessio onBuiltinCommand={handleBuiltinSlashCommand} 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 a67b1a51..140a648d 100644 --- a/hooks/useAgentSession.rpc.test.mjs +++ b/hooks/useAgentSession.rpc.test.mjs @@ -6108,6 +6108,14 @@ 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 () => { 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(); }); @@ -6124,6 +6132,117 @@ 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("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("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("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("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 72ece312..adc323af 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, 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"; @@ -312,3 +312,64 @@ 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 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, "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); + 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(); + 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"); + 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); + 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-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(${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], { 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"]); +}); + +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"); + 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"); + 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); +}); diff --git a/lib/draft-store.ts b/lib/draft-store.ts index 02605825..208c91fb 100644 --- a/lib/draft-store.ts +++ b/lib/draft-store.ts @@ -53,6 +53,8 @@ export function mergeRecoveredText(current: string, { text, replace }: DraftReco 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; @@ -165,6 +167,13 @@ export function endDraftSubmission(submission: DraftSubmission): void { submissions.delete(submission); } +/** 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 { for (const submission of submissions) if (submission.key === key) submission.edited = true; } @@ -225,8 +234,52 @@ 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); + }; +} + +// 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 `${SENT_KEY_PREFIX}${chat}:${base}`; +} + +export function isSentDraftKey(key: string): boolean { + 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 + * 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(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 + * 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 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 && 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) { const draft = getDraft(key) ?? { value: "", images: [], files: [] }; setDraft(key, { @@ -296,3 +349,9 @@ 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 (once per page, not per hot reload). +if (!globalThis.__tauChatDraftsFolded) { + globalThis.__tauChatDraftsFolded = true; + for (const key of [...drafts.keys()]) if (isSentDraftKey(key)) foldSentDraft(key); +}