Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
import { formatSessionLink, serializeInlineComposerFileReferences, type MessageAttachment } from "@pi-desktop/shared";
import { useComposerInputHistory } from "../../apps/desktop/src/features/chat/composer/hooks/useComposerInputHistory";
import type { AppState } from "../../apps/desktop/src/stores/app-state";
import { createQueueSlice } from "../../apps/desktop/src/stores/slices/queue-slice";
import type { SessionRuntime } from "../../apps/desktop/src/stores/runtime/session-runtime";
import { useComposerSubmit } from "../../apps/desktop/src/features/chat/composer/hooks/useComposerSubmit";
import { verifyComposerSubmission } from "./composer-submission";
import "./composer-draft-race";
import { createRoot } from "react-dom/client";
import { flushSync } from "react-dom";
import { createInstance } from "i18next";
import { I18nextProvider } from "react-i18next";
import { isBlockingOverlayActive } from "../../apps/desktop/src/lib/blocking-overlay";
import type { TFunction } from "i18next";
import { en } from "@pi-desktop/i18n";
import {
ComposerInput,
type ComposerInputProps,
} from "../../apps/desktop/src/features/chat/composer/ComposerInput";
import { useComposerAttachments } from "../../apps/desktop/src/features/chat/composer/hooks/useComposerAttachments";
import {
useComposerDraft,
type ComposerDraftController,
} from "../../apps/desktop/src/features/chat/composer/hooks/useComposerDraft";
import {
createFileReference,
editorSelectionRange,
readEditorValue,
setEditorCaret,
} from "../../apps/desktop/src/features/chat/composer/editor";
import { api } from "../../apps/desktop/src/lib/api";
import { FilesTab } from "../../apps/desktop/src/components/workpanel/FilesTab";
import { FileRefChip, MessageAttachmentImage } from "../../apps/desktop/src/features/chat/transcript/shared";
import { MessageRow } from "../../apps/desktop/src/features/chat/transcript/MessageRow";
import { SlotSessionProvider } from "../../apps/desktop/src/plugins/renderer-slots/use-slots";
import { useOpenChatFileRef } from "../../apps/desktop/src/hooks/use-preview-target";
import {
readComposerDraft,
resetComposerDraftCache,
sameDraftFileReference,
} from "../../apps/desktop/src/lib/composer-draft-cache";
import type { ComposerDraftSnapshot } from "../../apps/desktop/src/lib/composer-smart-stop";
import { useAppStore } from "../../apps/desktop/src/stores/app-store";
import { loadComposerInputHistory } from "../../apps/desktop/src/lib/composer-input-history";
import { promptAttachmentsFromDraft } from "../../apps/desktop/src/stores/helpers/store-helpers";
declare global {
var composerPreviewPointer: (input: { type: "mousePressed" | "mouseMoved" | "mouseReleased"; x: number; y: number }) => Promise<void>;
var composerPreviewPressKey: (key: string) => Promise<void>;
var composerPreviewCapture: (() => Promise<void>) | undefined;
var composerPasteProbe: (screenshotOnly?: boolean, fileReferencesOnly?: boolean, referenceProject?: string, referenceHistoryOnly?: boolean) => Promise<unknown>;
var composerHistoryProbe: (phase: "prepare" | "verify") => Promise<unknown>;
}
const assert = (value: unknown, message: string) => {
if (!value) throw new Error(message);
};
const sessions = [{ id: "paste-a" }, { id: "paste-b" }, { id: "history-created-session" }];
const noop = () => {};
let controller: ComposerDraftController;
let pastePending: Promise<unknown> | undefined;
let submitted = 0;
let rejectSubmission: () => Promise<void>;
let historySendPrompt: AppState["sendPrompt"] = async () => false;
let latestSubmission: Promise<void> = Promise.resolve();
function Fixture({ sessionId, t, workspacePath }: { sessionId: string; t: TFunction; workspacePath: string }) {
const draft = useComposerDraft({
variant: "docked",
activeSessionId: sessionId || null,
workspacePath,
sessions,
composerPrefill: null,
clearComposerPrefill: noop,
t,
invalidateComposerTransforms: noop,
inputBlocked: false,
});
controller = draft;
const inputHistory = useComposerInputHistory({
draftKey: draft.draftKey,
referenceSessionId: sessionId,
draft,
});
const submitController = useComposerSubmit({
value: draft.value, draftKey: draft.draftKey, activeSessionId: sessionId || null,
thinkingLevel: "off", modelReady: true, sendBlocked: false, pasting: false,
invalidateComposerTransforms: noop,
activeFileReferences: draft.activeFileReferences, t, draft,
recordHistory: inputHistory.record,
sendPrompt: (...args) => historySendPrompt(...args),
steerPrompt: async () => false, showToast: noop,
});
rejectSubmission = submitController.submit;
const submitFromComposer = (steering?: boolean) => {
inputHistory.exitBrowsing();
submitted++;
return submitController.submit(steering);
};
const attachments = useComposerAttachments({
inputBlocked: false,
activeSessionId: sessionId || null,
draftKey: draft.draftKey,
largePasteThreshold: 600,
t,
draft,
});
return (
<div className="composer-stack">
<div className="composer-shell">
<ComposerInput
imagePreview={draft.imagePreview}
directoryReferences={draft.activeFileReferences.filter((reference) => reference.kind === "directory")}
onRemoveDirectory={draft.removeDirectoryReference}
inputRef={draft.ref}
value={draft.value}
placeholderText=""
placeholderKey="fixture"
inputBlocked={attachments.pasting}
pasting={attachments.pasting}
enterToSend={true}
runActive={false}
composerAc={
{ open: false, close: noop } as ComposerInputProps["composerAc"]
}
onPaste={(event) => {
pastePending = Promise.resolve(attachments.pasteClipboardFiles(event));
}}
onAcceptCompletion={noop}
onSubmit={(steering) => { latestSubmission = submitFromComposer(steering); }}
onHistoryNavigate={inputHistory.navigate}
onInsertNewline={draft.insertNewlineInEditor}
onInput={(source, caret, composing) => { inputHistory.exitBrowsing(); draft.handleInput(source, caret, composing); }}
onCompositionStart={noop}
onCompositionEnd={noop}
onSettledInput={() => draft.setComposing(false)}
onFocus={noop}
onBlur={noop}
/>
</div>
</div>
);
}
function Mp4AttachmentChips({ scratchPath }: { scratchPath: string }) {
const openFile = useOpenChatFileRef();
return (
<div className="mp4-attachment-chips">
{[
{ name: "a.mp4", path: `attachments/${"a".repeat(64)}` },
{ name: "b.mp4", path: `attachments/${"b".repeat(64)}` },
{ name: "scratch.mp4", path: scratchPath },
].map((video) => (
<FileRefChip
key={video.name}
name={video.name}
path={video.path}
mimeType="video/mp4"
onOpen={openFile}
/>
))}
</div>
);
}
globalThis.composerPasteProbe = async (screenshotOnly = false, fileReferencesOnly = false, referenceProject = "", referenceHistoryOnly = false) => {
const i18n = createInstance();
await i18n.init({
lng: "en",
resources: { en: { translation: en } },
interpolation: { escapeValue: false },
});
const host = document.createElement("div");
document.body.append(host);
const errors: unknown[] = [];
const root = createRoot(host, {
onUncaughtError: (error) => errors.push(error),
});
let key = 0;
const render = (sessionId = "paste-a", workspacePath = "") => {
useAppStore.setState({ activeSessionId: sessionId });
flushSync(() =>
root.render(<I18nextProvider i18n={i18n}><Fixture key={key} sessionId={sessionId} t={i18n.t} workspacePath={workspacePath} /></I18nextProvider>),
);
assert(
errors.length === 0,
`React failed: ${errors.map(String).join("; ")}`,
);
};
const reset = async (
source = "prefix REPLACE suffix",
start = 7,
end = 14,
) => {
key++;
resetComposerDraftCache();
useAppStore.setState({ workPanelOpen: false, workspace: null });
render();
const editor = controller.ref.current!;
flushSync(() => controller.applyEditorDraft(source, [], start));
await new Promise(requestAnimationFrame);
editor.focus();
const range = document.createRange();
range.setStart(editor.firstChild!, start);
range.setEnd(editor.firstChild!, end);
const selection = window.getSelection()!;
selection.removeAllRanges();
selection.addRange(range);
return editor;
};
const dispatchPaste = async (
editor: HTMLDivElement,
text: string,
files: File[],
fileLines?: { workspace: string; path: string; start: number; end: number },
) => {
const data = new DataTransfer();
if (text) {
data.setData("text/plain", text);
data.setData("text/html", `<b>${text}</b>`);
}
for (const file of files) data.items.add(file);
if (fileLines) data.setData("application/x-pi-desktop-file-lines", JSON.stringify(fileLines));
const event = new ClipboardEvent("paste", {
clipboardData: data,
bubbles: true,
cancelable: true,
});
flushSync(() => editor.dispatchEvent(event));
await pastePending;
await new Promise((resolve) => setTimeout(resolve, 0));
assert(event.defaultPrevented, "paste was not handled");
assert(
errors.length === 0,
`React failed: ${errors.map(String).join("; ")}`,
);
return editor;
};
const paste = async (text: string, files: File[], empty = false) =>
dispatchPaste(await (empty ? reset("", 0, 0) : reset()), text, files);
const select = (editor: HTMLElement, start: number, end: number) => {
setEditorCaret(editor, start);
const selection = window.getSelection()!;
const range = selection.getRangeAt(0).cloneRange();
setEditorCaret(editor, end);
const last = selection.getRangeAt(0);
range.setEnd(last.startContainer, last.startOffset);
selection.removeAllRanges();
selection.addRange(range);
};
try {
const lineEditor = await reset();
const workspace = "/fixture/project";
useAppStore.setState({ activeProjectPath: workspace });
await dispatchPaste(lineEditor, "saved line selection", [], { workspace, path: workspace + "/gpt.py", start: 85, end: 86 });
const lineChip = lineEditor.querySelector(".composer-chip");
assert(lineChip?.textContent?.includes("gpt.py (85:86)"), "file range paste did not create a line chip");
assert(!lineEditor.textContent?.includes("saved line selection"), "file range paste inserted source text");
assert(controller.snapshotReferences("paste-a")[0]?.lineRange?.start === 85, "file range did not reach the draft");
for (let start = 1; start <= 3; start++) {
await dispatchPaste(lineEditor, "saved line selection", [], { workspace, path: workspace + "/gpt.py", start, end: start });
}
assert(controller.snapshotReferences("paste-a").length === 4, "file range limit fixture did not fill");
await dispatchPaste(lineEditor, "limit fallback text", [], { workspace, path: workspace + "/gpt.py", start: 4, end: 4 });
assert(lineEditor.textContent?.includes("limit fallback text"), "file range limit swallowed the pasted plain text");
assert(controller.snapshotReferences("paste-a").length === 4, "file range limit added an extra chip");
const otherProjectEditor = await reset();
await dispatchPaste(otherProjectEditor, "foreign selection", [], {
workspace: "/fixture/other", path: "/fixture/other/gpt.py", start: 85, end: 86,
});
assert(!otherProjectEditor.querySelector(".composer-chip"), "another project's paste created a file line chip");
assert(otherProjectEditor.textContent?.includes("foreign selection"), "another project's paste lost the plain text");
useAppStore.setState({ activeProjectPath: null });
useAppStore.setState({ sessions: [{
id: "paste-a", title: "Folder paste fixture", source: "desktop", mode: "agent",
permissionMode: "inherit", thinkingLevel: "off", messageCount: 0,
createdAt: "2026-01-01T00:00:00Z", updatedAt: "2026-01-01T00:00:00Z",
}] });
if (fileReferencesOnly || referenceHistoryOnly) {
const prefix = referenceHistoryOnly ? "" : "Inspect ";
await reset(prefix, prefix.length, prefix.length);
useAppStore.setState({ workspace: { path: referenceProject, name: "Reference fixture" } as AppState["workspace"] });
render("paste-a", referenceProject);
if (referenceHistoryOnly) {
const history = loadComposerInputHistory("paste-a")[0];
assert(history?.fileReferences.length === 3, "process restart lost reference history");
flushSync(() => controller.restoreDraftForKey("paste-a", history));
await new Promise(requestAnimationFrame);
} else {
const files = Array.from((document.getElementById("native-files") as HTMLInputElement).files!);
assert(files.length === 3 && files.every(file => api.getDroppedFilePath(file)), "native reference File paths missing");
for (const file of files) file.arrayBuffer = () => { throw new Error("disk file bytes were read by the renderer"); };
await dispatchPaste(controller.ref.current!, "", files);
}
const snapshot = controller.draftSnapshot(readEditorValue(controller.ref.current!));
const matchesSnapshot = (candidate: ComposerDraftSnapshot | undefined) => candidate !== undefined &&
candidate.text === snapshot.text && candidate.fileReferences.length === snapshot.fileReferences.length &&
candidate.fileReferences.every((file, index) => sameDraftFileReference(file, snapshot.fileReferences[index]));
assert(snapshot.fileReferences.length === 3, "native file-only selection did not attach every file");
const large = snapshot.fileReferences.find(file => file.name === "large reference.bin")!;
assert(large?.size === 67108865 && large.localReference && !large.path.includes("/scratch/"), "large file lost its original path, size or selection id");
assert(controller.ref.current!.textContent?.includes("64 MiB"), "file card did not display its size");
const image = snapshot.fileReferences.find(file => file.name === "native-image.png");
assert(image?.kind === "image" && !image.localReference && /[\\/]scratch[\\/]/.test(image.path), "native image file was not imported as an image attachment");
flushSync(() => root.render(null));
render("paste-a", referenceProject);
await new Promise(requestAnimationFrame);
assert(matchesSnapshot(controller.draftSnapshot(readEditorValue(controller.ref.current!))), "remount lost reference metadata");
const previousSend = historySendPrompt;
try {
historySendPrompt = async (content, draft) => {
const response = await api.prompt({ sessionId: "paste-a", content,
attachments: promptAttachmentsFromDraft(draft?.fileReferences ?? []) });
return response.accepted;
};
await rejectSubmission();
const history = loadComposerInputHistory("paste-a")[0];
assert(matchesSnapshot(history), "accepted history changed live reference metadata");
flushSync(() => controller.restoreDraftForKey("paste-a", history));
await new Promise(requestAnimationFrame);
assert(matchesSnapshot(controller.draftSnapshot(readEditorValue(controller.ref.current!))), "history recall lost removable references");
flushSync(() => controller.ref.current!.querySelector<HTMLButtonElement>(".composer-chip-remove")!.click());
assert(controller.fileReferences.length === 2, "restored reference was not removable");
} finally { historySendPrompt = previousSend; }
return { ok: true, largeFileReference: true, noRendererByteRead: true, metadataHistory: true,
refreshedSize: true, processRestartMetadata: referenceHistoryOnly };
}
const directoryEditor = await dispatchPaste(await reset("before after", 0, 6), "", []);
const directoryChip = directoryEditor.closest(".composer-input-wrap")?.querySelector(".directory-reference-card");
assert(directoryChip?.textContent?.includes("copied folder"), "native folder metadata did not render a chip");
assert(directoryChip!.getBoundingClientRect().bottom <= directoryEditor.getBoundingClientRect().top,
"folder card must be above the editable text");
assert(directoryChip!.getBoundingClientRect().width < 200, "short folder name leaves too much blank card width");
assert(directoryEditor.getBoundingClientRect().height < 40, "a short prompt leaves excess blank space below the card");
assert(readEditorValue(directoryEditor) === "before after", "folder paste changed the editable text");
assert(controller.fileReferences[0]?.kind === "directory", "folder chip must own a directory reference");
const content = serializeInlineComposerFileReferences(readEditorValue(directoryEditor), controller.activeFileReferences);
assert(content.includes("<dir>") && content.includes("Inspect their structure"), "model prompt lost directory context");
flushSync(() => directoryChip?.querySelector<HTMLButtonElement>(".directory-reference-remove")?.click());
assert(controller.fileReferences.length === 0, "folder chip could not be removed");
flushSync(() => root.render(
<I18nextProvider i18n={i18n}>
<SlotSessionProvider sessionId="paste-a">
<MessageRow message={{ id: "directory-message", role: "user", content, createdAt: "2026-01-01T00:00:00Z" }} isRunning={false} />
</SlotSessionProvider>
</I18nextProvider>,
));
assert(host.querySelector(".message-user-text")?.textContent === "before after", "user bubble leaked the model prompt");
const sentFolder = host.querySelector<HTMLButtonElement>(".message-bubble .directory-reference-main");
assert(sentFolder?.textContent?.includes("copied folder"), "user bubble lost the clickable folder");
sentFolder!.click();
// Settings replaces ChatSurface, then remounts the composer in the same
// workspace. Exercise the real draft hook and DOM across that lifecycle.
render("paste-a", "/project-a");
const referenceDraft = "Check \uE001 and \uE002";
const references = [
createFileReference("src/main.ts", "main.ts", "paste-a", { token: "\uE001" }),
createFileReference("/scratch/paste-a/notes.txt", "notes.txt", "paste-a", { token: "\uE002" }),
];
flushSync(() => controller.applyEditorDraft(referenceDraft, references, referenceDraft.length));
await new Promise(requestAnimationFrame);
flushSync(() => root.render(null));
render("paste-a", "/project-a");
await new Promise(requestAnimationFrame);
assert(readEditorValue(controller.ref.current!) === referenceDraft,
"Settings round-trip lost a workspace file reference from the draft");
assert(controller.fileReferences.length === 2 && controller.ref.current!.textContent!.includes("main.ts"),
"Settings round-trip must restore both workspace and scratch chips");
flushSync(() => root.render(null));
render("paste-a", "/project-b");
await new Promise(requestAnimationFrame);
assert(readEditorValue(controller.ref.current!) === "Check and \uE002",
"changing workspace while the composer is unmounted must remove the previous workspace's chip");
assert(controller.fileReferences.length === 1 && controller.fileReferences[0].path === references[1].path,
"changing workspace must preserve scratch references");
// Keep the source attachment snapshot when a paste finishes in another session.
await reset("keep \uE010 ", 7, 7);
const originalReference = createFileReference("/scratch/paste-a/original.txt", "original.txt", "paste-a", { token: "\uE010", kind: "file" });
flushSync(() => controller.applyEditorDraft("keep \uE010 ", [originalReference], 7));
await new Promise(requestAnimationFrame);
const originalPasteFiles = api.pasteFiles;
let releasePaste!: () => void;
const responseGate = new Promise<void>((resolve) => { releasePaste = resolve; });
let started = false;
api.pasteFiles = async () => {
started = true;
await responseGate;
return { files: [{ path: "/scratch/paste-a/new.txt", name: "new.txt", kind: "file", mimeType: "text/plain" }] };
};
try {
const pendingPaste = dispatchPaste(controller.ref.current!, "", [new File(["new"], "new.txt", {type: "text/plain"})]);
while (!started) await new Promise(requestAnimationFrame);
render("paste-b");
await new Promise(requestAnimationFrame);
releasePaste();
await pendingPaste;
assert(controller.value === "", "pending paste changed the destination draft");
render("paste-a");
const restoreDeadline = performance.now() + 3000;
while (!controller.fileReferences.some((reference) => reference.name === "new.txt") &&
performance.now() < restoreDeadline) {
await new Promise(requestAnimationFrame);
}
const names = controller.fileReferences.map((r) => r.name);
assert(names.includes("original.txt") && names.includes("new.txt"),
"PENDING_PASTE_SESSION_SWITCH lost original attachment: " + JSON.stringify({ names, text: readEditorValue(controller.ref.current!), visible: controller.ref.current!.textContent }));
} finally {
releasePaste();
api.pasteFiles = originalPasteFiles;
}
const nativeFiles = Array.from(
(document.getElementById("native-files") as HTMLInputElement).files!,
);
assert(
nativeFiles.length === 2 &&
nativeFiles.every((file) => api.getDroppedFilePath(file)),
"native File paths unavailable through real preload",
);
const image = new File([await nativeFiles[0].arrayBuffer()], "image.png", {
type: "image/png",
});
assert(
!api.getDroppedFilePath(image),
"synthetic clipboard image unexpectedly has a native path",
);
if (screenshotOnly) {
const readDirectories = api.readClipboardDirectories;
let directoryScans = 0;
api.readClipboardDirectories = async () => {
directoryScans++;
throw new Error("screenshot entered native directory discovery");
};
try {
await paste("", [image]);
assert(directoryScans === 0, "screenshot entered native directory discovery");
assert(controller.fileReferences.length === 1 && controller.fileReferences[0].kind === "image",
"screenshot bytes did not become an image attachment");
} finally {
api.readClipboardDirectories = readDirectories;
}
await paste("native-image.png", [nativeFiles[0]]);
assert(controller.fileReferences.length === 1 && controller.fileReferences[0].kind === "image",
"native image file lost its attachment path");
return { ok: true, screenshotWithoutDirectoryScan: true, nativeImagePreserved: true };
}
const text = "Word paragraph 中文\nsecond line";
let editor = await paste(text, [image]);
assert(
readEditorValue(editor) === `prefix ${text} suffix`,
`Word text mismatch: ${JSON.stringify(readEditorValue(editor))}; white-space=${getComputedStyle(editor).whiteSpace}; contenteditable=${editor.contentEditable}; DOM=${editor.innerHTML}`,
);
assert(
controller.fileReferences.length === 0,
"Word text created an image reference",
);
assert(
editorSelectionRange(editor).start === 7 + text.length,
`text paste caret moved: ${editorSelectionRange(editor).start} expected ${7 + text.length}; DOM=${editor.innerHTML}`,
);
assert(!editor.querySelector("b"), "rich HTML entered the draft");
const multilineCases = [
"first\r\n\r\nlast\r\n",
'<img src=x onerror="throw 1">\n<&> "quotes" \'single\'',
" leading \ntrailing ",
"line\n\n",
// A Word selection can start above the copied text, so the pasted string
// may begin with one or more line breaks.
"\nsecond",
"\n\nline",
"\nA\nB\n",
];
for (const content of multilineCases) {
editor = await paste(content, [image]);
const normalized = content.replace(/\r\n?/g, "\n");
assert(
readEditorValue(editor) === `prefix ${normalized} suffix`,
`multiline text changed: ${JSON.stringify(readEditorValue(editor))}`,
);
assert(
editorSelectionRange(editor).start === 7 + normalized.length,
"multiline caret moved",
);
assert(
!editor.querySelector("img,script,b"),
"plain text interpreted as HTML",
);
assert(document.execCommand("undo"), "native undo unavailable");
await new Promise(requestAnimationFrame);
assert(
readEditorValue(editor) === "prefix REPLACE suffix",
"undo did not restore the replaced selection",
);
assert(document.execCommand("redo"), "native redo unavailable");
await new Promise(requestAnimationFrame);
assert(
readEditorValue(editor) === `prefix ${normalized} suffix`,
"redo lost multiline text",
);
}
editor = await paste("line\n\n", [image], true);
assert(
readEditorValue(editor) === "line\n\n",
`trailing newlines lost: ${JSON.stringify(readEditorValue(editor))}`,
);
assert(
editorSelectionRange(editor).start === 6,
"empty editor paste caret moved",
);
// Forced insertHTML failure: the raw-DOM fallback must still store the
// editor's LF draft model instead of the clipboard's CRLF bytes.
const realExecCommand = document.execCommand.bind(document);
document.execCommand = ((
commandId: string,
...rest: [boolean?, string?]
) =>
commandId === "insertHTML"
? false
: realExecCommand(commandId, ...rest)) as typeof document.execCommand;
try {
editor = await paste("fallback\r\ntext", [image], true);
assert(
readEditorValue(editor) === "fallback\ntext",
`fallback kept clipboard line endings: ${JSON.stringify(readEditorValue(editor))}`,
);
} finally {
document.execCommand = realExecCommand;
}
const beforeReplace = "one\nTWO\nthree";
editor = await paste(beforeReplace, [image], true);
assert(
editor.querySelector("br"),
"multiline fixture is missing a real BR",
);
select(editor, 2, 8);
await dispatchPaste(editor, "A\nB", [image]);
assert(
readEditorValue(editor) === "onA\nBthree",
"replacement across BR changed surrounding text",
);
assert(
editorSelectionRange(editor).start === 5,
"replacement across BR moved caret",
);
assert(document.execCommand("undo"), "cross-BR undo unavailable");
await new Promise(requestAnimationFrame);
assert(
readEditorValue(editor) === beforeReplace,
"cross-BR undo changed text",
);
assert(document.execCommand("redo"), "cross-BR redo unavailable");
await new Promise(requestAnimationFrame);
assert(
readEditorValue(editor) === "onA\nBthree",
"cross-BR redo changed text",
);
const longText = "字".repeat(601);
editor = await paste(longText, [image]);
assert(
controller.fileReferences.length === 1 &&
controller.fileReferences[0].mimeType === "text/plain",
"large mixed paste did not use the text threshold",
);
assert(
readEditorValue(editor) ===
`prefix ${controller.fileReferences[0].token} suffix`,
"large text chip lost the selection boundary",
);
const longTextPath = controller.fileReferences[0].path;
await paste("", [new File([new Uint8Array(512 * 1024 + 1)], "clip.mp4", {
type: "video/mp4",
})]);
assert(controller.fileReferences.length === 1 &&
controller.fileReferences[0].mimeType === "video/mp4" &&
controller.fileReferences[0].path.endsWith(".mp4"),
"a pasted MP4 did not retain its playable scratch filename");
const scratchVideoPath = controller.fileReferences[0].path;
// Preview the persisted long-text attachment through the public work-panel
// entry point, with no project open (the temporary-task user path).
const previewHost = document.createElement("div");
document.body.append(previewHost);
const previewRoot = createRoot(previewHost);
const originalFsOpen = api.fsOpen;
const openRequests: Array<ReturnType<typeof api.fsOpen>> = [];
api.fsOpen = (path: string, mimeType?: string) => {
const request = originalFsOpen(path, mimeType);
openRequests.push(request);
return request;
};
try {
flushSync(() => previewRoot.render(
<I18nextProvider i18n={i18n}><FilesTab /><Mp4AttachmentChips scratchPath={scratchVideoPath} /></I18nextProvider>,
));
assert(previewHost.textContent?.includes(i18n.t("panel.files.noWorkspace")),
"file browsing without a project should show the empty state");
flushSync(() => useAppStore.getState().openFileInWorkPanel(
longTextPath, "text/plain",
));
const deadline = performance.now() + 3000;
while (!previewHost.querySelector(".file-viewer-code") && performance.now() < deadline) {
await new Promise(requestAnimationFrame);
}
assert(previewHost.querySelector(".file-viewer-code")?.textContent === longText,
"temporary-task attachment did not display its saved text in the file preview");
for (const [index, [hash, expected]] of [
["a", i18n.t("panel.files.tooLarge")],
["b", i18n.t("panel.files.binary")],
["scratch", i18n.t("panel.files.tooLarge")],
].entries()) {
const chip = previewHost.querySelector<HTMLButtonElement>(
`.mp4-attachment-chips [aria-label^="${hash}.mp4"]`,
);
assert(chip, `MP4 attachment chip is missing: ${hash}`);
flushSync(() => chip!.click());
const deadline = performance.now() + 3000;
while (!previewHost.textContent?.includes(expected) && performance.now() < deadline) {
await new Promise(requestAnimationFrame);
}
assert(previewHost.textContent?.includes(expected),
`MP4 attachment did not reach its expected preview state: ${hash}`);
const open = Array.from(previewHost.querySelectorAll<HTMLButtonElement>("button"))
.find((button) => button.textContent === i18n.t("chat.openFile"));
assert(open, `MP4 attachment has no system-player action: ${hash}`);
flushSync(() => open!.click());
assert(openRequests.length === index + 1, `MP4 open did not reach IPC: ${hash}`);
await openRequests[index];
}
flushSync(() => useAppStore.getState().openFileInWorkPanel("untrusted.sh", "video/mp4"));
const unsafeDeadline = performance.now() + 3000;
while ((previewHost.querySelector(".file-viewer-path")?.textContent !== "untrusted.sh" ||
!previewHost.textContent?.includes(i18n.t("panel.files.tooLarge"))) &&
performance.now() < unsafeDeadline) {
await new Promise(requestAnimationFrame);
}
assert(!Array.from(previewHost.querySelectorAll<HTMLButtonElement>("button"))
.some((button) => button.textContent === i18n.t("chat.openFile")),
"a spoofed video MIME must not offer an OS-open action for a script");
const back = previewHost.querySelector<HTMLButtonElement>(
`[aria-label="${i18n.t("panel.files.back")}"]`,
);
assert(back, "file preview must provide back navigation");
flushSync(() => back!.click());
assert(previewHost.textContent?.includes(i18n.t("panel.files.noWorkspace")),
"back from a temporary attachment should restore the no-project empty state");
} finally {
api.fsOpen = originalFsOpen;
flushSync(() => previewRoot.unmount());
previewHost.remove();
}
const readDirectories = api.readClipboardDirectories;
let screenshotDirectoryScans = 0;
api.readClipboardDirectories = async () => {
screenshotDirectoryScans++;
return readDirectories();
};
try {
await paste("", [image]);
} finally {
api.readClipboardDirectories = readDirectories;
}
assert(screenshotDirectoryScans === 0, "screenshot paste waited for native directory scanning");
assert(
controller.fileReferences.length === 1 &&
controller.fileReferences[0].kind === "image",
"image-only paste changed",
);
await paste("native-image.png", [nativeFiles[0]]);
assert(
controller.fileReferences.length === 1 &&
controller.fileReferences[0].kind === "image",
"native image file was mistaken for text",
);
// Pasted images are inline chips in the draft, exactly like a pasted file.
const draftText = () => {
let text = readEditorValue(controller.ref.current!);
for (const reference of controller.fileReferences) {
if (reference.token) text = text.split(reference.token).join("");
}
return text;
};
const imageChipByToken = (token: string) => controller.ref.current!
.querySelector<HTMLElement>(`.composer-chip[data-image][data-token="${token}"]`);
const chip = imageChipByToken(controller.fileReferences[0].token!)!;
assert(chip, "pasted images must render as inline chips");
assert(!document.querySelector(".composer-image-attachments"), "the detached attachment row must be gone");
assert(chip.getAttribute("role") === "button" && chip.tabIndex === 0,
"image chip must be keyboard accessible");
assert(draftText() === "prefix suffix", "image chip changed the surrounding draft text");
// #117: enter through the real chip, read through sandboxed image IPC,
// and keep the draft, caret, and work-panel state independent of inspection.
editor = controller.ref.current!;
const beforePreview = readEditorValue(editor);
const imageReference = controller.fileReferences[0];
const dialog = () => document.querySelector<HTMLDialogElement>("dialog.composer-image-preview[open]");
const until = async (condition: () => unknown, message: string) => {
const deadline = performance.now() + 5000;
while (!condition() && performance.now() < deadline) await new Promise(requestAnimationFrame);
assert(condition(), `${message}; errors=${errors.map(String)}; dialog=${dialog()?.textContent}; image=${dialog()?.querySelector("img")?.outerHTML}`);
};
let previewCheck = 0;
const previewReady = async () => {
previewCheck++;
await until(() => {
const img = dialog()?.querySelector<HTMLImageElement>(".composer-image-preview-viewport img");
return img?.complete && img.naturalWidth > 0 && img.style.width !== "";
}, `image preview did not load at check ${previewCheck}`);
await new Promise(requestAnimationFrame);
return dialog()!.querySelector<HTMLImageElement>(".composer-image-preview-viewport img")!;
};
const button = (label: string) => Array.from(dialog()!.querySelectorAll<HTMLButtonElement>("button"))
.find((element) => element.getAttribute("aria-label") === label || element.textContent === label)!;
const close = () => flushSync(() => button(i18n.t("common.close")).click());
// Hovering the chip reveals its preview card without opening the modal.
chip.dispatchEvent(new PointerEvent("pointerover", { bubbles: true }));
await until(() => document.querySelector<HTMLImageElement>(".image-hover-card img")?.naturalWidth === 1,
"hover preview card missing");
chip.dispatchEvent(new PointerEvent("pointerout", { bubbles: true }));
await until(() => !document.querySelector(".image-hover-card"), "hover preview card outlived the pointer");
editor.focus();
// A sent message's image attachment is that same chip, and hovering it shows
// the shared preview card instead of an inline thumbnail.
const messageHost = document.createElement("div");
messageHost.style.cssText = "position: relative;";
document.body.append(messageHost);
const messageRoot = createRoot(messageHost);
try {
const messageAttachment: MessageAttachment = {
kind: "image",
ref: imageReference.path,
name: imageReference.name,
};
flushSync(() => messageRoot.render(
<I18nextProvider i18n={i18n}>
<div role="list">
<MessageAttachmentImage attachment={messageAttachment} onOpenFile={noop} />
</div>
</I18nextProvider>,
));
await new Promise(requestAnimationFrame);
const messageChip = messageHost.querySelector<HTMLElement>(".message-attachment-image-chip .chat-file-chip");
assert(messageChip, "a message image attachment must render as a chip");
assert(!messageHost.querySelector("img"), "a message image attachment must not inline a thumbnail");
messageChip!.dispatchEvent(new PointerEvent("pointerover", { bubbles: true }));
await until(() => document.querySelector<HTMLImageElement>(".image-hover-card img")?.naturalWidth === 1,
"message hover preview card missing");
messageChip!.dispatchEvent(new PointerEvent("pointerout", { bubbles: true }));
await until(() => !document.querySelector(".image-hover-card"), "message hover card outlived the pointer");
} finally {
flushSync(() => messageRoot.unmount());
messageHost.remove();
}
setEditorCaret(editor, 7);
flushSync(() => chip.click());
assert(dialog(), "image attachment must open an overlay instead of the work panel");
assert(dialog()!.matches(":modal"), "preview must use native modal focus containment");
assert(isBlockingOverlayActive(), "preview must suppress native plugin surfaces");
const preview = await previewReady();
editor.focus();
assert(dialog()!.contains(document.activeElement), "modal allowed background input focus");
button(i18n.t("chat.imagePreview.fit")).focus();
await globalThis.composerPreviewPressKey("Tab");
await until(() => dialog()?.contains(document.activeElement), "Tab escaped the preview");
assert(preview.naturalWidth === 1 && preview.getBoundingClientRect().width === 1,
"small image must not be stretched to fill the window");
assert(!useAppStore.getState().workPanelOpen, "preview opened the work panel");
const viewport = dialog()!.querySelector<HTMLElement>(".composer-image-preview-viewport")!;
assert(Math.abs((preview.getBoundingClientRect().left + preview.getBoundingClientRect().right) / 2 -
(viewport.getBoundingClientRect().left + viewport.getBoundingClientRect().right) / 2) <= 1,
"preview must be horizontally centered");
assert(readEditorValue(editor) === beforePreview && controller.fileReferences.length === 1,
"preview changed the unsent draft");
flushSync(() => button(i18n.t("menu.zoomIn")).click());
assert(dialog()!.querySelector("output")?.textContent === "125%", `zoom in failed: ${dialog()!.querySelector("output")?.textContent}, disabled=${button(i18n.t("menu.zoomIn")).disabled}, imageStyle=${preview.getAttribute("style")}`);
flushSync(() => button(i18n.t("chat.imagePreview.fit")).click());
assert(dialog()!.querySelector("output")?.textContent === "100%", "fit did not reset zoom");
const download = dialog()!.querySelector<HTMLAnchorElement>("a[download]")!;
assert(download.download === imageReference.name && download.href === preview.src,
"download did not point to the original image with its filename");
close();
assert(!dialog() && !isBlockingOverlayActive(), "closing left the modal or native-view blocker active");
assert(document.activeElement === editor && editorSelectionRange(editor).start === 7,
"closing did not restore the draft caret");
for (const key of ["Enter", " "]) {
chip.focus();
// Chromium can keep the editing host focused for a nested non-editable chip.
const focusBeforePreview = document.activeElement;
const event = new KeyboardEvent("keydown", { key, bubbles: true, cancelable: true });
flushSync(() => chip.dispatchEvent(event));
assert(event.defaultPrevented, "preview key inserted text or sent the draft");
await previewReady();
assert(readEditorValue(editor) === beforePreview && submitted === 0,
"preview key altered or sent the draft");
await globalThis.composerPreviewPressKey("Escape");
await until(() => !dialog() && document.activeElement === focusBeforePreview,
"native Escape did not dismiss the preview and restore the original focus");
}
// The isolated host supplies real images within the allowed scratch directory.
const wide = createFileReference(imageReference.path.replace(/[^/\\]+$/, "wide-fixture.png"), "wide.png", "paste-a", {
kind: "image", mimeType: "image/png", token: "\ueffe",
});
flushSync(() => controller.applyEditorDraft(`${beforePreview}${wide.token}`, [imageReference, wide], 7));
flushSync(() => imageChipByToken(imageReference.token!)!.click());
await previewReady();
assert(button(i18n.t("chat.imagePreview.previous")).disabled, "first image should disable previous");
flushSync(() => button(i18n.t("chat.imagePreview.next")).click());
const widePreview = await previewReady();
const rect = widePreview.getBoundingClientRect();
assert(widePreview.naturalWidth === 1200 && Math.abs(rect.width / rect.height - 2) < 0.02,
"wide preview lost its original aspect ratio");
assert(rect.width <= dialog()!.querySelector<HTMLElement>(".composer-image-preview-viewport")!.clientWidth + 1 && rect.height <= dialog()!.querySelector<HTMLElement>(".composer-image-preview-viewport")!.clientHeight + 1,
"large image did not fit the preview viewport");
assert(button(i18n.t("chat.imagePreview.next")).disabled, "last image should disable next");
const startX = rect.left + rect.width / 2;
const startY = rect.top + rect.height / 2;
await globalThis.composerPreviewPointer({ type: "mousePressed", x: startX, y: startY });
await globalThis.composerPreviewPointer({ type: "mouseMoved", x: startX + 80, y: startY + 40 });
await globalThis.composerPreviewPointer({ type: "mouseReleased", x: startX + 80, y: startY + 40 });
await new Promise(requestAnimationFrame);
assert(dialog() && Math.abs(widePreview.getBoundingClientRect().left - rect.left - 80) <= 1 &&
Math.abs(widePreview.getBoundingClientRect().top - rect.top - 40) <= 1,
"dragging the image must move it without dismissing the preview");
flushSync(() => button(i18n.t("chat.imagePreview.fit")).click());
assert(Math.abs(widePreview.getBoundingClientRect().left - rect.left) <= 1,
"fit must recenter a dragged image");
const panViewport = dialog()!.querySelector<HTMLElement>(".composer-image-preview-viewport")!;
flushSync(() => panViewport.dispatchEvent(new WheelEvent("wheel", { deltaX: 30, deltaY: 20, bubbles: true, cancelable: true })));
assert(Math.abs(widePreview.getBoundingClientRect().left - rect.left + 30) <= 1,
"ordinary scrolling must pan the image");
flushSync(() => button(i18n.t("chat.imagePreview.fit")).click());
let capturedPointer = -1;
widePreview.addEventListener("pointerdown", (event) => { capturedPointer = event.pointerId; }, { once: true });
await globalThis.composerPreviewPointer({ type: "mousePressed", x: startX, y: startY });
assert(capturedPointer !== -1 && widePreview.hasPointerCapture(capturedPointer), "image drag did not capture its pointer");
flushSync(() => widePreview.dispatchEvent(new PointerEvent("pointercancel", { pointerId: capturedPointer, bubbles: true })));
assert(!widePreview.hasPointerCapture(capturedPointer) && !widePreview.hasAttribute("data-dragging"),
"cancelling must release capture and clear the dragging cursor");
await globalThis.composerPreviewPointer({ type: "mouseMoved", x: startX + 60, y: startY + 20 });
await globalThis.composerPreviewPointer({ type: "mouseReleased", x: startX + 60, y: startY + 20 });
await new Promise(requestAnimationFrame);
assert(dialog() && Math.abs(widePreview.getBoundingClientRect().left - rect.left) <= 1,
"cancelled pointer kept moving or dismissed the image");
flushSync(() => button(i18n.t("menu.zoomIn")).click());
const zoomedViewport = dialog()!.querySelector<HTMLElement>(".composer-image-preview-viewport")!;
const zoomedRect = widePreview.getBoundingClientRect();
assert(Math.abs((zoomedRect.left + zoomedRect.right) / 2 -
(zoomedViewport.getBoundingClientRect().left + zoomedViewport.getBoundingClientRect().right) / 2) <= 1,
"zoom must preserve the image center");
await globalThis.composerPreviewPointer({ type: "mousePressed", x: startX, y: startY });
await globalThis.composerPreviewPointer({ type: "mouseMoved", x: startX - 100, y: startY - 50 });
await globalThis.composerPreviewPointer({ type: "mouseReleased", x: startX - 100, y: startY - 50 });
await new Promise(requestAnimationFrame);
assert(Math.abs(widePreview.getBoundingClientRect().left - zoomedRect.left + 100) <= 1 && dialog(),
"zoomed image must support dragging");
flushSync(() => dialog()!.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowLeft", bubbles: true })));
await previewReady();
assert(dialog()!.querySelector("output")?.textContent === "100%", "gallery switch retained another image's zoom");
flushSync(() => dialog()!.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowRight", bubbles: true })));
const returnedPreview = await previewReady();
assert(Math.abs(returnedPreview.getBoundingClientRect().left - rect.left) <= 1,
"switching images must reset the pan position");
const backdrop = dialog()!.querySelector<HTMLElement>(".composer-image-preview-viewport")!;
flushSync(() => backdrop.click());
assert(!dialog(), "blank-area click did not close preview");
if (globalThis.composerPreviewCapture) await globalThis.composerPreviewCapture();
editor.focus();
const galleryDraft = readEditorValue(editor);
select(editor, 0, galleryDraft.length);
assert(document.execCommand("insertText", false, "new prompt"), "text replacement failed");
await new Promise(requestAnimationFrame);
assert(controller.fileReferences.length === 0,
"replacing the whole draft removed its inline image chips");
assert(controller.draftSnapshot("new prompt").fileReferences.length === 0,
"submission snapshot kept a replaced image");
assert(document.execCommand("undo"), "image draft text undo unavailable");
await new Promise(requestAnimationFrame);
assert(readEditorValue(editor) === galleryDraft && controller.fileReferences.length === 2,
"text undo did not restore the inline image chips");
// Cancelled image reads must never overwrite a later draft's image.
const realRead = api.fsReadImageDataUrl;
let rejectRead: ((reason: Error) => void) | undefined;
const delayed = createFileReference(imageReference.path, "delayed.png", "paste-a", {
kind: "image", mimeType: "image/png", token: imageReference.token,
});
api.fsReadImageDataUrl = () => new Promise((_resolve, reject) => { rejectRead = reject; });
try {
flushSync(() => controller.applyEditorDraft(beforePreview, [delayed], 7));
flushSync(() => imageChipByToken(imageReference.token!)!.click());
assert(rejectRead && dialog(), "deferred image read was not started");
api.fsReadImageDataUrl = realRead;
flushSync(() => controller.applyEditorDraft(beforePreview, [imageReference], 7));
assert(!dialog(), "removed preview attachment left the dialog open");
flushSync(() => imageChipByToken(imageReference.token!)!.click());
await previewReady();
rejectRead!(new Error("late fixture read failure"));
await new Promise(requestAnimationFrame);
assert(dialog()?.querySelector("img"), "stale failure replaced the newer preview");
} finally { api.fsReadImageDataUrl = realRead; }
render("paste-b");
await new Promise(requestAnimationFrame);
assert(!dialog() && !isBlockingOverlayActive(), "session switch retained the old preview");
render("paste-a");
await new Promise(requestAnimationFrame);
editor = controller.ref.current!;
const currentChip = imageChipByToken(imageReference.token!)!;
assert(currentChip, "returning to the session did not restore its image chip");
useAppStore.setState({ activeSessionId: "paste-b" });
flushSync(() => currentChip.click());
assert(!dialog(), "old chip opened in another session");
useAppStore.setState({ activeSessionId: "paste-a" });
const remove = currentChip.querySelector<HTMLButtonElement>(".composer-chip-remove")!;
flushSync(() => {
remove.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true }));
remove.click();
});
assert(!dialog() && submitted === 0, "remove opened the preview or submitted the prompt");
assert(controller.fileReferences.length === 0 && draftText() === "prefix suffix",
"remove did not preserve the surrounding draft");
// Failed images remain attached, show a retry action, and never blank the draft.
const missing = createFileReference(`${imageReference.path}.missing.png`, "missing.png", "paste-a", {
kind: "image", mimeType: "image/png", token: imageReference.token,
});
flushSync(() => controller.applyEditorDraft(beforePreview, [missing], 7));
flushSync(() => imageChipByToken(imageReference.token!)!.click());
await until(() => dialog()?.textContent?.includes(i18n.t("chat.imagePreview.error")), "missing image did not show an error");
assert(readEditorValue(editor) === beforePreview && controller.fileReferences.length === 1,
"failed preview lost the draft");
api.fsReadImageDataUrl = () => realRead(imageReference.path, imageReference.mimeType);
try {
flushSync(() => button(i18n.t("chat.imagePreview.retry")).click());
await previewReady();
} finally { api.fsReadImageDataUrl = realRead; }
close();
const corrupt = createFileReference(imageReference.path.replace(/[^/\\]+$/, "corrupt-fixture.png"), "corrupt.png", "paste-a", {
kind: "image", mimeType: "image/png", token: imageReference.token,
});
flushSync(() => controller.applyEditorDraft(beforePreview, [corrupt], 7));
flushSync(() => imageChipByToken(imageReference.token!)!.click());
await until(() => dialog()?.textContent?.includes(i18n.t("chat.imagePreview.error")), "undecodable image did not show retry");
assert(readEditorValue(editor) === beforePreview, "decode failure changed the draft");
close();
// An image-only draft remains sendable and survives session switching.
editor = await paste("", [image], true);
assert(controller.ref.current!.querySelectorAll(".composer-chip[data-image]").length === 1 &&
controller.draftSnapshot(readEditorValue(controller.ref.current!)).fileReferences.length === 1,
"image-only draft lost its sendable attachment");
const attachedId = controller.fileReferences[0].path;
flushSync(() => controller.restoreDraftForKey("paste-a", { text: "older draft", fileReferences: [] }));
assert(controller.ref.current!.querySelector(".composer-chip[data-image]") &&
controller.fileReferences[0]?.path === attachedId,
"restoring an old draft overwrote a newer image-only draft");
render("paste-b");
flushSync(() => controller.restoreDraftForKey("paste-a", { text: "older draft", fileReferences: [] }));
render("paste-a");
// The restored draft hydrates from the cache in the switch effect, so give
// the layout paint a bounded window before asserting the chip is back.
const restoredDeadline = performance.now() + 2000;
while (
(controller.fileReferences[0]?.path !== attachedId ||
!controller.ref.current!.querySelector(".composer-chip[data-image]")) &&
performance.now() < restoredDeadline
) {
await new Promise(requestAnimationFrame);
}
assert(controller.fileReferences[0]?.path === attachedId &&
controller.ref.current!.querySelector(".composer-chip[data-image]"),
"image-only draft did not survive session switching");
// A pasted conversation link is an inline chip, and the submitted text
// carries that link again.
const linkedSession = "session-link-fixture";
editor = await paste(`continue from ${formatSessionLink(linkedSession)}`, []);
const linkChip = editor.querySelector<HTMLElement>(
`.composer-chip[data-session-id="${linkedSession}"]`,
);
assert(linkChip, "a pasted conversation link must render as an inline chip");
assert(
!readEditorValue(editor).includes(formatSessionLink(linkedSession)),
"the chip replaces the raw link in the draft text",
);
assert(
serializeInlineComposerFileReferences(readEditorValue(editor), controller.fileReferences)
.includes(formatSessionLink(linkedSession)),
"the submitted text carries the conversation link",
);
assert(
linkChip!.querySelector(".composer-chip-name")?.textContent?.includes(linkedSession.slice(0, 8)),
"the chip names the conversation it opens",
);
await paste("file names", nativeFiles);
assert(
controller.fileReferences.length === 2,
"mixed native files were lost",
);
assert(
controller.fileReferences[1].mimeType === "text/plain",
"native text file became inline text",
);
const mixedDraft = controller.value;
const mixedReferences = controller.fileReferences;
flushSync(() => controller.ref.current!.querySelector<HTMLElement>('[data-action="expand-text-reference"]')!.click());
const textDeadline = performance.now() + 5000;
while (controller.fileReferences.length !== 1 && performance.now() < textDeadline) {
await new Promise(requestAnimationFrame);
}
assert(controller.value.includes("native file bytes") && controller.fileReferences[0]?.kind === "image",
"text chip no longer expands while preserving the image attachment");
flushSync(() => controller.applyEditorDraft(mixedDraft, mixedReferences, mixedDraft.length));
const saved = readComposerDraft("paste-a");
assert(
saved?.fileReferences.length === 2,
"file references did not persist in the owning draft",
);
render("paste-b");
await new Promise((resolve) => setTimeout(resolve, 0));
assert(controller.value === "", "attachments leaked into another session");
render("paste-a");
await new Promise((resolve) => setTimeout(resolve, 0));
assert(
controller.fileReferences.length === 2,
"session switch lost attachments",
);
const reference = createFileReference("/fixture/file.bin", "file.bin", "paste-a", { kind: "file", token: "\ueffd" });
flushSync(() =>
controller.applyEditorDraft(
`left${reference.token}right`,
[reference],
4,
),
);
await new Promise(requestAnimationFrame);
editor = controller.ref.current!;
select(editor, 3, 6);
await dispatchPaste(editor, "X\nY", [image]);
assert(
readEditorValue(editor) === "lefX\nYight",
"replacement across attachment chip changed surrounding text",
);
assert(
controller.fileReferences.length === 0,
"replaced attachment stayed in draft metadata",
);
// No store subscription forces a render between clearing and rejection.
const retryImage = createFileReference(imageReference.path, "retry.png", "paste-a", { kind: "image", mimeType: "image/png" });
flushSync(() => controller.applyEditorDraft("retry draft", [retryImage], 11));
await new Promise(requestAnimationFrame);
await rejectSubmission();
await new Promise(requestAnimationFrame);
const retryToken = controller.fileReferences[0]?.token ?? "";
assert(
retryToken !== "" &&
readEditorValue(controller.ref.current!) === `retry draft${retryToken}` &&
controller.fileReferences[0]?.path === imageReference.path,
"fast rejection before React commits must restore the text and attachments",
);
// Native undo must restore reference metadata as well as the visible chip.
await reset("inspect \uE050 please", 8, 9);
const undoReference = createFileReference("src/main.ts", "main.ts", "paste-a", { token: "\uE050" });
flushSync(() => controller.applyEditorDraft("inspect \uE050 please", [undoReference], 9));
await new Promise(requestAnimationFrame);
const undoEditor = controller.ref.current!;
undoEditor.focus();
select(undoEditor, 8, 9);
assert(document.execCommand("delete"), "native chip deletion unavailable");
await new Promise(requestAnimationFrame);
assert(document.execCommand("undo"), "native chip undo unavailable");
await new Promise(requestAnimationFrame);
assert(controller.fileReferences.some(r => r.path === "src/main.ts"), "Undo restored the chip without its file reference metadata");
assert(serializeInlineComposerFileReferences(readEditorValue(undoEditor), controller.activeFileReferences) === "inspect @src/main.ts please",
"undo must restore the path used by submission");
assert(document.execCommand("redo"), "native chip redo unavailable");
await new Promise(requestAnimationFrame);
assert(controller.fileReferences.length === 0, "redo retained a deleted attachment");
assert(document.execCommand("undo"), "second native chip undo unavailable");
await new Promise(requestAnimationFrame);
assert(controller.fileReferences.length === 1, "repeated undo lost the attachment");
render("paste-b");
await new Promise(requestAnimationFrame);
assert(controller.fileReferences.length === 0, "undo metadata leaked into another chat");
render("paste-a");
await new Promise(requestAnimationFrame);
assert(controller.fileReferences.some(r => r.path === "src/main.ts"),
"the restored reference did not survive a chat round-trip");
const restoredEditor = controller.ref.current!;
restoredEditor.focus();
select(restoredEditor, 8, 9);
assert(document.execCommand("delete"), "second chip deletion unavailable");
await new Promise(requestAnimationFrame);
assert(document.execCommand("insertText", false, "\uE050"), "private-use text insertion unavailable");
await new Promise(requestAnimationFrame);
assert(controller.fileReferences.length === 0,
"typing a removed chip's token must not resurrect an attachment");
// A batched away-and-back project change must invalidate deleted history,
// too: native undo must never attach the old relative path to a new context.
const priorWorkspace = useAppStore.getState().workspace;
await reset("inspect \uE050 please", 8, 9);
flushSync(() => controller.applyEditorDraft("inspect \uE050 please", [undoReference], 9));
await new Promise(requestAnimationFrame);
const workspaceUndoEditor = controller.ref.current!;
workspaceUndoEditor.focus();
select(workspaceUndoEditor, 8, 9);
assert(document.execCommand("delete"), "workspace undo deletion unavailable");
await new Promise(requestAnimationFrame);
flushSync(() => {
useAppStore.setState({ workspace: { path: "/other-project", name: "Other" } });
useAppStore.setState({ workspace: priorWorkspace });
});
assert(document.execCommand("undo"), "workspace native undo unavailable");
await new Promise(requestAnimationFrame);
assert(controller.fileReferences.length === 0,
"undo resurrected a reference after a batched workspace round-trip");
flushSync(() => root.render(null));
resetComposerDraftCache();
await verifyComposerSubmission(imageReference.path, i18n);
return {
ok: true,
nativeDirectoryMetadata: true,
fullComposerSubmissionAndOverflow: true,
mixedShortText: true,
multilineAndUndoRedo: true,
fileReferenceUndoRedo: true,
crossBreakAndChipSelection: true,
mixedLongText: true,
temporaryTaskTextPreview: true,
mp4AttachmentOpen: true,
imageOnly: true,
nativeImageFile: true,
imagePreviewAndKeyboard: true,
centeredImageGallery: true,
imageDragAndReset: true,
inlineImageChips: true,
imageZoomFocusAndRecovery: true,
nativeMultipleFiles: true,
selectionAndSessionDrafts: true,
workspaceReferencesAcrossRemount: true,
pendingPasteAcrossSessionSwitch: true,
};
} finally {
flushSync(() => root.unmount());
host.remove();
resetComposerDraftCache();
}
};
globalThis.composerHistoryProbe = async (phase) => {
const i18n = createInstance();
await i18n.init({
lng: "en",
resources: { en: { translation: en } },
interpolation: { escapeValue: false },
});
const host = document.createElement("div");
document.body.append(host);
const errors: unknown[] = [];
const root = createRoot(host, {
onUncaughtError: (error) => errors.push(error),
});
const render = (sessionId: string) => {
useAppStore.setState({ activeSessionId: sessionId || null });
flushSync(() =>
root.render(
<I18nextProvider i18n={i18n}>
<Fixture
key={sessionId || "home"}
sessionId={sessionId}
t={i18n.t}
workspacePath=""
/>
</I18nextProvider>,
),
);
assert(errors.length === 0, `React failed: ${errors.map(String).join("; ")}`);
};
const frame = () => new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
const press = async (key: string) => {
controller.ref.current!.focus();
await globalThis.composerPreviewPressKey(key);
await frame();
assert(errors.length === 0, `React failed after ${key}: ${errors.map(String).join("; ")}`);
};
try {
resetComposerDraftCache();
if (phase === "prepare") {
historySendPrompt = async (_content, _draft, sessionId, onAccepted) => {
if (!sessionId) throw new Error("a docked prompt must submit to its selected session");
onAccepted?.(sessionId);
return true;
};
render("paste-a");
await frame();
const send = async (text: string, references: ReturnType<typeof createFileReference>[] = []) => {
flushSync(() => controller.applyEditorDraft(text, references, text.length));
await frame();
await press("Enter");
await latestSubmission;
await frame();
assert(readEditorValue(controller.ref.current!) === "", "accepted send did not clear its draft");
};
await send("alpha");
await send("beta");
await send("beta");
await press("ArrowUp");
assert(readEditorValue(controller.ref.current!) === "beta", "ArrowUp did not recall the newest entry");
await press("ArrowUp");
assert(readEditorValue(controller.ref.current!) === "alpha", "ArrowUp did not walk to the older entry");
await press("ArrowDown");
assert(readEditorValue(controller.ref.current!) === "beta", "ArrowDown did not walk forward");
await press("ArrowDown");
assert(readEditorValue(controller.ref.current!) === "", "ArrowDown past newest did not clear the draft");
const fileReference = createFileReference(
"/scratch/paste-a/history.txt",
"history.txt",
"paste-a",
{ kind: "file", token: "\uE050" },
);
const attachedText = `inspect \uE050`;
await send(attachedText, [fileReference]);
await press("ArrowUp");
assert(
controller.fileReferences.some((reference) => reference.path === fileReference.path) &&
controller.ref.current!.querySelector(".composer-chip-name")?.textContent === "history.txt",
"history recall did not restore and render the file attachment chip",
);
render("paste-b");
await frame();
await press("ArrowUp");
assert(readEditorValue(controller.ref.current!) === "", "session B recalled session A history");
await send("beta");
await press("ArrowUp");
assert(readEditorValue(controller.ref.current!) === "beta", "session B did not recall its own entry");
render("paste-a");
await frame();
flushSync(() => controller.applyEditorDraft("", [], 0));
await frame();
await press("ArrowUp");
assert(
controller.fileReferences.some((reference) => reference.path === fileReference.path),
"returning to session A did not restore its attached history entry",
);
render("");
await frame();
await press("ArrowUp");
assert(readEditorValue(controller.ref.current!) === "", "the empty home composer recalled another session");
const homeText = "first home prompt";
flushSync(() => controller.applyEditorDraft(homeText, [], homeText.length));
await frame();
await frame();
let signalStarted!: () => void;
let releaseSend!: () => void;
const started = new Promise<void>((resolve) => { signalStarted = resolve; });
const sendGate = new Promise<void>((resolve) => { releaseSend = resolve; });
const originalPrompt = api.prompt;
let queueState = {
activeSessionId: null,
pendingPlans: {},
runningSessions: {},
sessions: [{ id: "history-created-session" }],
messages: [],
latestTurnResults: {},
sessionOutcomes: {},
isRunning: false,
rememberModel: noop,
} as unknown as AppState;
const queueRuntime = {
beginNavigationIntent: () => 1,
sessionModeSelections: new Map(),
submittedComposerDrafts: new Map(),
sessionTranscriptCache: new Map(),
insertOptimisticUserMessage: () => {},
retractOptimisticUserMessage: () => {},
} as unknown as SessionRuntime;
const queueSlice = createQueueSlice({
get: () => queueState,
set: (update) => {
const next = typeof update === "function" ? update(queueState) : update;
queueState = { ...queueState, ...next };
},
runtime: queueRuntime,
promptAttachmentsFromDraft: () => [],
withoutRecordKey: (record, key) => {
const next = { ...record };
delete next[key];
return next;
},
viewingSessionIdForPrompt: () => null,
messageErrorFromUnknown: () => { throw new Error("unexpected prompt failure"); },
assistantErrorMessage: () => { throw new Error("unexpected prompt failure"); },
materializeDraftSession: async () => "history-created-session",
flushPendingSessionConfiguration: async () => {},
});
historySendPrompt = queueSlice.sendPrompt;
api.prompt = async (input) => {
assert(input.sessionId === "history-created-session", "prompt used the wrong materialized session");
signalStarted();
await sendGate;
queueState = { ...queueState, activeSessionId: "paste-b" };
useAppStore.setState({ activeSessionId: "paste-b" });
};
try {
await press("Enter");
await Promise.race([
started,
latestSubmission.then(() => { throw new Error("Home submission settled before reaching the prompt boundary"); }),
]);
const homeSubmission = latestSubmission;
render("paste-b");
releaseSend();
await homeSubmission;
} finally {
api.prompt = originalPrompt;
}
render("history-created-session");
await frame();
await press("ArrowUp");
assert(
readEditorValue(controller.ref.current!) === "first home prompt",
"home's first prompt was not recorded under its materialized session after navigation",
);
return {
ok: true,
arrowNavigation: true,
sessionIsolation: true,
renderedAttachmentRecall: true,
homeSessionSwitchDuringSend: true,
};
}
render("paste-a");
await frame();
await press("ArrowUp");
const recalledText = readEditorValue(controller.ref.current!);
assert(
controller.fileReferences.some((reference) => reference.name === "history.txt") &&
controller.ref.current!.querySelector(".composer-chip-name")?.textContent === "history.txt",
"attachment history did not survive the Electron process restart",
);
assert(recalledText === "inspect \uE050", "the latest attached prompt changed after restart");
render("history-created-session");
await frame();
await press("ArrowUp");
assert(
readEditorValue(controller.ref.current!) === "first home prompt",
"the Home-created session history did not survive the Electron process restart",
);
return {
ok: true,
processRestartPersistence: true,
attachmentPersistence: true,
materializedHomeSessionPersistence: true,
};
} finally {
historySendPrompt = async () => false;
flushSync(() => root.unmount());
host.remove();
resetComposerDraftCache();
}
};