A desktop coding agent with free access to frontier models.
TypeScript
fix: a typed or sent prompt is kept when the new chat composer is replaced
ogsamrat7abc42545031
diff --git a/apps/app/src/react-app/domains/session/chat/new-task-composer.tsx b/apps/app/src/react-app/domains/session/chat/new-task-composer.tsxindex ac8ec9bd..ef2fbe98 100644--- a/apps/app/src/react-app/domains/session/chat/new-task-composer.tsx+++ b/apps/app/src/react-app/domains/session/chat/new-task-composer.tsx@@ -17,9 +17,12 @@ import { SandboxStatusChip } from "@/react-app/domains/session/surface/composer/import { SandboxSetupPanel } from "@/react-app/domains/session/surface/sandbox-setup-panel";import { SubagentModelMenu } from "@/react-app/domains/session/surface/composer/subagent-model-menu";import {+ persistableComposerDraftText,snapshotComposerSessionState,type ComposerSessionState,} from "@/react-app/domains/session/surface/composer-state-store";+import { clearSessionDraft, getSessionDraft, saveSessionDraft } from "@/react-app/domains/session/sync/draft-store";+import { toast } from "@/components/ui/sonner";import { encodeComposerMentionValue, type ComposerMentionKind } from "@/react-app/domains/session/surface/composer/mention-encoding";import {createPastedTextChip,@@ -46,6 +49,8 @@ export type NewTaskComposerContext = {workspaceId: string | null;/** Stable identity for draft ownership across workspace, endpoint, and account changes. */draftOwnerKey?: string;+ /** The draft store scope (draft-store.ts): the typed draft is kept there per project, so a remount does not lose it. */+ draftScope?: string | null;selectedModel: ModelRef;modelOptions?: readonly ModelOption[];modelUnavailable?: boolean;@@ -114,6 +119,8 @@ const emptyAgents = async (): Promise<Agent[]> => [];const emptyCommands = async (): Promise<SlashCommandOption[]> => [];const emptyFiles = async (): Promise<string[]> => [];const FALLBACK_MODEL: ModelRef = DEFAULT_MODEL;+/** The new-task draft is stored like a chat's, under this stand-in chat id. */+export const NEW_TASK_DRAFT_SESSION_ID = "new-task";/*** The real session composer, reused for the "What do you need done?" empty@@ -165,16 +172,34 @@ export function NewTaskComposer(props: NewTaskComposerProps) {const pluginConnectPushRef = useRef(0);const workspaceClient = context?.client ?? null;const workspaceId = context?.workspaceId ?? null;+ const draftScope = context?.draftScope ?? null;+ const draftRestoredRef = useRef(false);++ // Declared before the owner effect below, so a new owner's first pass never stores the previous owner's text.+ useEffect(() => {+ if (!draftRestoredRef.current || mountedDraftOwnerKeyRef.current !== draftOwnerKey || !workspaceId) return;+ // A send on its way keeps its text stored until its chat exists.+ if (submittingRef.current && !props.draft) return;+ saveSessionDraft(draftScope, workspaceId, NEW_TASK_DRAFT_SESSION_ID, { text: persistableComposerDraftText(props.draft, pastedText), mode: "prompt" });+ }, [draftOwnerKey, draftScope, pastedText, props.draft, workspaceId]);useEffect(() => {const holder = continuationHolderRef.current;holder.frozen = false;+ const stored = workspaceId ? getSessionDraft(draftScope, workspaceId, NEW_TASK_DRAFT_SESSION_ID)?.text ?? "" : "";+ draftRestoredRef.current = true;+ if (mountedDraftOwnerKeyRef.current === draftOwnerKey && !props.draft && stored) {+ // Remounted (a card above it, a restart moving the endpoint): the typed draft comes back.+ holder.state = { ...holder.state, draft: stored };+ draftRef.current = stored;+ props.onDraftChange(stored);+ }if (mountedDraftOwnerKeyRef.current !== draftOwnerKey) {mountedDraftOwnerKeyRef.current = draftOwnerKey;- holder.state = emptyNewTaskComposerState();- draftRef.current = "";+ holder.state = { ...emptyNewTaskComposerState(), draft: stored };+ draftRef.current = stored;submittingRef.current = false;- props.onDraftChange("");+ props.onDraftChange(stored);setAttachments([]);setMentions({});setPastedText([]);@@ -381,6 +406,8 @@ export function NewTaskComposer(props: NewTaskComposerProps) {const revision = draftRevisionRef.current;const submitted = snapshotComposerSessionState({ ...submissionHolder.state, draft: originalDraft });const resolved = resolvePastedTextPlaceholders(originalDraft, submitted.pasteParts);+ const submittedDraftScope = draftScope;+ const submittedWorkspaceId = workspaceId;if (!submitted.attachments.length) setPendingPrompt(resolved.replace(/\[attachment [^\]]+\]/g, ""));setPreparingAttachments(submitted.attachments.length > 0);setSubmissionError(null);@@ -399,8 +426,13 @@ export function NewTaskComposer(props: NewTaskComposerProps) {submitted,getContinuation: () => snapshotComposerSessionState(submissionHolder.state),});+ if (submittedWorkspaceId) clearSessionDraft(submittedDraftScope, submittedWorkspaceId, NEW_TASK_DRAFT_SESSION_ID);} catch (error) {- if (continuationHolderRef.current !== submissionHolder || submissionHolder.frozen) return;+ if (continuationHolderRef.current !== submissionHolder || submissionHolder.frozen) {+ // This composer was replaced meanwhile: its text stays stored for the project, say why it was not sent.+ toast.error(error instanceof Error ? error.message : "Could not create the conversation. Try again.");+ return;+ }if (!submitted.attachments.length) {if (draftRevisionRef.current === revision && !draftRef.current) {restoreComposer(submitted);diff --git a/apps/app/tests/new-task-draft-remount.test.tsx b/apps/app/tests/new-task-draft-remount.test.tsxnew file mode 100644index 00000000..b173d5ec--- /dev/null+++ b/apps/app/tests/new-task-draft-remount.test.tsx@@ -0,0 +1,123 @@+/** @jsxImportSource react */+import { expect, mock, test } from "bun:test";+import { GlobalRegistrator } from "@happy-dom/global-registrator";+import { createRequire } from "node:module";+import { act, useState } from "react";+import { createRoot, type Root } from "react-dom/client";++import type { NewTaskComposerContext } from "../src/react-app/domains/session/chat/new-task-composer";++function context(workspaceId: string): NewTaskComposerContext {+ return {+ client: null,+ workspaceId,+ draftOwnerKey: `owner:${workspaceId}`,+ draftScope: "local",+ selectedModel: { providerID: "test", modelID: "test-model" },+ modelPickerOpen: false,+ onModelPickerOpenChange: () => {},+ onModelChange: () => {},+ modelVariantLabel: "Default",+ modelVariant: null,+ onModelVariantChange: () => {},+ agentLabel: "OmniRush.ai",+ selectedAgent: null,+ listAgents: async () => [],+ onSelectAgent: () => {},+ listCommands: async () => [],+ searchFiles: async () => [],+ isRemoteWorkspace: false,+ isSandboxWorkspace: false,+ };+}++test("the new-task draft survives a remount of the composer and a send that fails after it", async () => {+ const require = createRequire(import.meta.url);+ // Bun's isolated test loader cycles Lexical's ESM entries; use their real CJS entries (composer-focus-continuity.test.tsx).+ for (const moduleId of [+ "lexical",+ "@lexical/react/LexicalComposer.js",+ "@lexical/react/LexicalPlainTextPlugin.js",+ "@lexical/react/LexicalContentEditable.js",+ "@lexical/react/LexicalErrorBoundary.js",+ "@lexical/react/LexicalOnChangePlugin.js",+ "@lexical/react/LexicalHistoryPlugin.js",+ "@lexical/react/LexicalComposerContext.js",+ ]) {+ const moduleExports = require(moduleId);+ mock.module(moduleId, () => moduleExports);+ }+ const registeredDom = typeof globalThis.window === "undefined" || typeof globalThis.document === "undefined";+ if (registeredDom) GlobalRegistrator.register({ url: "http://localhost/" });+ Object.defineProperty(globalThis, "IS_REACT_ACT_ENVIRONMENT", { configurable: true, value: true });+ mock.module("@/components/model-select", () => ({ ModelSelect: () => null }));+ mock.module("@/react-app/domains/session/surface/composer/workspace-run-mode-menu", () => ({ WorkspaceRunModeMenu: () => null }));+ mock.module("@/react-app/domains/session/surface/composer/full-permissions-toggle", () => ({ FullPermissionsToggle: () => null }));+ mock.module("@/react-app/domains/session/surface/composer/subagent-model-menu", () => ({ SubagentModelMenu: () => null }));+ window.localStorage.clear();+ const [{ LocalProvider }, { ShellConfigProvider }, { NewTaskComposer }] = await Promise.all([+ import("../src/react-app/kernel/local-provider"),+ import("../src/react-app/shell/shell-config"),+ import("../src/react-app/domains/session/chat/new-task-composer"),+ ]);++ let creation = Promise.withResolvers<void>();+ let typeDraft = (_text: string) => {};+ let openWorkspace = (_id: string) => {};+ function Hero() {+ // Like SessionEmptyHero: the draft is plain component state, gone when it remounts.+ const [text, setText] = useState("");+ const [workspaceId, setWorkspaceId] = useState("ws-b");+ typeDraft = setText;+ openWorkspace = setWorkspaceId;+ return <NewTaskComposer draft={text} onDraftChange={setText} busy={false} context={context(workspaceId)} onRunTask={() => creation.promise} />;+ }+ const container = document.createElement("div");+ document.body.append(container);+ let root: Root = createRoot(container);+ const editorText = () => container.querySelector('[data-lexical-editor="true"]')?.textContent ?? null;+ const remount = async () => {+ await act(async () => root.unmount());+ root = createRoot(container);+ await act(async () => root.render(<LocalProvider><ShellConfigProvider><Hero /></ShellConfigProvider></LocalProvider>));+ };+ try {+ await act(async () => root.render(<LocalProvider><ShellConfigProvider><Hero /></ShellConfigProvider></LocalProvider>));+ await act(async () => typeDraft("Half typed prompt"));+ // The sandbox card (or a restart) swaps the tree the composer sits in.+ await remount();+ expect(editorText()).toBe("Half typed prompt");++ // Another project starts empty and does not take this draft; coming back brings it again.+ await act(async () => openWorkspace("ws-c"));+ expect(editorText()).toBe("");+ await act(async () => openWorkspace("ws-b"));+ expect(editorText()).toBe("Half typed prompt");++ // Sent, the composer is replaced while the chat is being created, and the creation fails: the prompt is not lost.+ await act(async () => {+ const button = container.querySelector<HTMLButtonElement>('button[aria-label="Run task"]');+ if (!button || button.disabled) throw new Error(`Expected an enabled send button: ${container.textContent}`);+ button.click();+ });+ expect(editorText()).toBe("");+ await remount();+ await act(async () => creation.reject(new Error("engine restarting")));+ expect(editorText()).toBe("Half typed prompt");++ // A send that creates its chat clears the stored draft.+ creation = Promise.withResolvers<void>();+ await act(async () => {+ container.querySelector<HTMLButtonElement>('button[aria-label="Run task"]')?.click();+ });+ await act(async () => creation.resolve());+ await remount();+ expect(editorText()).toBe("");+ } finally {+ await act(async () => root.unmount());+ container.remove();+ window.localStorage.clear();+ mock.restore();+ if (registeredDom) await GlobalRegistrator.unregister();+ }+});