mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-26 18:35:33 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Plan mode lets a person ask an agent for a plan, review it as the task's Plan document, and accept it before any work starts > - People who use Google Antigravity agents type `/plan <request>`, as they do in other agent tools. Paperclip sent that text to the agent, and #22701 correctly neutralised it, so nothing happened > - An Antigravity run in Plan mode was also not read-only: the agent could still edit files and run commands while it "planned" > - This pull request makes a leading `/plan` in the composer select Plan mode, and keeps an Antigravity Plan-mode run read-only at its permission prompt > - The benefit is that `/plan` with an Antigravity agent gives the normal Paperclip plan flow (Plan document, accept, then execution on the same task), and planning cannot change the workspace ## Linked Issues or Issue Description Refs #22701 **What happened?** A person wrote `/plan add greeting.txt` to a Google Antigravity agent. The agent did not plan. In Plan mode the Antigravity agent could still edit files and run commands. **What did you expect?** `/plan <request>` starts Plan mode. The agent researches and proposes a plan in the task's Plan document. It does not change files until the person accepts the plan. **Steps to reproduce** 1. Assign a task to a Google Antigravity agent. 2. Write `/plan Add a file greeting.txt containing hello`. 3. See that the task stays in Auto mode, and that the agent creates the file. ## What Changed - Task composer: a leading `/plan` in a comment or in a new task selects Plan mode and sends the rest of the message without the command. `/plan` alone only switches the mode. The slash menu offers "Plan". A `/plan` anywhere else in the message (quoted, pasted, fenced, mid-sentence) stays ordinary text and does not change the mode. This is the typed form of the existing Plan mode control, so it works the same for every agent. - Antigravity runner (`antigravity-plan-mode.ts`, wired in `acpx-runtime-adapter.ts` and `runtime-host.ts`): when Paperclip runs an Antigravity task in Plan mode (the existing read-only task policy), the permission prompt fails closed. It allows only (a) the 1.5.2 server's built-in research tools (file read, search, directory listing, page read), named by the exact `Run <tool>?` prompt title, when the reported kind also matches that tool, and (b) the tools the runner's own Paperclip bridge registered for this run, on the runner-owned server named `paperclip`. The provider's reported kind alone never grants a read, and no other MCP server is trusted, runner-owned or not. It refuses file edits, terminal commands and everything else. Paperclip's server applies its Plan-mode rules to its own tools, and the agent writes the Plan document through them. - Composer command parsing moved to `ui/src/components/task-chat/composer-commands.ts`. `/goal` and `/plan` both use the shared rule. Both submit paths use one `/plan` decision: a bare `/plan` sends (in Plan mode) only when an attachment can be sent without text; otherwise it only selects Plan mode. A composer without Plan mode (the dashboard chat starter) keeps `/plan` as text. - Follow-up, not in this PR: the Kimi read-only gate (`kimiReadOnlyPermissionAllowed`) trusts every runner-owned MCP server by title prefix. It should get the same binding to the Paperclip bridge's registered tools. - No change to the #22701 guard. Every `/plan`, `/logout` and `/usage` that would reach the Antigravity server is still neutralised. - No change to the Antigravity admission patch, profile or closure digests. No shared contract change. ### Why not the native `/plan` of Antigravity 1.5.2 I checked the pinned 1.5.2 server and SDK sources and ran it live: - The server has no plan session mode (only `default`, `auto_edit`, `yolo`) and no plan config option. Its only route is the `/plan` text command, which it turns into an SDK slash-command object. - Live on 1.5.2 (Google sign-in, `gemini-3.8-flash-low`), a task with `Please /plan this ...` reached the model as `Please/BuiltinSlashCommandName.PLAN this ...`. The SDK sent the enum's string form instead of `plan`, so the harness did not enter planning mode. Over 61 native steps (about 5 minutes) the agent wrote no plan artifact, ran terminal commands, and searched the file system for that unknown name. I stopped the run. - A working native path needs a change inside the runtime (for example in the owned admission patch), which re-pins the closures for every platform and needs re-qualification. This PR does not do that. Paperclip's own Plan mode gives the user-visible result now, with no re-pin. ### Source of trust for slash commands (reused by `/swarm`) - `parseLeadingUserCommand(text, allowlist)` in `packages/shared/src/leading-user-command.ts` is the one rule. It returns `{ command, argument }` or `null`. - Trusted text: only what the signed-in user typed and submitted in the task composer. That is a comment body or the body of a new task. Conversations (chat) do not use it for `/plan`. - Never trusted: agent comments, chat or connector messages, API-posted text, issue text written by someone else, quoted or pasted parts, and every prompt Paperclip builds for an agent. These stay text, and the #22701 guard still neutralises any native command in them. - Inside trusted text, only a command at the very start counts: optional whitespace, `/name`, then whitespace or the end. The name is exact and lower-case and must be in the allowlist. Only `plan` is enabled. Whitespace follows the Antigravity server's Python rules (U+001C-U+001F count; U+FEFF does not). - A recognised command becomes a structured action (here: Plan mode). It never reaches an agent as command text. - Tests cover: leading whitespace and newlines, a command not at the start, quoted, fenced, forwarded and wrapped content, a neutralised command, case, `/planning`, `/plans`, paths and URLs, Python vs JavaScript whitespace, and the allowlist. ## Verification - `pnpm --filter @paperclipai/paperclip-runner exec vitest run src/drivers/acpx/antigravity-plan-mode.test.ts src/drivers/acpx/acpx-runtime-adapter.test.ts src/drivers/acpx/antigravity-native-commands.test.ts src/drivers/acpx/antigravity-admission.test.ts`: 250 passed. - `pnpm --filter @paperclipai/shared exec vitest run src/leading-user-command.test.ts`: 8 passed (red first: module missing). - `pnpm --filter @paperclipai/ui exec vitest run src/components/task-chat/TaskChatComposer.test.tsx src/components/MarkdownEditor.autocomplete.test.tsx`: all passed (TaskChatComposer 155). - Red before the fix: the adapter test showed an Antigravity Plan-mode run approved a file write and a terminal command (`allow_once`), and the four composer `/plan` tests failed. The negative test (a `/plan` inside the message stays text) passed before and after. - Runner and UI typecheck pass (`tsc --noEmit`; the UI's only errors are the existing ungenerated Storybook catalog files). - `pnpm verify` returned exit 2 (runner files outside the local test graph), so required CI supplies the broad coverage. - Live, on THIS branch: a local instance running this branch, Google sign-in, `gemini-3.8-flash-low`, driven in the browser through the task composer: 1. `/plan Create a file named plan-proof.txt containing the single line OK` in a new task: the task was created in Plan mode with the command removed. Plan run 3 min 34 s, terminal state **succeeded** (the agent handed in through `paperclip_finish`; run result accepted, waiting for plan approval). The Plan document and a Confirm / Request changes card appeared. One `ls -la` was refused by the read-only gate. No file was written. 2. Request changes ("Name the file plan-proof-2.txt instead."): revision run 28 s, succeeded. Plan document revision 2 named the new file; a new Confirm / Request changes card appeared. Still no file. 3. Confirm: execution run 55 s, succeeded; task Done; `plan-proof-2.txt` contains exactly `OK` plus a newline. 4. Normal task whose text contains a pasted `"we usually /plan things like this first"`: created in standard mode, text unchanged; run 68 s, succeeded, Done; `negative-proof.txt` = `NEG`; no refused tool call. 5. Dashboard "Start a chat" box: NOT run live. The box renders only with an experimental instance setting that is off on this instance, and I did not change instance settings. A unit test covers it (a composer without Plan mode keeps `/plan` as text). 6. Stop during a Plan-mode run: the run was cancelled about 1 s after Stop and did not revive (no new run for over 3 min); no file. Killing only the native Antigravity server process mid Plan-mode run: the run failed with a provider error, showed "Continuing automatically", and a continuation run started 36 s later and settled (succeeded, 3 min 17 s, response wake). No duplicate comments; the Plan document has one revision; no file written; the gate refused one shell command in each run. - Found live, NOT fixed here: in the recovered run of step 6 the model settled with "waiting for plan review" but did not open the Confirm card (in steps 1 and 2 it did). Paperclip creates that card automatically only from a harness's own plan proposal (Codex, Claude). For Antigravity it depends on the agent. Recommended follow-up: when a Plan-mode run settles with a new plan revision and no pending plan confirmation, the server opens the card itself. - To be clear: this is not Antigravity's native plan mode. Native plan mode on runtime 1.5.2 does not work (see above). This PR gives Paperclip's Plan mode, started by a trusted `/plan`, with the Antigravity run held read-only. ## Risks - Low to medium. Plan mode for Antigravity now refuses terminal commands, so the agent researches with its file read and search tools. A planner that relied on shell reads must use those tools instead. - Google Workspace accounts whose admin policy lets terminal commands run in a sandbox without a prompt skip the permission prompt for commands. That path cannot be blocked here. Personal Google accounts and API keys always prompt. - `/plan` as the first word of a message now selects Plan mode for every agent. To send the literal text, write `\/plan` or put other text first. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, with tool use (shell, file edit, browser automation not used), in Claude Code. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1704 lines
65 KiB
TypeScript
1704 lines
65 KiB
TypeScript
import { createUuid } from "@/lib/uuid";
|
|
import { useCurrentAccountGuard } from "@/hooks/useAccountBoundMutation";
|
|
import { ComposerFileDropTarget } from "./ComposerFileDropTarget";
|
|
import { AgentAvatar } from "../AgentAvatar";
|
|
import {
|
|
useEffect,
|
|
useId,
|
|
useRef,
|
|
useState,
|
|
type ChangeEvent,
|
|
type ClipboardEvent as ReactClipboardEvent,
|
|
type ReactNode,
|
|
} from "react";
|
|
import { cn } from "@/lib/utils";
|
|
import { taskChatComposerSurfaceClasses } from "./composer-surface";
|
|
import { useComposerStop } from "@/hooks/useComposerStop";
|
|
import { useComposerSubmitKey } from "@/hooks/useComposerSubmitKey";
|
|
import { useStreamlinedTaskChatPresentation } from "./presentation-mode";
|
|
import {
|
|
DRAFT_DEBOUNCE_MS,
|
|
clearDraft,
|
|
loadDraft,
|
|
loadDraftAttachments,
|
|
saveDraft,
|
|
saveDraftAttachments,
|
|
loadDraftSubmission,
|
|
replayableRequest,
|
|
saveDraftSubmission,
|
|
clearDraftSubmission,
|
|
settleDraftSubmission,
|
|
type ComposerDraftSubmission,
|
|
type ComposerSendRequest,
|
|
} from "@/lib/composer-draft";
|
|
import { classifySendFailure, type SendOutcome } from "@/lib/pending-send";
|
|
import { describeError } from "@/api/errors";
|
|
import { useAutoResend } from "@/hooks/useDurableSubmit";
|
|
import { useDraftOwner } from "@/hooks/useDraftOwner";
|
|
import { useRequestOwnerBinding } from "@/hooks/useRequestOwnerBinding";
|
|
import { PendingSendNotice } from "@/components/PendingSendNotice";
|
|
import {
|
|
ArrowUp,
|
|
RotateCw,
|
|
Square,
|
|
ChevronDown,
|
|
CircleHelp,
|
|
Loader2,
|
|
X,
|
|
} from "lucide-react";
|
|
import { Button } from "@/components/ui/button";
|
|
import {
|
|
Attachment,
|
|
AttachmentAction,
|
|
AttachmentActions,
|
|
AttachmentContent,
|
|
AttachmentDescription,
|
|
AttachmentGroup,
|
|
AttachmentMedia,
|
|
AttachmentTitle,
|
|
} from "@/components/ui/attachment";
|
|
import { fileKindForName, formatFileSize, isImageAttachment } from "./task-chat-attachments";
|
|
import {
|
|
MarkdownEditor,
|
|
type MarkdownEditorRef,
|
|
} from "@/components/MarkdownEditor";
|
|
import { nextWorkMode } from "@/lib/work-mode-meta";
|
|
import { trackRecentAssignee, trackRecentAssigneeUser } from "@/lib/recent-assignees";
|
|
import {
|
|
InlineEntitySelector,
|
|
type InlineEntityOption,
|
|
} from "@/components/InlineEntitySelector";
|
|
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
|
|
import type { MentionOption } from "@/components/MarkdownEditor";
|
|
import type { IssueAttachment, IssueWorkMode } from "@paperclipai/shared";
|
|
import type { RunnerGoalCapability } from "@paperclipai/shared";
|
|
import { parseRunnerGoalCommand, planSubmission, type RunnerGoalComposerCommand } from "./composer-commands";
|
|
import type { ActionCommandOption } from "@/context/EditorAutocompleteContext";
|
|
import { TaskChatComposerTakeoverActionsContext } from "./TaskChatComposerTakeoverContext";
|
|
|
|
import { TaskChatPausedTakeover, type TaskComposerPause } from "./TaskChatPausedTakeover";
|
|
import { ComposerImageAttachments, type ComposerImageAttachment } from "./ComposerImageAttachments";
|
|
import { ComposerRunSettingsPicker } from "./ComposerRunSettingsPicker";
|
|
import { TaskChatComposerBar } from "./TaskChatComposerBar";
|
|
import { ComposerAddMenu, ComposerModeChip, ComposerPrivacyChip } from "./ComposerAddMenu";
|
|
import { supportsComposerModel, type ComposerRunSettings } from "./composer-run-settings";
|
|
import { useCoordinatorPresentation } from "@/components/coordinator/CoordinatorPresentation";
|
|
import type { Agent, IssueAssigneeAdapterOverrides } from "@paperclipai/shared";
|
|
|
|
/** Structurally identical to IssueChatThread's module-private CommentReassignment. */
|
|
export interface CommentReassignment {
|
|
assigneeAgentId: string | null;
|
|
assigneeUserId: string | null;
|
|
}
|
|
|
|
export interface TaskChatComposerTakeover {
|
|
id: string;
|
|
label: string;
|
|
pendingCount: number;
|
|
content: ReactNode;
|
|
/** Hides the takeover without resolving it; the pending indicator can reopen it. */
|
|
onDismiss: () => void;
|
|
onSkip: () => Promise<void> | void;
|
|
onShowNext?: () => void;
|
|
/** Places Skip inside a structured question form's action row. */
|
|
inlineSkip?: boolean;
|
|
hideLabel?: boolean;
|
|
/** Some decision surfaces already provide a non-accept path of their own. */
|
|
hideSkip?: boolean;
|
|
}
|
|
|
|
interface TaskChatComposerProps {
|
|
onAdd?: (
|
|
body: string,
|
|
reopen?: boolean,
|
|
reassignment?: CommentReassignment,
|
|
attachmentIds?: string[],
|
|
clientRequestId?: string,
|
|
runSettings?: ComposerRunSettings,
|
|
) => Promise<void> | void;
|
|
/** New tasks share the editor and controls, but retain their draft until creation succeeds. */
|
|
creation?: {
|
|
value: string;
|
|
onChange: (value: string) => void;
|
|
onSubmit: (body: string, mode: IssueWorkMode, settings: ComposerRunSettings | null) => Promise<void>;
|
|
submitLabel: string;
|
|
canSubmitWithoutBody?: boolean;
|
|
header?: ReactNode;
|
|
details?: ReactNode;
|
|
contextBar?: ReactNode;
|
|
submitDisabled?: boolean;
|
|
/** Lock the editor, e.g. while a submitted create waits to resend. */
|
|
readOnly?: boolean;
|
|
privacy?: { private: boolean; inherited?: string; onChange: (value: boolean) => void };
|
|
onSelectFiles: (files: File[]) => void;
|
|
images?: ComposerImageAttachment[];
|
|
onRemoveImage?: (id: string) => void;
|
|
runSettings: ComposerRunSettings | null;
|
|
onRunSettingsChange: (settings: ComposerRunSettings | null) => void;
|
|
};
|
|
confirmedSubmissionIds?: ReadonlySet<string>;
|
|
onStop?: () => Promise<void>;
|
|
confirmedStoppedRunIds?: ReadonlySet<string>;
|
|
stopPending?: boolean;
|
|
stopScope?: "leaf" | "subtree";
|
|
workMode: IssueWorkMode;
|
|
onWorkModeChange?: (mode: IssueWorkMode) => Promise<void> | void;
|
|
disabled?: boolean;
|
|
disabledReason?: string | null;
|
|
placeholder?: string;
|
|
/** Preferred upload path: attaches the file to the task (mirrors legacy). */
|
|
onAttachImage?: (file: File) => Promise<IssueAttachment | void>;
|
|
onImageUpload?: (file: File) => Promise<string>;
|
|
/** Mentionable entities for the editor's @-autocomplete. */
|
|
mentions?: MentionOption[];
|
|
enableReassign?: boolean;
|
|
conversationMode?: boolean;
|
|
reassignOptions?: InlineEntityOption[];
|
|
agentMap?: ReadonlyMap<string, import("../AgentAvatar").AvatarAgent & { icon?: string | null }>;
|
|
modelAgents?: ReadonlyMap<string, Agent>;
|
|
companyId?: string | null;
|
|
assigneeAdapterOverrides?: IssueAssigneeAdapterOverrides | null;
|
|
userProfileMap?: ReadonlyMap<
|
|
string,
|
|
{ label: string; image: string | null }
|
|
> | null;
|
|
currentAssigneeValue?: string;
|
|
suggestedAssigneeValue?: string;
|
|
onPendingAssigneeChange?: (value: string | null) => void;
|
|
issueStatus?: string;
|
|
/** Mobile document-flow host: 16px editor text so iOS doesn't zoom on focus. */
|
|
mobile?: boolean;
|
|
/** Storage key used to restore, persist, and clear this task's text draft. */
|
|
draftKey?: string;
|
|
/** When set, the main composer temporarily edits this queued message. */
|
|
queuedEdit?: { commentId: string; body: string; stale?: boolean } | null;
|
|
onSaveQueuedEdit?: (commentId: string, body: string) => Promise<void>;
|
|
onCancelQueuedEdit?: () => void;
|
|
pause?: TaskComposerPause | null;
|
|
takeover?: TaskChatComposerTakeover | null;
|
|
pendingTakeover?: {
|
|
count: number;
|
|
label?: string;
|
|
onOpen: () => void;
|
|
} | null;
|
|
runnerGoalCapability?: RunnerGoalCapability | null;
|
|
onRunnerGoalCommand?: (
|
|
command: RunnerGoalComposerCommand,
|
|
) => Promise<void> | void;
|
|
onRunnerGoalReassign?: (
|
|
reassignment: CommentReassignment,
|
|
) => Promise<void> | void;
|
|
}
|
|
|
|
export { parsePlanCommand, parseRunnerGoalCommand } from "./composer-commands";
|
|
export type { ParsedRunnerGoalCommand, RunnerGoalComposerCommand } from "./composer-commands";
|
|
|
|
function identityInitials(label: string): string {
|
|
const parts = label.trim().split(/\s+/).filter(Boolean);
|
|
if (parts.length === 0) return "?";
|
|
if (parts.length === 1) return parts[0]!.slice(0, 2).toUpperCase();
|
|
return `${parts[0]![0]}${parts[parts.length - 1]![0]}`.toUpperCase();
|
|
}
|
|
|
|
function AssigneeIdentityAvatar({
|
|
assigneeValue,
|
|
label,
|
|
agentMap,
|
|
userProfileMap,
|
|
placement,
|
|
}: {
|
|
assigneeValue: string;
|
|
label: string;
|
|
agentMap: ReadonlyMap<string, import("../AgentAvatar").AvatarAgent & { icon?: string | null }> | undefined;
|
|
userProfileMap:
|
|
| ReadonlyMap<string, { label: string; image: string | null }>
|
|
| null
|
|
| undefined;
|
|
placement: "trigger" | "option";
|
|
}) {
|
|
if (assigneeValue.startsWith("agent:")) {
|
|
const agentId = assigneeValue.slice("agent:".length);
|
|
const icon = agentMap?.get(agentId)?.icon ?? "bot";
|
|
return (
|
|
<span
|
|
className="shrink-0"
|
|
data-assignee-identity={assigneeValue}
|
|
data-assignee-trigger-icon={placement === "trigger" ? icon : undefined}
|
|
data-assignee-option-icon={
|
|
placement === "option" ? assigneeValue : undefined
|
|
}
|
|
>
|
|
<AgentAvatar agent={agentMap?.get(agentId) ?? { id: agentId }} size={16} />
|
|
</span>
|
|
);
|
|
}
|
|
|
|
if (assigneeValue.startsWith("user:")) {
|
|
const userId = assigneeValue.slice("user:".length);
|
|
const profile = userProfileMap?.get(userId);
|
|
const resolvedLabel = profile?.label ?? label;
|
|
return (
|
|
<Avatar
|
|
size="xs"
|
|
className="shrink-0"
|
|
data-assignee-identity={assigneeValue}
|
|
data-assignee-trigger-avatar={
|
|
placement === "trigger" ? userId : undefined
|
|
}
|
|
data-assignee-option-avatar={
|
|
placement === "option" ? assigneeValue : undefined
|
|
}
|
|
>
|
|
{profile?.image ? <AvatarImage src={profile.image} alt="" /> : null}
|
|
<AvatarFallback>{identityInitials(resolvedLabel)}</AvatarFallback>
|
|
</Avatar>
|
|
);
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
/** v7 per-mode placeholder copy; `{agent}` is the pending assignee's name. */
|
|
function modePlaceholder(mode: IssueWorkMode, agentName: string, mobile: boolean): string {
|
|
if (mobile) {
|
|
if (mode === "planning") return `Plan with ${agentName}…`;
|
|
if (mode === "ask") return `Ask ${agentName}…`;
|
|
return `Work with ${agentName}`;
|
|
}
|
|
switch (mode) {
|
|
case "planning":
|
|
return `Plan with ${agentName} — shapes the plan doc, no code changes…`;
|
|
case "ask":
|
|
return `Ask ${agentName} a question — read-only, nothing runs…`;
|
|
default:
|
|
return `Work with ${agentName}`;
|
|
}
|
|
}
|
|
|
|
type ComposerAttachment = {
|
|
id: string;
|
|
attachmentId?: string;
|
|
inline?: boolean;
|
|
contentType?: string;
|
|
name: string;
|
|
size?: number;
|
|
status: "uploading" | "attached" | "error";
|
|
error?: string;
|
|
/** Set once uploaded; the submit path appends `[name](contentPath)` lines. */
|
|
contentPath?: string;
|
|
/**
|
|
* The picked file, kept after a failed upload so the chip can offer Retry.
|
|
* Uploads are not deduped by the server, so they never resend on their own.
|
|
*/
|
|
file?: File;
|
|
};
|
|
|
|
type QueuedEditBackup = {
|
|
body: string;
|
|
attachments: ComposerAttachment[];
|
|
pendingMode: IssueWorkMode | null;
|
|
pendingAssignee: string | null;
|
|
};
|
|
|
|
/** Local duplicate of IssueChatThread's module-private helper (same rule). */
|
|
function shouldImplicitlyReopenComment(
|
|
issueStatus: string | undefined,
|
|
assigneeValue: string,
|
|
) {
|
|
const resumesToTodo =
|
|
issueStatus === "done" ||
|
|
issueStatus === "cancelled" ||
|
|
issueStatus === "blocked";
|
|
return resumesToTodo && assigneeValue.startsWith("agent:");
|
|
}
|
|
|
|
function parseAssigneeValue(value: string): CommentReassignment | undefined {
|
|
if (!value) return { assigneeAgentId: null, assigneeUserId: null };
|
|
if (value.startsWith("agent:")) {
|
|
const id = value.slice("agent:".length);
|
|
return id ? { assigneeAgentId: id, assigneeUserId: null } : undefined;
|
|
}
|
|
if (value.startsWith("user:")) {
|
|
const id = value.slice("user:".length);
|
|
return id ? { assigneeAgentId: null, assigneeUserId: id } : undefined;
|
|
}
|
|
return undefined;
|
|
}
|
|
|
|
function escapeMarkdownLabel(name: string): string {
|
|
return name.replace(/[[\]]/g, "\\$&");
|
|
}
|
|
|
|
export function TaskChatComposer({
|
|
onAdd,
|
|
creation,
|
|
confirmedSubmissionIds,
|
|
onStop,
|
|
confirmedStoppedRunIds,
|
|
stopPending = false,
|
|
workMode,
|
|
onWorkModeChange,
|
|
disabled = false,
|
|
disabledReason,
|
|
placeholder,
|
|
onAttachImage,
|
|
onImageUpload,
|
|
mentions,
|
|
enableReassign = false,
|
|
conversationMode = false,
|
|
reassignOptions,
|
|
agentMap,
|
|
modelAgents,
|
|
companyId,
|
|
assigneeAdapterOverrides,
|
|
userProfileMap,
|
|
currentAssigneeValue = "",
|
|
suggestedAssigneeValue,
|
|
onPendingAssigneeChange,
|
|
issueStatus,
|
|
mobile = false,
|
|
draftKey,
|
|
queuedEdit = null,
|
|
onSaveQueuedEdit,
|
|
onCancelQueuedEdit,
|
|
pause = null,
|
|
takeover = null,
|
|
pendingTakeover = null,
|
|
runnerGoalCapability = null,
|
|
onRunnerGoalCommand,
|
|
onRunnerGoalReassign,
|
|
}: TaskChatComposerProps) {
|
|
const streamlined = useStreamlinedTaskChatPresentation();
|
|
const submitKey = useComposerSubmitKey();
|
|
const stopControl = useComposerStop(onStop, stopPending, confirmedStoppedRunIds);
|
|
const [localBody, setBody] = useState(() => (draftKey ? loadDraft(draftKey) : ""));
|
|
const body = creation ? creation.value : localBody;
|
|
const [submitting, setSubmitting] = useState(false);
|
|
const [uncertainSubmission, setUncertainSubmission] =
|
|
useState<ComposerDraftSubmission | null>(() =>
|
|
draftKey ? loadDraftSubmission(draftKey) : null,
|
|
);
|
|
const mountedTaskKey = useRef(draftKey);
|
|
useEffect(() => {
|
|
mountedTaskKey.current = draftKey;
|
|
setUncertainSubmission(draftKey ? loadDraftSubmission(draftKey) : null);
|
|
return () => {
|
|
mountedTaskKey.current = undefined;
|
|
};
|
|
}, [draftKey]);
|
|
const [takeoverBusy, setTakeoverBusy] = useState(false);
|
|
const [takeoverError, setTakeoverError] = useState<string | null>(null);
|
|
const [takeoverHeaderClaimed, setTakeoverHeaderClaimed] = useState(false);
|
|
const [takeoverHeaderSlot, setTakeoverHeaderSlot] =
|
|
useState<HTMLElement | null>(null);
|
|
const [takeoverControlsSlot, setTakeoverControlsSlot] =
|
|
useState<HTMLElement | null>(null);
|
|
const [pendingModeOverride, setPendingMode] = useState<IssueWorkMode | null>(null);
|
|
const modeChoiceGeneration = useRef(0);
|
|
const sentModeChoice = useRef<{ attemptId: string; generation: number } | null>(null);
|
|
const pendingMode = creation ? workMode : pendingModeOverride ?? workMode;
|
|
const [pendingAssignee, setPendingAssignee] = useState<string | null>(null);
|
|
const coordinator = useCoordinatorPresentation();
|
|
const [localRunSettings, setLocalRunSettings] = useState<ComposerRunSettings | null>(null);
|
|
const runSettings = creation ? creation.runSettings : localRunSettings;
|
|
const setRunSettings = creation ? creation.onRunSettingsChange : setLocalRunSettings;
|
|
useEffect(() => setLocalRunSettings(null), [draftKey, currentAssigneeValue]);
|
|
const [actionError, setActionError] = useState<string | null>(null);
|
|
const [attachments, setAttachmentState] = useState<ComposerAttachment[]>(
|
|
() =>
|
|
draftKey
|
|
? loadDraftAttachments(draftKey).map((item) => ({
|
|
...item,
|
|
id: `receipt:${item.attachmentId}`,
|
|
status: "attached",
|
|
}))
|
|
: [],
|
|
);
|
|
const attachmentsRef = useRef(attachments);
|
|
// Keep upload receipts durable while the optimistic message owns the preview.
|
|
// A rejected or uncertain send returns these same attachments to the draft.
|
|
const [sendingAttachmentIds, setSendingAttachmentIds] = useState<ReadonlySet<string> | null>(null);
|
|
function setAttachments(
|
|
update:
|
|
| ComposerAttachment[]
|
|
| ((previous: ComposerAttachment[]) => ComposerAttachment[]),
|
|
) {
|
|
const next =
|
|
typeof update === "function" ? update(attachmentsRef.current) : update;
|
|
attachmentsRef.current = next;
|
|
setAttachmentState(next);
|
|
const pending = pendingDraftRef.current;
|
|
if (pending && pending.draftKey === draftKey) {
|
|
saveDraftAttachments(pending.draftKey, next
|
|
.filter(item => item.status === "attached" && item.attachmentId)
|
|
.map(item => ({ ...item, inline: item.inline === true })), pending.attemptId);
|
|
}
|
|
}
|
|
const submittingRef = useRef(submitting);
|
|
submittingRef.current = submitting;
|
|
const pendingAssigneeRef = useRef(pendingAssignee);
|
|
pendingAssigneeRef.current = pendingAssignee;
|
|
const fileInputRef = useRef<HTMLInputElement | null>(null);
|
|
const editorRef = useRef<MarkdownEditorRef>(null);
|
|
const bodyRef = useRef(body);
|
|
bodyRef.current = body;
|
|
// Only the account that made a request may replay it.
|
|
const draftOwner = useDraftOwner();
|
|
const isCurrentAccount = useCurrentAccountGuard();
|
|
const pendingDraftRef = useRef<{
|
|
draftKey: string;
|
|
attemptId: string;
|
|
submittedBody: string;
|
|
submittedAttachmentIds: string[];
|
|
request: ComposerSendRequest;
|
|
requestOwner?: string;
|
|
} | null>(null);
|
|
const markRequestUnbound = useRequestOwnerBinding({
|
|
draftKey, owner: draftOwner, uncertainSubmission, setUncertainSubmission, pendingDraftRef,
|
|
});
|
|
function changeBody(value: string) {
|
|
bodyRef.current = value;
|
|
if (creation) {
|
|
creation.onChange(value);
|
|
return;
|
|
}
|
|
setBody(value);
|
|
const pending = pendingDraftRef.current;
|
|
if (!pending || pending.draftKey !== draftKey ||
|
|
loadDraftSubmission(pending.draftKey)?.attemptId !== pending.attemptId) return;
|
|
// Keep text typed during delivery durable too. Navigation may happen before
|
|
// either the request promise or the matching live server receipt arrives.
|
|
saveDraft(pending.draftKey,
|
|
value ? `${pending.submittedBody}\n\n${value}` : pending.submittedBody,
|
|
pending.attemptId);
|
|
saveDraftSubmission(pending.draftKey, {
|
|
attemptId: pending.attemptId, reviewed: false,
|
|
nextDraftOffset: pending.submittedBody.length + (value ? 2 : 0),
|
|
submittedAttachmentIds: pending.submittedAttachmentIds,
|
|
request: pending.request,
|
|
requestOwner: pending.requestOwner,
|
|
});
|
|
}
|
|
const draftTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
|
|
const queuedEditRef = useRef(queuedEdit);
|
|
queuedEditRef.current = queuedEdit;
|
|
const queuedEditBackupRef = useRef<QueuedEditBackup | null>(null);
|
|
const previousQueuedEditIdRef = useRef<string | null>(null);
|
|
|
|
useEffect(() => {
|
|
setTakeoverBusy(false);
|
|
setTakeoverError(null);
|
|
}, [takeover?.id]);
|
|
|
|
useEffect(() => {
|
|
const previousId = previousQueuedEditIdRef.current;
|
|
const nextEdit = queuedEdit;
|
|
const nextId = nextEdit?.commentId ?? null;
|
|
// A save error belongs to the edit that produced it.
|
|
if (previousId !== nextId) setActionError(null);
|
|
|
|
if (nextEdit && previousId !== nextId) {
|
|
if (!queuedEditBackupRef.current) {
|
|
queuedEditBackupRef.current = {
|
|
body: bodyRef.current,
|
|
attachments: attachmentsRef.current,
|
|
pendingMode: pendingModeOverride,
|
|
pendingAssignee: pendingAssigneeRef.current,
|
|
};
|
|
if (draftKey) saveDraft(draftKey, bodyRef.current);
|
|
}
|
|
if (draftTimer.current) {
|
|
clearTimeout(draftTimer.current);
|
|
draftTimer.current = null;
|
|
}
|
|
bodyRef.current = nextEdit.body;
|
|
setBody(nextEdit.body);
|
|
setAttachments([]);
|
|
requestAnimationFrame(() => editorRef.current?.focus());
|
|
} else if (!nextId && previousId) {
|
|
const backup = queuedEditBackupRef.current;
|
|
if (backup) {
|
|
bodyRef.current = backup.body;
|
|
setBody(backup.body);
|
|
setAttachments(backup.attachments);
|
|
setPendingMode(backup.pendingMode);
|
|
setPendingAssignee(backup.pendingAssignee);
|
|
if (draftKey) saveDraft(draftKey, backup.body);
|
|
}
|
|
queuedEditBackupRef.current = null;
|
|
requestAnimationFrame(() => editorRef.current?.focus());
|
|
}
|
|
|
|
previousQueuedEditIdRef.current = nextId;
|
|
}, [draftKey, pendingModeOverride, queuedEdit]);
|
|
|
|
useEffect(() => {
|
|
if (!draftKey || queuedEdit) return;
|
|
bodyRef.current = loadDraft(draftKey);
|
|
setBody(bodyRef.current);
|
|
}, [draftKey, queuedEdit]);
|
|
|
|
useEffect(() => {
|
|
if (!draftKey) return;
|
|
setAttachments(
|
|
loadDraftAttachments(draftKey).map((item) => ({
|
|
...item,
|
|
id: `receipt:${item.attachmentId}`,
|
|
status: "attached",
|
|
})),
|
|
);
|
|
}, [draftKey]);
|
|
|
|
useEffect(() => {
|
|
if (
|
|
!draftKey ||
|
|
queuedEdit ||
|
|
submitting ||
|
|
uncertainSubmission ||
|
|
attachments !== attachmentsRef.current
|
|
)
|
|
return;
|
|
saveDraftAttachments(
|
|
draftKey,
|
|
attachments
|
|
.filter((item) => item.status === "attached" && item.attachmentId)
|
|
.map((item) => ({
|
|
attachmentId: item.attachmentId,
|
|
name: item.name,
|
|
size: item.size,
|
|
inline: item.inline === true,
|
|
contentType: item.contentType,
|
|
contentPath: item.contentPath,
|
|
})),
|
|
);
|
|
}, [attachments, draftKey, queuedEdit, submitting]);
|
|
|
|
useEffect(() => {
|
|
if (!draftKey || queuedEdit || submitting) {
|
|
if (draftTimer.current) {
|
|
clearTimeout(draftTimer.current);
|
|
draftTimer.current = null;
|
|
}
|
|
return;
|
|
}
|
|
if (draftTimer.current) clearTimeout(draftTimer.current);
|
|
draftTimer.current = setTimeout(() => {
|
|
saveDraft(draftKey, body);
|
|
}, DRAFT_DEBOUNCE_MS);
|
|
}, [body, draftKey, queuedEdit, submitting]);
|
|
|
|
useEffect(() => {
|
|
return () => {
|
|
if (draftTimer.current) clearTimeout(draftTimer.current);
|
|
if (draftKey && !queuedEditRef.current && !submittingRef.current)
|
|
saveDraft(draftKey, bodyRef.current);
|
|
};
|
|
}, [draftKey]);
|
|
|
|
useEffect(() => {
|
|
if (!draftKey) return;
|
|
const flushDraft = () => {
|
|
if (!queuedEditRef.current && !submittingRef.current)
|
|
saveDraft(draftKey, bodyRef.current);
|
|
};
|
|
window.addEventListener("beforeunload", flushDraft);
|
|
return () => window.removeEventListener("beforeunload", flushDraft);
|
|
}, [draftKey]);
|
|
|
|
const canAcceptFiles =
|
|
!pause &&
|
|
!queuedEdit &&
|
|
!uncertainSubmission &&
|
|
Boolean(creation || onAttachImage || onImageUpload);
|
|
const showAssignee = Boolean(
|
|
enableReassign && reassignOptions && reassignOptions.length > 0,
|
|
);
|
|
const assigneeValue = creation || conversationMode ? currentAssigneeValue : pendingAssignee ?? suggestedAssigneeValue ?? currentAssigneeValue;
|
|
const showConversationModel = coordinator && conversationMode && supportsComposerModel(modelAgents?.get(assigneeValue.slice(6)));
|
|
const assigneeLabel =
|
|
reassignOptions?.find((o) => o.id === assigneeValue)?.label ?? "Unassigned";
|
|
const assigneeName =
|
|
assigneeLabel === "Unassigned" ? "the agent" : assigneeLabel;
|
|
const effectivePlaceholder = queuedEdit
|
|
? "Edit queued message…"
|
|
: (placeholder ?? modePlaceholder(pendingMode, assigneeName, mobile));
|
|
const planCommandOption: ActionCommandOption = {
|
|
id: "action:plan",
|
|
kind: "action",
|
|
command: "plan",
|
|
name: "Plan",
|
|
description: "Plan before acting. Nothing changes until you accept the plan.",
|
|
aliases: ["plan", "planning"],
|
|
};
|
|
const goalUnavailable = runnerGoalCapability?.availability !== "available";
|
|
const goalCommandOption: ActionCommandOption = {
|
|
id: "action:goal",
|
|
kind: "action",
|
|
command: "goal",
|
|
name: "Goal",
|
|
description:
|
|
!runnerGoalCapability || runnerGoalCapability.verified === false
|
|
? "Support will be verified when the session starts."
|
|
: "Pursue work across turns.",
|
|
aliases: ["goal", "pursue", "continue"],
|
|
disabled: goalUnavailable && runnerGoalCapability !== null,
|
|
disabledReason:
|
|
runnerGoalCapability?.reason ??
|
|
"Session goals are unsupported by this agent.",
|
|
};
|
|
|
|
function updatePendingAssignee(value: string | null) {
|
|
if (!creation && value && companyId) {
|
|
const selection = parseAssigneeValue(value);
|
|
if (selection?.assigneeAgentId) trackRecentAssignee(selection.assigneeAgentId, companyId);
|
|
if (selection?.assigneeUserId) trackRecentAssigneeUser(selection.assigneeUserId, companyId);
|
|
}
|
|
setPendingAssignee(value);
|
|
onPendingAssigneeChange?.(value);
|
|
}
|
|
|
|
function changeMode(mode: IssueWorkMode) {
|
|
modeChoiceGeneration.current += 1;
|
|
setPendingMode(mode);
|
|
if (creation) void onWorkModeChange?.(mode);
|
|
}
|
|
|
|
function settleSentMode(attemptId: string) {
|
|
const choice = sentModeChoice.current;
|
|
if (choice?.attemptId !== attemptId) return;
|
|
if (modeChoiceGeneration.current === choice.generation) setPendingMode(null);
|
|
sentModeChoice.current = null;
|
|
}
|
|
|
|
async function uploadImage(file: File): Promise<string> {
|
|
const id = createUuid();
|
|
setAttachments((prev) => [
|
|
...prev,
|
|
{
|
|
id,
|
|
name: file.name,
|
|
size: file.size,
|
|
contentType: file.type,
|
|
file,
|
|
status: "uploading",
|
|
},
|
|
]);
|
|
try {
|
|
const attachment = onAttachImage ? await onAttachImage(file) : undefined;
|
|
const url = onAttachImage
|
|
? attachment?.contentPath
|
|
: await onImageUpload?.(file);
|
|
if (!url) throw new Error("Upload did not return a file URL");
|
|
if (!attachmentsRef.current.some((item) => item.id === id))
|
|
throw new Error("Attachment was removed");
|
|
setAttachments((prev) =>
|
|
prev.map((item) =>
|
|
item.id === id
|
|
? {
|
|
...item,
|
|
attachmentId: attachment?.id,
|
|
contentPath: url,
|
|
status: "attached",
|
|
}
|
|
: item,
|
|
),
|
|
);
|
|
return url;
|
|
} catch (err) {
|
|
setAttachments((prev) =>
|
|
prev.map((item) =>
|
|
item.id === id
|
|
? {
|
|
...item,
|
|
status: "error",
|
|
error: describeError(err, { action: "upload the file" }).body,
|
|
file,
|
|
}
|
|
: item,
|
|
),
|
|
);
|
|
throw err;
|
|
}
|
|
}
|
|
|
|
/** Non-image files: attach to the task and track in the chip row. */
|
|
async function attachNonImageFile(file: File) {
|
|
const id = `${file.name}:${file.size}:${file.lastModified}:${Math.random().toString(36).slice(2)}`;
|
|
setAttachments((prev) => [
|
|
...prev,
|
|
{ id, name: file.name, size: file.size, contentType: file.type, status: "uploading" },
|
|
]);
|
|
try {
|
|
if (!onAttachImage) {
|
|
setAttachments((prev) =>
|
|
prev.map((item) =>
|
|
item.id === id
|
|
? {
|
|
...item,
|
|
status: "error",
|
|
error: "This file type cannot be attached here",
|
|
}
|
|
: item,
|
|
),
|
|
);
|
|
return;
|
|
}
|
|
const attachment = await onAttachImage(file);
|
|
if (!attachment?.contentPath)
|
|
throw new Error("Upload did not return a file URL");
|
|
const name = attachment?.originalFilename ?? file.name;
|
|
setAttachments((prev) =>
|
|
prev.map((item) =>
|
|
item.id === id
|
|
? {
|
|
...item,
|
|
name,
|
|
attachmentId: attachment?.id,
|
|
status: "attached",
|
|
contentPath: attachment?.contentPath,
|
|
}
|
|
: item,
|
|
),
|
|
);
|
|
} catch (err) {
|
|
setAttachments((prev) =>
|
|
prev.map((item) =>
|
|
item.id === id
|
|
? {
|
|
...item,
|
|
status: "error",
|
|
error: describeError(err, { action: "upload the file" }).body,
|
|
file,
|
|
}
|
|
: item,
|
|
),
|
|
);
|
|
}
|
|
}
|
|
|
|
/** Retry a failed upload from its kept file; only ever on an explicit click. */
|
|
function retryUpload(attachment: ComposerAttachment) {
|
|
const file = attachment.file;
|
|
if (!file) return;
|
|
setAttachments((prev) => prev.filter((item) => item.id !== attachment.id));
|
|
void attachPickedFile(file);
|
|
}
|
|
|
|
async function attachPickedFile(file: File) {
|
|
if (!file.type.startsWith("image/")) {
|
|
await attachNonImageFile(file);
|
|
return;
|
|
}
|
|
await uploadImage(file).catch(() => undefined);
|
|
}
|
|
|
|
function handleFileInputChange(evt: ChangeEvent<HTMLInputElement>) {
|
|
const files = evt.target.files;
|
|
if (files && files.length > 0) {
|
|
if (creation) {
|
|
creation.onSelectFiles(Array.from(files));
|
|
evt.target.value = "";
|
|
return;
|
|
}
|
|
void (async () => {
|
|
for (const file of Array.from(files)) await attachPickedFile(file);
|
|
})();
|
|
}
|
|
evt.target.value = "";
|
|
}
|
|
|
|
function prepareGoal() {
|
|
const current = bodyRef.current.trim();
|
|
changeBody(/^\/goal(?:\s|$)/.test(current) ? current : `/goal ${current}`);
|
|
setActionError(null);
|
|
requestAnimationFrame(() => editorRef.current?.focus());
|
|
}
|
|
|
|
function handlePasteCapture(evt: ReactClipboardEvent<HTMLDivElement>) {
|
|
if (!canAcceptFiles || disabled || creation?.readOnly) return;
|
|
const files = Array.from(evt.clipboardData?.files ?? []);
|
|
if (files.length === 0) return;
|
|
evt.preventDefault();
|
|
evt.stopPropagation();
|
|
if (creation) {
|
|
creation.onSelectFiles(files);
|
|
return;
|
|
}
|
|
for (const file of files) void attachPickedFile(file);
|
|
}
|
|
|
|
function isImage(item: ComposerAttachment) {
|
|
return isImageAttachment({ name: item.name, url: item.contentPath ?? "", contentType: item.contentType });
|
|
}
|
|
|
|
const attachedRefs = attachments.filter(
|
|
(item) => item.status === "attached" && item.contentPath && !item.inline,
|
|
);
|
|
const draftAttachments = attachments.filter(item => !sendingAttachmentIds?.has(item.id));
|
|
const imageAttachments = draftAttachments.filter(item => isImage(item) && !item.inline);
|
|
const visibleAttachments = draftAttachments.filter(
|
|
(item) => (!item.inline || item.status !== "attached") && !isImage(item),
|
|
);
|
|
// Sending mid-upload would silently drop the pending file from the comment;
|
|
// sending past a failed chip would discard the file the user selected and
|
|
// clear its error state, so both hold submission until resolved or removed.
|
|
const showStop =
|
|
!queuedEdit &&
|
|
!submitting &&
|
|
body.trim().length === 0 &&
|
|
attachments.length === 0 &&
|
|
Boolean(onStop || stopControl.stopping);
|
|
const uploadPending = attachments.some((item) => item.status === "uploading");
|
|
const uploadFailed = attachments.some((item) => item.status === "error");
|
|
const takeoverVisible = Boolean(takeover && !pause);
|
|
const previousTakeoverVisibleRef = useRef(takeoverVisible);
|
|
useEffect(() => {
|
|
if (previousTakeoverVisibleRef.current && !takeoverVisible && !queuedEdit) {
|
|
requestAnimationFrame(() => editorRef.current?.focus());
|
|
}
|
|
previousTakeoverVisibleRef.current = takeoverVisible;
|
|
}, [queuedEdit, takeoverVisible]);
|
|
|
|
const canResetPausedConversation = conversationMode && !queuedEdit && body.trim() === "/new" && attachments.length === 0;
|
|
|
|
async function submit() {
|
|
if (disabled || (pause && !canResetPausedConversation)) return;
|
|
if (creation) {
|
|
// Only a composer that offers Plan mode reads /plan; elsewhere it stays text.
|
|
const plan = onWorkModeChange
|
|
? planSubmission(bodyRef.current, Boolean(creation.canSubmitWithoutBody && creation.images?.length))
|
|
: ({ kind: "none" } as const);
|
|
if (plan.kind === "switch_mode" && !submittingRef.current) {
|
|
changeMode("planning");
|
|
creation.onChange("");
|
|
editorRef.current?.clear();
|
|
return;
|
|
}
|
|
if (submittingRef.current || uploadPending || uploadFailed || creation.submitDisabled || (!bodyRef.current.trim() && !creation.canSubmitWithoutBody)) return;
|
|
submittingRef.current = true;
|
|
setSubmitting(true);
|
|
setActionError(null);
|
|
try {
|
|
await creation.onSubmit(plan.kind === "send" ? plan.text : bodyRef.current, plan.kind === "send" ? "planning" : pendingMode, runSettings);
|
|
} catch (error) {
|
|
setActionError(describeError(error, { action: "create the task" }).body);
|
|
} finally {
|
|
submittingRef.current = false;
|
|
setSubmitting(false);
|
|
}
|
|
return;
|
|
}
|
|
if (!onAdd) return;
|
|
const retained =
|
|
draftKey && !queuedEdit ? loadDraftSubmission(draftKey) : null;
|
|
if (retained && !submitting) {
|
|
setUncertainSubmission(retained);
|
|
return;
|
|
}
|
|
const submittedBody = bodyRef.current;
|
|
const submittedAttachments = attachmentsRef.current;
|
|
const submittedAssignee = pendingAssigneeRef.current;
|
|
const submittedModeGeneration = modeChoiceGeneration.current;
|
|
// Plan mode belongs to tasks; a queued edit keeps its exact text.
|
|
const planCommand = queuedEdit || conversationMode || !onWorkModeChange
|
|
? ({ kind: "none" } as const)
|
|
: planSubmission(submittedBody, attachedRefs.length > 0);
|
|
if (planCommand.kind === "switch_mode") {
|
|
changeMode("planning");
|
|
bodyRef.current = "";
|
|
if (draftKey) clearDraft(draftKey);
|
|
setBody("");
|
|
editorRef.current?.clear();
|
|
return;
|
|
}
|
|
const sendMode = planCommand.kind === "send" ? "planning" : pendingMode;
|
|
const trimmed = planCommand.kind === "send" ? planCommand.text : submittedBody.trim();
|
|
const goalCommand = queuedEdit
|
|
? ({ matched: false } as const)
|
|
: parseRunnerGoalCommand(submittedBody);
|
|
if (goalCommand.matched && conversationMode) {
|
|
setActionError("Create a separate task for work that needs an ongoing execution goal.");
|
|
return;
|
|
}
|
|
if (goalCommand.matched) {
|
|
if ("error" in goalCommand) {
|
|
setActionError(goalCommand.error);
|
|
return;
|
|
}
|
|
if (attachmentsRef.current.length > 0) {
|
|
setActionError("Remove attachments before using /goal.");
|
|
return;
|
|
}
|
|
if (!onRunnerGoalCommand) {
|
|
setActionError(
|
|
runnerGoalCapability?.reason ??
|
|
"Session goals are unsupported by this agent.",
|
|
);
|
|
return;
|
|
}
|
|
if (
|
|
runnerGoalCapability &&
|
|
runnerGoalCapability.availability !== "available"
|
|
) {
|
|
setActionError(
|
|
runnerGoalCapability.reason ??
|
|
"Session goals are unsupported by this agent.",
|
|
);
|
|
return;
|
|
}
|
|
try {
|
|
const hasReassignment =
|
|
showAssignee && assigneeValue !== currentAssigneeValue;
|
|
if (hasReassignment && goalCommand.command.action !== "focus") {
|
|
const reassignment = parseAssigneeValue(assigneeValue);
|
|
if (!reassignment?.assigneeAgentId || !onRunnerGoalReassign) {
|
|
setActionError("Select an agent before starting a session goal.");
|
|
return;
|
|
}
|
|
await onRunnerGoalReassign(reassignment);
|
|
updatePendingAssignee(null);
|
|
}
|
|
await onRunnerGoalCommand(goalCommand.command);
|
|
setActionError(null);
|
|
bodyRef.current = "";
|
|
if (draftTimer.current) clearTimeout(draftTimer.current);
|
|
draftTimer.current = null;
|
|
if (draftKey) clearDraft(draftKey);
|
|
setBody("");
|
|
editorRef.current?.clear();
|
|
} catch (error) {
|
|
setActionError(
|
|
error instanceof Error
|
|
? error.message
|
|
: "The goal action could not be applied.",
|
|
);
|
|
}
|
|
return;
|
|
}
|
|
if (
|
|
(!trimmed && attachedRefs.length === 0) ||
|
|
uploadPending ||
|
|
uploadFailed ||
|
|
submitting ||
|
|
uncertainSubmission ||
|
|
disabled
|
|
)
|
|
return;
|
|
|
|
const refLines = attachedRefs
|
|
.map((item) => `${isImage(item) ? "!" : ""}[${escapeMarkdownLabel(item.name)}](${item.contentPath})`)
|
|
.join("\n");
|
|
// A queued edit must preserve the complete Markdown source. Normal sends
|
|
// keep the longstanding trimmed-body behavior.
|
|
const fullBody = queuedEdit
|
|
? submittedBody
|
|
: [trimmed, refLines].filter(Boolean).join("\n\n");
|
|
const hasReassignment =
|
|
showAssignee && assigneeValue !== currentAssigneeValue;
|
|
const reassignment = hasReassignment
|
|
? parseAssigneeValue(assigneeValue)
|
|
: undefined;
|
|
const reopen = shouldImplicitlyReopenComment(issueStatus, assigneeValue)
|
|
? true
|
|
: undefined;
|
|
|
|
// The thread renders the outgoing comment optimistically, so remove its
|
|
// text from the composer at the same time. The editor remains writable for
|
|
// the next draft while the request is pending.
|
|
bodyRef.current = "";
|
|
if (draftTimer.current) {
|
|
clearTimeout(draftTimer.current);
|
|
draftTimer.current = null;
|
|
}
|
|
if (draftKey && !queuedEdit) {
|
|
if (
|
|
submittedAttachments.some(
|
|
(item) => item.status === "attached" && item.attachmentId,
|
|
)
|
|
)
|
|
saveDraft(draftKey, submittedBody);
|
|
else clearDraft(draftKey);
|
|
}
|
|
setBody("");
|
|
setSendingAttachmentIds(new Set(submittedAttachments.map(item => item.id)));
|
|
setSubmitting(true);
|
|
let attemptId: string | null = null;
|
|
let request: ComposerSendRequest | null = null;
|
|
const requestOwner = draftOwner;
|
|
try {
|
|
if (queuedEdit) {
|
|
if (!onSaveQueuedEdit) return;
|
|
setActionError(null);
|
|
try {
|
|
await onSaveQueuedEdit(queuedEdit.commentId, fullBody);
|
|
} catch (error) {
|
|
// A rejected edit keeps its text below; say why it was not saved.
|
|
if (mountedTaskKey.current === draftKey && queuedEditRef.current?.commentId === queuedEdit.commentId)
|
|
setActionError(describeError(error, { action: "save this queued message" }).body);
|
|
throw error;
|
|
}
|
|
onCancelQueuedEdit?.();
|
|
return;
|
|
}
|
|
if (sendMode !== workMode && onWorkModeChange) {
|
|
await onWorkModeChange(sendMode);
|
|
}
|
|
const retainedAfterMode = draftKey ? loadDraftSubmission(draftKey) : null;
|
|
if (retainedAfterMode) {
|
|
setUncertainSubmission(retainedAfterMode);
|
|
setBody(submittedBody);
|
|
return;
|
|
}
|
|
attemptId = createUuid();
|
|
if (requestOwner === undefined) markRequestUnbound(attemptId);
|
|
// IDs come only from this composer's upload receipts, never from parsing
|
|
// arbitrary Markdown. A removed inline image no longer selects its receipt.
|
|
const attachmentIds = [
|
|
...new Set(
|
|
submittedAttachments
|
|
.filter(
|
|
(item) =>
|
|
item.status === "attached" &&
|
|
item.attachmentId &&
|
|
(!item.inline ||
|
|
(item.contentPath &&
|
|
submittedBody.includes(item.contentPath))),
|
|
)
|
|
.map((item) => item.attachmentId!),
|
|
),
|
|
];
|
|
// The exact request is stored before it is sent, so a lost response or
|
|
// an outage can resend it with the same ID instead of losing it.
|
|
request = {
|
|
body: fullBody,
|
|
...(reopen === undefined ? {} : { reopen }),
|
|
...(reassignment ? { reassignment } : {}),
|
|
...(attachmentIds.length ? { attachmentIds } : {}),
|
|
...(runSettings ? { runSettings: runSettings as unknown as Record<string, unknown> } : {}),
|
|
};
|
|
if (draftKey) {
|
|
saveDraft(draftKey, submittedBody);
|
|
saveDraftSubmission(draftKey, { attemptId, reviewed: false, request, requestOwner });
|
|
pendingDraftRef.current = { draftKey, attemptId, submittedBody, submittedAttachmentIds: attachmentIds, request, requestOwner };
|
|
changeBody(bodyRef.current);
|
|
}
|
|
sentModeChoice.current = { attemptId, generation: submittedModeGeneration };
|
|
if (runSettings) {
|
|
await onAdd(fullBody, reopen, reassignment, attachmentIds.length ? attachmentIds : undefined, attemptId, runSettings);
|
|
} else {
|
|
await onAdd(fullBody, reopen, reassignment, attachmentIds.length ? attachmentIds : undefined, attemptId);
|
|
}
|
|
// Navigation does not invalidate the server receipt. Settle the captured
|
|
// task before checking whether this composer is still on screen.
|
|
if (draftKey) settleDraftSubmission(draftKey, attemptId,
|
|
mountedTaskKey.current === draftKey ? bodyRef.current : undefined);
|
|
if (mountedTaskKey.current !== draftKey) return;
|
|
settleSentMode(attemptId);
|
|
const submittedIds = new Set(submittedAttachments.map((item) => item.id));
|
|
setAttachments((current) =>
|
|
current.filter((item) => !submittedIds.has(item.id)),
|
|
);
|
|
if (pendingAssigneeRef.current === submittedAssignee) {
|
|
updatePendingAssignee(null);
|
|
}
|
|
setRunSettings(null);
|
|
} catch (error) {
|
|
if (mountedTaskKey.current !== draftKey) return;
|
|
const nextDraft = bodyRef.current;
|
|
// Not delivered, or not known to be: keep it and resend with the same
|
|
// ID when the connection allows. The server dedupes by that ID.
|
|
if (attemptId && request && classifySendFailure(error) === "pending") {
|
|
const uncertain = {
|
|
attemptId, reviewed: false,
|
|
nextDraftOffset: submittedBody.length + (nextDraft ? 2 : 0),
|
|
submittedAttachmentIds: submittedAttachments.flatMap(item => item.attachmentId ? [item.attachmentId] : []),
|
|
request,
|
|
requestOwner,
|
|
};
|
|
setUncertainSubmission(uncertain);
|
|
if (draftKey && loadDraftSubmission(draftKey)?.attemptId === attemptId)
|
|
saveDraftSubmission(draftKey, uncertain);
|
|
} else if (draftKey && attemptId)
|
|
clearDraftSubmission(draftKey, attemptId);
|
|
// Restore the failed message for retry without discarding a next draft
|
|
// that was entered while the request was pending.
|
|
const restoredBody = nextDraft
|
|
? `${submittedBody}\n\n${nextDraft}`
|
|
: submittedBody;
|
|
bodyRef.current = restoredBody;
|
|
if (draftTimer.current) {
|
|
clearTimeout(draftTimer.current);
|
|
draftTimer.current = null;
|
|
}
|
|
if (draftKey) saveDraft(draftKey, restoredBody, attemptId ?? undefined);
|
|
setBody(restoredBody);
|
|
} finally {
|
|
if (pendingDraftRef.current?.attemptId === attemptId) pendingDraftRef.current = null;
|
|
setSendingAttachmentIds(null);
|
|
setSubmitting(false);
|
|
}
|
|
}
|
|
|
|
/** A confirmed receipt for the retained send: drop its text, keep any next draft. */
|
|
const settledSubmissionIds = useRef(new Set<string>());
|
|
function settleUncertainSubmission(submission: ComposerDraftSubmission) {
|
|
const settlementKey = JSON.stringify([draftKey, submission.attemptId]);
|
|
if (settledSubmissionIds.current.has(settlementKey)) return;
|
|
settledSubmissionIds.current.add(settlementKey);
|
|
settleSentMode(submission.attemptId);
|
|
const nextDraft = submission.nextDraftOffset === undefined
|
|
? "" : bodyRef.current.slice(submission.nextDraftOffset);
|
|
if (draftKey) settleDraftSubmission(draftKey, submission.attemptId, nextDraft);
|
|
setUncertainSubmission(null);
|
|
setActionError(null);
|
|
bodyRef.current = nextDraft;
|
|
setBody(nextDraft);
|
|
const submittedIds = submission.submittedAttachmentIds;
|
|
setAttachments(current => submittedIds
|
|
? current.filter(item => !item.attachmentId || !submittedIds.includes(item.attachmentId))
|
|
: []);
|
|
}
|
|
|
|
useEffect(() => {
|
|
if (!uncertainSubmission || !confirmedSubmissionIds?.has(uncertainSubmission.attemptId)) return;
|
|
settleUncertainSubmission(uncertainSubmission);
|
|
}, [confirmedSubmissionIds, draftKey, uncertainSubmission]);
|
|
|
|
async function resendUncertainSubmission(): Promise<SendOutcome> {
|
|
if (!isCurrentAccount()) return "pending";
|
|
const submission = uncertainSubmission;
|
|
const request = replayableRequest(submission, draftOwner);
|
|
if (!submission || !request || !onAdd) return "rejected";
|
|
const taskKey = draftKey;
|
|
const args = [
|
|
request.body,
|
|
request.reopen,
|
|
request.reassignment,
|
|
request.attachmentIds,
|
|
submission.attemptId,
|
|
] as const;
|
|
try {
|
|
if (request.runSettings) await onAdd(...args, request.runSettings as unknown as ComposerRunSettings);
|
|
else await onAdd(...args);
|
|
} catch (error) {
|
|
if (!isCurrentAccount()) return "pending";
|
|
const failure = classifySendFailure(error);
|
|
if (settledSubmissionIds.current.has(JSON.stringify([taskKey, submission.attemptId]))) return failure;
|
|
if (failure === "rejected") {
|
|
// A definitive answer: the text is already back in the editor.
|
|
if (taskKey) clearDraftSubmission(taskKey, submission.attemptId);
|
|
if (mountedTaskKey.current === taskKey) {
|
|
setUncertainSubmission(null);
|
|
setActionError(describeError(error, { action: "send this message" }).body);
|
|
}
|
|
}
|
|
return failure;
|
|
}
|
|
if (mountedTaskKey.current === taskKey) settleUncertainSubmission(submission);
|
|
else if (taskKey) settleDraftSubmission(taskKey, submission.attemptId);
|
|
return "sent";
|
|
}
|
|
|
|
const resendSourceId = useId();
|
|
const autoResend = useAutoResend({
|
|
sourceId: `task-chat-composer:${resendSourceId}`,
|
|
active: Boolean(replayableRequest(uncertainSubmission, draftOwner)) && !submitting,
|
|
resend: resendUncertainSubmission,
|
|
});
|
|
|
|
/** Stop resending; the text stays in the editor to edit or send again. */
|
|
function cancelUncertainSubmission() {
|
|
if (!uncertainSubmission) return;
|
|
settledSubmissionIds.current.add(JSON.stringify([draftKey, uncertainSubmission.attemptId]));
|
|
if (draftKey) clearDraftSubmission(draftKey, uncertainSubmission.attemptId);
|
|
setUncertainSubmission(null);
|
|
}
|
|
|
|
function skipTakeover() {
|
|
if (!takeover) return;
|
|
setTakeoverBusy(true);
|
|
setTakeoverError(null);
|
|
Promise.resolve(takeover.onSkip()).catch((cause) => {
|
|
setTakeoverBusy(false);
|
|
setTakeoverError(
|
|
cause instanceof Error
|
|
? cause.message
|
|
: "This request could not be skipped.",
|
|
);
|
|
});
|
|
}
|
|
|
|
const takeoverSkipButton = takeover ? (
|
|
<Button
|
|
type="button"
|
|
size="sm"
|
|
variant="outline"
|
|
disabled={takeoverBusy}
|
|
onClick={skipTakeover}
|
|
>
|
|
{takeoverBusy ? (
|
|
<Loader2 className="h-4 w-4 animate-spin" aria-hidden />
|
|
) : null}
|
|
Skip
|
|
</Button>
|
|
) : null;
|
|
|
|
if (pause && (!conversationMode || queuedEdit)) {
|
|
return <TaskChatPausedTakeover {...pause} hasDraft={Boolean(body.trim() || attachments.length)} />;
|
|
}
|
|
|
|
return (
|
|
<div className={cn("flex min-w-0 flex-col", creation?.contextBar ? "gap-0" : "gap-2")}>
|
|
<ComposerFileDropTarget
|
|
enabled={canAcceptFiles && !disabled && !submitting && !creation?.readOnly}
|
|
newTask={Boolean(creation)}
|
|
onFiles={(files) => {
|
|
if (creation) creation.onSelectFiles(files);
|
|
else for (const file of files) void attachPickedFile(file);
|
|
}}
|
|
/>
|
|
{takeoverVisible && takeover ? (
|
|
<section
|
|
className={cn(
|
|
"relative rounded-xl border border-border bg-card p-(--sz-18px) shadow-sm",
|
|
mobile ? "overflow-visible" : "max-h-(--tc-interaction-card-max-h) overflow-y-auto scrollbar-auto-hide",
|
|
)}
|
|
aria-label={takeover.label}
|
|
data-testid="task-chat-composer-takeover"
|
|
>
|
|
<div
|
|
className={cn(
|
|
"flex min-w-0 items-center gap-2",
|
|
takeover.hideLabel && takeover.pendingCount === 1
|
|
? "absolute right-0 top-0 z-10"
|
|
: "mb-3",
|
|
)}
|
|
data-testid="task-chat-composer-takeover-header"
|
|
>
|
|
<div className="min-w-0 flex-1">
|
|
{!takeoverHeaderClaimed && !takeover.hideLabel ? (
|
|
<strong className="block truncate text-sm font-medium text-foreground">
|
|
{takeover.label}
|
|
</strong>
|
|
) : null}
|
|
<div
|
|
ref={setTakeoverHeaderSlot}
|
|
className="flex min-w-0 items-center"
|
|
data-testid="task-chat-composer-takeover-title-slot"
|
|
/>
|
|
</div>
|
|
<div className="ml-auto flex shrink-0 items-center gap-1">
|
|
{takeover.pendingCount > 1 ? (
|
|
<Button type="button" size="sm" variant="ghost" className="h-7 px-2" onClick={takeover.onShowNext}>
|
|
{takeover.pendingCount} pending
|
|
</Button>
|
|
) : null}
|
|
<div ref={setTakeoverControlsSlot} className="flex shrink-0 items-center" data-testid="task-chat-composer-takeover-controls-slot" />
|
|
<Button type="button" size="icon-xs" variant="ghost" className="text-muted-foreground hover:text-foreground"
|
|
aria-label={`Dismiss ${takeover.label}`} disabled={takeoverBusy} onClick={takeover.onDismiss}>
|
|
<X aria-hidden />
|
|
</Button>
|
|
</div>
|
|
</div>
|
|
<div className={takeover.hideLabel && takeover.pendingCount === 1 ? "pr-8" : "pr-1"}
|
|
data-testid="task-chat-composer-takeover-body">
|
|
<TaskChatComposerTakeoverActionsContext.Provider
|
|
value={{
|
|
skipButton: takeover.inlineSkip && !takeover.hideSkip && takeoverSkipButton ? takeoverSkipButton : null,
|
|
dismiss: takeover.onDismiss,
|
|
headerSlot: takeoverHeaderSlot,
|
|
controlsSlot: takeoverControlsSlot,
|
|
setHeaderClaimed: setTakeoverHeaderClaimed,
|
|
}}
|
|
>
|
|
{takeover.content}
|
|
</TaskChatComposerTakeoverActionsContext.Provider>
|
|
</div>
|
|
{takeoverError ? <p className="mt-2 text-sm text-destructive" role="alert">{takeoverError}</p> : null}
|
|
{!takeover.inlineSkip && !takeover.hideSkip ? (
|
|
<div className="mt-3 flex items-center justify-end gap-2">{takeoverSkipButton}</div>
|
|
) : null}
|
|
</section>
|
|
) : null}
|
|
{creation?.contextBar ? (
|
|
<TaskChatComposerBar
|
|
className="flex h-11 min-w-0 items-center gap-2 px-2.5"
|
|
data-testid="task-chat-composer-context"
|
|
role="group"
|
|
aria-label="Task project and worktrees"
|
|
>
|
|
{creation.contextBar}
|
|
</TaskChatComposerBar>
|
|
) : null}
|
|
<div
|
|
data-editor-autocomplete-anchor=""
|
|
className={taskChatComposerSurfaceClasses(mobile, streamlined)}
|
|
onKeyDownCapture={(e) => {
|
|
// Capture mode shortcuts on the wrapper so they work while the rich
|
|
// editor is focused and win over Lexical/browser bindings. Match the
|
|
// period by key and code because hardware keyboards on iOS can omit
|
|
// `code` for Cmd+Period.
|
|
if (disabled || queuedEdit) return;
|
|
const isPeriod = e.key === "." || e.code === "Period";
|
|
const isModeShortcut =
|
|
(isPeriod && (e.metaKey || e.ctrlKey)) ||
|
|
(e.key === "Tab" && e.shiftKey);
|
|
if (isModeShortcut) {
|
|
e.preventDefault();
|
|
e.stopPropagation();
|
|
changeMode(nextWorkMode(pendingMode));
|
|
}
|
|
}}
|
|
onPasteCapture={handlePasteCapture}
|
|
>
|
|
{creation?.header}
|
|
{uncertainSubmission ? (
|
|
<PendingSendNotice
|
|
className="mb-3"
|
|
noun="message"
|
|
persisted={Boolean(draftKey && loadDraftSubmission(draftKey)?.attemptId === uncertainSubmission.attemptId && replayableRequest(loadDraftSubmission(draftKey), draftOwner))}
|
|
resending={autoResend.resending}
|
|
stalled={autoResend.stalled}
|
|
onResendNow={replayableRequest(uncertainSubmission, draftOwner) ? autoResend.resendNow : undefined}
|
|
onCancel={cancelUncertainSubmission}
|
|
/>
|
|
) : null}
|
|
{!takeoverVisible && (pendingTakeover || takeover) ? (
|
|
<button
|
|
type="button"
|
|
className="mb-2 flex w-full items-center gap-2 rounded-md bg-muted/50 px-2.5 py-2 text-left text-xs text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"
|
|
onClick={pendingTakeover?.onOpen}
|
|
data-testid="task-chat-pending-input-indicator"
|
|
>
|
|
<CircleHelp className="h-4 w-4 shrink-0" aria-hidden />
|
|
<span className="min-w-0 flex-1 truncate">
|
|
{pendingTakeover?.label ?? takeover?.label ?? "Pending input"}
|
|
</span>
|
|
<span className="shrink-0 font-medium">
|
|
{pendingTakeover?.count ?? takeover?.pendingCount ?? 1} pending
|
|
</span>
|
|
</button>
|
|
) : null}
|
|
{pause && conversationMode ? (
|
|
<div className="space-y-2">
|
|
<TaskChatPausedTakeover {...pause} hasDraft={Boolean(body.trim() || attachments.length)} />
|
|
<p className="text-xs text-muted-foreground">Send /new to start a fresh session and resume this conversation.</p>
|
|
</div>
|
|
) : null}
|
|
<ComposerImageAttachments
|
|
images={creation?.images ?? imageAttachments}
|
|
disabled={disabled || !!uncertainSubmission || submitting || creation?.readOnly}
|
|
onRemove={(id) => {
|
|
if (creation) creation.onRemoveImage?.(id);
|
|
else setAttachments(current => current.filter(item => item.id !== id));
|
|
}}
|
|
onRetry={creation ? undefined : (id) => {
|
|
const image = attachments.find(item => item.id === id);
|
|
if (image) retryUpload(image);
|
|
}}
|
|
/>
|
|
<div data-testid="task-chat-composer-input">
|
|
<MarkdownEditor
|
|
ref={editorRef}
|
|
value={body}
|
|
onChange={changeBody}
|
|
placeholder={
|
|
disabled
|
|
? (disabledReason ?? "Composer disabled")
|
|
: effectivePlaceholder
|
|
}
|
|
readOnly={disabled || !!uncertainSubmission || Boolean(creation && (submitting || creation.readOnly))}
|
|
mentions={mentions}
|
|
actionCommands={conversationMode ? [{
|
|
id: "action:new", kind: "action", command: "new", name: "New session",
|
|
description: "Start fresh context here, preserving conversation history.", aliases: ["new"],
|
|
disabled,
|
|
}] : creation ? (onWorkModeChange ? [planCommandOption] : [])
|
|
// A queued edit keeps its exact text, so /plan cannot select Plan mode there.
|
|
: onWorkModeChange && !queuedEdit ? [planCommandOption, goalCommandOption] : [goalCommandOption]}
|
|
onSubmit={() => void submit()}
|
|
submitKey={submitKey}
|
|
fileDropTarget="parent"
|
|
bordered={false}
|
|
className={cn(disabled && "opacity-60")}
|
|
contentClassName={
|
|
mobile
|
|
? "max-h-(--tc-composer-editor-max-height) min-h-(--sz-48px) overflow-y-auto px-1 py-1 text-base scrollbar-auto-hide"
|
|
: "max-h-(--sz-28dvh) min-h-(--sz-48px) overflow-y-auto px-1 py-1 text-sm scrollbar-auto-hide"
|
|
}
|
|
/>
|
|
</div>
|
|
|
|
{actionError ? (
|
|
<p
|
|
className="px-1 text-xs text-destructive"
|
|
role="alert"
|
|
data-testid={creation ? "task-chat-create-error" : queuedEdit ? "task-chat-queued-edit-error" : "task-chat-goal-error"}
|
|
>
|
|
{actionError}
|
|
</p>
|
|
) : null}
|
|
|
|
{visibleAttachments.length > 0 ? (
|
|
<AttachmentGroup
|
|
className="mb-1 px-1"
|
|
data-testid="task-chat-composer-attachments"
|
|
>
|
|
{visibleAttachments.map((attachment) => {
|
|
const kind = fileKindForName(attachment.name);
|
|
const KindIcon = kind.icon;
|
|
const sizeLabel = formatFileSize(attachment.size);
|
|
return (
|
|
<Attachment
|
|
key={attachment.id}
|
|
size="sm"
|
|
state={
|
|
attachment.status === "uploading"
|
|
? "uploading"
|
|
: attachment.status === "error"
|
|
? "error"
|
|
: "done"
|
|
}
|
|
>
|
|
<AttachmentMedia>
|
|
{attachment.status === "uploading" ? (
|
|
<Loader2 className="animate-spin" aria-hidden />
|
|
) : (
|
|
<KindIcon aria-hidden />
|
|
)}
|
|
</AttachmentMedia>
|
|
<AttachmentContent>
|
|
<AttachmentTitle className="max-w-48">
|
|
{attachment.name}
|
|
</AttachmentTitle>
|
|
<AttachmentDescription className="max-w-48">
|
|
{attachment.status === "uploading"
|
|
? "Uploading…"
|
|
: attachment.status === "error"
|
|
? (attachment.error ?? "Upload failed")
|
|
: [kind.label, sizeLabel]
|
|
.filter(Boolean)
|
|
.join(" · ")}
|
|
</AttachmentDescription>
|
|
</AttachmentContent>
|
|
<AttachmentActions>
|
|
{attachment.status === "error" && attachment.file ? (
|
|
<AttachmentAction
|
|
aria-label={`Retry ${attachment.name}`}
|
|
disabled={!!uncertainSubmission}
|
|
onClick={() => retryUpload(attachment)}
|
|
>
|
|
<RotateCw aria-hidden />
|
|
</AttachmentAction>
|
|
) : null}
|
|
<AttachmentAction
|
|
aria-label={`Remove ${attachment.name}`}
|
|
disabled={!!uncertainSubmission}
|
|
onClick={() =>
|
|
setAttachments((prev) =>
|
|
prev.filter((item) => item.id !== attachment.id),
|
|
)
|
|
}
|
|
>
|
|
<X aria-hidden />
|
|
</AttachmentAction>
|
|
</AttachmentActions>
|
|
</Attachment>
|
|
);
|
|
})}
|
|
</AttachmentGroup>
|
|
) : null}
|
|
|
|
{creation?.details}
|
|
|
|
<div
|
|
className={cn("mt-2 flex items-center gap-x-2 gap-y-3", mobile && !queuedEdit ? "flex-nowrap" : "flex-wrap")}
|
|
data-testid="task-chat-composer-actions"
|
|
>
|
|
<div className="flex min-w-0 max-w-full items-center gap-2">
|
|
{canAcceptFiles ? (
|
|
<input ref={fileInputRef} type="file" className="hidden" multiple onChange={handleFileInputChange} />
|
|
) : null}
|
|
<ComposerAddMenu
|
|
privacy={creation?.privacy}
|
|
mode={pendingMode}
|
|
onModeChange={!queuedEdit && onWorkModeChange ? changeMode : undefined}
|
|
onAttachFile={canAcceptFiles ? () => fileInputRef.current?.click() : undefined}
|
|
onGoal={!queuedEdit && !conversationMode && attachments.length === 0 &&
|
|
runnerGoalCapability?.availability === "available" && onRunnerGoalCommand
|
|
? prepareGoal : undefined}
|
|
disabled={disabled || !!uncertainSubmission || Boolean(creation?.readOnly)}
|
|
mobile={mobile}
|
|
triggerTestId="task-chat-composer-add"
|
|
menuTestId="task-chat-composer-add-menu"
|
|
/>
|
|
{creation?.privacy?.private ? <ComposerPrivacyChip inherited={creation.privacy.inherited} onRemove={() => creation.privacy!.onChange(false)} disabled={disabled} /> : null}
|
|
{queuedEdit ? (
|
|
<span className="px-1 text-xs font-medium text-muted-foreground">
|
|
{queuedEdit.stale
|
|
? "Queued message changed"
|
|
: "Editing queued message"}
|
|
</span>
|
|
) : (
|
|
<ComposerModeChip mode={pendingMode} onRemove={onWorkModeChange ? () => changeMode("standard") : undefined}
|
|
disabled={disabled || !!uncertainSubmission} testId="task-chat-composer-mode" mobile={mobile} />
|
|
)}
|
|
</div>
|
|
|
|
<div className={cn("ml-auto flex min-w-0 max-w-full items-center gap-2", mobile && !queuedEdit && "flex-1 justify-end")}>
|
|
|
|
{(showAssignee || showConversationModel) && !queuedEdit && companyId && modelAgents ? (
|
|
<ComposerRunSettingsPicker
|
|
companyId={companyId}
|
|
assigneeValue={assigneeValue}
|
|
currentAssigneeValue={currentAssigneeValue}
|
|
options={reassignOptions ?? []}
|
|
agents={modelAgents}
|
|
overrides={assigneeAdapterOverrides}
|
|
settings={runSettings}
|
|
onSettingsChange={setRunSettings}
|
|
onAssigneeChange={updatePendingAssignee}
|
|
allowAssigneeChange={showAssignee && !conversationMode}
|
|
renderAssigneeIdentity={(value, label, placement) => (
|
|
<AssigneeIdentityAvatar
|
|
assigneeValue={value}
|
|
label={label}
|
|
agentMap={agentMap}
|
|
userProfileMap={userProfileMap}
|
|
placement={placement}
|
|
/>
|
|
)}
|
|
disabled={disabled}
|
|
mobile={mobile}
|
|
/>
|
|
) : showAssignee && !queuedEdit ? (
|
|
<InlineEntitySelector
|
|
value={assigneeValue}
|
|
options={reassignOptions ?? []}
|
|
placeholder="Assignee"
|
|
mobileTitle="Select assignee"
|
|
noneLabel="No assignee"
|
|
searchPlaceholder="Search assignees…"
|
|
emptyMessage="No matches."
|
|
onChange={updatePendingAssignee}
|
|
disabled={disabled}
|
|
triggerTestId="task-chat-composer-assignee"
|
|
className="h-8 gap-1.5 border-0 bg-transparent px-2.5 text-xs shadow-none hover:bg-accent focus-visible:bg-accent focus-visible:ring-0"
|
|
renderTriggerValue={(option) => {
|
|
return (
|
|
<>
|
|
<AssigneeIdentityAvatar
|
|
assigneeValue={option?.id ?? ""}
|
|
label={assigneeLabel}
|
|
agentMap={agentMap}
|
|
userProfileMap={userProfileMap}
|
|
placement="trigger"
|
|
/>
|
|
<span className="max-w-40 truncate">{assigneeLabel}</span>
|
|
<ChevronDown
|
|
className="h-3 w-3 shrink-0 text-muted-foreground"
|
|
aria-hidden
|
|
/>
|
|
</>
|
|
);
|
|
}}
|
|
renderOption={(option) => {
|
|
return (
|
|
<>
|
|
<AssigneeIdentityAvatar
|
|
assigneeValue={option.id}
|
|
label={option.label}
|
|
agentMap={agentMap}
|
|
userProfileMap={userProfileMap}
|
|
placement="option"
|
|
/>
|
|
<span className="truncate">{option.label}</span>
|
|
</>
|
|
);
|
|
}}
|
|
/>
|
|
) : null}
|
|
|
|
{queuedEdit ? (
|
|
<button
|
|
type="button"
|
|
onClick={onCancelQueuedEdit}
|
|
disabled={submitting}
|
|
className="h-8 shrink-0 rounded-md px-2.5 text-xs font-medium text-muted-foreground transition-colors hover:bg-accent hover:text-foreground disabled:opacity-50"
|
|
>
|
|
Cancel
|
|
</button>
|
|
) : null}
|
|
<button
|
|
type="button"
|
|
onClick={() => void (showStop ? stopControl.stop() : submit())}
|
|
disabled={
|
|
showStop
|
|
? disabled || stopControl.stopping
|
|
: disabled ||
|
|
(Boolean(pause) && !canResetPausedConversation) ||
|
|
submitting ||
|
|
!!uncertainSubmission ||
|
|
uploadPending ||
|
|
uploadFailed ||
|
|
Boolean(creation?.submitDisabled) ||
|
|
(body.trim().length === 0 && attachedRefs.length === 0 && !creation?.canSubmitWithoutBody)
|
|
}
|
|
title={
|
|
showStop
|
|
? stopControl.stopping
|
|
? "Stopping…"
|
|
: "Stop response"
|
|
: queuedEdit
|
|
? queuedEdit.stale
|
|
? "Queue as new message"
|
|
: "Save queued message"
|
|
: uploadPending
|
|
? "Waiting for upload to finish"
|
|
: uploadFailed
|
|
? "Remove the failed attachment to send"
|
|
: `${creation?.submitLabel ?? "Send"} (${submitKey === "mod-enter" ? "⌘/Ctrl+Enter" : "Enter"})`
|
|
}
|
|
aria-label={
|
|
showStop
|
|
? stopControl.stopping
|
|
? "Stopping…"
|
|
: "Stop"
|
|
: queuedEdit
|
|
? queuedEdit.stale
|
|
? "Queue as new message"
|
|
: "Save queued message"
|
|
: creation?.submitLabel ?? "Send"
|
|
}
|
|
aria-busy={submitting}
|
|
className={cn(
|
|
"flex size-8 min-h-8 min-w-8 shrink-0 aspect-square items-center justify-center rounded-full transition-transform hover:scale-105 disabled:scale-100",
|
|
streamlined
|
|
? "bg-foreground text-background disabled:bg-foreground disabled:text-background disabled:opacity-100"
|
|
: "bg-primary text-primary-foreground disabled:bg-muted disabled:text-muted-foreground",
|
|
)}
|
|
data-testid={
|
|
showStop ? "task-chat-composer-stop" : "task-chat-composer-send"
|
|
}
|
|
data-slot="icon-button"
|
|
>
|
|
{submitting || (showStop && stopControl.stopping) ? (
|
|
<Loader2 className="h-4 w-4 animate-spin" aria-hidden />
|
|
) : showStop ? (
|
|
<Square className="h-4 w-4 fill-current" aria-hidden />
|
|
) : (
|
|
<ArrowUp className="h-4 w-4" aria-hidden />
|
|
)}
|
|
</button>
|
|
</div>
|
|
</div>
|
|
{stopControl.error ? (
|
|
<p role="alert" className="text-xs text-destructive">
|
|
{stopControl.error}
|
|
</p>
|
|
) : null}
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|