mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-26 10:07:24 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Google Antigravity agents can run Google's native `/swarm` (a coordinator, helpers and a verifier) only on the Antigravity CLI > - #22731 adds a verified CLI route to the Runner, but nothing selects it yet > - A swarm must start only when the signed-in user asks for it, only when an admin turned the experimental feature on, and never silently run as an ordinary request when it cannot run > - This pull request adds the trusted `/swarm` request in the task composer, the server checks and run selection behind an experimental flag, removes Paperclip delegation tools from a swarm turn, and adds the attended catalog cells, docs and ledger > - The benefit is that a user can start a native swarm from a task, and gets one plain message when it is not available ## Linked Issues or Issue Description Refs #22731, #22727, #22728, #22701 **Subsystem affected** Task composer (UI), issue comments API, run selection (server), Paperclip Runner tool bridge, runner-e2e catalog, docs. **Problem or motivation** A user who writes `/swarm <request>` to a Google Antigravity agent should get a real native swarm in the task folder. Today `/swarm` is neutralised text, and the task runs as an ordinary request. **Proposed solution** Read a leading `/swarm` with the shared rule from #22727 in the composer, send it as a structured request, check it on the server, and select the CLI route from #22731 for that run only. ## What Changed - **Trusted start (UI).** `parseSwarmCommand` in `composer-commands.ts` uses `parseLeadingUserCommand` (the one rule from #22727). A leading `/swarm` in the task composer sends the request text with `nativeCommand: "swarm"`; a bare `/swarm` asks for a request; `/swarm` with an assignee change is refused; `/swarm` anywhere else stays text. A resent draft keeps the structured request. - **Contract.** `addIssueCommentSchema` gains `nativeCommand: "swarm"`. `instance.experimental.enableAntigravitySwarm` (feature catalog, settings page, server defaults), off by default. No Cloud policy in Core. - **Server (`services/antigravity-swarm.ts`, comments route, runtime selection).** - The comments route accepts `nativeCommand` only from a signed-in board user. When a swarm cannot run it answers 422 with one plain message and posts nothing: flag off, not a Google Antigravity assignee, a chat, Plan mode. - An accepted request is recorded in the activity log (`issue.antigravity_swarm_requested`, server-written) and the assignee's wake carries the comment id. Comment text is never read as a command. - Run selection makes the run a swarm only when that activity record exists. It refuses a remote or cloud environment and Plan mode with a plain run failure, so a swarm is never run as an ordinary request. It logs `issue.antigravity_swarm_started` in plain language: helper actions are auto-approved, Paperclip does not sandbox the helpers and cannot see their shell commands, and usage is one total. - The native execution input sets the Antigravity provider mode `swarm` for that run only, and carries the verified request in its own field, `provider.swarmRequest` (the Runner contract accepts it only with that mode and requires it there, 1 to 16,000 characters). The Runner copies it into the model envelope as `swarmRequest`; the swarm route sends exactly `/swarm <swarmRequest>` and never reads `task.prompt`, which holds rendered wake comments, task context and text the Runner adds (handoff, attachments, queued messages). - The swarm turn contract (mode `swarm`, envelope `paperclip.native-model-envelope.v3`, `swarmRequest` of 1 to 16,000 characters) is declared as `antigravitySwarmTurn` in `protocol/provider-schemas/acpx-sidecar.schema.json` and generated into TypeScript, so the pack `contractDigest` covers it (it changes; older image packs are rebuilt rather than reused). Provider profile `commandDigest`s and versions are unchanged, so no saved session is reset. - What the swarm sees of the task: only the request. The title, the description (which other people or agents may have written) and other comments are not part of the prompt; the coordinator can read them through Paperclip's task tools as data if it needs context. - An empty `/swarm` or one over 16,000 characters is refused in the composer, by the comments route (422, nothing posted) and at run selection (plain run failure), so it never runs as ordinary work. - A swarm run never takes queued messages, and Interrupt treats it as already started: it stops the swarm and delivers the queued message as the next ordinary request, before or after the provider accepted the turn. - Retry after Stop, and past the three automatic attempts, counts only when the signed-in user asked for it (their own Retry request on the task after the last attempt). Wake reasons and copied run context are not proof: a recovery that copies the request marker, an automatic retry on the user's behalf, or an agent wake that names `task_retry` stay bounded. - **Runner.** For a swarm turn the Paperclip bridge drops delegation tools (`paperclip_create_task`, `paperclip_create_issue`, hire/assign tools); the instructions also tell the coordinator not to delegate. - **runner-e2e.** `antigravity-swarm` suite, 5 local cells (`two-helpers-and-verifier`, `stop-mid-swarm`, `process-loss-retry`, `follow-up-after-swarm`, `flag-off-refusal`), explicit-only, never in `--all` or CI matrix jobs. There is no automated executor yet: the launcher refuses the cells and points at the live recipe. Catalog counts updated (1392 cells). - **Docs.** `tests/runner-e2e/SUITES.md`, `doc/evals.md`, and the `/swarm` section, ledger row and live recipe in `doc/plans/2026-11-22-antigravity-qualification.md`. ## Verification - `pnpm --filter @paperclipai/server exec vitest run src/services/antigravity-swarm.test.ts`: 2 passed (red first: module missing; Plan mode red then green). - `pnpm --filter @paperclipai/server exec vitest run src/__tests__/issue-comment-reopen-routes.test.ts -t swarm`: 3 passed; 2 red against the route without this change. - `pnpm --filter @paperclipai/ui exec vitest run src/components/task-chat/TaskChatComposer.test.tsx`: 164 passed, including 4 new `/swarm` tests (red first). - Runner: `vitest run src/drivers/acpx/antigravity-swarm-*.test.ts`: 69 passed (route tool filter red first). - runner-e2e: `antigravity-swarm.test.ts` (red first) plus the catalog, selector and Antigravity tests: 28 files passed. - Typecheck: server, UI (except generated Storybook files absent from a worktree) and runner: no errors. - Live, real CLI 1.5.15 with the owner's sign-in, through the driver: the receipt verified (pinned identity, task folder, `auto` read back, `gemini-3.8-flash` + `low`). Google then refused the prompt with its 429 quota text; the driver reported it as a typed "out of quota" failure, retired the CLI and nothing was written. - **Not run live yet:** the full Paperclip proof (swarm to Done, Stop, kill and Retry, follow-up, flag off). This PR is merged only after it passes. Recipe: `doc/plans/2026-11-22-antigravity-qualification.md#swarm-live-proof`. ## Risks ### Security notes: the trust boundary Helpers are auto-approved and Paperclip does not sandbox the CLI on a local computer, so the boundary is who asked and what text is sent. Every input that can influence it: **(a) Whether a run is a swarm** - `nativeCommand: "swarm"` on the comment request: accepted only from a signed-in board user; the request record (`issue.antigravity_swarm_requested`, actor = that user, `commentId`) commits in the same transaction as the comment. Paperclip-written. - `antigravitySwarmCommentId` on the wake/run context: set only by the comments route and by run selection. It is a pointer, never trusted alone: selection re-verifies comment id + task + company + human author (no agent author) + a matching record by the same user. - The pending request for marker-less wakes: the task's latest human comment, verified the same way. - Retry inheritance: the run's `retryOfRunId` chain (server-written), bounded to 8 hops on the same task. - Manual vs automatic: a request's first run, or a user's own Retry request (`task_retry` / `retry_failed_run`, requested by a user, not `initiatedBy` automation) after the last attempt. Not the wake reason string. - Instance flag `enableAntigravitySwarm` (admin), the assignee's adapter config (Google Antigravity), execution target (local only), work mode (Standard only: Plan, Ask and any other mode are refused, at comment time and at run time), chat vs task: all Paperclip-owned settings. - Prior attempts on the same request (run status rows): Paperclip-written. **(b) What text and tools the swarm gets** - The prompt: `/swarm ` + `provider.swarmRequest`, which is the recorded comment body minus a leading `/swarm`, trimmed, byte for byte (tested through the production input builder and envelope with a merged wake that contains an agent comment). The verified request. - The system prompt append: only Paperclip-authored text: Paperclip's fixed execution prompt, the run's hand-in values (the server-written completion revision and criterion IDs that `paperclip_finish`/`paperclip_block` require; never a criterion's requirement text), and the fixed swarm rules. **The swarm runs without the agent's own instructions**: the instruction bundle and connection instructions are left out, because an agent with an editable instructions folder can rewrite its instructions in an earlier ordinary run, the helpers act under auto mode, and Paperclip keeps no user-approved copy of those instructions to trust instead. - Tools: only Paperclip's own MCP bridge (any other assigned tool server refuses the swarm), with delegation, hiring, routing and generic API operations removed. Paperclip's permission handler approves a CLI permission request only when its tool name is `mcp_paperclip_<tool>` and `<tool>` is one the run's bridge admits; everything else is refused, and the CLI then ends the turn. Tool descriptions are Paperclip-authored; tool results (for example other comments) are data the coordinator reads, not the request. - Model and mode: the agent's configured model, Antigravity's `auto` mode, both read back and pinned by the receipt. - Not sent: task title, description, wake comments, continuation events, attachments, queued messages, handoff text. Known residual: a Retry or recovery run that has not yet been selected (still preparing) does not carry the request marker, so an Interrupt in that short window keeps the message for the turn boundary instead of stopping the run; the message is delivered after the run ends. - Off by default and local only. With the flag on, helpers act under Antigravity's `auto` mode. **Paperclip does not sandbox them on a local computer**, and their tool calls never reach Paperclip, so helper shell commands can write outside the task folder where the CLI's own sandbox allows (workspace plus temp directories). The settings text, the activity log and the plan doc say so. - On macOS the CLI uses its own Google sign-in from the login keychain, not Paperclip's stored connection. - Google's consumer terms have a clause about third-party tools that access the service. A legal read is pending; this PR does not claim compliance. - `/swarm` as the first word of a composer message is now a swarm request for every agent; for agents other than Google Antigravity the server refuses it with a plain message. To send the literal text, put other text first. - The new runner-e2e cells are attended only and have no automated executor. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. Review round 2 (heada2decc65f3): Greptile's "swarms must guess completion fields" fixed as above (runner `nativeSystemInstructions`, red first 1 in the fake-CLI swarm runtime test; request text to the CLI still exactly `/swarm <request>`); CI typecheck failure was a TS18046 in `acpx-runtime-sidecar.test.ts` (test-program typecheck), fixed; master merged, its pruned `heartbeat-provider-limit-wait` and `provider-failure-classification` suites dropped, with this branch's swarm cases kept in `antigravity-swarm-provider-limit.test.ts` and `antigravity-swarm.test.ts`. No protocol schema change. Round 3 (head1444503e84, from live run6): CLI 1.5.15 names a client MCP call `mcp_<server>_<tool>` with no `_meta` (payload recorded from the pinned CLI, now the fake CLI's fixture), so Paperclip's permission handler refused the coordinator's own `get_task_context` and the CLI ended the turn on the denial. The handler now approves only tools the run's Paperclip bridge admits, by that name, and fails closed otherwise; a refused Paperclip tool is reported as such, not as a helper blocked outside the task folder. A swarm turn without a hand-in fails plainly (`ANTIGRAVITY_SWARM_NO_RESULT`: "The swarm ended without doing any work"), every swarm-route failure code settles as `antigravity_swarm_unavailable` (no automatic retry; Retry offered), and selection never starts another swarm automatically after one; a lost CLI process still recovers on its own. The run history always records whether the CLI's sign-in matches the connection account (with the reason when unknown). Usage-limit evidence is scoped by the executed provider mode, so limits from pre-scope swarms hold only swarms. Red first: runtime 5, server 3. Then (head74454a17f3): an empty `/swarm` body now gets the documented 422 `antigravity_swarm_unavailable` instead of a generic 400 (`addIssueSwarmCommentSchema`, route red first 1); an empty ordinary comment keeps its 400. Review round (earlier head): - `pnpm --filter @paperclipai/server exec vitest run` on the swarm, request-path, native-execution-input, first-turn, queued-comments and comment-route tests: 475 passed. Red first: request path 1, execution input 3, empty/over-long DB 3 and route 2, Interrupt during a swarm 2, Retry proof 2. - Runner `src/drivers/acpx src/contracts`: passed; swarm runtime red first 6 (request field, verbatim text, empty, over-long, no field, request only in the rendered prompt). - UI `TaskChatComposer.test.tsx`: over-long `/swarm` refused (red first 1). - Typecheck: server (layers), UI and runner: no errors. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, with tool use (shell, file edit) 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 - [ ] 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>
3967 lines
164 KiB
TypeScript
3967 lines
164 KiB
TypeScript
// @vitest-environment jsdom
|
||
|
||
import { act, StrictMode, useState, type ComponentProps, type ReactElement } from "react";
|
||
import { flushSync } from "react-dom";
|
||
import { createRoot, type Root } from "react-dom/client";
|
||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||
import {
|
||
buildAgentMentionHref,
|
||
buildSkillMentionHref,
|
||
instanceExperimentalSettingsSchema,
|
||
} from "@paperclipai/shared";
|
||
import { parsePlanCommand, parseRunnerGoalCommand, TaskChatComposer } from "./TaskChatComposer";
|
||
import { parseSwarmCommand, planSubmission, swarmRunSettingsRefusal } from "./composer-commands";
|
||
import { ComposerAddMenu } from "./ComposerAddMenu";
|
||
import { QuestionForm } from "./QuestionForm";
|
||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||
import type { Agent, HeartbeatRun, IssueWorkMode } from "@paperclipai/shared";
|
||
import { agentsApi } from "@/api/agents";
|
||
import { instanceSettingsApi } from "@/api/instanceSettings";
|
||
import { CoordinatorPresentation } from "@/components/coordinator/CoordinatorPresentation";
|
||
import { ThemeProvider } from "@/context/ThemeContext";
|
||
import { DRAFT_DEBOUNCE_MS } from "../../lib/composer-draft";
|
||
import {
|
||
loadDraftAttachments,
|
||
loadDraftSubmission,
|
||
saveDraft,
|
||
saveDraftSubmission,
|
||
} from "../../lib/composer-draft";
|
||
import { CommentSubmissionUnknownError } from "../../lib/comment-submit-result";
|
||
import { ApiError } from "../../api/api-error";
|
||
import { queryKeys } from "../../lib/queryKeys";
|
||
import { useAccountBoundMutation } from "../../hooks/useAccountBoundMutation";
|
||
import { waitForStoppedRuns } from "../../lib/wait-for-stopped-runs";
|
||
|
||
// The session lookup never answers on its own; tests set the account directly.
|
||
vi.mock("../../api/auth", async (importOriginal) => {
|
||
const actual = await importOriginal<typeof import("../../api/auth")>();
|
||
return { ...actual, authApi: { ...actual.authApi, getSession: () => new Promise(() => {}) } };
|
||
});
|
||
|
||
const mdxEditorMockState = vi.hoisted(() => ({
|
||
imagePluginOptions: null as {
|
||
imageUploadHandler?: (file: File) => Promise<string>;
|
||
} | null,
|
||
}));
|
||
|
||
vi.mock("@mdxeditor/editor", async () => {
|
||
const React = await import("react");
|
||
|
||
function setForwardedRef<T>(
|
||
ref: React.ForwardedRef<T | null>,
|
||
value: T | null,
|
||
) {
|
||
if (typeof ref === "function") {
|
||
ref(value);
|
||
return;
|
||
}
|
||
if (ref) {
|
||
(ref as React.MutableRefObject<T | null>).current = value;
|
||
}
|
||
}
|
||
|
||
interface MockHandle {
|
||
setMarkdown: (value: string) => void;
|
||
insertMarkdown: (value: string) => void;
|
||
focus: (callback?: () => void) => void;
|
||
}
|
||
|
||
const MDXEditor = React.forwardRef(function MockMDXEditor(
|
||
{
|
||
markdown,
|
||
onChange,
|
||
readOnly,
|
||
contentEditableClassName,
|
||
}: {
|
||
markdown: string;
|
||
onChange?: (value: string) => void;
|
||
readOnly?: boolean;
|
||
contentEditableClassName?: string;
|
||
},
|
||
forwardedRef: React.ForwardedRef<MockHandle | null>,
|
||
) {
|
||
const editableRef = React.useRef<HTMLDivElement>(null);
|
||
const contentRef = React.useRef(markdown);
|
||
const onChangeRef = React.useRef(onChange);
|
||
onChangeRef.current = onChange;
|
||
|
||
const handle = React.useMemo<MockHandle>(
|
||
() => ({
|
||
setMarkdown: (value: string) => {
|
||
contentRef.current = value;
|
||
if (editableRef.current) editableRef.current.textContent = value.replace(/(?: )+$/, (suffix) => " ".repeat(suffix.length / 6));
|
||
},
|
||
insertMarkdown: (value: string) => {
|
||
const next = contentRef.current
|
||
? `${contentRef.current}${value}`
|
||
: value;
|
||
contentRef.current = next;
|
||
if (editableRef.current) editableRef.current.textContent = next;
|
||
onChangeRef.current?.(next);
|
||
},
|
||
focus: (callback?: () => void) => {
|
||
editableRef.current?.focus();
|
||
callback?.();
|
||
},
|
||
}),
|
||
[],
|
||
);
|
||
|
||
React.useEffect(() => {
|
||
if (editableRef.current && contentRef.current) {
|
||
editableRef.current.textContent = contentRef.current;
|
||
}
|
||
setForwardedRef(forwardedRef, handle);
|
||
return () => setForwardedRef(forwardedRef, null);
|
||
}, [forwardedRef, handle]);
|
||
|
||
return (
|
||
<div
|
||
ref={editableRef}
|
||
data-testid="mdx-editor"
|
||
data-content-class-name={contentEditableClassName}
|
||
contentEditable={!readOnly}
|
||
suppressContentEditableWarning
|
||
onInput={(e) => {
|
||
const next = e.currentTarget.textContent ?? "";
|
||
contentRef.current = next;
|
||
onChangeRef.current?.(next);
|
||
}}
|
||
/>
|
||
);
|
||
});
|
||
|
||
return {
|
||
CodeMirrorEditor: () => null,
|
||
MDXEditor,
|
||
codeBlockPlugin: () => ({}),
|
||
codeMirrorPlugin: () => ({}),
|
||
createRootEditorSubscription$: Symbol("createRootEditorSubscription$"),
|
||
headingsPlugin: () => ({}),
|
||
imagePlugin: (options: {
|
||
imageUploadHandler?: (file: File) => Promise<string>;
|
||
}) => {
|
||
mdxEditorMockState.imagePluginOptions = options;
|
||
return {};
|
||
},
|
||
linkDialogPlugin: () => ({}),
|
||
linkPlugin: () => ({}),
|
||
listsPlugin: () => ({}),
|
||
markdownShortcutPlugin: () => ({}),
|
||
quotePlugin: () => ({}),
|
||
realmPlugin: (plugin: unknown) => plugin,
|
||
tablePlugin: () => ({}),
|
||
thematicBreakPlugin: () => ({}),
|
||
};
|
||
});
|
||
|
||
vi.mock("../../lib/mention-deletion", () => ({
|
||
mentionDeletionPlugin: () => ({}),
|
||
}));
|
||
|
||
vi.mock("../../lib/paste-normalization", () => ({
|
||
pasteNormalizationPlugin: () => ({}),
|
||
}));
|
||
|
||
const SLASH_HREF = buildSkillMentionHref("skill-1", "deploy");
|
||
|
||
vi.mock("../../context/EditorAutocompleteContext", () => ({
|
||
useEditorAutocomplete: () => ({
|
||
slashCommands: [
|
||
{
|
||
id: "skill:skill-1",
|
||
kind: "skill",
|
||
skillId: "skill-1",
|
||
key: "deploy",
|
||
name: "Deploy",
|
||
slug: "deploy",
|
||
description: null,
|
||
href: SLASH_HREF,
|
||
aliases: ["deploy", "Deploy"],
|
||
},
|
||
],
|
||
}),
|
||
}));
|
||
|
||
let container: HTMLDivElement;
|
||
let root: Root | null = null;
|
||
let originalRangeRect: typeof Range.prototype.getBoundingClientRect;
|
||
|
||
beforeEach(() => {
|
||
localStorage.clear();
|
||
container = document.createElement("div");
|
||
document.body.appendChild(container);
|
||
root = createRoot(container);
|
||
mdxEditorMockState.imagePluginOptions = null;
|
||
// jsdom ranges have zero-size rects; the mention menu measures the caret.
|
||
originalRangeRect = Range.prototype.getBoundingClientRect;
|
||
Range.prototype.getBoundingClientRect = () => ({
|
||
x: 32,
|
||
y: 24,
|
||
width: 12,
|
||
height: 18,
|
||
top: 24,
|
||
right: 44,
|
||
bottom: 42,
|
||
left: 32,
|
||
toJSON: () => ({}),
|
||
});
|
||
});
|
||
|
||
afterEach(() => {
|
||
flushSync(() => root?.unmount());
|
||
root = null;
|
||
container.remove();
|
||
Range.prototype.getBoundingClientRect = originalRangeRect;
|
||
window.getSelection()?.removeAllRanges();
|
||
});
|
||
|
||
function render(ui: ReactElement) {
|
||
flushSync(() => root!.render(<ThemeProvider>{ui}</ThemeProvider>));
|
||
}
|
||
|
||
async function flushAsync() {
|
||
await act(async () => {
|
||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||
});
|
||
}
|
||
|
||
function editable() {
|
||
return container.querySelector<HTMLDivElement>('[data-testid="mdx-editor"]')!;
|
||
}
|
||
|
||
function sendButton() {
|
||
return container.querySelector<HTMLButtonElement>(
|
||
'[data-testid="task-chat-composer-send"]',
|
||
)!;
|
||
}
|
||
|
||
/** Simulate typing: set the contenteditable's text and fire an input event. */
|
||
function typeText(value: string) {
|
||
const el = editable();
|
||
flushSync(() => {
|
||
el.textContent = value;
|
||
el.dispatchEvent(new Event("input", { bubbles: true }));
|
||
});
|
||
}
|
||
|
||
function pressKey(
|
||
key: string,
|
||
modifiers: { metaKey?: boolean; ctrlKey?: boolean; shiftKey?: boolean } = {},
|
||
) {
|
||
flushSync(() => {
|
||
editable().dispatchEvent(
|
||
new KeyboardEvent("keydown", {
|
||
key,
|
||
...modifiers,
|
||
bubbles: true,
|
||
cancelable: true,
|
||
}),
|
||
);
|
||
});
|
||
}
|
||
|
||
function openComposerAddMenu() {
|
||
const add = container.querySelector<HTMLButtonElement>('[data-testid="task-chat-composer-add"]')!;
|
||
flushSync(() => add.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true, button: 0 })));
|
||
return add;
|
||
}
|
||
|
||
function pasteFiles(files: File[]) {
|
||
const paste = new Event("paste", { bubbles: true, cancelable: true });
|
||
Object.defineProperty(paste, "clipboardData", {
|
||
value: { files, types: ["Files"] },
|
||
});
|
||
flushSync(() => {
|
||
editable().dispatchEvent(paste);
|
||
});
|
||
return paste;
|
||
}
|
||
|
||
/** Place the caret at the end of the editable's first text node and announce it. */
|
||
async function placeCaretAtEnd() {
|
||
const textNode = editable().firstChild;
|
||
expect(textNode?.nodeType).toBe(Node.TEXT_NODE);
|
||
const selection = window.getSelection();
|
||
const range = document.createRange();
|
||
range.setStart(textNode!, textNode!.textContent!.length);
|
||
range.collapse(true);
|
||
selection?.removeAllRanges();
|
||
selection?.addRange(range);
|
||
flushSync(() => {
|
||
document.dispatchEvent(new Event("selectionchange"));
|
||
});
|
||
// Mention detection defers via requestAnimationFrame after input events.
|
||
await flushAsync();
|
||
await flushAsync();
|
||
}
|
||
|
||
function autocompleteOption(matchText: string) {
|
||
const menu = document.body.querySelector(
|
||
'[data-testid="mention-autocomplete-menu"]',
|
||
);
|
||
expect(menu).toBeTruthy();
|
||
const option = Array.from(
|
||
menu!.querySelectorAll<HTMLButtonElement>('button[type="button"]'),
|
||
).find((node) => node.textContent?.includes(matchText));
|
||
expect(option).toBeTruthy();
|
||
return option!;
|
||
}
|
||
|
||
function renderComposer(props: ComponentProps<typeof TaskChatComposer>) {
|
||
render(<TaskChatComposer {...props} />);
|
||
}
|
||
|
||
describe("TaskChatComposer", () => {
|
||
describe("plain HTTP without randomUUID", () => {
|
||
beforeEach(() => {
|
||
vi.stubGlobal("crypto", { getRandomValues: crypto.getRandomValues.bind(crypto) });
|
||
});
|
||
afterEach(() => vi.unstubAllGlobals());
|
||
|
||
it.each([false, true])("sends repeated messages with distinct receipts (conversation=%s)", async (conversationMode) => {
|
||
const onAdd = vi.fn().mockResolvedValue(undefined);
|
||
renderComposer({ onAdd, conversationMode, workMode: "standard", draftKey: "http-repeated" });
|
||
for (let turn = 0; turn < 5; turn++) {
|
||
typeText(`Message ${turn}`);
|
||
if (turn % 2) pressKey("Enter", { metaKey: true });
|
||
else flushSync(() => sendButton().click());
|
||
await flushAsync();
|
||
expect(onAdd).toHaveBeenCalledTimes(turn + 1);
|
||
expect(onAdd.mock.calls[turn][0]).toBe(`Message ${turn}`);
|
||
expect(onAdd.mock.calls[turn][4]).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/);
|
||
expect(editable().textContent).toBe("");
|
||
expect(loadDraftSubmission("http-repeated")).toBeNull();
|
||
}
|
||
expect(new Set(onAdd.mock.calls.map(call => call[4])).size).toBe(5);
|
||
});
|
||
|
||
it("keeps the request identity and next draft after a lost receipt", async () => {
|
||
let rejectSend!: (error: Error) => void;
|
||
const onAdd = vi.fn()
|
||
.mockReturnValueOnce(new Promise<void>((_, reject) => { rejectSend = reject; }))
|
||
.mockResolvedValue(undefined);
|
||
renderComposer({ onAdd, workMode: "standard", draftKey: "http-retry" });
|
||
typeText("Keep this request");
|
||
await act(async () => sendButton().click());
|
||
expect(onAdd).toHaveBeenCalledOnce();
|
||
const attemptId = onAdd.mock.calls[0][4];
|
||
expect(loadDraftSubmission("http-retry")?.attemptId).toBe(attemptId);
|
||
typeText("Next draft");
|
||
await act(async () => rejectSend(new CommentSubmissionUnknownError()));
|
||
const resend = Array.from(container.querySelectorAll("button")).find(button => button.textContent === "Resend now")!;
|
||
await act(async () => resend.click());
|
||
expect(onAdd).toHaveBeenNthCalledWith(2, "Keep this request", undefined, undefined, undefined, attemptId);
|
||
expect(editable().textContent).toBe("Next draft");
|
||
expect(loadDraftSubmission("http-retry")).toBeNull();
|
||
});
|
||
|
||
it("uploads an image and submits its receipt on plain HTTP", async () => {
|
||
const onAdd = vi.fn().mockResolvedValue(undefined);
|
||
const attachmentId = "cdd72566-48f4-4996-8899-285101990a30";
|
||
const contentPath = `/api/attachments/${attachmentId}/content`;
|
||
const onAttachImage = vi.fn().mockResolvedValue({ id: attachmentId, contentPath });
|
||
renderComposer({ onAdd, onAttachImage, workMode: "standard" });
|
||
typeText("Inspect this image");
|
||
pasteFiles([new File(["synthetic image"], "sample.png", { type: "image/png" })]);
|
||
await flushAsync();
|
||
expect(onAttachImage).toHaveBeenCalledOnce();
|
||
expect(sendButton().disabled).toBe(false);
|
||
await act(async () => sendButton().click());
|
||
expect(onAdd).toHaveBeenCalledWith(`Inspect this image\n\n`, undefined, undefined, [attachmentId], expect.any(String));
|
||
});
|
||
});
|
||
|
||
it("stages creation images above the editor without changing the text", async () => {
|
||
const creation = {
|
||
value: "Before the screenshot",
|
||
onChange: vi.fn(), onSubmit: vi.fn().mockResolvedValue(undefined),
|
||
submitLabel: "Create task", onSelectFiles: vi.fn(), onRemoveImage: vi.fn(),
|
||
runSettings: null, onRunSettingsChange: vi.fn(),
|
||
};
|
||
render(<TaskChatComposer creation={creation} workMode="standard" />);
|
||
const image = new File(["png"], "screen.png", { type: "image/png" });
|
||
expect(pasteFiles([image]).defaultPrevented).toBe(true);
|
||
expect(creation.onSelectFiles).toHaveBeenCalledWith([image]);
|
||
render(<TaskChatComposer creation={{ ...creation, images: [{ id: "screen", name: image.name, file: image }] }} workMode="standard" />);
|
||
await flushAsync();
|
||
const row = container.querySelector('[data-testid="task-chat-composer-images"]')!;
|
||
const input = container.querySelector('[data-testid="task-chat-composer-input"]')!;
|
||
expect(row.compareDocumentPosition(input) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
|
||
expect(row.querySelector('img')?.alt).toBe("screen.png");
|
||
expect(editable().textContent).toBe(creation.value);
|
||
expect(creation.onChange).not.toHaveBeenCalled();
|
||
flushSync(() => container.querySelector<HTMLButtonElement>('button[aria-label="Remove screen.png"]')!.click());
|
||
expect(creation.onRemoveImage).toHaveBeenCalledWith("screen");
|
||
flushSync(() => sendButton().click());
|
||
await flushAsync();
|
||
expect(creation.onSubmit).toHaveBeenCalledWith(creation.value, "standard", null);
|
||
});
|
||
|
||
it("stages images and documents together when pasted into creation", () => {
|
||
const creation = {
|
||
value: "Inspect these files",
|
||
onChange: vi.fn(), onSubmit: vi.fn().mockResolvedValue(undefined),
|
||
submitLabel: "Create task", onSelectFiles: vi.fn(),
|
||
runSettings: null, onRunSettingsChange: vi.fn(),
|
||
};
|
||
render(<TaskChatComposer creation={creation} workMode="standard" onImageUpload={vi.fn()} />);
|
||
const image = new File(["png"], "screen.png", { type: "image/png" });
|
||
const document = new File(["notes"], "notes.txt", { type: "text/plain" });
|
||
expect(pasteFiles([image, document]).defaultPrevented).toBe(true);
|
||
expect(creation.onSelectFiles).toHaveBeenCalledWith([image, document]);
|
||
expect(pasteFiles([document]).defaultPrevented).toBe(true);
|
||
});
|
||
|
||
it("settles an acknowledged submission after navigating away", async () => {
|
||
const key = "navigate-before-save";
|
||
let resolveSend!: () => void;
|
||
const onAdd = vi.fn().mockReturnValue(new Promise<void>(resolve => { resolveSend = resolve; }));
|
||
render(<TaskChatComposer onAdd={onAdd} workMode="standard" draftKey={key} />);
|
||
typeText("Please write a motto");
|
||
pressKey("Enter", { metaKey: true });
|
||
await flushAsync();
|
||
const intent = loadDraftSubmission(key)!;
|
||
expect(onAdd.mock.calls[0]?.[4]).toBe(intent.attemptId);
|
||
render(<div>Another task</div>);
|
||
resolveSend();
|
||
await flushAsync();
|
||
expect(loadDraftSubmission(key)).toBeNull();
|
||
expect(localStorage.getItem(key)).toBeNull();
|
||
render(<TaskChatComposer onAdd={onAdd} workMode="standard" draftKey={key} />);
|
||
expect(container.textContent).not.toContain("Sending when reconnected…");
|
||
expect(editable().textContent).toBe("");
|
||
});
|
||
|
||
it.each([
|
||
{ reassignment: { assigneeAgentId: "old-agent", assigneeUserId: null } },
|
||
{ runSettings: { model: "old-model" } },
|
||
{ reopen: true },
|
||
])("keeps an uncertain composite send for reconciliation without resending task changes: %j", async (changes) => {
|
||
const key = "uncertain-composite";
|
||
const attemptId = "9af8228f-0be7-45ae-a104-6fbe0af6f1d3";
|
||
saveDraft(key, "Keep the comment");
|
||
saveDraftSubmission(key, { attemptId, reviewed: false, request: { body: "Keep the comment", ...changes }, requestOwner: "user-1" });
|
||
const onAdd = vi.fn();
|
||
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||
client.setQueryData(queryKeys.auth.session, { user: { id: "user-1" } });
|
||
render(<QueryClientProvider client={client}><TaskChatComposer onAdd={onAdd} workMode="standard" draftKey={key} /></QueryClientProvider>);
|
||
await flushAsync();
|
||
expect(container.textContent).toContain("We couldn’t confirm whether this message was sent.");
|
||
expect(container.textContent).not.toContain("Resend now");
|
||
expect(onAdd).not.toHaveBeenCalled();
|
||
const cancel = Array.from(container.querySelectorAll("button")).find(button => button.textContent === "Cancel")!;
|
||
flushSync(() => cancel.click());
|
||
await flushAsync();
|
||
expect(editable().textContent).toBe("Keep the comment");
|
||
expect(loadDraftSubmission(key)).toBeNull();
|
||
expect(onAdd).not.toHaveBeenCalled();
|
||
client.clear();
|
||
});
|
||
|
||
it("automatically reconciles a restored submission by its server receipt, not its text", async () => {
|
||
const key = "saved-receipt";
|
||
const attemptId = "9af8228f-0be7-45ae-a104-6fbe0af6f1d3";
|
||
saveDraft(key, "Already answered");
|
||
saveDraftSubmission(key, { attemptId, reviewed: false });
|
||
const onAdd = vi.fn();
|
||
render(<TaskChatComposer onAdd={onAdd} workMode="standard" draftKey={key}
|
||
confirmedSubmissionIds={new Set(["another-request"])} />);
|
||
expect(loadDraftSubmission(key)).not.toBeNull();
|
||
render(<TaskChatComposer onAdd={onAdd} workMode="standard" draftKey={key}
|
||
confirmedSubmissionIds={new Set([attemptId])} />);
|
||
await flushAsync();
|
||
expect(loadDraftSubmission(key)).toBeNull();
|
||
expect(editable().textContent).toBe("");
|
||
expect(onAdd).not.toHaveBeenCalled();
|
||
});
|
||
|
||
it("keeps the original key after account cancellation of an accepted initial send", async () => {
|
||
const key = "accepted-account-roundtrip";
|
||
const client = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } });
|
||
client.setQueryData(queryKeys.auth.session, { user: { id: "user-1" } });
|
||
let accepted!: () => void;
|
||
const post = vi.fn<(body: string, requestId?: string) => Promise<void>>()
|
||
.mockImplementationOnce(() => new Promise<void>(resolve => { accepted = resolve; })).mockResolvedValue(undefined);
|
||
function OwnedComposer() {
|
||
const mutation = useAccountBoundMutation({ mutationFn: ({ body, requestId }: { body: string; requestId?: string }) => post(body, requestId) });
|
||
return <TaskChatComposer draftKey={key} workMode="standard"
|
||
onAdd={(body, _reopen, _reassign, _files, requestId) => mutation.mutateAsync({ body, requestId })} />;
|
||
}
|
||
render(<QueryClientProvider client={client}><OwnedComposer /></QueryClientProvider>);
|
||
typeText("Accepted before the account changed");
|
||
pressKey("Enter", { metaKey: true });
|
||
await flushAsync();
|
||
const requestId = post.mock.calls[0][1]!;
|
||
flushSync(() => {
|
||
client.setQueryData(queryKeys.auth.session, { user: { id: "user-2" } });
|
||
client.setQueryData(queryKeys.auth.session, { user: { id: "user-1" } });
|
||
});
|
||
accepted();
|
||
await flushAsync();
|
||
expect(loadDraftSubmission(key)?.attemptId).toBe(requestId);
|
||
expect(editable().textContent).toBe("Accepted before the account changed");
|
||
const retry = Array.from(container.querySelectorAll("button")).find(button => button.textContent === "Resend now")!;
|
||
flushSync(() => retry.click());
|
||
await flushAsync();
|
||
expect(post).toHaveBeenCalledTimes(2);
|
||
expect(post.mock.calls[1][1]).toBe(requestId);
|
||
expect(loadDraftSubmission(key)).toBeNull();
|
||
client.clear();
|
||
});
|
||
|
||
it.each([false, true])("does not retry from a stale account render (returns to original=%s)", async (returns) => {
|
||
const key = "stale-account-retry";
|
||
const attemptId = "9af8228f-0be7-45ae-a104-6fbe0af6f1d3";
|
||
saveDraft(key, "Original account text");
|
||
saveDraftSubmission(key, { attemptId, reviewed: false, request: { body: "Original account text" }, requestOwner: "user-1" });
|
||
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||
client.setQueryData(queryKeys.auth.session, { user: { id: "user-1" } });
|
||
const onAdd = vi.fn().mockResolvedValue(undefined);
|
||
render(<QueryClientProvider client={client}><TaskChatComposer onAdd={onAdd} workMode="standard" draftKey={key} /></QueryClientProvider>);
|
||
await flushAsync();
|
||
const resend = Array.from(container.querySelectorAll("button")).find(button => button.textContent === "Resend now")!;
|
||
flushSync(() => {
|
||
client.setQueryData(queryKeys.auth.session, { user: { id: "user-2" } });
|
||
if (returns) client.setQueryData(queryKeys.auth.session, { user: { id: "user-1" } });
|
||
resend.click();
|
||
});
|
||
await flushAsync();
|
||
expect(onAdd).not.toHaveBeenCalled();
|
||
expect(loadDraftSubmission(key)?.attemptId).toBe(attemptId);
|
||
client.clear();
|
||
});
|
||
|
||
it.each(["success", "rejection"])("settles a receipt before its in-flight resend %s without cutting the next draft", async (outcome) => {
|
||
const key = "receipt-and-resend";
|
||
const attemptId = "9af8228f-0be7-45ae-a104-6fbe0af6f1d3";
|
||
saveDraft(key, "First request\n\nKeep this next draft");
|
||
saveDraftSubmission(key, { attemptId, reviewed: false, nextDraftOffset: 15, request: { body: "First request" }, requestOwner: "user-1" });
|
||
let finish!: () => void;
|
||
let fail!: (error: Error) => void;
|
||
const onAdd = vi.fn(() => new Promise<void>((resolve, reject) => { finish = resolve; fail = reject; }));
|
||
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||
client.setQueryData(queryKeys.auth.session, { user: { id: "user-1" } });
|
||
const show = (confirmedSubmissionIds = new Set<string>()) => render(<QueryClientProvider client={client}><TaskChatComposer onAdd={onAdd} workMode="standard" draftKey={key} confirmedSubmissionIds={confirmedSubmissionIds} /></QueryClientProvider>);
|
||
show(); await flushAsync();
|
||
const resend = Array.from(container.querySelectorAll("button")).find(button => button.textContent === "Resend now")!;
|
||
flushSync(() => resend.click()); await flushAsync();
|
||
expect(onAdd).toHaveBeenCalledTimes(1);
|
||
show(new Set([attemptId])); await flushAsync();
|
||
expect(editable().textContent).toBe("Keep this next draft");
|
||
if (outcome === "success") finish(); else fail(new Error("Late rejected resend"));
|
||
await flushAsync();
|
||
expect(container.textContent).not.toContain("Late rejected resend");
|
||
expect(editable().textContent).toBe("Keep this next draft");
|
||
expect(localStorage.getItem(key)).toBe("Keep this next draft");
|
||
client.clear();
|
||
});
|
||
|
||
it("preserves the next draft when an uncertain submission is later confirmed after reload", async () => {
|
||
const key = "uncertain-with-next-draft";
|
||
let rejectSend!: (error: Error) => void;
|
||
const onAdd = vi.fn().mockReturnValue(new Promise<void>((_resolve, reject) => { rejectSend = reject; }));
|
||
render(<TaskChatComposer onAdd={onAdd} workMode="standard" draftKey={key} />);
|
||
typeText("First request");
|
||
pressKey("Enter", { metaKey: true });
|
||
await flushAsync();
|
||
const attemptId = loadDraftSubmission(key)!.attemptId;
|
||
typeText("Keep this next draft");
|
||
rejectSend(new CommentSubmissionUnknownError());
|
||
await flushAsync();
|
||
render(<div>Another task</div>);
|
||
render(<TaskChatComposer onAdd={onAdd} workMode="standard" draftKey={key}
|
||
confirmedSubmissionIds={new Set([attemptId])} />);
|
||
await flushAsync();
|
||
expect(editable().textContent).toBe("Keep this next draft");
|
||
expect(localStorage.getItem(key)).toBe("Keep this next draft");
|
||
expect(loadDraftSubmission(key)).toBeNull();
|
||
expect(onAdd).toHaveBeenCalledTimes(1);
|
||
});
|
||
|
||
it.each(["acknowledgment", "receipt after reload"])("preserves a next draft across navigation before %s", async (confirmation) => {
|
||
const key = "navigate-with-next-draft";
|
||
let resolveSend!: () => void;
|
||
const onAdd = vi.fn().mockReturnValue(new Promise<void>(resolve => { resolveSend = resolve; }));
|
||
render(<TaskChatComposer onAdd={onAdd} workMode="standard" draftKey={key} />);
|
||
typeText("First request");
|
||
pressKey("Enter", { metaKey: true });
|
||
await flushAsync();
|
||
const attemptId = loadDraftSubmission(key)!.attemptId;
|
||
typeText("Keep the unsent next request");
|
||
render(<div>Another task</div>);
|
||
if (confirmation === "acknowledgment") {
|
||
resolveSend();
|
||
await flushAsync();
|
||
}
|
||
render(<TaskChatComposer onAdd={onAdd} workMode="standard" draftKey={key}
|
||
confirmedSubmissionIds={new Set([attemptId])} />);
|
||
await flushAsync();
|
||
expect(editable().textContent).toBe("Keep the unsent next request");
|
||
expect(localStorage.getItem(key)).toBe("Keep the unsent next request");
|
||
expect(loadDraftSubmission(key)).toBeNull();
|
||
expect(onAdd).toHaveBeenCalledTimes(1);
|
||
resolveSend();
|
||
await flushAsync();
|
||
expect(localStorage.getItem(key)).toBe("Keep the unsent next request");
|
||
});
|
||
|
||
it("does not copy another task's draft into a late acknowledged submission", async () => {
|
||
let resolveSend!: () => void;
|
||
const onAdd = vi.fn().mockReturnValue(new Promise<void>(resolve => { resolveSend = resolve; }));
|
||
render(<TaskChatComposer onAdd={onAdd} workMode="standard" draftKey="first-task" />);
|
||
typeText("First request");
|
||
pressKey("Enter", { metaKey: true });
|
||
await flushAsync();
|
||
render(<TaskChatComposer onAdd={onAdd} workMode="standard" draftKey="second-task" />);
|
||
typeText("Second task draft");
|
||
resolveSend();
|
||
await flushAsync();
|
||
expect(loadDraftSubmission("first-task")).toBeNull();
|
||
expect(localStorage.getItem("first-task")).toBeNull();
|
||
expect(editable().textContent).toBe("Second task draft");
|
||
});
|
||
|
||
it.each(["success", "unknown"])(
|
||
"does not overwrite another retained attempt after an older %s",
|
||
async (outcome) => {
|
||
const key = "exact-attempt-settlement";
|
||
let settle!: () => void;
|
||
const onAdd = vi.fn().mockReturnValue(
|
||
new Promise<void>((resolve, reject) => {
|
||
settle =
|
||
outcome === "success"
|
||
? resolve
|
||
: () => reject(new CommentSubmissionUnknownError());
|
||
}),
|
||
);
|
||
render(
|
||
<TaskChatComposer onAdd={onAdd} workMode="standard" draftKey={key} />,
|
||
);
|
||
typeText("Older request");
|
||
pressKey("Enter", { metaKey: true });
|
||
await flushAsync();
|
||
const newer = {
|
||
version: 1,
|
||
draftKey: key,
|
||
attemptId: "aaf8228f-0be7-45ae-a104-6fbe0af6f1d3",
|
||
reviewed: false,
|
||
};
|
||
localStorage.setItem(key, "Newer retained draft");
|
||
localStorage.setItem(`${key}:attachments:v1`, "newer receipt sentinel");
|
||
localStorage.setItem(`${key}:submission:v1`, JSON.stringify(newer));
|
||
settle();
|
||
await flushAsync();
|
||
await flushAsync();
|
||
window.dispatchEvent(new Event("beforeunload"));
|
||
expect(localStorage.getItem(`${key}:submission:v1`)).toBe(
|
||
JSON.stringify(newer),
|
||
);
|
||
expect(localStorage.getItem(key)).toBe("Newer retained draft");
|
||
expect(localStorage.getItem(`${key}:attachments:v1`)).toBe(
|
||
"newer receipt sentinel",
|
||
);
|
||
},
|
||
);
|
||
|
||
it("keeps an unconfirmed send in memory with disabled storage and resends it with the same request ID", async () => {
|
||
const storage = vi
|
||
.spyOn(Storage.prototype, "setItem")
|
||
.mockImplementation(() => {
|
||
throw new Error("Storage disabled");
|
||
});
|
||
const onAdd = vi
|
||
.fn()
|
||
.mockRejectedValueOnce(new CommentSubmissionUnknownError())
|
||
.mockResolvedValue(undefined);
|
||
try {
|
||
renderComposer({
|
||
onAdd: onAdd,
|
||
workMode: "standard",
|
||
draftKey: "storage-disabled",
|
||
});
|
||
typeText("Send this exactly once");
|
||
pressKey("Enter", { metaKey: true });
|
||
await flushAsync();
|
||
await flushAsync();
|
||
expect(sendButton().disabled).toBe(true);
|
||
expect(container.textContent).toContain("Sending when reconnected…");
|
||
expect(container.textContent).not.toContain("Discard draft");
|
||
pressKey("Enter", { metaKey: true });
|
||
await flushAsync();
|
||
expect(onAdd).toHaveBeenCalledTimes(1);
|
||
const resend = Array.from(container.querySelectorAll("button")).find(
|
||
(button) => button.textContent === "Resend now",
|
||
)!;
|
||
flushSync(() => resend.click());
|
||
await flushAsync();
|
||
await flushAsync();
|
||
expect(onAdd).toHaveBeenCalledTimes(2);
|
||
// Same body and same client request ID, so the server dedupes.
|
||
expect(onAdd.mock.calls[1]?.[0]).toBe(onAdd.mock.calls[0]?.[0]);
|
||
expect(onAdd.mock.calls[1]?.[4]).toBe(onAdd.mock.calls[0]?.[4]);
|
||
expect(container.textContent).not.toContain("Sending when reconnected…");
|
||
expect(editable().textContent).toBe("");
|
||
} finally {
|
||
storage.mockRestore();
|
||
}
|
||
});
|
||
|
||
it("gives an unconfirmed send back to the editor on Cancel without resending it", async () => {
|
||
const onAdd = vi.fn().mockRejectedValue(new CommentSubmissionUnknownError());
|
||
render(<TaskChatComposer onAdd={onAdd} workMode="standard" draftKey="cancel-pending" />);
|
||
typeText("Keep my words");
|
||
pressKey("Enter", { metaKey: true });
|
||
await flushAsync();
|
||
await flushAsync();
|
||
expect(loadDraftSubmission("cancel-pending")?.request?.body).toBe("Keep my words");
|
||
const cancel = Array.from(container.querySelectorAll("button")).find(
|
||
(button) => button.textContent === "Cancel",
|
||
)!;
|
||
flushSync(() => cancel.click());
|
||
await flushAsync();
|
||
expect(container.textContent).not.toContain("Sending when reconnected…");
|
||
expect(editable().textContent).toBe("Keep my words");
|
||
expect(loadDraftSubmission("cancel-pending")).toBeNull();
|
||
expect(sendButton().disabled).toBe(false);
|
||
expect(onAdd).toHaveBeenCalledTimes(1);
|
||
});
|
||
|
||
it("puts the text back with readable copy when a resend is rejected", async () => {
|
||
const { ApiError } = await import("../../api/client");
|
||
const onAdd = vi
|
||
.fn()
|
||
.mockRejectedValueOnce(new CommentSubmissionUnknownError())
|
||
.mockRejectedValueOnce(new ApiError("Forbidden", 403, { error: "Forbidden" }));
|
||
render(<TaskChatComposer onAdd={onAdd} workMode="standard" draftKey="rejected-resend" />);
|
||
typeText("Rejected later");
|
||
pressKey("Enter", { metaKey: true });
|
||
await flushAsync();
|
||
await flushAsync();
|
||
const resend = Array.from(container.querySelectorAll("button")).find(
|
||
(button) => button.textContent === "Resend now",
|
||
)!;
|
||
flushSync(() => resend.click());
|
||
await flushAsync();
|
||
await flushAsync();
|
||
expect(onAdd).toHaveBeenCalledTimes(2);
|
||
expect(container.textContent).not.toContain("Sending when reconnected…");
|
||
expect(editable().textContent).toBe("Rejected later");
|
||
expect(container.textContent).toContain("Forbidden");
|
||
expect(loadDraftSubmission("rejected-resend")).toBeNull();
|
||
});
|
||
|
||
it("resends a comment sent before the session loaded once the account is known", async () => {
|
||
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||
const onAdd = vi
|
||
.fn()
|
||
.mockRejectedValueOnce(new CommentSubmissionUnknownError())
|
||
.mockResolvedValue(undefined);
|
||
render(
|
||
<QueryClientProvider client={client}>
|
||
<TaskChatComposer onAdd={onAdd} workMode="standard" draftKey="owner-late" />
|
||
</QueryClientProvider>,
|
||
);
|
||
typeText("Sent before the session");
|
||
pressKey("Enter", { metaKey: true });
|
||
await flushAsync();
|
||
await flushAsync();
|
||
// Until the account is known the send cannot be replayed.
|
||
const resendButton = () => Array.from(container.querySelectorAll("button")).find(
|
||
(button) => button.textContent === "Resend now",
|
||
);
|
||
expect(resendButton()).toBeUndefined();
|
||
|
||
act(() => {
|
||
client.setQueryData(queryKeys.auth.session, { user: { id: "user-1" } });
|
||
});
|
||
await flushAsync();
|
||
await flushAsync();
|
||
expect(loadDraftSubmission("owner-late")?.requestOwner).toBe("user-1");
|
||
expect(container.textContent).toContain("Sending when reconnected…");
|
||
flushSync(() => resendButton()!.click());
|
||
await flushAsync();
|
||
await flushAsync();
|
||
expect(onAdd).toHaveBeenCalledTimes(2);
|
||
expect(onAdd.mock.calls[1]?.[4]).toBe(onAdd.mock.calls[0]?.[4]);
|
||
expect(container.textContent).not.toContain("Sending when reconnected…");
|
||
client.clear();
|
||
});
|
||
|
||
it("never binds an account to a stored send that has no owner", async () => {
|
||
const key = "owner-unknown-stored";
|
||
saveDraft(key, "Stored without owner");
|
||
saveDraftSubmission(key, {
|
||
attemptId: "baf8228f-0be7-45ae-a104-6fbe0af6f1d3",
|
||
reviewed: false,
|
||
request: { body: "Stored without owner" },
|
||
});
|
||
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||
client.setQueryData(queryKeys.auth.session, { user: { id: "user-1" } });
|
||
const onAdd = vi.fn();
|
||
render(
|
||
<QueryClientProvider client={client}>
|
||
<TaskChatComposer onAdd={onAdd} workMode="standard" draftKey={key} />
|
||
</QueryClientProvider>,
|
||
);
|
||
await flushAsync();
|
||
expect(Array.from(container.querySelectorAll("button")).some(
|
||
(button) => button.textContent === "Resend now",
|
||
)).toBe(false);
|
||
expect(loadDraftSubmission(key)?.requestOwner).toBeUndefined();
|
||
expect(onAdd).not.toHaveBeenCalled();
|
||
client.clear();
|
||
});
|
||
|
||
it("restores an in-flight submission as uncertain only for its exact task key", async () => {
|
||
const key = "uncertain-task-one";
|
||
const attemptId = "9af8228f-0be7-45ae-a104-6fbe0af6f1d3";
|
||
saveDraft(key, "Retained unknown draft");
|
||
saveDraftSubmission(key, { attemptId, reviewed: false });
|
||
const onAdd = vi.fn();
|
||
render(
|
||
<StrictMode>
|
||
<TaskChatComposer onAdd={onAdd} workMode="standard" draftKey={key} />
|
||
</StrictMode>,
|
||
);
|
||
expect(editable().textContent).toBe("Retained unknown draft");
|
||
expect(sendButton().disabled).toBe(true);
|
||
expect(loadDraftSubmission(key)?.attemptId).toBe(attemptId);
|
||
render(
|
||
<StrictMode>
|
||
<TaskChatComposer
|
||
onAdd={onAdd}
|
||
workMode="standard"
|
||
draftKey="uncertain-task-two"
|
||
/>
|
||
</StrictMode>,
|
||
);
|
||
await flushAsync();
|
||
typeText("Separate task draft");
|
||
await flushAsync();
|
||
expect(sendButton().disabled).toBe(false);
|
||
expect(loadDraftSubmission(key)?.attemptId).toBe(attemptId);
|
||
expect(onAdd).not.toHaveBeenCalled();
|
||
});
|
||
it("retains explicit upload receipt IDs across a failed send without uploading again", async () => {
|
||
const onAdd = vi
|
||
.fn()
|
||
.mockRejectedValueOnce(new Error("try again"))
|
||
.mockResolvedValue(undefined);
|
||
const id = "9af8228f-0be7-45ae-a104-6fbe0af6f1d3";
|
||
const onAttachImage = vi.fn().mockResolvedValue({
|
||
id,
|
||
contentPath: `/api/attachments/${id}/content`,
|
||
originalFilename: "notes.txt",
|
||
});
|
||
renderComposer({
|
||
onAdd: onAdd,
|
||
workMode: "standard",
|
||
onAttachImage: onAttachImage,
|
||
});
|
||
typeText("Inspect the new file.");
|
||
pasteFiles([new File(["new bytes"], "notes.txt", { type: "text/plain" })]);
|
||
await flushAsync();
|
||
flushSync(() => sendButton().click());
|
||
await flushAsync();
|
||
expect(onAdd.mock.calls[0]?.[3]).toEqual([id]);
|
||
flushSync(() => sendButton().click());
|
||
await flushAsync();
|
||
expect(onAdd.mock.calls[1]?.[3]).toEqual([id]);
|
||
expect(onAttachImage).toHaveBeenCalledTimes(1);
|
||
});
|
||
|
||
it("keeps a failed upload and retries it only when asked", async () => {
|
||
const id = "9af8228f-0be7-45ae-a104-6fbe0af6f1d3";
|
||
const { ApiError } = await import("../../api/client");
|
||
const onAttachImage = vi
|
||
.fn()
|
||
.mockRejectedValueOnce(new ApiError("Unavailable", 503, { error: "tenant_app_unavailable" }))
|
||
.mockResolvedValue({ id, contentPath: `/api/attachments/${id}/content`, originalFilename: "notes.txt" });
|
||
render(<TaskChatComposer onAdd={vi.fn()} workMode="standard" onAttachImage={onAttachImage} />);
|
||
pasteFiles([new File(["bytes"], "notes.txt", { type: "text/plain" })]);
|
||
await flushAsync();
|
||
expect(container.textContent).toContain("Paperclip is restarting or updating");
|
||
expect(container.textContent).not.toContain("tenant_app_unavailable");
|
||
await new Promise((resolve) => setTimeout(resolve, 50));
|
||
expect(onAttachImage).toHaveBeenCalledTimes(1);
|
||
const retry = container.querySelector<HTMLButtonElement>('button[aria-label="Retry notes.txt"]')!;
|
||
flushSync(() => retry.click());
|
||
await flushAsync();
|
||
expect(onAttachImage).toHaveBeenCalledTimes(2);
|
||
expect(container.querySelector('button[aria-label="Retry notes.txt"]')).toBeNull();
|
||
expect(container.textContent).not.toContain("Paperclip is restarting or updating");
|
||
expect(sendButton().disabled).toBe(false);
|
||
});
|
||
|
||
it("holds submission while an image upload is pending and binds its receipt", async () => {
|
||
const onAdd = vi.fn().mockResolvedValue(undefined);
|
||
const id = "5e5f9946-c706-4785-8988-d4d6f0f499ab";
|
||
let resolveUpload!: (value: unknown) => void;
|
||
const onAttachImage = vi.fn().mockReturnValue(
|
||
new Promise((resolve) => {
|
||
resolveUpload = resolve;
|
||
}),
|
||
);
|
||
renderComposer({
|
||
onAdd: onAdd,
|
||
workMode: "standard",
|
||
onAttachImage: onAttachImage,
|
||
});
|
||
typeText("Inspect the picture.");
|
||
pasteFiles([new File(["png"], "image.png", { type: "image/png" })]);
|
||
await flushAsync();
|
||
expect(sendButton().disabled).toBe(true);
|
||
pressKey("Enter", { metaKey: true });
|
||
expect(onAdd).not.toHaveBeenCalled();
|
||
resolveUpload({
|
||
id,
|
||
contentPath: `/api/attachments/${id}/content`,
|
||
originalFilename: "image.png",
|
||
});
|
||
await flushAsync();
|
||
expect(editable().textContent).toBe("Inspect the picture.");
|
||
expect(container.querySelector('img[alt="image.png"]')).not.toBeNull();
|
||
flushSync(() => sendButton().click());
|
||
await flushAsync();
|
||
expect(onAdd.mock.calls[0]?.[3]).toEqual([id]);
|
||
});
|
||
|
||
it("does not infer binding from arbitrary pasted attachment Markdown", async () => {
|
||
const onAdd = vi.fn().mockResolvedValue(undefined);
|
||
render(<TaskChatComposer onAdd={onAdd} workMode="standard" />);
|
||
typeText(
|
||
"[old file](/api/attachments/9af8228f-0be7-45ae-a104-6fbe0af6f1d3/content)",
|
||
);
|
||
flushSync(() => sendButton().click());
|
||
await flushAsync();
|
||
expect(onAdd.mock.calls[0]?.[3]).toBeUndefined();
|
||
});
|
||
|
||
it("submits multiple retained file and image receipts but not removed selections", async () => {
|
||
const onAdd = vi.fn().mockResolvedValue(undefined);
|
||
const receipts = [
|
||
"9af8228f-0be7-45ae-a104-6fbe0af6f1d3",
|
||
"5e5f9946-c706-4785-8988-d4d6f0f499ab",
|
||
"975687b9-d594-46a1-8b9e-707de6480fd7",
|
||
"0aab5c84-8722-40f6-ae89-4b35040cedcf",
|
||
];
|
||
const onAttachImage = vi.fn().mockImplementation(async (file: File) => {
|
||
const id = receipts[onAttachImage.mock.calls.length - 1]!;
|
||
return {
|
||
id,
|
||
contentPath: `/api/attachments/${id}/content`,
|
||
originalFilename: file.name,
|
||
};
|
||
});
|
||
renderComposer({
|
||
onAdd: onAdd,
|
||
workMode: "standard",
|
||
onAttachImage: onAttachImage,
|
||
});
|
||
pasteFiles([
|
||
new File(["one"], "one.txt", { type: "text/plain" }),
|
||
new File(["two"], "two.txt", { type: "text/plain" }),
|
||
]);
|
||
await flushAsync();
|
||
pasteFiles([new File(["png"], "three.png", { type: "image/png" }), new File(["png"], "removed.png", { type: "image/png" })]);
|
||
typeText("Only this picture remains");
|
||
await flushAsync();
|
||
flushSync(() =>
|
||
container
|
||
.querySelector<HTMLButtonElement>(
|
||
'button[aria-label="Remove two.txt"]',
|
||
)!
|
||
.click(),
|
||
);
|
||
flushSync(() => container.querySelector<HTMLButtonElement>('button[aria-label="Remove removed.png"]')!.click());
|
||
flushSync(() => sendButton().click());
|
||
await flushAsync();
|
||
expect(onAdd.mock.calls[0]?.[3]).toEqual([receipts[0], receipts[2]]);
|
||
expect(onAdd.mock.calls[0]?.[0]).not.toContain("two.txt");
|
||
expect(onAdd.mock.calls[0]?.[0]).not.toContain("removed.png");
|
||
});
|
||
|
||
it("restores file and image previews after a fresh composer mount", async () => {
|
||
const onAdd = vi.fn().mockResolvedValue(undefined);
|
||
const ids = [
|
||
"9af8228f-0be7-45ae-a104-6fbe0af6f1d3",
|
||
"5e5f9946-c706-4785-8988-d4d6f0f499ab",
|
||
];
|
||
const onAttachImage = vi.fn().mockImplementation(async (file: File) => {
|
||
const id = ids[onAttachImage.mock.calls.length - 1]!;
|
||
return {
|
||
id,
|
||
contentPath: `/api/attachments/${id}/content`,
|
||
originalFilename: file.name,
|
||
};
|
||
});
|
||
const props = {
|
||
onAdd,
|
||
workMode: "standard" as const,
|
||
onAttachImage,
|
||
draftKey: "receipt-reload",
|
||
};
|
||
render(<TaskChatComposer {...props} />);
|
||
pasteFiles([new File(["text"], "file.txt", { type: "text/plain" })]);
|
||
await flushAsync();
|
||
pasteFiles([new File(["png"], "clipboard-image", { type: "image/png" })]);
|
||
typeText("Inspect both files");
|
||
await flushAsync();
|
||
render(<div />);
|
||
render(<TaskChatComposer {...props} />);
|
||
await flushAsync();
|
||
expect(container.textContent).toContain("file.txt");
|
||
expect(editable().textContent).toBe("Inspect both files");
|
||
expect(container.querySelector('img[alt="clipboard-image"]')?.getAttribute("src")).toBe(`/api/attachments/${ids[1]}/content`);
|
||
flushSync(() => sendButton().click());
|
||
await flushAsync();
|
||
expect(onAdd.mock.calls[0]?.[3]).toEqual(ids);
|
||
expect(onAttachImage).toHaveBeenCalledTimes(2);
|
||
expect(localStorage.getItem("receipt-reload:attachments:v1")).toBeNull();
|
||
});
|
||
|
||
it("removes a pending image without a late insertion or restored receipt", async () => {
|
||
const onAdd = vi.fn().mockResolvedValue(undefined);
|
||
let resolveUpload!: (value: unknown) => void;
|
||
const onAttachImage = vi.fn().mockReturnValue(
|
||
new Promise((resolve) => {
|
||
resolveUpload = resolve;
|
||
}),
|
||
);
|
||
renderComposer({
|
||
onAdd: onAdd,
|
||
workMode: "standard",
|
||
onAttachImage: onAttachImage,
|
||
draftKey: "removed-pending",
|
||
});
|
||
typeText("Keep this text");
|
||
pasteFiles([new File(["png"], "pending.png", { type: "image/png" })]);
|
||
await flushAsync();
|
||
expect(container.textContent).toContain("pending.png");
|
||
expect(sendButton().disabled).toBe(true);
|
||
flushSync(() =>
|
||
container
|
||
.querySelector<HTMLButtonElement>(
|
||
'button[aria-label="Remove pending.png"]',
|
||
)!
|
||
.click(),
|
||
);
|
||
resolveUpload({
|
||
id: "9af8228f-0be7-45ae-a104-6fbe0af6f1d3",
|
||
contentPath:
|
||
"/api/attachments/9af8228f-0be7-45ae-a104-6fbe0af6f1d3/content",
|
||
});
|
||
await flushAsync();
|
||
expect(editable().textContent).toBe("Keep this text");
|
||
expect(localStorage.getItem("removed-pending:attachments:v1")).toBeNull();
|
||
flushSync(() => sendButton().click());
|
||
await flushAsync();
|
||
expect(onAdd.mock.calls[0]?.[3]).toBeUndefined();
|
||
});
|
||
it("adds 10px to the composer's original 8px interior padding", () => {
|
||
render(<TaskChatComposer onAdd={async () => {}} workMode="standard" />);
|
||
|
||
const composer = container.querySelector(
|
||
'[data-testid="task-chat-composer-input"]',
|
||
)?.parentElement;
|
||
|
||
expect(composer?.className).toContain("p-(--sz-18px)");
|
||
expect(composer?.className).not.toContain("p-2");
|
||
});
|
||
|
||
it("leaves an 8px token gap between the editor and action row", () => {
|
||
renderComposer({
|
||
onAdd: async () => {},
|
||
workMode: "planning",
|
||
onWorkModeChange: async () => {},
|
||
});
|
||
|
||
const actions = container.querySelector(
|
||
'[data-testid="task-chat-composer-actions"]',
|
||
);
|
||
|
||
expect(actions?.classList).toContain("mt-2");
|
||
expect(actions?.classList).not.toContain("mt-1");
|
||
});
|
||
|
||
it("renders a light card shell while preserving the borderless dark treatment", () => {
|
||
renderComposer({
|
||
onAdd: async () => {},
|
||
workMode: "planning",
|
||
onWorkModeChange: async () => {},
|
||
enableReassign: true,
|
||
currentAssigneeValue: "agent:runner",
|
||
reassignOptions: [{ id: "agent:runner", label: "Runner" }],
|
||
});
|
||
|
||
const composer = container.querySelector<HTMLElement>(".paperclip-task-chat-composer")!;
|
||
const mode = container.querySelector<HTMLElement>(
|
||
'[data-testid="task-chat-composer-mode"]',
|
||
)!;
|
||
const runner = container.querySelector<HTMLElement>(
|
||
'[data-testid="task-chat-composer-assignee"]',
|
||
)!;
|
||
|
||
expect(composer.classList).toContain("border");
|
||
expect(composer.classList).toContain("border-border");
|
||
expect(composer.classList).toContain("bg-card");
|
||
expect(composer.classList).toContain("shadow-(--shadow-task-composer)");
|
||
expect(composer.classList).toContain("dark:border-0");
|
||
expect(composer.classList).toContain("dark:bg-muted");
|
||
expect(composer.classList).toContain("dark:shadow-none");
|
||
expect(composer.className).not.toContain("focus-within:ring");
|
||
expect(mode.classList).toContain("rounded-full");
|
||
expect(mode.getAttribute("aria-label")).toBe("Remove Plan mode");
|
||
expect(runner.classList).toContain("border-0");
|
||
expect(runner.classList).not.toContain("border");
|
||
expect(runner.className).not.toContain("ring-2");
|
||
});
|
||
|
||
it("scopes the wrapping placeholder override to the task-chat composer", () => {
|
||
render(<TaskChatComposer onAdd={vi.fn()} workMode="standard" />);
|
||
|
||
expect(container.querySelector("[data-testid='task-chat-composer-input']")?.parentElement?.classList).toContain(
|
||
"paperclip-task-chat-composer",
|
||
);
|
||
});
|
||
|
||
it("uses a compact mobile editor that can grow with the message", () => {
|
||
render(<TaskChatComposer onAdd={vi.fn()} workMode="standard" mobile />);
|
||
|
||
expect(editable().dataset.contentClassName).toContain("min-h-(--sz-48px)");
|
||
expect(editable().dataset.contentClassName).toContain("max-h-(--tc-composer-editor-max-height)");
|
||
});
|
||
|
||
it("submits the trimmed body on Cmd+Enter and clears the draft", async () => {
|
||
const onAdd = vi.fn().mockResolvedValue(undefined);
|
||
render(<TaskChatComposer onAdd={onAdd} workMode="standard" />);
|
||
|
||
expect(sendButton().disabled).toBe(true);
|
||
typeText(" hello there ");
|
||
expect(sendButton().disabled).toBe(false);
|
||
|
||
pressKey("Enter", { metaKey: true });
|
||
await flushAsync();
|
||
await flushAsync();
|
||
|
||
expect(onAdd).toHaveBeenCalledWith("hello there", undefined, undefined, undefined, expect.any(String));
|
||
expect(editable().textContent).toBe("");
|
||
});
|
||
|
||
it("submits on Ctrl+Enter", async () => {
|
||
const onAdd = vi.fn().mockResolvedValue(undefined);
|
||
render(<TaskChatComposer onAdd={onAdd} workMode="standard" />);
|
||
|
||
typeText("hello");
|
||
pressKey("Enter", { ctrlKey: true });
|
||
await flushAsync();
|
||
|
||
expect(onAdd).toHaveBeenCalledWith("hello", undefined, undefined, undefined, expect.any(String));
|
||
});
|
||
|
||
it.each(["standard", "ask", "planning"] as const)("submits %s messages on Enter by default", async (workMode) => {
|
||
const onAdd = vi.fn().mockResolvedValue(undefined);
|
||
render(<TaskChatComposer onAdd={onAdd} workMode={workMode} />);
|
||
typeText("hello");
|
||
expect(sendButton().title).toBe("Send (Enter)");
|
||
pressKey("Enter");
|
||
await flushAsync();
|
||
expect(onAdd).toHaveBeenCalledWith("hello", undefined, undefined, undefined, expect.any(String));
|
||
});
|
||
|
||
it("does not submit on Shift+Enter (newline stays with the editor)", async () => {
|
||
const onAdd = vi.fn().mockResolvedValue(undefined);
|
||
render(<TaskChatComposer onAdd={onAdd} workMode="standard" />);
|
||
|
||
typeText("line one");
|
||
pressKey("Enter", { shiftKey: true });
|
||
await flushAsync();
|
||
|
||
expect(onAdd).not.toHaveBeenCalled();
|
||
expect(editable().textContent).toBe("line one");
|
||
});
|
||
|
||
it.each([false, true])("uses the experimental shortcut preference for new tasks (legacy=%s)", async (legacy) => {
|
||
const client = new QueryClient({ defaultOptions: { queries: { staleTime: Infinity, retry: false } } });
|
||
client.setQueryData(queryKeys.instance.experimentalSettings, { enableLegacyComposerSubmit: legacy });
|
||
const creation = {
|
||
value: "Create this task", onChange: vi.fn(), onSubmit: vi.fn().mockResolvedValue(undefined),
|
||
submitLabel: "Create task", onSelectFiles: vi.fn(), runSettings: null, onRunSettingsChange: vi.fn(),
|
||
};
|
||
render(<QueryClientProvider client={client}><TaskChatComposer creation={creation} workMode="standard" /></QueryClientProvider>);
|
||
expect(sendButton().title).toBe(`Create task (${legacy ? "⌘/Ctrl+Enter" : "Enter"})`);
|
||
pressKey("Enter", { shiftKey: true });
|
||
expect(creation.onSubmit).not.toHaveBeenCalled();
|
||
pressKey("Enter");
|
||
await flushAsync();
|
||
if (legacy) {
|
||
expect(creation.onSubmit).not.toHaveBeenCalled();
|
||
pressKey("Enter", { metaKey: true });
|
||
await flushAsync();
|
||
}
|
||
expect(creation.onSubmit).toHaveBeenCalledExactlyOnceWith(creation.value, "standard", null);
|
||
});
|
||
|
||
it.each([false, true])("waits for the saved shortcut preference before enabling Enter submission (legacy=%s)", async (legacy) => {
|
||
let resolveSettings!: (settings: Awaited<ReturnType<typeof instanceSettingsApi.getExperimental>>) => void;
|
||
const pendingSettings = new Promise<Awaited<ReturnType<typeof instanceSettingsApi.getExperimental>>>((resolve) => {
|
||
resolveSettings = resolve;
|
||
});
|
||
const getSettings = vi.spyOn(instanceSettingsApi, "getExperimental").mockReturnValue(pendingSettings);
|
||
const client = new QueryClient({ defaultOptions: { queries: { staleTime: Infinity, retry: false } } });
|
||
const onAdd = vi.fn().mockResolvedValue(undefined);
|
||
try {
|
||
render(<QueryClientProvider client={client}><TaskChatComposer onAdd={onAdd} workMode="standard" /></QueryClientProvider>);
|
||
typeText("Keep this draft");
|
||
pressKey("Enter");
|
||
await flushAsync();
|
||
expect(onAdd).not.toHaveBeenCalled();
|
||
expect(editable().textContent).toBe("Keep this draft");
|
||
|
||
await act(async () => {
|
||
resolveSettings(instanceExperimentalSettingsSchema.parse({ enableLegacyComposerSubmit: legacy }));
|
||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||
});
|
||
await flushAsync();
|
||
pressKey("Enter");
|
||
await flushAsync();
|
||
if (legacy) {
|
||
expect(onAdd).not.toHaveBeenCalled();
|
||
pressKey("Enter", { metaKey: true });
|
||
await flushAsync();
|
||
}
|
||
expect(onAdd).toHaveBeenCalledTimes(1);
|
||
} finally {
|
||
getSettings.mockRestore();
|
||
}
|
||
});
|
||
|
||
it("restores the old shortcut for task replies and updates the preference without remounting", async () => {
|
||
const client = new QueryClient({ defaultOptions: { queries: { staleTime: Infinity, retry: false } } });
|
||
client.setQueryData(queryKeys.instance.experimentalSettings, { enableLegacyComposerSubmit: true });
|
||
const onAdd = vi.fn().mockResolvedValue(undefined);
|
||
render(<QueryClientProvider client={client}><TaskChatComposer onAdd={onAdd} workMode="standard" /></QueryClientProvider>);
|
||
typeText("first message");
|
||
expect(sendButton().title).toBe("Send (⌘/Ctrl+Enter)");
|
||
pressKey("Enter");
|
||
pressKey("Enter", { shiftKey: true });
|
||
await flushAsync();
|
||
expect(onAdd).not.toHaveBeenCalled();
|
||
pressKey("Enter", { ctrlKey: true });
|
||
await flushAsync();
|
||
expect(onAdd).toHaveBeenCalledTimes(1);
|
||
|
||
await act(async () => {
|
||
client.setQueryData(queryKeys.instance.experimentalSettings, { enableLegacyComposerSubmit: false });
|
||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||
});
|
||
typeText("second message");
|
||
expect(sendButton().title).toBe("Send (Enter)");
|
||
pressKey("Enter");
|
||
await flushAsync();
|
||
expect(onAdd).toHaveBeenCalledTimes(2);
|
||
});
|
||
|
||
it("reflects an externally updated task mode after mounting", async () => {
|
||
const onAdd = vi.fn();
|
||
const onWorkModeChange = vi.fn();
|
||
renderComposer({ onAdd, onWorkModeChange, workMode: "standard" });
|
||
expect(container.querySelector('[data-testid="task-chat-composer-mode"]')).toBeNull();
|
||
|
||
renderComposer({ onAdd, onWorkModeChange, workMode: "planning" });
|
||
await flushAsync();
|
||
expect(container.querySelector('[data-testid="task-chat-composer-mode"]')?.getAttribute("data-pending-work-mode"))
|
||
.toBe("planning");
|
||
});
|
||
|
||
it("keeps a local draft mode while persisted task data refreshes", async () => {
|
||
const onAdd = vi.fn();
|
||
const onWorkModeChange = vi.fn();
|
||
renderComposer({ onAdd, onWorkModeChange, workMode: "standard" });
|
||
pressKey("Tab", { shiftKey: true });
|
||
|
||
renderComposer({ onAdd, onWorkModeChange, workMode: "ask" });
|
||
await flushAsync();
|
||
expect(container.querySelector('[data-testid="task-chat-composer-mode"]')?.getAttribute("data-pending-work-mode"))
|
||
.toBe("planning");
|
||
expect(onWorkModeChange).not.toHaveBeenCalled();
|
||
|
||
// Matching task data does not acknowledge an unsent local choice.
|
||
renderComposer({ onAdd, onWorkModeChange, workMode: "planning" });
|
||
renderComposer({ onAdd, onWorkModeChange, workMode: "standard" });
|
||
await flushAsync();
|
||
expect(container.querySelector('[data-testid="task-chat-composer-mode"]')?.getAttribute("data-pending-work-mode"))
|
||
.toBe("planning");
|
||
});
|
||
|
||
it("keeps the chosen mode and message when an optimistic mode save rolls back", async () => {
|
||
const onAdd = vi.fn();
|
||
let rejectSave!: () => void;
|
||
function OptimisticModeHarness() {
|
||
const [workMode, setWorkMode] = useState<IssueWorkMode>("standard");
|
||
return <TaskChatComposer onAdd={onAdd} workMode={workMode} onWorkModeChange={(mode) => {
|
||
setWorkMode(mode);
|
||
return new Promise<void>((_resolve, reject) => {
|
||
rejectSave = () => {
|
||
setWorkMode("standard");
|
||
reject(new Error("Mode save rejected"));
|
||
};
|
||
});
|
||
}} />;
|
||
}
|
||
render(<OptimisticModeHarness />);
|
||
pressKey("Tab", { shiftKey: true });
|
||
typeText("Keep this planning message");
|
||
pressKey("Enter");
|
||
await flushAsync();
|
||
await act(async () => rejectSave());
|
||
await flushAsync();
|
||
|
||
expect(editable().textContent).toBe("Keep this planning message");
|
||
expect(container.querySelector('[data-testid="task-chat-composer-mode"]')?.getAttribute("data-pending-work-mode"))
|
||
.toBe("planning");
|
||
expect(onAdd).not.toHaveBeenCalled();
|
||
});
|
||
|
||
it.each([
|
||
["standard", "planning", "standard"],
|
||
["ask", "standard", "ask"],
|
||
] as const)("keeps next draft mode %s → %s → %s through successful send", async (savedMode, sentMode, nextMode) => {
|
||
let resolveSend!: () => void;
|
||
const onAdd = vi.fn().mockReturnValue(new Promise<void>((resolve) => { resolveSend = resolve; }));
|
||
function PendingSendHarness() {
|
||
const [workMode, setWorkMode] = useState<IssueWorkMode>(savedMode);
|
||
return <TaskChatComposer onAdd={onAdd} workMode={workMode}
|
||
onWorkModeChange={async (mode) => { setWorkMode(mode); }} />;
|
||
}
|
||
const selectedMode = () => container.querySelector('[data-testid="task-chat-composer-mode"]')
|
||
?.getAttribute("data-pending-work-mode") ?? "standard";
|
||
render(<PendingSendHarness />);
|
||
pressKey("Tab", { shiftKey: true });
|
||
expect(selectedMode()).toBe(sentMode);
|
||
typeText("First message");
|
||
pressKey("Enter");
|
||
await flushAsync();
|
||
expect(onAdd).toHaveBeenCalledTimes(1);
|
||
|
||
if (nextMode === "standard") {
|
||
flushSync(() => container.querySelector<HTMLButtonElement>('[data-testid="task-chat-composer-mode"]')!.click());
|
||
} else {
|
||
pressKey("Tab", { shiftKey: true });
|
||
pressKey("Tab", { shiftKey: true });
|
||
}
|
||
expect(selectedMode()).toBe(nextMode);
|
||
typeText("Next message");
|
||
await act(async () => resolveSend());
|
||
await flushAsync();
|
||
expect(selectedMode()).toBe(nextMode);
|
||
expect(editable().textContent).toBe("Next message");
|
||
});
|
||
|
||
it.each([
|
||
["receipt", false], ["receipt", true],
|
||
["resend", false], ["resend", true],
|
||
] as const)("settles the sent mode through %s without clearing a newer choice (%s)", async (method, newerChoice) => {
|
||
const key = `mode-settlement-${method}-${newerChoice}`;
|
||
const onAdd = vi.fn().mockRejectedValueOnce(new CommentSubmissionUnknownError()).mockResolvedValue(undefined);
|
||
const onWorkModeChange = vi.fn().mockResolvedValue(undefined);
|
||
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||
client.setQueryData(queryKeys.auth.session, { user: { id: "user-1" } });
|
||
const show = (workMode: IssueWorkMode, confirmedSubmissionIds = new Set<string>()) => render(
|
||
<QueryClientProvider client={client}><TaskChatComposer onAdd={onAdd} workMode={workMode}
|
||
onWorkModeChange={onWorkModeChange} draftKey={key} confirmedSubmissionIds={confirmedSubmissionIds} /></QueryClientProvider>,
|
||
);
|
||
show("standard");
|
||
await flushAsync();
|
||
pressKey("Tab", { shiftKey: true });
|
||
typeText("First message");
|
||
pressKey("Enter", { metaKey: true });
|
||
await flushAsync();
|
||
expect(onAdd).toHaveBeenCalledTimes(1);
|
||
const intent = loadDraftSubmission(key)!;
|
||
expect(intent).not.toBeNull();
|
||
show("planning");
|
||
if (newerChoice) pressKey("Tab", { shiftKey: true });
|
||
|
||
if (method === "receipt") show("planning", new Set([intent.attemptId]));
|
||
else {
|
||
const resend = Array.from(container.querySelectorAll("button")).find(button => button.textContent === "Resend now")!;
|
||
flushSync(() => resend.click());
|
||
}
|
||
await flushAsync();
|
||
expect(loadDraftSubmission(key)).toBeNull();
|
||
show("standard");
|
||
await flushAsync();
|
||
expect(container.querySelector('[data-testid="task-chat-composer-mode"]')?.getAttribute("data-pending-work-mode") ?? "standard")
|
||
.toBe(newerChoice ? "ask" : "standard");
|
||
expect(onAdd).toHaveBeenCalledTimes(method === "receipt" ? 1 : 2);
|
||
if (method === "resend") expect(onAdd.mock.calls[1]?.[4]).toBe(intent.attemptId);
|
||
client.clear();
|
||
});
|
||
|
||
it("cycles the pending mode with Shift+Tab and applies it on submit", async () => {
|
||
const onAdd = vi.fn().mockResolvedValue(undefined);
|
||
const onWorkModeChange = vi.fn().mockResolvedValue(undefined);
|
||
renderComposer({
|
||
onAdd: onAdd,
|
||
workMode: "standard",
|
||
onWorkModeChange: onWorkModeChange,
|
||
});
|
||
|
||
expect(container.querySelector('[data-testid="task-chat-composer-add"]')).not.toBeNull();
|
||
expect(container.querySelector('[data-testid="task-chat-composer-mode"]')).toBeNull();
|
||
|
||
pressKey("Tab", { shiftKey: true });
|
||
const chip = container.querySelector<HTMLButtonElement>(
|
||
'[data-testid="task-chat-composer-mode"]',
|
||
)!;
|
||
expect(chip.getAttribute("data-pending-work-mode")).toBe("planning");
|
||
expect(chip.textContent).toContain("Plan");
|
||
|
||
typeText("do the plan");
|
||
pressKey("Enter", { metaKey: true });
|
||
await flushAsync();
|
||
|
||
expect(onWorkModeChange).toHaveBeenCalledWith("planning");
|
||
expect(onAdd).toHaveBeenCalledWith("do the plan", undefined, undefined, undefined, expect.any(String));
|
||
|
||
renderComposer({ onAdd, onWorkModeChange, workMode: "ask" });
|
||
await flushAsync();
|
||
expect(container.querySelector('[data-testid="task-chat-composer-mode"]')?.getAttribute("data-pending-work-mode"))
|
||
.toBe("ask");
|
||
});
|
||
|
||
it("cycles Auto, Plan, and Ask modes with Cmd+Period while focused", () => {
|
||
const onWorkModeChange = vi.fn().mockResolvedValue(undefined);
|
||
renderComposer({
|
||
onAdd: vi.fn(),
|
||
workMode: "standard",
|
||
onWorkModeChange: onWorkModeChange,
|
||
});
|
||
|
||
editable().focus();
|
||
|
||
expect(container.querySelector('[data-testid="task-chat-composer-add"]')?.getAttribute("aria-keyshortcuts")).toContain("Meta+Period");
|
||
expect(container.querySelector('[data-testid="task-chat-composer-mode"]')).toBeNull();
|
||
|
||
const cycleMode = () => {
|
||
const event = new KeyboardEvent("keydown", {
|
||
key: ".",
|
||
code: "Period",
|
||
metaKey: true,
|
||
bubbles: true,
|
||
cancelable: true,
|
||
});
|
||
flushSync(() => editable().dispatchEvent(event));
|
||
expect(event.defaultPrevented).toBe(true);
|
||
};
|
||
|
||
cycleMode();
|
||
const chip = container.querySelector<HTMLButtonElement>('[data-testid="task-chat-composer-mode"]')!;
|
||
expect(chip.getAttribute("data-pending-work-mode")).toBe("planning");
|
||
expect(chip.textContent).toContain("Plan");
|
||
|
||
cycleMode();
|
||
expect(chip.getAttribute("data-pending-work-mode")).toBe("ask");
|
||
expect(chip.textContent).toContain("Ask");
|
||
|
||
cycleMode();
|
||
expect(container.querySelector('[data-testid="task-chat-composer-mode"]')).toBeNull();
|
||
expect(onWorkModeChange).not.toHaveBeenCalled();
|
||
});
|
||
|
||
it("selects exclusive modes from the add menu and removes the active chip", () => {
|
||
render(<TaskChatComposer onAdd={vi.fn()} workMode="standard" onWorkModeChange={vi.fn()} />);
|
||
openComposerAddMenu();
|
||
expect(document.querySelector('[data-testid="composer-add-file"]')).toBeNull();
|
||
flushSync(() => (document.querySelector('[data-testid="composer-add-plan"]') as HTMLElement).click());
|
||
expect(container.querySelector('[data-testid="task-chat-composer-mode"]')?.textContent).toContain("Plan mode");
|
||
|
||
openComposerAddMenu();
|
||
flushSync(() => (document.querySelector('[data-testid="composer-add-ask"]') as HTMLElement).click());
|
||
expect(container.querySelector('[data-testid="task-chat-composer-mode"]')?.textContent).toContain("Ask mode");
|
||
|
||
flushSync(() => (container.querySelector('[data-testid="task-chat-composer-mode"]') as HTMLElement).click());
|
||
expect(container.querySelector('[data-testid="task-chat-composer-mode"]')).toBeNull();
|
||
});
|
||
|
||
it("opens a mobile Add dialog while keeping Send at the end of the footer", () => {
|
||
render(<TaskChatComposer onAdd={vi.fn()} workMode="standard" onWorkModeChange={vi.fn()}
|
||
onAttachImage={vi.fn().mockResolvedValue(undefined)} mobile enableReassign
|
||
reassignOptions={[{ id: "agent:codex", label: "Codie" }]}
|
||
currentAssigneeValue="agent:codex" />);
|
||
|
||
const actions = container.querySelector<HTMLElement>('[data-testid="task-chat-composer-actions"]')!;
|
||
expect(actions.lastElementChild?.lastElementChild).toBe(sendButton());
|
||
expect(actions.firstElementChild?.contains(sendButton())).toBe(false);
|
||
expect(actions.lastElementChild?.querySelector('[data-testid="task-chat-composer-assignee"]')).not.toBeNull();
|
||
expect(actions.querySelector('[data-testid="task-chat-composer-assignee"] [data-slot="agent-avatar"] img')).not.toBeNull();
|
||
|
||
flushSync(() => container.querySelector<HTMLButtonElement>('[data-testid="task-chat-composer-add"]')!.click());
|
||
const dialog = document.querySelector<HTMLElement>('[role="dialog"]');
|
||
expect(dialog?.textContent).toContain("Files and images");
|
||
expect(dialog?.textContent).toContain("Plan mode");
|
||
expect(dialog?.textContent).toContain("Ask mode");
|
||
|
||
flushSync(() => document.querySelector<HTMLButtonElement>('[data-testid="composer-add-plan"]')!.click());
|
||
const mode = container.querySelector<HTMLElement>('[data-testid="task-chat-composer-mode"]')!;
|
||
expect(mode.textContent).toContain("Plan mode");
|
||
expect(actions.contains(mode)).toBe(true);
|
||
expect(mode.querySelector(".sr-only")?.textContent).toBe("Plan mode");
|
||
expect(document.querySelector('[role="dialog"][data-state="open"]')).toBeNull();
|
||
});
|
||
|
||
it("opens the mobile file picker from the Add dialog", () => {
|
||
render(<TaskChatComposer onAdd={vi.fn()} workMode="standard" mobile
|
||
onAttachImage={vi.fn().mockResolvedValue(undefined)} />);
|
||
const input = container.querySelector<HTMLInputElement>('input[type="file"]')!;
|
||
const openPicker = vi.spyOn(input, "click").mockImplementation(() => {});
|
||
flushSync(() => container.querySelector<HTMLButtonElement>('[data-testid="task-chat-composer-add"]')!.click());
|
||
flushSync(() => document.querySelector<HTMLButtonElement>('[data-testid="composer-add-file"]')!.click());
|
||
expect(openPicker).toHaveBeenCalledOnce();
|
||
});
|
||
|
||
it("uses the Add dialog through the mobile shell's tablet breakpoint", () => {
|
||
const matchMedia = vi.fn((query: string) => ({
|
||
media: query,
|
||
matches: query === "(max-width: 767px)",
|
||
addEventListener: vi.fn(),
|
||
removeEventListener: vi.fn(),
|
||
} as unknown as MediaQueryList));
|
||
vi.stubGlobal("matchMedia", matchMedia);
|
||
try {
|
||
render(<ComposerAddMenu mode="standard" onModeChange={vi.fn()} />);
|
||
flushSync(() => container.querySelector<HTMLButtonElement>('[aria-label="Add to composer"]')!.click());
|
||
expect(document.querySelector('[role="dialog"]')).not.toBeNull();
|
||
expect(matchMedia).toHaveBeenCalledWith("(max-width: 767px)");
|
||
} finally {
|
||
vi.unstubAllGlobals();
|
||
}
|
||
});
|
||
|
||
it("uses the borderless Paper controls and inverse circular send button", () => {
|
||
renderComposer({
|
||
onAdd: vi.fn(),
|
||
workMode: "standard",
|
||
onWorkModeChange: vi.fn(),
|
||
enableReassign: true,
|
||
reassignOptions: [{ id: "agent:a1", label: "Chief of Staff" }],
|
||
currentAssigneeValue: "agent:a1",
|
||
});
|
||
|
||
const add = container.querySelector<HTMLButtonElement>(
|
||
'[data-testid="task-chat-composer-add"]',
|
||
)!;
|
||
const assignee = container.querySelector<HTMLButtonElement>(
|
||
'[data-testid="task-chat-composer-assignee"]',
|
||
)!;
|
||
const send = sendButton();
|
||
|
||
expect(add.classList).not.toContain("border");
|
||
expect(add.getAttribute("aria-label")).toBe("Add to composer");
|
||
expect(container.querySelector('[data-testid="task-chat-composer-mode"]')).toBeNull();
|
||
expect(assignee.classList).toContain("border-0");
|
||
expect(assignee.classList).toContain("shadow-none");
|
||
expect(send.classList).toContain("rounded-full");
|
||
expect(send.classList).toContain("bg-foreground");
|
||
expect(send.classList).toContain("text-background");
|
||
expect(send.classList).toContain("disabled:opacity-100");
|
||
});
|
||
|
||
it("passes reopen=true when the issue resumes-to-todo and the assignee is an agent", async () => {
|
||
const onAdd = vi.fn().mockResolvedValue(undefined);
|
||
renderComposer({
|
||
onAdd: onAdd,
|
||
workMode: "standard",
|
||
issueStatus: "done",
|
||
currentAssigneeValue: "agent:a1",
|
||
});
|
||
|
||
typeText("wake up");
|
||
pressKey("Enter", { metaKey: true });
|
||
await flushAsync();
|
||
|
||
expect(onAdd).toHaveBeenCalledWith("wake up", true, undefined, undefined, expect.any(String));
|
||
});
|
||
|
||
it("shows the add menu only when at least one action is available", () => {
|
||
render(<TaskChatComposer onAdd={vi.fn()} workMode="standard" />);
|
||
expect(
|
||
container.querySelector('[data-testid="task-chat-composer-add"]'),
|
||
).toBeNull();
|
||
|
||
renderComposer({
|
||
onAdd: vi.fn(),
|
||
workMode: "standard",
|
||
onAttachImage: vi.fn().mockResolvedValue(undefined),
|
||
});
|
||
expect(
|
||
container.querySelector('[data-testid="task-chat-composer-add"]'),
|
||
).not.toBeNull();
|
||
});
|
||
|
||
it("opens the file picker from the add menu", () => {
|
||
render(<TaskChatComposer onAdd={vi.fn()} workMode="standard"
|
||
onAttachImage={vi.fn().mockResolvedValue(undefined)} />);
|
||
const input = container.querySelector<HTMLInputElement>('input[type="file"]')!;
|
||
const openPicker = vi.spyOn(input, "click").mockImplementation(() => {});
|
||
openComposerAddMenu();
|
||
flushSync(() => document.querySelector<HTMLElement>('[data-testid="composer-add-file"]')!.click());
|
||
expect(openPicker).toHaveBeenCalledOnce();
|
||
});
|
||
|
||
it.each(["picker", "drop", "page drop"])("uploads images from %s into a preview row above the text", async (source) => {
|
||
const onAdd = vi.fn();
|
||
const onAttachImage = vi.fn().mockResolvedValue({ contentPath: "/attachments/shot.png" });
|
||
renderComposer({ onAdd, workMode: "standard", onAttachImage });
|
||
typeText("Review this image");
|
||
const file = new File(["png-bytes"], "shot.png", { type: "image/png" });
|
||
if (source === "picker") {
|
||
const input = container.querySelector<HTMLInputElement>('input[type="file"]')!;
|
||
Object.defineProperty(input, "files", { value: [file] });
|
||
flushSync(() => input.dispatchEvent(new Event("change", { bubbles: true })));
|
||
} else {
|
||
const event = new Event("drop", { bubbles: true, cancelable: true });
|
||
Object.defineProperty(event, "dataTransfer", { value: { types: ["Files"], files: [file] } });
|
||
flushSync(() => (source === "page drop" ? document.body : editable()).dispatchEvent(event));
|
||
expect(event.defaultPrevented).toBe(true);
|
||
}
|
||
await flushAsync();
|
||
const row = container.querySelector('[data-testid="task-chat-composer-images"]')!;
|
||
expect(row.querySelector('img')?.getAttribute("src")).toMatch(/^blob:/);
|
||
expect(row.compareDocumentPosition(editable()) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
|
||
expect(editable().textContent).toBe("Review this image");
|
||
expect(mdxEditorMockState.imagePluginOptions?.imageUploadHandler).toBeUndefined();
|
||
flushSync(() => sendButton().click());
|
||
await flushAsync();
|
||
expect(onAdd.mock.calls[0]?.[0]).toBe("Review this image\n\n");
|
||
});
|
||
|
||
it.each(["saved", "rejected", "unknown"] as const)("moves submitted screenshots out of the composer before the request is %s", async (outcome) => {
|
||
let resolveSend!: () => void;
|
||
let rejectSend!: (error: Error) => void;
|
||
const onAdd = vi.fn().mockReturnValue(new Promise<void>((resolve, reject) => {
|
||
resolveSend = resolve;
|
||
rejectSend = reject;
|
||
}));
|
||
const draftKey = `screenshots-${outcome}`;
|
||
const onAttachImage = vi.fn().mockResolvedValueOnce({
|
||
id: "8c365a89-5545-40f7-8cc0-ec6b20567827", contentPath: "/api/attachments/8c365a89-5545-40f7-8cc0-ec6b20567827/content", originalFilename: "shot.png", contentType: "image/png",
|
||
}).mockResolvedValue({
|
||
id: "266ff1d0-6be9-47cb-b2ed-300fce5fbcd3", contentPath: "/api/attachments/266ff1d0-6be9-47cb-b2ed-300fce5fbcd3/content", originalFilename: "next.png", contentType: "image/png",
|
||
});
|
||
renderComposer({ onAdd, workMode: "standard", draftKey, onAttachImage });
|
||
typeText("Check **this** screenshot");
|
||
pasteFiles([new File(["png"], "shot.png", { type: "image/png" })]);
|
||
await flushAsync();
|
||
expect(container.querySelector('[data-testid="task-chat-composer-images"]')).not.toBeNull();
|
||
|
||
flushSync(() => sendButton().click());
|
||
await flushAsync();
|
||
expect(onAdd.mock.calls[0]?.[0]).toBe("Check **this** screenshot\n\n");
|
||
expect(onAdd.mock.calls[0]?.[3]).toEqual(["8c365a89-5545-40f7-8cc0-ec6b20567827"]);
|
||
expect(editable().textContent).toBe("");
|
||
expect(container.querySelector('[data-testid="task-chat-composer-images"]')).toBeNull();
|
||
// Hiding the submitted preview must not discard its reload/retry receipt.
|
||
expect(loadDraftAttachments(draftKey).map(item => item.attachmentId)).toEqual(["8c365a89-5545-40f7-8cc0-ec6b20567827"]);
|
||
typeText("Next draft");
|
||
pasteFiles([new File(["next"], "next.png", { type: "image/png" })]);
|
||
await flushAsync();
|
||
expect(container.querySelector('img[alt="next.png"]')).not.toBeNull();
|
||
expect(container.querySelector('img[alt="shot.png"]')).toBeNull();
|
||
if (outcome === "saved") resolveSend();
|
||
else rejectSend(outcome === "unknown" ? new CommentSubmissionUnknownError() : new Error("Rejected"));
|
||
await flushAsync();
|
||
await flushAsync();
|
||
if (outcome === "saved") {
|
||
expect(container.querySelector('img[alt="shot.png"]')).toBeNull();
|
||
expect(editable().textContent).toBe("Next draft");
|
||
expect(loadDraftAttachments(draftKey).map(item => item.attachmentId)).toEqual(["266ff1d0-6be9-47cb-b2ed-300fce5fbcd3"]);
|
||
} else {
|
||
expect(container.querySelectorAll('img[alt="shot.png"]')).toHaveLength(1);
|
||
expect(editable().textContent).toBe("Check **this** screenshot\n\nNext draft");
|
||
expect(loadDraftAttachments(draftKey).map(item => item.attachmentId)).toEqual(["8c365a89-5545-40f7-8cc0-ec6b20567827", "266ff1d0-6be9-47cb-b2ed-300fce5fbcd3"]);
|
||
if (outcome === "unknown") expect(loadDraftSubmission(draftKey)?.request?.attachmentIds).toEqual(["8c365a89-5545-40f7-8cc0-ec6b20567827"]);
|
||
}
|
||
expect(container.querySelectorAll('img[alt="next.png"]')).toHaveLength(1);
|
||
});
|
||
|
||
it("keeps failed image uploads in the preview row for retry without changing the text", async () => {
|
||
const onAdd = vi.fn();
|
||
const onAttachImage = vi.fn().mockRejectedValueOnce(new Error("Too large"))
|
||
.mockResolvedValueOnce({ contentPath: "/attachments/retried.png" });
|
||
renderComposer({ onAdd, workMode: "standard", onAttachImage });
|
||
typeText("Keep the caption");
|
||
const file = new File(["png"], "retry.png", { type: "image/png" });
|
||
pasteFiles([file]);
|
||
await flushAsync();
|
||
expect(sendButton().disabled).toBe(true);
|
||
const retry = container.querySelector<HTMLButtonElement>('button[aria-label="Retry retry.png"]')!;
|
||
expect(retry).not.toBeNull();
|
||
flushSync(() => retry.click());
|
||
await flushAsync();
|
||
expect(onAttachImage).toHaveBeenCalledTimes(2);
|
||
expect(onAttachImage.mock.calls[1]?.[0]).toBe(file);
|
||
expect(editable().textContent).toBe("Keep the caption");
|
||
expect(sendButton().disabled).toBe(false);
|
||
flushSync(() => sendButton().click());
|
||
await flushAsync();
|
||
expect(onAdd.mock.calls[0]?.[0]).toBe("Keep the caption\n\n");
|
||
});
|
||
|
||
it("keeps existing image Markdown editable without an inline upload handler", () => {
|
||
localStorage.setItem("image-draft", "Caption\n\n");
|
||
render(<TaskChatComposer onAdd={vi.fn()} workMode="standard" draftKey="image-draft" />);
|
||
expect(editable().textContent).toContain("");
|
||
expect(mdxEditorMockState.imagePluginOptions).not.toBeNull();
|
||
expect(mdxEditorMockState.imagePluginOptions?.imageUploadHandler).toBeUndefined();
|
||
});
|
||
|
||
it("attaches pasted non-image files to the chip row and posts a link reference", async () => {
|
||
const onAdd = vi.fn().mockResolvedValue(undefined);
|
||
const onAttachImage = vi.fn().mockResolvedValue({
|
||
contentPath: "/attachments/notes.txt",
|
||
originalFilename: "notes.txt",
|
||
});
|
||
renderComposer({
|
||
onAdd: onAdd,
|
||
workMode: "standard",
|
||
onAttachImage: onAttachImage,
|
||
});
|
||
|
||
const file = new File(["plain"], "notes.txt", { type: "text/plain" });
|
||
const paste = pasteFiles([file]);
|
||
await flushAsync();
|
||
|
||
// The all-non-image paste is swallowed before the editor sees it.
|
||
expect(paste.defaultPrevented).toBe(true);
|
||
expect(onAttachImage).toHaveBeenCalledWith(file);
|
||
const chips = container.querySelector(
|
||
'[data-testid="task-chat-composer-attachments"]',
|
||
);
|
||
expect(chips?.textContent).toContain("notes.txt");
|
||
// base/attachment chip: kind · size description and a settled state.
|
||
expect(chips?.textContent).toContain("Text · 5 B");
|
||
expect(
|
||
chips
|
||
?.querySelector('[data-slot="attachment"]')
|
||
?.getAttribute("data-state"),
|
||
).toBe("done");
|
||
|
||
// The editor stays prose-only; the reference rides along at submit time,
|
||
// and an attached chip alone is enough to enable send.
|
||
expect(editable().textContent ?? "").not.toContain("notes.txt");
|
||
const send = container.querySelector<HTMLButtonElement>(
|
||
'[data-testid="task-chat-composer-send"]',
|
||
)!;
|
||
expect(send.disabled).toBe(false);
|
||
flushSync(() => send.click());
|
||
await flushAsync();
|
||
expect(onAdd).toHaveBeenCalledWith("[notes.txt](/attachments/notes.txt)", undefined, undefined, undefined, expect.any(String));
|
||
// Chips clear once the message posts.
|
||
expect(
|
||
container.querySelector('[data-testid="task-chat-composer-attachments"]'),
|
||
).toBeNull();
|
||
});
|
||
|
||
it("appends file references after typed prose on submit", async () => {
|
||
const onAdd = vi.fn().mockResolvedValue(undefined);
|
||
const onAttachImage = vi.fn().mockResolvedValue({
|
||
contentPath: "/attachments/notes.txt",
|
||
originalFilename: "notes.txt",
|
||
});
|
||
renderComposer({
|
||
onAdd: onAdd,
|
||
workMode: "standard",
|
||
onAttachImage: onAttachImage,
|
||
});
|
||
|
||
typeText("Please review this.");
|
||
pasteFiles([new File(["plain"], "notes.txt", { type: "text/plain" })]);
|
||
await flushAsync();
|
||
|
||
const send = container.querySelector<HTMLButtonElement>(
|
||
'[data-testid="task-chat-composer-send"]',
|
||
)!;
|
||
flushSync(() => send.click());
|
||
await flushAsync();
|
||
expect(onAdd).toHaveBeenCalledWith("Please review this.\n\n[notes.txt](/attachments/notes.txt)", undefined, undefined, undefined, expect.any(String));
|
||
});
|
||
|
||
it("blocks send while a file upload is pending, then includes the file once it lands", async () => {
|
||
const onAdd = vi.fn().mockResolvedValue(undefined);
|
||
let resolveUpload!: (value: {
|
||
contentPath: string;
|
||
originalFilename: string;
|
||
}) => void;
|
||
const onAttachImage = vi.fn().mockReturnValue(
|
||
new Promise<{ contentPath: string; originalFilename: string }>(
|
||
(resolve) => {
|
||
resolveUpload = resolve;
|
||
},
|
||
),
|
||
);
|
||
renderComposer({
|
||
onAdd: onAdd,
|
||
workMode: "standard",
|
||
onAttachImage: onAttachImage,
|
||
});
|
||
|
||
typeText("Here is the file.");
|
||
pasteFiles([new File(["plain"], "notes.txt", { type: "text/plain" })]);
|
||
await flushAsync();
|
||
|
||
// Text alone would enable send, but the in-flight upload must hold it —
|
||
// otherwise the comment posts without the file the user selected.
|
||
expect(sendButton().disabled).toBe(true);
|
||
pressKey("Enter", { metaKey: true });
|
||
await flushAsync();
|
||
expect(onAdd).not.toHaveBeenCalled();
|
||
|
||
resolveUpload({
|
||
contentPath: "/attachments/notes.txt",
|
||
originalFilename: "notes.txt",
|
||
});
|
||
await flushAsync();
|
||
expect(sendButton().disabled).toBe(false);
|
||
flushSync(() => sendButton().click());
|
||
await flushAsync();
|
||
expect(onAdd).toHaveBeenCalledWith("Here is the file.\n\n[notes.txt](/attachments/notes.txt)", undefined, undefined, undefined, expect.any(String));
|
||
});
|
||
|
||
it("blocks send while a failed attachment chip remains, then sends after it is removed", async () => {
|
||
const onAdd = vi.fn().mockResolvedValue(undefined);
|
||
const onAttachImage = vi.fn().mockRejectedValue(new Error("Too large"));
|
||
renderComposer({
|
||
onAdd: onAdd,
|
||
workMode: "standard",
|
||
onAttachImage: onAttachImage,
|
||
});
|
||
|
||
typeText("Here is the file.");
|
||
pasteFiles([new File(["plain"], "notes.txt", { type: "text/plain" })]);
|
||
await flushAsync();
|
||
|
||
// Text alone would enable send, but the failed chip must hold it —
|
||
// otherwise the comment posts without the file and the error chip clears.
|
||
expect(sendButton().disabled).toBe(true);
|
||
pressKey("Enter", { metaKey: true });
|
||
await flushAsync();
|
||
expect(onAdd).not.toHaveBeenCalled();
|
||
|
||
const remove = container.querySelector<HTMLButtonElement>(
|
||
'button[aria-label="Remove notes.txt"]',
|
||
);
|
||
flushSync(() => remove!.click());
|
||
expect(sendButton().disabled).toBe(false);
|
||
flushSync(() => sendButton().click());
|
||
await flushAsync();
|
||
expect(onAdd).toHaveBeenCalledWith("Here is the file.", undefined, undefined, undefined, expect.any(String));
|
||
});
|
||
|
||
it("removes an attachment chip via its remove button", async () => {
|
||
const onAttachImage = vi.fn().mockResolvedValue({
|
||
contentPath: "/attachments/notes.txt",
|
||
originalFilename: "notes.txt",
|
||
});
|
||
renderComposer({
|
||
onAdd: vi.fn(),
|
||
workMode: "standard",
|
||
onAttachImage: onAttachImage,
|
||
});
|
||
|
||
pasteFiles([new File(["plain"], "notes.txt", { type: "text/plain" })]);
|
||
await flushAsync();
|
||
|
||
const remove = container.querySelector<HTMLButtonElement>(
|
||
'button[aria-label="Remove notes.txt"]',
|
||
);
|
||
expect(remove).not.toBeNull();
|
||
flushSync(() => remove!.click());
|
||
expect(
|
||
container.querySelector('[data-testid="task-chat-composer-attachments"]'),
|
||
).toBeNull();
|
||
});
|
||
|
||
it("shows an error-state chip when a non-image upload fails", async () => {
|
||
const onAttachImage = vi.fn().mockRejectedValue(new Error("Too large"));
|
||
renderComposer({
|
||
onAdd: vi.fn(),
|
||
workMode: "standard",
|
||
onAttachImage: onAttachImage,
|
||
});
|
||
|
||
pasteFiles([new File(["plain"], "notes.txt", { type: "text/plain" })]);
|
||
await flushAsync();
|
||
|
||
const chips = container.querySelector(
|
||
'[data-testid="task-chat-composer-attachments"]',
|
||
);
|
||
expect(
|
||
chips
|
||
?.querySelector('[data-slot="attachment"]')
|
||
?.getAttribute("data-state"),
|
||
).toBe("error");
|
||
expect(chips?.textContent).toContain("Too large");
|
||
});
|
||
|
||
it("handles mixed image and document pastes without inserting images into the editor", async () => {
|
||
const onAttachImage = vi.fn().mockResolvedValue({
|
||
contentPath: "/attachments/notes.txt",
|
||
originalFilename: "notes.txt",
|
||
});
|
||
renderComposer({
|
||
onAdd: vi.fn(),
|
||
workMode: "standard",
|
||
onAttachImage: onAttachImage,
|
||
});
|
||
|
||
const image = new File(["png-bytes"], "shot.png", { type: "image/png" });
|
||
const text = new File(["plain"], "notes.txt", { type: "text/plain" });
|
||
const paste = pasteFiles([image, text]);
|
||
await flushAsync();
|
||
|
||
expect(paste.defaultPrevented).toBe(true);
|
||
const chips = container.querySelector(
|
||
'[data-testid="task-chat-composer-attachments"]',
|
||
)!;
|
||
expect(chips.textContent).toContain("notes.txt");
|
||
expect(chips.textContent).not.toContain("shot.png");
|
||
expect(container.querySelector('img[alt="shot.png"]')).not.toBeNull();
|
||
expect(editable().textContent).toBe("");
|
||
expect(onAttachImage).toHaveBeenCalledTimes(2);
|
||
expect(onAttachImage).toHaveBeenCalledWith(text);
|
||
expect(onAttachImage).toHaveBeenCalledWith(image);
|
||
});
|
||
|
||
it("inserts an @-mention from the autocomplete menu and posts it", async () => {
|
||
const onAdd = vi.fn().mockResolvedValue(undefined);
|
||
renderComposer({
|
||
onAdd: onAdd,
|
||
workMode: "standard",
|
||
mentions: [
|
||
{ id: "agent:a1", kind: "agent", name: "Clippy", agentId: "a1" },
|
||
],
|
||
});
|
||
|
||
typeText("@Cl");
|
||
await placeCaretAtEnd();
|
||
|
||
const option = autocompleteOption("Clippy");
|
||
flushSync(() => {
|
||
option.dispatchEvent(
|
||
new MouseEvent("mousedown", { bubbles: true, cancelable: true }),
|
||
);
|
||
});
|
||
await flushAsync();
|
||
|
||
const expected = `[@Clippy](${buildAgentMentionHref("a1", null)}) `;
|
||
expect(editable().textContent).toBe(expected);
|
||
|
||
pressKey("Enter", { metaKey: true });
|
||
await flushAsync();
|
||
expect(onAdd).toHaveBeenCalledWith(expected.trim(), undefined, undefined, undefined, expect.any(String));
|
||
});
|
||
|
||
it("does not submit an unselected slash menu with Enter", async () => {
|
||
const onAdd = vi.fn().mockResolvedValue(undefined);
|
||
render(<TaskChatComposer onAdd={onAdd} workMode="standard" />);
|
||
typeText("/dep");
|
||
await placeCaretAtEnd();
|
||
autocompleteOption("/deploy");
|
||
pressKey("Enter");
|
||
await flushAsync();
|
||
expect(onAdd).not.toHaveBeenCalled();
|
||
expect(editable().textContent).toBe("/dep");
|
||
|
||
pressKey("ArrowDown");
|
||
pressKey("Enter");
|
||
await flushAsync();
|
||
expect(onAdd).not.toHaveBeenCalled();
|
||
expect(editable().textContent).toBe(`[/deploy](${SLASH_HREF}) `);
|
||
pressKey("Enter", { metaKey: true });
|
||
await flushAsync();
|
||
expect(onAdd).toHaveBeenCalledTimes(1);
|
||
});
|
||
|
||
it("inserts a /-command from the autocomplete menu", async () => {
|
||
const onAdd = vi.fn().mockResolvedValue(undefined);
|
||
render(<TaskChatComposer onAdd={onAdd} workMode="standard" />);
|
||
|
||
typeText("/dep");
|
||
await placeCaretAtEnd();
|
||
|
||
const option = autocompleteOption("/deploy");
|
||
flushSync(() => {
|
||
option.dispatchEvent(
|
||
new MouseEvent("mousedown", { bubbles: true, cancelable: true }),
|
||
);
|
||
});
|
||
await flushAsync();
|
||
|
||
expect(editable().textContent).toBe(`[/deploy](${SLASH_HREF}) `);
|
||
});
|
||
|
||
describe("/swarm command", () => {
|
||
it("matches only the user's leading /swarm token, through the shared rule", () => {
|
||
expect(parseSwarmCommand(" /swarm two helpers write a.txt and b.txt ")).toEqual({ request: "two helpers write a.txt and b.txt" });
|
||
expect(parseSwarmCommand("[/sw](</swarm write a.txt>)")).toEqual({ request: "write a.txt" });
|
||
expect(parseSwarmCommand("/swarm")).toEqual({ request: "" });
|
||
expect(parseSwarmCommand("Please /swarm this")).toBeNull();
|
||
expect(parseSwarmCommand("> /swarm from a pasted email")).toBeNull();
|
||
expect(parseSwarmCommand("```\n/swarm\n```")).toBeNull();
|
||
expect(parseSwarmCommand("/swarms")).toBeNull();
|
||
expect(parseSwarmCommand("/Swarm do it")).toBeNull();
|
||
});
|
||
|
||
it("sends the request as a structured swarm request, without the command text", async () => {
|
||
const onAdd = vi.fn().mockResolvedValue(undefined);
|
||
renderComposer({ onAdd, workMode: "standard", onWorkModeChange: vi.fn() });
|
||
typeText("/swarm two helpers write a.txt and b.txt");
|
||
pressKey("Enter", { metaKey: true });
|
||
await flushAsync();
|
||
expect(onAdd).toHaveBeenCalledWith("two helpers write a.txt and b.txt", undefined, undefined, undefined, expect.any(String), undefined, "swarm");
|
||
});
|
||
|
||
it("asks for a request instead of sending a bare /swarm", async () => {
|
||
const onAdd = vi.fn().mockResolvedValue(undefined);
|
||
renderComposer({ onAdd, workMode: "standard", onWorkModeChange: vi.fn() });
|
||
typeText("/swarm");
|
||
pressKey("Enter", { metaKey: true });
|
||
await flushAsync();
|
||
expect(onAdd).not.toHaveBeenCalled();
|
||
expect(container.textContent).toContain("Write what the swarm should do after /swarm.");
|
||
});
|
||
|
||
it("refuses a /swarm request longer than a swarm accepts before sending it", async () => {
|
||
const onAdd = vi.fn().mockResolvedValue(undefined);
|
||
renderComposer({ onAdd, workMode: "standard", onWorkModeChange: vi.fn() });
|
||
typeText(`/swarm ${"x".repeat(16_001)}`);
|
||
pressKey("Enter", { metaKey: true });
|
||
await flushAsync();
|
||
expect(onAdd).not.toHaveBeenCalled();
|
||
expect(container.textContent).toContain("This swarm request is too long. Keep what follows /swarm under 16,000 characters.");
|
||
});
|
||
|
||
it("resends a /swarm request with the same request id after a lost receipt and a reload", async () => {
|
||
let rejectSend!: (error: Error) => void;
|
||
const onAdd = vi.fn().mockReturnValueOnce(new Promise<void>((_, reject) => { rejectSend = reject; })).mockResolvedValue(undefined);
|
||
renderComposer({ onAdd, workMode: "standard", onWorkModeChange: vi.fn(), draftKey: "swarm-retry" });
|
||
typeText("/swarm write a.txt");
|
||
await act(async () => sendButton().click());
|
||
const attemptId = onAdd.mock.calls[0][4];
|
||
await act(async () => rejectSend(new CommentSubmissionUnknownError()));
|
||
expect(loadDraftSubmission("swarm-retry")?.request).toMatchObject({ body: "write a.txt", nativeCommand: "swarm" });
|
||
renderComposer({ onAdd, workMode: "standard", onWorkModeChange: vi.fn(), draftKey: "swarm-retry" });
|
||
await flushAsync();
|
||
const resend = Array.from(container.querySelectorAll("button")).find(button => button.textContent === "Resend now")!;
|
||
await act(async () => resend.click());
|
||
expect(onAdd).toHaveBeenNthCalledWith(2, "write a.txt", undefined, undefined, undefined, attemptId, undefined, "swarm");
|
||
});
|
||
|
||
it("refuses /swarm in the new-task composer instead of creating an ordinary task", async () => {
|
||
const creation = { value: "/swarm write a.txt", onChange: vi.fn(), onSubmit: vi.fn().mockResolvedValue(undefined), submitLabel: "Create",
|
||
onSelectFiles: vi.fn(), runSettings: null, onRunSettingsChange: vi.fn() };
|
||
render(<TaskChatComposer creation={creation} workMode="standard" onWorkModeChange={vi.fn()} />);
|
||
pressKey("Enter", { metaKey: true });
|
||
await flushAsync();
|
||
expect(creation.onSubmit).not.toHaveBeenCalled();
|
||
expect(container.textContent).toContain("Create the task first, then send /swarm in a comment on it.");
|
||
});
|
||
|
||
it("refuses /swarm with a different model or effort chosen for the message", async () => {
|
||
const creation = { value: "", onChange: vi.fn(), onSubmit: vi.fn(), submitLabel: "Create", onSelectFiles: vi.fn(),
|
||
runSettings: { model: "gemini-4-argon-medium", effort: null, fast: false }, onRunSettingsChange: vi.fn() };
|
||
expect(swarmRunSettingsRefusal(creation.runSettings)).toBe("Swarm uses the agent's configured model. Clear the model and effort choices for this message, then send /swarm.");
|
||
expect(swarmRunSettingsRefusal(null)).toBeNull();
|
||
expect(swarmRunSettingsRefusal({ model: null, effort: null, fast: false })).toBeNull();
|
||
});
|
||
|
||
it("leaves a /swarm inside the message as ordinary text", async () => {
|
||
const onAdd = vi.fn().mockResolvedValue(undefined);
|
||
renderComposer({ onAdd, workMode: "standard", onWorkModeChange: vi.fn() });
|
||
typeText("Please /swarm this");
|
||
pressKey("Enter", { metaKey: true });
|
||
await flushAsync();
|
||
expect(onAdd).toHaveBeenCalledWith("Please /swarm this", undefined, undefined, undefined, expect.any(String));
|
||
});
|
||
});
|
||
|
||
describe("/plan command", () => {
|
||
it("matches only the user's leading /plan token", () => {
|
||
expect(parsePlanCommand(" /plan Add a greeting file ")).toEqual({ matched: true, request: "Add a greeting file" });
|
||
expect(parsePlanCommand("/plan")).toEqual({ matched: true, request: "" });
|
||
expect(parsePlanCommand("/plan\n\nLine one\nLine two")).toEqual({ matched: true, request: "Line one\nLine two" });
|
||
expect(parsePlanCommand("[/pl](</plan Add a greeting file>)")).toEqual({ matched: true, request: "Add a greeting file" });
|
||
// A /plan anywhere else is ordinary text, including quoted or pasted content.
|
||
expect(parsePlanCommand("Please /plan this first")).toEqual({ matched: false });
|
||
expect(parsePlanCommand("> /plan from a pasted email")).toEqual({ matched: false });
|
||
expect(parsePlanCommand("```\n/plan\n```")).toEqual({ matched: false });
|
||
expect(parsePlanCommand("\\/plan ordinary text")).toEqual({ matched: false });
|
||
expect(parsePlanCommand("/planning notes")).toEqual({ matched: false });
|
||
});
|
||
|
||
it("sends the request in Plan mode without the command", async () => {
|
||
const onAdd = vi.fn().mockResolvedValue(undefined);
|
||
const onWorkModeChange = vi.fn().mockResolvedValue(undefined);
|
||
renderComposer({ onAdd, workMode: "standard", onWorkModeChange });
|
||
typeText("/plan Add a greeting file");
|
||
pressKey("Enter", { metaKey: true });
|
||
await flushAsync();
|
||
expect(onWorkModeChange).toHaveBeenCalledWith("planning");
|
||
expect(onAdd).toHaveBeenCalledWith("Add a greeting file", undefined, undefined, undefined, expect.any(String));
|
||
expect(onWorkModeChange.mock.invocationCallOrder[0]).toBeLessThan(onAdd.mock.invocationCallOrder[0]!);
|
||
});
|
||
|
||
it("switches to Plan mode without sending when no request follows", async () => {
|
||
const onAdd = vi.fn().mockResolvedValue(undefined);
|
||
renderComposer({ onAdd, workMode: "standard", onWorkModeChange: vi.fn() });
|
||
typeText("/plan");
|
||
pressKey("Enter", { metaKey: true });
|
||
await flushAsync();
|
||
expect(onAdd).not.toHaveBeenCalled();
|
||
expect(container.querySelector('[data-testid="task-chat-composer-mode"]')?.getAttribute("data-pending-work-mode")).toBe("planning");
|
||
expect(editable().textContent).toBe("");
|
||
});
|
||
|
||
it("leaves a /plan inside the message as ordinary text", async () => {
|
||
const onAdd = vi.fn().mockResolvedValue(undefined);
|
||
const onWorkModeChange = vi.fn().mockResolvedValue(undefined);
|
||
renderComposer({ onAdd, workMode: "standard", onWorkModeChange });
|
||
typeText("Please /plan this first");
|
||
pressKey("Enter", { metaKey: true });
|
||
await flushAsync();
|
||
expect(onWorkModeChange).not.toHaveBeenCalled();
|
||
expect(onAdd).toHaveBeenCalledWith("Please /plan this first", undefined, undefined, undefined, expect.any(String));
|
||
});
|
||
|
||
it("offers Plan in the slash menu, except while editing a queued message", async () => {
|
||
const planOffered = () => Array.from(document.body.querySelectorAll<HTMLButtonElement>(
|
||
'[data-testid="mention-autocomplete-menu"] button[type="button"]')).some(node => node.textContent?.includes("/plan"));
|
||
render(<TaskChatComposer onAdd={vi.fn()} workMode="standard" onWorkModeChange={vi.fn()} />);
|
||
typeText("/pl");
|
||
await placeCaretAtEnd();
|
||
expect(planOffered()).toBe(true);
|
||
render(<TaskChatComposer workMode="standard" onAdd={vi.fn()} onWorkModeChange={vi.fn()}
|
||
queuedEdit={{ commentId: "queued", body: "" }} onSaveQueuedEdit={vi.fn()} />);
|
||
typeText("/pl");
|
||
await placeCaretAtEnd();
|
||
expect(planOffered()).toBe(false);
|
||
});
|
||
|
||
it("decides a bare /plan the same way for both submit paths", () => {
|
||
expect(planSubmission("/plan", false)).toEqual({ kind: "switch_mode" });
|
||
expect(planSubmission("/plan", true)).toEqual({ kind: "send", text: "" });
|
||
expect(planSubmission("/plan Ship it", false)).toEqual({ kind: "send", text: "Ship it" });
|
||
expect(planSubmission("Ship it /plan", true)).toEqual({ kind: "none" });
|
||
});
|
||
|
||
it("sends a bare /plan with an attachment as the request in Plan mode", async () => {
|
||
const onAdd = vi.fn().mockResolvedValue(undefined);
|
||
const onWorkModeChange = vi.fn().mockResolvedValue(undefined);
|
||
const id = "9af8228f-0be7-45ae-a104-6fbe0af6f1d3";
|
||
const onAttachImage = vi.fn().mockResolvedValue({ id, contentPath: `/api/attachments/${id}/content`, originalFilename: "spec.txt" });
|
||
renderComposer({ onAdd, workMode: "standard", onWorkModeChange, onAttachImage });
|
||
typeText("/plan");
|
||
pasteFiles([new File(["spec"], "spec.txt", { type: "text/plain" })]);
|
||
await flushAsync();
|
||
flushSync(() => sendButton().click());
|
||
await flushAsync();
|
||
expect(onWorkModeChange).toHaveBeenCalledWith("planning");
|
||
expect(onAdd).toHaveBeenCalledOnce();
|
||
expect(onAdd.mock.calls[0]?.[0]).not.toContain("/plan");
|
||
expect(onAdd.mock.calls[0]?.[3]).toEqual([id]);
|
||
});
|
||
|
||
it("creates a task from a bare /plan with an image only when the task may have no text", async () => {
|
||
const image = new File(["png"], "screen.png", { type: "image/png" });
|
||
const creation = { value: "/plan", onChange: vi.fn(), onSubmit: vi.fn().mockResolvedValue(undefined), submitLabel: "Create",
|
||
onSelectFiles: vi.fn(), runSettings: null, onRunSettingsChange: vi.fn(), images: [{ id: "screen", name: image.name, file: image }] };
|
||
render(<TaskChatComposer creation={{ ...creation, canSubmitWithoutBody: true }} workMode="standard" onWorkModeChange={vi.fn()} />);
|
||
pressKey("Enter", { metaKey: true });
|
||
await flushAsync();
|
||
expect(creation.onSubmit).toHaveBeenCalledWith("", "planning", null);
|
||
const onWorkModeChange = vi.fn();
|
||
const bare = { ...creation, onSubmit: vi.fn() };
|
||
render(<TaskChatComposer creation={bare} workMode="standard" onWorkModeChange={onWorkModeChange} />);
|
||
pressKey("Enter", { metaKey: true });
|
||
await flushAsync();
|
||
expect(bare.onSubmit).not.toHaveBeenCalled();
|
||
expect(onWorkModeChange).toHaveBeenCalledWith("planning");
|
||
});
|
||
|
||
it("keeps /plan as text in a composer that has no Plan mode", async () => {
|
||
const creation = { value: "/plan Add a greeting file", onChange: vi.fn(), onSubmit: vi.fn().mockResolvedValue(undefined),
|
||
submitLabel: "Start", onSelectFiles: vi.fn(), runSettings: null, onRunSettingsChange: vi.fn() };
|
||
render(<TaskChatComposer creation={creation} workMode="standard" />);
|
||
pressKey("Enter", { metaKey: true });
|
||
await flushAsync();
|
||
expect(creation.onSubmit).toHaveBeenCalledWith("/plan Add a greeting file", "standard", null);
|
||
});
|
||
|
||
it("creates a new task in Plan mode", async () => {
|
||
const creation = { value: "/plan Add a greeting file", onChange: vi.fn(), onSubmit: vi.fn().mockResolvedValue(undefined),
|
||
submitLabel: "Create", onSelectFiles: vi.fn(), runSettings: null, onRunSettingsChange: vi.fn() };
|
||
render(<TaskChatComposer creation={creation} workMode="standard" onWorkModeChange={vi.fn()} />);
|
||
pressKey("Enter", { metaKey: true });
|
||
await flushAsync();
|
||
expect(creation.onSubmit).toHaveBeenCalledWith("Add a greeting file", "planning", null);
|
||
});
|
||
});
|
||
|
||
describe("/goal action commands", () => {
|
||
const capability = {
|
||
availability: "available" as const,
|
||
verified: true,
|
||
actions: ["set", "pause", "resume", "clear"] as Array<
|
||
"set" | "pause" | "resume" | "clear"
|
||
>,
|
||
autonomousUpdates: true,
|
||
persistentAcrossResume: true,
|
||
maxObjectiveChars: 4_000,
|
||
tokenBudgetControl: true,
|
||
usageReporting: true,
|
||
};
|
||
|
||
it("matches only an exact first /goal token", () => {
|
||
expect(parseRunnerGoalCommand(" /goal Ship the feature ")).toEqual({
|
||
matched: true,
|
||
command: { action: "create", objective: "Ship the feature" },
|
||
});
|
||
expect(
|
||
parseRunnerGoalCommand(
|
||
"[/goal\u00a0](</goal Ship the feature across turns.>)",
|
||
),
|
||
).toEqual({
|
||
matched: true,
|
||
command: {
|
||
action: "create",
|
||
objective: "Ship the feature across turns.",
|
||
},
|
||
});
|
||
expect(
|
||
parseRunnerGoalCommand(
|
||
"[/go](</goal Return one concise confirmation, then complete.>)",
|
||
),
|
||
).toEqual({
|
||
matched: true,
|
||
command: {
|
||
action: "create",
|
||
objective: "Return one concise confirmation, then complete.",
|
||
},
|
||
});
|
||
expect(
|
||
parseRunnerGoalCommand("[/](/goal%20Confirm%20the%20goal%20state.)"),
|
||
).toEqual({
|
||
matched: true,
|
||
command: {
|
||
action: "create",
|
||
objective: "Confirm the goal state.",
|
||
},
|
||
});
|
||
expect(parseRunnerGoalCommand("[/goal](/goal%20pause)")).toEqual({
|
||
matched: true,
|
||
command: { action: "pause" },
|
||
});
|
||
expect(parseRunnerGoalCommand("/goal pause extra")).toEqual({
|
||
matched: true,
|
||
error: "/goal pause does not accept extra arguments.",
|
||
});
|
||
expect(parseRunnerGoalCommand("[goal](/goal Ship it)")).toEqual({
|
||
matched: false,
|
||
});
|
||
expect(parseRunnerGoalCommand("\\/goal ordinary text")).toEqual({
|
||
matched: false,
|
||
});
|
||
expect(parseRunnerGoalCommand("/goalkeeper ordinary text")).toEqual({
|
||
matched: false,
|
||
});
|
||
});
|
||
|
||
it("dispatches a goal action without posting a comment", async () => {
|
||
const onAdd = vi.fn().mockResolvedValue(undefined);
|
||
const onRunnerGoalCommand = vi.fn().mockResolvedValue(undefined);
|
||
renderComposer({
|
||
onAdd: onAdd,
|
||
workMode: "standard",
|
||
runnerGoalCapability: capability,
|
||
onRunnerGoalCommand: onRunnerGoalCommand,
|
||
});
|
||
|
||
typeText("/goal Ship the feature");
|
||
pressKey("Enter", { metaKey: true });
|
||
await flushAsync();
|
||
|
||
expect(onRunnerGoalCommand).toHaveBeenCalledWith({
|
||
action: "create",
|
||
objective: "Ship the feature",
|
||
});
|
||
expect(onAdd).not.toHaveBeenCalled();
|
||
expect(editable().textContent).toBe("");
|
||
});
|
||
|
||
it("shows Goal in the add menu only for a supported agent and prepares the command", async () => {
|
||
const onRunnerGoalCommand = vi.fn();
|
||
render(<TaskChatComposer onAdd={vi.fn()} workMode="standard"
|
||
onWorkModeChange={vi.fn()} runnerGoalCapability={capability} onRunnerGoalCommand={onRunnerGoalCommand} />);
|
||
typeText("Ship the feature");
|
||
openComposerAddMenu();
|
||
const goal = document.querySelector<HTMLElement>('[data-testid="composer-add-goal"]');
|
||
expect(goal).not.toBeNull();
|
||
flushSync(() => goal!.click());
|
||
await flushAsync();
|
||
expect(editable().textContent).toBe("/goal Ship the feature");
|
||
expect(onRunnerGoalCommand).not.toHaveBeenCalled();
|
||
|
||
render(<TaskChatComposer onAdd={vi.fn()} workMode="standard"
|
||
onWorkModeChange={vi.fn()}
|
||
runnerGoalCapability={{ ...capability, availability: "unsupported" }}
|
||
onRunnerGoalCommand={onRunnerGoalCommand} />);
|
||
openComposerAddMenu();
|
||
expect(document.querySelector('[data-testid="composer-add-goal"]')).toBeNull();
|
||
});
|
||
|
||
it("commits a pending agent reassignment before starting the goal", async () => {
|
||
const order: string[] = [];
|
||
const onAdd = vi.fn().mockResolvedValue(undefined);
|
||
const onPendingAssigneeChange = vi.fn();
|
||
const onRunnerGoalReassign = vi.fn().mockImplementation(async () => {
|
||
order.push("reassign");
|
||
});
|
||
const onRunnerGoalCommand = vi.fn().mockImplementation(async () => {
|
||
order.push("goal");
|
||
});
|
||
renderComposer({
|
||
onAdd: onAdd,
|
||
workMode: "standard",
|
||
enableReassign: true,
|
||
reassignOptions: [{ id: "agent:a1", label: "Clippy" }],
|
||
currentAssigneeValue: "",
|
||
onPendingAssigneeChange: onPendingAssigneeChange,
|
||
runnerGoalCapability: capability,
|
||
onRunnerGoalReassign: onRunnerGoalReassign,
|
||
onRunnerGoalCommand: onRunnerGoalCommand,
|
||
});
|
||
|
||
const trigger = container.querySelector<HTMLButtonElement>(
|
||
'[data-testid="task-chat-composer-assignee"]',
|
||
)!;
|
||
flushSync(() => trigger.click());
|
||
await flushAsync();
|
||
const option = [
|
||
...document.body.querySelectorAll<HTMLButtonElement>("button"),
|
||
].find((button) => button.textContent?.trim() === "Clippy");
|
||
expect(option).toBeDefined();
|
||
flushSync(() => option!.click());
|
||
await flushAsync();
|
||
|
||
openComposerAddMenu();
|
||
expect(document.querySelector('[data-testid="composer-add-goal"]')).not.toBeNull();
|
||
flushSync(() => document.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true })));
|
||
|
||
typeText("/goal Ship the feature");
|
||
pressKey("Enter", { metaKey: true });
|
||
await flushAsync();
|
||
|
||
expect(onPendingAssigneeChange).toHaveBeenCalledWith("agent:a1");
|
||
expect(onRunnerGoalReassign).toHaveBeenCalledWith({
|
||
assigneeAgentId: "a1",
|
||
assigneeUserId: null,
|
||
});
|
||
expect(onRunnerGoalCommand).toHaveBeenCalledWith({
|
||
action: "create",
|
||
objective: "Ship the feature",
|
||
});
|
||
expect(order).toEqual(["reassign", "goal"]);
|
||
expect(onAdd).not.toHaveBeenCalled();
|
||
});
|
||
|
||
it("preserves unsupported goal text and shows the provider reason", async () => {
|
||
const onAdd = vi.fn().mockResolvedValue(undefined);
|
||
renderComposer({
|
||
onAdd: onAdd,
|
||
workMode: "standard",
|
||
runnerGoalCapability: {
|
||
...capability,
|
||
availability: "unsupported",
|
||
actions: [],
|
||
reason: "Unsupported by OpenCode.",
|
||
},
|
||
onRunnerGoalCommand: vi.fn(),
|
||
});
|
||
|
||
typeText("/goal Ship the feature");
|
||
pressKey("Enter", { metaKey: true });
|
||
await flushAsync();
|
||
|
||
expect(onAdd).not.toHaveBeenCalled();
|
||
expect(editable().textContent).toBe("/goal Ship the feature");
|
||
expect(container.querySelector('[role="alert"]')?.textContent).toContain(
|
||
"Unsupported by OpenCode",
|
||
);
|
||
});
|
||
});
|
||
|
||
it("shows the assignee combobox only when reassign is enabled, with the current label", () => {
|
||
render(<TaskChatComposer onAdd={vi.fn()} workMode="standard" />);
|
||
expect(
|
||
container.querySelector('[data-testid="task-chat-composer-assignee"]'),
|
||
).toBeNull();
|
||
|
||
renderComposer({
|
||
onAdd: vi.fn(),
|
||
workMode: "standard",
|
||
enableReassign: true,
|
||
reassignOptions: [
|
||
{ id: "agent:a1", label: "Clippy" },
|
||
{ id: "user:u1", label: "Sam" },
|
||
],
|
||
currentAssigneeValue: "user:u1",
|
||
});
|
||
const trigger = container.querySelector(
|
||
'[data-testid="task-chat-composer-assignee"]',
|
||
);
|
||
expect(trigger?.textContent).toContain("Sam");
|
||
});
|
||
|
||
it("shows configured agent icons in the assignee trigger and dropdown options", async () => {
|
||
renderComposer({
|
||
onAdd: vi.fn(),
|
||
workMode: "standard",
|
||
enableReassign: true,
|
||
reassignOptions: [
|
||
{ id: "agent:a1", label: "Clippy" },
|
||
{ id: "agent:a2", label: "Plain Agent" },
|
||
],
|
||
agentMap: new Map([
|
||
["a1", { icon: "rocket" }],
|
||
["a2", { icon: null }],
|
||
]),
|
||
currentAssigneeValue: "agent:a1",
|
||
});
|
||
|
||
const trigger = container.querySelector<HTMLButtonElement>(
|
||
'[data-testid="task-chat-composer-assignee"]',
|
||
)!;
|
||
expect(
|
||
trigger.querySelector('[data-assignee-trigger-icon="rocket"]'),
|
||
).not.toBeNull();
|
||
|
||
flushSync(() => {
|
||
trigger.dispatchEvent(new MouseEvent("click", { bubbles: true }));
|
||
});
|
||
await flushAsync();
|
||
|
||
expect(
|
||
document.querySelector('[data-assignee-option-icon="agent:a1"]'),
|
||
).not.toBeNull();
|
||
expect(
|
||
document.querySelector('[data-assignee-option-icon="agent:a2"]'),
|
||
).not.toBeNull();
|
||
expect(
|
||
document
|
||
.querySelector('[data-assignee-identity="agent:a2"]')
|
||
?.getAttribute("data-assignee-option-icon"),
|
||
).toBe("agent:a2");
|
||
});
|
||
|
||
it("uses assignment suggestions and retains a manual human choice after refresh", async () => {
|
||
const view = (suggestion: string) => <TaskChatComposer onAdd={vi.fn()} workMode="standard"
|
||
enableReassign currentAssigneeValue="user:u1" suggestedAssigneeValue={suggestion}
|
||
reassignOptions={[{ id: "agent:a1", label: "Alpha" }, { id: "agent:a2", label: "Beta" }, { id: "user:u1", label: "Me" }]}
|
||
agentMap={new Map([["a1", { icon: "bot" }], ["a2", { icon: "bot" }]])} />;
|
||
render(view("agent:a1"));
|
||
const trigger = () => container.querySelector<HTMLButtonElement>('[data-testid="task-chat-composer-assignee"]')!;
|
||
expect(trigger().textContent).toContain("Alpha");
|
||
flushSync(() => root!.render(view("agent:a2")));
|
||
expect(trigger().textContent).toContain("Beta");
|
||
flushSync(() => trigger().click());
|
||
await flushAsync();
|
||
const me = document.querySelector('[data-assignee-identity="user:u1"]')!.closest("button")!;
|
||
flushSync(() => me.click());
|
||
await flushAsync();
|
||
flushSync(() => root!.render(view("agent:a1")));
|
||
expect(trigger().textContent).toContain("Me");
|
||
});
|
||
|
||
it("shows human avatars in assignee options and after selection", async () => {
|
||
renderComposer({
|
||
onAdd: vi.fn(),
|
||
workMode: "standard",
|
||
enableReassign: true,
|
||
reassignOptions: [
|
||
{ id: "agent:a1", label: "Clippy" },
|
||
{ id: "user:u1", label: "Sam Rivera" },
|
||
],
|
||
agentMap: new Map([["a1", { icon: "rocket" }]]),
|
||
userProfileMap: new Map([["u1", { label: "Sam Rivera", image: "/sam-avatar.png" }]]),
|
||
currentAssigneeValue: "agent:a1",
|
||
});
|
||
|
||
const trigger = container.querySelector<HTMLButtonElement>(
|
||
'[data-testid="task-chat-composer-assignee"]',
|
||
)!;
|
||
flushSync(() => {
|
||
trigger.dispatchEvent(new MouseEvent("click", { bubbles: true }));
|
||
});
|
||
await flushAsync();
|
||
|
||
const userOptionAvatar = document.querySelector(
|
||
'[data-assignee-option-avatar="user:u1"]',
|
||
);
|
||
expect(userOptionAvatar).not.toBeNull();
|
||
const userOption = userOptionAvatar?.closest("button");
|
||
flushSync(() => {
|
||
userOption?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
|
||
});
|
||
await flushAsync();
|
||
|
||
expect(trigger.textContent).toContain("Sam Rivera");
|
||
expect(
|
||
trigger.querySelector('[data-assignee-trigger-avatar="u1"]'),
|
||
).not.toBeNull();
|
||
});
|
||
|
||
describe("draft persistence", () => {
|
||
const draftKey = "task-chat-draft:issue-1";
|
||
|
||
it("restores a saved draft on mount", () => {
|
||
localStorage.setItem(draftKey, "unsent draft");
|
||
|
||
renderComposer({
|
||
onAdd: vi.fn(),
|
||
workMode: "standard",
|
||
draftKey: draftKey,
|
||
});
|
||
|
||
expect(editable().textContent).toBe("unsent draft");
|
||
expect(sendButton().disabled).toBe(false);
|
||
});
|
||
|
||
it("preserves a restored draft through the StrictMode effect probe", () => {
|
||
localStorage.setItem(draftKey, "still here");
|
||
|
||
render(
|
||
<StrictMode>
|
||
<TaskChatComposer
|
||
onAdd={vi.fn()}
|
||
workMode="standard"
|
||
draftKey={draftKey}
|
||
/>
|
||
</StrictMode>,
|
||
);
|
||
|
||
expect(editable().textContent).toBe("still here");
|
||
expect(localStorage.getItem(draftKey)).toBe("still here");
|
||
});
|
||
|
||
it("saves after the debounce and flushes a pending value on unmount", () => {
|
||
vi.useFakeTimers();
|
||
try {
|
||
renderComposer({
|
||
onAdd: vi.fn(),
|
||
workMode: "standard",
|
||
draftKey: draftKey,
|
||
});
|
||
typeText("work in progress");
|
||
expect(localStorage.getItem(draftKey)).toBeNull();
|
||
|
||
vi.advanceTimersByTime(DRAFT_DEBOUNCE_MS);
|
||
expect(localStorage.getItem(draftKey)).toBe("work in progress");
|
||
|
||
typeText("save before leaving");
|
||
flushSync(() => root?.unmount());
|
||
root = null;
|
||
expect(localStorage.getItem(draftKey)).toBe("save before leaving");
|
||
} finally {
|
||
vi.useRealTimers();
|
||
}
|
||
});
|
||
|
||
it("flushes a pending value before page unload", () => {
|
||
vi.useFakeTimers();
|
||
try {
|
||
renderComposer({
|
||
onAdd: vi.fn(),
|
||
workMode: "standard",
|
||
draftKey: draftKey,
|
||
});
|
||
typeText("save before reload");
|
||
|
||
window.dispatchEvent(new Event("beforeunload"));
|
||
|
||
expect(localStorage.getItem(draftKey)).toBe("save before reload");
|
||
} finally {
|
||
vi.useRealTimers();
|
||
}
|
||
});
|
||
|
||
it("clears the visible composer but retains an uncertain reload draft while sending", async () => {
|
||
localStorage.setItem(draftKey, "queued message");
|
||
const onAdd = vi.fn().mockReturnValue(new Promise<void>(() => {}));
|
||
renderComposer({
|
||
onAdd: onAdd,
|
||
workMode: "standard",
|
||
draftKey: draftKey,
|
||
});
|
||
|
||
pressKey("Enter", { metaKey: true });
|
||
await flushAsync();
|
||
|
||
expect(onAdd).toHaveBeenCalledWith("queued message", undefined, undefined, undefined, expect.any(String));
|
||
expect(editable().textContent).toBe("");
|
||
expect(localStorage.getItem(draftKey)).toBe("queued message");
|
||
expect(localStorage.getItem(`${draftKey}:submission:v1`)).toContain(
|
||
'"reviewed":false',
|
||
);
|
||
});
|
||
|
||
it("keeps text entered while an earlier send is pending", async () => {
|
||
let resolveSend!: () => void;
|
||
const onAdd = vi.fn().mockReturnValue(
|
||
new Promise<void>((resolve) => {
|
||
resolveSend = resolve;
|
||
}),
|
||
);
|
||
renderComposer({
|
||
onAdd: onAdd,
|
||
workMode: "standard",
|
||
draftKey: draftKey,
|
||
});
|
||
typeText("first message");
|
||
|
||
pressKey("Enter", { metaKey: true });
|
||
await flushAsync();
|
||
typeText("next message");
|
||
resolveSend();
|
||
await flushAsync();
|
||
await flushAsync();
|
||
|
||
expect(onAdd).toHaveBeenCalledWith("first message", undefined, undefined, undefined, expect.any(String));
|
||
expect(editable().textContent).toBe("next message");
|
||
expect(localStorage.getItem(draftKey)).toBe("next message");
|
||
});
|
||
|
||
it("keeps an attachment added while an earlier send is pending", async () => {
|
||
let resolveSend!: () => void;
|
||
const onAdd = vi.fn().mockReturnValue(
|
||
new Promise<void>((resolve) => {
|
||
resolveSend = resolve;
|
||
}),
|
||
);
|
||
const onAttachImage = vi.fn().mockResolvedValue({
|
||
contentPath: "/attachments/next.txt",
|
||
originalFilename: "next.txt",
|
||
});
|
||
renderComposer({
|
||
onAdd: onAdd,
|
||
workMode: "standard",
|
||
draftKey: draftKey,
|
||
onAttachImage: onAttachImage,
|
||
});
|
||
typeText("first message");
|
||
|
||
pressKey("Enter", { metaKey: true });
|
||
await flushAsync();
|
||
pasteFiles([new File(["next"], "next.txt", { type: "text/plain" })]);
|
||
await flushAsync();
|
||
resolveSend();
|
||
await flushAsync();
|
||
await flushAsync();
|
||
|
||
expect(onAdd).toHaveBeenCalledWith("first message", undefined, undefined, undefined, expect.any(String));
|
||
expect(
|
||
container.querySelector(
|
||
'[data-testid="task-chat-composer-attachments"]',
|
||
)?.textContent,
|
||
).toContain("next.txt");
|
||
});
|
||
|
||
it("restores a failed send before text entered while it was pending", async () => {
|
||
vi.useFakeTimers();
|
||
try {
|
||
let rejectSend!: (error: Error) => void;
|
||
const onAdd = vi.fn().mockReturnValue(
|
||
new Promise<void>((_resolve, reject) => {
|
||
rejectSend = reject;
|
||
}),
|
||
);
|
||
renderComposer({
|
||
onAdd: onAdd,
|
||
workMode: "standard",
|
||
draftKey: draftKey,
|
||
});
|
||
typeText("do not lose this");
|
||
vi.advanceTimersByTime(DRAFT_DEBOUNCE_MS);
|
||
vi.useRealTimers();
|
||
|
||
pressKey("Enter", { metaKey: true });
|
||
await flushAsync();
|
||
expect(editable().textContent).toBe("");
|
||
expect(localStorage.getItem(draftKey)).toBe("do not lose this");
|
||
|
||
typeText("next draft");
|
||
rejectSend(new Error("network down"));
|
||
await flushAsync();
|
||
await flushAsync();
|
||
|
||
expect(editable().textContent).toBe("do not lose this\n\nnext draft");
|
||
expect(localStorage.getItem(draftKey)).toBe(
|
||
"do not lose this\n\nnext draft",
|
||
);
|
||
} finally {
|
||
vi.useRealTimers();
|
||
}
|
||
});
|
||
});
|
||
|
||
it("gives separate identical chat submissions separate receipt identities", async () => {
|
||
const onAdd = vi.fn().mockResolvedValue(undefined);
|
||
render(<TaskChatComposer onAdd={onAdd} conversationMode workMode="standard" />);
|
||
typeText("Same message");
|
||
await act(async () => sendButton().click());
|
||
typeText("Same message");
|
||
await act(async () => sendButton().click());
|
||
expect(onAdd.mock.calls).toHaveLength(2);
|
||
expect(onAdd.mock.calls[0][4]).toEqual(expect.any(String));
|
||
expect(onAdd.mock.calls[1][4]).not.toBe(onAdd.mock.calls[0][4]);
|
||
});
|
||
|
||
it("shows model controls only in Coordinator chat and submits the choice without reassignment", async () => {
|
||
vi.stubGlobal("ResizeObserver", class { observe() {} unobserve() {} disconnect() {} });
|
||
const catalog = vi.spyOn(agentsApi, "adapterModels").mockResolvedValue([{ id: "gpt-6-astra", label: "GPT-6 Astra" }]);
|
||
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||
const agent = { id: "chat-agent", name: "Mira", adapterType: "codex_local", adapterConfig: { model: "gpt-6-sol" } } as unknown as Agent;
|
||
const agents = new Map([[agent.id, agent]]);
|
||
const onAdd = vi.fn().mockResolvedValue(undefined);
|
||
const paint = (coordinator: boolean) => render(<QueryClientProvider client={client}><CoordinatorPresentation.Provider value={coordinator}>
|
||
<TaskChatComposer onAdd={onAdd} conversationMode companyId="chat-company" workMode="standard"
|
||
currentAssigneeValue="agent:chat-agent" suggestedAssigneeValue="agent:someone-else" modelAgents={agents}
|
||
reassignOptions={[{ id: "agent:chat-agent", label: "Mira" }]} />
|
||
</CoordinatorPresentation.Provider></QueryClientProvider>);
|
||
try {
|
||
paint(false);
|
||
expect(container.querySelector('[aria-label="Select model and effort"]')).toBeNull();
|
||
paint(true);
|
||
await flushAsync();
|
||
expect(container.querySelector('[aria-label="Select assignee"]')).toBeNull();
|
||
await act(async () => container.querySelector<HTMLButtonElement>('[aria-label="Select model and effort"]')!.click());
|
||
await act(async () => document.querySelector<HTMLButtonElement>('[aria-label="Choose exact model"]')!.click());
|
||
const option = [...document.querySelectorAll<HTMLButtonElement>('button[role="option"]')].find(item => item.textContent?.startsWith("GPT-6 Astra"))!;
|
||
await act(async () => option.click());
|
||
const range = document.querySelector<HTMLInputElement>('input[aria-label="Effort"]')!;
|
||
await act(async () => {
|
||
Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(range, "3");
|
||
range.dispatchEvent(new Event("change", { bubbles: true }));
|
||
range.dispatchEvent(new Event("input", { bubbles: true }));
|
||
});
|
||
typeText("Please outline the launch.");
|
||
await act(async () => sendButton().click());
|
||
expect(onAdd).toHaveBeenCalledWith("Please outline the launch.", undefined, undefined, undefined, expect.any(String), { model: "gpt-6-astra", effort: "high", fast: false });
|
||
} finally {
|
||
render(<></>); client.clear(); catalog.mockRestore(); vi.unstubAllGlobals();
|
||
}
|
||
});
|
||
|
||
describe("paused task takeover", () => {
|
||
it("allows only standalone /new to resume a paused conversation through the normal composer", async () => {
|
||
const onAdd = vi.fn().mockResolvedValue(undefined);
|
||
render(<TaskChatComposer onAdd={onAdd} conversationMode workMode="standard" pause={{ scope: "leaf" }} />);
|
||
typeText("Keep working");
|
||
expect(sendButton().disabled).toBe(true);
|
||
await act(async () => sendButton().click());
|
||
expect(onAdd).not.toHaveBeenCalled();
|
||
typeText("/new");
|
||
expect(sendButton().disabled).toBe(false);
|
||
await act(async () => sendButton().click());
|
||
expect(onAdd).toHaveBeenCalledWith("/new", undefined, undefined, undefined, expect.any(String));
|
||
});
|
||
|
||
it("preserves a typed draft and blocks sending until resume completes", async () => {
|
||
const onAdd = vi.fn();
|
||
const onResume = vi.fn();
|
||
const props = { onAdd, workMode: "standard" as const, draftKey: "paused-draft" };
|
||
act(() => root!.render(<TaskChatComposer {...props} />));
|
||
typeText("Please check mobile too.");
|
||
act(() => root!.render(<TaskChatComposer {...props} pause={{ scope: "leaf", onResume }} />));
|
||
expect(container.querySelector('[contenteditable="true"]')).toBeNull();
|
||
expect(container.querySelector('button[aria-label="Send"]')).toBeNull();
|
||
expect(container.textContent).toContain("Your draft is saved.");
|
||
act(() => container.querySelector("button")!.click());
|
||
expect(onResume).toHaveBeenCalledOnce();
|
||
expect(onAdd).not.toHaveBeenCalled();
|
||
act(() => root!.render(<TaskChatComposer {...props} pause={{ scope: "leaf", pending: true, onResume }} />));
|
||
expect(container.querySelector("button")!.disabled).toBe(true);
|
||
act(() => root!.render(<TaskChatComposer {...props} />));
|
||
expect(editable().textContent).toBe("Please check mobile too.");
|
||
await act(async () => sendButton().click());
|
||
expect(onAdd).toHaveBeenCalledWith("Please check mobile too.", undefined, undefined, undefined, expect.any(String));
|
||
});
|
||
|
||
it("takes precedence over pending questions and queued-message edits", () => {
|
||
const onSkip = vi.fn();
|
||
act(() => root!.render(<TaskChatComposer
|
||
onAdd={vi.fn()} workMode="standard"
|
||
pause={{ scope: "subtree" }}
|
||
queuedEdit={{ commentId: "queued", body: "Queued draft" }}
|
||
takeover={{ id: "question", label: "Pending input", pendingCount: 1, content: <button>Answer question</button>, onDismiss: vi.fn(), onSkip }}
|
||
/>));
|
||
expect(container.textContent).toContain("Subtree is paused.");
|
||
expect(container.textContent).not.toContain("Answer question");
|
||
expect(container.textContent).not.toContain("Skip");
|
||
expect(container.querySelector('[contenteditable="true"]')).toBeNull();
|
||
expect(container.querySelector("button")!.disabled).toBe(true);
|
||
});
|
||
});
|
||
|
||
describe("queued message editing", () => {
|
||
const draftKey = "task-chat-draft:queued-edit";
|
||
|
||
function Harness({
|
||
onSave,
|
||
stale = false,
|
||
}: {
|
||
onSave: (commentId: string, body: string) => Promise<void>;
|
||
stale?: boolean;
|
||
}) {
|
||
const [queuedEdit, setQueuedEdit] = useState<{
|
||
commentId: string;
|
||
body: string;
|
||
stale?: boolean;
|
||
} | null>({
|
||
commentId: "queued-1",
|
||
body: "Complete queued markdown",
|
||
stale,
|
||
});
|
||
return (
|
||
<TaskChatComposer
|
||
onAdd={vi.fn()}
|
||
workMode="standard"
|
||
draftKey={draftKey}
|
||
queuedEdit={queuedEdit}
|
||
onSaveQueuedEdit={onSave}
|
||
onCancelQueuedEdit={() => setQueuedEdit(null)}
|
||
/>
|
||
);
|
||
}
|
||
|
||
it("restores the existing composer draft after cancelling an edit", async () => {
|
||
localStorage.setItem(draftKey, "Unsent normal draft");
|
||
render(<Harness onSave={vi.fn().mockResolvedValue(undefined)} />);
|
||
await flushAsync();
|
||
await vi.waitFor(() => {
|
||
expect(editable().textContent).toBe("Complete queued markdown");
|
||
});
|
||
expect(localStorage.getItem(draftKey)).toBe("Unsent normal draft");
|
||
|
||
const cancel = Array.from(container.querySelectorAll("button")).find(
|
||
(button) => button.textContent?.trim() === "Cancel",
|
||
);
|
||
flushSync(() => cancel?.click());
|
||
await flushAsync();
|
||
|
||
expect(editable().textContent).toBe("Unsent normal draft");
|
||
expect(localStorage.getItem(draftKey)).toBe("Unsent normal draft");
|
||
});
|
||
|
||
it("saves through the queue callback without posting a new comment", async () => {
|
||
localStorage.setItem(draftKey, "Normal draft stays here");
|
||
const onSave = vi.fn().mockResolvedValue(undefined);
|
||
render(<Harness onSave={onSave} />);
|
||
await flushAsync();
|
||
typeText("Edited queued markdown");
|
||
|
||
pressKey("Enter", { metaKey: true });
|
||
await flushAsync();
|
||
await flushAsync();
|
||
|
||
expect(onSave).toHaveBeenCalledWith("queued-1", "Edited queued markdown");
|
||
expect(editable().textContent).toBe("Normal draft stays here");
|
||
});
|
||
|
||
it("retains edited text when the queue target rejects the save", async () => {
|
||
const onSave = vi
|
||
.fn()
|
||
.mockRejectedValue(new Error("queued_comment_stale_target"));
|
||
render(<Harness onSave={onSave} />);
|
||
await flushAsync();
|
||
typeText("Keep this replacement text");
|
||
|
||
pressKey("Enter", { metaKey: true });
|
||
await flushAsync();
|
||
|
||
await vi.waitFor(() => {
|
||
expect(editable().textContent).toBe("Keep this replacement text");
|
||
expect(container.textContent).toContain("Editing queued message");
|
||
});
|
||
});
|
||
|
||
it("shows why a concurrent queue change rejected the save and keeps the edit", async () => {
|
||
const onSave = vi.fn().mockRejectedValue(new ApiError(
|
||
"The queued messages changed in another session",
|
||
409,
|
||
{ error: "The queued messages changed in another session", details: { code: "queued_comment_revision_conflict" } },
|
||
));
|
||
render(<Harness onSave={onSave} />);
|
||
await flushAsync();
|
||
typeText("Make the website blue");
|
||
|
||
pressKey("Enter", { metaKey: true });
|
||
await flushAsync();
|
||
|
||
await vi.waitFor(() => {
|
||
const alert = container.querySelector('[data-testid="task-chat-queued-edit-error"]');
|
||
expect(alert?.getAttribute("role")).toBe("alert");
|
||
expect(alert?.textContent).toBe(
|
||
"The queue changed in another session. Your edit is still here; save again to apply it to the latest queue.",
|
||
);
|
||
expect(editable().textContent).toBe("Make the website blue");
|
||
expect(container.textContent).toContain("Editing queued message");
|
||
});
|
||
|
||
onSave.mockResolvedValueOnce(undefined);
|
||
pressKey("Enter", { metaKey: true });
|
||
await flushAsync();
|
||
await flushAsync();
|
||
expect(onSave).toHaveBeenLastCalledWith("queued-1", "Make the website blue");
|
||
expect(container.querySelector('[data-testid="task-chat-queued-edit-error"]')).toBeNull();
|
||
});
|
||
|
||
it("offers a stale edit as a new queued message and preserves its Markdown source", async () => {
|
||
const onSave = vi.fn().mockResolvedValue(undefined);
|
||
render(<Harness onSave={onSave} stale />);
|
||
await flushAsync();
|
||
|
||
typeText(" replacement with trailing Markdown ");
|
||
expect(container.textContent).toContain("Queued message changed");
|
||
expect(sendButton().getAttribute("aria-label")).toBe(
|
||
"Queue as new message",
|
||
);
|
||
pressKey("Enter", { metaKey: true });
|
||
await flushAsync();
|
||
await flushAsync();
|
||
|
||
expect(onSave).toHaveBeenCalledWith(
|
||
"queued-1",
|
||
" replacement with trailing Markdown ",
|
||
);
|
||
});
|
||
});
|
||
|
||
describe("composer takeovers", () => {
|
||
it.each([false, true])("keeps the interaction card visible while sending a normal message (mobile=%s)", async (mobile) => {
|
||
const onAdd = vi.fn().mockResolvedValue(undefined);
|
||
renderComposer({
|
||
onAdd: onAdd,
|
||
workMode: "standard",
|
||
mobile: mobile,
|
||
takeover: {
|
||
id: "question-1",
|
||
label: "Question",
|
||
pendingCount: 1,
|
||
content: <p>Which environment?</p>,
|
||
onDismiss: vi.fn(),
|
||
onSkip: vi.fn(),
|
||
},
|
||
});
|
||
|
||
typeText("Continue investigating while I decide.");
|
||
expect(container.querySelector('[data-testid="task-chat-composer-takeover"]')?.textContent).toContain("Which environment?");
|
||
await act(async () => sendButton().click());
|
||
expect(onAdd).toHaveBeenCalledWith("Continue investigating while I decide.", undefined, undefined, undefined, expect.any(String));
|
||
expect(container.querySelector('[data-testid="task-chat-composer-takeover"]')?.textContent).toContain("Which environment?");
|
||
expect(editable().textContent).toBe("");
|
||
});
|
||
|
||
it("keeps the composer mode shortcut available beneath an open question", () => {
|
||
renderComposer({
|
||
onAdd: vi.fn(),
|
||
workMode: "standard",
|
||
onWorkModeChange: vi.fn(),
|
||
takeover: {
|
||
id: "question-1",
|
||
label: "Question",
|
||
pendingCount: 1,
|
||
content: <p>Which environment?</p>,
|
||
onDismiss: vi.fn(),
|
||
onSkip: vi.fn(),
|
||
},
|
||
});
|
||
pressKey(".", { metaKey: true });
|
||
expect(container.querySelector('[data-testid="task-chat-composer-mode"]')?.textContent).toContain("Plan");
|
||
expect(container.querySelector('[data-testid="task-chat-composer-takeover"]')).not.toBeNull();
|
||
});
|
||
|
||
it("shows a separate card above a usable editor and exposes Skip", async () => {
|
||
const onSkip = vi.fn().mockResolvedValue(undefined);
|
||
renderComposer({
|
||
onAdd: vi.fn(),
|
||
workMode: "standard",
|
||
takeover: {
|
||
id: "question-1",
|
||
label: "Deployment target",
|
||
pendingCount: 2,
|
||
content: <p>Which environment should receive this?</p>,
|
||
onDismiss: vi.fn(),
|
||
onSkip,
|
||
onShowNext: vi.fn(),
|
||
},
|
||
});
|
||
|
||
expect(
|
||
container.querySelector('[data-testid="task-chat-composer-takeover"]')
|
||
?.textContent,
|
||
).toContain("Which environment should receive this?");
|
||
const card = container.querySelector('[data-testid="task-chat-composer-takeover"]')!;
|
||
const composer = container.querySelector('.paperclip-task-chat-composer')!;
|
||
expect(card.compareDocumentPosition(composer) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
|
||
expect(container.querySelector('[data-testid="mdx-editor"]')).not.toBeNull();
|
||
expect(container.querySelector<HTMLButtonElement>('[data-testid="task-chat-composer-send"]')).not.toBeNull();
|
||
expect(container.textContent).not.toContain("Input needed");
|
||
expect(container.textContent).not.toContain("Write instead");
|
||
const skip = Array.from(
|
||
container.querySelectorAll<HTMLButtonElement>("button"),
|
||
).find((button) => button.textContent?.trim() === "Skip");
|
||
flushSync(() => skip?.click());
|
||
await flushAsync();
|
||
expect(onSkip).toHaveBeenCalledTimes(1);
|
||
});
|
||
|
||
it("restores the exact ordinary draft after Skip", async () => {
|
||
const draftKey = "task-composer-takeover-draft";
|
||
localStorage.setItem(draftKey, "Preserved draft with **markdown**");
|
||
|
||
function Harness() {
|
||
const [open, setOpen] = useState(true);
|
||
return (
|
||
<TaskChatComposer
|
||
onAdd={vi.fn()}
|
||
workMode="planning"
|
||
draftKey={draftKey}
|
||
takeover={
|
||
open
|
||
? {
|
||
id: "plan-review",
|
||
label: "Review plan",
|
||
pendingCount: 1,
|
||
content: <p>Do you accept this plan?</p>,
|
||
onDismiss: () => setOpen(false),
|
||
onSkip: () => setOpen(false),
|
||
}
|
||
: null
|
||
}
|
||
/>
|
||
);
|
||
}
|
||
|
||
render(<Harness />);
|
||
const skip = Array.from(
|
||
container.querySelectorAll<HTMLButtonElement>("button"),
|
||
).find((button) => button.textContent?.trim() === "Skip");
|
||
flushSync(() => skip?.click());
|
||
await flushAsync();
|
||
|
||
expect(editable().textContent).toBe("Preserved draft with **markdown**");
|
||
expect(container.textContent).not.toContain("Write instead");
|
||
});
|
||
|
||
it("keeps title, pending count, pagination, and dismiss on one header row", () => {
|
||
renderComposer({
|
||
onAdd: vi.fn(),
|
||
workMode: "standard",
|
||
takeover: {
|
||
id: "paged-questions",
|
||
label: "Release decisions",
|
||
pendingCount: 2,
|
||
inlineSkip: true,
|
||
content: (
|
||
<QuestionForm
|
||
id="release-decisions"
|
||
questionSet={{
|
||
schema: "paperclip.question_set.v1",
|
||
questions: [
|
||
{
|
||
id: "scope",
|
||
prompt: "Where should this ship?",
|
||
required: false,
|
||
answerMode: "single_select",
|
||
options: [{ id: "pilot", label: "Pilot" }],
|
||
},
|
||
{
|
||
id: "checks",
|
||
prompt: "Which checks matter?",
|
||
required: false,
|
||
answerMode: "multi_select",
|
||
options: [{ id: "a11y", label: "Accessibility" }],
|
||
},
|
||
],
|
||
}}
|
||
onSubmit={vi.fn()}
|
||
/>
|
||
),
|
||
onDismiss: vi.fn(),
|
||
onSkip: vi.fn(),
|
||
onShowNext: vi.fn(),
|
||
},
|
||
});
|
||
|
||
const header = container.querySelector(
|
||
'[data-testid="task-chat-composer-takeover-header"]',
|
||
);
|
||
expect(header?.textContent).toContain("Release decisions");
|
||
expect(header?.textContent).toContain("2 pending");
|
||
expect(header?.textContent).toContain("1 of 2");
|
||
expect(
|
||
header?.querySelector('button[aria-label="Dismiss Release decisions"]'),
|
||
).not.toBeNull();
|
||
expect(
|
||
header?.querySelector('[aria-label="Question pagination"]'),
|
||
).not.toBeNull();
|
||
expect(
|
||
container.querySelector(
|
||
'[data-testid="task-chat-composer-takeover-body"] [aria-label="Question pagination"]',
|
||
),
|
||
).toBeNull();
|
||
});
|
||
|
||
it("waits for the submit button on a single-select question", async () => {
|
||
const onSubmit = vi.fn();
|
||
renderComposer({
|
||
onAdd: vi.fn(),
|
||
workMode: "standard",
|
||
takeover: {
|
||
id: "opening-question",
|
||
label: "Questions",
|
||
pendingCount: 1,
|
||
inlineSkip: true,
|
||
content: (
|
||
<QuestionForm
|
||
id="first-task-opening"
|
||
questionSet={{
|
||
schema: "paperclip.question_set.v1",
|
||
submitLabel: "Continue",
|
||
questions: [
|
||
{
|
||
id: "first-task-opening",
|
||
prompt: "What would you like to do?",
|
||
required: true,
|
||
answerMode: "single_select",
|
||
options: [
|
||
{ id: "interview", label: "Interview me" },
|
||
{ id: "task", label: "I have a task in mind" },
|
||
],
|
||
},
|
||
],
|
||
}}
|
||
onSubmit={onSubmit}
|
||
/>
|
||
),
|
||
onDismiss: vi.fn(),
|
||
onSkip: vi.fn(),
|
||
},
|
||
});
|
||
|
||
const buttons = () =>
|
||
Array.from(container.querySelectorAll<HTMLButtonElement>("button"));
|
||
const interview = buttons().find((button) =>
|
||
button.textContent?.includes("Interview me"),
|
||
);
|
||
expect(interview).not.toBeUndefined();
|
||
|
||
// Picking the option only selects it: nothing is sent yet.
|
||
flushSync(() => interview?.click());
|
||
await flushAsync();
|
||
expect(interview?.getAttribute("data-selected")).toBe("true");
|
||
expect(onSubmit).not.toHaveBeenCalled();
|
||
|
||
// A required question cannot be skipped.
|
||
expect(
|
||
buttons().find((button) => button.textContent?.trim() === "Skip"),
|
||
).toBeUndefined();
|
||
|
||
// The submit button carries the card's label and does the sending.
|
||
const submit = buttons().find(
|
||
(button) => button.textContent?.trim() === "Continue",
|
||
);
|
||
expect(submit).not.toBeUndefined();
|
||
expect(submit?.disabled).toBe(false);
|
||
flushSync(() => submit?.click());
|
||
await flushAsync();
|
||
expect(onSubmit).toHaveBeenCalledTimes(1);
|
||
expect(onSubmit.mock.calls[0]?.[0]).toMatchObject({
|
||
answers: { "first-task-opening": { selectedOptionIds: ["interview"] } },
|
||
});
|
||
});
|
||
|
||
it("advances on Next, preserves answers when going back, and skips optional answers", async () => {
|
||
const onSubmit = vi.fn();
|
||
renderComposer({
|
||
onAdd: vi.fn(),
|
||
workMode: "standard",
|
||
takeover: {
|
||
id: "interview",
|
||
label: "Questions",
|
||
pendingCount: 1,
|
||
inlineSkip: true,
|
||
content: (
|
||
<QuestionForm
|
||
id="interview"
|
||
questionSet={{
|
||
schema: "paperclip.question_set.v1",
|
||
questions: [
|
||
{
|
||
id: "env",
|
||
prompt: "Where?",
|
||
required: true,
|
||
answerMode: "single_select",
|
||
options: [{ id: "staging", label: "Staging" }],
|
||
},
|
||
{
|
||
id: "when",
|
||
prompt: "When?",
|
||
required: false,
|
||
answerMode: "single_select",
|
||
options: [{ id: "today", label: "Today" }],
|
||
},
|
||
{
|
||
id: "who",
|
||
prompt: "Who?",
|
||
required: false,
|
||
answerMode: "single_select",
|
||
options: [{ id: "me", label: "Me" }],
|
||
},
|
||
],
|
||
}}
|
||
onSubmit={onSubmit}
|
||
/>
|
||
),
|
||
onDismiss: vi.fn(),
|
||
onSkip: vi.fn(),
|
||
},
|
||
});
|
||
|
||
const buttons = () =>
|
||
Array.from(container.querySelectorAll<HTMLButtonElement>("button"));
|
||
const byLabel = (label: string) =>
|
||
buttons().find((button) => button.textContent?.trim() === label);
|
||
|
||
// Page 1: required, so no Skip. Next explains a missing answer only
|
||
// after an attempt; selecting an answer still does not navigate.
|
||
expect(byLabel("Skip")).toBeUndefined();
|
||
expect(byLabel("Next")?.disabled).toBe(false);
|
||
flushSync(() => byLabel("Next")?.click());
|
||
expect(container.textContent).toContain("This question is required.");
|
||
expect(container.textContent).toContain("Where?");
|
||
flushSync(() => byLabel("Staging")?.click());
|
||
await flushAsync();
|
||
expect(container.textContent).toContain("Where?");
|
||
expect(byLabel("Next")?.disabled).toBe(false);
|
||
flushSync(() => byLabel("Next")?.click());
|
||
await flushAsync();
|
||
expect(onSubmit).not.toHaveBeenCalled();
|
||
expect(container.textContent).toContain("When?");
|
||
expect(document.activeElement?.textContent).toBe("When?");
|
||
|
||
// Page 2: answer, then Next. Go back to confirm it is saved, then skip.
|
||
flushSync(() => byLabel("Today")?.click());
|
||
await flushAsync();
|
||
flushSync(() => byLabel("Next")?.click());
|
||
await flushAsync();
|
||
expect(container.textContent).toContain("Who?");
|
||
flushSync(() => container.querySelector<HTMLButtonElement>('button[aria-label="Previous question"]')?.click());
|
||
await flushAsync();
|
||
expect(byLabel("Today")?.getAttribute("aria-checked")).toBe("true");
|
||
flushSync(() => byLabel("Skip")?.click());
|
||
await flushAsync();
|
||
expect(container.textContent).toContain("Who?");
|
||
expect(onSubmit).not.toHaveBeenCalled();
|
||
|
||
// Last page: primary reads Submit answers and sends everything.
|
||
expect(byLabel("Next")).toBeUndefined();
|
||
flushSync(() => byLabel("Me")?.click());
|
||
await flushAsync();
|
||
flushSync(() => byLabel("Submit answers")?.click());
|
||
await flushAsync();
|
||
expect(onSubmit).toHaveBeenCalledTimes(1);
|
||
const response = onSubmit.mock.calls[0]?.[0];
|
||
expect(response.answers.env).toEqual({ selectedOptionIds: ["staging"] });
|
||
expect(response.answers.when).toBeUndefined();
|
||
expect(response.answers.who).toEqual({ selectedOptionIds: ["me"] });
|
||
});
|
||
|
||
it.each(["click", "keyboard"])("records a single choice by %s without leaving the question", async (input) => {
|
||
const onSubmit = vi.fn();
|
||
render(<QuestionForm
|
||
id="selection-modes"
|
||
questionSet={{
|
||
schema: "paperclip.question_set.v1",
|
||
questions: [
|
||
{ id: "storage", prompt: "Storage?", required: true, answerMode: "single_select",
|
||
options: [{ id: "sqlite", label: "SQLite" }], customAnswer: { enabled: true } },
|
||
{ id: "features", prompt: "Features?", required: true, answerMode: "multi_select",
|
||
options: [{ id: "auth", label: "Sign in" }, { id: "search", label: "Search" }] },
|
||
{ id: "notes", prompt: "Notes?", required: false, answerMode: "text" },
|
||
],
|
||
}}
|
||
initialResponse={{ schema: "paperclip.question_response.v1", answers: { storage: { selectedOptionIds: ["sqlite"] } } }}
|
||
onSubmit={onSubmit}
|
||
/>);
|
||
const byLabel = (label: string) => Array.from(container.querySelectorAll<HTMLButtonElement>("button"))
|
||
.find((button) => button.textContent?.trim() === label)!;
|
||
// Restoring a selection does not advance. Other needs text first.
|
||
expect(container.textContent).toContain("1 of 3");
|
||
flushSync(() => byLabel("Other").click());
|
||
await flushAsync();
|
||
expect(container.textContent).toContain("1 of 3");
|
||
expect(container.querySelector('[data-testid="question-other-answer-composer"]')).not.toBeNull();
|
||
expect(byLabel("Next").disabled).toBe(false);
|
||
expect(container.querySelector('[role="alert"]')).toBeNull();
|
||
flushSync(() => {
|
||
if (input === "click") byLabel("SQLite").click();
|
||
else byLabel("SQLite").dispatchEvent(new KeyboardEvent("keydown", { key: "1", bubbles: true }));
|
||
});
|
||
await flushAsync();
|
||
// Answering re-enables Next and closes Other, but the reader stays here.
|
||
expect(container.textContent).toContain("1 of 3");
|
||
expect(container.querySelector('[data-testid="question-other-answer-composer"]')).toBeNull();
|
||
expect(byLabel("SQLite").getAttribute("aria-checked")).toBe("true");
|
||
expect(byLabel("Next").disabled).toBe(false);
|
||
flushSync(() => byLabel("Next").click());
|
||
await flushAsync();
|
||
expect(container.textContent).toContain("2 of 3");
|
||
expect(document.activeElement?.textContent).toBe("Features?");
|
||
flushSync(() => document.activeElement?.dispatchEvent(new KeyboardEvent("keydown", { key: "1", repeat: true, bubbles: true })));
|
||
expect(byLabel("Sign in").getAttribute("aria-checked")).toBe("false");
|
||
flushSync(() => byLabel("Sign in").click());
|
||
flushSync(() => byLabel("Search").click());
|
||
expect(container.textContent).toContain("2 of 3");
|
||
expect(byLabel("Sign in").getAttribute("aria-checked")).toBe("true");
|
||
expect(byLabel("Search").getAttribute("aria-checked")).toBe("true");
|
||
expect(onSubmit).not.toHaveBeenCalled();
|
||
flushSync(() => byLabel("Next").click());
|
||
await flushAsync();
|
||
expect(container.textContent).toContain("3 of 3");
|
||
flushSync(() => byLabel("Submit answers").click());
|
||
await flushAsync();
|
||
expect(onSubmit).toHaveBeenCalledExactlyOnceWith({
|
||
schema: "paperclip.question_response.v1",
|
||
answers: { storage: { selectedOptionIds: ["sqlite"] }, features: { selectedOptionIds: ["auth", "search"] } },
|
||
});
|
||
});
|
||
|
||
describe("single-choice selection stays on the page", () => {
|
||
const questionSet = {
|
||
schema: "paperclip.question_set.v1" as const,
|
||
questions: ["First", "Second", "Third"].map((prompt) => ({
|
||
id: prompt, prompt, required: true, answerMode: "single_select" as const,
|
||
options: [{ id: "yes", label: "Yes" }, { id: "no", label: "No" }],
|
||
customAnswer: { enabled: true as const },
|
||
})),
|
||
};
|
||
const form = () => (
|
||
<QuestionForm id="stationary" questionSet={questionSet} onSubmit={vi.fn()} />
|
||
);
|
||
const click = (selector: string) => act(() => {
|
||
flushSync(() => container.querySelector<HTMLButtonElement>(selector)!.click());
|
||
});
|
||
const buttonByText = (text: string) =>
|
||
Array.from(container.querySelectorAll("button")).find(
|
||
(button) => button.textContent?.trim() === text,
|
||
);
|
||
|
||
it("records the answer without navigating", () => {
|
||
render(form());
|
||
click('[role="radio"]');
|
||
expect(container.querySelector('[role="radio"]')?.getAttribute("aria-checked")).toBe("true");
|
||
expect(container.textContent).toContain("1 of 3");
|
||
expect(container.textContent).toContain("First");
|
||
});
|
||
|
||
it("lets the reader change their mind before moving on", () => {
|
||
render(form());
|
||
click('[role="radio"]');
|
||
const radios = () => Array.from(container.querySelectorAll('[role="radio"]'));
|
||
act(() => { flushSync(() => (radios()[1] as HTMLButtonElement).click()); });
|
||
expect(radios()[0]?.getAttribute("aria-checked")).toBe("false");
|
||
expect(radios()[1]?.getAttribute("aria-checked")).toBe("true");
|
||
expect(container.textContent).toContain("1 of 3");
|
||
});
|
||
|
||
it("advances only on an explicit Next", () => {
|
||
render(form());
|
||
click('[role="radio"]');
|
||
expect(container.textContent).toContain("1 of 3");
|
||
act(() => { flushSync(() => buttonByText("Next")!.click()); });
|
||
expect(container.textContent).toContain("2 of 3");
|
||
expect(document.activeElement?.textContent).toBe("Second");
|
||
});
|
||
|
||
it("keeps number-key selection on the same question", () => {
|
||
render(form());
|
||
const page = container.querySelector<HTMLElement>(".tc-question-page")!;
|
||
act(() => {
|
||
flushSync(() => page.dispatchEvent(
|
||
new KeyboardEvent("keydown", { key: "2", bubbles: true }),
|
||
));
|
||
});
|
||
expect(Array.from(container.querySelectorAll('[role="radio"]'))[1]?.getAttribute("aria-checked"))
|
||
.toBe("true");
|
||
expect(container.textContent).toContain("1 of 3");
|
||
});
|
||
|
||
// Selection now clears the form error, which it did not do on the last
|
||
// page before. A failed send has to outlive it: the answers are still
|
||
// unsent, so wiping the message would leave no sign of that at all.
|
||
it("keeps a failed send visible while the reader changes their answer", async () => {
|
||
const onSubmit = vi.fn().mockRejectedValue(new Error("Network unreachable"));
|
||
render(
|
||
<QuestionForm
|
||
id="failed-send"
|
||
questionSet={{
|
||
schema: "paperclip.question_set.v1" as const,
|
||
questions: [{
|
||
id: "only", prompt: "Only", required: true,
|
||
answerMode: "single_select" as const,
|
||
options: [{ id: "yes", label: "Yes" }, { id: "no", label: "No" }],
|
||
}],
|
||
}}
|
||
onSubmit={onSubmit}
|
||
/>,
|
||
);
|
||
const radios = () => Array.from(container.querySelectorAll<HTMLButtonElement>('[role="radio"]'));
|
||
act(() => { flushSync(() => radios()[0]!.click()); });
|
||
act(() => { flushSync(() => buttonByText("Submit answers")!.click()); });
|
||
await flushAsync();
|
||
expect(onSubmit).toHaveBeenCalledOnce();
|
||
expect(container.textContent).toContain("Network unreachable");
|
||
act(() => { flushSync(() => radios()[1]!.click()); });
|
||
expect(radios()[1]?.getAttribute("aria-checked")).toBe("true");
|
||
expect(container.textContent).toContain("Network unreachable");
|
||
});
|
||
|
||
// The other half of the same rule: the one complaint a selection does
|
||
// answer still goes away when it is answered.
|
||
it("clears a missing-answer complaint once that question is answered", async () => {
|
||
render(
|
||
<QuestionForm
|
||
id="missing-answer"
|
||
questionSet={{
|
||
schema: "paperclip.question_set.v1" as const,
|
||
questions: [
|
||
{
|
||
id: "First", prompt: "First", required: true,
|
||
answerMode: "single_select" as const,
|
||
options: [{ id: "yes", label: "Yes" }, { id: "no", label: "No" }],
|
||
},
|
||
{
|
||
id: "Second", prompt: "Second", required: false,
|
||
answerMode: "single_select" as const,
|
||
options: [{ id: "yes", label: "Yes" }, { id: "no", label: "No" }],
|
||
},
|
||
],
|
||
}}
|
||
onSubmit={vi.fn()}
|
||
/>,
|
||
);
|
||
const radios = () => Array.from(container.querySelectorAll<HTMLButtonElement>('[role="radio"]'));
|
||
// The pagination arrow browses without validating, so the reader can
|
||
// reach the end with the first question still blank. Skip on the last
|
||
// question then sends, which is where the complaint comes from.
|
||
click('[aria-label="Next question"]');
|
||
act(() => { flushSync(() => buttonByText("Skip")!.click()); });
|
||
await flushAsync();
|
||
expect(container.textContent).toContain("Question 1 needs an answer");
|
||
act(() => { flushSync(() => radios()[0]!.click()); });
|
||
expect(container.textContent).not.toContain("Question 1 needs an answer");
|
||
});
|
||
});
|
||
|
||
it("Skip on the last question submits the other answers", async () => {
|
||
const onSubmit = vi.fn();
|
||
renderComposer({
|
||
onAdd: vi.fn(),
|
||
workMode: "standard",
|
||
takeover: {
|
||
id: "optional-tail",
|
||
label: "Questions",
|
||
pendingCount: 1,
|
||
inlineSkip: true,
|
||
content: (
|
||
<QuestionForm
|
||
id="optional-tail"
|
||
questionSet={{
|
||
schema: "paperclip.question_set.v1",
|
||
questions: [
|
||
{
|
||
id: "env",
|
||
prompt: "Where?",
|
||
required: false,
|
||
answerMode: "single_select",
|
||
options: [{ id: "staging", label: "Staging" }],
|
||
},
|
||
{
|
||
id: "notes",
|
||
prompt: "Anything else?",
|
||
required: false,
|
||
answerMode: "text",
|
||
},
|
||
],
|
||
}}
|
||
onSubmit={onSubmit}
|
||
/>
|
||
),
|
||
onDismiss: vi.fn(),
|
||
onSkip: vi.fn(),
|
||
},
|
||
});
|
||
|
||
const byLabel = (label: string) =>
|
||
Array.from(
|
||
container.querySelectorAll<HTMLButtonElement>("button"),
|
||
).find((button) => button.textContent?.trim() === label);
|
||
flushSync(() => byLabel("Staging")?.click());
|
||
await flushAsync();
|
||
flushSync(() => byLabel("Next")?.click());
|
||
await flushAsync();
|
||
expect(container.textContent).toContain("Anything else?");
|
||
flushSync(() => byLabel("Skip")?.click());
|
||
await flushAsync();
|
||
expect(onSubmit).toHaveBeenCalledTimes(1);
|
||
expect(onSubmit.mock.calls[0]?.[0]).toMatchObject({
|
||
answers: { env: { selectedOptionIds: ["staging"] } },
|
||
});
|
||
});
|
||
|
||
it("Skip on the last question returns to a required question the arrows walked past", async () => {
|
||
const onSubmit = vi.fn();
|
||
renderComposer({
|
||
onAdd: vi.fn(),
|
||
workMode: "standard",
|
||
takeover: {
|
||
id: "walked-past",
|
||
label: "Questions",
|
||
pendingCount: 1,
|
||
inlineSkip: true,
|
||
content: (
|
||
<QuestionForm
|
||
id="walked-past"
|
||
questionSet={{
|
||
schema: "paperclip.question_set.v1",
|
||
questions: [
|
||
{
|
||
id: "env",
|
||
prompt: "Where?",
|
||
required: true,
|
||
answerMode: "single_select",
|
||
options: [{ id: "staging", label: "Staging" }],
|
||
},
|
||
{
|
||
id: "notes",
|
||
prompt: "Anything else?",
|
||
required: false,
|
||
answerMode: "text",
|
||
},
|
||
],
|
||
}}
|
||
onSubmit={onSubmit}
|
||
/>
|
||
),
|
||
onDismiss: vi.fn(),
|
||
onSkip: vi.fn(),
|
||
},
|
||
});
|
||
|
||
const byLabel = (label: string) =>
|
||
Array.from(
|
||
container.querySelectorAll<HTMLButtonElement>("button"),
|
||
).find((button) => button.textContent?.trim() === label);
|
||
// The pagination arrow browses past the unanswered required question.
|
||
const arrow = container.querySelector<HTMLButtonElement>(
|
||
'button[aria-label="Next question"]',
|
||
);
|
||
flushSync(() => arrow?.click());
|
||
await flushAsync();
|
||
expect(container.textContent).toContain("Anything else?");
|
||
|
||
// Skip here would send; instead the form goes back and says why.
|
||
flushSync(() => byLabel("Skip")?.click());
|
||
await flushAsync();
|
||
expect(onSubmit).not.toHaveBeenCalled();
|
||
expect(container.textContent).toContain("Where?");
|
||
expect(container.textContent).toContain(
|
||
"Question 1 needs an answer before you can send.",
|
||
);
|
||
});
|
||
|
||
it("Cancel closes the takeover and leaves the request pending", async () => {
|
||
const onSubmit = vi.fn();
|
||
const onDismiss = vi.fn();
|
||
const onSkip = vi.fn();
|
||
renderComposer({
|
||
onAdd: vi.fn(),
|
||
workMode: "standard",
|
||
takeover: {
|
||
id: "cancelable",
|
||
label: "Questions",
|
||
pendingCount: 1,
|
||
inlineSkip: true,
|
||
content: (
|
||
<QuestionForm
|
||
id="cancelable"
|
||
questionSet={{
|
||
schema: "paperclip.question_set.v1",
|
||
questions: [
|
||
{
|
||
id: "env",
|
||
prompt: "Where?",
|
||
required: true,
|
||
answerMode: "single_select",
|
||
options: [{ id: "staging", label: "Staging" }],
|
||
},
|
||
],
|
||
}}
|
||
onSubmit={onSubmit}
|
||
/>
|
||
),
|
||
onDismiss,
|
||
onSkip,
|
||
},
|
||
});
|
||
|
||
const cancel = Array.from(
|
||
container.querySelectorAll<HTMLButtonElement>("button"),
|
||
).find((button) => button.textContent?.trim() === "Cancel");
|
||
expect(cancel).not.toBeUndefined();
|
||
flushSync(() => cancel?.click());
|
||
await flushAsync();
|
||
expect(onDismiss).toHaveBeenCalledTimes(1);
|
||
expect(onSkip).not.toHaveBeenCalled();
|
||
expect(onSubmit).not.toHaveBeenCalled();
|
||
});
|
||
|
||
it("places Skip beside Submit answers for structured questions", () => {
|
||
renderComposer({
|
||
onAdd: vi.fn(),
|
||
workMode: "standard",
|
||
takeover: {
|
||
id: "structured-question",
|
||
label: "Deployment target",
|
||
pendingCount: 1,
|
||
inlineSkip: true,
|
||
content: (
|
||
<QuestionForm
|
||
id="deployment-target"
|
||
questionSet={{
|
||
schema: "paperclip.question_set.v1",
|
||
questions: [
|
||
{
|
||
id: "environment",
|
||
prompt: "Which environment should receive this?",
|
||
required: false,
|
||
answerMode: "multi_select",
|
||
options: [
|
||
{ id: "staging", label: "Staging", recommended: true },
|
||
{ id: "production", label: "Production" },
|
||
],
|
||
},
|
||
],
|
||
}}
|
||
onSubmit={vi.fn()}
|
||
/>
|
||
),
|
||
onDismiss: vi.fn(),
|
||
onSkip: vi.fn(),
|
||
},
|
||
});
|
||
|
||
const buttons = Array.from(
|
||
container.querySelectorAll<HTMLButtonElement>("button"),
|
||
);
|
||
const skip = buttons.find(
|
||
(button) => button.textContent?.trim() === "Skip",
|
||
);
|
||
const submit = buttons.find(
|
||
(button) => button.textContent?.trim() === "Submit answers",
|
||
);
|
||
expect(skip).not.toBeUndefined();
|
||
expect(submit).not.toBeUndefined();
|
||
expect(skip?.parentElement).toBe(submit?.parentElement);
|
||
expect(
|
||
buttons.filter((button) => button.textContent?.trim() === "Skip"),
|
||
).toHaveLength(1);
|
||
const takeoverBody = container.querySelector(
|
||
'[data-testid="task-chat-composer-takeover-body"]',
|
||
);
|
||
expect(takeoverBody?.className).not.toContain("max-h-");
|
||
expect(takeoverBody?.className).not.toContain("overflow-y-auto");
|
||
expect(takeoverBody?.className).not.toContain("pr-8");
|
||
|
||
const staging = buttons.find((button) =>
|
||
button.textContent?.includes("Staging"),
|
||
);
|
||
const production = buttons.find(
|
||
(button) => button.textContent?.trim() === "Production",
|
||
);
|
||
expect(staging?.getAttribute("data-recommended")).toBe("true");
|
||
expect(staging?.className.split(" ")).toContain("bg-muted/50");
|
||
expect(
|
||
production?.className
|
||
.split(" ")
|
||
.some(
|
||
(token) => token.startsWith("border") || token.startsWith("bg-"),
|
||
),
|
||
).toBe(false);
|
||
|
||
flushSync(() => staging?.click());
|
||
expect(staging?.getAttribute("data-selected")).toBe("true");
|
||
expect(staging?.className.split(" ")).toContain("bg-foreground/5");
|
||
});
|
||
|
||
it("hides Skip when the takeover already provides a request-changes path", () => {
|
||
renderComposer({
|
||
onAdd: vi.fn(),
|
||
workMode: "planning",
|
||
takeover: {
|
||
id: "plan-review",
|
||
label: "Review the proposed plan",
|
||
pendingCount: 1,
|
||
content: <p>Do you accept this plan?</p>,
|
||
onDismiss: vi.fn(),
|
||
onSkip: vi.fn(),
|
||
hideSkip: true,
|
||
},
|
||
});
|
||
|
||
expect(container.textContent).not.toContain("Skip");
|
||
expect(
|
||
container.querySelector(
|
||
'button[aria-label="Dismiss Review the proposed plan"]',
|
||
),
|
||
).not.toBeNull();
|
||
expect(
|
||
container.querySelector(
|
||
'[data-testid="task-chat-composer-takeover"] .border-t',
|
||
),
|
||
).toBeNull();
|
||
});
|
||
|
||
it("dismisses every takeover without invoking Skip", async () => {
|
||
const onDismiss = vi.fn();
|
||
const onSkip = vi.fn();
|
||
renderComposer({
|
||
onAdd: vi.fn(),
|
||
workMode: "standard",
|
||
takeover: {
|
||
id: "dismissable-question",
|
||
label: "Release questions",
|
||
pendingCount: 1,
|
||
content: <p>Which release should ship?</p>,
|
||
onDismiss,
|
||
onSkip,
|
||
},
|
||
});
|
||
|
||
flushSync(() =>
|
||
container
|
||
.querySelector<HTMLButtonElement>(
|
||
'button[aria-label="Dismiss Release questions"]',
|
||
)
|
||
?.click(),
|
||
);
|
||
await flushAsync();
|
||
|
||
expect(onDismiss).toHaveBeenCalledTimes(1);
|
||
expect(onSkip).not.toHaveBeenCalled();
|
||
});
|
||
});
|
||
});
|
||
|
||
describe("composer Stop", () => {
|
||
function stopButton() { return container.querySelector<HTMLButtonElement>('[data-testid="task-chat-composer-stop"]'); }
|
||
|
||
function nativeStopAwaitingContainment(): HeartbeatRun & { runtimeMode: "native" } {
|
||
const observed: Partial<HeartbeatRun> & { runtimeMode: "native" } = {
|
||
id: "run", companyId: "company", status: "cancelled", runtimeMode: "native",
|
||
resultJson: { executionCancellation: { state: "requested" }, nativeCancellation: {
|
||
schema: "paperclip.native-cancellation.v1", runId: "run", companyId: "company",
|
||
scope: "run", dispatched: true, dispatchState: "acknowledged",
|
||
} } };
|
||
return observed as HeartbeatRun & { runtimeMode: "native" };
|
||
}
|
||
|
||
it.each([{ runIds: ["first"] }, { runIds: ["first", "second"] }])("clears a timed-out Stop only after every exact target is confirmed: $runIds", async ({ runIds }) => {
|
||
vi.useFakeTimers();
|
||
try {
|
||
const onStop = vi.fn(() => waitForStoppedRuns(runIds, {
|
||
getRun: vi.fn(async id => ({ ...nativeStopAwaitingContainment(), id })), timeoutMs: 1000,
|
||
}));
|
||
const onAdd = vi.fn();
|
||
render(<TaskChatComposer workMode="standard" onAdd={onAdd} onStop={onStop} />);
|
||
flushSync(() => stopButton()!.click());
|
||
await act(async () => { await vi.advanceTimersByTimeAsync(1000); });
|
||
expect(container.querySelector('[role="alert"]')?.textContent).toContain("stop was requested");
|
||
render(<TaskChatComposer workMode="standard" onAdd={onAdd} confirmedStoppedRunIds={new Set(["unrelated"])} />);
|
||
await act(async () => {});
|
||
expect(container.querySelector('[role="alert"]')).not.toBeNull();
|
||
if (runIds.length > 1) {
|
||
render(<TaskChatComposer workMode="standard" onAdd={onAdd} confirmedStoppedRunIds={new Set([runIds[0]])} />);
|
||
await act(async () => {});
|
||
expect(container.querySelector('[role="alert"]')).not.toBeNull();
|
||
}
|
||
render(<TaskChatComposer workMode="standard" onAdd={onAdd} confirmedStoppedRunIds={new Set(runIds)} />);
|
||
await act(async () => {});
|
||
expect(container.querySelector('[role="alert"]')).toBeNull();
|
||
expect(onAdd).not.toHaveBeenCalled();
|
||
} finally { vi.useRealTimers(); }
|
||
});
|
||
|
||
it("keeps a newer Stop attempt independent of an earlier target's confirmation", async () => {
|
||
vi.useFakeTimers();
|
||
try {
|
||
const attempt = (id: string) => () => waitForStoppedRuns([id], {
|
||
getRun: vi.fn(async () => ({ ...nativeStopAwaitingContainment(), id })), timeoutMs: 1000,
|
||
});
|
||
render(<TaskChatComposer workMode="standard" onAdd={vi.fn()} onStop={attempt("first")} />);
|
||
flushSync(() => stopButton()!.click());
|
||
await act(async () => { await vi.advanceTimersByTimeAsync(1000); });
|
||
render(<TaskChatComposer workMode="standard" onAdd={vi.fn()} onStop={attempt("second")} />);
|
||
flushSync(() => stopButton()!.click());
|
||
await act(async () => { await vi.advanceTimersByTimeAsync(1000); });
|
||
render(<TaskChatComposer workMode="standard" onAdd={vi.fn()} confirmedStoppedRunIds={new Set(["first"])} />);
|
||
await act(async () => {});
|
||
expect(container.querySelector('[role="alert"]')).not.toBeNull();
|
||
render(<TaskChatComposer workMode="standard" onAdd={vi.fn()} confirmedStoppedRunIds={new Set(["second"])} />);
|
||
await act(async () => {});
|
||
expect(container.querySelector('[role="alert"]')).toBeNull();
|
||
} finally { vi.useRealTimers(); }
|
||
});
|
||
|
||
it("retains an ordinary Stop error when unrelated stop proof arrives", async () => {
|
||
render(<TaskChatComposer workMode="standard" onAdd={vi.fn()} onStop={async () => { throw new Error("Stop permission denied"); }} />);
|
||
flushSync(() => stopButton()!.click()); await flushAsync();
|
||
render(<TaskChatComposer workMode="standard" onAdd={vi.fn()} confirmedStoppedRunIds={new Set(["run"])} />);
|
||
await flushAsync();
|
||
expect(container.querySelector('[role="alert"]')?.textContent).toBe("Stop permission denied");
|
||
});
|
||
|
||
it("finishes one Stop without a stale warning when the server proves containment after native acknowledgement", async () => {
|
||
const requested = nativeStopAwaitingContainment();
|
||
let publishContainment!: (value: HeartbeatRun) => void;
|
||
const getRun = vi.fn(() => new Promise<HeartbeatRun>(resolve => { publishContainment = resolve; }));
|
||
const onStop = vi.fn(() => waitForStoppedRuns([requested.id], { initialRuns: [requested], getRun }));
|
||
const onAdd = vi.fn();
|
||
render(<TaskChatComposer workMode="standard" onAdd={onAdd} onStop={onStop} />);
|
||
flushSync(() => stopButton()!.click());
|
||
await flushAsync();
|
||
expect(stopButton()?.getAttribute("aria-label")).toBe("Stopping…");
|
||
expect(getRun).toHaveBeenCalledExactlyOnceWith(requested.id);
|
||
expect(container.querySelector('[role="alert"]')).toBeNull();
|
||
|
||
// The run can already appear Stopped while the independent execution proof
|
||
// is settling. Removing the action must neither prove Stop nor erase a draft.
|
||
render(<TaskChatComposer workMode="standard" onAdd={onAdd} />);
|
||
typeText("Keep this note.");
|
||
await act(async () => publishContainment({ ...requested, resultJson: { ...requested.resultJson,
|
||
executionCancellation: { state: "acknowledged", proof: "provider_termination_receipt" } } }));
|
||
await flushAsync();
|
||
expect(onStop).toHaveBeenCalledOnce();
|
||
expect(onAdd).not.toHaveBeenCalled();
|
||
expect(container.querySelector('[role="alert"]')).toBeNull();
|
||
expect(editable().textContent).toBe("Keep this note.");
|
||
});
|
||
|
||
it("does not mistake a native acknowledgement or disappearing Stop action for physical containment", async () => {
|
||
vi.useFakeTimers();
|
||
try {
|
||
const requested = nativeStopAwaitingContainment();
|
||
const getRun = vi.fn(async () => requested);
|
||
const onStop = vi.fn(() => waitForStoppedRuns([requested.id], { initialRuns: [requested], getRun, timeoutMs: 1000 }));
|
||
render(<TaskChatComposer workMode="standard" onAdd={vi.fn()} onStop={onStop} />);
|
||
flushSync(() => stopButton()!.click());
|
||
await act(async () => { await vi.advanceTimersByTimeAsync(0); });
|
||
render(<TaskChatComposer workMode="standard" onAdd={vi.fn()} />);
|
||
await act(async () => { await vi.advanceTimersByTimeAsync(1000); });
|
||
expect(onStop).toHaveBeenCalledOnce();
|
||
expect(container.querySelector('[role="alert"]')?.textContent).toContain("stop was requested");
|
||
} finally { vi.useRealTimers(); }
|
||
});
|
||
|
||
it("switches Stop to Send with text, whitespace back to Stop, without interrupting on keyboard submit", async () => {
|
||
const onStop = vi.fn(async () => {});
|
||
const onAdd = vi.fn(async () => {});
|
||
render(<TaskChatComposer workMode="standard" onAdd={onAdd} onStop={onStop} stopScope="subtree" />);
|
||
expect(stopButton()?.title).toBe("Stop response");
|
||
pressKey("Enter", { metaKey: true });
|
||
expect(onStop).not.toHaveBeenCalled();
|
||
expect(onAdd).not.toHaveBeenCalled();
|
||
typeText("Check mobile too.");
|
||
expect(stopButton()).toBeNull();
|
||
expect(sendButton().disabled).toBe(false);
|
||
flushSync(() => sendButton().click());
|
||
await flushAsync();
|
||
expect(onAdd).toHaveBeenCalledWith("Check mobile too.", undefined, undefined, undefined, expect.any(String));
|
||
expect(onStop).not.toHaveBeenCalled();
|
||
typeText(" \n ");
|
||
expect(stopButton()?.disabled).toBe(false);
|
||
});
|
||
|
||
it("blocks duplicate stops and preserves text typed while stopping", async () => {
|
||
let resolve!: () => void;
|
||
const onStop = vi.fn(() => new Promise<void>((done) => { resolve = done; }));
|
||
render(<TaskChatComposer workMode="standard" onAdd={vi.fn()} onStop={onStop} />);
|
||
const stop = stopButton()!;
|
||
flushSync(() => { stop.click(); stop.click(); });
|
||
expect(onStop).toHaveBeenCalledTimes(1);
|
||
expect(stopButton()?.disabled).toBe(true);
|
||
expect(stopButton()?.getAttribute("aria-label")).toBe("Stopping…");
|
||
typeText("Keep this draft.");
|
||
expect(sendButton().disabled).toBe(false);
|
||
resolve();
|
||
await flushAsync();
|
||
expect(editable().textContent).toBe("Keep this draft.");
|
||
});
|
||
|
||
it("reports failure without discarding the draft and permits retry", async () => {
|
||
const onStop = vi.fn().mockRejectedValueOnce(new Error("Unable to stop. Try again.")).mockResolvedValue(undefined);
|
||
render(<TaskChatComposer workMode="standard" onAdd={vi.fn()} onStop={onStop} />);
|
||
flushSync(() => stopButton()!.click());
|
||
await flushAsync();
|
||
expect(container.querySelector('[role="alert"]')?.textContent).toBe("Unable to stop. Try again.");
|
||
flushSync(() => stopButton()!.click());
|
||
await flushAsync();
|
||
expect(onStop).toHaveBeenCalledTimes(2);
|
||
expect(container.querySelector('[role="alert"]')).toBeNull();
|
||
});
|
||
|
||
it("retains disabled Send when idle or when stop permission is absent", () => {
|
||
render(<TaskChatComposer workMode="standard" onAdd={vi.fn()} />);
|
||
expect(stopButton()).toBeNull();
|
||
expect(sendButton().disabled).toBe(true);
|
||
render(<TaskChatComposer workMode="standard" onAdd={vi.fn()} onStop={vi.fn()} disabled />);
|
||
expect(stopButton()?.disabled).toBe(true);
|
||
});
|
||
|
||
it("never turns a queued edit's save action into Stop", () => {
|
||
render(<TaskChatComposer workMode="standard" onAdd={vi.fn()} onStop={vi.fn()} queuedEdit={{ commentId: "queued", body: "" }} onSaveQueuedEdit={vi.fn()} />);
|
||
expect(stopButton()).toBeNull();
|
||
expect(sendButton().getAttribute("aria-label")).toBe("Save queued message");
|
||
});
|
||
|
||
it.each([false, true])("keeps attachments in send mode after upload (failed=%s)", async (failed) => {
|
||
let resolve!: (value: never) => void;
|
||
let reject!: (error: Error) => void;
|
||
const onAttachImage = vi.fn(() => new Promise<never>((done, fail) => { resolve = done; reject = fail; }));
|
||
render(<TaskChatComposer workMode="standard" onAdd={vi.fn()} onStop={vi.fn()} onAttachImage={onAttachImage} />);
|
||
pasteFiles([new File(["notes"], "notes.txt", { type: "text/plain" })]);
|
||
await flushAsync();
|
||
expect(stopButton()).toBeNull();
|
||
expect(sendButton().disabled).toBe(true);
|
||
if (failed) reject(new Error("Upload failed"));
|
||
else resolve({ id: "attachment", contentPath: "/notes.txt", originalFilename: "notes.txt" } as never);
|
||
await flushAsync();
|
||
expect(stopButton()).toBeNull();
|
||
expect(sendButton().disabled).toBe(failed);
|
||
});
|
||
});
|