Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(desktop): block a second submit while a task is being created (#80137)

Paul D'Ambrad9ca59431a1e
diff --git a/products/desktop/packages/ui/src/features/task-detail/hooks/useTaskCreation.ts b/products/desktop/packages/ui/src/features/task-detail/hooks/useTaskCreation.ts
index b246b6618b7d..d52f8c4bb290 100644
--- a/products/desktop/packages/ui/src/features/task-detail/hooks/useTaskCreation.ts
+++ b/products/desktop/packages/ui/src/features/task-detail/hooks/useTaskCreation.ts
@@ -257,275 +257,292 @@ export function useTaskCreation({
const allowSubmit = contentOverride ? canSubmitBase : canSubmit;
if (!allowSubmit) return false;
- // Block over-limit cloud creation before the pending view so it doesn't flash.
- if (workspaceMode === "cloud" && !(await assertCloudUsageAvailable())) {
- return false;
- }
+ // Held for the whole submit, pre-flight awaits included, so a second
+ // Enter lands after `canSubmitBase` has already gone false.
+ setIsCreatingTask(true);
- // The local MCP server classification is fetched lazily on entering cloud
- // mode; submitting before it resolves would silently drop importedMcpServers/
- // relayedMcpServers below instead of including the user's local servers.
- if (workspaceMode === "cloud" && localMcpServersLoading) {
- toast.error("Still checking your local MCP servers", {
- description: "Try again in a moment.",
- });
- return false;
- }
+ try {
+ // Block over-limit cloud creation before the pending view so it doesn't flash.
+ if (workspaceMode === "cloud" && !(await assertCloudUsageAvailable())) {
+ return false;
+ }
- // Confirm a couple of worktree branch situations before starting the
- // task. Done before the pending view so a dialog (and a cancel) don't
- // leave a half-started task on screen. Reusing an existing worktree takes
- // priority over checking out a remote branch.
- let allowRemoteBranchCheckout = false;
- let reuseExistingWorktree = false;
- if (workspaceMode === "worktree" && branch && selectedDirectory) {
- try {
- const { status, existingWorktreePath, existingWorktreeTaskId } =
- await hostClient.workspace.checkWorktreeBranch.query({
- mainRepoPath: selectedDirectory,
- branch,
- });
- if (existingWorktreeTaskId) {
- // The branch's worktree already belongs to another task. Don't
- // create a duplicate; point the user at the task using it.
- const occupant = tasks?.find(
- (t) => t.id === existingWorktreeTaskId,
- );
- toast.error("Worktree already in use", {
- description: occupant
- ? `${branch} already has a worktree used by "${occupant.title}". Open that task to keep working there.`
- : `${branch} already has a worktree used by another task.`,
- });
- return false;
- }
- if (existingWorktreePath) {
- const confirmed = await useExistingWorktreeConfirmStore
- .getState()
- .confirm(branch, existingWorktreePath);
- if (!confirmed) {
+ // The local MCP server classification is fetched lazily on entering cloud
+ // mode; submitting before it resolves would silently drop importedMcpServers/
+ // relayedMcpServers below instead of including the user's local servers.
+ if (workspaceMode === "cloud" && localMcpServersLoading) {
+ toast.error("Still checking your local MCP servers", {
+ description: "Try again in a moment.",
+ });
+ return false;
+ }
+
+ // Confirm a couple of worktree branch situations before starting the
+ // task. Done before the pending view so a dialog (and a cancel) don't
+ // leave a half-started task on screen. Reusing an existing worktree takes
+ // priority over checking out a remote branch.
+ let allowRemoteBranchCheckout = false;
+ let reuseExistingWorktree = false;
+ if (workspaceMode === "worktree" && branch && selectedDirectory) {
+ try {
+ const { status, existingWorktreePath, existingWorktreeTaskId } =
+ await hostClient.workspace.checkWorktreeBranch.query({
+ mainRepoPath: selectedDirectory,
+ branch,
+ });
+ if (existingWorktreeTaskId) {
+ // The branch's worktree already belongs to another task. Don't
+ // create a duplicate; point the user at the task using it.
+ const occupant = tasks?.find(
+ (t) => t.id === existingWorktreeTaskId,
+ );
+ toast.error("Worktree already in use", {
+ description: occupant
+ ? `${branch} already has a worktree used by "${occupant.title}". Open that task to keep working there.`
+ : `${branch} already has a worktree used by another task.`,
+ });
return false;
}
- reuseExistingWorktree = true;
- } else if (status === "remote-only") {
- const confirmed = await useRemoteBranchConfirmStore
- .getState()
- .confirm(branch);
- if (!confirmed) {
- return false;
+ if (existingWorktreePath) {
+ const confirmed = await useExistingWorktreeConfirmStore
+ .getState()
+ .confirm(branch, existingWorktreePath);
+ if (!confirmed) {
+ return false;
+ }
+ reuseExistingWorktree = true;
+ } else if (status === "remote-only") {
+ const confirmed = await useRemoteBranchConfirmStore
+ .getState()
+ .confirm(branch);
+ if (!confirmed) {
+ return false;
+ }
+ allowRemoteBranchCheckout = true;
}
- allowRemoteBranchCheckout = true;
+ } catch (error) {
+ log.warn("Failed to check worktree branch availability", { error });
}
- } catch (error) {
- log.warn("Failed to check worktree branch availability", { error });
}
- }
-
- setIsCreatingTask(true);
- const content = contentOverride ?? editor.getContent();
- const plainPromptText = contentToPlainText(content).trim();
- const serializedContent = contentToXml(content).trim();
- const filePaths = extractFilePaths(content);
+ const content = contentOverride ?? editor.getContent();
+ const plainPromptText = contentToPlainText(content).trim();
+ const serializedContent = contentToXml(content).trim();
+ const filePaths = extractFilePaths(content);
- const shouldShowPendingView = !onTaskCreated && !!plainPromptText;
- const pendingTaskKey = shouldShowPendingView
- ? generatePendingTaskKey()
- : null;
+ const shouldShowPendingView = !onTaskCreated && !!plainPromptText;
+ const pendingTaskKey = shouldShowPendingView
+ ? generatePendingTaskKey()
+ : null;
- if (pendingTaskKey) {
- pendingTaskPromptStoreApi.set(pendingTaskKey, {
- promptText: plainPromptText,
- attachments: (content.attachments ?? []).map((a) => ({
- id: a.id,
- label: a.label,
- })),
- });
- navigateToTaskPending(pendingTaskKey);
- if (!contentOverride) {
- editor.clear();
+ if (pendingTaskKey) {
+ pendingTaskPromptStoreApi.set(pendingTaskKey, {
+ promptText: plainPromptText,
+ attachments: (content.attachments ?? []).map((a) => ({
+ id: a.id,
+ label: a.label,
+ })),
+ });
+ navigateToTaskPending(pendingTaskKey);
+ if (!contentOverride) {
+ editor.clear();
+ }
}
- }
- let createdTaskId: string | undefined;
+ let createdTaskId: string | undefined;
- try {
- if (!contentOverride) {
- const plainText = editor.getText()?.trim() ?? plainPromptText;
- if (plainText) {
- useTaskInputHistoryStore.getState().addPrompt(plainText);
+ try {
+ if (!contentOverride) {
+ const plainText = editor.getText()?.trim() ?? plainPromptText;
+ if (plainText) {
+ useTaskInputHistoryStore.getState().addPrompt(plainText);
+ }
}
- }
- const settings = useSettingsStore.getState();
- const defaultedChannelId =
- bluebirdEnabled && !channelId && !channelName
- ? personalChannel?.id
- : undefined;
+ const settings = useSettingsStore.getState();
+ const defaultedChannelId =
+ bluebirdEnabled && !channelId && !channelName
+ ? personalChannel?.id
+ : undefined;
- const localMcpServersForRun = partitionLocalMcpServersForRun(
- localMcpServers,
- adapter,
- );
- const input = prepareTaskInput(serializedContent, filePaths, {
- // Repo-optional surfaces may still supply an explicit task folder or
- // repository selection; otherwise creation falls back to scratch.
- selectedDirectory: selectedDirectory || undefined,
- selectedRepository: allowNoRepo ? null : selectedRepository,
- repositories,
- githubIntegrationId,
- githubUserIntegrationId,
- workspaceMode,
- branch,
- allowRemoteBranchCheckout,
- reuseExistingWorktree,
- executionMode,
- adapter,
- runtime,
- model,
- reasoningLevel,
- contextWindow,
- fastMode,
- environmentId,
- sandboxEnvironmentId,
- customImageId,
- signalReportId,
- additionalDirectories,
- channelContext,
- channelName,
- channelId: channelId ?? defaultedChannelId,
- channelContextId,
- customInstructions: getEffectiveCustomInstructions(settings),
- autoPublishCloudRuns: settings.autoPublishCloudRuns,
- rtkEnabledCloud: settings.rtkEnabledCloud,
- allowNoRepo,
- importedMcpServers: localMcpServersForRun.imported,
- relayedMcpServers: localMcpServersForRun.relayed,
- });
+ const localMcpServersForRun = partitionLocalMcpServersForRun(
+ localMcpServers,
+ adapter,
+ );
+ const input = prepareTaskInput(serializedContent, filePaths, {
+ // Repo-optional surfaces may still supply an explicit task folder or
+ // repository selection; otherwise creation falls back to scratch.
+ selectedDirectory: selectedDirectory || undefined,
+ selectedRepository: allowNoRepo ? null : selectedRepository,
+ repositories,
+ githubIntegrationId,
+ githubUserIntegrationId,
+ workspaceMode,
+ branch,
+ allowRemoteBranchCheckout,
+ reuseExistingWorktree,
+ executionMode,
+ adapter,
+ runtime,
+ model,
+ reasoningLevel,
+ contextWindow,
+ fastMode,
+ environmentId,
+ sandboxEnvironmentId,
+ customImageId,
+ signalReportId,
+ additionalDirectories,
+ channelContext,
+ channelName,
+ channelId: channelId ?? defaultedChannelId,
+ channelContextId,
+ customInstructions: getEffectiveCustomInstructions(settings),
+ autoPublishCloudRuns: settings.autoPublishCloudRuns,
+ rtkEnabledCloud: settings.rtkEnabledCloud,
+ allowNoRepo,
+ importedMcpServers: localMcpServersForRun.imported,
+ relayedMcpServers: localMcpServersForRun.relayed,
+ });
- if (executionMode) {
- useSettingsStore.getState().setLastUsedInitialTaskMode(executionMode);
- }
+ if (executionMode) {
+ useSettingsStore
+ .getState()
+ .setLastUsedInitialTaskMode(executionMode);
+ }
+
+ const result = await taskService.createTask(
+ input,
+ (output) => {
+ invalidateTasks(output.task);
+ // Stash the prompt's local attachment paths so the chat-title
+ // generator can read their contents when naming the task — needed
+ // for pasted-text prompts whose only signal is the file body, and
+ // especially for cloud tasks where the local path is otherwise lost
+ // once the file is uploaded as an artifact.
+ // Exclude folder chips — only file paths are readable by the title
+ // generator's readAbsoluteFile call.
+ const folderIds = new Set(
+ content.segments.flatMap((seg) =>
+ seg.type === "chip" && seg.chip.type === "folder"
+ ? [seg.chip.id]
+ : [],
+ ),
+ );
+ const fileOnlyPaths = filePaths.filter((p) => !folderIds.has(p));
+ if (fileOnlyPaths.length > 0) {
+ titleAttachmentStoreApi.set(output.task.id, fileOnlyPaths);
+ }
+ if (signalReportId) {
+ clearTaskInputReportAssociation();
+ }
+ createdTaskId = output.task.id;
+ if (pendingTaskKey) {
+ pendingTaskPromptStoreApi.move(pendingTaskKey, output.task.id);
+ }
+ // Clear the draft BEFORE navigating away. When onTaskCreated
+ // navigates (e.g. channels), it can synchronously unmount/destroy
+ // the editor; clearing afterwards would throw in clearContent()
+ // before the persisted draft is wiped, leaving stale text behind.
+ if (!pendingTaskKey && !contentOverride) {
+ editor.clear();
+ }
+ if (defaultedChannelId) {
+ track(ANALYTICS_EVENTS.CHANNEL_ACTION, {
+ action_type: "file_task",
+ surface: "task_input",
+ channel_id: defaultedChannelId,
+ task_id: output.task.id,
+ success: true,
+ });
+ }
+ onTaskCreatedEffect?.(output.task);
+ if (onTaskCreated) {
+ onTaskCreated(output.task);
+ } else {
+ void openTask(output.task);
+ }
+ useTourStore.getState().completeTour(createFirstTaskTour.id);
+ // Pre-flight already ran above for cloud; skip the service's duplicate check.
+ },
+ { skipCloudUsagePreflight: true },
+ );
- const result = await taskService.createTask(
- input,
- (output) => {
- invalidateTasks(output.task);
- // Stash the prompt's local attachment paths so the chat-title
- // generator can read their contents when naming the task — needed
- // for pasted-text prompts whose only signal is the file body, and
- // especially for cloud tasks where the local path is otherwise lost
- // once the file is uploaded as an artifact.
- // Exclude folder chips — only file paths are readable by the title
- // generator's readAbsoluteFile call.
- const folderIds = new Set(
- content.segments.flatMap((seg) =>
- seg.type === "chip" && seg.chip.type === "folder"
- ? [seg.chip.id]
- : [],
- ),
+ if (result.success && result.data.provisioningError) {
+ // Worktree provisioning failed but the task (and its prompt) was kept
+ // so the user can retry setup on it. Stay on the task the onTaskReady
+ // callback already navigated to — don't reopen the composer — and
+ // flag the failure so the task view shows a retry prompt.
+ useProvisioningStore
+ .getState()
+ .setFailed(result.data.task.id, result.data.provisioningError);
+ toastError(
+ getErrorTitle("workspace_creation"),
+ result.data.provisioningError,
);
- const fileOnlyPaths = filePaths.filter((p) => !folderIds.has(p));
- if (fileOnlyPaths.length > 0) {
- titleAttachmentStoreApi.set(output.task.id, fileOnlyPaths);
- }
- if (signalReportId) {
- clearTaskInputReportAssociation();
+ }
+
+ if (result.success) {
+ if (!result.data.provisioningError) {
+ if (pendingTaskKey) {
+ pendingTaskPromptStoreApi.clear(pendingTaskKey);
+ }
+ if (createdTaskId) {
+ pendingTaskPromptStoreApi.clear(createdTaskId);
+ }
}
- createdTaskId = output.task.id;
- if (pendingTaskKey) {
- pendingTaskPromptStoreApi.move(pendingTaskKey, output.task.id);
+ setAdditionalDirectoriesOverride(null);
+ // Guarantee the editor draft is wiped on success. editor.clear()
+ // above only runs inside the onTaskReady callback (and after it
+ // navigates the editor may be torn down); clearing the persisted
+ // draft directly here always runs and survives the unmount, so a
+ // submitted prompt never reappears on the next new task.
+ if (!contentOverride) {
+ useDraftStore.getState().actions.setDraft(sessionId, null);
}
- // Clear the draft BEFORE navigating away. When onTaskCreated
- // navigates (e.g. channels), it can synchronously unmount/destroy
- // the editor; clearing afterwards would throw in clearContent()
- // before the persisted draft is wiped, leaving stale text behind.
- if (!pendingTaskKey && !contentOverride) {
- editor.clear();
+ // The task-level repository/folder pick is consumed by this task;
+ // the next one starts from the space defaults again ("save to
+ // space" is the durable path).
+ if (allowNoRepo && channelId) {
+ useTaskRepositoryDraftStore.getState().clearDraft(channelId);
}
- if (defaultedChannelId) {
- track(ANALYTICS_EVENTS.CHANNEL_ACTION, {
- action_type: "file_task",
- surface: "task_input",
- channel_id: defaultedChannelId,
- task_id: output.task.id,
- success: true,
+ void trackTaskCreated(input, selectedDirectory, hostClient);
+ // Repo-less channel tasks create no workspace row (the agent runs in
+ // a scratch dir surfaced as a synthetic workspace), so the normal
+ // workspace.create invalidation never fires. Refresh the workspace
+ // cache so the task view resolves its cwd and skips the repo prompt.
+ if (allowNoRepo) {
+ void queryClient.invalidateQueries({
+ queryKey: trpc.workspace.getAll.queryKey(),
});
}
- onTaskCreatedEffect?.(output.task);
- if (onTaskCreated) {
- onTaskCreated(output.task);
+ }
+
+ if (!result.success) {
+ // Usage-limit blocks already show the upgrade modal; don't also toast an error.
+ if (isUsageLimitResult(result)) {
+ useUsageLimitStore.getState().show();
+ log.warn("Cloud task creation blocked by usage limit");
} else {
- void openTask(output.task);
+ const title = getErrorTitle(result.failedStep);
+ toastError(title, result.error);
+ log.error("Task creation failed", {
+ failedStep: result.failedStep,
+ error: result.error,
+ });
}
- useTourStore.getState().completeTour(createFirstTaskTour.id);
- // Pre-flight already ran above for cloud; skip the service's duplicate check.
- },
- { skipCloudUsagePreflight: true },
- );
-
- if (result.success && result.data.provisioningError) {
- // Worktree provisioning failed but the task (and its prompt) was kept
- // so the user can retry setup on it. Stay on the task the onTaskReady
- // callback already navigated to — don't reopen the composer — and
- // flag the failure so the task view shows a retry prompt.
- useProvisioningStore
- .getState()
- .setFailed(result.data.task.id, result.data.provisioningError);
- toastError(
- getErrorTitle("workspace_creation"),
- result.data.provisioningError,
- );
- }
-
- if (result.success) {
- if (!result.data.provisioningError) {
if (pendingTaskKey) {
pendingTaskPromptStoreApi.clear(pendingTaskKey);
+ if (createdTaskId) {
+ pendingTaskPromptStoreApi.clear(createdTaskId);
+ }
+ openTaskInput({ initialPrompt: plainPromptText });
}
- if (createdTaskId) {
- pendingTaskPromptStoreApi.clear(createdTaskId);
- }
- }
- setAdditionalDirectoriesOverride(null);
- // Guarantee the editor draft is wiped on success. editor.clear()
- // above only runs inside the onTaskReady callback (and after it
- // navigates the editor may be torn down); clearing the persisted
- // draft directly here always runs and survives the unmount, so a
- // submitted prompt never reappears on the next new task.
- if (!contentOverride) {
- useDraftStore.getState().actions.setDraft(sessionId, null);
- }
- // The task-level repository/folder pick is consumed by this task;
- // the next one starts from the space defaults again ("save to
- // space" is the durable path).
- if (allowNoRepo && channelId) {
- useTaskRepositoryDraftStore.getState().clearDraft(channelId);
- }
- void trackTaskCreated(input, selectedDirectory, hostClient);
- // Repo-less channel tasks create no workspace row (the agent runs in
- // a scratch dir surfaced as a synthetic workspace), so the normal
- // workspace.create invalidation never fires. Refresh the workspace
- // cache so the task view resolves its cwd and skips the repo prompt.
- if (allowNoRepo) {
- void queryClient.invalidateQueries({
- queryKey: trpc.workspace.getAll.queryKey(),
- });
- }
- }
-
- if (!result.success) {
- // Usage-limit blocks already show the upgrade modal; don't also toast an error.
- if (isUsageLimitResult(result)) {
- useUsageLimitStore.getState().show();
- log.warn("Cloud task creation blocked by usage limit");
- } else {
- const title = getErrorTitle(result.failedStep);
- toastError(title, result.error);
- log.error("Task creation failed", {
- failedStep: result.failedStep,
- error: result.error,
- });
}
+ return result.success;
+ } catch (error) {
+ toastError("Failed to create task", error);
+ log.error("Unexpected error during task creation", { error });
if (pendingTaskKey) {
pendingTaskPromptStoreApi.clear(pendingTaskKey);
if (createdTaskId) {
@@ -533,19 +550,8 @@ export function useTaskCreation({
}
openTaskInput({ initialPrompt: plainPromptText });
}
+ return false;
}
- return result.success;
- } catch (error) {
- toastError("Failed to create task", error);
- log.error("Unexpected error during task creation", { error });
- if (pendingTaskKey) {
- pendingTaskPromptStoreApi.clear(pendingTaskKey);
- if (createdTaskId) {
- pendingTaskPromptStoreApi.clear(createdTaskId);
- }
- openTaskInput({ initialPrompt: plainPromptText });
- }
- return false;
} finally {
setIsCreatingTask(false);
}