Files
PaperClipAI/ui/src/components/InlineEditor.tsx
T
DottaandPaperclip 27d35314be feat: connect experimental Cursor Cloud to native Runner (#18069)
## Thinking Path

> - Paperclip helps people manage AI agents at work.
> - Native Runner owns execution and task authority.
> - Operators need an explicit native Cursor Cloud choice.
> - Tools/files need company, task, session and run scope.
> - This connects setup and lifecycle to Runner Core.
> - Legacy agents retain their selected runtime/history.

## Linked Issues or Issue Description

Depends on #18068. Managed-only API placement and API-owned Stop
containment are in #18310. Refs #5664, #11803, #17299, and #17471. No
duplicate native integration was found.

## What Changed

- Add explicit native setup, Test, saved settings and dispatch with
no-prompt account/catalog/callback checks.
- Scope MCP to company, agent, task, session and run through
authenticated HTTPS. Register verified artifacts/work products; preserve
unpriced accounting, completion and budgets.
- Connect Question/Plan continuation, cold handoff and admitted fresh
sessions; recheck waiting admission under the task lock.
- Present audited Stop intent while preserving physical containment
proof; bound typed Stop metadata. Preserve title edits through
preference/navigation readiness.
- Select one live/history representation per run to prevent duplicate
settled cards. Integrate upstream task/read-state/retry/schema contracts
and repair two test fixtures.

## Verification

Core #18068 merged normally as `3910352c923a`. Product head
`5a60f541c982` has passing repository CI/build/browser checks, including
required `ci / verify` and `ci / e2e`, plus a fresh exact-head Greptile
5/5 review with zero unresolved threads. Two non-required external app
checks remain pending: Paperclip Review is queued waiting for its
assigned agent; Superagent Security Scan is reviewing the diff. These
are not claimed completed. The normal merge endpoint enforces the
repository rules; no policy or status override is used. The dependent
Top PR is addressing its fresh deferred-Stop review finding.

Product `5a60f541c982` passed 270 UI and 20 selected
Cloud/native/disk-full tests, UI/server typechecks, tokens and maps.
Top’s clean normal merge passed tokens/maps/diff checks; its matrix is
pending. Earlier receipts retain Core’s 47 Rust, 4 compiled-native
retirement and 19 settlement controls, normal Runner build, and runtime
9af build/recursive typecheck. Reproduced loading/shutdown CI fixture
failures passed 7/7 browser and 121/121 unit tests, including a
broken-unsubscribe negative control. No timeout/oracle was relaxed.

The actual-parent restack adopts 75 mainline paths, including
schema/permission and generic runtime changes, beyond the prior two
fixture repairs and client projection fix. The full difference from
hosted `9af1a5de42a2` is therefore larger than four files; backend
source also differs. The merged config-read checks match Core391, and
the Cursor placement/runtime/relay/selection modules match frozen9af;
selected affected regressions pass. Paid proof keeps its actual 9af
source/image identity. The separately tested live/history card fix is
not claimed deployed on that host.

On 9af, original saved settings survived reopening and fresh no-prompt
Test authenticated catalog/model/binding; no new Save is claimed. Fresh
Linux admission passed. With `claude-sonnet-4-5`, Artifact downloaded
exact 27 bytes and matched 121 canonical identities in complete
S3-served history. First Stop’s strict quiet FAILED on a 10.373-second
gap despite independent cancellation/no late artifact. One targeted
unchanged-sampler retry retained all 24 samples: 35.076 seconds quiet /
maximum gap 4.584 seconds, 67 ordered canonical identities, and separate
CANCELLED/artifact-absent status after the original 180-second deadline.
The pre-reload duplicate settled card is disclosed. Exact-ID cleanup for
the three new provider agents is awaiting authorization, so full grades
and the fresh Artifact’s post-cleanup download remain blocked. A
historical deleted-provider artifact was newly downloaded on 9af;
original F226 Question/Plan/reconnect and cleanup proof keep their
identities.

Retained failures: stale fixture 132/133; E8 48/135 with 87 reset-hook
failures; Mac 17 SQL failures/skips; earlier
title/startup/custody/Stop/deletion failures with unknown causes/bounded
recoveries; `dea023` Stop’s warning/50 duplicate identities; pre-repair
ACK and original Core CI failures. WSP’s 251-assertion, 7/8-suite
attempt failed physical PostgreSQL teardown; the unchanged wrapper rerun
passed 128. Retry alone establishes no cause or full local-suite pass.
All paid attempts remain recorded; vendor dollar cost is UNKNOWN.

## Risks

Experimental: Cursor independently acknowledges neither the effective
model nor instruction digest before the first prompt. Explicit values
are submitted and checked through behavior; unpriced provider dollar
cost stays UNKNOWN.

Callbacks need authenticated reachable HTTPS. Scope, revocation,
budgets, completion and cleanup remain authoritative. Operator Stop
intent is separate from physical containment. Saved legacy agents retain
their selected runtime. Prior shared title-save/deletion failures remain
disclosed.

## Model Used

OpenAI Codex, GPT-6 family, assisted with reasoning, repository tools,
code execution, browser verification, and delegated code review. The
serving model’s exact API ID and context window are not exposed. No
value is inferred from the model catalog.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used and the limits of available model
metadata
- [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 linked public issues or described the issue in this PR
- [x] I have not referenced internal or instance-local Paperclip issues
or links
- [x] My branch describes the change and contains no internal ticket ID
- [x] I have run the scoped local tests reported above; pending gates
are stated separately
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation
- [x] I have considered and documented the risks
- [x] All required CI gates pass on the current head
- [x] Fresh Greptile is 5/5 with no unresolved findings on the current
head
- [x] I will address all reviewer comments before requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-11-03 09:01:39 -06:00

528 lines
19 KiB
TypeScript

import { useState, useRef, useEffect, useCallback, useId } from "react";
import { cn } from "../lib/utils";
import { MarkdownBody, type MarkdownExternalReferenceMap } from "./MarkdownBody";
import { MarkdownEditor, type MarkdownEditorRef, type MentionOption } from "./MarkdownEditor";
import { useDurableAutosave } from "../hooks/useDurableAutosave";
import { useDraftOwner } from "../hooks/useDraftOwner";
import { loadStructuredDraft, saveStructuredDraft } from "../lib/composer-draft";
type StoredInlineDraft = { version: 1; draft: string; base: string };
import { FoldCurtain } from "./FoldCurtain";
interface InlineEditorProps {
value: string;
onSave: (value: string) => void | Promise<unknown>;
as?: "h1" | "h2" | "p" | "span";
className?: string;
placeholder?: string;
multiline?: boolean;
imageUploadHandler?: (file: File) => Promise<string>;
/** Called when a non-image file is dropped onto the editor. */
onDropFile?: (file: File) => Promise<void>;
mentions?: MentionOption[];
nullable?: boolean;
/** When true, long display-mode markdown is clipped with a fade curtain that expands on click. */
foldable?: boolean;
/**
* Optional host-resolved external object metadata. Forwarded to the read-mode
* `MarkdownBody` so resolved URLs render with the inline status icon prefix.
*/
externalReferences?: MarkdownExternalReferenceMap;
/**
* Mount the multiline editor already in edit mode, focused — for hosts whose
* own affordance opens the editor (the description bubble's pencil, PAP-375).
*/
defaultEditing?: boolean;
/** Notified when the editor swaps between display and edit mode. */
onEditingChange?: (editing: boolean) => void;
/**
* Keep unsaved edits in browser storage under this key, so a reload or an
* outage does not lose them. A stored edit is restored and saved on mount.
*/
draftKey?: string;
}
/** Shared padding so display and edit modes occupy the exact same box. */
const pad = "px-1 -mx-1";
const markdownPad = "px-1";
const AUTOSAVE_DEBOUNCE_MS = 900;
export function queueContainedBlurCommit(container: HTMLDivElement, onCommit: () => void) {
let frameId = requestAnimationFrame(() => {
frameId = requestAnimationFrame(() => {
frameId = 0;
const active = document.activeElement;
if (active instanceof Node && container.contains(active)) return;
onCommit();
});
});
return () => {
if (frameId === 0) return;
cancelAnimationFrame(frameId);
frameId = 0;
};
}
export function InlineEditor(props: InlineEditorProps) {
const draftOwner = useDraftOwner();
const [scope, setScope] = useState({ owner: draftOwner, generation: 0 });
const generation = scope.generation + (scope.owner !== undefined && scope.owner !== draftOwner ? 1 : 0);
if (scope.owner !== draftOwner) setScope({ owner: draftOwner, generation });
return <OwnedInlineEditor key={generation} {...props} draftOwner={draftOwner} />;
}
function OwnedInlineEditor({
value,
onSave,
as: Tag = "span",
className,
placeholder = "Click to edit...",
multiline = false,
nullable = false,
imageUploadHandler,
onDropFile,
mentions,
foldable = false,
externalReferences,
defaultEditing = false,
onEditingChange,
draftKey,
draftOwner,
}: InlineEditorProps & { draftOwner: string | undefined }) {
const [editing, setEditing] = useState(false);
const editingChangeCallback = useRef(onEditingChange);
editingChangeCallback.current = onEditingChange;
useEffect(() => {
if (multiline || !editing) return;
const notify = editingChangeCallback.current;
notify?.(true);
// Report only an edit that actually opened. This also retires the old
// account's edit on unmount, without a late save notifying its new owner.
return () => notify?.(false);
}, [editing, multiline]);
const [multilineEditing, setMultilineEditing] = useState(multiline && defaultEditing);
const [multilineFocused, setMultilineFocused] = useState(false);
const [draft, setDraft] = useState(value);
const unownedDraft = useRef<StoredInlineDraft | null>(null);
const lastPropValueRef = useRef(value);
const inputRef = useRef<HTMLTextAreaElement>(null);
const markdownRef = useRef<MarkdownEditorRef>(null);
const autosaveDebounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const blurCommitFrameRef = useRef<(() => void) | null>(null);
const pendingFocusFrameRef = useRef<number | null>(null);
const justEnteredEditRef = useRef(multiline && defaultEditing);
const hasBeenFocusedRef = useRef(false);
const autosave = useDurableAutosave<string>({
sourceId: `inline-editor:${useId()}`,
targetKey: draftKey ?? undefined,
save: async (next) => {
await onSave(next);
},
});
const { markDirty, reset, run: runAutosave } = autosave;
const autosaveState = autosave.status;
const autosaveStateRef = useRef(autosaveState);
autosaveStateRef.current = autosaveState;
// Unsaved edits are stored with the value they were based on, so a restored
// edit never silently overwrites a newer server value, and per signed-in
// account, so another account in this browser never sees or saves them.
const storageKey = draftKey && draftOwner !== undefined ? `paperclip:inline-draft:v2:${draftOwner}:${draftKey}` : null;
const clearStoredDraft = useCallback(() => {
if (!storageKey) return;
try {
localStorage.removeItem(storageKey);
} catch {
// Unavailable storage holds nothing to clear.
}
}, [storageKey]);
// Any path that lands the edit (blur, autosave, a resend after an outage)
// updates `value`; the stored copy is then no longer needed.
useEffect(() => {
if (!storageKey) return;
const stored = loadStructuredDraft<StoredInlineDraft | null>(storageKey, null);
if (stored && typeof stored.draft === "string" && stored.draft.trim() === value.trim()) clearStoredDraft();
}, [clearStoredDraft, storageKey, value]);
const changeDraft = useCallback((next: string) => {
setDraft(next);
if (draftOwner === undefined) unownedDraft.current = { version: 1, draft: next, base: value };
if (!storageKey) return;
if (next.trim() === value.trim()) clearStoredDraft();
else saveStructuredDraft(storageKey, { version: 1, draft: next, base: value } satisfies StoredInlineDraft);
}, [clearStoredDraft, draftOwner, storageKey, value]);
useEffect(() => {
const previousValue = lastPropValueRef.current;
lastPropValueRef.current = value;
setDraft((currentDraft) => {
if (multiline && multilineFocused && currentDraft !== previousValue) {
return currentDraft;
}
return value;
});
}, [value, multiline, multilineFocused]);
// An edit that never saved (reload, crash, outage) comes back. It saves on
// its own only when the server value is still the one it was based on;
// otherwise it waits in the editor for the user.
const restoredDraftRef = useRef<string | null>(null);
useEffect(() => {
if (!storageKey || restoredDraftRef.current === storageKey) return;
restoredDraftRef.current = storageKey;
if (unownedDraft.current) {
if (draft.trim() !== value.trim()) saveStructuredDraft(storageKey, { ...unownedDraft.current, draft });
else clearStoredDraft();
unownedDraft.current = null;
return;
}
const stored = loadStructuredDraft<StoredInlineDraft | null>(storageKey, null);
if (!stored || stored.version !== 1 || typeof stored.draft !== "string" || typeof stored.base !== "string") return;
if (stored.draft.trim() === value.trim()) {
clearStoredDraft();
return;
}
setDraft(stored.draft);
if (multiline) {
setMultilineEditing(true);
onEditingChange?.(true);
} else {
setEditing(true);
}
if (stored.base === value) void runAutosave(stored.draft.trim());
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [storageKey]);
useEffect(() => {
return () => {
if (autosaveDebounceRef.current) {
clearTimeout(autosaveDebounceRef.current);
}
if (blurCommitFrameRef.current !== null) {
blurCommitFrameRef.current();
blurCommitFrameRef.current = null;
}
if (pendingFocusFrameRef.current !== null) {
cancelAnimationFrame(pendingFocusFrameRef.current);
pendingFocusFrameRef.current = null;
}
};
}, []);
const autoSize = useCallback((el: HTMLTextAreaElement | null) => {
if (!el) return;
el.style.height = "auto";
el.style.height = `${el.scrollHeight}px`;
}, []);
useEffect(() => {
if (editing && inputRef.current) {
inputRef.current.focus();
inputRef.current.select();
if (inputRef.current instanceof HTMLTextAreaElement) {
autoSize(inputRef.current);
}
}
}, [editing, autoSize]);
useEffect(() => {
if (!multilineEditing || !multiline) return;
if (!justEnteredEditRef.current) return;
justEnteredEditRef.current = false;
if (pendingFocusFrameRef.current !== null) {
cancelAnimationFrame(pendingFocusFrameRef.current);
}
pendingFocusFrameRef.current = requestAnimationFrame(() => {
pendingFocusFrameRef.current = null;
markdownRef.current?.focus();
});
return () => {
if (pendingFocusFrameRef.current !== null) {
cancelAnimationFrame(pendingFocusFrameRef.current);
pendingFocusFrameRef.current = null;
}
};
}, [multilineEditing, multiline]);
// Once the editor has been focused at least once, it's blurred, and any
// autosave has settled, swap back to the MarkdownBody preview so inline
// issue refs render with status + quicklook.
useEffect(() => {
if (multilineFocused) {
hasBeenFocusedRef.current = true;
return;
}
if (!multiline || !multilineEditing) return;
if (!hasBeenFocusedRef.current) return;
// Waiting or failed saves keep the editor open, so the text stays visible.
if (autosaveState !== "idle") return;
hasBeenFocusedRef.current = false;
setMultilineEditing(false);
onEditingChange?.(false);
}, [multiline, multilineEditing, multilineFocused, autosaveState, onEditingChange]);
// A single-line edit that waited for the connection closes once it saves.
useEffect(() => {
if (multiline || !editing || autosaveState !== "saved") return;
if (document.activeElement === inputRef.current) return;
setEditing(false);
}, [autosaveState, editing, multiline]);
/** Save the draft if it changed. Never rejects; a failed save keeps the text. */
const commit = useCallback(async (nextValue = draft) => {
const valueToSave = nextValue.trim();
const valueChanged = valueToSave !== value;
const shouldSave = nullable
? valueChanged
: Boolean(valueToSave && valueChanged);
if (!shouldSave) {
setDraft(value);
if (draftKey) clearStoredDraft();
if (!multiline) setEditing(false);
return;
}
const result = await runAutosave(valueToSave);
// A single-line edit stays open until it is saved, so its text is not lost.
if (!multiline && result.kind === "saved") setEditing(false);
}, [clearStoredDraft, draft, draftKey, multiline, nullable, runAutosave, value]);
/** Multiline blur/submit: show autosave indicator when persisting */
const finalizeMultilineBlurOrSubmit = useCallback(() => {
const trimmed = draft.trim();
if (trimmed === value || (!trimmed && !nullable)) {
reset();
}
void commit();
}, [commit, draft, nullable, reset, value]);
const cancelPendingBlurCommit = useCallback(() => {
if (blurCommitFrameRef.current === null) return;
blurCommitFrameRef.current();
blurCommitFrameRef.current = null;
}, []);
const scheduleBlurCommit = useCallback((container: HTMLDivElement) => {
cancelPendingBlurCommit();
blurCommitFrameRef.current = queueContainedBlurCommit(container, () => {
blurCommitFrameRef.current = null;
if (autosaveDebounceRef.current) {
clearTimeout(autosaveDebounceRef.current);
}
setMultilineFocused(false);
finalizeMultilineBlurOrSubmit();
});
}, [cancelPendingBlurCommit, finalizeMultilineBlurOrSubmit]);
function handleKeyDown(e: React.KeyboardEvent) {
if (e.key === "Enter" && !multiline) {
e.preventDefault();
void commit();
}
if (e.key === "Escape") {
if (autosaveDebounceRef.current) {
clearTimeout(autosaveDebounceRef.current);
}
reset();
setDraft(value);
if (draftKey) clearStoredDraft();
if (multiline) {
setMultilineFocused(false);
setMultilineEditing(false);
onEditingChange?.(false);
hasBeenFocusedRef.current = false;
if (document.activeElement instanceof HTMLElement) {
document.activeElement.blur();
}
} else {
setEditing(false);
}
}
}
useEffect(() => {
if (!multiline) return;
if (!multilineFocused) return;
const trimmed = draft.trim();
// Nullable: empty draft can still be a real edit (clearing); only skip debounce when unchanged or empty is invalid.
if (trimmed === value || (!trimmed && !nullable)) {
if (autosaveStateRef.current !== "saved") {
reset();
}
return;
}
markDirty();
if (autosaveDebounceRef.current) {
clearTimeout(autosaveDebounceRef.current);
}
autosaveDebounceRef.current = setTimeout(() => {
void commit(trimmed);
}, AUTOSAVE_DEBOUNCE_MS);
return () => {
if (autosaveDebounceRef.current) {
clearTimeout(autosaveDebounceRef.current);
}
};
}, [commit, draft, markDirty, multiline, multilineFocused, nullable, reset, value]);
if (multiline) {
const previewValue = autosaveState === "saved" || autosaveState === "idle" ? draft : value;
const hasValue = Boolean(previewValue.trim());
const showEditor = multilineEditing || multilineFocused || !hasValue;
if (!showEditor) {
const enterEditMode = () => {
if (multilineEditing) return;
justEnteredEditRef.current = true;
setMultilineEditing(true);
onEditingChange?.(true);
};
return (
<div
className={cn(markdownPad, "rounded transition-colors hover:bg-accent/20")}
onClick={(event) => {
if (event.defaultPrevented) return;
const target = event.target as HTMLElement | null;
if (target && target.closest("a,button,[data-mention-kind],[data-radix-popper-content-wrapper]")) {
return;
}
enterEditMode();
}}
onDragEnter={() => enterEditMode()}
onKeyDown={(event) => {
if (event.key !== "Enter" && event.key !== " ") return;
event.preventDefault();
enterEditMode();
}}
role="textbox"
aria-multiline="true"
aria-label={placeholder}
tabIndex={0}
>
{foldable ? (
<FoldCurtain>
<MarkdownBody
className={cn("paperclip-edit-in-place-content", className)}
externalReferences={externalReferences}
>
{previewValue}
</MarkdownBody>
</FoldCurtain>
) : (
<MarkdownBody
className={cn("paperclip-edit-in-place-content", className)}
externalReferences={externalReferences}
>
{previewValue}
</MarkdownBody>
)}
</div>
);
}
return (
<div
className={cn(
markdownPad,
"rounded transition-colors",
multilineFocused ? "bg-transparent" : "hover:bg-accent/20",
)}
onFocusCapture={(event) => {
// Ignore focus events where the active element isn't actually inside
// the wrapper (React 19 can emit a synthetic focus after a blur).
const active = document.activeElement;
if (!(active instanceof Node) || !event.currentTarget.contains(active)) return;
cancelPendingBlurCommit();
setMultilineFocused(true);
}}
onBlurCapture={(event) => {
if (event.currentTarget.contains(event.relatedTarget as Node | null)) return;
if (pendingFocusFrameRef.current !== null) {
cancelAnimationFrame(pendingFocusFrameRef.current);
pendingFocusFrameRef.current = null;
}
scheduleBlurCommit(event.currentTarget);
}}
onKeyDown={handleKeyDown}
>
<MarkdownEditor
ref={markdownRef}
value={draft}
onChange={changeDraft}
placeholder={placeholder}
bordered={false}
className="bg-transparent"
contentClassName={cn("paperclip-edit-in-place-content", className)}
imageUploadHandler={imageUploadHandler}
onDropFile={onDropFile}
mentions={mentions}
onSubmit={() => {
finalizeMultilineBlurOrSubmit();
}}
/>
<div className="flex min-h-4 items-center justify-end pr-1">
<span
className={cn(
"text-(length:--text-micro) transition-opacity duration-150",
autosaveState === "error" ? "text-destructive" : "text-muted-foreground",
autosaveState === "idle" ? "opacity-0" : "opacity-100",
)}
role={autosaveState === "error" ? "alert" : "status"}
>
{autosave.label ?? "Idle"}
</span>
{autosaveState === "stalled" ? <button type="button" className="ml-2 text-xs text-foreground underline" onClick={autosave.resendNow}>Retry saving</button> : null}
</div>
</div>
);
}
if (editing) {
return (
<textarea
ref={inputRef}
value={draft}
rows={1}
onChange={(e) => {
changeDraft(e.target.value);
autoSize(e.target);
}}
onBlur={() => {
void commit();
}}
onKeyDown={handleKeyDown}
className={cn(
"w-full bg-transparent rounded outline-none resize-none overflow-hidden",
pad,
className
)}
/>
);
}
// Use div instead of Tag when rendering markdown to avoid invalid nesting
// (e.g. <p> cannot contain the <div>/<p> elements that markdown produces)
const DisplayTag = value && multiline ? "div" : Tag;
return (
<>
<DisplayTag
className={cn(
"cursor-pointer rounded hover:bg-accent/50 transition-colors overflow-hidden",
pad,
!value && "text-muted-foreground italic",
className,
)}
onClick={() => setEditing(true)}
>
{value || placeholder}
</DisplayTag>
{autosaveState === "stalled" ? <button type="button" className="text-xs text-foreground underline" onClick={autosave.resendNow}>Retry saving</button> : null}
</>
);
}