Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<PromptSubmissionResult>` (`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<PromptSubmissionResult>` (`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:<chat>:<workspace key>` (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
Expand Down
60 changes: 49 additions & 11 deletions components/ChatInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
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";
Expand Down Expand Up @@ -181,6 +181,12 @@
onBuiltinCommand?: (message: string) => Promise<BuiltinSlashCommandResult>;
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. */
Expand Down Expand Up @@ -302,6 +308,8 @@
generationSpeed,
onClearQueuedMessages,
draftKey = "new:unassigned",
draftOwner,
draftKeyContinues,
uploadHostId = LOCAL_HOST_ID,
resolveUploadHost,
cwd,
Expand Down Expand Up @@ -455,6 +463,8 @@
}, [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<DraftSubmission>());
// Async dictation and slash-command completions must see the latest edit gate.
const submissionBlockedRef = useRef(submissionBlocked);
const valueRef = useRef(value);
Expand Down Expand Up @@ -903,7 +913,10 @@
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();
Expand All @@ -927,8 +940,10 @@
// 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
Expand All @@ -938,7 +953,10 @@
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]);

Expand All @@ -956,6 +974,21 @@
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);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
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
Expand All @@ -966,9 +999,9 @@
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;
Expand All @@ -990,7 +1023,10 @@
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;
Expand Down Expand Up @@ -1152,13 +1188,14 @@
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,
Expand All @@ -1179,7 +1216,8 @@
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
Expand Down Expand Up @@ -1927,7 +1965,7 @@
}
}
},
[isMobile, isStreaming, onSteer, onFollowUp, onAbort, onMinimize, slashMenuOpen, slashQuery, filteredSlashCommands, slashActiveIndex, applySlashCommand, sendQueued, handleSend, getNextSlashIndex, atMenuOpen, atQuery, atMatches, atActiveIndex, applyAtCompletion, historyMenuOpen, inputHistory, historyActiveIndex, applyHistoryInput, value, toggleDictation, setValue]

Check warning on line 1968 in components/ChatInput.tsx

View workflow job for this annotation

GitHub Actions / Verify (ubuntu-latest)

React Hook useCallback has an unnecessary dependency: 'setValue'. Either exclude it or remove the dependency array

Check warning on line 1968 in components/ChatInput.tsx

View workflow job for this annotation

GitHub Actions / Verify (macos-latest)

React Hook useCallback has an unnecessary dependency: 'setValue'. Either exclude it or remove the dependency array

Check warning on line 1968 in components/ChatInput.tsx

View workflow job for this annotation

GitHub Actions / Verify (windows-latest)

React Hook useCallback has an unnecessary dependency: 'setValue'. Either exclude it or remove the dependency array
);

// The fullscreen editor submits like Enter in the composer: during a run it queues or steers.
Expand Down
30 changes: 27 additions & 3 deletions components/ChatWindow.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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<string | undefined>(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,
Expand Down Expand Up @@ -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,
});
Expand Down Expand Up @@ -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<string | null>(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) {
Expand Down Expand Up @@ -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}
Expand Down
Loading
Loading