Start an edited New workspace after a failed creation, and unify composer errors (#10482)

* fix(app): allow edited New workspace retries and unify composer errors

New workspace and the workspace setup dialog reused the mount's raw draft
or creation ID as the workspace.create idempotencyKey. When workspace
provisioning failed before readiness, the daemon kept that key's request
fingerprint on disk, so editing isolation, project, branch, prompt, or
model on the same screen failed with workspace_request_key_conflict.

Deriving the workspace idempotencyKey with draftCreationKey(id, request)
matches #9534 for agent drafts: unchanged retries (double-click,
reconnect, or resending as-is) keep one key, while edited retries start a
new workspace creation without requiring daemon or protocol changes.

Also move composer submission errors into one <Alert variant="error"
size="sm" /> slot owned by <Composer> (directly above the input, and in
ComposerFullscreenFooter when fullscreen) so New workspace, Workspace
draft tab, Workspace setup dialog, and active chat share the composer's
outer and inner rails without duplicate error toasts.

* fix(app): include launch target in creation key and toast background failures

Include launchTarget when deriving the New workspace creation key so
switching between blank Chat and a promptless terminal profile after a
pre-ready failure starts a fresh creation instead of replaying the failed
receipt.

Also show toast.error when workspace creation fails after the user has
left New workspace or closed WorkspaceSetupDialog, while keeping the
single composer alert with no duplicate toast when the form is still
visible.

* fix(app): avoid duplicate toast when handed-off agent startup fails

Once New workspace hands a ready workspace to its draft tab, the draft
tab awaits agentCreation.result and displays startup errors in its own
composer alert. Returning early after handoff prevents New workspace's
catch handler from firing a duplicate app-wide toast.
This commit is contained in:
Mohamed Boudra
2026-11-22 12:28:10 +07:00
committed by GitHub
parent 03adc4d4ba
commit 9cb0625cf5
7 changed files with 289 additions and 65 deletions
@@ -1,4 +1,21 @@
import { execFileSync } from "node:child_process";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import type { createCreationScenario } from "../support/helpers/creation";
import { gotoAppShell } from "../support/helpers/app";
import { fillComposerDraft } from "../support/helpers/composer";
import {
connectNewWorkspaceDaemonClient,
openNewWorkspaceComposer,
selectWorkspaceIsolation,
} from "../support/helpers/new-workspace";
import {
seedTerminalProfiles,
selectLaunchOption,
submitTerminalLaunch,
} from "../support/helpers/new-workspace-launch";
import { waitForSidebarHydration } from "../support/helpers/workspace-ui";
import { expect } from "../support/fixtures";
import { test } from "../support/creation-fixtures";
@@ -116,12 +133,14 @@ for (const scenario of [
test(`retrying failed agent initialization preserves its workspace${scenario.suffix}`, async ({
creation,
startup,
page,
}) => {
await creation.openWorkspaceForm("local");
await creation.submitPrompt("Retry this workspace and agent together.", "Create");
await creation.expectAgentStillStarting();
await startup.fail();
await creation.expectStartupFailure();
await expect(page.getByTestId("app-toast")).toHaveCount(0);
await creation.expectOneCreatedWorkspace();
await scenario.prepare(creation);
await creation.submitPrompt("Retry this workspace and agent together.");
@@ -180,6 +199,105 @@ test("an edited agent draft starts after its first start failed", async ({
await expect(page.getByText(/request_key_conflict/)).toHaveCount(0);
});
test("editing a failed New workspace submission starts without a request key conflict", async ({
page,
}) => {
// An empty git repository naturally rejects worktree creation before workspace_ready.
const repoDir = mkdtempSync(path.join(tmpdir(), "paseo-empty-git-ws-"));
execFileSync("git", ["init"], { cwd: repoDir, stdio: "ignore" });
const client = await connectNewWorkspaceDaemonClient();
let projectId: string | null = null;
try {
const seeded = await client.createWorkspace({
source: { kind: "directory", path: repoDir },
});
if (!seeded.workspace) throw new Error(seeded.error ?? "Failed to seed empty git project");
projectId = seeded.workspace.projectId;
const listed = await client.listProjects();
const project = listed.projects.find((entry) => entry.projectId === projectId);
if (!project?.projectKey) throw new Error("Seeded project has no projectKey");
await gotoAppShell(page);
await waitForSidebarHydration(page);
await openNewWorkspaceComposer(page, {
projectKey: project.projectKey,
projectDisplayName: seeded.workspace.projectDisplayName,
});
await selectWorkspaceIsolation(page, "worktree");
await fillComposerDraft(page, "Start original worktree task.");
await page.getByRole("button", { name: "Create", exact: true }).click();
const composerError = page.getByTestId("composer-error").filter({ visible: true }).first();
await expect(composerError).toContainText("Unable to resolve repository default branch");
// The failure renders once in the composer alert, not duplicated in a top toast.
await expect(page.getByText("Unable to resolve repository default branch")).toHaveCount(1);
await selectWorkspaceIsolation(page, "local");
await fillComposerDraft(page, "hi");
await page.getByRole("button", { name: "Create", exact: true }).click();
await expect(page).toHaveURL(/\/workspace\//);
await expect(page.getByText(/request_key_conflict/)).toHaveCount(0);
await expect(
page.getByTestId("user-message").filter({ hasText: "hi", visible: true }),
).toBeVisible();
} finally {
if (projectId) await client.removeProject(projectId).catch(() => undefined);
await client.close();
rmSync(repoDir, { recursive: true, force: true });
}
});
test("switching only the launch target after a failed New workspace creation starts a new workspace", async ({
creation,
workspaceProvision,
page,
}) => {
const profiles = await seedTerminalProfiles([
{
id: "promptless-shell",
name: "Promptless Shell",
command: "sh",
args: ["-c", "echo ready; sleep 5"],
promptArg: "none",
},
]);
try {
await creation.openWorkspaceForm("local");
await workspaceProvision.fail();
await page.getByRole("button", { name: "Create", exact: true }).click();
await expect(
page.getByTestId("composer-error").filter({ visible: true }).first(),
).toContainText("Workspace provisioning failed for test");
await selectLaunchOption(page, "promptless-shell");
await submitTerminalLaunch(page);
await creation.expectOneCreatedWorkspace();
await expect(
page.locator('[data-testid^="workspace-tab-terminal_"]').filter({ visible: true }).first(),
).toBeVisible();
} finally {
await profiles.restore();
}
});
test("failing New workspace creation after switching workspaces shows an error toast", async ({
creation,
workspaceProvision,
page,
}) => {
await creation.openWorkspaceForm("local");
await workspaceProvision.hold();
await page.getByRole("button", { name: "Create", exact: true }).click();
await page.locator('[data-testid^="sidebar-workspace-row-"]').first().click();
await expect(page).toHaveURL(/\/workspace\//);
await workspaceProvision.fail();
await expect(page.getByTestId("app-toast")).toContainText(
"Workspace provisioning failed for test",
);
});
for (const entry of [
{
name: "agent draft",
@@ -15,6 +15,11 @@ import { delayBrowserAgentCreatedStatus } from "./helpers/new-workspace";
export const test = base.extend<{
startup: { release(): Promise<void>; fail(): Promise<void> };
workspaceProvision: {
hold(): Promise<void>;
fail(): Promise<void>;
release(): Promise<void>;
};
promptRejection: void;
composerMetadata: { set(patch: Record<string, string>): Promise<void> };
creation: Awaited<ReturnType<typeof createCreationScenario>>;
@@ -70,6 +75,57 @@ export default function contribute(server) {
await client.close();
}
},
workspaceProvision: async ({ page }, provide) => {
void page;
const client = await connectNewWorkspaceDaemonClient();
const plugin = await copyPluginExample("lifecycle-logger");
const gate = path.join(plugin.directory, "workspace-provision.txt");
const holdFile = path.join(plugin.directory, "workspace-provision-hold.txt");
const failFile = path.join(plugin.directory, "workspace-provision-fail.txt");
const previous = await client.getDaemonConfig();
try {
await writeFile(
path.join(plugin.directory, "index.server.ts"),
`
import { readFile, rm } from "node:fs/promises";
export default function contribute(server) {
return server.before("workspace.create", async ({ request }) => {
const gate = ${JSON.stringify(gate)};
let command = await readFile(gate, "utf8").catch(() => "release");
while (command === "hold") {
await new Promise(resolve => setTimeout(resolve, 20));
command = await readFile(gate, "utf8").catch(() => "release");
}
if (command === "fail") {
await rm(gate, { force: true });
throw new Error("Workspace provisioning failed for test");
}
return request;
});
}
`,
);
await client.patchDaemonConfig({ pluginsEnabled: true });
await client.installDirectoryPlugin(plugin.directory);
await provide({
hold: async () => {
await writeFile(holdFile, "hold");
await rename(holdFile, gate);
},
fail: async () => {
await writeFile(failFile, "fail");
await rename(failFile, gate);
},
release: () => rm(gate, { force: true }),
});
} finally {
await rm(gate, { force: true });
await client.removePlugin("lifecycle-logger");
await client.patchDaemonConfig({ pluginsEnabled: previous.config.pluginsEnabled });
await plugin.cleanup();
await client.close();
}
},
promptRejection: async ({ page }, provide) => {
void page;
const client = await connectNewWorkspaceDaemonClient();
@@ -12,6 +12,7 @@ import { Composer } from "@/composer";
import { ProjectIconView } from "@/components/project-icon-view";
import { ICON_SIZE } from "@/styles/theme";
import { useToast } from "@/contexts/toast-context";
import { draftCreationKey } from "@/composer/draft/creation-key";
import { useAgentInputDraft } from "@/composer/draft/input-draft";
import { useProjectIcon } from "@/projects/icons";
import { useHostRuntimeClient, useHostRuntimeIsConnected } from "@/runtime/host-runtime";
@@ -96,13 +97,16 @@ async function callWorkspaceCreation({
worktreeSlug: string;
input: { cwd: string; agent?: CreateWorkspaceRequestOptions["agent"] };
}) {
return connectedClient.createWorkspace({
idempotencyKey: creationId,
const request: Omit<CreateWorkspaceRequestOptions, "idempotencyKey"> = {
agent: input.agent,
source:
creationMethod === "create_worktree"
? { kind: "worktree", cwd: input.cwd, worktreeSlug }
: { kind: "directory", path: input.cwd },
};
return connectedClient.createWorkspace({
...request,
idempotencyKey: draftCreationKey(creationId, request),
});
}
@@ -363,7 +367,9 @@ export function WorkspaceSetupDialog() {
} catch (error) {
const message = toErrorMessage(error);
setErrorMessage(message);
toast.error(message);
if (!getIsStillActive()) {
toast.error(message);
}
} finally {
if (getIsStillActive()) {
setPendingAction(null);
@@ -455,11 +461,10 @@ export function WorkspaceSetupDialog() {
commandDraft={composerState?.commandDraft}
agentControls={agentControlsWithDisabled}
inputWrapperStyle={styles.composerInputWrapper}
error={errorMessage}
/>
</KeyboardTranslateView>
</FileDropZone>
{errorMessage ? <Text style={styles.errorText}>{errorMessage}</Text> : null}
</AdaptiveModalSheet>
);
}
@@ -482,11 +487,6 @@ const styles = StyleSheet.create((theme) => ({
marginHorizontal: -theme.spacing[6],
marginVertical: -theme.spacing[2],
},
errorText: {
fontSize: theme.fontSize.base,
color: theme.colors.destructive,
lineHeight: 20,
},
composerSlot: {
paddingBottom: theme.spacing[4],
},
@@ -8,6 +8,21 @@ const request = {
clientMessageId: "draft-1:initial-message",
};
const workspaceRequest = {
source: {
kind: "worktree" as const,
cwd: "/repo",
projectId: "prj_1",
worktreeSlug: "clever-fox",
},
firstAgentContext: { prompt: "Start the original task.", attachments: [] },
agent: {
config: { provider: "codex", cwd: "/repo", model: "gpt-6" },
initialPrompt: "Start the original task.",
clientMessageId: "draft-1:initial-message",
},
};
describe("draftCreationKey", () => {
it("keeps the key for a retry of the same request, whatever its key order", () => {
const reordered = {
@@ -27,4 +42,52 @@ describe("draftCreationKey", () => {
expect(key).not.toBe(draftCreationKey("draft-1", request));
expect(key.startsWith("draft-1:")).toBe(true);
});
it.each([
{
name: "isolation",
edited: {
...workspaceRequest,
source: { kind: "directory" as const, path: "/repo", projectId: "prj_1" },
},
},
{
name: "project",
edited: {
...workspaceRequest,
source: { ...workspaceRequest.source, projectId: "prj_2", cwd: "/other" },
},
},
{
name: "prompt",
edited: {
...workspaceRequest,
firstAgentContext: { prompt: "hi", attachments: [] },
agent: { ...workspaceRequest.agent, initialPrompt: "hi" },
},
},
])(
"gives a New workspace request with edited $name a new key on the same draft",
({ edited }) => {
const key = draftCreationKey("draft-1", edited);
expect(key).not.toBe(draftCreationKey("draft-1", workspaceRequest));
expect(key.startsWith("draft-1:")).toBe(true);
},
);
it("gives a New workspace request with a changed launch target a new key even when the wire request matches", () => {
const emptyRequest = {
source: { kind: "directory" as const, path: "/repo", projectId: "prj_1" },
};
const chatKey = draftCreationKey("draft-1", {
request: emptyRequest,
launchTarget: { kind: "chat" },
});
const terminalKey = draftCreationKey("draft-1", {
request: emptyRequest,
launchTarget: { kind: "terminal", profileId: "shell" },
});
expect(terminalKey).not.toBe(chatKey);
expect(terminalKey.startsWith("draft-1:")).toBe(true);
});
});
@@ -1,7 +1,7 @@
import type { ComposerOptionControls } from "@/agent-controls/option-controls";
import { useCallback, useEffect, useMemo, useRef } from "react";
import type { JsonValue } from "@getpaseo/protocol/agent-types";
import { Keyboard, StyleSheet as RNStyleSheet, Text, View } from "react-native";
import { Keyboard, StyleSheet as RNStyleSheet, View } from "react-native";
import { useTranslation } from "react-i18next";
import { StyleSheet } from "react-native-unistyles";
import { CHAT_COLUMN_RAIL_DATASET } from "@/chat-rail";
@@ -536,16 +536,6 @@ export function WorkspaceDraftComposer({
);
return (
<View style={animatedStaticStyles.inputAreaWrapper} onLayout={onInputAreaLayout}>
{formErrorMessage ? (
<View
style={styles.formErrorRow}
dataSet={isComposerFullscreen ? undefined : CHAT_COLUMN_RAIL_DATASET}
>
<View style={styles.formError}>
<Text style={styles.errorText}>{formErrorMessage}</Text>
</View>
</View>
) : null}
{importPillPress && !isComposerFullscreen ? (
<View style={styles.importPillRow} dataSet={CHAT_COLUMN_RAIL_DATASET}>
<View style={styles.importPillContent}>
@@ -577,6 +567,7 @@ export function WorkspaceDraftComposer({
commandDraft={composerState.commandDraft}
agentControls={composerAgentControls}
isCompactLayout={isCompactComposerLayout}
error={formErrorMessage || null}
/>
</View>
);
@@ -592,11 +583,6 @@ const animatedStaticStyles = RNStyleSheet.create({
});
const styles = StyleSheet.create((theme) => ({
formErrorRow: {
width: "100%",
paddingHorizontal: theme.spacing[4],
alignItems: "center",
},
importPillRow: {
width: "100%",
paddingHorizontal: theme.spacing[4],
@@ -615,18 +601,4 @@ const styles = StyleSheet.create((theme) => ({
maxWidth: theme.contentMaxWidth,
flexDirection: "row",
},
formError: {
width: "100%",
maxWidth: theme.contentMaxWidth,
marginBottom: theme.spacing[2],
paddingHorizontal: theme.spacing[3],
paddingVertical: theme.spacing[2],
borderRadius: theme.borderRadius.md,
backgroundColor: theme.colors.surface2,
borderWidth: 1,
borderColor: theme.colors.destructive,
},
errorText: {
color: theme.colors.destructive,
},
}));
+8 -9
View File
@@ -8,6 +8,7 @@ import { createStore, type StoreApi } from "zustand/vanilla";
import { useStore } from "zustand";
import { getHostRuntimeStore } from "@/runtime/host-runtime";
import { LoadingSpinner } from "@/components/ui/loading-spinner";
import { Alert } from "@/components/ui/alert";
import {
View,
Pressable,
@@ -1016,6 +1017,8 @@ interface ComposerProps {
* `inputMode`.
*/
editingSession?: ComposerEditingSession;
/** Caller-owned submission error rendered in the composer's shared error slot. */
error?: string | null;
}
const EMPTY_ARRAY: readonly QueuedMessage[] = [];
@@ -1319,6 +1322,7 @@ function ComposerContentImpl({
isCompactLayout: isCompactLayoutOverride,
inputMode = "chat",
editingSession: providedEditingSession,
error: externalError,
readOnly = false,
submitLabel,
placeholder,
@@ -2544,14 +2548,13 @@ function ComposerContentImpl({
// Focusing the composer on a touch screen raises the on-screen keyboard over the conversation.
const messageInputAutoFocus = autoFocus && isDesktopWebBreakpoint && hasFinePointer;
const submitLoadingPressHandler = isAgentRunning ? handleCancelAgent : undefined;
const displayError = externalError || sendError;
const sendErrorNode = useMemo(
() =>
sendError ? (
<Text accessibilityRole="alert" style={styles.sendErrorText}>
{sendError}
</Text>
displayError ? (
<Alert variant="error" size="sm" description={displayError} testID="composer-error" />
) : null,
[sendError],
[displayError],
);
const githubEmptyText = githubSearchResultsQuery.isFetching
? t("composer.github.searching")
@@ -2837,10 +2840,6 @@ const styles = StyleSheet.create((theme: Theme) => ({
queueSendButton: {
backgroundColor: theme.colors.accent,
},
sendErrorText: {
color: theme.colors.palette.red[500],
fontSize: theme.fontSize.base,
},
})) as unknown as Record<string, object>;
const ThemedAttachmentSpinner = withUnistyles(LoadingSpinner);
@@ -24,6 +24,7 @@ import { TitlebarDragRegion } from "@/components/desktop/titlebar-drag-region";
import { MenuHeader } from "@/components/headers/menu-header";
import { useIsCompactFormFactor } from "@/constants/layout";
import { useToast } from "@/contexts/toast-context";
import { draftCreationKey } from "@/composer/draft/creation-key";
import { useAgentInputDraft } from "@/composer/draft/input-draft";
import { useForgeSearchQuery } from "@/git/use-forge-search-query";
import { getForgePresentation } from "@/git/forge";
@@ -336,6 +337,7 @@ interface WorkspaceCreationResult {
async function createMultiplicityWorkspace(input: {
idempotencyKey: string;
launchTarget: LaunchTarget;
worktreeSlug: string;
client: NonNullable<ReturnType<typeof useHostRuntimeClient>>;
isolation: "local" | "worktree";
@@ -365,10 +367,8 @@ async function createMultiplicityWorkspace(input: {
prompt: input.prompt,
attachments: input.attachments,
});
const payload = await input.client.createWorkspace({
idempotencyKey: input.idempotencyKey,
const request: Omit<CreateWorkspaceRequestOptions, "idempotencyKey" | "onEvent"> = {
agent: input.agent,
onEvent: input.onEvent,
source: isWorktree
? {
kind: "worktree",
@@ -387,6 +387,14 @@ async function createMultiplicityWorkspace(input: {
},
...(firstAgentContext ? { firstAgentContext } : {}),
...(Object.keys(input.metadata).length > 0 ? { metadata: { ...input.metadata } } : {}),
};
const payload = await input.client.createWorkspace({
...request,
idempotencyKey: draftCreationKey(input.idempotencyKey, {
request,
launchTarget: input.launchTarget,
}),
onEvent: input.onEvent,
});
if (payload.error || !payload.workspace) {
throw new Error(payload.error ?? input.createFailedMessage);
@@ -508,7 +516,7 @@ async function createWorkspaceChatAgent(input: CreateChatAgentInput): Promise<Su
});
const images = await encodeImages(wirePayload.images);
let navigated = false;
let outcome: SubmitOutcome = "background";
const delivery: { outcome: SubmitOutcome } = { outcome: "background" };
const initialAgent: NonNullable<CreateWorkspaceRequestOptions["agent"]> = {
config: {
provider,
@@ -545,7 +553,7 @@ async function createWorkspaceChatAgent(input: CreateChatAgentInput): Promise<Su
provider,
composerState,
});
outcome = submitWorkspaceDraft({
delivery.outcome = submitWorkspaceDraft({
clearConsumedDraft,
draftKey: input.draftKey,
draftContextScopeKey: input.draftContextScopeKey,
@@ -571,9 +579,15 @@ async function createWorkspaceChatAgent(input: CreateChatAgentInput): Promise<Su
};
// A retry after a failed agent start belongs to the ready workspace's draft, not to this creation.
const agentCreation = { result: Promise.resolve().then(() => execute()) };
await agentCreation.result;
if (outcome === "background") clearConsumedDraft();
return outcome;
try {
await agentCreation.result;
} catch (error) {
// Once handed off to the workspace draft tab, that tab owns surfacing agent startup errors.
if (delivery.outcome === "navigated") return delivery.outcome;
throw error;
}
if (delivery.outcome === "background") clearConsumedDraft();
return delivery.outcome;
}
function buildComposerConfig(input: {
@@ -1349,6 +1363,7 @@ export function NewWorkspaceScreen({
: undefined;
const normalizedWorkspace = await createMultiplicityWorkspace({
idempotencyKey: creationIdentity.draftId,
launchTarget,
worktreeSlug: creationIdentity.worktreeSlug,
client: connectedClient,
isolation: createsWorktree ? "worktree" : "local",
@@ -1373,6 +1388,7 @@ export function NewWorkspaceScreen({
creationIdentity,
creationResult,
effectiveIsolation,
launchTarget,
mergeWorkspaces,
queryClient,
selectedItem,
@@ -1443,7 +1459,9 @@ export function NewWorkspaceScreen({
const message = toErrorMessage(error);
setPendingAction(null);
setErrorMessage(message);
toast.error(message);
if (!isStillOnCreateScreen()) {
toast.error(message);
}
}
},
[
@@ -1524,7 +1542,9 @@ export function NewWorkspaceScreen({
const message = toErrorMessage(error);
setPendingAction(null);
setErrorMessage(message);
toast.error(message);
if (!isStillOnCreateScreen()) {
toast.error(message);
}
}
}, [
ensureWorkspace,
@@ -1662,6 +1682,7 @@ export function NewWorkspaceScreen({
clearDraft={noopClearDraft}
autoFocus={terminalTakesPrompt}
autoFocusKey={launchFocusKey}
error={errorMessage}
/>
) : (
<Composer
@@ -1693,6 +1714,7 @@ export function NewWorkspaceScreen({
autoFocusKey={launchFocusKey}
commandDraft={composerState?.commandDraft}
agentControls={agentControlsWithDisabled}
error={errorMessage}
/>
);
return (
@@ -1705,7 +1727,6 @@ export function NewWorkspaceScreen({
onImportSession={importSession.open}
>
{composer}
{errorMessage ? <Text style={styles.errorText}>{errorMessage}</Text> : null}
</NewWorkspaceLayout>
{importSession.sheet}
</FileDropZone>
@@ -1867,11 +1888,6 @@ const styles = StyleSheet.create((theme) => ({
fontWeight: theme.fontWeight.normal,
color: theme.colors.foreground,
},
errorText: {
fontSize: theme.fontSize.base,
color: theme.colors.destructive,
lineHeight: 20,
},
}));
/**